AliSpeech.py 5.0 KB

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