trigger.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import logging
  2. import snowboy.snowboydecoder
  3. import sys
  4. import signal
  5. import ears
  6. import tts
  7. # Demo code for listening two hotwords at the same time
  8. INTERRUPTED = False
  9. DEFAULT_SENSITIVITY = 0.5
  10. def _signal_handler(signal, frame):
  11. global INTERRUPTED
  12. INTERRUPTED = True
  13. def _interrupt_callback():
  14. global INTERRUPTED
  15. return INTERRUPTED
  16. def _callback(model):
  17. logging.info('%s triggered.', model['model'].split('/')[-1])
  18. if 'callback' in model:
  19. model['callback'].call()
  20. elif 'callbacks' in model:
  21. logging.info('waiting for keyword...')
  22. preferred_phrases = model['callbacks'].keys()
  23. for v in model['callbacks'].itervalues():
  24. preferred_phrases.extend(v.preferred_phrases())
  25. tokens = ears.listen(tokenize=True, preferred_phrases=preferred_phrases, pause_threshold=1)
  26. if tokens:
  27. keyword = tokens[0].lower()
  28. if keyword in model['callbacks']:
  29. return model['callbacks'][keyword].call(trigger=keyword, additional_tokens=tokens[1:])
  30. tts.tts('callback failed.')
  31. def loop_model(model):
  32. signal.signal(signal.SIGINT, _signal_handler)
  33. while not INTERRUPTED:
  34. raw_input('Press enter to listen.')
  35. _callback(model)
  36. def start(models):
  37. callbacks = []
  38. for m in models:
  39. if 'callbacks' in m:
  40. m['callbacks'] = {k.lower().strip(): v for k, v in m['callbacks'].iteritems()}
  41. def c():
  42. _callback(m)
  43. callbacks.append(c)
  44. logging.info('Launching Snowboy hotword detector...')
  45. signal.signal(signal.SIGINT, _signal_handler)
  46. detector = snowboy.snowboydecoder.HotwordDetector(decoder_model=models[0]['model'],
  47. resource='/home/martin/workspaces/visual-code/voice_control/resources/snowboy/common.res',
  48. sensitivity=DEFAULT_SENSITIVITY)
  49. logging.info('Stream opened.')
  50. detector.start(detected_callback=callbacks[0], interrupt_check=_interrupt_callback, sleep_time=0.03)
  51. detector.terminate()