houndify.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import speech_recognition as sr
  2. from kalliope.core import Utils
  3. from kalliope.stt.Utils import SpeechRecognition
  4. class Houndify(SpeechRecognition):
  5. def __init__(self, callback=None, **kwargs):
  6. """
  7. Start recording the microphone and analyse audio with Houndify api
  8. :param callback: The callback function to call to send the text
  9. :param kwargs:
  10. """
  11. SpeechRecognition.__init__(self)
  12. # callback function to call after the translation speech/tex
  13. self.main_controller_callback = callback
  14. self.client_id = kwargs.get('client_id', None)
  15. self.key = kwargs.get('key', None)
  16. # only english supported
  17. # self.language = kwargs.get('language', "en-US")
  18. self.show_all = kwargs.get('show_all', False)
  19. # start listening in the background
  20. self.set_callback(self.houndify_callback)
  21. self.start_listening()
  22. def houndify_callback(self, recognizer, audio):
  23. """
  24. called from the background thread
  25. """
  26. try:
  27. captured_audio = recognizer.recognize_houndify(audio,
  28. client_id=self.client_id,
  29. client_key=self.key,
  30. show_all=self.show_all)
  31. Utils.print_success("Houndify Speech Recognition thinks you said %s" % captured_audio)
  32. self._analyse_audio(captured_audio)
  33. except sr.UnknownValueError:
  34. Utils.print_warning("Houndify Speech Recognition could not understand audio")
  35. # callback anyway, we need to listen again for a new order
  36. self._analyse_audio(audio_to_text=None)
  37. except sr.RequestError as e:
  38. Utils.print_danger("Could not request results from Houndify Speech Recognition service; {0}".format(e))
  39. # callback anyway, we need to listen again for a new order
  40. self._analyse_audio(audio_to_text=None)
  41. # stop listening for an audio
  42. self.stop_listening()
  43. def _analyse_audio(self, audio_to_text):
  44. """
  45. Confirm the audio exists and run it in a Callback
  46. :param audio_to_text: the captured audio
  47. """
  48. if self.main_controller_callback is not None:
  49. self.main_controller_callback(audio_to_text)