From 3a15011f4d39b56432c9df4b5ddfd5bae4486b91 Mon Sep 17 00:00:00 2001 From: Sen Liang Date: Sun, 24 Apr 2022 14:06:52 +0800 Subject: [PATCH] update audduio2pose v1.0 --- common/animation.py | 84 ++++ .../infer_audio2mesh_CN_20220312.yaml | 27 +- .../infer_audio2mesh_CN_20220322.yaml | 13 +- .../train_audio2mesh_CN_20220312.yaml | 32 +- .../train_audio2pose_luox_20220415.yaml | 94 +++++ infer_one_live.py | 35 +- infer_one_wt_gt.py | 62 +-- scripts/Actor2Data/run-01-prepare-data.py | 135 ++++--- scripts/Actor2Data/run-21-features-3dmm.py | 6 +- .../run-41-train-dict-data-raw-deca.py | 34 +- scripts/Actor4Data/run-00-mean-coeff.py | 78 ++++ scripts/Actor4Data/run-01-prepare-data.py | 139 +++++++ .../Actor4Data/run-20-deca-reconstruction.py | 157 ++++++++ scripts/Actor4Data/run-21-features-3dmm.py | 99 +++++ .../Actor4Data/run-22-deca-render-video.py | 103 +++++ scripts/Actor4Data/run-30-dectect-landmark.py | 73 ++++ .../run-41-train-dict-data-raw-deca.py | 188 +++++++++ scripts/Actor4Data/stack_video.py | 66 +++ scripts/Actor4Data/valid-test-train.json | 0 scripts/LuoXData/run-31-features-3dmm-pose.py | 3 - scripts/Obama/run-51-features-3dmm-pose.py | 27 +- .../Obama/run-53-train-dict-data-raw-pose.py | 184 +++++++++ src/config.py | 18 +- src/datasets/motion_pose.py | 5 +- src/models/model_audio2mesh.py | 97 +++-- src/models/model_audio2pose.py | 376 ++++++++++-------- src/nn/audio2pose_mvae.py | 155 ++++---- train.py | 10 +- 28 files changed, 1817 insertions(+), 483 deletions(-) create mode 100644 experiments/audio2pose/train_audio2pose_luox_20220415.yaml create mode 100644 scripts/Actor4Data/run-00-mean-coeff.py create mode 100755 scripts/Actor4Data/run-01-prepare-data.py create mode 100644 scripts/Actor4Data/run-20-deca-reconstruction.py create mode 100644 scripts/Actor4Data/run-21-features-3dmm.py create mode 100644 scripts/Actor4Data/run-22-deca-render-video.py create mode 100644 scripts/Actor4Data/run-30-dectect-landmark.py create mode 100644 scripts/Actor4Data/run-41-train-dict-data-raw-deca.py create mode 100644 scripts/Actor4Data/stack_video.py create mode 100644 scripts/Actor4Data/valid-test-train.json create mode 100644 scripts/Obama/run-53-train-dict-data-raw-pose.py diff --git a/common/animation.py b/common/animation.py index 934be37..1292321 100644 --- a/common/animation.py +++ b/common/animation.py @@ -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] diff --git a/experiments/audio2mesh/infer_audio2mesh_CN_20220312.yaml b/experiments/audio2mesh/infer_audio2mesh_CN_20220312.yaml index 1a2f577..76947c4 100644 --- a/experiments/audio2mesh/infer_audio2mesh_CN_20220312.yaml +++ b/experiments/audio2mesh/infer_audio2mesh_CN_20220312.yaml @@ -14,8 +14,7 @@ FREQ: MODEL: - # name: 'audio2mesh' - name: 'audio2mesh2' + name: 'audio2mesh' name_netG: "audio2mesh" dim_motion: 53 # 68*2 @@ -27,19 +26,23 @@ 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: @@ -52,16 +55,15 @@ DATASET: shifting_speed: True # root: './data/Actor2/Actor2-raw-7h' # obama-deca-3-5-08-mini - root: './data/Actor2/Actor2-raw-1h' # obama-deca-3-5-08-mini - + 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' - nwind_second_train: 1 # 3 - nwind_second_valid: 1 # 3 - nwind_second_test: 1 # 15 + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 TRAIN: @@ -71,5 +73,6 @@ TRAIN: TEST: batch_size: 20 + LOSS: names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"] \ No newline at end of file diff --git a/experiments/audio2mesh/infer_audio2mesh_CN_20220322.yaml b/experiments/audio2mesh/infer_audio2mesh_CN_20220322.yaml index 890eed5..554dbac 100644 --- a/experiments/audio2mesh/infer_audio2mesh_CN_20220322.yaml +++ b/experiments/audio2mesh/infer_audio2mesh_CN_20220322.yaml @@ -7,7 +7,7 @@ verbose: False isTrain: False MODEL: - name: 'audio2mesh2' + name: 'audio2mesh' name_netG: "audio2mesh" dim_motion: 53 # 68*2 @@ -16,9 +16,14 @@ MODEL: pretrain: True - # 2h, rec-vel, load_epoch 145 - path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220322/20220405-19H39M26S" - load_epoch: 145 + # # 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 diff --git a/experiments/audio2mesh/train_audio2mesh_CN_20220312.yaml b/experiments/audio2mesh/train_audio2mesh_CN_20220312.yaml index c1f0416..309347d 100644 --- a/experiments/audio2mesh/train_audio2mesh_CN_20220312.yaml +++ b/experiments/audio2mesh/train_audio2mesh_CN_20220312.yaml @@ -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 \ No newline at end of file + lambda_rec_ldmk: 0 + lambda_closure_x: 0 + lambda_closure_y: 0 \ No newline at end of file diff --git a/experiments/audio2pose/train_audio2pose_luox_20220415.yaml b/experiments/audio2pose/train_audio2pose_luox_20220415.yaml new file mode 100644 index 0000000..b15a398 --- /dev/null +++ b/experiments/audio2pose/train_audio2pose_luox_20220415.yaml @@ -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 diff --git a/infer_one_live.py b/infer_one_live.py index fc89bd7..635dae6 100644 --- a/infer_one_live.py +++ b/infer_one_live.py @@ -52,9 +52,13 @@ if __name__ == "__main__": # 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/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") @@ -81,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 ...") @@ -106,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(): @@ -131,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) diff --git a/infer_one_wt_gt.py b/infer_one_wt_gt.py index 8513af7..396c98a 100644 --- a/infer_one_wt_gt.py +++ b/infer_one_wt_gt.py @@ -53,10 +53,12 @@ if __name__ == "__main__": # 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}/") - ipath_audio = ipath_data.joinpath("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") @@ -66,53 +68,29 @@ if __name__ == "__main__": 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') - # 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") - - # path_audio = Path("./data/test/cut_NVP.wav") - # path_audio = Path("./data/test/cut_LSP.wav") - # path_audio = Path("/yrfs/cf/data/render/obama_train.wav") - # path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim_120s.wav") - # path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav") - - # wav2vec 2.0 - - # path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_120s.wav") - # path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P22/audio/audio_trim.wav") - - # path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/test_pangzi_zh_cut15.wav") - # path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/P74_lite.mp3") - - # path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/test_video_15.wav") - # path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/cut_lsz.wav") - # path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/obama.wav") - - # data extract audio - # Load data_audio and extract features # load raw speech - audio_raw, sample_rate = torchaudio.load(ipath_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(ipath_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) sample_rate = 16000 - 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() + 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 ) * 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 = 30 + nwinds = 60 data_motion = torch.from_numpy(data_motion[np.newaxis, :50*nwinds, :]) # (1, 3000, 53) - audio_raw = audio_raw[:nwinds * sample_rate] + raw_speech = raw_speech[:nwinds * sample_rate] # load wav2Vec model @@ -124,10 +102,10 @@ if __name__ == "__main__": # padding half frame length for bed and end npad = int(0.5 * 16000* ( 1 / 50) + 0.5) - audio_pad = np.pad(audio_raw, pad_width=((npad, npad)), mode="edge") - print(f"after padding audio_pad = {audio_pad.shape}, dtype={audio_pad.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_pad, sampling_rate=16000, return_tensors="pt") + inputs = processor(pad_speech, sampling_rate=16000, return_tensors="pt") inputs = inputs.to(device) with torch.no_grad(): @@ -149,4 +127,4 @@ if __name__ == "__main__": 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, audio_raw, suffix) + model.infer_with_gt(cond, data_motion, raw_speech, suffix) diff --git a/scripts/Actor2Data/run-01-prepare-data.py b/scripts/Actor2Data/run-01-prepare-data.py index 0f9af79..d12bb7c 100755 --- a/scripts/Actor2Data/run-01-prepare-data.py +++ b/scripts/Actor2Data/run-01-prepare-data.py @@ -1,3 +1,4 @@ +import os from pathlib import Path import json import moviepy @@ -38,19 +39,19 @@ 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)) print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}") @@ -62,72 +63,80 @@ if __name__ == '__main__': 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 -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())) + # # 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!! ") + # # 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}") + # # 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())) + # # 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) diff --git a/scripts/Actor2Data/run-21-features-3dmm.py b/scripts/Actor2Data/run-21-features-3dmm.py index 5d0cb0a..f09f6f2 100644 --- a/scripts/Actor2Data/run-21-features-3dmm.py +++ b/scripts/Actor2Data/run-21-features-3dmm.py @@ -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") diff --git a/scripts/Actor2Data/run-41-train-dict-data-raw-deca.py b/scripts/Actor2Data/run-41-train-dict-data-raw-deca.py index e69bb83..f333f3b 100644 --- a/scripts/Actor2Data/run-41-train-dict-data-raw-deca.py +++ b/scripts/Actor2Data/run-41-train-dict-data-raw-deca.py @@ -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}") diff --git a/scripts/Actor4Data/run-00-mean-coeff.py b/scripts/Actor4Data/run-00-mean-coeff.py new file mode 100644 index 0000000..b87150d --- /dev/null +++ b/scripts/Actor4Data/run-00-mean-coeff.py @@ -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}") diff --git a/scripts/Actor4Data/run-01-prepare-data.py b/scripts/Actor4Data/run-01-prepare-data.py new file mode 100755 index 0000000..8df0bec --- /dev/null +++ b/scripts/Actor4Data/run-01-prepare-data.py @@ -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) + + + + diff --git a/scripts/Actor4Data/run-20-deca-reconstruction.py b/scripts/Actor4Data/run-20-deca-reconstruction.py new file mode 100644 index 0000000..bc51d7e --- /dev/null +++ b/scripts/Actor4Data/run-20-deca-reconstruction.py @@ -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()) + + + diff --git a/scripts/Actor4Data/run-21-features-3dmm.py b/scripts/Actor4Data/run-21-features-3dmm.py new file mode 100644 index 0000000..28a28ce --- /dev/null +++ b/scripts/Actor4Data/run-21-features-3dmm.py @@ -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! ") + + + diff --git a/scripts/Actor4Data/run-22-deca-render-video.py b/scripts/Actor4Data/run-22-deca-render-video.py new file mode 100644 index 0000000..4bbf54a --- /dev/null +++ b/scripts/Actor4Data/run-22-deca-render-video.py @@ -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) + + + + + + diff --git a/scripts/Actor4Data/run-30-dectect-landmark.py b/scripts/Actor4Data/run-30-dectect-landmark.py new file mode 100644 index 0000000..a578028 --- /dev/null +++ b/scripts/Actor4Data/run-30-dectect-landmark.py @@ -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 \ No newline at end of file diff --git a/scripts/Actor4Data/run-41-train-dict-data-raw-deca.py b/scripts/Actor4Data/run-41-train-dict-data-raw-deca.py new file mode 100644 index 0000000..664c62a --- /dev/null +++ b/scripts/Actor4Data/run-41-train-dict-data-raw-deca.py @@ -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}") \ No newline at end of file diff --git a/scripts/Actor4Data/stack_video.py b/scripts/Actor4Data/stack_video.py new file mode 100644 index 0000000..13598c8 --- /dev/null +++ b/scripts/Actor4Data/stack_video.py @@ -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}") + + + diff --git a/scripts/Actor4Data/valid-test-train.json b/scripts/Actor4Data/valid-test-train.json new file mode 100644 index 0000000..e69de29 diff --git a/scripts/LuoXData/run-31-features-3dmm-pose.py b/scripts/LuoXData/run-31-features-3dmm-pose.py index 18b62b7..a38dce0 100644 --- a/scripts/LuoXData/run-31-features-3dmm-pose.py +++ b/scripts/LuoXData/run-31-features-3dmm-pose.py @@ -1,7 +1,4 @@ -import os -import sys import json -import librosa import numpy as np from pathlib import Path diff --git a/scripts/Obama/run-51-features-3dmm-pose.py b/scripts/Obama/run-51-features-3dmm-pose.py index 3740d73..ddef127 100644 --- a/scripts/Obama/run-51-features-3dmm-pose.py +++ b/scripts/Obama/run-51-features-3dmm-pose.py @@ -1,7 +1,4 @@ -import os -import sys import json -import librosa import numpy as np from pathlib import Path @@ -44,23 +41,15 @@ if __name__ == "__main__": 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)}") + # 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) / fps / 60 - duration_coeff += len(vframe_coeff) / fps / 60 - print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min") - - if len(vframe_frame) != nframe_trim: - print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframe_trim}") - continue + # if len(vframe_frame) != nframe_trim: + # print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframe_trim}") + # continue - if len(vframe_coeff)+1 < nframe_trim: - print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframe_trim}") - continue feat_pos = [] feat_cam = [] @@ -68,6 +57,7 @@ if __name__ == "__main__": 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 @@ -84,6 +74,9 @@ if __name__ == "__main__": 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! ") diff --git a/scripts/Obama/run-53-train-dict-data-raw-pose.py b/scripts/Obama/run-53-train-dict-data-raw-pose.py new file mode 100644 index 0000000..c999832 --- /dev/null +++ b/scripts/Obama/run-53-train-dict-data-raw-pose.py @@ -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}") \ No newline at end of file diff --git a/src/config.py b/src/config.py index f79ff6c..b27cdce 100644 --- a/src/config.py +++ b/src/config.py @@ -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() diff --git a/src/datasets/motion_pose.py b/src/datasets/motion_pose.py index 5e48d0e..e96c9e1 100644 --- a/src/datasets/motion_pose.py +++ b/src/datasets/motion_pose.py @@ -24,9 +24,6 @@ class MotionPoseDataset(Dataset): self.phase = phase path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz") - self.nseqR = opt.MODEL.n_lookprevs # 5, number of previous sequence - self.nseqL = opt.MODEL.n_lookahead # 20, number of future sequence - 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) @@ -51,7 +48,7 @@ class MotionPoseDataset(Dataset): elif self.phase == "valid": return 3000 #3000 else: - return 100 + return 500 def __getitem__(self, idx): """ diff --git a/src/models/model_audio2mesh.py b/src/models/model_audio2mesh.py index b8d54e9..29fe5e2 100644 --- a/src/models/model_audio2mesh.py +++ b/src/models/model_audio2mesh.py @@ -2,9 +2,6 @@ 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 @@ -19,7 +16,7 @@ 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.animation import save_animation_with_gt2, write_video, write_video_with_gt from common.debug import debug from common.losses import WingLoss @@ -101,7 +98,7 @@ class Audio2MeshModel(Base): def set_input(self, batch_input): - + """ """ # motion data data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) @@ -170,7 +167,7 @@ class Audio2MeshModel(Base): return pred - def training(self, batch_input): + def training(self, batch_input, idx_epoch=0, idx_batch=0): self.train() # set train model self.set_input(batch_input) @@ -195,7 +192,7 @@ class Audio2MeshModel(Base): 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) @@ -224,11 +221,18 @@ class Audio2MeshModel(Base): # !! 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) + suffix=suffix,vis_landmarks=False) + + if save_npy: # save result batch_pdt_geo = batch_pdt_geo.cpu().numpy() @@ -237,7 +241,7 @@ class Audio2MeshModel(Base): print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}") - def infer(self, batch_cond, path_audio, suffix="", save_npy=True): + def infer(self, batch_cond, raw_speech, suffix="", save_npy=True): self.eval() self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) @@ -251,10 +255,9 @@ class Audio2MeshModel(Base): 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) - + 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 batch_pdt_geo = batch_pdt_geo.cpu().numpy() @@ -263,7 +266,7 @@ class Audio2MeshModel(Base): 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) @@ -277,9 +280,9 @@ class Audio2MeshModel(Base): 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) @@ -299,9 +302,6 @@ class Audio2MeshModel(Base): 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 @@ -402,8 +402,7 @@ class Audio2MeshModel(Base): return loss, loss_dict - - def save_reconstruct(self, batch_pdt_geo, path_audio, path_save, suffix=""): + def save_reconstruct(self, batch_pdt_geo, raw_speech, path_save, suffix="", vis_landmarks=False): # batch_pdt_geo, [B x N x dim_motion] B, N, *_ = batch_pdt_geo.shape @@ -412,7 +411,6 @@ class Audio2MeshModel(Base): # 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): @@ -427,16 +425,24 @@ class Audio2MeshModel(Base): # render render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) - render_pt = render_pt.cpu() # 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, ...])) - # 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 + 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() @@ -459,7 +465,7 @@ class Audio2MeshModel(Base): return images @torch.no_grad() - def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix=""): + 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] @@ -467,7 +473,7 @@ class Audio2MeshModel(Base): 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}.mp4") + ipath_save = path_save.joinpath(f"{suffix}_{0:02d}_pt_gt.mp4") v_render_pt = [] v_render_gt = [] @@ -488,18 +494,22 @@ class Audio2MeshModel(Base): 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_gt = util.batch_orth_proj(kldmk3d_gt, cam); - kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:]; + 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)) + 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): @@ -507,13 +517,9 @@ class Audio2MeshModel(Base): 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 + 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)}") - save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=50, path_audio=tmp_audio.name) @torch.no_grad() @@ -589,6 +595,9 @@ 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() diff --git a/src/models/model_audio2pose.py b/src/models/model_audio2pose.py index 55a9f34..f27bf69 100644 --- a/src/models/model_audio2pose.py +++ b/src/models/model_audio2pose.py @@ -30,9 +30,9 @@ class Audio2PoseModel(Base): self.logger = logger self.names_model = ["G"] # G - self.nc_motion = opt.MODEL.dim_motion # 9-dim pose (rotation-3 + translation-2 + sacle-1) - self.nc_speech = opt.MODEL.dim_speech # 1024-dim - self.nc_latent = opt.MODEL.nc_latent # 64 + 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) @@ -67,17 +67,32 @@ class Audio2PoseModel(Base): 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["pose"].float().to(self.device) # (B, nsteps, nc_motion) + 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"x = {x.shape}, dtype={x.dtype}", verbose=False) + 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])}, \ @@ -89,10 +104,10 @@ class Audio2PoseModel(Base): # 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_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_speech), sampling_rate=16000, return_tensors="pt") + 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) @@ -102,13 +117,20 @@ class Audio2PoseModel(Base): 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.nc_speech = cond.size() - self.x = x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion) + 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): @@ -121,20 +143,79 @@ class Audio2PoseModel(Base): return pred - def training(self, batch_input): + 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) - batch_x = self.x[:, 1:].reshape(-1, self.nc_motion) # [B*(nsteps-1), nc_motion] - batch_c = self.c[:, 1:].reshape(-1, self.nwind, self.nc_speech) # [B*(nsteps-1), nwind, nc_speech] - batch_x_prev = self.x[:, :-1] # [B*(nsteps-1), nc_motion] - - # forward - batch_pt, batch_mu, batch_lv = self.netG(batch_x, batch_x_prev, batch_c) # [B*(nsteps-1), nc_motion] - debug(self.opt, f"traing batch_pt = {batch_pt.shape}, batch_gt = {batch_x.shape}") - - # loss - loss, loss_dict = self.eval_losses(batch_pt, batch_x, batch_mu, batch_lv) + # 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() @@ -147,8 +228,7 @@ class Audio2PoseModel(Base): 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) @@ -165,7 +245,7 @@ class Audio2PoseModel(Base): # forward ibatch_pt, ibatch_mu, ibatch_lv = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion] - self.logger.info(f"[test] ibatch_pt = {ibatch_pt.shape}") + 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) @@ -176,74 +256,73 @@ class Audio2PoseModel(Base): 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.nc_latent) # [B * (nstep-1), nc_latent] - batch_lv = batch_lv.reshape(-1, self.nc_latent) # [B * (nstep-1), nc_latent] - batch_pt = batch_pt[:, 1:, self.nc_motion].reshape(-1, self.nc_motion) # [B * (nstep-1), nc_motion] - batch_gt = self.x[:, 1:, self.nc_motion].reshape(-1, self.nc_motion) # [B * (nstep-1), nc_motion] + 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_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 + 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_pdt_geo.shape}") + print(f"testing pt shape = {batch_pos.shape}") # !! add specific when render & output !! - batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific + batch_pos = batch_pos - self.temp_verts + self.temp_verts_specific # render & and save - self.save_reconstruct(batch_pdt_geo, path_audio, + self.save_reconstruct(batch_pos, path_audio, path_save=Path(self.opt.OUTPUT_DIR), suffix=suffix) if save_npy: # save result - batch_pdt_geo = batch_pdt_geo.cpu().numpy() + batch_pos = batch_pos.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}") + np.save(path_save_npy, batch_pos) + print(f"save infer_result shape = {batch_pos.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(): - + batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion] - batch_pt[:, 0] = self.x[:, 0] # assign first frame + # 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_x = self.x[:, istep] # [B, nc_motion] + 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(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion] - self.logger.info(f"[test] ibatch_pt = {ibatch_pt.shape}") + ibatch_pt = self.netG.sample(ibatch_z, ibatch_x_prev, ibatch_c) # [B, nc_motion] - batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt + 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}") + # 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_{cur_epoch:05d}_{cur_batch:03d}') + 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) @@ -255,46 +334,17 @@ class Audio2PoseModel(Base): 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 + # 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 + # print(f"template verts reshape = {verts.shape}") 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(self, batch_pt, batch_gt, batch_mu, batch_lv): """ Computes the VAE loss function. pramas: @@ -302,12 +352,13 @@ class Audio2PoseModel(Base): 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 + 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, ] @@ -317,19 +368,17 @@ class Audio2PoseModel(Base): if self.opt.LOSS.lambda_kl > 0: loss += loss_kl * self.opt.LOSS.lambda_kl - # velocity loss - batch_pt = batch_pt.reshape(self.B, self.nsteps, self.nc_motion) - batch_gt = batch_gt.reshape(self.B, self.nsteps, self.nc_motion) + 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-1, nc_motion] - diff_gt = batch_gt[:, 1:, :] - batch_gt[:, :-1, :] # (B, nsteps-1, nc_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_rec"] = loss_vel_rec.detach() - - if self.opt.LOSS.lambda_vel_rec > 0: - loss += loss_vel_rec * self.opt.LOSS.lambda_vel_rec + 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() @@ -337,40 +386,54 @@ class Audio2PoseModel(Base): 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] + @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_geo.shape + B, N, *_ = batch_pdt_pos.shape nbatch_render = 10 # for each batch for i in range(B): - ipos_pt = batch_pdt_geo[i, ...] + 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): - # split - kpos_pt = ipos_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] - nbatch_real = kpos_pt.size(0) + + # 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] - # 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}") + # 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] - # render - render_pt = self.render_geometry(kpos_pt, cam, self.device) # (nbatch_real, 3, 512, 512) - render_pt = render_pt.cpu() - # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + # 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 - # print(f"testing v_render_pt = {len(v_render_pt)}") - save_images_with_audio(v_render_pt, path_audio, ipath_save) + save_images_with_audio(v_render_pt, tmp_audio.name, ipath_save) @torch.no_grad() @@ -392,14 +455,15 @@ class Audio2PoseModel(Base): return images + @torch.no_grad() - def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix=""): - # batch_pdt_geo, [1 x N x 5023 x 3] + 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_geo.shape + B, N, *_ = batch_pdt_pos.shape - ipos_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3] + 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") @@ -422,19 +486,22 @@ class Audio2PoseModel(Base): 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}") - # landmarks 3d - kldmk3d_pt = self.netF.seletec_3d68(kpos_pt) # [nbatch_real x 68 x 3] - kldmk3d_gt = self.netF.seletec_3d68(kpos_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)) + 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, ...])) @@ -452,40 +519,47 @@ class Audio2PoseModel(Base): @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=9] - # batch_pdt_pos, [B x N x nc_motion=9] + # 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 9] - ipos_gt = batch_tgt_pos[i, ...] # [N x 9] + 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] - # split - kpos_pt = ipos_pt[k:k+nbatch_render, :6] # [nbatch_real x 6] - kpos_gt = ipos_gt[k:k+nbatch_render, :6] # [nbatch_real x 6] - kcam_pt = ipos_pt[k:k+nbatch_render, 6:] # [nbatch_real x 3] - kcam_gt = ipos_gt[k:k+nbatch_render, 6:] # [nbatch_real x 3] + # 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] - kidn_gt = self.idn[k:k+nbatch_render, :] # [nbatch_real, 100] - kexp_gt = self.exp[k:k+nbatch_render, :] # [nbatch_real, 50] + # 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.get_vertices(kidn_gt.clone(), kexp_gt.clone(), kpos_pt) # (nbatch_read, 5023, 3) - kgeo_gt = self.get_vertices(kidn_gt.clone(), kexp_gt.clone(), kpos_gt) # (nbatch_read, 5023, 3) - + 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).detach().cpu() # (nbatch_real, 3, 512, 512) - render_gt = self.render_geometry(kgeo_gt, kcam_gt, self.device).detach().cpu() # (nbatch_real, 3, 512, 512) + 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 @@ -524,18 +598,10 @@ def tensor2image(tensor): def define_netG(opt): netG = None - if opt.MODEL.name_netG == "audio2mesh": - from src.nn.audio2mesh import Audio2Mesh - netG = Audio2Mesh(opt) + if opt.MODEL.name_netG == "audio2pose_mvae": + from src.nn.audio2pose_mvae import PoseMixtureVAE + netG = PoseMixtureVAE(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!") diff --git a/src/nn/audio2pose_mvae.py b/src/nn/audio2pose_mvae.py index c01584e..99742fd 100644 --- a/src/nn/audio2pose_mvae.py +++ b/src/nn/audio2pose_mvae.py @@ -1,30 +1,30 @@ 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, - nc_motion, - latent_size, - nseqR, - nseqF, - num_experts, - ): - super().__init__() - self.nc_motion = nc_motion - self.latent_size = latent_size - self.nseqR = nseqR - self.nseqF = nseqF + def __init__(self, opt): + super(PoseMixtureVAE, self).__init__() - nc_speech = 1024 - nc_feat_c = 128 - hidden_size = 256 + 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(nc_speech), - nn.Conv2d(nc_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 8 x 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), @@ -38,32 +38,34 @@ class PoseMixtureVAE(nn.Module): 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, nc_feat_c, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # nc_feat_c x 1 x 1 + 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() # nc_feat_c + nn.Flatten() # dim_feat_c ) - self.encoder = Encoder(nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF) - self.decoder = MixedDecoder(nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF, num_experts) + 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 nc_motion) - x_pre: shape = (B x nc_motion) - c : shape = (B x nwind x nc_speech) + 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 nc_motion) + 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(c, 1, 3) # (B, 1, nwind, nc_speech) -> (B, nc_speech, nwind, 1) + 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) - self.logger.info(f"[forward] transpose c shape = {c.shape}, feac_c shape = {feat_c.shape}") + 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) @@ -75,18 +77,17 @@ class PoseMixtureVAE(nn.Module): def sample(self, z, x_prev, c): """ forward function parameters: - z : shape = (B x nc_motion) - x_pre: shape = (B x nc_motion) - c : shape = (B x nwind x nc_speech) + 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 nc_motion) + y : shape = (B x dim_motion) """ # condition header - c = torch.unsqueeze(c, dim=1).transpose(c, 1, 3) # (B, 1, nwind, nc_speech) -> (B, nc_speech, nwind, 1) - feat_c = self.layer_cond(c) # (B, nc_feat_c) - self.logger.info(f"[forward] transpose c shape = {c.shape}, feac_c shape = {feat_c.shape}") - + 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) @@ -96,17 +97,17 @@ class PoseMixtureVAE(nn.Module): class Encoder(nn.Module): - def __init__(self, nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF): + 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 = nc_motion * nseqF + nc_motion * nseqR + nc_feat_c + input_size = dim_motion * nseqF + dim_motion * nseqR + dim_feat_c - self.fc1 = nn.Linear(input_size, hidden_size) - self.fc2 = nn.Linear(nc_motion * nseqF + hidden_size, hidden_size) + self.fc1 = nn.Linear(input_size, dim_hidden) + self.fc2 = nn.Linear(dim_motion * nseqF + dim_hidden, dim_hidden) - self.fc_mu = nn.Linear(nc_motion * nseqF + hidden_size, latent_size) - self.fc_logvar = nn.Linear(nc_motion * nseqF + hidden_size, latent_size) + 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): @@ -117,47 +118,47 @@ class Encoder(nn.Module): def forward(self, x, x_prev, feat_c): """ - x shape = (B, nc_motion) - x_prev shape = (B, nc_motion) - feat_c shape = (B, nc_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, nc_motion * nseqR + nc_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, hidden_size) - h2 = F.elu(self.fc2(torch.cat((x, h1), dim=1))) # (B, hidden_size) - s = torch.cat((x, h2), dim=1) # (B, nc_motion * nseqF + hidden_size) + 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, latent_size) - logvar = self.fc_logvar(s) # (B, latent_size) + mu = self.fc_mu(s) # (B, dim_latent) + logvar = self.fc_logvar(s) # (B, dim_latent) - z = self.reparameterize(mu, logvar) # (B, latent_size) + z = self.reparameterize(mu, logvar) # (B, dim_latent) return z, mu, logvar class Decoder(nn.Module): - def __init__(self, nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF): + def __init__(self, dim_motion, dim_feat_c, dim_latent, dim_hidden, nseqR, nseqF): super().__init__() # Decoder # Takes latent | condition as input - input_size = latent_size + nc_motion * nseqR + nc_feat_c - output_size = nseqF * nc_motion - self.fc4 = nn.Linear(input_size, hidden_size) - self.fc5 = nn.Linear(latent_size + hidden_size, hidden_size) - self.out = nn.Linear(latent_size + hidden_size, output_size) + 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, latent_size) - x_prev shape = (B, nc_motion) - feat_c shape = (B, nc_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, nc_motion * nseqR + nc_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, hidden_size) - h5 = F.elu(self.fc5(torch.cat((z, h4), dim=1))) # (B, hidden_size) + 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) @@ -165,19 +166,19 @@ class Decoder(nn.Module): class MixedDecoder(nn.Module): - def __init__(self, nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF, num_experts): + def __init__(self, dim_motion, dim_feat_c, dim_latent, dim_hidden, nseqR, nseqF, num_experts): super().__init__() - input_size = latent_size + nc_motion * nseqR + nc_feat_c - inter_size = latent_size + hidden_size - output_size = nseqF * nc_motion + 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, hidden_size)), - nn.Parameter(torch.empty(num_experts, hidden_size)), + 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, hidden_size)), - nn.Parameter(torch.empty(num_experts, hidden_size)), + 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)), @@ -205,12 +206,12 @@ class MixedDecoder(nn.Module): def forward(self, z, x_prev, feat_c): """ - z shape = (B, latent_size) - x_prev shape = (B, nc_motion) - feat_c shape = (B, nc_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, nc_motion + nc_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) @@ -225,7 +226,7 @@ class MixedDecoder(nn.Module): 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, hidden_size) + feat_o = activation(out) # (B, dim_hidden) else: feat_o = out # (B, output_size) diff --git a/train.py b/train.py index f6dc998..52617ee 100644 --- a/train.py +++ b/train.py @@ -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 @@ -109,9 +108,12 @@ 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 @@ -146,14 +148,12 @@ if __name__ == "__main__": ################ upate learning rate by validataion model.update_learning_rate(valid_loss_dict["all"]) - if opt.TRAIN.apply_update_parameters: - model.update_parameters(epoch) ################# 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