Fucius commited on
Commit
5635f36
1 Parent(s): 9f39446

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +593 -12
app.py CHANGED
@@ -1,17 +1,598 @@
1
  import spaces
2
- from diffusers import DiffusionPipeline
3
- import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- pipe = DiffusionPipeline.from_pretrained("Fucius/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16")
7
- pipe.to('cuda')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- @spaces.GPU
10
- def generate(prompt):
11
- return pipe(prompt).images
12
 
13
- gr.Interface(
14
- fn=generate,
15
- inputs=gr.Text(),
16
- outputs=gr.Gallery(),
17
- ).launch()
 
1
  import spaces
2
+ import sys
3
+ import os
4
+
5
+
6
+ print(os.system(f"pwd"))
7
+
8
+
9
+ os.system(f"git clone https://github.com/Curt-Park/yolo-world-with-efficientvit-sam.git")
10
+ cwd0 = os.getcwd()
11
+ cwd1 = os.path.join(cwd0, "yolo-world-with-efficientvit-sam")
12
+ os.chdir(cwd1)
13
+ os.system("make setup")
14
+ os.system(f"cd /home/user/app")
15
+
16
+ sys.path.append('./')
17
  import gradio as gr
18
+ import random
19
+ import numpy as np
20
+ from gradio_demo.character_template import character_man, lorapath_man
21
+ from gradio_demo.character_template import character_woman, lorapath_woman
22
+ from gradio_demo.character_template import styles, lorapath_styles
23
+ import torch
24
+ import os
25
+ from typing import Tuple, List
26
+ import copy
27
+ import argparse
28
+ from diffusers.utils import load_image
29
+ import cv2
30
+ from PIL import Image, ImageOps
31
+ from transformers import DPTFeatureExtractor, DPTForDepthEstimation
32
+ from controlnet_aux import OpenposeDetector
33
+ from controlnet_aux.open_pose.body import Body
34
+
35
+ try:
36
+ from inference.models import YOLOWorld
37
+ from src.efficientvit.models.efficientvit.sam import EfficientViTSamPredictor
38
+ from src.efficientvit.sam_model_zoo import create_sam_model
39
+ import supervision as sv
40
+ except:
41
+ print("YoloWorld can not be load")
42
+
43
+ try:
44
+ from groundingdino.models import build_model
45
+ from groundingdino.util import box_ops
46
+ from groundingdino.util.slconfig import SLConfig
47
+ from groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
48
+ from groundingdino.util.inference import annotate, predict
49
+ from segment_anything import build_sam, SamPredictor
50
+ import groundingdino.datasets.transforms as T
51
+ except:
52
+ print("groundingdino can not be load")
53
+
54
+ from src.pipelines.lora_pipeline import LoraMultiConceptPipeline
55
+ from src.prompt_attention.p2p_attention import AttentionReplace
56
+ from diffusers import ControlNetModel, StableDiffusionXLPipeline
57
+ from src.pipelines.lora_pipeline import revise_regionally_controlnet_forward
58
+
59
+ from download import OMG_download
60
+
61
+ CHARACTER_MAN_NAMES = list(character_man.keys())
62
+ CHARACTER_WOMAN_NAMES = list(character_woman.keys())
63
+ STYLE_NAMES = list(styles.keys())
64
+ MAX_SEED = np.iinfo(np.int32).max
65
+
66
+ ### Description
67
+ title = r"""
68
+ <h1 align="center">OMG: Occlusion-friendly Personalized Multi-concept Generation In Diffusion Models</h1>
69
+ """
70
+
71
+ description = r"""
72
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/' target='_blank'><b>OMG: Occlusion-friendly Personalized Multi-concept Generation In Diffusion Models</b></a>.<br>
73
+ How to use:<br>
74
+ 1. Select two characters.
75
+ 2. Enter a text prompt as done in normal text-to-image models.
76
+ 3. Click the <b>Submit</b> button to start customizing.
77
+ 4. Enjoy the generated image😊!
78
+ """
79
+
80
+ article = r"""
81
+ ---
82
+ 📝 **Citation**
83
+ <br>
84
+ If our work is helpful for your research or applications, please cite us via:
85
+ ```bibtex
86
+ @article{,
87
+ title={OMG: Occlusion-friendly Personalized Multi-concept Generation In Diffusion Models},
88
+ author={},
89
+ journal={},
90
+ year={}
91
+ }
92
+ ```
93
+ """
94
+
95
+ tips = r"""
96
+ ### Usage tips of OMG
97
+ 1. Input text prompts to describe a man and a woman
98
+ """
99
+
100
+ css = '''
101
+ .gradio-container {width: 85% !important}
102
+ '''
103
+
104
+ def sample_image(pipe,
105
+ input_prompt,
106
+ input_neg_prompt=None,
107
+ generator=None,
108
+ concept_models=None,
109
+ num_inference_steps=50,
110
+ guidance_scale=7.5,
111
+ controller=None,
112
+ stage=None,
113
+ region_masks=None,
114
+ lora_list = None,
115
+ styleL=None,
116
+ **extra_kargs
117
+ ):
118
+
119
+ spatial_condition = extra_kargs.pop('spatial_condition')
120
+ if spatial_condition is not None:
121
+ spatial_condition_input = [spatial_condition] * len(input_prompt)
122
+ else:
123
+ spatial_condition_input = None
124
+
125
+ images = pipe(
126
+ prompt=input_prompt,
127
+ concept_models=concept_models,
128
+ negative_prompt=input_neg_prompt,
129
+ generator=generator,
130
+ guidance_scale=guidance_scale,
131
+ num_inference_steps=num_inference_steps,
132
+ cross_attention_kwargs={"scale": 0.8},
133
+ controller=controller,
134
+ stage=stage,
135
+ region_masks=region_masks,
136
+ lora_list=lora_list,
137
+ styleL=styleL,
138
+ image=spatial_condition_input,
139
+ **extra_kargs).images
140
+
141
+ return images
142
+
143
+ def load_image_yoloworld(image_source) -> Tuple[np.array, torch.Tensor]:
144
+ image = np.asarray(image_source)
145
+ return image
146
+
147
+ def load_image_dino(image_source) -> Tuple[np.array, torch.Tensor]:
148
+ transform = T.Compose(
149
+ [
150
+ T.RandomResize([800], max_size=1333),
151
+ T.ToTensor(),
152
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
153
+ ]
154
+ )
155
+ image = np.asarray(image_source)
156
+ image_transformed, _ = transform(image_source, None)
157
+ return image, image_transformed
158
+
159
+ def predict_mask(segmentmodel, sam, image, TEXT_PROMPT, segmentType, confidence = 0.2, threshold = 0.5):
160
+ if segmentType=='GroundingDINO':
161
+ image_source, image = load_image_dino(image)
162
+ boxes, logits, phrases = predict(
163
+ model=segmentmodel,
164
+ image=image,
165
+ caption=TEXT_PROMPT,
166
+ box_threshold=0.3,
167
+ text_threshold=0.25
168
+ )
169
+ sam.set_image(image_source)
170
+ H, W, _ = image_source.shape
171
+ boxes_xyxy = box_ops.box_cxcywh_to_xyxy(boxes) * torch.Tensor([W, H, W, H])
172
+
173
+ transformed_boxes = sam.transform.apply_boxes_torch(boxes_xyxy, image_source.shape[:2]).cuda()
174
+ masks, _, _ = sam.predict_torch(
175
+ point_coords=None,
176
+ point_labels=None,
177
+ boxes=transformed_boxes,
178
+ multimask_output=False,
179
+ )
180
+ masks=masks[0].squeeze(0)
181
+ else:
182
+ image_source = load_image_yoloworld(image)
183
+ segmentmodel.set_classes([TEXT_PROMPT])
184
+ results = segmentmodel.infer(image_source, confidence=confidence)
185
+ detections = sv.Detections.from_inference(results).with_nms(
186
+ class_agnostic=True, threshold=threshold
187
+ )
188
+ masks = None
189
+ if len(detections) != 0:
190
+ print(TEXT_PROMPT + " detected!")
191
+ sam.set_image(image_source, image_format="RGB")
192
+ masks, _, _ = sam.predict(box=detections.xyxy[0], multimask_output=False)
193
+ masks = torch.from_numpy(masks.squeeze())
194
+
195
+ return masks
196
+
197
+ def prepare_text(prompt, region_prompts):
198
+ '''
199
+ Args:
200
+ prompt_entity: [subject1]-*-[attribute1]-*-[Location1]|[subject2]-*-[attribute2]-*-[Location2]|[global text]
201
+ Returns:
202
+ full_prompt: subject1, attribute1 and subject2, attribute2, global text
203
+ context_prompt: subject1 and subject2, global text
204
+ entity_collection: [(subject1, attribute1), Location1]
205
+ '''
206
+ region_collection = []
207
+
208
+ regions = region_prompts.split('|')
209
+
210
+ for region in regions:
211
+ if region == '':
212
+ break
213
+ prompt_region, neg_prompt_region = region.split('-*-')
214
+ prompt_region = prompt_region.replace('[', '').replace(']', '')
215
+ neg_prompt_region = neg_prompt_region.replace('[', '').replace(']', '')
216
+
217
+ region_collection.append((prompt_region, neg_prompt_region))
218
+ return (prompt, region_collection)
219
+
220
+
221
+ def build_model_sd(pretrained_model, controlnet_path, device, prompts):
222
+ controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16).to(device)
223
+ pipe = LoraMultiConceptPipeline.from_pretrained(
224
+ pretrained_model, controlnet=controlnet, torch_dtype=torch.float16, variant="fp16").to(device)
225
+ controller = AttentionReplace(prompts, 50, cross_replace_steps={"default_": 1.}, self_replace_steps=0.4, tokenizer=pipe.tokenizer, device=device, dtype=torch.float16, width=1024//32, height=1024//32)
226
+ revise_regionally_controlnet_forward(pipe.unet, controller)
227
+ pipe_concept = StableDiffusionXLPipeline.from_pretrained(pretrained_model, torch_dtype=torch.float16,
228
+ variant="fp16").to(device)
229
+ return pipe, controller, pipe_concept
230
+
231
+ def build_model_lora(pipe_concept, lora_paths, style_path, condition, args, pipe):
232
+ pipe_list = []
233
+ if condition == "Human pose":
234
+ controlnet = ControlNetModel.from_pretrained(args.openpose_checkpoint, torch_dtype=torch.float16).to(device)
235
+ pipe.controlnet = controlnet
236
+ elif condition == "Canny Edge":
237
+ controlnet = ControlNetModel.from_pretrained(args.canny_checkpoint, torch_dtype=torch.float16, variant="fp16").to(device)
238
+ pipe.controlnet = controlnet
239
+ elif condition == "Depth":
240
+ controlnet = ControlNetModel.from_pretrained(args.depth_checkpoint, torch_dtype=torch.float16).to(device)
241
+ pipe.controlnet = controlnet
242
+
243
+ if style_path is not None and os.path.exists(style_path):
244
+ pipe_concept.load_lora_weights(style_path, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
245
+ pipe.load_lora_weights(style_path, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
246
+
247
+ for lora_path in lora_paths.split('|'):
248
+ adapter_name = lora_path.split('/')[-1].split('.')[0]
249
+ pipe_concept.load_lora_weights(lora_path, weight_name="pytorch_lora_weights.safetensors", adapter_name=adapter_name)
250
+ pipe_concept.enable_xformers_memory_efficient_attention()
251
+ pipe_list.append(adapter_name)
252
+ return pipe_list
253
+
254
+ def build_yolo_segment_model(sam_path, device):
255
+ yolo_world = YOLOWorld(model_id="yolo_world/l")
256
+ sam = EfficientViTSamPredictor(
257
+ create_sam_model(name="xl1", weight_url=sam_path).to(device).eval()
258
+ )
259
+ return yolo_world, sam
260
+
261
+ def load_model_hf(repo_id, filename, ckpt_config_filename, device='cpu'):
262
+ args = SLConfig.fromfile(ckpt_config_filename)
263
+ model = build_model(args)
264
+ args.device = device
265
+
266
+ checkpoint = torch.load(os.path.join(repo_id, filename), map_location='cpu')
267
+ log = model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)
268
+ print("Model loaded from {} \n => {}".format(filename, log))
269
+ _ = model.eval()
270
+ return model
271
+
272
+ def build_dino_segment_model(ckpt_repo_id, sam_checkpoint):
273
+ ckpt_filenmae = "groundingdino_swinb_cogcoor.pth"
274
+ ckpt_config_filename = os.path.join(ckpt_repo_id, "GroundingDINO_SwinB.cfg.py")
275
+ groundingdino_model = load_model_hf(ckpt_repo_id, ckpt_filenmae, ckpt_config_filename)
276
+ sam = build_sam(checkpoint=sam_checkpoint)
277
+ sam.cuda()
278
+ sam_predictor = SamPredictor(sam)
279
+ return groundingdino_model, sam_predictor
280
+
281
+ def resize_and_center_crop(image, output_size=(1024, 576)):
282
+ width, height = image.size
283
+ aspect_ratio = width / height
284
+ new_height = output_size[1]
285
+ new_width = int(aspect_ratio * new_height)
286
+
287
+ resized_image = image.resize((new_width, new_height), Image.LANCZOS)
288
+
289
+ if new_width < output_size[0] or new_height < output_size[1]:
290
+ padding_color = "gray"
291
+ resized_image = ImageOps.expand(resized_image,
292
+ ((output_size[0] - new_width) // 2,
293
+ (output_size[1] - new_height) // 2,
294
+ (output_size[0] - new_width + 1) // 2,
295
+ (output_size[1] - new_height + 1) // 2),
296
+ fill=padding_color)
297
+
298
+ left = (resized_image.width - output_size[0]) / 2
299
+ top = (resized_image.height - output_size[1]) / 2
300
+ right = (resized_image.width + output_size[0]) / 2
301
+ bottom = (resized_image.height + output_size[1]) / 2
302
+
303
+ cropped_image = resized_image.crop((left, top, right, bottom))
304
+
305
+ return cropped_image
306
+
307
+ def main(device, segment_type):
308
+ pipe, controller, pipe_concept = build_model_sd(args.pretrained_sdxl_model, args.openpose_checkpoint, device, prompts_tmp)
309
+
310
+ if segment_type == 'GroundingDINO':
311
+ detect_model, sam = build_dino_segment_model(args.dino_checkpoint, args.sam_checkpoint)
312
+ else:
313
+ detect_model, sam = build_yolo_segment_model(args.efficientViT_checkpoint, device)
314
+
315
+ resolution_list = ["1440*728",
316
+ "1344*768",
317
+ "1216*832",
318
+ "1152*896",
319
+ "1024*1024",
320
+ "896*1152",
321
+ "832*1216",
322
+ "768*1344",
323
+ "728*1440"]
324
+ ratio_list = [1440 / 728, 1344 / 768, 1216 / 832, 1152 / 896, 1024 / 1024, 896 / 1152, 832 / 1216, 768 / 1344,
325
+ 728 / 1440]
326
+ condition_list = ["None",
327
+ "Human pose",
328
+ "Canny Edge",
329
+ "Depth"]
330
+
331
+ depth_estimator = DPTForDepthEstimation.from_pretrained(args.dpt_checkpoint).to("cuda")
332
+ feature_extractor = DPTFeatureExtractor.from_pretrained(args.dpt_checkpoint)
333
+ body_model = Body(args.pose_detector_checkpoint)
334
+ openpose = OpenposeDetector(body_model)
335
+
336
+ def remove_tips():
337
+ return gr.update(visible=False)
338
+
339
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
340
+ if randomize_seed:
341
+ seed = random.randint(0, MAX_SEED)
342
+ return seed
343
+
344
+ def get_humanpose(img):
345
+ openpose_image = openpose(img)
346
+ return openpose_image
347
+
348
+ def get_cannyedge(image):
349
+ image = np.array(image)
350
+ image = cv2.Canny(image, 100, 200)
351
+ image = image[:, :, None]
352
+ image = np.concatenate([image, image, image], axis=2)
353
+ canny_image = Image.fromarray(image)
354
+ return canny_image
355
+
356
+ def get_depth(image):
357
+ image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
358
+ with torch.no_grad(), torch.autocast("cuda"):
359
+ depth_map = depth_estimator(image).predicted_depth
360
+
361
+ depth_map = torch.nn.functional.interpolate(
362
+ depth_map.unsqueeze(1),
363
+ size=(1024, 1024),
364
+ mode="bicubic",
365
+ align_corners=False,
366
+ )
367
+ depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
368
+ depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
369
+ depth_map = (depth_map - depth_min) / (depth_max - depth_min)
370
+ image = torch.cat([depth_map] * 3, dim=1)
371
+ image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
372
+ image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
373
+ return image
374
+
375
+ @spaces.GPU
376
+ def generate_image(prompt1, negative_prompt, man, woman, resolution, local_prompt1, local_prompt2, seed, condition, condition_img1, style):
377
+ try:
378
+ path1 = lorapath_man[man]
379
+ path2 = lorapath_woman[woman]
380
+ pipe_concept.unload_lora_weights()
381
+ pipe.unload_lora_weights()
382
+ pipe_list = build_model_lora(pipe_concept, path1 + "|" + path2, lorapath_styles[style], condition, args, pipe)
383
+
384
+ if lorapath_styles[style] is not None and os.path.exists(lorapath_styles[style]):
385
+ styleL = True
386
+ else:
387
+ styleL = False
388
+
389
+ input_list = [prompt1]
390
+ condition_list = [condition_img1]
391
+ output_list = []
392
+
393
+ width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
394
+
395
+ kwargs = {
396
+ 'height': height,
397
+ 'width': width,
398
+ }
399
+
400
+ for prompt, condition_img in zip(input_list, condition_list):
401
+ if prompt!='':
402
+ input_prompt = []
403
+ p = '{prompt}, 35mm photograph, film, professional, 4k, highly detailed.'
404
+ if styleL:
405
+ p = styles[style] + p
406
+ input_prompt.append([p.replace("{prompt}", prompt), p.replace("{prompt}", prompt)])
407
+ if styleL:
408
+ input_prompt.append([(styles[style] + local_prompt1, character_man.get(man)[1]),
409
+ (styles[style] + local_prompt2, character_woman.get(woman)[1])])
410
+ else:
411
+ input_prompt.append([(local_prompt1, character_man.get(man)[1]),
412
+ (local_prompt2, character_woman.get(woman)[1])])
413
+
414
+ if condition == 'Human pose' and condition_img is not None:
415
+ index = ratio_list.index(
416
+ min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
417
+ resolution = resolution_list[index]
418
+ width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
419
+ kwargs['height'] = height
420
+ kwargs['width'] = width
421
+ condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
422
+ spatial_condition = get_humanpose(condition_img)
423
+ elif condition == 'Canny Edge' and condition_img is not None:
424
+ index = ratio_list.index(
425
+ min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
426
+ resolution = resolution_list[index]
427
+ width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
428
+ kwargs['height'] = height
429
+ kwargs['width'] = width
430
+ condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
431
+ spatial_condition = get_cannyedge(condition_img)
432
+ elif condition == 'Depth' and condition_img is not None:
433
+ index = ratio_list.index(
434
+ min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
435
+ resolution = resolution_list[index]
436
+ width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
437
+ kwargs['height'] = height
438
+ kwargs['width'] = width
439
+ condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
440
+ spatial_condition = get_depth(condition_img)
441
+ else:
442
+ spatial_condition = None
443
+
444
+ kwargs['spatial_condition'] = spatial_condition
445
+ controller.reset()
446
+ image = sample_image(
447
+ pipe,
448
+ input_prompt=input_prompt,
449
+ concept_models=pipe_concept,
450
+ input_neg_prompt=[negative_prompt] * len(input_prompt),
451
+ generator=torch.Generator(device).manual_seed(seed),
452
+ controller=controller,
453
+ stage=1,
454
+ lora_list=pipe_list,
455
+ styleL=styleL,
456
+ **kwargs)
457
+
458
+ controller.reset()
459
+ if pipe.tokenizer("man")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
460
+ mask1 = predict_mask(detect_model, sam, image[0], 'man', args.segment_type, confidence=0.15,
461
+ threshold=0.5)
462
+ else:
463
+ mask1 = None
464
+
465
+ if pipe.tokenizer("woman")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
466
+ mask2 = predict_mask(detect_model, sam, image[0], 'woman', args.segment_type, confidence=0.15,
467
+ threshold=0.5)
468
+ else:
469
+ mask2 = None
470
+
471
+ if mask1 is None and mask2 is None:
472
+ output_list.append(image[1])
473
+ else:
474
+ image = sample_image(
475
+ pipe,
476
+ input_prompt=input_prompt,
477
+ concept_models=pipe_concept,
478
+ input_neg_prompt=[negative_prompt] * len(input_prompt),
479
+ generator=torch.Generator(device).manual_seed(seed),
480
+ controller=controller,
481
+ stage=2,
482
+ region_masks=[mask1, mask2],
483
+ lora_list=pipe_list,
484
+ styleL=styleL,
485
+ **kwargs)
486
+ output_list.append(image[1])
487
+ else:
488
+ output_list.append(None)
489
+ output_list.append(spatial_condition)
490
+ return output_list
491
+ except:
492
+ print("error")
493
+ return
494
+
495
+ def get_local_value_man(input):
496
+ return character_man[input][0]
497
+
498
+ def get_local_value_woman(input):
499
+ return character_woman[input][0]
500
+
501
+
502
+ with gr.Blocks(css=css) as demo:
503
+ # description
504
+ gr.Markdown(title)
505
+ gr.Markdown(description)
506
+
507
+ with gr.Row():
508
+ gallery = gr.Image(label="Generated Images", height=512, width=512)
509
+ gen_condition = gr.Image(label="Spatial Condition", height=512, width=512)
510
+ usage_tips = gr.Markdown(label="Usage tips of OMG", value=tips, visible=False)
511
+
512
+ with gr.Row():
513
+ condition_img1 = gr.Image(label="Input an RGB image for condition", height=128, width=128)
514
+
515
+ # character choose
516
+ with gr.Row():
517
+ man = gr.Dropdown(label="Character 1 selection", choices=CHARACTER_MAN_NAMES, value="Chris Evans (identifier: Chris Evans)")
518
+ woman = gr.Dropdown(label="Character 2 selection", choices=CHARACTER_WOMAN_NAMES, value="Taylor Swift (identifier: TaylorSwift)")
519
+ resolution = gr.Dropdown(label="Image Resolution (width*height)", choices=resolution_list, value="1024*1024")
520
+ condition = gr.Dropdown(label="Input condition type", choices=condition_list, value="None")
521
+ style = gr.Dropdown(label="style", choices=STYLE_NAMES, value="None")
522
+
523
+ with gr.Row():
524
+ local_prompt1 = gr.Textbox(label="Character1_prompt",
525
+ info="Describe the Character 1, this prompt should include the identifier of character 1",
526
+ value="Close-up photo of the Chris Evans, 35mm photograph, film, professional, 4k, highly detailed.")
527
+ local_prompt2 = gr.Textbox(label="Character2_prompt",
528
+ info="Describe the Character 2, this prompt should include the identifier of character2",
529
+ value="Close-up photo of the TaylorSwift, 35mm photograph, film, professional, 4k, highly detailed.")
530
+
531
+ man.change(get_local_value_man, man, local_prompt1)
532
+ woman.change(get_local_value_woman, woman, local_prompt2)
533
+
534
+ # prompt
535
+ with gr.Column():
536
+ prompt = gr.Textbox(label="Prompt 1",
537
+ info="Give a simple prompt to describe the first image content",
538
+ placeholder="Required",
539
+ value="close-up shot, photography, a man and a woman on the street, facing the camera smiling")
540
+
541
+
542
+ with gr.Accordion(open=False, label="Advanced Options"):
543
+ seed = gr.Slider(
544
+ label="Seed",
545
+ minimum=0,
546
+ maximum=MAX_SEED,
547
+ step=1,
548
+ value=42,
549
+ )
550
+ negative_prompt = gr.Textbox(label="Negative Prompt",
551
+ placeholder="noisy, blurry, soft, deformed, ugly",
552
+ value="noisy, blurry, soft, deformed, ugly")
553
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
554
+
555
+ submit = gr.Button("Submit", variant="primary")
556
+
557
+ submit.click(
558
+ fn=remove_tips,
559
+ outputs=usage_tips,
560
+ ).then(
561
+ fn=randomize_seed_fn,
562
+ inputs=[seed, randomize_seed],
563
+ outputs=seed,
564
+ queue=False,
565
+ api_name=False,
566
+ ).then(
567
+ fn=generate_image,
568
+ inputs=[prompt, negative_prompt, man, woman, resolution, local_prompt1, local_prompt2, seed, condition, condition_img1, style],
569
+ outputs=[gallery, gen_condition]
570
+ )
571
+ demo.launch()
572
 
573
+ def parse_args():
574
+ parser = argparse.ArgumentParser('', add_help=False)
575
+ parser.add_argument('--pretrained_sdxl_model', default='Fucius/stable-diffusion-xl-base-1.0', type=str)
576
+ parser.add_argument('--openpose_checkpoint', default='thibaud/controlnet-openpose-sdxl-1.0', type=str)
577
+ parser.add_argument('--canny_checkpoint', default='diffusers/controlnet-canny-sdxl-1.0', type=str)
578
+ parser.add_argument('--depth_checkpoint', default='diffusers/controlnet-depth-sdxl-1.0', type=str)
579
+ parser.add_argument('--efficientViT_checkpoint', default='../checkpoint/sam/xl1.pt', type=str)
580
+ parser.add_argument('--dino_checkpoint', default='./checkpoint/GroundingDINO', type=str)
581
+ parser.add_argument('--sam_checkpoint', default='./checkpoint/sam/sam_vit_h_4b8939.pth', type=str)
582
+ parser.add_argument('--dpt_checkpoint', default='Intel/dpt-hybrid-midas', type=str)
583
+ parser.add_argument('--pose_detector_checkpoint', default='../checkpoint/ControlNet/annotator/ckpts/body_pose_model.pth', type=str)
584
+ parser.add_argument('--prompt', default='Close-up photo of the cool man and beautiful woman in surprised expressions as they accidentally discover a mysterious island while on vacation by the sea, 35mm photograph, film, professional, 4k, highly detailed.', type=str)
585
+ parser.add_argument('--negative_prompt', default='noisy, blurry, soft, deformed, ugly', type=str)
586
+ parser.add_argument('--seed', default=22, type=int)
587
+ parser.add_argument('--suffix', default='', type=str)
588
+ parser.add_argument('--segment_type', default='yoloworld', help='GroundingDINO or yoloworld', type=str)
589
+ return parser.parse_args()
590
 
591
+ if __name__ == '__main__':
592
+ args = parse_args()
 
593
 
594
+ prompts = [args.prompt]*2
595
+ prompts_tmp = copy.deepcopy(prompts)
596
+ device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
597
+ download = OMG_download()
598
+ main(device, args.segment_type)