Fucius commited on
Commit
480c829
1 Parent(s): 6b4e58b

Delete gradio_demo/app_generateOne.py

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