Tonic commited on
Commit
c6c641c
·
1 Parent(s): 3fca32f

Delete app.py

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