File size: 6,553 Bytes
c59c099
 
 
 
 
 
 
 
8b2504d
 
 
f8f2937
8b2504d
 
c59c099
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b2504d
c59c099
8b2504d
c59c099
 
8b2504d
 
c59c099
 
 
 
8b2504d
 
 
 
 
c59c099
8b2504d
 
c59c099
8b2504d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c59c099
8b2504d
c59c099
 
 
 
8b2504d
c59c099
 
 
 
 
 
8b2504d
c59c099
8b2504d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff749ef
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import insightface
import os
import onnxruntime
import cv2
import gfpgan
import tempfile
import time
import gradio as gr
import sys
from torchvision.transforms import functional
from PIL import Image

# ์ฐธ์กฐ์ฝ”๋“œ์—์„œ ์‚ฌ์šฉ๋œ ๋ชจ๋“ˆ ์ž„ํฌํŠธ ์ˆ˜์ •
sys.modules["torchvision.transforms.functional_tensor"] = functional

class Predictor:
    def __init__(self):
        self.setup()

    def setup(self):
        os.makedirs('models', exist_ok=True)
        os.chdir('models')
        if not os.path.exists('GFPGANv1.4.pth'):
            os.system(
                'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth'
            )
        if not os.path.exists('inswapper_128.onnx'):
            os.system(
                'wget https://huggingface.co/ashleykleynhans/inswapper/resolve/main/inswapper_128.onnx'
            )
        os.chdir('..')  # ๋””๋ ‰ํ† ๋ฆฌ ๋ณ€๊ฒฝ ์™„๋ฃŒ

        """๐Ÿ’Ž Load the model into memory to make running multiple predictions efficient"""
        self.face_swapper = insightface.model_zoo.get_model('models/inswapper_128.onnx',
                                                            providers=onnxruntime.get_available_providers())
        # self.face_swapper.prepare(ctx_id=0, det_size=(640, 640))  # ์ด ์ค„์„ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.

        self.face_enhancer = gfpgan.GFPGANer(model_path='models/GFPGANv1.4.pth', upscale=1)
        self.face_analyser = insightface.app.FaceAnalysis(name='buffalo_l')
        self.face_analyser.prepare(ctx_id=0, det_size=(640, 640))

    def get_face_image(self, img_data, face):
        # ์–ผ๊ตด ์˜์—ญ์„ ์ž˜๋ผ๋‚ด๊ธฐ
        x1, y1, x2, y2 = [int(coord) for coord in face.bbox]
        face_img = img_data[y1:y2, x1:x2]
        return face_img

    def predict(self, input_image_path, swap_image_path):
        """๐Ÿงถ Run a single prediction on the model"""
        try:
            frame = cv2.imread(input_image_path)
            if frame is None:
                print("โŒ Target image could not be read.")
                return None
            analysed = self.face_analyser.get(frame)
            if not analysed:
                print("โŒ No face found in target image.")
                return None
            face = max(analysed, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))
            target_face_img = self.get_face_image(frame, face)

            swap_frame = cv2.imread(swap_image_path)
            if swap_frame is None:
                print("โŒ Swap image could not be read.")
                return None
            swap_analysed = self.face_analyser.get(swap_frame)
            if not swap_analysed:
                print("โŒ No face found in swap image.")
                return None
            swap_face = max(swap_analysed, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))
            swap_face_img = self.get_face_image(swap_frame, swap_face)

            # ์–ผ๊ตด ๊ต์ฒด ์ˆ˜ํ–‰
            result = self.face_swapper.get(frame, face, swap_face, paste_back=True)

            # ์–ผ๊ตด ํ–ฅ์ƒ ์ˆ˜ํ–‰
            _, _, result = self.face_enhancer.enhance(
                result,
                paste_back=True
            )
            out_path = os.path.join(tempfile.mkdtemp(), f"{str(int(time.time()))}.jpg")
            cv2.imwrite(out_path, result)
            return out_path
        except Exception as e:
            print(f"{e}")
            return None

# Predictor ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
predictor = Predictor()

# CSS ๋ฐ ํ…Œ๋งˆ ์„ค์ •
css = """
/* "Swap Faces" ๋ฒ„ํŠผ ์Šคํƒ€์ผ */
button#swap-button {
    background-color: #FB923C !important; /* ์ฃผํ™ฉ์ƒ‰ ๋ฐฐ๊ฒฝ */
    color: white !important; /* ํฐ์ƒ‰ ๊ธ€์”จ */
}
/* "์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ (JPG)" ๋ฒ„ํŠผ ์Šคํƒ€์ผ */
button#download-button {
    background-color: #FB923C !important; /* ์ฃผํ™ฉ์ƒ‰ ๋ฐฐ๊ฒฝ */
    color: white !important; /* ํฐ์ƒ‰ ๊ธ€์”จ */
}
/* ํ•„์š”์— ๋”ฐ๋ผ ์ถ”๊ฐ€์ ์ธ ์Šคํƒ€์ผ์„ ์—ฌ๊ธฐ์— ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค */
"""

demo_theme = gr.themes.Soft(
    primary_hue=gr.themes.Color(
        c50="#FFF7ED",
        c100="#FFEDD5",
        c200="#FED7AA",
        c300="#FDBA74",
        c400="#FB923C",
        c500="#F97316",
        c600="#EA580C",
        c700="#C2410C",
        c800="#9A3412",
        c900="#7C2D12",
        c950="#431407",
    ),
    secondary_hue="zinc",
    neutral_hue="zinc",
    font=("Pretendard", "sans-serif")
)

# JPG ๋‹ค์šด๋กœ๋“œ ๊ธฐ๋Šฅ ๊ตฌํ˜„
def save_as_jpg(file_path):
    try:
        if file_path is None:
            return None
        # ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ๋ฐ›์•„ PIL ์ด๋ฏธ์ง€๋กœ ๋ณ€ํ™˜
        img = Image.open(file_path)
        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
            img.save(tmp, format="JPEG")
            tmp_path = tmp.name
        return tmp_path  # ํŒŒ์ผ ๊ฒฝ๋กœ ๋ฐ˜ํ™˜
    except Exception as error:
        print(f"Error saving as JPG: {error}")
        return None

# Clear ํ•จ์ˆ˜: ์ž…๋ ฅ ๋ฐ ์ถœ๋ ฅ ์ดˆ๊ธฐํ™”
def clear_all():
    return [None, None, None]

# Gradio Interface ๊ตฌ์„ฑ
with gr.Blocks(theme=demo_theme, css=css) as demo:
    with gr.Row():
        # ์™ผ์ชฝ ์„น์…˜: ์ž…๋ ฅ
        with gr.Column(scale=1):
            target_image = gr.Image(
                type="filepath",
                label="์–ผ๊ตด์„ ๋ณ€๊ฒฝํ•  ์ด๋ฏธ์ง€"
            )
            swap_image = gr.Image(
                type="filepath",
                label="๊ต์ฒดํ•  ์–ผ๊ตด"
            )
            swap_button = gr.Button("์–ผ๊ตด ๊ต์ฒด", elem_id="swap-button")
            clear_button = gr.Button("๋ฆฌ์…‹ํ•˜๊ธฐ")
        
        # ์˜ค๋ฅธ์ชฝ ์„น์…˜: ์ถœ๋ ฅ
        with gr.Column(scale=1):
            result_image = gr.Image(
                type="filepath",
                label="๊ฒฐ๊ณผ ์ด๋ฏธ์ง€"
            )
            download_jpg_button = gr.Button("JPG๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ", elem_id="download-button")
            download_file = gr.File(label="JPG ์ด๋ฏธ์ง€ ๋‹ค์šด๋ฐ›๊ธฐ")
    
    # ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ ์˜ˆ์ธก ํ•จ์ˆ˜ ํ˜ธ์ถœ
    swap_button.click(
        fn=predictor.predict,
        inputs=[target_image, swap_image],
        outputs=result_image
    )

    # ๋ฆฌ์…‹ํ•˜๊ธฐ ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ ์ž…๋ ฅ ๋ฐ ์ถœ๋ ฅ ์ด๋ฏธ์ง€ ์ดˆ๊ธฐํ™”
    clear_button.click(
        fn=clear_all,
        inputs=None,
        outputs=[target_image, swap_image, result_image]
    )

    # JPG ๋‹ค์šด๋กœ๋“œ ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ ํŒŒ์ผ ์ƒ์„ฑ
    download_jpg_button.click(
        fn=save_as_jpg,
        inputs=result_image,
        outputs=download_file
    )

# Gradio Interface ์‹คํ–‰
demo.launch()