tttoaster commited on
Commit
ac31431
1 Parent(s): 307cb32

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +778 -0
app.py ADDED
@@ -0,0 +1,778 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import datetime
4
+ import json
5
+ from typing import Optional
6
+ import transformers
7
+ from dataclasses 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
+
15
+ from utils import build_logger
16
+ from conversation import conv_seed_llama2
17
+
18
+ import hydra
19
+ import pyrootutils
20
+ import torch
21
+ import re
22
+ import time
23
+ from omegaconf import OmegaConf
24
+ from flask import Flask
25
+ import json
26
+ from typing import Optional
27
+ import cv2
28
+ from diffusers import AutoencoderKL, UNet2DConditionModel, EulerDiscreteScheduler
29
+
30
+ pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
31
+
32
+ from src.data.any_res import process_anyres_image
33
+
34
+ BOI_TOKEN = '<img>'
35
+ BOP_TOKEN = '<patch>'
36
+ EOI_TOKEN = '</img>'
37
+ EOP_TOKEN = '</patch>'
38
+ IMG_TOKEN = '<img_{:05d}>'
39
+
40
+ IMG_FLAG = '<image>'
41
+ num_img_in_tokens = 64
42
+ num_img_out_tokens = 64
43
+
44
+ resolution_grids = ['1x1', '1x2', '1x3', '1x4', '1x5', '1x6', '1x10', '2x1', '3x1', '4x1', '5x1', '6x1', '10x1', '2x2', '2x3', '3x2', '2x4', '4x2']
45
+ base_resolution = 448
46
+
47
+ app = Flask(__name__)
48
+
49
+
50
+ def decode_image(encoded_image: str) -> Image:
51
+ decoded_bytes = base64.b64decode(encoded_image.encode('utf-8'))
52
+ buffer = io.BytesIO(decoded_bytes)
53
+ image = Image.open(buffer)
54
+ return image
55
+
56
+
57
+ def encode_image(image: Image.Image, format: str = 'PNG') -> str:
58
+ with io.BytesIO() as buffer:
59
+ image.save(buffer, format=format)
60
+ encoded_image = base64.b64encode(buffer.getvalue()).decode('utf-8')
61
+ return encoded_image
62
+
63
+
64
+ @dataclass
65
+ class Arguments:
66
+ image_transform: Optional[str] = field(default='configs/processer/qwen_448_transform.yaml', metadata={"help": "config path of image transform"})
67
+ tokenizer: Optional[str] = field(default='configs/tokenizer/clm_llama_tokenizer_224loc_anyres.yaml', metadata={"help": "config path of tokenizer used to initialize tokenizer"})
68
+ llm: Optional[str] = field(default='configs/clm_models/llm_seed_x_i.yaml', metadata={"help": "config path of llm"})
69
+ visual_encoder: Optional[str] = field(default='configs/visual_encoder/qwen_vitg_448.yaml', metadata={"help": "config path of visual encoder"})
70
+ sd_adapter: Optional[str] = field(default='configs/sdxl_adapter/sdxl_qwen_vit_resampler_l4_q64_pretrain_no_normalize.yaml', metadata={"help": "config path of sd adapter"})
71
+ agent: Optional[str] = field(default='configs/clm_models/agent_seed_x_i.yaml', metadata={"help": "config path of agent model"})
72
+ diffusion_path: Optional[str] = field(default='stabilityai/stable-diffusion-xl-base-1.0', metadata={"help": "diffusion model path"})
73
+ has_bbox: Optional[bool] = field(default=True, metadata={"help": "visualize the box"})
74
+
75
+ port: Optional[str] = field(default=80, metadata={"help": "network port"})
76
+ llm_device: Optional[str] = field(default='cuda:0', metadata={"help": "llm device"})
77
+ vit_sd_device: Optional[str] = field(default='cuda:0', metadata={"help": "sd and vit device"})
78
+ dtype: Optional[str] = field(default='fp16', metadata={"help": "mix percision"})
79
+ multi_resolution: Optional[bool] = field(default=True, metadata={"help": "multi resolution"})
80
+
81
+
82
+ parser = transformers.HfArgumentParser(Arguments)
83
+ args, = parser.parse_args_into_dataclasses()
84
+
85
+ def extract_box(output_str):
86
+ boxes = re.findall('(.*?)<box_end>', output_str)
87
+ if len(boxes) >0:
88
+ bboxes = [[int(num) for num in re.findall('<loc-(\d+)>', box)] for box in boxes]
89
+ else:
90
+ bboxes = None
91
+
92
+ return bboxes
93
+
94
+
95
+ def visualize_bbox(image, bboxes):
96
+ img_width, img_height = image.size
97
+ image = np.array(image)
98
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
99
+ for bbox in bboxes:
100
+ x_center, y_center, box_width, box_height = bbox
101
+
102
+ x_center = x_center / 224 * img_width
103
+ y_center = y_center / 224 * img_height
104
+
105
+ box_width = box_width /224 * img_width
106
+ box_height = box_height / 224 * img_height
107
+
108
+ x1 = int(x_center - box_width / 2)
109
+ y1 = int(y_center - box_height / 2)
110
+ x2 = int(x_center + box_width / 2)
111
+ y2 = int(y_center + box_height / 2)
112
+
113
+ cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 4)
114
+
115
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
116
+ image = Image.fromarray(image)
117
+ return image
118
+
119
+
120
+ class LLMService:
121
+
122
+ def __init__(self, args) -> None:
123
+
124
+ self.llm_device = args.llm_device
125
+ self.vit_sd_device = args.vit_sd_device
126
+
127
+ dtype = args.dtype
128
+ if dtype == 'fp16':
129
+ self.dtype = torch.float16
130
+ elif dtype == 'bf16':
131
+ self.dtype = torch.bfloat16
132
+ else:
133
+ raise ValueError
134
+
135
+ image_transform_cfg = OmegaConf.load(args.image_transform)
136
+ self.image_transform = hydra.utils.instantiate(image_transform_cfg)
137
+
138
+ tokenizer_cfg = OmegaConf.load(args.tokenizer)
139
+ self.tokenizer = hydra.utils.instantiate(tokenizer_cfg)
140
+
141
+ visual_encoder_cfg = OmegaConf.load(args.visual_encoder)
142
+ self.visual_encoder = hydra.utils.instantiate(visual_encoder_cfg)
143
+ self.visual_encoder.eval().to(self.vit_sd_device, dtype=self.dtype)
144
+ print('Init visual encoder done')
145
+
146
+ llm_cfg = OmegaConf.load(args.llm)
147
+ llm = hydra.utils.instantiate(llm_cfg, torch_dtype=self.dtype)
148
+ print('Init llm done.')
149
+
150
+ agent_cfg = OmegaConf.load(args.agent)
151
+ self.agent = hydra.utils.instantiate(agent_cfg, llm=llm)
152
+
153
+ self.agent.eval().to(self.llm_device, dtype=self.dtype)
154
+ print('Init agent mdoel Done')
155
+
156
+ noise_scheduler = EulerDiscreteScheduler.from_pretrained(args.diffusion_path, subfolder="scheduler")
157
+
158
+ vae = AutoencoderKL.from_pretrained(args.diffusion_path, subfolder="vae").to(self.vit_sd_device, dtype=self.dtype)
159
+
160
+
161
+ unet = UNet2DConditionModel.from_pretrained(args.diffusion_path, subfolder="unet").to(dtype=self.dtype)
162
+
163
+ sd_adapter_cfg = OmegaConf.load(args.sd_adapter)
164
+
165
+ self.sd_adapter = hydra.utils.instantiate(sd_adapter_cfg, unet=unet).eval().to(dtype=self.dtype)
166
+
167
+ self.sd_adapter.init_pipe(vae=vae,
168
+ scheduler=noise_scheduler,
169
+ visual_encoder=self.visual_encoder.to("cpu"),
170
+ image_transform=self.image_transform,
171
+ discrete_model=None,
172
+ dtype=self.dtype,
173
+ device="cpu")
174
+
175
+ print('Init sd adapter pipe done.')
176
+
177
+ self.visual_encoder.to(self.vit_sd_device, dtype=self.dtype)
178
+
179
+ self.boi_token_id = self.tokenizer.encode(BOI_TOKEN, add_special_tokens=False)[0]
180
+ self.eoi_token_id = self.tokenizer.encode(EOI_TOKEN, add_special_tokens=False)[0]
181
+
182
+ self.bop_token_id = self.tokenizer.encode(BOP_TOKEN, add_special_tokens=False)[0]
183
+ self.eop_token_id = self.tokenizer.encode(EOP_TOKEN, add_special_tokens=False)[0]
184
+
185
+ self.multi_resolution = args.multi_resolution
186
+ if self.multi_resolution:
187
+ self.base_resolution = base_resolution
188
+ grid_pinpoints = []
189
+ for scale in resolution_grids:
190
+ s1, s2 = scale.split('x')
191
+ grid_pinpoints.append([int(s1)*base_resolution, int(s2)*base_resolution])
192
+ self.grid_pinpoints = grid_pinpoints
193
+
194
+ service = LLMService(args)
195
+
196
+
197
+ def generate(text_list, image_list, max_new_tokens, force_boi, force_bbox):
198
+ with torch.no_grad():
199
+ text_list = text_list.split(IMG_FLAG)
200
+ top_p = 0.5
201
+ assert len(text_list) == len(image_list) + 1
202
+
203
+ image_tokens = BOI_TOKEN + ''.join([IMG_TOKEN.format(int(item)) for item in range(num_img_in_tokens)]) + EOI_TOKEN
204
+
205
+ input_images = []
206
+ if len(image_list) > 0:
207
+ image_tensor_list = []
208
+ embeds_cmp_mask = []
209
+ embeds_gen_mask = []
210
+
211
+ if service.multi_resolution:
212
+ patch_pos = []
213
+ image_patch_length = []
214
+ image_size_list = []
215
+
216
+ for idx, image_item in enumerate(image_list):
217
+ if isinstance(image_item, str):
218
+ image = decode_image(image_item)
219
+ print('after decode image size:', image.size)
220
+ input_images.append(image)
221
+
222
+ if service.multi_resolution:
223
+ image_size_list.append(image.size)
224
+ print('image size:', image.size)
225
+ image_tensor, patch_pos_tensor = process_anyres_image(image, service.image_transform, service.grid_pinpoints, service.base_resolution)
226
+ image_tensor_list.append(image_tensor)
227
+ patch_pos.append(patch_pos_tensor)
228
+ image_patch_length.append(image_tensor.shape[0])
229
+ print('image_patch_length', image_patch_length)
230
+ embeds_cmp_mask.extend([True]*image_tensor.shape[0])
231
+ embeds_gen_mask.extend([False]*image_tensor.shape[0])
232
+
233
+ else:
234
+ image_tensor = service.image_transform(image)
235
+ image_tensor_list.append(image_tensor)
236
+ embeds_cmp_mask.append(True)
237
+ embeds_gen_mask.append(False)
238
+ else:
239
+ raise ValueError
240
+
241
+ if service.multi_resolution:
242
+ pixel_values = torch.cat(image_tensor_list).to(service.vit_sd_device, dtype=service.dtype)
243
+ patch_position = torch.cat(patch_pos, dim=0)
244
+
245
+ image_tokens_list = []
246
+ for patch_length in image_patch_length:
247
+ image_tokens = ''
248
+ for _ in range(patch_length-1):
249
+ image_tokens += BOP_TOKEN + ''.join(IMG_TOKEN.format(int(item)) for item in range(num_img_in_tokens)) + EOP_TOKEN
250
+ image_tokens += BOI_TOKEN + ''.join(IMG_TOKEN.format(int(item)) for item in range(num_img_in_tokens)) + EOI_TOKEN
251
+ image_tokens_list.append(image_tokens)
252
+ else:
253
+ pixel_values = torch.stack(image_tensor_list).to(service.vit_sd_device, dtype=service.dtype)
254
+
255
+ image_embeds = service.visual_encoder(pixel_values)
256
+ image_embeds = image_embeds.to(service.llm_device)
257
+
258
+ embeds_cmp_mask = torch.tensor(embeds_cmp_mask, dtype=torch.bool).to(service.llm_device)
259
+ embeds_gen_mask = torch.tensor(embeds_gen_mask, dtype=torch.bool).to(service.llm_device)
260
+
261
+ else:
262
+ image_embeds = None
263
+ patch_position = 0
264
+ embeds_cmp_mask = None
265
+ embeds_gen_mask = None
266
+
267
+ if service.multi_resolution:
268
+ input_text = ''
269
+ for i, c in enumerate(text_list[:-1]):
270
+ input_text += c + image_tokens_list[i]
271
+ input_text += text_list[-1]
272
+
273
+ else:
274
+ input_text = image_tokens.join(text_list)
275
+
276
+ if force_boi:
277
+ input_text = input_text + BOI_TOKEN
278
+
279
+ if force_bbox:
280
+ input_text = input_text + '[[ <box_start>'
281
+ print('input_text:', input_text)
282
+ input_ids = service.tokenizer.encode(input_text, add_special_tokens=False)
283
+ input_ids = [service.tokenizer.bos_token_id] + input_ids
284
+
285
+ input_ids = torch.tensor(input_ids).to(service.llm_device, dtype=torch.long)
286
+ ids_cmp_mask = torch.zeros_like(input_ids, dtype=torch.bool).to(service.llm_device)
287
+ ids_gen_mask = torch.zeros_like(input_ids, dtype=torch.bool).to(service.llm_device)
288
+
289
+ if service.multi_resolution:
290
+ boi_indices = torch.where(torch.logical_or(input_ids == service.boi_token_id, input_ids == service.bop_token_id))[0].tolist()
291
+ eoi_indices = torch.where(torch.logical_or(input_ids == service.eoi_token_id, input_ids == service.eop_token_id))[0].tolist()
292
+ else:
293
+ boi_indices = torch.where(input_ids == service.boi_token_id)[0].tolist()
294
+ eoi_indices = torch.where(input_ids == service.eoi_token_id)[0].tolist()
295
+
296
+ for boi_idx, eoi_idx in zip(boi_indices, eoi_indices):
297
+ ids_cmp_mask[boi_idx + 1:eoi_idx] = True
298
+
299
+ input_ids = input_ids.unsqueeze(0)
300
+ ids_cmp_mask = ids_cmp_mask.unsqueeze(0)
301
+ ids_gen_mask = ids_gen_mask.unsqueeze(0)
302
+
303
+ error_msg = []
304
+
305
+ if service.multi_resolution:
306
+ output = service.agent.generate(
307
+ tokenizer=service.tokenizer,
308
+ input_ids=input_ids,
309
+ image_embeds=image_embeds,
310
+ patch_positions=patch_position,
311
+ embeds_cmp_mask=embeds_cmp_mask,
312
+ ids_cmp_mask=ids_cmp_mask,
313
+ num_img_gen_tokens=num_img_out_tokens,
314
+ max_new_tokens=max_new_tokens,
315
+ dtype=service.dtype,
316
+ device=service.llm_device,
317
+ top_p=top_p,
318
+ )
319
+ else:
320
+ output = service.agent.generate(
321
+ tokenizer=service.tokenizer,
322
+ input_ids=input_ids,
323
+ image_embeds=image_embeds,
324
+ embeds_cmp_mask=embeds_cmp_mask,
325
+ ids_cmp_mask=ids_cmp_mask,
326
+ num_img_gen_tokens=num_img_out_tokens,
327
+ max_new_tokens=max_new_tokens,
328
+ dtype=service.dtype,
329
+ device=service.llm_device,
330
+ top_p=top_p,
331
+ )
332
+
333
+ gen_imgs_base64_list = []
334
+ generated_text = output['text']
335
+ generated_text = generated_text.replace(EOI_TOKEN, IMG_FLAG).replace(service.tokenizer.eos_token, '')
336
+
337
+ if output['has_img_output']:
338
+ print('loading visual encoder and llm to CPU, and sd to GPU')
339
+ a = time.time()
340
+ service.agent = service.agent.to("cpu")
341
+ service.sd_adapter = service.sd_adapter.to(service.vit_sd_device, dtype=service.dtype)
342
+ print("Loading finished: ", time.time() - a)
343
+
344
+ img_gen_feat = output['img_gen_feat'].to(service.vit_sd_device, dtype=service.dtype)
345
+
346
+ for img_idx in range(output['num_gen_imgs']):
347
+ img_feat = img_gen_feat[img_idx:img_idx + 1]
348
+ generated_image = service.sd_adapter.generate(image_embeds=img_feat, num_inference_steps=50)[0]
349
+ image_base64 = encode_image(generated_image)
350
+ gen_imgs_base64_list.append(image_base64)
351
+
352
+ print('loading visual encoder and llm to GPU, and sd to CPU')
353
+ a = time.time()
354
+ service.sd_adapter = service.sd_adapter.to("cpu")
355
+ service.visual_encoder = service.visual_encoder.to(service.vit_sd_device, dtype=service.dtype)
356
+ service.agent = service.agent.to(service.vit_sd_device, dtype=service.dtype)
357
+ print("Loading finished: ", time.time() - a)
358
+
359
+ if args.has_bbox:
360
+ bboxes = extract_box(generated_text)
361
+ if bboxes is not None and len(input_images) > 0:
362
+ image_viz = visualize_bbox(input_images[0], bboxes)
363
+ image_base64 = encode_image(image_viz)
364
+ gen_imgs_base64_list.append(image_base64)
365
+ generated_text = re.sub(r'\[\[ <box_start>.*?<box_end>.*?\]\]', 'the green bounding box', generated_text)
366
+ generated_text += IMG_FLAG
367
+ print(input_text + generated_text)
368
+ return {'text': generated_text, 'images': gen_imgs_base64_list, 'error_msg': error_msg}
369
+
370
+ def http_bot(dialog_state, input_state, max_new_tokens, max_turns, force_image_gen, force_bbox,
371
+ request: gr.Request):
372
+ print('input_state:', input_state)
373
+
374
+ if len(dialog_state.messages) == 0 or dialog_state.messages[-1]['role'] != dialog_state.roles[0] or len(
375
+ dialog_state.messages[-1]['message']['text'].strip(' ?.;!/')) == 0:
376
+ return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
377
+
378
+ if len(dialog_state.messages) > max_turns * 2:
379
+ output_state = init_input_state()
380
+ output_state['text'] = 'Error: History exceeds maximum rounds, please clear history and restart.'
381
+ dialog_state.messages.append({'role': dialog_state.roles[1], 'message': output_state})
382
+ input_state = init_input_state()
383
+ return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (disable_btn,) * 3 + (enable_btn,)
384
+
385
+ prompt = dialog_state.get_prompt()
386
+ text = prompt['text']
387
+ max_new_tokens = int(max_new_tokens)
388
+ images = prompt['images']
389
+ force_boi = force_image_gen
390
+ force_bbox = force_bbox
391
+
392
+ results = generate(text, images, max_new_tokens, force_boi, force_bbox)
393
+ print('response: ', {'text': results['text'], 'error_msg': results['error_msg']})
394
+
395
+ output_state = init_input_state()
396
+ image_dir = get_conv_image_dir()
397
+ output_state['text'] = results['text']
398
+
399
+ for image_base64 in results['images']:
400
+ if image_base64 == '':
401
+ image_path = ''
402
+ else:
403
+ image = decode_image(image_base64)
404
+ image = image.convert('RGB')
405
+ image_path = get_image_name(image=image, image_dir=image_dir)
406
+ if not os.path.exists(image_path):
407
+ image.save(image_path)
408
+ output_state['images'].append(image_path)
409
+
410
+ dialog_state.messages.append({'role': dialog_state.roles[1], 'message': output_state})
411
+
412
+ vote_last_response(dialog_state, 'common', request)
413
+ input_state = init_input_state()
414
+ chatbot = update_error_msg(dialog_state.to_gradio_chatbot(), results['error_msg'])
415
+ return (dialog_state, input_state, chatbot) + (enable_btn,) * 4
416
+
417
+
418
+ IMG_FLAG = '<image>'
419
+ LOGDIR = 'log'
420
+
421
+ logger = build_logger("gradio_seed_x", LOGDIR)
422
+ headers = {"User-Agent": "SEED-X Client"}
423
+
424
+ no_change_btn = gr.Button.update()
425
+ enable_btn = gr.Button.update(interactive=True)
426
+ disable_btn = gr.Button.update(interactive=False)
427
+
428
+ conv_seed_llama = conv_seed_llama2
429
+
430
+
431
+ def get_conv_log_filename():
432
+ t = datetime.datetime.now()
433
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
434
+ return name
435
+
436
+
437
+ def get_conv_image_dir():
438
+ name = os.path.join(LOGDIR, 'images')
439
+ os.makedirs(name, exist_ok=True)
440
+ return name
441
+
442
+
443
+ def get_image_name(image, image_dir=None):
444
+ buffer = io.BytesIO()
445
+ image.save(buffer, format='PNG')
446
+ image_bytes = buffer.getvalue()
447
+ md5 = hashlib.md5(image_bytes).hexdigest()
448
+
449
+ if image_dir is not None:
450
+ image_name = os.path.join(image_dir, md5 + '.png')
451
+ else:
452
+ image_name = md5 + '.png'
453
+
454
+ return image_name
455
+
456
+
457
+ def resize_image_square(image, target_size=448):
458
+ resized_image = image.resize((target_size, target_size))
459
+ return resized_image
460
+
461
+
462
+ def resize_image(image, max_size=512):
463
+ width, height = image.size
464
+ aspect_ratio = float(width) / float(height)
465
+
466
+ if width > height:
467
+ new_width = max_size
468
+ new_height = int(new_width / aspect_ratio)
469
+ else:
470
+ new_height = max_size
471
+ new_width = int(new_height * aspect_ratio)
472
+
473
+ resized_image = image.resize((new_width, new_height))
474
+ return resized_image
475
+
476
+
477
+ def center_crop_image(image, max_aspect_ratio=1.5):
478
+ width, height = image.size
479
+ aspect_ratio = max(width, height) / min(width, height)
480
+
481
+ if aspect_ratio >= max_aspect_ratio:
482
+ if width > height:
483
+ new_width = int(height * max_aspect_ratio)
484
+ left = (width - new_width) // 2
485
+ right = (width + new_width) // 2
486
+ top = 0
487
+ bottom = height
488
+ else:
489
+ new_height = int(width * max_aspect_ratio)
490
+ left = 0
491
+ right = width
492
+ top = (height - new_height) // 2
493
+ bottom = (height + new_height) // 2
494
+
495
+ cropped_image = image.crop((left, top, right, bottom))
496
+ return cropped_image
497
+ else:
498
+ return image
499
+
500
+
501
+ def vote_last_response(state, vote_type, request: gr.Request):
502
+ with open(get_conv_log_filename(), "a") as fout:
503
+ data = {
504
+ "tstamp": round(time.time(), 4),
505
+ "type": vote_type,
506
+ "state": state.dict(),
507
+ "ip": request.client.host,
508
+ }
509
+ fout.write(json.dumps(data) + "\n")
510
+
511
+
512
+ def upvote_last_response(state, request: gr.Request):
513
+ logger.info(f"upvote. ip: {request.client.host}")
514
+ vote_last_response(state, "upvote", request)
515
+ return (disable_btn,) * 2
516
+
517
+
518
+ def downvote_last_response(state, request: gr.Request):
519
+ logger.info(f"downvote. ip: {request.client.host}")
520
+ vote_last_response(state, "downvote", request)
521
+ return (disable_btn,) * 2
522
+
523
+
524
+ def regenerate(dialog_state, request: gr.Request):
525
+ logger.info(f"regenerate. ip: {request.client.host}")
526
+ if dialog_state.messages[-1]['role'] == dialog_state.roles[1]:
527
+ dialog_state.messages.pop()
528
+ return (
529
+ dialog_state,
530
+ dialog_state.to_gradio_chatbot(),
531
+ ) + (disable_btn,) * 4
532
+
533
+
534
+ def clear_history(request: gr.Request):
535
+ logger.info(f"clear_history. ip: {request.client.host}")
536
+ dialog_state = conv_seed_llama.copy()
537
+ input_state = init_input_state()
538
+ return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (disable_btn,) * 4
539
+
540
+
541
+ def init_input_state():
542
+ return {'images': [], 'text': ''}
543
+
544
+
545
+ def add_text(dialog_state, input_state, text, request: gr.Request):
546
+ logger.info(f"add_text. ip: {request.client.host}.")
547
+ if text is None or len(text) == 0:
548
+ return (dialog_state, input_state, "", dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
549
+ input_state['text'] += text
550
+
551
+
552
+ if len(dialog_state.messages) > 0 and dialog_state.messages[-1]['role'] == dialog_state.roles[0]:
553
+ dialog_state.messages[-1]['message'] = input_state
554
+ else:
555
+ dialog_state.messages.append({'role': dialog_state.roles[0], 'message': input_state})
556
+ print('add_text: ', dialog_state.to_gradio_chatbot())
557
+
558
+ return (dialog_state, input_state, "", dialog_state.to_gradio_chatbot()) + (disable_btn,) * 4
559
+
560
+
561
+ def is_blank(image):
562
+ image_array = np.array(image)
563
+ unique_colors = np.unique(image_array)
564
+ print('unique_colors', len(unique_colors))
565
+ return len(unique_colors) == 1
566
+
567
+
568
+ def add_image(dialog_state, input_state, image, request: gr.Request):
569
+ logger.info(f"add_image. ip: {request.client.host}.")
570
+ if image is None:
571
+ return (dialog_state, input_state, None, dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
572
+
573
+ image = image.convert('RGB')
574
+
575
+ print('image size:', image.size)
576
+
577
+ image = center_crop_image(image, max_aspect_ratio=10)
578
+
579
+ image_dir = get_conv_image_dir()
580
+ image_path = get_image_name(image=image, image_dir=image_dir)
581
+ if not os.path.exists(image_path):
582
+ image.save(image_path)
583
+ input_state['images'].append(image_path)
584
+ input_state['text'] += IMG_FLAG
585
+
586
+ if len(dialog_state.messages) > 0 and dialog_state.messages[-1]['role'] == dialog_state.roles[0]:
587
+ dialog_state.messages[-1]['message'] = input_state
588
+ else:
589
+ dialog_state.messages.append({'role': dialog_state.roles[0], 'message': input_state})
590
+
591
+ print('add_image:', dialog_state)
592
+
593
+ return (dialog_state, input_state, None, dialog_state.to_gradio_chatbot()) + (disable_btn,) * 4
594
+
595
+
596
+ def update_error_msg(chatbot, error_msg):
597
+ if len(error_msg) > 0:
598
+ info = '\n-------------\nSome errors occurred during response, please clear history and restart.\n' + '\n'.join(
599
+ error_msg)
600
+ chatbot[-1][-1] = chatbot[-1][-1] + info
601
+
602
+ return chatbot
603
+
604
+
605
+ def load_demo(request: gr.Request):
606
+ logger.info(f"load_demo. ip: {request.client.host}")
607
+ dialog_state = conv_seed_llama.copy()
608
+ input_state = init_input_state()
609
+ return dialog_state, input_state
610
+
611
+
612
+ title = ("""
613
+ # SEED-X-I
614
+ [[Paper]](https://arxiv.org/abs/2404.14396) [[Code]](https://github.com/AILab-CVC/SEED-X)
615
+
616
+ Demo of a general instruction-tuned model SEED-X-I (17B) from the foundation model SEED-X.
617
+
618
+ 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.
619
+
620
+ 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).
621
+
622
+ 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.
623
+
624
+
625
+ ## Tips:
626
+ * Check out the conversation examples (at the bottom) for inspiration.
627
+
628
+ * 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.
629
+
630
+ * 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.
631
+
632
+ * 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.
633
+
634
+ * You can click "Force Bounding Box" to compel the model to produce bounding box for object detection.
635
+
636
+ * 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.
637
+
638
+ """)
639
+
640
+ css = """
641
+ img {
642
+ font-family: 'Helvetica';
643
+ font-weight: 300;
644
+ line-height: 2;
645
+ text-align: center;
646
+
647
+ width: auto;
648
+ height: auto;
649
+ display: block;
650
+ position: relative;
651
+ }
652
+
653
+ img:before {
654
+ content: " ";
655
+ display: block;
656
+
657
+ position: absolute;
658
+ top: -10px;
659
+ left: 0;
660
+ height: calc(100% + 10px);
661
+ width: 100%;
662
+ background-color: rgb(230, 230, 230);
663
+ border: 2px dotted rgb(200, 200, 200);
664
+ border-radius: 5px;
665
+ }
666
+
667
+ img:after {
668
+ content: " ";
669
+ display: block;
670
+ font-size: 16px;
671
+ font-style: normal;
672
+ font-family: FontAwesome;
673
+ color: rgb(100, 100, 100);
674
+
675
+ position: absolute;
676
+ top: 5px;
677
+ left: 0;
678
+ width: 100%;
679
+ text-align: center;
680
+ }
681
+
682
+ """
683
+
684
+ if __name__ == '__main__':
685
+
686
+ examples_mix = [
687
+ ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/bank.png?raw=true', 'Can I conntect with an advisor on Sunday?'],
688
+ ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/ground.png?raw=true',
689
+ 'Is there anything in the image that can protect me from catching the flu virus when I go out? Show me the location.'],
690
+ ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/arrow.jpg?raw=true', 'What is the object pointed by the red arrow?'],
691
+ ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/shanghai.png?raw=true', 'Where was this image taken? Explain your answer.'],
692
+ ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/GPT4.png?raw=true', 'How long does it take to make GPT-4 safer?'],
693
+ ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/twitter.png?raw=true',
694
+ 'Please provide a comprehensive description of this image.'],
695
+ ]
696
+ examples_text = [
697
+ ['I want to build a two story cabin in the woods, with many commanding windows. Can you show me a picture?'],
698
+ ['Use your imagination to design a concept image for Artificial General Intelligence (AGI). Show me an image.'],
699
+ [
700
+ 'Can you design an illustration for “The Three-Body Problem” to depict a scene from the novel? Show me a picture.'],
701
+ [
702
+ 'My four year old son loves toy trains. Can you design a fancy birthday cake for him? Please generate a picture.'],
703
+ [
704
+ 'Generate an image of a portrait of young nordic girl, age 25, freckled skin, neck tatoo, blue eyes 35mm lens, photography, ultra details.'],
705
+ ['Generate an impressionist painting of an astronaut in a jungle.']
706
+ ]
707
+ with gr.Blocks(css=css) as demo:
708
+ gr.Markdown(title)
709
+ dialog_state = gr.State()
710
+ input_state = gr.State()
711
+ with gr.Row():
712
+ with gr.Column(scale=3):
713
+ with gr.Row():
714
+ image = gr.Image(type='pil', label='input_image')
715
+ with gr.Row():
716
+ text = gr.Textbox(lines=5,
717
+ show_label=False,
718
+ label='input_text',
719
+ elem_id='textbox',
720
+ placeholder="Enter text or add image, and press submit,").style(container=False)
721
+ with gr.Row():
722
+ add_image_btn = gr.Button("Add Image")
723
+ add_text_btn = gr.Button("Add Text")
724
+
725
+ submit_btn = gr.Button("Submit")
726
+
727
+ with gr.Row():
728
+ max_new_tokens = gr.Slider(minimum=64,
729
+ maximum=1024,
730
+ value=768,
731
+ step=64,
732
+ interactive=True,
733
+ label="Max Output Tokens")
734
+ max_turns = gr.Slider(minimum=1, maximum=9, value=3, step=1, interactive=True,
735
+ label="Max History Rounds")
736
+ force_img_gen = gr.Radio(choices=[True, False], value=False, label='Force Image Generation')
737
+ force_bbox = gr.Radio(choices=[True, False], value=False, label='Force Bounding Box')
738
+
739
+ with gr.Column(scale=7):
740
+ chatbot = gr.Chatbot(elem_id='chatbot', label="SEED-X-I").style(height=700)
741
+ with gr.Row():
742
+ upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
743
+ downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
744
+ regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
745
+ clear_btn = gr.Button(value="🗑️ Clear history", interactive=False)
746
+
747
+ with gr.Row():
748
+ with gr.Column(scale=0.7):
749
+ gr.Examples(examples=examples_mix, label='Input examples', inputs=[image, text])
750
+ with gr.Column(scale=0.3):
751
+ gr.Examples(examples=examples_text, label='Input examples', inputs=[text])
752
+
753
+ # Register listeners
754
+ btn_list = [upvote_btn, downvote_btn, regenerate_btn, clear_btn]
755
+ upvote_btn.click(upvote_last_response, [dialog_state], [upvote_btn, downvote_btn])
756
+ downvote_btn.click(downvote_last_response, [dialog_state], [upvote_btn, downvote_btn])
757
+
758
+ regenerate_btn.click(regenerate, [dialog_state], [dialog_state, chatbot] + btn_list).then(
759
+ http_bot, [dialog_state, input_state, max_new_tokens, max_turns, force_img_gen, force_bbox],
760
+ [dialog_state, input_state, chatbot] + btn_list)
761
+ add_image_btn.click(add_image, [dialog_state, input_state, image],
762
+ [dialog_state, input_state, image, chatbot] + btn_list)
763
+
764
+ add_text_btn.click(add_text, [dialog_state, input_state, text],
765
+ [dialog_state, input_state, text, chatbot] + btn_list)
766
+
767
+ submit_btn.click(
768
+ add_image, [dialog_state, input_state, image], [dialog_state, input_state, image, chatbot] + btn_list).then(
769
+ add_text, [dialog_state, input_state, text],
770
+ [dialog_state, input_state, text, chatbot, upvote_btn, downvote_btn, regenerate_btn, clear_btn]).then(
771
+ http_bot,
772
+ [dialog_state, input_state, max_new_tokens, max_turns, force_img_gen, force_bbox],
773
+ [dialog_state, input_state, chatbot] + btn_list)
774
+ clear_btn.click(clear_history, None, [dialog_state, input_state, chatbot] + btn_list)
775
+
776
+ demo.load(load_demo, None, [dialog_state, input_state])
777
+
778
+ demo.launch(server_name='0.0.0.0', server_port=80, enable_queue=True)