bing.py 2.2 KB

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