__init__.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import Queue
  2. import threading
  3. import console
  4. import conf
  5. LANGUAGE = 'en-GB'
  6. PREFERRED_PHRASES = None
  7. _TOKEN_STREAM = None
  8. _RESET_SERVICES = []
  9. class TokenStream(object):
  10. def __init__(self):
  11. self.preferred_phrases = None
  12. self.buffer = Queue.Queue()
  13. def add_token(self, token):
  14. self.buffer.put(token)
  15. def get_token(self, timeout):
  16. try:
  17. return self.buffer.get(timeout=timeout).strip().lower()
  18. except Queue.Empty:
  19. return None
  20. def get_line(self, timeout):
  21. return self.get_token(timeout)
  22. def reset(self):
  23. self.buffer = Queue.Queue()
  24. def launch_input_sources(curses_client, interrupt_check):
  25. global _TOKEN_STREAM
  26. _TOKEN_STREAM = TokenStream()
  27. global _RESET_SERVICES
  28. _RESET_SERVICES = []
  29. services = [
  30. console.ConsoleInput(curses_client, _TOKEN_STREAM),
  31. ]
  32. if conf.SPEECH_INPUT_ENABLED and conf.SNOWBOY_HOTWORD_MODEL:
  33. import google_cloud_speech
  34. import snowboy_hotword_detector
  35. speech_detector = google_cloud_speech.GoogleCloudSpeech(_TOKEN_STREAM, interrupt_check)
  36. hotword_detector = snowboy_hotword_detector.HotwordDetector(speech_detector, interrupt_check)
  37. services.append(hotword_detector)
  38. _RESET_SERVICES.append(hotword_detector)
  39. if conf.SLACK_BOT_API_KEY:
  40. import slack_bot
  41. services.append(slack_bot.SlackBot(_TOKEN_STREAM))
  42. for s in services:
  43. t = threading.Thread(target=s.run)
  44. t.setDaemon(True)
  45. t.start()
  46. def get_token(timeout=120, preferred_phrases=None):
  47. global PREFERRED_PHRASES
  48. PREFERRED_PHRASES = preferred_phrases
  49. return _TOKEN_STREAM.get_token(timeout)
  50. def get_line(timeout=120, preferred_phrases=None):
  51. global PREFERRED_PHRASES
  52. PREFERRED_PHRASES = preferred_phrases
  53. return _TOKEN_STREAM.get_line(timeout)
  54. def token_available():
  55. return not _TOKEN_STREAM.buffer.empty()
  56. def get_until_terminated(timeout=120, terminators=['done', 'cancel'], preferred_phrases=None):
  57. global PREFERRED_PHRASES
  58. PREFERRED_PHRASES = preferred_phrases
  59. res = []
  60. t = get_token(timeout=timeout, preferred_phrases=preferred_phrases)
  61. while t not in terminators:
  62. res.append(t)
  63. t = get_token(timeout=timeout, preferred_phrases=preferred_phrases)
  64. return res, t
  65. def reset():
  66. for service in _RESET_SERVICES:
  67. service.reset()
  68. _TOKEN_STREAM.reset()