add audio2mesh_ar

This commit is contained in:
Sen Liang committed 2022-03-14 18:13:13 +08:00
1 parent ded9b27f71
commit e0f24982d1
46 files changed
+3902 -310

No files matched your search

+5 -1
View File
@@ -1,6 +1,6 @@
import moviepy.editor as mpy
import numpy as np
import os
import sys
# sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.landmark import landmark_to_images
@@ -171,6 +171,10 @@ def save_images_with_audio(images, path_audio, path_save):
audioclip.close()
animation.close()
# add
path_save2 = str(path_save).replace(".mp4", "2.mp4")
cmd = f"ffmpeg -y -i {str(path_save)} -i {str(path_audio)} -map 0:v -vcodec libx264 -map 1:a -c:v copy -shortest {str(path_save2)}"
os.system(cmd)
def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audio=None, start_time=None, end_time=None):
+39
View File
@@ -0,0 +1,39 @@
import numpy as np
from scipy import interpolate
def resample_by_nsteps(feat, nsteps_tgt):
"""
feat, (nframes, ... ) (with source_fps)
"""
nsteps_src = feat.shape[0]
data_idx = np.arange(0, nsteps_src, 1)
samp_idx = np.arange(0, nsteps_src-1, (nsteps_src - 1) / nsteps_tgt)
# print(f"data_idx = {list(data_idx)} \nsmap_idx = {list(samp_idx)}")
# sample function
func = interpolate.interp1d(data_idx, y=feat, axis=0)
data_interpolate = func(samp_idx)
return data_interpolate
def convert_fps(data, source_fps = 30, target_fps=25):
"""
data, (nframes, ... ) (with source_fps)
"""
nsize = data.shape[0]
data_idx = np.arange(0, nsize, 1)
samp_idx = np.arange(0, nsize-1, 1.0*source_fps/target_fps)
func = interpolate.interp1d(data_idx, data=data, axis=0)
data_interpolate = func(samp_idx)
if source_fps < target_fps:
data_interpolate = np.concatenate([data_interpolate, data[-1:]])
return data_interpolate
# def
+84
View File
@@ -0,0 +1,84 @@
import time
import os,sys
import pprint
import shutil
import argparse
from pathlib import Path
import torch
import numpy as np
# from torch.utils.tensorboard import SummaryWriter
# writer = SummaryWriter(log_dir='tb', flush_secs=30)
import torch
from torch.utils.data import DataLoader
from src.datasets import create_dataset
from src.models import create_model, calculate_model_params
from src.config import config as opt
from src.config import update_config
from common.vis.visualizer import Visualizer
from common.logger import Logger
torch.autograd.set_detect_anomaly(True)
# os.environ['CUDA_VISIBLE_DEVICES']="2, 5,6,7,8,9"
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
opt.OUTPUT_DIR = logger.path_output
logger.info(opt.OUTPUT_DIR)
logger.info(pprint.pformat(opt))
# validation
valid_dataset = create_dataset(opt, phase='valid')
valid_loader = DataLoader(valid_dataset,
batch_size=opt.TRAIN.batch_size * len(opt.GPUS),
shuffle=False,
num_workers=opt.WORKERS,
pin_memory=False)
logger.info(f"validation dataset size = {len(valid_dataset)}, batch = {len(valid_loader)}")
# get model
model = create_model(opt, logger)
model.setup(opt)
# validation
logger.info("validation...")
loss_valid = 0
for iv, ibatch_valid in enumerate(valid_loader):
loss_valid += model.validation(ibatch_valid) # forward and backward
# print logger
if (iv+1) % opt.FREQ.batch_print == 0 and epoch % opt.FREQ.epoch_print == 0:
losses = model.get_current_losses() # pach to loss dict
visor.print_current_losses(epoch, iv, losses)
visor.plot_current_losses_valid(epoch, float(iv)/len(valid_loader), losses)
logger.info(f"validation loss = {loss_valid /(iv+1) }") # len(valid_loader)
@@ -1,4 +1,4 @@
GPUS: '0'
GPUS: '3'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -8,18 +8,18 @@ isTrain: False
MODEL:
name: 'audio2mesh'
name_netG: "audio2mesh_resnet"
# name_netG: "audio2mesh"
# name: 'audio2mesh'
name: 'audio2mesh_specific'
# name_netG: "audio2mesh_resnet"
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220208/20220228-18H41M46S"
load_epoch: 175
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220208/20220217-18H29M20S"
load_epoch: 160
DATASET:
@@ -0,0 +1,49 @@
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
isTrain: False
MODEL:
# name: 'audio2mesh'
name: 'audio2mesh_specific'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220313-13H26M47S"
load_epoch: 100
DATASET:
fps: 50
sr: 16000
name: "motion_live"
root: './data/Actor2/Actor2-raw-2h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.00001
batch_size: 64
shuffle: True
apply_testing: True
apply_validation: True
@@ -1,4 +1,4 @@
GPUS: '9'
GPUS: '0'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -9,17 +9,20 @@ isTrain: False
MODEL:
# name: 'audio2mesh'
name: 'audio2mesh_specific'
name_netG: "audio2mesh_resnet"
# name_netG: "audio2mesh"
name_header: "resnet50" # "resnet50", "resnet34",
# name_netG: "audio2mesh_resnet"
name_netG: "audio2mesh"
# name_header: "resnet50" # "resnet50", "resnet34",
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220220/20220225-18H53M05S"
load_epoch: 285
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220217-17H36M22S"
load_epoch: 115
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220220/20220223-22H17M02S"
# load_epoch: 60
DATASET:
fps: 50
@@ -0,0 +1,84 @@
GPUS: '0'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-ar-actor2-no-veloctiy"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh_ar'
name_netG: "audio2mesh_ar"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220225-19H08M53S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-2h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
optimizer: 'Adam'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
nesterov: True
grad_clip_norm: False
# lr_policy: 'multistep'
# lr_milestones: [50, 100]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 100
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 0
@@ -1,17 +1,16 @@
GPUS: '6'
GPUS: '2'
WORKERS: 8
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9900
vsdm_port: 9920
vsdm_ncol: 4
vsdm_env: "audio2mesh-resnet-cn-50-outliar"
vsdm_env: "audio2mesh-bigger-flip-pretrain"
FREQ:
epoch_save: 5
@@ -19,27 +18,26 @@ FREQ:
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh'
name_netG: "audio2mesh_resnet"
name_header: "resnet50" # "resnet50", "resnet34",
name_netG: "audio2mesh"
# name_header: "resnet50" # "resnet50", "resnet34",
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220208/20220225-16H33M13S"
load_epoch: 200
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220208/20220217-18H29M20S"
load_epoch: 160
DATASET:
fps: 50
sr: 16000
name: "motion_live"
# root: './data/LuoXData-raw-deca-toy' # obama-deca-3-5-08-mini
# root: './data/LuoXData-raw-deca-4min' # obama-deca-3-5-08-mini
root: './data/LuoXData-raw-deca-16h' # obama-deca-3-5-08-mini
flip: True
root: './data/LuoXData-raw-deca-16h' # LuoXData-raw-deca-16h
root_raw: '/yrfs/lsen/DATA/LuoXData/processing2'
filter: 'savgol'
speech_extractor: 'wav2vec'
@@ -72,12 +70,11 @@ TRAIN:
resume: False
reset_lr: False
resume_suffix: "20220211-16H54M11S"
resume_suffix: "20220303-14H22M20S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "rec_geo_l1", "vel_geo", "vel_geo_w", "vel_geo_l1"]
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 10
@@ -1,4 +1,4 @@
GPUS: '5'
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -9,9 +9,10 @@ verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9900
vsdm_port: 9920
vsdm_ncol: 4
vsdm_env: "audio2mesh-specific-cn-resnet50-outliar-pretrain"
vsdm_env: "audio2mesh-cn-speed-dropout"
FREQ:
epoch_save: 5
@@ -19,23 +20,28 @@ FREQ:
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh_specific'
name_netG: "audio2mesh_resnet"
name_header: "resnet50" # "resnet50", "resnet34",
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220225-19H08M53S"
load_epoch: 295
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live2"
root: './data/LuoXData-raw-deca-16h' # obama-deca-3-5-08-mini
name: "motion_live"
flip: False
shifting_speed: True
root: './data/LuoXData-raw-16h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/LuoXData/processing2'
path_mean_dict: './data/DECA_LuoXData_mean.npy'
filter: 'savgol'
@@ -49,8 +55,8 @@ TEST:
batch_size: 2
TRAIN:
lr: 0.00001
batch_size: 64
lr: 0.0001
batch_size: 128
shuffle: True
apply_testing: True
@@ -75,6 +81,6 @@ TRAIN:
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "rec_geo_l1", "vel_geo", "vel_geo_w", "vel_geo_l1"]
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 10
@@ -0,0 +1,85 @@
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-actor2-1100"
FREQ:
epoch_save: 5
epoch_valid: 1
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220225-19H08M53S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
flip: False
shifting_speed: True
root: './data/Actor2/Actor2-raw-2h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
TEST:
batch_size: 2
TRAIN:
lr: 0.0001
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
optimizer: 'Adam'
momentum: 0.9
beta1: 0.5
beta2: 0.999
weight_decay: 0.0001
nesterov: True
grad_clip_norm: False
# lr_policy: 'multistep'
# lr_milestones: [50, 100]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 100
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 100
@@ -1,4 +1,4 @@
GPUS: '6'
GPUS: '3'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -8,9 +8,9 @@ verbose: False
VISUAL:
use_HTML: False
use_visdom: True
vsdm_port: 9900
vsdm_port: 9920
vsdm_ncol: 4
vsdm_env: "audio2mesh-specific-en-resnet50-outliar2"
vsdm_env: "audio2mesh-en-velocity-100-2"
FREQ:
epoch_save: 5
@@ -19,9 +19,9 @@ FREQ:
epoch_test: 5
MODEL:
name: 'audio2mesh_specific'
name_netG: "audio2mesh_resnet"
name_header: "resnet50" # "resnet50", "resnet34",
name: 'audio2mesh'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
@@ -34,8 +34,12 @@ MODEL:
DATASET:
fps: 50
sr: 16000
name: "motion_live2"
root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini
name: "motion_live"
flip: False
shifting_speed: False
root: './data/obama-raw-deca-8h-50fps' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Obama/processing'
path_mean_dict: './data/DECA_obama_mean_wf.npy'
filter: 'savgol'
@@ -50,7 +54,7 @@ TEST:
TRAIN:
lr: 0.0001
batch_size: 64
batch_size: 128
shuffle: True
apply_testing: True
@@ -67,14 +71,13 @@ TRAIN:
# lr_milestones: [50, 100]
lr_policy: 'plateau'
resume: False
resume: True
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
resume_suffix: "20220309-19H52M04S"
epoch_begin: 25 # 5000 # 2300 # 2600
epoch_end: 300
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_vel_geo: 100
+125
View File
@@ -0,0 +1,125 @@
import sys
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch.nn.functional as F
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
def infer_one(path_audio, model, processor, extractor):
# load raw speech
audio_raw, sample_rate = torchaudio.load(path_audio)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"resampling: audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# padding half frame length for bed and end
npad = int(0.5 * 16000* ( 1 / 50) + 0.5)
audio_raw = np.pad(audio_raw, pad_width=((npad, npad)), mode="edge")
print(f"after padding audio_raw = {audio_raw.shape}, dtype={audio_raw.dtype}")
inputs = processor(audio_raw, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
with torch.no_grad():
output = extractor(**inputs)
cond = output.last_hidden_state
print(f"cond shape = {cond.shape}")
# convert to windows
cond = F.pad(cond, pad=(0, 0, 8, 7), mode="replicate")
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
nseq = cond.size(1)
print(f"after convert window cond shape = {cond.shape}")
# self.data = self.data[:, 7:7+nseq, :]
model.infer(cond, path_audio, \
f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}")
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
# get model
model = create_model(opt, logger)
model.setup(opt) # load model
# model.remove_weightnorm()
# load wav2Vec model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(device)
path_folder = Path("/mfs/dylan/tts/wav")
vpath_wav = sorted(path_folder.glob("*.wav"))
for ipath_audio in vpath_wav:
print(f"procesing ... {ipath_audio}")
infer_one(ipath_audio, model, processor, extractor)
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
# path_audio = Path("./data/test/cut_NVP.wav")
# path_audio = Path("./data/test/cut_LSP.wav")
# path_audio = Path("/yrfs/cf/data/render/obama_train.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P22/audio/audio_trim.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/test_pangzi_zh_cut15.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/P74_lite.mp3")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/test_video_15.wav")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/cut_lsz.wav")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/obama.wav")
# data extract audio
# Load data_audio and extract features
+10 -68
View File
@@ -32,6 +32,8 @@ def parese_args():
return args
if __name__ == "__main__":
args = parese_args()
path_config = Path(args.opt)
@@ -44,8 +46,14 @@ if __name__ == "__main__":
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim_120s.wav")
path_audio = Path("/yrfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav")
# path_audio = Path("./data/test/cut_NVP.wav")
# path_audio = Path("./data/test/cut_LSP.wav")
# path_audio = Path("/yrfs/cf/data/render/obama_train.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P22/audio/audio_trim.wav")
@@ -69,14 +77,7 @@ if __name__ == "__main__":
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# clip
# if len(audio_raw) > 16000 * 120:
# audio_raw = audio_raw[:16000*120]
# audio_raw_numpy = audio_raw.numpy()
print(f"resampling: audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# load wav2Vec model
print("load Wav2Vec2Model ...")
@@ -114,62 +115,3 @@ if __name__ == "__main__":
model.infer(cond, path_audio, \
f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}")
# # # Add for WaveFlow
# # # model.netG.module = model.netG.module.remove_weightnorm(model.netG.module)
# # # for i, batch_input in enumerate(test_loader):
# # motion = batch_input['data'].float().to(device) # (nbatch, nsteps=60, dim_motion=136)
# # speech = batch_input['cond'].float().to(device) # (nbatch, nsteps=173, dim_condit=80)
# # motion = motion.permute(0, 2, 1) # (nbatch, 136, 60)
# # speech = speech.permute(0, 2, 1) # (nbatch, 80, 173)
# # B = motion.size(0)
# # motion_gt = motion.permute(0,2,1)[0:1, :, :]
# # # generate k samples
# # motion_pt = []
# # for j in range(3):
# # data_pt = model.testing(batch_input, cur_epoch=opt.MODEL.load_epoch, save_animation=False) # B x nsteps x 136
# # data_pt = data_pt[0:1, :, :]
# # motion_pt.append(data_pt)
# # # save
# # print("data_pt shape = ", data_pt.shape)
# # np.save(f"data/ldmk_pdt_align30_{j}.npy", data_pt.cpu().numpy()[0])
# # motion_pt = torch.cat(motion_pt, dim=0) # 8 x nsteps x 136
# # nsteps = min(motion_gt.size(1), motion_pt.size(1))
# # total_motion = torch.cat([motion_gt[:, :nsteps, :], motion_pt[:, :nsteps, :]], dim=0)
# # print(f"total motion shape = {total_motion.shape}")
# # path_save=Path(opt.OUTPUT_DIR).joinpath(f'sampled_{opt.MODEL.load_epoch:05d}.mp4')
# # save_animation_grid(total_motion, path_save=path_save, path_audio=path_audio, ncol=2, w=256, h=256, dpi=100)
# # # animation_with_audio(path_save, path_audio)
# # print(f"SVAE -> {opt.OUTPUT_DIR}")
# # # break
# # # # infer
# # # epoch_beg = 400
# # # epoch_end = 580
# # # for epoch in range(epoch_end, epoch_beg, -50):
# # # print(f"Testing the epoch{epoch}/{epoch_end}")
# # # opt.MODEL.load_epoch = epoch # set load epoch
# # # model.setup(opt) # load model
# # # for i, ibatch_data in enumerate(test_loader):
# # # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=i)
# # # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*100+1))
# # # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*1000+1))
# # # break
+67 -20
View File
@@ -486,42 +486,89 @@
},
{
"cell_type": "code",
"execution_count": 97,
"execution_count": 112,
"metadata": {},
"outputs": [],
"source": [
"def interpolate_features(features, input_rate, output_rate, output_len=None):\n",
" num_features = features.shape[1]\n",
" input_len = features.shape[0]\n",
" \n",
" seq_len = input_len / float(input_rate)\n",
" if output_len is None:\n",
" output_len = int(seq_len * output_rate)\n",
" \n",
" input_timestamps = np.arange(input_len) / float(input_rate)\n",
" output_timestamps = np.arange(output_len) / float(output_rate)\n",
" output_features = np.zeros((output_len, num_features))\n",
" \n",
" for feat in range(num_features):\n",
" output_features[:, feat] = np.interp(output_timestamps,\n",
" input_timestamps,\n",
" features[:, feat])\n",
" return output_features\n",
"\n",
"\n",
"from scipy import interpolate\n",
"def convert_fps(y, source_fps = 30, target_fps=25):\n",
" \"\"\" \n",
" y, (nframes x nc_feat) (with source_fps)\n",
" \"\"\"\n",
"\n",
" nsteps = y.shape[0]\n",
" x = np.arange(0, nsteps, 1)\n",
" # print(\"x:\", x[::30], x[-10:])\n",
" func = interpolate.interp1d(x, y=y, axis=0)\n",
"\n",
" x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)\n",
" # print(\"x_new\", x_new[::30], x_new[-10:])\n",
" y_new = func(x_new)\n",
"\n",
" if source_fps < target_fps:\n",
" y_new = np.concatenate([y_new, y[-1:]])\n",
"\n",
" return y_new\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 65794, 65795, 65805, 65797, 65798, 65799, 65800, 65801, 65802, 65803, 65804, 65806, 65807, 65808, 65809, 65810, 65811, 65812, 65813, 65814, 65815, 65816, 65817, 65818, 65819, 65820, 65821, 65822, 65823, 65824, 65825, 65826, 65827, 65828, 65829, 65830, 65831, 65832, 65833, 65834, 65835, 65836, 65837, 65838, 65839, 65840, 65841, 65842, 65843, 65844, 65845, 65846, 65847, 65848, 65849, 65850, 65851, 65852, 65853, 65854, 65855, 65856, 65857, 65858, 65859, 65860, 65861, 65862, 65863, 65864, 65865, 65866, 65867, 65868, 65869, 65870, 65871, 65872, 65873, 65874, 65875, 65876, 65877, 65878, 65879, 65880, 65881, 65882, 65883, 65884, 65885, 65886, 65887, 65888, 65889, 65890, 65891, 65892, 65893, 65894, 65895, 65896, 65897, 65898, 65899, 65900, 65901, 65902, 65903, 65904, 65905, 65906, 65907, 65908, 65909, 65910, 65911, 65912, 65913, 65914, 65915, 65916, 65917, 65918, 65919, 65920, 65921, 65922, 65923, 65924, 65925, 65926, 65927, 65928, 65929, 65930, 65931, 65932, 65933, 65934, 65935, 65936, 65937, 65938, 65939, 65940, 65941, 65942, 65943, 65944, 65945, 65946, 65947, 65948, 65957, 65949, 65950, 65951, 65952, 65953, 65954, 65955, 65956, 65958, 65959, 65960, 66248, 66249, 66250, 66251, 66252, 66253, 66254, 66255, 66256, 66257, 66258, 66259, 66260, 66261, 66262, 66263, 66264, 66265, 66266, 66267, 66268, 66269, 66270, 66271, 66272, 66273, 66274, 66275, 66276, 66277, 66278, 66279, 66280, 66281, 66282, 66283, 66284, 66285, 66286, 66287, 66288, 66289, 66290, 66291, 66292, 66293, 66294, 66295, 66296, 66297, 66298, 66299, 66300, 66301, 66302, 66303, 66304, 66305, 66306, 66307, 66308, 66309, 66310, 66311, 66312, 66313, 66314, 66315, 66316, 66317, 66318, 66319, 66320, 66321, 66322, 66323, 66324, 66325, 66326, 66327, 66328, 66329, 66330, 66331, 66332, 66333, 66334, 66335, 66336, 66337, 66338, 66339, 66340, 66341, 66342, 66343, 66344, 66345, 66346, 66347, 66348, 66349, 66350, 66351, 66352, 66353, 66354, 66355, 66356, 66357, 66358, 66359, 66360, 66361, 66362, 66363, 66364, 66365, 66366, 66367, 66368, 66369, 66370, 66371, 66372, 66373, 66374, 66375, 66376, 66377, 66378, 66379, 66380, 66381, 66382, 66383, 66384, 66385, 66386, 66387, 66388, 66389, 66390, 66391, 66392, 66393, 66394, 66395, 66396, 66397, 66398, 66399, 66400, 26250, 26251, 26252, 26253, 26254, 26255, 26256, 26257, 26258, 26259, 26260, 26261, 26262, 26263, 26264, 26265, 26266, 26267, 26268, 66630, 66631, 66632, 66633, 66634, 66635, 66636, 66637, 66638, 66639, 66640, 66641, 66642, 66643, 66644, 66645, 66646, 66647, 66648, 66649, 66650, 66651, 66652, 66653, 66654, 66655, 66656, 66657, 66658, 66659, 66660, 66661, 66662, 66663, 66664, 66665, 66666, 66667, 66668, 66669, 66670, 66671, 66672, 66673, 66674, 66675, 66676, 66677, 66678, 66679, 66680, 66681, 66682, 66683, 66684, 66685, 66686, 66687, 66688, 66689, 66690, 66691, 66692, 66693, 66694, 66695, 66696, 66697, 66698, 66699, 66700, 66701, 66702, 66703, 66704, 66705, 66706, 66707, 66708, 66709, 66710, 66711, 66712, 66713, 66714, 66715, 66716, 66717, 66718, 66719, 66720, 66721, 66722, 66723, 66724, 66725, 66726, 66727, 66728, 66729, 66730, 66731, 66732, 66733, 66734, 66735, 66736, 66737, 66738, 66739, 66740, 66741, 66742, 66743, 66744, 66745, 66746, 66747, 66748, 66749, 66750, 66751, 66752, 66753, 66754, 66755, 66756, 66757, 66758, 66759, 66760, 66761, 66762, 66763, 66764, 66765, 66766, 66767, 66768, 66769, 66770, 66771, 66772, 66773, 66774, 66775, 66776, 66777, 66778, 66779, 66780, 66781, 66782, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 138Line truncated
"idx_filter len=24171/ total len=129700, percents = 18.636083269082498 %\n",
"remain idx len=105529/ total len=129700, percents = 81.3639167309175 %\n"
"(12800, 5023, 3)\n",
"(7673, 5023, 3)\n"
]
}
],
"source": [
"\n"
"path_data1 = \"../experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220303-14H18M22S/obama_train_infer_20220217-17H36M22S_epoch_115.npy\"\n",
"path_data1_save = \"../experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220303-14H18M22S/obama_train_infer_20220217-17H36M22S_epoch_115_29_97fps.npy\"\n",
"\n",
"\n",
"data1 = np.load(path_data1)\n",
"data1.shape\n",
"\n",
"data1 = data1.reshape(12800, 5023, 3)\n",
"print(data1.shape)\n",
"\n",
"data2 = convert_fps(data1, source_fps=50, target_fps=29.97265625)\n",
"print(data2.shape)\n"
]
},
{
"cell_type": "code",
"execution_count": 45,
"execution_count": 118,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0.00266631, 0.00262837, 0.00337514, ..., 0.00482252, 0.00508082,\n",
" 0.00521696], dtype=float32)"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"outputs": [],
"source": [
"data[:, 0] "
"data2 = data2.reshape(1, 7673, 5023, 3)\n",
"\n",
"np.save(path_data1_save, data2)"
]
},
{
+363
View File
@@ -0,0 +1,363 @@
rec_perc = np.percentile(data[:, 0], q=75) * 2
vel_perc = np.percentile(data[:, 1], q=75) * 5
print(f"rec_prec 75% = {rec_perc}, vel_perc 75% = {vel_perc}")
processing... > 2021-P01
(129700, 3)
idx_rec len=1208/ total len=129700, percents = 0.9313801079414032 %
idx_vel len=210/ total len=129700, percents = 0.16191210485736315 %
idx_filter len=1407/ total len=129700, percents = 1.084811102544333 %
idx_filter len=35159/ total len=129700, percents = 27.107941403238243 %
remain idx len=94541/ total len=129700, percents = 72.89205859676176 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P01/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P02
(148750, 3)
idx_rec len=1990/ total len=148750, percents = 1.33781512605042 %
idx_vel len=225/ total len=148750, percents = 0.15126050420168066 %
idx_filter len=2201/ total len=148750, percents = 1.4796638655462184 %
idx_filter len=38100/ total len=148750, percents = 25.613445378151262 %
remain idx len=110650/ total len=148750, percents = 74.38655462184875 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P02/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P03
(233050, 3)
idx_rec len=3271/ total len=233050, percents = 1.4035614674962456 %
idx_vel len=536/ total len=233050, percents = 0.22999356361295858 %
idx_filter len=3772/ total len=233050, percents = 1.6185367946792535 %
idx_filter len=78697/ total len=233050, percents = 33.76829006650933 %
remain idx len=154353/ total len=233050, percents = 66.23170993349066 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P03/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P04
(57350, 3)
idx_rec len=307/ total len=57350, percents = 0.5353095030514385 %
idx_vel len=112/ total len=57350, percents = 0.1952920662598082 %
idx_filter len=418/ total len=57350, percents = 0.7288578901482128 %
idx_filter len=15716/ total len=57350, percents = 27.403661726242373 %
remain idx len=41634/ total len=57350, percents = 72.59633827375762 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P04/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P05
(38850, 3)
idx_rec len=309/ total len=38850, percents = 0.7953667953667953 %
idx_vel len=81/ total len=38850, percents = 0.2084942084942085 %
idx_filter len=388/ total len=38850, percents = 0.9987129987129987 %
idx_filter len=12412/ total len=38850, percents = 31.948519948519948 %
remain idx len=26438/ total len=38850, percents = 68.05148005148006 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P05/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P06
(103900, 3)
idx_rec len=777/ total len=103900, percents = 0.7478344562078922 %
idx_vel len=303/ total len=103900, percents = 0.29162656400384984 %
idx_filter len=1044/ total len=103900, percents = 1.0048123195380174 %
idx_filter len=34870/ total len=103900, percents = 33.56111645813282 %
remain idx len=69030/ total len=103900, percents = 66.43888354186718 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P06/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P07
(27950, 3)
idx_rec len=9/ total len=27950, percents = 0.03220035778175313 %
idx_vel len=42/ total len=27950, percents = 0.15026833631484796 %
idx_filter len=51/ total len=27950, percents = 0.18246869409660108 %
idx_filter len=5839/ total len=27950, percents = 20.89087656529517 %
remain idx len=22111/ total len=27950, percents = 79.10912343470483 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P07/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P08
(184000, 3)
idx_rec len=2284/ total len=184000, percents = 1.241304347826087 %
idx_vel len=457/ total len=184000, percents = 0.2483695652173913 %
idx_filter len=2720/ total len=184000, percents = 1.4782608695652173 %
idx_filter len=62221/ total len=184000, percents = 33.81576086956522 %
remain idx len=121779/ total len=184000, percents = 66.18423913043478 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P08/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P09
(21500, 3)
idx_rec len=306/ total len=21500, percents = 1.4232558139534883 %
idx_vel len=222/ total len=21500, percents = 1.0325581395348837 %
idx_filter len=487/ total len=21500, percents = 2.2651162790697676 %
idx_filter len=13897/ total len=21500, percents = 64.63720930232559 %
remain idx len=7603/ total len=21500, percents = 35.36279069767442 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P10
(178750, 3)
idx_rec len=1126/ total len=178750, percents = 0.62993006993007 %
idx_vel len=375/ total len=178750, percents = 0.2097902097902098 %
idx_filter len=1497/ total len=178750, percents = 0.8374825174825175 %
idx_filter len=56091/ total len=178750, percents = 31.37958041958042 %
remain idx len=122659/ total len=178750, percents = 68.62041958041958 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P10/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P11
(73500, 3)
idx_rec len=304/ total len=73500, percents = 0.41360544217687073 %
idx_vel len=162/ total len=73500, percents = 0.22040816326530613 %
idx_filter len=448/ total len=73500, percents = 0.6095238095238096 %
idx_filter len=20965/ total len=73500, percents = 28.523809523809526 %
remain idx len=52535/ total len=73500, percents = 71.47619047619048 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P11/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P12
(51300, 3)
idx_rec len=94/ total len=51300, percents = 0.18323586744639375 %
idx_vel len=86/ total len=51300, percents = 0.16764132553606237 %
idx_filter len=180/ total len=51300, percents = 0.3508771929824561 %
idx_filter len=12907/ total len=51300, percents = 25.159844054580898 %
remain idx len=38396/ total len=51300, percents = 74.84600389863547 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P12/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P14
(18400, 3)
idx_rec len=98/ total len=18400, percents = 0.532608695652174 %
idx_vel len=123/ total len=18400, percents = 0.6684782608695652 %
idx_filter len=202/ total len=18400, percents = 1.0978260869565217 %
idx_filter len=7873/ total len=18400, percents = 42.78804347826087 %
remain idx len=10530/ total len=18400, percents = 57.22826086956522 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P14/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P16
(66400, 3)
idx_rec len=173/ total len=66400, percents = 0.2605421686746988 %
idx_vel len=111/ total len=66400, percents = 0.16716867469879518 %
idx_filter len=279/ total len=66400, percents = 0.42018072289156627 %
idx_filter len=16739/ total len=66400, percents = 25.20933734939759 %
remain idx len=49661/ total len=66400, percents = 74.79066265060241 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P16/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P19
(33350, 3)
idx_rec len=140/ total len=33350, percents = 0.4197901049475262 %
idx_vel len=48/ total len=33350, percents = 0.14392803598200898 %
idx_filter len=186/ total len=33350, percents = 0.5577211394302849 %
idx_filter len=7486/ total len=33350, percents = 22.44677661169415 %
remain idx len=25864/ total len=33350, percents = 77.55322338830585 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P19/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P20
(21300, 3)
idx_rec len=68/ total len=21300, percents = 0.3192488262910798 %
idx_vel len=13/ total len=21300, percents = 0.06103286384976526 %
idx_filter len=81/ total len=21300, percents = 0.38028169014084506 %
idx_filter len=2774/ total len=21300, percents = 13.023474178403756 %
remain idx len=18529/ total len=21300, percents = 86.9906103286385 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P20/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P21
(21300, 3)
idx_rec len=4/ total len=21300, percents = 0.018779342723004695 %
idx_vel len=17/ total len=21300, percents = 0.07981220657276995 %
idx_filter len=21/ total len=21300, percents = 0.09859154929577464 %
idx_filter len=2543/ total len=21300, percents = 11.938967136150234 %
remain idx len=18757/ total len=21300, percents = 88.06103286384976 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P21/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P22
(15700, 3)
idx_rec len=76/ total len=15700, percents = 0.4840764331210191 %
idx_vel len=45/ total len=15700, percents = 0.28662420382165604 %
idx_filter len=118/ total len=15700, percents = 0.7515923566878981 %
idx_filter len=6824/ total len=15700, percents = 43.46496815286624 %
remain idx len=8876/ total len=15700, percents = 56.53503184713376 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P22/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P24
(171900, 3)
idx_rec len=983/ total len=171900, percents = 0.5718440954043048 %
idx_vel len=399/ total len=171900, percents = 0.23211169284467714 %
idx_filter len=1347/ total len=171900, percents = 0.7835951134380453 %
idx_filter len=48662/ total len=171900, percents = 28.308318789994182 %
remain idx len=123238/ total len=171900, percents = 71.69168121000581 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P24/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P25
(74300, 3)
idx_rec len=188/ total len=74300, percents = 0.253028263795424 %
idx_vel len=158/ total len=74300, percents = 0.2126514131897712 %
idx_filter len=323/ total len=74300, percents = 0.4347240915208614 %
idx_filter len=12738/ total len=74300, percents = 17.14401076716016 %
remain idx len=61562/ total len=74300, percents = 82.85598923283983 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P25/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P26
(15250, 3)
idx_rec len=11/ total len=15250, percents = 0.07213114754098361 %
idx_vel len=17/ total len=15250, percents = 0.11147540983606558 %
idx_filter len=26/ total len=15250, percents = 0.17049180327868851 %
idx_filter len=1873/ total len=15250, percents = 12.281967213114754 %
remain idx len=13377/ total len=15250, percents = 87.71803278688525 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P26/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P27
(55700, 3)
idx_rec len=194/ total len=55700, percents = 0.348294434470377 %
idx_vel len=45/ total len=55700, percents = 0.0807899461400359 %
idx_filter len=239/ total len=55700, percents = 0.42908438061041293 %
idx_filter len=8551/ total len=55700, percents = 15.351885098743267 %
remain idx len=47149/ total len=55700, percents = 84.64811490125673 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P27/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P29
(35700, 3)
idx_rec len=91/ total len=35700, percents = 0.2549019607843137 %
idx_vel len=48/ total len=35700, percents = 0.13445378151260504 %
idx_filter len=128/ total len=35700, percents = 0.3585434173669468 %
idx_filter len=4113/ total len=35700, percents = 11.521008403361344 %
remain idx len=31587/ total len=35700, percents = 88.47899159663865 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P29/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P30
(163500, 3)
idx_rec len=901/ total len=163500, percents = 0.5510703363914373 %
idx_vel len=237/ total len=163500, percents = 0.14495412844036698 %
idx_filter len=1115/ total len=163500, percents = 0.6819571865443425 %
idx_filter len=34727/ total len=163500, percents = 21.239755351681957 %
remain idx len=128773/ total len=163500, percents = 78.76024464831804 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P30/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P31
(162650, 3)
idx_rec len=433/ total len=162650, percents = 0.2662158007992622 %
idx_vel len=147/ total len=162650, percents = 0.09037811251152782 %
idx_filter len=580/ total len=162650, percents = 0.35659391331079004 %
idx_filter len=24896/ total len=162650, percents = 15.306486320319705 %
remain idx len=137754/ total len=162650, percents = 84.6935136796803 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P31/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P32
(9000, 3)
idx_rec len=40/ total len=9000, percents = 0.4444444444444444 %
idx_vel len=7/ total len=9000, percents = 0.07777777777777778 %
idx_filter len=47/ total len=9000, percents = 0.5222222222222223 %
idx_filter len=1334/ total len=9000, percents = 14.822222222222223 %
remain idx len=7666/ total len=9000, percents = 85.17777777777778 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P32/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P33
(66850, 3)
idx_rec len=984/ total len=66850, percents = 1.4719521316379955 %
idx_vel len=195/ total len=66850, percents = 0.2916978309648467 %
idx_filter len=1130/ total len=66850, percents = 1.6903515332834704 %
idx_filter len=18149/ total len=66850, percents = 27.148840688107704 %
remain idx len=48701/ total len=66850, percents = 72.8511593118923 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P33/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P34
(11700, 3)
idx_rec len=17/ total len=11700, percents = 0.1452991452991453 %
idx_vel len=10/ total len=11700, percents = 0.08547008547008547 %
idx_filter len=27/ total len=11700, percents = 0.23076923076923078 %
idx_filter len=1916/ total len=11700, percents = 16.376068376068375 %
remain idx len=9784/ total len=11700, percents = 83.62393162393163 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P34/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P35
(31950, 3)
idx_rec len=65/ total len=31950, percents = 0.20344287949921752 %
idx_vel len=73/ total len=31950, percents = 0.22848200312989045 %
idx_filter len=133/ total len=31950, percents = 0.4162754303599374 %
idx_filter len=7522/ total len=31950, percents = 23.54303599374022 %
remain idx len=24428/ total len=31950, percents = 76.45696400625978 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P35/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P36
(15100, 3)
idx_rec len=478/ total len=15100, percents = 3.165562913907285 %
idx_vel len=26/ total len=15100, percents = 0.17218543046357615 %
idx_filter len=502/ total len=15100, percents = 3.3245033112582782 %
idx_filter len=4708/ total len=15100, percents = 31.178807947019866 %
remain idx len=10392/ total len=15100, percents = 68.82119205298014 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P36/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P37
(164200, 3)
idx_rec len=705/ total len=164200, percents = 0.42935444579780757 %
idx_vel len=138/ total len=164200, percents = 0.08404384896467722 %
idx_filter len=840/ total len=164200, percents = 0.5115712545676004 %
idx_filter len=23842/ total len=164200, percents = 14.520097442143728 %
remain idx len=140358/ total len=164200, percents = 85.47990255785628 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P37/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P38
(69050, 3)
idx_rec len=250/ total len=69050, percents = 0.3620564808110065 %
idx_vel len=58/ total len=69050, percents = 0.08399710354815351 %
idx_filter len=308/ total len=69050, percents = 0.44605358435916004 %
idx_filter len=8673/ total len=69050, percents = 12.560463432295439 %
remain idx len=60377/ total len=69050, percents = 87.43953656770456 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P38/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P39
(22400, 3)
idx_rec len=164/ total len=22400, percents = 0.7321428571428571 %
idx_vel len=33/ total len=22400, percents = 0.14732142857142858 %
idx_filter len=189/ total len=22400, percents = 0.84375 %
idx_filter len=4261/ total len=22400, percents = 19.022321428571427 %
remain idx len=18139/ total len=22400, percents = 80.97767857142857 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P39/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P40
(15700, 3)
idx_rec len=0/ total len=15700, percents = 0.0 %
idx_vel len=1/ total len=15700, percents = 0.006369426751592357 %
idx_filter len=1/ total len=15700, percents = 0.006369426751592357 %
idx_filter len=153/ total len=15700, percents = 0.9745222929936306 %
remain idx len=15547/ total len=15700, percents = 99.02547770700637 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P40/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P41
(50450, 3)
idx_rec len=344/ total len=50450, percents = 0.6818632309217046 %
idx_vel len=137/ total len=50450, percents = 0.27155599603567887 %
idx_filter len=470/ total len=50450, percents = 0.931615460852329 %
idx_filter len=15452/ total len=50450, percents = 30.62834489593657 %
remain idx len=35001/ total len=50450, percents = 69.37760158572844 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P41/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P42
(15100, 3)
idx_rec len=12/ total len=15100, percents = 0.07947019867549669 %
idx_vel len=27/ total len=15100, percents = 0.17880794701986755 %
idx_filter len=36/ total len=15100, percents = 0.23841059602649006 %
idx_filter len=3237/ total len=15100, percents = 21.43708609271523 %
remain idx len=11863/ total len=15100, percents = 78.56291390728477 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P42/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P43
(173900, 3)
idx_rec len=745/ total len=173900, percents = 0.4284071305347901 %
idx_vel len=291/ total len=173900, percents = 0.16733755031627373 %
idx_filter len=1020/ total len=173900, percents = 0.58654399079931 %
idx_filter len=39644/ total len=173900, percents = 22.79700977573318 %
remain idx len=134259/ total len=173900, percents = 77.20471535365152 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P43/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P44
(52750, 3)
idx_rec len=308/ total len=52750, percents = 0.5838862559241706 %
idx_vel len=70/ total len=52750, percents = 0.13270142180094788 %
idx_filter len=373/ total len=52750, percents = 0.7071090047393365 %
idx_filter len=8045/ total len=52750, percents = 15.251184834123222 %
remain idx len=44705/ total len=52750, percents = 84.74881516587678 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P44/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P45
(21450, 3)
idx_rec len=23/ total len=21450, percents = 0.10722610722610723 %
idx_vel len=6/ total len=21450, percents = 0.027972027972027972 %
idx_filter len=29/ total len=21450, percents = 0.1351981351981352 %
idx_filter len=1112/ total len=21450, percents = 5.1841491841491845 %
remain idx len=20338/ total len=21450, percents = 94.81585081585082 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P45/audio/idx_w150_20220228-18H41M46S_175.npy
processing... > 2021-P46
(36100, 3)
idx_rec len=234/ total len=36100, percents = 0.6481994459833795 %
idx_vel len=38/ total len=36100, percents = 0.10526315789473684 %
idx_filter len=272/ total len=36100, percents = 0.7534626038781164 %
idx_filter len=7231/ total len=36100, percents = 20.030470914127424 %
remain idx len=28869/ total len=36100, percents = 79.96952908587258 %
save to > /yrfs/lsen/DATA/LuoXData/processing2/2021-P46/audio/idx_w150_20220228-18H41M46S_175.npy
+279
View File
@@ -0,0 +1,279 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Moviepy - Building video ../../coolTextEffects.avi.\n",
"Moviepy - Writing video ../../coolTextEffects.avi\n",
"\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
" "
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Moviepy - Done !\n",
"Moviepy - video ready ../../coolTextEffects.avi\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"\r"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"from moviepy.editor import *\n",
"from moviepy.video.tools.segmenting import findObjects\n",
"\n",
"# WE CREATE THE TEXT THAT IS GOING TO MOVE, WE CENTER IT.\n",
"\n",
"screensize = (720,460)\n",
"txtClip = TextClip('Cool effect',color='white', font=\"Amiri-Bold\",\n",
" kerning = 5, fontsize=100)\n",
"cvc = CompositeVideoClip( [txtClip.set_pos('center')],\n",
" size=screensize)\n",
"\n",
"# THE NEXT FOUR FUNCTIONS DEFINE FOUR WAYS OF MOVING THE LETTERS\n",
"\n",
"\n",
"# helper function\n",
"rotMatrix = lambda a: np.array( [[np.cos(a),np.sin(a)], \n",
" [-np.sin(a),np.cos(a)]] )\n",
"\n",
"def vortex(screenpos,i,nletters):\n",
" d = lambda t : 1.0/(0.3+t**8) #damping\n",
" a = i*np.pi/ nletters # angle of the movement\n",
" v = rotMatrix(a).dot([-1,0])\n",
" if i%2 : v[1] = -v[1]\n",
" return lambda t: screenpos+400*d(t)*rotMatrix(0.5*d(t)*a).dot(v)\n",
" \n",
"def cascade(screenpos,i,nletters):\n",
" v = np.array([0,-1])\n",
" d = lambda t : 1 if t<0 else abs(np.sinc(t)/(1+t**4))\n",
" return lambda t: screenpos+v*400*d(t-0.15*i)\n",
"\n",
"def arrive(screenpos,i,nletters):\n",
" v = np.array([-1,0])\n",
" d = lambda t : max(0, 3-3*t)\n",
" return lambda t: screenpos-400*v*d(t-0.2*i)\n",
" \n",
"def vortexout(screenpos,i,nletters):\n",
" d = lambda t : max(0,t) #damping\n",
" a = i*np.pi/ nletters # angle of the movement\n",
" v = rotMatrix(a).dot([-1,0])\n",
" if i%2 : v[1] = -v[1]\n",
" return lambda t: screenpos+400*d(t-0.1*i)*rotMatrix(-0.2*d(t)*a).dot(v)\n",
"\n",
"\n",
"\n",
"# WE USE THE PLUGIN findObjects TO LOCATE AND SEPARATE EACH LETTER\n",
"\n",
"letters = findObjects(cvc) # a list of ImageClips\n",
"\n",
"\n",
"# WE ANIMATE THE LETTERS\n",
"\n",
"def moveLetters(letters, funcpos):\n",
" return [ letter.set_pos(funcpos(letter.screenpos,i,len(letters)))\n",
" for i,letter in enumerate(letters)]\n",
"\n",
"clips = [ CompositeVideoClip( moveLetters(letters,funcpos),\n",
" size = screensize).subclip(0,5)\n",
" for funcpos in [vortex, cascade, arrive, vortexout] ]\n",
"\n",
"# WE CONCATENATE EVERYTHING AND WRITE TO A FILE\n",
"\n",
"final_clip = concatenate_videoclips(clips)\n",
"final_clip.write_videofile('../../coolTextEffects.avi',fps=25,codec='mpeg4')"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"\n",
"import resampy\n",
"import random\n",
"import numpy as np\n",
"import numpy as np\n",
"from scipy import interpolate\n",
"\n",
"\n",
"def resample_by_nsteps(feat, nsteps_tgt):\n",
" \"\"\" \n",
" feat, (nframes, ... ) (with source_fps)\n",
" \"\"\"\n",
"\n",
" nsteps_src = feat.shape[0]\n",
" data_idx = np.arange(0, nsteps_src, 1)\n",
" samp_idx = np.arange(0, nsteps_src-1, (nsteps_src - 1) / nsteps_tgt)\n",
" # print(f\"data_idx = {list(data_idx)}\")\n",
" # print(f\"smap_idx = {list(samp_idx)}\")\n",
" # sample\n",
" func = interpolate.interp1d(data_idx, y=feat, axis=0)\n",
" data_interpolate = func(samp_idx)\n",
"\n",
" return data_interpolate\n",
"\n",
"\n",
"# def convert_fps(feat, source_fps = 30, target_fps=25):\n",
"# \"\"\" \n",
"# feat, (nframes, ... ) (with source_fps)\n",
"# \"\"\"\n",
"\n",
"# nsize = feat.shape[0]\n",
"# data_idx = np.arange(0, nsize, 1)\n",
"# samp_idx = np.arange(0, nsize-1, 1.0*source_fps/target_fps)\n",
"\n",
"\n",
"# print(f\"1.0*source_fps/target_fps = {1.0*source_fps/target_fps}\")\n",
"\n",
"# # get sample idx\n",
"# # if source_fps > target_fps:\n",
"\n",
"# print(f\"data_idx = {list(data_idx)}\")\n",
"# print(f\"smap_idx = {list(samp_idx)}\")\n",
"\n",
"# # sample\n",
"# func = interpolate.interp1d(data_idx, y=feat, axis=0)\n",
"# data_interpolate = func(samp_idx)\n",
"\n",
"# del func\n",
"\n",
"# return data_interpolate\n",
"\n",
"\n",
"\n",
"def interpolate_feat(feat, input_rate, output_rate, nsteps_tgt=None):\n",
" \n",
" feat_shape = feat.shape\n",
" feat = feat.reshape(feat_shape[0], -1)\n",
"\n",
" dim_feat = feat.shape[1]\n",
"\n",
" nsteps_src = feat.shape[0]\n",
"\n",
"\n",
" seq_len = nsteps_src / float(input_rate)\n",
" if nsteps_tgt is None:\n",
" nsteps_tgt = int(seq_len * output_rate)\n",
"\n",
" input_timestamps = np.arange(nsteps_src) / float(input_rate)\n",
" output_timestamps = np.arange(nsteps_tgt) / float(output_rate)\n",
" output_feat = np.zeros((nsteps_tgt, dim_feat))\n",
"\n",
" for feat in range(dim_feat):\n",
" output_feat[:, feat] = np.interp(output_timestamps,\n",
" input_timestamps,\n",
" feat[:, feat])\n",
" return output_feat"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(150, 1024)"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\n",
"data.shape"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"nsteps = 150, random speed = 0.9, nsteps_speed = 135\n",
"data_idx = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134]\n",
"smap_idx = [0.0, 0.8933333333333333, 1.7866666666666666, 2.6799999999999997, 3.5733333333333333, 4.466666666666667, 5.359999999999999, 6.253333333333333, 7.1466666666666665, 8.04, 8.933333333333334, 9.826666666666666, 10.719999999999999, 11.613333333333333, 12.506666666666666, 13.4, 14.293333333333333, 15.186666666666666, 16.08, 16.973333333333333, 17.866666666666667, 18.759999999999998, 19.653333333333332, 20.546666666666667, 21.439999999999998, 22.333333333333332, 23.226666666666667, 24.12, 25.013333333333332, 25.906666666666666, 26.8, 27.69333333333333, 28.586666666666666, 29.48, 30.37333333333333, 31.266666666666666, 32.16, 33.053333333333335, 33.946666666666665, 34.839999999999996, 35.733333333333334, 36.626666666666665, 37.519999999999996, 38.413333333333334, 39.306666666666665, 40.199999999999996, 41.093333333333334, 41.986666666666665, 42.879999999999995, 43.77333333333333, 44.666666666666664, 45.56, 46.45333333333333, 47.346666666666664, 48.24, 49.13333333333333, 50.026666666666664, 50.92, 51.81333333333333, 52.70666666666666, 53.6, 54.49333333333333, 55.38666666666666, 56.28, 57.17333333333333, 58.06666666666666, 58.96, 59.85333333333333, 60.74666666666666, 61.64, 62.53333333333333, 63.42666666666666, 64.32, 65.21333333333334, 66.10666666666667, 67.0, 67.89333333333333, 68.78666666666666, 69.67999999999999, 70.57333333333334, 71.46666666666667, 72.36, 73.25333333333333, 74.14666666666666, 75.03999999999999, 75.93333333333334, 76.82666666666667, 77.72, 78.61333333333333, 79.50666666666666, 80.39999999999999, 81.29333333333334, 82.18666666666667, 83.08, 83.97333333333333, 84.86666666666666, 85.75999999999999, 86.65333333333334, 87.54666666666667, 88.44, 89.33333333333333, 90.22666666666666, 91.12, 92.01333333333334, 92.90666666666667, 93.8, 94.69333333333333, 95.58666666666666, 96.48, 97.37333333333333, 98.26666666666667, 99.16, 100.05333333333333, 100.94666666666666, 101.84, 102.73333333333333, 103.62666666666667, 104.52, 105.41333333333333, 106.30666666666666, 107.2, 108.09333333333333, 108.98666666666666, 109.88, 110.77333333333333, 111.66666666666666, 112.56, 113.45333333333333, 114.34666666666666, 115.24, 116.13333333333333, 117.02666666666667, 117.92, 118.81333333333333, 119.70666666666666, 120.6, 121.49333333333333, 122.38666666666667, 123.28, 124.17333333333333, 125.06666666666666, 125.96, 126.85333333333332, 127.74666666666667, 128.64, 129.53333333333333, 130.42666666666668, 131.32, 132.21333333333334, 133.10666666666665]\n",
"data shape = (135, 1024), data_convert = (150, 1024), nstep_speed=135\n"
]
}
],
"source": [
"data = np.random.random(size=(150, 1024))\n",
"nsteps = data.shape[0]\n",
"\n",
"speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]\n",
"nsteps_speed = int(nsteps * speed)\n",
"\n",
"data = np.random.random(size=(nsteps_speed, 1024))\n",
"\n",
"print(f\"nsteps = {nsteps}, random speed = {speed}, nsteps_speed = {nsteps_speed}\")\n",
"\n",
"data_convert = resample_by_nsteps(data, nsteps_tgt=nsteps)\n",
"\n",
"print(f\"data shape = {data.shape}, data_convert = {data_convert.shape}, nstep_speed={nsteps_speed}\")\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"interpreter": {
"hash": "7631c3454b293d59f44fb25da873c3d73daf8a0a859dfd3174f920d540a4d0d0"
},
"kernelspec": {
"display_name": "Python 3.8.8 ('base')",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
+125
View File
@@ -0,0 +1,125 @@
from pathlib import Path
import json
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_root = Path("/yrfs/lsen/DATA/Actor1")
vpath_videos = sorted(path_root.glob("raw/*.MP4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
IDs = ["1-29min", "2-23min", "3-27min"]
# 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 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
# if ipath_infor.exists():
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# 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
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0)
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()))
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframes:
print(f"\n Skip: have already done!")
continue
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
@@ -0,0 +1,155 @@
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:3"
# 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("/yrfs/lsen/DATA/Actor1/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 ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print("\nprocessing ...", ivideo_name)
# if ivideo_name not in IDs: continue
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())
+101
View File
@@ -0,0 +1,101 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# path_data = Path('/yrfs/lsen/DATA/TestData/processing') # '../data/trinity/source'
path_data = Path("/yrfs/lsen/DATA/Actor1/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! ")
@@ -25,8 +25,10 @@ def tensor2image(tensor):
if __name__ == "__main__":
# load data
pid = "1645666605877506" # "2021-P22"
path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
pid = "2022-P01" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor1/processing")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
@@ -53,7 +55,7 @@ if __name__ == "__main__":
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pos_no_idn.mp4")
path_save = path_data.joinpath("video/deca_render_no_pos.mp4")
v_render_pt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
@@ -67,8 +69,8 @@ if __name__ == "__main__":
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)
# 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"]]
+62
View File
@@ -0,0 +1,62 @@
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/TestData/processing/1645666605877506/video/predict_compare_3.mp4"
path_clipA = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render.mp4"
path_clipB = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render_no_pos.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/TestData/processing/1645666605877506/audio/audio_trim.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
# 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)
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}")
+120
View File
@@ -0,0 +1,120 @@
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
fid = "AA7A9571"
path_root = Path("/yrfs/lsen/DATA/Actor2/processing")
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 ipath_coeff in vpath_coeff:
data_coeff = np.load(ipath_coeff, allow_pickle=True).item()
# print(data_coeff.keys())
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, )
}
path_save = "./data/Actor2/DECA_Actor2_mean.npy"
np.save(path_save, mean_DECA)
print("save to --> ", path_save)
print(f"mean deca = \n {mean_DECA}")
# Have 21499 frames
# 'cam': array([ 9.8221273e+00, -9.2755520e-04, 2.8869644e-02], dtype=float32),
# 'pose': array([ 0.04063781, -0.00623041, -0.01067916,
# 0.11206006, 0.00411261, 0.02320058], dtype=float32),
# 'exp': array([-0.6491158 , -0.0998203 , 0.10486019, 0.37043977, -0.29840025,
# -0.41017675, 0.327057 , 0.04885808, -0.06325228, 0.4434316 ,
# 0.05493879, 0.66853815, -0.10403663, 0.01440001, 0.25900015,
# -0.46350944, -0.41076973, -0.10278799, -0.08775225, 0.51222765,
# 0.10053314, -0.26408502, 0.11820181, -0.05676581, 0.02643572,
# 0.16058844, -0.11792275, 0.12630136, -0.23953533, -0.10915831,
# -0.16660552, 0.00958887, 0.2679962 , -0.26946628, 0.19901456,
# -0.09804437, -0.03807065, -0.12970755, 0.01078465, 0.19384004,
# -0.06548703, -0.03329738, 0.11319494, -0.02613433, 0.02363422,
# 0.02380173, -0.11122038, 0.13734889, 0.1255798 , 0.13813666],
# dtype=float32),
# 'shape': array([ 0.00951388, -0.22505675, -0.53953266, -0.4397285 , 0.37905172,
# 0.11540896, -0.36891365, -0.218832 , -0.3684414 , 0.24644622,
# 0.6223965 , -0.16298303, -0.35899413, -0.11834836, -0.04909257,
# -0.13188031, 0.35037243, -0.10429271, 0.25443867, -0.18088193,
# 0.16413063, 0.20566346, 0.0501059 , -0.19294368, -0.00809607,
# -0.08120474, -0.07019995, 0.01174292, 0.33962983, 0.04500978,
# -0.25193816, -0.2265279 , 0.14124256, 0.21158281, -0.09555811,
# 0.14076404, 0.04877019, 0.03229018, -0.00235608, -0.08356833,
# 0.09741616, 0.2644469 , 0.13229795, -0.14537199, -0.2314888 ,
# -0.48501098, -0.13492987, -0.13772976, -0.18299519, -0.11046503,
# 0.04127223, -0.4613573 , -0.06382176, 0.08914807, 0.08793663,
# 0.11848436, 0.03956904, 0.04172374, -0.04793308, 0.30301905,
# -0.06345342, 0.04190513, 0.13665007, -0.03253645, 0.08728135,
# 0.06684338, 0.02282041, 0.00583193, -0.11710295, -0.06365721,
# -0.00492529, -0.14196472, 0.03584495, -0.00815303, -0.00147824,
# 0.2087406 , -0.11037645, -0.04405028, -0.129121 , 0.03147175,
# -0.03467533, -0.00330734, 0.13060835, -0.02846657, 0.05666886,
# -0.07806987, -0.17371002, 0.05375125, -0.04018219, 0.08453278,
# -0.05303599, -0.11419729, -0.16071273, -0.00130347, -0.1172006 ,
# -0.06073425, -0.03826162, -0.0587554 , -0.06399846, -0.14208533],
# dtype=float32)}
+130
View File
@@ -0,0 +1,130 @@
from pathlib import Path
import json
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_raw = Path("/ssdata1/cf/data/raw/20220311")
path_root = Path("/yrfs/lsen/DATA/Actor2")
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["clip_full"]
# for each video
for i, ipath_item in enumerate(vpath_videos[2:]):
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
if ipath_infor.exists():
continue
# with open(str(ipath_infor), "r") as f:
# info = json.load(f)
# nframe_info = info['nframes']
# 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
# 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()))
# check frames
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframes:
# print(f"\n Skip: have already done!")
# continue
# get audio
audio_sub = video.audio
if audio_sub is None:
print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}")
# # check fps
# if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...")
# save video feature
info = {"nframes": nframes,
"fps": video.fps,
"width": video.w,
"height": video.h}
with open(str(ipath_infor), 'w+') as f:
json.dump(info, f)
print(info)
print(f"save video info in -> {ipath_infor}\n")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50)
@@ -0,0 +1,157 @@
import os, sys
import numpy as np
import cv2
from time import time
import argparse
import json
from pathlib import Path
from torch.utils.data import DataLoader
sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old')
from decalib.deca import DECA
from decalib.datasets.datasets2 import ObamaData
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def main(args):
# device = args.device
device = "cuda:0"
# 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("/yrfs/lsen/DATA/Actor2/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 > 18: 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())
@@ -7,11 +7,12 @@ from pathlib import Path
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/TestData/processing') # '../data/trinity/source'
# path_data = Path('/yrfs/lsen/DATA/TestData/processing') # '../data/trinity/source'
path_data = Path("/yrfs/lsen/DATA/Actor2/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:
@@ -0,0 +1,103 @@
import sys
import numpy as np
import torch
from pathlib import Path
# common
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion")
from common.animation import save_images_with_audio
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
if __name__ == "__main__":
# load data
device = torch.device("cuda:4")
pid = "AA7A9568" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor2/processing")
path_data = path_root.joinpath(pid)
path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy")
path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy")
path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy")
# path_audio = path_data.joinpath("audio/audio_trim.wav")
path_audio = path_data.joinpath("audio/audio_trim_120s.wav")
# data_pos = np.load(path_pos)[:] # N x 6
# data_idn = np.load(path_idn) # N x 100
# data_exp = np.load(path_exp) # N x 50
# N = data_exp.shape[0]
data_pos = np.load(path_pos)[:6000] # N x 6
data_idn = np.load(path_idn)[:6000] # N x 100
data_exp = np.load(path_exp)[:6000] # N x 50
N = data_exp.shape[0]
# load mean
path_deca_mean = Path("./data/Actor2/DECA_Actor2_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
netR = DECA(config = deca_cfg, device=device)
# render
path_save = path_data.joinpath("video/deca_render_no_pos_trim_120s.mp4")
v_render_pt = []
nbatch_render = 5
for k in range(0, N, nbatch_render):
codedict = {}
codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = codedict["exp"].shape[0]
codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6)
codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6]
# codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6)
# codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100)
codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100)
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = netR.decode_one(codedict, nbatch_real, device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
save_images_with_audio(v_render_pt, path_audio, path_save)
@@ -0,0 +1,182 @@
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("/yrfs/lsen/DATA/Actor2/processing")
path_save = Path('data/Actor2/Actor2-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(["AA7A9568"])
vid_valid = set(["AA7A9569"])
vid_train = vids - vid_test - vid_valid
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
if durations_train / 3600 > 2: 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,
}
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"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}")
+65
View File
@@ -0,0 +1,65 @@
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_22.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_CN_20220312/20220314-15H08M06S/audio_trim_120s_infer_20220313-13H26M47S_epoch_100_002.mp4"
path_clipB = "/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
video = video.set_audio(audio) # audd audio
# save
video.write_videofile(path_save, fps=fps_save, logger=None)
print(f"save to > {path_save}")
@@ -31,12 +31,9 @@ if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
path_save = Path('data/LuoXData-raw-deca-3min') # processing
path_save = Path('data/LuoXData-raw-16h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files, \n {v_dir_videos[:3]}")
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
@@ -44,14 +41,14 @@ if __name__ == "__main__":
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
# vid_test = set(["2021-P09", "2021-P22"])
# vid_valid = set(["2021-P14", "2021-P20"])
# vid_train = vids - vid_test - vid_test
vid_test = set(["2021-P09", "2021-P22"])
vid_valid = set(["2021-P14", "2021-P20"])
vid_train = vids - vid_test - vid_valid
vids = set(["2021-P09", "2021-P14", "2021-P22"])
vid_test = set(["2021-P09" ])
vid_valid = set(["2021-P14" ])
vid_train = set(["2021-P22" ])
# 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}")
@@ -63,6 +60,9 @@ if __name__ == "__main__":
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")
@@ -70,6 +70,7 @@ if __name__ == "__main__":
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")
ipath_idx = ipath_data.joinpath("audio/idx_w150_20220228-18H41M46S_175.npy")
# check existing
if not ipath_speech.exists():
@@ -93,6 +94,7 @@ if __name__ == "__main__":
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
data_idx = np.load(ipath_idx, allow_pickle=True).tolist() # (nframe_for_sampling, ), set
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}"
@@ -115,16 +117,15 @@ if __name__ == "__main__":
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]
####################################
# ####################################
# # 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
@@ -136,40 +137,49 @@ if __name__ == "__main__":
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
"idx_sampling": data_idx,
}
if durations_train / 3600 > 16:
break
if vid in vid_valid:
durations_valid += nframes/fps
# 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,
}
# data_valid[vid] = {
# "fps": info["fps"],
# "sr": 16000,
# "nframe": nframes,
# "data_motion": data_motion,
# "data_speech": audio_raw,
# "data_shape": data_idn,
# "idx_sampling": data_idx,
# }
if vid in vid_test:
durations_test += nframes/fps
# 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,
# "idx_sampling": data_idx,
# }
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_idn,
}
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)
# 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"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
# 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}")
+12 -13
View File
@@ -18,13 +18,14 @@ if __name__ == "__main__":
path_clipA = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-19H47M15S/audio_trim_60_120s_infer_20220217-18H29M20S_epoch_160_00.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220302-10H48M39S/audio_trim_60_120s_infer_20220228-18H41M46S_epoch_175_00.mp4"
path_clipC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_idn_no_pos_60_120s.mp4"
path_clipC = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220303-19H05M13S/audio_trim_60_120s_infer_20220303-14H22M20S_epoch_025_00.mp4"
# path_clipC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_idn_no_pos_60_120s.mp4"
# # path_audio = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav"
path_clipAA = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220302-10H38M39S/audio_trim_60_120s_infer_20220225-19H08M53S_epoch_280_00.mp4"
path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
# path_clipAA = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4"
# path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220302-10H38M39S/audio_trim_60_120s_infer_20220225-19H08M53S_epoch_280_00.mp4"
path_clipD = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.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"
@@ -34,10 +35,11 @@ if __name__ == "__main__":
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
clip_D = mpy.VideoFileClip(path_clipD)
clip_AA = mpy.VideoFileClip(path_clipAA)
clip_BB = mpy.VideoFileClip(path_clipBB)
clip_CC = mpy.VideoFileClip(path_clipCC)
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
# clip_CC = mpy.VideoFileClip(path_clipCC)
audio = mpy.AudioFileClip(path_audio)
@@ -59,15 +61,12 @@ if __name__ == "__main__":
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 = 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_D]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
path_save = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/predict_compare_20220302.mp4"
path_save = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/predict_compare4_20220303.mp4"
# path_save = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220216-12H58M21S/compare_voca.mp4"
video.write_videofile(path_save, fps=50, logger=None)
print(f"save to > {path_save}")
@@ -6,7 +6,7 @@ from scipy import interpolate
def convert_fps(y, source_fps = 30, target_fps=25):
"""
y, N x 136, with 30fps
y, nframes x nc_feat (with source_fps)
"""
nsteps = y.shape[0]
@@ -27,7 +27,7 @@ def convert_fps(y, source_fps = 30, target_fps=25):
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-raw-deca-9h-50fps') # processing
path_save = Path('data/obama-raw-deca-8h-50fps') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
@@ -38,6 +38,7 @@ if __name__ == "__main__":
vid_test = set(vids[:2])
vid_valid = set(vids[2:4])
vid_train = set(vids) - vid_test - vid_valid
print("vid_test = ", vid_test)
print("vid_valid = ", vid_valid)
@@ -48,12 +49,15 @@ if __name__ == "__main__":
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_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
# ipath_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
if not ipath_speech.exists():
@@ -90,7 +94,7 @@ if __name__ == "__main__":
# load data
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
feat_pos = np.load(ipath_pos) # (nframe_trim, 6)
feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
# feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
feat_pos_head = feat_pos[:, :3] # (nframe_trim, 3)
feat_pos_lips = feat_pos[:, 3:] # (nframe_trim, 3)
@@ -103,10 +107,9 @@ if __name__ == "__main__":
# resample to 30fps
fps_convert = 50
data_motion = convert_fps(data_motion, source_fps=fps, target_fps=fps_convert)
data_shape = convert_fps(feat_idn, source_fps=fps, target_fps=fps_convert)
# data_shape = convert_fps(feat_idn, source_fps=fps, target_fps=fps_convert)
nframe_convert = data_motion.shape[0]
assert data_motion.shape[0] == data_shape.shape[0], f"motion = {data_motion.shape[0]} shape = {data_shape.shape[0]}"
# assert data_motion.shape[0] == data_shape.shape[0], f"motion = {data_motion.shape[0]} shape = {data_shape.shape[0]}"
print(f"after convert motion = {data_motion.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}")
# print(f"after convert shape = {data_shape.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}")
@@ -131,38 +134,43 @@ if __name__ == "__main__":
"nframe": nframe_convert,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_shape,
# "data_shape": data_shape,
}
if vid in vid_valid:
durations_valid += nframe_trim / fps
data_valid[vid] = {
"W": width, "H": height,
"sr":16000, "FPS": fps_convert,
"nframe": nframe_convert,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_shape,
}
if durations_train / 3600 > 8:
break
if vid in vid_test:
durations_test += nframe_trim / fps
data_test[vid] = {
"W": width, "H": height,
"sr":16000, "FPS": fps_convert,
"nframe": nframe_convert,
"data_motion": data_motion,
"data_speech": audio_raw,
"data_shape": data_shape,
}
# if vid in vid_valid:
# durations_valid += nframe_trim / fps
# data_valid[vid] = {
# "W": width, "H": height,
# "sr":16000, "FPS": fps_convert,
# "nframe": nframe_convert,
# "data_motion": data_motion,
# "data_speech": audio_raw,
# # "data_shape": data_shape,
# }
# if vid in vid_test:
# durations_test += nframe_trim / fps
# data_test[vid] = {
# "W": width, "H": height,
# "sr":16000, "FPS": fps_convert,
# "nframe": nframe_convert,
# "data_motion": data_motion,
# "data_speech": audio_raw,
# # "data_shape": data_shape,
# }
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)
# 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 / 3600} h), data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
# 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 / 3600} h), data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")
+19 -10
View File
@@ -8,23 +8,31 @@ from pathlib import Path
if __name__ == "__main__":
fps_save = 30
path_save = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/audio2mesh_compare_60_115_GT.mp4"
fps_save = 50
# path_save = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/audio2mesh_compare_60_115_GT.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H57M52S/audio_trim_60_120s_infer_20220217-17H36M22S_epoch_115_00.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H48M06S/audio_trim_60_120s_infer_20220223-22H17M02S_epoch_060_00.mp4"
path_clipC = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/deca_render_no_pose_60_120s.mp4"
path_save = "./data/compare_test_obama.mp4"
path_clipA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220303-14H18M22S/obama_train_infer_20220217-17H36M22S_epoch_115_00.mp4"
path_clipB = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220303-14H15M46S/obama_train_infer_20220223-22H17M02S_epoch_060_00.mp4"
# path_clipC = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/deca_render_no_pose_60_120s.mp4"
# path_clipA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H57M52S/audio_trim_60_120s_infer_20220217-17H36M22S_epoch_115_00.mp4"
# path_clipB = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H48M06S/audio_trim_60_120s_infer_20220223-22H17M02S_epoch_060_00.mp4"
# path_clipC = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/deca_render_no_pose_60_120s.mp4"
# path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220224-17H27M45S/audio_trim_120s_infer_20220223-22H17M02S_epoch_060_00.mp4"
# path_clipBB = "/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/video/deca_render_no_pose_120s.mp4"
# path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4"
path_audio = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav"
path_audio = "/yrfs/cf/data/render/obama_train.wav"
# path_audio = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav"
clip_A = mpy.VideoFileClip(path_clipA)
clip_B = mpy.VideoFileClip(path_clipB)
clip_C = mpy.VideoFileClip(path_clipC)
# clip_C = mpy.VideoFileClip(path_clipC)
# clip_AA = mpy.VideoFileClip(path_clipAA)
# clip_BB = mpy.VideoFileClip(path_clipBB)
@@ -42,16 +50,17 @@ if __name__ == "__main__":
# clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512))
# align to clipGT
duration = min(min(clip_A.duration, clip_C.duration), audio.duration)
# duration = min(min(clip_A.duration, clip_C.duration), audio.duration)
duration = min(min(clip_A.duration, clip_B.duration), audio.duration)
clip_A = clip_A.set_duration(duration)
clip_B = clip_B.set_duration(duration)
clip_C = clip_C.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_AA, clip_BB]]) # clip_C
video = mpy.clips_array([[clip_A, clip_B, clip_C]]) # clip_C
video = mpy.clips_array([[clip_A, clip_B]]) # clip_C
video = video.set_audio(audio) # audd audio
# save
+14 -18
View File
@@ -6,12 +6,13 @@ from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1")
path_root = Path("/yrfs/lsen/DATA/TestData")
vpath_videos = sorted(path_root.glob("raw/*.mp4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# IDs = ["2021-P29"]
IDs = ["clip_full"]
# for each video
for i, ipath_item in enumerate(vpath_videos):
@@ -19,7 +20,7 @@ if __name__ == '__main__':
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if i < 40: continue
# if iname not in IDs: continue
if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing", ipath_item.stem)
@@ -39,21 +40,24 @@ if __name__ == '__main__':
# info = json.load(f)
# nframe_info = info['nframes']
# 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
# Trim
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.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()))
# 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
@@ -61,23 +65,17 @@ if __name__ == '__main__':
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)}")
# Trim
# video = video.subclip(t_start=20.0, t_end=int(video.duration)-20.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()))
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframes:
print(f"\n Skip: have already done!")
continue
# nframe_real = len(list(ipath_frame.glob("*.jpg")))
# if nframe_real == nframes:
# print(f"\n Skip: have already done!")
# continue
# get audio
audio_sub = video.audio
@@ -91,7 +89,6 @@ if __name__ == '__main__':
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")
@@ -111,7 +108,6 @@ if __name__ == '__main__':
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"
@@ -22,13 +22,18 @@ def main(args):
deca = DECA(config = deca_cfg, device=device)
path_data = Path("/yrfs/lsen/DATA/TestData/processing")
# path_data = Path("/yrfs/lsen/DATA/Actor1/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 ipath_data in v_dir_videos[1:]:
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print("\nprocessing ...", ivideo_name)
if ivideo_name not in IDs: continue
ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames")
@@ -58,7 +63,6 @@ def main(args):
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:
@@ -66,7 +70,7 @@ def main(args):
continue
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector)
dataloader = DataLoader(datatest, batch_size=48, shuffle=False, drop_last=False)
dataloader = DataLoader(datatest, batch_size=64, shuffle=False, drop_last=False)
for i, ibatch_data in enumerate(dataloader):
@@ -114,7 +118,7 @@ if __name__ == '__main__':
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:2', type=str,
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'],
+101
View File
@@ -0,0 +1,101 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
# path_data = Path('/yrfs/lsen/DATA/TestData/processing') # '../data/trinity/source'
path_data = Path("/yrfs/lsen/DATA/Actor1/processing")
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps / 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
# continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
# continue
if ipath_save_exp.exists() and ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_exp}")
continue
feat_exp = []
feat_pos = []
feat_idn = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_exp.append(data_coeff["exp"])
feat_pos.append(data_coeff["pose"])
feat_idn.append(data_coeff["shape"])
# save
feat_exp = np.array(feat_exp) # (nframe_trim, 50)
feat_pos = np.array(feat_pos) # (nframe_trim, 6)
feat_idn = np.array(feat_idn) # (nframe_trim, 100)
# # pad one
# feat_exp = np.pad(feat_exp, ((0,1),(0,0)), mode="edge")
# feat_pos = np.pad(feat_pos, ((0,1),(0,0)), mode="edge")
# feat_idn = np.pad(feat_idn, ((0,1),(0,0)), mode="edge")
if nframes == feat_idn.shape[0]:
np.save(ipath_save_exp, feat_exp)
np.save(ipath_save_pos, feat_pos)
np.save(ipath_save_idn, feat_idn)
print(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2)
else:
print("ERROR, skip! ")
@@ -0,0 +1,97 @@
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
pid = "2022-P01" # "2021-P22", actor-2HD
# path_root = Path("/yrfs/lsen/DATA/TestData/processing/")
path_root = Path("/yrfs/lsen/DATA/Actor1/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_60_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]
# load mean
path_deca_mean = Path("./data/DECA_LuoXData_mean.npy")
mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(mean_dict.keys())
# load deca model
device = torch.device("cuda:0")
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.mp4")
v_render_pt = []
nbatch_render = 10
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)
+2
View File
@@ -143,6 +143,8 @@ config.DATASET.filter = '' # "gaussian" | "savgol"
# augmentation
config.DATASET.flip = False
config.DATASET.shifting_speed = False
#############################
# Trainning related parameter
+184 -16
View File
@@ -1,11 +1,14 @@
import imp
import numpy as np
import torch
import time
import random
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
from common.debug import debug
# common
from common.resampling import resample_by_nsteps
class MotionLiveDataset(Dataset):
"""
@@ -18,7 +21,6 @@ class MotionLiveDataset(Dataset):
"""
super(MotionLiveDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
@@ -26,7 +28,6 @@ class MotionLiveDataset(Dataset):
# for test
# if phase == "valid":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
# if phase == "test":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
@@ -49,7 +50,6 @@ class MotionLiveDataset(Dataset):
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
# path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
# path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
# print(f"load data ... --> {path_motion} | {path_speech}")
@@ -65,9 +65,9 @@ class MotionLiveDataset(Dataset):
def __len__(self):
if self.phase == "train":
return 20000 #40000
return 30000 #40000
elif self.phase == "valid":
return 2000 #5000
return 3000 #5000
else:
return 100
@@ -91,15 +91,32 @@ class MotionLiveDataset(Dataset):
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
# data_shape = data["data_shape"] # (nframes, nc_shape)
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
# data_shape = data["data_shape"] # (nframes, nc_shape)
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
if self.phase == "train" and self.opt.DATASET.shifting_speed and random.random() < 0.3:
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
beg_frame = np.random.randint(nframe - int(self.nsteps_frame * speed) - 10) + 5 # select from (5:-5)
end_frame = beg_frame + int(self.nsteps_frame * speed)
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + int(self.nsteps_segmt * speed)
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}"
# print(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}")
# resample to same nsteps
data_motion = resample_by_nsteps(data_motion, nsteps_tgt=self.nsteps_frame)
data_speech = resample_by_nsteps(data_speech, nsteps_tgt=self.nsteps_segmt)
# print(f"resampling > data_speech shape={data_speech.shape} data_motion shape={data_motion.shape} \n")
else:
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
@@ -108,21 +125,172 @@ class MotionLiveDataset(Dataset):
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame, :] # (nteps, 53)
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
# data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: reverse
if self.phase == "train" and self.opt.DATASET.flip:
data_motion, data_speech = self.make_auguments_flip(data_motion, data_speech, p=0.3)
# print(f"flip: data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# random augments: shuffle speed
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def make_auguments_flip(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1].copy()
data_speech = data_speech[::-1].copy()
return data_motion, data_speech
def make_auguments_speed(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() > p:
return data_motion, data_speech
nsteps_motion = data_motion.shape[0]
nsteps_speech = data_speech.shape[0]
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
if speed < 0:
data_motion = data_motion[:nsteps_motion*speed]
data_speech = data_speech[:nsteps_speech*speed]
return data_motion, data_speech
class MotionLiveEvalDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
"""
phase = "train | valid | test "
"""
super(MotionLiveEvalDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
print(f"\n [{self.phase}] load data ... --> {path_data}")
# dict vid: {"data_motion", # [nframe, 53]
# "data_speech", # [duration * sample_rate, ] raw deepseep
# "nframe", "fps", "sr"}
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.annodb_accums = self.count_annotations()
self.overlap = 0.5
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
return self.annodb_accums[-1]
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, anno_dict in enumerate(self.annodb.values()):
acc += anno_dict["data_motion"].shape[0] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows
annodb_accums[i+1] = acc # 2
return annodb_accums
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
for i, iacc in enumerate(self.annodb_accums):
if idx > iacc -1 and idx < self.annodb_accums[i+1]:
pid, new_idx = i, idx - iacc
break
print(f"DEBUG: idx={idx}, pid = {pid}, iacc ={self.annodb_accums[i]}, new_idx = {new_idx}")
# return item
vid = self.pids[pid]
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
beg_frame = new_idx
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\nnsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
print(f"data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
# "shape": data_shape,
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
+45 -2
View File
@@ -1,3 +1,4 @@
from random import random
import numpy as np
import torch
import time
@@ -10,7 +11,9 @@ from common.debug import debug
class MotionLive2Dataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
Prepares conditioning information (previous poses + control signal) and the corresponding next poses
+ shape
"""
def __init__(self, opt, phase="train"):
"""
@@ -110,7 +113,6 @@ class MotionLive2Dataset(Dataset):
data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
@@ -130,3 +132,44 @@ class MotionLive2Dataset(Dataset):
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
return result
def make_auguments_reverse(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1]
data_speech = data_speech[::-1]
return data_motion, data_speech
def make_auguments_speed(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() > p:
return data_motion, data_speech
nsteps_motion = data_motion.shape[0]
nsteps_speech = data_speech.shape[0]
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
if speed < 0:
data_motion = data_motion[:nsteps_motion*speed]
data_speech = data_speech[:nsteps_speech*speed]
return data_motion, data_speech
+160
View File
@@ -0,0 +1,160 @@
import numpy as np
import random
import time
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
from common.debug import debug
class MotionLive3Dataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses
+ shape
+ selected idx
"""
def __init__(self, opt, phase="train"):
"""
phase = "train | valid | test "
"""
super(MotionLive3Dataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
# for test
# if phase == "valid":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
# if phase == "test":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
print(f"\n [{self.phase}] load data ... --> {path_data}")
# dict vid: {"data_motion", # [nframe, 53]
# "data_speech", # [duration * sample_rate, ] raw deepseep
# "nframe", "fps", "sr"}
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
# path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
# path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
# print(f"load data ... --> {path_motion} | {path_speech}")
# self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
# self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
# print(f"motion data ={self.data_motion.shape}, output={self.data_speech.shape}")
# self.nc_motion = self.data_motion.shape[-1]
# self.nc_speech = self.data_speech.shape[-1]
# debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech }")
def __len__(self):
if self.phase == "train":
return 20000 #40000
elif self.phase == "valid":
return 2000 #5000
else:
return 100
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# # filter "2021-P29"
# while vid == "2021-P29":
# vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
# data_shape = data["data_shape"] # (nframes, nc_shape)\
set_idx = data["idx_sampling"] # (nframes_sampling)
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
if self.phase == "train":
beg_frame = random.sample(set_idx,1)[0]
if beg_frame + self.nsteps_frame > nframe: # resampling when last
beg_frame = nframe - self.nsteps_frame - 5
else:
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame, :] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
# data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: reverse
if self.phase == "train" and self.opt.DATASET.flip:
data_motion, data_speech = self.make_auguments_flip(data_motion, data_speech, p=0.3)
# random augments: shuffle speed
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
# "shape": data_shape,
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
}
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
return result
def make_auguments_flip(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1].copy()
data_speech = data_speech[::-1].copy()
return data_motion, data_speech
+15 -16
View File
@@ -195,7 +195,6 @@ class Audio2MeshModel(Base):
return loss
def infer(self, batch_cond, path_audio, suffix=""):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
@@ -210,11 +209,11 @@ class Audio2MeshModel(Base):
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
# save result
samples_pt = samples_pt.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, samples_pt)
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
# # save result
# samples_pt = samples_pt.cpu().numpy()
# path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
# np.save(path_save_npy, samples_pt)
# print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
@@ -307,7 +306,7 @@ class Audio2MeshModel(Base):
return loss_stack
def eval_losses(self, batch_pdt_geo, batch_tgt):
def eval_losses_active(self, batch_pdt_geo, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
@@ -378,8 +377,7 @@ class Audio2MeshModel(Base):
return loss, loss_dict
def eval_losses_old(self, batch_pdt_geo, batch_tgt):
def eval_losses(self, batch_pdt_geo, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
@@ -394,23 +392,24 @@ class Audio2MeshModel(Base):
# synthesis geo rec
loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["loss_rec_geo"] = loss_rec_geo.detach()
loss_dict["loss_rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach()
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.mean().detach()
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["loss_vel_geo"] = loss_vel_geo.detach()
loss_dict["loss_vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.detach()
loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['loss_all'] = loss.detach()
+577
View File
@@ -0,0 +1,577 @@
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models.info import flame_mouth_idx
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2MeshARModel(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
# define networks
self.netG = define_netG(opt)
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
# init last layer
init_exp_weight = np.load("/ssdata1/lsen/CODE/voca/training_data/init_expression_basis.npy")
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
init_exp_weight = init_exp_weight[:, :50]
self.netG.module.decoder_mesh.weight.data = init_exp_weight
print(f"init_exp_weight shape = {init_exp_weight.shape}")
# # print network parameters
# for name, param in self.netG.named_parameters():
# print(name, '\t\t', param.size())
# load mean lighting & shape
self.netR, self.flame = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR)
path_deca_mean = Path("./data/DECA_obama_mean.npy")
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
self.template_verts = self.get_template_vertices()
debug(opt, f"template_verts shape = {self.template_verts.shape}")
debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True)
# if filter outlier
# if self.opt.LOSS.filter_outlier:
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
self.loss_func_l1 = nn.L1Loss(reduction="none")
if self.isTrain:
self.names_loss = opt.LOSS.names
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
# define loss weight
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
def set_input(self, batch_input):
# motion data
y = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
self.B, self.nsteps = y.size(0), y.size(1)
debug(self.opt, f"data = {y.shape}, dtype={y.dtype}", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
# speech data
x = None
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
if self.opt.DATASET.speech_extractor == "wav2vec":
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
raw_speech = list(raw_speech)
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(self.device)
with torch.no_grad():
output = self.extractor(**inputs)
x = output.last_hidden_state
# x = output.extract_features
else:
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
# B x nsteps x nc_feat
debug(self.opt, f"data = {y.shape}, dtype={y.dtype}, device={y.device}", verbose=False)
debug(self.opt, f"cond = {x.shape}, dtype={x.dtype}, device={x.device}", verbose=False)
# unfold speech data
x = x.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
x = x.permute(0, 1, 3, 2) # (nseqs, 16, 53)
self.nsteps_align = x.size(1)
y = y[:, 7:7+self.nsteps_align] # B x nsteps x nc_motion
y = self.get_vertices(y) # B x nsteps x 5023 x 3
debug(self.opt, f"\n a data = {y.shape}, dtype={y.dtype}, device={y.device}", verbose=False)
debug(self.opt, f"a cond = {x.shape}, dtype={x.dtype}, device={x.device}", verbose=False)
# for autoregressive training
self.x = x # B x nseq x nwind x nc_condit
self.y_tgt = y # B x nseq x 5023 x 3
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
batch_x = self.x[:, 1:] # B x nsteps-1 x nwind x nc_condit
batch_y_tgt = self.y_tgt[:, 1:] # B x nsteps-1 x 5023 x 3
batch_y_pre = self.y_tgt[:, :-1] # B x nsteps-1 x 5023 x 3
batch_y_pdf = self.netG(batch_x, batch_y_pre) # B x nsteps-1 x 5023 x 3
batch_y_pdf += self.template_verts # B x nsteps-1 x 5023 x 3
debug(self.opt, f"traing batch_y_pdf = {batch_y_pdf.shape}, batch_y_tgt = {batch_y_tgt.shape}", verbose=False)
# loss
loss, self.loss_dict = self.eval_losses(batch_y_pdf, batch_y_tgt)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss
def validation(self, batch_input):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
batch_x = self.x[:, 1:] # B x nsteps-1 x nwind x nc_condit
batch_y_tgt = self.y_tgt[:, 1:] # B x nsteps-1 x 5023 x 3
batch_y_pre = self.y_tgt[:, :-1] # B x nsteps-1 x 5023 x 3
batch_y_pdf = self.netG(batch_x, batch_y_pre) # B x nsteps-1 x 5023 x 3
batch_y_pdf += self.template_verts # B x nsteps-1 x 5023 x 3
loss, self.loss_dict = self.eval_losses(batch_y_pdf, batch_y_tgt)
return loss
def infer(self, batch_cond, path_audio, suffix=""):
self.eval()
x = batch_cond.float().to(self.device) # B x nsteps x nwind x nc_condit
B, nsteps, *_ = x.shape
with torch.no_grad():
# prepare batch_y_pdf
batch_y_pdf = torch.zeros(B, nsteps, self.template_verts.shape[-2], 3) # B x nsteps x 5023 x 3
ibatch_y_pre = self.template_verts.expand(B, -1, -1, -1) # B x 1 x 5023 x 3
for istep in range(nsteps):
ibatch_x = x[:, istep:istep+1] # B x 1 x nwind x nc_condit
ibatch_y_pdt = self.netG(ibatch_x, ibatch_y_pre) # B x 1 x 5023 x 3
ibatch_y_pdt += self.template_verts # B x 1 x 5023 x 3
ibatch_y_pre = ibatch_y_pdt[:] # update ibatch_y_pre
batch_y_pdf[:, istep] = ibatch_y_pdt.cpu().detach()[:, -1] # update y_tgt
print(f"testing pt shape = {batch_y_pdf.shape}, x shape = {x.shape}")
self.save_reconstruct(batch_y_pdf, path_audio, path_save=Path(self.opt.OUTPUT_DIR), suffix=suffix)
# save result
samples_pt = samples_pt.numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, samples_pt)
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
B, nsteps, *_ = self.x.shape
with torch.no_grad():
batch_y_pdf = torch.zeros_like(self.y_tgt) # B x nsteps x 5023 x 3
# batch_y_pdf[:, 0] = self.y_tgt[:, 0] # init first GT as PT
batch_y_pdf[:, 0] = self.template_verts.expand(B, -1, -1, -1) # init first GT as PT
# ibatch_y_pre = self.y_tgt[:, 0] # B x 1 x 5023 x 3
ibatch_y_pre = self.template_verts.expand(B, -1, -1, -1) # B x 1 x 5023 x 3
for istep in range(1, self.nsteps_align):
ibatch_x = self.x[:, istep:istep+1] # B x 1 x nwind x nc_condit
ibatch_y_pdt = self.netG(ibatch_x, ibatch_y_pre) # B x 1 x 5023 x 3
ibatch_y_pdt += self.template_verts # B x 1 x 5023 x 3
ibatch_y_pre = ibatch_y_pdt[:] # update ibatch_y_pre
batch_y_pdf[:, istep] = ibatch_y_pdt[:, -1] # update y_tgt
# samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3
print(f"testing pt shape = {batch_y_pdf.shape}, gt shape = {self.y_tgt.shape}")
self.save_reconstruct_with_gt(batch_y_pdf, self.y_tgt,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
def get_template_vertices(self, mean_dict=None):
if mean_dict is not None:
pass
else:
batch_shape = torch.zeros(1, 100).to(self.device)
batch_exp = torch.zeros(1, 50).to(self.device)
batch_pos = torch.zeros(1, 6).to(self.device)
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
print(f"template verts reshape = {verts.shape}")
return verts
def get_vertices(self, batch_motion):
"""
batch_motion, (nbatch, seqlen, 53)
"""
batch_exp = batch_motion[..., :50]
batch_pos = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_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
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
# print(f"verts reshape = {verts.shape}")
return verts
def eval_losses_for_infer_loss(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # B x nsteps x num_vertices x 3
loss_rec_geo = loss_rec_geo.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
loss_rec_geo = loss_rec_geo.detach()
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo1 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # B x nsteps-1
loss_vel_geo1 = loss_vel_geo1.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps-1
loss_vel_geo1 = F.pad(loss_vel_geo1, pad=(0, 1), mode="replicate").detach() # B x nsteps
diff_pdt_geo = batch_pdt_geo[:, 2:, :] - batch_pdt_geo[:, :-2, :]
diff_tgt_geo = batch_tgt_geo[:, 2:, :] - batch_tgt_geo[:, :-2, :]
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # B x nsteps-2
loss_vel_geo2 = loss_vel_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps-2
loss_vel_geo2 = F.pad(loss_vel_geo2, pad=(0, 2), mode="replicate").detach() # B x nsteps
# stack among these losses
loss_stack = torch.stack([loss_rec_geo, loss_vel_geo1, loss_vel_geo2], dim=2) # B x nsteps x 3
return loss_stack
def eval_losses_active(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = {}
# B = batch_pdt_geo.size(0)
# print(f"batch_pdt_geo = {batch_pdt_geo.shape}, batch_tgt_geo = {batch_tgt_geo.shape}, B = {B}")
# synthesis geo rec
loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # B
loss_dict["loss_rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo = self.loss_func_l1(batch_pdt_geo, batch_tgt_geo) # B
loss_dict["loss_rec_geo_l1"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) # B x nsteps x num_vertices x 3
loss_rec_geo2 = loss_rec_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
# filter outliar
threshold_rec, mean_rec = torch.quantile(loss_rec_geo2, q=0.75) * 1.5, torch.quantile(loss_rec_geo2, q=0.5)
b_outlier_rec = loss_rec_geo2 > threshold_rec # B x nsteps
# print(f"threshold_rec = {threshold_rec.shape}")
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # 1,
loss_dict["loss_vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo = self.loss_func_l1(diff_pdt_geo, diff_tgt_geo) # 1,
loss_dict["loss_vel_geo_l1"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) # B x nsteps x num_vertices x 3
loss_vel_geo2 = loss_vel_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
# filter outliar
threshold_vel, mean_vel = torch.quantile(loss_vel_geo2, q=0.75) * 1.5, torch.quantile(loss_vel_geo2, q=0.5)
b_outlier_vel = loss_vel_geo2 > threshold_vel # B x (nsteps-1)
# print(f"threshold_vel = {threshold_vel.shape}")
# find outliar in both loss data
b_outlier_rec[:, :-1] = b_outlier_rec[:, :-1] & b_outlier_vel[:, :]
if torch.any(b_outlier_rec):
# print(f"b_outlier_rec = {b_outlier_rec}")
# print(f"outerliar size= {loss_rec_geo2[b_outlier_rec].shape} / {loss_rec_geo2.numel()} ")
loss_rec_geo2[b_outlier_rec] = mean_rec
loss_vel_geo2[b_outlier_rec[:, :-1]] = mean_vel
# calculate again
loss_rec_geo2 = loss_rec_geo2.mean()
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach()
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
loss_vel_geo2 = loss_vel_geo2.mean()
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.detach()
loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['loss_all'] = loss.detach()
return loss, loss_dict
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = {}
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["loss_rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.mean().detach()
loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
# loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["loss_vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.mean().detach()
if self.opt.LOSS.lambda_vel_geo > 0:
loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
# loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['loss_all'] = loss.detach()
return loss, loss_dict
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
B, N, *_ = samples_pt.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = samples_pt[i, ...]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, ipath_save)
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
# samples_pt, [B x N x 5023 x 3]
# samples_gt, [B x N x 5023 x 3]
B, N, *_ = samples_pt.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = samples_pt[i, ...] # [N x 5023 x 3]
igeo_gt = samples_gt[i, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# get audio
jvid = self.batch_vid[i]
jnframe = self.batch_nframe[i].numpy()
jstart_frame = self.batch_interv[0][i].numpy()
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + 7 + self.nsteps_align) / self.opt.DATASET.fps # xxx.yyy min
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
#########################################
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2mesh_ar":
from src.nn.audio2mesh_ar import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_voca":
from src.nn.audio2mesh_voca import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_resnet":
from src.nn.audio2mesh_resnet import Audio2Mesh
netG = Audio2Mesh(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
# to GPU
netG.to(f"cuda:{opt.GPUS[0]}")
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
return netG
def define_netR(device):
# import
from src.nn.FLAME import FLAME
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
# use device
# device = "cuda:2"
# whether to use FLAME texture model to generate uv texture map
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
# reconstruction model
netR = DECA(config = deca_cfg, device=device)
# flame model
flame = FLAME(deca_cfg.model).to(device)
return netR, flame
-1
View File
@@ -251,7 +251,6 @@ class Audio2MeshSpecificModel(Base):
else:
batch_shape = torch.zeros(1, 100).to(self.device)
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
print(f"template verts reshape = {verts.shape}")
+2 -1
View File
@@ -46,7 +46,8 @@ class Audio2Mesh(nn.Module):
nn.Flatten(), # 64,
nn.Linear(in_features=128, out_features=2048), # 128,
nn.Linear(in_features=128, out_features=2048),
# nn.Dropout(0.3), # 128,
nn.Tanh(),
nn.Linear(in_features=2048, out_features=50) # 50,
+107
View File
@@ -0,0 +1,107 @@
from tkinter.tix import Y_REGION
import torch
import torch.nn as nn
from common.debug import debug
class Audio2Mesh(nn.Module):
def __init__(self, opt):
super(Audio2Mesh, self).__init__()
self.opt = opt
self.num_vertices = opt.MODEL.num_vertices
self.nc_motion = 3 * self.num_vertices # 3 * 5023
self.dim_cond = opt.MODEL.dim_speech # 1024
# encoder
self.encoder_x = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
nn.BatchNorm2d(self.dim_cond),
# block 1
nn.Conv2d(self.dim_cond, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 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), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Flatten(), # 64,
)
self.encoder_y = nn.Sequential( # (nbatch x seqlen x nc_motion)
nn.Linear(in_features=self.nc_motion, out_features=256),
nn.LeakyReLU(0.02, True),
nn.Linear(in_features=256, out_features=128),
nn.Tanh(),
)
self.fusion_net = nn.Sequential(
nn.Linear(in_features=256, out_features=2048),
# nn.Dropout(0.3), # 128,
nn.Tanh(),
nn.Linear(in_features=2048, out_features=50) # 50,
)
# output FLAME mesh
self.decoder_mesh = nn.Linear(in_features=50, out_features=self.nc_motion)
def forward(self, x, y_prev):
""" forward function
Args:
x: [nbatch x seqlen x nwind x nc_condit]
y_prev: [nbatch x seqlen x nc_motion]
return:
y: [nbatch x seqlen x nc_motion]
"""
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
# preprocessing data
y_prev = y_prev.reshape(nbatch * nseqlen, -1) # (B * nseq, nc_motion)
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
feat_x = self.encoder_x(x) # (B * nseq, 128)
feat_y = self.encoder_y(y_prev) # (B * nseq, 128)
feat = torch.cat([feat_x, feat_y], dim=1) # (B * nseq, 256)
debug(self.opt, f"[forward] feat_x = {feat_x.shape}, feat_y = {feat_y.shape}, feat = {feat.shape}, ", verbose=False)
feat = self.fusion_net(feat) # (B * nseq, 50)
debug(self.opt, f"[forward] fusion feat = {feat.shape}, ", verbose=False)
# predict FLAME mesh
pred_vert = self.decoder_mesh(feat) # (B * nseq, nc_motion)
debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False)
pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3)
debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False)
return pred_vert
-1
View File
@@ -39,7 +39,6 @@ def parese_args():
return args
if __name__ == "__main__":
args = parese_args()