131 lines
5.1 KiB
Python
131 lines
5.1 KiB
Python
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
|
|
|
|
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("/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 = "4R3A0004"
|
|
ipath_data = Path(f"/mfs/lsen/DATA/Actor2/happy/{fID}/")
|
|
ipath_audio = ipath_data.joinpath("audio/audio_trim_60s.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 ) * 16000
|
|
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 = 60
|
|
data_motion = torch.from_numpy(data_motion[np.newaxis, :50*nwinds, :]) # (1, 3000, 53)
|
|
raw_speech = raw_speech[:nwinds * 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
|
|
|
|
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)
|