snowboy_hotword_detector.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import logging
  2. import time
  3. import snowboy.snowboydecoder
  4. import base
  5. import conf
  6. import output
  7. class State(object):
  8. LAUNCH_HOTWORD_DETECTION = 'LAUNCH_HOTWORD_DETECTION'
  9. HOTWORD_DETECTION = 'HOTWORD_DETECTION'
  10. LAUNCH_SPEECH_DETECTION = 'LAUNCH_SPEECH_DETECTION'
  11. SPEECH_DETECTION = 'SPEECH_DETECTION'
  12. class HotwordDetector(base.InputSource):
  13. hotword_detector = None
  14. state = State.LAUNCH_HOTWORD_DETECTION
  15. def __init__(self, speech_detector, global_interrupt_check):
  16. self.global_interrupt_check = global_interrupt_check
  17. self.speech_detector = speech_detector
  18. self.speech_detector.interrupt_check = self._speech_detection_interrupt_check
  19. def _hotword_interrupt_check(self):
  20. return self.global_interrupt_check() or self.state != State.HOTWORD_DETECTION
  21. def _speech_detection_interrupt_check(self):
  22. return self.global_interrupt_check() or self.state not in [State.SPEECH_DETECTION, State.LAUNCH_SPEECH_DETECTION]
  23. def _callback(self):
  24. self.state = State.LAUNCH_SPEECH_DETECTION
  25. def run(self):
  26. while True:
  27. if self.global_interrupt_check():
  28. output.debug('SR: global interrupt: returning')
  29. return
  30. elif self.state == State.LAUNCH_HOTWORD_DETECTION:
  31. self.speech_detector.terminate()
  32. self.hotword_detector = snowboy.snowboydecoder.HotwordDetector(conf.SNOWBOY_HOTWORD_MODEL, sensitivity=0.5)
  33. self.state = State.HOTWORD_DETECTION
  34. self.hotword_detector.start(detected_callback=self._callback, interrupt_check=self._hotword_interrupt_check)
  35. elif self.state == State.LAUNCH_SPEECH_DETECTION:
  36. self.hotword_detector.terminate()
  37. self.hotword_detector = None
  38. self.state = State.SPEECH_DETECTION
  39. self.speech_detector.run()
  40. time.sleep(0.1)
  41. def reset(self):
  42. if self.state != State.HOTWORD_DETECTION:
  43. output.debug('SR: reset received.')
  44. self.state = State.LAUNCH_HOTWORD_DETECTION