英語のPodcastを聞いていると、聞き取りが難しいときとかがある。 英語のスクリプトがあると便利なので、google speech apiをつかってどの程度のものができるか試してみる。
参考: Use the Google Cloud Speech API to transcribe a podcast – vxlabs
Podcastは.wavやmp3だと思うので、これを.flacに変換する。とりあえず下記サイトで変換する。
https://online-audio-converter.com/ja/
flacにしたら、Google Cloud Storage上にアップロードしておく。
Google Speech APIの変換用メタデータを準備する(async-request.json)。
{ "config": { "encoding": "FLAC", "sampleRateHertz": 16000, "language_code": "en-US" }, "audio":{ "uri":"gs://podcast/podcast.flac" } }
Curlで変換を実行する。事前にgcloudのコマンド設定やgoogle speech apiをenableにしておくのは忘れずに。
curl -X POST \ -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ -H "Content-Type: application/json; charset=utf-8" \ --data @async-request.json "https://speech.googleapis.com/v1/speech:longrunningrecognize"
IDが帰ってくるのでこれを元に進捗を確認する。
{ "name": "5525841372631663248" }
下記のように進捗を確認できる。
curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ -H "Content-Type: application/json; charset=utf-8" \ "https://speech.googleapis.com/v1/operations/5525841372631663248" { "name": "5525841372631663248", "metadata": { "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata", "progressPercent": 73, "startTime": "2018-04-09T14:42:58.535933Z", "lastUpdateTime": "2018-04-09T14:50:34.162436Z" } }
終わると下記のようなレスポンスを返すので、一旦ローカルに書き出しておく。 results.alternatives.transcriptに認識結果が掲載される。
curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ -H "Content-Type: application/json; charset=utf-8" \ "https://speech.googleapis.com/v1/operations/5525841372631663248" { "name": "5525841372631663248", "metadata": { "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata", "progressPercent": 100, "startTime": "2018-04-09T14:42:58.535933Z", "lastUpdateTime": "2018-04-09T14:53:18.541552Z" }, "done": true, "response": { "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse", "results": [ { "alternatives": [ { "transcript": "hello and welcome to the supp...", "confidence": 0.9129662 } ] },
curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ -H "Content-Type: application/json; charset=utf-8" \ "https://speech.googleapis.com/v1/operations/5525841372631663248" > script.json
ローカルに書き出したjsonを必要なスクリプトの部分だけ抜き出す。
import json with open('./script.json') as f: # results: a list of dicts, each with 'alternatives', which is a list of transcripts res = json.load(f)['response']['results'] num_like = 0 num_words = 0 for r in res: alts = r['alternatives'] # ensure that we only have one alternative per result assert len(alts) == 1 # break into lowercase words print(alts[0]['transcript'] + "\n")
$ python script.py > script.txt
流れが掴めたので、一括で全部できるようにしたいが、とりあえずメモ。