File size: 1,857 Bytes
a428dd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0783197
 
 
 
 
a428dd1
0783197
a428dd1
 
 
 
0783197
 
a428dd1
 
0783197
 
 
 
 
 
a428dd1
0783197
 
 
a428dd1
0783197
 
a428dd1
 
0783197
 
 
 
 
 
 
 
 
 
 
96e56d7
0783197
 
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
from huggingface_hub import hf_hub_url, hf_hub_download

import gradio as gr
import numpy as np
import requests

import torch
from torchvision import transforms
from torch.autograd import Variable

from PIL import Image

import warnings
warnings.filterwarnings('ignore')

# モデルのダウンロード
path_to_model = hf_hub_download(
    repo_id="opetrova/face-frontalization",
    filename="generator_v0.pt"
)

# network.py をカレントディレクトリにダウンロード
network_url = hf_hub_url(repo_id="opetrova/face-frontalization", filename="network.py")
r = requests.get(network_url, allow_redirects=True)
open('network.py', 'wb').write(r.content)

# PyTorch 2.6 以降は weights_only=False を指定しないとエラーになる
saved_model = torch.load(path_to_model, map_location=torch.device("cpu"), weights_only=False)

def frontalize(image):
    # 画像を [1, 3, 128, 128] tensor に変換
    preprocess = transforms.Compose((
        transforms.ToPILImage(),
        transforms.Resize(size=(128, 128)),
        transforms.ToTensor(),
    ))
    input_tensor = torch.unsqueeze(preprocess(image), 0)

    # 推論
    generated_image = saved_model(Variable(input_tensor.type(torch.FloatTensor)))
    generated_image = generated_image.detach().squeeze().permute(1, 2, 0).numpy()
    generated_image = (generated_image + 1.0) / 2.0  # [-1,1] → [0,1]

    return generated_image

# Gradio インターフェース
iface = gr.Interface(
    fn=frontalize,
    inputs=gr.Image(type="numpy"),
    outputs="image",
    title="Face Frontalization",
    description=(
        'PyTorch implementation of a supervised GAN '
        '(see <a href="https://blog.scaleway.com/gpu-instances-using-deep-learning-to-obtain-frontal-rendering-of-facial-images/">blog post</a>)'
    ),
    examples=["amos.png", "clarissa.png"],
)

iface.launch()