File size: 12,313 Bytes
e3af00f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import gc
import os
from pathlib import Path

import cv2
from PIL import Image
from tqdm import tqdm

from .preprocess_dir.utils import crop_with_fan as cwf
from .preprocess_dir.utils import face_finder as ff
from .util import *


# template video μ „μ²˜λ¦¬
# preprocess_template_old(κΈ°μ‘΄ν•¨μˆ˜) 와 κΈ°λŠ₯은 λ™μΌν•˜κ³ , λ©”λͺ¨λ¦¬ μ‚¬μš©λŸ‰ μ€„μž„
def preprocess_template(
    config_path,
    template_video_path,
    reference_face,
    work_root_path,
    device,
    template_frame_ratio=1.0,
    template_video_ratio=[1.0],
    callback=None,
    verbose=False,
    save_frames=True,
    silent_video_path=None,
    no_infer_frames=[],
):
    """template video μ „μ²˜λ¦¬

    Parameters
    ----------
    config_path (str) : μ„€μ •νŒŒμΌ 경둜
    template_video_path (str) : ν…œν”Œλ¦Ώ μ˜μƒ 경둜
    reference_face : (str) : μ°Έκ³ ν•  μ–Όκ΅΄ 이미지 경둜
    work_root_path (str) : μž‘μ—…ν΄λ” 경둜. μ „μ²˜λ¦¬ 정보가 μ €μž₯됨.
    device (str) : device 정보. ex) cuda:0
    template_frame_ratio (float) : ν…œν”Œλ¦Ώ λΉ„λ””μ˜€ resize λΉ„μœ¨. 1.0: μ˜μƒ κ·ΈλŒ€λ‘œ μ‚¬μš©
    template_video_ratio (list[float]) : ν…œν”Œλ¦Ώ λΉ„λ””μ˜€ resize λΉ„μœ¨. 1.0: μ˜μƒ κ·ΈλŒ€λ‘œ μ‚¬μš©
    save_frames (bool) : ν…œν”Œλ¦Ώ λΉ„λ””μ˜€ ν”„λ ˆμž„ μ €μž₯μ—¬λΆ€
    no_infer_frames (list[tuple[int,int]]) : 좔둠에 μ‚¬μš©λ˜μ§€ μ•ŠλŠ”frame ꡬ간. μ‹œμž‘μ€ 포함, 끝은 ν¬ν•¨λ˜μ§€ μ•ŠμŒ.
    """
    load_gpu = False

    config = read_config(config_path)

    image_size = config.img_size

    callback1 = callback_inter(
        callback, min_per=0, max_per=2, desc="preprocess_template 1", verbose=verbose
    )
    callback2 = callback_inter(
        callback, min_per=2, max_per=20, desc="preprocess_template 2", verbose=verbose
    )
    callback3 = callback_inter(
        callback, min_per=20, max_per=100, desc="preprocess_template 3", verbose=verbose
    )

    preprocess_dir = get_preprocess_dir(work_root_path, config.name)
    Path(preprocess_dir).mkdir(exist_ok=True, parents=True)
    # snow : for debug
    if verbose:
        print("preprocess_dir: ", preprocess_dir, ", work_root_path:", work_root_path)

    # μ „μ²˜λ¦¬ 파일 경둜
    crop_mp4 = get_crop_mp4_dir(preprocess_dir, template_video_path)

    if not Path(crop_mp4).exists():
        load_gpu = True

        ff.init_face_finder(device)
        cwf.init_fan(device)

        if verbose:
            print("ν…œν”Œλ¦Ώ λΉ„λ””μ˜€ 처리 ... ")

        # μ•„λ‚˜μš΄μ„œ μ–Όκ΅΄ 정보λ₯Ό κ΅¬ν•œλ‹€.
        df_face, imgs = ff.find_face(reference_face)
        callback1(100)  # μ§„ν–‰μœ¨μ„ μ•Œλ €μ€€λ‹€.

        g_anchor_ebd = df_face["ebd"].values[0]
        # ν…œν”Œλ¦Ώ λ™μ˜μƒμ—μ„œ μ•„λ‚˜μš΄μ„œ μ–Όκ΅΄ μœ„μΉ˜λ§Œ μ €μž₯ν•΄ λ†“λŠ”λ‹€
        df_paths = ff.save_face_info3(
            template_video_path,
            g_anchor_ebd,
            config.move,
            base=preprocess_dir,
            callback=callback2,
            verbose=verbose,
        )

        ### μ–Όκ΅΄ μ˜μ—­μ„ FAN λžœλ“œλ§ˆν¬ 기반으둜 크둭해 λ†“λŠ”λ‹€
        assert len(df_paths) == 1
        if config.move:
            if verbose:
                print("cwf.save_crop_info_move --")
            df_fan_path = cwf.save_crop_info_move(
                image_size=image_size,
                anchor_box_path=df_paths[0],
                mp4_path=template_video_path,
                out_dir=crop_mp4,
                crop_offset_y=config.crop_offset_y,
                crop_margin=config.crop_margin,
                callback=callback3,
                verbose=verbose,
            )
        else:
            if verbose:
                print("cwf.save_crop_info2 --")
            df_fan_path = cwf.save_crop_info2(
                image_size=image_size,
                anchor_box_path=df_paths[0],
                mp4_path=template_video_path,
                out_dir=crop_mp4,
                crop_offset_y=config.crop_offset_y,
                crop_margin=config.crop_margin,
                no_infer_frames=no_infer_frames,
                callback=callback3,
                verbose=verbose,
            )
        # snow : for debug
        if verbose:
            print("df_fan_path: ", df_fan_path)
        ff.del_face_finder()
        cwf.del_fan()
    else:
        if verbose:
            print("μ „μ²˜λ¦¬κ°€ 이미 λ˜μ–΄μžˆμŒ")
    callback3(100)

    # 1. save frames for stf
    if save_frames:
        frame_dir = get_frame_dir(
            preprocess_dir, template_video_path, ratio=template_frame_ratio
        )
        if verbose:
            print("frame_dir:", frame_dir)
        save_template_frames(
            template_video_path=template_video_path,
            template_frames_path=frame_dir,
            ratio=template_frame_ratio,
            save_in_video=False,
            verbose=verbose,
        )
        if silent_video_path is not None:
            frame_dir = get_frame_dir(
                preprocess_dir, silent_video_path, ratio=template_frame_ratio
            )
            save_template_frames(
                template_video_path=silent_video_path,
                template_frames_path=frame_dir,
                ratio=template_frame_ratio,
                save_in_video=False,
                verbose=verbose,
            )

    if template_video_path.endswith(".mov"):
        # TODO snow : μ„±λŠ₯ 확인 ν•„μš”.
        # μ§€κΈˆμ€ mov 인 경우만 νŒŒμΌμ„ μ €μž₯ν•œλ‹€. μΆ”λ‘ ν•  λ•Œ λŠλ €μ„œ 라고 ν•œλ‹€. by hojin

        # 2. save video for encoding
        for video_ratio in template_video_ratio:
            if video_ratio != 1.0:
                out_path = get_template_ratio_file_path(
                    preprocess_dir, template_video_path, ratio=video_ratio
                )
                save_template_frames(
                    template_video_path=template_video_path,
                    template_frames_path="",
                    template_video_path_with_ratio=out_path,
                    ratio=video_ratio,
                    save_in_video=True,
                    verbose=verbose,
                )
                if silent_video_path is not None:
                    out_path = get_template_ratio_file_path(
                        preprocess_dir, silent_video_path, ratio=video_ratio
                    )
                    save_template_webm_ratio(
                        template_video_path=silent_video_path,
                        ratio=video_ratio,
                        out_path=out_path,
                        verbose=verbose,
                    )

    if template_video_path.endswith(".webm"):
        # TODO snow : μ„±λŠ₯ 확인 ν•„μš”. ratio 개수만큼 webm 을 λ§Œλ“ λ‹€.
        for video_ratio in template_video_ratio:
            out_path = get_template_ratio_file_path(
                preprocess_dir, template_video_path, ratio=video_ratio
            )
            save_template_webm_ratio(
                template_video_path=template_video_path,
                ratio=video_ratio,
                out_path=out_path,
                verbose=verbose,
            )
            if silent_video_path is not None:
                out_path = get_template_ratio_file_path(
                    preprocess_dir, silent_video_path, ratio=video_ratio
                )
                save_template_webm_ratio(
                    template_video_path=silent_video_path,
                    ratio=video_ratio,
                    out_path=out_path,
                    verbose=verbose,
                )

    gc.collect()
    return load_gpu


# snow: webm ν…œν”Œλ¦Ώμ„ ratio λ³„λ‘œ resize ν•˜μ—¬ μ €μž₯ν•˜λŠ” ν•¨μˆ˜
def save_template_webm_ratio(template_video_path, ratio, out_path, verbose):
    def resize_(size, img):
        w, h = size
        img = cv2.resize(img, (w, h), inter_alg_(w, h, img))
        return img

    def inter_alg_(w, h, img):
        if w * h < img.shape[0] * img.shape[1]:
            return cv2.INTER_AREA
        else:
            return cv2.INTER_CUBIC

    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    reader, meta = get_four_channel_ffmpeg_reader(template_video_path)
    if Path(out_path).exists():
        if verbose:
            print(f"ratio 파일이 μ €μž₯λ˜μ–΄ 있음, {out_path}")
        return

    if verbose:
        print(f"webm ratio template, org:{template_video_path}, ratio:{ratio}")
    size_org = meta["size"]
    size = list(int(round(ratio * v)) // 2 * 2 for v in size_org)
    writer = get_webm_ffmpeg_writer(
        out_path, size=size, fps=meta["fps"], wav_path=template_video_path
    )
    writer.send(None)  # seed the generator

    total_cnt, _ = imageio_ffmpeg.count_frames_and_secs(template_video_path)
    for idx, f in tqdm(
        enumerate(reader), total=total_cnt, desc=f"save webm ratio:{ratio}, size:{size}"
    ):
        f = np.frombuffer(f, dtype=np.uint8)
        f = f.reshape(size_org[1], size_org[0], 4)
        f = resize_(size, f)
        writer.send(f)  # seed the generator
    writer.close()


# hojin
# png frame μΆ”μΆœ + crop
def save_template_frames(
    template_video_path,
    template_frames_path,
    template_video_path_with_ratio=None,
    ratio=1.0,
    save_in_video=False,
    verbose=False,
):
    def inter_alg_(w, h, img):
        if w * h < img.shape[0] * img.shape[1]:
            return cv2.INTER_AREA
        else:
            return cv2.INTER_CUBIC

    def resize_(size, img):
        w, h = size
        img = cv2.resize(img, (w, h), inter_alg_(w, h, img))
        return img

    # hojin: ν…œν”Œλ¦Ώμ„ ν”„λ ˆμž„λ³„λ‘œ μ €μž₯해두기 -> write_video_in_threadμ—μ„œ reader μ‚¬μš©ν•˜μ§€ μ•ŠκΈ° μœ„ν•¨
    if save_in_video == False:
        if Path(template_frames_path).exists():
            if verbose:
                print("ν”„λ ˆμž„μ΄ λͺ¨λ‘ μ €μž₯λ˜μ–΄ 있음")
            return
    else:
        if Path(template_video_path_with_ratio).exists():
            if verbose:
                print("λΉ„λ””μ˜€κ°€ μƒμ„±λ˜μ–΄ 있음")
            return
        os.makedirs(os.path.dirname(template_video_path_with_ratio), exist_ok=True)

    if template_video_path.endswith(".mov") or template_video_path.endswith(".webm"):
        reader, meta = get_four_channel_ffmpeg_reader(template_video_path)
    else:  # mp4
        reader, meta = get_three_channel_ffmpeg_reader(template_video_path)
    size_org = meta["size"]
    size = list(int(round(ratio * v)) // 2 * 2 for v in size_org)
    fps = meta["fps"]
    if verbose:
        print(meta)

    total_cnt, _ = imageio_ffmpeg.count_frames_and_secs(template_video_path)

    if save_in_video is False:
        Path(template_frames_path).mkdir(exist_ok=True, parents=True)

    # hojin: μΆ”μΆœν•œ ν”„λ ˆμž„μ„ 내보내기λ₯Ό μœ„ν•΄μ„œ λ‹€μ‹œ mov둜 λ§Œλ“€μ–΄λ†“κΈ° (ratio<1.0)
    writer = None

    if verbose:
        print("template_frames_path: ", template_frames_path)
    for idx, f in tqdm(
        enumerate(reader),
        total=total_cnt,
        desc=f"save frames f{ratio}"
        if save_in_video is False
        else f"save video f{ratio}",
    ):
        name = f"""{idx:05d}.webp"""
        f = np.frombuffer(f, dtype=np.uint8)
        f = f.reshape(
            size_org[1], size_org[0], 3 if template_video_path.endswith(".mp4") else 4
        )
        f = resize_(size, f)
        if save_in_video is False:
            f = np.ascontiguousarray(f)
            f = Image.fromarray(
                f, mode="RGB" if template_video_path.endswith(".mp4") else "RGBA"
            )
            f.save(
                str(Path(template_frames_path) / str(name)), format="png", lossless=True
            )
            # cv2.imwrite(str(Path(template_frames_path) / str(name)), f[:, :, [2, 1, 0, 3]], [int(cv2.IMWRITE_PNG_COMPRESSION), 3])

        if writer is None and save_in_video is True:
            if ratio != 1.0:
                writer = imageio_ffmpeg.write_frames(
                    template_video_path_with_ratio,
                    size=size,
                    fps=fps,
                    quality=10,
                    pix_fmt_in="rgba",
                    pix_fmt_out="rgba",
                    codec="png",
                    macro_block_size=1,
                )
                writer.send(None)

        if writer:
            writer.send(f)

    if writer:
        writer.close()


# hojin end