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