__init__.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import Queue
  2. import threading
  3. import console
  4. import google_cloud_speech
  5. LANGUAGE = 'en-GB'
  6. PREFERRED_PHRASES = None
  7. _TOKEN_STREAM = None
  8. class TokenStream(object):
  9. def __init__(self):
  10. self.preferred_phrases = None
  11. self.buffer = Queue.Queue()
  12. def add_token(self, token):
  13. self.buffer.put(token)
  14. def get_token(self, timeout):
  15. try:
  16. return self.buffer.get(timeout=timeout).strip().lower()
  17. except Queue.Empty:
  18. return None
  19. def get_line(self, timeout):
  20. return self.get_token(timeout)
  21. def launch_input_sources():
  22. global _TOKEN_STREAM
  23. _TOKEN_STREAM = TokenStream()
  24. services = [
  25. console.ConsoleInput(_TOKEN_STREAM),
  26. google_cloud_speech.GoogleCloudSpeech(_TOKEN_STREAM),
  27. ]
  28. for s in services:
  29. t = threading.Thread(target=s.run)
  30. t.setDaemon(True)
  31. t.start()
  32. def get_token(timeout=120, preferred_phrases=None):
  33. return _TOKEN_STREAM.get_token(timeout)
  34. def get_line(timeout=120, preferred_phrases=None):
  35. return _TOKEN_STREAM.get_line(timeout)
  36. def token_available():
  37. return not _TOKEN_STREAM.buffer.empty()
  38. def get_until_terminated(timeout=120, terminators=['done', 'cancel'], preferred_phrases=None):
  39. res = []
  40. t = get_token(timeout=timeout, preferred_phrases=preferred_phrases)
  41. while t not in terminators:
  42. res.append(t)
  43. t = get_token(timeout=timeout, preferred_phrases=preferred_phrases)
  44. return res, t