File size: 2,421 Bytes
4a0c367
 
 
 
16c392d
4a0c367
91865ff
5c58b46
13452b9
4a0c367
 
 
 
 
 
cd1a7a2
4a0c367
16c392d
5c58b46
16c392d
4a0c367
 
13452b9
16c392d
 
 
 
 
 
 
4a0c367
13452b9
16c392d
 
 
 
 
 
 
4a0c367
16c392d
4a0c367
16c392d
 
 
 
 
 
 
 
4a0c367
 
 
16c392d
 
 
be0884f
4a0c367
b073765
16c392d
 
 
 
 
 
 
 
b073765
 
16c392d
 
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
import os
import sys
import types
import cv2
import gradio as gr
import numpy as np
from gfpgan import GFPGANer
from huggingface_hub import hf_hub_download

# -------- Patch برای جلوگیری از ارور torchvision.transforms.functional_tensor --------
try:
    import torchvision.transforms.functional_tensor
except ModuleNotFoundError:
    # ساخت یک ماژول خالی به جای functional_tensor
    sys.modules['torchvision.transforms.functional_tensor'] = types.ModuleType('functional_tensor')

# -------- کش مدل‌ها --------
loaded_models = {}

def load_model(version):
    if version not in loaded_models:
        if version == "v1.4 (original)":
            model_path = hf_hub_download("leonelhs/gfpgan", "GFPGANv1.4.pth")
            loaded_models[version] = GFPGANer(
                model_path=model_path,
                upscale=1,
                arch='original',
                channel_multiplier=2,
                bg_upsampler=None
            )
        elif version == "v1.3 (clean)":
            model_path = hf_hub_download("leonelhs/gfpgan", "GFPGANv1.3.pth")
            loaded_models[version] = GFPGANer(
                model_path=model_path,
                upscale=1,
                arch='clean',
                channel_multiplier=2,
                bg_upsampler=None
            )
    return loaded_models[version]

# -------- تابع اصلی پردازش تصویر --------
def enhance_face(image, version):
    restorer = load_model(version)

    if isinstance(image, np.ndarray):
        img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    else:
        raise ValueError("Invalid image format")

    _, _, restored_img = restorer.enhance(
        img, has_aligned=False, only_center_face=False, paste_back=True
    )

    restored_img = cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
    return restored_img

# -------- رابط کاربری Gradio --------
iface = gr.Interface(
    fn=enhance_face,
    inputs=[
        gr.Image(type="numpy", label="Upload your Anime/Cartoon image"),
        gr.Radio(["v1.3 (clean)", "v1.4 (original)"], value="v1.4 (original)", label="Choose GFPGAN Version")
    ],
    outputs=gr.Image(type="numpy", label="Restored Cartoon Face"),
    title="Cartoon Face Restoration with GFPGAN",
    description="Upload a cartoonized image (e.g. from AnimeGAN) and restore it with GFPGAN."
)

if __name__ == "__main__":
    iface.launch()