Python3使用訊飛AIUI的WEB API進行開發
阿新 • • 發佈:2018-12-10
解決問題
AIUI的官方文件當中僅有python 2.7的實現, 在python 3 中處理字元編碼方式不同,官方github當中的python 3實現不完整。因此這裡貼出自己在應用中的實現。
環境配置
python 3.5
Github地址
原始碼
import requests
import time
import hashlib
import base64
# from bitarray import bitarray
import json
URL = "http://openapi.xfyun.cn/v2/aiui"
APPID = "" # 你的APP ID
API_KEY = "" # 你的API_KEY
AUE = "raw"
AUTH_ID = "" # 你的AUTH ID
DATA_TYPE = "text" # 明確處理型別 text文字/audio音訊
SAMPLE_RATE = "16000"
SCENE = "main" # 情景值
RESULT_LEVEL = "complete"
LAT = "23.16" # 緯度
LNG = "113.23" # 經度
#個性化引數,需轉義
PERS_PARAM = "{\\\"auth_id\\\":\\\"2894c985bf8b1111c6728db79d3479ae\\\"}"
FILE_PATH = "test.txt" # 如需要從文字中讀取,填寫文字檔案地址,每行為一個輸入
def buildHeader():
curTime = str(int(time.time()))
param = "{\"result_level\":\""+RESULT_LEVEL+"\",\"auth_id\":\""+AUTH_ID+"\",\"data_type\":\""+DATA_TYPE+"\",\"sample_rate\":\""+SAMPLE_RATE+"\",\"scene\":\""+SCENE+"\",\"lat\":\""+LAT+"\",\"lng\":\""+LNG+"\"}"
#使用個性化引數時引數格式如下:
#param = "{\"result_level\":\""+RESULT_LEVEL+"\",\"auth_id\":\""+AUTH_ID+"\",\"data_type\":\""+DATA_TYPE+"\",\"sample_rate\":\""+SAMPLE_RATE+"\",\"scene\":\""+SCENE+"\",\"lat\":\""+LAT+"\",\"lng\":\""+LNG+"\",\"pers_param\":\""+PERS_PARAM+"\"}"
# error: a bytes-like object is required, not 'str'
paramBase64 = base64.b64encode(param.encode('utf-8'))
m2 = hashlib.md5()
print
print('type of paramBase64:', type(paramBase64))
print("(str(paramBase64, 'utf-8')", str(paramBase64, 'utf-8'))
m2.update((API_KEY + curTime + str(paramBase64, 'utf-8')).encode('utf-8'))
checkSum = m2.hexdigest()
# 在 Http Request Header 中配置以下引數用於授權認證
header = {
'X-CurTime': curTime,
'X-Param': paramBase64,
'X-Appid': APPID,
'X-CheckSum': checkSum,
}
return header
def readFile(filePath):
binfile = open(filePath, 'rb')
data = binfile.read()
print('data in file:', data)
return data
def request2Aiui(text):
bintext = str.encode(text)
r = requests.post(URL, headers=buildHeader(), data=bintext)
# if you need to post data in file
# r = requests.post(URL, headers=buildHeader(), data=readFile(FILE_PATH))
content = r.content
# 注意: str轉json之前, 接收到的content內容為二進位制,需進行utf-8轉碼
json_resp = json.loads(content.decode('utf-8'))
code = json_resp['code']
if code == '0':
print('success in response')
# return the response['data']
# 返回的為一個list,每個元素對應一行輸入
return json_resp['data']
else:
# error response
'''
{
"code":"10105",
"desc":"illegal access|illegal client_ip",
"data":[],
"sid":"xxxxxx"
}
'''
#print(json_resp)
#print(content)
raise Exception(json_resp)
if __name__ == '__main__':
try:
test_text = u'今天的天氣怎麼樣'
resp = request2Aiui(test_text)
print(resp)
except Exception as e:
print(e.args)