yerang commited on
Commit
db97da0
·
verified ·
1 Parent(s): e86dc78

Create stf_utils.py

Browse files
Files changed (1) hide show
  1. stf_utils.py +199 -0
stf_utils.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from pydub import AudioSegment
5
+ import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False)
6
+ from pathlib import Path
7
+ import subprocess
8
+ from pathlib import Path
9
+ import av
10
+ import imageio
11
+ import numpy as np
12
+ from rich.progress import track
13
+ from tqdm import tqdm
14
+
15
+ import stf_alternative
16
+ import os.path as osp
17
+ import shutil
18
+ import zipfile
19
+
20
+
21
+
22
+ def exec_cmd(cmd):
23
+ subprocess.run(
24
+ cmd, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
25
+ )
26
+
27
+
28
+ def images2video(images, wfp, **kwargs):
29
+ fps = kwargs.get("fps", 24)
30
+ video_format = kwargs.get("format", "mp4") # default is mp4 format
31
+ codec = kwargs.get("codec", "libx264") # default is libx264 encoding
32
+ quality = kwargs.get("quality") # video quality
33
+ pixelformat = kwargs.get("pixelformat", "yuv420p") # video pixel format
34
+ image_mode = kwargs.get("image_mode", "rgb")
35
+ macro_block_size = kwargs.get("macro_block_size", 2)
36
+ ffmpeg_params = ["-crf", str(kwargs.get("crf", 18))]
37
+
38
+ writer = imageio.get_writer(
39
+ wfp,
40
+ fps=fps,
41
+ format=video_format,
42
+ codec=codec,
43
+ quality=quality,
44
+ ffmpeg_params=ffmpeg_params,
45
+ pixelformat=pixelformat,
46
+ macro_block_size=macro_block_size,
47
+ )
48
+
49
+ n = len(images)
50
+ for i in track(range(n), description="writing", transient=True):
51
+ if image_mode.lower() == "bgr":
52
+ writer.append_data(images[i][..., ::-1])
53
+ else:
54
+ writer.append_data(images[i])
55
+
56
+ writer.close()
57
+
58
+ # print(f':smiley: Dump to {wfp}\n', style="bold green")
59
+ print(f"Dump to {wfp}\n")
60
+
61
+
62
+ def merge_audio_video(video_fp, audio_fp, wfp):
63
+ if osp.exists(video_fp) and osp.exists(audio_fp):
64
+ cmd = f"ffmpeg -i {video_fp} -i {audio_fp} -c:v copy -c:a aac {wfp} -y"
65
+ exec_cmd(cmd)
66
+ print(f"merge {video_fp} and {audio_fp} to {wfp}")
67
+ else:
68
+ print(f"video_fp: {video_fp} or audio_fp: {audio_fp} not exists!")
69
+
70
+
71
+
72
+
73
+ class STFPipeline:
74
+ def __init__(self,
75
+ stf_path: str = "/home/user/app/stf/",
76
+ device: str = "cuda:0",
77
+ template_video_path: str = "templates/front_one_piece_dress_nodded_cut.webm",
78
+ config_path: str = "front_config.json",
79
+ checkpoint_path: str = "089.pth",
80
+ #root_path: str = "works"
81
+ root_path: str = "/tmp/works",
82
+ female_video: bool=True
83
+
84
+ ):
85
+ #os.makedirs(root_path, exist_ok=True)
86
+ shutil.copytree('/home/user/app/stf/works', '/tmp/works', dirs_exist_ok=True)
87
+
88
+
89
+
90
+ if female_video:
91
+ dir_zip= os.path.join(root_path, 'preprocess/nasilhong_f_v1_front/crop_video_front_one_piece_dress_nodded_cut.zip')
92
+ dir_target=os.path.join(root_path,'preprocess/nasilhong_f_v1_front/')
93
+ zipfile.ZipFile(dir_zip, 'r').extractall(dir_target)
94
+
95
+ dir_zip=os.path.join(root_path,'preprocess/nasilhong_f_v1_front/front_one_piece_dress_nodded_cut.zip')
96
+ dir_target=os.path.join(root_path,'preprocess/nasilhong_f_v1_front/')
97
+ zipfile.ZipFile(dir_zip, 'r').extractall(dir_target)
98
+ else:
99
+ dir_zip= os.path.join(root_path, 'preprocess/Ian_v3_front/crop_video_Cam2_2309071202_0012_Natural_Looped.zip')
100
+ dir_target=os.path.join(root_path,'preprocess/Ian_v3_front/')
101
+ zipfile.ZipFile(dir_zip, 'r').extractall(dir_target)
102
+
103
+ dir_zip=os.path.join(root_path,'preprocess/Ian_v3_front/Cam2_2309071202_0012_Natural_Looped.zip')
104
+ dir_target=os.path.join(root_path,'preprocess/Ian_v3_front/')
105
+ zipfile.ZipFile(dir_zip, 'r').extractall(dir_target)
106
+
107
+
108
+ self.config_path = os.path.join(stf_path, config_path)
109
+ self.checkpoint_path = os.path.join(stf_path, checkpoint_path)
110
+ #self.work_root_path = os.path.join(stf_path, root_path)
111
+ self.work_root_path = os.path.join(root_path)
112
+ self.device = device
113
+ self.template_video_path=os.path.join(stf_path, template_video_path)
114
+
115
+ # model = stf_alternative.create_model(
116
+ # config_path=config_path,
117
+ # checkpoint_path=checkpoint_path,
118
+ # work_root_path=work_root_path,
119
+ # device=device,
120
+ # wavlm_path="microsoft/wavlm-large",
121
+ # )
122
+ # self.template = stf_alternative.Template(
123
+ # model=model,
124
+ # config_path=config_path,
125
+ # template_video_path=template_video_path,
126
+ # )
127
+
128
+
129
+
130
+ def execute(self, audio: str):
131
+
132
+
133
+ model = stf_alternative.create_model(
134
+ config_path=self.config_path,
135
+ checkpoint_path=self.checkpoint_path,
136
+ work_root_path=self.work_root_path,
137
+ device=self.device,
138
+ wavlm_path="microsoft/wavlm-large",
139
+ )
140
+
141
+
142
+ self.template = stf_alternative.Template(
143
+ model=model,
144
+ config_path=self.config_path,
145
+ template_video_path=self.template_video_path,
146
+ )
147
+
148
+
149
+
150
+ # Path("dubbing").mkdir(exist_ok=True)
151
+ # save_path = os.path.join("dubbing", Path(audio).stem+"--lip.mp4")
152
+ Path("/tmp/dubbing").mkdir(exist_ok=True)
153
+ save_path = os.path.join("/tmp/dubbing", Path(audio).stem+"--lip.mp4")
154
+
155
+ reader = iter(self.template._get_reader(num_skip_frames=0))
156
+
157
+ audio_segment = AudioSegment.from_file(audio)
158
+ pivot = 0
159
+ results = []
160
+
161
+ # try:
162
+
163
+ # gen_infer = self.template.gen_infer(
164
+ # audio_segment,
165
+ # pivot,
166
+ # )
167
+ # for idx, (it, chunk) in enumerate(gen_infer, pivot):
168
+ # frame = next(reader)
169
+ # composed = self.template.compose(idx, frame, it)
170
+ # frame_name = f"{idx}".zfill(5)+".jpg"
171
+ # results.append(it['pred'])
172
+ # pivot = idx + 1
173
+ # except StopIteration as e:
174
+ # pass
175
+
176
+
177
+ with ThreadPoolExecutor(1) as p:
178
+ try:
179
+
180
+ gen_infer = self.template.gen_infer_concurrent(
181
+ p,
182
+ audio_segment,
183
+ pivot,
184
+ )
185
+ for idx, (it, chunk) in enumerate(gen_infer, pivot):
186
+ frame = next(reader)
187
+ composed = self.template.compose(idx, frame, it)
188
+ frame_name = f"{idx}".zfill(5)+".jpg"
189
+ results.append(it['pred'])
190
+ pivot = idx + 1
191
+ except StopIteration as e:
192
+ pass
193
+
194
+ images2video(results, save_path)
195
+
196
+ save_path_aud = save_path.replace('.mp4', '_aud.mp4')
197
+ merge_audio_video(save_path, audio, save_path_aud)
198
+
199
+ return save_path_aud #save_path