Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple keys with Google speech api #514

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions client/stt.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,14 @@ def __init__(self, api_key=None, language='en-us'):
self._api_key = None
self._http = requests.Session()
self.language = language

if isinstance(api_key, list):
self.key_index = 0
self.request_count = 0
self.api_quota = 50
else:
self.key_index = False

self.api_key = api_key

@property
Expand All @@ -339,9 +347,13 @@ def api_key(self, value):

def _regenerate_request_url(self):
if self.api_key and self.language:
if self.key_index is not False:
key = self.api_key[self.key_index]
else:
key = self.api_key
query = urllib.urlencode({'output': 'json',
'client': 'chromium',
'key': self.api_key,
'key': key,
'lang': self.language,
'maxresults': 6,
'pfilter': 2})
Expand Down Expand Up @@ -382,14 +394,20 @@ def transcribe(self, fp):
self._logger.critical('Language info missing, transcription ' +
'request aborted.')
return []

elif self.key_index is not False \
and self.request_count >= self.api_quota:
print('Switching api keys to stay under quota')
self.key_index = ((self.key_index + 1) % len(self.api_key))
self.request_count = 0
self._regenerate_request_url()
wav = wave.open(fp, 'rb')
frame_rate = wav.getframerate()
wav.close()
data = fp.read()

headers = {'content-type': 'audio/l16; rate=%s' % frame_rate}
r = self._http.post(self.request_url, data=data, headers=headers)
self.request_count += 1
try:
r.raise_for_status()
except requests.exceptions.HTTPError:
Expand Down