Spaces:
Runtime error
Runtime error
Add gradio
Browse files- README.md +12 -3
- app.py +410 -0
- entrypoint.sh +9 -0
- musetalk/utils/preprocessing.py +41 -0
- requirements.txt +3 -0
README.md
CHANGED
|
@@ -11,7 +11,7 @@ Chao Zhan,
|
|
| 11 |
Wenjiang Zhou
|
| 12 |
(<sup>*</sup>Equal Contribution, <sup>†</sup>Corresponding Author, [email protected])
|
| 13 |
|
| 14 |
-
**[github](https://github.com/TMElyralab/MuseTalk)** **[huggingface](https://huggingface.co/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 |
|
|
@@ -26,7 +26,8 @@ We introduce `MuseTalk`, a **real-time high quality** lip-syncing model (30fps+
|
|
| 26 |
1. training codes (comming soon).
|
| 27 |
|
| 28 |
# News
|
| 29 |
-
- [04/02/2024]
|
|
|
|
| 30 |
|
| 31 |
## Model
|
| 32 |

|
|
@@ -158,14 +159,22 @@ MuseTalk was trained in latent spaces, where the images were encoded by a freeze
|
|
| 158 |
|
| 159 |
# TODO:
|
| 160 |
- [x] trained models and inference codes.
|
|
|
|
|
|
|
| 161 |
- [ ] technical report.
|
| 162 |
- [ ] training codes.
|
| 163 |
-
- [ ] online UI.
|
| 164 |
- [ ] a better model (may take longer).
|
| 165 |
|
| 166 |
|
| 167 |
# Getting Started
|
| 168 |
We provide a detailed tutorial about the installation and the basic usage of MuseTalk for new users:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
## Installation
|
| 170 |
To prepare the Python environment and install additional packages such as opencv, diffusers, mmcv, etc., please follow the steps below:
|
| 171 |
### Build environment
|
|
|
|
| 11 |
Wenjiang Zhou
|
| 12 |
(<sup>*</sup>Equal Contribution, <sup>†</sup>Corresponding Author, [email protected])
|
| 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 |
|
|
|
|
| 26 |
1. training codes (comming soon).
|
| 27 |
|
| 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 |

|
|
|
|
| 159 |
|
| 160 |
# TODO:
|
| 161 |
- [x] trained models and inference codes.
|
| 162 |
+
- [x] Huggingface Gradio [demo](https://huggingface.co/spaces/TMElyralab/MuseTalk).
|
| 163 |
+
- [ ] codes for real-time inference.
|
| 164 |
- [ ] technical report.
|
| 165 |
- [ ] training codes.
|
|
|
|
| 166 |
- [ ] a better model (may take longer).
|
| 167 |
|
| 168 |
|
| 169 |
# Getting Started
|
| 170 |
We provide a detailed tutorial about the installation and the basic usage of MuseTalk for new users:
|
| 171 |
+
|
| 172 |
+
## Third party integration
|
| 173 |
+
Thanks for the third-party integration, which makes installation and use more convenient for everyone.
|
| 174 |
+
We also hope you note that we have not verified, maintained, or updated third-party. Please refer to this project for specific results.
|
| 175 |
+
|
| 176 |
+
### [ComfyUI](https://github.com/chaojie/ComfyUI-MuseTalk)
|
| 177 |
+
|
| 178 |
## Installation
|
| 179 |
To prepare the Python environment and install additional packages such as opencv, diffusers, mmcv, etc., please follow the steps below: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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import pdb
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import spaces
|
| 8 |
+
import numpy as np
|
| 9 |
+
import sys
|
| 10 |
+
import subprocess
|
| 11 |
+
|
| 12 |
+
from huggingface_hub import snapshot_download
|
| 13 |
+
import requests
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import os
|
| 17 |
+
from omegaconf import OmegaConf
|
| 18 |
+
import numpy as np
|
| 19 |
+
import cv2
|
| 20 |
+
import torch
|
| 21 |
+
import glob
|
| 22 |
+
import pickle
|
| 23 |
+
from tqdm import tqdm
|
| 24 |
+
import copy
|
| 25 |
+
from argparse import Namespace
|
| 26 |
+
import shutil
|
| 27 |
+
import gdown
|
| 28 |
+
import imageio
|
| 29 |
+
import ffmpeg
|
| 30 |
+
from moviepy.editor import *
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
ProjectDir = os.path.abspath(os.path.dirname(__file__))
|
| 34 |
+
CheckpointsDir = os.path.join(ProjectDir, "models")
|
| 35 |
+
|
| 36 |
+
def print_directory_contents(path):
|
| 37 |
+
for child in os.listdir(path):
|
| 38 |
+
child_path = os.path.join(path, child)
|
| 39 |
+
if os.path.isdir(child_path):
|
| 40 |
+
print(child_path)
|
| 41 |
+
|
| 42 |
+
def download_model():
|
| 43 |
+
if not os.path.exists(CheckpointsDir):
|
| 44 |
+
os.makedirs(CheckpointsDir)
|
| 45 |
+
print("Checkpoint Not Downloaded, start downloading...")
|
| 46 |
+
tic = time.time()
|
| 47 |
+
snapshot_download(
|
| 48 |
+
repo_id="TMElyralab/MuseTalk",
|
| 49 |
+
local_dir=CheckpointsDir,
|
| 50 |
+
max_workers=8,
|
| 51 |
+
local_dir_use_symlinks=True,
|
| 52 |
+
)
|
| 53 |
+
# weight
|
| 54 |
+
os.makedirs(f"{CheckpointsDir}/sd-vae-ft-mse/")
|
| 55 |
+
snapshot_download(
|
| 56 |
+
repo_id="stabilityai/sd-vae-ft-mse",
|
| 57 |
+
local_dir=CheckpointsDir+'/sd-vae-ft-mse',
|
| 58 |
+
max_workers=8,
|
| 59 |
+
local_dir_use_symlinks=True,
|
| 60 |
+
)
|
| 61 |
+
#dwpose
|
| 62 |
+
os.makedirs(f"{CheckpointsDir}/dwpose/")
|
| 63 |
+
snapshot_download(
|
| 64 |
+
repo_id="yzd-v/DWPose",
|
| 65 |
+
local_dir=CheckpointsDir+'/dwpose',
|
| 66 |
+
max_workers=8,
|
| 67 |
+
local_dir_use_symlinks=True,
|
| 68 |
+
)
|
| 69 |
+
#vae
|
| 70 |
+
url = "https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt"
|
| 71 |
+
response = requests.get(url)
|
| 72 |
+
# 确保请求成功
|
| 73 |
+
if response.status_code == 200:
|
| 74 |
+
# 指定文件保存的位置
|
| 75 |
+
file_path = f"{CheckpointsDir}/whisper/tiny.pt"
|
| 76 |
+
os.makedirs(f"{CheckpointsDir}/whisper/")
|
| 77 |
+
# 将文件内容写入指定位置
|
| 78 |
+
with open(file_path, "wb") as f:
|
| 79 |
+
f.write(response.content)
|
| 80 |
+
else:
|
| 81 |
+
print(f"请求失败,状态码:{response.status_code}")
|
| 82 |
+
#gdown face parse
|
| 83 |
+
url = "https://drive.google.com/uc?id=154JgKpzCPW82qINcVieuPH3fZ2e0P812"
|
| 84 |
+
os.makedirs(f"{CheckpointsDir}/face-parse-bisent/")
|
| 85 |
+
file_path = f"{CheckpointsDir}/face-parse-bisent/79999_iter.pth"
|
| 86 |
+
gdown.download(url, file_path, quiet=False)
|
| 87 |
+
#resnet
|
| 88 |
+
url = "https://download.pytorch.org/models/resnet18-5c106cde.pth"
|
| 89 |
+
response = requests.get(url)
|
| 90 |
+
# 确保请求成功
|
| 91 |
+
if response.status_code == 200:
|
| 92 |
+
# 指定文件保存的位置
|
| 93 |
+
file_path = f"{CheckpointsDir}/face-parse-bisent/resnet18-5c106cde.pth"
|
| 94 |
+
# 将文件内容写入指定位置
|
| 95 |
+
with open(file_path, "wb") as f:
|
| 96 |
+
f.write(response.content)
|
| 97 |
+
else:
|
| 98 |
+
print(f"请求失败,状态码:{response.status_code}")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
toc = time.time()
|
| 102 |
+
|
| 103 |
+
print(f"download cost {toc-tic} seconds")
|
| 104 |
+
print_directory_contents(CheckpointsDir)
|
| 105 |
+
|
| 106 |
+
else:
|
| 107 |
+
print("Already download the model.")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
download_model() # for huggingface deployment.
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
from musetalk.utils.utils import get_file_type,get_video_fps,datagen
|
| 117 |
+
from musetalk.utils.preprocessing import get_landmark_and_bbox,read_imgs,coord_placeholder,get_bbox_range
|
| 118 |
+
from musetalk.utils.blending import get_image
|
| 119 |
+
from musetalk.utils.utils import load_all_model
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@spaces.GPU(duration=600)
|
| 127 |
+
@torch.no_grad()
|
| 128 |
+
def inference(audio_path,video_path,bbox_shift,progress=gr.Progress(track_tqdm=True)):
|
| 129 |
+
args_dict={"result_dir":'./results/output', "fps":25, "batch_size":8, "output_vid_name":'', "use_saved_coord":False}#same with inferenece script
|
| 130 |
+
args = Namespace(**args_dict)
|
| 131 |
+
|
| 132 |
+
input_basename = os.path.basename(video_path).split('.')[0]
|
| 133 |
+
audio_basename = os.path.basename(audio_path).split('.')[0]
|
| 134 |
+
output_basename = f"{input_basename}_{audio_basename}"
|
| 135 |
+
result_img_save_path = os.path.join(args.result_dir, output_basename) # related to video & audio inputs
|
| 136 |
+
crop_coord_save_path = os.path.join(result_img_save_path, input_basename+".pkl") # only related to video input
|
| 137 |
+
os.makedirs(result_img_save_path,exist_ok =True)
|
| 138 |
+
|
| 139 |
+
if args.output_vid_name=="":
|
| 140 |
+
output_vid_name = os.path.join(args.result_dir, output_basename+".mp4")
|
| 141 |
+
else:
|
| 142 |
+
output_vid_name = os.path.join(args.result_dir, args.output_vid_name)
|
| 143 |
+
############################################## extract frames from source video ##############################################
|
| 144 |
+
if get_file_type(video_path)=="video":
|
| 145 |
+
save_dir_full = os.path.join(args.result_dir, input_basename)
|
| 146 |
+
os.makedirs(save_dir_full,exist_ok = True)
|
| 147 |
+
# cmd = f"ffmpeg -v fatal -i {video_path} -start_number 0 {save_dir_full}/%08d.png"
|
| 148 |
+
# os.system(cmd)
|
| 149 |
+
# 读取视频
|
| 150 |
+
reader = imageio.get_reader(video_path)
|
| 151 |
+
|
| 152 |
+
# 保存图片
|
| 153 |
+
for i, im in enumerate(reader):
|
| 154 |
+
imageio.imwrite(f"{save_dir_full}/{i:08d}.png", im)
|
| 155 |
+
input_img_list = sorted(glob.glob(os.path.join(save_dir_full, '*.[jpJP][pnPN]*[gG]')))
|
| 156 |
+
fps = get_video_fps(video_path)
|
| 157 |
+
else: # input img folder
|
| 158 |
+
input_img_list = glob.glob(os.path.join(video_path, '*.[jpJP][pnPN]*[gG]'))
|
| 159 |
+
input_img_list = sorted(input_img_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
|
| 160 |
+
fps = args.fps
|
| 161 |
+
#print(input_img_list)
|
| 162 |
+
############################################## extract audio feature ##############################################
|
| 163 |
+
whisper_feature = audio_processor.audio2feat(audio_path)
|
| 164 |
+
whisper_chunks = audio_processor.feature2chunks(feature_array=whisper_feature,fps=fps)
|
| 165 |
+
############################################## preprocess input image ##############################################
|
| 166 |
+
if os.path.exists(crop_coord_save_path) and args.use_saved_coord:
|
| 167 |
+
print("using extracted coordinates")
|
| 168 |
+
with open(crop_coord_save_path,'rb') as f:
|
| 169 |
+
coord_list = pickle.load(f)
|
| 170 |
+
frame_list = read_imgs(input_img_list)
|
| 171 |
+
else:
|
| 172 |
+
print("extracting landmarks...time consuming")
|
| 173 |
+
coord_list, frame_list = get_landmark_and_bbox(input_img_list, bbox_shift)
|
| 174 |
+
with open(crop_coord_save_path, 'wb') as f:
|
| 175 |
+
pickle.dump(coord_list, f)
|
| 176 |
+
bbox_shift_text=get_bbox_range(input_img_list, bbox_shift)
|
| 177 |
+
i = 0
|
| 178 |
+
input_latent_list = []
|
| 179 |
+
for bbox, frame in zip(coord_list, frame_list):
|
| 180 |
+
if bbox == coord_placeholder:
|
| 181 |
+
continue
|
| 182 |
+
x1, y1, x2, y2 = bbox
|
| 183 |
+
crop_frame = frame[y1:y2, x1:x2]
|
| 184 |
+
crop_frame = cv2.resize(crop_frame,(256,256),interpolation = cv2.INTER_LANCZOS4)
|
| 185 |
+
latents = vae.get_latents_for_unet(crop_frame)
|
| 186 |
+
input_latent_list.append(latents)
|
| 187 |
+
|
| 188 |
+
# to smooth the first and the last frame
|
| 189 |
+
frame_list_cycle = frame_list + frame_list[::-1]
|
| 190 |
+
coord_list_cycle = coord_list + coord_list[::-1]
|
| 191 |
+
input_latent_list_cycle = input_latent_list + input_latent_list[::-1]
|
| 192 |
+
############################################## inference batch by batch ##############################################
|
| 193 |
+
print("start inference")
|
| 194 |
+
video_num = len(whisper_chunks)
|
| 195 |
+
batch_size = args.batch_size
|
| 196 |
+
gen = datagen(whisper_chunks,input_latent_list_cycle,batch_size)
|
| 197 |
+
res_frame_list = []
|
| 198 |
+
for i, (whisper_batch,latent_batch) in enumerate(tqdm(gen,total=int(np.ceil(float(video_num)/batch_size)))):
|
| 199 |
+
|
| 200 |
+
tensor_list = [torch.FloatTensor(arr) for arr in whisper_batch]
|
| 201 |
+
audio_feature_batch = torch.stack(tensor_list).to(unet.device) # torch, B, 5*N,384
|
| 202 |
+
audio_feature_batch = pe(audio_feature_batch)
|
| 203 |
+
|
| 204 |
+
pred_latents = unet.model(latent_batch, timesteps, encoder_hidden_states=audio_feature_batch).sample
|
| 205 |
+
recon = vae.decode_latents(pred_latents)
|
| 206 |
+
for res_frame in recon:
|
| 207 |
+
res_frame_list.append(res_frame)
|
| 208 |
+
|
| 209 |
+
############################################## pad to full image ##############################################
|
| 210 |
+
print("pad talking image to original video")
|
| 211 |
+
for i, res_frame in enumerate(tqdm(res_frame_list)):
|
| 212 |
+
bbox = coord_list_cycle[i%(len(coord_list_cycle))]
|
| 213 |
+
ori_frame = copy.deepcopy(frame_list_cycle[i%(len(frame_list_cycle))])
|
| 214 |
+
x1, y1, x2, y2 = bbox
|
| 215 |
+
try:
|
| 216 |
+
res_frame = cv2.resize(res_frame.astype(np.uint8),(x2-x1,y2-y1))
|
| 217 |
+
except:
|
| 218 |
+
# print(bbox)
|
| 219 |
+
continue
|
| 220 |
+
|
| 221 |
+
combine_frame = get_image(ori_frame,res_frame,bbox)
|
| 222 |
+
cv2.imwrite(f"{result_img_save_path}/{str(i).zfill(8)}.png",combine_frame)
|
| 223 |
+
|
| 224 |
+
# cmd_img2video = f"ffmpeg -y -v fatal -r {fps} -f image2 -i {result_img_save_path}/%08d.png -vcodec libx264 -vf format=rgb24,scale=out_color_matrix=bt709,format=yuv420p temp.mp4"
|
| 225 |
+
# print(cmd_img2video)
|
| 226 |
+
# os.system(cmd_img2video)
|
| 227 |
+
# 帧率
|
| 228 |
+
fps = 25
|
| 229 |
+
# 图片路径
|
| 230 |
+
# 输出视频路径
|
| 231 |
+
output_video = 'temp.mp4'
|
| 232 |
+
|
| 233 |
+
# 读取图片
|
| 234 |
+
def is_valid_image(file):
|
| 235 |
+
pattern = re.compile(r'\d{8}\.png')
|
| 236 |
+
return pattern.match(file)
|
| 237 |
+
|
| 238 |
+
images = []
|
| 239 |
+
files = [file for file in os.listdir(result_img_save_path) if is_valid_image(file)]
|
| 240 |
+
files.sort(key=lambda x: int(x.split('.')[0]))
|
| 241 |
+
|
| 242 |
+
for file in files:
|
| 243 |
+
filename = os.path.join(result_img_save_path, file)
|
| 244 |
+
images.append(imageio.imread(filename))
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# 保存视频
|
| 248 |
+
imageio.mimwrite(output_video, images, 'FFMPEG', fps=fps, codec='libx264', pixelformat='yuv420p')
|
| 249 |
+
|
| 250 |
+
# cmd_combine_audio = f"ffmpeg -y -v fatal -i {audio_path} -i temp.mp4 {output_vid_name}"
|
| 251 |
+
# print(cmd_combine_audio)
|
| 252 |
+
# os.system(cmd_combine_audio)
|
| 253 |
+
|
| 254 |
+
input_video = './temp.mp4'
|
| 255 |
+
# Check if the input_video and audio_path exist
|
| 256 |
+
if not os.path.exists(input_video):
|
| 257 |
+
raise FileNotFoundError(f"Input video file not found: {input_video}")
|
| 258 |
+
if not os.path.exists(audio_path):
|
| 259 |
+
raise FileNotFoundError(f"Audio file not found: {audio_path}")
|
| 260 |
+
|
| 261 |
+
# 读取视频
|
| 262 |
+
reader = imageio.get_reader(input_video)
|
| 263 |
+
fps = reader.get_meta_data()['fps'] # 获取原视频的帧率
|
| 264 |
+
|
| 265 |
+
# 将帧存储在列表中
|
| 266 |
+
frames = images
|
| 267 |
+
|
| 268 |
+
# 保存视频并添加音频
|
| 269 |
+
# imageio.mimwrite(output_vid_name, frames, 'FFMPEG', fps=fps, codec='libx264', audio_codec='aac', input_params=['-i', audio_path])
|
| 270 |
+
|
| 271 |
+
# input_video = ffmpeg.input(input_video)
|
| 272 |
+
|
| 273 |
+
# input_audio = ffmpeg.input(audio_path)
|
| 274 |
+
|
| 275 |
+
print(len(frames))
|
| 276 |
+
|
| 277 |
+
# imageio.mimwrite(
|
| 278 |
+
# output_video,
|
| 279 |
+
# frames,
|
| 280 |
+
# 'FFMPEG',
|
| 281 |
+
# fps=25,
|
| 282 |
+
# codec='libx264',
|
| 283 |
+
# audio_codec='aac',
|
| 284 |
+
# input_params=['-i', audio_path],
|
| 285 |
+
# output_params=['-y'], # Add the '-y' flag to overwrite the output file if it exists
|
| 286 |
+
# )
|
| 287 |
+
# writer = imageio.get_writer(output_vid_name, fps = 25, codec='libx264', quality=10, pixelformat='yuvj444p')
|
| 288 |
+
# for im in frames:
|
| 289 |
+
# writer.append_data(im)
|
| 290 |
+
# writer.close()
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# Load the video
|
| 296 |
+
video_clip = VideoFileClip(input_video)
|
| 297 |
+
|
| 298 |
+
# Load the audio
|
| 299 |
+
audio_clip = AudioFileClip(audio_path)
|
| 300 |
+
|
| 301 |
+
# Set the audio to the video
|
| 302 |
+
video_clip = video_clip.set_audio(audio_clip)
|
| 303 |
+
|
| 304 |
+
# Write the output video
|
| 305 |
+
video_clip.write_videofile(output_vid_name, codec='libx264', audio_codec='aac',fps=25)
|
| 306 |
+
|
| 307 |
+
os.remove("temp.mp4")
|
| 308 |
+
#shutil.rmtree(result_img_save_path)
|
| 309 |
+
print(f"result is save to {output_vid_name}")
|
| 310 |
+
return output_vid_name,bbox_shift_text
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# load model weights
|
| 315 |
+
audio_processor,vae,unet,pe = load_all_model()
|
| 316 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 317 |
+
timesteps = torch.tensor([0], device=device)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def check_video(video):
|
| 323 |
+
if not isinstance(video, str):
|
| 324 |
+
return video # in case of none type
|
| 325 |
+
# Define the output video file name
|
| 326 |
+
dir_path, file_name = os.path.split(video)
|
| 327 |
+
if file_name.startswith("outputxxx_"):
|
| 328 |
+
return video
|
| 329 |
+
# Add the output prefix to the file name
|
| 330 |
+
output_file_name = "outputxxx_" + file_name
|
| 331 |
+
|
| 332 |
+
os.makedirs('./results',exist_ok=True)
|
| 333 |
+
os.makedirs('./results/output',exist_ok=True)
|
| 334 |
+
os.makedirs('./results/input',exist_ok=True)
|
| 335 |
+
|
| 336 |
+
# Combine the directory path and the new file name
|
| 337 |
+
output_video = os.path.join('./results/input', output_file_name)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
# # Run the ffmpeg command to change the frame rate to 25fps
|
| 341 |
+
# command = f"ffmpeg -i {video} -r 25 -vcodec libx264 -vtag hvc1 -pix_fmt yuv420p crf 18 {output_video} -y"
|
| 342 |
+
|
| 343 |
+
# 读取视频
|
| 344 |
+
reader = imageio.get_reader(video)
|
| 345 |
+
fps = reader.get_meta_data()['fps'] # 获取原视频的帧率
|
| 346 |
+
|
| 347 |
+
# 将帧存储在列表中
|
| 348 |
+
frames = [im for im in reader]
|
| 349 |
+
|
| 350 |
+
# 保存视频
|
| 351 |
+
imageio.mimwrite(output_video, frames, 'FFMPEG', fps=25, codec='libx264', quality=9, pixelformat='yuv420p')
|
| 352 |
+
return output_video
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height: 576px}"""
|
| 358 |
+
|
| 359 |
+
with gr.Blocks(css=css) as demo:
|
| 360 |
+
gr.Markdown(
|
| 361 |
+
"<div align='center'> <h1>MuseTalk: Real-Time High Quality Lip Synchronization with Latent Space Inpainting </span> </h1> \
|
| 362 |
+
<h2 style='font-weight: 450; font-size: 1rem; margin: 0rem'>\
|
| 363 |
+
</br>\
|
| 364 |
+
Yue Zhang <sup>\*</sup>,\
|
| 365 |
+
Minhao Liu<sup>\*</sup>,\
|
| 366 |
+
Zhaokang Chen,\
|
| 367 |
+
Bin Wu<sup>†</sup>,\
|
| 368 |
+
Yingjie He,\
|
| 369 |
+
Chao Zhan,\
|
| 370 |
+
Wenjiang Zhou\
|
| 371 |
+
(<sup>*</sup>Equal Contribution, <sup>†</sup>Corresponding Author, [email protected])\
|
| 372 |
+
Lyra Lab, Tencent Music Entertainment\
|
| 373 |
+
</h2> \
|
| 374 |
+
<a style='font-size:18px;color: #000000' href='https://github.com/TMElyralab/MuseTalk'>[Github Repo]</a>\
|
| 375 |
+
<a style='font-size:18px;color: #000000' href='https://github.com/TMElyralab/MuseTalk'>[Huggingface]</a>\
|
| 376 |
+
<a style='font-size:18px;color: #000000' href=''> [Technical report(Coming Soon)] </a>\
|
| 377 |
+
<a style='font-size:18px;color: #000000' href=''> [Project Page(Coming Soon)] </a> </div>"
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
with gr.Row():
|
| 381 |
+
with gr.Column():
|
| 382 |
+
audio = gr.Audio(label="Driven Audio",type="filepath")
|
| 383 |
+
video = gr.Video(label="Reference Video",sources=['upload'])
|
| 384 |
+
bbox_shift = gr.Number(label="BBox_shift value, px", value=0)
|
| 385 |
+
bbox_shift_scale = gr.Textbox(label="BBox_shift recommend value lower bound,The corresponding bbox range is generated after the initial result is generated. \n If the result is not good, it can be adjusted according to this reference value", value="",interactive=False)
|
| 386 |
+
|
| 387 |
+
btn = gr.Button("Generate")
|
| 388 |
+
out1 = gr.Video()
|
| 389 |
+
|
| 390 |
+
video.change(
|
| 391 |
+
fn=check_video, inputs=[video], outputs=[video]
|
| 392 |
+
)
|
| 393 |
+
btn.click(
|
| 394 |
+
fn=inference,
|
| 395 |
+
inputs=[
|
| 396 |
+
audio,
|
| 397 |
+
video,
|
| 398 |
+
bbox_shift,
|
| 399 |
+
],
|
| 400 |
+
outputs=[out1,bbox_shift_scale]
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# Set the IP and port
|
| 404 |
+
ip_address = "0.0.0.0" # Replace with your desired IP address
|
| 405 |
+
port_number = 7860 # Replace with your desired port number
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
demo.queue().launch(
|
| 409 |
+
share=False , debug=True, server_name=ip_address, server_port=port_number
|
| 410 |
+
)
|
entrypoint.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
echo "entrypoint.sh"
|
| 4 |
+
whoami
|
| 5 |
+
which python
|
| 6 |
+
source /opt/conda/etc/profile.d/conda.sh
|
| 7 |
+
conda activate musev
|
| 8 |
+
which python
|
| 9 |
+
python app.py
|
musetalk/utils/preprocessing.py
CHANGED
|
@@ -40,6 +40,47 @@ def read_imgs(img_list):
|
|
| 40 |
frames.append(frame)
|
| 41 |
return frames
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def get_landmark_and_bbox(img_list,upperbondrange =0):
|
| 44 |
frames = read_imgs(img_list)
|
| 45 |
batch_size_fa = 1
|
|
|
|
| 40 |
frames.append(frame)
|
| 41 |
return frames
|
| 42 |
|
| 43 |
+
def get_bbox_range(img_list,upperbondrange =0):
|
| 44 |
+
frames = read_imgs(img_list)
|
| 45 |
+
batch_size_fa = 1
|
| 46 |
+
batches = [frames[i:i + batch_size_fa] for i in range(0, len(frames), batch_size_fa)]
|
| 47 |
+
coords_list = []
|
| 48 |
+
landmarks = []
|
| 49 |
+
if upperbondrange != 0:
|
| 50 |
+
print('get key_landmark and face bounding boxes with the bbox_shift:',upperbondrange)
|
| 51 |
+
else:
|
| 52 |
+
print('get key_landmark and face bounding boxes with the default value')
|
| 53 |
+
average_range_minus = []
|
| 54 |
+
average_range_plus = []
|
| 55 |
+
for fb in tqdm(batches):
|
| 56 |
+
results = inference_topdown(model, np.asarray(fb)[0])
|
| 57 |
+
results = merge_data_samples(results)
|
| 58 |
+
keypoints = results.pred_instances.keypoints
|
| 59 |
+
face_land_mark= keypoints[0][23:91]
|
| 60 |
+
face_land_mark = face_land_mark.astype(np.int32)
|
| 61 |
+
|
| 62 |
+
# get bounding boxes by face detetion
|
| 63 |
+
bbox = fa.get_detections_for_batch(np.asarray(fb))
|
| 64 |
+
|
| 65 |
+
# adjust the bounding box refer to landmark
|
| 66 |
+
# Add the bounding box to a tuple and append it to the coordinates list
|
| 67 |
+
for j, f in enumerate(bbox):
|
| 68 |
+
if f is None: # no face in the image
|
| 69 |
+
coords_list += [coord_placeholder]
|
| 70 |
+
continue
|
| 71 |
+
|
| 72 |
+
half_face_coord = face_land_mark[29]#np.mean([face_land_mark[28], face_land_mark[29]], axis=0)
|
| 73 |
+
range_minus = (face_land_mark[30]- face_land_mark[29])[1]
|
| 74 |
+
range_plus = (face_land_mark[29]- face_land_mark[28])[1]
|
| 75 |
+
average_range_minus.append(range_minus)
|
| 76 |
+
average_range_plus.append(range_plus)
|
| 77 |
+
if upperbondrange != 0:
|
| 78 |
+
half_face_coord[1] = upperbondrange+half_face_coord[1] #手动调整 + 向下(偏29) - 向上(偏28)
|
| 79 |
+
|
| 80 |
+
text_range=f"Total frame:「{len(frames)}」 Manually adjust range : [ -{int(sum(average_range_minus) / len(average_range_minus))}~{int(sum(average_range_plus) / len(average_range_plus))} ] , the current value: {upperbondrange}"
|
| 81 |
+
return text_range
|
| 82 |
+
|
| 83 |
+
|
| 84 |
def get_landmark_and_bbox(img_list,upperbondrange =0):
|
| 85 |
frames = read_imgs(img_list)
|
| 86 |
batch_size_fa = 1
|
requirements.txt
CHANGED
|
@@ -9,3 +9,6 @@ opencv-python==4.9.0.80
|
|
| 9 |
soundfile==0.12.1
|
| 10 |
transformers==4.39.2
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
soundfile==0.12.1
|
| 10 |
transformers==4.39.2
|
| 11 |
|
| 12 |
+
gdown
|
| 13 |
+
requests
|
| 14 |
+
imageio[ffmpeg]
|