Fucius commited on
Commit
16c78d0
1 Parent(s): 64fdfbc

Delete gradio_demo/app_generateOne.py

Browse files
Files changed (1) hide show
  1. gradio_demo/app_generateOne.py +0 -582
gradio_demo/app_generateOne.py DELETED
@@ -1,582 +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, ImageOps
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, pipe):
217
- pipe_list = []
218
- if condition == "Human pose":
219
- controlnet = ControlNetModel.from_pretrained(args.openpose_checkpoint, torch_dtype=torch.float16).to(device)
220
- pipe.controlnet = controlnet
221
- elif condition == "Canny Edge":
222
- controlnet = ControlNetModel.from_pretrained(args.canny_checkpoint, torch_dtype=torch.float16, variant="fp16").to(device)
223
- pipe.controlnet = controlnet
224
- elif condition == "Depth":
225
- controlnet = ControlNetModel.from_pretrained(args.depth_checkpoint, torch_dtype=torch.float16).to(device)
226
- pipe.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
- pipe.load_lora_weights(style_path, weight_name="pytorch_lora_weights.safetensors", adapter_name='style')
231
-
232
- for lora_path in lora_paths.split('|'):
233
- adapter_name = lora_path.split('/')[-1].split('.')[0]
234
- pipe_concept.load_lora_weights(lora_path, weight_name="pytorch_lora_weights.safetensors", adapter_name=adapter_name)
235
- pipe_concept.enable_xformers_memory_efficient_attention()
236
- pipe_list.append(adapter_name)
237
- return pipe_list
238
-
239
- def build_yolo_segment_model(sam_path, device):
240
- yolo_world = YOLOWorld(model_id="yolo_world/l")
241
- sam = EfficientViTSamPredictor(
242
- create_sam_model(name="xl1", weight_url=sam_path).to(device).eval()
243
- )
244
- return yolo_world, sam
245
-
246
- def load_model_hf(repo_id, filename, ckpt_config_filename, device='cpu'):
247
- args = SLConfig.fromfile(ckpt_config_filename)
248
- model = build_model(args)
249
- args.device = device
250
-
251
- checkpoint = torch.load(os.path.join(repo_id, filename), map_location='cpu')
252
- log = model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False)
253
- print("Model loaded from {} \n => {}".format(filename, log))
254
- _ = model.eval()
255
- return model
256
-
257
- def build_dino_segment_model(ckpt_repo_id, sam_checkpoint):
258
- ckpt_filenmae = "groundingdino_swinb_cogcoor.pth"
259
- ckpt_config_filename = os.path.join(ckpt_repo_id, "GroundingDINO_SwinB.cfg.py")
260
- groundingdino_model = load_model_hf(ckpt_repo_id, ckpt_filenmae, ckpt_config_filename)
261
- sam = build_sam(checkpoint=sam_checkpoint)
262
- sam.cuda()
263
- sam_predictor = SamPredictor(sam)
264
- return groundingdino_model, sam_predictor
265
-
266
- def resize_and_center_crop(image, output_size=(1024, 576)):
267
- width, height = image.size
268
- aspect_ratio = width / height
269
- new_height = output_size[1]
270
- new_width = int(aspect_ratio * new_height)
271
-
272
- resized_image = image.resize((new_width, new_height), Image.LANCZOS)
273
-
274
- if new_width < output_size[0] or new_height < output_size[1]:
275
- padding_color = "gray"
276
- resized_image = ImageOps.expand(resized_image,
277
- ((output_size[0] - new_width) // 2,
278
- (output_size[1] - new_height) // 2,
279
- (output_size[0] - new_width + 1) // 2,
280
- (output_size[1] - new_height + 1) // 2),
281
- fill=padding_color)
282
-
283
- left = (resized_image.width - output_size[0]) / 2
284
- top = (resized_image.height - output_size[1]) / 2
285
- right = (resized_image.width + output_size[0]) / 2
286
- bottom = (resized_image.height + output_size[1]) / 2
287
-
288
- cropped_image = resized_image.crop((left, top, right, bottom))
289
-
290
- return cropped_image
291
-
292
- def main(device, segment_type):
293
- pipe, controller, pipe_concept = build_model_sd(args.pretrained_sdxl_model, args.openpose_checkpoint, device, prompts_tmp)
294
-
295
- if segment_type == 'GroundingDINO':
296
- detect_model, sam = build_dino_segment_model(args.dino_checkpoint, args.sam_checkpoint)
297
- else:
298
- detect_model, sam = build_yolo_segment_model(args.efficientViT_checkpoint, device)
299
-
300
- resolution_list = ["1440*728",
301
- "1344*768",
302
- "1216*832",
303
- "1152*896",
304
- "1024*1024",
305
- "896*1152",
306
- "832*1216",
307
- "768*1344",
308
- "728*1440"]
309
- ratio_list = [1440 / 728, 1344 / 768, 1216 / 832, 1152 / 896, 1024 / 1024, 896 / 1152, 832 / 1216, 768 / 1344,
310
- 728 / 1440]
311
- condition_list = ["None",
312
- "Human pose",
313
- "Canny Edge",
314
- "Depth"]
315
-
316
- depth_estimator = DPTForDepthEstimation.from_pretrained(args.dpt_checkpoint).to("cuda")
317
- feature_extractor = DPTFeatureExtractor.from_pretrained(args.dpt_checkpoint)
318
- body_model = Body(args.pose_detector_checkpoint)
319
- openpose = OpenposeDetector(body_model)
320
-
321
- def remove_tips():
322
- return gr.update(visible=False)
323
-
324
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
325
- if randomize_seed:
326
- seed = random.randint(0, MAX_SEED)
327
- return seed
328
-
329
- def get_humanpose(img):
330
- openpose_image = openpose(img)
331
- return openpose_image
332
-
333
- def get_cannyedge(image):
334
- image = np.array(image)
335
- image = cv2.Canny(image, 100, 200)
336
- image = image[:, :, None]
337
- image = np.concatenate([image, image, image], axis=2)
338
- canny_image = Image.fromarray(image)
339
- return canny_image
340
-
341
- def get_depth(image):
342
- image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
343
- with torch.no_grad(), torch.autocast("cuda"):
344
- depth_map = depth_estimator(image).predicted_depth
345
-
346
- depth_map = torch.nn.functional.interpolate(
347
- depth_map.unsqueeze(1),
348
- size=(1024, 1024),
349
- mode="bicubic",
350
- align_corners=False,
351
- )
352
- depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
353
- depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
354
- depth_map = (depth_map - depth_min) / (depth_max - depth_min)
355
- image = torch.cat([depth_map] * 3, dim=1)
356
- image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
357
- image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
358
- return image
359
-
360
- def generate_image(prompt1, negative_prompt, man, woman, resolution, local_prompt1, local_prompt2, seed, condition, condition_img1, style):
361
- try:
362
- path1 = lorapath_man[man]
363
- path2 = lorapath_woman[woman]
364
- pipe_concept.unload_lora_weights()
365
- pipe.unload_lora_weights()
366
- pipe_list = build_model_lora(pipe_concept, path1 + "|" + path2, lorapath_styles[style], condition, args, pipe)
367
-
368
- if lorapath_styles[style] is not None and os.path.exists(lorapath_styles[style]):
369
- styleL = True
370
- else:
371
- styleL = False
372
-
373
- input_list = [prompt1]
374
- condition_list = [condition_img1]
375
- output_list = []
376
-
377
- width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
378
-
379
- kwargs = {
380
- 'height': height,
381
- 'width': width,
382
- }
383
-
384
- for prompt, condition_img in zip(input_list, condition_list):
385
- if prompt!='':
386
- input_prompt = []
387
- p = '{prompt}, 35mm photograph, film, professional, 4k, highly detailed.'
388
- if styleL:
389
- p = styles[style] + p
390
- input_prompt.append([p.replace("{prompt}", prompt), p.replace("{prompt}", prompt)])
391
- if styleL:
392
- input_prompt.append([(styles[style] + local_prompt1, character_man.get(man)[1]),
393
- (styles[style] + local_prompt2, character_woman.get(woman)[1])])
394
- else:
395
- input_prompt.append([(local_prompt1, character_man.get(man)[1]),
396
- (local_prompt2, character_woman.get(woman)[1])])
397
-
398
- if condition == 'Human pose' and condition_img is not None:
399
- index = ratio_list.index(
400
- min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
401
- resolution = resolution_list[index]
402
- width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
403
- kwargs['height'] = height
404
- kwargs['width'] = width
405
- condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
406
- spatial_condition = get_humanpose(condition_img)
407
- elif condition == 'Canny Edge' and condition_img is not None:
408
- index = ratio_list.index(
409
- min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
410
- resolution = resolution_list[index]
411
- width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
412
- kwargs['height'] = height
413
- kwargs['width'] = width
414
- condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
415
- spatial_condition = get_cannyedge(condition_img)
416
- elif condition == 'Depth' and condition_img is not None:
417
- index = ratio_list.index(
418
- min(ratio_list, key=lambda x: abs(x - condition_img.shape[1] / condition_img.shape[0])))
419
- resolution = resolution_list[index]
420
- width, height = int(resolution.split("*")[0]), int(resolution.split("*")[1])
421
- kwargs['height'] = height
422
- kwargs['width'] = width
423
- condition_img = resize_and_center_crop(Image.fromarray(condition_img), (width, height))
424
- spatial_condition = get_depth(condition_img)
425
- else:
426
- spatial_condition = None
427
-
428
- kwargs['spatial_condition'] = spatial_condition
429
- controller.reset()
430
- image = sample_image(
431
- pipe,
432
- input_prompt=input_prompt,
433
- concept_models=pipe_concept,
434
- input_neg_prompt=[negative_prompt] * len(input_prompt),
435
- generator=torch.Generator(device).manual_seed(seed),
436
- controller=controller,
437
- stage=1,
438
- lora_list=pipe_list,
439
- styleL=styleL,
440
- **kwargs)
441
-
442
- controller.reset()
443
- if pipe.tokenizer("man")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
444
- mask1 = predict_mask(detect_model, sam, image[0], 'man', args.segment_type, confidence=0.15,
445
- threshold=0.5)
446
- else:
447
- mask1 = None
448
-
449
- if pipe.tokenizer("woman")["input_ids"][1] in pipe.tokenizer(args.prompt)["input_ids"][1:-1]:
450
- mask2 = predict_mask(detect_model, sam, image[0], 'woman', args.segment_type, confidence=0.15,
451
- threshold=0.5)
452
- else:
453
- mask2 = None
454
-
455
- if mask1 is None and mask2 is None:
456
- output_list.append(image[1])
457
- else:
458
- image = sample_image(
459
- pipe,
460
- input_prompt=input_prompt,
461
- concept_models=pipe_concept,
462
- input_neg_prompt=[negative_prompt] * len(input_prompt),
463
- generator=torch.Generator(device).manual_seed(seed),
464
- controller=controller,
465
- stage=2,
466
- region_masks=[mask1, mask2],
467
- lora_list=pipe_list,
468
- styleL=styleL,
469
- **kwargs)
470
- output_list.append(image[1])
471
- else:
472
- output_list.append(None)
473
- output_list.append(spatial_condition)
474
- return output_list
475
- except:
476
- print("error")
477
- return
478
-
479
- def get_local_value_man(input):
480
- return character_man[input][0]
481
-
482
- def get_local_value_woman(input):
483
- return character_woman[input][0]
484
-
485
-
486
- with gr.Blocks(css=css) as demo:
487
- # description
488
- gr.Markdown(title)
489
- gr.Markdown(description)
490
-
491
- with gr.Row():
492
- gallery = gr.Image(label="Generated Images", height=512, width=512)
493
- gen_condition = gr.Image(label="Spatial Condition", height=512, width=512)
494
- usage_tips = gr.Markdown(label="Usage tips of OMG", value=tips, visible=False)
495
-
496
- with gr.Row():
497
- condition_img1 = gr.Image(label="Input an RGB image for condition", height=128, width=128)
498
-
499
- # character choose
500
- with gr.Row():
501
- man = gr.Dropdown(label="Character 1 selection", choices=CHARACTER_MAN_NAMES, value="Chris Evans (identifier: Chris Evans)")
502
- woman = gr.Dropdown(label="Character 2 selection", choices=CHARACTER_WOMAN_NAMES, value="Taylor Swift (identifier: TaylorSwift)")
503
- resolution = gr.Dropdown(label="Image Resolution (width*height)", choices=resolution_list, value="1024*1024")
504
- condition = gr.Dropdown(label="Input condition type", choices=condition_list, value="None")
505
- style = gr.Dropdown(label="style", choices=STYLE_NAMES, value="None")
506
-
507
- with gr.Row():
508
- local_prompt1 = gr.Textbox(label="Character1_prompt",
509
- info="Describe the Character 1, this prompt should include the identifier of character 1",
510
- value="Close-up photo of the Chris Evans, 35mm photograph, film, professional, 4k, highly detailed.")
511
- local_prompt2 = gr.Textbox(label="Character2_prompt",
512
- info="Describe the Character 2, this prompt should include the identifier of character2",
513
- value="Close-up photo of the TaylorSwift, 35mm photograph, film, professional, 4k, highly detailed.")
514
-
515
- man.change(get_local_value_man, man, local_prompt1)
516
- woman.change(get_local_value_woman, woman, local_prompt2)
517
-
518
- # prompt
519
- with gr.Column():
520
- prompt = gr.Textbox(label="Prompt 1",
521
- info="Give a simple prompt to describe the first image content",
522
- placeholder="Required",
523
- value="close-up shot, photography, a man and a woman on the street, facing the camera smiling")
524
-
525
-
526
- with gr.Accordion(open=False, label="Advanced Options"):
527
- seed = gr.Slider(
528
- label="Seed",
529
- minimum=0,
530
- maximum=MAX_SEED,
531
- step=1,
532
- value=42,
533
- )
534
- negative_prompt = gr.Textbox(label="Negative Prompt",
535
- placeholder="noisy, blurry, soft, deformed, ugly",
536
- value="noisy, blurry, soft, deformed, ugly")
537
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
538
-
539
- submit = gr.Button("Submit", variant="primary")
540
-
541
- submit.click(
542
- fn=remove_tips,
543
- outputs=usage_tips,
544
- ).then(
545
- fn=randomize_seed_fn,
546
- inputs=[seed, randomize_seed],
547
- outputs=seed,
548
- queue=False,
549
- api_name=False,
550
- ).then(
551
- fn=generate_image,
552
- inputs=[prompt, negative_prompt, man, woman, resolution, local_prompt1, local_prompt2, seed, condition, condition_img1, style],
553
- outputs=[gallery, gen_condition]
554
- )
555
- demo.launch(server_name='0.0.0.0',server_port=7861, debug=True)
556
-
557
- def parse_args():
558
- parser = argparse.ArgumentParser('', add_help=False)
559
- parser.add_argument('--pretrained_sdxl_model', default='./checkpoint/stable-diffusion-xl-base-1.0', type=str)
560
- parser.add_argument('--openpose_checkpoint', default='./checkpoint/controlnet-openpose-sdxl-1.0', type=str)
561
- parser.add_argument('--canny_checkpoint', default='./checkpoint/controlnet-canny-sdxl-1.0', type=str)
562
- parser.add_argument('--depth_checkpoint', default='./checkpoint/controlnet-depth-sdxl-1.0', type=str)
563
- parser.add_argument('--efficientViT_checkpoint', default='./checkpoint/sam/xl1.pt', type=str)
564
- parser.add_argument('--dino_checkpoint', default='./checkpoint/GroundingDINO', type=str)
565
- parser.add_argument('--sam_checkpoint', default='./checkpoint/sam/sam_vit_h_4b8939.pth', type=str)
566
- parser.add_argument('--dpt_checkpoint', default='./checkpoint/dpt-hybrid-midas', type=str)
567
- parser.add_argument('--pose_detector_checkpoint', default='./checkpoint/ControlNet/annotator/ckpts/body_pose_model.pth', type=str)
568
- 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)
569
- parser.add_argument('--negative_prompt', default='noisy, blurry, soft, deformed, ugly', type=str)
570
- parser.add_argument('--seed', default=22, type=int)
571
- parser.add_argument('--suffix', default='', type=str)
572
- parser.add_argument('--segment_type', default='yoloworld', help='GroundingDINO or yoloworld', type=str)
573
- return parser.parse_args()
574
-
575
- if __name__ == '__main__':
576
- args = parse_args()
577
-
578
- prompts = [args.prompt]*2
579
- prompts_tmp = copy.deepcopy(prompts)
580
- device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
581
-
582
- main(device, args.segment_type)