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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
description = '''
|
2 |
+
# 🙋🏻♂️Welcome to🌟Tonic's🦄Qwen-VL-Chat🤩Bot!🚀
|
3 |
+
This WebUI is based on Qwen-VL-Chat, implementing chatbot functionalities. Qwen-VL-Chat is a multimodal input model. You can use this Space to test out the current model [qwen/Qwen-VL-Chat](https://huggingface.co/qwen/Qwen-VL-Chat) You can also use 🧑🏻🚀qwen/Qwen-VL-Chat🚀 by cloning this space. 🧬🔬🔍 Simply click here: [Duplicate Space](https://huggingface.co/spaces/Tonic1/VLChat?duplicate=true)
|
4 |
+
Join us: 🌟TeamTonic🌟 is always making cool demos! Join our active builder's🛠️community on 👻Discord: [Discord](https://discord.gg/nXx5wbX9) On 🤗Huggingface: [TeamTonic](https://huggingface.co/TeamTonic) & [MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Polytonic](https://github.com/tonic-ai) & contribute to 🌟 [PolyGPT](https://github.com/tonic-ai/polygpt-alpha)
|
5 |
+
'''
|
6 |
+
disclaimer = """
|
7 |
+
Note: This demo is governed by the original license of Qwen-VL. We strongly advise users not to knowingly generate or allow others to knowingly generate harmful content,
|
8 |
+
including hate speech, violence, pornography, deception, etc. (Note: This demo is subject to the license agreement of Qwen-VL. We strongly advise users not to disseminate or allow others to disseminate the following content, including but not limited to hate speech, violence, pornography, and fraud-related harmful information.)
|
9 |
+
"""
|
10 |
+
|
11 |
+
from modelscope import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, snapshot_download
|
12 |
+
from argparse import ArgumentParser
|
13 |
+
from pathlib import Path
|
14 |
+
import shutil
|
15 |
+
import copy
|
16 |
+
import gradio as gr
|
17 |
+
import os
|
18 |
+
import re
|
19 |
+
import secrets
|
20 |
+
import tempfile
|
21 |
+
|
22 |
+
#GlobalVariables
|
23 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
|
24 |
+
DEFAULT_CKPT_PATH = 'qwen/Qwen-VL-Chat'
|
25 |
+
REVISION = 'v1.0.4'
|
26 |
+
BOX_TAG_PATTERN = r"<box>([\s\S]*?)</box>"
|
27 |
+
PUNCTUATION = "ï¼Â?。"#$%&'()*+,ï¼Âï¼Â:;<ï¼Â>ï¼ [\]^_`{|ï½Â~⦅ï½ 「」、ã€Â〃》「ã€Â『ã€Âã€Â】ã€â€Ã£â‚¬â€¢Ã£â‚¬â€“〗〘〙〚〛〜ã€Â〞〟〰〾〿–â€â€Ã¢â‚¬ËœÃ¢â‚¬â„¢Ã¢â‚¬â€ºÃ¢â‚¬Å“â€Â„‟…‧ï¹Â."
|
28 |
+
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(Path(tempfile.gettempdir()) / "gradio")
|
29 |
+
tokenizer = None
|
30 |
+
model = None
|
31 |
+
|
32 |
+
def _get_args() -> ArgumentParser:
|
33 |
+
parser = ArgumentParser()
|
34 |
+
parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH,
|
35 |
+
help="Checkpoint name or path, default to %(default)r")
|
36 |
+
parser.add_argument("--revision", type=str, default=REVISION)
|
37 |
+
parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only")
|
38 |
+
|
39 |
+
parser.add_argument("--share", action="store_true", default=False,
|
40 |
+
help="Create a publicly shareable link for the interface.")
|
41 |
+
parser.add_argument("--inbrowser", action="store_true", default=False,
|
42 |
+
help="Automatically launch the interface in a new tab on the default browser.")
|
43 |
+
parser.add_argument("--server-port", type=int, default=8000,
|
44 |
+
help="Demo server port.")
|
45 |
+
parser.add_argument("--server-name", type=str, default="127.0.0.1",
|
46 |
+
help="Demo server name.")
|
47 |
+
|
48 |
+
args = parser.parse_args()
|
49 |
+
return args
|
50 |
+
|
51 |
+
def handle_image_submission(_chatbot, task_history, file) -> tuple:
|
52 |
+
print("handle_image_submission called")
|
53 |
+
if file is None:
|
54 |
+
print("No file uploaded")
|
55 |
+
return _chatbot, task_history
|
56 |
+
print("File received:", file)
|
57 |
+
file_path = save_image(file, uploaded_file_dir)
|
58 |
+
print("File saved at:", file_path)
|
59 |
+
history_item = ((file_path,), None)
|
60 |
+
_chatbot.append(history_item)
|
61 |
+
task_history.append(history_item)
|
62 |
+
return predict(_chatbot, task_history, tokenizer, model)
|
63 |
+
|
64 |
+
|
65 |
+
def _load_model_tokenizer(args) -> tuple:
|
66 |
+
global tokenizer, model
|
67 |
+
model_id = args.checkpoint_path
|
68 |
+
model_dir = snapshot_download(model_id, revision=args.revision)
|
69 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
70 |
+
model_dir, trust_remote_code=True, resume_download=True,
|
71 |
+
)
|
72 |
+
|
73 |
+
if args.cpu_only:
|
74 |
+
device_map = "cpu"
|
75 |
+
else:
|
76 |
+
device_map = "auto"
|
77 |
+
|
78 |
+
model = AutoModelForCausalLM.from_pretrained(
|
79 |
+
model_dir,
|
80 |
+
device_map=device_map,
|
81 |
+
trust_remote_code=True,
|
82 |
+
bf16=True,
|
83 |
+
resume_download=True,
|
84 |
+
).eval()
|
85 |
+
model.generation_config = GenerationConfig.from_pretrained(
|
86 |
+
model_dir, trust_remote_code=True, resume_download=True,
|
87 |
+
)
|
88 |
+
|
89 |
+
return model, tokenizer
|
90 |
+
|
91 |
+
|
92 |
+
def _parse_text(text: str) -> str:
|
93 |
+
lines = text.split("\n")
|
94 |
+
lines = [line for line in lines if line != ""]
|
95 |
+
count = 0
|
96 |
+
for i, line in enumerate(lines):
|
97 |
+
if "```" in line:
|
98 |
+
count += 1
|
99 |
+
items = line.split("`")
|
100 |
+
if count % 2 == 1:
|
101 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
102 |
+
else:
|
103 |
+
lines[i] = f"<br></code></pre>"
|
104 |
+
else:
|
105 |
+
if i > 0:
|
106 |
+
if count % 2 == 1:
|
107 |
+
line = line.replace("`", r"\`")
|
108 |
+
line = line.replace("<", "<")
|
109 |
+
line = line.replace(">", ">")
|
110 |
+
line = line.replace(" ", " ")
|
111 |
+
line = line.replace("*", "*")
|
112 |
+
line = line.replace("_", "_")
|
113 |
+
line = line.replace("-", "-")
|
114 |
+
line = line.replace(".", ".")
|
115 |
+
line = line.replace("!", "!")
|
116 |
+
line = line.replace("(", "(")
|
117 |
+
line = line.replace(")", ")")
|
118 |
+
line = line.replace("$", "$")
|
119 |
+
lines[i] = "<br>" + line
|
120 |
+
text = "".join(lines)
|
121 |
+
return text
|
122 |
+
|
123 |
+
def save_image(image_file, upload_dir: str) -> str:
|
124 |
+
print("save_image called with:", image_file)
|
125 |
+
Path(upload_dir).mkdir(parents=True, exist_ok=True)
|
126 |
+
filename = secrets.token_hex(10) + Path(image_file.name).suffix
|
127 |
+
file_path = Path(upload_dir) / filename
|
128 |
+
print("Saving to:", file_path)
|
129 |
+
with open(image_file.name, "rb") as f_input, open(file_path, "wb") as f_output:
|
130 |
+
f_output.write(f_input.read())
|
131 |
+
return str(file_path)
|
132 |
+
|
133 |
+
|
134 |
+
def add_file(history, task_history, file):
|
135 |
+
if file is None:
|
136 |
+
return history, task_history
|
137 |
+
file_path = save_image(file)
|
138 |
+
history = history + [((file_path,), None)]
|
139 |
+
task_history = task_history + [((file_path,), None)]
|
140 |
+
return history, task_history
|
141 |
+
|
142 |
+
|
143 |
+
def predict(_chatbot, task_history) -> list:
|
144 |
+
print("predict called")
|
145 |
+
if not _chatbot:
|
146 |
+
return _chatbot
|
147 |
+
chat_query = _chatbot[-1][0]
|
148 |
+
print("Chat query:", chat_query)
|
149 |
+
|
150 |
+
if isinstance(chat_query, tuple):
|
151 |
+
query = [{'image': chat_query[0]}]
|
152 |
+
else:
|
153 |
+
query = [{'text': _parse_text(chat_query)}]
|
154 |
+
|
155 |
+
print("Query for model:", query)
|
156 |
+
inputs = tokenizer.from_list_format(query)
|
157 |
+
tokenized_inputs = tokenizer(inputs, return_tensors='pt')
|
158 |
+
tokenized_inputs = tokenized_inputs.to(model.device)
|
159 |
+
|
160 |
+
pred = model.generate(**tokenized_inputs)
|
161 |
+
response = tokenizer.decode(pred.cpu()[0], skip_special_tokens=False)
|
162 |
+
print("Model response:", response)
|
163 |
+
if 'image' in query[0]:
|
164 |
+
image = tokenizer.draw_bbox_on_latest_picture(response)
|
165 |
+
if image is not None:
|
166 |
+
image_path = save_image(image, uploaded_file_dir)
|
167 |
+
_chatbot[-1] = (chat_query, (image_path,))
|
168 |
+
else:
|
169 |
+
_chatbot[-1] = (chat_query, "No image to display.")
|
170 |
+
else:
|
171 |
+
_chatbot[-1] = (chat_query, response)
|
172 |
+
return _chatbot
|
173 |
+
|
174 |
+
def save_uploaded_image(image_file, upload_dir):
|
175 |
+
if image is None:
|
176 |
+
return None
|
177 |
+
temp_dir = secrets.token_hex(20)
|
178 |
+
temp_dir = Path(uploaded_file_dir) / temp_dir
|
179 |
+
temp_dir.mkdir(exist_ok=True, parents=True)
|
180 |
+
name = f"tmp{secrets.token_hex(5)}.jpg"
|
181 |
+
filename = temp_dir / name
|
182 |
+
image.save(str(filename))
|
183 |
+
return str(filename)
|
184 |
+
|
185 |
+
def regenerate(_chatbot, task_history) -> list:
|
186 |
+
if not task_history:
|
187 |
+
return _chatbot
|
188 |
+
item = task_history[-1]
|
189 |
+
if item[1] is None:
|
190 |
+
return _chatbot
|
191 |
+
task_history[-1] = (item[0], None)
|
192 |
+
chatbot_item = _chatbot.pop(-1)
|
193 |
+
if chatbot_item[0] is None:
|
194 |
+
_chatbot[-1] = (_chatbot[-1][0], None)
|
195 |
+
else:
|
196 |
+
_chatbot.append((chatbot_item[0], None))
|
197 |
+
return predict(_chatbot, task_history, tokenizer, model)
|
198 |
+
|
199 |
+
def add_text(history, task_history, text) -> tuple:
|
200 |
+
task_text = text
|
201 |
+
if len(text) >= 2 and text[-1] in PUNCTUATION and text[-2] not in PUNCTUATION:
|
202 |
+
task_text = text[:-1]
|
203 |
+
history = history + [(_parse_text(text), None)]
|
204 |
+
task_history = task_history + [(task_text, None)]
|
205 |
+
return history, task_history, ""
|
206 |
+
|
207 |
+
def add_file(history, task_history, file):
|
208 |
+
if file is None:
|
209 |
+
return history, task_history # Return if no file is uploaded
|
210 |
+
file_path = file.name
|
211 |
+
history = history + [((file.name,), None)]
|
212 |
+
task_history = task_history + [((file.name,), None)]
|
213 |
+
return history, task_history
|
214 |
+
|
215 |
+
def reset_user_input():
|
216 |
+
return gr.update(value="")
|
217 |
+
|
218 |
+
def process_response(response: str) -> str:
|
219 |
+
response = response.replace("<ref>", "").replace(r"</ref>", "")
|
220 |
+
response = re.sub(BOX_TAG_PATTERN, "", response)
|
221 |
+
return response
|
222 |
+
|
223 |
+
def process_history_for_model(task_history) -> list:
|
224 |
+
processed_history = []
|
225 |
+
for query, response in task_history:
|
226 |
+
if isinstance(query, tuple):
|
227 |
+
query = {'image': query[0]}
|
228 |
+
else:
|
229 |
+
query = {'text': query}
|
230 |
+
response = response or ""
|
231 |
+
processed_history.append((query, response))
|
232 |
+
return processed_history
|
233 |
+
|
234 |
+
def reset_state(task_history) -> list:
|
235 |
+
task_history.clear()
|
236 |
+
return []
|
237 |
+
|
238 |
+
|
239 |
+
def _launch_demo(args, model, tokenizer):
|
240 |
+
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
|
241 |
+
Path(tempfile.gettempdir()) / "gradio"
|
242 |
+
)
|
243 |
+
|
244 |
+
with gr.Blocks() as demo:
|
245 |
+
gr.Markdown(description)
|
246 |
+
with gr.Row():
|
247 |
+
with gr.Column(scale=1):
|
248 |
+
chatbot = gr.Chatbot(label='Qwen-VL-Chat')
|
249 |
+
with gr.Column(scale=1):
|
250 |
+
with gr.Row():
|
251 |
+
query = gr.Textbox(lines=2, label='Input', placeholder="Type your message here...")
|
252 |
+
submit_btn = gr.Button("🚀 Submit")
|
253 |
+
with gr.Row():
|
254 |
+
file_upload = gr.UploadButton("📠Upload Image", file_types=["image"])
|
255 |
+
submit_file_btn = gr.Button("Submit Image")
|
256 |
+
regen_btn = gr.Button("ðŸ¤â€Ã¯Â¸Â Regenerate")
|
257 |
+
empty_bin = gr.Button("🧹 Clear History")
|
258 |
+
task_history = gr.State([])
|
259 |
+
|
260 |
+
submit_btn.click(
|
261 |
+
fn=predict,
|
262 |
+
inputs=[chatbot, task_history],
|
263 |
+
outputs=[chatbot]
|
264 |
+
)
|
265 |
+
|
266 |
+
submit_file_btn.click(
|
267 |
+
fn=handle_image_submission,
|
268 |
+
inputs=[chatbot, task_history, file_upload],
|
269 |
+
outputs=[chatbot, task_history]
|
270 |
+
)
|
271 |
+
|
272 |
+
regen_btn.click(
|
273 |
+
fn=regenerate,
|
274 |
+
inputs=[chatbot, task_history],
|
275 |
+
outputs=[chatbot]
|
276 |
+
)
|
277 |
+
|
278 |
+
empty_bin.click(
|
279 |
+
fn=reset_state,
|
280 |
+
inputs=[task_history],
|
281 |
+
outputs=[task_history],
|
282 |
+
)
|
283 |
+
|
284 |
+
query.submit(
|
285 |
+
fn=add_text,
|
286 |
+
inputs=[chatbot, task_history, query],
|
287 |
+
outputs=[chatbot, task_history, query]
|
288 |
+
)
|
289 |
+
|
290 |
+
gr.Markdown(disclaimer)
|
291 |
+
|
292 |
+
demo.queue().launch()
|
293 |
+
|
294 |
+
|
295 |
+
def main():
|
296 |
+
args = _get_args()
|
297 |
+
model, tokenizer = _load_model_tokenizer(args)
|
298 |
+
_launch_demo(args, model, tokenizer)
|
299 |
+
|
300 |
+
if __name__ == '__main__':
|
301 |
+
main()
|