Merge branch 'master' of ssh://dev.rcrai.com:30022/liangsen/audio-to-motion

This commit is contained in:
sen.liang committed 2022-04-24 14:10:15 +08:00
commit 4d4015350c
51 files changed
+4259 -1346

No files matched your search

+85 -2
View File
@@ -1,10 +1,14 @@
import moviepy.editor as mpy
import numpy as np
import os
import cv2
import sys
# sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.landmark import landmark_to_images
import tempfile
from scipy.io import wavfile
def save_animation(data_motion, path_save, suffix, w=128*5, h=72*5, dpi=80):
""" convert data_motion to .mp4 animation
@@ -139,6 +143,86 @@ def save_animation_with_gts(images_list, path_save):
# close
animation.close()
# def write_videos(images, raw_speech, path_save, fps=50):
def write_video(list_images, raw_speech, path_video, fps=50, sr=16000):
""" convert images_pt to .mp4 animation
list_images, shape len=N list [512, 512, 3], or [1080, 1920, 3]
raw_speech, shape = (nsegmet, )
"""
num_frame = len(list_images)
H, W = list_images[0].shape[:2]
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=sr, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (W, H), True)
for i in range(num_frame):
writer.write(list_images[i])
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
# close tmp file
file_audio.close()
file_video.close()
def write_video_with_gt(images_pt, images_gt, raw_speech, path_video, fps=50, sr=16000):
""" convert images_pt to .mp4 animation
images_pt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3]
images_gt, shape len= N list [H, W, 3], like [224, 224, 3], [512, 512, 3], or [1080, 1920, 3]
raw_speech, shape = (nsegmet, )
"""
num_frame = len(images_pt)
H, W = images_pt[0].shape[:2]
file_audio = tempfile.NamedTemporaryFile(suffix='.wav')
file_video = tempfile.NamedTemporaryFile(suffix='.mp4')
# write audio
wavfile.write(file_audio.name, rate=sr, data=raw_speech)
# write video
if int(cv2.__version__[0]) < 3:
writer = cv2.VideoWriter(file_video.name, cv2.cv.CV_FOURCC(*'mp4v'), fps, (2*W, H), True)
else:
writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (2*W, H), True)
for i in range(num_frame):
concate_image = np.concatenate((images_pt[i], images_gt), axis=1) # (H, 2*W, 3)
writer.write(concate_image)
# close
writer.release()
cv2.destroyAllWindows
# concate to video
cmd = f"ffmpeg -y -i {file_video.name} -i {file_audio.name} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest -loglevel quiet {str(path_video)}"
os.system(cmd)
# close tmp file
file_audio.close()
file_video.close()
def save_images_with_audio(images, path_audio, path_save, fps=50):
""" convert images_pt to .mp4 animation
images_pt, shape len=N list [224, 224, 3]
@@ -187,7 +271,7 @@ def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audi
"""
# print(f"images_pt shape = {len(images_pt)}, shape[0]={images_pt[0].shape}")
fps = fps if fps else 30
fps = fps if fps else 50
N = len(images_pt)
duration = N / fps
@@ -216,7 +300,6 @@ def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audi
animation = animation.set_audio(audioclip)
animation = animation.set_duration(duration)
animation.write_videofile(str(path_save), fps=fps)
# close
+104
View File
@@ -0,0 +1,104 @@
# 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__), '../audio2motion')))
from src.config import config as opt
from src.config import update_config
from src.datasets import create_dataset
from src.models import create_model, calculate_model_params
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/audio2mesh-{path_ckpt.stem}-{opt.MODEL.load_epoch}.onnx")
if not path_onnx.exists():
# forward
batch_input = torch.randn((20, 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.module, # model being run
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((20, 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}")
# 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,100:120,0]} \
batch_onnx[0][0,0,100:120,0]=\n{batch_onnx[0,0,100:120,0]}")
print('The numerical values are same between Pytorch and ONNX')
+85
View File
@@ -0,0 +1,85 @@
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from lsp.options.test_feature2face_options import TestOptions as RenderOptions
from lsp.models import create_model
from lsp.models import feature2face_model
from lsp.models.feature2face_G import Feature2Face_G
if __name__ == '__main__':
# create m2f model
gen_opt = RenderOptions().parse()
gen_opt.name = "ljj" #args.name
gen_opt.batch_size = 64 #args.batch_size_m2f
path_ckpt_m2f = f'./data/render/models/{gen_opt.name}/render_g.pkl'
device = torch.device("cuda:0")
# model_m2f = create_model(gen_opt)
# model_m2f.Feature2Face_G.eval()
# model_m2f.Feature2Face_G.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG = Feature2Face_G(gen_opt).to(device)
netG = torch.nn.DataParallel(netG, [device,])
netG.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG.eval()
path_onnx = Path(f"checkpoints/render/{gen_opt.name}/render_g.onnx")
path_onnx.parent.mkdir(parents=True, exist_ok=True)
if not path_onnx.exists():
# forward test
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input) # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
torch.onnx.export(
netG.module, # model being run
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"},
"output": {0: "batch_size"}
}
)
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
############################################ valify onnx
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input).detach().cpu().numpy() # (B, 3, 512, 512)
print(f"batch_input 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, :, 100] = \n{batch_otput[0, 0, 100:120, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0, 0, 100:120, 100]}")
print('The numerical values are same between Pytorch and ONNX')
+108
View File
@@ -0,0 +1,108 @@
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
from torchaudio.models.wav2vec2.utils import import_huggingface_model
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../audio2motion')))
from src.config import config as opt
from src.config import update_config
from src.datasets import create_dataset
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
# https://github.com/ccoreilly/wav2vec2-service/blob/master/convert_torch_to_onnx.py
# https://huggingface.co/docs/transformers/serialization
# https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2Model
if __name__ == "__main__":
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
# build the model
device = "cuda:9"
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
# import
model_extractor = import_huggingface_model(extractor)
model_extractor.eval() # set the model to inference mode
model_extractor.to(device)
# print(f"model_extractor device = {model_extractor.device}")
# forward
raw_speech = np.random.randn(1, 16000*10) # (B, nsegments)
print(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
# padding half frame length for bed and end
npad = int(0.5 * 16000 * ( 1 / 50) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
print(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
speech = list(raw_speech)
inputs = processor(speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
print(f"inputs keys = {inputs.keys()}")
with torch.no_grad():
# output = extractor(**inputs)
output = extractor(**inputs).last_hidden_state
output = output.cpu().numpy()
print(f"self.output shape = {output.shape}")
print(f"input_values shape = {inputs['input_values'].shape}, attention_mask shape = {inputs['attention_mask'].shape}")
# x_input = (inputs["input_values"], inputs["attention_mask"])
raw_speech = torch.from_numpy(raw_speech).float().to(device)
path_onnx = Path(f"checkpoints/wav2vec2/{MODEL_ID.split('/')[-1]}.onnx")
if not path_onnx.exists():
torch.onnx.export(
model_extractor, # model being run
raw_speech, # model input (or a tuple for multiple inputs)
str(path_onnx), # where to save the model (can be a file or file-like object)
export_params=True, # store the trained parameter weights inside the model file
opset_version=11, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names = ['input'], # the model's input names
output_names = ['output'], # the model's output names
dynamic_axes={'input' : {0: "batch_size", 1 : 'audio_len'}, # variable length axes
'output' : {0: "batch_size", 1 : 'nseqlen'}
})
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
############################################ valify onnx
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
raw_speech = inputs['input_values']
print(f"raw_speech = {raw_speech.shape}, inputs['input_values'] = {inputs['input_values'].shape}")
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(['output'], {"input": raw_speech.detach().cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(output, batch_onnx, atol=1e-3), 'The outputs are different between Pytorch and ONNX'
print(f"output[0, :20, 100] = \n{output[0, :20, 100]} \batch_onnx[0, :20, 100]=\n{batch_onnx[0,:20,100]}")
print('The numerical values are same between Pytorch and ONNX')
@@ -1,4 +1,4 @@
GPUS: '5'
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -14,8 +14,7 @@ FREQ:
MODEL:
# name: 'audio2mesh'
name: 'audio2mesh2'
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
@@ -27,33 +26,37 @@ MODEL:
# load_epoch: 35
# 2h, 1:10, epoch 105
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220313-13H26M47S"
load_epoch: 100
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220313-13H26M47S"
# load_epoch: 100
# 1h, 1:10, epoch 105
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220315-16H46M54S"
# load_epoch: 75
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H11M43S"
# load_epoch: 65
# 5h, 1:10, epoch 25
# 5h, 1:10, epoch 50
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H10M14S"
# load_epoch: 25
# load_epoch: 50
# 1h happy epoch
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220414-21H46M33S"
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220415-14H10M19S"
load_epoch: 25
DATASET:
fps: 50
sr: 16000
# name: "motion_live"
name: "motion_eval"
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
# root: './data/Actor2/Actor2-raw-7h' # obama-deca-3-5-08-mini
root: './data/Actor2/Actor2-raw-2h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
root: './data/Actor2/Actor2-happy-1h' # obama-deca-3-5-08-mini
root_raw: '/mfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
@@ -67,6 +70,9 @@ TRAIN:
apply_testing: True
apply_validation: True
TEST:
batch_size: 20
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
@@ -2,7 +2,7 @@ GPUS: '8'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
DEBUG: True
verbose: False
isTrain: False
@@ -0,0 +1,53 @@
GPUS: '9'
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
# # 2h, rec-vel, load_epoch 145
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220322/20220405-19H39M26S"
# load_epoch: 145
# 1h, rec-vel, load_epoch 155
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220322/20220405-18H57M05S"
load_epoch: 155
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor3/Actor3-raw-2h' # obama-deca-3-5-08-mini
root_raw: '/mfs/lsen/DATA/Actor3/processing'
path_mean_dict: './data/Actor3/DECA_Actor3_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
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"]
@@ -1,4 +1,4 @@
GPUS: '8'
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -10,26 +10,26 @@ VISUAL:
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-actor2-5h-1100"
vsdm_env: "actor2-1h-happy-pretrain"
FREQ:
batch_print: 20
epoch_save: 5
epoch_valid: 1
epoch_test: 10
epoch_test: 5
MODEL:
name: 'audio2mesh2'
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220314-15H41M13S"
load_epoch: 0
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H10M14S"
load_epoch: 50
DATASET:
@@ -40,8 +40,8 @@ DATASET:
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
root: './data/Actor2/Actor2-happy-1h' # obama-deca-3-5-08-mini
root_raw: '/mfs/lsen/DATA/Actor2/happy'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
@@ -54,7 +54,7 @@ TEST:
batch_size: 2
TRAIN:
lr: 0.0001
lr: 0.00005
batch_size: 64
shuffle: True
@@ -68,21 +68,21 @@ TRAIN:
weight_decay: 0.0001
nesterov: True
grad_clip_norm: False
lr_policy: 'multistep'
lr_milestones: [20, 50]
# lr_policy: 'plateau'
# lr_policy: 'multistep'
# lr_milestones: [20, 50]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 100
epoch_end: 300
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_ldmk: 1
lambda_closure_x: 1
lambda_closure_y: 1
lambda_rec_ldmk: 0
lambda_closure_x: 0
lambda_closure_y: 0
@@ -1,4 +1,4 @@
GPUS: '9'
GPUS: '8'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -11,16 +11,16 @@ VISUAL:
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-actor1-5h-110"
vsdm_env: "audio2mesh-actor1-16h-closure"
FREQ:
epoch_save: 5
epoch_valid: 1
epoch_valid: 2
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh'
name: 'audio2mesh2'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
@@ -31,16 +31,16 @@ MODEL:
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-18H24M47S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor1/Actor1-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor1/processing'
root: './data/Actor1/Actor1-raw-16h' # obama-deca-3-5-08-mini
root_raw: '/mfs/lsen/DATA/Actor1/processing'
path_mean_dict: './data/Actor1/DECA_Actor1_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
@@ -68,18 +68,20 @@ TRAIN:
weight_decay: 0.0001
nesterov: True
grad_clip_norm: False
lr_policy: 'multistep'
lr_milestones: [10, 50]
# lr_policy: 'plateau'
# lr_policy: 'multistep'
# lr_milestones: [10, 50]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 100
epoch_end: 300
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_ldmk: 0
lambda_closure_x: 0
lambda_closure_y: 10
@@ -1,4 +1,4 @@
GPUS: '3'
GPUS: '4'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -6,7 +6,7 @@ DEBUG: False
verbose: False
VISUAL:
vsdm_env: "audio2mesh-actor3-2h-ldmk"
vsdm_env: "audio2mesh-actor3-2h"
FREQ:
epoch_save: 5
@@ -22,9 +22,10 @@ MODEL:
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H10M14S"
load_epoch: 0
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220407-10H07M49S"
load_epoch: 35
DATASET:
fps: 50
@@ -49,14 +50,14 @@ TEST:
TRAIN:
lr: 0.0001
batch_size: 100
lr: 0.00005
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
optimizer: 'Adam'
optimizer: 'SGD'
momentum: 0.9
beta1: 0.5
beta2: 0.999
@@ -71,13 +72,13 @@ TRAIN:
reset_lr: False
resume_suffix: "20220403-00H39M11S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 500
epoch_end: 300
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_ldmk: 1
lambda_rec_ldmk: 0
lambda_closure_x: 1
lambda_closure_y: 1
@@ -0,0 +1,94 @@
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2pose'
DEBUG: False
verbose: False
VISUAL:
vsdm_env: "actor2-1h-happy-pretrain"
FREQ:
batch_print: 20
epoch_save: 5
epoch_valid: 1
epoch_test: 5
MODEL:
name: 'audio2pose'
name_netG: "audio2pose_mvae"
dim_motion: 6
dim_speech: 1024
dim_hidden: 64
num_vertices: 5023
n_lookahead_motion: 1
n_lookprevs_motion: 1
pretrain: True
path_checkpoint: "experiments/audio2pose/train_audio2pose_luox_20220415/20220416-02H02M55S"
load_epoch: 300
DATASET:
fps: 50
sr: 16000
name_train: "motion_pose"
name_valid: "motion_pose"
flip: False
shifting_speed: False
root: './data/LuoXData/LuoXData-pose-16h' # obama-deca-3-5-08-mini
root_raw: '/mfs/lsen/DATA/LuoXData/processing2'
path_mean_dict: './data/LuoXData/DECA_LuoXData_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
batch_size: 100
shuffle: True
apply_testing: True
apply_validation: True
optimizer: 'Adam'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
nesterov: True
grad_clip_norm: False
# lr_policy: 'multistep'
# lr_milestones: [20, 50]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 150
# for cyclical schedule
apply_update_parameters: True
n_cycle_period: 25
epoch_teacher: 50
epoch_sampling: 50
LOSS:
names: ["rec", "kl", "vel", "all"]
lambda_kl: 1
lambda_vel: 10
+24 -15
View File
@@ -49,8 +49,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/Actor2/processing/AA7A9568/audio/audio_trim_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")
# path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9978/audio/audio_trim_60s.wav")
# path_audio = Path("data/ali_test_d.wav")
path_audio = Path("data/bank-demo.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor2/happy/4R3A0004/audio/audio_trim_60s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Actor1/processing/2-23min/audio/audio_trim_120_120s.wav")
# path_audio = Path("data/test/outputs20220319.wav")
# path_audio = Path("./data/47e6d985dc11469ab7f6f47cc0b5e625_trim.wav")
@@ -77,21 +85,22 @@ if __name__ == "__main__":
# 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)}")
raw_speech, sample_rate = torchaudio.load(path_audio)
print(f"raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if len(raw_speech.shape) == 2:
raw_speech = raw_speech[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"resampling: audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
raw_speech = resampler(raw_speech).squeeze().numpy()
sample_rate= 16000
print(f"resampling: raw_speech shape = {raw_speech.shape}, sr = {16000}, duration = {(len(raw_speech)/16000)}")
# padding to
len_align = (audio_raw.shape[0] // 16000 ) * 16000
audio_raw = audio_raw[: len_align]
print(f"after audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw)/sample_rate)}")
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
raw_speech = raw_speech[: len_align]
print(f"after raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech)/sample_rate)}")
# load wav2Vec model
print("load Wav2Vec2Model ...")
@@ -102,10 +111,10 @@ if __name__ == "__main__":
# 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}")
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(audio_raw, sampling_rate=16000, return_tensors="pt")
inputs = processor(pad_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
with torch.no_grad():
@@ -127,5 +136,5 @@ if __name__ == "__main__":
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}")
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)
+130
View File
@@ -0,0 +1,130 @@
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)
@@ -32,7 +32,7 @@ if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor1/processing")
path_save = Path('data/Actor1/Actor1-raw-7h') # processing
path_save = Path('data/Actor1/Actor1-raw-16h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
@@ -63,6 +63,7 @@ if __name__ == "__main__":
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# vid_tmp = ["34-28min"]
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
@@ -71,8 +72,10 @@ if __name__ == "__main__":
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 5: break
# if vid in vid_tmp:continue
if durations_train / 3600 > 8: break
# if durations_valid / 3600 > 4: break
print(f"\n processing the {i}-th video {vid} ... ")
@@ -100,14 +103,13 @@ if __name__ == "__main__":
print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
# 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}"
# assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
data_pos_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
@@ -146,7 +148,7 @@ if __name__ == "__main__":
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
# "data_shape": data_idn,
}
@@ -159,7 +161,7 @@ if __name__ == "__main__":
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
# "data_shape": data_idn,
}
@@ -172,7 +174,7 @@ if __name__ == "__main__":
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
# "data_shape": data_idn,
}
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
+78 -68
View File
@@ -1,3 +1,4 @@
import os
from pathlib import Path
import json
import moviepy
@@ -8,8 +9,10 @@ if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_raw = Path("/ssdata1/cf/data/raw/20220319")
path_root = Path("/yrfs/lsen/DATA/Actor2")
# path_raw = Path("/ssdata1/cf/data/raw/20220319")
path_raw = Path("/ssdata1/cf/data/raw/20220408")
# path_root = Path("/mfs/lsen/DATA/Actor2/processing")
path_root = Path("/mfs/lsen/DATA/Actor2/happy")
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
@@ -25,7 +28,7 @@ if __name__ == '__main__':
# if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing", ipath_item.stem)
ipath_data = path_root.joinpath(ipath_item.stem)
ipath_frame = ipath_data.joinpath("frames")
ipath_video = ipath_data.joinpath("video")
@@ -36,18 +39,18 @@ if __name__ == '__main__':
ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True)
# # load video info & check
if ipath_infor.exists():
# continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframe_info = info['nframes']
# # # load video info & check
# if ipath_infor.exists():
# # continue
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframe_info:
print(f"\n Skip: have already done!")
continue
# # check frames
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframe_info:
# print(f"\n Skip: have already done!")
# continue
# load video
video = VideoFileClip(str(ipath_item))
@@ -61,72 +64,79 @@ if __name__ == '__main__':
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.0)
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# nframes = len(list(video.iter_frames()))
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# save sub video fps=50
# add
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
if not ipath_video_sub.exists():
cmd = f"ffmpeg -y -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
os.system(cmd)
print(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = len(list(video.iter_frames()))
# # Trim
# # video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
# video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# # video = video.subclip(t_start=5.0, t_end=60.0)
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = int(video.duration * video.fps)
# # nframes = len(list(video.iter_frames()))
# # print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# # if fps != 50
# if video.fps != 50:
# print("FPS NOT = 50!! ")
# # save sub video fps=50
# ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
# if ipath_video_sub.exists():
# print("\nERROR: ipath_video_sub.exists()")
# continue
# else:
# video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
# print(f"save video > {ipath_video_sub}")
# # reload video
# video.close()
# video = VideoFileClip(str(ipath_video_sub))
# print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = len(list(video.iter_frames()))
# # get audio
# audio_sub = video.audio
# if audio_sub is None:
# print("\nERROR: audio info is None")
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
# print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# # save audio_sub
# ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
# audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
# print(f"save audio > {ipath_audio_sub}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # # check fps
# # if int(video.fps) != 50:
# # print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# # ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# # video.write_videofile(str(ipath_video_save), fps=50.0)
# # print(f"save video to > {ipath_video_save}...")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# # save video feature
# info = {"nframes": nframes,
# "fps": video.fps,
# "width": video.w,
# "height": video.h}
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
# with open(str(ipath_infor), 'w+') as f:
# json.dump(info, f)
# print(info)
# print(f"save video info in -> {ipath_infor}\n")
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
# # save trim video
# print(f"write_images_sequence...")
# ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
# video.write_images_sequence(ipath_format, fps=50)
@@ -24,7 +24,8 @@ def main(args):
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
# path_data = Path("/mfs/lsen/DATA/Actor2/processing")
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
@@ -39,7 +40,6 @@ def main(args):
# if ivideo_name not in IDs: continue
# if i > 25: break
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
+4 -2
View File
@@ -7,8 +7,10 @@ from pathlib import Path
if __name__ == "__main__":
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
v_dir_videos = sorted(path_data.glob("*"))
# path_data = Path("/mfs/lsen/DATA/Actor2/processing")
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
@@ -29,8 +29,10 @@ def landmark_resample_fps(y, source_fps = 30, target_fps=25):
if __name__ == "__main__":
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
path_save = Path('data/Actor2/Actor2-raw-7h') # processing
# path_data = Path("/mfs/lsen/DATA/Actor2/processing")
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
path_save = Path('data/Actor2/Actor2-happy-1h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
@@ -40,22 +42,20 @@ if __name__ == "__main__":
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["AA7A9568", "AA7A9577"])
# vid_valid = set(["AA7A9569", "AA7A9578"])
vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579',
'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602',
'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610',
'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618',
'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627',
'AA7A9628'])
### for processing data
# vid_test = set(["AA7A9568", "AA7A9577"])
# # vid_valid = set(["AA7A9569", "AA7A9578"])
# vid_valid = set(['AA7A9641', 'AA7A9644', 'AA7A9645', 'AA7A9648', 'AA7A9640',
# 'AA7A9630', 'AA7A9637', 'AA7A9636', 'AA7A9569', 'AA7A9578',
# 'AA7A9632', 'AA7A9638', 'AA7A9651', 'AA7A9647', 'AA7A9643',
# 'AA7A9650', 'AA7A9629', 'AA7A9642', 'AA7A9631', 'AA7A9635',
# 'AA7A9634'])
# vid_train = vids - vid_test - vid_valid
vid_valid = vids - vid_test - vid_train
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
vid_test = set(["4R3A0004"])
vid_valid = set(["4R3A0004"])
vid_train = vids - vid_test - vid_valid
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
+73 -64
View File
@@ -1,5 +1,6 @@
from pathlib import Path
import json
import os
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
@@ -36,18 +37,18 @@ if __name__ == '__main__':
ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True)
# # load video info & check
if ipath_infor.exists():
# continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframe_info = info['nframes']
# # # load video info & check
# if ipath_infor.exists():
# # continue
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframe_info:
print(f"\n Skip: have already done!")
continue
# # check frames
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframe_info:
# print(f"\n Skip: have already done!")
# continue
# load video
video = VideoFileClip(str(ipath_item))
@@ -61,71 +62,79 @@ if __name__ == '__main__':
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.0)
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# nframes = len(list(video.iter_frames()))
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# save sub video fps=50
# add
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
if not ipath_video_sub.exists():
cmd = f"ffmpeg -y -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
os.system(cmd)
print(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = len(list(video.iter_frames()))
# # Trim
# # video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
# video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# # video = video.subclip(t_start=5.0, t_end=60.0)
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = int(video.duration * video.fps)
# # nframes = len(list(video.iter_frames()))
# # print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# # if fps != 50
# if video.fps != 50:
# print("FPS NOT = 50!! ")
# # save sub video fps=50
# ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
# if ipath_video_sub.exists():
# print("\nERROR: ipath_video_sub.exists()")
# continue
# else:
# video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
# print(f"save video > {ipath_video_sub}")
# # reload video
# video.close()
# video = VideoFileClip(str(ipath_video_sub))
# print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = len(list(video.iter_frames()))
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
# # get audio
# audio_sub = video.audio
# if audio_sub is None:
# print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # save audio_sub
# ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
# audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
# print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# # # check fps
# # if int(video.fps) != 50:
# # print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# # ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# # video.write_videofile(str(ipath_video_save), fps=50.0)
# # print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
# # save video feature
# info = {"nframes": nframes,
# "fps": video.fps,
# "width": video.w,
# "height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# with open(str(ipath_infor), 'w+') as f:
# json.dump(info, f)
# print(info)
# print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
# # save trim video
# print(f"write_images_sequence...")
# ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
# video.write_images_sequence(ipath_format, fps=50)
+78
View File
@@ -0,0 +1,78 @@
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
fid = "BU6A9965"
path_root = Path("/mfs/lsen/DATA/Actor3/processing")
path_save = Path("./data/Actor3/DECA_Actor3_mean.npy")
path_save.parent.mkdir(parents=True, exist_ok=True)
path_data = path_root.joinpath(fid)
path_coeff = path_data.joinpath("DECA_coeff")
vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False)
print(f"Have {len(vpath_coeff)} frames")
feat_shape = []
feat_tex = []
feat_cam = []
feat_exp = []
feat_pos = []
feat_light = []
feat_detail = []
for i, ipath_coeff in enumerate(vpath_coeff):
if i > 1000: break
data_coeff = np.load(ipath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_tex.append(data_coeff["tex"])
feat_cam.append(data_coeff["cam"])
feat_light.append(data_coeff["light"])
feat_detail.append(data_coeff["detail"])
feat_shape.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_tex = np.array(feat_tex) # (nframe_trim, 50)
feat_cam = np.array(feat_cam) # (nframe_trim, 6)
feat_light = np.array(feat_light) # (nframe_trim, 50)
feat_detail = np.array(feat_detail) # (nframe_trim, 6)
feat_shape = np.array(feat_shape) # (nframe_trim, 50)
mean_exp = feat_exp.mean(axis=0)
mean_pos = feat_pos.mean(axis=0)
mean_tex = feat_tex.mean(axis=0)
mean_cam = feat_cam.mean(axis=0)
mean_light = feat_light.mean(axis=0)
mean_detail = feat_detail.mean(axis=0)
mean_shape = feat_shape.mean(axis=0)
print(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}")
print(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}")
print(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}")
print(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}")
print(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}")
print(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}")
print(f"mean_shape shape = {feat_shape.shape}, mean = {mean_shape.shape}, \n{mean_shape}")
# save
mean_DECA = {
"exp": mean_exp, # (50, )
"pose": mean_pos, # (6, )
"tex": mean_tex, # (50, )
"cam": mean_cam, # (3, )
"light": mean_light, # (9, 3)
"detail": mean_detail,# (128, )
"shape": mean_shape, # (100, )
}
np.save(path_save, mean_DECA)
print("save to --> ", path_save)
print(f"mean deca = \n {mean_DECA}")
+139
View File
@@ -0,0 +1,139 @@
from pathlib import Path
import json
import os
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
path_raw = Path("/ssdata1/cf/data/raw/20220422")
path_root = Path("/mfs/lsen/DATA/Actor4")
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["clip_full"]
durations = 0
# for each video
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if i < 40: continue
# if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing", ipath_item.stem)
ipath_frame = ipath_data.joinpath("frames")
ipath_video = ipath_data.joinpath("video")
ipath_audio = ipath_data.joinpath("audio")
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame.mkdir(parents=True, exist_ok=True)
ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True)
# # # load video info & check
# if ipath_infor.exists():
# # continue
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# # check frames
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframe_info:
# print(f"\n Skip: have already done!")
# continue
# load video
video = VideoFileClip(str(ipath_item))
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
if video.audio is None:
print("\nERROR: audio info is None")
continue
durations += video.duration
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue
# add
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if not ipath_video_sub.exists():
cmd = f"ffmpeg -y -hide_banner -loglevel error -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
os.system(cmd)
print(f"save video > {ipath_video_sub}")
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.0)
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# nframes = len(list(video.iter_frames()))
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# save sub video fps=50
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
print(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = len(list(video.iter_frames()))
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
@@ -0,0 +1,157 @@
import os, sys
import numpy as np
import cv2
from time import time
import argparse
import json
from pathlib import Path
from torch.utils.data import DataLoader
sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old')
from decalib.deca import DECA
from decalib.datasets.datasets2 import ObamaData
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def main(args):
# device = args.device
device = "cuda:7"
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# IDs = ["actor-2HD", "actor-3HD"]
# IDs = ["clip_full"]
# for each video
for i, ipath_data in enumerate(v_dir_videos):
ivideo_name = ipath_data.stem
print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name)
# if ivideo_name not in IDs: continue
# if i > 25: break
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d")
ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
# ipath_vis = ipath_data.joinpath("DECA_vis2")
ipath_kpt2d.mkdir(parents=True, exist_ok=True)
ipath_kpt3d.mkdir(parents=True, exist_ok=True)
ipath_coeff.mkdir(parents=True, exist_ok=True)
# ipath_vis.mkdir(parents=True, exist_ok=True)
# load video info
if not ipath_infor.exists():
print(f"\n ERROR: info.json not existing {ipath_infor}")
continue
with open(str(ipath_infor), "r") as f:
info = json.load(f)
nframes = info['nframes']
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real != nframes:
print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}")
continue
# check if finish
nkpt2d = len(list(ipath_kpt2d.glob("*.txt")))
if nkpt2d + 10 > nframes:
print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}")
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector, device=device)
dataloader = DataLoader(datatest, batch_size=128, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
batch_names = ibatch_data["names"]
batch_image = ibatch_data["image"].to(device)
if i%10 == 0:
print(f"batch {i:04}/{len(dataloader)}... name = ", batch_names[:5])
codedict = deca.encode(batch_image) # encoder
opdict, visdict = deca.decode(codedict, batch_image) # decoder
for j, jname in enumerate(batch_names):
jpath_kpt2d = ipath_kpt2d.joinpath(f"{jname}.txt")
jpath_kpt3d = ipath_kpt3d.joinpath(f"{jname}.txt")
jpath_coeff = ipath_coeff.joinpath(f"{jname}.json")
np.savetxt(jpath_kpt2d, opdict['landmarks2d'][j].cpu().numpy(), fmt="%.6f")
np.savetxt(jpath_kpt3d, opdict['landmarks3d'][j].cpu().numpy(), fmt="%.6f")
# save coeff
jcodedict = {}
for key, value in codedict.items():
jcodedict[key] = value[j].cpu().numpy()
# print("json = ", jcodedict)
np.save(jpath_coeff, jcodedict)
# # save render
# render_names = ['inputs', 'rendered_images']
# # render_names = ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']
# for vis_name in render_names:
# if vis_name not in visdict.keys():
# continue
# img = util.tensor2image(visdict[vis_name][j])
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img)
# save vis
# cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_vis.jpg")), deca.visualize(visdict))
# break
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='DECA: Detailed Expression Capture and Animation')
parser.add_argument('-i', '--inputpath', default='TestSamples/examples', type=str,
help='path to the test data, can be image folder, image path, image list, video')
parser.add_argument('-d', '--device', default='cuda:0', type=str,
help='set device, cpu for using cpu' )
# process test images
parser.add_argument('--iscrop', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to crop input image, set false only when the test image are well cropped' )
parser.add_argument('--detector', default='fan', type=str,
help='detector for cropping face, check decalib/detectors.py for details' )
# save
parser.add_argument('--useTex', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to use FLAME texture model to generate uv texture map, \
set it to True only if you downloaded texture model' )
parser.add_argument('--saveVis', default=True, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization of output' )
parser.add_argument('--saveKpt', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save 2D and 3D keypoints' )
parser.add_argument('--saveDepth', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save depth image' )
parser.add_argument('--saveObj', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .obj, detail mesh will end with _detail.obj. \
Note that saving objs could be slow' )
parser.add_argument('--saveMat', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save outputs as .mat' )
parser.add_argument('--saveImages', default=False, type=lambda x: x.lower() in ['true', '1'],
help='whether to save visualization output as seperate images' )
main(parser.parse_args())
@@ -0,0 +1,99 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
feat_exp = []
feat_pos = []
feat_idn = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_idn.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_idn = np.array(feat_idn) # (nframe_trim, 100)
# # pad one
# feat_exp = np.pad(feat_exp, ((0,1),(0,0)), mode="edge")
# feat_pos = np.pad(feat_pos, ((0,1),(0,0)), mode="edge")
# feat_idn = np.pad(feat_idn, ((0,1),(0,0)), mode="edge")
if nframes == feat_idn.shape[0]:
np.save(ipath_save_exp, feat_exp)
np.save(ipath_save_pos, feat_pos)
np.save(ipath_save_idn, feat_idn)
print(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
@@ -0,0 +1,103 @@
import sys
import numpy as np
import torch
from pathlib import Path
# common
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.animation import save_images_with_audio
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
if __name__ == "__main__":
# load data
device = torch.device("cuda:4")
pid = "AA7A9568" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor2/processing")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy")
path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
# path_audio = path_data.joinpath("audio/audio_trim.wav")
path_audio = path_data.joinpath("audio/audio_trim_120s.wav")
# data_pos = np.load(path_pos)[:] # N x 6
# data_idn = np.load(path_idn) # N x 100
# data_exp = np.load(path_exp) # N x 50
# N = data_exp.shape[0]
data_pos = np.load(path_pos)[:6000] # N x 6
data_idn = np.load(path_idn)[:6000] # N x 100
data_exp = np.load(path_exp)[:6000] # N x 50
N = data_exp.shape[0]
# load mean
path_deca_mean = Path("./data/Actor2/DECA_Actor2_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pos_trim_120s.mp4")
v_render_pt = []
nbatch_render = 5
for k in range(0, N, nbatch_render):
codedict = {}
codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = codedict["exp"].shape[0]
codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6)
codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6]
# codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6)
# codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100)
codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100)
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = netR.decode_one(codedict, nbatch_real, device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
save_images_with_audio(v_render_pt, path_audio, path_save)
@@ -0,0 +1,73 @@
from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
from zmq import device
class ImagesDataset(Dataset):
def __init__(self, path_folder:Path):
self.path_folder = path_folder
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
def __len__(self):
return len(self.list_image)
def __getitem__(self, idx):
path_frame = self.list_image[idx]
image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
image = np.asarray(image)
return {"image_name": path_frame.stem, "image": image}
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
vpath_videos = sorted(path_data.glob("*"))
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:1"
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
print(f"load FaceAlignment model in {device}")
# IDs = ["2-23min"]
# for each word
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if iname not in IDs: continue
ipath_infor = ipath_item.joinpath("video/info.json")
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
ipath_frame = ipath_item.joinpath("frames")
ipath_ldmks.mkdir(parents=True, exist_ok=True)
dataset = ImagesDataset(ipath_frame)
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
for k, ibatch in enumerate(dloader):
ibatch_name = ibatch["image_name"]
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
if k%100 == 0:
print(f"batching {k}/{len(dloader)} ... ")
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
# save landmarks
for jldmk, jname in zip(pred, ibatch_name):
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
# break
@@ -0,0 +1,188 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def landmark_resample_fps(y, source_fps = 30, target_fps=25):
""" y, N x 136, with 30fps
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
path_save = Path('data/Actor3/Actor3-raw-2h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["BU6A9978"])
vid_valid = set(["BU6A9965","BU6A9980","BU6A9978"])
# vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579',
# 'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602',
# 'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610',
# 'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618',
# 'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627',
# 'AA7A9628'])
vid_train = vids - vid_test - vid_valid
# vid_valid = vids - vid_test - vid_train
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
# if durations_train / 3600 > 6: break
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_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(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_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_head = data_pos[:, :3] # (nframe, 3)
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30
print(f"motion = {data_motion.shape}")
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
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)}")
# ####################################
# # clips 4min
# nclip = 4
# nframes = nclip * 60 * 50 # min * 60s * fps
# nsegmts = nclip * 60 * 16000 # min * 60s * sr
# data_motion = data_motion[:nframes]
# audio_raw = audio_raw[:nsegmts]
# data_idn = data_idn[:nframes]
# ####################################
if vid in vid_train:
durations_train += nframes/fps
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_valid:
durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
if vid in vid_test:
durations_test += nframes/fps
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
# print(f"Total ids: data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)})")
# print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
+66
View File
@@ -0,0 +1,66 @@
import os
import numpy as np
import moviepy.editor as mpy
from pathlib import Path
if __name__ == "__main__":
fps_save = 50
path_save = "/yrfs/lsen/DATA/Actor2/processing/AA7A9568/video/predict_compare_3_AR.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_CN_20220312/20220314-15H08M06S/audio_trim_120s_infer_20220313-13H26M47S_epoch_100_002.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2meshAR_CN_20220314/20220317-15H57M26S/audio_trim_120s_infer_20220316-23H56M06S_epoch_050_002.mp4"
path_clipC = "/yrfs/lsen/DATA/Actor2/processing/AA7A9568/video/deca_render_no_pose_120s.mp4"
# path_clipC = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render_no_pos_no_idn.mp4"
# path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220223-21H45M05S/audio_trim_60_120s_infer_20220215-15H12M28S_epoch_120_00.mp4"
# path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
# path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
path_audio = "/yrfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
print(f"clip_A duration = {clip_A.duration}, clip_B duration = {clip_B.duration}")
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
print(f"audio duration = {audio.duration}")
# txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18)
# clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18)
# clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512))
# txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18)
# clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512))
# align to clipGT
duration = min(min(clip_A.duration, clip_B.duration), audio.duration)
print(f"duration min = {duration}")
clip_A = clip_A.set_duration(duration)
clip_B = clip_B.set_duration(duration)
clip_C = clip_C.set_duration(duration)
audio = audio.set_duration(duration)
# stack
# video = mpy.clips_array([[clip_A, clip_B, clip_C], [clip_AA, clip_BB, clip_CC]]) # clip_C
video = mpy.clips_array([[clip_A, clip_B, clip_C]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
video.write_videofile(path_save, fps=fps_save, logger=None)
print(f"save to > {path_save}")
Whitespace-only changes.
@@ -0,0 +1,87 @@
import json
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
if ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_pos}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps // 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
feat_pos = []
feat_cam = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if j%1000 == 0: print(f"processing the {j}-th frame ... ")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_pos.append(data_coeff["pose"])
feat_cam.append(data_coeff["cam"])
# save
feat = np.concatenate([np.array(feat_pos), np.array(feat_cam)], axis=1) # (nframe_trim, 6+3)
# pad one
if nframes == feat.shape[0] + 1:
feat = np.pad(feat, ((0,1),(0,0)), mode="edge")
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframes}\n save to -> {ipath_save_pos}") # (nframe, 9)
elif nframes == feat.shape[0]:
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframes}\n save to -> {ipath_save_pos}") # (nframe, 9)
else:
print("ERROR, skip! ")
@@ -0,0 +1,165 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def landmark_resample_fps(y, source_fps = 30, target_fps=25):
""" y, N x 136, with 30fps
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
path_save = Path('data/LuoXData/LuoXData-pose-16h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_pos_cam_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["2021-P09", "2021-P22"])
vid_valid = set(["2021-P14", "2021-P20"])
vid_train = vids - vid_test - vid_valid
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_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(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 9)
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}"
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
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)}")
if vid in vid_train:
durations_train += nframes/fps
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
# if durations_train / 3600 > 16:
# break
if vid in vid_valid:
durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
if vid in vid_test:
durations_test += nframes/fps
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
print(f"--> {path_save}")
@@ -0,0 +1,84 @@
import json
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
if ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_pos}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}, duration ={nframe_trim / fps // 60}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# check
# vframe_frame = list(ipath_frame.glob("*.jpg"))
# vframe_coeff = list(ipath_coeff.glob("*.npy"))
# print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
# if len(vframe_frame) != nframe_trim:
# print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframe_trim}")
# continue
feat_pos = []
feat_cam = []
for j in range(ibeg, iend):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:05d}.json.npy")
if j%1000 == 0: print(f"processing the {j}-th frame ... ")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_pos.append(data_coeff["pose"])
feat_cam.append(data_coeff["cam"])
# save
feat = np.concatenate([np.array(feat_pos), np.array(feat_cam)], axis=1) # (nframe_trim, 6+3)
# pad one
if nframe_trim == feat.shape[0]:
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframe_trim}\n save to -> {ipath_save_pos}") # (nframe, 9)
duration_coeff += nframe_trim / fps / 60
print(f"add duration_coeff={duration_coeff} min")
else:
print("ERROR, skip! ")
@@ -0,0 +1,184 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def convert_fps(y, source_fps = 30, target_fps=25):
"""
y, nframes x nc_feat (with source_fps)
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/Obama/obama-pose-8h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_pos_cam_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = [ipath.stem for ipath in v_dir_videos]
print(f"Have {len(v_dir_videos)} video id[:3] > {vids[:3]}")
# print(f"vids total= {vids}")
vid_test = set(vids[ :2])
vid_valid = set(vids[2:10])
vid_train = set(vids) - vid_test - vid_valid
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
# print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
if not ipath_info.exists():
print(f"ERROR: NOT Exist {ipath_info}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}, duration ={nframe_trim / fps // 60}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 9)
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}"
# resample to 30fps
fps_convert = 50
data_exp = convert_fps(data_exp, source_fps=fps, target_fps=fps_convert)
data_pos = convert_fps(data_pos, source_fps=fps, target_fps=fps_convert)
data_idn = convert_fps(data_idn, source_fps=fps, target_fps=fps_convert)
nframe_convert = data_pos.shape[0]
print(f"after convert motion = {data_pos.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}")
# assert data_motion.shape[0] == data_shape.shape[0], f"motion = {data_motion.shape[0]} shape = {data_shape.shape[0]}"
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
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)}")
if vid in vid_train:
durations_train += nframe_convert/fps_convert
data_train[vid] = {
"fps": fps_convert,
"sr": 16000,
"nframe": nframe_convert,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
if durations_train / 3600 > 8:
break
if vid in vid_valid:
durations_valid += nframe_convert/fps_convert
data_valid[vid] = {
"fps": fps_convert,
"sr": 16000,
"nframe": nframe_convert,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
if vid in vid_test:
durations_test += nframe_convert/fps_convert
data_test[vid] = {
"fps": fps_convert,
"sr": 16000,
"nframe": nframe_convert,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
print(f"--> {path_save}")
View File
Whitespace-only changes.
@@ -0,0 +1,141 @@
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
import onnx
import onnxruntime as rt
import os, sys
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.datasets import create_dataset
from src.models import create_model, calculate_model_params
from common.logger import Logger
def _convert_batchnorm(module):
"""Convert the syncBNs into normal BN3ds."""
module_output = module
if isinstance(module, torch.nn.SyncBatchNorm):
module_output = torch.nn.BatchNorm3d(module.num_features, module.eps,
module.momentum, module.affine,
module.track_running_stats)
if module.affine:
module_output.weight.data = module.weight.data.clone().detach()
module_output.bias.data = module.bias.data.clone().detach()
# keep requires_grad unchanged
module_output.weight.requires_grad = module.weight.requires_grad
module_output.bias.requires_grad = module.bias.requires_grad
module_output.running_mean = module.running_mean
module_output.running_var = module.running_var
module_output.num_batches_tracked = module.num_batches_tracked
for name, child in module.named_children():
module_output.add_module(name, _convert_batchnorm(child))
del module
return module_output
def parse_args():
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
parser.add_argument("--opt", type=str, default="experiments/audio2mesh/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)
# load dataset
test_dataset = create_dataset(opt, phase='valid')
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)
logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
# for _, ibatch_test in enumerate(test_loader):
# model.testing(batch_input=ibatch_test, cur_epoch=epoch) # forward and backward
# break
# build the model
model = create_model(opt, logger)
model.setup(opt) # load checkpoints
model.eval()
# export model
netG = model.netG
netG.eval() # set inference model
path_ckpt = Path(opt.MODEL.path_checkpoint)
path_onnx = Path(f"checkpoints/audio2mesh-{path_ckpt.stem}-{opt.MODEL.load_epoch}.onnx")
if not path_onnx.exists():
# forward
batch_input = next(iter(test_loader))
batch_otput = model.forward(batch_input)
print(f"cond shape = {model.cond.shape}, batch_otput shape = {batch_otput.shape}")
torch.onnx.export(
netG, # model being run
model.cond,
str(path_onnx),
export_params=True,
verbose=True,
opset_version=11,
input_names=["cond"],
output_names=["mesh"],
dynamic_axes = {
"cond": {0: "batch_size", 1: "nseqlen"},
"mesh": {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
# get pytorch output
batch_input = next(iter(test_loader))
batch_otput = model.forward(batch_input).detach().cpu().numpy()
print(f"cond shape = {model.cond.shape}, batch_otput shape = {batch_otput.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(["mesh"], {"cond": model.cond.cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(batch_otput, batch_onnx), 'The outputs are different between Pytorch and ONNX'
print('The numerical values are same between Pytorch and ONNX')
@@ -0,0 +1,83 @@
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from lsp.options.test_feature2face_options import TestOptions as RenderOptions
from lsp.models import create_model
from lsp.models import feature2face_model
from lsp.models.feature2face_G import Feature2Face_G
if __name__ == '__main__':
# create m2f model
gen_opt = RenderOptions().parse()
gen_opt.name = "ljj" #args.name
gen_opt.batch_size = 64 #args.batch_size_m2f
path_ckpt_m2f = f'./data/render/models/{gen_opt.name}/render_g.pkl'
device = torch.device("cuda:0")
# model_m2f = create_model(gen_opt)
# model_m2f.Feature2Face_G.eval()
# model_m2f.Feature2Face_G.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG = Feature2Face_G(gen_opt).to(device)
netG = torch.nn.DataParallel(netG, [device,])
netG.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG.eval()
path_onnx = Path(f"./data/render/models/{gen_opt.name}/render_g.onnx")
if not path_onnx.exists():
# forward test
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input) # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
torch.onnx.export(
netG.module, # model being run
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"},
"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(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input).detach().cpu().numpy() # (B, 3, 512, 512)
print(f"batch_input 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('The numerical values are same between Pytorch and ONNX')
print(f"output[0, :, 100] = \n{batch_otput[0, 0, 100:120, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0, 0, 100:120, 100]}")
+157
View File
@@ -0,0 +1,157 @@
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
from torchaudio.models.wav2vec2.utils import import_huggingface_model
import onnx
import onnxruntime as rt
import os, sys
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.datasets import create_dataset
from src.models import create_model, calculate_model_params
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
# https://github.com/ccoreilly/wav2vec2-service/blob/master/convert_torch_to_onnx.py
# https://huggingface.co/docs/transformers/serialization
# https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2Model
def parse_args():
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
parser.add_argument("--opt", type=str, default="experiments/xxx.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)
# load dataset
test_dataset = create_dataset(opt, phase='valid')
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)
logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
# build the model
device = "cuda:9"
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
# import
model_extractor = import_huggingface_model(extractor)
model_extractor.eval() # set the model to inference mode
model_extractor.to(device)
# print(f"model_extractor device = {model_extractor.device}")
path_ckpt = Path(opt.MODEL.path_checkpoint)
path_onnx = Path(f"checkpoints/wav2vec2/{MODEL_ID.split('/')[-1]}.onnx")
# forward
batch_input = next(iter(test_loader))
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
print(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
# padding half frame length for bed and end
npad = int(0.5 * 16000 * ( 1 / 50) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
print(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
speech = list(raw_speech)
inputs = processor(speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
print(f"inputs keys = {inputs.keys()}")
with torch.no_grad():
# output = extractor(**inputs)
output = extractor(**inputs).last_hidden_state
output = output.cpu().numpy()
print(f"self.output shape = {output.shape}")
print(f"input_values shape = {inputs['input_values'].shape}, attention_mask shape = {inputs['attention_mask'].shape}")
# x_input = (inputs["input_values"], inputs["attention_mask"])
raw_speech = torch.from_numpy(raw_speech).float().to(device)
if not path_onnx.exists():
torch.onnx.export(
model_extractor, # model being run
raw_speech, # model input (or a tuple for multiple inputs)
str(path_onnx), # where to save the model (can be a file or file-like object)
export_params=True, # store the trained parameter weights inside the model file
opset_version=11, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names = ['input'], # the model's input names
output_names = ['output'], # the model's output names
dynamic_axes={'input' : {0: "batch_size", 1 : 'audio_len'}, # variable length axes
'output' : {0: "batch_size", 1 : 'nseqlen'}
})
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
# get pytorch output
# batch_input = next(iter(test_loader))
# model.set_input(batch_input)
# print(f"cond shape = {model.cond.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
# x_input = {
# "input_values": model.inputs["input_values"].cpu().numpy(),
# "attention_mask": model.inputs["attention_mask"].cpu().numpy()
# }
print(f"raw_speech = {raw_speech.shape}, inputs['input_values'] = {inputs['input_values'].shape}")
raw_speech = inputs['input_values']
batch_onnx = sess.run(['output'], {"input": raw_speech.detach().cpu().numpy()})
print(f"batch_onnx len= {len(batch_onnx)}, [0] shape = {batch_onnx[0].shape}")
assert np.allclose(output, batch_onnx[0], atol=1e-3), 'The outputs are different between Pytorch and ONNX'
print(f"output[0, :, 100] = \n{output[0, :, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0][0,:,100]}")
print('The numerical values are same between Pytorch and ONNX')
@@ -0,0 +1,36 @@
import onnx
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, help="input model")
parser.add_argument("--output", required=True, help="output model")
args = parser.parse_args()
return args
def remove_initializer_from_input():
args = get_args()
model = onnx.load(args.input)
if model.ir_version < 4:
print(
'Model with ir_version below 4 requires to include initilizer in graph input'
)
return
inputs = model.graph.input
name_to_input = {}
for input in inputs:
name_to_input[input.name] = input
for initializer in model.graph.initializer:
if initializer.name in name_to_input:
inputs.remove(name_to_input[initializer.name])
onnx.save(model, args.output)
if __name__ == '__main__':
remove_initializer_from_input()
@@ -0,0 +1,65 @@
GPUS: '8'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: True
verbose: False
isTrain: False
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh2'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# # # 1h 1:10
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-02H14M47S"
load_epoch: 100
# # # 2h 1:10
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-18H22M47S"
# load_epoch: 100
# # 3h 1:100
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220316-16H38M26S"
# load_epoch: 100
# # 5h
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220321-17H42M19S"
# load_epoch: 100
DATASET:
fps: 50
sr: 16000
# name: "motion_live"
name: "motion_eval"
root: './data/Actor1/Actor1-raw-1h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor1/processing'
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
TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
@@ -0,0 +1 @@
[2022-04-06 16:22:02,962][INFO] device set to cuda:8
+11 -7
View File
@@ -63,8 +63,8 @@ config.FREQ.update_html = 1
# visual
config.VISUAL = edict()
config.VISUAL.use_HTML = True
config.VISUAL.use_visdom = True
config.VISUAL.use_HTML = False
config.VISUAL.use_visdom = False
config.VISUAL.vsdm_id = 0
config.VISUAL.vsdm_wsize = 256
@@ -213,10 +213,11 @@ config.TRAIN.load_iter = 0
config.TRAIN.epoch = 0
# for cyclical schedule
config.TRAIN.n_cycle = 5
config.TRAIN.ratio = 0.8
config.TRAIN.beta_start= 0.0
config.TRAIN.beta_stop = 1.0
config.TRAIN.n_cycle_period = 50
# for scheular sampling
config.TRAIN.epoch_teacher = 0
config.TRAIN.epoch_sampling = 0
config.TRAIN.optimizer = 'adam'
config.TRAIN.momentum = 0.9
@@ -250,11 +251,14 @@ config.LOSS.lambda_rec_ldmk = 0
config.LOSS.lambda_closure_x = 0
config.LOSS.lambda_closure_y = 0
# for Flow
config.LOSS.lambda_logp = 0
config.LOSS.lambda_logdet = 0
# for vae
config.LOSS.lambda_kl = 0
config.LOSS.lambda_vel = 0
#############################
# TEST related params
config.TEST = edict()
-7
View File
@@ -10,13 +10,6 @@ class MotionEvalDataset(Dataset):
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
# self,
# path_data = "./data_valid.npz", # opt.DATASET.root
# fps = 50, # opt.DATASET.fps
# sr = 16000, # opt.DATASET.sr
# num_windows = 3, # eval(f"opt.DATASET.nwind_second_{phase}")
# filter = "savgol",
# ):
super(MotionEvalDataset, self).__init__()
self.opt = opt
+5 -134
View File
@@ -25,16 +25,8 @@ class MotionLiveDataset(Dataset):
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
# for test
# if phase == "valid":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
# if phase == "test":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
print(f"[{self.phase}] load data ... --> {path_data}")
# dict vid: {"data_motion", # [nframe, 53]
# "data_speech", # [duration * sample_rate, ] raw deepseep
# "nframe", "fps", "sr"}
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
@@ -50,22 +42,11 @@ class MotionLiveDataset(Dataset):
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
# path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
# path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
# print(f"load data ... --> {path_motion} | {path_speech}")
# self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
# self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
# print(f"motion data ={self.data_motion.shape}, output={self.data_speech.shape}")
# self.nc_motion = self.data_motion.shape[-1]
# self.nc_speech = self.data_speech.shape[-1]
# debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech }")
def __len__(self):
if self.phase == "train":
return 10000
return 20000
elif self.phase == "valid":
return 3000 #3000
else:
@@ -83,10 +64,6 @@ class MotionLiveDataset(Dataset):
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# # filter "2021-P29"
# while vid == "2021-P29":
# vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
@@ -107,7 +84,7 @@ class MotionLiveDataset(Dataset):
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, int(self.nsteps_segmt * speed) = {int(self.nsteps_segmt * speed)}, vid={vid}"
assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}"
# print(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}")
@@ -127,9 +104,11 @@ class MotionLiveDataset(Dataset):
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
@@ -186,112 +165,4 @@ class MotionLiveDataset(Dataset):
data_speech = data_speech[:nsteps_speech*speed]
return data_motion, data_speech
class MotionLiveEvalDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
"""
phase = "valid | test "
"""
super(MotionLiveEvalDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
print(f"\n [{self.phase}] load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.annodb_accums = self.count_annotations()
self.overlap = 0.5
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
return self.annodb_accums[-1]
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, anno_dict in enumerate(self.annodb.values()):
acc += anno_dict["data_motion"].shape[0] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows
annodb_accums[i+1] = acc # 2
return annodb_accums
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
for i, iacc in enumerate(self.annodb_accums):
if idx > iacc -1 and idx < self.annodb_accums[i+1]:
pid, new_idx = i, idx - iacc
break
print(f"DEBUG: idx={idx}, pid = {pid}, iacc ={self.annodb_accums[i]}, new_idx = {new_idx}")
# return item
vid = self.pids[pid]
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
beg_frame = new_idx
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\nnsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
print(f"data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
}
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
return result
+160
View File
@@ -0,0 +1,160 @@
import imp
import numpy as np
import time
import random
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
# common
from common.resampling import resample_by_nsteps
class MotionPoseDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
"""
phase = "train | valid | test "
"""
super(MotionPoseDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
print(f"[{self.phase}] load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
if self.phase == "train":
return 20000
elif self.phase == "valid":
return 3000 #3000
else:
return 500
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_idn = data["data_idn"] # (nframes, nc_idn=100)
data_exp = data["data_exp"] # (nframes, nc_exp=50)
data_pos = data["data_pos"] # (nframes, nc_pos=9) pose=6, camera=3
data_aud = data["data_speech"] # (nsegemts, )
nframe = data_pos.shape[0]
nsegmt = data_aud.shape[0]
if self.phase == "train" and self.opt.DATASET.shifting_speed and random.random() < 0.3:
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
beg_frame = np.random.randint(nframe - int(self.nsteps_frame * speed) - 10) + 5 # select from (5:-5)
end_frame = beg_frame + int(self.nsteps_frame * speed)
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + int(self.nsteps_segmt * speed)
data_idn = data_idn[beg_frame:end_frame] # (nteps, 100)
data_exp = data_exp[beg_frame:end_frame] # (nteps, 50)
data_pos = data_pos[beg_frame:end_frame] # (nteps, 9)
data_aud = data_aud[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_aud.shape[0] == int(self.nsteps_segmt * speed), f"data_aud shape={data_aud.shape}, int(self.nsteps_segmt * speed) = {int(self.nsteps_segmt * speed)}, vid={vid}"
assert data_pos.shape[0] == int(self.nsteps_frame * speed), f"data_pos shape={data_pos.shape}, vid={vid}"
# print(f"speed={speed}, data_aud shape={data_aud.shape} data_pos shape={data_pos.shape}")
# resample to same nsteps
data_idn = resample_by_nsteps(data_idn, nsteps_tgt=self.nsteps_frame)
data_exp = resample_by_nsteps(data_exp, nsteps_tgt=self.nsteps_frame)
data_pos = resample_by_nsteps(data_pos, nsteps_tgt=self.nsteps_frame)
data_aud = resample_by_nsteps(data_aud, nsteps_tgt=self.nsteps_segmt)
# print(f"resampling > data_aud shape={data_aud.shape} data_pos shape={data_pos.shape} \n")
else:
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_idn = data_idn[beg_frame:end_frame] # (nteps, 100)
data_exp = data_exp[beg_frame:end_frame] # (nteps, 50)
data_pos = data_pos[beg_frame:end_frame] # (nteps, 9)
data_aud = data_aud[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_aud.shape[0] == self.nsteps_segmt, f"data_aud shape={data_aud.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
assert data_pos.shape[0] == self.nsteps_frame, f"data_pos shape={data_pos.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
# data_idn = savgol_filter(data_idn, window_length=5, polyorder=3, axis=0, mode='nearest')
data_exp = savgol_filter(data_exp, window_length=5, polyorder=3, axis=0, mode='nearest')
data_pos = savgol_filter(data_pos, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: shuffle speed
result = {
"idn": data_idn, # (nsteps_frame, 100)
"exp": data_exp, # (nsteps_frame, 50)
"pos": data_pos, # (nsteps_frame, 9)
"aud": data_aud, # (nsteps_segmt,)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def make_auguments_speed(self, data_pos, data_aud, p=0.5):
'''
parameters:
data_pos: (nsteps_motion, 53)
data_aud: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() > p:
return data_pos, data_aud
nsteps_motion = data_pos.shape[0]
nsteps_speech = data_aud.shape[0]
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
if speed < 0:
data_pos = data_pos[:nsteps_motion*speed]
data_aud = data_aud[:nsteps_speech*speed]
return data_pos, data_aud
+314 -285
View File
@@ -1,23 +1,25 @@
import sys
import numpy as np
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models.info import flame_mouth_idx, flame_mouth_upper_idx, flame_mouth_lower_idx
from src.models.info import flame_mouth_idx
from src.models.info import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk
from src.models.info import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
from src.losses.metrics import MeanDictMetric
from src.utils import util
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.animation import save_animation_with_gt2, write_video, write_video_with_gt
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2MeshModel(Base):
@@ -36,7 +38,10 @@ class Audio2MeshModel(Base):
init_exp_weight = np.load("./data/init_expression_basis.npy")
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
init_exp_weight = init_exp_weight[:, :50]
if isinstance(self.netG, torch.nn.DataParallel):
self.netG.module.decoder_mesh.weight.data = init_exp_weight
else:
self.netG.decoder_mesh.weight.data = init_exp_weight
print(f"init_exp_weight shape = {init_exp_weight.shape}")
# # print network parameters
@@ -44,16 +49,22 @@ class Audio2MeshModel(Base):
# print(name, '\t\t', param.size())
# load mean lighting & shape
self.netR, self.flame = define_netR(device=self.device)
# self.netR, self.flame = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR)
self.netF = define_FLAME(opt, self.device)
self.netR = define_render(opt, self.device)
# path_deca_mean = Path("./data/DECA_obama_mean.npy")
path_deca_mean = self.opt.DATASET.path_mean_dict
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
# get template
self.template_verts = self.get_template_vertices() # 1 x 1 x 5023 x 3
self.template_verts_specific = self.get_template_vertices(self.mean_dict) # 1 x 1 x 5023 x 3
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
# if filter outlier
# if self.opt.LOSS.filter_outlier:
@@ -66,7 +77,6 @@ class Audio2MeshModel(Base):
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
if self.isTrain:
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
@@ -75,33 +85,36 @@ class Audio2MeshModel(Base):
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
self.extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(self.device)
def set_input(self, batch_input):
""" """
# motion data
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
self.B, self.nsteps = self.data.size(0), self.data.size(1)
self.B, self.nsteps = data.size(0), data.size(1)
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
# speech data
self.cond = None
cond = None
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
@@ -120,37 +133,51 @@ class Audio2MeshModel(Base):
with torch.no_grad():
output = self.extractor(**inputs)
self.cond = output.last_hidden_state
# self.cond = output.extract_features
cond = output.last_hidden_state
else:
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
# B x nsteps x nc_feat
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}, device={data.device}", verbose=False)
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
# unfold speech data
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
self.cond = cond
self.nseq = self.cond.size(1)
self.data = self.data[:, 7:7+self.nseq, :]
self.nseq = cond.size(1)
data = data[:, 7:7+self.nseq, :]
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
def training(self, batch_input):
def forward(self, batch_input):
self.set_input(batch_input)
# forward
pred = self.netG(self.cond)
debug(self.opt, f"traing pred = {pred.shape}", verbose=False)
return pred
def training(self, batch_input, idx_epoch=0, idx_batch=0):
self.train() # set train model
self.set_input(batch_input)
# forward
self.pred = self.netG(self.cond)
self.pred += self.template_verts
self.pred += self.temp_verts
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
# loss
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
loss, loss_dict = self.eval_losses(self.pred, self.vert)
# backward
self.optimizer_G.zero_grad()
@@ -162,72 +189,104 @@ class Audio2MeshModel(Base):
self.optimizer_G.step()
return loss
return loss_dict
def validation(self, batch_input):
def validation(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
self.pred = self.netG(self.cond)
self.pred += self.template_verts
pred = self.netG(self.cond)
pred += self.temp_verts
_, loss_dict = self.eval_losses(self.pred, self.data)
loss, loss_dict = self.eval_losses(pred, self.vert)
return loss_dict
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
def infer_with_gt(self, batch_cond, batch_data, audio_raw, suffix="", save_npy=True):
self.eval()
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
data = batch_data.float().to(self.device) # (B, nframe, 53)
vert, ldmk2d, ldmk3d = self.get_vertices(data)
with torch.no_grad():
batch_pdt_geo = self.netG(cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pdt_geo.shape}")
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pdt_geo, audio_raw,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
# render & and save
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
self.save_reconstruct_with_gt2(batch_pdt_geo, vert, audio_raw,
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()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def infer(self, batch_cond, raw_speech, suffix="", save_npy=True):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad():
samples_pt = self.netG(self.cond) # B x N x dim_motion
samples_pt += self.template_verts # B x N x 5023 x 3
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {samples_pt.shape}")
print(f"testing pt shape = {batch_pdt_geo.shape}")
# !! add specific when render & output !!
samples_pt = samples_pt - self.template_verts + self.template_verts_specific
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(samples_pt, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
self.save_reconstruct(batch_pdt_geo, raw_speech, path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
if save_npy:
# save result
samples_pt = samples_pt.cpu().numpy()
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
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}")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
samples_pt = self.netG(self.cond) # B x N x 5023 x 3
samples_pt += self.template_verts # B x N x 5023 x 3
samples_gt = self.get_vertices(self.data) # B x N x 5023 x 3
# samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3
batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
# !! add specific when render & output !!
samples_pt = samples_pt - self.template_verts + self.template_verts_specific
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}")
self.save_reconstruct_with_gt(samples_pt, samples_gt,
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device)
batch_pos = torch.zeros(1, 6).to(self.device)
batch_pose = torch.zeros(1, 6).to(self.device)
if mean_dict is not None:
batch_shape = self.mean_dict["shape"].reshape(1, 100)
@@ -235,13 +294,16 @@ class Audio2MeshModel(Base):
else:
batch_shape = torch.zeros(1, 100).to(self.device)
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
print(f"template verts reshape = {verts.shape}")
# np.save("./data/template.npy", verts.squeeze().cpu().numpy())
# print(f"save template.npy = {verts.squeeze().shape}")
# assert False
with torch.no_grad():
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
return verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
print(f"template verts reshape = {verts.shape}")
return verts, ldmk2d, ldmk3d
def get_vertices(self, batch_motion):
@@ -249,197 +311,41 @@ class Audio2MeshModel(Base):
batch_motion, (nbatch, seqlen, 53)
"""
batch_exp = batch_motion[..., :50]
batch_pos = batch_motion[..., 50:]
batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos
batch_pose[:, 3:6] = batch_pos_mouth
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
with torch.no_grad():
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
# print(f"verts reshape = {verts.shape}")
ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
return verts
return verts, ldmk2d, ldmk3d
def eval_losses_for_infer_loss(self, batch_pdt_geo, batch_tgt):
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
# get mesh geometry
batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # B x nsteps x num_vertices x 3
loss_rec_geo = loss_rec_geo.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
loss_rec_geo = loss_rec_geo.detach()
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo1 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # B x nsteps-1
loss_vel_geo1 = loss_vel_geo1.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps-1
loss_vel_geo1 = F.pad(loss_vel_geo1, pad=(0, 1), mode="replicate").detach() # B x nsteps
diff_pdt_geo = batch_pdt_geo[:, 2:, :] - batch_pdt_geo[:, :-2, :]
diff_tgt_geo = batch_tgt_geo[:, 2:, :] - batch_tgt_geo[:, :-2, :]
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # B x nsteps-2
loss_vel_geo2 = loss_vel_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps-2
loss_vel_geo2 = F.pad(loss_vel_geo2, pad=(0, 2), mode="replicate").detach() # B x nsteps
# stack among these losses
loss_stack = torch.stack([loss_rec_geo, loss_vel_geo1, loss_vel_geo2], dim=2) # B x nsteps x 3
return loss_stack
def eval_losses_active(self, batch_pdt_geo, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = {}
# get mesh geometry
batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
# B = batch_pdt_geo.size(0)
# print(f"batch_pdt_geo = {batch_pdt_geo.shape}, batch_tgt_geo = {batch_tgt_geo.shape}, B = {B}")
loss_dict = OrderedDict()
# synthesis geo rec
loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # B
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo = self.loss_func_l1(batch_pdt_geo, batch_tgt_geo) # B
loss_dict["rec_geo_l1"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) # B x nsteps x num_vertices x 3
loss_rec_geo2 = loss_rec_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
# filter outliar
threshold_rec, mean_rec = torch.quantile(loss_rec_geo2, q=0.75) * 1.5, torch.quantile(loss_rec_geo2, q=0.5)
b_outlier_rec = loss_rec_geo2 > threshold_rec # B x nsteps
# print(f"threshold_rec = {threshold_rec.shape}")
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # 1,
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo = self.loss_func_l1(diff_pdt_geo, diff_tgt_geo) # 1,
loss_dict["vel_geo_l1"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) # B x nsteps x num_vertices x 3
loss_vel_geo2 = loss_vel_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
# filter outliar
threshold_vel, mean_vel = torch.quantile(loss_vel_geo2, q=0.75) * 1.5, torch.quantile(loss_vel_geo2, q=0.5)
b_outlier_vel = loss_vel_geo2 > threshold_vel # B x (nsteps-1)
# print(f"threshold_vel = {threshold_vel.shape}")
# find outliar in both loss data
b_outlier_rec[:, :-1] = b_outlier_rec[:, :-1] & b_outlier_vel[:, :]
if torch.any(b_outlier_rec):
# print(f"b_outlier_rec = {b_outlier_rec}")
# print(f"outerliar size= {loss_rec_geo2[b_outlier_rec].shape} / {loss_rec_geo2.numel()} ")
loss_rec_geo2[b_outlier_rec] = mean_rec
loss_vel_geo2[b_outlier_rec[:, :-1]] = mean_vel
# calculate again
loss_rec_geo2 = loss_rec_geo2.mean()
loss_dict["rec_geo_w"] = loss_rec_geo2.detach()
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
loss_vel_geo2 = loss_vel_geo2.mean()
loss_dict["vel_geo_w"] = loss_vel_geo2.detach()
loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['all'] = loss.detach()
return loss, loss_dict
def eval_losses_for_valid(self, batch_pdt_geo, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss_dict = {}
# get mesh geometry
batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
# closure loss
diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
- batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
- batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
loss_dict["closure"] = loss_closure.mean().detach()
if self.opt.LOSS.lambda_closure > 0:
loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
# total loss
loss_dict["all"] = loss.clone().detach()
# return
return loss, loss_dict
def eval_losses(self, batch_pdt_geo, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = {}
# get mesh geometry
batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
@@ -451,43 +357,60 @@ class Audio2MeshModel(Base):
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
if self.opt.LOSS.lambda_vel_geo:
if self.opt.LOSS.lambda_vel_geo > 0:
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
# landmarks loss
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
# closure loss
diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
- batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
if self.opt.LOSS.lambda_rec_ldmk > 0:
loss += loss_rec_ldmk.mean() * self.opt.LOSS.lambda_rec_ldmk
diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
- batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
# mouth closure_x loss (left/right mouth)
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
loss_dict["closure"] = loss_closure.mean().detach()
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_x"] = loss_closure_x.mean().detach()
if self.opt.LOSS.lambda_closure_x > 0:
loss += loss_closure_x.mean() * self.opt.LOSS.lambda_closure_x
# mouth closure_y loss (upper/lower mouth)
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_y"] = loss_closure_y.mean().detach()
if self.opt.LOSS.lambda_closure_y > 0:
loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y
if self.opt.LOSS.lambda_closure > 0:
loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
# total loss
loss_dict["all"] = loss.clone().detach()
loss_dict["all"] = loss.detach()
# return
return loss, loss_dict
def save_reconstruct(self, batch_pdt_geo, raw_speech, path_save, suffix="", vis_landmarks=False):
# batch_pdt_geo, [B x N x dim_motion]
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
B, N, *_ = samples_pt.shape
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = samples_pt[i, ...]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
igeo_pt = batch_pdt_geo[i, ...]
v_render_pt = []
for k in range(0, N, nbatch_render):
@@ -501,28 +424,115 @@ class Audio2MeshModel(Base):
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
else:
render_pt = render_pt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# write video
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
write_video(v_render_pt, raw_speech, ipath_save, fps=50)
self.logger.info(f"save video to -> {str(ipath_save)}")
@torch.no_grad()
def render_geometry(self, verts, cam=None, device=None):
"""
verts: [N x 5023 x 3]
"""
batch_size = verts.size(0)
if cam is None:
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
# orth_proj
verts_proj = util.batch_orth_proj(verts, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
return images
@torch.no_grad()
def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_geo, [1 x N x 5023 x 3]
# batch_tgt_geo, [1 x N x 5023 x 3]
B, N, *_ = batch_pdt_geo.shape
igeo_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[0, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{0:02d}_pt_gt.mp4")
v_render_pt = []
v_render_gt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[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).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
else:
render_pt = render_pt.cpu()
render_gt = render_gt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, ipath_save)
write_video_with_gt(v_render_pt, v_render_gt, raw_speech, ipath_save, fps=50, sr=16000)
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
# samples_pt, [B x N x 5023 x 3]
# samples_gt, [B x N x 5023 x 3]
B, N, *_ = samples_pt.shape
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, path_save, suffix=""):
# batch_pdt_geo, [B x N x 5023 x 3]
# batch_tgt_geo, [B x N x 5023 x 3]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = samples_pt[i, ...] # [N x 5023 x 3]
igeo_gt = samples_gt[i, ...] # [N x 5023 x 3]
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
@@ -533,18 +543,36 @@ class Audio2MeshModel(Base):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[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)
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
# kldmk3d_pt = kldmk3d_pt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
# kldmk3d_gt = kldmk3d_gt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2
# write to image
# render_pt = tensor2image(render_pt) # (nbatch_real, 3, 512, 512), on cpu
# render_gt = tensor2image(render_gt) # (nbatch_real, 3, 512, 512), on cpu
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
@@ -567,12 +595,17 @@ class Audio2MeshModel(Base):
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
#########################################
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
# image = tensor.detach().cpu().numpy()
image = tensor.numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
@@ -596,35 +629,31 @@ def define_netG(opt):
# to GPU
netG.to(f"cuda:{opt.GPUS[0]}")
if len(opt.GPUS) > 1:
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
return netG
def define_netR(device):
# import
def define_FLAME(opt, device):
from src.nn.FLAME import FLAME
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
model = FLAME(opt.FLAME).to(device)
# use device
# device = "cuda:2"
# whether to use FLAME texture model to generate uv texture map
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
# reconstruction model
netR = DECA(config = deca_cfg, device=device)
# flame model
flame = FLAME(deca_cfg.model).to(device)
return model
return netR, flame
def define_render(opt, device):
from src.utils.renderer import SRenderY, set_rasterizer
set_rasterizer(opt.RENDER.rasterizer_type)
model = SRenderY(opt.RENDER.image_size,
obj_filename=opt.RENDER.topology_path,
uv_size=opt.RENDER.uv_size,
rasterizer_type=opt.RENDER.rasterizer_type
).to(device)
return model
-616
View File
@@ -1,616 +0,0 @@
from collections import OrderedDict
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models.info import flame_mouth_idx
from src.models.info import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk
from src.models.info import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
from src.utils import util
from torchmetrics import MaxMetric, MeanMetric
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2Mesh2Model(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
# define networks
self.netG = define_netG(opt)
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
# init last layer
init_exp_weight = np.load("./data/init_expression_basis.npy")
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
init_exp_weight = init_exp_weight[:, :50]
self.netG.module.decoder_mesh.weight.data = init_exp_weight
print(f"init_exp_weight shape = {init_exp_weight.shape}")
# # print network parameters
# for name, param in self.netG.named_parameters():
# print(name, '\t\t', param.size())
# load mean lighting & shape
# self.netR, self.flame = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR)
self.netF = define_FLAME(opt, self.device)
self.netR = define_render(opt, self.device)
# path_deca_mean = Path("./data/DECA_obama_mean.npy")
path_deca_mean = self.opt.DATASET.path_mean_dict
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
# get template
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
# if filter outlier
# if self.opt.LOSS.filter_outlier:
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
self.loss_func_l1 = nn.L1Loss(reduction="none")
self.names_loss = opt.LOSS.names
# define loss weight
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
if self.isTrain:
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
self.extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(self.device)
def set_input(self, batch_input):
# motion data
data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
self.B, self.nsteps = data.size(0), data.size(1)
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
# speech data
cond = None
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
if self.opt.DATASET.speech_extractor == "wav2vec":
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
raw_speech = list(raw_speech)
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(self.device)
with torch.no_grad():
output = self.extractor(**inputs)
cond = output.last_hidden_state
# cond = output.extract_features
else:
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
# B x nsteps x nc_feat
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}, device={data.device}", verbose=False)
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
# unfold speech data
cond = cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
self.cond = cond
self.nseq = cond.size(1)
data = data[:, 7:7+self.nseq, :]
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
# forward
self.pred = self.netG(self.cond)
self.pred += self.temp_verts
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
# loss
loss, loss_dict = self.eval_losses(self.pred, self.vert)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss_dict
def validation(self, batch_input):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
pred = self.netG(self.cond)
pred += self.temp_verts
loss, loss_dict = self.eval_losses(pred, self.vert)
return loss_dict
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad():
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pdt_geo.shape}")
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pdt_geo, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device)
batch_pose = torch.zeros(1, 6).to(self.device)
if mean_dict is not None:
batch_shape = self.mean_dict["shape"].reshape(1, 100)
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
else:
batch_shape = torch.zeros(1, 100).to(self.device)
with torch.no_grad():
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
print(f"template verts reshape = {verts.shape}")
# np.save("./data/template.npy", verts.squeeze().cpu().numpy())
# print(f"save template.npy = {verts.squeeze().shape}")
# assert False
return verts, ldmk2d, ldmk3d
def get_vertices(self, batch_motion):
"""
batch_motion, (nbatch, seqlen, 53)
"""
batch_exp = batch_motion[..., :50]
batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos_mouth
with torch.no_grad():
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
return verts, ldmk2d, ldmk3d
def eval_losses_for_valid(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss_dict = {}
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # (B, N, num_vertices, 3)
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # (B, N-1, num_vertices, 3)
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
# landmarks loss
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
# ldmk3d_pdt_dis = torch.sqrt(((ldmk3d_pdt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
# ldmk3d_tgt_dis = torch.sqrt(((ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
# loss_rec_ldmk = (ldmk3d_pdt_dis - ldmk3d_tgt_dis).abs().mean() # (B*N, 68) ==> (1,)
# loss_rec_ldmk= self.loss_func_wing(ldmk3d_pdt_dis, ldmk3d_tgt_dis)
# loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
# mouth closure_x loss (left/right mouth)
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_x"] = loss_closure_x.mean().detach()
# mouth closure_y loss (upper/lower mouth)
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_y"] = loss_closure_y.mean().detach()
# # closure loss
# diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
# - batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
# diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
# - batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
# loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
# loss_dict["closure"] = loss_closure.mean().detach()
# if self.opt.LOSS.lambda_closure > 0:
# loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
return loss_dict
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = OrderedDict()
# synthesis geo rec
loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
if self.opt.LOSS.lambda_vel_geo > 0:
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
# landmarks loss
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
if self.opt.LOSS.lambda_rec_ldmk > 0:
loss += loss_rec_ldmk.mean() * self.opt.LOSS.lambda_rec_ldmk
# mouth closure_x loss (left/right mouth)
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_x"] = loss_closure_x.mean().detach()
if self.opt.LOSS.lambda_closure_x > 0:
loss += loss_closure_x.mean() * self.opt.LOSS.lambda_closure_x
# mouth closure_y loss (upper/lower mouth)
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_y"] = loss_closure_y.mean().detach()
if self.opt.LOSS.lambda_closure_y > 0:
loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y
# total loss
loss_dict["all"] = loss.detach()
return loss, loss_dict
def save_reconstruct(self, batch_pdt_geo, path_audio, path_save, suffix=""):
# batch_pdt_geo, [B x N x dim_motion]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = batch_pdt_geo[i, ...]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[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)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, ipath_save)
@torch.no_grad()
def render_geometry(self, verts, cam=None, device=None):
"""
verts: [N x 5023 x 3]
"""
batch_size = verts.size(0)
if cam is None:
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
# orth_proj
verts_proj = util.batch_orth_proj(verts, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
return images
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, path_save, suffix=""):
# batch_pdt_geo, [B x N x 5023 x 3]
# batch_tgt_geo, [B x N x 5023 x 3]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[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).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
# kldmk3d_pt = kldmk3d_pt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
# kldmk3d_gt = kldmk3d_gt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2
# write to image
# render_pt = tensor2image(render_pt) # (nbatch_real, 3, 512, 512), on cpu
# render_gt = tensor2image(render_gt) # (nbatch_real, 3, 512, 512), on cpu
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = 'r', gt_color='g')
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = 'g')
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# get audio
jvid = self.batch_vid[i]
jnframe = self.batch_nframe[i].numpy()
jstart_frame = self.batch_interv[0][i].numpy()
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
#########################################
def tensor2image(tensor):
# image = tensor.detach().cpu().numpy()
image = tensor.numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2mesh":
from src.nn.audio2mesh import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_voca":
from src.nn.audio2mesh_voca import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_resnet":
from src.nn.audio2mesh_resnet import Audio2Mesh
netG = Audio2Mesh(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
# to GPU
netG.to(f"cuda:{opt.GPUS[0]}")
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
return netG
def define_FLAME(opt, device):
from src.nn.FLAME import FLAME
model = FLAME(opt.FLAME).to(device)
return model
def define_render(opt, device):
from src.utils.renderer import SRenderY, set_rasterizer
set_rasterizer(opt.RENDER.rasterizer_type)
model = SRenderY(opt.RENDER.image_size,
obj_filename=opt.RENDER.topology_path,
uv_size=opt.RENDER.uv_size,
rasterizer_type=opt.RENDER.rasterizer_type
).to(device)
return model
+1 -1
View File
@@ -261,8 +261,8 @@ class Audio2MeshARModel(Base):
# ibatch_y_pre = self.y_tgt[:, 0:1] # B x 1 x 5023 x 3
ibatch_y_pre = self.template_verts.expand(B, -1, -1, -1) # B x 1 x 5023 x 3
for istep in range(1, self.nsteps_align):
for istep in range(1, self.nsteps_align):
ibatch_x = self.x[:, istep:istep+1] # B x 1 x nwind x nc_condit
ibatch_y_pdt = self.netG(ibatch_x, ibatch_y_pre) # B x 1 x 5023 x 3
+651
View File
@@ -0,0 +1,651 @@
import numpy as np
from collections import OrderedDict
import tempfile
from scipy.io import wavfile
import torch
import torch.nn as nn
from pathlib import Path
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
from src.utils import util
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2PoseModel(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
self.dim_motion = opt.MODEL.dim_motion # 6-dim pose (rotation-3 + translation-2 + sacle-1)
self.dim_speech = opt.MODEL.dim_speech # 1024-dim
self.dim_latent = opt.MODEL.dim_hidden # 64
# define networks
self.netG = define_netG(opt)
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
self.netF = define_FLAME(opt, self.device)
self.netR = define_render(opt, self.device)
self.processor, self.extractor = define_extractor(opt, self.device)
# path_deca_mean = Path("./data/DECA_obama_mean.npy")
path_deca_mean = self.opt.DATASET.path_mean_dict
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
# get template
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
# loss function
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
self.loss_func_l1 = nn.L1Loss(reduction="none")
self.names_loss = opt.LOSS.names
if self.isTrain:
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
# schedule traning
self.sample_schedule = torch.cat((
# First part is pure teacher forcing
torch.zeros(self.opt.TRAIN.epoch_teacher),
# Second part with schedule sampling
torch.linspace(0.0, 1.0, self.opt.TRAIN.epoch_sampling),
# last part is pure student
torch.ones(self.opt.TRAIN.epoch_end - self.opt.TRAIN.epoch_sampling - self.opt.TRAIN.epoch_teacher),
))
def set_input(self, batch_input):
# motion data
x = batch_input["pos"].float().to(self.device) # (B, nsteps, 9) 3-headpose 3-mouthpose, 1-scale, 2-translate
self.idn = batch_input["idn"].float().to(self.device) # (B, nsteps, 100)
self.exp = batch_input["exp"].float().to(self.device) # (B, nsteps, 50)
self.pos_mouth = x[..., 3:6] # (B, nsteps, 3)
self.x = x[..., [0,1,2,6,7,8]] # (B, nsteps, 6)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
debug(self.opt, f"pos = {self.x.shape}, dtype={self.x.dtype},exp = {self.exp.shape}, idn = {self.idn.shape}, ", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
# speech data
raw_speech = batch_input["aud"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_pad = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_pad = {raw_pad.shape}, dtype={raw_pad.dtype}", verbose=False)
inputs = self.processor(list(raw_pad), sampling_rate=16000, return_tensors="pt")
with torch.no_grad():
cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
# unfold speech data
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nsteps, nc_codit, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nsteps, 16, nc_speech)
# setup
self.c = cond # (B, nsteps, 16, nc_speech)
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
self.x = self.x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion)
self.raw_speech = raw_speech[:, 7*self.opt.DATASET.sr: (7+self.nsteps)*self.opt.DATASET.sr] # (B, nsteps * sr)
self.idn = self.idn[:, 7:7+self.nsteps, :]
self.exp = self.exp[:, 7:7+self.nsteps, :]
self.pos_mouth = self.pos_mouth[:, 7:7+self.nsteps, :]
debug(self.opt, f"x = {self.x.shape}, dtype={self.x.dtype}, device={self.x.device}", verbose=False)
debug(self.opt, f"c = {self.c.shape}, dtype={self.c.dtype}, device={self.c.device}", verbose=False)
debug(self.opt, f"idn = {self.idn.shape}, dtype={self.idn.dtype}, device={self.idn.device}", verbose=False)
debug(self.opt, f"exp = {self.exp.shape}, dtype={self.exp.dtype}, device={self.exp.device}", verbose=False)
def forward(self, batch_input):
self.set_input(batch_input)
# forward
pred = self.netG(self.cond)
debug(self.opt, f"traing pred = {pred.shape}", verbose=False)
return pred
def update_parameters(self, epoch):
# update beta
N = self.opt.TRAIN.n_cycle_period # 50
n = epoch % N
if n < N * 0.1: # 5
beta_update = 0
elif n < N * 0.3: # 5 ~ 15 => 0.0001 ~ 0.01
beta_update = 0.0001 + (n - 0.1 * N) * ((0.01 - 0.0001) / (0.2 * N))
elif n < N * 0.5: # 15~25 => 0.01 ~ 0.1
beta_update = 0.01 + (n - 0.3 * N) * ((0.1 - 0.01) / (0.2 * N))
elif n < N * 0.7: # 35~25 => 0.1 ~ 1
beta_update = 0.1 + (n - 0.5 * N) * ((1 - 0.1) / (0.2 * N))
elif n < N * 0.8: # 35~40 => 0.1 ~ 1
beta_update = 1
else: # 40~50 => 1 ~0
beta_update = 1 + (n - 0.8 * N) * ((0 - 1) / (0.2 * N))
self.opt.LOSS.lambda_kl = beta_update
self.logger.info(f"\t[UPDATE] lambda_kl = {self.opt.LOSS.lambda_kl}")
def training(self, batch_input, idx_epoch=0, idx_batch=0):
self.train() # set train model
self.set_input(batch_input)
# get input
batch_gt = self.x[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
# random
use_student = torch.rand(1) < self.sample_schedule[idx_epoch]
if not use_student:
batch_c = self.c[:, 1:].reshape(-1, self.nwind, self.dim_speech) # [B*(nsteps-1), nwind, nc_speech]
batch_x_prev = self.x[:, :-1].reshape(-1, self.dim_motion) # [B*(nsteps-1), nc_motion]
# forward
batch_pt, batch_mu, batch_lv = self.netG(batch_gt, batch_x_prev, batch_c) # [B*(nsteps-1), nc_motion]
debug(self.opt, f"traing batch_pt = {batch_pt.shape}, batch_gt = {batch_gt.shape}")
else:
batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
batch_pt[:, 0] = self.x[:, 0] # assign first frame
batch_mu = []
batch_lv = []
for istep in range(1, self.nsteps):
ibatch_x = self.x[:, istep] # [B, nc_motion]
ibatch_c = self.c[:, istep] # [B, nwind, nc_speech]
ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion]
# forward
ibatch_pt, ibatch_mu, ibatch_lv = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion]
debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}")
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
batch_mu.append(ibatch_mu)
batch_lv.append(ibatch_lv)
# prepare data for eval_loss
batch_mu = torch.stack(batch_mu, dim=1) # [B, nstep-1, latent_size]
batch_lv = torch.stack(batch_lv, dim=1) # [B, nstep-1, latent_size]
debug(self.opt, f"[valid] batch_mu = {batch_mu.shape}, batch_lv = {batch_lv.shape}, batch_pt= {batch_pt.shape}")
batch_mu = batch_mu.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_lv = batch_lv.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_pt = batch_pt[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
# evaluate loss
loss, loss_dict = self.eval_losses(batch_pt, batch_gt, batch_mu, batch_lv)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss_dict
def validation(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
batch_pt[:, 0] = self.x[:, 0] # assign first frame
batch_mu = []
batch_lv = []
for istep in range(1, self.nsteps):
ibatch_x = self.x[:, istep] # [B, nc_motion]
ibatch_c = self.c[:, istep] # [B, nwind, nc_speech]
ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion]
# forward
ibatch_pt, ibatch_mu, ibatch_lv = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion]
debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}")
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
batch_mu.append(ibatch_mu)
batch_lv.append(ibatch_lv)
# prepare data for eval_loss
batch_mu = torch.stack(batch_mu, dim=1) # [B, nstep-1, latent_size]
batch_lv = torch.stack(batch_lv, dim=1) # [B, nstep-1, latent_size]
debug(self.opt, f"[valid] batch_mu = {batch_mu.shape}, batch_lv = {batch_lv.shape}, batch_pt= {batch_pt.shape}")
batch_mu = batch_mu.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_lv = batch_lv.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_pt = batch_pt[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
batch_gt = self.x[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
loss, loss_dict = self.eval_losses(batch_pt, batch_gt, batch_mu, batch_lv)
return loss_dict
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
self.eval()
c = batch_cond.float().to(self.device) # (B, nsteps, 16, nc_speech)
nbtach, nstep, *_ = c.shape
with torch.no_grad():
batch_pos = self.netG(self.cond) # B x N x dim_motion
batch_pos += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pos.shape}")
# !! add specific when render & output !!
batch_pos = batch_pos - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pos, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
if save_npy:
# save result
batch_pos = batch_pos.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pos)
print(f"save infer_result shape = {batch_pos.shape} -> {path_save_npy}")
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
# batch_pt[:, 0, 3] = self.x[:, 0, 3] # T-pose + first scale from input data
batch_pt[:, 0] = self.x[:, 0] # T-pose + first scale from input data
for istep in range(1, self.nsteps):
ibatch_z = torch.randn((self.B, self.dim_latent), device=self.device) # [B, dim_latent]
ibatch_c = self.c[:, istep] # [B, nwind, nc_speech]
ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion]
# forward
ibatch_pt = self.netG.sample(ibatch_z, ibatch_x_prev, ibatch_c) # [B, nc_motion]
debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}")
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
# save video
# print(f"testing pt shape = {batch_pt.shape}, gt shape = {self.x.shape}")
self.save_reconstruct_with_gt(batch_pt, self.x,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
@torch.no_grad()
def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device)
batch_pose = torch.zeros(1, 6).to(self.device)
if mean_dict is not None:
batch_shape = self.mean_dict["shape"].reshape(1, 100)
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
else:
batch_shape = torch.zeros(1, 100).to(self.device)
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
# print(f"template verts reshape = {verts.shape}")
return verts, ldmk2d, ldmk3d
def eval_losses(self, batch_pt, batch_gt, batch_mu, batch_lv):
""" Computes the VAE loss function.
pramas:
batch_pt, batch_gt: [B * nsteps, nc_motion]
batch_mu, batch_lv: [B * nsteps, nc_latent]
"""
loss = 0
loss_dict = OrderedDict()
# recon loss
loss_rec = (batch_pt - batch_gt).pow(2).mean()
loss_dict["rec"] = loss_rec.detach()
loss += loss_rec
# kl loss
loss_kl = -0.5 * (1 + batch_lv - batch_mu.pow(2) - batch_lv.exp()).sum().clamp(max=0) # [B*nsteps, ]
loss_kl /= batch_lv.numel()
loss_dict["kl"] = loss_kl.detach()
if self.opt.LOSS.lambda_kl > 0:
loss += loss_kl * self.opt.LOSS.lambda_kl
# velocity loss
batch_pt = batch_pt.reshape(self.B, -1, self.dim_motion)
batch_gt = batch_gt.reshape(self.B, -1, self.dim_motion)
diff_pt = batch_pt[:, 1:, :] - batch_pt[:, :-1, :] # [B, nsteps-2, nc_motion]
diff_gt = batch_gt[:, 1:, :] - batch_gt[:, :-1, :] # (B, nsteps-2, nc_motion)
loss_vel_rec = (diff_pt - diff_gt).pow(2).mean()
loss_dict["vel"] = loss_vel_rec.detach()
if self.opt.LOSS.lambda_vel > 0:
loss += loss_vel_rec * self.opt.LOSS.lambda_vel
# total loss
loss_dict["all"] = loss.detach()
return loss, loss_dict
@torch.no_grad()
def save_reconstruct(self, batch_pdt_pos, raw_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_pos, [B x N x dim_motion]
B, N, *_ = batch_pdt_pos.shape
nbatch_render = 10
# for each batch
for i in range(B):
ipos_pt = batch_pdt_pos[i, ...] # [N x 9]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
# get gt coeff
kpos_mouth_gt= self.pos_mouth[i, k:k+nbatch_render, :] # [nbatch_real, 3]
kidn_gt = self.idn[i, k:k+nbatch_render, :] # [nbatch_real, 100]
kexp_gt = self.exp[i, k:k+nbatch_render, :] # [nbatch_real, 50]
# get exp & cam
kpos_pt = torch.cat([ipos_pt[k:k+nbatch_render, :3], kpos_mouth_gt], dim=1) # [nbatch_real x 6]
kcam_pt = ipos_pt[k:k+nbatch_render, 3:] # [nbatch_real x 3]
# print(f"kidn_gt={kidn_gt.shape}, kexp_gt={kexp_gt.shape}, kpos_pt={kpos_pt.shape}")
# get geometry & render
kgeo_pt, kldmk2d_pt, kldmk3d_pt = self.netF(kidn_gt, kexp_gt, kpos_pt) # [nbatch x 5023 x 3], [nbatch x 68 x 3]
render_pt = self.render_geometry(kgeo_pt, kcam_pt, self.device) # (nbatch_real, 3, 512, 512)
# print(f"testing v_render_pt = {len(v_render_pt)}")
if vis_landmarks:
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, kcam_pt);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
else:
render_pt = render_pt.cpu()
# append each frame
nbatch_real = kpos_pt.size(0)
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# write tmp audio
tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav')
wavfile.write(tmp_audio.name, rate=16000, data=raw_speech)
# save animation
save_images_with_audio(v_render_pt, tmp_audio.name, ipath_save)
@torch.no_grad()
def render_geometry(self, verts, cam=None, device=None):
"""
verts: [N x 5023 x 3]
"""
batch_size = verts.size(0)
if cam is None:
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
# orth_proj
verts_proj = util.batch_orth_proj(verts, cam);
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
# render
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
return images
@torch.no_grad()
def save_reconstruct_with_gt2(self, batch_pdt_pos, batch_tgt_geo, raw_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_pos, [1 x N x 5023 x 3]
# batch_tgt_geo, [1 x N x 5023 x 3]
B, N, *_ = batch_pdt_pos.shape
ipos_pt = batch_pdt_pos[0, ...] # [N x 5023 x 3]
ipos_gt = batch_tgt_geo[0, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{0:02d}.mp4")
v_render_pt = []
v_render_gt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
# split
kpos_pt = ipos_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kpos_gt = ipos_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kpos_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kpos_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kpos_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
else:
render_pt = render_pt.cpu()
render_gt = render_gt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# write tmp audio
tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav')
wavfile.write(tmp_audio.name, rate=16000, data=raw_speech)
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=50, path_audio=tmp_audio.name)
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_pos, batch_tgt_pos, path_save, suffix=""):
# batch_pdt_pos, [B x N x nc_motion=6]
# batch_pdt_pos, [B x N x nc_motion=6]
B, N, *_ = batch_pdt_pos.shape
nbatch_render = 10
# for each batch
for i in range(B):
ipos_pt = batch_pdt_pos[i, ...] # [N x 6]
ipos_gt = batch_tgt_pos[i, ...] # [N x 6]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
# get gt coeff
kpos_mouth_gt= self.pos_mouth[i, k:k+nbatch_render, :] # [nbatch_real, 3]
kidn_gt = self.idn[i, k:k+nbatch_render, :] # [nbatch_real, 100]
kexp_gt = self.exp[i, k:k+nbatch_render, :] # [nbatch_real, 50]
# get exp
kpos_pt = torch.cat([ipos_pt[k:k+nbatch_render, :3], kpos_mouth_gt], dim=1) # [nbatch_real x 6]
kpos_gt = torch.cat([ipos_gt[k:k+nbatch_render, :3], kpos_mouth_gt], dim=1) # [nbatch_real x 6]
# get cam
kcam_pt = ipos_pt[k:k+nbatch_render, 3:] # [nbatch_real x 3]
kcam_gt = ipos_gt[k:k+nbatch_render, 3:] # [nbatch_real x 3]
kcam_pt[:, 0] *= 0.7
kcam_gt[:, 0] *= 0.7
# print(f"kidn_gt={kidn_gt.shape}, kexp_gt={kexp_gt.shape}, kpos_pt={kpos_pt.shape}")
# get geometry
kgeo_pt, *_ = self.netF(kidn_gt, kexp_gt, kpos_pt) # [nbatch x 5023 x 3], [nbatch x 68 x 3]
kgeo_gt, *_ = self.netF(kidn_gt, kexp_gt, kpos_gt) # [nbatch x 5023 x 3], [nbatch x 68 x 3]
# render geometry
render_pt = self.render_geometry(kgeo_pt, kcam_pt, self.device).cpu() # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, kcam_gt, self.device).cpu() # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
nbatch_real = kpos_pt.shape[0]
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# get audio
jvid = self.batch_vid[i]
jstart_frame = self.batch_interv[0][i].numpy()
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + 7 + self.nsteps) / self.opt.DATASET.fps # xxx.yyy min
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
#########################################
def tensor2image(tensor):
# image = tensor.detach().cpu().numpy()
image = tensor.numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2pose_mvae":
from src.nn.audio2pose_mvae import PoseMixtureVAE
netG = PoseMixtureVAE(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
# to GPU
netG.to(f"cuda:{opt.GPUS[0]}")
if len(opt.GPUS) > 1:
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
return netG
def define_FLAME(opt, device):
from src.nn.FLAME import FLAME
model = FLAME(opt.FLAME).to(device)
return model
def define_render(opt, device):
from src.utils.renderer import SRenderY, set_rasterizer
set_rasterizer(opt.RENDER.rasterizer_type)
model = SRenderY(opt.RENDER.image_size,
obj_filename=opt.RENDER.topology_path,
uv_size=opt.RENDER.uv_size,
rasterizer_type=opt.RENDER.rasterizer_type
).to(device)
return model
def define_extractor(opt, device):
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor
-2
View File
@@ -29,13 +29,11 @@ class Audio2Mesh(nn.Module):
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
+233
View File
@@ -0,0 +1,233 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from common.debug import debug
class PoseMixtureVAE(nn.Module):
def __init__(self, opt):
super(PoseMixtureVAE, self).__init__()
self.opt = opt
self.dim_motion = opt.MODEL.dim_motion # 9
self.dim_latent = opt.MODEL.dim_hidden # 64
self.dim_speech = opt.MODEL.dim_speech # 1024
self.nseqR = opt.MODEL.n_lookprevs_motion
self.nseqF = opt.MODEL.n_lookahead_motion
self.num_experts = 6
dim_feat_c = 128
dim_hidden = 256
self.layer_cond = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
nn.BatchNorm2d(self.dim_speech),
nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 4 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 4 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, dim_feat_c, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # dim_feat_c x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Flatten() # dim_feat_c
)
self.encoder = Encoder(self.dim_motion, dim_feat_c, self.dim_latent, dim_hidden, self.nseqR, self.nseqF)
self.decoder = MixedDecoder(self.dim_motion, dim_feat_c, self.dim_latent, dim_hidden, self.nseqR, self.nseqF, self.num_experts)
def forward(self, x, x_prev, c):
""" forward function
parameters:
x : shape = (B x dim_motion)
x_pre: shape = (B x dim_motion)
c : shape = (B x nwind x dim_speech)
return:
y : shape = (B x dim_motion)
"""
debug(self.opt, f"[forward] input x shape = {x.shape}, x_prev shape = {x_prev.shape}")
# condition header
c = torch.unsqueeze(c, dim=1).transpose(1, 3) # (B, 1, nwind, dim_speech) -> (B, dim_speech, nwind, 1)
feat_c = self.layer_cond(c) # (B, 64)
debug(self.opt, f"[forward] transpose c shape = {c.shape}, feac_c shape = {feat_c.shape}")
# encoder
z, mu, logvar = self.encoder(x, x_prev, feat_c)
debug(self.opt, f"[forward] encode z={z.shape}, mu={mu.shape}, logvar={logvar.shape}")
# decoder
pred = self.decoder(z, x_prev, feat_c)
return pred, mu, logvar
def sample(self, z, x_prev, c):
""" forward function
parameters:
z : shape = (B x dim_latent)
x_pre: shape = (B x dim_motion)
c : shape = (B x nwind x dim_speech)
return:
y : shape = (B x dim_motion)
"""
# condition header
c = torch.unsqueeze(c, dim=1).transpose(1, 3) # (B, 1, nwind, dim_speech) -> (B, dim_speech, nwind, 1)
feat_c = self.layer_cond(c) # (B, 64)
debug(self.opt, f"[forward] transpose c shape = {c.shape}, feac_c shape = {feat_c.shape}")
pred = self.decoder(z, x_prev, feat_c)
return pred
class Encoder(nn.Module):
def __init__(self, dim_motion, dim_feat_c, dim_latent, dim_hidden, nseqR, nseqF):
super().__init__()
# Encoder
# Takes pose | condition (n * poses) as input
input_size = dim_motion * nseqF + dim_motion * nseqR + dim_feat_c
self.fc1 = nn.Linear(input_size, dim_hidden)
self.fc2 = nn.Linear(dim_motion * nseqF + dim_hidden, dim_hidden)
self.fc_mu = nn.Linear(dim_motion * nseqF + dim_hidden, dim_latent)
self.fc_logvar = nn.Linear(dim_motion * nseqF + dim_hidden, dim_latent)
def reparameterize(self, mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def forward(self, x, x_prev, feat_c):
"""
x shape = (B, dim_motion)
x_prev shape = (B, dim_motion)
feat_c shape = (B, dim_feat_c)
"""
feat_c = torch.cat((x_prev, feat_c), dim=1) # (B, dim_motion * nseqR + dim_feat_c)
h1 = F.elu(self.fc1(torch.cat((x, feat_c), dim=1))) # (B, dim_hidden)
h2 = F.elu(self.fc2(torch.cat((x, h1), dim=1))) # (B, dim_hidden)
s = torch.cat((x, h2), dim=1) # (B, dim_motion * nseqF + dim_hidden)
mu = self.fc_mu(s) # (B, dim_latent)
logvar = self.fc_logvar(s) # (B, dim_latent)
z = self.reparameterize(mu, logvar) # (B, dim_latent)
return z, mu, logvar
class Decoder(nn.Module):
def __init__(self, dim_motion, dim_feat_c, dim_latent, dim_hidden, nseqR, nseqF):
super().__init__()
# Decoder
# Takes latent | condition as input
input_size = dim_latent + dim_motion * nseqR + dim_feat_c
output_size = nseqF * dim_motion
self.fc4 = nn.Linear(input_size, dim_hidden)
self.fc5 = nn.Linear(dim_latent + dim_hidden, dim_hidden)
self.out = nn.Linear(dim_latent + dim_hidden, output_size)
def forward(self, z, x_prev, feat_c):
"""
z shape = (B, dim_latent)
x_prev shape = (B, dim_motion)
feat_c shape = (B, dim_feat_c)
"""
feat_c = torch.cat((x_prev, feat_c), dim=1) # (B, dim_motion * nseqR + dim_feat_c)
h4 = F.elu(self.fc4(torch.cat((z, feat_c), dim=1))) # (B, dim_hidden)
h5 = F.elu(self.fc5(torch.cat((z, h4), dim=1))) # (B, dim_hidden)
pred = self.out(torch.cat((z, h5), dim=1)) # (B, output_size)
return pred
class MixedDecoder(nn.Module):
def __init__(self, dim_motion, dim_feat_c, dim_latent, dim_hidden, nseqR, nseqF, num_experts):
super().__init__()
input_size = dim_latent + dim_motion * nseqR + dim_feat_c
inter_size = dim_latent + dim_hidden
output_size = nseqF * dim_motion
self.decoder_layers = [(
nn.Parameter(torch.empty(num_experts, input_size, dim_hidden)),
nn.Parameter(torch.empty(num_experts, dim_hidden)),
F.elu,),(
nn.Parameter(torch.empty(num_experts, inter_size, dim_hidden)),
nn.Parameter(torch.empty(num_experts, dim_hidden)),
F.elu,),(
nn.Parameter(torch.empty(num_experts, inter_size, output_size)),
nn.Parameter(torch.empty(num_experts, output_size)),
None,),
]
# init layers
for index, (weight, bias, _) in enumerate(self.decoder_layers):
index = str(index)
torch.nn.init.kaiming_uniform_(weight)
bias.data.fill_(0.01)
self.register_parameter("w" + index, weight)
self.register_parameter("b" + index, bias)
# Gating network
gate_hsize = 64
self.gate = nn.Sequential(
nn.Linear(input_size, gate_hsize),
nn.ELU(),
nn.Linear(gate_hsize, gate_hsize),
nn.ELU(),
nn.Linear(gate_hsize, num_experts),
)
def forward(self, z, x_prev, feat_c):
"""
z shape = (B, dim_latent)
x_prev shape = (B, dim_motion)
feat_c shape = (B, dim_feat_c)
"""
feat_c = torch.cat((x_prev, feat_c), dim=1) # (B, dim_motion + dim_feat_c)
coefficients = F.softmax(self.gate(torch.cat((z, feat_c), dim=1)), dim=1) # (B, num_experts)
feat_o = feat_c
for (weight, bias, activation) in self.decoder_layers:
flat_weight = weight.flatten(start_dim=1, end_dim=2)
mixed_weight = torch.matmul(coefficients, flat_weight)\
.view(coefficients.shape[0], *weight.shape[1:3])
input = torch.cat((z, feat_o), dim=1).unsqueeze(1)
mixed_bias = torch.matmul(coefficients, bias).unsqueeze(1)
out = torch.baddbmm(mixed_bias, input, mixed_weight).squeeze(1)
if activation is not None:
feat_o = activation(out) # (B, dim_hidden)
else:
feat_o = out # (B, output_size)
return feat_o
+36 -47
View File
@@ -577,95 +577,84 @@ def dict_tensor2npy(tensor_dict):
# ---------------------------------- visualization
# end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype = np.int32) - 1
end_list = np.array([17, 22, 27, 31, 36], dtype = np.int32) - 1
def plot_kpts(image, kpts, color = 'r'):
def plot_kpts(image, kpts, color = (255,0,0), color_line=(255,255,255)):
''' Draw 68 key points
Args:
image: the input image
kpt: (68, 3).
'''
if color == 'r':
c = (255, 0, 0)
elif color == 'g':
c = (0, 255, 0)
elif color == 'b':
c = (255, 0, 0)
image = image.copy()
kpts = kpts.copy()
# radius = max(int(min(image.shape[0], image.shape[1])/200), 1)
radius = 1
for i in range(kpts.shape[0]):
st = kpts[i, :2]
if kpts.shape[1]==4:
if kpts[i, 3] > 0.5:
c = (0, 255, 0)
else:
c = (0, 0, 255)
# draw cicle
image = cv2.circle(image,(int(st[0]), int(st[1])), radius, c, -1)
# draw line
if i not in end_list:
ed = kpts[i + 1, :2] if i != 67 else kpts[60, :2]
ed = kpts[36, :2] if i == 41 else ed
ed = kpts[42, :2] if i == 47 else ed
image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), (255, 255, 255), radius)
image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), color_line, radius)
# draw cicle
image = cv2.circle(image,(int(st[0]), int(st[1])), radius, color, -1)
return image
def plot_verts(image, kpts, color = 'r'):
def plot_verts(image, kpts, color = (255,0,0)):
''' Draw 68 key points
Args:
image: the input image
kpt: (68, 3).
'''
c = (0, 0, 0)
c = (255, 0, 0) if color == 'r' else c
c = (0, 255, 0) if color == 'g' else c
c = (0, 0, 255) if color == 'b' else c
c = (0, 255, 255) if color == 'y' else c
image = image.copy()
for i in range(kpts.shape[0]):
st = kpts[i, :2]
image = cv2.circle(image,(int(st[0]), int(st[1])), 1, c, -1)
image = cv2.circle(image,(int(st[0]), int(st[1])), 1, color, -1)
return image
def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = 'g', isScale=True, gt_color = 'r'):
def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = (0, 255, 0), isScale=True, color_gt = (255, 0, 0)):
# visualize landmarks
vis_landmarks = []
images = images.cpu().numpy()
predicted_landmarks = landmarks.detach().cpu().numpy()
if gt_landmarks is not None:
gt_landmarks_np = gt_landmarks.detach().cpu().numpy()
ldmks_pt = landmarks.detach().cpu().numpy()
ldmks_gt = gt_landmarks.detach().cpu().numpy() if gt_landmarks is not None else None
vis_landmarks = []
for i in range(images.shape[0]):
image = images[i]
image = image.transpose(1,2,0)[:,:,[2,1,0]].copy(); image = (image*255)
image = images[i].transpose(1,2,0)[:,:,[2,1,0]].copy()
image = image*255
# if landmarks is scale
ildmks_pt = ldmks_pt[i]
if isScale:
predicted_landmark = predicted_landmarks[i]
predicted_landmark[...,0] = predicted_landmark[...,0]*image.shape[1]/2 + image.shape[1]/2
predicted_landmark[...,1] = predicted_landmark[...,1]*image.shape[0]/2 + image.shape[0]/2
else:
predicted_landmark = predicted_landmarks[i]
ildmks_pt[...,0] = ildmks_pt[...,0]*image.shape[1]/2 + image.shape[1]/2
ildmks_pt[...,1] = ildmks_pt[...,1]*image.shape[0]/2 + image.shape[0]/2
#
if predicted_landmark.shape[0] == 68:
image_landmarks = plot_kpts(image, predicted_landmark, color)
if gt_landmarks is not None:
image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color)
if ildmks_pt.shape[0] == 68:
image_landmarks = plot_kpts(image, ildmks_pt, color, color_line=color)
else:
image_landmarks = plot_verts(image, predicted_landmark, color)
if gt_landmarks is not None:
image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color)
image_landmarks = plot_verts(image, ildmks_pt, color, color_line=color)
# if have landmarks gt
if ldmks_gt is not None:
ildmks_gt = ldmks_gt[i]
if isScale:
ildmks_gt[...,0] = ildmks_gt[...,0]*image.shape[1]/2 + image.shape[1]/2
ildmks_gt[...,1] = ildmks_gt[...,1]*image.shape[0]/2 + image.shape[0]/2
if ildmks_gt.shape[0] == 68:
image_landmarks = plot_kpts(image_landmarks, ildmks_gt, color_gt, color_line=color_gt)
else:
image_landmarks = plot_verts(image_landmarks, ildmks_gt, color_gt, color_line=color_gt)
vis_landmarks.append(image_landmarks)
+11 -14
View File
@@ -14,7 +14,6 @@ from src.config import config as opt
from src.config import update_config
from src.losses.metrics import MeanDictMetric
# from common.vis.visualizer import Visualizer
from torch.utils.tensorboard import SummaryWriter
@@ -47,9 +46,9 @@ def logger_loss(logger, epoch, batch, loss_dict):
msg_loss = "".join([f" {k}= {v:0.5f} " for k,v in loss_dict.items()])
logger.info(msg_head + msg_loss)
def plot_loss(visor, iter, loss_dict):
def plot_loss(visor, iter, loss_dict, suffix="train"):
for k,v in loss_dict.items():
visor.add_scalar(f"loss/loss_{k}", v, iter)
visor.add_scalar(f"{suffix}/loss_{k}", v, iter)
if __name__ == "__main__":
@@ -109,26 +108,24 @@ if __name__ == "__main__":
# update learning_rate
train_metric.reset()
if opt.TRAIN.apply_update_parameters:
model.update_parameters(epoch)
for i, ibatch_data in enumerate(train_loader):
train_loss_dict = model.training(ibatch_data) # forward and backward
train_loss_dict = model.training(ibatch_data, epoch, i) # forward and backward
train_metric.update(train_loss_dict)
# print logger
if (i+1) % opt.FREQ.batch_print == 0 and epoch % opt.FREQ.epoch_print == 0:
logger_loss(logger, epoch, i, train_loss_dict)
plot_loss(visor, epoch + (i/len(train_loader)), train_loss_dict)
plot_loss(visor, epoch + (i/len(train_loader)), train_loss_dict, suffix="train")
# log toatl of each epoch
train_loss_dict = train_metric.compute_to_dict() # compute mean value
logger_loss(logger, epoch, "mean", train_loss_dict)
################ upate learning rate
model.update_learning_rate(train_loss_dict["all"])
if opt.TRAIN.apply_update_parameters:
model.update_parameters(epoch)
################ validation
if opt.TRAIN.apply_validation and (epoch+1) % opt.FREQ.epoch_valid == 0:
logger.info("validation...")
@@ -147,19 +144,19 @@ if __name__ == "__main__":
# print total
valid_loss_dict = valid_metric.compute_to_dict() # compute mean value
logger_loss(logger, epoch, "mean", valid_loss_dict)
plot_loss(visor, epoch+1, valid_loss_dict)
plot_loss(visor, epoch+1, valid_loss_dict, suffix="valid")
################ upate learning rate by validataion
model.update_learning_rate(valid_loss_dict["all"])
################# testing
if opt.TRAIN.apply_testing and (epoch+1) % opt.FREQ.epoch_test == 0:
logger.info("Test...")
for _, ibatch_test in enumerate(test_loader):
model.testing(batch_input=ibatch_test, cur_epoch=epoch) # forward and backward
model.testing(batch_input=ibatch_test, idx_epoch=epoch) # forward and backward
break
################# save epoch
if (epoch + 1) % opt.FREQ.epoch_save == 0:
logger.info(f"saving the model at the end of epoch {epoch:04d}, iters {i:06d}")
model.save_networks(epoch+1)