Ryukijano commited on
Commit
6e3f87e
·
verified ·
1 Parent(s): 5d8b4f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -135
app.py CHANGED
@@ -1,136 +1,133 @@
1
- import spaces
2
- from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline, AutoencoderKL, EulerAncestralDiscreteScheduler
3
- from diffusers.utils import load_image
4
- from PIL import Image
5
- import torch
6
- import numpy as np
7
- import cv2
8
- import gradio as gr
9
- from torchvision import transforms
10
- import fire
11
- import os
12
-
13
- controlnet = ControlNetModel.from_pretrained(
14
- "geyongtao/HumanWild",
15
- torch_dtype=torch.float16
16
- ).to('cuda')
17
-
18
- vae = AutoencoderKL.from_pretrained(
19
- "madebyollin/sdxl-vae-fp16-fix",
20
- torch_dtype=torch.float16).to("cuda")
21
-
22
- pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
23
- "stabilityai/stable-diffusion-xl-base-1.0",
24
- controlnet=controlnet,
25
- vae=vae,
26
- torch_dtype=torch.float16,
27
- use_safetensors=True,
28
- low_cpu_mem_usage=True,
29
- offload_state_dict=True,
30
- ).to('cuda')
31
- pipe.controlnet.to(memory_format=torch.channels_last)
32
-
33
- # pipe.enable_xformers_memory_efficient_attention()
34
- pipe.force_zeros_for_empty_prompt = False
35
-
36
-
37
- def resize_image(image):
38
- image = image.convert('RGB')
39
- current_size = image.size
40
- if current_size[0] > current_size[1]:
41
- center_cropped_image = transforms.functional.center_crop(image, (current_size[1], current_size[1]))
42
- else:
43
- center_cropped_image = transforms.functional.center_crop(image, (current_size[0], current_size[0]))
44
- resized_image = transforms.functional.resize(center_cropped_image, (1024, 1024))
45
- return resized_image
46
-
47
- def get_normal_map(image):
48
- image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
49
- with torch.no_grad(), torch.autocast("cuda"):
50
- depth_map = depth_estimator(image).predicted_depth
51
- image = transforms.functional.center_crop(image, min(image.shape[-2:]))
52
- depth_map = torch.nn.functional.interpolate(
53
- depth_map.unsqueeze(1),
54
- size=(1024, 1024),
55
- mode="bicubic",
56
- align_corners=False,
57
- )
58
- depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
59
- depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
60
- depth_map = (depth_map - depth_min) / (depth_max - depth_min)
61
- image = torch.cat([depth_map] * 3, dim=1)
62
- image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
63
- image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
64
- return image
65
-
66
-
67
- @spaces.GPU
68
- def generate_(prompt, negative_prompt, normal_image, num_steps, controlnet_conditioning_scale, seed):
69
- generator = torch.Generator("cuda").manual_seed(seed)
70
- images = pipe(
71
- prompt,
72
- negative_prompt=negative_prompt,
73
- image=normal_image,
74
- num_inference_steps=num_steps,
75
- controlnet_conditioning_scale=float(controlnet_conditioning_scale),
76
- num_images_per_prompt=2,
77
- generator=generator,
78
- ).images
79
- return images
80
-
81
- @spaces.GPU
82
- def process(normal_image, prompt, negative_prompt, num_steps, controlnet_conditioning_scale, seed):
83
- # resize input_image to 1024x1024
84
- normal_image = resize_image(normal_image)
85
- # depth_image = get_depth_map(input_image)
86
- images = generate_(prompt, negative_prompt, normal_image, num_steps, controlnet_conditioning_scale, seed)
87
-
88
- return [images[0], images[1]]
89
-
90
-
91
- def run_demo():
92
-
93
- _TITLE = '''3D Human Reconstruction in the Wild with Synthetic Data Using Generative Models'''
94
-
95
- block = gr.Blocks().queue()
96
-
97
- with block:
98
- gr.Markdown("# 3D Human Reconstruction in the Wild with Synthetic Data Using Generative Models ")
99
- gr.HTML('''
100
- <p style="margin-bottom: 10px; font-size: 94%">
101
- This is a demo for Surface Normal ControlNet that using
102
- <a href="https://huggingface.co/geyongtao/HumanWild" target="_blank"> HumanWild model</a> pretrained weight.
103
- <a style="display:inline-block; margin-left: .5em" href='https://github.com/YongtaoGe/WildHuman/'><img src='https://img.shields.io/github/stars/YongtaoGe/WildHuman?style=social' /></a>
104
- </p>
105
- ''')
106
- with gr.Row():
107
- with gr.Column():
108
- input_image = gr.Image(sources=None, type="pil") # None for upload, ctrl+v and webcam
109
-
110
- example_folder = os.path.join(os.path.dirname(__file__), "./assets")
111
- example_fns = [os.path.join(example_folder, example) for example in os.listdir(example_folder)]
112
- gr.Examples(
113
- examples=example_fns,
114
- inputs=[input_image],
115
- cache_examples=False,
116
- label='Examples (click one of the images below to start)',
117
- examples_per_page=30
118
- )
119
-
120
- prompt = gr.Textbox(label="Prompt", value="a person, in the wild")
121
- negative_prompt = gr.Textbox(visible=False, label="Negative prompt", value="Logo,Watermark,Text,Ugly,Morbid,Extra fingers,Poorly drawn hands,Mutation,Blurry,Extra limbs,Gross proportions,Missing arms,Mutated hands,Long neck,Duplicate,Mutilated,Mutilated hands,Poorly drawn face,Deformed,Bad anatomy,Cloned face,Malformed limbs,Missing legs,Too many fingers")
122
- num_steps = gr.Slider(label="Number of steps", minimum=25, maximum=50, value=30, step=1)
123
- controlnet_conditioning_scale = gr.Slider(label="ControlNet conditioning scale", minimum=0.1, maximum=1.0, value=0.95, step=0.05)
124
- seed = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, randomize=True,)
125
- run_button = gr.Button(value="Run")
126
-
127
- with gr.Column():
128
- result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery", columns=[2], height='auto')
129
- ips = [input_image, prompt, negative_prompt, num_steps, controlnet_conditioning_scale, seed]
130
-
131
- run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
132
-
133
- block.launch(debug = True)
134
-
135
- if __name__ == '__main__':
136
  fire.Fire(run_demo)
 
1
+ import spaces
2
+ from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline, AutoencoderKL, EulerAncestralDiscreteScheduler
3
+ from diffusers.utils import load_image
4
+ from PIL import Image
5
+ import torch
6
+ import numpy as np
7
+ import cv2
8
+ import gradio as gr
9
+ from torchvision import transforms
10
+ import fire
11
+ import os
12
+
13
+ controlnet = ControlNetModel.from_pretrained(
14
+ "geyongtao/HumanWild",
15
+ torch_dtype=torch.float16
16
+ ).to('cuda')
17
+
18
+ vae = AutoencoderKL.from_pretrained(
19
+ "madebyollin/sdxl-vae-fp16-fix",
20
+ torch_dtype=torch.float16).to("cuda")
21
+
22
+ pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
23
+ "stabilityai/stable-diffusion-xl-base-1.0",
24
+ controlnet=controlnet,
25
+ vae=vae,
26
+ torch_dtype=torch.float16,
27
+ use_safetensors=True,
28
+ low_cpu_mem_usage=True,
29
+ offload_state_dict=True,
30
+ ).to('cuda')
31
+ pipe.controlnet.to(memory_format=torch.channels_last)
32
+
33
+ # pipe.enable_xformers_memory_efficient_attention()
34
+ pipe.force_zeros_for_empty_prompt = False
35
+
36
+
37
+ def resize_image(image):
38
+ image = image.convert('RGB')
39
+ current_size = image.size
40
+ if current_size[0] > current_size[1]:
41
+ center_cropped_image = transforms.functional.center_crop(image, (current_size[1], current_size[1]))
42
+ else:
43
+ center_cropped_image = transforms.functional.center_crop(image, (current_size[0], current_size[0]))
44
+ resized_image = transforms.functional.resize(center_cropped_image, (1024, 1024))
45
+ return resized_image
46
+
47
+ def get_normal_map(image):
48
+ image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
49
+ with torch.no_grad(), torch.autocast("cuda"):
50
+ depth_map = depth_estimator(image).predicted_depth
51
+ image = transforms.functional.center_crop(image, min(image.shape[-2:]))
52
+ depth_map = torch.nn.functional.interpolate(
53
+ depth_map.unsqueeze(1),
54
+ size=(1024, 1024),
55
+ mode="bicubic",
56
+ align_corners=False,
57
+ )
58
+ depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
59
+ depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
60
+ depth_map = (depth_map - depth_min) / (depth_max - depth_min)
61
+ image = torch.cat([depth_map] * 3, dim=1)
62
+ image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
63
+ image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
64
+ return image
65
+
66
+
67
+ @spaces.GPU
68
+ def generate_(prompt, negative_prompt, normal_image, num_steps, controlnet_conditioning_scale, seed):
69
+ generator = torch.Generator("cuda").manual_seed(seed)
70
+ images = pipe(
71
+ prompt,
72
+ negative_prompt=negative_prompt,
73
+ image=normal_image,
74
+ num_inference_steps=num_steps,
75
+ controlnet_conditioning_scale=float(controlnet_conditioning_scale),
76
+ num_images_per_prompt=2,
77
+ generator=generator,
78
+ ).images
79
+ return images
80
+
81
+ @spaces.GPU
82
+ def process(normal_image, prompt, negative_prompt, num_steps, controlnet_conditioning_scale, seed):
83
+ # resize input_image to 1024x1024
84
+ normal_image = resize_image(normal_image)
85
+ # depth_image = get_depth_map(input_image)
86
+ images = generate_(prompt, negative_prompt, normal_image, num_steps, controlnet_conditioning_scale, seed)
87
+
88
+ return [images[0], images[1]]
89
+
90
+
91
+ def run_demo():
92
+
93
+ _TITLE = '''3D Human Reconstruction in the Wild with Synthetic Data Using Generative Models'''
94
+
95
+ block = gr.Blocks().queue()
96
+
97
+ with block:
98
+ gr.Markdown("# 3D Human Reconstruction in the Wild with Synthetic Data Using Generative Models ")
99
+ gr.HTML('''
100
+ <p style="margin-bottom: 10px; font-size: 94%">
101
+ This is a demo for Surface Normal ControlNet
102
+ ''')
103
+ with gr.Row():
104
+ with gr.Column():
105
+ input_image = gr.Image(sources=None, type="pil") # None for upload, ctrl+v and webcam
106
+
107
+ example_folder = os.path.join(os.path.dirname(__file__), "./assets")
108
+ example_fns = [os.path.join(example_folder, example) for example in os.listdir(example_folder)]
109
+ gr.Examples(
110
+ examples=example_fns,
111
+ inputs=[input_image],
112
+ cache_examples=False,
113
+ label='Examples (click one of the images below to start)',
114
+ examples_per_page=30
115
+ )
116
+
117
+ prompt = gr.Textbox(label="Prompt", value="a person, in the wild")
118
+ negative_prompt = gr.Textbox(visible=False, label="Negative prompt", value="Logo,Watermark,Text,Ugly,Morbid,Extra fingers,Poorly drawn hands,Mutation,Blurry,Extra limbs,Gross proportions,Missing arms,Mutated hands,Long neck,Duplicate,Mutilated,Mutilated hands,Poorly drawn face,Deformed,Bad anatomy,Cloned face,Malformed limbs,Missing legs,Too many fingers")
119
+ num_steps = gr.Slider(label="Number of steps", minimum=25, maximum=50, value=30, step=1)
120
+ controlnet_conditioning_scale = gr.Slider(label="ControlNet conditioning scale", minimum=0.1, maximum=1.0, value=0.95, step=0.05)
121
+ seed = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, randomize=True,)
122
+ run_button = gr.Button(value="Run")
123
+
124
+ with gr.Column():
125
+ result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery", columns=[2], height='auto')
126
+ ips = [input_image, prompt, negative_prompt, num_steps, controlnet_conditioning_scale, seed]
127
+
128
+ run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
129
+
130
+ block.launch(debug = True)
131
+
132
+ if __name__ == '__main__':
 
 
 
133
  fire.Fire(run_demo)