voicerss.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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://www.voicerss.org/controls/speech.ashx"
  8. TTS_CONTENT_TYPE = "audio/mpeg"
  9. TTS_TIMEOUT_SEC = 30
  10. class Voicerss(TTSModule):
  11. def __init__(self, **kwargs):
  12. super(Voicerss, 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("[voicerss] 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("Voicerss : 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("Voicerss : 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. "src": self.words,
  55. "hl": self.language,
  56. "c": "mp3"
  57. }