You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

210 satır
8.4KB

  1. # -*- coding:utf-8 -*-
  2. #
  3. # Author: njnuko
  4. # Email: njnuko@163.com
  5. #
  6. # 这个文档是基于官方的demo来改的,固体官方demo文档请参考官网
  7. #
  8. # 语音听写流式 WebAPI 接口调用示例 接口文档(必看):https://doc.xfyun.cn/rest_api/语音听写(流式版).html
  9. # webapi 听写服务参考帖子(必看):http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=38947&extra=
  10. # 语音听写流式WebAPI 服务,热词使用方式:登陆开放平台https://www.xfyun.cn/后,找到控制台--我的应用---语音听写(流式)---服务管理--个性化热词,
  11. # 设置热词
  12. # 注意:热词只能在识别的时候会增加热词的识别权重,需要注意的是增加相应词条的识别率,但并不是绝对的,具体效果以您测试为准。
  13. # 语音听写流式WebAPI 服务,方言试用方法:登陆开放平台https://www.xfyun.cn/后,找到控制台--我的应用---语音听写(流式)---服务管理--识别语种列表
  14. # 可添加语种或方言,添加后会显示该方言的参数值
  15. # 错误码链接:https://www.xfyun.cn/document/error-code (code返回错误码时必看)
  16. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
  17. import websocket
  18. import datetime
  19. import hashlib
  20. import base64
  21. import hmac
  22. import json
  23. from urllib.parse import urlencode
  24. import time
  25. import ssl
  26. from wsgiref.handlers import format_date_time
  27. from datetime import datetime
  28. from time import mktime
  29. import _thread as thread
  30. import os
  31. import wave
  32. STATUS_FIRST_FRAME = 0 # 第一帧的标识
  33. STATUS_CONTINUE_FRAME = 1 # 中间帧标识
  34. STATUS_LAST_FRAME = 2 # 最后一帧的标识
  35. #############
  36. #whole_dict 是用来存储返回值的,由于带语音修正,所以用dict来存储,有更新的化pop之前的值,最后再合并
  37. global whole_dict
  38. #这个文档是官方文档改的,这个参数是用来做函数调用时用的
  39. global wsParam
  40. ##############
  41. class Ws_Param(object):
  42. # 初始化
  43. def __init__(self, APPID, APIKey, APISecret,BusinessArgs, AudioFile):
  44. self.APPID = APPID
  45. self.APIKey = APIKey
  46. self.APISecret = APISecret
  47. self.AudioFile = AudioFile
  48. self.BusinessArgs = BusinessArgs
  49. # 公共参数(common)
  50. self.CommonArgs = {"app_id": self.APPID}
  51. # 业务参数(business),更多个性化参数可在官网查看
  52. #self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000}
  53. # 生成url
  54. def create_url(self):
  55. url = 'wss://ws-api.xfyun.cn/v2/iat'
  56. # 生成RFC1123格式的时间戳
  57. now = datetime.now()
  58. date = format_date_time(mktime(now.timetuple()))
  59. # 拼接字符串
  60. signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
  61. signature_origin += "date: " + date + "\n"
  62. signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
  63. # 进行hmac-sha256进行加密
  64. signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
  65. digestmod=hashlib.sha256).digest()
  66. signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
  67. authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
  68. self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
  69. authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
  70. # 将请求的鉴权参数组合为字典
  71. v = {
  72. "authorization": authorization,
  73. "date": date,
  74. "host": "ws-api.xfyun.cn"
  75. }
  76. # 拼接鉴权参数,生成url
  77. url = url + '?' + urlencode(v)
  78. #print("date: ",date)
  79. #print("v: ",v)
  80. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  81. #print('websocket url :', url)
  82. return url
  83. # 收到websocket消息的处理
  84. def on_message(ws, message):
  85. global whole_dict
  86. try:
  87. code = json.loads(message)["code"]
  88. sid = json.loads(message)["sid"]
  89. if code != 0:
  90. errMsg = json.loads(message)["message"]
  91. print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
  92. else:
  93. temp1 = json.loads(message)["data"]["result"]
  94. data = json.loads(message)["data"]["result"]["ws"]
  95. sn = temp1["sn"]
  96. if "rg" in temp1.keys():
  97. rep = temp1["rg"]
  98. rep_start = rep[0]
  99. rep_end = rep[1]
  100. for sn in range(rep_start,rep_end+1):
  101. #print("before pop",whole_dict)
  102. #print("sn",sn)
  103. whole_dict.pop(sn,None)
  104. #print("after pop",whole_dict)
  105. results = ""
  106. for i in data:
  107. for w in i["cw"]:
  108. results += w["w"]
  109. whole_dict[sn]=results
  110. #print("after add",whole_dict)
  111. else:
  112. results = ""
  113. for i in data:
  114. for w in i["cw"]:
  115. results += w["w"]
  116. whole_dict[sn]=results
  117. #print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)))
  118. except Exception as e:
  119. print("receive msg,but parse exception:", e)
  120. # 收到websocket错误的处理
  121. def on_error(ws, error):
  122. print("### error:", error)
  123. # 收到websocket关闭的处理
  124. def on_close(ws,a,b):
  125. print("### closed ###")
  126. # 收到websocket连接建立的处理
  127. def on_open(ws):
  128. global wsParam
  129. def run(*args):
  130. frameSize = 8000 # 每一帧的音频大小
  131. intervel = 0.04 # 发送音频间隔(单位:s)
  132. status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧
  133. with wave.open(wsParam.AudioFile, "rb") as fp:
  134. while True:
  135. buf = fp.readframes(frameSize)
  136. # 文件结束
  137. if not buf:
  138. status = STATUS_LAST_FRAME
  139. # 第一帧处理
  140. # 发送第一帧音频,带business 参数
  141. # appid 必须带上,只需第一帧发送
  142. if status == STATUS_FIRST_FRAME:
  143. d = {"common": wsParam.CommonArgs,
  144. "business": wsParam.BusinessArgs,
  145. "data": {"status": 0, "format": "audio/L16;rate=16000","audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw"}}
  146. d = json.dumps(d)
  147. ws.send(d)
  148. status = STATUS_CONTINUE_FRAME
  149. # 中间帧处理
  150. elif status == STATUS_CONTINUE_FRAME:
  151. d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
  152. "audio": str(base64.b64encode(buf), 'utf-8'),
  153. "encoding": "raw"}}
  154. ws.send(json.dumps(d))
  155. # 最后一帧处理
  156. elif status == STATUS_LAST_FRAME:
  157. d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
  158. "audio": str(base64.b64encode(buf), 'utf-8'),
  159. "encoding": "raw"}}
  160. ws.send(json.dumps(d))
  161. time.sleep(1)
  162. break
  163. # 模拟音频采样间隔
  164. time.sleep(intervel)
  165. ws.close()
  166. thread.start_new_thread(run, ())
  167. #提供给xunfei_voice调用的函数
  168. def xunfei_asr(APPID,APISecret,APIKey,BusinessArgsASR,AudioFile):
  169. global whole_dict
  170. global wsParam
  171. whole_dict = {}
  172. wsParam1 = Ws_Param(APPID=APPID, APISecret=APISecret,
  173. APIKey=APIKey,BusinessArgs=BusinessArgsASR,
  174. AudioFile=AudioFile)
  175. #wsParam是global变量,给上面on_open函数调用使用的
  176. wsParam = wsParam1
  177. websocket.enableTrace(True)
  178. wsUrl = wsParam.create_url()
  179. ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
  180. ws.on_open = on_open
  181. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  182. #把字典的值合并起来做最后识别的输出
  183. whole_words = ""
  184. for i in sorted(whole_dict.keys()):
  185. whole_words += whole_dict[i]
  186. return whole_words