voxygen.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. voice = get_voice(voice, language)
  22. tempfile = CACHE_PATH + voice + "." + sha1 + ".tts"
  23. get_audio(voice, words, tempfile, cache)
  24. play_audio(tempfile)
  25. if not cache:
  26. os.remove(tempfile)
  27. def get_audio(voice, text, filepath, cache):
  28. if not cache or not os.path.exists(filepath):
  29. payload = {
  30. "method": "redirect",
  31. "text": text.encode('utf8'),
  32. "voice": voice
  33. }
  34. r = requests.get("https://www.voxygen.fr/sites/all/modules/voxygen_voices/assets/proxy/index.php", params=payload, stream=True)
  35. logging.debug("Trying to get url: %s response code: %s", r.url, r.status_code)
  36. if r.status_code == 200:
  37. with open(os.path.abspath(filepath), "wb") as sound_file:
  38. sound_file.write(r.content)
  39. def play_audio(music_file, volume=0.8):
  40. pygame.mixer.init(16000, -16, 1, 2048)
  41. pygame.mixer.music.set_volume(volume)
  42. clock = pygame.time.Clock()
  43. try:
  44. pygame.mixer.music.load(music_file)
  45. logging.debug("Music file {} loaded!".format(music_file))
  46. except pygame.error:
  47. os.remove(music_file)
  48. logging.debug("File {} not found! ({})".format(music_file, pygame.get_error()))
  49. return
  50. pygame.mixer.music.play()
  51. while pygame.mixer.music.get_busy():
  52. clock.tick(10)
  53. def get_voice(voice=None, language=None):
  54. if language in VOXYGEN_LANGUAGES:
  55. if voice in VOXYGEN_LANGUAGES[language]:
  56. return VOXYGEN_LANGUAGES[language][voice]
  57. logging.debug("Cannot find language maching language: %s voice: %s", language, voice)
  58. return ""
  59. def wipe_cache():
  60. shutil.rmtree(CACHE_PATH)