LightSY commited on
Commit
92bea53
·
1 Parent(s): e38d81a

Upload 4 files

Browse files
Files changed (4) hide show
  1. app_hug.py +721 -0
  2. audio.py +135 -0
  3. hparams.py +101 -0
  4. requirements.txt +6 -0
app_hug.py ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+
4
+ # from os import listdir, path
5
+ # from models import Wav2Lip
6
+ import platform
7
+ import subprocess
8
+
9
+ import argparse
10
+
11
+ from gradio.outputs import Video
12
+ from wheel.cli import pack
13
+
14
+ import audio
15
+ import cv2
16
+ import numpy as np
17
+ # import onnx
18
+ import onnxruntime
19
+ import os
20
+ from tqdm import tqdm
21
+ import gradio as gr
22
+ from facelib.utils.face_restoration_helper import FaceRestoreHelper
23
+ import os
24
+
25
+ # from glob import glob
26
+ # import face_detection
27
+
28
+
29
+ parser = argparse.ArgumentParser(
30
+ description='Inference code to lip-sync videos in the wild using Wav2Lip models')
31
+
32
+ parser.add_argument('--face', type=str,
33
+ help='输入视频路径', required=False)
34
+ parser.add_argument('--audio', type=str,
35
+ help='输入音频路径',
36
+ required=False)
37
+
38
+ parser.add_argument('--outfile', type=str, help='输出文件名,无需后缀',
39
+ default=None)
40
+
41
+ parser.add_argument('--face_restore', action='store_true',
42
+ help='启用此参数时,调用gfpggan修复人脸,将耗费更多时间')
43
+
44
+ args = parser.parse_args()
45
+ args.img_size = 96
46
+ args.static = False
47
+ args.fps = 25
48
+ args.pads = [0, 10, 0, 0]
49
+ args.face_det_batch_size = 16
50
+ args.wav2lip_batch_size = 128
51
+ args.resize_factor = 1
52
+ args.crop = [0, -1, 0, -1]
53
+ args.box = [-1, -1, -1, -1]
54
+ args.rotate = False
55
+ args.nosmooth = False
56
+
57
+
58
+ # if os.path.isfile(args.face) and args.face.split('.')[1] in ['jpg', 'png', 'jpeg']:
59
+ # args.static = True
60
+
61
+
62
+ def get_smoothened_boxes(boxes, T):
63
+ for i in range(len(boxes)):
64
+ if i + T > len(boxes):
65
+ window = boxes[len(boxes) - T:]
66
+ else:
67
+ window = boxes[i: i + T]
68
+ boxes[i] = np.mean(window, axis=0)
69
+ return boxes
70
+
71
+
72
+ def face_detect(images):
73
+ face_helper = FaceRestoreHelper(
74
+ upscale_factor=1,
75
+ face_size=512,
76
+ crop_ratio=(1, 1),
77
+ det_model='retinaface_mobile0.25', # retinaface_mobile0.25,retinaface_resnet50
78
+ save_ext='png',
79
+ use_parse=False,
80
+ device='cuda'
81
+ )
82
+
83
+ face_helper.clean_all()
84
+
85
+ # detector = face_detection.FaceAlignment(face_detection.LandmarksType._2D, ##这里用到了face_detection
86
+ # flip_input=False)
87
+
88
+ batch_size = args.face_det_batch_size
89
+
90
+ while 1:
91
+ predictions = []
92
+ print('\n人脸检测中......')
93
+ try:
94
+ for i in tqdm(range(0, len(images), batch_size)):
95
+ predictions.extend(
96
+ face_helper.face_detector.batched_detect_faces_bbox(np.array(images[i:i + batch_size])))
97
+ # predictions.extend(detector.get_detections_for_batch(np.array(images[i:i + batch_size])))
98
+ except RuntimeError:
99
+ if batch_size == 1:
100
+ raise RuntimeError(
101
+ 'Image too big to run face detection on GPU. Please use the --resize_factor argument')
102
+ batch_size //= 2
103
+ print('Recovering from Out Of Memory error; New batch size: {}'.format(batch_size))
104
+ continue
105
+ break
106
+
107
+ results = []
108
+ pady1, pady2, padx1, padx2 = args.pads
109
+ # TODO 跳过无人像frame
110
+ head_exist = []
111
+ for rect, image in zip(predictions, images):
112
+ if rect is not None:
113
+ first_head_rect = rect
114
+ first_head_image = image
115
+ break
116
+ for rect, image in zip(predictions, images):
117
+ if rect is None:
118
+ head_exist.append(False)
119
+ if len(results) == 0:
120
+ y1 = max(0, first_head_rect[1] - pady1)
121
+ y2 = min(first_head_image.shape[0], first_head_rect[3] + pady2)
122
+ x1 = max(0, first_head_rect[0] - padx1)
123
+ x2 = min(first_head_image.shape[1], first_head_rect[2] + padx2)
124
+ results.append([x1, y1, x2, y2])
125
+ else:
126
+ results.append(results[-1])
127
+ # cv2.imwrite('temp/faulty_frame.jpg', image) # check this frame where the face was not detected.
128
+ # raise ValueError('Face not detected! Ensure the video contains a face in all the frames.')
129
+ else:
130
+ head_exist.append(True)
131
+ y1 = max(0, rect[1] - pady1)
132
+ y2 = min(image.shape[0], rect[3] + pady2)
133
+ x1 = max(0, rect[0] - padx1)
134
+ x2 = min(image.shape[1], rect[2] + padx2)
135
+ results.append([x1, y1, x2, y2])
136
+
137
+ boxes = np.array(results)
138
+ if not args.nosmooth: boxes = get_smoothened_boxes(boxes, T=5)
139
+ results = [[image[y1: y2, x1:x2], (y1, y2, x1, x2)] for image, (x1, y1, x2, y2) in zip(images, boxes)]
140
+ return results, head_exist
141
+
142
+
143
+ def datagen2(frames, mels):
144
+ img_batch, head_exist_batch, mel_batch, frame_batch, coords_batch = [], [], [], [], []
145
+
146
+ # ***************************1、识别人脸对应的位置坐标,未识别的人脸的帧对应为None ***************************
147
+ if args.box[0] == -1:
148
+ if not args.static:
149
+ face_det_results, head_exist = face_detect(frames) # BGR2RGB for CNN face detection
150
+ else:
151
+ face_det_results, head_exist = face_detect([frames[0]])
152
+ else:
153
+ print('Using the specified bounding box instead of face detection...')
154
+ y1, y2, x1, x2 = args.box
155
+ face_det_results = [[f[y1: y2, x1:x2], (y1, y2, x1, x2)] for f in frames]
156
+ head_exist = [True] * len(frames)
157
+
158
+ for i, m in enumerate(mels):
159
+ # 获取对应的一组音频对应的帧下标idx
160
+ idx = 0 if args.static else i % len(frames)
161
+ # 获取对应的一组音频对应的帧
162
+ frame_to_save = frames[idx].copy()
163
+ # 获取对应的一组音频对应的帧对应的人脸坐标
164
+ face, coords = face_det_results[idx].copy()
165
+
166
+ face = cv2.resize(face, (args.img_size, args.img_size))
167
+ head_exist_batch.append(head_exist[idx])
168
+ img_batch.append(face)
169
+ mel_batch.append(m)
170
+ frame_batch.append(frame_to_save)
171
+ coords_batch.append(coords)
172
+
173
+ if len(img_batch) >= args.wav2lip_batch_size:
174
+ img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
175
+
176
+ img_masked = img_batch.copy()
177
+ img_masked[:, args.img_size // 2:] = 0
178
+
179
+ img_batch = np.concatenate((img_masked, img_batch), axis=3) / 255.
180
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
181
+
182
+ yield img_batch, head_exist_batch, mel_batch, frame_batch, coords_batch
183
+ img_batch, head_exist_batch, mel_batch, frame_batch, coords_batch = [], [], [], [], []
184
+
185
+ if len(img_batch) > 0:
186
+ img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
187
+
188
+ img_masked = img_batch.copy()
189
+ img_masked[:, args.img_size // 2:] = 0
190
+
191
+ img_batch = np.concatenate((img_masked, img_batch), axis=3) / 255.
192
+ mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
193
+
194
+ yield img_batch, head_exist_batch, mel_batch, frame_batch, coords_batch
195
+
196
+
197
+ def main(input_video, input_audio, idx):
198
+ face_default = input_video
199
+ audio_default = input_audio
200
+ outfile_default = 'results/' + str(idx) + '.mp4'
201
+ # print(args.outfile)
202
+ if not os.path.exists('temp'):
203
+ os.mkdir('temp')
204
+ if not os.path.exists('results'):
205
+ os.mkdir('results')
206
+
207
+ if not os.path.isfile(face_default):
208
+ raise ValueError('--face argument must be a valid path to video/image file') ##--face 参数必须是视频/图像文件的有效路径
209
+
210
+ elif face_default.split('.')[1] in ['jpg', 'png', 'jpeg']:
211
+ full_frames = [cv2.imread(face_default)]
212
+ fps = args.fps
213
+
214
+ else:
215
+ video_stream = cv2.VideoCapture(face_default)
216
+ fps = video_stream.get(cv2.CAP_PROP_FPS)
217
+
218
+ # frame_width = int(video_stream.get(cv2.CAP_PROP_FRAME_WIDTH))
219
+ # frame_height = int(video_stream.get(cv2.CAP_PROP_FRAME_HEIGHT))
220
+ # frame_size = frame_height * frame_width
221
+ # if frame_size > 345600:
222
+ # args.resize_factor = int(np.sqrt(frame_size / 345600))
223
+
224
+ print('Reading video frames...') ##正在读取视频帧...
225
+
226
+ full_frames = []
227
+ while 1:
228
+ still_reading, frame = video_stream.read()
229
+ if not still_reading:
230
+ video_stream.release()
231
+ break
232
+
233
+ if args.resize_factor > 1:
234
+ frame = cv2.resize(frame, (frame.shape[1] // args.resize_factor, frame.shape[0] // args.resize_factor))
235
+
236
+ if args.rotate:
237
+ frame = cv2.rotate(frame, cv2.cv2.ROTATE_90_CLOCKWISE)
238
+
239
+ y1, y2, x1, x2 = args.crop
240
+ if x2 == -1: x2 = frame.shape[1]
241
+ if y2 == -1: y2 = frame.shape[0]
242
+
243
+ frame = frame[y1:y2, x1:x2]
244
+
245
+ full_frames.append(frame)
246
+ if (len(full_frames) > 300 * fps):
247
+ # print('不得输入超过5分钟的视频!')
248
+ raise ValueError('不得输入超过5分钟的视频!')
249
+
250
+ print("可用于推理的视频帧数: " + str(len(full_frames))) ##可用于推理的帧数:
251
+
252
+ if not audio_default.endswith('.wav'):
253
+ print('Extracting raw audio...')
254
+ command = 'ffmpeg -y -i {} -strict -2 {}'.format(audio_default, 'temp/' + str(idx) + '.wav')
255
+
256
+ subprocess.call(command, shell=True)
257
+ args.audio = 'temp/' + str(idx) + '.wav'
258
+
259
+ wav = audio.load_wav(args.audio, 16000)
260
+ mel = audio.melspectrogram(wav)
261
+ print(mel.shape)
262
+
263
+ if np.isnan(mel.reshape(-1)).sum() > 0:
264
+ raise ValueError('Mel contains nan! Using a TTS voice? Add a small epsilon noise to the wav file and try again')
265
+
266
+ mel_chunks = []
267
+ mel_idx_multiplier = 80. / fps
268
+ i = 0
269
+ while 1:
270
+ start_idx = int(i * mel_idx_multiplier)
271
+ if start_idx + mel_step_size > len(mel[0]):
272
+ mel_chunks.append(mel[:, len(mel[0]) - mel_step_size:])
273
+ break
274
+ mel_chunks.append(mel[:, start_idx: start_idx + mel_step_size])
275
+ i += 1
276
+
277
+ print("Length of mel chunks: {}".format(len(mel_chunks)))
278
+
279
+ full_frames = full_frames[:len(mel_chunks)]
280
+
281
+ batch_size = args.wav2lip_batch_size
282
+ gen = datagen2(full_frames.copy(), mel_chunks)
283
+ # print(gen)
284
+ # TODO 加载模型
285
+ sess = onnxruntime.InferenceSession('weights/model.onnx', providers=[('CUDAExecutionProvider', {'device_id': 0, }),
286
+ 'CPUExecutionProvider']) ##这里用onnxruntime引入onnx到sess
287
+ # for i, (img_batch, mel_batch, frames, coords) in enumerate(tqdm(gen,
288
+ # total=int(
289
+ # np.ceil(float(len(mel_chunks)) / batch_size)))):
290
+ # j=0
291
+ for i, (img_batch, exist_head_batch, mel_batch, frames, coords) in enumerate(tqdm(gen,
292
+ total=int(np.ceil(float(
293
+ len(mel_chunks)) / batch_size)))):
294
+
295
+ if i == 0:
296
+ # model = load_model(args.checkpoint_path)
297
+ # print("Model loaded")
298
+
299
+ frame_h, frame_w = full_frames[0].shape[:-1]
300
+ out = cv2.VideoWriter('temp/' + str(idx) + '.avi',
301
+ cv2.VideoWriter_fourcc(*'DIVX'), fps, (frame_w, frame_h))
302
+ print('\n运行W2L-TD中......')
303
+
304
+ input0 = np.transpose(mel_batch, (0, 3, 1, 2))
305
+ input1 = np.transpose(img_batch, (0, 3, 1, 2))
306
+
307
+ input0 = np.array(input0, dtype=np.float32)
308
+ input1 = np.array(input1, dtype=np.float32)
309
+
310
+ pred = sess.run(None, {'mel': input0,
311
+ 'img': input1}) # 这一部分使用sess的run函数来运行onnx,输出onnx的结果。因为是双输入,onnx要用动态输入形成。
312
+
313
+ pred = pred[0]
314
+ np.array(pred) ##这一步是将list转变成array,因为后边要用到transponse,这个必须是array类型才能调用
315
+ pred = pred.transpose(0, 2, 3, 1) * 255. ##pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255.原来是这样的
316
+
317
+ # for p, f, c in zip(pred, frames, coords):
318
+ for p, f, c, exist in zip(pred, frames, coords, exist_head_batch):
319
+ if exist:
320
+ y1, y2, x1, x2 = c
321
+
322
+ p = cv2.resize(p.astype(np.uint8), (x2 - x1, y2 - y1))
323
+
324
+ f[y1:y2, x1:x2] = p
325
+ out.write(f)
326
+
327
+ # im = Image.fromarray(f)
328
+ # im.save('temp/' + str(j) + ".jpeg")
329
+ # j += 1
330
+ out.release()
331
+
332
+ print('main')
333
+ print(audio_default)
334
+ print('temp/' + str(idx) + '.avi')
335
+ print(outfile_default)
336
+ command = 'ffmpeg -y -i {} -i {} -strict -2 -q:v 1 {}'.format(audio_default, 'temp/' + str(idx) + '.avi',
337
+ outfile_default)
338
+
339
+ if subprocess.call(command, shell=platform.system() != 'Windows'):
340
+ print('失败!请检查输出信息!')
341
+ else:
342
+ print("成功!")
343
+ print('结果文件在' + outfile_default)
344
+
345
+ return outfile_default
346
+
347
+
348
+ # TODO 带人脸修复版
349
+
350
+
351
+ def img2tensor(imgs, bgr2rgb=True, float32=True):
352
+ """Numpy array to tensor.
353
+
354
+ Args:
355
+ imgs (list[ndarray] | ndarray): Input images.
356
+ bgr2rgb (bool): Whether to change bgr to rgb.
357
+ float32 (bool): Whether to change to float32.
358
+
359
+ Returns:
360
+ list[tensor] | tensor: Tensor images. If returned results only have
361
+ one element, just return tensor.
362
+ """
363
+
364
+ def _totensor(img, bgr2rgb, float32):
365
+ if img.shape[2] == 3 and bgr2rgb:
366
+ if img.dtype == 'float64':
367
+ img = img.astype('float32')
368
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
369
+ # img = torch.from_numpy(img.transpose(2, 0, 1))
370
+ img = img.transpose(2, 0, 1)
371
+ if float32:
372
+ img = img.astype(np.float32)
373
+ return img
374
+
375
+ if isinstance(imgs, list):
376
+ return [_totensor(img, bgr2rgb, float32) for img in imgs]
377
+ else:
378
+ return _totensor(imgs, bgr2rgb, float32)
379
+
380
+
381
+ def tensor2img(tensor, rgb2bgr=True, out_type=np.uint8, min_max=(0, 1)):
382
+ """Convert torch Tensors into image numpy arrays.
383
+
384
+ After clamping to [min, max], values will be normalized to [0, 1].
385
+
386
+ Args:
387
+ tensor (Tensor or list[Tensor]): Accept shapes:
388
+ 1) 4D mini-batch Tensor of shape (B x 3/1 x H x W);
389
+ 2) 3D Tensor of shape (3/1 x H x W);
390
+ 3) 2D Tensor of shape (H x W).
391
+ Tensor channel should be in RGB order.
392
+ rgb2bgr (bool): Whether to change rgb to bgr.
393
+ out_type (numpy type): output types. If ``np.uint8``, transform outputs
394
+ to uint8 type with range [0, 255]; otherwise, float type with
395
+ range [0, 1]. Default: ``np.uint8``.
396
+ min_max (tuple[int]): min and max values for clamp.
397
+
398
+ Returns:
399
+ (Tensor or list): 3D ndarray of shape (H x W x C) OR 2D ndarray of
400
+ shape (H x W). The channel order is BGR.
401
+ """
402
+ # if not (torch.is_tensor(tensor) or (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
403
+ # raise TypeError(f'tensor or list of tensors expected, got {type(tensor)}')
404
+ #
405
+ # if torch.is_tensor(tensor):
406
+ # tensor = [tensor]
407
+ tensor = [tensor]
408
+ result = []
409
+ for _tensor in tensor:
410
+ # _tensor = _tensor.squeeze(0).float().detach().cpu().clamp_(*min_max)
411
+ _tensor = np.clip(np.squeeze(_tensor, axis=0), -1, 1)
412
+ _tensor = (_tensor - min_max[0]) / (min_max[1] - min_max[0])
413
+
414
+ n_dim = _tensor.ndim
415
+ if n_dim == 4:
416
+ img_np = make_grid(_tensor, nrow=int(np.sqrt(_tensor.size(0))), normalize=False).numpy()
417
+ img_np = img_np.transpose(1, 2, 0)
418
+ if rgb2bgr:
419
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
420
+ elif n_dim == 3:
421
+ # img_np = _tensor.numpy()
422
+ img_np = _tensor
423
+ img_np = img_np.transpose(1, 2, 0)
424
+ if img_np.shape[2] == 1: # gray image
425
+ img_np = np.squeeze(img_np, axis=2)
426
+ else:
427
+ if rgb2bgr:
428
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
429
+ elif n_dim == 2:
430
+ img_np = _tensor.numpy()
431
+ else:
432
+ raise TypeError('Only support 4D, 3D or 2D tensor. ' f'But received with dimension: {n_dim}')
433
+ if out_type == np.uint8:
434
+ # Unlike MATLAB, numpy.unit8() WILL NOT round by default.
435
+ img_np = (img_np * 255.0).round()
436
+ img_np = img_np.astype(out_type)
437
+ result.append(img_np)
438
+ if len(result) == 1:
439
+ result = result[0]
440
+ return result
441
+
442
+
443
+ def my_normalize(img, channel_mean, channel_std):
444
+ for i in range(3):
445
+ img[i, :, :] = (img[i, :, :] - channel_mean[i]) / channel_std[i]
446
+
447
+ return img
448
+
449
+
450
+ mel_step_size = 16
451
+
452
+
453
+ def with_face_restore(input_video, input_audio, idx):
454
+ face_res = input_video
455
+ audio_res = input_audio
456
+ outfile_res = 'results/' + str(idx) + '.mp4'
457
+
458
+ if not os.path.exists('temp'):
459
+ os.mkdir('temp')
460
+ if not os.path.exists('results'):
461
+ os.mkdir('results')
462
+
463
+ if not os.path.isfile(face_res):
464
+ raise ValueError('--face argument must be a valid path to video/image file')
465
+
466
+ elif face_res.split('.')[1] in ['jpg', 'png', 'jpeg']:
467
+ full_frames = [cv2.imread(face_res)]
468
+ fps = args.fps
469
+
470
+ else:
471
+ video_stream = cv2.VideoCapture(face_res)
472
+ fps = video_stream.get(cv2.CAP_PROP_FPS)
473
+
474
+ need_resize = False
475
+ frame_width = int(video_stream.get(cv2.CAP_PROP_FRAME_WIDTH))
476
+ frame_height = int(video_stream.get(cv2.CAP_PROP_FRAME_HEIGHT))
477
+ frame_size = frame_height * frame_width
478
+ if frame_size < 262144:
479
+ need_resize = True
480
+
481
+ print('Reading video frames...') ##正在读取视频帧...
482
+
483
+ full_frames = []
484
+ while 1:
485
+ still_reading, frame = video_stream.read()
486
+ if not still_reading:
487
+ video_stream.release()
488
+ break
489
+
490
+ if args.resize_factor > 1:
491
+ frame = cv2.resize(frame, (frame.shape[1] // args.resize_factor, frame.shape[0] // args.resize_factor))
492
+
493
+ if args.rotate:
494
+ frame = cv2.rotate(frame, cv2.cv2.ROTATE_90_CLOCKWISE)
495
+
496
+ y1, y2, x1, x2 = args.crop
497
+ if x2 == -1: x2 = frame.shape[1]
498
+ if y2 == -1: y2 = frame.shape[0]
499
+
500
+ frame = frame[y1:y2, x1:x2]
501
+
502
+ full_frames.append(frame)
503
+ if (len(full_frames) > 300 * fps):
504
+ # print('不得输入超过5分钟的视频!')
505
+ raise ValueError('不得输入超过5分钟的视频!')
506
+
507
+ print("可用于推理的视频帧数: " + str(len(full_frames))) ##可用于推理的帧数:
508
+
509
+ if not audio_res.endswith('.wav'):
510
+ print('Extracting raw audio...')
511
+ command = 'ffmpeg -y -i {} -strict -2 {}'.format(audio_res, 'temp/' + str(idx) + '.wav')
512
+
513
+ subprocess.call(command, shell=True)
514
+ audio_res = 'temp/' + str(idx) + '.wav'
515
+
516
+ print('extract to ' + audio_res)
517
+ wav = audio.load_wav(audio_res, 16000)
518
+ mel = audio.melspectrogram(wav)
519
+ print(mel.shape)
520
+
521
+ if np.isnan(mel.reshape(-1)).sum() > 0:
522
+ raise ValueError('Mel contains nan! Using a TTS voice? Add a small epsilon noise to the wav file and try again')
523
+
524
+ mel_chunks = []
525
+ mel_idx_multiplier = 80. / fps
526
+ i = 0
527
+ while 1:
528
+ start_idx = int(i * mel_idx_multiplier)
529
+ if start_idx + mel_step_size > len(mel[0]):
530
+ mel_chunks.append(mel[:, len(mel[0]) - mel_step_size:])
531
+ break
532
+ mel_chunks.append(mel[:, start_idx: start_idx + mel_step_size])
533
+ i += 1
534
+
535
+ print("Length of mel chunks: {}".format(len(mel_chunks)))
536
+
537
+ full_frames = full_frames[:len(mel_chunks)]
538
+
539
+ batch_size = args.wav2lip_batch_size
540
+ gen = datagen2(full_frames.copy(), mel_chunks)
541
+
542
+ # sess_options = onnxruntime.SessionOptions()
543
+ # sess_options.intra_op_num_threads = 2
544
+
545
+ device = onnxruntime.get_device()
546
+ if device == 'GPU':
547
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
548
+ else:
549
+ providers = ['CPUExecutionProvider']
550
+ print('Onnxruntime using {}'.format(providers))
551
+
552
+ sess = onnxruntime.InferenceSession('weights/W2LTD.onnx', providers=providers)
553
+ sess_gfp = onnxruntime.InferenceSession('weights/GFPGANv1.4.onnx', providers=providers)
554
+
555
+ upscale_factor = 1
556
+ face_helper = FaceRestoreHelper(
557
+ upscale_factor=upscale_factor,
558
+ face_size=512,
559
+ crop_ratio=(1, 1),
560
+ det_model='retinaface_mobile0.25', # retinaface_mobile0.25,retinaface_resnet50
561
+ save_ext='png',
562
+ use_parse=False,
563
+ )
564
+ # j=0
565
+
566
+ for i, (img_batch, exist_head_batch, mel_batch, frames, coords) in enumerate(tqdm(gen,
567
+ total=int(np.ceil(float(
568
+ len(mel_chunks)) / batch_size)))):
569
+ if i == 0:
570
+ frame_h, frame_w = full_frames[0].shape[:-1]
571
+ # frame_h, frame_w = restored_img.shape[:-1]
572
+ out = cv2.VideoWriter('temp/' + str(idx) + '.avi',
573
+ cv2.VideoWriter_fourcc(*'DIVX'), fps,
574
+ (frame_w * upscale_factor, frame_h * upscale_factor))
575
+ print('运行W2L-TD中......')
576
+
577
+ input0 = np.transpose(mel_batch, (0, 3, 1, 2))
578
+ input1 = np.transpose(img_batch, (0, 3, 1, 2))
579
+
580
+ input0 = np.array(input0, dtype=np.float32)
581
+ input1 = np.array(input1, dtype=np.float32)
582
+
583
+ # print("batch write message:", len(img_batch), len(frames), len(coords), len(exist_head_batch))
584
+
585
+ # 这一部分就是将原本有的pytorch替换成普通python代码
586
+ pred = sess.run(None, {'mel': input0,
587
+ 'img': input1}) # 这一部分使用sess的run函数来运行onnx,输出onnx的结果。因为是双输入,onnx要用动态输入形成。
588
+
589
+ pred = pred[0]
590
+ np.array(pred) ##这一步是将list转变成array,因为后边要用到transponse,这个必须是array类型才能调用
591
+ pred = pred.transpose(0, 2, 3, 1) * 255. ##pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255.原来是这样的
592
+
593
+ for p, f, c, exist in zip(pred, frames, coords, exist_head_batch):
594
+ if exist:
595
+ y1, y2, x1, x2 = c
596
+ p = cv2.resize(p.astype(np.uint8), (x2 - x1, y2 - y1))
597
+ f[y1:y2, x1:x2] = p
598
+ out.write(f)
599
+
600
+ out.release()
601
+
602
+ res_frames = []
603
+ res_stream = cv2.VideoCapture('temp/' + str(idx) + '.avi')
604
+ while 1:
605
+ still_reading, frame = res_stream.read()
606
+ if not still_reading:
607
+ res_stream.release()
608
+ break
609
+ res_frames.append(frame)
610
+
611
+ frame_h, frame_w = full_frames[0].shape[:-1]
612
+ # print('temp/' + str(idx) + '_2.avi')
613
+ out = cv2.VideoWriter('temp/' + str(idx) + '_2.avi', cv2.VideoWriter_fourcc(*'DIVX'), fps,
614
+ (frame_w * upscale_factor, frame_h * upscale_factor))
615
+ print('GFPGAN人脸修复中......')
616
+ cnt_noface = 0
617
+ for f in tqdm(res_frames):
618
+ face_helper.clean_all()
619
+ face_helper.read_image(f)
620
+ num_det_faces = face_helper.get_face_landmarks_5(only_center_face=True, resize=640, eye_dist_threshold=5)
621
+ if num_det_faces == 0:
622
+ out.write(f)
623
+ # cnt_noface+=1
624
+ continue
625
+ # print(num_det_faces)
626
+ face_helper.align_warp_face()
627
+ for index, cropped_face in enumerate(face_helper.cropped_faces):
628
+ cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
629
+ cropped_face_t = my_normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
630
+ cropped_face_t = np.expand_dims(cropped_face_t, axis=0)
631
+ try:
632
+
633
+ output = sess_gfp.run(None, {'input': cropped_face_t})[0]
634
+ restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
635
+
636
+ except Exception as error:
637
+ print(f'\tFailed inference for GFPGAN: {error} \n 结果有误!')
638
+ restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
639
+
640
+ restored_face = restored_face.astype('uint8')
641
+ face_helper.add_restored_face(restored_face, cropped_face)
642
+
643
+ bg_img = None
644
+ face_helper.get_inverse_affine(None)
645
+ restored_img = face_helper.paste_faces_to_input_image(upsample_img=bg_img, draw_box=False, )
646
+ out.write(restored_img)
647
+
648
+ out.release()
649
+
650
+ print(audio_res)
651
+ print('temp/' + str(idx) + '_2.avi')
652
+ print(outfile_res)
653
+ command = 'ffmpeg -y -i {} -i {} -strict -2 -q:v 1 {}'.format(audio_res, 'temp/' + str(idx) + '_2.avi', outfile_res)
654
+
655
+ if subprocess.call(command, shell=platform.system() != 'Windows'):
656
+ print('失败!请检查输出信息!')
657
+ else:
658
+ print("成功!")
659
+ print('结果文件在' + outfile_res)
660
+
661
+ return outfile_res
662
+
663
+
664
+ title = "虚拟化身-2D虚拟人语音驱动算法"
665
+ description = r"输入仅含有单人像的视频和用于驱动的音频后,点击submit按钮,可得到你想要的video! ----Node团队<br>Tips1:启用人脸修复会大幅增加运算时间,如遇错误,请尝试取消勾选该选项^_^<br>" \
666
+ r"Tips2:云服务器带宽只有4M,受制于服务器网络情况,不建议上传大于40MB的文件,容易出现错误~XD<br>🔥 W2L-TD<br>"
667
+
668
+
669
+ def video_identity(video=gr.Video(), audio=gr.Audio(), face_restore=gr.Radio()):
670
+ input_video = video
671
+ input_audio = audio
672
+ filelist = os.listdir('results/')
673
+ filelists = []
674
+ for i in filelist:
675
+ filelists.append(i.split('.')[0])
676
+ idx = str(np.random.randint(0, 1e7)).zfill(7)
677
+ while (idx in filelists):
678
+ idx = str(np.random.randint(0, 1e7)).zfill(7)
679
+
680
+ # outfile = 'results/' + idx + '.mp4'
681
+ # print(outfile)
682
+ outfile = None
683
+ if int(face_restore) == 1:
684
+ print('main\n' + input_video + '\n' + input_audio + '\n' + str(idx))
685
+ outfile = main(input_video, input_audio, idx=idx)
686
+ else:
687
+ print('facerestore\n' + input_video + '\n' + input_audio + '\n' + str(idx))
688
+ outfile = with_face_restore(input_video, input_audio, idx=idx)
689
+
690
+ out = os.path.join(os.path.dirname(__file__), outfile)
691
+
692
+ return out
693
+
694
+
695
+ demo = gr.Interface(video_identity,
696
+ [
697
+ gr.Video(label='Input Video'),
698
+ gr.Audio(type='filepath', label='Input Audio'),
699
+ gr.Radio(["是", "否"], label="启用人脸修复", value='是', type='index'),
700
+ ],
701
+ "playable_video",
702
+ allow_flagging='never',
703
+ title=title,
704
+ description=description,
705
+ examples=[
706
+ ['media/bbc.mp4', 'media/文本1-男-en-US.mp3', '是'],
707
+ ['media/xwlb.mp4', 'media/文本2-女-en-US.mp3', '是'],
708
+ ['media/wty2.mp4', 'media/文本3-女-en-US.mp3', '是'],
709
+ ['media/ywm.mp4', 'media/文本1-男-zh-CN.mp3', '是'],
710
+ ['media/tq.mp4', 'media/文本2-男-zh-CN.mp3', '是'],
711
+ ['media/lx.mp4', 'media/文本3-男-zh-CN.mp3', '是'],
712
+ ['media/weather1.mp4', 'media/文本4-女-zh-CN.mp3', '是'],
713
+ ['media/biden.mp4', 'media/文本5-女-zh-CN.mp3', '是'],
714
+ ],
715
+ cache_examples=True,
716
+ )
717
+
718
+ if __name__ == "__main__":
719
+ gr.close_all()
720
+ # demo.queue(concurrency_count=3, max_size=6)
721
+ demo.launch(show_error=True, server_port=7860, max_threads=6)
audio.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import librosa
2
+ import librosa.filters
3
+ import numpy as np
4
+ from scipy.io import wavfile
5
+ from scipy import signal
6
+ from hparams import hparams as hp
7
+
8
+ def load_wav(path, sr):
9
+ return librosa.core.load(path, sr=sr)[0]
10
+
11
+ def save_wav(wav, path, sr):
12
+ wav *= 32767 / max(0.01, np.max(np.abs(wav)))
13
+ #proposed by @dsmiller
14
+ wavfile.write(path, sr, wav.astype(np.int16))
15
+
16
+ def save_wavenet_wav(wav, path, sr):
17
+ librosa.output.write_wav(path, wav, sr=sr)
18
+
19
+ def preemphasis(wav, k, preemphasize=True):
20
+ if preemphasize:
21
+ return signal.lfilter([1, -k], [1], wav)
22
+ return wav
23
+
24
+ def inv_preemphasis(wav, k, inv_preemphasize=True):
25
+ if inv_preemphasize:
26
+ return signal.lfilter([1], [1, -k], wav)
27
+ return wav
28
+
29
+ def get_hop_size():
30
+ hop_size = hp.hop_size
31
+ if hop_size is None:
32
+ assert hp.frame_shift_ms is not None
33
+ hop_size = int(hp.frame_shift_ms / 1000 * hp.sample_rate)
34
+ return hop_size
35
+
36
+ def linearspectrogram(wav):
37
+ D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize))
38
+ S = _amp_to_db(np.abs(D)) - hp.ref_level_db
39
+
40
+ if hp.signal_normalization:
41
+ return _normalize(S)
42
+ return S
43
+
44
+ def melspectrogram(wav):
45
+ D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize))
46
+ S = _amp_to_db(_linear_to_mel(np.abs(D))) - hp.ref_level_db
47
+
48
+ if hp.signal_normalization:
49
+ return _normalize(S)
50
+ return S
51
+
52
+ def _lws_processor():
53
+ import lws
54
+ return lws.lws(hp.n_fft, get_hop_size(), fftsize=hp.win_size, mode="speech")
55
+
56
+ def _stft(y):
57
+ if hp.use_lws:
58
+ return _lws_processor(hp).stft(y).T
59
+ else:
60
+ return librosa.stft(y=y, n_fft=hp.n_fft, hop_length=get_hop_size(), win_length=hp.win_size)
61
+
62
+ ##########################################################
63
+ #Those are only correct when using lws!!! (This was messing with Wavenet quality for a long time!)
64
+ def num_frames(length, fsize, fshift):
65
+ """Compute number of time frames of spectrogram
66
+ """
67
+ pad = (fsize - fshift)
68
+ if length % fshift == 0:
69
+ M = (length + pad * 2 - fsize) // fshift + 1
70
+ else:
71
+ M = (length + pad * 2 - fsize) // fshift + 2
72
+ return M
73
+
74
+
75
+ def pad_lr(x, fsize, fshift):
76
+ """Compute left and right padding
77
+ """
78
+ M = num_frames(len(x), fsize, fshift)
79
+ pad = (fsize - fshift)
80
+ T = len(x) + 2 * pad
81
+ r = (M - 1) * fshift + fsize - T
82
+ return pad, pad + r
83
+ ##########################################################
84
+ #Librosa correct padding
85
+ def librosa_pad_lr(x, fsize, fshift):
86
+ return 0, (x.shape[0] // fshift + 1) * fshift - x.shape[0]
87
+
88
+ # Conversions
89
+ _mel_basis = None
90
+
91
+ def _linear_to_mel(spectogram):
92
+ global _mel_basis
93
+ if _mel_basis is None:
94
+ _mel_basis = _build_mel_basis()
95
+ return np.dot(_mel_basis, spectogram)
96
+
97
+ def _build_mel_basis():
98
+ assert hp.fmax <= hp.sample_rate // 2
99
+ return librosa.filters.mel(hp.sample_rate, hp.n_fft, n_mels=hp.num_mels,
100
+ fmin=hp.fmin, fmax=hp.fmax)
101
+
102
+ def _amp_to_db(x):
103
+ min_level = np.exp(hp.min_level_db / 20 * np.log(10))
104
+ return 20 * np.log10(np.maximum(min_level, x))
105
+
106
+ def _db_to_amp(x):
107
+ return np.power(10.0, (x) * 0.05)
108
+
109
+ def _normalize(S):
110
+ if hp.allow_clipping_in_normalization:
111
+ if hp.symmetric_mels:
112
+ return np.clip((2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value,
113
+ -hp.max_abs_value, hp.max_abs_value)
114
+ else:
115
+ return np.clip(hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)), 0, hp.max_abs_value)
116
+
117
+ assert S.max() <= 0 and S.min() - hp.min_level_db >= 0
118
+ if hp.symmetric_mels:
119
+ return (2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value
120
+ else:
121
+ return hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db))
122
+
123
+ def _denormalize(D):
124
+ if hp.allow_clipping_in_normalization:
125
+ if hp.symmetric_mels:
126
+ return (((np.clip(D, -hp.max_abs_value,
127
+ hp.max_abs_value) + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value))
128
+ + hp.min_level_db)
129
+ else:
130
+ return ((np.clip(D, 0, hp.max_abs_value) * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db)
131
+
132
+ if hp.symmetric_mels:
133
+ return (((D + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db)
134
+ else:
135
+ return ((D * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db)
hparams.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from glob import glob
2
+ import os
3
+
4
+ def get_image_list(data_root, split):
5
+ filelist = []
6
+
7
+ with open('filelists/{}.txt'.format(split)) as f:
8
+ for line in f:
9
+ line = line.strip()
10
+ if ' ' in line: line = line.split()[0]
11
+ filelist.append(os.path.join(data_root, line))
12
+
13
+ return filelist
14
+
15
+ class HParams:
16
+ def __init__(self, **kwargs):
17
+ self.data = {}
18
+
19
+ for key, value in kwargs.items():
20
+ self.data[key] = value
21
+
22
+ def __getattr__(self, key):
23
+ if key not in self.data:
24
+ raise AttributeError("'HParams' object has no attribute %s" % key)
25
+ return self.data[key]
26
+
27
+ def set_hparam(self, key, value):
28
+ self.data[key] = value
29
+
30
+
31
+ # Default hyperparameters
32
+ hparams = HParams(
33
+ num_mels=80, # Number of mel-spectrogram channels and local conditioning dimensionality
34
+ # network
35
+ rescale=True, # Whether to rescale audio prior to preprocessing
36
+ rescaling_max=0.9, # Rescaling value
37
+
38
+ # Use LWS (https://github.com/Jonathan-LeRoux/lws) for STFT and phase reconstruction
39
+ # It"s preferred to set True to use with https://github.com/r9y9/wavenet_vocoder
40
+ # Does not work if n_ffit is not multiple of hop_size!!
41
+ use_lws=False,
42
+
43
+ n_fft=800, # Extra window size is filled with 0 paddings to match this parameter
44
+ hop_size=200, # For 16000Hz, 200 = 12.5 ms (0.0125 * sample_rate)
45
+ win_size=800, # For 16000Hz, 800 = 50 ms (If None, win_size = n_fft) (0.05 * sample_rate)
46
+ sample_rate=16000, # 16000Hz (corresponding to librispeech) (sox --i <filename>)
47
+
48
+ frame_shift_ms=None, # Can replace hop_size parameter. (Recommended: 12.5)
49
+
50
+ # Mel and Linear spectrograms normalization/scaling and clipping
51
+ signal_normalization=True,
52
+ # Whether to normalize mel spectrograms to some predefined range (following below parameters)
53
+ allow_clipping_in_normalization=True, # Only relevant if mel_normalization = True
54
+ symmetric_mels=True,
55
+ # Whether to scale the data to be symmetric around 0. (Also multiplies the output range by 2,
56
+ # faster and cleaner convergence)
57
+ max_abs_value=4.,
58
+ # max absolute value of data. If symmetric, data will be [-max, max] else [0, max] (Must not
59
+ # be too big to avoid gradient explosion,
60
+ # not too small for fast convergence)
61
+ # Contribution by @begeekmyfriend
62
+ # Spectrogram Pre-Emphasis (Lfilter: Reduce spectrogram noise and helps model certitude
63
+ # levels. Also allows for better G&L phase reconstruction)
64
+ preemphasize=True, # whether to apply filter
65
+ preemphasis=0.97, # filter coefficient.
66
+
67
+ # Limits
68
+ min_level_db=-100,
69
+ ref_level_db=20,
70
+ fmin=55,
71
+ # Set this to 55 if your speaker is male! if female, 95 should help taking off noise. (To
72
+ # test depending on dataset. Pitch info: male~[65, 260], female~[100, 525])
73
+ fmax=7600, # To be increased/reduced depending on data.
74
+
75
+ ###################### Our training parameters #################################
76
+ img_size=96,
77
+ fps=25,
78
+
79
+ batch_size=16,
80
+ initial_learning_rate=1e-4,
81
+ nepochs=200000000000000000, ### ctrl + c, stop whenever eval loss is consistently greater than train loss for ~10 epochs
82
+ num_workers=0,
83
+ checkpoint_interval=3000,
84
+ eval_interval=3000,
85
+ save_optimizer_state=True,
86
+
87
+ syncnet_wt=0.0, # is initially zero, will be set automatically to 0.03 later. Leads to faster convergence.
88
+ syncnet_batch_size=64,
89
+ syncnet_lr=1e-4,
90
+ syncnet_eval_interval=10000,
91
+ syncnet_checkpoint_interval=10000,
92
+
93
+ disc_wt=0.07,
94
+ disc_initial_learning_rate=1e-4,
95
+ )
96
+
97
+
98
+ def hparams_debug_string():
99
+ values = hparams.values()
100
+ hp = [" %s: %s" % (name, values[name]) for name in sorted(values) if name != "sentences"]
101
+ return "Hyperparameters:\n" + "\n".join(hp)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ librosa==0.8.0
2
+ numpy==1.23.5
3
+ scikit-learn==1.0.1
4
+ tqdm==4.65.0
5
+ onnxruntime==1.12.0
6
+ opencv-python==4.7.0.72