[Python]WatsonのSpeech To Textを使うお話


概要

PythonからIBMのAI、Watsonに音声データを送信していわゆる音声認識をしましょうというお話です。

環境

  • MacBook Pro high Serra 10.13.5
  • Python 3.6.6
  • pip 10.0.1
  • Visual Studio Code

準備

手順

  1. Pythonでwatson-developer-cloudを使えるようにする。
  2. Watsonにアクセスするusername、passwordを取得する。
  3. Watsonに音声データを送信する。
  4. Watsonの結果を表示する。

Pythonでwatson-developer-cloudを使えるようにする。

ターミナルで次のコマンドを打ちます。

pip install "watson-developer-cloud>=1.4.0"

最後の行に`Successfully"と表示されていれば大丈夫です。

Windowsでうまく行かない人はもしかしてVisual Build Toolsがインストールされていないかも?
https://qiita.com/white0221/items/b48f1b64dbd810e21702
以前まとめたものです。

Watsonにアクセスするusername、passwordを取得する。

IBMのサイトでSpeech To Textを選んで作成し、視覚情報を得ます。

{
  "url": "https://stream.watsonplatform.net/text-to-speech/api",
  "username": "••••••••••••••••••••••••••••••••••••",
  "password": "••••••••••••"
}

こんな風にマスクされているので右上の目のマークを押して表示させます。

このusernameとpasswordを用いてwatsonと通信を行います。

サンプルコード

今回はvoice.wavファイルを送信することにします。また、音声データは日本語として認識するようにja-JP_BroadbandModelを指定します。サポートしている音声ファイルや言語はIBMのAPI referenceを参照。音声ファイルは頑張って録音して、wav形式でなければオンラインコンバータか何かでコンバートしましょう。返却データはjson形式です。

SpeechToText.py
from watson_developer_cloud import SpeechToTextV1
import json

# define
user = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
pswd = "xxxxxxxxxxxx"
audio_file = open("voice.wav", "rb")
cont_type = "audio/wav"
lang = "ja-JP_BroadbandModel"

# watson connection
stt = SpeechToTextV1(username=user, password=pswd)
result_json = stt.recognize(audio=audio_file, content_type=cont_type, model=lang)

# print
for i in range(len(result_json["results"])):
    print(result_json["results"][i]["alternatives"][0]["transcript"])

# json file save
result = json.dumps(result_json, indent=2)
f = open("result.json", "w")
f.write(result)
f.close()

実行例

$ python SpeechToText.py
こんにちは ワトソン の 音声認識 テスト です  
result.json

{
  "results": [
      {
          "alternatives": [
              {
                  "confidence": 0.xxx,
                  "transcript": "こんにちは ワトソン の 音声認識 テスト です "
              }
          ],
          "final": true
      }
  ],
  "result_index": 0
}

まとめ

こんな感じに以外と手軽にできました。
おそらく英語ができればもっと色々できると思うんですが・・・。
IBMさん、ドキュメントの日本語化お願いします。

WebSocketを用いてリアルタイム音声認識ができるはずなので模索中です。できたら記事にします。

参考文献

https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/python.html?python#introduction
https://qiita.com/nanako_ut/items/7d53c81b89cdeae1e676