acapela.py 1.9 KB

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