|
@@ -21,6 +21,7 @@ import time
|
|
|
import uuid
|
|
import uuid
|
|
|
import tempfile
|
|
import tempfile
|
|
|
import shutil
|
|
import shutil
|
|
|
|
|
+import logging
|
|
|
|
|
|
|
|
__author__ = "Anthony Zhang (Uberi)"
|
|
__author__ = "Anthony Zhang (Uberi)"
|
|
|
__version__ = "3.5.0"
|
|
__version__ = "3.5.0"
|
|
@@ -34,6 +35,7 @@ except ImportError: # use the Python 3 modules
|
|
|
from urllib.request import Request, urlopen
|
|
from urllib.request import Request, urlopen
|
|
|
from urllib.error import URLError, HTTPError
|
|
from urllib.error import URLError, HTTPError
|
|
|
|
|
|
|
|
|
|
+CACHED_GOOGLE_CLOUD_SPEECH_SERVICES = None
|
|
|
|
|
|
|
|
class WaitTimeoutError(Exception): pass
|
|
class WaitTimeoutError(Exception): pass
|
|
|
|
|
|
|
@@ -546,6 +548,8 @@ class Recognizer(AudioSource):
|
|
|
target_energy = energy * self.dynamic_energy_ratio
|
|
target_energy = energy * self.dynamic_energy_ratio
|
|
|
self.energy_threshold = self.energy_threshold * damping + target_energy * (1 - damping)
|
|
self.energy_threshold = self.energy_threshold * damping + target_energy * (1 - damping)
|
|
|
|
|
|
|
|
|
|
+ #logging.info('Waiting for start of phrase (energy: %i; energy threshold: %i)', energy, self.energy_threshold)
|
|
|
|
|
+
|
|
|
# read audio input until the phrase ends
|
|
# read audio input until the phrase ends
|
|
|
pause_count, phrase_count = 0, 0
|
|
pause_count, phrase_count = 0, 0
|
|
|
phrase_start_time = elapsed_time
|
|
phrase_start_time = elapsed_time
|
|
@@ -569,9 +573,11 @@ class Recognizer(AudioSource):
|
|
|
if pause_count > pause_buffer_count: # end of the phrase
|
|
if pause_count > pause_buffer_count: # end of the phrase
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
|
|
+ #logging.info('Waiting for end of phrase (energy: %i; energy threshold: %i)', energy, self.energy_threshold)
|
|
|
|
|
+
|
|
|
# check how long the detected phrase is, and retry listening if the phrase is too short
|
|
# check how long the detected phrase is, and retry listening if the phrase is too short
|
|
|
phrase_count -= pause_count # exclude the buffers for the pause before the phrase
|
|
phrase_count -= pause_count # exclude the buffers for the pause before the phrase
|
|
|
- if phrase_count >= phrase_buffer_count or len(buffer) == 0: break # phrase is long enough or we've reached the end of the stream, so stop listening
|
|
|
|
|
|
|
+ if phrase_count >= phrase_buffer_count or len(buffer) == 0 or True: break # phrase is long enough or we've reached the end of the stream, so stop listening
|
|
|
|
|
|
|
|
# obtain frame data
|
|
# obtain frame data
|
|
|
for i in range(pause_count - non_speaking_buffer_count): frames.pop() # remove extra non-speaking frames at the end
|
|
for i in range(pause_count - non_speaking_buffer_count): frames.pop() # remove extra non-speaking frames at the end
|
|
@@ -725,7 +731,7 @@ class Recognizer(AudioSource):
|
|
|
response_text = response.read().decode("utf-8")
|
|
response_text = response.read().decode("utf-8")
|
|
|
|
|
|
|
|
# ignore any blank blocks
|
|
# ignore any blank blocks
|
|
|
- actual_result = []
|
|
|
|
|
|
|
+ actual_result = {}
|
|
|
for line in response_text.split("\n"):
|
|
for line in response_text.split("\n"):
|
|
|
if not line: continue
|
|
if not line: continue
|
|
|
result = json.loads(line)["result"]
|
|
result = json.loads(line)["result"]
|
|
@@ -738,7 +744,7 @@ class Recognizer(AudioSource):
|
|
|
if len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
|
|
if len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
|
|
|
|
|
|
|
|
# return alternative with highest confidence score
|
|
# return alternative with highest confidence score
|
|
|
- best_hypothesis = max(actual_result["alternative"], key=lambda alternative: alternative["confidence"])
|
|
|
|
|
|
|
+ best_hypothesis = max(actual_result["alternative"], key=lambda alternative: alternative.get("confidence", 0))
|
|
|
if "transcript" not in best_hypothesis: raise UnknownValueError()
|
|
if "transcript" not in best_hypothesis: raise UnknownValueError()
|
|
|
return best_hypothesis["transcript"]
|
|
return best_hypothesis["transcript"]
|
|
|
|
|
|
|
@@ -758,7 +764,7 @@ class Recognizer(AudioSource):
|
|
|
"""
|
|
"""
|
|
|
assert isinstance(audio_data, AudioData), "`audio_data` must be audio data"
|
|
assert isinstance(audio_data, AudioData), "`audio_data` must be audio data"
|
|
|
assert isinstance(language, str), "`language` must be a string"
|
|
assert isinstance(language, str), "`language` must be a string"
|
|
|
- assert preferred_phrases is None or all(isinstance(preferred_phrases, str) for preferred_phrases in preferred_phrases), "`preferred_phrases` must be a list of strings"
|
|
|
|
|
|
|
+ assert preferred_phrases is None or all(isinstance(preferred_phrases, basestring) for preferred_phrases in preferred_phrases), "`preferred_phrases` must be a list of strings"
|
|
|
|
|
|
|
|
# See https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig
|
|
# See https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionConfig
|
|
|
flac_data = audio_data.get_flac_data(
|
|
flac_data = audio_data.get_flac_data(
|
|
@@ -787,17 +793,24 @@ class Recognizer(AudioSource):
|
|
|
for result in response["results"]:
|
|
for result in response["results"]:
|
|
|
transcript += result["alternatives"][0]["transcript"].strip() + " "
|
|
transcript += result["alternatives"][0]["transcript"].strip() + " "
|
|
|
|
|
|
|
|
- return transcript
|
|
|
|
|
|
|
+ return transcript.strip()
|
|
|
|
|
|
|
|
@staticmethod
|
|
@staticmethod
|
|
|
def get_speech_service():
|
|
def get_speech_service():
|
|
|
|
|
+ global CACHED_GOOGLE_CLOUD_SPEECH_SERVICES
|
|
|
|
|
+ if CACHED_GOOGLE_CLOUD_SPEECH_SERVICES is not None:
|
|
|
|
|
+ return CACHED_GOOGLE_CLOUD_SPEECH_SERVICES
|
|
|
|
|
+
|
|
|
try:
|
|
try:
|
|
|
from oauth2client.client import GoogleCredentials
|
|
from oauth2client.client import GoogleCredentials
|
|
|
from googleapiclient.discovery import build
|
|
from googleapiclient.discovery import build
|
|
|
|
|
|
|
|
credentials = GoogleCredentials.get_application_default()
|
|
credentials = GoogleCredentials.get_application_default()
|
|
|
|
|
|
|
|
- return build("speech", "v1beta1", credentials=credentials)
|
|
|
|
|
|
|
+ service = build("speech", "v1beta1", credentials=credentials)
|
|
|
|
|
+ CACHED_GOOGLE_CLOUD_SPEECH_SERVICES = service
|
|
|
|
|
+ return service
|
|
|
|
|
+
|
|
|
except ImportError:
|
|
except ImportError:
|
|
|
raise ImportError("Could not find google-api-python-client; check "
|
|
raise ImportError("Could not find google-api-python-client; check "
|
|
|
"installation")
|
|
"installation")
|