Procházet zdrojové kódy

#21 add snowboy hotword gating for speech recognition

Martin před 9 roky
rodič
revize
dab8b3cb52

+ 22 - 4
voice_control/input_sources/__init__.py

@@ -7,6 +7,8 @@ LANGUAGE = 'en-GB'
 PREFERRED_PHRASES = None
 _TOKEN_STREAM = None
 
+_RESET_SERVICES = []
+
 class TokenStream(object):
     def __init__(self):
         self.preferred_phrases = None
@@ -23,19 +25,30 @@ class TokenStream(object):
 
     def get_line(self, timeout):
         return self.get_token(timeout)
+    
+    def reset(self):
+        self.buffer = Queue.Queue()
 
-def launch_input_sources(curses_client):
+def launch_input_sources(curses_client, interrupt_check):
     global _TOKEN_STREAM
     _TOKEN_STREAM = TokenStream()
 
+    global _RESET_SERVICES
+    _RESET_SERVICES = []
+
     services = [
         console.ConsoleInput(curses_client, _TOKEN_STREAM),
     ]
 
-    if conf.SPEECH_INPUT_ENABLED:
+    if conf.SPEECH_INPUT_ENABLED and conf.SNOWBOY_HOTWORD_MODEL:
         import google_cloud_speech
-        services.append(google_cloud_speech.GoogleCloudSpeech(_TOKEN_STREAM))
-        
+        import snowboy_hotword_detector
+
+        speech_detector = google_cloud_speech.GoogleCloudSpeech(_TOKEN_STREAM, interrupt_check)
+        hotword_detector = snowboy_hotword_detector.HotwordDetector(speech_detector, interrupt_check)
+        services.append(hotword_detector)
+        _RESET_SERVICES.append(hotword_detector)
+    
     if conf.SLACK_BOT_API_KEY:
         import slack_bot
         services.append(slack_bot.SlackBot(_TOKEN_STREAM))
@@ -67,3 +80,8 @@ def get_until_terminated(timeout=120, terminators=['done', 'cancel'], preferred_
         res.append(t)
         t = get_token(timeout=timeout, preferred_phrases=preferred_phrases)
     return res, t
+
+def reset():
+    for service in _RESET_SERVICES:
+        service.reset()
+    _TOKEN_STREAM.reset()

+ 26 - 14
voice_control/input_sources/google_cloud_speech.py

@@ -3,13 +3,15 @@ import base
 import speech_recognition as sr
 import output
 import input_sources
+import conf
 
 class GoogleCloudSpeech(base.InputSource):
     recognizer = None
     stopper = None
 
-    def __init__(self, token_stream):
+    def __init__(self, token_stream, interrupt_check):
         self.token_stream = token_stream
+        self.interrupt_check = interrupt_check
 
     def _init(self):
         self.recognizer = sr.Recognizer()
@@ -20,34 +22,33 @@ class GoogleCloudSpeech(base.InputSource):
         with sr.Microphone() as source:
             self.recognizer.adjust_for_ambient_noise(source)
 
-        self.recognizer.energy_threshold = max(400, self.recognizer.energy_threshold)
+        self.recognizer.energy_threshold = max(conf.SPEECH_RECOGNITION_MIN_ENERGY_LEVEL, self.recognizer.energy_threshold)
 
-        output.debug('sr: recognizer initialized, at energy threshold %i.' % self.recognizer.energy_threshold)
+        output.debug('SR: Recognizer initialized, at energy threshold %i.' % self.recognizer.energy_threshold)
 
     def _recognizer_callback(self, recognizer, audio):
-
-        output.debug('Calling recognition APIs (preferred_phrases: %s)...' % input_sources.PREFERRED_PHRASES)
+        output.debug('SR: Calling recognition APIs (preferred_phrases: %s)...' % input_sources.PREFERRED_PHRASES)
 
         text = None
 
         try:
             t = time.time()
             text = recognizer.recognize_google_cloud(audio, language=input_sources.LANGUAGE, preferred_phrases=input_sources.PREFERRED_PHRASES)
-            output.debug('Google cloud speech: %s (%.2f s)' % (text, time.time() - t))
+            output.debug('SR: Google cloud speech: %s (%.2f s)' % (text, time.time() - t))
         except sr.UnknownValueError:
-            output.debug('Google Cloud Speech Recognition could not understand audio')
+            output.debug('SR: Google Cloud Speech Recognition could not understand audio')
         except sr.RequestError, e:
-            output.debug("Could not request results from Google Cloud Speech Recognition service: %s" % str(e))
+            output.debug('SR: Could not request results from Google Cloud Speech Recognition service: %s' % str(e))
         
         if text is None:
             try:
                 t = time.time()
                 text = recognizer.recognize_google(audio, language=input_sources.LANGUAGE)
-                output.debug('Google speech: %s (%.2f s)' % (text, time.time() - t))
+                output.debug('SR: Google speech: %s (%.2f s)' % (text, time.time() - t))
             except sr.UnknownValueError:
-                output.debug('Google Speech Recognition could not understand audio')
+                output.debug('SR: Google Speech Recognition could not understand audio')
             except sr.RequestError, e:
-                output.debug("Could not request results from Google Speech Recognition service: %s" % e)
+                output.debug('SR: Could not request results from Google Speech Recognition service: %s' % e)
 
         if text:
             for t in text.split(' '):
@@ -55,11 +56,22 @@ class GoogleCloudSpeech(base.InputSource):
                 if t:
                     self.token_stream.add_token(t)
         else:
-            output.failure('Google speech-to-text failed.')
+            output.failure('SR: Google speech-to-text failed.')
 
     def run(self):
         self._init()
-
         self.stopper = self.recognizer.listen_in_background(sr.Microphone(), self._recognizer_callback)
+        output.debug('SR: Listening...')
 
-        output.debug('sr: listening...')
+        while self.stopper is not None:
+            if self.interrupt_check():
+                self.stopper()
+                self.stopper = None
+                return
+            
+            time.sleep(0.1)
+    
+    def terminate(self):
+        if self.stopper is not None:
+            self.stopper()
+            self.stopper = None

+ 55 - 0
voice_control/input_sources/snowboy_hotword_detector.py

@@ -0,0 +1,55 @@
+import logging
+import time
+import snowboy.snowboydecoder
+import base
+import conf
+import output
+
+class State(object):
+    LAUNCH_HOTWORD_DETECTION = 'LAUNCH_HOTWORD_DETECTION'
+    HOTWORD_DETECTION = 'HOTWORD_DETECTION'
+
+    LAUNCH_SPEECH_DETECTION = 'LAUNCH_SPEECH_DETECTION'
+    SPEECH_DETECTION = 'SPEECH_DETECTION'
+
+class HotwordDetector(base.InputSource):
+    hotword_detector = None
+    state = State.LAUNCH_HOTWORD_DETECTION
+
+    def __init__(self, speech_detector, global_interrupt_check):
+        self.global_interrupt_check = global_interrupt_check
+        self.speech_detector = speech_detector
+        self.speech_detector.interrupt_check = self._speech_detection_interrupt_check
+
+    def _hotword_interrupt_check(self):
+        return self.global_interrupt_check() or self.state != State.HOTWORD_DETECTION
+
+    def _speech_detection_interrupt_check(self):
+        return self.global_interrupt_check() or self.state != State.SPEECH_DETECTION
+
+    def _callback(self):
+        self.state = State.LAUNCH_SPEECH_DETECTION
+
+    def run(self):
+        while True:
+            if self.global_interrupt_check():
+                output.debug('SR: global interrupt: returning')
+                return
+
+            elif self.state == State.LAUNCH_HOTWORD_DETECTION:
+                self.speech_detector.terminate()
+                self.hotword_detector = snowboy.snowboydecoder.HotwordDetector(conf.SNOWBOY_HOTWORD_MODEL, sensitivity=0.5)
+                self.state = State.HOTWORD_DETECTION
+                self.hotword_detector.start(detected_callback=self._callback, interrupt_check=self._hotword_interrupt_check)
+
+            elif self.state == State.LAUNCH_SPEECH_DETECTION:
+                self.hotword_detector.terminate()
+                self.hotword_detector = None
+                self.state = State.SPEECH_DETECTION
+                self.speech_detector.run()
+
+            time.sleep(0.1)
+
+    def reset(self):
+        output.debug('SR: reset received.')
+        self.state = State.LAUNCH_HOTWORD_DETECTION

+ 2 - 2
voice_control/main.py

@@ -40,8 +40,8 @@ def _run(cclient):
     signal.signal(signal.SIGINT, _signal_handler)
 
     output.init_services(cclient)
-    input_sources.launch_input_sources(cclient)
-    services.launch_services(cclient, _interrupt_callback)
+    input_sources.launch_input_sources(cclient, _interrupt_callback)
+    services.launch_services(cclient, _interrupt_callback, _signal_handler)
 
 if __name__ == "__main__":
     if False:

+ 14 - 3
voice_control/services/__init__.py

@@ -1,7 +1,7 @@
+import logging
 import threading
 import traceback
 
-import todo_wunderlist
 import input_sources
 import output
 import services.help
@@ -40,7 +40,7 @@ def _get_services(cclient):
 
     return res
 
-def launch_services(cclient, interrupted):
+def launch_services(cclient, interrupted, trigger_interrupted):
     _services = _get_services(cclient)
 
     for s in _services.values():
@@ -51,14 +51,25 @@ def launch_services(cclient, interrupted):
     output.text('Ready. Available services: %s.' % ', '.join(sorted(_services.keys())))
 
     while not interrupted():
-        input_sources.PREFERRED_PHRASES = _services.keys() + ['quit']
+        input_sources.PREFERRED_PHRASES = _services.keys() + ['quit', 'cancel']
+
         t = input_sources.get_token(1)
         if t is not None and t in _services and _services[t].initialized:
             try:
                 _services[t].call()
+                output.success()
             except Exception, e:
                 output.failure(s='Error: %s' % traceback.format_exc())
+
         elif t == 'quit':
+            trigger_interrupted()
             return
+        
+        elif t == 'cancel':
+            pass
+
         elif t is not None:
             output.failure('"%s" is not a valid service.' % t)
+
+        if t is not None:
+            input_sources.reset()