Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
|
4 |
+
|
5 |
+
# 读取图片
|
6 |
+
import base64
|
7 |
+
# Function to encode the image
|
8 |
+
def encode_image(image_path):
|
9 |
+
with open(image_path, "rb") as image_file:
|
10 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
11 |
+
|
12 |
+
import requests
|
13 |
+
import os
|
14 |
+
|
15 |
+
openai_api_key = os.environ.get('openai_api_key')
|
16 |
+
|
17 |
+
def ask_image(image,text,api_token=openai_api_key):
|
18 |
+
base64_image = encode_image(image)
|
19 |
+
messages=[
|
20 |
+
{
|
21 |
+
"role": "user",
|
22 |
+
"content": [
|
23 |
+
{"type": "text", "text": text},
|
24 |
+
{
|
25 |
+
"type": "image_url",
|
26 |
+
"image_url": {
|
27 |
+
"url":f"data:image/jpeg;base64,{base64_image}"
|
28 |
+
# "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
|
29 |
+
},
|
30 |
+
},
|
31 |
+
],
|
32 |
+
}
|
33 |
+
]
|
34 |
+
|
35 |
+
# 请求头部信息
|
36 |
+
headers = {
|
37 |
+
'Authorization': f'Bearer {api_token}'
|
38 |
+
}
|
39 |
+
|
40 |
+
# 请求体信息
|
41 |
+
data = {
|
42 |
+
'model': 'gpt-4o', # 可以根据需要更换其他模型
|
43 |
+
'messages': messages,
|
44 |
+
'temperature': 0.7 # 可以根据需要调整
|
45 |
+
}
|
46 |
+
|
47 |
+
|
48 |
+
# 设定最大重试次数
|
49 |
+
max_retry = 3
|
50 |
+
|
51 |
+
for i in range(max_retry):
|
52 |
+
try:
|
53 |
+
# 发送请求
|
54 |
+
response = requests.post('https://burn.hair/v1/chat/completions', headers=headers, json=data)
|
55 |
+
|
56 |
+
# 解析响应内容
|
57 |
+
response_data = response.json()
|
58 |
+
response_content = response_data['choices'][0]['message']['content']
|
59 |
+
usage = response_data['usage']
|
60 |
+
|
61 |
+
return response_content
|
62 |
+
|
63 |
+
except Exception as e:
|
64 |
+
# 如果已经达到最大重试次数,那么返回空值
|
65 |
+
if i == max_retry - 1:
|
66 |
+
print(f'重试次数已达上限,仍未能成功获取数据,错误信息:{e}')
|
67 |
+
response_content = ''
|
68 |
+
usage = {}
|
69 |
+
return response_content
|
70 |
+
else:
|
71 |
+
# 如果未达到最大重试次数,打印错误信息,并继续下一次循环
|
72 |
+
print(f'第{i+1}次请求失败,错误信息:{e},准备进行第{i+2}次尝试')
|
73 |
+
|
74 |
+
|
75 |
+
# gradio demo
|
76 |
+
|
77 |
+
title = "Ask Image"
|
78 |
+
description = "Ask anything about your Image"
|
79 |
+
|
80 |
+
demo = gr.Interface(
|
81 |
+
fn=ask_image,
|
82 |
+
inputs=[gr.Image(label='',type='filepath'), gr.Text(label="Question")],
|
83 |
+
outputs=[gr.Textbox(label="Answer",lines=3)],
|
84 |
+
title = title,
|
85 |
+
description = description
|
86 |
+
)
|
87 |
+
demo.queue(max_size = 20)
|
88 |
+
|
89 |
+
demo.launch(share = True)
|