PageRenderTime 49ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/ressources/tts.py

https://gitlab.com/tmartinez69009/googleTTS
Python | 64 lines | 57 code | 3 blank | 4 comment | 3 complexity | a579d62d6ecf5d8abf025c2dda2e177f MD5 | raw file
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from gtts import gTTS
  4. import argparse
  5. import os
  6. import subprocess, time
  7. import hashlib
  8. import requests
  9. # Args
  10. desc = "Creates an mp3 file from spoken text via the Google Text-to-Speech API"
  11. parser = argparse.ArgumentParser(description=desc)
  12. text_group = parser.add_mutually_exclusive_group(required=True)
  13. text_group.add_argument('-t', '--text', help="text to speak")
  14. text_group.add_argument('-f', '--file', help="file to speak")
  15. #args = parser.add_argument("destination", default='cache/out.mp3', help="destination mp3 file", action='store')
  16. args = parser.add_argument('-o', '--option', default='', help="mplayer options")
  17. args = parser.add_argument('-u', '--url', default='', help="tts url")
  18. args = parser.add_argument('-l', '--lang', default='en', help="ISO 639-1 language code to speak in: " + str(gTTS.LANGUAGES))
  19. args = parser.add_argument('--debug', default=False, action="store_true")
  20. args = parser.parse_args()
  21. try:
  22. if args.text:
  23. text = args.text
  24. else:
  25. with open(args.file, "r") as f:
  26. text = f.read()
  27. cachepath=os.path.abspath(os.path.join(os.path.dirname(__file__), 'cache'))
  28. hashtxt = hashlib.md5(args.lang+'-'+text+args.url).hexdigest()
  29. hashfile = hashtxt+'.mp3'
  30. found = 0
  31. for file in os.listdir(cachepath):
  32. print(file)
  33. if str(hashfile) == str(file) :
  34. found=1
  35. print 'fichier trouve'
  36. break
  37. print hashtxt
  38. if found == 0 :
  39. if args.url and len(args.url) > 1:
  40. if args.url == 'pico':
  41. os.system("pico2wave -l "+args.lang+" -w "+cachepath+"/voice.wav \""+text+"\"")
  42. os.system("sox "+cachepath+"/voice.wav -r 48k "+cachepath+"/"+hashfile)
  43. else :
  44. #mp3file = urllib2.urlopen(args.url+'&text='+text)
  45. mp3file = requests.get(args.url.replace('#text#',text), stream=True)
  46. output = open(cachepath+'/'+hashfile,'wb')
  47. output.write(mp3file.content)
  48. output.close()
  49. else :
  50. tts = gTTS(text=text, lang=args.lang, debug=args.debug)
  51. tts.save(cachepath+'/'+hashfile)
  52. cmd = ['mplayer']
  53. cmd.extend(args.option.split())
  54. cmd.append(cachepath+'/'+hashfile)
  55. with open(os.devnull, 'wb') as nul:
  56. subprocess.call(cmd, stdin=nul)
  57. except Exception as e:
  58. print(str(e))