add streaming inference support

This commit is contained in:
sen.liang committed 2022-06-17 19:03:40 +08:00
1 parent e0c6694f52
commit dd5b0646be
13 files changed
+775 -808

No files matched your search

@@ -1,4 +1,4 @@
GPUS: '1' GPUS: '0'
WORKERS: 4 WORKERS: 4
OUTPUT_DIR: 'experiments/audio2motion' OUTPUT_DIR: 'experiments/audio2motion'
@@ -19,7 +19,7 @@ MODEL:
dim_speech: 1024 dim_speech: 1024
num_vertices: 5023 num_vertices: 5023
pretrain: True pretrain: False
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_actor2_20220420/20220607-17H27M53S" path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_actor2_20220420/20220607-17H27M53S"
load_epoch: 120 load_epoch: 120
@@ -19,7 +19,7 @@ MODEL:
dim_speech: 1024 dim_speech: 1024
num_vertices: 5023 num_vertices: 5023
pretrain: True pretrain: False
# from actor2 # from actor2
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_actor2_20220420/20220607-17H27M53S" path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_actor2_20220420/20220607-17H27M53S"
load_epoch: 120 load_epoch: 120
+115 -60
View File
@@ -1,22 +1,24 @@
import time import sys,os
import sys
import pprint import pprint
import shutil
import argparse import argparse
import numpy as np
from pathlib import Path from pathlib import Path
import torch.nn.functional as F
from scipy.io import wavfile
import torch import torch
from torch.utils.data import DataLoader import torchaudio
from src.datasets import create_dataset from src.models import create_model
from src.models import create_model, calculate_model_params
from src.config import config as opt from src.config import config as opt
from src.config import update_config from src.config import update_config
from common.vis.visualizer import Visualizer import warnings
from common.logger import Logger warnings.filterwarnings("ignore")
from common.animation import save_animation_grid
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True) torch.autograd.set_detect_anomaly(True)
@@ -33,81 +35,134 @@ def parese_args():
args = pareser.parse_args() args = pareser.parse_args()
return args return args
def load_speech_data(path_audio, align=True):
"""
return sr=16000 raw audio data
"""
if not path_audio.exists():
raise(f"NOT existing {path_audio}")
# Load raw audio data
raw_speech, sr = torchaudio.load(path_audio)
logger.info(f"raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech[0])/sr)} s")
if len(raw_speech.shape) == 2:
raw_speech = raw_speech[0]
# resampling to 16KHz
if sr != 16000:
resampler = torchaudio.transforms.Resample(sr, 16_000)
raw_speech = resampler(raw_speech).squeeze().numpy()
sr = 16000
logger.info(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/16000)} s")
else:
raw_speech = raw_speech.numpy()
# if align to 1/50s
if align:
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
raw_speech = raw_speech[: len_align]
logger.info(f"align to 1/50s: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/sr)} s")
return raw_speech, sr
def define_extractor(device):
logger.info("load Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor
if __name__ == "__main__": if __name__ == "__main__":
args = parese_args() args = parese_args()
path_config = Path(args.opt) path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix) logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
logger.info(pprint.pformat(opt))
# logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output opt.OUTPUT_DIR = logger.path_output
# load motion
test_dataset = create_dataset(opt, phase='test')
test_loader = DataLoader(test_dataset,
batch_size=opt.TEST.batch_size * len(opt.GPUS),
shuffle=True, # NOTE: usually set False
num_workers=opt.WORKERS,
pin_memory=False)
# logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
# load wav2Vec model
processor, extractor = define_extractor(device)
# get model # load audio-driven model
model = create_model(opt, logger) model = create_model(opt, logger)
model.setup(opt) # load model model.setup(opt)
# model.remove_weightnorm()
# Add for WaveFlow # path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
# model.netG.module = model.netG.module.remove_weightnorm(model.netG.module)
for i, batch_input in enumerate(test_loader):
motion = batch_input['data'].float().to(device) # (nbatch, nsteps=60, dim_motion=136) # path_audio = Path("/mfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav")
speech = batch_input["cond"].float().to(device) # (nbatch, nsteps=173, dim_condit=80)
motion = motion.permute(0, 2, 1) # (nbatch, 136, 60)
speech = speech.permute(0, 2, 1) # (nbatch, 80, 173)
B = motion.size(0)
motion_gt = motion.permute(0,2,1)[0:1, :, :]
path_audio = Path("./data/test/Actor6_4R3A0139_audio_trim.wav")
# generate k samples # path_audio = Path("/mfs/lsen/DATA/Actor7/processing/4R3A0178/audio/audio_trim_120s.wav")
motion_pt = [] # vid_valid = set(["BU6A9965","BU6A9978"])
for j in range(8): # path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9965/audio/audio_trim_60s.wav")
data_pt = model.testing(batch_input, cur_epoch=opt.MODEL.load_epoch, save_animation=False) # B x nsteps x 136 # path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9978/audio/audio_trim_60s.wav")
data_pt = data_pt[0:1, :, :]
motion_pt.append(data_pt)
motion_pt = torch.cat(motion_pt, dim=0) # 8 x nsteps x 136 # path_audio = Path("data/test/actor6/actor6_sentence4_1.wav")
nsteps = min(motion_gt.size(1), motion_pt.size(1))
total_motion = torch.cat([motion_gt[:, :nsteps, :], motion_pt[:, :nsteps, :]], dim=0)
print(f"total motion shape = {total_motion.shape}") # path_audio = Path("data/bank-demo.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor4/processing/4R3A0024/audio/audio_trim_60_60s.wav")
# path_audio = Path("data/test/ali_test_222.wav")
path_save=Path(opt.OUTPUT_DIR).joinpath(f'sampled_{opt.MODEL.load_epoch:05d}_{i:03d}.mp4') # acotr 5
# path_audio = Path("/ssdata1/lsen/DATA/Actor5/smile/4R3A0071/audio/audio_trim_60_60s.wav")
save_animation_grid(total_motion, path_save=path_save, ncol=3, w=256, h=256, dpi=100) # path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/tts-scenes/tts-scene-1.wav")
# path_audio = Path("/ssdata1/lsen/CODE/audio-to-motion/data/test/ali_test_new.wav")
# path_folder = Path("./data/test/tts-scenes")
# opt.OUTPUT_DIR = path_folder.joinpath("inference_video_actor5_with_npy")
# opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"SVAE -> {opt.OUTPUT_DIR}") # load audio
# break raw_speech, sr = load_speech_data(path_audio, align=True)
# # infer # padding half frame length for bed and end
# epoch_beg = 400 fps = 50
# epoch_end = 580 npad_wv = 0.5 # for wav2vec 2.0: padding half frame length for bed and end
# for epoch in range(epoch_end, epoch_beg, -50): npad_wd_head, npad_wd_tail = 7, 8 # for audio2motion: nwind_size = 16, need_pad 15 frame for each clips
# print(f"Testing the epoch{epoch}/{epoch_end}") npad_head = int(sr*(npad_wd_head/fps) + sr*(npad_wv/fps) + 0.5)
npad_tail = int(sr*(npad_wd_tail/fps) + sr*(npad_wv/fps) + 0.5)
# opt.MODEL.load_epoch = epoch # set load epoch pad_speech = np.pad(raw_speech, pad_width=((npad_head, npad_tail)), mode="edge")
# model.setup(opt) # load model print(f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}")
# for i, ibatch_data in enumerate(test_loader): with torch.no_grad():
# model.testing(ibatch_data, cur_epoch=epoch, cur_batch=i) inputs = processor(pad_speech, sampling_rate=sr, return_tensors="pt").to(device)
# model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*100+1)) cond = extractor(**inputs).last_hidden_state
# model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*1000+1))
# break logger.info(f"\t\t [processor] processor input_values = {inputs['input_values'].shape}")
logger.info(f"\t\t [extractor] last_hidden_state = {cond.shape}")
# convert to windows
# cond = F.pad(cond, pad=(0, 0, 8, 7), mode="replicate")
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
nseq = cond.size(1)
print(f"after convert window cond shape = {cond.shape}")
# # save wav
# cmd = f"cp {str(path_audio)} {str(Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.name}'))}"
# os.system(cmd)
# save trim wav
path_audio_pad_trim = Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.stem}_input_pad_trim.wav')
wavfile.write(str(path_audio_pad_trim), rate=sr, data=raw_speech)
# inference
path_save = f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}"
model.infer(cond, raw_speech[np.newaxis, :], path_save)
File renamed without changes.
-177
View File
@@ -1,177 +0,0 @@
import sys
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch
import librosa
from src.models import create_model, calculate_model_params
from src.config import config as opt
from src.config import update_config
from common.vis.visualizer import Visualizer
from common.logger import Logger
from common.animation import save_images_with_audio
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
# load motion
# test_dataset = create_dataset(opt, phase='test')
# test_loader = DataLoader(test_dataset,
# batch_size=opt.TEST.batch_size * len(opt.GPUS),
# shuffle=True, # NOTE: usually set False
# num_workers=opt.WORKERS,
# pin_memory=False)
# path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
# vid = "Celebrating-Independence-Day"
# path_audio = path_data.joinpath(vid, "audio/audio_trim.wav")
# path_speech = path_data.joinpath(vid, "audio/feat_mel_no_align_trim.npy")
# path_motion = path_data.joinpath(vid, "audio/feat_ldmk_trim_norm.npy")
path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/test_video_15.wav")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/cut_lsz.wav")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/obama.wav")
# data extract audio
# Load data_audio and extract features
# load trim audio
fps = 30
numcep = 27
nseqR = opt.MODEL.n_lookprevs_speech # 3~9
nseqL = opt.MODEL.n_lookahead_speech # 3~9
data, sr = librosa.load(str(path_audio), sr=16000)
hop_len = int(sr / fps)
n_fft = int(sr * 0.13) # default 2048
print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
# melspectrogram
feat = librosa.feature.melspectrogram(y=data, sr=sr,
n_fft=n_fft, # FFT窗口的长度
hop_length=hop_len, # 帧移
win_length=n_fft, # 窗口长度,默认=n_fft
window="hann", # 加hanming窗
n_mels=numcep, # 滤波器组
fmin=0.0, fmax=8000)
feat = np.log(feat+1).T
print(f"sr={sr}, data ={data.shape}, feat = {feat.shape}, (min,max)=({np.min(feat), np.max(feat)}")
# padding
# Add empty initial and final contexts
empty_contextR = np.zeros((nseqR, numcep), dtype=feat.dtype)
empty_contextL = np.zeros((nseqL, numcep), dtype=feat.dtype)
feat = np.concatenate((empty_contextR, feat, empty_contextL)) # (469, 27)
# feat = torch.from_numpy(feat).unsqueeze_(0)
print(f"after padding feat ={feat.shape}")
# logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
# get model
model = create_model(opt, logger)
model.setup(opt) # load model
# model.remove_weightnorm()
nstep = feat.shape[0]
nstep_new = nstep - nseqR - nseqL
wsize = nseqR + 1 + nseqL
# prepare data condition: nc_condit = (nseqR + 1 + nseqL) * nc_speech
data_speech = torch.from_numpy(feat) # (nstep, nc_speech)
res_condit = data_speech.unfold(dimension=0, size=wsize, step=1) # (nstep_new, nc_speech, wsize)
res_condit = res_condit.swapaxes_(1,2) # (nstep_new, wsize, nc_speech)
res_condit = res_condit.reshape(1, nstep_new, -1) # (1, nsetp_new, nc_condit)
assert res_condit.shape[-1] == wsize * numcep
model.infer(res_condit, path_audio, f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}")
# # Add for WaveFlow
# # model.netG.module = model.netG.module.remove_weightnorm(model.netG.module)
# # for i, batch_input in enumerate(test_loader):
# motion = batch_input['data'].float().to(device) # (nbatch, nsteps=60, dim_motion=136)
# speech = batch_input['cond'].float().to(device) # (nbatch, nsteps=173, dim_condit=80)
# motion = motion.permute(0, 2, 1) # (nbatch, 136, 60)
# speech = speech.permute(0, 2, 1) # (nbatch, 80, 173)
# B = motion.size(0)
# motion_gt = motion.permute(0,2,1)[0:1, :, :]
# # generate k samples
# motion_pt = []
# for j in range(3):
# data_pt = model.testing(batch_input, cur_epoch=opt.MODEL.load_epoch, save_animation=False) # B x nsteps x 136
# data_pt = data_pt[0:1, :, :]
# motion_pt.append(data_pt)
# # save
# print("data_pt shape = ", data_pt.shape)
# np.save(f"data/ldmk_pdt_align30_{j}.npy", data_pt.cpu().numpy()[0])
# motion_pt = torch.cat(motion_pt, dim=0) # 8 x nsteps x 136
# nsteps = min(motion_gt.size(1), motion_pt.size(1))
# total_motion = torch.cat([motion_gt[:, :nsteps, :], motion_pt[:, :nsteps, :]], dim=0)
# print(f"total motion shape = {total_motion.shape}")
# path_save=Path(opt.OUTPUT_DIR).joinpath(f'sampled_{opt.MODEL.load_epoch:05d}.mp4')
# save_animation_grid(total_motion, path_save=path_save, path_audio=path_audio, ncol=2, w=256, h=256, dpi=100)
# # animation_with_audio(path_save, path_audio)
# print(f"SVAE -> {opt.OUTPUT_DIR}")
# # break
# # # infer
# # epoch_beg = 400
# # epoch_end = 580
# # for epoch in range(epoch_end, epoch_beg, -50):
# # print(f"Testing the epoch{epoch}/{epoch_end}")
# # opt.MODEL.load_epoch = epoch # set load epoch
# # model.setup(opt) # load model
# # for i, ibatch_data in enumerate(test_loader):
# # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=i)
# # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*100+1))
# # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*1000+1))
# # break
-143
View File
@@ -1,143 +0,0 @@
import sys,os
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch.nn.functional as F
from scipy.io import wavfile
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
import warnings
warnings.filterwarnings("ignore")
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
# logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav")
path_audio = Path("./data/test/Actor6_4R3A0139_audio_trim.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor7/processing/4R3A0178/audio/audio_trim_120s.wav")
# vid_valid = set(["BU6A9965","BU6A9978"])
# path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9965/audio/audio_trim_60s.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9978/audio/audio_trim_60s.wav")
# path_audio = Path("data/test/actor6/actor6_sentence4_1.wav")
# path_audio = Path("data/bank-demo.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor4/processing/4R3A0024/audio/audio_trim_60_60s.wav")
# path_audio = Path("data/test/ali_test_222.wav")
# acotr 5
# path_audio = Path("/ssdata1/lsen/DATA/Actor5/smile/4R3A0071/audio/audio_trim_60_60s.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/tts-scenes/tts-scene-1.wav")
# path_audio = Path("/ssdata1/lsen/CODE/audio-to-motion/data/test/ali_test_new.wav")
# path_folder = Path("./data/test/tts-scenes")
# opt.OUTPUT_DIR = path_folder.joinpath("inference_video_actor5_with_npy")
# opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
# load raw speech
raw_speech, sample_rate = torchaudio.load(path_audio)
# raw_speech = raw_speech.numpy()
print(f"raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech[0])/sample_rate)}")
if len(raw_speech.shape) == 2:
raw_speech = raw_speech[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
raw_speech = resampler(raw_speech).squeeze().numpy()
sample_rate = 16000
print(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {16000}, duration = {(len(raw_speech)/16000)}")
else:
raw_speech = raw_speech.numpy()
# padding to
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
raw_speech = raw_speech[: len_align]
print(f"after raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech)/sample_rate)}")
# load wav2Vec model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# MODEL_ID_PATH = "./data/wav2vec2-large-xlsr-53-chinese-zh-cn.json"
processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID, cache_dir="/home/liangsen/.cache/huggingface/transformers")
extractor = Wav2Vec2Model.from_pretrained(pretrained_model_name_or_path=MODEL_ID, cache_dir="/home/liangsen/.cache/huggingface/transformers").to(device)
# padding half frame length for bed and end
npad = int(0.5 * 16000* ( 1 / 50) + 0.5)
pad_speech = np.pad(raw_speech, pad_width=((npad, npad)), mode="edge")
print(f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}")
inputs = processor(pad_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
with torch.no_grad():
output = extractor(**inputs)
cond = output.last_hidden_state
print(f"cond shape = {cond.shape}")
# convert to windows
cond = F.pad(cond, pad=(0, 0, 8, 7), mode="replicate")
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
nseq = cond.size(1)
print(f"after convert window cond shape = {cond.shape}")
# self.data = self.data[:, 7:7+nseq, :]
# get model
model = create_model(opt, logger)
model.setup(opt) # load model
# model.remove_weightnorm()
# # save wav
# cmd = f"cp {str(path_audio)} {str(Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.name}'))}"
# os.system(cmd)
# save trim wav
path_audio_pad_trim = Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.stem}_input_pad_trim.wav')
wavfile.write(str(path_audio_pad_trim), rate=16000, data=raw_speech)
# inference
path_save = f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}"
model.infer(cond, raw_speech[np.newaxis, :], path_save)
-230
View File
@@ -1,230 +0,0 @@
import sys
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch.nn.functional as F
import json
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
def load_speech_data(path_audio):
"""
return sr=16000 raw audio data
"""
if not path_audio.exists():
raise(f"NOT existing {path_audio}")
# Load data_audio
data_speech, sample_rate = torchaudio.load(path_audio)
# print(f"data_speech shape = {data_speech.shape}, sr = {sample_rate}, duration = {(len(data_speech[0])/sample_rate)}")
if len(data_speech.shape) == 2:
data_speech = data_speech[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
data_speech = resampler(data_speech).squeeze().numpy()
# print(f"data_speech shape = {data_speech.shape}, sr = {16000}, duration = {(len(data_speech)/16000)}")
return data_speech
def load_motion_data(path_info, path_feat_exp, path_feat_pos):
if not path_feat_exp.exists() or not path_feat_pos.exists() :
raise(f"NOT existing {path_feat_exp} | {path_feat_pos}")
# load video info
with open(str(path_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
# print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(path_feat_exp) # (nframe, 50)
data_pos = np.load(path_feat_pos) # (nframe, 6)
# data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
# assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
return data_motion
def processing_one_file(path_data, processor, extractor, model):
# base path of this data
path_info = path_data.joinpath("video/info.json")
path_feat_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
path_feat_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
path_speech = path_data.joinpath("audio/audio_trim.wav")
path_loss_save = path_data.joinpath("audio/loss_20220228-18H41M46S_175.npy")
# load data
data_speech = load_speech_data(path_speech)
data_motion = load_motion_data(path_info, path_feat_exp, path_feat_pos)
total_segmt = data_speech.shape[0]
print(f"\t load: data_speech = {data_speech.shape}, data_motion={data_motion.shape}")
# clip speech & motion data
fps = opt.DATASET.fps # 50
sr = opt.DATASET.sr # 16000
nwind = opt.DATASET.nwind_second_test
nsteps_frame = nwind * fps
nsteps_segmt = nwind * sr
print(f"\t setting: fps = {fps}, sr = {sr}, nwind={nwind}, nsteps_frame={nsteps_frame}, nsteps_segmt={nsteps_segmt}")
beg_segmt, beg_frame = 0, 0
nframe_total_real = 0
batch_loss, batch_frame = [], []
while beg_segmt < len(data_speech):
end_segmt = beg_segmt + nsteps_segmt # update
end_frame = beg_frame + nsteps_frame # update
print(f"\n\t\t while loop ... beg_frame:end_frame = {beg_frame}:{end_frame}")
###### get clip data_motion
idata_motion = data_motion[beg_frame:end_frame] # (nframe_steps?, nc_motion)
if idata_motion.shape[0] < nsteps_frame:
inpad_motion = nsteps_frame - idata_motion.shape[0]
print(f"\t idata_motion = {idata_motion.shape}, need padding inpad_motion = {inpad_motion}")
idata_motion = np.pad(idata_motion, pad_width=((0, inpad_motion),(0,0)), mode="edge") # (nframe_steps, nc_motion)
print(f"\t after padding idata_motion = {idata_motion.shape}")
idata_motion = torch.from_numpy(idata_motion).reshape(1, nsteps_frame, -1) # 1 x nframe_steps x nc_motion
###### get clip data_speech
# padding data for wave2vect alignment
npad_wv = int(0.5 * sr * ( 1 / fps) + 0.5)
npad_wd1, npad_wd2 = 7, 8 # nwind_size = 16, need_pad 15 frame for each clips
nframe_real = nsteps_frame
ibeg_segmt = int(beg_segmt - sr * (npad_wd1/fps) - npad_wv - 0.5)
iend_segmt = int(end_segmt + sr * (npad_wd2/fps) + npad_wv + 0.5)
idata_speech = data_speech[max(ibeg_segmt, 0): min(iend_segmt, total_segmt)] # (nsegmt_steps + npad_wv, )
inpad_l = - ibeg_segmt if ibeg_segmt < 0 else 0
inpad_r = iend_segmt - total_segmt if iend_segmt > total_segmt else 0
if inpad_l + inpad_r > 0:
print(f"\t idata_speech = {idata_speech.shape}, inpad_l = {inpad_l}, inpad_r={inpad_r} ")
idata_speech = np.pad(idata_speech, pad_width=((inpad_l, inpad_r)), mode="edge") # (nsegmt_steps + 2npad_wv, )
print(f"\t after padding idata_speech = {idata_speech.shape}")
if end_segmt > total_segmt:
nframe_real = int(((total_segmt - beg_segmt) / sr ) * fps)
else:
nframe_real = nsteps_frame
# do audio extraction
# print(f"\t before extraction idata_speech = {idata_speech.shape}, nframe_real={nframe_real}")
inputs = processor(idata_speech, sampling_rate=16000, return_tensors="pt").to(device)
with torch.no_grad():
output = extractor(**inputs)
cond = output.last_hidden_state
# print(f"\t cond shape = {cond.shape}")
cond = cond.unfold(dimension=1, size=16, step=1) # (1, nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (1, nseqs, 16, 53)
nseq = cond.size(1)
# print(f"\t after convert window cond shape = {cond.shape}")
assert nseq == nsteps_frame, f"\t cond = {cond.shape}, nsteps_frame={nsteps_frame}"
idata_speech = cond # 1 x nsteps_frames x 16 x nc_speech
########### infer loss
print(f"\t idata_motion={idata_motion.shape} idata_speech = {idata_speech.shape}")
loss = model.infer_loss(idata_speech, idata_motion) # 1 x nsteps_frames x 3
print(f"\t predict loss shape = {loss.shape}")
########### update
batch_loss.append(loss)
batch_frame.append(nframe_real)
beg_segmt, beg_frame = end_segmt, end_frame
nframe_total_real += nframe_real
#
batch_loss = torch.concat(batch_loss, dim=0) # B x nsteps x 16 x nc_speech
batch_frame = torch.from_numpy(np.array(batch_frame)) # B
assert data_motion.shape[0] == nframe_total_real, \
f"nframe_total_real/{nframe_total_real} of infrence should = data_motion.shape[0]/{data_motion.shape[0]}"
print(f"\t nframe toatl = {nframe_total_real}")
print(f"\t data_speech = {data_speech.shape}, duration = {total_segmt/sr}, nframe_infer={(total_segmt/sr) * fps} \n")
print(f"\t batch_loss = {batch_loss.shape}, batch_frame={batch_frame.shape}")
batch_loss = batch_loss.cpu().numpy().reshape(-1, 3)
batch_loss = batch_loss[:nframe_total_real, :] # B x nframe_real
# save batch loss
np.save(path_loss_save, batch_loss)
print(f"\t save loss > {path_loss_save}")
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
# load wav2Vec model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(device)
# load audio-driven model
model = create_model(opt, logger)
model.setup(opt)
# iterater folders
path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
print(f"Have {len(v_dir_videos)} dir files > {v_dir_videos[:3]}")
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
print(f"\n processing the {i}-th video {vid} ... ")
processing_one_file(ipath_data, processor, extractor, model)
# break
-142
View File
@@ -1,142 +0,0 @@
import sys
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch.nn.functional as F
from scipy.signal import savgol_filter
from scipy.io import wavfile
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
import warnings
warnings.filterwarnings("ignore")
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
device = torch.device(f'cuda:6') # get device name: CPU or GPU
# logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav")
# vid_valid = set(["BU6A9965","BU6A9978"])
# path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9965/audio/audio_trim_60s.wav")
# fID = "BU6A9965"
# ipath_data = Path(f"/mfs/lsen/DATA/Actor3/processing/{fID}/")
fID = "4R3A0139"
actor="Actor6"
sub_folder = "processing2" # smile, processing, processing2
ipath_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}/{fID}/") # processing
ipath_audio = ipath_data.joinpath("audio/audio_trim.wav")
# laod motion
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_motion = np.concatenate([data_exp, data_pos[:, 3:]], axis=1) # (nframe, 53) --> fps=30
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# load raw speech
raw_speech, sample_rate = torchaudio.load(ipath_audio)
print(f"raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech[0])/sample_rate)}")
if len(raw_speech.shape) == 2:
raw_speech = raw_speech[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
sample_rate = 16000
raw_speech = resampler(raw_speech).squeeze().numpy()
print(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {16000}, duration = {(len(raw_speech)/16000)}")
# padding to
# len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
# raw_speech = raw_speech[: len_align]
# print(f"after raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech)/sample_rate)}")
nwinds_beg = 0
nwinds_end = 60
data_motion = torch.from_numpy(data_motion[np.newaxis, 50*nwinds_beg:50*nwinds_end, :]) # (1, 3000, 53)
raw_speech = raw_speech[nwinds_beg *sample_rate : nwinds_end * sample_rate]
# load wav2Vec model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# MODEL_ID_PATH = "./data/wav2vec2-large-xlsr-53-chinese-zh-cn.json"
processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID, cache_dir="/home/liangsen/.cache/huggingface/transformers")
extractor = Wav2Vec2Model.from_pretrained(pretrained_model_name_or_path=MODEL_ID, cache_dir="/home/liangsen/.cache/huggingface/transformers").to(device)
# padding half frame length for bed and end
npad = int(0.5 * 16000* ( 1 / 50) + 0.5)
pad_speech = np.pad(raw_speech, pad_width=((npad, npad)), mode="edge")
print(f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}")
inputs = processor(pad_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
with torch.no_grad():
output = extractor(**inputs)
cond = output.last_hidden_state
print(f"cond shape = {cond.shape}")
# convert to windows
cond = F.pad(cond, pad=(0, 0, 8, 7), mode="replicate")
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
nseq = cond.size(1)
print(f"after convert window cond shape = {cond.shape}")
# self.data = self.data[:, 7:7+nseq, :]
# get model
model = create_model(opt, logger)
model.setup(opt) # load model
# save trim wav
path_audio_pad_trim = Path(opt.OUTPUT_DIR).joinpath(f'{ipath_audio.stem}_input_pad_trim.wav')
wavfile.write(str(path_audio_pad_trim), rate=16000, data=raw_speech)
suffix = f"{ipath_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}"
model.infer_with_gt(cond, data_motion, raw_speech, suffix)
+344
View File
@@ -0,0 +1,344 @@
import os
import argparse
import numpy as np
from pathlib import Path
import json
import time
import cv2
import tempfile
from scipy.io import wavfile
from scipy.signal import savgol_filter
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
def write_video(list_images, raw_speech, path_video, W=1920, H=1080, fps=50):
num_frame = len(list_images)
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=16000, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (W, H), True)
for i in range(num_frame):
writer.write(list_images[i])
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
logger.info(f"save video to -> {path_video}")
# close tmp file
file_audio.close()
file_video.close()
def load_speech_data(path_audio, align=True):
"""
return sr=16000 raw audio data
"""
if not path_audio.exists():
raise(f"NOT existing {path_audio}")
# Load raw audio data
raw_speech, sr = torchaudio.load(path_audio)
logger.info(f"raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech[0])/sr)} s")
if len(raw_speech.shape) == 2:
raw_speech = raw_speech[0]
# resampling to 16KHz
if sr != 16000:
resampler = torchaudio.transforms.Resample(sr, 16_000)
raw_speech = resampler(raw_speech).squeeze().numpy()
sr = 16000
logger.info(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/16000)} s")
else:
raw_speech = raw_speech.numpy()
# if align to 1/50s
if align:
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
raw_speech = raw_speech[: len_align]
logger.info(f"align to 1/50s: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/sr)} s")
return raw_speech, sr
def load_motion_data(path_info, path_feat_exp, path_feat_pos):
if not path_feat_exp.exists() or not path_feat_pos.exists() :
raise(f"NOT existing {path_feat_exp} | {path_feat_pos}")
# load video info
with open(str(path_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
# logger.info(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(path_feat_exp) # (nframe, 50)
data_pos = np.load(path_feat_pos) # (nframe, 6)
# data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
# assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_coeff = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
return data_coeff
def define_extractor(device):
logger.info("load Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
# logger.info(plogger.info.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
logger.info(f"logging path = {opt.OUTPUT_DIR}")
# load wav2Vec model
processor, extractor = define_extractor(device)
# load audio-driven model
model = create_model(opt, logger)
model.setup(opt)
# input audio data
fID = "4R3A0139"
actor="Actor6"
sub_folder = "processing2" # smile, processing, processing2
path_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}/{fID}/") # processing
path_audio = path_data.joinpath("audio/audio_trim.wav")
# path_audio = Path("./data/test/Actor6_4R3A0139_audio_trim.wav")
# path_folder = Path("./data")
# opt.OUTPUT_DIR = path_folder.joinpath(f"tmp_{path_audio.stem}")
# opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
# load audio
raw_speech, sr = load_speech_data(path_audio, align=True)
# setting stream chunk
fps = 50
nduration_predict = 0.5
nduration_history = 3
nduration_future = 0.5
logger.info(f"[stream setting]: fps = {fps}, sr = {sr}")
# setting stream parameters
nsteps_frame = int(nduration_predict * fps + 0.5)
nsteps_segmt = int(nduration_predict * sr + 0.5)
logger.info(f"[stream setting]: \t nduration_predict = {nduration_predict}, nsteps_frame = {nsteps_frame}, nsteps_segmt={nsteps_segmt}")
nsteps_frame_pre = int(nduration_history * fps + 0.5)
nsteps_segmt_pre = int(nduration_history * sr + 0.5)
logger.info(f"[stream setting]: \t nduration_history = {nduration_history}, nsteps_frame_pre = {nsteps_frame_pre}, nsteps_segmt_fut={nsteps_segmt_pre}")
nsteps_frame_fut = int(nduration_future * fps + 0.5)
nsteps_segmt_fut = int(nduration_future * sr + 0.5)
logger.info(f"[stream setting]: \t nduration_future = {nduration_future}, nsteps_frame_fut = {nsteps_frame_fut}, nsteps_segmt_fut={nsteps_segmt_fut}")
nsteps_each_batch = nsteps_frame + nsteps_frame_pre + nsteps_frame_fut
logger.info(f"[stream setting]: \t nsteps_each_batch = {nduration_future}")
# get total frame size
total_segmt = raw_speech.shape[0]
total_frame = int((total_segmt / sr) * fps + 0.5)
# total_frame = int((total_frame // nsteps_frame ) * nsteps_frame + 0.5) # align & trim to predict turnk size
total_frame = int((total_frame // nsteps_frame + 1) * nsteps_frame + 0.5) # align & trim to predict turnk size, add more
logger.info(f"total_frame = {total_frame}, total_segmt = {total_segmt}")
# start stream
beg_segmt, beg_frame = 0, 0
batch_mesh, batch_coef = [],[]
time_beg = time.time()
total_time_wav2vec, total_time_audio2motion = [], []
while beg_frame < total_frame:
end_segmt = beg_segmt + nsteps_segmt # update (beg_segmt, end_segmt)
end_frame = beg_frame + nsteps_frame # update (beg_frame, end_frame)
logger.info(f"\t\t while loop ... (beg,end) frame = ({beg_frame:06d}:{end_frame:06d}), segmt = ({beg_segmt:06d}:{end_segmt:06d})")
# if not(end_segmt <= total_segmt and end_frame <= total_frame):
# logger.info(f"\t\t while loop ... (beg,end) frame = ({beg_frame:06d}:{end_frame:06d}), segmt = ({beg_segmt:06d}:{end_segmt:06d})")
# break
# assert end_segmt <= total_segmt and end_frame <= total_frame
# padding raw speech
npad_wv = int(0.5 * sr * ( 1 / fps) + 0.5) # for wav2vec 2.0: padding half frame length for bed and end
npad_wd_head, npad_wd_tail = 7, 8 # for audio2motion: nwind_size = 16, need_pad 15 frame for each clips
ibeg_segmt = int(beg_segmt - sr * (npad_wd_head / fps) - npad_wv - nsteps_segmt_pre - 0.5)
iend_segmt = int(end_segmt + sr * (npad_wd_tail / fps) + npad_wv + nsteps_segmt_fut + 0.5)
idata_speech = raw_speech[max(ibeg_segmt, 0): min(iend_segmt, total_segmt)] # (nsegmt_steps + npad_wv, )
# if ibeg_segmt & iend_segmt out-of-range
# then need padding
npad_head = - ibeg_segmt if ibeg_segmt < 0 else 0
npda_tail = iend_segmt - total_segmt if iend_segmt > total_segmt else 0
if npad_head + npda_tail > 0:
logger.info(f"\t before padding idata_speech = {idata_speech.shape}, npad_head = {npad_head}, npda_tail={npda_tail} npad_wv={npad_wv}")
idata_speech = np.pad(idata_speech, pad_width=((npad_head, npda_tail)), mode='constant', constant_values=0) # (nsegmt_steps + 2npad_wv, )
logger.info(f"\t after padding idata_speech = {idata_speech.shape}")
# audio feature extraction
logger.info(f"\t [wav2vec] input idata_speech = {idata_speech.shape}")
with torch.no_grad():
inputs = processor(idata_speech, sampling_rate=16000, return_tensors="pt").to(device)
logger.info(f"\t\t [processor] processor input_values = {inputs['input_values'].shape}")
time_wav2vec_beg = time.time()
ifeat_speech = extractor(**inputs).last_hidden_state
total_time_wav2vec.append( time.time() - time_wav2vec_beg)
logger.info(f"\t\t [extractor] last_hidden_state = {ifeat_speech.shape}")
ifeat_speech = ifeat_speech.unfold(dimension=1, size=16, step=1) # (1, nseqs, nc_motion, 16)
ifeat_speech = ifeat_speech.permute(0, 1, 3, 2) # (1, nseqs, 16, 53)
nseq = ifeat_speech.size(1)
logger.info(f"\t\t after convert window ifeat_speech shape = {ifeat_speech.shape}")
assert nseq == nsteps_frame_pre + nsteps_frame + nsteps_frame_fut, f"\t ifeat_speech = {ifeat_speech.shape} != nsteps_frame + nsteps_frame_pre + nsteps_frame_fut ={nsteps_frame + nsteps_frame_pre + nsteps_frame_fut}"
# cut the history & future condition
ifeat_speech = ifeat_speech[:, nsteps_frame_pre:nsteps_frame_pre+nsteps_frame, : ] # (B, nsteps_frame, 16, nc_condit)
# infer mesh
time_audio2motion_beg = time.time()
ibatch_coef = model.forward(ifeat_speech) # 1 x nsteps_frame x 53
total_time_audio2motion.append( time.time() - time_audio2motion_beg)
ibatch_mesh, *_ = model.get_vertices(ibatch_coef) # 1 x nsteps_frame x 5023 x 3
batch_coef.append(ibatch_coef[0]) # nstep_frame x 53
batch_mesh.append(ibatch_mesh[0]) # nstep_frame x 5023 x 3
logger.info(f"\t [audio2motion] ifeat_speech = {ifeat_speech.shape}, ibatch_coef = {ibatch_coef.shape}, ibatch_mesh = {ibatch_mesh.shape}")
##### update
beg_segmt = end_segmt
beg_frame = end_frame
# record time
total_time = time.time() - time_beg
logger.info(f"total_time = {total_time:.2f}, total_frame = {total_frame}, fps = {total_frame / total_time : 0.2f}")
mean_time_wav2vec = np.mean(total_time_wav2vec)
logger.info(f"one forward mean_time_wav2vec = {mean_time_wav2vec:.6f}, one forward fps = {1 / mean_time_wav2vec : 0.2f}, batch forward fps= {nsteps_frame / mean_time_wav2vec : 0.2f}")
mean_time_audio2motion = np.mean(total_time_audio2motion)
logger.info(f"one forward mean_time_audio2motion = {mean_time_audio2motion:.6f}, one forward fps = {1 / mean_time_audio2motion : 0.2f}, batch forward fps= {nsteps_frame / mean_time_audio2motion : 0.2f}")
# render to video
batch_coef = torch.cat(batch_coef, dim=0) # N x 53
batch_mesh = torch.cat(batch_mesh, dim=0) # N x 5023 x 3
logger.info(f"concat batch_coef = {batch_coef.shape}, batch_mesh = {batch_mesh.shape}")
assert batch_mesh.shape[0] == total_frame
# compare with normal pdt result
if True:
# load GT coeff
ipath_feat_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_coeff = np.concatenate([data_exp, data_pos[:, 3:]], axis=1) # (nframe, 53)
data_coeff = savgol_filter(data_coeff, window_length=5, polyorder=3, axis=0, mode='nearest')
data_coeff = data_coeff[:total_frame] # (N, 53)
# path_coeff = Path("experiments/audio2motion/infer_audio2motion_CN_20220525/20220614-17H32M35S/Actor6_4R3A0139_audio_trim_infer_20220602-16H31M37S_epoch_150_coeff.npy")
# data_coeff = np.load(path_coeff)[0, :total_frame]
# logger.info(f"data_coeff = {data_coeff.shape}, load from -> {path_coeff}")
batch_coef = batch_coef.cpu().numpy()
# Diff
diff = np.abs(batch_coef - data_coeff).mean()
logger.info(f"rec_exp = {diff:0.6f}, rato = { ((0.075764 - diff ) / 0.075764) * 100 :0.2f} %")
# velocity loss
diff_pt = batch_coef[1:] - batch_coef[:-1]
diff_gt = data_coeff[1:] - data_coeff[:-1]
diff = np.abs(diff_pt - diff_gt).mean()
logger.info(f"vel_exp = {diff:0.6f}, rato = { ((0.017867 - diff ) / 0.017867) * 100 :0.2f} %")
rendered_mesh = model.render_geometry_batch(batch_mesh, vis_landmarks=False) # N x 512 x 512 x 3
logger.info(f"rendered_mesh len = {len(rendered_mesh)}")
# save video
path_video = opt.OUTPUT_DIR.joinpath(path_audio.stem + "_S2_rendered_mesh_video.mp4")
write_video(rendered_mesh, raw_speech, path_video, W=512, H=512)
logger.info(f"write_video to --> {path_video}")
+164
View File
@@ -0,0 +1,164 @@
import sys
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch.nn.functional as F
from scipy.signal import savgol_filter
from scipy.io import wavfile
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
import warnings
warnings.filterwarnings("ignore")
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
def load_speech_data(path_audio, align=True):
"""
return sr=16000 raw audio data
"""
if not path_audio.exists():
raise(f"NOT existing {path_audio}")
# Load raw audio data
raw_speech, sr = torchaudio.load(path_audio)
logger.info(f"raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech[0])/sr)} s")
if len(raw_speech.shape) == 2:
raw_speech = raw_speech[0]
# resampling to 16KHz
if sr != 16000:
resampler = torchaudio.transforms.Resample(sr, 16_000)
raw_speech = resampler(raw_speech).squeeze().numpy()
sr = 16000
logger.info(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/16000)} s")
else:
raw_speech = raw_speech.numpy()
# if align to 1/50s
if align:
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
raw_speech = raw_speech[: len_align]
logger.info(f"align to 1/50s: raw_speech shape = {raw_speech.shape}, sr = {sr}, duration = {(len(raw_speech)/sr)} s")
return raw_speech, sr
def define_extractor(device):
logger.info("load Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
# logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
logger.info(f"logging path = {opt.OUTPUT_DIR}")
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
# load wav2Vec model
processor, extractor = define_extractor(device)
# load audio-driven model
model = create_model(opt, logger)
model.setup(opt)
# setting data
fID = "4R3A0139"
actor="Actor6"
sub_folder = "processing2" # smile, processing, processing2
ipath_data = Path(f"/mfs/lsen/DATA/{actor}/{sub_folder}/{fID}/") # processing
ipath_audio = ipath_data.joinpath("audio/audio_trim.wav")
# load audio
raw_speech, sr = load_speech_data(ipath_audio, align=True)
# load motion
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_motion = np.concatenate([data_exp, data_pos[:, 3:]], axis=1) # (nframe, 53) --> fps=30
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
data_motion = torch.from_numpy(data_motion[np.newaxis, :, :]) # (1, nframe, 53)
###################### # trim
# nwinds_beg = 0
# nwinds_end = 60
# data_motion = data_motion[:, 50*nwinds_beg:50*nwinds_end, :] # (1, 3000, 53)
# raw_speech = raw_speech[nwinds_beg *sr : nwinds_end * sr]
###################### padding
fps = 50
npad_wv = 0.5 # for wav2vec 2.0: padding half frame length for bed and end
npad_wd_head, npad_wd_tail = 7, 8 # for audio2motion: nwind_size = 16, need_pad 15 frame for each clips
npad_head = int(sr*(npad_wd_head/fps) + sr*(npad_wv/fps) + 0.5)
npad_tail = int(sr*(npad_wd_tail/fps) + sr*(npad_wv/fps) + 0.5)
pad_speech = np.pad(raw_speech, pad_width=((npad_head, npad_tail)), mode="edge")
logger.info(f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}")
with torch.no_grad():
inputs = processor(pad_speech, sampling_rate=sr, return_tensors="pt").to(device)
cond = extractor(**inputs).last_hidden_state
logger.info(f"\t\t [processor] processor input_values = {inputs['input_values'].shape}")
logger.info(f"\t\t [extractor] last_hidden_state = {cond.shape}")
# convert to windows
# cond = F.pad(cond, pad=(0, 0, 8, 7), mode="replicate")
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
nseq = cond.size(1)
logger.info(f"after convert window cond shape = {cond.shape}")
# save trim wav
path_audio_pad_trim = Path(opt.OUTPUT_DIR).joinpath(f'{ipath_audio.stem}_input_pad_trim.wav')
wavfile.write(str(path_audio_pad_trim), rate=sr, data=raw_speech)
suffix = f"{ipath_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}"
model.infer_with_gt(cond, data_motion, raw_speech[np.newaxis, :], suffix)
+27 -28
View File
@@ -192,7 +192,7 @@ class Audio2MeshModel(Base):
return loss_dict return loss_dict
@torch.no_grad()
def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True): def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True):
""" """
batch batch = [B, nsegment] batch batch = [B, nsegment]
@@ -204,42 +204,41 @@ class Audio2MeshModel(Base):
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
data = batch_data.float().to(self.device) # (B, nframe, 53) data = batch_data.float().to(self.device) # (B, nframe, 53)
vert, ldmk2d, ldmk3d = self.get_vertices(data) batch_tgt_geo, *_ = self.get_vertices(data)
vert = vert - self.temp_verts + self.temp_verts_specific # add template batch_tgt_geo = batch_tgt_geo - self.temp_verts + self.temp_verts_specific # add template
# add a dimensions # add a dimensions
# if batch_speech.dims == 1: # if batch_speech.dims == 1:
batch_speech = batch_speech[np.newaxis, :] # (B, nsegmt) batch_speech = batch_speech[np.newaxis, :] # (B, nsegmt)
print(f"batch_speech shape = {batch_speech.shape}") # (1, nsegmt) print(f"batch_speech shape = {batch_speech.shape}") # (1, nsegmt)
with torch.no_grad(): batch_pdt_geo = self.netG(cond) # B x N x dim_motion
batch_pdt_geo = self.netG(cond) # B x N x dim_motion batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3 print(f"testing pt shape = {batch_pdt_geo.shape}") # 1, 3000, 5023, 3
print(f"testing pt shape = {batch_pdt_geo.shape}") # 1, 3000, 5023, 3
# !! add specific when render & output !! # !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save # render & and save
self.save_reconstruct(batch_pdt_geo, batch_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
# render & and save
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {batch_tgt_geo.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, batch_tgt_geo, batch_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
self.save_reconstruct(batch_pdt_geo, batch_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
# render & and save
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, vert, batch_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True): def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
self.eval() self.eval()
+122 -25
View File
@@ -37,12 +37,14 @@ class Audio2MotionModel(Base):
# define FLAME & render # define FLAME & render
self.netF = define_FLAME(opt, self.device) self.netF = define_FLAME(opt, self.device)
self.netR = define_render(opt, self.device) self.netR = define_render(opt, self.device)
self.processor, self.extractor = define_extractor(opt, self.device)
if self.isTrain:
self.processor, self.extractor = define_extractor(opt, self.device)
# path_deca_mean = Path("./data/DECA_obama_mean.npy") # path_deca_mean = Path("./data/DECA_obama_mean.npy")
path_deca_mean = self.opt.DATASET.path_mean_dict path_deca_mean = self.opt.DATASET.path_mean_dict
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}") self.logger.info(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
# get template # get template
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \ self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
@@ -135,6 +137,18 @@ class Audio2MotionModel(Base):
debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False) debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
@torch.no_grad()
def forward(self, batch_cond):
self.eval()
cond = batch_cond.float().to(self.device) # B x N x 16 x nc_speech
batch_pdt = self.netG(cond) # B x N x dim_motion
# self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
return batch_pdt
def training(self, batch_input, idx_epoch=0, idx_batch=0): def training(self, batch_input, idx_epoch=0, idx_batch=0):
self.train() # set train model self.train() # set train model
self.set_input(batch_input) self.set_input(batch_input)
@@ -168,31 +182,71 @@ class Audio2MotionModel(Base):
return loss_dict return loss_dict
@torch.no_grad()
def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True, eval_loss=True):
self.eval()
cond = batch_cond.float().to(self.device) # B x N x 16 x nc_condit
data = batch_data.float().to(self.device) # B x N x nc_motion
batch_pdt = self.netG(cond) # B x N x nc_motion
self.logger.info(f"testing pt shape = {batch_pdt.shape}")
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
batch_tgt_geo, *_ = self.get_vertices(data) # B x N x 5023 x 3
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}, batch_tgt_geo = {batch_tgt_geo.shape}")
if save_npy:
# save result
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
np.save(path_save_npy, batch_pdt.cpu().numpy())
self.logger.info(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}")
if eval_loss:
loss, loss_dict = self.eval_losses(batch_pdt, data)
self.logger.info(loss_dict)
# l1 loss
diff = torch.abs(batch_pdt - data).mean()
self.logger.info(f"l1 coeff rec loss = {diff:0.6f}")
# render & and save
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
# save with GT
self.save_reconstruct_with_gt(batch_pdt_geo, batch_tgt_geo, batch_speech,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
@torch.no_grad()
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True): def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
self.eval() self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad(): batch_pdt = self.netG(cond) # B x N x dim_motion
batch_pdt = self.netG(self.cond) # B x N x dim_motion self.logger.info(f"testing pt shape = {batch_pdt.shape}")
print(f"testing pt shape = {batch_pdt.shape}")
# to geo # to geo
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3 batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
print(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}") self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
# render & and save # render & and save
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR), self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False) suffix=suffix, vis_landmarks=False)
if save_npy: if save_npy:
# save result # save result
# batch_pdt_geo = batch_pdt_geo.cpu().numpy() # batch_pdt_geo = batch_pdt_geo.cpu().numpy()
batch_pdt = batch_pdt.cpu().numpy() batch_pdt = batch_pdt.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy") path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
np.save(path_save_npy, batch_pdt) np.save(path_save_npy, batch_pdt)
print(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}") self.logger.info(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}")
def testing(self, batch_input, idx_epoch=0, idx_batch=0): def testing(self, batch_input, idx_epoch=0, idx_batch=0):
@@ -203,7 +257,7 @@ class Audio2MotionModel(Base):
batch_pdt = self.netG(self.cond) # B x N x dim_motion batch_pdt = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3 batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
print(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}") self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech, self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech,
@@ -229,7 +283,7 @@ class Audio2MotionModel(Base):
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3 ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3 ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
print(f"template verts reshape = {verts.shape}") self.logger.info(f"template verts reshape = {verts.shape}")
return verts, ldmk2d, ldmk3d return verts, ldmk2d, ldmk3d
@@ -346,11 +400,11 @@ class Audio2MotionModel(Base):
# cam # cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3) cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}") # self.logger.info(f"cam shape = {cam.shape}")
# render # render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") # self.logger.info(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks: if vis_landmarks:
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3] kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
@@ -370,6 +424,48 @@ class Audio2MotionModel(Base):
self.logger.info(f"save video to -> {str(ipath_save)}") self.logger.info(f"save video to -> {str(ipath_save)}")
@torch.no_grad()
def render_geometry_batch(self, pred_mesh, vis_landmarks=True):
""" render geometry from audio2mesh prediction
pred_mesh: shape = N x 5023 x 3
return:
batch_faces: shape = N x 512 x 512 x 3
"""
N, *_ = pred_mesh.shape
v_render_pt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
kgeo_pt = pred_mesh[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# self.logger.info(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# self.logger.info(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
else:
render_pt = render_pt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
return v_render_pt
@torch.no_grad() @torch.no_grad()
def render_geometry(self, verts, cam=None, device=None): def render_geometry(self, verts, cam=None, device=None):
""" """
@@ -418,12 +514,12 @@ class Audio2MotionModel(Base):
# cam # cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3) cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}") # self.logger.info(f"cam shape = {cam.shape}")
# render # render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") # self.logger.info(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks: if vis_landmarks:
# landmarks 3d # landmarks 3d
@@ -510,6 +606,7 @@ def define_render(opt, device):
return model return model
def define_extractor(opt, device): def define_extractor(opt, device):
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...") print("load Wav2Vec2Model ...")