22. May 2013

Using Google's Speech Recognition Web Service with Python

Google powers a mostly undocumented web service for speech recognition. The web service accepts audio data and returns a transcription. Here is a way to communicate with the web service via HTTPS POST and Python.

The reverse engineering has already been done in this tutorial. I received the hint from a friendly fellow student. Here is a Python script doing the same job. Note that the web service (see the demo page) accepts audio in the FLAC format. Use the flac program in order to convert wave to flac.

 1 #!/usr/bin/env python2
 2 # -*- coding: utf-8 -*-
 3 
 4 import httplib
 5 import json
 6 import sys
 7 
 8 def speech_to_text(audio):
 9     url = "www.google.com"
10     path = "/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en"
11     headers = { "Content-type": "audio/x-flac; rate=16000" };
12     params = {"xjerr": "1", "client": "chromium"}
13     conn = httplib.HTTPSConnection(url)
14     conn.request("POST", path, audio, headers)
15     response = conn.getresponse()
16     data = response.read()
17     jsdata = json.loads(data)
18     return jsdata["hypotheses"][0]["utterance"]
19 
20 if __name__ == "__main__":
21     if len(sys.argv) != 2 or "--help" in sys.argv:
22         print "Usage: stt.py <flac-audio-file>"
23         sys.exit(-1)
24     else:
25         with open(sys.argv[1], "r") as f:
26             speech = f.read()
27         text = speech_to_text(speech)
28         print text

Download the file: file: stt.py [836.00B]
Category:
download: 4456