CoolFace
Apppublic

Harsha909/video-pose-normalization

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
gradio_scribble_interactive.py107 linesDownload Raw Back to root
1from share import *
2import config
3
4import einops
5import gradio as gr
6import numpy as np
7import torch
8import random
9
10from pytorch_lightning import seed_everything
11from annotator.util import resize_image, HWC3
12from cldm.model import create_model, load_state_dict
13from cldm.ddim_hacked import DDIMSampler
14
15
16preprocessor = None
17
18model_name = 'control_v11p_sd15_scribble'
19model = create_model(f'./models/{model_name}.yaml').cpu()
20model.load_state_dict(load_state_dict('./models/v1-5-pruned.ckpt', location='cuda'), strict=False)
21model.load_state_dict(load_state_dict(f'./models/{model_name}.pth', location='cuda'), strict=False)
22model = model.cuda()
23ddim_sampler = DDIMSampler(model)
24
25
26def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
27    with torch.no_grad():
28        img = resize_image(HWC3(input_image['mask'][:, :, 0]), image_resolution)
29        H, W, C = img.shape
30
31        detected_map = np.zeros_like(img, dtype=np.uint8)
32        detected_map[np.min(img, axis=2) > 127] = 255
33
34        control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
35        control = torch.stack([control for _ in range(num_samples)], dim=0)
36        control = einops.rearrange(control, 'b h w c -> b c h w').clone()
37
38        if seed == -1:
39            seed = random.randint(0, 65535)
40        seed_everything(seed)
41
42        if config.save_memory:
43            model.low_vram_shift(is_diffusing=False)
44
45        cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
46        un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
47        shape = (4, H // 8, W // 8)
48
49        if config.save_memory:
50            model.low_vram_shift(is_diffusing=True)
51
52        model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13)
53        # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
54
55        samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
56                                                     shape, cond, verbose=False, eta=eta,
57                                                     unconditional_guidance_scale=scale,
58                                                     unconditional_conditioning=un_cond)
59
60        if config.save_memory:
61            model.low_vram_shift(is_diffusing=False)
62
63        x_samples = model.decode_first_stage(samples)
64        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)
65
66        results = [x_samples[i] for i in range(num_samples)]
67    return [detected_map] + results
68
69
70def create_canvas(w, h):
71    return np.zeros(shape=(h, w, 3), dtype=np.uint8) + 255
72
73
74block = gr.Blocks().queue()
75with block:
76    with gr.Row():
77        gr.Markdown("## Control Stable Diffusion with Interactive Scribbles")
78    with gr.Row():
79        with gr.Column():
80            canvas_width = gr.Slider(label="Canvas Width", minimum=256, maximum=1024, value=512, step=1)
81            canvas_height = gr.Slider(label="Canvas Height", minimum=256, maximum=1024, value=512, step=1)
82            create_button = gr.Button(label="Start", value='Open drawing canvas!')
83            input_image = gr.Image(source='upload', type='numpy', tool='sketch')
84            gr.Markdown(value='Do not forget to change your brush width to make it thinner. '
85                              'Just click on the small pencil icon in the upper right corner of the above block.')
86            create_button.click(fn=create_canvas, inputs=[canvas_width, canvas_height], outputs=[input_image])
87            prompt = gr.Textbox(label="Prompt")
88            run_button = gr.Button(label="Run")
89            num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
90            seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, value=12345)
91            with gr.Accordion("Advanced options", open=False):
92                image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
93                strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
94                guess_mode = gr.Checkbox(label='Guess Mode', value=False)
95                ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
96                scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
97                eta = gr.Slider(label="DDIM ETA", minimum=0.0, maximum=1.0, value=1.0, step=0.01)
98                a_prompt = gr.Textbox(label="Added Prompt", value='best quality')
99                n_prompt = gr.Textbox(label="Negative Prompt", value='lowres, bad anatomy, bad hands, cropped, worst quality')
100        with gr.Column():
101            result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
102    ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
103    run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
104
105
106block.launch(server_name='0.0.0.0')
107