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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2023-2024 DeepSeek.
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
4 |
+
# this software and associated documentation files (the "Software"), to deal in
|
5 |
+
# the Software without restriction, including without limitation the rights to
|
6 |
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
7 |
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
8 |
+
# subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in all
|
11 |
+
# copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
15 |
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
16 |
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
17 |
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
18 |
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
19 |
+
|
20 |
+
# -*- coding:utf-8 -*-
|
21 |
+
from argparse import ArgumentParser
|
22 |
+
|
23 |
+
import io
|
24 |
+
import sys
|
25 |
+
import base64
|
26 |
+
from PIL import Image
|
27 |
+
|
28 |
+
import gradio as gr
|
29 |
+
import torch
|
30 |
+
|
31 |
+
from deepseek_vl2.serve.app_modules.gradio_utils import (
|
32 |
+
cancel_outputing,
|
33 |
+
delete_last_conversation,
|
34 |
+
reset_state,
|
35 |
+
reset_textbox,
|
36 |
+
wrap_gen_fn,
|
37 |
+
)
|
38 |
+
from deepseek_vl2.serve.app_modules.overwrites import reload_javascript
|
39 |
+
from deepseek_vl2.serve.app_modules.presets import (
|
40 |
+
CONCURRENT_COUNT,
|
41 |
+
MAX_EVENTS,
|
42 |
+
description,
|
43 |
+
description_top,
|
44 |
+
title
|
45 |
+
)
|
46 |
+
from deepseek_vl2.serve.app_modules.utils import (
|
47 |
+
configure_logger,
|
48 |
+
is_variable_assigned,
|
49 |
+
strip_stop_words,
|
50 |
+
parse_ref_bbox,
|
51 |
+
pil_to_base64,
|
52 |
+
display_example
|
53 |
+
)
|
54 |
+
|
55 |
+
from deepseek_vl2.serve.inference import (
|
56 |
+
convert_conversation_to_prompts,
|
57 |
+
deepseek_generate,
|
58 |
+
load_model,
|
59 |
+
)
|
60 |
+
from deepseek_vl2.models.conversation import SeparatorStyle
|
61 |
+
|
62 |
+
logger = configure_logger()
|
63 |
+
|
64 |
+
MODELS = [
|
65 |
+
"DeepSeek-VL2-tiny",
|
66 |
+
"DeepSeek-VL2-small",
|
67 |
+
"DeepSeek-VL2",
|
68 |
+
|
69 |
+
"deepseek-ai/deepseek-vl2-tiny",
|
70 |
+
"deepseek-ai/deepseek-vl2-small",
|
71 |
+
"deepseek-ai/deepseek-vl2",
|
72 |
+
]
|
73 |
+
|
74 |
+
DEPLOY_MODELS = dict()
|
75 |
+
IMAGE_TOKEN = "<image>"
|
76 |
+
|
77 |
+
examples_list = [
|
78 |
+
# visual grounding - 1
|
79 |
+
[
|
80 |
+
["images/visual_grounding_1.jpeg"],
|
81 |
+
"<|ref|>The giraffe at the back.<|/ref|>",
|
82 |
+
],
|
83 |
+
|
84 |
+
# visual grounding - 2
|
85 |
+
[
|
86 |
+
["images/visual_grounding_2.jpg"],
|
87 |
+
"ๆพๅฐ<|ref|>ๆทกๅฎๅง<|/ref|>",
|
88 |
+
],
|
89 |
+
|
90 |
+
# visual grounding - 3
|
91 |
+
[
|
92 |
+
["images/visual_grounding_3.png"],
|
93 |
+
"Find all the <|ref|>Watermelon slices<|/ref|>",
|
94 |
+
],
|
95 |
+
|
96 |
+
# grounding conversation
|
97 |
+
[
|
98 |
+
["images/grounding_conversation_1.jpeg"],
|
99 |
+
"<|grounding|>I want to throw out the trash now, what should I do?",
|
100 |
+
],
|
101 |
+
|
102 |
+
# in-context visual grounding
|
103 |
+
[
|
104 |
+
[
|
105 |
+
"images/incontext_visual_grounding_1.jpeg",
|
106 |
+
"images/icl_vg_2.jpeg"
|
107 |
+
],
|
108 |
+
"<|grounding|>In the first image, an object within the red rectangle is marked. Locate the object of the same category in the second image."
|
109 |
+
],
|
110 |
+
|
111 |
+
# vqa
|
112 |
+
[
|
113 |
+
["images/vqa_1.jpg"],
|
114 |
+
"Describe each stage of this image in detail",
|
115 |
+
],
|
116 |
+
|
117 |
+
# multi-images
|
118 |
+
[
|
119 |
+
[
|
120 |
+
"images/multi_image_1.jpeg",
|
121 |
+
"images/mi_2.jpeg",
|
122 |
+
"images/mi_3.jpeg"
|
123 |
+
],
|
124 |
+
"่ฝๅธฎๆ็จ่ฟๅ ไธช้ฃๆๅไธ้่ๅ?",
|
125 |
+
]
|
126 |
+
|
127 |
+
]
|
128 |
+
|
129 |
+
|
130 |
+
def fetch_model(model_name: str, dtype=torch.bfloat16):
|
131 |
+
global args, DEPLOY_MODELS
|
132 |
+
|
133 |
+
if args.local_path:
|
134 |
+
model_path = args.local_path
|
135 |
+
else:
|
136 |
+
model_path = model_name
|
137 |
+
|
138 |
+
if model_name in DEPLOY_MODELS:
|
139 |
+
model_info = DEPLOY_MODELS[model_name]
|
140 |
+
print(f"{model_name} has been loaded.")
|
141 |
+
else:
|
142 |
+
print(f"{model_name} is loading...")
|
143 |
+
DEPLOY_MODELS[model_name] = load_model(model_path, dtype=dtype)
|
144 |
+
print(f"Load {model_name} successfully...")
|
145 |
+
model_info = DEPLOY_MODELS[model_name]
|
146 |
+
|
147 |
+
return model_info
|
148 |
+
|
149 |
+
|
150 |
+
def generate_prompt_with_history(
|
151 |
+
text, images, history, vl_chat_processor, tokenizer, max_length=2048
|
152 |
+
):
|
153 |
+
"""
|
154 |
+
Generate a prompt with history for the deepseek application.
|
155 |
+
|
156 |
+
Args:
|
157 |
+
text (str): The text prompt.
|
158 |
+
images (list[PIL.Image.Image]): The image prompt.
|
159 |
+
history (list): List of previous conversation messages.
|
160 |
+
tokenizer: The tokenizer used for encoding the prompt.
|
161 |
+
max_length (int): The maximum length of the prompt.
|
162 |
+
|
163 |
+
Returns:
|
164 |
+
tuple: A tuple containing the generated prompt, image list, conversation, and conversation copy. If the prompt could not be generated within the max_length limit, returns None.
|
165 |
+
"""
|
166 |
+
global IMAGE_TOKEN
|
167 |
+
|
168 |
+
sft_format = "deepseek"
|
169 |
+
user_role_ind = 0
|
170 |
+
bot_role_ind = 1
|
171 |
+
|
172 |
+
# Initialize conversation
|
173 |
+
conversation = vl_chat_processor.new_chat_template()
|
174 |
+
|
175 |
+
if history:
|
176 |
+
conversation.messages = history
|
177 |
+
|
178 |
+
if images is not None and len(images) > 0:
|
179 |
+
|
180 |
+
num_image_tags = text.count(IMAGE_TOKEN)
|
181 |
+
num_images = len(images)
|
182 |
+
|
183 |
+
if num_images > num_image_tags:
|
184 |
+
pad_image_tags = num_images - num_image_tags
|
185 |
+
image_tokens = "\n".join([IMAGE_TOKEN] * pad_image_tags)
|
186 |
+
|
187 |
+
# append the <image> in a new line after the text prompt
|
188 |
+
text = image_tokens + "\n" + text
|
189 |
+
elif num_images < num_image_tags:
|
190 |
+
remove_image_tags = num_image_tags - num_images
|
191 |
+
text = text.replace(IMAGE_TOKEN, "", remove_image_tags)
|
192 |
+
|
193 |
+
# print(f"prompt = {text}, len(images) = {len(images)}")
|
194 |
+
text = (text, images)
|
195 |
+
|
196 |
+
conversation.append_message(conversation.roles[user_role_ind], text)
|
197 |
+
conversation.append_message(conversation.roles[bot_role_ind], "")
|
198 |
+
|
199 |
+
# Create a copy of the conversation to avoid history truncation in the UI
|
200 |
+
conversation_copy = conversation.copy()
|
201 |
+
logger.info("=" * 80)
|
202 |
+
logger.info(get_prompt(conversation))
|
203 |
+
|
204 |
+
rounds = len(conversation.messages) // 2
|
205 |
+
|
206 |
+
for _ in range(rounds):
|
207 |
+
current_prompt = get_prompt(conversation)
|
208 |
+
current_prompt = (
|
209 |
+
current_prompt.replace("</s>", "")
|
210 |
+
if sft_format == "deepseek"
|
211 |
+
else current_prompt
|
212 |
+
)
|
213 |
+
|
214 |
+
if torch.tensor(tokenizer.encode(current_prompt)).size(-1) <= max_length:
|
215 |
+
return conversation_copy
|
216 |
+
|
217 |
+
if len(conversation.messages) % 2 != 0:
|
218 |
+
gr.Error("The messages between user and assistant are not paired.")
|
219 |
+
return
|
220 |
+
|
221 |
+
try:
|
222 |
+
for _ in range(2): # pop out two messages in a row
|
223 |
+
conversation.messages.pop(0)
|
224 |
+
except IndexError:
|
225 |
+
gr.Error("Input text processing failed, unable to respond in this round.")
|
226 |
+
return None
|
227 |
+
|
228 |
+
gr.Error("Prompt could not be generated within max_length limit.")
|
229 |
+
return None
|
230 |
+
|
231 |
+
|
232 |
+
def to_gradio_chatbot(conv):
|
233 |
+
"""Convert the conversation to gradio chatbot format."""
|
234 |
+
ret = []
|
235 |
+
for i, (role, msg) in enumerate(conv.messages[conv.offset:]):
|
236 |
+
if i % 2 == 0:
|
237 |
+
if type(msg) is tuple:
|
238 |
+
msg, images = msg
|
239 |
+
|
240 |
+
if isinstance(images, list):
|
241 |
+
for j, image in enumerate(images):
|
242 |
+
if isinstance(image, str):
|
243 |
+
with open(image, "rb") as f:
|
244 |
+
data = f.read()
|
245 |
+
img_b64_str = base64.b64encode(data).decode()
|
246 |
+
image_str = (f'<img src="data:image/png;base64,{img_b64_str}" '
|
247 |
+
f'alt="user upload image" style="max-width: 300px; height: auto;" />')
|
248 |
+
else:
|
249 |
+
image_str = pil_to_base64(image, f"user upload image_{j}", max_size=800, min_size=400)
|
250 |
+
|
251 |
+
# replace the <image> tag in the message
|
252 |
+
msg = msg.replace(IMAGE_TOKEN, image_str, 1)
|
253 |
+
|
254 |
+
else:
|
255 |
+
pass
|
256 |
+
|
257 |
+
ret.append([msg, None])
|
258 |
+
else:
|
259 |
+
ret[-1][-1] = msg
|
260 |
+
return ret
|
261 |
+
|
262 |
+
|
263 |
+
def to_gradio_history(conv):
|
264 |
+
"""Convert the conversation to gradio history state."""
|
265 |
+
return conv.messages[conv.offset:]
|
266 |
+
|
267 |
+
|
268 |
+
def get_prompt(conv) -> str:
|
269 |
+
"""Get the prompt for generation."""
|
270 |
+
system_prompt = conv.system_template.format(system_message=conv.system_message)
|
271 |
+
if conv.sep_style == SeparatorStyle.DeepSeek:
|
272 |
+
seps = [conv.sep, conv.sep2]
|
273 |
+
if system_prompt == "" or system_prompt is None:
|
274 |
+
ret = ""
|
275 |
+
else:
|
276 |
+
ret = system_prompt + seps[0]
|
277 |
+
for i, (role, message) in enumerate(conv.messages):
|
278 |
+
if message:
|
279 |
+
if type(message) is tuple: # multimodal message
|
280 |
+
message, _ = message
|
281 |
+
ret += role + ": " + message + seps[i % 2]
|
282 |
+
else:
|
283 |
+
ret += role + ":"
|
284 |
+
return ret
|
285 |
+
else:
|
286 |
+
return conv.get_prompt()
|
287 |
+
|
288 |
+
|
289 |
+
def transfer_input(input_text, input_images):
|
290 |
+
print("transferring input text and input image")
|
291 |
+
|
292 |
+
return (
|
293 |
+
input_text,
|
294 |
+
input_images,
|
295 |
+
gr.update(value=""),
|
296 |
+
gr.update(value=None),
|
297 |
+
gr.Button(visible=True)
|
298 |
+
)
|
299 |
+
|
300 |
+
|
301 |
+
@wrap_gen_fn
|
302 |
+
def predict(
|
303 |
+
text,
|
304 |
+
images,
|
305 |
+
chatbot,
|
306 |
+
history,
|
307 |
+
top_p,
|
308 |
+
temperature,
|
309 |
+
repetition_penalty,
|
310 |
+
max_length_tokens,
|
311 |
+
max_context_length_tokens,
|
312 |
+
model_select_dropdown,
|
313 |
+
):
|
314 |
+
"""
|
315 |
+
Function to predict the response based on the user's input and selected model.
|
316 |
+
|
317 |
+
Parameters:
|
318 |
+
user_text (str): The input text from the user.
|
319 |
+
user_image (str): The input image from the user.
|
320 |
+
chatbot (str): The chatbot's name.
|
321 |
+
history (str): The history of the chat.
|
322 |
+
top_p (float): The top-p parameter for the model.
|
323 |
+
temperature (float): The temperature parameter for the model.
|
324 |
+
max_length_tokens (int): The maximum length of tokens for the model.
|
325 |
+
max_context_length_tokens (int): The maximum length of context tokens for the model.
|
326 |
+
model_select_dropdown (str): The selected model from the dropdown.
|
327 |
+
|
328 |
+
Returns:
|
329 |
+
generator: A generator that yields the chatbot outputs, history, and status.
|
330 |
+
"""
|
331 |
+
print("running the prediction function")
|
332 |
+
try:
|
333 |
+
tokenizer, vl_gpt, vl_chat_processor = fetch_model(model_select_dropdown)
|
334 |
+
|
335 |
+
if text == "":
|
336 |
+
yield chatbot, history, "Empty context."
|
337 |
+
return
|
338 |
+
except KeyError:
|
339 |
+
yield [[text, "No Model Found"]], [], "No Model Found"
|
340 |
+
return
|
341 |
+
|
342 |
+
if images is None:
|
343 |
+
images = []
|
344 |
+
|
345 |
+
# load images
|
346 |
+
pil_images = []
|
347 |
+
for img_or_file in images:
|
348 |
+
try:
|
349 |
+
# load as pil image
|
350 |
+
if isinstance(images, Image.Image):
|
351 |
+
pil_images.append(img_or_file)
|
352 |
+
else:
|
353 |
+
image = Image.open(img_or_file.name).convert("RGB")
|
354 |
+
pil_images.append(image)
|
355 |
+
except Exception as e:
|
356 |
+
print(f"Error loading image: {e}")
|
357 |
+
|
358 |
+
conversation = generate_prompt_with_history(
|
359 |
+
text,
|
360 |
+
pil_images,
|
361 |
+
history,
|
362 |
+
vl_chat_processor,
|
363 |
+
tokenizer,
|
364 |
+
max_length=max_context_length_tokens,
|
365 |
+
)
|
366 |
+
all_conv, last_image = convert_conversation_to_prompts(conversation)
|
367 |
+
|
368 |
+
stop_words = conversation.stop_str
|
369 |
+
gradio_chatbot_output = to_gradio_chatbot(conversation)
|
370 |
+
|
371 |
+
full_response = ""
|
372 |
+
with torch.no_grad():
|
373 |
+
for x in deepseek_generate(
|
374 |
+
conversations=all_conv,
|
375 |
+
vl_gpt=vl_gpt,
|
376 |
+
vl_chat_processor=vl_chat_processor,
|
377 |
+
tokenizer=tokenizer,
|
378 |
+
stop_words=stop_words,
|
379 |
+
max_length=max_length_tokens,
|
380 |
+
temperature=temperature,
|
381 |
+
repetition_penalty=repetition_penalty,
|
382 |
+
top_p=top_p,
|
383 |
+
chunk_size=args.chunk_size
|
384 |
+
):
|
385 |
+
full_response += x
|
386 |
+
response = strip_stop_words(full_response, stop_words)
|
387 |
+
conversation.update_last_message(response)
|
388 |
+
gradio_chatbot_output[-1][1] = response
|
389 |
+
|
390 |
+
# sys.stdout.write(x)
|
391 |
+
# sys.stdout.flush()
|
392 |
+
|
393 |
+
yield gradio_chatbot_output, to_gradio_history(conversation), "Generating..."
|
394 |
+
|
395 |
+
if last_image is not None:
|
396 |
+
# TODO always render the last image's visual grounding image
|
397 |
+
vg_image = parse_ref_bbox(response, last_image)
|
398 |
+
if vg_image is not None:
|
399 |
+
vg_base64 = pil_to_base64(vg_image, f"vg", max_size=800, min_size=400)
|
400 |
+
gradio_chatbot_output[-1][1] += vg_base64
|
401 |
+
yield gradio_chatbot_output, to_gradio_history(conversation), "Generating..."
|
402 |
+
|
403 |
+
print("flushed result to gradio")
|
404 |
+
torch.cuda.empty_cache()
|
405 |
+
|
406 |
+
if is_variable_assigned("x"):
|
407 |
+
print(f"{model_select_dropdown}:\n{text}\n{'-' * 80}\n{x}\n{'=' * 80}")
|
408 |
+
print(
|
409 |
+
f"temperature: {temperature}, "
|
410 |
+
f"top_p: {top_p}, "
|
411 |
+
f"repetition_penalty: {repetition_penalty}, "
|
412 |
+
f"max_length_tokens: {max_length_tokens}"
|
413 |
+
)
|
414 |
+
|
415 |
+
yield gradio_chatbot_output, to_gradio_history(conversation), "Generate: Success"
|
416 |
+
|
417 |
+
|
418 |
+
# @wrap_gen_fn
|
419 |
+
def retry(
|
420 |
+
text,
|
421 |
+
images,
|
422 |
+
chatbot,
|
423 |
+
history,
|
424 |
+
top_p,
|
425 |
+
temperature,
|
426 |
+
repetition_penalty,
|
427 |
+
max_length_tokens,
|
428 |
+
max_context_length_tokens,
|
429 |
+
model_select_dropdown,
|
430 |
+
):
|
431 |
+
if len(history) == 0:
|
432 |
+
yield (chatbot, history, "Empty context")
|
433 |
+
return
|
434 |
+
|
435 |
+
chatbot.pop()
|
436 |
+
history.pop()
|
437 |
+
text = history.pop()[-1]
|
438 |
+
if type(text) is tuple:
|
439 |
+
text, image = text
|
440 |
+
|
441 |
+
yield from predict(
|
442 |
+
text,
|
443 |
+
images,
|
444 |
+
chatbot,
|
445 |
+
history,
|
446 |
+
top_p,
|
447 |
+
temperature,
|
448 |
+
repetition_penalty,
|
449 |
+
max_length_tokens,
|
450 |
+
max_context_length_tokens,
|
451 |
+
model_select_dropdown,
|
452 |
+
args.chunk_size
|
453 |
+
)
|
454 |
+
|
455 |
+
|
456 |
+
def preview_images(files):
|
457 |
+
if files is None:
|
458 |
+
return []
|
459 |
+
|
460 |
+
image_paths = []
|
461 |
+
for file in files:
|
462 |
+
# ไฝฟ็จ file.name ่ทๅๆไปถ่ทฏๅพ
|
463 |
+
# image = Image.open(file.name)
|
464 |
+
image_paths.append(file.name)
|
465 |
+
return image_paths # ่ฟๅๆๆๅพ็่ทฏๅพ๏ผ็จไบ้ข่ง
|
466 |
+
|
467 |
+
|
468 |
+
def build_demo(args):
|
469 |
+
# fetch model
|
470 |
+
if not args.lazy_load:
|
471 |
+
fetch_model(args.model_name)
|
472 |
+
|
473 |
+
with open("deepseek_vl2/serve/assets/custom.css", "r", encoding="utf-8") as f:
|
474 |
+
customCSS = f.read()
|
475 |
+
|
476 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
477 |
+
history = gr.State([])
|
478 |
+
input_text = gr.State()
|
479 |
+
input_images = gr.State()
|
480 |
+
|
481 |
+
with gr.Row():
|
482 |
+
gr.HTML(title)
|
483 |
+
status_display = gr.Markdown("Success", elem_id="status_display")
|
484 |
+
gr.Markdown(description_top)
|
485 |
+
|
486 |
+
with gr.Row(equal_height=True):
|
487 |
+
with gr.Column(scale=4):
|
488 |
+
with gr.Row():
|
489 |
+
chatbot = gr.Chatbot(
|
490 |
+
elem_id="deepseek_chatbot",
|
491 |
+
show_share_button=True,
|
492 |
+
bubble_full_width=False,
|
493 |
+
height=600,
|
494 |
+
)
|
495 |
+
with gr.Row():
|
496 |
+
with gr.Column(scale=4):
|
497 |
+
text_box = gr.Textbox(
|
498 |
+
show_label=False, placeholder="Enter text", container=False
|
499 |
+
)
|
500 |
+
with gr.Column(
|
501 |
+
min_width=70,
|
502 |
+
):
|
503 |
+
submitBtn = gr.Button("Send")
|
504 |
+
with gr.Column(
|
505 |
+
min_width=70,
|
506 |
+
):
|
507 |
+
cancelBtn = gr.Button("Stop")
|
508 |
+
with gr.Row():
|
509 |
+
emptyBtn = gr.Button(
|
510 |
+
"๐งน New Conversation",
|
511 |
+
)
|
512 |
+
retryBtn = gr.Button("๐ Regenerate")
|
513 |
+
delLastBtn = gr.Button("๐๏ธ Remove Last Turn")
|
514 |
+
|
515 |
+
with gr.Column():
|
516 |
+
upload_images = gr.Files(file_types=["image"], show_label=True)
|
517 |
+
gallery = gr.Gallery(columns=[3], height="200px", show_label=True)
|
518 |
+
|
519 |
+
upload_images.change(preview_images, inputs=upload_images, outputs=gallery)
|
520 |
+
|
521 |
+
with gr.Tab(label="Parameter Setting") as parameter_row:
|
522 |
+
top_p = gr.Slider(
|
523 |
+
minimum=-0,
|
524 |
+
maximum=1.0,
|
525 |
+
value=0.9,
|
526 |
+
step=0.05,
|
527 |
+
interactive=True,
|
528 |
+
label="Top-p",
|
529 |
+
)
|
530 |
+
temperature = gr.Slider(
|
531 |
+
minimum=0,
|
532 |
+
maximum=1.0,
|
533 |
+
value=0.1,
|
534 |
+
step=0.1,
|
535 |
+
interactive=True,
|
536 |
+
label="Temperature",
|
537 |
+
)
|
538 |
+
repetition_penalty = gr.Slider(
|
539 |
+
minimum=0.0,
|
540 |
+
maximum=2.0,
|
541 |
+
value=1.1,
|
542 |
+
step=0.1,
|
543 |
+
interactive=True,
|
544 |
+
label="Repetition penalty",
|
545 |
+
)
|
546 |
+
max_length_tokens = gr.Slider(
|
547 |
+
minimum=0,
|
548 |
+
maximum=4096,
|
549 |
+
value=2048,
|
550 |
+
step=8,
|
551 |
+
interactive=True,
|
552 |
+
label="Max Generation Tokens",
|
553 |
+
)
|
554 |
+
max_context_length_tokens = gr.Slider(
|
555 |
+
minimum=0,
|
556 |
+
maximum=8192,
|
557 |
+
value=4096,
|
558 |
+
step=128,
|
559 |
+
interactive=True,
|
560 |
+
label="Max History Tokens",
|
561 |
+
)
|
562 |
+
model_select_dropdown = gr.Dropdown(
|
563 |
+
label="Select Models",
|
564 |
+
choices=[args.model_name],
|
565 |
+
multiselect=False,
|
566 |
+
value=args.model_name,
|
567 |
+
interactive=True,
|
568 |
+
)
|
569 |
+
|
570 |
+
# show images, but not visible
|
571 |
+
show_images = gr.HTML(visible=False)
|
572 |
+
# show_images = gr.Image(type="pil", interactive=False, visible=False)
|
573 |
+
|
574 |
+
def format_examples(examples_list):
|
575 |
+
examples = []
|
576 |
+
for images, texts in examples_list:
|
577 |
+
examples.append([images, display_example(images), texts])
|
578 |
+
|
579 |
+
return examples
|
580 |
+
|
581 |
+
gr.Examples(
|
582 |
+
examples=format_examples(examples_list),
|
583 |
+
inputs=[upload_images, show_images, text_box],
|
584 |
+
)
|
585 |
+
|
586 |
+
gr.Markdown(description)
|
587 |
+
|
588 |
+
input_widgets = [
|
589 |
+
input_text,
|
590 |
+
input_images,
|
591 |
+
chatbot,
|
592 |
+
history,
|
593 |
+
top_p,
|
594 |
+
temperature,
|
595 |
+
repetition_penalty,
|
596 |
+
max_length_tokens,
|
597 |
+
max_context_length_tokens,
|
598 |
+
model_select_dropdown,
|
599 |
+
]
|
600 |
+
output_widgets = [chatbot, history, status_display]
|
601 |
+
|
602 |
+
transfer_input_args = dict(
|
603 |
+
fn=transfer_input,
|
604 |
+
inputs=[text_box, upload_images],
|
605 |
+
outputs=[input_text, input_images, text_box, upload_images, submitBtn],
|
606 |
+
show_progress=True,
|
607 |
+
)
|
608 |
+
|
609 |
+
predict_args = dict(
|
610 |
+
fn=predict,
|
611 |
+
inputs=input_widgets,
|
612 |
+
outputs=output_widgets,
|
613 |
+
show_progress=True,
|
614 |
+
)
|
615 |
+
|
616 |
+
retry_args = dict(
|
617 |
+
fn=retry,
|
618 |
+
inputs=input_widgets,
|
619 |
+
outputs=output_widgets,
|
620 |
+
show_progress=True,
|
621 |
+
)
|
622 |
+
|
623 |
+
reset_args = dict(
|
624 |
+
fn=reset_textbox, inputs=[], outputs=[text_box, status_display]
|
625 |
+
)
|
626 |
+
|
627 |
+
predict_events = [
|
628 |
+
text_box.submit(**transfer_input_args).then(**predict_args),
|
629 |
+
submitBtn.click(**transfer_input_args).then(**predict_args),
|
630 |
+
]
|
631 |
+
|
632 |
+
emptyBtn.click(reset_state, outputs=output_widgets, show_progress=True)
|
633 |
+
emptyBtn.click(**reset_args)
|
634 |
+
retryBtn.click(**retry_args)
|
635 |
+
|
636 |
+
delLastBtn.click(
|
637 |
+
delete_last_conversation,
|
638 |
+
[chatbot, history],
|
639 |
+
output_widgets,
|
640 |
+
show_progress=True,
|
641 |
+
)
|
642 |
+
|
643 |
+
cancelBtn.click(cancel_outputing, [], [status_display], cancels=predict_events)
|
644 |
+
|
645 |
+
return demo
|
646 |
+
|
647 |
+
|
648 |
+
if __name__ == "__main__":
|
649 |
+
parser = ArgumentParser()
|
650 |
+
parser.add_argument("--model_name", type=str, default="deepseek-ai/deepseek-vl2-small", choices=MODELS, help="model name")
|
651 |
+
parser.add_argument("--local_path", type=str, default="", help="huggingface ckpt, optional")
|
652 |
+
parser.add_argument("--ip", type=str, default="0.0.0.0", help="ip address")
|
653 |
+
parser.add_argument("--port", type=int, default=37913, help="port number")
|
654 |
+
parser.add_argument("--root_path", type=str, default="", help="root path")
|
655 |
+
parser.add_argument("--lazy_load", action='store_true')
|
656 |
+
parser.add_argument("--chunk_size", type=int, default=512,
|
657 |
+
help="chunk size for the model for prefiiling. "
|
658 |
+
"When using 40G gpu for vl2-small, set a chunk_size for incremental_prefilling."
|
659 |
+
"Otherwise, default value is -1, which means we do not use incremental_prefilling.")
|
660 |
+
args = parser.parse_args()
|
661 |
+
|
662 |
+
demo = build_demo(args)
|
663 |
+
demo.title = "DeepSeek-VL2 Chatbot"
|
664 |
+
|
665 |
+
reload_javascript()
|
666 |
+
demo.queue(concurrency_count=CONCURRENT_COUNT, max_size=MAX_EVENTS).launch(
|
667 |
+
# share=False,
|
668 |
+
share=True,
|
669 |
+
favicon_path="deepseek_vl2/serve/assets/favicon.ico",
|
670 |
+
)
|