feishen29 commited on
Commit
9c79eab
·
verified ·
1 Parent(s): beaa943

Delete ckpt/app.py

Browse files
Files changed (1) hide show
  1. ckpt/app.py +0 -399
ckpt/app.py DELETED
@@ -1,399 +0,0 @@
1
- import sys
2
- from PIL import Image
3
- import gradio as gr
4
- import numpy as np
5
- import cv2
6
- from modelscope.outputs import OutputKeys
7
- from modelscope.pipelines import pipeline
8
- from modelscope.utils.constant import Tasks
9
- from dressing_sd.pipelines.pipeline_sd import PipIpaControlNet
10
- from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
11
-
12
- from torchvision import transforms
13
- import cv2
14
- from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
15
- import diffusers
16
-
17
- from transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
18
- from adapter.attention_processor import CacheAttnProcessor2_0, RefSAttnProcessor2_0, RefLoraSAttnProcessor2_0, LoRAIPAttnProcessor2_0
19
- from diffusers import ControlNetModel, UNet2DConditionModel, \
20
- AutoencoderKL, DDIMScheduler
21
- from adapter.resampler import Resampler
22
-
23
- from transformers import (
24
- CLIPImageProcessor,
25
- CLIPVisionModelWithProjection,
26
- CLIPTextModel,
27
- CLIPTextModelWithProjection,
28
- )
29
- from diffusers import DDPMScheduler, AutoencoderKL, UniPCMultistepScheduler
30
- from typing import List
31
-
32
- import torch
33
-
34
- import argparse
35
- import os
36
-
37
- from controlnet_aux import OpenposeDetector
38
- from insightface.app import FaceAnalysis
39
- from insightface.utils import face_align
40
-
41
-
42
- # device = 'cuda:2' if torch.cuda.is_available() else 'cpu'
43
-
44
- parser = argparse.ArgumentParser(description='ReferenceAdapter diffusion')
45
- parser.add_argument('--if_resampler', type=bool, default=True)
46
- parser.add_argument('--if_ipa', type=bool, default=True)
47
- parser.add_argument('--if_control', type=bool, default=True)
48
-
49
- parser.add_argument('--pretrained_model_name_or_path',
50
- default="./ckpt/Realistic_Vision_V4.0_noVAE",
51
- type=str)
52
- parser.add_argument('--ip_ckpt',
53
- default="./ckpt/ip-adapter-faceid-plus_sd15.bin",
54
- type=str)
55
- parser.add_argument('--pretrained_image_encoder_path',
56
- default="./ckpt/image_encoder/",
57
- type=str)
58
- parser.add_argument('--pretrained_vae_model_path',
59
- default="./ckpt/sd-vae-ft-mse/",
60
- type=str)
61
- parser.add_argument('--model_ckpt',
62
- default="./ckpt/IMAGDressing-v1_512.pt",
63
- type=str)
64
- parser.add_argument('--output_path', type=str, default="./output_ipa_control_resampler")
65
- # parser.add_argument('--device', type=str, default="cuda:0")
66
- args = parser.parse_args()
67
-
68
- # svae path
69
- output_path = args.output_path
70
-
71
- if not os.path.exists(output_path):
72
- os.makedirs(output_path)
73
-
74
- device = "cuda" if torch.cuda.is_available() else "cpu"
75
- args.device = device
76
-
77
- base_path = 'feishen29/IMAGDressing-v1'
78
-
79
- generator = torch.Generator(device=args.device).manual_seed(42)
80
- vae = AutoencoderKL.from_pretrained(args.pretrained_vae_model_path).to(dtype=torch.float16, device=args.device)
81
- tokenizer = CLIPTokenizer.from_pretrained("./ckpt/tokenizer")
82
- text_encoder = CLIPTextModel.from_pretrained("./ckpt/text_encoder").to(
83
- dtype=torch.float16, device=args.device)
84
- image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.pretrained_image_encoder_path).to(
85
- dtype=torch.float16, device=args.device)
86
- unet = UNet2DConditionModel.from_pretrained("./ckpt/unet").to(
87
- dtype=torch.float16,device=args.device)
88
-
89
- image_face_fusion = pipeline('face_fusion_torch', model='damo/cv_unet_face_fusion_torch', model_revision='v1.0.3')
90
-
91
- #face_model
92
- app = FaceAnalysis(providers=[('CUDAExecutionProvider', {"device_id": args.device})]) ##使用GPU:0, 默认使用buffalo_l就可以了
93
- app.prepare(ctx_id=0, det_size=(640, 640))
94
-
95
- # def ref proj weight
96
- image_proj = Resampler(
97
- dim=unet.config.cross_attention_dim,
98
- depth=4,
99
- dim_head=64,
100
- heads=12,
101
- num_queries=16,
102
- embedding_dim=image_encoder.config.hidden_size,
103
- output_dim=unet.config.cross_attention_dim,
104
- ff_mult=4
105
- )
106
- image_proj = image_proj.to(dtype=torch.float16, device=args.device)
107
-
108
- # set attention processor
109
- attn_procs = {}
110
- st = unet.state_dict()
111
- for name in unet.attn_processors.keys():
112
- cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
113
- if name.startswith("mid_block"):
114
- hidden_size = unet.config.block_out_channels[-1]
115
- elif name.startswith("up_blocks"):
116
- block_id = int(name[len("up_blocks.")])
117
- hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
118
- elif name.startswith("down_blocks"):
119
- block_id = int(name[len("down_blocks.")])
120
- hidden_size = unet.config.block_out_channels[block_id]
121
- # lora_rank = hidden_size // 2 # args.lora_rank
122
- if cross_attention_dim is None:
123
- attn_procs[name] = RefLoraSAttnProcessor2_0(name, hidden_size)
124
- else:
125
- attn_procs[name] = LoRAIPAttnProcessor2_0(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
126
-
127
- unet.set_attn_processor(attn_procs)
128
- adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
129
- adapter_modules = adapter_modules.to(dtype=torch.float16, device=args.device)
130
- del st
131
-
132
- ref_unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet").to(
133
- dtype=torch.float16,
134
- device=args.device)
135
- ref_unet.set_attn_processor(
136
- {name: CacheAttnProcessor2_0() for name in ref_unet.attn_processors.keys()}) # set cache
137
-
138
- # weights load
139
- model_sd = torch.load(args.model_ckpt, map_location="cpu")["module"]
140
-
141
- ref_unet_dict = {}
142
- unet_dict = {}
143
- image_proj_dict = {}
144
- adapter_modules_dict = {}
145
- for k in model_sd.keys():
146
- if k.startswith("ref_unet"):
147
- ref_unet_dict[k.replace("ref_unet.", "")] = model_sd[k]
148
- elif k.startswith("unet"):
149
- unet_dict[k.replace("unet.", "")] = model_sd[k]
150
- elif k.startswith("proj"):
151
- image_proj_dict[k.replace("proj.", "")] = model_sd[k]
152
- elif k.startswith("adapter_modules") and 'ref' in k:
153
- adapter_modules_dict[k.replace("adapter_modules.", "")] = model_sd[k]
154
- else:
155
- print(k)
156
-
157
- ref_unet.load_state_dict(ref_unet_dict)
158
- image_proj.load_state_dict(image_proj_dict)
159
- adapter_modules.load_state_dict(adapter_modules_dict, strict=False)
160
-
161
- noise_scheduler = DDIMScheduler(
162
- num_train_timesteps=1000,
163
- beta_start=0.00085,
164
- beta_end=0.012,
165
- beta_schedule="scaled_linear",
166
- clip_sample=False,
167
- set_alpha_to_one=False,
168
- steps_offset=1,
169
- )
170
- # noise_scheduler = UniPCMultistepScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler")
171
-
172
- control_net_openpose = ControlNetModel.from_pretrained(
173
- "/home/sf/control_v11p_sd15_openpose",
174
- torch_dtype=torch.float16).to(device=args.device)
175
- # pipe = PipIpaControlNet(unet=unet, reference_unet=ref_unet, vae=vae, tokenizer=tokenizer,
176
- # text_encoder=text_encoder, image_encoder=image_encoder,
177
- # ip_ckpt=args.ip_ckpt,
178
- # ImgProj=image_proj, controlnet=control_net_openpose,
179
- # scheduler=noise_scheduler,
180
- # safety_checker=StableDiffusionSafetyChecker,
181
- # feature_extractor=CLIPImageProcessor)
182
-
183
- img_transform = transforms.Compose([
184
- transforms.Resize([640, 512], interpolation=transforms.InterpolationMode.BILINEAR),
185
- transforms.ToTensor(),
186
- transforms.Normalize([0.5], [0.5]),
187
- ])
188
-
189
- openpose_model = OpenposeDetector.from_pretrained("/home/sf/ControlNet").to(args.device)
190
-
191
- def resize_img(input_image, max_side=640, min_side=512, size=None,
192
- pad_to_max_side=False, mode=Image.BILINEAR, base_pixel_number=64):
193
- w, h = input_image.size
194
- ratio = min_side / min(h, w)
195
- w, h = round(ratio*w), round(ratio*h)
196
- ratio = max_side / max(h, w)
197
- input_image = input_image.resize([round(ratio*w), round(ratio*h)], mode)
198
- w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number
199
- h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number
200
- input_image = input_image.resize([w_resize_new, h_resize_new], mode)
201
- return input_image
202
-
203
- def tryon_process(garm_img, face_img, pose_img, prompt, cloth_guidance_scale, caption_guidance_scale,
204
- face_guidance_scale,self_guidance_scale, cross_guidance_scale,if_ipa, if_post, if_control, denoise_steps, seed=42):
205
- # prompt = prompt + ', confident smile expression, fashion, best quality, amazing quality, very aesthetic'
206
- if prompt is None:
207
- prompt = "a photography of a model"
208
- prompt = prompt + ', best quality, high quality'
209
- print(prompt, cloth_guidance_scale, if_ipa, if_control, denoise_steps, seed)
210
- clip_image_processor = CLIPImageProcessor()
211
- # clothes_img = garm_img.convert("RGB")
212
- if not garm_img:
213
- raise gr.Error("请上传衣服 / Please upload garment")
214
- clothes_img = resize_img(garm_img)
215
- vae_clothes = img_transform(clothes_img).unsqueeze(0)
216
- # print(vae_clothes.shape)
217
- ref_clip_image = clip_image_processor(images=clothes_img, return_tensors="pt").pixel_values
218
-
219
- if if_ipa:
220
- # image = cv2.imread(face_img)
221
- faces = app.get(face_img)
222
-
223
- if not faces:
224
- raise gr.Error("人脸检测异常,尝试其他肖像 / Abnormal face detection. Try another portrait")
225
- faceid_embeds = torch.from_numpy(faces[0].normed_embedding).unsqueeze(0)
226
- face_image = face_align.norm_crop(face_img, landmark=faces[0].kps, image_size=224) # you can also segment the face
227
-
228
- # face_img = face_image[:, :, ::-1]
229
- # face_img = Image.fromarray(face_image.astype('uint8'))
230
- # face_img.save('face.png')
231
-
232
- face_clip_image = clip_image_processor(images=face_image, return_tensors="pt").pixel_values
233
- else:
234
- faceid_embeds = None
235
- face_clip_image = None
236
-
237
- if if_control:
238
- pose_img = openpose_model(pose_img.convert("RGB"))
239
- # pose_img.save('pose.png')
240
- pose_image = diffusers.utils.load_image(pose_img)
241
- else:
242
- pose_image = None
243
- # print(if_ipa, if_control)
244
- # pipe, generator = prepare_pipeline(args, if_ipa, if_control, unet, ref_unet, vae, tokenizer, text_encoder,
245
- # image_encoder, image_proj, control_net_openpose)
246
-
247
- noise_scheduler = DDIMScheduler(
248
- num_train_timesteps=1000,
249
- beta_start=0.00085,
250
- beta_end=0.012,
251
- beta_schedule="scaled_linear",
252
- clip_sample=False,
253
- set_alpha_to_one=False,
254
- steps_offset=1,
255
- )
256
- # noise_scheduler = UniPCMultistepScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler")
257
- pipe = PipIpaControlNet(unet=unet, reference_unet=ref_unet, vae=vae, tokenizer=tokenizer,
258
- text_encoder=text_encoder, image_encoder=image_encoder,
259
- ip_ckpt=args.ip_ckpt,
260
- ImgProj=image_proj, controlnet=control_net_openpose,
261
- scheduler=noise_scheduler,
262
- safety_checker=StableDiffusionSafetyChecker,
263
- feature_extractor=CLIPImageProcessor)
264
- output = pipe(
265
- ref_image=vae_clothes,
266
- prompt=prompt,
267
- ref_clip_image=ref_clip_image,
268
- pose_image=pose_image,
269
- face_clip_image=face_clip_image,
270
- faceid_embeds=faceid_embeds,
271
- null_prompt='',
272
- negative_prompt='bare, naked, nude, undressed, monochrome, lowres, bad anatomy, worst quality, low quality',
273
- width=512,
274
- height=640,
275
- num_images_per_prompt=1,
276
- guidance_scale=caption_guidance_scale,
277
- image_scale=cloth_guidance_scale,
278
- ipa_scale=face_guidance_scale,
279
- s_lora_scale= self_guidance_scale,
280
- c_lora_scale= cross_guidance_scale,
281
- generator=generator,
282
- num_inference_steps=denoise_steps,
283
- ).images
284
-
285
- if if_post and if_ipa:
286
- # 将 PIL 图像转换为 NumPy 数组
287
- output_array = np.array(output[0])
288
- # 将 RGB 图像转换为 BGR 图像
289
- bgr_array = cv2.cvtColor(output_array, cv2.COLOR_RGB2BGR)
290
- # 将 NumPy 数组转换为 PIL 图像
291
- bgr_image = Image.fromarray(bgr_array)
292
- result = image_face_fusion(dict(template=bgr_image, user=Image.fromarray(face_image.astype('uint8'))))
293
- return result[OutputKeys.OUTPUT_IMG]
294
- return output[0]
295
-
296
- example_path = os.path.dirname(__file__)
297
-
298
- garm_list = os.listdir(os.path.join(example_path, "cloth", 'cloth'))
299
- garm_list_path = [os.path.join(example_path, "cloth", 'cloth', garm) for garm in garm_list]
300
-
301
- face_list = os.listdir(os.path.join(example_path, "face", 'face'))
302
- face_list_path = [os.path.join(example_path, "face", 'face', face) for face in face_list]
303
-
304
- pose_list = os.listdir(os.path.join(example_path, "pose", 'pose'))
305
- pose_list_path = [os.path.join(example_path, "pose", 'pose', pose) for pose in pose_list]
306
-
307
-
308
-
309
- ##default human
310
-
311
-
312
- image_blocks = gr.Blocks().queue()
313
- with image_blocks as demo:
314
- gr.Markdown("## IMAGDressing-v1: Customizable Virtual Dressing 👕👔👚")
315
- gr.Markdown(
316
- "Customize your virtual look with ease—adjust your appearance, pose, and garment as you like<br>."
317
- "If you enjoy this project, please check out the [source codes](https://github.com/muzishen/IMAGDressing) and [model](https://huggingface.co/feishen29/IMAGDressing). Do not hesitate to give us a star. Thank you!<br>"
318
- "Your support fuels the development of new versions."
319
- )
320
- with gr.Row():
321
- with gr.Column():
322
- garm_img = gr.Image(label="Garment", sources='upload', type="pil")
323
- example = gr.Examples(
324
- inputs=garm_img,
325
- examples_per_page=8,
326
- examples=garm_list_path)
327
-
328
- with gr.Column():
329
- imgs = gr.Image(label="Face", sources='upload', type="numpy")
330
-
331
- with gr.Row():
332
- is_checked_face = gr.Checkbox(label="Yes", info="Use face ", value=False)
333
- example = gr.Examples(
334
- inputs=imgs,
335
- examples_per_page=10,
336
- examples=face_list_path
337
- )
338
- with gr.Row():
339
- is_checked_postprocess = gr.Checkbox(label="Yes", info="Use postprocess ", value=False)
340
-
341
- with gr.Column():
342
- pose_img = gr.Image(label="Pose", sources='upload', type="pil")
343
- with gr.Row():
344
- is_checked_pose = gr.Checkbox(label="Yes", info="Use pose ", value=False)
345
-
346
- example = gr.Examples(
347
- inputs=pose_img,
348
- examples_per_page=8,
349
- examples=pose_list_path)
350
-
351
- # with gr.Column():
352
- # # image_out = gr.Image(label="Output", elem_id="output-img", height=400)
353
- # masked_img = gr.Image(label="Masked image output", elem_id="masked-img", show_share_button=False)
354
- with gr.Column():
355
- # image_out = gr.Image(label="Output", elem_id="output-img", height=400)
356
- image_out = gr.Image(label="Output", elem_id="output-img", show_share_button=False)
357
- # Add usage tips below the output image
358
- gr.Markdown("""
359
- ### Usage Tips
360
- - **Upload Images**: Upload your desired garment, face, and pose images in the respective sections.
361
- - **Select Options**: Use the checkboxes to include face and pose in the generated output.
362
- - **View Output**: The resulting image will be displayed in the Output section.
363
- - **Examples**: Click on example images to quickly load and test different configurations.
364
- - **Advanced Settings**: Click on **Advanced Settings** to edit captions and adjust hyperparameters.
365
- - **Feedback**: If you have any issues or suggestions, please let us know through the [GitHub repository](https://github.com/muzishen/IMAGDressing).
366
- """)
367
- with gr.Column():
368
- try_button = gr.Button(value="Dressing")
369
- with gr.Accordion(label="Advanced Settings", open=False):
370
- with gr.Row(elem_id="prompt-container"):
371
- with gr.Row():
372
- prompt = gr.Textbox(placeholder="Description of prompt ex) A beautiful woman dress Short Sleeve Round Neck T-shirts",value='A beautiful woman',
373
- show_label=False, elem_id="prompt")
374
- # with gr.Row():
375
- # neg_prompt = gr.Textbox(placeholder="Description of neg prompt ex) Short Sleeve Round Neck T-shirts",
376
- # show_label=False, elem_id="neg_prompt")
377
- with gr.Row():
378
- cloth_guidance_scale = gr.Slider(label="Cloth guidance Scale", minimum=0.0, maximum=1.0, value=0.9, step=0.1,
379
- visible=True)
380
- with gr.Row():
381
- caption_guidance_scale = gr.Slider(label="Prompt Guidance Scale", minimum=1, maximum=10., value=7.0, step=0.1,
382
- visible=True)
383
- with gr.Row():
384
- face_guidance_scale = gr.Slider(label="Face Guidance Scale", minimum=0.0, maximum=2.0, value=0.9, step=0.1,
385
- visible=True)
386
- with gr.Row():
387
- self_guidance_scale = gr.Slider(label="Self-Attention Lora Scale", minimum=0.0, maximum=0.5, value=0.2, step=0.1,
388
- visible=True)
389
- with gr.Row():
390
- cross_guidance_scale = gr.Slider(label="Cross-Attention Lora Scale", minimum=0.0, maximum=0.5, value=0.2, step=0.1,
391
- visible=True)
392
- with gr.Row():
393
- denoise_steps = gr.Number(label="Denoising Steps", minimum=20, maximum=50, value=30, step=1)
394
- seed = gr.Number(label="Seed", minimum=-1, maximum=2147483647, step=1, value=20240508)
395
-
396
- try_button.click(fn=tryon_process, inputs=[garm_img, imgs, pose_img, prompt, cloth_guidance_scale, caption_guidance_scale, face_guidance_scale,self_guidance_scale, cross_guidance_scale, is_checked_face, is_checked_postprocess, is_checked_pose, denoise_steps, seed],
397
- outputs=[image_out], api_name='tryon')
398
-
399
- image_blocks.launch(server_port=20021) # 指定固定端口