Happy new years

This commit is contained in:
Sen Liang committed 2022-02-07 17:28:40 +08:00
1 parent c7175dd7ff
commit 8c4865effb
53 files changed
+4604 -61

No files matched your search

+168
View File
@@ -0,0 +1,168 @@
import sys
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch.nn.functional as F
import torch
import torchaudio
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
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("/ssdata1/lsen/CODE/Audio2Motion/data/test/test_pangzi_zh_cut15.wav")
# 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 raw speech
audio_raw, sample_rate = torchaudio.load(path_audio)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# clip 15s
# if len(audio_raw) > 16000 * 5:
# audio_raw = audio_raw[:16000*5]
# audio_raw_numpy = audio_raw.numpy()
# 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)
# padding half frame length for bed and end
npad = int(0.5 * 16000* ( 1 / 50) + 0.5)
audio_raw = np.pad(audio_raw, pad_width=((npad, npad)), mode="edge")
print(f"after padding audio_raw = {audio_raw.shape}, dtype={audio_raw.dtype}")
inputs = processor(audio_raw, 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()
model.infer(cond, 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