Created
November 13, 2017 14:55
-
-
Save akiko-pusu/31595bb8937889d456d29f5f239087c3 to your computer and use it in GitHub Desktop.
Google Cloud Speech API を叩くpython scriptのサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import pprint | |
import os # 環境変数を扱うモジュール | |
import sys # コマンドライン引数を扱うモジュール | |
import requests # http通信に便利なモジュール | |
# | |
# $ python --version | |
# Python 3.5.4 | |
# | |
# HTTPリクエス用のモジュール:requestsを使います | |
# http://docs.python-requests.org/en/master/ | |
# | |
# 実行方法: | |
# | |
# (1) requestsモジュールが入っていなければ先にインストール | |
# (2) API用のキーを環境変数にセット | |
# (3) python sample.py を実行、もしくは python sample.py 送信したいjsonファイルを指定 | |
# | |
# | |
# $ pip install requests | |
# $ export GOOGLE_API_KEY=<API用のキー> | |
# $ python sample.py | |
# | |
# Google Cloud Speech APIについてはこちら: | |
# api https://speech.googleapis.com/v1beta1 | |
def read_json(filename): | |
""" 指定したjsonファイルからデータを読み取る関数 """ | |
pprint.pprint('ファイル: %s のデータを送信します。' % filename) | |
with open(filename, 'rb') as file: | |
payload = file.read() | |
return payload | |
def set_filename(): | |
""" 引数で指定されたファイル名を取得 """ | |
argvs = sys.argv # コマンドライン引数を格納したリストの取得 | |
argc = len(argvs) # 引数の個数 | |
# ファイル名を引数で指定します (無ければsync-request.jsonを利用) | |
filename = 'sync-request.json' | |
if argc == 2: | |
filename = argvs[1] | |
return filename | |
def main(): | |
""" 引数で指定されたファイル名を取得 (無ければsync-request.jsonを利用) """ | |
filename = set_filename() | |
base_url = 'https://speech.googleapis.com/v1beta1/speech:syncrecognize?key={}' | |
# APIキーは実行時の環境変数から取得します | |
api_key = os.environ.get("GOOGLE_API_KEY") | |
base_url = base_url.format(api_key) | |
headers = {'content-type': 'application/json'} | |
# POSTパラメータは二つ目の引数に辞書で指定する | |
response = requests.post( | |
base_url, | |
data=read_json(filename), headers=headers) | |
# レスポンスオブジェクトのjsonメソッドを使うと、 | |
# JSONデータをPythonの辞書オブジェクトに変換して取得できる | |
pprint.pprint(response.json()) | |
if __name__ == '__main__': | |
main() |
上記は Google Cloud Speech APIを叩くサンプル。
ドキュメントはこちら: https://cloud.google.com/speech/docs/sync-recognize?hl=ja
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
with open を使えば、処理が終わったらcloseを裏で実施してくれる。
(明示的にopen -> closeしないとファイルを開ける上限に引っかかってしまう場合があるので注意!)