ali.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # -*- coding: UTF-8 -*-
  2. from __future__ import division
  3. from ..__load__ import *
  4. import http.client
  5. import urllib.parse
  6. class Ali(object):
  7. def processGETRequest(self, appKey, token, voice, text, format, sampleRate) :
  8. host = 'nls-gateway.cn-shanghai.aliyuncs.com'
  9. url = 'https://' + host + '/stream/v1/tts'
  10. # 设置URL请求参数
  11. url = url + '?appkey=' + appKey
  12. url = url + '&token=' + token
  13. url = url + '&text=' + text
  14. url = url + '&format=' + format
  15. url = url + '&sample_rate=' + str(sampleRate)
  16. url = url + '&voice=' + voice
  17. Demeter.logger.debug(url)
  18. conn = http.client.HTTPSConnection(host)
  19. conn.request(method='GET', url=url)
  20. # 处理服务端返回的响应
  21. response = conn.getresponse()
  22. Demeter.logger.debug('Response status and response reason:')
  23. Demeter.logger.debug(response.status ,response.reason)
  24. contentType = response.getheader('Content-Type')
  25. Demeter.logger.debug(contentType)
  26. body = response.read()
  27. if 'audio/mpeg' == contentType :
  28. Demeter.logger.debug('The GET request succeed!')
  29. tmpfile = writeTempFile(body, '.mp3')
  30. conn.close()
  31. return tmpfile
  32. else :
  33. Demeter.logger.debug('The GET request failed: ' + str(body))
  34. conn.close()
  35. return None
  36. def processPOSTRequest(self, appKey, token, voice, text, format, sampleRate) :
  37. host = 'nls-gateway.cn-shanghai.aliyuncs.com'
  38. url = 'https://' + host + '/stream/v1/tts'
  39. # 设置HTTPS Headers
  40. httpHeaders = {
  41. 'Content-Type': 'application/json'
  42. }
  43. # 设置HTTPS Body
  44. body = {'appkey': appKey, 'token': token, 'text': text, 'format': format, 'sample_rate': sampleRate, 'voice': voice}
  45. body = json.dumps(body)
  46. Demeter.logger.debug('The POST request body content: ' + body)
  47. # Python 2.x 请使用httplib
  48. # conn = httplib.HTTPSConnection(host)
  49. # Python 3.x 请使用http.client
  50. conn = http.client.HTTPSConnection(host)
  51. conn.request(method='POST', url=url, body=body, headers=httpHeaders)
  52. # 处理服务端返回的响应
  53. response = conn.getresponse()
  54. Demeter.logger.debug('Response status and response reason:')
  55. Demeter.logger.debug(response.status ,response.reason)
  56. contentType = response.getheader('Content-Type')
  57. Demeter.logger.debug(contentType)
  58. body = response.read()
  59. if 'audio/mpeg' == contentType :
  60. Demeter.logger.debug('The POST request succeed!')
  61. tmpfile = writeTempFile(body, '.mp3')
  62. conn.close()
  63. return tmpfile
  64. else :
  65. Demeter.logger.critical('The POST request failed: ' + str(body))
  66. conn.close()
  67. return None
  68. def process(self, request, token, audioContent) :
  69. # 读取音频文件
  70. host = 'nls-gateway.cn-shanghai.aliyuncs.com'
  71. # 设置HTTP请求头部
  72. httpHeaders = {
  73. 'X-NLS-Token': token,
  74. 'Content-type': 'application/octet-stream',
  75. 'Content-Length': len(audioContent)
  76. }
  77. conn = http.client.HTTPConnection(host)
  78. conn.request(method='POST', url=request, body=audioContent, headers=httpHeaders)
  79. response = conn.getresponse()
  80. Demeter.logger.debug('Response status and response reason:')
  81. Demeter.logger.debug(response.status ,response.reason)
  82. body = response.read()
  83. try:
  84. Demeter.logger.debug('Recognize response is:')
  85. body = json.loads(body)
  86. Demeter.logger.debug(body)
  87. status = body['status']
  88. if status == 20000000 :
  89. result = body['result']
  90. Demeter.logger.debug('Recognize result: ' + result)
  91. conn.close()
  92. return result
  93. else :
  94. Demeter.logger.critical('Recognizer failed!')
  95. conn.close()
  96. return None
  97. except ValueError:
  98. Demeter.logger.debug('The response is not json format string')
  99. conn.close()
  100. return None
  101. def tts(self, appKey, token, voice, text):
  102. # 采用RFC 3986规范进行urlencode编码
  103. textUrlencode = text
  104. textUrlencode = urllib.parse.quote_plus(textUrlencode)
  105. textUrlencode = textUrlencode.replace("+", "%20")
  106. textUrlencode = textUrlencode.replace("*", "%2A")
  107. textUrlencode = textUrlencode.replace("%7E", "~")
  108. format = 'mp3'
  109. sampleRate = 16000
  110. return self.processPOSTRequest(appKey, token, voice, text, format, sampleRate)
  111. def asr(self, appKey, token, wave_file):
  112. # 服务请求地址
  113. url = 'http://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/asr'
  114. pcm = getPcmFromWav(wave_file)
  115. # 音频文件
  116. format = 'pcm'
  117. sampleRate = 16000
  118. enablePunctuationPrediction = True
  119. enableInverseTextNormalization = True
  120. enableVoiceDetection = False
  121. # 设置RESTful请求参数
  122. request = url + '?appkey=' + appKey
  123. request = request + '&format=' + format
  124. request = request + '&sample_rate=' + str(sampleRate)
  125. if enablePunctuationPrediction :
  126. request = request + '&enable_punctuation_prediction=' + 'true'
  127. if enableInverseTextNormalization :
  128. request = request + '&enable_inverse_text_normalization=' + 'true'
  129. if enableVoiceDetection :
  130. request = request + '&enable_voice_detection=' + 'true'
  131. Demeter.logger.debug('Request: ' + request)
  132. return self.process(request, token, pcm)