add infer loss for LuoXData with long data by clip & alignment data

This commit is contained in:
Sen Liang committed 2022-03-03 11:25:48 +08:00
1 parent 386df9a4ab
commit ded9b27f71
42 files changed
+1233 -1361

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
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