[A-00090]pythonでSpeech-to-Text API(GCP)を使用する

Google Cloudが提供するSpeech-to-Text APIをpythonから利用する方法を記載しておく。
公式ドキュメントはこちら
https://cloud.google.com/speech-to-text/docs/libraries?hl=ja
・セットアップ
pythonライブラリをインストールします。下記のコマンドを実行してください。
後述するサンプルでは仮想環境を利用します。
. .venv/bin/activate
pip install --upgrade google-cloud-speech
・音声ファイルをテキストに変換する
Speech-to-Text APIは指定した音声ファイルを読み込み、それをテキストに変換します。
まずはGoogleCloudStorageを作成してください。<bucket_name>には任意の名前を入れてください。
gcloud storage buckets create gs://<bucket_name>
次にCloudStorage上にspeechディレクトリを作成します。

作成したら、speechディレクトリに適当な音声ファイルをアップロードしてください。
音声ファイルのサンプルはこちらのサイトから取得可能です。
http://pro-video.jp/voice/announce/

実行するコードは下記となります。
from google.cloud import speech
# Instantiates a client
client = speech.SpeechClient()
# The name of the audio file to transcribe
gcs_uri = "gs://<bucket_name>/speech/ohayo01mayu.mp3"
audio = speech.RecognitionAudio(uri=gcs_uri)
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.ENCODING_UNSPECIFIED,
sample_rate_hertz=16000,
language_code="ja-JP",
)
# Detects speech in the audio file
response = client.recognize(config=config, audio=audio)
for result in response.results:
print("Transcript: {}".format(result.alternatives[0].transcript))
(.venv) MacBook-Pro:test2_project$ python3 speechtest.py
Transcript: おはよう
上記の通り、音声ファイルの内容をテキスト化する事ができました。
コメントを残す