Python3使用讯飞AIUI的WEB API进行开发

解决问题

AIUI的官方文档当中仅有python 2.7的实现, 在python 3 中处理字符编码方式不同,官方github当中的python 3实现不完整。因此这里贴出自己在应用中的实现。

环境配置

python 3.5

Github地址

https://github.com/chrispinkyang/AIUI_Web_API.git

源码

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)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值