Spaces:
Running
on
Zero
Running
on
Zero
File size: 14,827 Bytes
8f6558d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
import os
import platform
import torch
import gradio as gr
from huggingface_hub import snapshot_download
import uuid
import shutil
from pydub import AudioSegment
import spaces
from src.facerender.pirender_animate import AnimateFromCoeff_PIRender
from src.utils.preprocess import CropAndExtract
from src.test_audio2coeff import Audio2Coeff
from src.facerender.animate import AnimateFromCoeff
from src.generate_batch import get_data
from src.generate_facerender_batch import get_facerender_data
from src.utils.init_path import init_path
def get_source_image(image):
return image
def toggle_audio_file(choice):
if choice == False:
return gr.update(visible=True), gr.update(visible=False)
else:
return gr.update(visible=False), gr.update(visible=True)
def ref_video_fn(path_of_ref_video):
if path_of_ref_video is not None:
return gr.update(value=True)
else:
return gr.update(value=False)
if torch.cuda.is_available():
device = "cuda"
elif platform.system() == 'Darwin': # macos
device = "mps"
else:
device = "cpu"
os.environ['TORCH_HOME'] = 'checkpoints'
checkpoint_path = 'checkpoints'
config_path = 'src/config'
snapshot_download(repo_id='vinthony/SadTalker-V002rc',
local_dir='./checkpoints', local_dir_use_symlinks=True)
def mp3_to_wav(mp3_filename, wav_filename, frame_rate):
mp3_file = AudioSegment.from_file(file=mp3_filename)
mp3_file.set_frame_rate(frame_rate).export(wav_filename, format="wav")
@spaces.GPU()
def test(source_image, driven_audio, preprocess='crop',
still_mode=False, use_enhancer=False, batch_size=1, size=256,
pose_style=0,
facerender='facevid2vid',
exp_scale=1.0,
use_ref_video=False,
ref_video=None,
ref_info=None,
use_idle_mode=False,
length_of_audio=0, use_blink=True,
result_dir='./results/'):
sadtalker_paths = init_path(
checkpoint_path, config_path, size, False, preprocess)
audio_to_coeff = Audio2Coeff(sadtalker_paths, device)
preprocess_model = CropAndExtract(sadtalker_paths, device)
if facerender == 'facevid2vid' and device != 'mps':
animate_from_coeff = AnimateFromCoeff(
sadtalker_paths, device)
elif facerender == 'pirender' or device == 'mps':
animate_from_coeff = AnimateFromCoeff_PIRender(
sadtalker_paths, device)
facerender = 'pirender'
else:
raise (RuntimeError('Unknown model: {}'.format(facerender)))
time_tag = str(uuid.uuid4())
save_dir = os.path.join(result_dir, time_tag)
os.makedirs(save_dir, exist_ok=True)
input_dir = os.path.join(save_dir, 'input')
os.makedirs(input_dir, exist_ok=True)
print(source_image)
pic_path = os.path.join(input_dir, os.path.basename(source_image))
shutil.move(source_image, input_dir)
if driven_audio is not None and os.path.isfile(driven_audio):
audio_path = os.path.join(input_dir, os.path.basename(driven_audio))
# mp3 to wav
if '.mp3' in audio_path:
mp3_to_wav(driven_audio, audio_path.replace('.mp3', '.wav'), 16000)
audio_path = audio_path.replace('.mp3', '.wav')
else:
shutil.move(driven_audio, input_dir)
elif use_idle_mode:
# generate audio from this new audio_path
audio_path = os.path.join(
input_dir, 'idlemode_'+str(length_of_audio)+'.wav')
from pydub import AudioSegment
one_sec_segment = AudioSegment.silent(
duration=1000*length_of_audio) # duration in milliseconds
one_sec_segment.export(audio_path, format="wav")
else:
print(use_ref_video, ref_info)
assert use_ref_video == True and ref_info == 'all'
if use_ref_video and ref_info == 'all': # full ref mode
ref_video_videoname = os.path.basename(ref_video)
audio_path = os.path.join(save_dir, ref_video_videoname+'.wav')
print('new audiopath:', audio_path)
# if ref_video contains audio, set the audio from ref_video.
cmd = r"ffmpeg -y -hide_banner -loglevel error -i %s %s" % (
ref_video, audio_path)
os.system(cmd)
os.makedirs(save_dir, exist_ok=True)
# crop image and extract 3dmm from image
first_frame_dir = os.path.join(save_dir, 'first_frame_dir')
os.makedirs(first_frame_dir, exist_ok=True)
first_coeff_path, crop_pic_path, crop_info = preprocess_model.generate(
pic_path, first_frame_dir, preprocess, True, size)
if first_coeff_path is None:
raise AttributeError("No face is detected")
if use_ref_video:
print('using ref video for genreation')
ref_video_videoname = os.path.splitext(os.path.split(ref_video)[-1])[0]
ref_video_frame_dir = os.path.join(save_dir, ref_video_videoname)
os.makedirs(ref_video_frame_dir, exist_ok=True)
print('3DMM Extraction for the reference video providing pose')
ref_video_coeff_path, _, _ = preprocess_model.generate(
ref_video, ref_video_frame_dir, preprocess, source_image_flag=False)
else:
ref_video_coeff_path = None
if use_ref_video:
if ref_info == 'pose':
ref_pose_coeff_path = ref_video_coeff_path
ref_eyeblink_coeff_path = None
elif ref_info == 'blink':
ref_pose_coeff_path = None
ref_eyeblink_coeff_path = ref_video_coeff_path
elif ref_info == 'pose+blink':
ref_pose_coeff_path = ref_video_coeff_path
ref_eyeblink_coeff_path = ref_video_coeff_path
elif ref_info == 'all':
ref_pose_coeff_path = None
ref_eyeblink_coeff_path = None
else:
raise ('error in refinfo')
else:
ref_pose_coeff_path = None
ref_eyeblink_coeff_path = None
# audio2ceoff
if use_ref_video and ref_info == 'all':
# audio_to_coeff.generate(batch, save_dir, pose_style, ref_pose_coeff_path)
coeff_path = ref_video_coeff_path
else:
batch = get_data(first_coeff_path, audio_path, device, ref_eyeblink_coeff_path=ref_eyeblink_coeff_path, still=still_mode,
idlemode=use_idle_mode, length_of_audio=length_of_audio, use_blink=use_blink) # longer audio?
coeff_path = audio_to_coeff.generate(
batch, save_dir, pose_style, ref_pose_coeff_path)
# coeff2video
data = get_facerender_data(coeff_path, crop_pic_path, first_coeff_path, audio_path, batch_size, still_mode=still_mode,
preprocess=preprocess, size=size, expression_scale=exp_scale, facemodel=facerender)
return_path = animate_from_coeff.generate(
data, save_dir, pic_path, crop_info, enhancer='gfpgan' if use_enhancer else None, preprocess=preprocess, img_size=size)
video_name = data['video_name']
print(f'The generated video is named {video_name} in {save_dir}')
del preprocess_model
del audio_to_coeff
del animate_from_coeff
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
import gc
gc.collect()
return return_path
with gr.Blocks(analytics_enabled=False) as demo:
with gr.Row().style(equal_height=False):
with gr.Column(variant='panel'):
with gr.Tabs(elem_id="sadtalker_source_image"):
with gr.TabItem('Source image'):
with gr.Row():
source_image = gr.Image(
label="Source image", source="upload", type="filepath", elem_id="img2img_image").style(width=512)
with gr.Tabs(elem_id="sadtalker_driven_audio"):
with gr.TabItem('Driving Methods'):
gr.Markdown(
"Possible driving combinations: <br> 1. Audio only 2. Audio/IDLE Mode + Ref Video(pose, blink, pose+blink) 3. IDLE Mode only 4. Ref Video only (all) ")
with gr.Row():
driven_audio = gr.Audio(
label="Input audio", source="upload", type="filepath")
driven_audio_no = gr.Audio(
label="Use IDLE mode, no audio is required", source="upload", type="filepath", visible=False)
with gr.Column():
use_idle_mode = gr.Checkbox(
label="Use Idle Animation")
length_of_audio = gr.Number(
value=5, label="The length(seconds) of the generated video.")
use_idle_mode.change(toggle_audio_file, inputs=use_idle_mode, outputs=[
driven_audio, driven_audio_no]) # todo
with gr.Row():
ref_video = gr.Video(
label="Reference Video", source="upload", type="filepath", elem_id="vidref").style(width=512)
with gr.Column():
use_ref_video = gr.Checkbox(
label="Use Reference Video")
ref_info = gr.Radio(['pose', 'blink', 'pose+blink', 'all'], value='pose', label='Reference Video',
info="How to borrow from reference Video?((fully transfer, aka, video driving mode))")
ref_video.change(ref_video_fn, inputs=ref_video, outputs=[
use_ref_video]) # todo
with gr.Column(variant='panel'):
with gr.Tabs(elem_id="sadtalker_checkbox"):
with gr.TabItem('Settings'):
with gr.Column(variant='panel'):
# width = gr.Slider(minimum=64, elem_id="img2img_width", maximum=2048, step=8, label="Manually Crop Width", value=512) # img2img_width
# height = gr.Slider(minimum=64, elem_id="img2img_height", maximum=2048, step=8, label="Manually Crop Height", value=512) # img2img_width
with gr.Row():
pose_style = gr.Slider(
minimum=0, maximum=45, step=1, label="Pose style", value=0)
exp_weight = gr.Slider(
minimum=0, maximum=3, step=0.1, label="expression scale", value=1)
blink_every = gr.Checkbox(
label="use eye blink", value=True)
with gr.Row():
size_of_image = gr.Radio(
[256, 512], value=256, label='face model resolution', info="use 256/512 model?")
preprocess_type = gr.Radio(
['crop', 'resize', 'full', 'extcrop', 'extfull'], value='crop', label='preprocess', info="How to handle input image?")
with gr.Row():
is_still_mode = gr.Checkbox(
label="Still Mode (fewer head motion, works with preprocess `full`)")
facerender = gr.Radio(
['facevid2vid', 'pirender'], value='facevid2vid', label='facerender', info="which face render?")
with gr.Row():
batch_size = gr.Slider(
label="batch size in generation", step=1, maximum=10, value=1)
enhancer = gr.Checkbox(
label="GFPGAN as Face enhancer")
submit = gr.Button(
'Generate', elem_id="sadtalker_generate", variant='primary')
with gr.Tabs(elem_id="sadtalker_genearted"):
gen_video = gr.Video(
label="Generated video", format="mp4").style(width=256)
submit.click(
fn=test,
inputs=[source_image,
driven_audio,
preprocess_type,
is_still_mode,
enhancer,
batch_size,
size_of_image,
pose_style,
facerender,
exp_weight,
use_ref_video,
ref_video,
ref_info,
use_idle_mode,
length_of_audio,
blink_every
],
outputs=[gen_video],
)
with gr.Row():
examples = [
[
'examples/source_image/full_body_1.png',
'examples/driven_audio/bus_chinese.wav',
'crop',
True,
False
],
[
'examples/source_image/full_body_2.png',
'examples/driven_audio/japanese.wav',
'crop',
False,
False
],
[
'examples/source_image/full3.png',
'examples/driven_audio/deyu.wav',
'crop',
False,
True
],
[
'examples/source_image/full4.jpeg',
'examples/driven_audio/eluosi.wav',
'full',
False,
True
],
[
'examples/source_image/full4.jpeg',
'examples/driven_audio/imagine.wav',
'full',
True,
True
],
[
'examples/source_image/full_body_1.png',
'examples/driven_audio/bus_chinese.wav',
'full',
True,
False
],
[
'examples/source_image/art_13.png',
'examples/driven_audio/fayu.wav',
'resize',
True,
False
],
[
'examples/source_image/art_5.png',
'examples/driven_audio/chinese_news.wav',
'resize',
False,
False
],
[
'examples/source_image/art_5.png',
'examples/driven_audio/RD_Radio31_000.wav',
'resize',
True,
True
],
]
gr.Examples(examples=examples,
inputs=[
source_image,
driven_audio,
preprocess_type,
is_still_mode,
enhancer],
outputs=[gen_video],
fn=test,
cache_examples=os.getenv('SYSTEM') == 'spaces')
demo.launch(debug=True)
|