2023-08-30 15:30:11 +02:00
|
|
|
import PIL.Image
|
|
|
|
import cv2
|
|
|
|
import numpy as np
|
|
|
|
import torch
|
|
|
|
|
2024-01-05 09:38:55 +01:00
|
|
|
from iopaint.const import KANDINSKY22_NAME
|
2024-01-05 09:40:06 +01:00
|
|
|
from .base import DiffusionInpaintModel
|
2024-01-05 08:19:23 +01:00
|
|
|
from iopaint.schema import InpaintRequest
|
2023-08-30 15:30:11 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Kandinsky(DiffusionInpaintModel):
|
|
|
|
pad_mod = 64
|
|
|
|
min_size = 512
|
|
|
|
|
|
|
|
def init_model(self, device: torch.device, **kwargs):
|
|
|
|
from diffusers import AutoPipelineForInpainting
|
|
|
|
|
|
|
|
fp16 = not kwargs.get("no_half", False)
|
|
|
|
use_gpu = device == torch.device("cuda") and torch.cuda.is_available()
|
|
|
|
torch_dtype = torch.float16 if use_gpu and fp16 else torch.float32
|
|
|
|
|
|
|
|
model_kwargs = {
|
|
|
|
"torch_dtype": torch_dtype,
|
|
|
|
}
|
|
|
|
|
|
|
|
self.model = AutoPipelineForInpainting.from_pretrained(
|
2023-12-27 15:00:07 +01:00
|
|
|
self.name, **model_kwargs
|
2023-08-30 15:30:11 +02:00
|
|
|
).to(device)
|
2024-01-08 14:49:18 +01:00
|
|
|
if torch.backends.mps.is_available():
|
|
|
|
self.model.enable_attention_slicing()
|
2023-08-30 15:30:11 +02:00
|
|
|
|
|
|
|
self.callback = kwargs.pop("callback", None)
|
|
|
|
|
2023-12-30 16:36:44 +01:00
|
|
|
def forward(self, image, mask, config: InpaintRequest):
|
2023-08-30 15:30:11 +02:00
|
|
|
"""Input image and output image have same size
|
|
|
|
image: [H, W, C] RGB
|
|
|
|
mask: [H, W, 1] 255 means area to repaint
|
|
|
|
return: BGR IMAGE
|
|
|
|
"""
|
2024-01-02 07:34:36 +01:00
|
|
|
self.set_scheduler(config)
|
2023-08-30 15:30:11 +02:00
|
|
|
|
|
|
|
generator = torch.manual_seed(config.sd_seed)
|
|
|
|
mask = mask.astype(np.float32) / 255
|
|
|
|
img_h, img_w = image.shape[:2]
|
|
|
|
|
2023-11-14 07:02:10 +01:00
|
|
|
# kandinsky 没有 strength
|
2023-08-30 15:30:11 +02:00
|
|
|
output = self.model(
|
|
|
|
prompt=config.prompt,
|
|
|
|
negative_prompt=config.negative_prompt,
|
|
|
|
image=PIL.Image.fromarray(image),
|
|
|
|
mask_image=mask[:, :, 0],
|
|
|
|
height=img_h,
|
|
|
|
width=img_w,
|
|
|
|
num_inference_steps=config.sd_steps,
|
|
|
|
guidance_scale=config.sd_guidance_scale,
|
|
|
|
output_type="np",
|
2024-01-02 10:13:11 +01:00
|
|
|
callback_on_step_end=self.callback,
|
2023-11-14 07:02:10 +01:00
|
|
|
generator=generator,
|
2023-08-30 15:30:11 +02:00
|
|
|
).images[0]
|
|
|
|
|
|
|
|
output = (output * 255).round().astype("uint8")
|
|
|
|
output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR)
|
|
|
|
return output
|
|
|
|
|
|
|
|
|
|
|
|
class Kandinsky22(Kandinsky):
|
2024-01-05 09:38:55 +01:00
|
|
|
name = KANDINSKY22_NAME
|