snowboy.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import logging
  2. import time
  3. from trigger.snowboy import snowboydecoder
  4. class MissingParameterException(Exception):
  5. pass
  6. logging.basicConfig()
  7. logger = logging.getLogger("kalliope")
  8. class Snowboy(object):
  9. def __init__(self, **kwargs):
  10. # pause listening boolean
  11. self.interrupted = False
  12. self.kill_received = False
  13. # callback function to call when hotword caught
  14. self.callback = kwargs.get('callback', None)
  15. if self.callback is None:
  16. raise MissingParameterException("callback function is required with snowboy")
  17. # get the pmdl file to load
  18. self.pmdl = kwargs.get('pmdl_file', None)
  19. if self.pmdl is None:
  20. raise MissingParameterException("Pmdl file is required with snowboy")
  21. self.detector = snowboydecoder.HotwordDetector(self.pmdl, sensitivity=0.5, detected_callback=self.callback,
  22. interrupt_check=self.interrupt_callback,
  23. sleep_time=0.03)
  24. def interrupt_callback(self):
  25. """
  26. This function will be passed to snowboy to stop the main thread
  27. :return:
  28. """
  29. return self.interrupted
  30. def start(self):
  31. """
  32. Start the snowboy thread and wait for a Kalliope trigger word
  33. :return:
  34. """
  35. # start snowboy loop
  36. self.detector.daemon = True
  37. try:
  38. self.detector.start()
  39. while not self.kill_received:
  40. # once the main thread has started child thread, there's nothing else for it to do.
  41. # So it exits, and the threads are destroyed instantly. So let's keep the main thread alive
  42. time.sleep(1)
  43. except KeyboardInterrupt:
  44. self.kill_received = True
  45. self.detector.kill_received = True
  46. # we wait that a callback
  47. self.detector.terminate()
  48. def pause(self):
  49. """
  50. pause the Snowboy main thread
  51. """
  52. logger.debug("Pausing snowboy process")
  53. self.detector.paused = True
  54. def unpause(self):
  55. """
  56. unpause the Snowboy main thread
  57. """
  58. logger.debug("Unpausing snowboy process")
  59. self.detector.paused = False