googletts.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import requests
  2. from core import FileManager
  3. from core.TTS.TTSModule import TTSModule, FailToLoadSoundFile
  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. def say(self, words):
  14. """
  15. :param words: The sentence to say
  16. """
  17. self.generate_and_play(words, self._generate_audio_file)
  18. def _generate_audio_file(self):
  19. """
  20. Generic method used as a Callback in TTSModule
  21. - must provided the audio file and write it on the disk
  22. .. raises:: FailToLoadSoundFile
  23. """
  24. # Prepare payload
  25. payload = self.get_payload()
  26. # getting the audio
  27. r = requests.get(TTS_URL, params=payload, stream=True, timeout=TTS_TIMEOUT_SEC)
  28. content_type = r.headers['Content-Type']
  29. logger.debug("Googletts : Trying to get url: %s response code: %s and content-type: %s",
  30. r.url,
  31. r.status_code,
  32. content_type)
  33. # Verify the response status code and the response content type
  34. if r.status_code != requests.codes.ok or content_type != TTS_CONTENT_TYPE:
  35. raise FailToLoadSoundFile("Googletts : Fail while trying to remotely access the audio file")
  36. # OK we get the audio we can write the sound file
  37. FileManager.write_in_file(self.file_path, r.content)
  38. def get_payload(self):
  39. """
  40. Generic method used load the payload used to access the remote api
  41. :return: Payload to use to access the remote api
  42. """
  43. return {
  44. "q": self.words,
  45. "tl": self.language,
  46. "ie": "UTF-8",
  47. "total": "1",
  48. "client": "tw-ob"
  49. }