littlebird13 commited on
Commit
6d43b0c
·
verified ·
1 Parent(s): d5f1dde

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +233 -0
app.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ import os
6
+ import numpy as np
7
+ from urllib3.exceptions import HTTPError
8
+ os.system('pip install dashscope modelscope -U')
9
+
10
+ from argparse import ArgumentParser
11
+ from pathlib import Path
12
+
13
+ import copy
14
+ import gradio as gr
15
+ import os
16
+ import re
17
+ import secrets
18
+ import tempfile
19
+ import requests
20
+ from http import HTTPStatus
21
+ from dashscope import MultiModalConversation
22
+ import dashscope
23
+ API_KEY = os.environ['API_KEY']
24
+ dashscope.api_key = API_KEY
25
+
26
+ REVISION = 'v1.0.4'
27
+ BOX_TAG_PATTERN = r"<box>([\s\S]*?)</box>"
28
+ PUNCTUATION = "!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏."
29
+
30
+
31
+ def _get_args():
32
+ parser = ArgumentParser()
33
+ parser.add_argument("--revision", type=str, default=REVISION)
34
+ parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only")
35
+
36
+ parser.add_argument("--share", action="store_true", default=False,
37
+ help="Create a publicly shareable link for the interface.")
38
+ parser.add_argument("--inbrowser", action="store_true", default=False,
39
+ help="Automatically launch the interface in a new tab on the default browser.")
40
+ parser.add_argument("--server-port", type=int, default=7860,
41
+ help="Demo server port.")
42
+ parser.add_argument("--server-name", type=str, default="127.0.0.1",
43
+ help="Demo server name.")
44
+
45
+ args = parser.parse_args()
46
+ return args
47
+
48
+ def _parse_text(text):
49
+ lines = text.split("\n")
50
+ lines = [line for line in lines if line != ""]
51
+ count = 0
52
+ for i, line in enumerate(lines):
53
+ if "```" in line:
54
+ count += 1
55
+ items = line.split("`")
56
+ if count % 2 == 1:
57
+ lines[i] = f'<pre><code class="language-{items[-1]}">'
58
+ else:
59
+ lines[i] = f"<br></code></pre>"
60
+ else:
61
+ if i > 0:
62
+ if count % 2 == 1:
63
+ line = line.replace("`", r"\`")
64
+ line = line.replace("<", "&lt;")
65
+ line = line.replace(">", "&gt;")
66
+ line = line.replace(" ", "&nbsp;")
67
+ line = line.replace("*", "&ast;")
68
+ line = line.replace("_", "&lowbar;")
69
+ line = line.replace("-", "&#45;")
70
+ line = line.replace(".", "&#46;")
71
+ line = line.replace("!", "&#33;")
72
+ line = line.replace("(", "&#40;")
73
+ line = line.replace(")", "&#41;")
74
+ line = line.replace("$", "&#36;")
75
+ lines[i] = "<br>" + line
76
+ text = "".join(lines)
77
+ return text
78
+
79
+
80
+ def _remove_image_special(text):
81
+ text = text.replace('<ref>', '').replace('</ref>', '')
82
+ return re.sub(r'<box>.*?(</box>|$)', '', text)
83
+
84
+ def _launch_demo(args):
85
+ uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
86
+ Path(tempfile.gettempdir()) / "gradio"
87
+ )
88
+
89
+ def predict(_chatbot, task_history):
90
+ chat_query = _chatbot[-1][0]
91
+ query = task_history[-1][0]
92
+ if len(chat_query) == 0:
93
+ _chatbot.pop()
94
+ task_history.pop()
95
+ return _chatbot
96
+ print("User: " + _parse_text(query))
97
+ history_cp = copy.deepcopy(task_history)
98
+ full_response = ""
99
+ messages = []
100
+ content = []
101
+ for q, a in history_cp:
102
+ if isinstance(q, (tuple, list)):
103
+ content.append({'image': f'file://{q[0]}'})
104
+ else:
105
+ content.append({'text': q})
106
+ messages.append({'role': 'user', 'content': content})
107
+ messages.append({'role': 'assistant', 'content': [{'text': a}]})
108
+ content = []
109
+ messages.pop()
110
+ responses = MultiModalConversation.call(
111
+ model='qwen-vl-max-0809', messages=messages, stream=True,
112
+ )
113
+ for response in responses:
114
+ if not response.status_code == HTTPStatus.OK:
115
+ raise HTTPError(f'response.code: {response.code}\nresponse.message: {response.message}')
116
+ response = response.output.choices[0].message.content
117
+ response_text = []
118
+ for ele in response:
119
+ if 'text' in ele:
120
+ response_text.append(ele['text'])
121
+ elif 'box' in ele:
122
+ response_text.append(ele['box'])
123
+ response_text = ''.join(response_text)
124
+ _chatbot[-1] = (_parse_text(chat_query), _remove_image_special(response_text))
125
+ yield _chatbot
126
+
127
+ if len(response) > 1:
128
+ result_image = response[-1]['result_image']
129
+ resp = requests.get(result_image)
130
+ os.makedirs(uploaded_file_dir, exist_ok=True)
131
+ name = f"tmp{secrets.token_hex(20)}.jpg"
132
+ filename = os.path.join(uploaded_file_dir, name)
133
+ with open(filename, 'wb') as f:
134
+ f.write(resp.content)
135
+ response = ''.join(r['box'] if 'box' in r else r['text'] for r in response[:-1])
136
+ _chatbot.append((None, (filename,)))
137
+ else:
138
+ response = response[0]['text']
139
+ _chatbot[-1] = (_parse_text(chat_query), response)
140
+ full_response = _parse_text(response)
141
+
142
+ task_history[-1] = (query, full_response)
143
+ print("Qwen2-VL-Chat: " + _parse_text(full_response))
144
+ yield _chatbot
145
+
146
+
147
+ def regenerate(_chatbot, task_history):
148
+ if not task_history:
149
+ return _chatbot
150
+ item = task_history[-1]
151
+ if item[1] is None:
152
+ return _chatbot
153
+ task_history[-1] = (item[0], None)
154
+ chatbot_item = _chatbot.pop(-1)
155
+ if chatbot_item[0] is None:
156
+ _chatbot[-1] = (_chatbot[-1][0], None)
157
+ else:
158
+ _chatbot.append((chatbot_item[0], None))
159
+ _chatbot_gen = predict(_chatbot, task_history)
160
+ for _chatbot in _chatbot_gen:
161
+ yield _chatbot
162
+
163
+ def add_text(history, task_history, text):
164
+ task_text = text
165
+ history = history if history is not None else []
166
+ task_history = task_history if task_history is not None else []
167
+ history = history + [(_parse_text(text), None)]
168
+ task_history = task_history + [(task_text, None)]
169
+ return history, task_history, ""
170
+
171
+ def add_file(history, task_history, file):
172
+ history = history if history is not None else []
173
+ task_history = task_history if task_history is not None else []
174
+ history = history + [((file.name,), None)]
175
+ task_history = task_history + [((file.name,), None)]
176
+ return history, task_history
177
+
178
+ def reset_user_input():
179
+ return gr.update(value="")
180
+
181
+ def reset_state(task_history):
182
+ task_history.clear()
183
+ return []
184
+
185
+ with gr.Blocks() as demo:
186
+ gr.Markdown("""\
187
+ <p align="center"><img src="https://modelscope.oss-cn-beijing.aliyuncs.com/resource/qwen.png" style="height: 80px"/><p>""")
188
+ gr.Markdown("""<center><font size=8>Qwen2-VL-Max</center>""")
189
+ gr.Markdown(
190
+ """\
191
+ <center><font size=3>This WebUI is based on Qwen2-VL-Max, developed by Alibaba Cloud.</center>""")
192
+ gr.Markdown("""<center><font size=3>本WebUI基于Qwen2-VL-Max。</center>""")
193
+
194
+ chatbot = gr.Chatbot(label='Qwen2-VL-Max', elem_classes="control-height", height=500)
195
+ query = gr.Textbox(lines=2, label='Input')
196
+ task_history = gr.State([])
197
+
198
+ with gr.Row():
199
+ addfile_btn = gr.UploadButton("📁 Upload (上传文件)", file_types=["image"])
200
+ submit_btn = gr.Button("🚀 Submit (发送)")
201
+ regen_btn = gr.Button("🤔️ Regenerate (重试)")
202
+ empty_bin = gr.Button("🧹 Clear History (清除历史)")
203
+
204
+ submit_btn.click(add_text, [chatbot, task_history, query], [chatbot, task_history]).then(
205
+ predict, [chatbot, task_history], [chatbot], show_progress=True
206
+ )
207
+ submit_btn.click(reset_user_input, [], [query])
208
+ empty_bin.click(reset_state, [task_history], [chatbot], show_progress=True)
209
+ regen_btn.click(regenerate, [chatbot, task_history], [chatbot], show_progress=True)
210
+ addfile_btn.upload(add_file, [chatbot, task_history, addfile_btn], [chatbot, task_history], show_progress=True)
211
+
212
+ gr.Markdown("""\
213
+ <font size=2>Note: This demo is governed by the original license of Qwen2-VL. \
214
+ We strongly advise users not to knowingly generate or allow others to knowingly generate harmful content, \
215
+ including hate speech, violence, pornography, deception, etc. \
216
+ (注:本演示受Qwen2-VL的许可协议限制。我们强烈建议,用户不应传播及不应允许他人传播以下内容,\
217
+ 包括但不限于仇恨言论、暴力、色情、欺诈相关的有害信息。)""")
218
+
219
+ demo.queue().launch(
220
+ share=args.share,
221
+ # inbrowser=args.inbrowser,
222
+ # server_port=args.server_port,
223
+ # server_name=args.server_name,
224
+ )
225
+
226
+
227
+ def main():
228
+ args = _get_args()
229
+ _launch_demo(args)
230
+
231
+
232
+ if __name__ == '__main__':
233
+ main()