|
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- import websocket
- import datetime
- import hashlib
- import base64
- import hmac
- import json
- from urllib.parse import urlencode
- import time
- import ssl
- from wsgiref.handlers import format_date_time
- from datetime import datetime
- from time import mktime
- import _thread as thread
- import os
- import wave
-
-
- STATUS_FIRST_FRAME = 0
- STATUS_CONTINUE_FRAME = 1
- STATUS_LAST_FRAME = 2
-
-
-
- global whole_dict
-
- global wsParam
-
-
-
- class Ws_Param(object):
-
- def __init__(self, APPID, APIKey, APISecret,BusinessArgs, AudioFile):
- self.APPID = APPID
- self.APIKey = APIKey
- self.APISecret = APISecret
- self.AudioFile = AudioFile
- self.BusinessArgs = BusinessArgs
-
- self.CommonArgs = {"app_id": self.APPID}
-
-
-
-
- def create_url(self):
- url = 'wss://ws-api.xfyun.cn/v2/iat'
-
- now = datetime.now()
- date = format_date_time(mktime(now.timetuple()))
-
-
- signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
- signature_origin += "date: " + date + "\n"
- signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
-
- signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
- digestmod=hashlib.sha256).digest()
- signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
-
- authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
- self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
- authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
-
- v = {
- "authorization": authorization,
- "date": date,
- "host": "ws-api.xfyun.cn"
- }
-
- url = url + '?' + urlencode(v)
-
-
-
-
- return url
-
-
-
- def on_message(ws, message):
- global whole_dict
- try:
- code = json.loads(message)["code"]
- sid = json.loads(message)["sid"]
- if code != 0:
- errMsg = json.loads(message)["message"]
- print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
- else:
- temp1 = json.loads(message)["data"]["result"]
- data = json.loads(message)["data"]["result"]["ws"]
- sn = temp1["sn"]
- if "rg" in temp1.keys():
- rep = temp1["rg"]
- rep_start = rep[0]
- rep_end = rep[1]
- for sn in range(rep_start,rep_end+1):
-
-
- whole_dict.pop(sn,None)
-
- results = ""
- for i in data:
- for w in i["cw"]:
- results += w["w"]
- whole_dict[sn]=results
-
- else:
- results = ""
- for i in data:
- for w in i["cw"]:
- results += w["w"]
- whole_dict[sn]=results
-
- except Exception as e:
- print("receive msg,but parse exception:", e)
-
-
-
-
- def on_error(ws, error):
- print("### error:", error)
-
-
-
- def on_close(ws,a,b):
- print("### closed ###")
-
-
-
- def on_open(ws):
- global wsParam
- def run(*args):
- frameSize = 8000
- intervel = 0.04
- status = STATUS_FIRST_FRAME
-
- with wave.open(wsParam.AudioFile, "rb") as fp:
- while True:
- buf = fp.readframes(frameSize)
-
- if not buf:
- status = STATUS_LAST_FRAME
-
-
-
- if status == STATUS_FIRST_FRAME:
- d = {"common": wsParam.CommonArgs,
- "business": wsParam.BusinessArgs,
- "data": {"status": 0, "format": "audio/L16;rate=16000","audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw"}}
- d = json.dumps(d)
- ws.send(d)
- status = STATUS_CONTINUE_FRAME
-
- elif status == STATUS_CONTINUE_FRAME:
- d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), 'utf-8'),
- "encoding": "raw"}}
- ws.send(json.dumps(d))
-
- elif status == STATUS_LAST_FRAME:
- d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
- "audio": str(base64.b64encode(buf), 'utf-8'),
- "encoding": "raw"}}
- ws.send(json.dumps(d))
- time.sleep(1)
- break
-
- time.sleep(intervel)
- ws.close()
-
- thread.start_new_thread(run, ())
-
-
- def xunfei_asr(APPID,APISecret,APIKey,BusinessArgsASR,AudioFile):
- global whole_dict
- global wsParam
- whole_dict = {}
- wsParam1 = Ws_Param(APPID=APPID, APISecret=APISecret,
- APIKey=APIKey,BusinessArgs=BusinessArgsASR,
- AudioFile=AudioFile)
-
- wsParam = wsParam1
- websocket.enableTrace(False)
- wsUrl = wsParam.create_url()
- ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
- ws.on_open = on_open
- ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
-
- whole_words = ""
- for i in sorted(whole_dict.keys()):
- whole_words += whole_dict[i]
- return whole_words
-
-
|