animegan2-pytorch/hubconf.py

64 lines
1.8 KiB
Python
Raw Permalink Normal View History

2021-11-06 21:12:06 +01:00
import torch
2021-11-06 21:51:14 +01:00
def generator(pretrained=True, device="cpu", progress=True, check_hash=True):
2021-11-06 22:01:52 +01:00
from model import Generator
2021-11-07 07:12:44 +01:00
release_url = "https://github.com/bryandlee/animegan2-pytorch/raw/main/weights"
2021-11-06 21:48:30 +01:00
known = {
name: f"{release_url}/{name}.pt"
for name in [
2021-11-06 22:01:52 +01:00
'celeba_distill', 'face_paint_512_v1', 'face_paint_512_v2', 'paprika'
2021-11-06 21:48:30 +01:00
]
}
2021-11-06 21:23:03 +01:00
device = torch.device(device)
model = Generator().to(device)
2021-11-06 21:20:24 +01:00
2021-11-06 21:12:06 +01:00
if type(pretrained) == str:
2021-11-06 21:48:30 +01:00
# Look if a known name is passed, otherwise assume it's a URL
ckpt_url = known.get(pretrained, pretrained)
2021-11-06 21:12:06 +01:00
pretrained = True
else:
2021-11-06 21:48:30 +01:00
ckpt_url = known.get('face_paint_512_v2')
2021-11-06 21:12:06 +01:00
if pretrained is True:
state_dict = torch.hub.load_state_dict_from_url(
ckpt_url,
2021-11-06 21:23:03 +01:00
map_location=device,
2021-11-06 21:12:06 +01:00
progress=progress,
check_hash=check_hash,
)
model.load_state_dict(state_dict)
2021-11-06 21:20:24 +01:00
2021-11-06 21:51:14 +01:00
return model
2021-11-06 22:01:52 +01:00
def face2paint(device="cpu", size=512):
2021-11-06 21:51:14 +01:00
from PIL import Image
from torchvision.transforms.functional import to_tensor, to_pil_image
def face2paint(
model: torch.nn.Module,
img: Image.Image,
2021-11-06 22:01:52 +01:00
size: int = size,
2021-11-06 21:51:14 +01:00
side_by_side: bool = True,
device: str = device,
) -> Image.Image:
w, h = img.size
s = min(w, h)
img = img.crop(((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2))
img = img.resize((size, size), Image.LANCZOS)
2021-11-06 22:01:52 +01:00
with torch.no_grad():
input = to_tensor(img).unsqueeze(0) * 2 - 1
output = model(input.to(device)).cpu()[0]
2021-11-06 21:51:14 +01:00
2021-11-06 22:01:52 +01:00
if side_by_side:
output = torch.cat([input[0], output], dim=2)
2021-11-06 21:51:14 +01:00
2021-11-06 22:01:52 +01:00
output = (output * 0.5 + 0.5).clip(0, 1)
2021-11-06 21:51:14 +01:00
return to_pil_image(output)
return face2paint