acapela.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import requests
  2. import re
  3. from core import FileManager
  4. from core.TTS.TTSModule import TTSModule, FailToLoadSoundFile, MissingTTSParameter
  5. import logging
  6. logging.basicConfig()
  7. logger = logging.getLogger("kalliope")
  8. TTS_URL = "http://www.acapela-group.com/demo-tts/DemoHTML5Form_V2_fr.php"
  9. TTS_CONTENT_TYPE = "audio/mpeg"
  10. TTS_TIMEOUT_SEC = 30
  11. class Acapela(TTSModule):
  12. def __init__(self, **kwargs):
  13. super(Acapela, self).__init__(**kwargs)
  14. self.voice = kwargs.get('voice', None)
  15. if self.voice is None:
  16. raise MissingTTSParameter("voice parameter is required by the Acapela TTS")
  17. def say(self, words):
  18. """
  19. :param words: The sentence to say
  20. """
  21. self.generate_and_play(words, self._generate_audio_file)
  22. def _generate_audio_file(self):
  23. """
  24. Generic method used as a Callback in TTSModule
  25. - must provided the audio file and write it on the disk
  26. .. raises:: FailToLoadSoundFile
  27. """
  28. # Prepare payload
  29. payload = self.get_payload()
  30. # Get the mp3 URL from the page
  31. url = Acapela.get_audio_link(TTS_URL, payload)
  32. # getting the mp3
  33. r = requests.get(url, params=payload, stream=True, timeout=TTS_TIMEOUT_SEC)
  34. content_type = r.headers['Content-Type']
  35. logger.debug("Acapela : Trying to get url: %s response code: %s and content-type: %s",
  36. r.url,
  37. r.status_code,
  38. content_type)
  39. # Verify the response status code and the response content type
  40. if r.status_code != requests.codes.ok or content_type != TTS_CONTENT_TYPE:
  41. raise FailToLoadSoundFile("Acapela : Fail while trying to remotely access the audio file")
  42. # OK we get the audio we can write the sound file
  43. FileManager.write_in_file(self.file_path, r.content)
  44. def get_payload(self):
  45. """
  46. Generic method used load the payload used to acces the remote api
  47. :return: Payload to use to access the remote api
  48. """
  49. return {
  50. "MyLanguages": self.language,
  51. "MySelectedVoice": self.voice,
  52. "MyTextForTTS": self.words,
  53. "t": "1",
  54. "SendToVaaS": ""
  55. }
  56. @staticmethod
  57. def get_audio_link(url, payload, timeout_expected=TTS_TIMEOUT_SEC):
  58. """
  59. Return the audio link
  60. :param url: the url to access
  61. :param payload: the payload to use to acces the remote api
  62. :param timeout_expected: timeout before the post request is cancel
  63. :return: the audio link
  64. :rtype: String
  65. """
  66. r = requests.post(url, payload, timeout=timeout_expected)
  67. data = r.content
  68. return re.search("(?P<url>https?://[^\s]+).mp3", data).group(0)