update Actor6

This commit is contained in:
liangsen committed 2022-05-27 16:23:49 +08:00
1 parent dac314c9a5
commit e9b2b238b2
35 files changed
+1223 -694

No files matched your search

+16 -13
View File
@@ -29,21 +29,24 @@ class Logger(logging.Logger):
def __init__(self, path_output, path_config=None, postfix=None, level=logging.NOTSET ):
logging.Logger.__init__(self, '', level)
# logger filename suffix
suffix = f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}"
if postfix is not None:
suffix += "_" + str(postfix)
# make dir
basename = path_config.name.split(".")[0] if path_config is not None else "log"
if postfix is None:
postfix = f"{datetime.datetime.now().strftime('%Y%m%d-%HH%MM%SS')}"
self.path_output = Path(path_output).joinpath(basename, postfix)
self.path_output.mkdir(parents=True, exist_ok=True)
# copy config
dst = self.path_output.joinpath(path_config.name)
shutil.copyfile(src=path_config, dst=dst)
# make dir & set filename
if path_config is not None:
basename = path_config.name.split(".")[0]
self.path_output = Path(path_output).joinpath(basename, suffix)
self.path_output.mkdir(parents=True, exist_ok=True)
filename = self.path_output.joinpath(f"logger.log")
shutil.copyfile(src=path_config, dst=self.path_output.joinpath(path_config.name))
else:
self.path_output = Path(path_output)
self.path_output.mkdir(parents=True, exist_ok=True)
filename = self.path_output.joinpath(suffix + ".log")
# add file hander
filename = self.path_output.joinpath(f"logger.log")
fHander = logging.FileHandler(filename)
fFormat = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
fHander.setFormatter(fFormat)
@@ -54,6 +57,7 @@ class Logger(logging.Logger):
cFormat = ColoredFormatter( RESET_SEQ+"[%(asctime)s] %(message)s"+RESET_SEQ )
cHander.setFormatter(cFormat)
self.addHandler(cHander)
def setContext(self, key, value):
self.context[key] = value
@@ -72,7 +76,6 @@ class Logger(logging.Logger):
super(Logger, self).error(e[1].message)
class ColoredFormatter(logging.Formatter):
def __init__(self, msg, use_color = True):
logging.Formatter.__init__(self, msg, datefmt='%Y-%m-%d %H:%M:%S')
+1 -3
View File
@@ -14,8 +14,6 @@ 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
@@ -64,7 +62,7 @@ if __name__ == '__main__':
# cond shape = torch.Size([20, 35, 16, 1024]), batch_otput shape = (20, 35, 5023, 3)
torch.onnx.export(
netG.module, # model being run
netG, # model being run, netG.module,
batch_input,
str(path_onnx),
export_params=True,
@@ -1,31 +0,0 @@
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
isTrain: False
MODEL:
name: 'audio2mesh_ar'
name_netG: "audio2mesh_ar"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2meshAR_CN_20220314/20220316-23H56M06S"
load_epoch: 50
DATASET:
fps: 50
sr: 16000
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
TRAIN:
apply_testing: True
apply_validation: True
@@ -1,4 +1,4 @@
GPUS: '7'
GPUS: '6'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -6,14 +6,9 @@ DEBUG: False
verbose: False
isTrain: False
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh2'
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
@@ -21,25 +16,26 @@ MODEL:
num_vertices: 5023
pretrain: True
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220321-17H42M19S"
# load_epoch: 100
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_actor2_closure/20220326-12H43M01S"
load_epoch: 25
# 1h,
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220522-10H56M38SNone"
# load_epoch: 55
# 1.5h
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220525-07H18M45S"
load_epoch: 15
DATASET:
fps: 50
sr: 16000
# name: "motion_live"
name: "motion_eval"
name_train: "motion_live"
name_valid: "motion_eval"
root: './data/Actor6/Actor6-raw-processing2-1h'
path_mean_dict: './data/Actor6/mean_deca_coeff_Actor6_processing2.npy'
root: './data/Actor2/Actor2-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
@@ -49,5 +45,6 @@ TRAIN:
apply_testing: True
apply_validation: True
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
@@ -1,57 +0,0 @@
GPUS: '0'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
isTrain: False
MODEL:
# name: 'audio2mesh'
name: 'audio2mesh_specific'
# name_netG: "audio2mesh_resnet"
name_netG: "audio2mesh"
# name_header: "resnet50" # "resnet50", "resnet34",
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220217-17H36M22S"
load_epoch: 115
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220220/20220223-22H17M02S"
# load_epoch: 60
DATASET:
fps: 50
sr: 16000
name: "motion_live"
root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Obama/processing'
# path_mean_dict: './data/DECA_obama_mean.npy'
path_mean_dict: './data/DECA_obama_mean_wf.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
TRAIN:
lr: 0.0001
batch_size: 64
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: [50, 100, 200]
lr_policy: 'plateau'
@@ -1,83 +0,0 @@
GPUS: '4'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9940
vsdm_ncol: 4
vsdm_env: "audio2mesh-ar-actor1-3h-1100"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh_ar'
name_netG: "audio2mesh_ar"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220225-19H08M53S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
flip: False
shifting_speed: True
root: './data/Actor1/Actor1-raw-3h' # 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
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
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: [50, 100]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 200
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 100
@@ -1,84 +0,0 @@
GPUS: '2'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-ar-actor2-110"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh_ar'
name_netG: "audio2mesh_ar"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220225-19H08M53S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
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: [50, 100]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 100
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 10
@@ -1,4 +1,4 @@
GPUS: '0'
GPUS: '8'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -6,43 +6,40 @@ DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-actor2-5h-test"
vsdm_env: "audio2mesh-actor6-smile"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 2
epoch_test: 1
batch_print: 20
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
# 1h, rec-vel, load_epoch 20
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220525-07H18M45S"
load_epoch: 45
DATASET:
fps: 50
sr: 16000
name: "motion_live"
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
root: './data/Actor6/Actor6-raw-processing2-2h'
path_mean_dict: './data/Actor6/mean_deca_coeff_Actor6_processing2.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
@@ -53,36 +50,40 @@ DATASET:
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 64
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
apply_lr_scheduler: True
apply_update_parameters: True
optimizer: 'Adam'
optimizer: 'SGD'
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]
# nesterov: True
# lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 100
lr_step_gamma: 0.5
lr_policy: 'multistep'
lr_milestones: [10, 30, 50]
resume: False
reset_lr: True
resume_suffix: "20220524-21H54M38S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["all", "rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_vel_geo: 100
lambda_rec_ldmk: 1
lambda_closure_x: 1
lambda_closure_y: 1
@@ -1,87 +0,0 @@
GPUS: '2'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9950
vsdm_ncol: 4
vsdm_env: "audio2mesh-actor2-no-clousure"
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: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220314-15H41M13S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
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: 100
LOSS:
names: ["all", "rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_ldmk: 0
lambda_closure_x: 0
lambda_closure_y: 0
@@ -1,83 +0,0 @@
GPUS: '2'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-ss-actor2-5h-1-01"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh_ss'
name_netG: "audio2mesh_ss"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H10M14S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
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: 100
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w", "rec_code"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_code: 0.1
@@ -1,81 +0,0 @@
GPUS: '6'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9900
vsdm_ncol: 4
vsdm_env: "audio2mesh-resnet-en-weight-101"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh'
name_netG: "audio2mesh_resnet"
name_header: "resnet101" # "resnet50", "resnet34",
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S"
load_epoch: 155
DATASET:
fps: 50
sr: 16000
name: "motion_live"
root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Obama/processing'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.00001
batch_size: 64
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: [50, 100]
# lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220211-16H54M11S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 10
@@ -1,83 +0,0 @@
GPUS: '3'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9920
vsdm_ncol: 4
vsdm_env: "audio2mesh-en-velocity-100-2"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220220/20220225-18H53M05S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
flip: False
shifting_speed: False
root: './data/obama-raw-deca-8h-50fps' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Obama/processing'
path_mean_dict: './data/DECA_obama_mean_wf.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
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: [50, 100]
lr_policy: 'plateau'
resume: True
reset_lr: False
resume_suffix: "20220309-19H52M04S"
epoch_begin: 25 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 100
-1
View File
@@ -78,7 +78,6 @@ def infer_one(path_audio, model, processor, extractor, save_npy):
print(f"after convert window cond shape = {cond.shape}")
# self.data = self.data[:, 7:7+nseq, :]
# save trim wav
path_audio_pad_trim = Path(opt.OUTPUT_DIR).joinpath(f'{path_audio.stem}_input_pad_trim.wav')
wavfile.write(str(path_audio_pad_trim), rate=16000, data=raw_speech)
+12 -9
View File
@@ -56,26 +56,26 @@ if __name__ == "__main__":
# 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/audio_007_008.wav")
# path_audio = Path("data/bank-demo.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor4/processing/4R3A0024/audio/audio_trim_60_60s.wav")
# path_audio = Path("data/test/ali_test_222.wav")
# acotr 5
# path_audio = Path("/ssdata1/lsen/DATA/Actor5/processing/4R3A0071/audio/audio_trim_60_60s.wav")
# path_audio = Path("/ssdata1/lsen/DATA/Actor5/smile/4R3A0071/audio/audio_trim_60_60s.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/tts-scenes/tts-scene-1.wav")
path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/tts-scenes/tts-scene-1.wav")
# path_audio = Path("/ssdata1/lsen/CODE/audio-to-motion/data/test/ali_test_new.wav")
path_folder = Path("./data/test/tts-scenes")
opt.OUTPUT_DIR = path_folder.joinpath("inference_video_actor5_with_npy")
opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
# path_folder = Path("./data/test/tts-scenes")
# opt.OUTPUT_DIR = path_folder.joinpath("inference_video_actor5_with_npy")
# opt.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
# load raw speech
raw_speech, sample_rate = torchaudio.load(path_audio)
raw_speech = raw_speech.numpy()
# raw_speech = raw_speech.numpy()
print(f"raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech[0])/sample_rate)}")
@@ -87,6 +87,8 @@ if __name__ == "__main__":
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)}")
else:
raw_speech = raw_speech.numpy()
# padding to
len_align = (raw_speech.shape[0] // (16000 // 50) ) * (16000 // 50)
@@ -137,4 +139,5 @@ if __name__ == "__main__":
# inference
path_save = f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}"
model.infer(cond, raw_speech, path_save)
model.infer(cond, raw_speech[np.newaxis, :], path_save)
+19 -8
View File
@@ -6,6 +6,8 @@ from pathlib import Path
import torch.nn.functional as F
from scipy.signal import savgol_filter
from scipy.io import wavfile
import torch
import torchaudio
@@ -41,7 +43,8 @@ if __name__ == "__main__":
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
device = torch.device(f'cuda:6') # get device name: CPU or GPU
# logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
@@ -56,8 +59,11 @@ if __name__ == "__main__":
# fID = "BU6A9965"
# ipath_data = Path(f"/mfs/lsen/DATA/Actor3/processing/{fID}/")
fID = "4R3A0071"
ipath_data = Path(f"/ssdata1/lsen/DATA/Actor5/processing/{fID}/")
fID = "4R3A0139"
actor="Actor6"
sub_folder = "processing2" # smile, processing, processing2
ipath_data = Path(f"/ssdata1/lsen/DATA/{actor}/{sub_folder}/{fID}/") # processing
ipath_audio = ipath_data.joinpath("audio/audio_trim.wav")
# laod motion
@@ -84,12 +90,12 @@ if __name__ == "__main__":
# 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)}")
# 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)}")
nwinds_beg = 60
nwinds_end = 120
nwinds_beg = 0
nwinds_end = 60
data_motion = torch.from_numpy(data_motion[np.newaxis, 50*nwinds_beg:50*nwinds_end, :]) # (1, 3000, 53)
raw_speech = raw_speech[nwinds_beg *sample_rate : nwinds_end * sample_rate]
@@ -126,5 +132,10 @@ if __name__ == "__main__":
model = create_model(opt, logger)
model.setup(opt) # load model
# save trim wav
path_audio_pad_trim = Path(opt.OUTPUT_DIR).joinpath(f'{ipath_audio.stem}_input_pad_trim.wav')
wavfile.write(str(path_audio_pad_trim), rate=16000, data=raw_speech)
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)
@@ -27,9 +27,9 @@ if __name__ == "__main__":
# load data
device = torch.device("cuda:4")
pid = "AA7A9568" # "2021-P22", actor-2HD
pid = "4R3A0071" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor2/processing")
path_root = Path("/ssdata1/lsen/DATA/Actor5/smile")
path_data = path_root.joinpath(pid)
@@ -37,7 +37,7 @@ if __name__ == "__main__":
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")
path_audio = path_data.joinpath("audio/audio_trim_60_60s.wav")
# data_pos = np.load(path_pos)[:] # N x 6
# data_idn = np.load(path_idn) # N x 100
+12 -4
View File
@@ -28,17 +28,17 @@ class ImagesDataset(Dataset):
if __name__ == "__main__":
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
vpath_videos = sorted(path_data.glob("*"))
path_data = Path("/ssdata1/lsen/DATA/Actor5/processing")
vpath_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:1"
device = "cuda:7"
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):
for i, ipath_item in enumerate(vpath_videos[16:]):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
@@ -49,9 +49,17 @@ if __name__ == "__main__":
ipath_frame = ipath_item.joinpath("frames")
ipath_ldmks.mkdir(parents=True, exist_ok=True)
# check
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
if num_frame == num_ladmk:
print(f"\n Skip: have already done!")
continue
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
+86
View File
@@ -0,0 +1,86 @@
import numpy as np
from pathlib import Path
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
# fid = "4R3A0071"
fid = '4R3A0110'
path_root = Path("/ssdata1/lsen/DATA/Actor6/processing")
# path_save = Path("./data/Actor5/DECA_Actor5_mean_smile.npy")
path_save = Path("./data/Actor6/DECA_Actor6_mean.npy")
path_save.parent.mkdir(parents=True, exist_ok=True)
logger = Logger(path_save.parent, postfix="mean_coeff")
path_data = path_root.joinpath(fid)
path_coeff = path_data.joinpath("DECA_coeff")
vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False)
logger.info(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 > 2000: 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)
logger.info(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}")
logger.info(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}")
logger.info(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}")
logger.info(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}")
logger.info(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}")
logger.info(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}")
logger.info(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)
logger.info("save to --> ", path_save)
logger.info(f"mean deca = \n {mean_DECA}")
+160
View File
@@ -0,0 +1,160 @@
from pathlib import Path
import json
import os
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == '__main__':
# path_raw = Path("/ssdata1/cf/data/raw/actor06/20220517")
path_raw = Path("/ssdata1/cf/data/raw/actor06/20220519")
path_root = Path("/ssdata1/lsen/DATA/Actor6/processing2")
path_root.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_root)
# get all videos
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False)
logger.info(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
logger.info(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if i > 0: continue
# if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath(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:
logger.info(f"\n Skip: have already done!")
continue
# convert image
ipath_item_rotation = ipath_video.joinpath("video_raw_rotation.mp4")
if not ipath_item_rotation.exists():
cmd = f"ffmpeg -i {str(ipath_item)} -vf 'transpose=1' {str(ipath_item_rotation)}"
logger.info(cmd)
os.system(cmd)
# load video
# video = VideoFileClip(str(ipath_item))
video = VideoFileClip(str(ipath_item_rotation))
logger.info(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:
logger.info("\nERROR: audio info is None")
continue
durations += video.duration
logger.info(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_rotation)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
# os.system(cmd)
# logger.info(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)
logger.info(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()))
# logger.info(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:
logger.info("FPS NOT = 50!! ")
# save sub video fps=50
ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists():
logger.info("\nERROR: ipath_video_sub.exists()")
continue
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
logger.info(f"save video > {ipath_video_sub}")
# reload video
video.close()
video = VideoFileClip(str(ipath_video_sub))
logger.info(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:
logger.info("\nERROR: audio info is None")
continue
logger.info(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)
logger.info(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# logger.info(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)
# logger.info(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)
logger.info(info)
logger.info(f"save video info in -> {ipath_infor}\n")
# save trim video
logger.info(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
@@ -0,0 +1,153 @@
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:8"
# 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("/ssdata1/lsen/DATA/Actor6/processing2")
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())
+100
View File
@@ -0,0 +1,100 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path("/ssdata1/lsen/DATA/Actor6/processing2")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
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,81 @@
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("/ssdata1/lsen/DATA/Actor6/processing2")
vpath_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
device = "cuda:8"
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):
if not ipath_item.is_dir(): continue
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)
# check
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_ladmk = len(list(ipath_ldmks.glob("*.txt")))
if num_frame == num_ladmk:
print(f"\n Skip: have already done!")
continue
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,169 @@
import json
import numpy as np
from pathlib2 import Path
import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
# path_data = Path("/mfs/lsen/DATA/Actor4/smile")
path_data = Path("/ssdata1/lsen/DATA/Actor6/processing")
path_save = Path('data/Actor6/Actor6-raw-1h') # processing
# path_save = Path('data/Actor5/Actor5-smile-1h') # processing
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
logger.info(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])
# logger.info(f"vids total= {vids}")
# # actor5 raw
vid_test = set(["4R3A0110", "4R3A0112", "4R3A0113"])
vid_valid = set(["4R3A0110", "4R3A0112", "4R3A0113"])
vid_train = vids - vid_test - vid_valid
# actor5 smile
# vid_test = set(["4R3A0071"])
# vid_valid = set(["4R3A0071"])
# vid_train = set(["4R3A0070", "4R3A0072", "4R3A0073", "4R3A0074", "4R3A0075"])
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
list_train, list_valid, list_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
logger.info(f"\n\tprocessing 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():
logger.info(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
logger.info(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']
logger.info(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
logger.info(f"motion = {data_motion.shape}")
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
logger.info(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()
logger.info(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
list_train.append(vid)
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
list_valid.append(vid)
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
list_test.append(vid)
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})")
logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})")
logger.info(f"actual train ID: > {list_train} ")
logger.info(f"actual valid ID: > {list_valid} ")
logger.info(f"actual test ID: > {list_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)
logger.info(f"--> {path_save}")
@@ -0,0 +1,149 @@
import json
import numpy as np
from pathlib2 import Path
import torchaudio
import os, sys
sys.path.insert(0, os.getcwd())
from common.logger import Logger
if __name__ == "__main__":
subfolder = "processing" # processing, smile, body
path_data = Path(f"/ssdata1/lsen/DATA/Actor5/{subfolder}")
path_save = Path(f'data/Actor5/data-render-{subfolder}-1h')
path_save.mkdir(parents=True, exist_ok=True)
# set logging
logger = Logger(path_save)
# get files
v_dir_videos = sorted(path_data.glob("*"))
logger.info(f"Have {len(v_dir_videos)} dir files")
vids = set([ipath.stem for ipath in v_dir_videos])
logger.info(f"vids total= {vids}")
# # # actor5 raw
# vid_test = set(["4R3A0063", "4R3A0071"])
# vid_valid = set(["4R3A0063", "4R3A0071"])
# vid_train = vids - vid_test - vid_valid
# actor5 smile
if subfolder == "smile":
vid_test = set(["4R3A0071"])
vid_valid = set(["4R3A0071"])
vid_train = set(["4R3A0070", "4R3A0072", "4R3A0073", "4R3A0074", "4R3A0075", "4R3A0076"])
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
else:
vid_test = set(["4R3A0063", "4R3A0071"])
vid_valid = set(["4R3A0063", "4R3A0071"])
vid_train = vids - vid_test - vid_valid
logger.info(f"vid test= {vid_test} \nvalid= {vid_valid}")
logger.info(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
list_train, list_valid, list_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
logger.info(f"\n\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff") # DECA coeff of shape/exp/light
ipath_frame = ipath_data.joinpath("frames_crop_512") # cropped image 512x512
ipath_ldmks = ipath_data.joinpath("frames_crop_ldmks_512") # cropped landmarks within 512x512
ipath_parse = ipath_data.joinpath("frames_crop_parse_512") # cropped mask
# check info existing
if not ipath_info.exists():
logger.info(f"NOT existing {ipath_info}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
assert fps == 50, "fps should be 50"
logger.info(f"info={info}, duration = {nframes/fps}")
# check files total exists
num_coeff = len(list(ipath_coeff.glob("*.npy")))
num_frame = len(list(ipath_frame.glob("*.jpg")))
num_ldmks = len(list(ipath_ldmks.glob("*.txt")))
num_parse = len(list(ipath_parse.glob("*.npy")))
if (num_coeff != nframes) or (num_frame != nframes) or (num_ldmks != nframes) or (num_parse != nframes):
logger.info(f"num of ipath_coeff ({num_coeff}) shoud be {nframes} > {ipath_coeff}")
logger.info(f"num of ipath_frame ({num_frame}) shoud be {nframes} > {ipath_frame}")
logger.info(f"num of ipath_ldmks ({num_ldmks}) shoud be {nframes} > {ipath_ldmks}")
logger.info(f"num of ipath_parse ({num_parse}) shoud be {nframes} > {ipath_parse}")
continue
# load coeff
ipath_feat_coeff = ipath_data.joinpath("audio/feat_DECA_trim.npy")
data_coeff = np.load(ipath_feat_coeff) # (nframe, 236)
data_coeff = data_coeff.astype(np.float16) # convert float16
if vid in vid_train:
durations_train += nframes/fps
list_train.append(vid)
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
if vid in vid_valid:
durations_valid += nframes/fps
list_valid.append(vid)
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
if vid in vid_test:
durations_test += nframes/fps
list_test.append(vid)
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"path_data": str(ipath_data),
"data_coeff": data_coeff
}
logger.info(f"Total frames: data_train ({durations_train/60:.2f} min) ({durations_train/3600:.2f} h) , ids = ({len(data_train)})")
logger.info(f"Total frames: data_valid ({durations_valid/60:.2f} min) ({durations_valid/3600:.2f} h) , ids = ({len(data_valid)})")
logger.info(f"Total frames: data_test ({durations_test/60:.2f} min) ({durations_test/3600:.2f} h) , ids = ({len(data_test)})")
logger.info(f"actual train ID: > {list_train} ")
logger.info(f"actual valid ID: > {list_valid} ")
logger.info(f"actual test ID: > {list_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)
logger.info(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.
+12
View File
@@ -8,6 +8,7 @@ from scipy.signal import savgol_filter
# common
from common.resampling import resample_by_nsteps
from audiomentations import Compose, AddGaussianNoise, TimeStretch, PitchShift, Shift
class MotionLiveDataset(Dataset):
@@ -42,6 +43,10 @@ class MotionLiveDataset(Dataset):
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
self.audio_augment = Compose([
AddGaussianNoise(min_amplitude=0.001, max_amplitude=0.015, p=0.2),
PitchShift(min_semitones=-4, max_semitones=4, p=0.2),
])
def __len__(self):
@@ -72,6 +77,7 @@ class MotionLiveDataset(Dataset):
nframe = data_motion.shape[0]
nsegmt = data_speech.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]
@@ -109,6 +115,12 @@ class MotionLiveDataset(Dataset):
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
# audio augment
data_speech = self.audio_augment(samples=data_speech, sample_rate=self.sr )
# print(f"after augment data speech = {data_speech.shape}, before nsegmt = {nsegmt}, nframe={nframe}")
# assert data_speech.shape[0] == (end_segmt-beg_segmt), f"after augment data speech {data_speech.shape} should = {end_segmt-beg_segmt}"
# 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')
+2 -1
View File
@@ -145,7 +145,8 @@ class Base():
"""
for scheduler in self.schedulers:
if self.opt.TRAIN.lr_policy == 'plateau':
scheduler.step(cur_loss)
if cur_loss is not None:
scheduler.step(cur_loss)
else:
scheduler.step()
+25 -9
View File
@@ -2,6 +2,8 @@
import numpy as np
from collections import OrderedDict
import pickle
import torch
import torch.nn as nn
from pathlib import Path
@@ -61,12 +63,21 @@ class Audio2MeshModel(Base):
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)
# save template mesh
path_deca_mean = Path(path_deca_mean)
path_temp_pkl = path_deca_mean.parent.joinpath(path_deca_mean.stem + "_data_template_mesh.pkl")
if not path_temp_pkl.exists(): # load from cache
self.logger.info(f"Load template mesh from raw 3DMM... (!NOT FOUND {path_temp_pkl}) ")
template_mesh = self.temp_verts_specific.cpu().numpy() # verts: (1 x 1 x 5023 x 3)
# save template data
with open(str(path_temp_pkl), 'wb') as f:
pickle.dump(template_mesh, f)
# self.temp_verts_specific = np.load("/ssdata1/lsen/CODE/audio-to-motion/data/Actor4/template_meiyan2.npy") # (5023, 3)
# self.temp_verts_specific = self.temp_verts_specific.reshape(1, 1, 5023, 3)
# self.temp_verts_specific = torch.from_numpy(self.temp_verts_specific).to(self.device)
# save to
# loss function
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
self.loss_func_l1 = nn.L1Loss(reduction="none")
@@ -184,22 +195,28 @@ class Audio2MeshModel(Base):
def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True):
"""
batch batch = [B, nsegment]
"""
print(f"batch_speech.shape = {batch_speech.shape}")
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)
vert = vert - self.temp_verts + self.temp_verts_specific # add template
# add a dimensions
# if batch_speech.dims == 1:
print(f"batch_speech shape = {batch_speech}")
batch_speech = batch_speech[np.newaxis, :] # (B, nsegmt)
batch_speech = batch_speech[np.newaxis, :] # (B, nsegmt)
print(f"batch_speech shape = {batch_speech.shape}") # (1, nsegmt)
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}")
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}") # 1, 3000, 5023, 3
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
@@ -427,7 +444,7 @@ class Audio2MeshModel(Base):
# write video
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
write_video(v_render_pt, batch_speech, ipath_save, fps=50)
write_video(v_render_pt, batch_speech[i], ipath_save, fps=50)
self.logger.info(f"save video to -> {str(ipath_save)}")
@@ -555,7 +572,6 @@ def define_FLAME(opt, device):
return model
def define_render(opt, device):
from src.utils.renderer import SRenderY, set_rasterizer
+1
View File
@@ -167,6 +167,7 @@ class Audio2motionLiveModel(Base):
loss = 0
loss_dict = {}
batch_pdt_exp = batch_pdt[..., :50]
batch_pdt_pos = batch_pdt[..., 50:]
+1
View File
@@ -119,6 +119,7 @@ class Audio2motionLive2Model(Base):
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)
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
-1
View File
@@ -51,7 +51,6 @@ class Audio2MotionVOCA(nn.Module):
nn.Linear(in_features=2048, out_features=128) # 50,
)
# output
self.decoder = nn.Sequential(
nn.Linear(in_features=128, out_features=self.dim_motion),
+5 -4
View File
@@ -110,7 +110,7 @@ if __name__ == "__main__":
train_metric.reset()
if opt.TRAIN.apply_update_parameters:
model.update_parameters(epoch)
model.update_learning_rate()
# model.update_learning_rate()
for i, ibatch_data in enumerate(train_loader):
@@ -147,9 +147,9 @@ if __name__ == "__main__":
logger_loss(logger, epoch, "mean", valid_loss_dict)
plot_loss(visor, epoch+1, valid_loss_dict, suffix="valid")
################ upate learning rate by validataion
# if opt.TRAIN.apply_lr_scheduler:
# model.update_learning_rate(valid_loss_dict["all"])
############### upate learning rate by validataion
if opt.TRAIN.apply_lr_scheduler:
model.update_learning_rate(valid_loss_dict["all"])
################# testing
if opt.TRAIN.apply_testing and (epoch+1) % opt.FREQ.epoch_test == 0:
@@ -162,3 +162,4 @@ if __name__ == "__main__":
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)