Spaces:
Runtime error
Runtime error
Create app2.py
Browse files
app2.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from share import *
|
2 |
+
import config
|
3 |
+
|
4 |
+
import cv2
|
5 |
+
import einops
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import random
|
10 |
+
|
11 |
+
from pytorch_lightning import seed_everything
|
12 |
+
from annotator.util import resize_image, HWC3
|
13 |
+
from cldm.model import create_model, load_state_dict
|
14 |
+
from cldm.ddim_hacked import DDIMSampler
|
15 |
+
|
16 |
+
import dlib
|
17 |
+
from PIL import Image, ImageDraw
|
18 |
+
|
19 |
+
model = create_model('./models/cldm_v15.yaml').cpu()
|
20 |
+
model.load_state_dict(load_state_dict('./models/control_sd15_landmarks.pth', location='cuda'))
|
21 |
+
model = model.cuda()
|
22 |
+
ddim_sampler = DDIMSampler(model)
|
23 |
+
|
24 |
+
detector = dlib.get_frontal_face_detector()
|
25 |
+
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
|
26 |
+
|
27 |
+
def draw_landmarks(image, landmarks, color="white", radius=2.5):
|
28 |
+
draw = ImageDraw.Draw(image)
|
29 |
+
for dot in landmarks:
|
30 |
+
x, y = dot
|
31 |
+
draw.ellipse((x-radius, y-radius, x+radius, y+radius), fill=color)
|
32 |
+
|
33 |
+
def get_68landmarks_img(img):
|
34 |
+
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
35 |
+
faces = detector(gray)
|
36 |
+
landmarks = []
|
37 |
+
for face in faces:
|
38 |
+
shape = predictor(gray, face)
|
39 |
+
for i in range(68):
|
40 |
+
x = shape.part(i).x
|
41 |
+
y = shape.part(i).y
|
42 |
+
landmarks.append((x, y))
|
43 |
+
con_img = Image.new('RGB', (img.shape[1], img.shape[0]), color=(0, 0, 0))
|
44 |
+
draw_landmarks(con_img, landmarks)
|
45 |
+
con_img = np.array(con_img)
|
46 |
+
return con_img
|
47 |
+
|
48 |
+
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, landmark_direct_mode, strength, scale, seed, eta):
|
49 |
+
with torch.no_grad():
|
50 |
+
img = resize_image(HWC3(input_image), image_resolution)
|
51 |
+
H, W, C = img.shape
|
52 |
+
|
53 |
+
if landmark_direct_mode:
|
54 |
+
detected_map = img
|
55 |
+
else:
|
56 |
+
detected_map = get_68landmarks_img(img)
|
57 |
+
detected_map = HWC3(detected_map)
|
58 |
+
|
59 |
+
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
|
60 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
61 |
+
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
|
62 |
+
|
63 |
+
if seed == -1:
|
64 |
+
seed = random.randint(0, 65535)
|
65 |
+
seed_everything(seed)
|
66 |
+
|
67 |
+
if config.save_memory:
|
68 |
+
model.low_vram_shift(is_diffusing=False)
|
69 |
+
|
70 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
|
71 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
72 |
+
shape = (4, H // 8, W // 8)
|
73 |
+
|
74 |
+
if config.save_memory:
|
75 |
+
model.low_vram_shift(is_diffusing=True)
|
76 |
+
|
77 |
+
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
|
78 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
|
79 |
+
shape, cond, verbose=False, eta=eta,
|
80 |
+
unconditional_guidance_scale=scale,
|
81 |
+
unconditional_conditioning=un_cond)
|
82 |
+
|
83 |
+
if config.save_memory:
|
84 |
+
model.low_vram_shift(is_diffusing=False)
|
85 |
+
|
86 |
+
x_samples = model.decode_first_stage(samples)
|
87 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
88 |
+
|
89 |
+
results = [x_samples[i] for i in range(num_samples)]
|
90 |
+
return [255 - detected_map] + results
|
91 |
+
|
92 |
+
|
93 |
+
block = gr.Blocks().queue()
|
94 |
+
with block:
|
95 |
+
with gr.Row():
|
96 |
+
gr.Markdown("## Control Stable Diffusion with Face Landmarks")
|
97 |
+
with gr.Row():
|
98 |
+
with gr.Column():
|
99 |
+
input_image = gr.Image(source='upload', type="numpy")
|
100 |
+
prompt = gr.Textbox(label="Prompt")
|
101 |
+
run_button = gr.Button(label="Run")
|
102 |
+
with gr.Accordion("Advanced options", open=False):
|
103 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
|
104 |
+
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
|
105 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
106 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
107 |
+
landmark_direct_mode = gr.Checkbox(label='Input Landmark Directly', value=False)
|
108 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
|
109 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
110 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
|
111 |
+
eta = gr.Number(label="eta (DDIM)", value=0.0)
|
112 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
|
113 |
+
n_prompt = gr.Textbox(label="Negative Prompt",
|
114 |
+
value='cartoon, disfigured, bad art, deformed, poorly drawn, extra limbs, weird colors, blurry, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
|
115 |
+
with gr.Column():
|
116 |
+
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
|
117 |
+
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, landmark_direct_mode, strength, scale, seed, eta]
|
118 |
+
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
|
119 |
+
|
120 |
+
|
121 |
+
block.launch(server_name='0.0.0.0')
|