voxygen.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import hashlib
  2. import os
  3. import shutil
  4. import pygame
  5. import requests
  6. import logging
  7. VOXYGEN_LANGUAGES = dict(
  8. fr=dict(electra="Electra", emma="Emma", becool="Becool", agnes="Agnes", loic="Loic", fabienne="Fabienne", helene="Helene", marion="Marion", matteo="Matteo",
  9. melodine="Melodine", mendoo="Mendoo", michel="Michel", moussa="Moussa", philippe="Philippe", sorciere="Sorciere"),
  10. ar=dict(adel="Adel"),
  11. de=dict(matthias="Matthias", jylvia="Sylvia"),
  12. uk=dict(bronwen="Bronwen", elizabeth="elizabeth", judith="Judith", paul="Paul", witch="Witch"),
  13. us=dict(bruce="Bruce", jenny="Jenny"),
  14. es=dict(martha="Martha"),
  15. it=dict(sonia="Sonia"))
  16. CACHE_PATH = "/tmp/jarvis/tts/voxygen/"
  17. def say(words=None, voice=None, language=None, cache=None):
  18. if not os.path.exists(CACHE_PATH):
  19. os.makedirs(CACHE_PATH)
  20. sha1 = hashlib.sha1(words).hexdigest()
  21. tempfile = CACHE_PATH + voice + "." + sha1 + ".tts"
  22. get_audio(voice, words, tempfile, cache)
  23. play_audio(tempfile)
  24. if not cache:
  25. os.remove(tempfile)
  26. def get_audio(voice, text, filepath, cache):
  27. if not cache or not os.path.exists(filepath):
  28. payload = {
  29. "method": "redirect",
  30. "text": text.encode('utf8'),
  31. "voice": voice
  32. }
  33. r = requests.get("https://www.voxygen.fr/sites/all/modules/voxygen_voices/assets/proxy/index.php", params=payload, stream=True)
  34. logging.debug("Trying to get url: %s response code: %s", r.url, r.status_code)
  35. if r.status_code == 200:
  36. with open(os.path.abspath(filepath), "wb") as sound_file:
  37. sound_file.write(r.content)
  38. def play_audio(music_file, volume=0.8):
  39. pygame.mixer.init(16000, -16, 1, 2048)
  40. pygame.mixer.music.set_volume(volume)
  41. clock = pygame.time.Clock()
  42. try:
  43. pygame.mixer.music.load(music_file)
  44. logging.debug("Music file {} loaded!".format(music_file))
  45. except pygame.error:
  46. os.remove(music_file)
  47. logging.debug("File {} not found! ({})".format(music_file, pygame.get_error()))
  48. return
  49. pygame.mixer.music.play()
  50. while pygame.mixer.music.get_busy():
  51. clock.tick(10)
  52. def get_voice(voice=None, language=None):
  53. if language in VOXYGEN_LANGUAGES:
  54. if voice in VOXYGEN_LANGUAGES[language]:
  55. return VOXYGEN_LANGUAGES[language][voice]
  56. logging.debug("Cannot find language maching language: %s voice: %s", language, voice)
  57. return ""
  58. def wipe_cache():
  59. shutil.rmtree(CACHE_PATH)