googletts.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import requests
  2. from kalliope.core import FileManager
  3. from kalliope.core.TTS.TTSModule import TTSModule, FailToLoadSoundFile, MissingTTSParameter
  4. import logging
  5. logging.basicConfig()
  6. logger = logging.getLogger("kalliope")
  7. TTS_URL = "http://translate.google.com/translate_tts"
  8. TTS_CONTENT_TYPE = "audio/mpeg"
  9. TTS_TIMEOUT_SEC = 30
  10. class Googletts(TTSModule):
  11. def __init__(self, **kwargs):
  12. super(Googletts, self).__init__(**kwargs)
  13. self._check_parameters()
  14. def say(self, words):
  15. """
  16. :param words: The sentence to say
  17. """
  18. self.generate_and_play(words, self._generate_audio_file)
  19. def _check_parameters(self):
  20. """
  21. Check parameters are ok, raise MissingTTSParameterException exception otherwise.
  22. :return: true if parameters are ok, raise an exception otherwise
  23. .. raises:: MissingTTSParameterException
  24. """
  25. if self.language == "default" or self.language is None:
  26. raise MissingTTSParameter("[GoogleTTS] Missing parameters, check documentation !")
  27. return True
  28. def _generate_audio_file(self):
  29. """
  30. Generic method used as a Callback in TTSModule
  31. - must provided the audio file and write it on the disk
  32. .. raises:: FailToLoadSoundFile
  33. """
  34. # Prepare payload
  35. payload = self.get_payload()
  36. # getting the audio
  37. r = requests.get(TTS_URL, params=payload, stream=True, timeout=TTS_TIMEOUT_SEC)
  38. content_type = r.headers['Content-Type']
  39. logger.debug("Googletts : Trying to get url: %s response code: %s and content-type: %s",
  40. r.url,
  41. r.status_code,
  42. content_type)
  43. # Verify the response status code and the response content type
  44. if r.status_code != requests.codes.ok or content_type != TTS_CONTENT_TYPE:
  45. raise FailToLoadSoundFile("Googletts : Fail while trying to remotely access the audio file")
  46. # OK we get the audio we can write the sound file
  47. FileManager.write_in_file(self.file_path, r.content)
  48. def get_payload(self):
  49. """
  50. Generic method used load the payload used to access the remote api
  51. :return: Payload to use to access the remote api
  52. """
  53. return {
  54. "q": self.words,
  55. "tl": self.language,
  56. "ie": "UTF-8",
  57. "total": "1",
  58. "client": "tw-ob"
  59. }