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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
import yaml
|
| 6 |
+
import einops
|
| 7 |
+
|
| 8 |
+
from omegaconf import OmegaConf
|
| 9 |
+
from modules_forge.supported_preprocessor import Preprocessor, PreprocessorParameter
|
| 10 |
+
from modules_forge.utils import numpy_to_pytorch, resize_image_with_pad
|
| 11 |
+
from modules_forge.shared import preprocessor_dir, add_supported_preprocessor
|
| 12 |
+
from modules.modelloader import load_file_from_url
|
| 13 |
+
from annotator.lama.saicinpainting.training.trainers import load_checkpoint
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class PreprocessorInpaint(Preprocessor):
|
| 17 |
+
def __init__(self):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.name = 'inpaint_global_harmonious'
|
| 20 |
+
self.tags = ['Inpaint']
|
| 21 |
+
self.model_filename_filters = ['inpaint']
|
| 22 |
+
self.slider_resolution = PreprocessorParameter(visible=False)
|
| 23 |
+
self.fill_mask_with_one_when_resize_and_fill = True
|
| 24 |
+
self.expand_mask_when_resize_and_fill = True
|
| 25 |
+
|
| 26 |
+
def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
|
| 27 |
+
mask = mask.round()
|
| 28 |
+
mixed_cond = cond * (1.0 - mask) - mask
|
| 29 |
+
return mixed_cond, None
|
| 30 |
+
|
| 31 |
+
class PreprocessorInpaintNoobAIXL(Preprocessor):
|
| 32 |
+
def __init__(self):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.name = 'inpaint_noobai_xl'
|
| 35 |
+
self.tags = ['Inpaint']
|
| 36 |
+
self.model_filename_filters = ['inpaint', 'noobai']
|
| 37 |
+
self.slider_resolution = PreprocessorParameter(visible=False)
|
| 38 |
+
self.fill_mask_with_one_when_resize_and_fill = True
|
| 39 |
+
self.expand_mask_when_resize_and_fill = True
|
| 40 |
+
|
| 41 |
+
def __call__(self, input_image, resolution=512, slider_1=None, slider_2=None, slider_3=None, input_mask=None, **kwargs):
|
| 42 |
+
if input_mask is None:
|
| 43 |
+
return input_image
|
| 44 |
+
|
| 45 |
+
if not isinstance(input_image, np.ndarray):
|
| 46 |
+
input_image = np.array(input_image)
|
| 47 |
+
if not isinstance(input_mask, np.ndarray):
|
| 48 |
+
input_mask = np.array(input_mask)
|
| 49 |
+
|
| 50 |
+
mask = input_mask.astype(np.float32) / 255.0
|
| 51 |
+
mask = (mask > 0.5).astype(np.float32)
|
| 52 |
+
|
| 53 |
+
# Create a copy of the input image
|
| 54 |
+
result = input_image.copy()
|
| 55 |
+
|
| 56 |
+
# Convert mask to proper shape if needed
|
| 57 |
+
if mask.ndim == 2:
|
| 58 |
+
mask = np.expand_dims(mask, axis=-1)
|
| 59 |
+
if mask.shape[-1] == 1:
|
| 60 |
+
mask = np.repeat(mask, 3, axis=-1)
|
| 61 |
+
|
| 62 |
+
mask_indices = mask > 0.5
|
| 63 |
+
result[mask_indices] = 0.0
|
| 64 |
+
|
| 65 |
+
return result
|
| 66 |
+
|
| 67 |
+
def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
|
| 68 |
+
mask = mask.round()
|
| 69 |
+
mixed_cond = cond.clone()
|
| 70 |
+
mixed_cond = mixed_cond * (1.0 - mask)
|
| 71 |
+
|
| 72 |
+
return mixed_cond, None
|
| 73 |
+
class PreprocessorInpaintOnly(PreprocessorInpaint):
|
| 74 |
+
def __init__(self):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.name = 'inpaint_only'
|
| 77 |
+
self.image = None
|
| 78 |
+
self.mask = None
|
| 79 |
+
self.latent = None
|
| 80 |
+
|
| 81 |
+
def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
|
| 82 |
+
mask = mask.round()
|
| 83 |
+
self.image = cond
|
| 84 |
+
self.mask = mask
|
| 85 |
+
|
| 86 |
+
vae = process.sd_model.forge_objects.vae
|
| 87 |
+
# This is a powerful VAE with integrated memory management, bf16, and tiled fallback.
|
| 88 |
+
|
| 89 |
+
latent_image = vae.encode(self.image.movedim(1, -1))
|
| 90 |
+
latent_image = process.sd_model.forge_objects.vae.first_stage_model.process_in(latent_image)
|
| 91 |
+
|
| 92 |
+
B, C, H, W = latent_image.shape
|
| 93 |
+
|
| 94 |
+
latent_mask = self.mask
|
| 95 |
+
latent_mask = torch.nn.functional.interpolate(latent_mask, size=(H * 8, W * 8), mode="bilinear").round()
|
| 96 |
+
latent_mask = torch.nn.functional.max_pool2d(latent_mask, (8, 8)).round().to(latent_image)
|
| 97 |
+
|
| 98 |
+
unet = process.sd_model.forge_objects.unet.clone()
|
| 99 |
+
|
| 100 |
+
def pre_cfg(model, c, uc, x, timestep, model_options):
|
| 101 |
+
noisy_latent = latent_image.to(x) + timestep[:, None, None, None].to(x) * torch.randn_like(latent_image).to(x)
|
| 102 |
+
x = x * latent_mask.to(x) + noisy_latent.to(x) * (1.0 - latent_mask.to(x))
|
| 103 |
+
return model, c, uc, x, timestep, model_options
|
| 104 |
+
|
| 105 |
+
def post_cfg(args):
|
| 106 |
+
denoised = args['denoised']
|
| 107 |
+
denoised = denoised * latent_mask.to(denoised) + latent_image.to(denoised) * (1.0 - latent_mask.to(denoised))
|
| 108 |
+
return denoised
|
| 109 |
+
|
| 110 |
+
unet.add_sampler_pre_cfg_function(pre_cfg)
|
| 111 |
+
unet.set_model_sampler_post_cfg_function(post_cfg)
|
| 112 |
+
|
| 113 |
+
process.sd_model.forge_objects.unet = unet
|
| 114 |
+
|
| 115 |
+
self.latent = latent_image
|
| 116 |
+
|
| 117 |
+
mixed_cond = cond * (1.0 - mask) - mask
|
| 118 |
+
|
| 119 |
+
return mixed_cond, None
|
| 120 |
+
|
| 121 |
+
def process_after_every_sampling(self, process, params, *args, **kwargs):
|
| 122 |
+
a1111_batch_result = args[0]
|
| 123 |
+
new_results = []
|
| 124 |
+
|
| 125 |
+
for img in a1111_batch_result.images:
|
| 126 |
+
sigma = 7
|
| 127 |
+
mask = self.mask[0, 0].detach().cpu().numpy().astype(np.float32)
|
| 128 |
+
mask = cv2.dilate(mask, np.ones((sigma, sigma), dtype=np.uint8))
|
| 129 |
+
mask = cv2.blur(mask, (sigma, sigma))[None]
|
| 130 |
+
mask = torch.from_numpy(np.ascontiguousarray(mask).copy()).to(img).clip(0, 1)
|
| 131 |
+
raw = self.image[0].to(img).clip(0, 1)
|
| 132 |
+
img = img.clip(0, 1)
|
| 133 |
+
new_results.append(raw * (1.0 - mask) + img * mask)
|
| 134 |
+
|
| 135 |
+
a1111_batch_result.images = new_results
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class PreprocessorInpaintLama(PreprocessorInpaintOnly):
|
| 140 |
+
def __init__(self):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.name = 'inpaint_only+lama'
|
| 143 |
+
|
| 144 |
+
def load_model(self):
|
| 145 |
+
remote_model_path = "https://huggingface.co/lllyasviel/Annotators/resolve/main/ControlNetLama.pth"
|
| 146 |
+
model_path = load_file_from_url(remote_model_path, model_dir=preprocessor_dir)
|
| 147 |
+
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lama_config.yaml')
|
| 148 |
+
cfg = yaml.safe_load(open(config_path, 'rt'))
|
| 149 |
+
cfg = OmegaConf.create(cfg)
|
| 150 |
+
cfg.training_model.predict_only = True
|
| 151 |
+
cfg.visualizer.kind = 'noop'
|
| 152 |
+
model = load_checkpoint(cfg, os.path.abspath(model_path), strict=False, map_location='cpu')
|
| 153 |
+
self.setup_model_patcher(model)
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
def __call__(self, input_image, resolution, slider_1=None, slider_2=None, slider_3=None, input_mask=None, **kwargs):
|
| 157 |
+
if input_mask is None:
|
| 158 |
+
return input_image
|
| 159 |
+
|
| 160 |
+
H, W, C = input_image.shape
|
| 161 |
+
raw_color = input_image.copy()
|
| 162 |
+
raw_mask = input_mask.copy()
|
| 163 |
+
|
| 164 |
+
input_image, remove_pad = resize_image_with_pad(input_image, 256)
|
| 165 |
+
input_mask, remove_pad = resize_image_with_pad(input_mask, 256)
|
| 166 |
+
input_mask = input_mask[..., :1]
|
| 167 |
+
|
| 168 |
+
self.load_model()
|
| 169 |
+
|
| 170 |
+
self.move_all_model_patchers_to_gpu()
|
| 171 |
+
|
| 172 |
+
color = np.ascontiguousarray(input_image).astype(np.float32) / 255.0
|
| 173 |
+
mask = np.ascontiguousarray(input_mask).astype(np.float32) / 255.0
|
| 174 |
+
with torch.no_grad():
|
| 175 |
+
color = self.send_tensor_to_model_device(torch.from_numpy(color))
|
| 176 |
+
mask = self.send_tensor_to_model_device(torch.from_numpy(mask))
|
| 177 |
+
mask = (mask > 0.5).float()
|
| 178 |
+
color = color * (1 - mask)
|
| 179 |
+
image_feed = torch.cat([color, mask], dim=2)
|
| 180 |
+
image_feed = einops.rearrange(image_feed, 'h w c -> 1 c h w')
|
| 181 |
+
prd_color = self.model_patcher.model(image_feed)[0]
|
| 182 |
+
prd_color = einops.rearrange(prd_color, 'c h w -> h w c')
|
| 183 |
+
prd_color = prd_color * mask + color * (1 - mask)
|
| 184 |
+
prd_color *= 255.0
|
| 185 |
+
prd_color = prd_color.detach().cpu().numpy().clip(0, 255).astype(np.uint8)
|
| 186 |
+
|
| 187 |
+
prd_color = remove_pad(prd_color)
|
| 188 |
+
prd_color = cv2.resize(prd_color, (W, H))
|
| 189 |
+
|
| 190 |
+
alpha = raw_mask.astype(np.float32) / 255.0
|
| 191 |
+
fin_color = prd_color.astype(np.float32) * alpha + raw_color.astype(np.float32) * (1 - alpha)
|
| 192 |
+
fin_color = fin_color.clip(0, 255).astype(np.uint8)
|
| 193 |
+
|
| 194 |
+
return fin_color
|
| 195 |
+
|
| 196 |
+
def process_before_every_sampling(self, process, cond, mask, *args, **kwargs):
|
| 197 |
+
cond, mask = super().process_before_every_sampling(process, cond, mask, *args, **kwargs)
|
| 198 |
+
sigma_max = process.sd_model.forge_objects.unet.model.predictor.sigma_max
|
| 199 |
+
original_noise = kwargs['noise']
|
| 200 |
+
process.modified_noise = original_noise + self.latent.to(original_noise) / sigma_max.to(original_noise)
|
| 201 |
+
return cond, mask
|
| 202 |
+
|
| 203 |
+
add_supported_preprocessor(PreprocessorInpaintNoobAIXL())
|
| 204 |
+
|
| 205 |
+
add_supported_preprocessor(PreprocessorInpaint())
|
| 206 |
+
|
| 207 |
+
add_supported_preprocessor(PreprocessorInpaintOnly())
|
| 208 |
+
|
| 209 |
+
add_supported_preprocessor(PreprocessorInpaintLama())
|