initial commit

This commit is contained in:
Sen Liang committed 2022-01-21 17:42:41 +08:00
commit c7175dd7ff
127 files changed
+13949

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import numpy as np
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
vid = "Celebrating-Independence-Day"
path_motion = path_data.joinpath(vid, "audio/feat_ldmk_trim.npy")
data_motion = np.load(path_motion) # (N, 68, 2)
print(f"data_motion={data_motion.shape}, mean = {data_motion.mean((0,1))}, min={data_motion.min((0,1))}, max={data_motion.max((0,1))}")
# get rect
min_data = data_motion.min(axis=1) # (N, 2)
max_data = data_motion.max(axis=1) # (N, 2)
print(f"min_x={min_data.shape}, max_y={max_data.shape}")
# get mean rect
min_x, min_y = min_data.mean(axis=0) # (2, )
max_x, max_y = max_data.mean(axis=0)
print(f"RECT = ({min_x}, {min_y}, {max_x}, {max_y}), size=({max_x - min_x}, {max_y - min_y})")
# RECT = (696.6033078880407, 276.86030534351147, 1056.871755725191, 667.1918575063613), size=(360.26844783715023, 390.33155216284985)
+142
View File
@@ -0,0 +1,142 @@
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the NVIDIA CORPORATION nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# *****************************************************************************\
import os
import random
import argparse
import json
import torch
import torch.utils.data
import sys
from scipy.io.wavfile import read
# We're using the audio processing from TacoTron2 to make sure it matches
sys.path.insert(0, 'tacotron2')
from tacotron2.layers import TacotronSTFT
MAX_WAV_VALUE = 32768.0
def files_to_list(filename):
"""
Takes a text file of filenames and makes a list of filenames
"""
with open(filename, encoding='utf-8') as f:
files = f.readlines()
files = [f.rstrip() for f in files]
return files
def load_wav_to_torch(full_path):
"""
Loads wavdata into torch array
"""
sampling_rate, data = read(full_path)
return torch.from_numpy(data).float(), sampling_rate
class Mel2Samp(torch.utils.data.Dataset):
"""
This is the main class that calculates the spectrogram and returns the
spectrogram, audio pair.
"""
def __init__(self, training_files, segment_length, filter_length,
hop_length, win_length, sampling_rate, mel_fmin, mel_fmax):
self.audio_files = files_to_list(training_files)
random.seed(1234)
random.shuffle(self.audio_files)
self.stft = TacotronSTFT(filter_length=filter_length,
hop_length=hop_length,
win_length=win_length,
sampling_rate=sampling_rate,
mel_fmin=mel_fmin, mel_fmax=mel_fmax)
self.segment_length = segment_length
self.sampling_rate = sampling_rate
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
def __getitem__(self, index):
# Read audio
filename = self.audio_files[index]
audio, sampling_rate = load_wav_to_torch(filename)
if sampling_rate != self.sampling_rate:
raise ValueError("{} SR doesn't match target {} SR".format(
sampling_rate, self.sampling_rate))
# Take segment
if audio.size(0) >= self.segment_length:
max_audio_start = audio.size(0) - self.segment_length
audio_start = random.randint(0, max_audio_start)
audio = audio[audio_start:audio_start+self.segment_length]
else:
audio = torch.nn.functional.pad(audio, (0, self.segment_length - audio.size(0)), 'constant').data
mel = self.get_mel(audio)
audio = audio / MAX_WAV_VALUE
return (mel, audio)
def __len__(self):
return len(self.audio_files)
# ===================================================================
# Takes directory of clean audio and makes directory of spectrograms
# Useful for making test sets
# ===================================================================
if __name__ == "__main__":
# Get defaults so it can work with no Sacred
parser = argparse.ArgumentParser()
parser.add_argument('-f', "--filelist_path", required=True)
parser.add_argument('-c', '--config', type=str,
help='JSON file for configuration')
parser.add_argument('-o', '--output_dir', type=str,
help='Output directory')
args = parser.parse_args()
with open(args.config) as f:
data = f.read()
data_config = json.loads(data)["data_config"]
mel2samp = Mel2Samp(**data_config)
filepaths = files_to_list(args.filelist_path)
# Make directory if it doesn't exist
if not os.path.isdir(args.output_dir):
os.makedirs(args.output_dir)
os.chmod(args.output_dir, 0o775)
for filepath in filepaths:
audio, sr = load_wav_to_torch(filepath)
melspectrogram = mel2samp.get_mel(audio)
filename = os.path.basename(filepath)
new_filepath = args.output_dir + '/' + filename + '.pt'
print(new_filepath)
torch.save(melspectrogram, new_filepath)
+116
View File
@@ -0,0 +1,116 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
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
if i % 50 == 0:
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("audio/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
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}")
# assert data_motion.shape[0] == data_speech.shape[0]
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}")
+125
View File
@@ -0,0 +1,125 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
path_save = Path('data/obama-landmark-mel-pose') # obama-landmark-mel
# path_save = Path('data/obama-3dmm-mel') # obama-landmark-mel
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 = [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
if i % 50 == 0:
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_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_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
if not ipath_speech.exists() or not ipath_pos.exists() or not ipath_motion.exists():
print(f"ERROR: NOT Exist {ipath_speech} or {ipath_pos} or {ipath_motion}" )
continue
# check existing
if 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_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
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
# feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
# feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
data_pose = np.load(ipath_pos) # (nframe_trim, 6) # (N, 6)
# data_motion = np.concatenate([feat_idn, feat_exp, feat_pos], axis=1) # (N, 156)
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}")
# assert data_motion.shape[0] == data_speech.shape[0]
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,
"data_pose": data_pose
}
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,
"data_pose": data_pose
}
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,
"data_pose": data_pose
}
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}")
+148
View File
@@ -0,0 +1,148 @@
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}")
+72
View File
@@ -0,0 +1,72 @@
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/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
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_audio_trim = ipath_data.joinpath("audio/audio_trim.wav")
ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy")
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# load trim audio
data, sr = librosa.load(str(ipath_audio_trim), sr=16484) # 16484 = fps * 550 让这个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"sr={sr}, data ={data.shape}, mel = {mel.shape}, (min,max)=({np.min(mel), np.max(mel)}")
# align to video
assert mel.shape[0] >= nframe_trim
mel_align = mel[:nframe_trim, :]
# save
# np.save(ipath_save_feat, mel_align)
@@ -0,0 +1,139 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import torch
from scipy.io.wavfile import read
# We're using the audio processing from TacoTron2 to make sure it matches
sys.path.insert(0, '/mnt/data/CODE/Audio2Expression/3rdpart/')
import tacotron2
from tacotron2.layers import TacotronSTFT
MAX_WAV_VALUE = 32768.0
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
print(f"Have {len(v_dir_videos)} dir files")
# load STFT
model = TacotronSTFT(filter_length=1024,
hop_length=256,
win_length=1024,
sampling_rate=22050,
mel_fmin=0.0, mel_fmax=8000)
# set windows
nwin_train_secs = 6 # 6, 2
overlap = 0.8
fps = 30
# for each video
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_audio = ipath_data.joinpath("audio/audio_trim.wav")
ipath_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
ipath_save_audio = ipath_data.joinpath("audio/feat_mel_trim_split_6s.npy") # feat_mel_trim_split
ipath_save_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm_split_6s.npy") # feat_ldmk_trim_norm_split
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
if not ipath_audio.exists() or not ipath_ladmk.exists():
print(f"ERROR: NOT Exist {ipath_audio} or {ipath_ladmk}")
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
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 landmark
data_ladmk = np.load(ipath_ladmk).reshape(-1, 136) # (nframe, 136)
assert data_ladmk.shape[0] == nframe_trim, f"the length of landmark {data_ladmk.shape[0]} != nframe_trim {nframe_trim}"
nsize_ldmk = int( nwin_train_secs * fps )
nstep_ldmk = int( nwin_train_secs * fps * (1-overlap) )
data_ladmk = torch.from_numpy(data_ladmk).float()
data_ladmk2 = data_ladmk.unfold(dimension=0, size=nsize_ldmk, step=nstep_ldmk) # (nframe_trim//30, 136, 30)
data_ladmk2 = data_ladmk2.permute(0, 2, 1) # (nsplits, nsteps, 136)
print(f"data landmark unfold = {data_ladmk2.shape}")
# print(f"check data landmark[32, ::50] = {data_ladmk[62, ::50]}, \n data_ladmk2[1, ::50, 2] = {data_ladmk2[2, ::50, 2]}")
print(f"ldmk ==> nsize = {nsize_ldmk}, nstep = {nstep_ldmk}, len = {nframe_trim // nstep_ldmk}")
# load trim audio
audio, sr = librosa.load(str(ipath_audio)) # 16484 = fps * 550 让这个sr是fps的整数,
if sr != 22050:
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
audio = torch.from_numpy(audio).float()
audio = audio.unsqueeze(0)
melspec = model.mel_spectrogram(audio)
melspec = torch.squeeze(melspec, 0) # (80, 20374)
print(f"landmark = {data_ladmk.shape}, min-max({data_ladmk.min():.4f}, {data_ladmk.max():.4f}), Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / nframe_trim}")
rato = melspec.shape[1] / nframe_trim
nsize_audio = int( nsize_ldmk * rato) + 1 # 518 (if nwind=6s),
nstep_audio = int( nstep_ldmk * rato)
print(f"audio ==> rato = {rato}, nsize = {nsize_audio}, nstep = {nstep_audio}, len={melspec.shape[1] // nstep_audio }")
nsplit = data_ladmk2.shape[0]
data_melspec = torch.zeros(nsplit, 80, nsize_audio)
# nsize = int(nwin_train_secs * fps * rato) + 1 # rate = melspec.shape[1] / nframe_trim
for i in range(nsplit):
nseg_beg = int( i * nstep_ldmk * rato )
nseg_end = nseg_beg + nsize_audio
# print(f"{i:03d}/{nsplit}, {nseg_beg:05d}-{nseg_end:05d}")
data_melspec[i] = melspec[:, nseg_beg:nseg_end]
data_melspec = data_melspec.permute(0, 2, 1) # (nsplits, nsteps, 80)
print(f"data_melspec = {data_melspec.shape}, data_ladmk = {data_ladmk2.shape}")
# save
np.save(ipath_save_audio, data_melspec) # (nsplit, 173, 80)
np.save(ipath_save_ladmk, data_ladmk2) # (nsplit, 60, 136)
# break
@@ -0,0 +1,119 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import torch
from scipy.io.wavfile import read
# We're using the audio processing from TacoTron2 to make sure it matches
sys.path.insert(0, '/mnt/data2/CODE/Audio2Expression/3rdpart/')
import tacotron2
from tacotron2.layers import TacotronSTFT
MAX_WAV_VALUE = 32768.0
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# load STFT
model = TacotronSTFT(filter_length=1024,
hop_length=256,
win_length=1024,
sampling_rate=22050,
mel_fmin=0.0, mel_fmax=8000)
# set windows
nwin_train_secs = 2 # 6, 2
overlap = 0.8
fps = 30
# for each video
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_audio = ipath_data.joinpath("audio/audio_trim.wav")
ipath_save = ipath_data.joinpath("audio/feat_mel_trim_split_2s.npy") # feat_mel_trim_split
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
if not ipath_audio.exists():
print(f"ERROR: NOT Exist {ipath_audio}")
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
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
# split frames
nsize_split = int( nwin_train_secs * fps )
nstep_split = int( nwin_train_secs * fps * (1-overlap) )
nsplit = (nframe_trim - nsize_split) // nstep_split + 1
print(f"frame ==> nsize = {nsize_split}, nstep = {nstep_split}, len = {nsplit}")
# load trim audio
audio, sr = librosa.load(str(ipath_audio)) # 16484 = fps * 550 让这个sr是fps的整数,
if sr != 22050:
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
audio = torch.from_numpy(audio).float()
audio = audio.unsqueeze(0)
melspec = model.mel_spectrogram(audio)
melspec = torch.squeeze(melspec, 0) # (80, 20374)
print(f"Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / nframe_trim}")
rato = melspec.shape[1] / nframe_trim
nsize_audio = int( nsize_split * rato) + 1 # 518 (if nwind=6s),
# nstep_audio = int( nstep_split * rato)
print(f"audio ==> rato = {rato}, nsize = {nsize_audio}") # nstep = {nstep_audio}, len={(melspec.shape[1] - nsize_audio) // nstep_audio + 1}")
data_melspec = torch.zeros(nsplit, 80, nsize_audio)
# nsize = int(nwin_train_secs * fps * rato) + 1 # rate = melspec.shape[1] / nframe_trim
for i in range(nsplit):
nseg_beg = int( i * nstep_split * rato )
nseg_end = nseg_beg + nsize_audio
data_melspec[i] = melspec[:, nseg_beg:nseg_end]
# print(f"{i:03d}/{nsplit}, {nseg_beg:05d}-{nseg_end:05d}")
# save
data_melspec = data_melspec.permute(0, 2, 1) # (nsplits, nsteps, 80)
np.save(ipath_save, data_melspec) # (nsplit, 173, 80)
print(f"data_melspec = {data_melspec.shape}, save to --> {ipath_save}")
# break
+101
View File
@@ -0,0 +1,101 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import torch
from scipy.io.wavfile import read
# We're using the audio processing from TacoTron2 to make sure it matches
sys.path.insert(0, '/ssdata1/lsen/CODE/Audio2Expression/3rdpart/')
import tacotron2
from tacotron2.layers import TacotronSTFT
MAX_WAV_VALUE = 32768.0
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# load STFT
model = TacotronSTFT(filter_length=1024,
hop_length=256,
win_length=1024,
sampling_rate=22050,
mel_fmin=0.0, mel_fmax=8000)
# set windows
nwin_train_secs = 2 # 6, 2
overlap = 0.8
fps = 30
# for each video
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_audio = ipath_data.joinpath("audio/audio_trim.wav")
ipath_save = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy") # feat_mel_trim_split
# ipath_audio = "/mnt/data2/CODE/waveglow/data/LJSpeech-1.1/wavs/LJ001-0013.wav"
if not ipath_audio.exists():
print(f"ERROR: NOT Exist {ipath_audio}")
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
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 trim audio
audio, sr = librosa.load(str(ipath_audio)) # 16484 = fps * 550 让这个sr是fps的整数,
if sr != 22050:
raise ValueError(f"{sr} SR doesn't match target 22050 SR")
audio = torch.from_numpy(audio).float()
audio = audio.unsqueeze(0)
print(f"audio shape = {audio.shape}, audio min-max({audio.min():.4f}, {audio.max():.4f})")
melspec = model.mel_spectrogram(audio)
melspec = torch.squeeze(melspec, 0) # (80, 20374)
print(f"Melspec shape = {melspec.shape}, min-max({melspec.min():.4f}, {melspec.max():.4f}), rate = {melspec.shape[1] / nframe_trim}")
# save
melspec = melspec.permute(1,0) # (nsplits, nsteps, 80)
# np.save(ipath_save, melspec) # (nsplit, 173, 80)
print(f"melspec = {melspec.shape}, save to --> {ipath_save}")
# break
+79
View File
@@ -0,0 +1,79 @@
import os
import sys
import json
import numpy as np
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_ldmk = ipath_data.joinpath("landmk-PFLD")
ipath_save_feat = ipath_data.joinpath("audio/feat_ldmk_trim.npy")
if ipath_save_feat.exists():
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# load landmark
feat_ldmk = []
prev_ldmk = None
nContinue = 0
for j in range(ibeg, iend):
jpath_ldmk = ipath_ldmk.joinpath(f"frame--{j:05d}.txt")
if not jpath_ldmk.exists():
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk)
if nContinue <= 2:
data_ldmk = prev_ldmk
nContinue += 1
else:
nContinue += 1
break
else:
data_ldmk = np.loadtxt(jpath_ldmk).astype(np.float)
prev_ldmk = data_ldmk
nContinue = 0
feat_ldmk.append(data_ldmk)
# if j % 100 == 0:
# print(f"the {j:05d}-th landmark")
# save
feat_ldmk = np.array(feat_ldmk)
if nContinue <= 2 and feat_ldmk.shape[0] == (iend-ibeg):
np.save(ipath_save_feat, feat_ldmk)
print(f"feat shape = {feat_ldmk.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
else:
print(f"ERROR: some landmark missing or length not same, length = {feat_ldmk.shape}/{iend-ibeg}")
@@ -0,0 +1,77 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import torch
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# set windows
nwin_train_secs = 2 # 6, 2
overlap = 0.8
fps = 30
# for each video
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_ladmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
ipath_save = ipath_data.joinpath("audio/feat_ldmk_trim_norm_split_2s.npy") # feat_mel_trim_split
if not ipath_ladmk.exists():
print(f"ERROR: NOT Exist {ipath_ladmk}")
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
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 landmark
data_ladmk = np.load(ipath_ladmk).reshape(-1, 136) # (nframe, 136)
assert data_ladmk.shape[0] == nframe_trim, f"the length of landmark {data_ladmk.shape[0]} != nframe_trim {nframe_trim}"
# split frames
nsize_split = int( nwin_train_secs * fps )
nstep_split = int( nwin_train_secs * fps * (1-overlap) )
nsplit = (nframe_trim - nsize_split) // nstep_split + 1
print(f"frame ==> nsize = {nsize_split}, nstep = {nstep_split}, len = {nsplit}")
# split landmark
data_ladmk = torch.from_numpy(data_ladmk).float()
data_ladmk2 = data_ladmk.unfold(dimension=0, size=nsize_split, step=nstep_split) # (nframe_trim//30, 136, 30)
data_ladmk2 = data_ladmk2.permute(0, 2, 1) # (nsplits, nsteps, 136)
print(f"data landmark unfold = {data_ladmk2.shape}")
# print(f"check data landmark[32, ::50] = {data_ladmk[62, ::50]}, \n data_ladmk2[1, ::50, 2] = {data_ladmk2[2, ::50, 2]}")
# save
np.save(ipath_save, data_ladmk2) # (nsplit, 60, 136)
print(f"data_ladmk2 = {data_ladmk2.shape}, save to --> {ipath_save}")
# break
@@ -0,0 +1,92 @@
import os
import sys
import json
import numpy as np
from pathlib2 import Path
import sys
sys.path.insert(0, "/mnt/data2/CODE/Audio2Expression")
from common.landmark import landmark_normalize
# from common.animation import save_animation, save_animation_with_gt
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # processing
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
if ivideo_name not in ["Celebrating-Independence-Day"]:
continue
print(f"\n processing {ivideo_name} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_ldmk = ipath_data.joinpath("landmk-PFLD")
ipath_save_feat = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
# if ipath_save_feat.exists():
# continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# load landmark
feat_ldmk = []
prev_ldmk = None
nContinue = 0
for j in range(ibeg, iend):
jpath_ldmk = ipath_ldmk.joinpath(f"frame--{j:05d}.txt")
if not jpath_ldmk.exists():
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk)
if nContinue <= 2:
data_ldmk = prev_ldmk
nContinue += 1
else:
nContinue += 1
break
else:
data_ldmk = np.loadtxt(jpath_ldmk).astype(np.float)
data_ldmk, _, _ = landmark_normalize(data_ldmk) # normalize
prev_ldmk = data_ldmk
nContinue = 0
feat_ldmk.append(data_ldmk)
# if j % 100 == 0:
# print(f"the {j:05d}-th landmark")
# save
feat_ldmk = np.array(feat_ldmk) # (N, 68, 2)
if nContinue <= 2 and feat_ldmk.shape[0] == (iend-ibeg):
np.save(ipath_save_feat, feat_ldmk)
print(f"feat shape = {feat_ldmk.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
# save to animation
else:
print(f"ERROR: some landmark missing or length not same, length = {feat_ldmk.shape}/{iend-ibeg}")
+167
View File
@@ -0,0 +1,167 @@
import os
import sys
import json
import shutil
import numpy as np
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
idx_pos = [0, 1, 2, 5, 15, 16, 17, 18]
# for each video
counter = 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
# if ivideo_name != "Weekly-Address-Continuing-to-Grow-the-Economy-in-the-New-Year":
# continue
print(f"\n processing {ivideo_name} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_pose = ipath_data.joinpath("openpose")
ipath_feat_body = ipath_data.joinpath("audio/openpose_upbody_trim.npy")
ipath_feat_face = ipath_data.joinpath("audio/openpose_face_trim.npy")
if ipath_feat_body.exists() and ipath_feat_face.exists():
counter += 1
# os.remove(str(ipath_feat_body))
# os.remove(str(ipath_feat_face))
continue
# load video info
nContinue = 0
with open(str(ipath_info), "r") as f:
info = json.load(f)
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 pose
feat_body = []
feat_face = []
prev_feat_body = None
prev_feat_face = None
nContinue = 0
for j in range(ibeg, iend):
# print(f"{j}-th frame, of {ibeg}, {iend}")
# if j > ibeg + 10: break
jpath_pose = ipath_pose.joinpath(f"video_orignal_{j:012d}_keypoints.json")
if not jpath_pose.exists():
print("ERROR: Missing the landmark of frame --> ", jpath_pose)
if prev_feat_body is None:
print("ERRO: The first should be a person")
nContinue = 100
break
# give two change
if nContinue <= 2:
ipose_face = prev_feat_face
ipose_body = prev_feat_body
nContinue += 1
else:
nContinue = 100
break
else:
# load json file
with open(str(jpath_pose)) as f:
ipose = json.load(f)
# read pose and face
npid = len(ipose['people'])
if npid == 0:
print(f"ERROR: detected NO person! of the {j}-th frames")
if prev_feat_body is None:
print("ERRO: The first should be a person")
nContinue = 100
break
# give two change
if nContinue <= 2:
ipose_face = prev_feat_face
ipose_body = prev_feat_body
nContinue += 1
else:
nContinue = 100
break
elif npid > 1:
print(f"\nERROR: detected MULTI persons, should select one!, the {j}-th in ({ibeg},{iend}), ")
# print(ipose)
# select the detetected which closest to prev_feat_face
nContinue = 0
diff_center = np.zeros((npid,))
for i in range(npid):
tmp_prev = 0 if prev_feat_body is None else prev_feat_body
ipose_body = np.array(ipose['people'][i]['pose_keypoints_2d']).reshape(-1, 3)[idx_pos, :2]
diff_center[i] = np.mean(np.abs(ipose_body - tmp_prev))
idx = np.argmin(diff_center) if prev_feat_body is not None else np.argmax(diff_center)
ipose_face = np.array(ipose['people'][idx]['face_keypoints_2d']).reshape(-1, 3)[:, :2]
ipose_body = np.array(ipose['people'][idx]['pose_keypoints_2d']).reshape(-1, 3)[idx_pos, :2]
print(f"\t selected the {idx}-th pose")
else:
nContinue = 0
ipose_face = np.array(ipose['people'][0]['face_keypoints_2d']).reshape(-1, 3)[:, :2]
ipose_body = np.array(ipose['people'][0]['pose_keypoints_2d']).reshape(-1, 3)[idx_pos, :2]
if prev_feat_body is not None:
# check pose corrected
# print(f"face shpe = {ipose_face.shape}, body = {ipose_body.shape}")
for k in range(ipose_body.shape[0]):
if ipose_body[k][0] == 0 and ipose_body[k][1] == 0:
ipose_body[k, :] = prev_feat_body[k, :]
if prev_feat_face is not None:
# check landmark corrected
for k in range(ipose_face.shape[0]):
if ipose_face[k][0] == 0 and ipose_face[k][1] == 0:
ipose_face[k, :] = prev_feat_face[k, :]
# add to feat
feat_body.append(ipose_body)
feat_face.append(ipose_face)
prev_feat_body = ipose_body
prev_feat_face = ipose_face
# break
# visualize
# save
if nContinue <= 2:
# save
feat_body = np.array(feat_body)
feat_face = np.array(feat_face)
print(f"save... feat_body shape = {feat_body.shape}, feat_face shape = {feat_face.shape}")
np.save(ipath_feat_body, feat_body)
np.save(ipath_feat_face, feat_face)
counter += 1
else:
print("nContinue > 2 some landmark broken or cut-off") # (nframe, 68, 2)
# break
print(f"OVER: processing {counter} videos")
+120
View File
@@ -0,0 +1,120 @@
import os
import json
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
from common.landmark import landmark_normalize
from common.animation import save_animation, save_animation_with_gt
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_ldmk_dlib = ipath_data.joinpath("landmk")
ipath_ldmk_pfld = ipath_data.joinpath("landmk-PFLD")
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# load landmark
vldmk_dlib, vldmk_pfld = [], []
pldmk_dlib, pldmk_pfld = None, None
nContinue_dlib, nContinue_pfld = 0, 0
for j in range(ibeg, iend):
# load Dlib
jpath_ldmk_dlib = ipath_ldmk_dlib.joinpath(f"frame-{j:05d}.txt")
jpath_ldmk_pfld = ipath_ldmk_pfld.joinpath(f"frame--{j:05d}.txt")
# add Dlib landmark
if not jpath_ldmk_dlib.exists():
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk_dlib)
if nContinue_dlib <= 2:
data_ldmk = pldmk_dlib
nContinue_dlib += 1
else:
nContinue_dlib += 1
break
else:
data_ldmk = np.loadtxt(jpath_ldmk_dlib).astype(np.float)
data_ldmk, _, _ = landmark_normalize(data_ldmk)
pldmk_dlib = data_ldmk
nContinue_dlib = 0
vldmk_dlib.append(data_ldmk)
# add PFLD landmark
if not jpath_ldmk_pfld.exists():
print("ERROR: Missing the landmark of frame --> ", jpath_ldmk_pfld)
if nContinue_pfld <= 2:
data_ldmk = pldmk_pfld
nContinue_pfld += 1
else:
nContinue_pfld += 1
break
else:
data_ldmk = np.loadtxt(jpath_ldmk_pfld).astype(np.float)
data_ldmk, _, _ = landmark_normalize(data_ldmk)
pldmk_pfld = data_ldmk
nContinue_pfld = 0
vldmk_pfld.append(data_ldmk)
# if j % 100 == 0:
# print(f"the {j:05d}-th landmark")
# save
vldmk_dlib = np.array(vldmk_dlib).reshape(1, -1, 68, 2) # (N, 68, 2)
vldmk_pfld = np.array(vldmk_pfld).reshape(1, -1, 68, 2)
print(f"vldmk_dlib shape = {vldmk_dlib.shape}, vldmk_pfld shape= {vldmk_pfld.shape}") # (nframe, 68, 2)
if nContinue_pfld <= 2 and nContinue_dlib <= 2 and vldmk_dlib.shape[0] == (iend-ibeg):
# np.save(ipath_save_feat, vldmk_dlib)
# show annotation
save_animation_with_gt(vldmk_dlib, vldmk_pfld,
path_save=Path(ipath_data),
suffix=f'DLIB_PLDF',
w=256, h=256, dpi=100)
# print(f"feat shape = {vldmk_dlib.shape}, save to -> {ipath_save_feat}") # (nframe, 68, 2)
else:
print(f"ERROR: some landmark missing or length not same, length = {vldmk_dlib.shape}/{iend-ibeg}")
@@ -0,0 +1,73 @@
import os
import sys
import json
import numpy as np
from pathlib2 import Path
def load_video_info(path_info, verbose=True):
with open(str(ipath_info), "r") as f:
info = json.load(f)
W = info["width"][0] # 1280 or 1920
H = info["height"][0] # 720 or 1080
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
if verbose: print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
return ibeg, iend, nframe_trim, W, H, info
else:
if verbose: print(f"ERROR: info['active_frames'] = {info['active_frames']}")
return None, None, None, W, H, info
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-no-scale-alignment') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# get mean pose
total_pose = []
total_shoulder = []
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_pose = ipath_data.joinpath("audio/openpose_upbody_trim.npy")
ibeg, iend, _, W, H, info= load_video_info(ipath_info, verbose=False)
if ibeg is None: continue
if not ipath_feat_pose.exists(): continue
idata_pose = np.load(ipath_feat_pose) # (nframes, 8, 2)
imean_pose = np.mean(idata_pose, axis=0) # (8, 2)
imean_pose = imean_pose / np.array([W, H])
imean_shoulder = np.sqrt((imean_pose[3,0]-imean_pose[2,0])**2 + (imean_pose[3,1]-imean_pose[2,1])**2)
print(f"data pose shape = {idata_pose.shape}, mean shape={imean_pose.shape}, root={imean_pose[1]}, size shoulder = {imean_shoulder}--> {ivideo_name}")
total_pose.append(imean_pose)
total_shoulder.append(imean_shoulder)
# update info
info["mean_shoulder_size"] =imean_shoulder
info["mean_pose"] = list(imean_pose.reshape(-1))
with open(str(ipath_info), 'w+') as f:
json.dump(info, f)
print(f"update video info in -> {ipath_info}")
total_pose = np.array(total_pose)
mean_pose = np.mean(total_pose, axis=0)
mean_shoulder = np.mean(total_shoulder)
print(f"total_pose shape = {total_pose.shape}, mean pose ={mean_pose.shape}, mean[1,] = {mean_pose[1,:]}, mean shoulder size = {mean_shoulder}")
# save mean
np.save(path_save.joinpath("mean_pose.npy"), mean_pose) # (8,2)
np.save(path_save.joinpath("mean_shoulder.npy"), mean_shoulder)
+174
View File
@@ -0,0 +1,174 @@
import os
import sys
import json
# import moviepy.editor as mpy
import numpy as np
from pathlib2 import Path
import sys
sys.path.insert(0, "/mnt/data2/CODE/TalkingGlow")
from common.utils import smooth
from common.logger import Logger
from common.landmark import landmark_to_images
def load_video_info(path_info, verbose=True):
with open(str(ipath_info), "r") as f:
info = json.load(f)
W = info["width"][0] # 1280 or 1920
H = info["height"][0] # 720 or 1080
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
if verbose: print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
return ibeg, iend, nframe_trim, W, H, info
else:
if verbose: print(f"ERROR: info['active_frames'] = {info['active_frames']}")
return None, None, None, W, H, info
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-no-scale-alignment') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# get mean pose
mean_pose = np.load(path_save.joinpath("mean_pose.npy")) # (8,2)
mean_shoulder = np.load(path_save.joinpath("mean_shoulder.npy")) # (1,)
print(f"mean pose = {mean_pose.shape}, root pose = {mean_pose[1]}, mean shoulder = {mean_shoulder}")
# for each video
ncounter = 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
# if ivideo_name != "Weekly-Address-Ensuring-Equal-Pay-for-Equal-Work":
# continue
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_ldmk = ipath_data.joinpath("audio/feat_ldmk_trim.npy")
ipath_feat_pose = ipath_data.joinpath("audio/openpose_upbody_trim.npy")
ipath_feat_ldmk_align = ipath_data.joinpath("audio/feat_ldmk_align_trim.npy")
ipath_feat_pose_align = ipath_data.joinpath("audio/openpose_upbody_align_trim.npy")
if not ipath_feat_ldmk.exists() or not ipath_feat_pose.exists():
continue
elif ipath_feat_ldmk_align.exists() and ipath_feat_pose_align.exists():
ncounter += 1
continue
else:
print(f"\n processing the {ncounter}-th videp, {ivideo_name} ... ")
ncounter += 1
# load video info
ibeg, iend, _, W, H, info = load_video_info(ipath_info)
if ibeg is None: continue
# load landmark feat
data_ldmk = np.load(ipath_feat_ldmk) # (nframe, 68, 2)
data_pose = np.load(ipath_feat_pose) # (nframe, 8, 2)
data_ldmk = data_ldmk / np.array([[[W, H]]]) # scale landmark
data_pose = data_pose / np.array([[[W, H]]]) # scale pose
print(f"data landmark shape={data_ldmk.shape}, pose shape = {data_pose.shape}")
assert data_ldmk.shape[0] == data_pose.shape[0], "nframes length should be same"
##################################
# STEP 1: get sacle and smooth scale
v_scale = []
for j in range(data_ldmk.shape[0]):
jdata_pose = data_pose[j, :, :] # (8, 2)
jshoulder = np.sqrt((jdata_pose[3,0]-jdata_pose[2,0])**2 + (jdata_pose[3,1]-jdata_pose[2,1])**2)
scale = mean_shoulder / jshoulder
v_scale.append(scale)
# if j % 100 == 0:
# print(f"\nthe {ibeg + j}-th frame!")
# print(f"pose root = {data_pose[j, 1, :]}, mean pose root = {mean_pose[1]}")
# print(f"should size = {jshoulder:.4f}, mean shoulder = {mean_shoulder:.4f}, scale = {scale:0.4f}")
v_scale = np.array(v_scale)
v_scale_smooth = smooth(v_scale, window_len=60, window='hanning')
print(f"scale shape= {v_scale.shape}, smooth = {v_scale_smooth.shape}")
# for v, s in zip(v_scale, v_scale_smooth):
# print(f"orignal {v:.4f}, smooth={s:.4f}, mean={mean_shoulder:.4f}")
##################################
# STEP 2: sacle landmark and pose
data_ldmk_scale = []
data_pose_scale = []
for j in range(data_ldmk.shape[0]):
jdata_ldmk_scale = data_ldmk[j, :, :] * v_scale_smooth[j]
jdata_pose_scale = data_pose[j, :, :] * v_scale_smooth[j]
data_ldmk_scale.append(jdata_ldmk_scale)
data_pose_scale.append(jdata_pose_scale)
# if j % 100 == 0:
# jshoulder_scale = np.sqrt((jdata_pose_scale[3,0]-jdata_pose_scale[2,0])**2 + (jdata_pose_scale[3,1]-jdata_pose_scale[2,1])**2)
# print(f"\nthe {ibeg + j}-th frame!")
# print(f"pose root = {data_pose[j, 1, :]}, scale root={jdata_pose_scale[1]}, mean pose root = {mean_pose[1]}")
# print(f"shoulder size = {jshoulder:.4f}, scale ={jshoulder_scale:.4f} mean shoulder = {mean_shoulder:.4f}, scale = {v_scale[j]:.4f}, smooth scale={v_scale_smooth[j]:.4f}")
data_ldmk_scale = np.array(data_ldmk_scale)
data_pose_scale = np.array(data_pose_scale)
##################################
# STEP 3: alignment to mean-pose
data_ldmk_align = []
data_pose_align = []
for j in range(data_ldmk.shape[0]):
jpose_root = data_pose_scale[j, 1, :] # (2, )
jmean_root = mean_pose[1, :] # (2, )
jdeta = jmean_root - jpose_root
jdata_ldmk_align = data_ldmk_scale[j, :, :] + jdeta.reshape(1, 2)
jdata_pose_align = data_pose_scale[j, :, :] + jdeta.reshape(1, 2)
data_ldmk_align.append(jdata_ldmk_align)
data_pose_align.append(jdata_pose_align)
if j % 1000 == 0:
jshoulder = np.sqrt((data_pose[j,3,0]-data_pose[j,2,0])**2 + (data_pose[j,3,1]-data_pose[j,2,1])**2)
jshoulder_scale = np.sqrt((data_pose_scale[j,3,0]-data_pose_scale[j,2,0])**2 + (data_pose_scale[j,3,1]-data_pose_scale[j,2,1])**2)
jshoulder_align = np.sqrt((jdata_pose_align[3,0]-jdata_pose_align[2,0])**2 + (jdata_pose_align[3,1]-jdata_pose_align[2,1])**2)
print(f"\nthe {ibeg + j}-th frame!")
print(f"orignal root = {data_pose[j, 1, :]}, scale={jdata_pose_scale[1]}, align = {jdata_pose_align[1]}, mean = {mean_pose[1]}")
print(f"orignal shoulder = {jshoulder:.4f}, scale ={jshoulder_scale:.4f} mean shoulder = {mean_shoulder:.4f}")
print(f"orignal scale = {v_scale[j]:.4f}, smooth scale={v_scale_smooth[j]:.4f}")
data_ldmk_align = np.array(data_ldmk_align)
data_pose_align = np.array(data_pose_align)
##################################
# STEP 4: save & visualization
np.save(ipath_feat_ldmk_align, data_ldmk_align)
np.save(ipath_feat_pose_align, data_pose_align)
print(f"align ldmk shape={data_ldmk_align.shape}, pose shape = {data_pose_align.shape}--> save to {ipath_feat_ldmk_align}")
# visualization
# images_gt = landmark_to_images(data_ldmk[::10, ...], w=128*5, h=72*5, dpi=100, norm=True, prex="GT") # (N, W, H, 3)
# images_pt = landmark_to_images(data_ldmk_align[::10, ...], w=128*5, h=72*5, dpi=100, norm=True, prex="Alignment") # (N, W, H, 3)
# print("convert to video")
# data_motion_mix = np.concatenate([images_gt, images_pt], axis=1) # (N, W, 2H, 3)
# data_motion_mix = data_motion_mix.astype(np.uint8)
# print("data shape = ", data_motion_mix.shape)
# fps = 10
# N = data_motion_mix.shape[0]
# animation = mpy.VideoClip(lambda t: data_motion_mix[int(fps * t + 0.5),...], duration= N // fps)
# animation.write_videofile("my_animation.mp4", fps=fps)
+157
View File
@@ -0,0 +1,157 @@
import os
import sys
import json
import joblib as jl
import numpy as np
from pathlib2 import Path
from sklearn.preprocessing import StandardScaler
def fit_and_standardize(data):
(nseq, nWind, nfeat) = data.shape
data_reshape = data.copy().reshape(-1, nfeat)
scaler = StandardScaler().fit(data_reshape)
data_scale = scaler.transform(data_reshape).reshape(nseq, nWind, nfeat)
return data_scale, scaler
def standardize(data, scaler):
shape = data.shape
flat = data.copy().reshape((shape[0]*shape[1], shape[2]))
scaled = scaler.transform(flat).reshape(shape)
return scaled
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)
sliced = np.zeros((n_sequences, window_size, data.shape[1])).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('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-no-scale-alignment-2-5') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_align_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = [ipath.stem for ipath in v_dir_videos]
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)
# set windows
nwin_train_secs = 2 # 6
nwin_test_secs = 5 # 20
window_overlap = 0.2 # 0.8
fps = 30
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
# 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 == 0:
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_align_trim.npy")
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
# 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
# print("width=",width, "height=",height, "-->", ipath_data)
data_motion = np.load(ipath_feat_motion).reshape(-1, 136) # (nframe, 68, 2)
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
# data_motion = data_motion / np.array([[[width, height]]])
# data_motion = data_motion.reshape(-1, 136)
# print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
assert data_motion.shape[0] == data_speech.shape[0]
nfeat_motion = data_motion.shape[1]
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)
elif vid in vid_valid:
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_valid.append(motion_sliced)
speech_valid.append(speech_sliced)
else:
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 data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
# save
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
_, motion_scaler = fit_and_standardize(motion_train)
_, speech_scaler = fit_and_standardize(speech_train)
# print(motion_scaler.mean_ )
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
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)
# motion_valid = standardize(motion_valid, motion_scaler)
# speech_valid = standardize(speech_valid, speech_scaler)
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)
# motion_test = standardize(motion_test, motion_scaler)
# speech_test = standardize(speech_test, speech_scaler)
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}")
@@ -0,0 +1,173 @@
import os
import sys
import json
import joblib as jl
import numpy as np
from pathlib2 import Path
from sklearn.preprocessing import StandardScaler
def fit_and_standardize(data):
(nseq, nWind, nfeat) = data.shape
data_reshape = data.copy().reshape(-1, nfeat)
scaler = StandardScaler().fit(data_reshape)
data_scale = scaler.transform(data_reshape).reshape(nseq, nWind, nfeat)
return data_scale, scaler
def standardize(data, scaler):
shape = data.shape
flat = data.copy().reshape((shape[0]*shape[1], shape[2]))
scaled = scaler.transform(flat).reshape(shape)
return scaled
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)
sliced = np.zeros((n_sequences, window_size, data.shape[1])).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('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-diff') # processing
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)
# set windows
nwin_train_secs = 2 # 6
nwin_test_secs = 5 # 20
window_overlap = 0.5 # 0.8
fps = 30
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
# 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 == 0:
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
# 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
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
# load data
data_motion = np.load(ipath_feat_motion).reshape(-1, 68, 2) # (nframe, 68, 2)
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
data_direct = data_motion[1:, :, :] - data_motion[:-1, :, :] # (N-1, 68, 2)
data_tmp = data_direct * data_direct # (N-1, 68, 2)
data_tmp = np.sqrt(data_tmp[:, :, 0] + data_tmp[:, :, 1]) # (N-1, 68)
data_direct = data_direct / (data_tmp.reshape(-1, 68, 1) + 1e-8) # (N-1, 68, 2)
data_direct = np.clip(data_direct, -1.0, 1.0) # clips to (-1 ~ 1)
data_motion = data_motion[:-1, :, :] # (N-1, 68, 2)
data_speech = data_speech[:-1, :] # (N-1, 27)
data_motion = np.concatenate([data_motion, data_direct], axis=2) # (N-1, 68, 4)
print(f"data_motion concate shape = {data_motion.shape}")
data_motion = data_motion.reshape(-1, 272)
# data_motion = data_motion / np.array([[[width, height]]])
# data_motion = data_motion.reshape(-1, 136)
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
assert data_motion.shape[0] == data_speech.shape[0]
nfeat_motion = data_motion.shape[1]
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)
elif vid in vid_valid:
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_valid.append(motion_sliced)
speech_valid.append(speech_sliced)
else:
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 data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
# save
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
# _, motion_scaler = fit_and_standardize(motion_train)
# _, speech_scaler = fit_and_standardize(speech_train)
# print(motion_scaler.mean_ )
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
# jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
# jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
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)
# motion_valid = standardize(motion_valid, motion_scaler)
# speech_valid = standardize(speech_valid, speech_scaler)
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)
# motion_test = standardize(motion_test, motion_scaler)
# speech_test = standardize(speech_test, speech_scaler)
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}")
@@ -0,0 +1,165 @@
import os
import sys
import json
import joblib as jl
import numpy as np
from pathlib2 import Path
from sklearn.preprocessing import StandardScaler
def fit_and_standardize(data):
(nseq, nWind, nfeat) = data.shape
data_reshape = data.copy().reshape(-1, nfeat)
scaler = StandardScaler().fit(data_reshape)
data_scale = scaler.transform(data_reshape).reshape(nseq, nWind, nfeat)
return data_scale, scaler
def standardize(data, scaler):
shape = data.shape
flat = data.copy().reshape((shape[0]*shape[1], shape[2]))
scaled = scaler.transform(flat).reshape(shape)
return scaled
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)
sliced = np.zeros((n_sequences, window_size, data.shape[1])).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('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
path_save = Path('data/obama-landmark-pose-3-5-05') # processing
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)
# set windows
nwin_train_secs = 3 # 6
nwin_test_secs = 5 # 20
window_overlap = 0.5 # 0.8
fps = 30
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
# 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 == 0:
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_ldmk = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
# 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
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
data_ldmk = np.load(ipath_feat_ldmk).reshape(-1, 136) # (nframe, 136)
data_pose = np.load(ipath_feat_pos) # (nframe, 3)
data_motion = np.concatenate([data_ldmk, data_pose], axis=1) # (nframe, 139)
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
# data_motion = data_motion / np.array([[[width, height]]])
# data_motion = data_motion.reshape(-1, 136)
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
assert data_motion.shape[0] == data_speech.shape[0]
nfeat_motion = data_motion.shape[1]
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)
elif vid in vid_valid:
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_valid.append(motion_sliced)
speech_valid.append(speech_sliced)
else:
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 data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
# save
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
# _, motion_scaler = fit_and_standardize(motion_train)
# _, speech_scaler = fit_and_standardize(speech_train)
# print(motion_scaler.mean_ )
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
# jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
# jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
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)
# motion_valid = standardize(motion_valid, motion_scaler)
# speech_valid = standardize(speech_valid, speech_scaler)
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)
# motion_test = standardize(motion_test, motion_scaler)
# speech_test = standardize(speech_test, speech_scaler)
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}")
@@ -0,0 +1,89 @@
import os
import sys
import json
import joblib as jl
import numpy as np
from pathlib2 import Path
from sklearn.preprocessing import StandardScaler
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-landmark-split-6') # processing
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
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 vid not in vid_test: continue
if i % 50 == 0:
print(f"\n processing the {i}-th video {vid} ... ")
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm_split_6s.npy") # feat_ldmk_trim_norm_split
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim_split_6s.npy") # feat_ldmk_trim_norm_split
data_motion = np.load(ipath_feat_motion) # (nsplit, 173, 80)
data_speech = np.load(ipath_feat_speech) # (nsplit, 60, 136)
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
assert data_motion.shape[0] == data_speech.shape[0]
if vid in vid_train:
motion_train.append(data_motion)
speech_train.append(data_speech)
elif vid in vid_valid:
motion_valid.append(data_motion)
speech_valid.append(data_speech)
else:
motion_test.append(data_motion)
speech_test.append(data_speech)
# # save
# motion_train = np.concatenate(motion_train, axis=0) # (10612, 60, 136)
# speech_train = np.concatenate(speech_train, axis=0) # (10612, 173, 80)
# 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, 60, 136)
# speech_valid = np.concatenate(speech_valid, axis=0) # (350, 173, 80)
# 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, 60, 136)
speech_test = np.concatenate(speech_test, axis=0) # (41, 173, 80)
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}")
@@ -0,0 +1,136 @@
import json
import numpy as np
from pathlib2 import Path
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)
sliced = np.zeros((n_sequences, window_size, data.shape[1])).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/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-landmark-3-5-05') # processing
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)
# set windows
nwin_train_secs = 3 # 6
nwin_test_secs = 5 # 20
window_overlap = 0.5 # 0.8
fps = 30
nwin_train = nwin_train_secs * fps # 6 * 20 = 120
nwin_test = nwin_test_secs * fps # 20 * 20 = 400
# 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 == 0:
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_motion = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy") #
ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy")
# 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
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
data_motion = np.load(ipath_feat_motion).reshape(-1, 136) # (nframe, 68, 2)
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
# data_motion = data_motion / np.array([[[width, height]]])
# data_motion = data_motion.reshape(-1, 136)
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
assert data_motion.shape[0] == data_speech.shape[0]
# nfeat_motion = data_motion.shape[1]
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)
elif vid in vid_valid:
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_valid.append(motion_sliced)
speech_valid.append(speech_sliced)
else:
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 data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
# save
motion_train = np.concatenate(motion_train, axis=0) # (10612, 180, 136)
speech_train = np.concatenate(speech_train, axis=0) # (10612, 180, 27)
# _, motion_scaler = fit_and_standardize(motion_train)
# _, speech_scaler = fit_and_standardize(speech_train)
# print(motion_scaler.mean_ )
np.savez(path_save.joinpath("motion_train.npz"), data=motion_train)
np.savez(path_save.joinpath("speech_train.npz"), data=speech_train)
# jl.dump(motion_scaler, str(path_save.joinpath(f'motion_scaler.sav')))
# jl.dump(speech_scaler, str(path_save.joinpath(f'speech_scaler.sav')))
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)
# motion_valid = standardize(motion_valid, motion_scaler)
# speech_valid = standardize(speech_valid, speech_scaler)
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)
# motion_test = standardize(motion_test, motion_scaler)
# speech_test = standardize(speech_test, speech_scaler)
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}")
Whitespace-only changes.
+75
View File
@@ -0,0 +1,75 @@
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/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# for each video
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_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():
continue
if not ipath_infors.exists():
continue
print(f"\n processing {ivideo_name} ... ")
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
feat_exp = []
feat_pos = []
feat_idn = []
for j in range(ibeg, iend):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:05d}.json.npy")
if not jpath_coeff.exists():
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)
if nframe_trim == 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"exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape},nframe_trim = {nframe_trim} \n save to -> {ipath_save_exp}") # (nframe, 68, 2)
# print(f"idn={feat_idn.shape},nframe_trim = {nframe_trim} \n save to -> {ipath_save_exp}") # (nframe, 68, 2)
@@ -0,0 +1,86 @@
import os
import sys
import json
import torch
import numpy as np
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path('/mnt/data2/DATA/Obama/processing/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"))
print(f"Have {len(v_dir_videos)} dir files")
# set windows
nwin_train_secs = 2 # 6, 2
overlap = 0.8
fps = 30
# for each video
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_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_save = ipath_data.joinpath("audio/feat_DECA_trim_split_2s.npy") # feat_mel_trim_split
if not ipath_exp.exists() or not ipath_pos.exists() or not ipath_idn.exists():
print(f"ERROR: NOT Exist {ipath_exp} or {ipath_pos} or {ipath_idn}" )
continue
print(f"\n processing {ivideo_name} ... ")
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
width = info["width"][0] # 1280 or 1920
height = info["height"][0] # 720 or 1080
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
feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
feat_pos = np.load(ipath_pos) # (nframe_trim, 6)
feat_3dmm = np.concatenate([feat_idn, feat_exp, feat_pos], axis=1)
if nframe_trim != feat_3dmm.shape[0]:
print(f"ERROR: nframe_trim = {nframe_trim} != feat_3dmm len {feat_3dmm.shape[0]}")
continue
# split
nsize_split = int( nwin_train_secs * fps )
nstep_split = int( nwin_train_secs * fps * (1-overlap) )
feat_3dmm = torch.from_numpy(feat_3dmm).float()
feat_3dmm2 = feat_3dmm.unfold(dimension=0, size=nsize_split, step=nstep_split) # (nframe_trim//30, 136, 30)
feat_3dmm2 = feat_3dmm2.permute(0, 2, 1) # (nsplits, nsteps, 136)
print(f"data feat_3dmm unfold = {feat_3dmm2.shape}")
# print(f"check data landmark[32, ::50] = {data_ladmk[62, ::50]}, \n data_ladmk2[1, ::50, 2] = {data_ladmk2[2, ::50, 2]}")
print(f"ldmk ==> nsize = {nsize_split}, nstep = {nstep_split}, len = {(nframe_trim - nsize_split) // nstep_split + 1}")
# save
np.save(ipath_save, feat_3dmm2) # (nsplit, 60, 136)
print(f"feat_3dmm={feat_3dmm.shape}, feat_3dmm2={feat_3dmm2.shape}, save to -> {ipath_save}") # (nframe, 68, 2)
@@ -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/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-dsv1-deca-5-10-08-mini8k') # 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 = [ipath.stem for ipath in v_dir_videos]
nv_total = len(v_dir_videos)
nv_valid, nv_test = 1, 1
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)
# set windows
nwin_train_secs = 5 # 6
nwin_test_secs = 10 # 20
window_overlap = 0.8
fps = 30
nwin_train = nwin_train_secs * fps # 3 * 30 = 90
nwin_test = nwin_test_secs * fps # 5 * 30 = 150
# 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
if i % 50 == 0:
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_deepspeech010_trim.npy")
ipath_feat_speech = ipath_data.joinpath("audio/feat_deepspeech_v1_trim.npy")
if not ipath_feat_speech.exists():
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("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
# 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*2, 16, 29) --> fps=60
print(f"motion = {data_motion.shape}, speech = {data_speech.shape}")
# # downsampling data_speech, 60fps --> fps
# (nseq, nwind, nfeat) = data_speech.shape # (nframe*2, 16, 29)
# data_speech = data_speech.reshape(nseq, -1) # (nframe*2, 16x29)
# data_speech = interpolate_features(data_speech, 60, fps, output_len=data_motion.shape[0])
# data_speech = data_speech.reshape(-1, nwind, nfeat)
# print(f"after motion = {data_motion.shape}, speech = {data_speech.shape}")
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=window_overlap)
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
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, 180, 136)
speech_train = np.concatenate(speech_train, axis=0) # (nframe, 180, 27)
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,129 @@
import json
import numpy as np
from pathlib2 import Path
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)
sliced = np.zeros((n_sequences, window_size, data.shape[1])).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/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-deca-5-10-08') # 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 = [ipath.stem for ipath in v_dir_videos]
nv_total = len(v_dir_videos)
nv_valid, nv_test = 1, 1
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)
# set windows
nwin_train_secs = 5 # 6
nwin_test_secs = 10 # 20
window_overlap = 0.8
fps = 30
nwin_train = nwin_train_secs * fps # 3 * 30 = 90
nwin_test = nwin_test_secs * fps # 5 * 30 = 150
# 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 >= 5: continue
if i % 50 == 0:
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")
# 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
print("width=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data)
# 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)
data_speech = np.load(ipath_feat_speech) # (nframe, 27)
print(f"data_exp data = {data_exp.shape},data_pos = {data_pos.shape}, \n motion = {data_motion.shape}, speech = {data_speech.shape}")
assert data_exp.shape[0] == data_speech.shape[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=window_overlap)
speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap)
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 data = {motion_sliced.shape}, speech data = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)})")
# save
motion_train = np.concatenate(motion_train, axis=0) # (nframe, 180, 136)
speech_train = np.concatenate(speech_train, axis=0) # (nframe, 180, 27)
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}")
@@ -0,0 +1,122 @@
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/Obama/processing') # '../data/trinity/source'
path_save = Path('data/obama-deca-mel') # 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 = [ipath.stem for ipath in v_dir_videos]
nv_total = len(v_dir_videos)
nv_valid, nv_test = 1, 1
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
if i % 50 == 0:
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_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
if not ipath_speech.exists():
print(f"ERROR: NOT Exist {ipath_speech}" )
continue
if not ipath_exp.exists() or not ipath_pos.exists():
print(f"ERROR: NOT Exist {ipath_pos} or {ipath_exp}" )
continue
# check existing
if 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_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
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
# feat_idn = np.load(ipath_idn) # (nframe_trim, 100)
feat_exp = np.load(ipath_exp) # (nframe_trim, 50)
feat_pos = np.load(ipath_pos) # (nframe_trim, 6) # (N, 6)
data_motion = np.concatenate([feat_exp, feat_pos[:, 3:6]], axis=1) # (N, 53)
data_speech = np.load(ipath_speech) # (M, 80) please note that M != N
print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}")
# assert data_motion.shape[0] == data_speech.shape[0]
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}")