fffiloni commited on
Commit
3cbfa4c
·
verified ·
1 Parent(s): a6028c9

Create gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +383 -0
gradio_app.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: UTF-8 -*-
2
+ import os
3
+ os.environ['HYDRA_FULL_ERROR']='1'
4
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
5
+
6
+ import argparse
7
+ import shutil
8
+ import uuid
9
+ import os
10
+ import numpy as np
11
+ from tqdm import tqdm
12
+ import cv2
13
+ from rich.progress import track
14
+ import tyro
15
+
16
+
17
+ from PIL import Image
18
+ import time
19
+ import torch
20
+ import torch.nn.functional as F
21
+ from torch import nn
22
+ import imageio
23
+ from pydub import AudioSegment
24
+ from pykalman import KalmanFilter
25
+
26
+
27
+ from src.config.argument_config import ArgumentConfig
28
+ from src.config.inference_config import InferenceConfig
29
+ from src.config.crop_config import CropConfig
30
+ from src.live_portrait_pipeline import LivePortraitPipeline
31
+ from src.utils.camera import get_rotation_matrix
32
+ from dataset_process import audio
33
+
34
+ from dataset_process.croper import Croper
35
+
36
+
37
+ def parse_audio_length(audio_length, sr, fps):
38
+ bit_per_frames = sr / fps
39
+ num_frames = int(audio_length / bit_per_frames)
40
+ audio_length = int(num_frames * bit_per_frames)
41
+ return audio_length, num_frames
42
+
43
+ def crop_pad_audio(wav, audio_length):
44
+ if len(wav) > audio_length:
45
+ wav = wav[:audio_length]
46
+ elif len(wav) < audio_length:
47
+ wav = np.pad(wav, [0, audio_length - len(wav)], mode='constant', constant_values=0)
48
+ return wav
49
+
50
+ class Conv2d(nn.Module):
51
+ def __init__(self, cin, cout, kernel_size, stride, padding, residual=False, use_act=True, *args, **kwargs):
52
+ super().__init__(*args, **kwargs)
53
+ self.conv_block = nn.Sequential(
54
+ nn.Conv2d(cin, cout, kernel_size, stride, padding),
55
+ nn.BatchNorm2d(cout)
56
+ )
57
+ self.act = nn.ReLU()
58
+ self.residual = residual
59
+ self.use_act = use_act
60
+
61
+ def forward(self, x):
62
+ out = self.conv_block(x)
63
+ if self.residual:
64
+ out += x
65
+
66
+ if self.use_act:
67
+ return self.act(out)
68
+ else:
69
+ return out
70
+
71
+ class AudioEncoder(nn.Module):
72
+ def __init__(self, wav2lip_checkpoint, device):
73
+ super(AudioEncoder, self).__init__()
74
+
75
+ self.audio_encoder = nn.Sequential(
76
+ Conv2d(1, 32, kernel_size=3, stride=1, padding=1),
77
+ Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True),
78
+ Conv2d(32, 32, kernel_size=3, stride=1, padding=1, residual=True),
79
+
80
+ Conv2d(32, 64, kernel_size=3, stride=(3, 1), padding=1),
81
+ Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True),
82
+ Conv2d(64, 64, kernel_size=3, stride=1, padding=1, residual=True),
83
+
84
+ Conv2d(64, 128, kernel_size=3, stride=3, padding=1),
85
+ Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True),
86
+ Conv2d(128, 128, kernel_size=3, stride=1, padding=1, residual=True),
87
+
88
+ Conv2d(128, 256, kernel_size=3, stride=(3, 2), padding=1),
89
+ Conv2d(256, 256, kernel_size=3, stride=1, padding=1, residual=True),
90
+
91
+ Conv2d(256, 512, kernel_size=3, stride=1, padding=0),
92
+ Conv2d(512, 512, kernel_size=1, stride=1, padding=0),)
93
+
94
+ #### load the pre-trained audio_encoder
95
+ wav2lip_state_dict = torch.load(wav2lip_checkpoint, map_location=torch.device(device))['state_dict']
96
+ state_dict = self.audio_encoder.state_dict()
97
+
98
+ for k,v in wav2lip_state_dict.items():
99
+ if 'audio_encoder' in k:
100
+ state_dict[k.replace('module.audio_encoder.', '')] = v
101
+ self.audio_encoder.load_state_dict(state_dict)
102
+
103
+ def forward(self, audio_sequences):
104
+ B = audio_sequences.size(0)
105
+
106
+ audio_sequences = torch.cat([audio_sequences[:, i] for i in range(audio_sequences.size(1))], dim=0)
107
+
108
+ audio_embedding = self.audio_encoder(audio_sequences) # B, 512, 1, 1
109
+ dim = audio_embedding.shape[1]
110
+ audio_embedding = audio_embedding.reshape((B, -1, dim, 1, 1))
111
+
112
+ return audio_embedding.squeeze(-1).squeeze(-1) #B seq_len+1 512
113
+
114
+ def partial_fields(target_class, kwargs):
115
+ return target_class(**{k: v for k, v in kwargs.items() if hasattr(target_class, k)})
116
+
117
+ def dct2device(dct: dict, device):
118
+ for key in dct:
119
+ dct[key] = torch.tensor(dct[key]).to(device)
120
+ return dct
121
+
122
+ def save_video_with_watermark(video, audio, save_path):
123
+ temp_file = str(uuid.uuid4())+'.mp4'
124
+ cmd = r'ffmpeg -y -i "%s" -i "%s" -vcodec copy "%s"' % (video, audio, temp_file)
125
+ os.system(cmd)
126
+ shutil.move(temp_file, save_path)
127
+
128
+ class Inferencer(object):
129
+ def __init__(self):
130
+ st=time.time()
131
+ print('#'*25+'Start initialization'+'#'*25)
132
+ self.device = 'cuda'
133
+
134
+ from model import get_model
135
+ self.point_diffusion = get_model()
136
+ ckpt = torch.load('KDTalker.pth')
137
+
138
+ self.point_diffusion.load_state_dict(ckpt['model'])
139
+ self.point_diffusion.eval()
140
+ self.point_diffusion.to(self.device)
141
+
142
+ lm_croper_checkpoint = 'ckpts/shape_predictor_68_face_landmarks.dat'
143
+ self.croper = Croper(lm_croper_checkpoint)
144
+
145
+ self.norm_info = dict(np.load('dataset_process/norm.npz'))
146
+
147
+ wav2lip_checkpoint = 'ckpts/wav2lip.pth'
148
+ self.wav2lip_model = AudioEncoder(wav2lip_checkpoint, 'cuda')
149
+ self.wav2lip_model.cuda()
150
+ self.wav2lip_model.eval()
151
+
152
+ # set tyro theme
153
+ tyro.extras.set_accent_color("bright_cyan")
154
+ args = tyro.cli(ArgumentConfig)
155
+
156
+ # specify configs for inference
157
+ self.inf_cfg = partial_fields(InferenceConfig, args.__dict__) # use attribute of args to initial InferenceConfig
158
+ self.crop_cfg = partial_fields(CropConfig, args.__dict__) # use attribute of args to initial CropConfig
159
+
160
+ self.live_portrait_pipeline = LivePortraitPipeline(inference_cfg=self.inf_cfg, crop_cfg=self.crop_cfg)
161
+
162
+ def _norm(self, data_dict):
163
+ for k in data_dict.keys():
164
+ if k in ['yaw', 'pitch', 'roll', 't', 'exp', 'scale', 'kp', ]:
165
+ v=data_dict[k]
166
+ data_dict[k] = (v - self.norm_info[k+'_mean'])/self.norm_info[k+'_std']
167
+ return data_dict
168
+
169
+ def _denorm(self, data_dict):
170
+ for k in data_dict.keys():
171
+ if k in ['yaw', 'pitch', 'roll', 't', 'exp', 'scale', 'kp']:
172
+ v=data_dict[k]
173
+ data_dict[k] = v * self.norm_info[k+'_std'] + self.norm_info[k+'_mean']
174
+ return data_dict
175
+
176
+ def output_to_dict(self, data):
177
+ output = {}
178
+ output['scale'] = data[:, 0]
179
+ output['yaw'] = data[:, 1, None]
180
+ output['pitch'] = data[:, 2, None]
181
+ output['roll'] = data[:, 3, None]
182
+ output['t'] = data[:, 4:7]
183
+ output['exp'] = data[:, 7:]
184
+ return output
185
+
186
+ def extract_mel_from_audio(self, audio_file_path):
187
+ syncnet_mel_step_size = 16
188
+ fps = 25
189
+ wav = audio.load_wav(audio_file_path, 16000)
190
+ wav_length, num_frames = parse_audio_length(len(wav), 16000, 25)
191
+ wav = crop_pad_audio(wav, wav_length)
192
+ orig_mel = audio.melspectrogram(wav).T
193
+ spec = orig_mel.copy()
194
+ indiv_mels = []
195
+
196
+ for i in tqdm(range(num_frames), 'mel:'):
197
+ start_frame_num = i - 2
198
+ start_idx = int(80. * (start_frame_num / float(fps)))
199
+ end_idx = start_idx + syncnet_mel_step_size
200
+ seq = list(range(start_idx, end_idx))
201
+ seq = [min(max(item, 0), orig_mel.shape[0] - 1) for item in seq]
202
+ m = spec[seq, :]
203
+ indiv_mels.append(m.T)
204
+ indiv_mels = np.asarray(indiv_mels) # T 80 16
205
+ return indiv_mels
206
+
207
+ def extract_wav2lip_from_audio(self, audio_file_path):
208
+ asd_mel = self.extract_mel_from_audio(audio_file_path)
209
+ asd_mel = torch.FloatTensor(asd_mel).cuda().unsqueeze(0).unsqueeze(2)
210
+ with torch.no_grad():
211
+ hidden = self.wav2lip_model(asd_mel)
212
+ return hidden[0].cpu().detach().numpy()
213
+
214
+ def headpose_pred_to_degree(self, pred):
215
+ device = pred.device
216
+ idx_tensor = [idx for idx in range(66)]
217
+ idx_tensor = torch.FloatTensor(idx_tensor).to(device)
218
+ pred = F.softmax(pred)
219
+ degree = torch.sum(pred * idx_tensor, 1) * 3 - 99
220
+ return degree
221
+
222
+ @torch.no_grad()
223
+ def generate_with_audio_img(self, image_path, audio_path, save_path):
224
+ image = np.array(Image.open(image_path).convert('RGB'))
225
+ cropped_image, crop, quad = self.croper.crop([image], still=False, xsize=512)
226
+ input_image = cv2.resize(cropped_image[0], (256, 256))
227
+
228
+ I_s = torch.FloatTensor(input_image.transpose((2, 0, 1))).unsqueeze(0).cuda() / 255
229
+
230
+ x_s_info = self.live_portrait_pipeline.live_portrait_wrapper.get_kp_info(I_s)
231
+ x_c_s = x_s_info['kp'].reshape(1, 21, -1)
232
+ R_s = get_rotation_matrix(x_s_info['pitch'], x_s_info['yaw'], x_s_info['roll'])
233
+ f_s = self.live_portrait_pipeline.live_portrait_wrapper.extract_feature_3d(I_s)
234
+ x_s = self.live_portrait_pipeline.live_portrait_wrapper.transform_keypoint(x_s_info)
235
+
236
+ ######## process driving info ########
237
+ kp_info = {}
238
+ for k in x_s_info.keys():
239
+ kp_info[k] = x_s_info[k].cpu().numpy()
240
+
241
+ kp_info = self._norm(kp_info)
242
+
243
+ ori_kp = torch.cat([torch.zeros([1, 7]), torch.Tensor(kp_info['kp'])], -1).cuda()
244
+
245
+ input_x = np.concatenate([kp_info[k] for k in ['scale', 'yaw', 'pitch', 'roll', 't', 'exp']], 1)
246
+ input_x = np.expand_dims(input_x, -1)
247
+ input_x = np.expand_dims(input_x, 0)
248
+ input_x = np.concatenate([input_x, input_x, input_x], -1)
249
+
250
+ aud_feat = self.extract_wav2lip_from_audio(audio_path)
251
+
252
+ sample_frame = 64
253
+ padding_size = (sample_frame - aud_feat.shape[0] % sample_frame) % sample_frame
254
+
255
+ if padding_size > 0:
256
+ aud_feat = np.concatenate((aud_feat, aud_feat[:padding_size, :]), axis=0)
257
+ else:
258
+ aud_feat = aud_feat
259
+
260
+ outputs = [input_x]
261
+
262
+ sample_frame = 64
263
+ for i in range(0, aud_feat.shape[0] - 1, sample_frame):
264
+ input_mel = torch.Tensor(aud_feat[i: i + sample_frame]).unsqueeze(0).cuda()
265
+ kp0 = torch.Tensor(outputs[-1])[:, -1].cuda()
266
+ pred_kp = self.point_diffusion.forward_sample(70, ref_kps=kp0, ori_kps=ori_kp, aud_feat=input_mel,
267
+ scheduler='ddim', num_inference_steps=50)
268
+ outputs.append(pred_kp.cpu().numpy())
269
+
270
+ outputs = np.mean(np.concatenate(outputs, 1)[0, 1:aud_feat.shape[0] - padding_size + 1], -1)
271
+ output_dict = self.output_to_dict(outputs)
272
+ output_dict = self._denorm(output_dict)
273
+
274
+ num_frame = output_dict['yaw'].shape[0]
275
+ x_d_info = {}
276
+ for key in output_dict:
277
+ x_d_info[key] = torch.tensor(output_dict[key]).cuda()
278
+
279
+ # smooth
280
+ def smooth(sequence, n_dim_state=1):
281
+ kf = KalmanFilter(initial_state_mean=sequence[0],
282
+ transition_covariance=0.05 * np.eye(n_dim_state),
283
+ observation_covariance=0.001 * np.eye(n_dim_state))
284
+ state_means, _ = kf.smooth(sequence)
285
+ return state_means
286
+
287
+ yaw_data = x_d_info['yaw'].cpu().numpy()
288
+ pitch_data = x_d_info['pitch'].cpu().numpy()
289
+ roll_data = x_d_info['roll'].cpu().numpy()
290
+ t_data = x_d_info['t'].cpu().numpy()
291
+ exp_data = x_d_info['exp'].cpu().numpy()
292
+
293
+ smoothed_pitch = smooth(pitch_data, n_dim_state=1)
294
+ smoothed_yaw = smooth(yaw_data, n_dim_state=1)
295
+ smoothed_roll = smooth(roll_data, n_dim_state=1)
296
+ smoothed_t = smooth(t_data, n_dim_state=3)
297
+ smoothed_exp = smooth(exp_data, n_dim_state=63)
298
+
299
+ x_d_info['pitch'] = torch.Tensor(smoothed_pitch).cuda()
300
+ x_d_info['yaw'] = torch.Tensor(smoothed_yaw).cuda()
301
+ x_d_info['roll'] = torch.Tensor(smoothed_roll).cuda()
302
+ x_d_info['t'] = torch.Tensor(smoothed_t).cuda()
303
+ x_d_info['exp'] = torch.Tensor(smoothed_exp).cuda()
304
+
305
+ template_dct = {'motion': [], 'c_d_eyes_lst': [], 'c_d_lip_lst': []}
306
+ for i in track(range(num_frame), description='Making motion templates...', total=num_frame):
307
+ x_d_i_info = x_d_info
308
+ R_d_i = get_rotation_matrix(x_d_i_info['pitch'][i], x_d_i_info['yaw'][i], x_d_i_info['roll'][i])
309
+
310
+ item_dct = {
311
+ 'scale': x_d_i_info['scale'][i].cpu().numpy().astype(np.float32),
312
+ 'R_d': R_d_i.cpu().numpy().astype(np.float32),
313
+ 'exp': x_d_i_info['exp'][i].reshape(1, 21, -1).cpu().numpy().astype(np.float32),
314
+ 't': x_d_i_info['t'][i].cpu().numpy().astype(np.float32),
315
+ }
316
+
317
+ template_dct['motion'].append(item_dct)
318
+
319
+ I_p_lst = []
320
+ R_d_0, x_d_0_info = None, None
321
+
322
+ for i in track(range(num_frame), description='🚀Animating...', total=num_frame):
323
+ x_d_i_info = template_dct['motion'][i]
324
+ for key in x_d_i_info:
325
+ x_d_i_info[key] = torch.tensor(x_d_i_info[key]).cuda()
326
+ R_d_i = x_d_i_info['R_d']
327
+
328
+ if i == 0:
329
+ R_d_0 = R_d_i
330
+ x_d_0_info = x_d_i_info
331
+
332
+ if self.inf_cfg.flag_relative_motion:
333
+ R_new = (R_d_i @ R_d_0.permute(0, 2, 1)) @ R_s
334
+ delta_new = x_s_info['exp'].reshape(1, 21, -1) + (x_d_i_info['exp'] - x_d_0_info['exp'])
335
+ scale_new = x_s_info['scale'] * (x_d_i_info['scale'] / x_d_0_info['scale'])
336
+ t_new = x_s_info['t'] + (x_d_i_info['t'] - x_d_0_info['t'])
337
+ else:
338
+ R_new = R_d_i
339
+ delta_new = x_d_i_info['exp']
340
+ scale_new = x_s_info['scale']
341
+ t_new = x_d_i_info['t']
342
+
343
+ t_new[..., 2].fill_(0)
344
+ x_d_i_new = scale_new * (x_c_s @ R_new + delta_new) + t_new
345
+
346
+ out = self.live_portrait_pipeline.live_portrait_wrapper.warp_decode(f_s, x_s, x_d_i_new)
347
+ I_p_i = self.live_portrait_pipeline.live_portrait_wrapper.parse_output(out['out'])[0]
348
+ I_p_lst.append(I_p_i)
349
+
350
+ video_name = save_path.split('/')[-1]
351
+ video_save_dir = os.path.dirname(save_path)
352
+ path = os.path.join(video_save_dir, 'temp_' + video_name)
353
+
354
+ imageio.mimsave(path, I_p_lst, fps=float(25))
355
+
356
+ audio_name = audio_path.split('/')[-1]
357
+ new_audio_path = os.path.join(video_save_dir, audio_name)
358
+ start_time = 0
359
+ sound = AudioSegment.from_file(audio_path)
360
+ end_time = start_time + num_frame * 1 / 25 * 1000
361
+ word1 = sound.set_frame_rate(16000)
362
+ word = word1[start_time:end_time]
363
+ word.export(new_audio_path, format="wav")
364
+
365
+ save_video_with_watermark(path, new_audio_path, save_path, watermark=False)
366
+ print(f'The generated video is named {video_save_dir}/{video_name}')
367
+
368
+ os.remove(path)
369
+ os.remove(new_audio_path)
370
+
371
+
372
+ if __name__ == '__main__':
373
+ parser = argparse.ArgumentParser()
374
+ parser.add_argument("-source_image", type=str, default="example/source_image/WDA_BenCardin1_000.png",
375
+ help="source image")
376
+ parser.add_argument("-driven_audio", type=str, default="example/driven_audio/WDA_BenCardin1_000.wav",
377
+ help="driving audio")
378
+ parser.add_argument("-output", type=str, default="results/output.mp4", help="output video file name", )
379
+
380
+ args = parser.parse_args()
381
+
382
+ Infer = Inferencer()
383
+ Infer.generate_with_audio_img(args.source_image, args.driven_audio, args.output)