googletts.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. self.generate_and_play(words, self._generate_audio_file)
  15. def _generate_audio_file(self):
  16. # Prepare payload
  17. payload = self.get_payload()
  18. # getting the audio
  19. r = requests.get(TTS_URL, params=payload, stream=True, timeout=TTS_TIMEOUT_SEC)
  20. content_type = r.headers['Content-Type']
  21. logger.debug("Googletts : Trying to get url: %s response code: %s and content-type: %s",
  22. r.url,
  23. r.status_code,
  24. content_type)
  25. # Verify the response status code and the response content type
  26. if r.status_code != requests.codes.ok or content_type != TTS_CONTENT_TYPE:
  27. raise FailToLoadSoundFile("Googletts : Fail while trying to remotely access the audio file")
  28. # OK we get the audio we can write the sound file
  29. FileManager.write_in_file(self.file_path, r.content)
  30. def get_payload(self):
  31. return {
  32. "q": self.words,
  33. "tl": self.language,
  34. "ie": "UTF-8",
  35. "total": "1",
  36. "client": "tw-ob"
  37. }