Files
audio2motion/scripts/Obama/run-02-generate-data.py
T
2022-01-21 17:42:41 +08:00

148 lines
5.4 KiB
Python

import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
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('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
# path_save = Path('data/obama-landmark-mel') # obama-landmark-mel
path_save = Path('data/obama-landmark-mfcc') # obama-landmark-mel
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = [ipath.stem for ipath in v_dir_videos]
nv_total = len(v_dir_videos)
nv_valid, nv_test = 2, 2
nv_train = nv_total - (nv_valid + nv_test)
vid_test = vids[:nv_test]
vid_valid = vids[nv_test:nv_test+nv_valid]
vid_train = vids[nv_test+nv_valid:]
print("vid_test = ", vid_test)
# for each video
data_train, data_valid, data_test = {}, {}, {}
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_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
ipath_speech = ipath_data.joinpath("video/mfcc_feat.npy")
# ipath_motion = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
# ipath_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
# check existing
if not ipath_motion.exists() or not ipath_speech.exists() or not ipath_info.exists():
msg = "ERROR: NOT exsiting "
if not ipath_info.exists():
msg += f"\n\t {ipath_info} "
if not ipath_motion.exists():
msg += f"\n {ipath_motion} "
if not ipath_speech.exists():
msg += f"\n\t {ipath_speech} "
print(msg)
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
fps = info["fps"]
print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
# fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
# print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# load data
data_motion = np.load(ipath_motion).reshape(-1, 136) # (N, 136)
data_speech = np.load(ipath_speech) # (M, 80)
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}, mfcc len / 4 = {data_speech.shape[0] / 4}")
# assert data_motion.shape[0] == data_speech.shape[0]
# resample fps=25.0
data_motion_25fps = landmark_resample_fps(data_motion, source_fps=fps, target_fps=25.0)
print(f"data_pt_30fps shape = {data_motion.shape}, data_motion_25fps = {data_motion_25fps.shape}")
# alignment
nsetps = min(data_motion_25fps.shape[0], data_speech.shape[0] // 4)
print(f"nsetps = {nsetps}")
data_motion = data_motion_25fps[:nsetps, :]
data_speech = data_speech[:nsetps*4, :].reshape(nsetps, -1)
print(f"after alignment data_motion = {data_motion.shape}, data_speech = {data_speech.shape}")
if vid in vid_train:
data_train[vid] = {
"W": width, "H": height, "FPS": info["fps"],
"nframe": nframe_trim, "trim": [ibeg, iend],
"data_motion": data_motion,
"data_speech": data_speech
}
elif vid in vid_valid:
data_valid[vid] = {
"W": width, "H": height, "FPS": info["fps"],
"nframe": nframe_trim, "trim": [ibeg, iend],
"data_motion": data_motion,
"data_speech": data_speech
}
else:
data_test[vid] = {
"W": width, "H": height, "FPS": info["fps"],
"nframe": nframe_trim, "trim": [ibeg, iend],
"data_motion": data_motion,
"data_speech": data_speech
}
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"save data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)}) --> {path_save}")