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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from modelscope import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, snapshot_download
|
| 3 |
+
from argparse import ArgumentParser
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import shutil
|
| 6 |
+
import copy
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import secrets
|
| 11 |
+
import tempfile
|
| 12 |
+
|
| 13 |
+
#GlobalVariables
|
| 14 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
|
| 15 |
+
DEFAULT_CKPT_PATH = 'qwen/Qwen-VL-Chat'
|
| 16 |
+
REVISION = 'v1.0.4'
|
| 17 |
+
BOX_TAG_PATTERN = r"<box>([\s\S]*?)</box>"
|
| 18 |
+
PUNCTUATION = "ï¼Â?。"#$%&'()*+,ï¼Âï¼Â:;<ï¼Â>ï¼ [\]^_`{|ï½Â~⦅ï½ 「」、ã€Â〃》「ã€Â『ã€Âã€Â】ã€â€Ã£â‚¬â€¢Ã£â‚¬â€“〗〘〙〚〛〜ã€Â〞〟〰〾〿–â€â€Ã¢â‚¬ËœÃ¢â‚¬â„¢Ã¢â‚¬â€ºÃ¢â‚¬Å“â€Â„‟…‧ï¹Â."
|
| 19 |
+
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(Path(tempfile.gettempdir()) / "gradio")
|
| 20 |
+
tokenizer = None
|
| 21 |
+
model = None
|
| 22 |
+
|
| 23 |
+
def _get_args() -> ArgumentParser:
|
| 24 |
+
parser = ArgumentParser()
|
| 25 |
+
parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH,
|
| 26 |
+
help="Checkpoint name or path, default to %(default)r")
|
| 27 |
+
parser.add_argument("--revision", type=str, default=REVISION)
|
| 28 |
+
parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only")
|
| 29 |
+
|
| 30 |
+
parser.add_argument("--share", action="store_true", default=False,
|
| 31 |
+
help="Create a publicly shareable link for the interface.")
|
| 32 |
+
parser.add_argument("--inbrowser", action="store_true", default=False,
|
| 33 |
+
help="Automatically launch the interface in a new tab on the default browser.")
|
| 34 |
+
parser.add_argument("--server-port", type=int, default=8000,
|
| 35 |
+
help="Demo server port.")
|
| 36 |
+
parser.add_argument("--server-name", type=str, default="127.0.0.1",
|
| 37 |
+
help="Demo server name.")
|
| 38 |
+
|
| 39 |
+
args = parser.parse_args()
|
| 40 |
+
return args
|
| 41 |
+
|
| 42 |
+
def handle_image_submission(_chatbot, task_history, file) -> tuple:
|
| 43 |
+
print("handle_image_submission called")
|
| 44 |
+
if file is None:
|
| 45 |
+
print("No file uploaded")
|
| 46 |
+
return _chatbot, task_history
|
| 47 |
+
print("File received:", file)
|
| 48 |
+
file_path = save_image(file, uploaded_file_dir)
|
| 49 |
+
print("File saved at:", file_path)
|
| 50 |
+
history_item = ((file_path,), None)
|
| 51 |
+
_chatbot.append(history_item)
|
| 52 |
+
task_history.append(history_item)
|
| 53 |
+
return predict(_chatbot, task_history, tokenizer, model)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _load_model_tokenizer(args) -> tuple:
|
| 57 |
+
global tokenizer, model
|
| 58 |
+
model_id = args.checkpoint_path
|
| 59 |
+
model_dir = snapshot_download(model_id, revision=args.revision)
|
| 60 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 61 |
+
model_dir, trust_remote_code=True, resume_download=True,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
if args.cpu_only:
|
| 65 |
+
device_map = "cpu"
|
| 66 |
+
else:
|
| 67 |
+
device_map = "auto"
|
| 68 |
+
|
| 69 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 70 |
+
model_dir,
|
| 71 |
+
device_map=device_map,
|
| 72 |
+
trust_remote_code=True,
|
| 73 |
+
bf16=True,
|
| 74 |
+
resume_download=True,
|
| 75 |
+
).eval()
|
| 76 |
+
model.generation_config = GenerationConfig.from_pretrained(
|
| 77 |
+
model_dir, trust_remote_code=True, resume_download=True,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
return model, tokenizer
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _parse_text(text: str) -> str:
|
| 84 |
+
lines = text.split("\n")
|
| 85 |
+
lines = [line for line in lines if line != ""]
|
| 86 |
+
count = 0
|
| 87 |
+
for i, line in enumerate(lines):
|
| 88 |
+
if "```" in line:
|
| 89 |
+
count += 1
|
| 90 |
+
items = line.split("`")
|
| 91 |
+
if count % 2 == 1:
|
| 92 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
| 93 |
+
else:
|
| 94 |
+
lines[i] = f"<br></code></pre>"
|
| 95 |
+
else:
|
| 96 |
+
if i > 0:
|
| 97 |
+
if count % 2 == 1:
|
| 98 |
+
line = line.replace("`", r"\`")
|
| 99 |
+
line = line.replace("<", "<")
|
| 100 |
+
line = line.replace(">", ">")
|
| 101 |
+
line = line.replace(" ", " ")
|
| 102 |
+
line = line.replace("*", "*")
|
| 103 |
+
line = line.replace("_", "_")
|
| 104 |
+
line = line.replace("-", "-")
|
| 105 |
+
line = line.replace(".", ".")
|
| 106 |
+
line = line.replace("!", "!")
|
| 107 |
+
line = line.replace("(", "(")
|
| 108 |
+
line = line.replace(")", ")")
|
| 109 |
+
line = line.replace("$", "$")
|
| 110 |
+
lines[i] = "<br>" + line
|
| 111 |
+
text = "".join(lines)
|
| 112 |
+
return text
|
| 113 |
+
|
| 114 |
+
def save_image(image_file, upload_dir: str) -> str:
|
| 115 |
+
print("save_image called with:", image_file)
|
| 116 |
+
Path(upload_dir).mkdir(parents=True, exist_ok=True)
|
| 117 |
+
filename = secrets.token_hex(10) + Path(image_file.name).suffix
|
| 118 |
+
file_path = Path(upload_dir) / filename
|
| 119 |
+
print("Saving to:", file_path)
|
| 120 |
+
with open(image_file.name, "rb") as f_input, open(file_path, "wb") as f_output:
|
| 121 |
+
f_output.write(f_input.read())
|
| 122 |
+
return str(file_path)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def add_file(history, task_history, file):
|
| 126 |
+
if file is None:
|
| 127 |
+
return history, task_history
|
| 128 |
+
file_path = save_image(file)
|
| 129 |
+
history = history + [((file_path,), None)]
|
| 130 |
+
task_history = task_history + [((file_path,), None)]
|
| 131 |
+
return history, task_history
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def predict(_chatbot, task_history) -> list:
|
| 135 |
+
print("predict called")
|
| 136 |
+
if not _chatbot:
|
| 137 |
+
return _chatbot
|
| 138 |
+
chat_query = _chatbot[-1][0]
|
| 139 |
+
print("Chat query:", chat_query)
|
| 140 |
+
|
| 141 |
+
if isinstance(chat_query, tuple):
|
| 142 |
+
query = [{'image': chat_query[0]}]
|
| 143 |
+
else:
|
| 144 |
+
query = [{'text': _parse_text(chat_query)}]
|
| 145 |
+
|
| 146 |
+
print("Query for model:", query)
|
| 147 |
+
inputs = tokenizer.from_list_format(query)
|
| 148 |
+
tokenized_inputs = tokenizer(inputs, return_tensors='pt')
|
| 149 |
+
tokenized_inputs = tokenized_inputs.to(model.device)
|
| 150 |
+
|
| 151 |
+
pred = model.generate(**tokenized_inputs)
|
| 152 |
+
response = tokenizer.decode(pred.cpu()[0], skip_special_tokens=False)
|
| 153 |
+
print("Model response:", response)
|
| 154 |
+
if 'image' in query[0]:
|
| 155 |
+
image = tokenizer.draw_bbox_on_latest_picture(response)
|
| 156 |
+
if image is not None:
|
| 157 |
+
image_path = save_image(image, uploaded_file_dir)
|
| 158 |
+
_chatbot[-1] = (chat_query, (image_path,))
|
| 159 |
+
else:
|
| 160 |
+
_chatbot[-1] = (chat_query, "No image to display.")
|
| 161 |
+
else:
|
| 162 |
+
_chatbot[-1] = (chat_query, response)
|
| 163 |
+
return _chatbot
|
| 164 |
+
|
| 165 |
+
def save_uploaded_image(image_file, upload_dir):
|
| 166 |
+
if image is None:
|
| 167 |
+
return None
|
| 168 |
+
temp_dir = secrets.token_hex(20)
|
| 169 |
+
temp_dir = Path(uploaded_file_dir) / temp_dir
|
| 170 |
+
temp_dir.mkdir(exist_ok=True, parents=True)
|
| 171 |
+
name = f"tmp{secrets.token_hex(5)}.jpg"
|
| 172 |
+
filename = temp_dir / name
|
| 173 |
+
image.save(str(filename))
|
| 174 |
+
return str(filename)
|
| 175 |
+
|
| 176 |
+
def regenerate(_chatbot, task_history) -> list:
|
| 177 |
+
if not task_history:
|
| 178 |
+
return _chatbot
|
| 179 |
+
item = task_history[-1]
|
| 180 |
+
if item[1] is None:
|
| 181 |
+
return _chatbot
|
| 182 |
+
task_history[-1] = (item[0], None)
|
| 183 |
+
chatbot_item = _chatbot.pop(-1)
|
| 184 |
+
if chatbot_item[0] is None:
|
| 185 |
+
_chatbot[-1] = (_chatbot[-1][0], None)
|
| 186 |
+
else:
|
| 187 |
+
_chatbot.append((chatbot_item[0], None))
|
| 188 |
+
return predict(_chatbot, task_history, tokenizer, model)
|
| 189 |
+
|
| 190 |
+
def add_text(history, task_history, text) -> tuple:
|
| 191 |
+
task_text = text
|
| 192 |
+
if len(text) >= 2 and text[-1] in PUNCTUATION and text[-2] not in PUNCTUATION:
|
| 193 |
+
task_text = text[:-1]
|
| 194 |
+
history = history + [(_parse_text(text), None)]
|
| 195 |
+
task_history = task_history + [(task_text, None)]
|
| 196 |
+
return history, task_history, ""
|
| 197 |
+
|
| 198 |
+
def add_file(history, task_history, file):
|
| 199 |
+
if file is None:
|
| 200 |
+
return history, task_history # Return if no file is uploaded
|
| 201 |
+
file_path = file.name
|
| 202 |
+
history = history + [((file.name,), None)]
|
| 203 |
+
task_history = task_history + [((file.name,), None)]
|
| 204 |
+
return history, task_history
|
| 205 |
+
|
| 206 |
+
def reset_user_input():
|
| 207 |
+
return gr.update(value="")
|
| 208 |
+
|
| 209 |
+
def process_response(response: str) -> str:
|
| 210 |
+
response = response.replace("<ref>", "").replace(r"</ref>", "")
|
| 211 |
+
response = re.sub(BOX_TAG_PATTERN, "", response)
|
| 212 |
+
return response
|
| 213 |
+
|
| 214 |
+
def process_history_for_model(task_history) -> list:
|
| 215 |
+
processed_history = []
|
| 216 |
+
for query, response in task_history:
|
| 217 |
+
if isinstance(query, tuple):
|
| 218 |
+
query = {'image': query[0]}
|
| 219 |
+
else:
|
| 220 |
+
query = {'text': query}
|
| 221 |
+
response = response or ""
|
| 222 |
+
processed_history.append((query, response))
|
| 223 |
+
return processed_history
|
| 224 |
+
|
| 225 |
+
def reset_state(task_history) -> list:
|
| 226 |
+
task_history.clear()
|
| 227 |
+
return []
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _launch_demo(args, model, tokenizer):
|
| 231 |
+
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
|
| 232 |
+
Path(tempfile.gettempdir()) / "gradio"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
with gr.Blocks() as demo:
|
| 236 |
+
gr.Markdown("""
|
| 237 |
+
# 🙋🏻♂️欢迎来到🌟Tonic 的🦄Qwen-VL-Chat🤩Bot!🚀
|
| 238 |
+
# 🙋🏻♂️Welcome toTonic's Qwen-VL-Chat Bot!
|
| 239 |
+
该WebUI基于Qwen-VL-Chat,实现聊天机器人功能。 但我必须解决它的很多问题,也许我也能获得一些荣誉。
|
| 240 |
+
Qwen-VL-Chat 是一种多模式输入模型。 您可以使用此空间来测试当前模型 [qwen/Qwen-VL-Chat](https://huggingface.co/qwen/Qwen-VL-Chat) 您也可以使用 🧑🏻🚀qwen/Qwen-VL -通过克隆这个空间来聊天🚀。 🧬🔬🔍 只需点击这里:[重复空间](https://huggingface.co/spaces/Tonic1/VLChat?duplicate=true)
|
| 241 |
+
加入我们:🌟TeamTonic🌟总是在制作很酷的演示! 在 👻Discord 上加入我们活跃的构建者🛠️社区:[Discord](https://discord.gg/nXx5wbX9) 在 🤗Huggingface 上:[TeamTonic](https://huggingface.co/TeamTonic) 和 [MultiTransformer](https:/ /huggingface.co/MultiTransformer) 在 🌐Github 上:[Polytonic](https://github.com/tonic-ai) 并为 🌟 [PolyGPT](https://github.com/tonic-ai/polygpt-alpha) 做出贡献 )
|
| 242 |
+
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)
|
| 243 |
+
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)
|
| 244 |
+
""")
|
| 245 |
+
with gr.Row():
|
| 246 |
+
with gr.Column(scale=1):
|
| 247 |
+
chatbot = gr.Chatbot(label='Qwen-VL-Chat')
|
| 248 |
+
with gr.Column(scale=1):
|
| 249 |
+
with gr.Row():
|
| 250 |
+
query = gr.Textbox(lines=2, label='Input', placeholder="Type your message here...")
|
| 251 |
+
submit_btn = gr.Button("🚀 Submit")
|
| 252 |
+
with gr.Row():
|
| 253 |
+
file_upload = gr.UploadButton("📠Upload Image", file_types=["image"])
|
| 254 |
+
submit_file_btn = gr.Button("Submit Image")
|
| 255 |
+
regen_btn = gr.Button("ðŸ¤â€Ã¯Â¸Â Regenerate")
|
| 256 |
+
empty_bin = gr.Button("🧹 Clear History")
|
| 257 |
+
task_history = gr.State([])
|
| 258 |
+
|
| 259 |
+
submit_btn.click(
|
| 260 |
+
fn=predict,
|
| 261 |
+
inputs=[chatbot, task_history],
|
| 262 |
+
outputs=[chatbot]
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
submit_file_btn.click(
|
| 266 |
+
fn=handle_image_submission,
|
| 267 |
+
inputs=[chatbot, task_history, file_upload],
|
| 268 |
+
outputs=[chatbot, task_history]
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
regen_btn.click(
|
| 272 |
+
fn=regenerate,
|
| 273 |
+
inputs=[chatbot, task_history],
|
| 274 |
+
outputs=[chatbot]
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
empty_bin.click(
|
| 278 |
+
fn=reset_state,
|
| 279 |
+
inputs=[task_history],
|
| 280 |
+
outputs=[task_history],
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
query.submit(
|
| 284 |
+
fn=add_text,
|
| 285 |
+
inputs=[chatbot, task_history, query],
|
| 286 |
+
outputs=[chatbot, task_history, query]
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
gr.Markdown("""
|
| 290 |
+
注意:此演示受 Qwen-VL 原始许可证的约束。我们强烈建议用户不要故意生成或允许他人故意生成有害内容,
|
| 291 |
+
包括仇恨言论、暴力、色情、欺骗等。(注:本演示受Qwen-VL许可协议约束,强烈建议用户不要传播或允许他人传播以下内容,包括但不限于仇恨言论、暴力、色情、欺诈相关的有害信息 .)
|
| 292 |
+
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,
|
| 293 |
+
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.)
|
| 294 |
+
""")
|
| 295 |
+
|
| 296 |
+
demo.queue().launch()
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def main():
|
| 300 |
+
args = _get_args()
|
| 301 |
+
model, tokenizer = _load_model_tokenizer(args)
|
| 302 |
+
_launch_demo(args, model, tokenizer)
|
| 303 |
+
|
| 304 |
+
if __name__ == '__main__':
|
| 305 |
+
main()
|