cherubhao commited on
Commit
5768e6c
·
verified ·
1 Parent(s): f3c6b5d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import base64
5
+
6
+ def call_api(image, text_input):
7
+ # Check if image is provided
8
+ if image is None:
9
+ return "请上传图片"
10
+
11
+ # Handle image processing
12
+ try:
13
+ # Read image file
14
+ if isinstance(image, str):
15
+ # If it's a filepath
16
+ with open(image, "rb") as f:
17
+ image_data = f.read()
18
+ else:
19
+ # If it's already in memory (Gradio might pass different types)
20
+ image_data = image
21
+
22
+ # Convert to base64
23
+ image_base64 = base64.b64encode(image_data).decode("utf-8")
24
+ image_url = f"data:image/jpeg;base64,{image_base64}"
25
+
26
+ # Construct request payload
27
+ payload = {
28
+ "model": "/data1/models/PKUAgri/qwen2_vl_lora_sft",
29
+ "messages": [
30
+ {
31
+ "role": "user",
32
+ "content": [
33
+ {"type": "image_url", "image_url": {"url": image_url}},
34
+ {"type": "text", "text": text_input}
35
+ ]
36
+ }
37
+ ]
38
+ }
39
+
40
+ headers = {
41
+ "Content-Type": "application/json"
42
+ }
43
+
44
+ # Make API call
45
+ response = requests.post(
46
+ "http://10.1.10.115:4001/v1/chat/completions",
47
+ data=json.dumps(payload),
48
+ headers=headers,
49
+ timeout=30
50
+ )
51
+
52
+ if response.status_code == 200:
53
+ res = response.json()
54
+ return res["choices"][0]["message"]["content"]
55
+ else:
56
+ return f"错误: {response.status_code} - {response.text}"
57
+
58
+ except Exception as e:
59
+ return f"处理请求时出错: {str(e)}"
60
+
61
+
62
+ # Build Gradio interface
63
+ with gr.Blocks() as demo:
64
+ gr.Markdown("## 🌄 病虫害识别模型")
65
+
66
+ with gr.Row():
67
+ image_input = gr.Image(type="filepath", label="上传图片")
68
+ text_input = gr.Textbox(label="请输入你的问题", placeholder="例如:图中有什么?")
69
+
70
+ submit_btn = gr.Button("提交")
71
+ output = gr.Textbox(label="回答", lines=5)
72
+
73
+ submit_btn.click(fn=call_api, inputs=[image_input, text_input], outputs=output)
74
+
75
+ # Launch the app
76
+ if __name__ == "__main__":
77
+ demo.launch(server_name="0.0.0.0", server_port= 40011, share=True)