Martin 10 سال پیش
والد
کامیت
d6890312ce
2فایلهای تغییر یافته به همراه30 افزوده شده و 6 حذف شده
  1. 11 0
      .gitignore
  2. 19 6
      speech_recognition/__init__.py

+ 11 - 0
.gitignore

@@ -0,0 +1,11 @@
+*.egg-info
+build
+dist
+__pycache__
+*.pyc
+speech_recognition/pocketsphinx-data/fr-FR/
+speech_recognition/pocketsphinx-data/zh-CN/
+fr-FR.zip
+zh-CN.zip
+pocketsphinx-python/
+.settings

+ 19 - 6
speech_recognition/__init__.py

@@ -21,6 +21,7 @@ import time
 import uuid
 import tempfile
 import shutil
+import logging
 
 __author__ = "Anthony Zhang (Uberi)"
 __version__ = "3.5.0"
@@ -34,6 +35,7 @@ except ImportError:  # use the Python 3 modules
     from urllib.request import Request, urlopen
     from urllib.error import URLError, HTTPError
 
+CACHED_GOOGLE_CLOUD_SPEECH_SERVICES = None
 
 class WaitTimeoutError(Exception): pass
 
@@ -546,6 +548,8 @@ class Recognizer(AudioSource):
                     target_energy = energy * self.dynamic_energy_ratio
                     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
             pause_count, phrase_count = 0, 0
             phrase_start_time = elapsed_time
@@ -569,9 +573,11 @@ class Recognizer(AudioSource):
                 if pause_count > pause_buffer_count:  # end of the phrase
                     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
             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
         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")
 
         # ignore any blank blocks
-        actual_result = []
+        actual_result = {}
         for line in response_text.split("\n"):
             if not line: continue
             result = json.loads(line)["result"]
@@ -738,7 +744,7 @@ class Recognizer(AudioSource):
         if len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
 
         # 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()
         return best_hypothesis["transcript"]
 
@@ -758,7 +764,7 @@ class Recognizer(AudioSource):
         """
         assert isinstance(audio_data, AudioData), "`audio_data` must be audio data"
         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
         flac_data = audio_data.get_flac_data(
@@ -787,17 +793,24 @@ class Recognizer(AudioSource):
         for result in response["results"]:
             transcript += result["alternatives"][0]["transcript"].strip() + " "
 
-        return transcript
+        return transcript.strip()
 
     @staticmethod
     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:
             from oauth2client.client import GoogleCredentials
             from googleapiclient.discovery import build
 
             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:
             raise ImportError("Could not find google-api-python-client; check "
                               "installation")