wit.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import speech_recognition as sr
  2. from kalliope.core import Utils
  3. from kalliope.stt.Utils import SpeechRecognition
  4. class Wit(SpeechRecognition):
  5. def __init__(self, callback=None, **kwargs):
  6. """
  7. Start recording the microphone and analyse audio with Wit.ai 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.key = kwargs.get('key', None)
  15. self.show_all = kwargs.get('show_all', False)
  16. # start listening in the background
  17. self.set_callback(self.wit_callback)
  18. self.start_listening()
  19. def wit_callback(self, recognizer, audio):
  20. try:
  21. captured_audio = recognizer.recognize_wit(audio,
  22. key=self.key,
  23. show_all=self.show_all)
  24. Utils.print_success("Wit.ai Speech Recognition thinks you said %s" % captured_audio)
  25. self._analyse_audio(captured_audio)
  26. except sr.UnknownValueError:
  27. Utils.print_warning("Wit.ai Speech Recognition could not understand audio")
  28. # callback anyway, we need to listen again for a new order
  29. self._analyse_audio(audio_to_text=None)
  30. except sr.RequestError as e:
  31. Utils.print_danger("Could not request results from Wit.ai Speech Recognition service; {0}".format(e))
  32. # callback anyway, we need to listen again for a new order
  33. self._analyse_audio(audio_to_text=None)
  34. # stop listening for an audio
  35. self.stop_listening()
  36. def _analyse_audio(self, audio_to_text):
  37. """
  38. Confirm the audio exists and run it in a Callback
  39. :param audio_to_text: the captured audio
  40. """
  41. if self.main_controller_callback is not None:
  42. self.main_controller_callback(audio_to_text)