quantumos commited on
Commit
726f9ef
·
verified ·
1 Parent(s): 4eb7c59

Update inference-orginal.py

Browse files
Files changed (1) hide show
  1. inference-orginal.py +277 -277
inference-orginal.py CHANGED
@@ -1,277 +1,277 @@
1
- import argparse
2
-
3
- import os
4
- import cv2
5
- import numpy as np
6
- import torch
7
- import torchaudio.functional
8
- import torchvision.io
9
- from PIL import Image
10
- from diffusers import AutoencoderKL, DDIMScheduler
11
- from diffusers.utils.import_utils import is_xformers_available
12
- from diffusers.utils.torch_utils import randn_tensor
13
- from insightface.app import FaceAnalysis
14
- from omegaconf import OmegaConf
15
- from transformers import CLIPVisionModelWithProjection, Wav2Vec2Model, Wav2Vec2Processor
16
-
17
- from modules import UNet2DConditionModel, UNet3DConditionModel, VKpsGuider, AudioProjection
18
- from pipelines import VExpressPipeline
19
- from pipelines.utils import draw_kps_image, save_video
20
- from pipelines.utils import retarget_kps
21
-
22
-
23
- def parse_args():
24
- parser = argparse.ArgumentParser()
25
-
26
- parser.add_argument('--unet_config_path', type=str, default='./model_ckpts/stable-diffusion-v1-5/unet/config.json')
27
- parser.add_argument('--vae_path', type=str, default='./model_ckpts/sd-vae-ft-mse/')
28
- parser.add_argument('--audio_encoder_path', type=str, default='./model_ckpts/wav2vec2-base-960h/')
29
- parser.add_argument('--insightface_model_path', type=str, default='./model_ckpts/insightface_models/')
30
-
31
- parser.add_argument('--denoising_unet_path', type=str, default='./model_ckpts/v-express/denoising_unet.bin')
32
- parser.add_argument('--reference_net_path', type=str, default='./model_ckpts/v-express/reference_net.bin')
33
- parser.add_argument('--v_kps_guider_path', type=str, default='./model_ckpts/v-express/v_kps_guider.bin')
34
- parser.add_argument('--audio_projection_path', type=str, default='./model_ckpts/v-express/audio_projection.bin')
35
- parser.add_argument('--motion_module_path', type=str, default='./model_ckpts/v-express/motion_module.bin')
36
-
37
- parser.add_argument('--retarget_strategy', type=str, default='fix_face') # fix_face, no_retarget, offset_retarget, naive_retarget
38
-
39
- parser.add_argument('--device', type=str, default='cuda')
40
- parser.add_argument('--gpu_id', type=int, default=0)
41
- parser.add_argument('--dtype', type=str, default='fp16')
42
-
43
- parser.add_argument('--num_pad_audio_frames', type=int, default=2)
44
- parser.add_argument('--standard_audio_sampling_rate', type=int, default=16000)
45
-
46
- parser.add_argument('--reference_image_path', type=str, default='./test_samples/emo/talk_emotion/ref.jpg')
47
- parser.add_argument('--audio_path', type=str, default='./test_samples/emo/talk_emotion/aud.mp3')
48
- parser.add_argument('--kps_path', type=str, default='./test_samples/emo/talk_emotion/kps.pth')
49
- parser.add_argument('--output_path', type=str, default='./output/emo/talk_emotion.mp4')
50
-
51
- parser.add_argument('--image_width', type=int, default=512)
52
- parser.add_argument('--image_height', type=int, default=512)
53
- parser.add_argument('--fps', type=float, default=30.0)
54
- parser.add_argument('--seed', type=int, default=42)
55
- parser.add_argument('--num_inference_steps', type=int, default=25)
56
- parser.add_argument('--guidance_scale', type=float, default=3.5)
57
- parser.add_argument('--context_frames', type=int, default=12)
58
- parser.add_argument('--context_stride', type=int, default=1)
59
- parser.add_argument('--context_overlap', type=int, default=4)
60
- parser.add_argument('--reference_attention_weight', default=0.95, type=float)
61
- parser.add_argument('--audio_attention_weight', default=3., type=float)
62
-
63
- args = parser.parse_args()
64
-
65
- return args
66
-
67
-
68
- def load_reference_net(unet_config_path, reference_net_path, dtype, device):
69
- reference_net = UNet2DConditionModel.from_config(unet_config_path).to(dtype=dtype, device=device)
70
- reference_net.load_state_dict(torch.load(reference_net_path, map_location="cpu"), strict=False)
71
- print(f'Loaded weights of Reference Net from {reference_net_path}.')
72
- return reference_net
73
-
74
-
75
- def load_denoising_unet(inference_config_path, unet_config_path, denoising_unet_path, motion_module_path, dtype, device):
76
- inference_config = OmegaConf.load(inference_config_path)
77
- denoising_unet = UNet3DConditionModel.from_config_2d(
78
- unet_config_path,
79
- unet_additional_kwargs=inference_config.unet_additional_kwargs,
80
- ).to(dtype=dtype, device=device)
81
- denoising_unet.load_state_dict(torch.load(denoising_unet_path, map_location="cpu"), strict=False)
82
- print(f'Loaded weights of Denoising U-Net from {denoising_unet_path}.')
83
-
84
- denoising_unet.load_state_dict(torch.load(motion_module_path, map_location="cpu"), strict=False)
85
- print(f'Loaded weights of Denoising U-Net Motion Module from {motion_module_path}.')
86
-
87
- return denoising_unet
88
-
89
-
90
- def load_v_kps_guider(v_kps_guider_path, dtype, device):
91
- v_kps_guider = VKpsGuider(320, block_out_channels=(16, 32, 96, 256)).to(dtype=dtype, device=device)
92
- v_kps_guider.load_state_dict(torch.load(v_kps_guider_path, map_location="cpu"))
93
- print(f'Loaded weights of V-Kps Guider from {v_kps_guider_path}.')
94
- return v_kps_guider
95
-
96
-
97
- def load_audio_projection(
98
- audio_projection_path,
99
- dtype,
100
- device,
101
- inp_dim: int,
102
- mid_dim: int,
103
- out_dim: int,
104
- inp_seq_len: int,
105
- out_seq_len: int,
106
- ):
107
- audio_projection = AudioProjection(
108
- dim=mid_dim,
109
- depth=4,
110
- dim_head=64,
111
- heads=12,
112
- num_queries=out_seq_len,
113
- embedding_dim=inp_dim,
114
- output_dim=out_dim,
115
- ff_mult=4,
116
- max_seq_len=inp_seq_len,
117
- ).to(dtype=dtype, device=device)
118
- audio_projection.load_state_dict(torch.load(audio_projection_path, map_location='cpu'))
119
- print(f'Loaded weights of Audio Projection from {audio_projection_path}.')
120
- return audio_projection
121
-
122
-
123
- def get_scheduler(inference_config_path):
124
- inference_config = OmegaConf.load(inference_config_path)
125
- scheduler_kwargs = OmegaConf.to_container(inference_config.noise_scheduler_kwargs)
126
- scheduler = DDIMScheduler(**scheduler_kwargs)
127
- return scheduler
128
-
129
-
130
- def main():
131
- args = parse_args()
132
-
133
- device = torch.device(f'{args.device}:{args.gpu_id}' if args.device == 'cuda' else args.device)
134
- dtype = torch.float16 if args.dtype == 'fp16' else torch.float32
135
-
136
- vae_path = args.vae_path
137
- audio_encoder_path = args.audio_encoder_path
138
-
139
- vae = AutoencoderKL.from_pretrained(vae_path).to(dtype=dtype, device=device)
140
- audio_encoder = Wav2Vec2Model.from_pretrained(audio_encoder_path).to(dtype=dtype, device=device)
141
- audio_processor = Wav2Vec2Processor.from_pretrained(audio_encoder_path)
142
-
143
- unet_config_path = args.unet_config_path
144
- reference_net_path = args.reference_net_path
145
- denoising_unet_path = args.denoising_unet_path
146
- v_kps_guider_path = args.v_kps_guider_path
147
- audio_projection_path = args.audio_projection_path
148
- motion_module_path = args.motion_module_path
149
-
150
- inference_config_path = './inference_v2.yaml'
151
- scheduler = get_scheduler(inference_config_path)
152
- reference_net = load_reference_net(unet_config_path, reference_net_path, dtype, device)
153
- denoising_unet = load_denoising_unet(
154
- inference_config_path, unet_config_path, denoising_unet_path, motion_module_path,
155
- dtype, device
156
- )
157
- v_kps_guider = load_v_kps_guider(v_kps_guider_path, dtype, device)
158
- audio_projection = load_audio_projection(
159
- audio_projection_path,
160
- dtype,
161
- device,
162
- inp_dim=denoising_unet.config.cross_attention_dim,
163
- mid_dim=denoising_unet.config.cross_attention_dim,
164
- out_dim=denoising_unet.config.cross_attention_dim,
165
- inp_seq_len=2 * (2 * args.num_pad_audio_frames + 1),
166
- out_seq_len=2 * args.num_pad_audio_frames + 1,
167
- )
168
-
169
- if is_xformers_available():
170
- reference_net.enable_xformers_memory_efficient_attention()
171
- denoising_unet.enable_xformers_memory_efficient_attention()
172
- else:
173
- raise ValueError("xformers is not available. Make sure it is installed correctly")
174
-
175
- generator = torch.manual_seed(args.seed)
176
- pipeline = VExpressPipeline(
177
- vae=vae,
178
- reference_net=reference_net,
179
- denoising_unet=denoising_unet,
180
- v_kps_guider=v_kps_guider,
181
- audio_processor=audio_processor,
182
- audio_encoder=audio_encoder,
183
- audio_projection=audio_projection,
184
- scheduler=scheduler,
185
- ).to(dtype=dtype, device=device)
186
-
187
- app = FaceAnalysis(
188
- providers=['CUDAExecutionProvider' if args.device == 'cuda' else 'CPUExecutionProvider'],
189
- provider_options=[{'device_id': args.gpu_id}] if args.device == 'cuda' else [],
190
- root=args.insightface_model_path,
191
- )
192
- app.prepare(ctx_id=0, det_size=(args.image_height, args.image_width))
193
-
194
- reference_image = Image.open(args.reference_image_path).convert('RGB')
195
- reference_image = reference_image.resize((args.image_height, args.image_width))
196
-
197
- reference_image_for_kps = cv2.imread(args.reference_image_path)
198
- reference_image_for_kps = cv2.resize(reference_image_for_kps, (args.image_width, args.image_height))
199
- reference_kps = app.get(reference_image_for_kps)[0].kps[:3]
200
-
201
- _, audio_waveform, meta_info = torchvision.io.read_video(args.audio_path, pts_unit='sec')
202
- audio_sampling_rate = meta_info['audio_fps']
203
- print(f'Length of audio is {audio_waveform.shape[1]} with the sampling rate of {audio_sampling_rate}.')
204
- if audio_sampling_rate != args.standard_audio_sampling_rate:
205
- audio_waveform = torchaudio.functional.resample(
206
- audio_waveform,
207
- orig_freq=audio_sampling_rate,
208
- new_freq=args.standard_audio_sampling_rate,
209
- )
210
- audio_waveform = audio_waveform.mean(dim=0)
211
-
212
- duration = audio_waveform.shape[0] / args.standard_audio_sampling_rate
213
- video_length = int(duration * args.fps)
214
- print(f'The corresponding video length is {video_length}.')
215
-
216
- if args.kps_path != "":
217
- assert os.path.exists(args.kps_path), f'{args.kps_path} does not exist'
218
- kps_sequence = torch.tensor(torch.load(args.kps_path)) # [len, 3, 2]
219
- print(f'The original length of kps sequence is {kps_sequence.shape[0]}.')
220
- kps_sequence = torch.nn.functional.interpolate(kps_sequence.permute(1, 2, 0), size=video_length, mode='linear')
221
- kps_sequence = kps_sequence.permute(2, 0, 1)
222
- print(f'The interpolated length of kps sequence is {kps_sequence.shape[0]}.')
223
-
224
- retarget_strategy = args.retarget_strategy
225
- if retarget_strategy == 'fix_face':
226
- kps_sequence = torch.tensor([reference_kps] * video_length)
227
- elif retarget_strategy == 'no_retarget':
228
- kps_sequence = kps_sequence
229
- elif retarget_strategy == 'offset_retarget':
230
- kps_sequence = retarget_kps(reference_kps, kps_sequence, only_offset=True)
231
- elif retarget_strategy == 'naive_retarget':
232
- kps_sequence = retarget_kps(reference_kps, kps_sequence, only_offset=False)
233
- else:
234
- raise ValueError(f'The retarget strategy {retarget_strategy} is not supported.')
235
-
236
- kps_images = []
237
- for i in range(video_length):
238
- kps_image = np.zeros_like(reference_image_for_kps)
239
- kps_image = draw_kps_image(kps_image, kps_sequence[i])
240
- kps_images.append(Image.fromarray(kps_image))
241
-
242
- vae_scale_factor = 8
243
- latent_height = args.image_height // vae_scale_factor
244
- latent_width = args.image_width // vae_scale_factor
245
-
246
- latent_shape = (1, 4, video_length, latent_height, latent_width)
247
- vae_latents = randn_tensor(latent_shape, generator=generator, device=device, dtype=dtype)
248
-
249
- video_latents = pipeline(
250
- vae_latents=vae_latents,
251
- reference_image=reference_image,
252
- kps_images=kps_images,
253
- audio_waveform=audio_waveform,
254
- width=args.image_width,
255
- height=args.image_height,
256
- video_length=video_length,
257
- num_inference_steps=args.num_inference_steps,
258
- guidance_scale=args.guidance_scale,
259
- context_frames=args.context_frames,
260
- context_stride=args.context_stride,
261
- context_overlap=args.context_overlap,
262
- reference_attention_weight=args.reference_attention_weight,
263
- audio_attention_weight=args.audio_attention_weight,
264
- num_pad_audio_frames=args.num_pad_audio_frames,
265
- generator=generator,
266
- ).video_latents
267
-
268
- video_tensor = pipeline.decode_latents(video_latents)
269
- if isinstance(video_tensor, np.ndarray):
270
- video_tensor = torch.from_numpy(video_tensor)
271
-
272
- save_video(video_tensor, args.audio_path, args.output_path, args.fps)
273
- print(f'The generated video has been saved at {args.output_path}.')
274
-
275
-
276
- if __name__ == '__main__':
277
- main()
 
1
+ import argparse
2
+
3
+ import os
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+ import torchaudio.functional
8
+ import torchvision.io
9
+ from PIL import Image
10
+ from diffusers import AutoencoderKL, DDIMScheduler
11
+ from diffusers.utils.import_utils import is_xformers_available
12
+ from diffusers.utils.torch_utils import randn_tensor
13
+ from insightface.app import FaceAnalysis
14
+ from omegaconf import OmegaConf
15
+ from transformers import CLIPVisionModelWithProjection, Wav2Vec2Model, Wav2Vec2Processor
16
+
17
+ from modules import UNet2DConditionModel, UNet3DConditionModel, VKpsGuider, AudioProjection
18
+ from pipelines import VExpressPipeline
19
+ from pipelines.utils import draw_kps_image, save_video
20
+ from pipelines.utils import retarget_kps
21
+
22
+
23
+ def parse_args():
24
+ parser = argparse.ArgumentParser()
25
+
26
+ parser.add_argument('--unet_config_path', type=str, default='./model_ckpts/stable-diffusion-v1-5/unet/config.json')
27
+ parser.add_argument('--vae_path', type=str, default='./model_ckpts/sd-vae-ft-mse/')
28
+ parser.add_argument('--audio_encoder_path', type=str, default='./model_ckpts/wav2vec2-base-960h/')
29
+ parser.add_argument('--insightface_model_path', type=str, default='./model_ckpts/insightface_models/')
30
+
31
+ parser.add_argument('--denoising_unet_path', type=str, default='./model_ckpts/v-express/denoising_unet.bin')
32
+ parser.add_argument('--reference_net_path', type=str, default='./model_ckpts/v-express/reference_net.bin')
33
+ parser.add_argument('--v_kps_guider_path', type=str, default='./model_ckpts/v-express/v_kps_guider.bin')
34
+ parser.add_argument('--audio_projection_path', type=str, default='./model_ckpts/v-express/audio_projection.bin')
35
+ parser.add_argument('--motion_module_path', type=str, default='./model_ckpts/v-express/motion_module.bin')
36
+
37
+ parser.add_argument('--retarget_strategy', type=str, default='fix_face') # fix_face, no_retarget, offset_retarget, naive_retarget
38
+
39
+ parser.add_argument('--device', type=str, default='cuda')
40
+ parser.add_argument('--gpu_id', type=int, default=0)
41
+ parser.add_argument('--dtype', type=str, default='fp16')
42
+
43
+ parser.add_argument('--num_pad_audio_frames', type=int, default=2)
44
+ parser.add_argument('--standard_audio_sampling_rate', type=int, default=16000)
45
+
46
+ parser.add_argument('--reference_image_path', type=str, default='./test_samples/emo/talk_emotion/ref.jpg')
47
+ parser.add_argument('--audio_path', type=str, default='./test_samples/emo/talk_emotion/aud.mp3')
48
+ parser.add_argument('--kps_path', type=str, default='./test_samples/emo/talk_emotion/kps.pth')
49
+ parser.add_argument('--output_path', type=str, default='./output/emo/talk_emotion.mp4')
50
+
51
+ parser.add_argument('--image_width', type=int, default=512)
52
+ parser.add_argument('--image_height', type=int, default=512)
53
+ parser.add_argument('--fps', type=float, default=30.0)
54
+ parser.add_argument('--seed', type=int, default=42)
55
+ parser.add_argument('--num_inference_steps', type=int, default=25)
56
+ parser.add_argument('--guidance_scale', type=float, default=3.5)
57
+ parser.add_argument('--context_frames', type=int, default=12)
58
+ parser.add_argument('--context_stride', type=int, default=1)
59
+ parser.add_argument('--context_overlap', type=int, default=4)
60
+ parser.add_argument('--reference_attention_weight', default=0.95, type=float)
61
+ parser.add_argument('--audio_attention_weight', default=3., type=float)
62
+
63
+ args = parser.parse_args()
64
+
65
+ return args
66
+
67
+
68
+ def load_reference_net(unet_config_path, reference_net_path, dtype, device):
69
+ reference_net = UNet2DConditionModel.from_config(unet_config_path).to(dtype=dtype, device=device)
70
+ reference_net.load_state_dict(torch.load(reference_net_path, map_location="cpu"), strict=False)
71
+ print(f'Loaded weights of Reference Net from {reference_net_path}.')
72
+ return reference_net
73
+
74
+
75
+ def load_denoising_unet(inference_config_path, unet_config_path, denoising_unet_path, motion_module_path, dtype, device):
76
+ inference_config = OmegaConf.load(inference_config_path)
77
+ denoising_unet = UNet3DConditionModel.from_config_2d(
78
+ unet_config_path,
79
+ unet_additional_kwargs=inference_config.unet_additional_kwargs,
80
+ ).to(dtype=dtype, device=device)
81
+ denoising_unet.load_state_dict(torch.load(denoising_unet_path, map_location="cpu"), strict=False)
82
+ print(f'Loaded weights of Denoising U-Net from {denoising_unet_path}.')
83
+
84
+ denoising_unet.load_state_dict(torch.load(motion_module_path, map_location="cpu"), strict=False)
85
+ print(f'Loaded weights of Denoising U-Net Motion Module from {motion_module_path}.')
86
+
87
+ return denoising_unet
88
+
89
+
90
+ def load_v_kps_guider(v_kps_guider_path, dtype, device):
91
+ v_kps_guider = VKpsGuider(320, block_out_channels=(16, 32, 96, 256)).to(dtype=dtype, device=device)
92
+ v_kps_guider.load_state_dict(torch.load(v_kps_guider_path, map_location="cpu"))
93
+ print(f'Loaded weights of V-Kps Guider from {v_kps_guider_path}.')
94
+ return v_kps_guider
95
+
96
+
97
+ def load_audio_projection(
98
+ audio_projection_path,
99
+ dtype,
100
+ device,
101
+ inp_dim: int,
102
+ mid_dim: int,
103
+ out_dim: int,
104
+ inp_seq_len: int,
105
+ out_seq_len: int,
106
+ ):
107
+ audio_projection = AudioProjection(
108
+ dim=mid_dim,
109
+ depth=4,
110
+ dim_head=64,
111
+ heads=12,
112
+ num_queries=out_seq_len,
113
+ embedding_dim=inp_dim,
114
+ output_dim=out_dim,
115
+ ff_mult=4,
116
+ max_seq_len=inp_seq_len,
117
+ ).to(dtype=dtype, device=device)
118
+ audio_projection.load_state_dict(torch.load(audio_projection_path, map_location='cpu'))
119
+ print(f'Loaded weights of Audio Projection from {audio_projection_path}.')
120
+ return audio_projection
121
+
122
+
123
+ def get_scheduler(inference_config_path):
124
+ inference_config = OmegaConf.load(inference_config_path)
125
+ scheduler_kwargs = OmegaConf.to_container(inference_config.noise_scheduler_kwargs)
126
+ scheduler = DDIMScheduler(**scheduler_kwargs)
127
+ return scheduler
128
+
129
+
130
+ def main():
131
+ args = parse_args()
132
+
133
+ device = torch.device(f'{args.device}:{args.gpu_id}' if args.device == 'cuda' else args.device)
134
+ dtype = torch.float16 if args.dtype == 'fp16' else torch.float32
135
+
136
+ vae_path = args.vae_path
137
+ audio_encoder_path = args.audio_encoder_path
138
+
139
+ vae = AutoencoderKL.from_pretrained(vae_path).to(dtype=dtype, device=device)
140
+ audio_encoder = Wav2Vec2Model.from_pretrained(audio_encoder_path).to(dtype=dtype, device=device)
141
+ audio_processor = Wav2Vec2Processor.from_pretrained(audio_encoder_path)
142
+
143
+ unet_config_path = args.unet_config_path
144
+ reference_net_path = args.reference_net_path
145
+ denoising_unet_path = args.denoising_unet_path
146
+ v_kps_guider_path = args.v_kps_guider_path
147
+ audio_projection_path = args.audio_projection_path
148
+ motion_module_path = args.motion_module_path
149
+
150
+ inference_config_path = './inference_v2.yaml'
151
+ scheduler = get_scheduler(inference_config_path)
152
+ reference_net = load_reference_net(unet_config_path, reference_net_path, dtype, device)
153
+ denoising_unet = load_denoising_unet(
154
+ inference_config_path, unet_config_path, denoising_unet_path, motion_module_path,
155
+ dtype, device
156
+ )
157
+ v_kps_guider = load_v_kps_guider(v_kps_guider_path, dtype, device)
158
+ audio_projection = load_audio_projection(
159
+ audio_projection_path,
160
+ dtype,
161
+ device,
162
+ inp_dim=denoising_unet.config.cross_attention_dim,
163
+ mid_dim=denoising_unet.config.cross_attention_dim,
164
+ out_dim=denoising_unet.config.cross_attention_dim,
165
+ inp_seq_len=2 * (2 * args.num_pad_audio_frames + 1),
166
+ out_seq_len=2 * args.num_pad_audio_frames + 1,
167
+ )
168
+
169
+ if is_xformers_available():
170
+ reference_net.enable_xformers_memory_efficient_attention()
171
+ denoising_unet.enable_xformers_memory_efficient_attention()
172
+ else:
173
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
174
+
175
+ generator = torch.manual_seed(args.seed)
176
+ pipeline = VExpressPipeline(
177
+ vae=vae,
178
+ reference_net=reference_net,
179
+ denoising_unet=denoising_unet,
180
+ v_kps_guider=v_kps_guider,
181
+ audio_processor=audio_processor,
182
+ audio_encoder=audio_encoder,
183
+ audio_projection=audio_projection,
184
+ scheduler=scheduler,
185
+ ).to(dtype=dtype, device=device)
186
+
187
+ app = FaceAnalysis(
188
+ providers=['CUDAExecutionProvider' if args.device == 'cuda' else 'CPUExecutionProvider'],
189
+ provider_options=[{'device_id': args.gpu_id}] if args.device == 'cuda' else [],
190
+ root=args.insightface_model_path,
191
+ )
192
+ app.prepare(ctx_id=0, det_size=(args.image_height, args.image_width))
193
+
194
+ reference_image = Image.open(args.reference_image_path).convert('RGB')
195
+ reference_image = reference_image.resize((args.image_height, args.image_width))
196
+
197
+ reference_image_for_kps = cv2.imread(args.reference_image_path)
198
+ reference_image_for_kps = cv2.resize(reference_image_for_kps, (args.image_width, args.image_height))
199
+ reference_kps = app.get(reference_image_for_kps)[0].kps[:3]
200
+
201
+ _, audio_waveform, meta_info = torchvision.io.read_video(args.audio_path, pts_unit='sec')
202
+ audio_sampling_rate = meta_info['audio_fps']
203
+ print(f'Length of audio is {audio_waveform.shape[1]} with the sampling rate of {audio_sampling_rate}.')
204
+ if audio_sampling_rate != args.standard_audio_sampling_rate:
205
+ audio_waveform = torchaudio.functional.resample(
206
+ audio_waveform,
207
+ orig_freq=audio_sampling_rate,
208
+ new_freq=args.standard_audio_sampling_rate,
209
+ )
210
+ audio_waveform = audio_waveform.mean(dim=0)
211
+
212
+ duration = audio_waveform.shape[0] / args.standard_audio_sampling_rate
213
+ video_length = int(duration * args.fps)
214
+ print(f'The corresponding video length is {video_length}.')
215
+
216
+ if args.kps_path != "":
217
+ assert os.path.exists(args.kps_path), f'{args.kps_path} does not exist'
218
+ kps_sequence = torch.tensor(torch.load(args.kps_path)) # [len, 3, 2]
219
+ print(f'The original length of kps sequence is {kps_sequence.shape[0]}.')
220
+ kps_sequence = torch.nn.functional.interpolate(kps_sequence.permute(1, 2, 0), size=video_length, mode='linear')
221
+ kps_sequence = kps_sequence.permute(2, 0, 1)
222
+ print(f'The interpolated length of kps sequence is {kps_sequence.shape[0]}.')
223
+
224
+ retarget_strategy = args.retarget_strategy
225
+ if retarget_strategy == 'fix_face':
226
+ kps_sequence = torch.tensor([reference_kps] * video_length)
227
+ elif retarget_strategy == 'no_retarget':
228
+ kps_sequence = kps_sequence
229
+ elif retarget_strategy == 'offset_retarget':
230
+ kps_sequence = retarget_kps(reference_kps, kps_sequence, only_offset=True)
231
+ elif retarget_strategy == 'naive_retarget':
232
+ kps_sequence = retarget_kps(reference_kps, kps_sequence, only_offset=False)
233
+ else:
234
+ raise ValueError(f'The retarget strategy {retarget_strategy} is not supported.')
235
+
236
+ kps_images = []
237
+ for i in range(video_length):
238
+ kps_image = np.zeros_like(reference_image_for_kps)
239
+ kps_image = draw_kps_image(kps_image, kps_sequence[i])
240
+ kps_images.append(Image.fromarray(kps_image))
241
+
242
+ vae_scale_factor = 8
243
+ latent_height = args.image_height // vae_scale_factor
244
+ latent_width = args.image_width // vae_scale_factor
245
+
246
+ latent_shape = (1, 4, video_length, latent_height, latent_width)
247
+ vae_latents = randn_tensor(latent_shape, generator=generator, device=device, dtype=dtype)
248
+
249
+ video_latents = pipeline(
250
+ vae_latents=vae_latents,
251
+ reference_image=reference_image,
252
+ kps_images=kps_images,
253
+ audio_waveform=audio_waveform,
254
+ width=args.image_width,
255
+ height=args.image_height,
256
+ video_length=video_length,
257
+ num_inference_steps=args.num_inference_steps,
258
+ guidance_scale=args.guidance_scale,
259
+ context_frames=args.context_frames,
260
+ context_stride=args.context_stride,
261
+ context_overlap=args.context_overlap,
262
+ reference_attention_weight=args.reference_attention_weight,
263
+ audio_attention_weight=args.audio_attention_weight,
264
+ num_pad_audio_frames=args.num_pad_audio_frames,
265
+ generator=generator,
266
+ ).video_latents
267
+
268
+ video_tensor = pipeline.decode_latents(video_latents)
269
+ if isinstance(video_tensor, np.ndarray):
270
+ video_tensor = torch.from_numpy(video_tensor)
271
+
272
+ save_video(video_tensor, args.audio_path, args.output_path, args.fps)
273
+ print(f'The generated video has been saved at {args.output_path}.')
274
+
275
+
276
+ if __name__ == '__main__':
277
+ main()