shenglongw commited on
Commit
295865d
·
verified ·
1 Parent(s): ddd1188

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -176
app.py CHANGED
@@ -1,190 +1,169 @@
1
- # app.py
2
  import gradio as gr
3
  import os
4
 
5
- import gradio as gr
6
- import modelscope_studio as mgr
7
- from http import HTTPStatus
 
8
  import dashscope
9
- from dashscope import Generation
10
- from dashscope.api_entities.dashscope_response import Role
11
- from typing import List, Optional, Tuple, Dict
12
- from urllib.error import HTTPError
13
 
14
- default_system = 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.'
15
 
 
16
  YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN')
17
  dashscope.api_key = YOUR_API_TOKEN
18
-
19
- History = List[Tuple[str, str]]
20
- Messages = List[Dict[str, str]]
21
-
22
-
23
- latex_delimiters = [{
24
- "left": "\\(",
25
- "right": "\\)",
26
- "display": True
27
- }, {
28
- "left": "\\begin\{equation\}",
29
- "right": "\\end\{equation\}",
30
- "display": True
31
- }, {
32
- "left": "\\begin\{align\}",
33
- "right": "\\end\{align\}",
34
- "display": True
35
- }, {
36
- "left": "\\begin\{alignat\}",
37
- "right": "\\end\{alignat\}",
38
- "display": True
39
- }, {
40
- "left": "\\begin\{gather\}",
41
- "right": "\\end\{gather\}",
42
- "display": True
43
- }, {
44
- "left": "\\begin\{CD\}",
45
- "right": "\\end\{CD\}",
46
- "display": True
47
- }, {
48
- "left": "\\[",
49
- "right": "\\]",
50
- "display": True
51
- }]
52
-
53
- def clear_session() -> History:
54
- return '', []
55
-
56
-
57
- def modify_system_session(system: str) -> str:
58
- if system is None or len(system) == 0:
59
- system = default_system
60
- return system, system, []
61
-
62
-
63
- def history_to_messages(history: History, system: str) -> Messages:
64
- messages = [{'role': Role.SYSTEM, 'content': system}]
65
- for h in history:
66
- messages.append({'role': Role.USER, 'content': h[0].text})
67
- messages.append({'role': Role.ASSISTANT, 'content': h[1].text})
68
- return messages
69
-
70
-
71
- def messages_to_history(messages: Messages) -> Tuple[str, History]:
72
- assert messages[0]['role'] == Role.SYSTEM
73
- system = messages[0]['content']
74
- history = []
75
- for q, r in zip(messages[1::2], messages[2::2]):
76
- history.append([q['content'], r['content']])
77
- return system, history
78
-
79
-
80
- def model_chat(query: Optional[str], history: Optional[History], system: str, radio: str
81
- ) -> Tuple[str, str, History, str]:
82
- if query is None:
83
- query = ''
84
- if history is None:
85
- history = []
86
- messages = history_to_messages(history, system)
87
- messages.append({'role': Role.USER, 'content': query})
88
 
89
- label_model = f"qwen2.5-{radio.lower()}-instruct"
 
 
 
 
 
 
 
 
 
 
90
 
91
- gen = Generation.call(
92
- model=label_model,
93
- messages=messages,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  result_format='message',
95
  stream=True
96
  )
97
- for response in gen:
98
- if response.status_code == HTTPStatus.OK:
99
- role = response.output.choices[0].message.role
100
- response = response.output.choices[0].message.content
101
- system, history = messages_to_history(messages + [{'role': role, 'content': response}])
102
- yield '', history, system
103
- else:
104
- raise ValueError('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
105
- response.request_id, response.status_code,
106
- response.code, response.message
107
- ))
108
-
109
-
110
- def chiose_radio(radio, system):
111
- mark_ = gr.Markdown(value=f"<center><font size=8>Qwen2.5-{radio}-instruct👾</center>")
112
- chatbot = mgr.Chatbot(label=f'{radio.lower()}')
113
-
114
- if system is None or len(system) == 0:
115
- system = default_system
116
-
117
- return mark_, chatbot, system, system, ""
118
-
119
-
120
- def update_other_radios(value, other_radio1, other_radio2):
121
- if value == "":
122
- if other_radio1 != "":
123
- selected = other_radio1
124
- else:
125
- selected = other_radio2
126
- return selected, other_radio1, other_radio2
127
- return value, "", ""
128
-
129
-
130
- def main():
131
- # 创建两个标签
132
- with gr.Blocks() as demo:
133
- gr.Markdown("""<center><font size=8>Qwen2.5: A Party of Foundation Models!</center>""")
134
- with gr.Row():
135
- options_1 = ["72B", "32B", "14B", "7B", "3B", "1.5B", "0.5B"]
136
- options_math = ["Math-72B", "Math-7B", "Math-1.5B"]
137
- options_coder = ["Coder-7B", "Coder-1.5B"]
138
- with gr.Row():
139
- radio1 = gr.Radio(choices=options_1, label="Qwen2.5:", value=options_1[0])
140
- with gr.Row():
141
- radio2 = gr.Radio(choices=options_math, label="Qwen2.5-Math:")
 
 
 
 
 
 
 
 
 
 
142
  with gr.Row():
143
- radio3 = gr.Radio(choices=options_coder, label="Qwen2.5-Coder:")
144
-
145
- radio = gr.Radio(value=options_1[0], visible=False)
146
- radio1.change(fn=update_other_radios, inputs=[radio1, radio2, radio3], outputs=[radio, radio2, radio3])
147
- radio2.change(fn=update_other_radios, inputs=[radio2, radio1, radio3], outputs=[radio, radio1, radio3])
148
- radio3.change(fn=update_other_radios, inputs=[radio3, radio1, radio2], outputs=[radio, radio1, radio2])
149
-
150
- with gr.Row():
151
- with gr.Accordion():
152
- mark_ = gr.Markdown("""<center><font size=8>Qwen2.5-72B-instruct 👾</center>""")
153
- with gr.Row():
154
- with gr.Column(scale=3):
155
- system_input = gr.Textbox(value=default_system, lines=1, label='System')
156
- with gr.Column(scale=1):
157
- modify_system = gr.Button("🛠️ Set system prompt and clear history", scale=2)
158
- system_state = gr.Textbox(value=default_system, visible=False)
159
- chatbot = mgr.Chatbot(label=options_1[0].lower(), latex_delimiters=latex_delimiters)
160
- textbox = gr.Textbox(lines=1, label='Input')
161
-
162
- with gr.Row():
163
- clear_history = gr.Button("🧹 Clear history")
164
- sumbit = gr.Button("🚀 Send")
165
-
166
- textbox.submit(model_chat,
167
- inputs=[textbox, chatbot, system_state, radio],
168
- outputs=[textbox, chatbot, system_input])
169
-
170
- sumbit.click(model_chat,
171
- inputs=[textbox, chatbot, system_state, radio],
172
- outputs=[textbox, chatbot, system_input],
173
- concurrency_limit=5)
174
- clear_history.click(fn=clear_session,
175
- inputs=[],
176
- outputs=[textbox, chatbot])
177
- modify_system.click(fn=modify_system_session,
178
- inputs=[system_input],
179
- outputs=[system_state, system_input, chatbot])
180
-
181
- radio.change(chiose_radio,
182
- inputs=[radio, system_input],
183
- outputs=[mark_, chatbot, system_state, system_input, textbox])
184
-
185
- demo.queue(api_open=False,default_concurrency_limit=40)
186
- demo.launch(max_threads=40)
187
-
188
-
189
- if __name__ == "__main__":
190
- main()
 
 
1
  import gradio as gr
2
  import os
3
 
4
+ os.system('pip install dashscope -U')
5
+ import tempfile
6
+ from pathlib import Path
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=False):
18
+ # 获取上传文件的目录
19
+ global math_messages
20
+ math_messages = [] # reset when upload image
21
+ uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
22
+ Path(tempfile.gettempdir()) / "gradio"
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.'}]
40
+ }, {
41
+ 'role': 'user',
42
+ 'content': [
43
+ {'image': f'file://{filename}'},
44
+ {'text': 'Please describe the math-related content in this image, ensuring that any LaTeX formulas are correctly transcribed. Non-mathematical details do not need to be described.'}
45
+ ]
46
+ }]
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"]
54
+
55
+ def get_math_response(image_description, user_question):
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:
63
+ content = ''
64
+ query = f"{content}User question: {user_question}"
65
+ math_messages.append({'role': 'user', 'content': query})
66
+ response = Generation.call(
67
+ model="qwen2-math-72b-instruct",
68
+ messages=math_messages,
69
  result_format='message',
70
  stream=True
71
  )
72
+ answer = None
73
+ for resp in response:
74
+ if resp.output is None:
75
+ continue
76
+ answer = resp.output.choices[0].message.content
77
+ yield answer.replace("\\", "\\\\")
78
+ print(f'query: {query}\nanswer: {answer}')
79
+ if answer is None:
80
+ math_messages.pop()
81
+ 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 = """
100
+ #qwen-md .katex-display { display: inline; }
101
+ #qwen-md .katex-display>.katex { display: inline; }
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>📖 Qwen2-Math Demo</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()