Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,11 +7,15 @@ from pathlib import Path
|
|
| 7 |
import secrets
|
| 8 |
import dashscope
|
| 9 |
from dashscope import MultiModalConversation, Generation
|
|
|
|
| 10 |
|
|
|
|
|
|
|
| 11 |
YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN')
|
| 12 |
dashscope.api_key = YOUR_API_TOKEN
|
| 13 |
math_messages = []
|
| 14 |
-
def process_image(image):
|
|
|
|
| 15 |
global math_messages
|
| 16 |
math_messages = [] # reset when upload image
|
| 17 |
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
|
|
@@ -19,12 +23,17 @@ def process_image(image):
|
|
| 19 |
)
|
| 20 |
os.makedirs(uploaded_file_dir, exist_ok=True)
|
| 21 |
|
|
|
|
| 22 |
name = f"tmp{secrets.token_hex(20)}.jpg"
|
| 23 |
filename = os.path.join(uploaded_file_dir, name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
image.save(filename)
|
| 25 |
-
|
| 26 |
|
| 27 |
-
#
|
| 28 |
messages = [{
|
| 29 |
'role': 'system',
|
| 30 |
'content': [{'text': 'You are a helpful assistant.'}]
|
|
@@ -38,6 +47,7 @@ def process_image(image):
|
|
| 38 |
|
| 39 |
response = MultiModalConversation.call(model='qwen-vl-max-0809', messages=messages)
|
| 40 |
|
|
|
|
| 41 |
os.remove(filename)
|
| 42 |
|
| 43 |
return response.output.choices[0]["message"]["content"]
|
|
@@ -46,7 +56,7 @@ def get_math_response(image_description, user_question):
|
|
| 46 |
global math_messages
|
| 47 |
if not math_messages:
|
| 48 |
math_messages.append({'role': 'system', 'content': 'You are a helpful math assistant.'})
|
| 49 |
-
math_messages = math_messages[:1]
|
| 50 |
if image_description is not None:
|
| 51 |
content = f'Image description: {image_description}\n\n'
|
| 52 |
else:
|
|
@@ -72,11 +82,18 @@ def get_math_response(image_description, user_question):
|
|
| 72 |
math_messages.append({'role': 'assistant', 'content': answer})
|
| 73 |
|
| 74 |
|
| 75 |
-
def math_chat_bot(image, question):
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
yield from get_math_response(image_description, question)
|
| 81 |
|
| 82 |
css = """
|
|
@@ -85,31 +102,68 @@ css = """
|
|
| 85 |
#qwen-md .katex-display>.katex>.katex-html { display: inline; }
|
| 86 |
"""
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
],
|
| 96 |
-
outputs=gr.Markdown(label="answer", latex_delimiters=[
|
| 97 |
-
{"left": "\\(", "right": "\\)", "display": True},
|
| 98 |
-
{"left": "\\begin\{equation\}", "right": "\\end\{equation\}", "display": True},
|
| 99 |
-
{"left": "\\begin\{align\}", "right": "\\end\{align\}", "display": True},
|
| 100 |
-
{"left": "\\begin\{alignat\}", "right": "\\end\{alignat\}", "display": True},
|
| 101 |
-
{"left": "\\begin\{gather\}", "right": "\\end\{gather\}", "display": True},
|
| 102 |
-
{"left": "\\begin\{CD\}", "right": "\\end\{CD\}", "display": True},
|
| 103 |
-
{"left": "\\[", "right": "\\]", "display": True}
|
| 104 |
-
], elem_id="qwen-md"),
|
| 105 |
-
# title="📖 Qwen2 Math Demo",
|
| 106 |
-
allow_flagging='never',
|
| 107 |
-
description="""\
|
| 108 |
<p align="center"><img src="https://modelscope.oss-cn-beijing.aliyuncs.com/resource/qwen.png" style="height: 60px"/><p>"""
|
| 109 |
-
|
| 110 |
-
|
| 111 |
<center><font size=3>This WebUI is based on Qwen2-VL for OCR and Qwen2-Math for mathematical reasoning. You can input either images or texts of mathematical or arithmetic problems.</center>"""
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import secrets
|
| 8 |
import dashscope
|
| 9 |
from dashscope import MultiModalConversation, Generation
|
| 10 |
+
from PIL import Image
|
| 11 |
|
| 12 |
+
|
| 13 |
+
# 设置API密钥
|
| 14 |
YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN')
|
| 15 |
dashscope.api_key = YOUR_API_TOKEN
|
| 16 |
math_messages = []
|
| 17 |
+
def process_image(image, shouldConvert):
|
| 18 |
+
# 获取上传文件的目录
|
| 19 |
global math_messages
|
| 20 |
math_messages = [] # reset when upload image
|
| 21 |
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
|
|
|
|
| 23 |
)
|
| 24 |
os.makedirs(uploaded_file_dir, exist_ok=True)
|
| 25 |
|
| 26 |
+
# 创建临时文件路径
|
| 27 |
name = f"tmp{secrets.token_hex(20)}.jpg"
|
| 28 |
filename = os.path.join(uploaded_file_dir, name)
|
| 29 |
+
# 保存上传的图片
|
| 30 |
+
if shouldConvert:
|
| 31 |
+
new_img = Image.new('RGB', size=(image.width, image.height), color=(255, 255, 255))
|
| 32 |
+
new_img.paste(image, (0, 0), mask=image)
|
| 33 |
+
image = new_img
|
| 34 |
image.save(filename)
|
|
|
|
| 35 |
|
| 36 |
+
# 调用qwen-vl-max-0809模型处理图片
|
| 37 |
messages = [{
|
| 38 |
'role': 'system',
|
| 39 |
'content': [{'text': 'You are a helpful assistant.'}]
|
|
|
|
| 47 |
|
| 48 |
response = MultiModalConversation.call(model='qwen-vl-max-0809', messages=messages)
|
| 49 |
|
| 50 |
+
# 清理临时文件
|
| 51 |
os.remove(filename)
|
| 52 |
|
| 53 |
return response.output.choices[0]["message"]["content"]
|
|
|
|
| 56 |
global math_messages
|
| 57 |
if not math_messages:
|
| 58 |
math_messages.append({'role': 'system', 'content': 'You are a helpful math assistant.'})
|
| 59 |
+
math_messages = math_messages[:1]
|
| 60 |
if image_description is not None:
|
| 61 |
content = f'Image description: {image_description}\n\n'
|
| 62 |
else:
|
|
|
|
| 82 |
math_messages.append({'role': 'assistant', 'content': answer})
|
| 83 |
|
| 84 |
|
| 85 |
+
def math_chat_bot(image, sketchpad, question, state):
|
| 86 |
+
current_tab_index = state["tab_index"]
|
| 87 |
+
image_description = None
|
| 88 |
+
# Upload
|
| 89 |
+
if current_tab_index == 0:
|
| 90 |
+
if image is not None:
|
| 91 |
+
image_description = process_image(image)
|
| 92 |
+
# Sketch
|
| 93 |
+
elif current_tab_index == 1:
|
| 94 |
+
print(sketchpad)
|
| 95 |
+
if sketchpad and sketchpad["composite"]:
|
| 96 |
+
image_description = process_image(sketchpad["composite"], True)
|
| 97 |
yield from get_math_response(image_description, question)
|
| 98 |
|
| 99 |
css = """
|
|
|
|
| 102 |
#qwen-md .katex-display>.katex>.katex-html { display: inline; }
|
| 103 |
"""
|
| 104 |
|
| 105 |
+
def tabs_select(e: gr.SelectData, _state):
|
| 106 |
+
_state["tab_index"] = e.index
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# 创建Gradio接口
|
| 110 |
+
with gr.Blocks(css=css) as demo:
|
| 111 |
+
gr.HTML("""\
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
<p align="center"><img src="https://modelscope.oss-cn-beijing.aliyuncs.com/resource/qwen.png" style="height: 60px"/><p>"""
|
| 113 |
+
"""<center><font size=8>📖 千问数学解题机器人</center>"""
|
| 114 |
+
"""\
|
| 115 |
<center><font size=3>This WebUI is based on Qwen2-VL for OCR and Qwen2-Math for mathematical reasoning. You can input either images or texts of mathematical or arithmetic problems.</center>"""
|
| 116 |
+
)
|
| 117 |
+
state = gr.State({"tab_index": 0})
|
| 118 |
+
with gr.Row():
|
| 119 |
+
with gr.Column():
|
| 120 |
+
with gr.Tabs() as input_tabs:
|
| 121 |
+
with gr.Tab("Upload"):
|
| 122 |
+
input_image = gr.Image(type="pil", label="Upload"),
|
| 123 |
+
with gr.Tab("Sketch"):
|
| 124 |
+
input_sketchpad = gr.Sketchpad(type="pil", label="Sketch", layers=False)
|
| 125 |
+
input_tabs.select(fn=tabs_select, inputs=[state])
|
| 126 |
+
input_text = gr.Textbox(label="input your question")
|
| 127 |
+
with gr.Row():
|
| 128 |
+
with gr.Column():
|
| 129 |
+
clear_btn = gr.ClearButton(
|
| 130 |
+
[*input_image, input_sketchpad, input_text])
|
| 131 |
+
with gr.Column():
|
| 132 |
+
submit_btn = gr.Button("Submit", variant="primary")
|
| 133 |
+
with gr.Column():
|
| 134 |
+
output_md = gr.Markdown(label="answer",
|
| 135 |
+
latex_delimiters=[{
|
| 136 |
+
"left": "\\(",
|
| 137 |
+
"right": "\\)",
|
| 138 |
+
"display": True
|
| 139 |
+
}, {
|
| 140 |
+
"left": "\\begin\{equation\}",
|
| 141 |
+
"right": "\\end\{equation\}",
|
| 142 |
+
"display": True
|
| 143 |
+
}, {
|
| 144 |
+
"left": "\\begin\{align\}",
|
| 145 |
+
"right": "\\end\{align\}",
|
| 146 |
+
"display": True
|
| 147 |
+
}, {
|
| 148 |
+
"left": "\\begin\{alignat\}",
|
| 149 |
+
"right": "\\end\{alignat\}",
|
| 150 |
+
"display": True
|
| 151 |
+
}, {
|
| 152 |
+
"left": "\\begin\{gather\}",
|
| 153 |
+
"right": "\\end\{gather\}",
|
| 154 |
+
"display": True
|
| 155 |
+
}, {
|
| 156 |
+
"left": "\\begin\{CD\}",
|
| 157 |
+
"right": "\\end\{CD\}",
|
| 158 |
+
"display": True
|
| 159 |
+
}, {
|
| 160 |
+
"left": "\\[",
|
| 161 |
+
"right": "\\]",
|
| 162 |
+
"display": True
|
| 163 |
+
}],
|
| 164 |
+
elem_id="qwen-md")
|
| 165 |
+
submit_btn.click(
|
| 166 |
+
fn=math_chat_bot,
|
| 167 |
+
inputs=[*input_image, input_sketchpad, input_text, state],
|
| 168 |
+
outputs=output_md)
|
| 169 |
+
demo.launch()
|