Happy new years

This commit is contained in:
Sen Liang committed 2022-02-07 17:28:40 +08:00
1 parent c7175dd7ff
commit 8c4865effb
53 files changed
+4604 -61

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
from pathlib import Path
import json
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == '__main__':
path_root = Path("/yrfs/lsen/DATA/LuoXData")
vpath_videos = sorted(path_root.glob("raw/*.mp4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files")
# for each video
for i, ipath_item in enumerate(vpath_videos):
iname = ipath_item.stem
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
# if i < 40: continue
# if iname not in IDs: continue
# data path
ipath_data = path_root.joinpath("processing2", 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_sub = video.subclip(t_start=20.0, t_end=int(video.duration)-20.0)
print(f"after cut video duration = {video_sub.duration}, fps = {video_sub.fps}, (start, end)=({video_sub.start},{video_sub.end}), nframes={int(video_sub.duration * video_sub.fps)}")
nframes = int(video_sub.duration * video_sub.fps)
# check frames
nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframes:
print(f"\n Skip: have already done!")
continue
# check fps
if int(video_sub.fps) != 50:
print(f"\n Skip: fps != 50 realy fps={video_sub.fps}")
continue
# save video feature
info = {"nframes": nframes,
"fps":video_sub.fps,
"width": video_sub.w,
"height": video_sub.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 sub video
# ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
# video_sub.write_videofile(str(ipath_video_sub), fps=50, audio=True)
# print(f"save video > {ipath_video_sub}")
# get audio
audio_sub = video_sub.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}")
# save trim video
print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video_sub.write_images_sequence(ipath_format, fps=50)
@@ -0,0 +1,73 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files, \n {v_dir_videos[:3]}")
# for each speaker
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if i >= 50: continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_audio = ipath_data.joinpath("audio/audio_trim.wav")
ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy")
# check
if not ipath_audio.exists():
print(f"NOT existing {ipath_audio}")
continue
if ipath_save_feat.exists():
print(f"have existing {ipath_save_feat}")
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}")
assert fps == 50, "fps should be 50"
# load trim audio
data, sr = librosa.load(str(ipath_audio), sr= int(0.5 + fps * ( 16000 / fps ))) # 16000 = fps * 640 让这个sr是fps的整数,
hop_len = int(sr / fps)
n_fft = int(sr * 0.13) # default 2048
print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
# melspectrogram
mel = librosa.feature.melspectrogram(y=data, sr=sr,
n_fft=n_fft, # FFT窗口的长度
hop_length=hop_len, # 帧移
win_length=n_fft, # 窗口长度,默认=n_fft
window="hann", # 加hanming窗
n_mels=27, # 滤波器组
fmin=0.0, fmax=8000)
mel = np.log(mel+1).T
print(f"mel = {mel.shape}, frames = {(len(data) / sr) * fps}, (min,max)=({np.min(mel), np.max(mel)}")
# align to video
if mel.shape[0] < nframes:
print(f"\n skip, mel shape ={mel.shape}, frames={(len(data) / sr) * fps}")
else:
mel_align = mel[:nframes, :]
# save
np.save(ipath_save_feat, mel_align)
@@ -0,0 +1,141 @@
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
# run DECA
deca_cfg.model.use_tex = args.useTex
deca = DECA(config = deca_cfg, device=device)
path_data = Path("/yrfs/lsen/DATA/LuoXData/processing2")
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
for ipath_data in v_dir_videos[17:]:
ivideo_name = ipath_data.stem
print("\nprocessing ...", ivideo_name)
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)
dataloader = DataLoader(datatest, batch_size=48, 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%50 == 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
# for vis_name in ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']:
# 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)
# 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/LuoXData/processing2') # '../data/trinity/source'
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) - 1):
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,160 @@
import json
import numpy as np
from pathlib2 import Path
def interpolate_features(features, input_rate, output_rate, output_len=None):
num_features = features.shape[1]
input_len = features.shape[0]
seq_len = input_len / float(input_rate)
if output_len is None:
output_len = int(seq_len * output_rate)
input_timestamps = np.arange(input_len) / float(input_rate)
output_timestamps = np.arange(output_len) / float(output_rate)
output_features = np.zeros((output_len, num_features))
for feat in range(num_features):
output_features[:, feat] = np.interp(output_timestamps,
input_timestamps,
features[:, feat])
return output_features
def slice_data(data, window_size, overlap):
nframes = data.shape[0]
overlap_frames = (int)(overlap*window_size)
n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames)
if data.ndim == 2:
sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32)
else:
sliced = np.zeros((n_sequences, window_size, data.shape[1], data.shape[2])).astype(np.float32)
if n_sequences>0:
# extract sequences from the data
for i in range(0, n_sequences):
frameIdx = (window_size-overlap_frames) * i
sliced[i] = data[frameIdx:frameIdx+window_size].copy()
else:
print("WARNING: data too small for window")
return sliced
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
# path_save = Path('data/LuoXData-ds093raw-deca-3-10-08-mini5') # processing
path_save = Path('data/LuoXData-deca-5-10-07-mini') # 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(["2021-P14"])
vid_valid = set(["2021-P14"]) #set(["2021-P14"])
# vid_train = set(['2021-P01', '2021-P02', '2021-P'])
vid_train = vids - vid_test - vid_test
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# set windows
nwin_train_secs = 5 # 6
nwin_test_secs = 10 # 20
window_overlap = 0.7
fps = 50
nwin_train = nwin_train_secs * fps # 5 * 50 = 250
nwin_test = nwin_test_secs * fps # 10 * 50 = 500
# for each video
motion_train, motion_valid, motion_test = [], [], []
speech_train, speech_valid, speech_test = [], [], []
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
# if i >= 50: continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
# ipath_feat_speech = ipath_data.joinpath("audio/audio_trim_ds093.npy")
# ipath_feat_speech = ipath_data.joinpath("audio/audio_trim_ds093_raw.npy")
if not ipath_feat_speech.exists():
print(f"NOT existing {ipath_feat_speech}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
print(f"info={info}")
assert fps == 50, "fps should be 50"
# laod motion & speech data
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
pos_head = data_pos[:, :3] # (nframe, 3)
pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, pos_lips], axis=1) # (nframe, 53) --> fps=30
data_speech = np.load(ipath_feat_speech) # (nframe, 256) --> fps=60
print(f"motion = {data_motion.shape}, speech = {data_speech.shape}")
# filter data_speech
# data_speech[data_speech < 0] = 0
if vid in vid_train:
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap)
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
motion_train.append(motion_sliced)
speech_train.append(speech_sliced)
if vid in vid_valid:
motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=0)
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=0)
motion_valid.append(motion_sliced)
speech_valid.append(speech_sliced)
if vid in vid_test:
motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0)
speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0)
motion_test.append(motion_sliced)
speech_test.append(speech_sliced)
print(f"sliced motion = {motion_sliced.shape}, speech = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)}) \n")
# save
motion_train = np.concatenate(motion_train, axis=0) # (nframe, 250, 53)
speech_train = np.concatenate(speech_train, axis=0) # (nframe, 250, 256)
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}")
motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136)
speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27)
np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid)
np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid)
print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}")
motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136)
speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27)
np.savez(path_save.joinpath("motion_test.npz"), data=motion_test)
np.savez(path_save.joinpath("speech_test.npz"), data=speech_test)
print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}\n")
@@ -0,0 +1,153 @@
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/LuoXData/processing2') # '../data/trinity/source'
path_save = Path('data/LuoXData-raw-deca-8h') # 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")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
print(f"vids total= {vids}")
vid_test = set(["2021-P09"])
vid_valid = set(["2021-P14"]) #set(["2021-P14"])
# vid_train = set(['2021-P01', '2021-P02', '2021-P'])
vid_train = vids - vid_test - vid_test
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
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_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)
pos_head = data_pos[:, :3] # (nframe, 3)
pos_lips = data_pos[:, 3:] # (nframe, 3)
data_motion = np.concatenate([data_exp, 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)}")
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
}
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
}
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
}
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total ids: data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)})")
print(f"Total frames: data_train ({durations_train / 3600} h), data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)")
print(f"--> {path_save}")