add infer support for audio2motion

This commit is contained in:
sen.liang committed 2022-06-09 11:00:50 +08:00
1 parent 0b46d9f3eb
commit 23fdd42edd
23 files changed
+824 -74

No files matched your search

+1 -1
View File
@@ -9,11 +9,11 @@ import numpy as np
import onnx import onnx
import onnxruntime as rt import onnxruntime as rt
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
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 src.models import create_model
from common.logger import Logger from common.logger import Logger
+102
View File
@@ -0,0 +1,102 @@
# Copyright (c) OpenMMLab. All rights reserved.
import os
import sys
import argparse
from pathlib import Path
import torch
import numpy as np
import onnx
import onnxruntime as rt
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.config import config as opt
from src.config import update_config
from src.models import create_model
from common.logger import Logger
def parse_args():
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
parser.add_argument("--opt", type=str, default="experiments/infer_audio2mesh_CN_20220312.yaml", help="experiment configure file name")
args, _ = parser.parse_known_args()
update_config(args.opt)
# parser.add_argument('checkpoint', help='checkpoint file')
# parser.add_argument('--show', action='store_true', help='show onnx graph')
# parser.add_argument('--output-file', type=str, default='tmp.onnx')
# parser.add_argument('--opset-version', type=int, default=11)
# parser.add_argument('--verify', action='store_true', help='verify the onnx model output against pytorch output')
# parser.add_argument('--is-localizer', action='store_true', help='whether it is a localizer')
# parser.add_argument('--shape', type=int, nargs='+', default=[1, 3, 8, 224, 224], help='input video size')
# parser.add_argument('--softmax', action='store_true', help='wheter to add softmax layer at the end of recognizers')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_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)
# build the model
model = create_model(opt, logger)
model.setup(opt) # load checkpoints
# export model
netG = model.netG
netG.eval() # set inference model
path_ckpt = Path(opt.MODEL.path_checkpoint)
path_onnx = Path(f"checkpoints/audio2motion-{path_ckpt.stem}-{opt.MODEL.load_epoch}.onnx")
if not path_onnx.exists():
# forward
batch_input = torch.randn((1, 35, 16, 1024)).float().to(model.device) # (B, nseq, nseqlen, nc_condit)
batch_otput = model.netG.forward(batch_input).detach().cpu().numpy() # (B, nseq, 5023, 3)
print(f"cond shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
# cond shape = torch.Size([20, 35, 16, 1024]), batch_otput shape = (20, 35, 5023, 3)
torch.onnx.export(
netG, # model being run, netG.module,
batch_input,
str(path_onnx),
export_params=True,
verbose=True,
opset_version=11,
input_names=["input"],
output_names=["output"],
dynamic_axes = {
"input": {0: "batch_size", 1: "nseqlen"},
"output": {0: "batch_size"}
}
)
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
############################################ valify
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
batch_input = torch.randn((1, 35, 16, 1024)).float().to(model.device) # (B, nseq, nseqlen, nc_condit)
batch_otput = model.netG.forward(batch_input).detach().cpu().numpy() # (B, nseq, 53)
print(f"cond shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(["output"], {"input": batch_input.cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(batch_otput, batch_onnx, atol=1e-4), 'The outputs are different between Pytorch and ONNX'
print(f"output[0,0,100:120,0] = \n{batch_otput[0,0,::5]} \
batch_onnx[0][0,0,100:120,0]=\n{batch_onnx[0,0,::5]}")
print('The numerical values are same between Pytorch and ONNX')
@@ -21,9 +21,9 @@ MODEL:
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220522-10H56M38SNone" # path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220522-10H56M38SNone"
# load_epoch: 55 # load_epoch: 55
# 1.5h # 2 h
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220525-07H18M45S" path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220527/20220528-08H46M43S"
load_epoch: 15 load_epoch: 170
DATASET: DATASET:
fps: 50 fps: 50
@@ -0,0 +1,51 @@
GPUS: '6'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
isTrain: False
MODEL:
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# 1h,
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220522-10H56M38SNone"
# load_epoch: 55
# 2 h
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220527/20220528-08H46M43S"
load_epoch: 170
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
root: './data/Actor7/Actor7-raw-processing-2h'
path_mean_dict: './data/Actor7/mean_deca_coeff_Actor7_processing.npy'
filter: 'savgol'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
@@ -19,9 +19,9 @@ MODEL:
dim_speech: 1024 dim_speech: 1024
num_vertices: 5023 num_vertices: 5023
pretrain: False pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220525-07H18M45S" path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220527/20220527-16H36M24S"
load_epoch: 45 load_epoch: 80
DATASET: DATASET:
@@ -48,7 +48,7 @@ TEST:
TRAIN: TRAIN:
lr: 0.0001 lr: 0.00005 #0.0001
batch_size: 128 batch_size: 128
shuffle: True shuffle: True
@@ -57,18 +57,18 @@ TRAIN:
apply_lr_scheduler: True apply_lr_scheduler: True
apply_update_parameters: True apply_update_parameters: True
optimizer: 'Adam' optimizer: 'SGD'
momentum: 0.9 momentum: 0.9
beta1: 0.5 beta1: 0.5
beta2: 0.999 beta2: 0.999
weight_decay: 0.0001 weight_decay: 0.0001
nesterov: True nesterov: True
lr_policy: 'plateau'
# lr_policy: 'plateau'
# lr_step_gamma: 0.5 lr_step_gamma: 0.5
# lr_policy: 'multistep' lr_policy: 'multistep'
# lr_milestones: [10, 30, 50] lr_milestones: [10, 50]
resume: False resume: False
reset_lr: True reset_lr: True
@@ -0,0 +1,56 @@
GPUS: '1'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
isTrain: False
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# 1h,
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220522-10H56M38SNone"
# load_epoch: 55
# 2 h
# [2022-06-01 06:28:38,734][INFO] [Epoch:134-mean] rec_exp= 1.38721 rec_pos= 0.21776 rec_geo= 0.00342 vel_exp= 0.30778 vel_pos= 0.05136 vel_geo= 0.00073 all= 6.30447
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_20220520/20220602-16H36M42S"
load_epoch: 290
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
# root: './data/Actor5/Actor5-raw-processing-1h'
# root: './data/Actor2/Actor2-raw-7h'
# root: "./data/Actor7/Actor7-raw-processing-2h"
root: "./data/Actor6/Actor6-raw-processing2-2h"
path_mean_dict: './data/Actor5/mean_deca_coeff_Actor5_processing.npy'
filter: 'savgol'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
@@ -0,0 +1,47 @@
GPUS: '1'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
isTrain: False
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# 1h,
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_20220525/20220602-16H31M37S"
load_epoch: 150
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
root: './data/Actor6/Actor6-raw-processing2-2h'
# root: './data/Actor2/Actor2-raw-7h'
# root: "./data/Actor7/Actor7-raw-processing-2h"
path_mean_dict: './data/Actor6/mean_deca_coeff_Actor6_processing2.npy'
filter: 'savgol'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
@@ -0,0 +1,50 @@
GPUS: '0'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
isTrain: False
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# 1h,
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_20220527/20220528-09H40M00S"
load_epoch: 160
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
# root: './data/Actor2/Actor2-raw-7h'
# root: './data/Actor7/Actor7-raw-processing-2h'
# root: "./data/Actor7/Actor7-raw-processing-2h"
root: "./data/Actor6/Actor6-raw-processing2-2h"
path_mean_dict: './data/Actor7/mean_deca_coeff_Actor7_processing.npy'
filter: 'savgol'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
@@ -0,0 +1,50 @@
GPUS: '0'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
isTrain: False
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# 1h,
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_actor2_20220420/20220607-17H27M53S"
load_epoch: 50
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
# root: './data/Actor2/Actor2-raw-7h'
# root: './data/Actor5/Actor5-raw-processing-1h'
# root: "./data/Actor6/Actor6-raw-processing2-2h"
root: "./data/Actor7/Actor7-raw-processing-2h"
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
@@ -0,0 +1,87 @@
GPUS: '1'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_20220527/20220528-09H40M00S"
load_epoch: 160
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor5/Actor5-raw-processing-1h'
path_mean_dict: './data/Actor5/mean_deca_coeff_Actor5_processing.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.00005 #0.0001
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
apply_lr_scheduler: True
apply_update_parameters: True
optimizer: 'SGD'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
# nesterov: True
# lr_policy: 'plateau'
lr_step_gamma: 0.5
lr_policy: 'multistep'
lr_milestones: [10, 50, 100]
resume: False
reset_lr: True
resume_suffix: "20220524-21H54M38S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
lambda_rec_exp: 0.5
lambda_rec_pos: 1
lambda_rec_geo: 100
lambda_vel_exp: 10
lambda_vel_pos: 10
lambda_vel_geo: 100
@@ -0,0 +1,89 @@
GPUS: '0'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# 1h,
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_actor2_20220420/20220607-17H27M53S"
load_epoch: 50
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor6/Actor6-raw-processing2-2h'
path_mean_dict: './data/Actor6/mean_deca_coeff_Actor6_processing2.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.00005 #0.0001
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
apply_lr_scheduler: True
apply_update_parameters: True
optimizer: 'SGD'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
nesterov: True
# lr_policy: 'plateau'
lr_step_gamma: 0.5
lr_policy: 'multistep'
lr_milestones: [10, 50, 100]
resume: False
reset_lr: True
resume_suffix: "20220524-21H54M38S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
lambda_rec_exp: 0.5
lambda_rec_pos: 1
lambda_rec_geo: 100
lambda_vel_exp: 10
lambda_vel_pos: 10
lambda_vel_geo: 100
@@ -19,10 +19,9 @@ MODEL:
dim_speech: 1024 dim_speech: 1024
num_vertices: 5023 num_vertices: 5023
pretrain: False pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220525-07H18M45S" path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_20220527/20220527-19H07M53S"
load_epoch: 45 load_epoch: 20
DATASET: DATASET:
fps: 50 fps: 50
@@ -48,7 +47,7 @@ TEST:
TRAIN: TRAIN:
lr: 0.0001 lr: 0.00005 #0.0001
batch_size: 128 batch_size: 128
shuffle: True shuffle: True
@@ -57,18 +56,18 @@ TRAIN:
apply_lr_scheduler: True apply_lr_scheduler: True
apply_update_parameters: True apply_update_parameters: True
optimizer: 'Adam' optimizer: 'SGD'
momentum: 0.9 momentum: 0.9
beta1: 0.5 beta1: 0.5
beta2: 0.999 beta2: 0.999
weight_decay: 0.0001 weight_decay: 0.0001
nesterov: True # nesterov: True
lr_policy: 'plateau' # lr_policy: 'plateau'
# lr_step_gamma: 0.5 lr_step_gamma: 0.5
# lr_policy: 'multistep' lr_policy: 'multistep'
# lr_milestones: [10, 30, 50] lr_milestones: [10, 50, 100]
resume: False resume: False
reset_lr: True reset_lr: True
@@ -79,10 +78,10 @@ TRAIN:
LOSS: LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"] names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
lambda_rec_exp: 1 lambda_rec_exp: 0.5
lambda_rec_pos: 1 lambda_rec_pos: 1
lambda_rec_geo: 1 lambda_rec_geo: 100
lambda_vel_exp: 10 lambda_vel_exp: 10
lambda_vel_pos: 10 lambda_vel_pos: 10
lambda_vel_geo: 10 lambda_vel_geo: 100
@@ -0,0 +1,87 @@
GPUS: '1'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_actor1_20220420/20220608-18H10M34S"
load_epoch: 60
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor1/Actor1-raw-16h'
path_mean_dict: './data/Actor1/DECA_Actor1_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.00005 #0.0001
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
apply_lr_scheduler: True
apply_update_parameters: True
optimizer: 'SGD'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
nesterov: True
# lr_policy: 'plateau'
lr_step_gamma: 0.5
lr_policy: 'multistep'
lr_milestones: [10, 50, 100]
resume: False
reset_lr: True
resume_suffix: "20220524-21H54M38S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
lambda_rec_exp: 0.5
lambda_rec_pos: 1
lambda_rec_geo: 100
lambda_vel_exp: 10
lambda_vel_pos: 10
lambda_vel_geo: 100
@@ -0,0 +1,87 @@
GPUS: '0'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2motion'
DEBUG: False
verbose: False
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2motion'
name_netG: "audio2motion_voca33"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2motion/train_audio2motion_CN_20220527/20220528-09H40M00S"
load_epoch: 160
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-7h'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001 #0.0001
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
apply_lr_scheduler: True
apply_update_parameters: True
optimizer: 'Adam'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
nesterov: True
lr_policy: 'plateau'
# lr_step_gamma: 0.5
# lr_policy: 'multistep'
# lr_milestones: [10, 50, 100]
resume: False
reset_lr: True
resume_suffix: "20220524-21H54M38S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"]
lambda_rec_exp: 0.5
lambda_rec_pos: 1
lambda_rec_geo: 100
lambda_vel_exp: 10
lambda_vel_pos: 10
lambda_vel_geo: 100
+9 -24
View File
@@ -40,7 +40,8 @@ def infer_one(path_audio, model, processor, extractor, save_npy):
# load raw speech # load raw speech
raw_speech, sample_rate = torchaudio.load(path_audio) raw_speech, sample_rate = torchaudio.load(path_audio)
raw_speech = raw_speech.numpy() # raw_speech = raw_speech.numpy()
print(f"raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech[0])/sample_rate)}") print(f"raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech[0])/sample_rate)}")
if len(raw_speech.shape) == 2: if len(raw_speech.shape) == 2:
@@ -49,8 +50,10 @@ def infer_one(path_audio, model, processor, extractor, save_npy):
if sample_rate != 16000: if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000) resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
raw_speech = resampler(raw_speech).squeeze().numpy() raw_speech = resampler(raw_speech).squeeze().numpy()
sample_rate = 16000 sample_rate = 16000
print(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {16000}, duration = {(len(raw_speech)/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 # padding to
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50) len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
@@ -84,7 +87,8 @@ def infer_one(path_audio, model, processor, extractor, save_npy):
# inference # inference
path_save = f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}" path_save = f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}"
model.infer(cond, raw_speech, path_save) # model.infer(cond, raw_speech, path_save)
model.infer(cond, raw_speech[np.newaxis, :], path_save)
if __name__ == "__main__": if __name__ == "__main__":
@@ -112,8 +116,8 @@ if __name__ == "__main__":
# path_folder = Path("/mfs/dylan/tts/wav") # path_folder = Path("/mfs/dylan/tts/wav")
# path_folder = Path("/mfs/dylan/tts/wav_sen") # path_folder = Path("/mfs/dylan/tts/wav_sen")
path_folder = Path("./data/test/tts-scenes") path_folder = Path("./data/sentencee5_ac5")
opt.OUTPUT_DIR = path_folder.joinpath("inference_video_actor5_with_npy") opt.OUTPUT_DIR = path_folder.joinpath("audio2motion_actor6_result")
opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True) opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
save_npy = True save_npy = True
@@ -131,23 +135,4 @@ if __name__ == "__main__":
# except: # except:
# print("\n continue ! > ipath_audio",ipath_audio) # print("\n continue ! > ipath_audio",ipath_audio)
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
# path_audio = Path("./data/test/cut_NVP.wav")
# path_audio = Path("./data/test/cut_LSP.wav")
# path_audio = Path("/yrfs/cf/data/render/obama_train.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P22/audio/audio_trim.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/test_pangzi_zh_cut15.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/P74_lite.mp3")
# 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
+6 -6
View File
@@ -50,13 +50,16 @@ if __name__ == "__main__":
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav") # 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") # 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"]) # 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/BU6A9965/audio/audio_trim_60s.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9978/audio/audio_trim_60s.wav") # path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9978/audio/audio_trim_60s.wav")
path_audio = Path("data/audio_007_008.wav") # path_audio = Path("data/test/actor6/actor6_sentence4_1.wav")
# path_audio = Path("data/bank-demo.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("/mfs/lsen/DATA/Actor4/processing/4R3A0024/audio/audio_trim_60_60s.wav")
# path_audio = Path("data/test/ali_test_222.wav") # path_audio = Path("data/test/ali_test_222.wav")
@@ -72,7 +75,6 @@ if __name__ == "__main__":
# opt.OUTPUT_DIR = path_folder.joinpath("inference_video_actor5_with_npy") # opt.OUTPUT_DIR = path_folder.joinpath("inference_video_actor5_with_npy")
# opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True) # opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
# load raw speech # load raw speech
raw_speech, sample_rate = torchaudio.load(path_audio) raw_speech, sample_rate = torchaudio.load(path_audio)
# raw_speech = raw_speech.numpy() # raw_speech = raw_speech.numpy()
@@ -85,7 +87,7 @@ if __name__ == "__main__":
if sample_rate != 16000: if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000) resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
raw_speech = resampler(raw_speech).squeeze().numpy() raw_speech = resampler(raw_speech).squeeze().numpy()
sample_rate= 16000 sample_rate = 16000
print(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {16000}, duration = {(len(raw_speech)/16000)}") print(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {16000}, duration = {(len(raw_speech)/16000)}")
else: else:
raw_speech = raw_speech.numpy() raw_speech = raw_speech.numpy()
@@ -132,12 +134,10 @@ if __name__ == "__main__":
# cmd = f"cp {str(path_audio)} {str(Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.name}'))}" # cmd = f"cp {str(path_audio)} {str(Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.name}'))}"
# os.system(cmd) # os.system(cmd)
# save trim wav # save trim wav
path_audio_pad_trim = Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.stem}_input_pad_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) wavfile.write(str(path_audio_pad_trim), rate=16000, data=raw_speech)
# inference # inference
path_save = f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}" 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) model.infer(cond, raw_speech[np.newaxis, :], path_save)
+1
View File
@@ -119,6 +119,7 @@ if __name__ == "__main__":
cond = output.last_hidden_state cond = output.last_hidden_state
print(f"cond shape = {cond.shape}") print(f"cond shape = {cond.shape}")
# convert to windows # convert to windows
cond = F.pad(cond, pad=(0, 0, 8, 7), mode="replicate") 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.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

+1 -1
View File
@@ -534,7 +534,7 @@ def tensor2image(tensor):
image = image*255. image = image*255.
image = np.maximum(np.minimum(image, 255), 0) image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]] image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy() return image.astype(np.uint8).copy()
+18 -12
View File
@@ -157,8 +157,6 @@ class Audio2MotionModel(Base):
return loss_dict return loss_dict
def validation(self, batch_input): def validation(self, batch_input):
self.eval() # set eval model self.eval() # set eval model
self.set_input(batch_input) self.set_input(batch_input)
@@ -171,23 +169,31 @@ class Audio2MotionModel(Base):
return loss_dict return loss_dict
def infer(self, batch_cond, path_audio, suffix=""): 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) self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad(): with torch.no_grad():
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion batch_pdt = self.netG(self.cond) # B x N x dim_motion
print(f"testing pt shape = {samples_pt.shape}") print(f"testing pt shape = {batch_pdt.shape}")
self.save_reconstruct(samples_pt, path_audio, # to geo
path_save=Path(self.opt.OUTPUT_DIR), batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
suffix=suffix) print(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
# save result
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, samples_pt)
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
# render & and save
self.save_reconstruct(batch_pdt_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()
batch_pdt = batch_pdt.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
np.save(path_save_npy, batch_pdt)
print(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):
self.eval() # set eval model self.eval() # set eval model
+1 -1
View File
@@ -57,7 +57,7 @@ class Audio2Motion(nn.Module):
nn.Linear(in_features=128, out_features=self.dim_motion), nn.Linear(in_features=128, out_features=self.dim_motion),
) )
def forward(self, x): def forward(self, x):
""" forward function """ forward function
Args: Args:
+52
View File
@@ -0,0 +1,52 @@
self.sess_netA = self._load_Audio2MotionModel(opt.ckpt_audio2motion)
# def _load_Audio2MeshModel(self, path_onnx):
# self.logger.info("_load_Audio2MeshModel ...")
# sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
# return sess
def _load_Audio2MotionModel(self, path_onnx):
self.logger.info("_load_Audio2MotionModel ...")
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
return sess
@torch.no_grad()
def render_raw_geometry(self, pred_mesh):
""" render geometry from audio2mesh prediction
pred_mesh: shape = B x N x 5023 x 3
return:
batch_faces: shape = B x N x 512 x 512 x 3
"""
pred_mesh = pred_mesh[0]
N, *_ = pred_mesh.shape
nbatch_render = 10
# each time render nbatch_render=10 images (prevent N is bigger, out of memory)
rendered_mesh = []
for k in range(0, N, nbatch_render):
# split
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)
# proj by camera
verts_proj = batch_orth_proj(kgeo_pt, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(kgeo_pt, verts_proj).cpu() # (nbatch_real, 3, 512, 512)
# append each frame
for j in range(nbatch_real):
rendered_mesh.append(self.tensor2image_netR(images[j, ...]))
return rendered_mesh
+1
View File
@@ -128,6 +128,7 @@ if __name__ == "__main__":
logger_loss(logger, epoch, "mean", train_loss_dict) logger_loss(logger, epoch, "mean", train_loss_dict)
################ validation ################ validation
if opt.TRAIN.apply_validation and (epoch+1) % opt.FREQ.epoch_valid == 0: if opt.TRAIN.apply_validation and (epoch+1) % opt.FREQ.epoch_valid == 0:
logger.info("validation...") logger.info("validation...")