Update app.py
Browse files
app.py
CHANGED
@@ -4,9 +4,9 @@ import mimetypes
|
|
4 |
import json, os
|
5 |
import asyncio
|
6 |
import aiohttp
|
7 |
-
|
8 |
import subprocess
|
9 |
|
|
|
10 |
def upgrade_pip():
|
11 |
try:
|
12 |
subprocess.check_call([os.sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
|
@@ -14,13 +14,11 @@ def upgrade_pip():
|
|
14 |
except subprocess.CalledProcessError:
|
15 |
print("pip 升級失敗")
|
16 |
|
17 |
-
# 呼叫升級函數
|
18 |
upgrade_pip()
|
19 |
|
20 |
LLM_API = os.environ.get("LLM_API")
|
21 |
LLM_URL = os.environ.get("LLM_URL")
|
22 |
-
|
23 |
-
USER_ID = "HuggingFace Space" # Placeholder user ID
|
24 |
|
25 |
async def send_chat_message(LLM_URL, LLM_API, category, file_id):
|
26 |
payload = {
|
@@ -37,18 +35,14 @@ async def send_chat_message(LLM_URL, LLM_API, category, file_id):
|
|
37 |
}
|
38 |
]
|
39 |
}
|
40 |
-
print("Sending chat message payload:", payload) # Debug information
|
41 |
async with aiohttp.ClientSession() as session:
|
42 |
async with session.post(
|
43 |
f"{LLM_URL}/chat-messages",
|
44 |
headers={"Authorization": f"Bearer {LLM_API}"},
|
45 |
json=payload
|
46 |
) as response:
|
47 |
-
print("Request URL:", f"{LLM_URL}/chat-messages")
|
48 |
-
print("Response status code:", response.status)
|
49 |
if response.status == 404:
|
50 |
return "Error: Endpoint not found (404)"
|
51 |
-
|
52 |
last_thought = None
|
53 |
async for line in response.content:
|
54 |
if line:
|
@@ -58,11 +52,7 @@ async def send_chat_message(LLM_URL, LLM_API, category, file_id):
|
|
58 |
last_thought = data.get("thought")
|
59 |
except (IndexError, json.JSONDecodeError):
|
60 |
continue
|
61 |
-
|
62 |
-
if last_thought:
|
63 |
-
return last_thought.strip()
|
64 |
-
else:
|
65 |
-
return "Error: No thought found in the response"
|
66 |
|
67 |
async def upload_file(LLM_URL, LLM_API, file_path, user_id):
|
68 |
if not os.path.exists(file_path):
|
@@ -73,17 +63,14 @@ async def upload_file(LLM_URL, LLM_API, file_path, user_id):
|
|
73 |
form_data = aiohttp.FormData()
|
74 |
form_data.add_field('file', f, filename=file_path, content_type=mime_type)
|
75 |
form_data.add_field('user', user_id)
|
76 |
-
|
77 |
async with session.post(
|
78 |
f"{LLM_URL}/files/upload",
|
79 |
headers={"Authorization": f"Bearer {LLM_API}"},
|
80 |
data=form_data
|
81 |
) as response:
|
82 |
-
print("Upload response status code:", response.status) # Debug information
|
83 |
if response.status == 404:
|
84 |
return "Error: Endpoint not found (404)"
|
85 |
response_text = await response.text()
|
86 |
-
print("Raw upload response text:", response_text) # Debug information
|
87 |
try:
|
88 |
return json.loads(response_text)
|
89 |
except json.JSONDecodeError:
|
@@ -91,21 +78,14 @@ async def upload_file(LLM_URL, LLM_API, file_path, user_id):
|
|
91 |
|
92 |
async def handle_input(file_path, category):
|
93 |
upload_response = await upload_file(LLM_URL, LLM_API, file_path, USER_ID)
|
94 |
-
|
95 |
-
if "error" in upload_response:
|
96 |
return upload_response
|
97 |
-
file_id = upload_response.get("id")
|
98 |
if not file_id:
|
99 |
return "Error: No file ID returned from upload"
|
100 |
-
|
101 |
-
chat_response = await send_chat_message(LLM_URL, LLM_API, category, file_id)
|
102 |
-
print("Chat response:", chat_response) # Debug information
|
103 |
-
return chat_response
|
104 |
-
|
105 |
-
# Define Gradio interface
|
106 |
-
file_input = gr.Image(label='圖片上傳', type='filepath')
|
107 |
-
category = gr.Radio(label="Message Category", choices=["機票", "計程車乘車證明", "通行明細 (etag)", "QRCODE發票", "超商高鐵車票", "高鐵車票", "超商台鐵車票", "台鐵車票"])
|
108 |
|
|
|
109 |
examples = [
|
110 |
['DEMO/boarding-pass.png', '機票'],
|
111 |
['DEMO/taxi.jpg', '計程車乘車證明'],
|
@@ -134,16 +114,29 @@ LINKS = """
|
|
134 |
<a href='https://blog.twman.org/2023/07/wsl.html' target='_blank'>用PPOCRLabel來幫PaddleOCR做OCR的微調和標註</a><br>
|
135 |
<a href='https://blog.twman.org/2023/07/HugIE.html' target='_blank'>基於機器閱讀理解和指令微調的統一信息抽取框架之診斷書醫囑資訊擷取分析</a><br>
|
136 |
"""
|
|
|
|
|
137 |
with gr.Blocks() as iface:
|
138 |
gr.HTML(TITLE)
|
139 |
gr.HTML(SUBTITLE)
|
140 |
gr.HTML(LINKS)
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
examples=examples,
|
146 |
-
|
|
|
147 |
)
|
148 |
|
149 |
-
iface.launch()
|
|
|
4 |
import json, os
|
5 |
import asyncio
|
6 |
import aiohttp
|
|
|
7 |
import subprocess
|
8 |
|
9 |
+
# pip 升級
|
10 |
def upgrade_pip():
|
11 |
try:
|
12 |
subprocess.check_call([os.sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
|
|
|
14 |
except subprocess.CalledProcessError:
|
15 |
print("pip 升級失敗")
|
16 |
|
|
|
17 |
upgrade_pip()
|
18 |
|
19 |
LLM_API = os.environ.get("LLM_API")
|
20 |
LLM_URL = os.environ.get("LLM_URL")
|
21 |
+
USER_ID = "HuggingFace Space"
|
|
|
22 |
|
23 |
async def send_chat_message(LLM_URL, LLM_API, category, file_id):
|
24 |
payload = {
|
|
|
35 |
}
|
36 |
]
|
37 |
}
|
|
|
38 |
async with aiohttp.ClientSession() as session:
|
39 |
async with session.post(
|
40 |
f"{LLM_URL}/chat-messages",
|
41 |
headers={"Authorization": f"Bearer {LLM_API}"},
|
42 |
json=payload
|
43 |
) as response:
|
|
|
|
|
44 |
if response.status == 404:
|
45 |
return "Error: Endpoint not found (404)"
|
|
|
46 |
last_thought = None
|
47 |
async for line in response.content:
|
48 |
if line:
|
|
|
52 |
last_thought = data.get("thought")
|
53 |
except (IndexError, json.JSONDecodeError):
|
54 |
continue
|
55 |
+
return last_thought.strip() if last_thought else "Error: No thought found in the response"
|
|
|
|
|
|
|
|
|
56 |
|
57 |
async def upload_file(LLM_URL, LLM_API, file_path, user_id):
|
58 |
if not os.path.exists(file_path):
|
|
|
63 |
form_data = aiohttp.FormData()
|
64 |
form_data.add_field('file', f, filename=file_path, content_type=mime_type)
|
65 |
form_data.add_field('user', user_id)
|
|
|
66 |
async with session.post(
|
67 |
f"{LLM_URL}/files/upload",
|
68 |
headers={"Authorization": f"Bearer {LLM_API}"},
|
69 |
data=form_data
|
70 |
) as response:
|
|
|
71 |
if response.status == 404:
|
72 |
return "Error: Endpoint not found (404)"
|
73 |
response_text = await response.text()
|
|
|
74 |
try:
|
75 |
return json.loads(response_text)
|
76 |
except json.JSONDecodeError:
|
|
|
78 |
|
79 |
async def handle_input(file_path, category):
|
80 |
upload_response = await upload_file(LLM_URL, LLM_API, file_path, USER_ID)
|
81 |
+
if isinstance(upload_response, str) and upload_response.startswith("Error"):
|
|
|
82 |
return upload_response
|
83 |
+
file_id = upload_response.get("id")
|
84 |
if not file_id:
|
85 |
return "Error: No file ID returned from upload"
|
86 |
+
return await send_chat_message(LLM_URL, LLM_API, category, file_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
+
# UI 元件 & 資料
|
89 |
examples = [
|
90 |
['DEMO/boarding-pass.png', '機票'],
|
91 |
['DEMO/taxi.jpg', '計程車乘車證明'],
|
|
|
114 |
<a href='https://blog.twman.org/2023/07/wsl.html' target='_blank'>用PPOCRLabel來幫PaddleOCR做OCR的微調和標註</a><br>
|
115 |
<a href='https://blog.twman.org/2023/07/HugIE.html' target='_blank'>基於機器閱讀理解和指令微調的統一信息抽取框架之診斷書醫囑資訊擷取分析</a><br>
|
116 |
"""
|
117 |
+
|
118 |
+
# Gradio Blocks 寫法(全新修正)
|
119 |
with gr.Blocks() as iface:
|
120 |
gr.HTML(TITLE)
|
121 |
gr.HTML(SUBTITLE)
|
122 |
gr.HTML(LINKS)
|
123 |
+
|
124 |
+
with gr.Row():
|
125 |
+
file_input = gr.Image(label='圖片上傳', type='filepath')
|
126 |
+
category = gr.Radio(label="Message Category", choices=[
|
127 |
+
"機票", "計程車乘車證明", "通行明細 (etag)", "QRCODE發票",
|
128 |
+
"超商高鐵車票", "高鐵車票", "超商台鐵車票", "台鐵車票"
|
129 |
+
])
|
130 |
+
|
131 |
+
submit_btn = gr.Button("解析")
|
132 |
+
output_text = gr.Textbox(label="解析結果", lines=10)
|
133 |
+
|
134 |
+
submit_btn.click(fn=handle_input, inputs=[file_input, category], outputs=output_text)
|
135 |
+
|
136 |
+
gr.Examples(
|
137 |
examples=examples,
|
138 |
+
inputs=[file_input, category],
|
139 |
+
label="範例圖片與類型"
|
140 |
)
|
141 |
|
142 |
+
iface.launch()
|