先去https://console.xfyun.cn/app/myapp 申请APPID和APISecret
一定要购买,不然不能用,新用户免费体验
接下来使用python尝试临时调用
# -*- coding:utf-8 -*-
import hashlib
import base64
import hmac
import time
import random
from urllib.parse import urlencode
import json
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
class Document_Upload:
def __init__(self, APPId, APISecret, timestamp):
self.APPId = APPId
self.APISecret = APISecret
self.Timestamp = timestamp
def get_origin_signature(self):
m2 = hashlib.md5()
data = bytes(self.APPId + self.Timestamp, encoding="utf-8")
m2.update(data)
checkSum = m2.hexdigest()
return checkSum
def get_signature(self):
# 获取原始签名
signature_origin = self.get_origin_signature()
# 使用加密键加密文本
signature = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
digestmod=hashlib.sha1).digest()
# base64密文编码
signature = base64.b64encode(signature).decode(encoding='utf-8')
return signature
def get_header(self):
signature = self.get_signature()
header = {
"appId": self.APPId,
"timestamp": self.Timestamp,
"signature": signature,
}
return header
# 提交网络文件
def get_body(self):
body = {
"file": "",
"url": "文件网络地址 例如: https://xxx.xx.com/xxx.pdf",
"fileName": "文件名, 例如:xxx.pdf",
"fileType": "wiki",
"callbackUrl": "your_callbackUrl"
}
form = MultipartEncoder(
fields=body,
boundary='------------------' + str(random.randint(1e28, 1e29 - 1))
)
return form
# 提交本地文件
def get_files_and_body(self):
body = {
"url": "",
"fileName": "背影.txt",
"fileType": "wiki",
"needSummary": False,
"stepByStep": False,
"callbackUrl": "your_callbackUrl",
}
files = {'file': open('背影.txt', 'rb')}
return files, body
if __name__ == '__main__':
# 先去 开放平台控制台(https://console.xfyun.cn)创建应用,获取下列应用信息进行替换
APPId = "申请的APPId"
APISecret = "申请的APISecret"
curTime = str(int(time.time()))
request_url = "https://chatdoc.xfyun.cn/openapi/fileUpload"
document_upload = Document_Upload(APPId, APISecret, curTime)
headers = document_upload.get_header()
# ******************提交网络文件
# body = document_upload.get_body()
# headers['Content-Type'] = body.content_type
# response = requests.post(request_url, data=body, headers=headers)
# ******************提交本地文件
files, body = document_upload.get_files_and_body()
response = requests.post(request_url, files=files, data=body, headers=headers)
print("请求头", response.request.headers, type(response.request.headers))
print('onMessage:\n' + response.text)
# 文档上传成功
准备一篇作文:
运行以上代码后,会返回一个fileId,该id是上传文件后,生成的
将该fileId放入以下文件:
# -*- coding:utf-8 -*-
import hashlib
import base64
import hmac
import time
from urllib.parse import urlencode
import json
import websocket
import _thread as thread
import ssl
class Document_Q_And_A:
def __init__(self, APPId, APISecret, TimeStamp, OriginUrl):
self.appId = APPId
self.apiSecret = APISecret
self.timeStamp = TimeStamp
self.originUrl = OriginUrl
def get_origin_signature(self):
m2 = hashlib.md5()
data = bytes(self.appId + self.timeStamp, encoding="utf-8")
m2.update(data)
checkSum = m2.hexdigest()
return checkSum
def get_signature(self):
# 获取原始签名
signature_origin = self.get_origin_signature()
# print(signature_origin)
# 使用加密键加密文本
signature = hmac.new(self.apiSecret.encode('utf-8'), signature_origin.encode('utf-8'),
digestmod=hashlib.sha1).digest()
# base64密文编码
signature = base64.b64encode(signature).decode(encoding='utf-8')
# print(signature)
return signature
def get_header(self):
signature = self.get_signature()
header = {
"Content-Type": "application/json",
"appId": self.appId,
"timestamp": self.timeStamp,
"signature": signature
}
return header
def get_url(self):
signature = self.get_signature()
header = {
"appId": self.appId,
"timestamp": self.timeStamp,
"signature": signature
}
return self.originUrl + "?" + f'appId={self.appId}×tamp={self.timeStamp}&signature={signature}'
# 使用urlencode会导致签名乱码
# return self.originUrl + "?" + urlencode(header)
def get_body(self):
data = {
"chatExtends": {
"wikiPromptTpl": "请将以下内容作为已知信息:\n<wikicontent>\n请根据以上内容回答用户的问题。\n问题:<wikiquestion>\n回答:",
"wikiFilterScore": 0.83,
"temperature": 0.5
},
"fileIds": [
"078556196c6643398fedd4eff199a2f9"
],
"messages": [
{
"role": "user",
"content": "父亲在车站买了什么东西?"
}
]
}
return data
# 收到websocket错误的处理
def on_error(ws, error):
print("### error:", error)
# 收到websocket关闭的处理
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
print("关闭代码:", close_status_code)
print("关闭原因:", close_msg)
# 收到websocket连接建立的处理
def on_open(ws):
thread.start_new_thread(run, (ws,))
def run(ws, *args):
data = json.dumps(ws.question)
ws.send(data)
# 收到websocket消息的处理
def on_message(ws, message):
# print(message)
data = json.loads(message)
code = data['code']
if code != 0:
print(f'请求错误: {code}, {data}')
ws.close()
else:
content = data["content"]
status = data["status"]
# print(f'status = {status}')
print(content, end='')
if status == 2:
ws.close()
if __name__ == '__main__':
# 先去 开放平台控制台(https://console.xfyun.cn)创建应用,获取下列应用信息进行替换
APPId = "539f5ee2"
APISecret = "ZGI3NDU5ZTYyN2UxNDZmODkzNjliOTY5"
curTime = str(int(time.time()))
OriginUrl = "wss://chatdoc.xfyun.cn/openapi/chat"
document_Q_And_A = Document_Q_And_A(APPId, APISecret, curTime, OriginUrl)
wsUrl = document_Q_And_A.get_url()
print(wsUrl)
headers = document_Q_And_A.get_header()
body = document_Q_And_A.get_body()
# 禁用WebSocket库的跟踪功能,使其不再输出详细的调试信息。
websocket.enableTrace(False)
ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
ws.appid = APPId
ws.question = body
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
# 文档问答成功
运行即可