google.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from time import sleep
  2. import speech_recognition as sr
  3. from kalliope.core import Utils
  4. from kalliope.stt.Utils import SpeechRecognition
  5. class Google(SpeechRecognition):
  6. def __init__(self, callback=None, **kwargs):
  7. """
  8. Start recording the microphone and analyse audio with google api
  9. :param callback: The callback function to call to send the text
  10. :param kwargs:
  11. """
  12. # give the audio file path to process directly to the mother class if exist
  13. SpeechRecognition.__init__(self, kwargs.get('audio_file_path', None))
  14. # callback function to call after the translation speech/tex
  15. self.main_controller_callback = callback
  16. self.key = kwargs.get('key', None)
  17. self.language = kwargs.get('language', "en-US")
  18. self.show_all = kwargs.get('show_all', False)
  19. # set the callback that will process the audio stream
  20. self.set_callback(self.google_callback)
  21. # start processing, record a sample from the microphone if no audio file path provided, else read the file
  22. self.start_processing()
  23. def google_callback(self, recognizer, audio):
  24. """
  25. called from the background thread
  26. """
  27. try:
  28. captured_audio = recognizer.recognize_google(audio,
  29. key=self.key,
  30. language=self.language,
  31. show_all=self.show_all)
  32. Utils.print_success("Google Speech Recognition thinks you said %s" % captured_audio)
  33. self._analyse_audio(audio_to_text=captured_audio)
  34. except sr.UnknownValueError:
  35. Utils.print_warning("Google Speech Recognition could not understand audio")
  36. # callback anyway, we need to listen again for a new order
  37. self._analyse_audio(audio_to_text=None)
  38. except sr.RequestError as e:
  39. Utils.print_danger("Could not request results from Google Speech Recognition service; {0}".format(e))
  40. # callback anyway, we need to listen again for a new order
  41. self._analyse_audio(audio_to_text=None)
  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)