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import dataclass, field
|
8 |
+
import io
|
9 |
+
import base64
|
10 |
+
from PIL import Image
|
11 |
+
import gradio as gr
|
12 |
+
import time
|
13 |
+
import hashlib
|
14 |
+
import requests
|
15 |
+
import subprocess
|
16 |
+
|
17 |
+
from utils import build_logger
|
18 |
+
from conversation import conv_seed_llama2
|
19 |
+
|
20 |
+
subprocess.call(['python3', 'src/demo/seed_llama_flask.py', '--image_transform', 'configs/processer/qwen_448_transform.yaml', \
|
21 |
+
'--tokenizer', 'configs/tokenizer/clm_llama_tokenizer_224loc_anyres.yaml', \
|
22 |
+
'--llm', 'configs/clm_models/llm_seed_x_i.yaml', \
|
23 |
+
'--visual_encoder', 'configs/visual_encoder/qwen_vitg_448.yaml', \
|
24 |
+
'--sd_adapter', 'configs/sdxl_adapter/sdxl_qwen_vit_resampler_l4_q64_pretrain_no_normalize.yaml', \
|
25 |
+
'--agent', 'configs/clm_models/agent_seed_x_i.yaml', \
|
26 |
+
'--diffusion_path', 'https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0', \
|
27 |
+
'--port', '7890', '--llm_device', 'cuda:0', '--vit_sd_device', 'cuda:0', '--multi_resolution', 'True', '--has_bbox'])
|
28 |
+
|
29 |
+
IMG_FLAG = '<image>'
|
30 |
+
LOGDIR = 'log'
|
31 |
+
|
32 |
+
logger = build_logger("gradio_seed_x", LOGDIR)
|
33 |
+
headers = {"User-Agent": "SEED-X Client"}
|
34 |
+
|
35 |
+
no_change_btn = gr.Button.update()
|
36 |
+
enable_btn = gr.Button.update(interactive=True)
|
37 |
+
disable_btn = gr.Button.update(interactive=False)
|
38 |
+
|
39 |
+
|
40 |
+
@dataclass
|
41 |
+
class Arguments:
|
42 |
+
server_port: Optional[int] = field(default=7860, metadata={"help": "network port"})
|
43 |
+
server_name: Optional[str] = field(default='0.0.0.0', metadata={"help": "network address"})
|
44 |
+
request_address: Optional[str] = field(default='http://127.0.0.1:7890/generate',
|
45 |
+
metadata={"help": "request address"})
|
46 |
+
|
47 |
+
|
48 |
+
parser = transformers.HfArgumentParser(Arguments)
|
49 |
+
args, = parser.parse_args_into_dataclasses()
|
50 |
+
conv_seed_llama = conv_seed_llama2
|
51 |
+
|
52 |
+
|
53 |
+
def decode_image(encoded_image: str) -> Image:
|
54 |
+
decoded_bytes = base64.b64decode(encoded_image.encode('utf-8'))
|
55 |
+
buffer = io.BytesIO(decoded_bytes)
|
56 |
+
image = Image.open(buffer)
|
57 |
+
return image
|
58 |
+
|
59 |
+
|
60 |
+
def encode_image(image: Image.Image, format: str = 'PNG') -> str:
|
61 |
+
with io.BytesIO() as buffer:
|
62 |
+
image.save(buffer, format=format)
|
63 |
+
encoded_image = base64.b64encode(buffer.getvalue()).decode('utf-8')
|
64 |
+
return encoded_image
|
65 |
+
|
66 |
+
|
67 |
+
def get_conv_log_filename():
|
68 |
+
t = datetime.datetime.now()
|
69 |
+
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
|
70 |
+
return name
|
71 |
+
|
72 |
+
|
73 |
+
def get_conv_image_dir():
|
74 |
+
name = os.path.join(LOGDIR, 'images')
|
75 |
+
os.makedirs(name, exist_ok=True)
|
76 |
+
return name
|
77 |
+
|
78 |
+
|
79 |
+
def get_image_name(image, image_dir=None):
|
80 |
+
buffer = io.BytesIO()
|
81 |
+
image.save(buffer, format='PNG')
|
82 |
+
image_bytes = buffer.getvalue()
|
83 |
+
md5 = hashlib.md5(image_bytes).hexdigest()
|
84 |
+
|
85 |
+
if image_dir is not None:
|
86 |
+
image_name = os.path.join(image_dir, md5 + '.png')
|
87 |
+
else:
|
88 |
+
image_name = md5 + '.png'
|
89 |
+
|
90 |
+
return image_name
|
91 |
+
|
92 |
+
|
93 |
+
def resize_image_square(image, target_size=448):
|
94 |
+
resized_image = image.resize((target_size, target_size))
|
95 |
+
return resized_image
|
96 |
+
|
97 |
+
|
98 |
+
def resize_image(image, max_size=512):
|
99 |
+
width, height = image.size
|
100 |
+
aspect_ratio = float(width) / float(height)
|
101 |
+
|
102 |
+
if width > height:
|
103 |
+
new_width = max_size
|
104 |
+
new_height = int(new_width / aspect_ratio)
|
105 |
+
else:
|
106 |
+
new_height = max_size
|
107 |
+
new_width = int(new_height * aspect_ratio)
|
108 |
+
|
109 |
+
resized_image = image.resize((new_width, new_height))
|
110 |
+
return resized_image
|
111 |
+
|
112 |
+
|
113 |
+
def center_crop_image(image, max_aspect_ratio=1.5):
|
114 |
+
width, height = image.size
|
115 |
+
aspect_ratio = max(width, height) / min(width, height)
|
116 |
+
|
117 |
+
if aspect_ratio >= max_aspect_ratio:
|
118 |
+
if width > height:
|
119 |
+
new_width = int(height * max_aspect_ratio)
|
120 |
+
left = (width - new_width) // 2
|
121 |
+
right = (width + new_width) // 2
|
122 |
+
top = 0
|
123 |
+
bottom = height
|
124 |
+
else:
|
125 |
+
new_height = int(width * max_aspect_ratio)
|
126 |
+
left = 0
|
127 |
+
right = width
|
128 |
+
top = (height - new_height) // 2
|
129 |
+
bottom = (height + new_height) // 2
|
130 |
+
|
131 |
+
cropped_image = image.crop((left, top, right, bottom))
|
132 |
+
return cropped_image
|
133 |
+
else:
|
134 |
+
return image
|
135 |
+
|
136 |
+
|
137 |
+
def vote_last_response(state, vote_type, request: gr.Request):
|
138 |
+
with open(get_conv_log_filename(), "a") as fout:
|
139 |
+
data = {
|
140 |
+
"tstamp": round(time.time(), 4),
|
141 |
+
"type": vote_type,
|
142 |
+
"state": state.dict(),
|
143 |
+
"ip": request.client.host,
|
144 |
+
}
|
145 |
+
fout.write(json.dumps(data) + "\n")
|
146 |
+
|
147 |
+
|
148 |
+
def upvote_last_response(state, request: gr.Request):
|
149 |
+
logger.info(f"upvote. ip: {request.client.host}")
|
150 |
+
vote_last_response(state, "upvote", request)
|
151 |
+
return (disable_btn,) * 2
|
152 |
+
|
153 |
+
|
154 |
+
def downvote_last_response(state, request: gr.Request):
|
155 |
+
logger.info(f"downvote. ip: {request.client.host}")
|
156 |
+
vote_last_response(state, "downvote", request)
|
157 |
+
return (disable_btn,) * 2
|
158 |
+
|
159 |
+
|
160 |
+
def regenerate(dialog_state, request: gr.Request):
|
161 |
+
logger.info(f"regenerate. ip: {request.client.host}")
|
162 |
+
if dialog_state.messages[-1]['role'] == dialog_state.roles[1]:
|
163 |
+
dialog_state.messages.pop()
|
164 |
+
return (
|
165 |
+
dialog_state,
|
166 |
+
dialog_state.to_gradio_chatbot(),
|
167 |
+
) + (disable_btn,) * 4
|
168 |
+
|
169 |
+
|
170 |
+
def clear_history(request: gr.Request):
|
171 |
+
logger.info(f"clear_history. ip: {request.client.host}")
|
172 |
+
dialog_state = conv_seed_llama.copy()
|
173 |
+
input_state = init_input_state()
|
174 |
+
return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (disable_btn,) * 4
|
175 |
+
|
176 |
+
|
177 |
+
def init_input_state():
|
178 |
+
return {'images': [], 'text': ''}
|
179 |
+
|
180 |
+
|
181 |
+
def add_text(dialog_state, input_state, text, request: gr.Request):
|
182 |
+
logger.info(f"add_text. ip: {request.client.host}.")
|
183 |
+
# if len(input_state['text']) == 0:
|
184 |
+
if text is None or len(text) == 0:
|
185 |
+
# dialog_state.skip_next = True
|
186 |
+
return (dialog_state, input_state, "", dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
|
187 |
+
input_state['text'] += text
|
188 |
+
|
189 |
+
|
190 |
+
if len(dialog_state.messages) > 0 and dialog_state.messages[-1]['role'] == dialog_state.roles[0]:
|
191 |
+
dialog_state.messages[-1]['message'] = input_state
|
192 |
+
else:
|
193 |
+
dialog_state.messages.append({'role': dialog_state.roles[0], 'message': input_state})
|
194 |
+
print('add_text: ', dialog_state.to_gradio_chatbot())
|
195 |
+
|
196 |
+
return (dialog_state, input_state, "", dialog_state.to_gradio_chatbot()) + (disable_btn,) * 4
|
197 |
+
|
198 |
+
|
199 |
+
def is_blank(image):
|
200 |
+
image_array = np.array(image)
|
201 |
+
unique_colors = np.unique(image_array)
|
202 |
+
print('unique_colors', len(unique_colors))
|
203 |
+
return len(unique_colors) == 1
|
204 |
+
|
205 |
+
|
206 |
+
def add_image(dialog_state, input_state, image, request: gr.Request):
|
207 |
+
logger.info(f"add_image. ip: {request.client.host}.")
|
208 |
+
if image is None:
|
209 |
+
return (dialog_state, input_state, None, dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
|
210 |
+
|
211 |
+
image = image.convert('RGB')
|
212 |
+
|
213 |
+
print('image size:', image.size)
|
214 |
+
|
215 |
+
image = center_crop_image(image, max_aspect_ratio=10)
|
216 |
+
|
217 |
+
image_dir = get_conv_image_dir()
|
218 |
+
image_path = get_image_name(image=image, image_dir=image_dir)
|
219 |
+
if not os.path.exists(image_path):
|
220 |
+
image.save(image_path)
|
221 |
+
input_state['images'].append(image_path)
|
222 |
+
input_state['text'] += IMG_FLAG
|
223 |
+
|
224 |
+
if len(dialog_state.messages) > 0 and dialog_state.messages[-1]['role'] == dialog_state.roles[0]:
|
225 |
+
dialog_state.messages[-1]['message'] = input_state
|
226 |
+
else:
|
227 |
+
dialog_state.messages.append({'role': dialog_state.roles[0], 'message': input_state})
|
228 |
+
|
229 |
+
print('add_image:', dialog_state)
|
230 |
+
|
231 |
+
return (dialog_state, input_state, None, dialog_state.to_gradio_chatbot()) + (disable_btn,) * 4
|
232 |
+
|
233 |
+
|
234 |
+
def http_bot(dialog_state, input_state, max_new_tokens, max_turns, force_image_gen, force_bbox,
|
235 |
+
request: gr.Request):
|
236 |
+
logger.info(f"http_bot. ip: {request.client.host}")
|
237 |
+
print('input_state:', input_state)
|
238 |
+
|
239 |
+
if len(dialog_state.messages) == 0 or dialog_state.messages[-1]['role'] != dialog_state.roles[0] or len(
|
240 |
+
dialog_state.messages[-1]['message']['text'].strip(' ?.;!/')) == 0:
|
241 |
+
return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
|
242 |
+
|
243 |
+
if len(dialog_state.messages) > max_turns * 2:
|
244 |
+
output_state = init_input_state()
|
245 |
+
output_state['text'] = 'Error: History exceeds maximum rounds, please clear history and restart.'
|
246 |
+
dialog_state.messages.append({'role': dialog_state.roles[1], 'message': output_state})
|
247 |
+
input_state = init_input_state()
|
248 |
+
return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (disable_btn,) * 3 + (enable_btn,)
|
249 |
+
|
250 |
+
prompt = dialog_state.get_prompt()
|
251 |
+
payload = {
|
252 |
+
'text': prompt['text'],
|
253 |
+
'max_new_tokens': int(max_new_tokens),
|
254 |
+
'images': prompt['images'],
|
255 |
+
'force_boi': force_image_gen,
|
256 |
+
'force_bbox': force_bbox,
|
257 |
+
}
|
258 |
+
|
259 |
+
print(
|
260 |
+
'request: ', {
|
261 |
+
'text': prompt['text'],
|
262 |
+
'max_new_tokens': int(max_new_tokens),
|
263 |
+
})
|
264 |
+
print('request_address', args.request_address)
|
265 |
+
response = requests.request(method="POST", url=args.request_address, headers=headers, json=payload)
|
266 |
+
results = response.json()
|
267 |
+
print('response: ', {'text': results['text'], 'error_msg': results['error_msg']})
|
268 |
+
|
269 |
+
output_state = init_input_state()
|
270 |
+
image_dir = get_conv_image_dir()
|
271 |
+
output_state['text'] = results['text']
|
272 |
+
|
273 |
+
for image_base64 in results['images']:
|
274 |
+
if image_base64 == '':
|
275 |
+
image_path = ''
|
276 |
+
else:
|
277 |
+
image = decode_image(image_base64)
|
278 |
+
image = image.convert('RGB')
|
279 |
+
image_path = get_image_name(image=image, image_dir=image_dir)
|
280 |
+
if not os.path.exists(image_path):
|
281 |
+
image.save(image_path)
|
282 |
+
output_state['images'].append(image_path)
|
283 |
+
|
284 |
+
dialog_state.messages.append({'role': dialog_state.roles[1], 'message': output_state})
|
285 |
+
|
286 |
+
vote_last_response(dialog_state, 'common', request)
|
287 |
+
input_state = init_input_state()
|
288 |
+
chatbot = update_error_msg(dialog_state.to_gradio_chatbot(), results['error_msg'])
|
289 |
+
return (dialog_state, input_state, chatbot) + (enable_btn,) * 4
|
290 |
+
|
291 |
+
|
292 |
+
def update_error_msg(chatbot, error_msg):
|
293 |
+
if len(error_msg) > 0:
|
294 |
+
info = '\n-------------\nSome errors occurred during response, please clear history and restart.\n' + '\n'.join(
|
295 |
+
error_msg)
|
296 |
+
chatbot[-1][-1] = chatbot[-1][-1] + info
|
297 |
+
|
298 |
+
return chatbot
|
299 |
+
|
300 |
+
|
301 |
+
def load_demo(request: gr.Request):
|
302 |
+
logger.info(f"load_demo. ip: {request.client.host}")
|
303 |
+
dialog_state = conv_seed_llama.copy()
|
304 |
+
input_state = init_input_state()
|
305 |
+
return dialog_state, input_state
|
306 |
+
|
307 |
+
|
308 |
+
title = ("""
|
309 |
+
# SEED-X-I
|
310 |
+
[[Paper]](https://arxiv.org/abs/2404.14396) [[Code]](https://github.com/AILab-CVC/SEED-X)
|
311 |
+
|
312 |
+
Demo of a general instruction-tuned model SEED-X-I (17B) from the foundation model SEED-X.
|
313 |
+
|
314 |
+
SEED-X-I can follow multimodal instruction (including images with **dynamic resolutions**) and make responses with **images, texts and bounding boxes** in multi-turn conversation.
|
315 |
+
|
316 |
+
SEED-X-I **does not support image manipulation**. If you want to experience **SEED-X-Edit** for high-precision image editing, please refer to [[Inference Code]](https://github.com/AILab-CVC/SEED-X).
|
317 |
+
|
318 |
+
Due to insufficient GPU memory, when generating images, we need to offload the LLM to the CPU and move the de-tokenizer to the CPU, which will **result in a long processing time**. If you want to experience the normal model inference speed, you can run [[Inference Code]](https://github.com/AILab-CVC/SEED-X) locally.
|
319 |
+
|
320 |
+
|
321 |
+
## Tips:
|
322 |
+
* Check out the conversation examples (at the bottom) for inspiration.
|
323 |
+
|
324 |
+
* You can adjust "Max History Rounds" to try a conversation with up to five rounds. For more turns, you can download our checkpoints from GitHub and deploy them locally for inference.
|
325 |
+
|
326 |
+
* Our demo supports a mix of images and texts as input. You can freely upload an image or enter text, and then click on "Add Image/Text". You can repeat the former step multiple times, and click on "Submit" for model inference at last.
|
327 |
+
|
328 |
+
* You can click "Force Image Generation" to compel the model to produce images when necessary. For example, our model might struggle to generate images when there is an excessive amount of text-only context.
|
329 |
+
|
330 |
+
* You can click "Force Bounding Box" to compel the model to produce bounding box for object detection.
|
331 |
+
|
332 |
+
* SEED-X was trained with English-only data. It may process with other languages due to the inherent capabilities from LLaMA, but might not stable.
|
333 |
+
|
334 |
+
""")
|
335 |
+
|
336 |
+
css = """
|
337 |
+
img {
|
338 |
+
font-family: 'Helvetica';
|
339 |
+
font-weight: 300;
|
340 |
+
line-height: 2;
|
341 |
+
text-align: center;
|
342 |
+
|
343 |
+
width: auto;
|
344 |
+
height: auto;
|
345 |
+
display: block;
|
346 |
+
position: relative;
|
347 |
+
}
|
348 |
+
|
349 |
+
img:before {
|
350 |
+
content: " ";
|
351 |
+
display: block;
|
352 |
+
|
353 |
+
position: absolute;
|
354 |
+
top: -10px;
|
355 |
+
left: 0;
|
356 |
+
height: calc(100% + 10px);
|
357 |
+
width: 100%;
|
358 |
+
background-color: rgb(230, 230, 230);
|
359 |
+
border: 2px dotted rgb(200, 200, 200);
|
360 |
+
border-radius: 5px;
|
361 |
+
}
|
362 |
+
|
363 |
+
img:after {
|
364 |
+
content: " ";
|
365 |
+
display: block;
|
366 |
+
font-size: 16px;
|
367 |
+
font-style: normal;
|
368 |
+
font-family: FontAwesome;
|
369 |
+
color: rgb(100, 100, 100);
|
370 |
+
|
371 |
+
position: absolute;
|
372 |
+
top: 5px;
|
373 |
+
left: 0;
|
374 |
+
width: 100%;
|
375 |
+
text-align: center;
|
376 |
+
}
|
377 |
+
|
378 |
+
"""
|
379 |
+
|
380 |
+
if __name__ == '__main__':
|
381 |
+
|
382 |
+
examples_mix = [
|
383 |
+
['https://github.com/AILab-CVC/SEED-X/blob/main/demos/bank.png?raw=true', 'Can I conntect with an advisor on Sunday?'],
|
384 |
+
['https://github.com/AILab-CVC/SEED-X/blob/main/demos/ground.png?raw=true',
|
385 |
+
'Is there anything in the image that can protect me from catching the flu virus when I go out? Show me the location.'],
|
386 |
+
['https://github.com/AILab-CVC/SEED-X/blob/main/demos/arrow.jpg?raw=true', 'What is the object pointed by the red arrow?'],
|
387 |
+
['https://github.com/AILab-CVC/SEED-X/blob/main/demos/shanghai.png?raw=true', 'Where was this image taken? Explain your answer.'],
|
388 |
+
['https://github.com/AILab-CVC/SEED-X/blob/main/demos/GPT4.png?raw=true', 'How long does it take to make GPT-4 safer?'],
|
389 |
+
['https://github.com/AILab-CVC/SEED-X/blob/main/demos/twitter.png?raw=true',
|
390 |
+
'Please provide a comprehensive description of this image.'],
|
391 |
+
]
|
392 |
+
|
393 |
+
examples_text = [
|
394 |
+
['I want to build a two story cabin in the woods, with many commanding windows. Can you show me a picture?'],
|
395 |
+
['Use your imagination to design a concept image for Artificial General Intelligence (AGI). Show me an image.'],
|
396 |
+
[
|
397 |
+
'Can you design an illustration for “The Three-Body Problem” to depict a scene from the novel? Show me a picture.'],
|
398 |
+
[
|
399 |
+
'My four year old son loves toy trains. Can you design a fancy birthday cake for him? Please generate a picture.'],
|
400 |
+
[
|
401 |
+
'Generate an image of a portrait of young nordic girl, age 25, freckled skin, neck tatoo, blue eyes 35mm lens, photography, ultra details.'],
|
402 |
+
['Generate an impressionist painting of an astronaut in a jungle.']
|
403 |
+
]
|
404 |
+
with gr.Blocks(css=css) as demo:
|
405 |
+
gr.Markdown(title)
|
406 |
+
dialog_state = gr.State()
|
407 |
+
input_state = gr.State()
|
408 |
+
with gr.Row():
|
409 |
+
with gr.Column(scale=3):
|
410 |
+
with gr.Row():
|
411 |
+
image = gr.Image(type='pil', label='input_image')
|
412 |
+
with gr.Row():
|
413 |
+
text = gr.Textbox(lines=5,
|
414 |
+
show_label=False,
|
415 |
+
label='input_text',
|
416 |
+
elem_id='textbox',
|
417 |
+
placeholder="Enter text or add image, and press submit,").style(container=False)
|
418 |
+
with gr.Row():
|
419 |
+
add_image_btn = gr.Button("Add Image")
|
420 |
+
add_text_btn = gr.Button("Add Text")
|
421 |
+
|
422 |
+
submit_btn = gr.Button("Submit")
|
423 |
+
|
424 |
+
with gr.Row():
|
425 |
+
max_new_tokens = gr.Slider(minimum=64,
|
426 |
+
maximum=1024,
|
427 |
+
value=768,
|
428 |
+
step=64,
|
429 |
+
interactive=True,
|
430 |
+
label="Max Output Tokens")
|
431 |
+
max_turns = gr.Slider(minimum=1, maximum=9, value=3, step=1, interactive=True,
|
432 |
+
label="Max History Rounds")
|
433 |
+
force_img_gen = gr.Radio(choices=[True, False], value=False, label='Force Image Generation')
|
434 |
+
force_bbox = gr.Radio(choices=[True, False], value=False, label='Force Bounding Box')
|
435 |
+
|
436 |
+
with gr.Column(scale=7):
|
437 |
+
chatbot = gr.Chatbot(elem_id='chatbot', label="SEED-X-I").style(height=700)
|
438 |
+
with gr.Row():
|
439 |
+
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
|
440 |
+
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
|
441 |
+
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
|
442 |
+
clear_btn = gr.Button(value="🗑️ Clear history", interactive=False)
|
443 |
+
|
444 |
+
with gr.Row():
|
445 |
+
with gr.Column(scale=0.7):
|
446 |
+
gr.Examples(examples=examples_mix, label='Input examples', inputs=[image, text])
|
447 |
+
with gr.Column(scale=0.3):
|
448 |
+
gr.Examples(examples=examples_text, label='Input examples', inputs=[text])
|
449 |
+
|
450 |
+
# Register listeners
|
451 |
+
btn_list = [upvote_btn, downvote_btn, regenerate_btn, clear_btn]
|
452 |
+
upvote_btn.click(upvote_last_response, [dialog_state], [upvote_btn, downvote_btn])
|
453 |
+
downvote_btn.click(downvote_last_response, [dialog_state], [upvote_btn, downvote_btn])
|
454 |
+
|
455 |
+
regenerate_btn.click(regenerate, [dialog_state], [dialog_state, chatbot] + btn_list).then(
|
456 |
+
http_bot, [dialog_state, input_state, max_new_tokens, max_turns, force_img_gen, force_bbox],
|
457 |
+
[dialog_state, input_state, chatbot] + btn_list)
|
458 |
+
add_image_btn.click(add_image, [dialog_state, input_state, image],
|
459 |
+
[dialog_state, input_state, image, chatbot] + btn_list)
|
460 |
+
|
461 |
+
add_text_btn.click(add_text, [dialog_state, input_state, text],
|
462 |
+
[dialog_state, input_state, text, chatbot] + btn_list)
|
463 |
+
|
464 |
+
submit_btn.click(
|
465 |
+
add_image, [dialog_state, input_state, image], [dialog_state, input_state, image, chatbot] + btn_list).then(
|
466 |
+
add_text, [dialog_state, input_state, text],
|
467 |
+
[dialog_state, input_state, text, chatbot, upvote_btn, downvote_btn, regenerate_btn, clear_btn]).then(
|
468 |
+
http_bot,
|
469 |
+
[dialog_state, input_state, max_new_tokens, max_turns, force_img_gen, force_bbox],
|
470 |
+
[dialog_state, input_state, chatbot] + btn_list)
|
471 |
+
clear_btn.click(clear_history, None, [dialog_state, input_state, chatbot] + btn_list)
|
472 |
+
|
473 |
+
demo.load(load_demo, None, [dialog_state, input_state])
|
474 |
+
|
475 |
+
demo.launch(server_name=args.server_name, server_port=args.server_port, enable_queue=True)
|