czk32611 commited on
Commit
1e64633
·
1 Parent(s): f7602ff

Add codes for real time inference

Browse files
README.md CHANGED
@@ -11,7 +11,7 @@ Chao Zhan,
11
  Wenjiang Zhou
12
  (<sup>*</sup>Equal Contribution, <sup>†</sup>Corresponding Author, benbinwu@tencent.com)
13
 
14
- **[github](https://github.com/TMElyralab/MuseTalk)** **[huggingface](https://huggingface.co/TMElyralab/MuseTalk)** **[gradio](https://huggingface.co/spaces/TMElyralab/MuseTalk)** **Project (comming soon)** **Technical report (comming soon)**
15
 
16
  We introduce `MuseTalk`, a **real-time high quality** lip-syncing model (30fps+ on an NVIDIA Tesla V100). MuseTalk can be applied with input videos, e.g., generated by [MuseV](https://github.com/TMElyralab/MuseV), as a complete virtual human solution.
17
 
@@ -28,12 +28,13 @@ We introduce `MuseTalk`, a **real-time high quality** lip-syncing model (30fps+
28
  # News
29
  - [04/02/2024] Release MuseTalk project and pretrained models.
30
  - [04/16/2024] Release Gradio [demo](https://huggingface.co/spaces/TMElyralab/MuseTalk) on HuggingFace Spaces (thanks to HF team for their community grant)
 
31
 
32
  ## Model
33
  ![Model Structure](assets/figs/musetalk_arc.jpg)
34
  MuseTalk was trained in latent spaces, where the images were encoded by a freezed VAE. The audio was encoded by a freezed `whisper-tiny` model. The architecture of the generation network was borrowed from the UNet of the `stable-diffusion-v1-4`, where the audio embeddings were fused to the image embeddings by cross-attention.
35
 
36
- Note that although we use a very similar architecture as Stable Diffusion, MuseTalk is distinct in that it is `Not` a diffusion model. Instead, MuseTalk operates by inpainting in the latent space with `a single step`.
37
 
38
  ## Cases
39
  ### MuseV + MuseTalk make human photos alive!
@@ -162,7 +163,7 @@ Note that although we use a very similar architecture as Stable Diffusion, MuseT
162
  # TODO:
163
  - [x] trained models and inference codes.
164
  - [x] Huggingface Gradio [demo](https://huggingface.co/spaces/TMElyralab/MuseTalk).
165
- - [ ] codes for real-time inference.
166
  - [ ] technical report.
167
  - [ ] training codes.
168
  - [ ] a better model (may take longer).
@@ -262,9 +263,30 @@ python -m scripts.inference --inference_config configs/inference/test.yaml --bbo
262
 
263
  As a complete solution to virtual human generation, you are suggested to first apply [MuseV](https://github.com/TMElyralab/MuseV) to generate a video (text-to-video, image-to-video or pose-to-video) by referring [this](https://github.com/TMElyralab/MuseV?tab=readme-ov-file#text2video). Frame interpolation is suggested to increase frame rate. Then, you can use `MuseTalk` to generate a lip-sync video by referring [this](https://github.com/TMElyralab/MuseTalk?tab=readme-ov-file#inference).
264
 
265
- # Note
266
 
267
- If you want to launch online video chats, you are suggested to generate videos using MuseV and apply necessary pre-processing such as face detection and face parsing in advance. During online chatting, only UNet and the VAE decoder are involved, which makes MuseTalk real-time.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
 
270
  # Acknowledgement
 
11
  Wenjiang Zhou
12
  (<sup>*</sup>Equal Contribution, <sup>†</sup>Corresponding Author, benbinwu@tencent.com)
13
 
14
+ **[github](https://github.com/TMElyralab/MuseTalk)** **[huggingface](https://huggingface.co/TMElyralab/MuseTalk)** **[space](https://huggingface.co/spaces/TMElyralab/MuseTalk)** **Project (comming soon)** **Technical report (comming soon)**
15
 
16
  We introduce `MuseTalk`, a **real-time high quality** lip-syncing model (30fps+ on an NVIDIA Tesla V100). MuseTalk can be applied with input videos, e.g., generated by [MuseV](https://github.com/TMElyralab/MuseV), as a complete virtual human solution.
17
 
 
28
  # News
29
  - [04/02/2024] Release MuseTalk project and pretrained models.
30
  - [04/16/2024] Release Gradio [demo](https://huggingface.co/spaces/TMElyralab/MuseTalk) on HuggingFace Spaces (thanks to HF team for their community grant)
31
+ - [04/17/2024] :mega: We release a pipeline that utilizes MuseTalk for real-time inference.
32
 
33
  ## Model
34
  ![Model Structure](assets/figs/musetalk_arc.jpg)
35
  MuseTalk was trained in latent spaces, where the images were encoded by a freezed VAE. The audio was encoded by a freezed `whisper-tiny` model. The architecture of the generation network was borrowed from the UNet of the `stable-diffusion-v1-4`, where the audio embeddings were fused to the image embeddings by cross-attention.
36
 
37
+ Note that although we use a very similar architecture as Stable Diffusion, MuseTalk is distinct in that it is **NOT** a diffusion model. Instead, MuseTalk operates by inpainting in the latent space with a single step.
38
 
39
  ## Cases
40
  ### MuseV + MuseTalk make human photos alive!
 
163
  # TODO:
164
  - [x] trained models and inference codes.
165
  - [x] Huggingface Gradio [demo](https://huggingface.co/spaces/TMElyralab/MuseTalk).
166
+ - [x] codes for real-time inference.
167
  - [ ] technical report.
168
  - [ ] training codes.
169
  - [ ] a better model (may take longer).
 
263
 
264
  As a complete solution to virtual human generation, you are suggested to first apply [MuseV](https://github.com/TMElyralab/MuseV) to generate a video (text-to-video, image-to-video or pose-to-video) by referring [this](https://github.com/TMElyralab/MuseV?tab=readme-ov-file#text2video). Frame interpolation is suggested to increase frame rate. Then, you can use `MuseTalk` to generate a lip-sync video by referring [this](https://github.com/TMElyralab/MuseTalk?tab=readme-ov-file#inference).
265
 
266
+ #### :new: Real-time inference
267
 
268
+ Here, we provide the inference script. This script first applies necessary pre-processing such as face detection, face parsing and VAE encode in advance. During inference, only UNet and the VAE decoder are involved, which makes MuseTalk real-time.
269
+ ```
270
+ python -m scripts.realtime_inference --inference_config configs/inference/realtime.yaml
271
+ ```
272
+ configs/inference/realtime.yaml is the path to the real-time inference configuration file, including `preparation`, `video_path` , `bbox_shift` and `audio_clips`.
273
+
274
+ 1. Set `preparation` to `True` in `realtime.yaml` to prepare the materials for a new `avatar`. (If the `bbox_shift` has changed, you also need to re-prepare the materials.)
275
+ 1. After that, the `avatar` will use an audio clip selected from `audio_clips` to generate video.
276
+ ```
277
+ Inferring using: data/audio/yongen.wav
278
+ ```
279
+ 1. While MuseTalk is inferring, sub-threads can simultaneously stream the results to the users. The generation process can achieve up to 50fps on an NVIDIA Tesla V100.
280
+ ```
281
+ 2%|██▍ | 3/141 [00:00<00:32, 4.30it/s] # inference process
282
+ Generating the 6-th frame with FPS: 48.58 # playing process
283
+ Generating the 7-th frame with FPS: 48.74
284
+ Generating the 8-th frame with FPS: 49.17
285
+ 3%|███▎ | 4/141 [00:00<00:32, 4.21it/s]
286
+ ```
287
+ 1. Set `preparation` to `False` and run this script if you want to genrate more videos using the same avatar.
288
+
289
+ If you want to generate multiple videos using the same avatar/video, you can also use this script to **SIGNIFICANTLY** expedite the generation process.
290
 
291
 
292
  # Acknowledgement
configs/inference/realtime.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ avator_1:
2
+ preparation: False
3
+ bbox_shift: 5
4
+ video_path: "data/video/sun.mp4"
5
+ audio_clips:
6
+ audio_0: "data/audio/yongen.wav"
7
+ audio_1: "data/audio/sun.wav"
8
+
9
+
10
+
musetalk/utils/blending.py CHANGED
@@ -57,3 +57,44 @@ def get_image(image,face,face_box,upper_boundary_ratio = 0.5,expand=1.2):
57
  body.paste(face_large, crop_box[:2], mask_image)
58
  body = np.array(body)
59
  return body[:,:,::-1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  body.paste(face_large, crop_box[:2], mask_image)
58
  body = np.array(body)
59
  return body[:,:,::-1]
60
+
61
+ def get_image_prepare_material(image,face_box,upper_boundary_ratio = 0.5,expand=1.2):
62
+ body = Image.fromarray(image[:,:,::-1])
63
+
64
+ x, y, x1, y1 = face_box
65
+ #print(x1-x,y1-y)
66
+ crop_box, s = get_crop_box(face_box, expand)
67
+ x_s, y_s, x_e, y_e = crop_box
68
+
69
+ face_large = body.crop(crop_box)
70
+ ori_shape = face_large.size
71
+
72
+ mask_image = face_seg(face_large)
73
+ mask_small = mask_image.crop((x-x_s, y-y_s, x1-x_s, y1-y_s))
74
+ mask_image = Image.new('L', ori_shape, 0)
75
+ mask_image.paste(mask_small, (x-x_s, y-y_s, x1-x_s, y1-y_s))
76
+
77
+ # keep upper_boundary_ratio of talking area
78
+ width, height = mask_image.size
79
+ top_boundary = int(height * upper_boundary_ratio)
80
+ modified_mask_image = Image.new('L', ori_shape, 0)
81
+ modified_mask_image.paste(mask_image.crop((0, top_boundary, width, height)), (0, top_boundary))
82
+
83
+ blur_kernel_size = int(0.1 * ori_shape[0] // 2 * 2) + 1
84
+ mask_array = cv2.GaussianBlur(np.array(modified_mask_image), (blur_kernel_size, blur_kernel_size), 0)
85
+ return mask_array,crop_box
86
+
87
+ def get_image_blending(image,face,face_box,mask_array,crop_box):
88
+ body = Image.fromarray(image[:,:,::-1])
89
+ face = Image.fromarray(face[:,:,::-1])
90
+
91
+ x, y, x1, y1 = face_box
92
+ x_s, y_s, x_e, y_e = crop_box
93
+ face_large = body.crop(crop_box)
94
+
95
+ mask_image = Image.fromarray(mask_array)
96
+ mask_image = mask_image.convert("L")
97
+ face_large.paste(face, (x-x_s, y-y_s, x1-x_s, y1-y_s))
98
+ body.paste(face_large, crop_box[:2], mask_image)
99
+ body = np.array(body)
100
+ return body[:,:,::-1]
scripts/realtime_inference.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from omegaconf import OmegaConf
4
+ import numpy as np
5
+ import cv2
6
+ import torch
7
+ import glob
8
+ import pickle
9
+ import sys
10
+ from tqdm import tqdm
11
+ import copy
12
+ import json
13
+ from musetalk.utils.utils import get_file_type,get_video_fps,datagen
14
+ from musetalk.utils.preprocessing import get_landmark_and_bbox,read_imgs,coord_placeholder
15
+ from musetalk.utils.blending import get_image,get_image_prepare_material,get_image_blending
16
+ from musetalk.utils.utils import load_all_model
17
+ import shutil
18
+
19
+ import threading
20
+ import queue
21
+
22
+ import time
23
+
24
+ # load model weights
25
+ audio_processor,vae,unet,pe = load_all_model()
26
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
+ timesteps = torch.tensor([0], device=device)
28
+
29
+
30
+ def video2imgs(vid_path, save_path, ext = '.png',cut_frame = 10000000):
31
+ cap = cv2.VideoCapture(vid_path)
32
+ count = 0
33
+ while True:
34
+ if count > cut_frame:
35
+ break
36
+ ret, frame = cap.read()
37
+ if ret:
38
+ cv2.imwrite(f"{save_path}/{count:08d}.png", frame)
39
+ count += 1
40
+ else:
41
+ break
42
+
43
+ def osmakedirs(path_list):
44
+ for path in path_list:
45
+ os.makedirs(path) if not os.path.exists(path) else None
46
+
47
+
48
+ @torch.no_grad()
49
+ class Avatar:
50
+ def __init__(self, avatar_id, video_path, bbox_shift, batch_size, preparation):
51
+ self.avatar_id = avatar_id
52
+ self.video_path = video_path
53
+ self.bbox_shift = bbox_shift
54
+ self.avatar_path = f"./results/avatars/{avatar_id}"
55
+ self.full_imgs_path = f"{self.avatar_path}/full_imgs"
56
+ self.coords_path = f"{self.avatar_path}/coords.pkl"
57
+ self.latents_out_path= f"{self.avatar_path}/latents.pt"
58
+ self.video_out_path = f"{self.avatar_path}/vid_output/"
59
+ self.mask_out_path =f"{self.avatar_path}/mask"
60
+ self.mask_coords_path =f"{self.avatar_path}/mask_coords.pkl"
61
+ self.avatar_info_path = f"{self.avatar_path}/avator_info.json"
62
+ self.avatar_info = {
63
+ "avatar_id":avatar_id,
64
+ "video_path":video_path,
65
+ "bbox_shift":bbox_shift
66
+ }
67
+ self.preparation = preparation
68
+ self.batch_size = batch_size
69
+ self.idx = 0
70
+ self.init()
71
+
72
+ def init(self):
73
+ if self.preparation:
74
+ if os.path.exists(self.avatar_path):
75
+ response = input(f"{self.avatar_id} exists, Do you want to re-create it ? (y/n)")
76
+ if response.lower() == "y":
77
+ shutil.rmtree(self.avatar_path)
78
+ print("*********************************")
79
+ print(f" creating avator: {self.avatar_id}")
80
+ print("*********************************")
81
+ osmakedirs([self.avatar_path,self.full_imgs_path,self.video_out_path,self.mask_out_path])
82
+ self.prepare_material()
83
+ else:
84
+ self.input_latent_list_cycle = torch.load(self.latents_out_path)
85
+ with open(self.coords_path, 'rb') as f:
86
+ self.coord_list_cycle = pickle.load(f)
87
+ input_img_list = glob.glob(os.path.join(self.full_imgs_path, '*.[jpJP][pnPN]*[gG]'))
88
+ input_img_list = sorted(input_img_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
89
+ self.frame_list_cycle = read_imgs(input_img_list)
90
+ with open(self.mask_coords_path, 'rb') as f:
91
+ self.mask_coords_list_cycle = pickle.load(f)
92
+ input_mask_list = glob.glob(os.path.join(self.mask_out_path, '*.[jpJP][pnPN]*[gG]'))
93
+ input_mask_list = sorted(input_mask_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
94
+ self.mask_list_cycle = read_imgs(input_mask_list)
95
+ else:
96
+ print("*********************************")
97
+ print(f" creating avator: {self.avatar_id}")
98
+ print("*********************************")
99
+ osmakedirs([self.avatar_path,self.full_imgs_path,self.video_out_path,self.mask_out_path])
100
+ self.prepare_material()
101
+ else:
102
+ with open(self.avatar_info_path, "r") as f:
103
+ avatar_info = json.load(f)
104
+
105
+ if avatar_info['bbox_shift'] != self.avatar_info['bbox_shift']:
106
+ response = input(f" 【bbox_shift】 is changed, you need to re-create it ! (c/continue)")
107
+ if response.lower() == "c":
108
+ shutil.rmtree(self.avatar_path)
109
+ print("*********************************")
110
+ print(f" creating avator: {self.avatar_id}")
111
+ print("*********************************")
112
+ osmakedirs([self.avatar_path,self.full_imgs_path,self.video_out_path,self.mask_out_path])
113
+ self.prepare_material()
114
+ else:
115
+ sys.exit()
116
+ else:
117
+ self.input_latent_list_cycle = torch.load(self.latents_out_path)
118
+ with open(self.coords_path, 'rb') as f:
119
+ self.coord_list_cycle = pickle.load(f)
120
+ input_img_list = glob.glob(os.path.join(self.full_imgs_path, '*.[jpJP][pnPN]*[gG]'))
121
+ input_img_list = sorted(input_img_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
122
+ self.frame_list_cycle = read_imgs(input_img_list)
123
+ with open(self.mask_coords_path, 'rb') as f:
124
+ self.mask_coords_list_cycle = pickle.load(f)
125
+ input_mask_list = glob.glob(os.path.join(self.mask_out_path, '*.[jpJP][pnPN]*[gG]'))
126
+ input_mask_list = sorted(input_mask_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
127
+ self.mask_list_cycle = read_imgs(input_mask_list)
128
+
129
+ def prepare_material(self):
130
+ print("preparing data materials ... ...")
131
+ with open(self.avatar_info_path, "w") as f:
132
+ json.dump(self.avatar_info, f)
133
+
134
+ if os.path.isfile(self.video_path):
135
+ video2imgs(self.video_path, self.full_imgs_path, ext = 'png')
136
+ else:
137
+ print(f"copy files in {self.video_path}")
138
+ files = os.listdir(self.video_path)
139
+ files.sort()
140
+ files = [file for file in files if file.split(".")[-1]=="png"]
141
+ for filename in files:
142
+ shutil.copyfile(f"{self.video_path}/{filename}", f"{self.full_imgs_path}/{filename}")
143
+ input_img_list = sorted(glob.glob(os.path.join(self.full_imgs_path, '*.[jpJP][pnPN]*[gG]')))
144
+
145
+ print("extracting landmarks...")
146
+ coord_list, frame_list = get_landmark_and_bbox(input_img_list, self.bbox_shift)
147
+ input_latent_list = []
148
+ idx = -1
149
+ # maker if the bbox is not sufficient
150
+ coord_placeholder = (0.0,0.0,0.0,0.0)
151
+ for bbox, frame in zip(coord_list, frame_list):
152
+ idx = idx + 1
153
+ if bbox == coord_placeholder:
154
+ continue
155
+ x1, y1, x2, y2 = bbox
156
+ crop_frame = frame[y1:y2, x1:x2]
157
+ resized_crop_frame = cv2.resize(crop_frame,(256,256),interpolation = cv2.INTER_LANCZOS4)
158
+ latents = vae.get_latents_for_unet(resized_crop_frame)
159
+ input_latent_list.append(latents)
160
+
161
+ self.frame_list_cycle = frame_list + frame_list[::-1]
162
+ self.coord_list_cycle = coord_list + coord_list[::-1]
163
+ self.input_latent_list_cycle = input_latent_list + input_latent_list[::-1]
164
+ self.mask_coords_list_cycle = []
165
+ self.mask_list_cycle = []
166
+
167
+ for i,frame in enumerate(tqdm(self.frame_list_cycle)):
168
+ cv2.imwrite(f"{self.full_imgs_path}/{str(i).zfill(8)}.png",frame)
169
+
170
+ face_box = self.coord_list_cycle[i]
171
+ mask,crop_box = get_image_prepare_material(frame,face_box)
172
+ cv2.imwrite(f"{self.mask_out_path}/{str(i).zfill(8)}.png",mask)
173
+ self.mask_coords_list_cycle += [crop_box]
174
+ self.mask_list_cycle.append(mask)
175
+
176
+ with open(self.mask_coords_path, 'wb') as f:
177
+ pickle.dump(self.mask_coords_list_cycle, f)
178
+
179
+ with open(self.coords_path, 'wb') as f:
180
+ pickle.dump(self.coord_list_cycle, f)
181
+
182
+ torch.save(self.input_latent_list_cycle, os.path.join(self.latents_out_path))
183
+ #
184
+
185
+ def process_frames(self, res_frame_queue,video_len):
186
+ print(video_len)
187
+ while True:
188
+ if self.idx>=video_len-1:
189
+ break
190
+ try:
191
+ start = time.time()
192
+ res_frame = res_frame_queue.get(block=True, timeout=1)
193
+ except queue.Empty:
194
+ continue
195
+
196
+ bbox = self.coord_list_cycle[self.idx%(len(self.coord_list_cycle))]
197
+ ori_frame = copy.deepcopy(self.frame_list_cycle[self.idx%(len(self.frame_list_cycle))])
198
+ x1, y1, x2, y2 = bbox
199
+ try:
200
+ res_frame = cv2.resize(res_frame.astype(np.uint8),(x2-x1,y2-y1))
201
+ except:
202
+ continue
203
+ mask = self.mask_list_cycle[self.idx%(len(self.mask_list_cycle))]
204
+ mask_crop_box = self.mask_coords_list_cycle[self.idx%(len(self.mask_coords_list_cycle))]
205
+ #combine_frame = get_image(ori_frame,res_frame,bbox)
206
+ combine_frame = get_image_blending(ori_frame,res_frame,bbox,mask,mask_crop_box)
207
+
208
+ fps = 1/(time.time()-start)
209
+ print(f"Generating the {self.idx}-th frame with FPS: {fps:.2f}")
210
+ cv2.imwrite(f"{self.avatar_path}/tmp/{str(self.idx).zfill(8)}.png",combine_frame)
211
+ self.idx = self.idx + 1
212
+
213
+ def inference(self, audio_path, out_vid_name, fps):
214
+ os.makedirs(self.avatar_path+'/tmp',exist_ok =True)
215
+ ############################################## extract audio feature ##############################################
216
+ whisper_feature = audio_processor.audio2feat(audio_path)
217
+ whisper_chunks = audio_processor.feature2chunks(feature_array=whisper_feature,fps=fps)
218
+ ############################################## inference batch by batch ##############################################
219
+ video_num = len(whisper_chunks)
220
+ print("start inference")
221
+ res_frame_queue = queue.Queue()
222
+ self.idx = 0
223
+ # # Create a sub-thread and start it
224
+ process_thread = threading.Thread(target=self.process_frames, args=(res_frame_queue,video_num))
225
+ process_thread.start()
226
+ start_time = time.time()
227
+ gen = datagen(whisper_chunks,self.input_latent_list_cycle, self.batch_size)
228
+ print(f"processing audio:{audio_path} costs {(time.time() - start_time) * 1000}ms")
229
+ start_time = time.time()
230
+ res_frame_list = []
231
+
232
+ for i, (whisper_batch,latent_batch) in enumerate(tqdm(gen,total=int(np.ceil(float(video_num)/self.batch_size)))):
233
+ start_time = time.time()
234
+ tensor_list = [torch.FloatTensor(arr) for arr in whisper_batch]
235
+ audio_feature_batch = torch.stack(tensor_list).to(unet.device) # torch, B, 5*N,384
236
+ audio_feature_batch = pe(audio_feature_batch)
237
+
238
+ pred_latents = unet.model(latent_batch, timesteps, encoder_hidden_states=audio_feature_batch).sample
239
+ recon = vae.decode_latents(pred_latents)
240
+ for res_frame in recon:
241
+ res_frame_queue.put(res_frame)
242
+ # Close the queue and sub-thread after all tasks are completed
243
+ process_thread.join()
244
+
245
+ if out_vid_name is not None:
246
+ # optional
247
+ cmd_img2video = f"ffmpeg -y -v fatal -r {fps} -f image2 -i {self.avatar_path}/tmp/%08d.png -vcodec libx264 -vf format=rgb24,scale=out_color_matrix=bt709,format=yuv420p -crf 18 {self.avatar_path}/temp.mp4"
248
+ print(cmd_img2video)
249
+ os.system(cmd_img2video)
250
+
251
+ output_vid = os.path.join(self.video_out_path, out_vid_name+".mp4") # on
252
+ cmd_combine_audio = f"ffmpeg -y -v fatal -i {audio_path} -i {self.avatar_path}/temp.mp4 {output_vid}"
253
+ print(cmd_combine_audio)
254
+ os.system(cmd_combine_audio)
255
+
256
+ os.remove(f"{self.avatar_path}/temp.mp4")
257
+ shutil.rmtree(f"{self.avatar_path}/tmp")
258
+ print(f"result is save to {output_vid}")
259
+
260
+
261
+
262
+
263
+
264
+ if __name__ == "__main__":
265
+ '''
266
+ This script is used to simulate online chatting and applies necessary pre-processing such as face detection and face parsing in advance. During online chatting, only UNet and the VAE decoder are involved, which makes MuseTalk real-time.
267
+ '''
268
+
269
+ parser = argparse.ArgumentParser()
270
+ parser.add_argument("--inference_config", type=str, default="configs/inference/realtime.yaml")
271
+ parser.add_argument("--fps", type=int, default=25)
272
+ parser.add_argument("--batch_size", type=int, default=4)
273
+
274
+ args = parser.parse_args()
275
+
276
+ inference_config = OmegaConf.load(args.inference_config)
277
+ print(inference_config)
278
+
279
+
280
+ for avatar_id in inference_config:
281
+ data_preparation = inference_config[avatar_id]["preparation"]
282
+ video_path = inference_config[avatar_id]["video_path"]
283
+ bbox_shift = inference_config[avatar_id]["bbox_shift"]
284
+ avatar = Avatar(
285
+ avatar_id = avatar_id,
286
+ video_path = video_path,
287
+ bbox_shift = bbox_shift,
288
+ batch_size = args.batch_size,
289
+ preparation= data_preparation)
290
+
291
+ audio_clips = inference_config[avatar_id]["audio_clips"]
292
+ for audio_num, audio_path in audio_clips.items():
293
+ print("Inferring using:",audio_path)
294
+ avatar.inference(audio_path, audio_num, args.fps)
295
+