File size: 4,678 Bytes
300ee94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# from https://github.com/lllyasviel/ControlNet/blob/main/gradio_canny2image.py

import einops
import numpy as np
import torch
from PIL import Image
import sys
import os
import yaml

CONTROL_NET_PATH = '/home/takuma/Documents/co/ControlNet-v1-1-nightly/'
CONTROL_NET_MODEL_PATH = '../../ControlNet-v1-1'
sys.path.append(CONTROL_NET_PATH)

from share import *
from pytorch_lightning import seed_everything
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
from diffusers.utils import load_image

test_prompt = "best quality, extremely detailed"
test_negative_prompt = "blur, lowres, bad anatomy, worst quality, low quality"

@torch.no_grad()
def generate(prompt, n_prompt, seed, control, image, ddim_steps=20, eta=0.0, scale=9.0, H=512, W=512, strength = 1.0, guess_mode=False, denoise_strength=1.0):
    seed_everything(seed)

    cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt] * num_samples)]}
    un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
    shape = (4, H // 8, W // 8)

    noise = torch.randn((1,) + shape, device="cpu", generator=torch.Generator(device="cpu").manual_seed(seed)).cuda()

    ddim_sampler.make_schedule(ddim_steps, ddim_eta=eta, verbose=True)
    t_enc = min(int(denoise_strength * ddim_steps), ddim_steps - 1)
    z = model.get_first_stage_encoding(model.encode_first_stage(image))
    z_enc = ddim_sampler.stochastic_encode(z, torch.tensor([t_enc] * num_samples).to(model.device), noise=noise)

    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

    samples = ddim_sampler.decode(z_enc, cond, t_enc, unconditional_guidance_scale=scale, unconditional_conditioning=un_cond)

    x_samples = model.decode_first_stage(samples)
    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)
 
    return Image.fromarray(x_samples[0])

def control_images(control_image_folder, model_name):
    with open('./control_images.yaml', 'r') as f:
        d = yaml.safe_load(f)
    filenames = d[model_name]
    return [Image.open(f'{control_image_folder}/{fn}').convert("RGB") for fn in filenames]

def resize_for_condition_image(input_image: Image, resolution: int):
    input_image = input_image.convert("RGB")
    W, H = input_image.size
    k = float(resolution) / min(H, W)
    H *= k
    W *= k
    H = int(round(H / 64.0)) * 64
    W = int(round(W / 64.0)) * 64
    img = input_image.resize((W, H), resample=Image.LANCZOS if k > 1 else Image.AREA)
    return img

if __name__ == '__main__':
    model_name = "f1e_sd15_tile"

    original_image_folder = "./control_images/"
    control_image_folder = './control_images/converted/'
    output_image_folder = './output_images/ref/'
    os.makedirs(output_image_folder, exist_ok=True)

    if model_name == 'p_sd15s2_lineart_anime':
        base_model_file = 'anything-v3-full.safetensors'
    else:
        base_model_file = 'v1-5-pruned.ckpt'

    num_samples = 1
    model = create_model(f'{CONTROL_NET_MODEL_PATH}/control_v11{model_name}.yaml').cpu()
    model.load_state_dict(load_state_dict(f'{CONTROL_NET_PATH}/models/{base_model_file}', location='cuda'), strict=False)
    model.load_state_dict(load_state_dict(f'{CONTROL_NET_MODEL_PATH}/control_v11{model_name}.pth', location='cuda'), strict=False)
    model = model.cuda()
    ddim_sampler = DDIMSampler(model)

    original_image_filenames = [
        "dog_64x64.png",
    ]

    image_conditions = [
        resize_for_condition_image(
            Image.open(f"{original_image_folder}{fn}"),
            resolution=512,
        )
        for fn in original_image_filenames
    ]


    for i, control_image in enumerate(image_conditions):
        control = np.array(control_image).copy()
        control = torch.from_numpy(control).float().cuda() / 255.0
        control = torch.stack([control for _ in range(num_samples)], dim=0)
        control = einops.rearrange(control, 'b h w c -> b c h w').clone()

        img = np.array(control_image).copy()
        img = torch.from_numpy(img).float().cuda() / 127.0 - 1.0
        img = torch.stack([img for _ in range(num_samples)], dim=0)
        img = einops.rearrange(img, 'b h w c -> b c h w').clone()

        for seed in range(4):
            image = generate(test_prompt, test_negative_prompt, seed=seed, control=control, image=img)
            image.save(f'{output_image_folder}output_{model_name}_{i}_{seed}.png')