houndify.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. # give the audio file path to process directly to the mother class if exist
  12. SpeechRecognition.__init__(self, kwargs.get('audio_file_path', None))
  13. # callback function to call after the translation speech/tex
  14. self.main_controller_callback = callback
  15. self.client_id = kwargs.get('client_id', None)
  16. self.key = kwargs.get('key', None)
  17. # only english supported
  18. # self.language = kwargs.get('language', "en-US")
  19. self.show_all = kwargs.get('show_all', False)
  20. # start listening in the background
  21. self.set_callback(self.houndify_callback)
  22. # start processing, record a sample from the microphone if no audio file path provided, else read the file
  23. self.start_processing()
  24. def houndify_callback(self, recognizer, audio):
  25. """
  26. called from the background thread
  27. """
  28. try:
  29. captured_audio = recognizer.recognize_houndify(audio,
  30. client_id=self.client_id,
  31. client_key=self.key,
  32. show_all=self.show_all)
  33. Utils.print_success("Houndify Speech Recognition thinks you said %s" % captured_audio)
  34. self._analyse_audio(captured_audio)
  35. except sr.UnknownValueError:
  36. Utils.print_warning("Houndify Speech Recognition could not understand audio")
  37. # callback anyway, we need to listen again for a new order
  38. self._analyse_audio(audio_to_text=None)
  39. except sr.RequestError as e:
  40. Utils.print_danger("Could not request results from Houndify Speech Recognition service; {0}".format(e))
  41. # callback anyway, we need to listen again for a new order
  42. self._analyse_audio(audio_to_text=None)
  43. # stop listening for an audio
  44. self.stop_listening()
  45. def _analyse_audio(self, audio_to_text):
  46. """
  47. Confirm the audio exists and run it in a Callback
  48. :param audio_to_text: the captured audio
  49. """
  50. if self.main_controller_callback is not None:
  51. self.main_controller_callback(audio_to_text)