Fucius commited on
Commit
e8b8b98
1 Parent(s): b4054cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +409 -247
app.py CHANGED
@@ -1,34 +1,28 @@
1
  import spaces
2
- import sys
3
- import os
4
-
5
-
6
-
7
- # os.system(f"git clone https://github.com/Curt-Park/yolo-world-with-efficientvit-sam.git")
8
- # cwd0 = os.getcwd()
9
- # cwd1 = os.path.join(cwd0, "yolo-world-with-efficientvit-sam")
10
- # os.chdir(cwd1)
11
- # os.system("make setup")
12
- # os.system(f"cd /home/user/app")
13
 
 
14
  sys.path.append('./')
15
- import gradio as gr
16
- import random
 
 
17
  import numpy as np
18
- from gradio_demo.character_template import character_man, lorapath_man
19
- from gradio_demo.character_template import character_woman, lorapath_woman
20
- from gradio_demo.character_template import styles, lorapath_styles
21
  import torch
22
- import os
23
  from typing import Tuple, List
 
 
 
24
  import copy
25
- import argparse
26
- from diffusers.utils import load_image
27
- import cv2
 
28
  from PIL import Image, ImageOps
29
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
30
- # from controlnet_aux import OpenposeDetector
31
- # from controlnet_aux.open_pose.body import Body
32
 
33
  try:
34
  from inference.models import YOLOWorld
@@ -49,25 +43,28 @@ try:
49
  except:
50
  print("groundingdino can not be load")
51
 
52
- from src.pipelines.lora_pipeline import LoraMultiConceptPipeline
 
53
  from src.prompt_attention.p2p_attention import AttentionReplace
54
- from diffusers import ControlNetModel, StableDiffusionXLPipeline
55
- from src.pipelines.lora_pipeline import revise_regionally_controlnet_forward
56
-
57
- from download import OMG_download
58
 
59
- CHARACTER_MAN_NAMES = list(character_man.keys())
60
- CHARACTER_WOMAN_NAMES = list(character_woman.keys())
61
  STYLE_NAMES = list(styles.keys())
 
 
 
62
  MAX_SEED = np.iinfo(np.int32).max
63
 
64
- ### Description
65
  title = r"""
66
- <h1 align="center">OMG: Occlusion-friendly Personalized Multi-concept Generation In Diffusion Models</h1>
67
  """
68
 
69
  description = r"""
70
- <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>
 
71
  How to use:<br>
72
  1. Select two characters.
73
  2. Enter a text prompt as done in normal text-to-image models.
@@ -99,26 +96,56 @@ css = '''
99
  .gradio-container {width: 85% !important}
100
  '''
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  def sample_image(pipe,
103
  input_prompt,
104
  input_neg_prompt=None,
105
  generator=None,
106
  concept_models=None,
107
  num_inference_steps=50,
108
- guidance_scale=7.5,
109
  controller=None,
 
 
110
  stage=None,
111
  region_masks=None,
112
- lora_list = None,
113
- styleL=None,
114
  **extra_kargs
115
  ):
116
 
117
- spatial_condition = extra_kargs.pop('spatial_condition')
118
- if spatial_condition is not None:
119
- spatial_condition_input = [spatial_condition] * len(input_prompt)
120
  else:
121
- spatial_condition_input = None
 
122
 
123
  images = pipe(
124
  prompt=input_prompt,
@@ -129,13 +156,12 @@ def sample_image(pipe,
129
  num_inference_steps=num_inference_steps,
130
  cross_attention_kwargs={"scale": 0.8},
131
  controller=controller,
 
 
132
  stage=stage,
 
133
  region_masks=region_masks,
134
- lora_list=lora_list,
135
- styleL=styleL,
136
- image=spatial_condition_input,
137
  **extra_kargs).images
138
-
139
  return images
140
 
141
  def load_image_yoloworld(image_source) -> Tuple[np.array, torch.Tensor]:
@@ -154,6 +180,37 @@ def load_image_dino(image_source) -> Tuple[np.array, torch.Tensor]:
154
  image_transformed, _ = transform(image_source, None)
155
  return image, image_transformed
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  def predict_mask(segmentmodel, sam, image, TEXT_PROMPT, segmentType, confidence = 0.2, threshold = 0.5):
158
  if segmentType=='GroundingDINO':
159
  image_source, image = load_image_dino(image)
@@ -192,6 +249,40 @@ def predict_mask(segmentmodel, sam, image, TEXT_PROMPT, segmentType, confidence
192
 
193
  return masks
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  def prepare_text(prompt, region_prompts):
196
  '''
197
  Args:
@@ -208,74 +299,28 @@ def prepare_text(prompt, region_prompts):
208
  for region in regions:
209
  if region == '':
210
  break
211
- prompt_region, neg_prompt_region = region.split('-*-')
212
  prompt_region = prompt_region.replace('[', '').replace(']', '')
213
  neg_prompt_region = neg_prompt_region.replace('[', '').replace(']', '')
214
 
215
- region_collection.append((prompt_region, neg_prompt_region))
216
  return (prompt, region_collection)
217
 
218
-
219
- def build_model_sd(pretrained_model, controlnet_path, device, prompts):
220
- controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16).to(device)
221
- pipe = LoraMultiConceptPipeline.from_pretrained(
222
- pretrained_model, controlnet=controlnet, torch_dtype=torch.float16, variant="fp16").to(device)
223
- 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)
224
- revise_regionally_controlnet_forward(pipe.unet, controller)
225
- pipe_concept = StableDiffusionXLPipeline.from_pretrained(pretrained_model, torch_dtype=torch.float16,
226
- variant="fp16").to(device)
227
- return pipe, controller, pipe_concept
228
-
229
- def build_model_lora(pipe_concept, lora_paths, style_path, condition, args, pipe):
230
- pipe_list = []
231
- if condition == "Human pose":
232
  controlnet = ControlNetModel.from_pretrained(args.openpose_checkpoint, torch_dtype=torch.float16).to(device)
233
- pipe.controlnet = controlnet
234
- elif condition == "Canny Edge":
235
  controlnet = ControlNetModel.from_pretrained(args.canny_checkpoint, torch_dtype=torch.float16, variant="fp16").to(device)
236
- pipe.controlnet = controlnet
237
- elif condition == "Depth":
238
  controlnet = ControlNetModel.from_pretrained(args.depth_checkpoint, torch_dtype=torch.float16).to(device)
239
- pipe.controlnet = controlnet
240
 
241
  if style_path is not None and os.path.exists(style_path):
242
  pipe_concept.load_lora_weights(style_path, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
243
  pipe.load_lora_weights(style_path, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
244
 
245
- for lora_path in lora_paths.split('|'):
246
- adapter_name = lora_path.split('/')[-1].split('.')[0]
247
- pipe_concept.load_lora_weights(lora_path, weight_name="pytorch_lora_weights.safetensors", adapter_name=adapter_name)
248
- pipe_concept.enable_xformers_memory_efficient_attention()
249
- pipe_list.append(adapter_name)
250
- return pipe_list
251
-
252
- def build_yolo_segment_model(sam_path, device):
253
- yolo_world = YOLOWorld(model_id="yolo_world/l")
254
- sam = EfficientViTSamPredictor(
255
- create_sam_model(name="xl1", weight_url=sam_path).to(device).eval()
256
- )
257
- return yolo_world, sam
258
-
259
- def load_model_hf(repo_id, filename, ckpt_config_filename, device='cpu'):
260
- args = SLConfig.fromfile(ckpt_config_filename)
261
- model = build_model(args)
262
- args.device = device
263
-
264
- checkpoint = torch.load(os.path.join(repo_id, filename), map_location='cpu')
265
- log = model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)
266
- print("Model loaded from {} \n => {}".format(filename, log))
267
- _ = model.eval()
268
- return model
269
-
270
- def build_dino_segment_model(ckpt_repo_id, sam_checkpoint):
271
- ckpt_filenmae = "groundingdino_swinb_cogcoor.pth"
272
- ckpt_config_filename = os.path.join(ckpt_repo_id, "GroundingDINO_SwinB.cfg.py")
273
- groundingdino_model = load_model_hf(ckpt_repo_id, ckpt_filenmae, ckpt_config_filename)
274
- sam = build_sam(checkpoint=sam_checkpoint)
275
- sam.cuda()
276
- sam_predictor = SamPredictor(sam)
277
- return groundingdino_model, sam_predictor
278
-
279
  def resize_and_center_crop(image, output_size=(1024, 576)):
280
  width, height = image.size
281
  aspect_ratio = width / height
@@ -303,12 +348,14 @@ def resize_and_center_crop(image, output_size=(1024, 576)):
303
  return cropped_image
304
 
305
  def main(device, segment_type):
306
- pipe, controller, pipe_concept = build_model_sd(args.pretrained_sdxl_model, args.openpose_checkpoint, device, prompts_tmp)
307
-
308
- # if segment_type == 'GroundingDINO':
309
- # detect_model, sam = build_dino_segment_model(args.dino_checkpoint, args.sam_checkpoint)
310
- # else:
311
- # detect_model, sam = build_yolo_segment_model(args.efficientViT_checkpoint, device)
 
 
312
 
313
  resolution_list = ["1440*728",
314
  "1344*768",
@@ -328,8 +375,12 @@ def main(device, segment_type):
328
 
329
  depth_estimator = DPTForDepthEstimation.from_pretrained(args.dpt_checkpoint).to("cuda")
330
  feature_extractor = DPTFeatureExtractor.from_pretrained(args.dpt_checkpoint)
331
- # body_model = Body(args.pose_detector_checkpoint)
332
- # openpose = OpenposeDetector(body_model)
 
 
 
 
333
 
334
  def remove_tips():
335
  return gr.update(visible=False)
@@ -371,167 +422,278 @@ def main(device, segment_type):
371
  return image
372
 
373
  @spaces.GPU
374
- def generate_image(prompt1, negative_prompt, man, woman, resolution, local_prompt1, local_prompt2, seed, condition, condition_img1, style):
375
- try:
376
- path1 = lorapath_man[man]
377
- path2 = lorapath_woman[woman]
378
- pipe_concept.unload_lora_weights()
379
- pipe.unload_lora_weights()
380
- pipe_list = build_model_lora(pipe_concept, path1 + "|" + path2, lorapath_styles[style], condition, args, pipe)
381
-
382
- if lorapath_styles[style] is not None and os.path.exists(lorapath_styles[style]):
383
- styleL = True
384
- else:
385
- styleL = False
386
-
387
- input_list = [prompt1]
388
- condition_list = [condition_img1]
389
- output_list = []
390
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
  width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
 
393
- kwargs = {
394
- 'height': height,
395
- 'width': width,
396
- }
397
-
398
- for prompt, condition_img in zip(input_list, condition_list):
399
- if prompt!='':
400
- input_prompt = []
401
- p = '{prompt}, 35mm photograph, film, professional, 4k, highly detailed.'
402
- if styleL:
403
- p = styles[style] + p
404
- input_prompt.append([p.replace("{prompt}", prompt), p.replace("{prompt}", prompt)])
405
- if styleL:
406
- input_prompt.append([(styles[style] + local_prompt1, character_man.get(man)[1]),
407
- (styles[style] + local_prompt2, character_woman.get(woman)[1])])
408
- else:
409
- input_prompt.append([(local_prompt1, character_man.get(man)[1]),
410
- (local_prompt2, character_woman.get(woman)[1])])
411
-
412
- if condition == 'Human pose' and condition_img is not None:
413
- index = ratio_list.index(
414
- min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
415
- resolution = resolution_list[index]
416
- width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
417
- kwargs['height'] = height
418
- kwargs['width'] = width
419
- condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
420
- spatial_condition = get_humanpose(condition_img)
421
- elif condition == 'Canny Edge' and condition_img is not None:
422
- index = ratio_list.index(
423
- min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
424
- resolution = resolution_list[index]
425
- width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
426
- kwargs['height'] = height
427
- kwargs['width'] = width
428
- condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
429
- spatial_condition = get_cannyedge(condition_img)
430
- elif condition == 'Depth' and condition_img is not None:
431
- index = ratio_list.index(
432
- min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
433
- resolution = resolution_list[index]
434
- width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
435
- kwargs['height'] = height
436
- kwargs['width'] = width
437
- condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
438
- spatial_condition = get_depth(condition_img)
439
- else:
440
- spatial_condition = None
441
-
442
- kwargs['spatial_condition'] = spatial_condition
443
- controller.reset()
444
  image = sample_image(
445
  pipe,
446
  input_prompt=input_prompt,
447
- concept_models=pipe_concept,
448
  input_neg_prompt=[negative_prompt] * len(input_prompt),
449
  generator=torch.Generator(device).manual_seed(seed),
450
  controller=controller,
451
- stage=1,
452
- lora_list=pipe_list,
453
- styleL=styleL,
 
 
 
454
  **kwargs)
455
 
456
- controller.reset()
457
- if pipe.tokenizer("man")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
458
- mask1 = predict_mask(detect_model, sam, image[0], 'man', args.segment_type, confidence=0.15,
459
- threshold=0.5)
460
- else:
461
- mask1 = None
462
-
463
- if pipe.tokenizer("woman")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
464
- mask2 = predict_mask(detect_model, sam, image[0], 'woman', args.segment_type, confidence=0.15,
465
- threshold=0.5)
466
- else:
467
- mask2 = None
468
-
469
- if mask1 is None and mask2 is None:
470
- output_list.append(image[1])
471
- else:
472
- image = sample_image(
473
- pipe,
474
- input_prompt=input_prompt,
475
- concept_models=pipe_concept,
476
- input_neg_prompt=[negative_prompt] * len(input_prompt),
477
- generator=torch.Generator(device).manual_seed(seed),
478
- controller=controller,
479
- stage=2,
480
- region_masks=[mask1, mask2],
481
- lora_list=pipe_list,
482
- styleL=styleL,
483
- **kwargs)
484
- output_list.append(image[1])
485
- else:
486
- output_list.append(None)
487
- output_list.append(spatial_condition)
488
- return output_list
489
- except:
490
- print("error")
491
- return
492
-
493
- def get_local_value_man(input):
494
- return character_man[input][0]
495
-
496
- def get_local_value_woman(input):
497
- return character_woman[input][0]
498
-
499
- @spaces.GPU
500
- def generate(prompt):
501
- print(os.system(prompt))
502
- return prompt
503
-
504
- gr.Interface(
505
- fn=generate,
506
- inputs=gr.Text(),
507
- outputs=gr.Gallery(),
508
- ).launch()
509
-
510
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
 
512
  def parse_args():
513
  parser = argparse.ArgumentParser('', add_help=False)
514
- parser.add_argument('--pretrained_sdxl_model', default='Fucius/stable-diffusion-xl-base-1.0', type=str)
515
- parser.add_argument('--openpose_checkpoint', default='thibaud/controlnet-openpose-sdxl-1.0', type=str)
516
- parser.add_argument('--canny_checkpoint', default='diffusers/controlnet-canny-sdxl-1.0', type=str)
517
- parser.add_argument('--depth_checkpoint', default='diffusers/controlnet-depth-sdxl-1.0', type=str)
518
- parser.add_argument('--efficientViT_checkpoint', default='../checkpoint/sam/xl1.pt', type=str)
519
- parser.add_argument('--dino_checkpoint', default='./checkpoint/GroundingDINO', type=str)
520
- parser.add_argument('--sam_checkpoint', default='./checkpoint/sam/sam_vit_h_4b8939.pth', type=str)
521
- parser.add_argument('--dpt_checkpoint', default='Intel/dpt-hybrid-midas', type=str)
522
- parser.add_argument('--pose_detector_checkpoint', default='../checkpoint/ControlNet/annotator/ckpts/body_pose_model.pth', type=str)
523
- 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)
 
 
 
 
 
524
  parser.add_argument('--negative_prompt', default='noisy, blurry, soft, deformed, ugly', type=str)
525
- parser.add_argument('--seed', default=22, type=int)
 
 
 
 
 
 
 
 
526
  parser.add_argument('--suffix', default='', type=str)
527
  parser.add_argument('--segment_type', default='yoloworld', help='GroundingDINO or yoloworld', type=str)
 
528
  return parser.parse_args()
529
 
530
  if __name__ == '__main__':
531
  args = parse_args()
532
 
533
- prompts = [args.prompt]*2
 
534
  prompts_tmp = copy.deepcopy(prompts)
 
 
 
 
 
 
 
535
  device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
536
- download = OMG_download()
537
- main(device, args.segment_type)
 
1
  import spaces
2
+ import torch
3
+ torch.jit.script = lambda f: f
 
 
 
 
 
 
 
 
 
4
 
5
+ import sys
6
  sys.path.append('./')
7
+ import argparse
8
+ import hashlib
9
+ import json
10
+ import os.path
11
  import numpy as np
 
 
 
12
  import torch
 
13
  from typing import Tuple, List
14
+ from diffusers import DPMSolverMultistepScheduler
15
+ from diffusers.models import T2IAdapter
16
+ from PIL import Image
17
  import copy
18
+ from diffusers import ControlNetModel, StableDiffusionXLPipeline
19
+ from insightface.app import FaceAnalysis
20
+ import gradio as gr
21
+ import random
22
  from PIL import Image, ImageOps
23
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
24
+ from controlnet_aux import OpenposeDetector
25
+ from controlnet_aux.open_pose.body import Body
26
 
27
  try:
28
  from inference.models import YOLOWorld
 
43
  except:
44
  print("groundingdino can not be load")
45
 
46
+ from src.pipelines.instantid_pipeline import InstantidMultiConceptPipeline
47
+ from src.pipelines.instantid_single_pieline import InstantidSingleConceptPipeline
48
  from src.prompt_attention.p2p_attention import AttentionReplace
49
+ from src.pipelines.instantid_pipeline import revise_regionally_controlnet_forward
50
+ import cv2
51
+ import math
52
+ import PIL.Image
53
 
54
+ from gradio_demo.character_template import styles, lorapath_styles
 
55
  STYLE_NAMES = list(styles.keys())
56
+
57
+
58
+
59
  MAX_SEED = np.iinfo(np.int32).max
60
 
 
61
  title = r"""
62
+ <h1 align="center">OMG: Occlusion-friendly Personalized Multi-concept Generation In Diffusion Models (OMG + InstantID)</h1>
63
  """
64
 
65
  description = r"""
66
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/kongzhecn/OMG/' target='_blank'><b>OMG: Occlusion-friendly Personalized Multi-concept Generation In Diffusion Models</b></a>.<be>.<br>
67
+ <a href='https://kongzhecn.github.io/omg-project/' target='_blank'><b>[Project]</b></a>.<a href='https://github.com/kongzhecn/OMG/' target='_blank'><b>[Code]</b></a>.<a href='https://arxiv.org/abs/2403.10983/' target='_blank'><b>[Arxiv]</b></a>.<br>
68
  How to use:<br>
69
  1. Select two characters.
70
  2. Enter a text prompt as done in normal text-to-image models.
 
96
  .gradio-container {width: 85% !important}
97
  '''
98
 
99
+
100
+
101
+ def build_dino_segment_model(ckpt_repo_id, sam_checkpoint):
102
+ ckpt_filenmae = "groundingdino_swinb_cogcoor.pth"
103
+ ckpt_config_filename = os.path.join(ckpt_repo_id, "GroundingDINO_SwinB.cfg.py")
104
+ groundingdino_model = load_model_hf(ckpt_repo_id, ckpt_filenmae, ckpt_config_filename)
105
+ sam = build_sam(checkpoint=sam_checkpoint)
106
+ sam.cuda()
107
+ sam_predictor = SamPredictor(sam)
108
+ return groundingdino_model, sam_predictor
109
+
110
+ def load_model_hf(repo_id, filename, ckpt_config_filename, device='cpu'):
111
+ args = SLConfig.fromfile(ckpt_config_filename)
112
+ model = build_model(args)
113
+ args.device = device
114
+
115
+ checkpoint = torch.load(os.path.join(repo_id, filename), map_location='cpu')
116
+ log = model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)
117
+ print("Model loaded from {} \n => {}".format(filename, log))
118
+ _ = model.eval()
119
+ return model
120
+
121
+ def build_yolo_segment_model(sam_path, device):
122
+ yolo_world = YOLOWorld(model_id="yolo_world/l")
123
+ sam = EfficientViTSamPredictor(
124
+ create_sam_model(name="xl1", weight_url=sam_path).to(device).eval()
125
+ )
126
+ return yolo_world, sam
127
+
128
  def sample_image(pipe,
129
  input_prompt,
130
  input_neg_prompt=None,
131
  generator=None,
132
  concept_models=None,
133
  num_inference_steps=50,
134
+ guidance_scale=3.0,
135
  controller=None,
136
+ face_app=None,
137
+ image=None,
138
  stage=None,
139
  region_masks=None,
140
+ controlnet_conditioning_scale=None,
 
141
  **extra_kargs
142
  ):
143
 
144
+ if image is not None:
145
+ image_condition = [image]
 
146
  else:
147
+ image_condition = None
148
+
149
 
150
  images = pipe(
151
  prompt=input_prompt,
 
156
  num_inference_steps=num_inference_steps,
157
  cross_attention_kwargs={"scale": 0.8},
158
  controller=controller,
159
+ image=image_condition,
160
+ face_app=face_app,
161
  stage=stage,
162
+ controlnet_conditioning_scale = controlnet_conditioning_scale,
163
  region_masks=region_masks,
 
 
 
164
  **extra_kargs).images
 
165
  return images
166
 
167
  def load_image_yoloworld(image_source) -> Tuple[np.array, torch.Tensor]:
 
180
  image_transformed, _ = transform(image_source, None)
181
  return image, image_transformed
182
 
183
+ def draw_kps_multi(image_pil, kps_list, color_list=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)]):
184
+ stickwidth = 4
185
+ limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
186
+
187
+
188
+ w, h = image_pil.size
189
+ out_img = np.zeros([h, w, 3])
190
+
191
+ for kps in kps_list:
192
+ kps = np.array(kps)
193
+ for i in range(len(limbSeq)):
194
+ index = limbSeq[i]
195
+ color = color_list[index[0]]
196
+
197
+ x = kps[index][:, 0]
198
+ y = kps[index][:, 1]
199
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
200
+ angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
201
+ polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0,
202
+ 360, 1)
203
+ out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
204
+ out_img = (out_img * 0.6).astype(np.uint8)
205
+
206
+ for idx_kp, kp in enumerate(kps):
207
+ color = color_list[idx_kp]
208
+ x, y = kp
209
+ out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
210
+
211
+ out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8))
212
+ return out_img_pil
213
+
214
  def predict_mask(segmentmodel, sam, image, TEXT_PROMPT, segmentType, confidence = 0.2, threshold = 0.5):
215
  if segmentType=='GroundingDINO':
216
  image_source, image = load_image_dino(image)
 
249
 
250
  return masks
251
 
252
+ def build_model_sd(pretrained_model, controlnet_path, face_adapter, device, prompts, antelopev2_path, width, height, style_lora):
253
+ controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
254
+ pipe = InstantidMultiConceptPipeline.from_pretrained(
255
+ pretrained_model, controlnet=controlnet, torch_dtype=torch.float16, variant="fp16").to(device)
256
+
257
+ controller = AttentionReplace(prompts, 50, cross_replace_steps={"default_": 1.},
258
+ self_replace_steps=0.4, tokenizer=pipe.tokenizer, device=device, width=width, height=height,
259
+ dtype=torch.float16)
260
+ revise_regionally_controlnet_forward(pipe.unet, controller)
261
+
262
+ controlnet_concept = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
263
+ pipe_concept = InstantidSingleConceptPipeline.from_pretrained(
264
+ pretrained_model,
265
+ controlnet=controlnet_concept,
266
+ torch_dtype=torch.float16
267
+ )
268
+ pipe_concept.load_ip_adapter_instantid(face_adapter)
269
+ pipe_concept.set_ip_adapter_scale(0.8)
270
+ pipe_concept.to(device)
271
+ pipe_concept.image_proj_model.to(pipe_concept._execution_device)
272
+
273
+ if style_lora is not None and os.path.exists(style_lora):
274
+ pipe.load_lora_weights(style_lora, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
275
+ pipe_concept.load_lora_weights(style_lora, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
276
+
277
+
278
+ # modify
279
+ app = FaceAnalysis(name='antelopev2', root=antelopev2_path,
280
+ providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
281
+ app.prepare(ctx_id=0, det_size=(640, 640))
282
+
283
+ return pipe, controller, pipe_concept, app
284
+
285
+
286
  def prepare_text(prompt, region_prompts):
287
  '''
288
  Args:
 
299
  for region in regions:
300
  if region == '':
301
  break
302
+ prompt_region, neg_prompt_region, ref_img = region.split('-*-')
303
  prompt_region = prompt_region.replace('[', '').replace(']', '')
304
  neg_prompt_region = neg_prompt_region.replace('[', '').replace(']', '')
305
 
306
+ region_collection.append((prompt_region, neg_prompt_region, ref_img))
307
  return (prompt, region_collection)
308
 
309
+ def build_model_lora(pipe, pipe_concept, style_path, condition, condition_img):
310
+ if condition == "Human pose" and condition_img is not None:
 
 
 
 
 
 
 
 
 
 
 
 
311
  controlnet = ControlNetModel.from_pretrained(args.openpose_checkpoint, torch_dtype=torch.float16).to(device)
312
+ pipe.controlnet2 = controlnet
313
+ elif condition == "Canny Edge" and condition_img is not None:
314
  controlnet = ControlNetModel.from_pretrained(args.canny_checkpoint, torch_dtype=torch.float16, variant="fp16").to(device)
315
+ pipe.controlnet2 = controlnet
316
+ elif condition == "Depth" and condition_img is not None:
317
  controlnet = ControlNetModel.from_pretrained(args.depth_checkpoint, torch_dtype=torch.float16).to(device)
318
+ pipe.controlnet2 = controlnet
319
 
320
  if style_path is not None and os.path.exists(style_path):
321
  pipe_concept.load_lora_weights(style_path, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
322
  pipe.load_lora_weights(style_path, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  def resize_and_center_crop(image, output_size=(1024, 576)):
325
  width, height = image.size
326
  aspect_ratio = width / height
 
348
  return cropped_image
349
 
350
  def main(device, segment_type):
351
+ pipe, controller, pipe_concepts, face_app = build_model_sd(args.pretrained_model, args.controlnet_path,
352
+ args.face_adapter_path, device, prompts_tmp,
353
+ args.antelopev2_path, width // 32, height // 32,
354
+ args.style_lora)
355
+ if segment_type == 'GroundingDINO':
356
+ detect_model, sam = build_dino_segment_model(args.dino_checkpoint, args.sam_checkpoint)
357
+ else:
358
+ detect_model, sam = build_yolo_segment_model(args.efficientViT_checkpoint, device)
359
 
360
  resolution_list = ["1440*728",
361
  "1344*768",
 
375
 
376
  depth_estimator = DPTForDepthEstimation.from_pretrained(args.dpt_checkpoint).to("cuda")
377
  feature_extractor = DPTFeatureExtractor.from_pretrained(args.dpt_checkpoint)
378
+ body_model = Body(args.pose_detector_checkpoint)
379
+ openpose = OpenposeDetector(body_model)
380
+
381
+ prompts_rewrite = [args.prompt_rewrite]
382
+ input_prompt_test = [prepare_text(p, p_w) for p, p_w in zip(prompts, prompts_rewrite)]
383
+ input_prompt_test = [prompts, input_prompt_test[0][1]]
384
 
385
  def remove_tips():
386
  return gr.update(visible=False)
 
422
  return image
423
 
424
  @spaces.GPU
425
+ def generate_image(prompt1, negative_prompt, reference_1, reference_2, resolution, local_prompt1, local_prompt2, seed, style, identitynet_strength_ratio, adapter_strength_ratio, condition, condition_img, controlnet_ratio, cfg_scale):
426
+ identitynet_strength_ratio = float(identitynet_strength_ratio)
427
+ adapter_strength_ratio = float(adapter_strength_ratio)
428
+ controlnet_ratio = float(controlnet_ratio)
429
+ cfg_scale = float(cfg_scale)
430
+
431
+ if lorapath_styles[style] is not None and os.path.exists(lorapath_styles[style]):
432
+ styleL = True
433
+ else:
434
+ styleL = False
435
+
436
+ width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
437
+ kwargs = {
438
+ 'height': height,
439
+ 'width': width,
440
+ 't2i_controlnet_conditioning_scale': controlnet_ratio,
441
+ }
442
+
443
+ if condition == 'Human pose' and condition_img is not None:
444
+ index = ratio_list.index(
445
+ min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
446
+ resolution = resolution_list[index]
447
+ width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
448
+ kwargs['height'] = height
449
+ kwargs['width'] = width
450
+ condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
451
+ spatial_condition = get_humanpose(condition_img)
452
+ elif condition == 'Canny Edge' and condition_img is not None:
453
+ index = ratio_list.index(
454
+ min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
455
+ resolution = resolution_list[index]
456
  width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
457
+ kwargs['height'] = height
458
+ kwargs['width'] = width
459
+ condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
460
+ spatial_condition = get_cannyedge(condition_img)
461
+ elif condition == 'Depth' and condition_img is not None:
462
+ index = ratio_list.index(
463
+ min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
464
+ resolution = resolution_list[index]
465
+ width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
466
+ kwargs['height'] = height
467
+ kwargs['width'] = width
468
+ condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
469
+ spatial_condition = get_depth(condition_img)
470
+ else:
471
+ spatial_condition = None
472
+
473
+ kwargs['t2i_image'] = spatial_condition
474
+ pipe.unload_lora_weights()
475
+ pipe_concepts.unload_lora_weights()
476
+ build_model_lora(pipe, pipe_concepts, lorapath_styles[style], condition, condition_img)
477
+ pipe_concepts.set_ip_adapter_scale(adapter_strength_ratio)
478
+
479
+ input_list = [prompt1]
480
+
481
+
482
+ for prompt in input_list:
483
+ if prompt != '':
484
+ input_prompt = []
485
+ p = '{prompt}, 35mm photograph, film, professional, 4k, highly detailed.'
486
+ if styleL:
487
+ p = styles[style] + p
488
+ input_prompt.append([p.replace('{prompt}', prompt), p.replace("{prompt}", prompt)])
489
+ if styleL:
490
+ input_prompt.append([(styles[style] + local_prompt1, 'noisy, blurry, soft, deformed, ugly',
491
+ PIL.Image.fromarray(reference_1)),
492
+ (styles[style] + local_prompt2, 'noisy, blurry, soft, deformed, ugly',
493
+ PIL.Image.fromarray(reference_2))])
494
+ else:
495
+ input_prompt.append(
496
+ [(local_prompt1, 'noisy, blurry, soft, deformed, ugly', PIL.Image.fromarray(reference_1)),
497
+ (local_prompt2, 'noisy, blurry, soft, deformed, ugly', PIL.Image.fromarray(reference_2))])
498
+
499
+
500
+ controller.reset()
501
+ image = sample_image(
502
+ pipe,
503
+ input_prompt=input_prompt,
504
+ concept_models=pipe_concepts,
505
+ input_neg_prompt=[negative_prompt] * len(input_prompt),
506
+ generator=torch.Generator(device).manual_seed(seed),
507
+ controller=controller,
508
+ face_app=face_app,
509
+ controlnet_conditioning_scale=identitynet_strength_ratio,
510
+ stage=1,
511
+ guidance_scale=cfg_scale,
512
+ **kwargs)
513
+
514
+ controller.reset()
515
+
516
+ if pipe.tokenizer("man")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
517
+ mask1 = predict_mask(detect_model, sam, image[0], 'man', args.segment_type, confidence=0.05,
518
+ threshold=0.5)
519
+ else:
520
+ mask1 = None
521
+
522
+ if pipe.tokenizer("woman")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
523
+ mask2 = predict_mask(detect_model, sam, image[0], 'woman', args.segment_type, confidence=0.05,
524
+ threshold=0.5)
525
+ else:
526
+ mask2 = None
527
+
528
+ if mask1 is not None or mask2 is not None:
529
+ face_info = face_app.get(cv2.cvtColor(np.array(image[0]), cv2.COLOR_RGB2BGR))
530
+ face_kps = draw_kps_multi(image[0], [face['kps'] for face in face_info])
531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  image = sample_image(
533
  pipe,
534
  input_prompt=input_prompt,
535
+ concept_models=pipe_concepts,
536
  input_neg_prompt=[negative_prompt] * len(input_prompt),
537
  generator=torch.Generator(device).manual_seed(seed),
538
  controller=controller,
539
+ face_app=face_app,
540
+ image=face_kps,
541
+ stage=2,
542
+ controlnet_conditioning_scale=identitynet_strength_ratio,
543
+ region_masks=[mask1, mask2],
544
+ guidance_scale=cfg_scale,
545
  **kwargs)
546
 
547
+ return [image[1], spatial_condition]
548
+ # return image
549
+
550
+ with gr.Blocks(css=css) as demo:
551
+ # description
552
+ gr.Markdown(title)
553
+ gr.Markdown(description)
554
+
555
+ with gr.Row():
556
+ gallery = gr.Image(label="Generated Images", height=512, width=512)
557
+ gallery1 = gr.Image(label="Input Condition", height=512, width=512)
558
+ usage_tips = gr.Markdown(label="Usage tips of OMG", value=tips, visible=False)
559
+
560
+
561
+ with gr.Row():
562
+ reference_1 = gr.Image(label="Input an RGB image for Character man", height=128, width=128)
563
+ reference_2 = gr.Image(label="Input an RGB image for Character woman", height=128, width=128)
564
+ condition_img1 = gr.Image(label="Input an RGB image for condition (Optional)", height=128, width=128)
565
+
566
+
567
+
568
+
569
+ with gr.Row():
570
+ local_prompt1 = gr.Textbox(label="Character1_prompt",
571
+ info="Describe the Character 1",
572
+ value="Close-up photo of the a man, 35mm photograph, professional, 4k, highly detailed.")
573
+ local_prompt2 = gr.Textbox(label="Character2_prompt",
574
+ info="Describe the Character 2",
575
+ value="Close-up photo of the a woman, 35mm photograph, professional, 4k, highly detailed.")
576
+ with gr.Row():
577
+ identitynet_strength_ratio = gr.Slider(
578
+ label="IdentityNet strength (for fidelity)",
579
+ minimum=0,
580
+ maximum=1.5,
581
+ step=0.05,
582
+ value=0.80,
583
+ )
584
+ adapter_strength_ratio = gr.Slider(
585
+ label="Image adapter strength (for detail)",
586
+ minimum=0,
587
+ maximum=1.5,
588
+ step=0.05,
589
+ value=0.80,
590
+ )
591
+ controlnet_ratio = gr.Slider(
592
+ label="ControlNet strength",
593
+ minimum=0,
594
+ maximum=1.5,
595
+ step=0.05,
596
+ value=1,
597
+ )
598
+
599
+ cfg_ratio = gr.Slider(
600
+ label="CFG scale ",
601
+ minimum=0.5,
602
+ maximum=10,
603
+ step=0.5,
604
+ value=3.0,
605
+ )
606
+
607
+ resolution = gr.Dropdown(label="Image Resolution (width*height)", choices=resolution_list,
608
+ value="1024*1024")
609
+ style = gr.Dropdown(label="style", choices=STYLE_NAMES, value="None")
610
+ condition = gr.Dropdown(label="Input condition type", choices=condition_list, value="None")
611
+
612
+
613
+ # prompt
614
+ with gr.Column():
615
+ prompt = gr.Textbox(label="Prompt 1",
616
+ info="Give a simple prompt to describe the first image content",
617
+ placeholder="Required",
618
+ value="close-up shot, photography, a man and a woman on the street, facing the camera smiling")
619
+
620
+
621
+ with gr.Accordion(open=False, label="Advanced Options"):
622
+ seed = gr.Slider(
623
+ label="Seed",
624
+ minimum=0,
625
+ maximum=MAX_SEED,
626
+ step=1,
627
+ value=42,
628
+ )
629
+ negative_prompt = gr.Textbox(label="Negative Prompt",
630
+ placeholder="noisy, blurry, soft, deformed, ugly",
631
+ value="noisy, blurry, soft, deformed, ugly")
632
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
633
+
634
+ submit = gr.Button("Submit", variant="primary")
635
+
636
+ submit.click(
637
+ fn=remove_tips,
638
+ outputs=usage_tips,
639
+ ).then(
640
+ fn=randomize_seed_fn,
641
+ inputs=[seed, randomize_seed],
642
+ outputs=seed,
643
+ queue=False,
644
+ api_name=False,
645
+ ).then(
646
+ fn=generate_image,
647
+ inputs=[prompt, negative_prompt, reference_1, reference_2, resolution, local_prompt1, local_prompt2, seed, style, identitynet_strength_ratio, adapter_strength_ratio, condition, condition_img1, controlnet_ratio, cfg_ratio],
648
+ outputs=[gallery, gallery1]
649
+ )
650
+ demo.launch(server_name='0.0.0.0',server_port=7861, debug=True)
651
 
652
  def parse_args():
653
  parser = argparse.ArgumentParser('', add_help=False)
654
+ parser.add_argument('--pretrained_model', default='/home/data1/kz_dir/checkpoint/YamerMIX_v8', type=str)
655
+ parser.add_argument('--controlnet_path', default='/home/user/app/checkpoint/InstantID/ControlNetModel', type=str)
656
+ parser.add_argument('--face_adapter_path', default='/home/user/app/checkpoint/InstantID/ip-adapter.bin', type=str)
657
+ parser.add_argument('--openpose_checkpoint', default='/home/user/app/checkpoint/controlnet-openpose-sdxl-1.0', type=str)
658
+ parser.add_argument('--canny_checkpoint', default='/home/user/app/checkpoint/controlnet-canny-sdxl-1.0', type=str)
659
+ parser.add_argument('--depth_checkpoint', default='/home/user/app/checkpoint/controlnet-depth-sdxl-1.0', type=str)
660
+ parser.add_argument('--dpt_checkpoint', default='/home/user/app/checkpoint/dpt-hybrid-midas', type=str)
661
+ parser.add_argument('--pose_detector_checkpoint',
662
+ default='../checkpoint/ControlNet/annotator/ckpts/body_pose_model.pth', type=str)
663
+ parser.add_argument('--efficientViT_checkpoint', default='/home/user/app/checkpoint/sam/xl1.pt', type=str)
664
+ parser.add_argument('--dino_checkpoint', default='/home/user/app/checkpoint/GroundingDINO', type=str)
665
+ parser.add_argument('--sam_checkpoint', default='/home/user/app/checkpoint/sam/sam_vit_h_4b8939.pth', type=str)
666
+ parser.add_argument('--antelopev2_path', default='/home/user/app/checkpoint/antelopev2', type=str)
667
+ parser.add_argument('--save_dir', default='results/instantID', type=str)
668
+ parser.add_argument('--prompt', default='Close-up photo of the cool man and beautiful woman as they accidentally discover a mysterious island while on vacation by the sea, facing the camera smiling, 35mm photograph, film, professional, 4k, highly detailed.', type=str)
669
  parser.add_argument('--negative_prompt', default='noisy, blurry, soft, deformed, ugly', type=str)
670
+ parser.add_argument('--prompt_rewrite',
671
+ default='[Close-up photo of a man, 35mm photograph, professional, 4k, highly detailed.]-*'
672
+ '-[noisy, blurry, soft, deformed, ugly]-*-'
673
+ '../example/chris-evans.jpg|'
674
+ '[Close-up photo of a woman, 35mm photograph, professional, 4k, highly detailed.]-'
675
+ '*-[noisy, blurry, soft, deformed, ugly]-*-'
676
+ '../example/TaylorSwift.png',
677
+ type=str)
678
+ parser.add_argument('--seed', default=0, type=int)
679
  parser.add_argument('--suffix', default='', type=str)
680
  parser.add_argument('--segment_type', default='yoloworld', help='GroundingDINO or yoloworld', type=str)
681
+ parser.add_argument('--style_lora', default='', type=str)
682
  return parser.parse_args()
683
 
684
  if __name__ == '__main__':
685
  args = parse_args()
686
 
687
+ prompts = [args.prompt] * 2
688
+
689
  prompts_tmp = copy.deepcopy(prompts)
690
+
691
+ width, height = 1024, 1024
692
+ kwargs = {
693
+ 'height': height,
694
+ 'width': width,
695
+ }
696
+
697
  device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
698
+ main(device, args.segment_type)
699
+