kevinwang676 commited on
Commit
925ec43
·
verified ·
1 Parent(s): e5e7032

Create app_new.py

Browse files
Files changed (1) hide show
  1. app_new.py +413 -0
app_new.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ force_download=True, resume_download=False
53
+ )
54
+ # weight
55
+ os.makedirs(f"{CheckpointsDir}/sd-vae-ft-mse/")
56
+ snapshot_download(
57
+ repo_id="stabilityai/sd-vae-ft-mse",
58
+ local_dir=CheckpointsDir+'/sd-vae-ft-mse',
59
+ max_workers=8,
60
+ local_dir_use_symlinks=True,
61
+ force_download=True, resume_download=False
62
+ )
63
+ #dwpose
64
+ os.makedirs(f"{CheckpointsDir}/dwpose/")
65
+ snapshot_download(
66
+ repo_id="yzd-v/DWPose",
67
+ local_dir=CheckpointsDir+'/dwpose',
68
+ max_workers=8,
69
+ local_dir_use_symlinks=True,
70
+ force_download=True, resume_download=False
71
+ )
72
+ #vae
73
+ url = "https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt"
74
+ response = requests.get(url)
75
+ # 确保请求成功
76
+ if response.status_code == 200:
77
+ # 指定文件保存的位置
78
+ file_path = f"{CheckpointsDir}/whisper/tiny.pt"
79
+ os.makedirs(f"{CheckpointsDir}/whisper/")
80
+ # 将文件内容写入指定位置
81
+ with open(file_path, "wb") as f:
82
+ f.write(response.content)
83
+ else:
84
+ print(f"请求失败,状态码:{response.status_code}")
85
+ #gdown face parse
86
+ url = "https://drive.google.com/uc?id=154JgKpzCPW82qINcVieuPH3fZ2e0P812"
87
+ os.makedirs(f"{CheckpointsDir}/face-parse-bisent/")
88
+ file_path = f"{CheckpointsDir}/face-parse-bisent/79999_iter.pth"
89
+ gdown.download(url, file_path, quiet=False)
90
+ #resnet
91
+ url = "https://download.pytorch.org/models/resnet18-5c106cde.pth"
92
+ response = requests.get(url)
93
+ # 确保请求成功
94
+ if response.status_code == 200:
95
+ # 指定文件保存的位置
96
+ file_path = f"{CheckpointsDir}/face-parse-bisent/resnet18-5c106cde.pth"
97
+ # 将文件内容写入指定位置
98
+ with open(file_path, "wb") as f:
99
+ f.write(response.content)
100
+ else:
101
+ print(f"请求失败,状态码:{response.status_code}")
102
+
103
+
104
+ toc = time.time()
105
+
106
+ print(f"download cost {toc-tic} seconds")
107
+ print_directory_contents(CheckpointsDir)
108
+
109
+ else:
110
+ print("Already download the model.")
111
+
112
+
113
+
114
+
115
+
116
+ download_model() # for huggingface deployment.
117
+
118
+
119
+ from musetalk.utils.utils import get_file_type,get_video_fps,datagen
120
+ from musetalk.utils.preprocessing import get_landmark_and_bbox,read_imgs,coord_placeholder,get_bbox_range
121
+ from musetalk.utils.blending import get_image
122
+ from musetalk.utils.utils import load_all_model
123
+
124
+
125
+
126
+
127
+
128
+
129
+ @spaces.GPU(duration=600)
130
+ @torch.no_grad()
131
+ def inference(audio_path,video_path,bbox_shift,progress=gr.Progress(track_tqdm=True)):
132
+ args_dict={"result_dir":'./results/output', "fps":25, "batch_size":8, "output_vid_name":'', "use_saved_coord":False}#same with inferenece script
133
+ args = Namespace(**args_dict)
134
+
135
+ input_basename = os.path.basename(video_path).split('.')[0]
136
+ audio_basename = os.path.basename(audio_path).split('.')[0]
137
+ output_basename = f"{input_basename}_{audio_basename}"
138
+ result_img_save_path = os.path.join(args.result_dir, output_basename) # related to video & audio inputs
139
+ crop_coord_save_path = os.path.join(result_img_save_path, input_basename+".pkl") # only related to video input
140
+ os.makedirs(result_img_save_path,exist_ok =True)
141
+
142
+ if args.output_vid_name=="":
143
+ output_vid_name = os.path.join(args.result_dir, output_basename+".mp4")
144
+ else:
145
+ output_vid_name = os.path.join(args.result_dir, args.output_vid_name)
146
+ ############################################## extract frames from source video ##############################################
147
+ if get_file_type(video_path)=="video":
148
+ save_dir_full = os.path.join(args.result_dir, input_basename)
149
+ os.makedirs(save_dir_full,exist_ok = True)
150
+ # cmd = f"ffmpeg -v fatal -i {video_path} -start_number 0 {save_dir_full}/%08d.png"
151
+ # os.system(cmd)
152
+ # 读取视频
153
+ reader = imageio.get_reader(video_path)
154
+
155
+ # 保存图片
156
+ for i, im in enumerate(reader):
157
+ imageio.imwrite(f"{save_dir_full}/{i:08d}.png", im)
158
+ input_img_list = sorted(glob.glob(os.path.join(save_dir_full, '*.[jpJP][pnPN]*[gG]')))
159
+ fps = get_video_fps(video_path)
160
+ else: # input img folder
161
+ input_img_list = glob.glob(os.path.join(video_path, '*.[jpJP][pnPN]*[gG]'))
162
+ input_img_list = sorted(input_img_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
163
+ fps = args.fps
164
+ #print(input_img_list)
165
+ ############################################## extract audio feature ##############################################
166
+ whisper_feature = audio_processor.audio2feat(audio_path)
167
+ whisper_chunks = audio_processor.feature2chunks(feature_array=whisper_feature,fps=fps)
168
+ ############################################## preprocess input image ##############################################
169
+ if os.path.exists(crop_coord_save_path) and args.use_saved_coord:
170
+ print("using extracted coordinates")
171
+ with open(crop_coord_save_path,'rb') as f:
172
+ coord_list = pickle.load(f)
173
+ frame_list = read_imgs(input_img_list)
174
+ else:
175
+ print("extracting landmarks...time consuming")
176
+ coord_list, frame_list = get_landmark_and_bbox(input_img_list, bbox_shift)
177
+ with open(crop_coord_save_path, 'wb') as f:
178
+ pickle.dump(coord_list, f)
179
+ bbox_shift_text=get_bbox_range(input_img_list, bbox_shift)
180
+ i = 0
181
+ input_latent_list = []
182
+ for bbox, frame in zip(coord_list, frame_list):
183
+ if bbox == coord_placeholder:
184
+ continue
185
+ x1, y1, x2, y2 = bbox
186
+ crop_frame = frame[y1:y2, x1:x2]
187
+ crop_frame = cv2.resize(crop_frame,(256,256),interpolation = cv2.INTER_LANCZOS4)
188
+ latents = vae.get_latents_for_unet(crop_frame)
189
+ input_latent_list.append(latents)
190
+
191
+ # to smooth the first and the last frame
192
+ frame_list_cycle = frame_list + frame_list[::-1]
193
+ coord_list_cycle = coord_list + coord_list[::-1]
194
+ input_latent_list_cycle = input_latent_list + input_latent_list[::-1]
195
+ ############################################## inference batch by batch ##############################################
196
+ print("start inference")
197
+ video_num = len(whisper_chunks)
198
+ batch_size = args.batch_size
199
+ gen = datagen(whisper_chunks,input_latent_list_cycle,batch_size)
200
+ res_frame_list = []
201
+ for i, (whisper_batch,latent_batch) in enumerate(tqdm(gen,total=int(np.ceil(float(video_num)/batch_size)))):
202
+
203
+ tensor_list = [torch.FloatTensor(arr) for arr in whisper_batch]
204
+ audio_feature_batch = torch.stack(tensor_list).to(unet.device) # torch, B, 5*N,384
205
+ audio_feature_batch = pe(audio_feature_batch)
206
+
207
+ pred_latents = unet.model(latent_batch, timesteps, encoder_hidden_states=audio_feature_batch).sample
208
+ recon = vae.decode_latents(pred_latents)
209
+ for res_frame in recon:
210
+ res_frame_list.append(res_frame)
211
+
212
+ ############################################## pad to full image ##############################################
213
+ print("pad talking image to original video")
214
+ for i, res_frame in enumerate(tqdm(res_frame_list)):
215
+ bbox = coord_list_cycle[i%(len(coord_list_cycle))]
216
+ ori_frame = copy.deepcopy(frame_list_cycle[i%(len(frame_list_cycle))])
217
+ x1, y1, x2, y2 = bbox
218
+ try:
219
+ res_frame = cv2.resize(res_frame.astype(np.uint8),(x2-x1,y2-y1))
220
+ except:
221
+ # print(bbox)
222
+ continue
223
+
224
+ combine_frame = get_image(ori_frame,res_frame,bbox)
225
+ cv2.imwrite(f"{result_img_save_path}/{str(i).zfill(8)}.png",combine_frame)
226
+
227
+ # 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"
228
+ # print(cmd_img2video)
229
+ # os.system(cmd_img2video)
230
+ # 帧率
231
+ fps = 25
232
+ # 图片路径
233
+ # 输出视频路径
234
+ output_video = 'temp.mp4'
235
+
236
+ # 读取图片
237
+ def is_valid_image(file):
238
+ pattern = re.compile(r'\d{8}\.png')
239
+ return pattern.match(file)
240
+
241
+ images = []
242
+ files = [file for file in os.listdir(result_img_save_path) if is_valid_image(file)]
243
+ files.sort(key=lambda x: int(x.split('.')[0]))
244
+
245
+ for file in files:
246
+ filename = os.path.join(result_img_save_path, file)
247
+ images.append(imageio.imread(filename))
248
+
249
+
250
+ # 保存视频
251
+ imageio.mimwrite(output_video, images, 'FFMPEG', fps=fps, codec='libx264', pixelformat='yuv420p')
252
+
253
+ # cmd_combine_audio = f"ffmpeg -y -v fatal -i {audio_path} -i temp.mp4 {output_vid_name}"
254
+ # print(cmd_combine_audio)
255
+ # os.system(cmd_combine_audio)
256
+
257
+ input_video = './temp.mp4'
258
+ # Check if the input_video and audio_path exist
259
+ if not os.path.exists(input_video):
260
+ raise FileNotFoundError(f"Input video file not found: {input_video}")
261
+ if not os.path.exists(audio_path):
262
+ raise FileNotFoundError(f"Audio file not found: {audio_path}")
263
+
264
+ # 读取视频
265
+ reader = imageio.get_reader(input_video)
266
+ fps = reader.get_meta_data()['fps'] # 获取原视频的帧率
267
+
268
+ # 将帧存储在列表中
269
+ frames = images
270
+
271
+ # 保存视频并添加音频
272
+ # imageio.mimwrite(output_vid_name, frames, 'FFMPEG', fps=fps, codec='libx264', audio_codec='aac', input_params=['-i', audio_path])
273
+
274
+ # input_video = ffmpeg.input(input_video)
275
+
276
+ # input_audio = ffmpeg.input(audio_path)
277
+
278
+ print(len(frames))
279
+
280
+ # imageio.mimwrite(
281
+ # output_video,
282
+ # frames,
283
+ # 'FFMPEG',
284
+ # fps=25,
285
+ # codec='libx264',
286
+ # audio_codec='aac',
287
+ # input_params=['-i', audio_path],
288
+ # output_params=['-y'], # Add the '-y' flag to overwrite the output file if it exists
289
+ # )
290
+ # writer = imageio.get_writer(output_vid_name, fps = 25, codec='libx264', quality=10, pixelformat='yuvj444p')
291
+ # for im in frames:
292
+ # writer.append_data(im)
293
+ # writer.close()
294
+
295
+
296
+
297
+
298
+ # Load the video
299
+ video_clip = VideoFileClip(input_video)
300
+
301
+ # Load the audio
302
+ audio_clip = AudioFileClip(audio_path)
303
+
304
+ # Set the audio to the video
305
+ video_clip = video_clip.set_audio(audio_clip)
306
+
307
+ # Write the output video
308
+ video_clip.write_videofile(output_vid_name, codec='libx264', audio_codec='aac',fps=25)
309
+
310
+ os.remove("temp.mp4")
311
+ #shutil.rmtree(result_img_save_path)
312
+ print(f"result is save to {output_vid_name}")
313
+ return output_vid_name,bbox_shift_text
314
+
315
+
316
+
317
+ # load model weights
318
+ audio_processor,vae,unet,pe = load_all_model()
319
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
320
+ timesteps = torch.tensor([0], device=device)
321
+
322
+
323
+
324
+
325
+ def check_video(video):
326
+ if not isinstance(video, str):
327
+ return video # in case of none type
328
+ # Define the output video file name
329
+ dir_path, file_name = os.path.split(video)
330
+ if file_name.startswith("outputxxx_"):
331
+ return video
332
+ # Add the output prefix to the file name
333
+ output_file_name = "outputxxx_" + file_name
334
+
335
+ os.makedirs('./results',exist_ok=True)
336
+ os.makedirs('./results/output',exist_ok=True)
337
+ os.makedirs('./results/input',exist_ok=True)
338
+
339
+ # Combine the directory path and the new file name
340
+ output_video = os.path.join('./results/input', output_file_name)
341
+
342
+
343
+ # # Run the ffmpeg command to change the frame rate to 25fps
344
+ # command = f"ffmpeg -i {video} -r 25 -vcodec libx264 -vtag hvc1 -pix_fmt yuv420p crf 18 {output_video} -y"
345
+
346
+ # 读取视频
347
+ reader = imageio.get_reader(video)
348
+ fps = reader.get_meta_data()['fps'] # 获取原视频的帧率
349
+
350
+ # 将帧存储在列表中
351
+ frames = [im for im in reader]
352
+
353
+ # 保存视频
354
+ imageio.mimwrite(output_video, frames, 'FFMPEG', fps=25, codec='libx264', quality=9, pixelformat='yuv420p')
355
+ return output_video
356
+
357
+
358
+
359
+
360
+ css = """#input_img {max-width: 1024px !important} #output_vid {max-width: 1024px; max-height: 576px}"""
361
+
362
+ with gr.Blocks(css=css) as demo:
363
+ gr.Markdown(
364
+ "<div align='center'> <h1>MuseTalk: Real-Time High Quality Lip Synchronization with Latent Space Inpainting </span> </h1> \
365
+ <h2 style='font-weight: 450; font-size: 1rem; margin: 0rem'>\
366
+ </br>\
367
+ Yue Zhang <sup>\*</sup>,\
368
+ Minhao Liu<sup>\*</sup>,\
369
+ Zhaokang Chen,\
370
+ Bin Wu<sup>†</sup>,\
371
+ Yingjie He,\
372
+ Chao Zhan,\
373
+ Wenjiang Zhou\
374
+ (<sup>*</sup>Equal Contribution, <sup>†</sup>Corresponding Author, benbinwu@tencent.com)\
375
+ Lyra Lab, Tencent Music Entertainment\
376
+ </h2> \
377
+ <a style='font-size:18px;color: #000000' href='https://github.com/TMElyralab/MuseTalk'>[Github Repo]</a>\
378
+ <a style='font-size:18px;color: #000000' href='https://github.com/TMElyralab/MuseTalk'>[Huggingface]</a>\
379
+ <a style='font-size:18px;color: #000000' href=''> [Technical report(Coming Soon)] </a>\
380
+ <a style='font-size:18px;color: #000000' href=''> [Project Page(Coming Soon)] </a> </div>"
381
+ )
382
+
383
+ with gr.Row():
384
+ with gr.Column():
385
+ audio = gr.Audio(label="Driven Audio",type="filepath")
386
+ video = gr.Video(label="Reference Video",sources=['upload'])
387
+ bbox_shift = gr.Number(label="BBox_shift value, px", value=0)
388
+ 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)
389
+
390
+ btn = gr.Button("Generate")
391
+ out1 = gr.Video()
392
+
393
+ video.change(
394
+ fn=check_video, inputs=[video], outputs=[video]
395
+ )
396
+ btn.click(
397
+ fn=inference,
398
+ inputs=[
399
+ audio,
400
+ video,
401
+ bbox_shift,
402
+ ],
403
+ outputs=[out1,bbox_shift_scale]
404
+ )
405
+
406
+ # Set the IP and port
407
+ ip_address = "0.0.0.0" # Replace with your desired IP address
408
+ port_number = 7860 # Replace with your desired port number
409
+
410
+
411
+ demo.queue().launch(
412
+ share=True, debug=True, show_error=True #server_name=ip_address, server_port=port_number
413
+ )