Apiai.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import speech_recognition as sr
  2. from core import Utils
  3. from core.OrderListener import OrderListener
  4. class Apiai(OrderListener):
  5. def __init__(self, callback=None, **kwargs):
  6. """
  7. Start recording the microphone and analyse audio with Apiai api
  8. :param callback: The callback function to call to send the text
  9. :param kwargs:
  10. """
  11. OrderListener.__init__(self)
  12. """
  13. Start recording the microphone
  14. :return:
  15. """
  16. # callback function to call after the translation speech/tex
  17. self.callback = callback
  18. # obtain audio from the microphone
  19. r = sr.Recognizer()
  20. with sr.Microphone() as source:
  21. # listen for 1 second to calibrate the energy threshold for ambient noise levels
  22. r.adjust_for_ambient_noise(source)
  23. Utils.print_info("Say something!")
  24. audio = r.listen(source)
  25. # recognize speech using Apiai Speech Recognition
  26. try:
  27. key = kwargs.get('key', None)
  28. language = kwargs.get('language', "en")
  29. session_id= kwargs.get('session_id', None)
  30. show_all = kwargs.get('show_all', False)
  31. captured_audio = r.recognize_api(audio, client_access_token=key, language=language, session_id=session_id, show_all=show_all)
  32. Utils.print_success("Apiai Speech Recognition thinks you said %s" % captured_audio)
  33. self._analyse_audio(captured_audio)
  34. except sr.UnknownValueError as e:
  35. Utils.print_warning("Apiai Speech Recognition could not understand audio; {0}".format(e))
  36. except sr.RequestError as e:
  37. Utils.print_danger("Could not request results from Apiai Speech Recognition service; {0}".format(e))
  38. def _analyse_audio(self, audio):
  39. # if self.main_controller is not None:
  40. # self.main_controller.analyse_order(audio)
  41. if self.callback is not None:
  42. self.callback(audio)