Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.70 KB | None | 0 0
  1. ToolsAE.py
  2.  
  3. # -*- coding: utf-8 -*-
  4. import os, stat, time, json, hashlib
  5. import urllib3.request, requests
  6. import subprocess
  7.  
  8. class IamToken(object):
  9. def __init__(self):
  10. self.filename = '/var/lib/asterisk/agi-bin/iam.token'
  11. self.expireTime = 60*60*11
  12.  
  13. def get(self):
  14. self.__iamUpdate()
  15. with open(self.filename) as f:
  16. key = f.read()
  17. return key.rstrip()
  18.  
  19. def __iamUpdate(self):
  20. modTimeIam = int(os.path.getmtime(self.filename))
  21. curTime = int(time.time())
  22. if modTimeIam < curTime-self.expireTime:
  23. iamCmd = subprocess.Popen(['/usr/local/bin/yc','iam', 'create-token'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  24. out, err = iamCmd.communicate()
  25. with open(self.filename, "w") as f:
  26. f.write(out.rstrip())
  27.  
  28. class YandexSpeechSTT(object):
  29. def __init__(self, folderId, iamToken):
  30. self.folderId = folderId
  31. self.iamToken = iamToken
  32.  
  33. def __convertAudio(self, fileSrc, fileDst):
  34. convertCmd = subprocess.Popen(['/usr/bin/opusenc', fileSrc, fileDst], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  35. output, error = convertCmd.communicate()
  36. if convertCmd.returncode != 0:
  37. raise Exception(error.strip())
  38. os.remove(fileSrc)
  39.  
  40. def convertVoiceToText(self, fileSrc, topic):
  41. import urllib2
  42. fileDst = '/tmp/' + os.path.splitext(os.path.basename(fileSrc))[0] + '.ogg'
  43. self.__convertAudio(fileSrc, fileDst)
  44.  
  45. with open(fileDst, "rb") as f:
  46. data = f.read()
  47.  
  48. params = "&".join([
  49. "topic=%s" % topic,
  50. "folderId=%s" % self.folderId,
  51. "lang=ru-RU"
  52. ])
  53.  
  54. url = urllib2.Request("https://stt.api.cloud.yandex.net/speech/v1/stt:recognize?%s" % params, data=data)
  55. url.add_header("Authorization", "Bearer %s" % self.iamToken)
  56.  
  57. responseData = urllib2.urlopen(url).read().decode('UTF-8')
  58. decodedData = json.loads(responseData)
  59.  
  60. if decodedData.get("error_code") is None:
  61. os.remove(fileDst)
  62. return decodedData.get("result")
  63. else:
  64. raise Exception("Error_code: %s, message: %s" % (decodedData.get("error_code"), decodedData.get("error_message")))
  65.  
  66. class YandexSpeechTTS(object):
  67. def __init__(self, folderId, iamToken):
  68. self.folderId = folderId
  69. self.iamToken = iamToken
  70. self.dstPath = '/var/lib/asterisk/sounds/ru/ysc'
  71. self.dstMd5Path = '/var/lib/asterisk/sounds/ru/ysc/md5'
  72.  
  73. def __synthesize(self, text):
  74. url = 'https://tts.api.cloud.yandex.net/speech/v1/tts:synthesize'
  75. headers = {'Authorization': 'Bearer ' + self.iamToken,}
  76.  
  77. data = {
  78. 'text': text,
  79. 'lang': 'ru-RU',
  80. 'folderId': self.folderId,
  81. 'format': 'lpcm',
  82. 'emotion': 'neutral',
  83. 'speed': '1.0',
  84. 'voice': 'jane',
  85. 'sampleRateHertz': 48000,
  86. }
  87.  
  88. resp = requests.post(url, headers=headers, data=data, stream=True, verify=False)
  89. if resp.status_code != 200:
  90. raise Exception("Invalid response received: code: %d, message: %s" % (resp.status_code, resp.text))
  91. for chunk in resp.iter_content(chunk_size=None):
  92. yield chunk
  93.  
  94. def __textToHashFname(self, hash, text):
  95. with open(self.dstMd5Path + "/" + hash, "w") as f:
  96. f.write(text)
  97.  
  98. def __convertAudio(self, typ, fileSrc, fileDst, text):
  99. if typ == 'ast':
  100. convertCmd = subprocess.Popen(['/usr/bin/sox', fileSrc, '-e', 'a-law', '-t', 'RAW', '-r', '8000', '-c', '1', fileDst], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  101. if typ == 'raw':
  102. convertCmd = subprocess.Popen(['/usr/bin/sox', '-r', '48000', '-b', '16', '-e', 'signed-integer', '-c', '1', fileSrc, fileDst], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  103. self.__textToHashFname(textToHash(text),text)
  104. output, error = convertCmd.communicate()
  105. if convertCmd.returncode != 0:
  106. raise Exception(error.strip())
  107.  
  108. def ToFile(self, filename, text):
  109. fileSrc = self.dstPath + "/" + filename + '.raw'
  110. fileDst = self.dstPath + "/" + filename + '.wav'
  111. fileAster = self.dstPath + "/" + filename + '.alaw'
  112. exPath = self.dstMd5Path + "/" + textToHash(text)
  113.  
  114. if os.path.isfile(exPath) and os.path.isfile(fileAster):
  115. return
  116.  
  117. with open(fileSrc, "wb") as f:
  118. for audio_content in self.__synthesize(text):
  119. f.write(audio_content)
  120.  
  121. self.__convertAudio('raw', fileSrc, fileDst, text)
  122. os.remove(fileSrc)
  123. self.__convertAudio('ast', fileDst, fileAster, text)
  124. os.remove(fileDst)
  125.  
  126. def textToHash(text):
  127. return hashlib.md5(text).hexdigest()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement