Last active
January 11, 2017 09:53
-
-
Save sujoyu/abc5505086a822605e14fff75163d9e6 to your computer and use it in GitHub Desktop.
A simple Google Speech API sample for Python2.
This file contains hidden or 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 argparse | |
import base64 | |
import json | |
from googleapiclient import discovery | |
import httplib2 | |
import Tkinter as tk | |
import tkFileDialog | |
DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?' | |
'version={apiVersion}') | |
def get_speech_service(): | |
http = httplib2.Http() | |
return discovery.build( | |
'speech', 'v1beta1', http=http, discoveryServiceUrl=DISCOVERY_URL, developerKey='<API Key>') | |
def main(speech_file): | |
"""Transcribe the given audio file. | |
Args: | |
speech_file: the name of the audio file. | |
""" | |
with open(speech_file, 'rb') as speech: | |
speech_content = base64.b64encode(speech.read()) | |
service = get_speech_service() | |
service_request = service.speech().syncrecognize( | |
body={ | |
'config': { | |
'encoding': 'LINEAR16', # raw 16-bit signed LE samples | |
'sampleRate': 44100, # 16 khz | |
'languageCode': 'ja-JP', # a BCP-47 language tag | |
}, | |
'audio': { | |
'content': speech_content.decode('UTF-8') | |
} | |
}) | |
response = service_request.execute() | |
f = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt") | |
if f is None: # asksaveasfile return `None` if dialog closed with "cancel". | |
return | |
f.write(response['results'][0]['alternatives'][0]['transcript'].encode('utf-8')) | |
f.close() | |
def onCancel(): | |
exit() | |
if __name__ == '__main__': | |
root = tk.Tk() | |
root.title("transcriber") | |
root.option_add('*font', ('FixedSys', 14)) | |
tk.Label(text="transcribing...").pack() | |
root.update() | |
file_path = tkFileDialog.askopenfilename() | |
main(file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment