61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
|
#usr/bin/python2.7
|
||
|
|
||
|
import requests
|
||
|
import json
|
||
|
|
||
|
class Chatbot:
|
||
|
def init(self, appkey, base_url):
|
||
|
self.appkey = appkey
|
||
|
self.base_url = base_url
|
||
|
|
||
|
# Upload pictures
|
||
|
def upload_img(self, imgpath="test.jpg"):
|
||
|
headers = {
|
||
|
'Authorization': 'Bearer {}'.format(self.appkey),
|
||
|
}
|
||
|
|
||
|
files = {
|
||
|
'file': (imgpath, open(imgpath, 'rb'), 'image/jpg'), # Replace with the actual file path and type
|
||
|
}
|
||
|
try:
|
||
|
response = requests.post(url=self.base_url + '/files/upload', headers=headers, files=files, data={'user': 'robot'})
|
||
|
except Exception as e:
|
||
|
print("error", e)
|
||
|
|
||
|
img_id = json.loads(response.content)["id"]
|
||
|
|
||
|
return img_id
|
||
|
|
||
|
# 计算
|
||
|
def img2text(self, path="./img/test.jpg"):
|
||
|
img_id = self.upload_img(path)
|
||
|
payload = {
|
||
|
"inputs": {},
|
||
|
"query": "What is the answer to this math problem? Please give the numerical answer directly.",
|
||
|
"response_mode": "blocking",
|
||
|
"conversation_id": "",
|
||
|
"user": "robot",
|
||
|
"files": [
|
||
|
{
|
||
|
"type": "image",
|
||
|
"transfer_method": "local_file",
|
||
|
"upload_file_id": img_id
|
||
|
}
|
||
|
]
|
||
|
}
|
||
|
|
||
|
headers = {
|
||
|
'Authorization': 'Bearer {}'.format(self.appkey),
|
||
|
'Content-Type': 'application/json',
|
||
|
}
|
||
|
|
||
|
response = requests.post(url=self.base_url + '/chat-messages', headers=headers, data=json.dumps(payload))
|
||
|
|
||
|
ans = ""
|
||
|
if response.status_code == 200:
|
||
|
for line in response.iter_lines():
|
||
|
if line: # Make sure the row is not empty
|
||
|
temp = json.loads(line)
|
||
|
ans += temp["answer"]
|
||
|
|
||
|
return ans
|