File size: 8,955 Bytes
2de3774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import os
import sys
import cv2
import re
from shared import path_manager
import modules.async_worker as worker
from tqdm import tqdm

from modules.util import generate_temp_filename

from PIL import Image
import imageio.v3 as iio
import numpy as np
import torch
import insightface

from importlib.abc import MetaPathFinder, Loader
from importlib.util import spec_from_loader, module_from_spec

class ImportRedirector(MetaPathFinder):
    def __init__(self, redirect_map):
        self.redirect_map = redirect_map

    def find_spec(self, fullname, path, target=None):
        if fullname in self.redirect_map:
            return spec_from_loader(fullname, ImportLoader(self.redirect_map[fullname]))
        return None

class ImportLoader(Loader):
    def __init__(self, redirect):
        self.redirect = redirect

    def create_module(self, spec):
        return None

    def exec_module(self, module):
        import importlib
        redirected = importlib.import_module(self.redirect)
        module.__dict__.update(redirected.__dict__)

# Set up the redirection
redirect_map = {
    'torchvision.transforms.functional_tensor': 'torchvision.transforms.functional'
}

sys.meta_path.insert(0, ImportRedirector(redirect_map))

import gfpgan
from facexlib.utils.face_restoration_helper import FaceRestoreHelper

# Requirements:
# insightface==0.7.3
# onnxruntime-gpu==1.16.1
# gfpgan==1.3.8
#
# add to settings/powerup.json
#
#  "Faceswap": {
#    "type": "faceswap"
#  }
#
# Models in models/faceswap/
# https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth
# and inswapper_128.onnx from where you can find it

class pipeline:
    pipeline_type = ["faceswap"]

    analyser_model = None
    analyser_hash = ""
    swapper_model = None
    swapper_hash = ""
    gfpgan_model = None

    def parse_gen_data(self, gen_data):
        gen_data["original_image_number"] = gen_data["image_number"]
        gen_data["image_number"] = 1
        gen_data["show_preview"] = False
        return gen_data

    def load_base_model(self, name):
        model_name = "inswapper_128.onnx"
        if not self.swapper_hash == model_name:
            print(f"Loading swapper model: {model_name}")
            model_path = os.path.join(path_manager.model_paths["faceswap_path"], model_name)
            try:
                with open(os.devnull, "w") as sys.stdout:
                    self.swapper_model = insightface.model_zoo.get_model(
                        model_path,
                        download=False,
                        download_zip=False,
                    )
                    self.swapper_hash = model_name
                sys.stdout = sys.__stdout__
            except:
                print(f"Failed loading model! {model_path}")

        model_name = "buffalo_l"
        det_thresh = 0.5
        if not self.analyser_hash == model_name:
            print(f"Loading analyser model: {model_name}")
            try:
                with open(os.devnull, "w") as sys.stdout:
                    self.analyser_model = insightface.app.FaceAnalysis(name=model_name)
                    self.analyser_model.prepare(
                        ctx_id=0, det_thresh=det_thresh, det_size=(640, 640)
                    )
                    self.analyser_hash = model_name
                sys.stdout = sys.__stdout__
            except:
                print(f"Failed loading model! {model_name}")

    def load_gfpgan_model(self):
        if self.gfpgan_model is None:
            channel_multiplier = 2

            model_name = "GFPGANv1.4.pth"
            model_path = os.path.join(path_manager.model_paths["faceswap_path"], model_name)

            # https://github.com/TencentARC/GFPGAN/blob/master/inference_gfpgan.py
            self.gfpgan_model = gfpgan.GFPGANer
            self.gfpgan_model.bg_upsampler = None
            # initialize model
            self.gfpgan_model.device = torch.device(
                "cuda" if torch.cuda.is_available() else "cpu"
            )

            upscale = 2
            self.gfpgan_model.face_helper = FaceRestoreHelper(
                upscale,
                det_model="retinaface_resnet50",
                model_rootpath=path_manager.model_paths["faceswap_path"],
            )
            # face_size=512,
            # crop_ratio=(1, 1),
            # save_ext='png',
            # use_parse=True,
            # device=self.device,

            self.gfpgan_model.gfpgan = gfpgan.GFPGANv1Clean(
                out_size=512,
                num_style_feat=512,
                channel_multiplier=channel_multiplier,
                decoder_load_path=None,
                fix_decoder=False,
                num_mlp=8,
                input_is_latent=True,
                different_w=True,
                narrow=1,
                sft_half=True,
            )

            loadnet = torch.load(model_path)
            if "params_ema" in loadnet:
                keyname = "params_ema"
            else:
                keyname = "params"
            self.gfpgan_model.gfpgan.load_state_dict(loadnet[keyname], strict=True)
            self.gfpgan_model.gfpgan.eval()
            self.gfpgan_model.gfpgan = self.gfpgan_model.gfpgan.to(
                self.gfpgan_model.device
            )

    def load_keywords(self, lora):
        return ""

    def load_loras(self, loras):
        return

    def refresh_controlnet(self, name=None):
        return

    def clean_prompt_cond_caches(self):
        return

    def swap_faces(self, original_image, input_faces, out_faces):
        idx = 0
        for out_face in out_faces:
            original_image = self.swapper_model.get(
                original_image,
                out_face,
                input_faces[idx % len(input_faces)],
                paste_back=True,
            )
            idx += 1
        return original_image

    def restore_faces(self, image):
        self.load_gfpgan_model()

        image_bgr = image[:, :, ::-1]
        _cropped_faces, _restored_faces, gfpgan_output_bgr = self.gfpgan_model.enhance(
            self.gfpgan_model,
            image_bgr,
            has_aligned=False,
            only_center_face=False,
            paste_back=True,
            weight=0.5,
        )
        image = gfpgan_output_bgr[:, :, ::-1]

        return image

    def process(
        self,
        gen_data=None,
        callback=None,
    ):
        worker.add_result(
            gen_data["task_id"],
            "preview",
            (-1, f"Generating ...", None)
        )

        input_image = gen_data["input_image"]
        input_image = cv2.cvtColor(np.asarray(input_image), cv2.COLOR_RGB2BGR)
        input_faces = sorted(
            self.analyser_model.get(input_image), key=lambda x: x.bbox[0]
        )

        prompt = gen_data["prompt"].strip()
        if re.fullmatch("https?://.*\.gif", prompt, re.IGNORECASE) is not None:
            x = iio.immeta(prompt)
            duration = x["duration"]
            loop = x["loop"]
            gif = cv2.VideoCapture(prompt)

            # Swap
            in_imgs = []
            out_imgs = []
            while True:
                ret, frame = gif.read()
                if not ret:
                    break
                in_imgs.append(frame)

            with tqdm(total=len(in_imgs), desc="Groop", unit="frames") as progress:
                i=0
                steps=len(in_imgs)
                for frame in in_imgs:
                    out_faces = sorted(
                        self.analyser_model.get(frame), key=lambda x: x.bbox[0]
                    )
                    frame = self.swap_faces(frame, input_faces, out_faces)
                    out_imgs.append(
                        Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
                    )
                    i+=1
                    callback(i, 0, 0, steps, out_imgs[-1])
                    progress.update(1)
            images = generate_temp_filename(
                folder=path_manager.model_paths["temp_outputs_path"], extension="gif"
            )
            os.makedirs(os.path.dirname(images), exist_ok=True)
            out_imgs[0].save(
                images,
                save_all=True,
                append_images=out_imgs[1:],
                optimize=True,
                duration=duration,
                loop=loop,
            )
        else:
            output_image = cv2.imread(gen_data["main_view"])
            if output_image is None:
                images = "html/error.png"
            else:
                output_faces = sorted(
                    self.analyser_model.get(output_image), key=lambda x: x.bbox[0]
                )
                result_image = self.swap_faces(output_image, input_faces, output_faces)
                result_image = self.restore_faces(result_image)
                images = Image.fromarray(cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB))

        return [images]