acapela.py 2.5 KB

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