acapela.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. self.generate_and_play(words, self._generate_audio_file)
  19. def _generate_audio_file(self):
  20. # Prepare payload
  21. payload = self.get_payload()
  22. # Get the mp3 URL from the page
  23. url = Acapela.get_audio_link(TTS_URL, payload)
  24. # getting the mp3
  25. r = requests.get(url, params=payload, stream=True, timeout=TTS_TIMEOUT_SEC)
  26. content_type = r.headers['Content-Type']
  27. logger.debug("Acapela : Trying to get url: %s response code: %s and content-type: %s",
  28. r.url,
  29. r.status_code,
  30. content_type)
  31. # Verify the response status code and the response content type
  32. if r.status_code != requests.codes.ok or content_type != TTS_CONTENT_TYPE:
  33. raise FailToLoadSoundFile("Acapela : Fail while trying to remotely access the audio file")
  34. # OK we get the audio we can write the sound file
  35. FileManager.write_in_file(self.file_path, r.content)
  36. def get_payload(self):
  37. return {
  38. "MyLanguages": self.language,
  39. "MySelectedVoice": self.voice,
  40. "MyTextForTTS": self.words,
  41. "t": "1",
  42. "SendToVaaS": ""
  43. }
  44. @staticmethod
  45. def get_audio_link(url, payload, timeout_expected=TTS_TIMEOUT_SEC):
  46. r = requests.post(url, payload, timeout=timeout_expected)
  47. data = r.content
  48. return re.search("(?P<url>https?://[^\s]+).mp3", data).group(0)