Fucius commited on
Commit
c81af02
·
verified ·
1 Parent(s): 242978f

Update app.py

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