initial commit

This commit is contained in:
Sen Liang committed 2022-01-21 17:42:41 +08:00
commit c7175dd7ff
127 files changed
+13949

No files matched your search

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