Created
December 14, 2016 02:07
-
-
Save KustomApe/60f8facdf128ba3c902f70c5d4d6195e to your computer and use it in GitHub Desktop.
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
"""Google Cloud Speech API sample application using the REST API for batch | |
processing.""" | |
import argparse | |
import base64 | |
import json | |
from googleapiclient import discovery | |
import httplib2 | |
from oauth2client.client import GoogleCredentials | |
DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?' | |
'version={apiVersion}') | |
def get_speech_service(): | |
credentials = GoogleCredentials.get_application_default().create_scoped( | |
['https://www.googleapis.com/auth/cloud-platform']) | |
http = httplib2.Http() | |
credentials.authorize(http) | |
return discovery.build( | |
'speech', 'v1beta1', http=http, discoveryServiceUrl=DISCOVERY_URL) | |
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': 16000, # 16 khz | |
'languageCode': 'ja-UP', # a BCP-47 language tag ja-UP cmn-Hans-CN en-US | |
}, | |
'audio': { | |
'content': speech_content.decode('UTF-8') | |
} | |
}) | |
response = service_request.execute() | |
print(json.dumps(response)) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'speech_file', help='Full path of audio file to be recognized') | |
args = parser.parse_args() | |
main(args.speech_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment