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

+163
View File
@@ -0,0 +1,163 @@
import time
import sys
import argparse
from pathlib import Path
import numpy as np
import imageio
import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
sys.path.insert(0, "/mnt/data/CODE/Audio2Expression")
from src.datasets import create_dataset
from src.models.functions import get_pad_mask, get_subsequent_mask
from src.models import create_model, calculate_model_params
from src.config import config as opt
from src.config import update_config
from src.datasets.grid_ldmk import GRID_LdmkDataset
from src.models.transformer_a2l import TransformerA2L
from common.logger import Logger
from common.vis.visualizer import Visualizer
from common.metrics.utils import AverageMeterDict
from common.image import save_image
from common.landmark import landmark_to_image
def parese_args():
pareser = argparse.ArgumentParser(description='Facial Landmark Disentangle Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/W300/test-landmark.yaml", help="experiment configure file name")
pareser.add_argument("--load_epoch", default=None, help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
return pareser.parse_args()
if __name__ == "__main__":
args = parese_args()
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
path_checkpoint = Path(opt.MODEL.path_checkpoint)
# update load_epoch
if args.load_epoch is not None:
opt.MODEL.load_epoch = args.load_epoch
# setting logger and output dir
path_config = Path(args.opt)
logger = Logger(opt.OUTPUT_DIR, path_config=path_config)
opt.OUTPUT_DIR = logger.path_output
path_save = Path(opt.OUTPUT_DIR)
# update load_epoch
if args.load_epoch is not None:
opt.MODEL.load_epoch = args.load_epoch
# load data
data_test = GRID_LdmkDataset(opt)
data_loader = DataLoader(data_test, batch_size=opt.TEST.batch_size, shuffle=False, drop_last=False)
logger.info(f"test dataset = {len(data_test)}, data_batch = {len(data_loader)}")
# load model
netG = TransformerA2L(opt) # [100, 500, 1000, 2000, 2300]
seleted_epochs = [3390, 3000, 2500, 2000, 1500, 1000, 500] #8000, 9000,10000] #000, 9000, 9500, 10000]
print("load from -->", path_checkpoint)
for epoch in seleted_epochs:
netG.eval()
# load model parameters
ipath_checkpoint = path_checkpoint.joinpath("checkpoints", f'{epoch}_net_G.pth')
state_dict = torch.load(str(ipath_checkpoint), map_location=str(device))
netG.load_state_dict(state_dict)
netG = netG.to(device)
# test data
avg_meter = AverageMeterDict()
for i, ibatch_data in enumerate(data_loader):
with torch.no_grad():
batch_ldmk = ibatch_data['ldmk_norm'] # (1, 25N, 68, 2)
batch_mfcc = ibatch_data['mfcc_feat'] # (1, 100N, 13)
batch_path = ibatch_data['ldmk_path']
# batch_mask = get_subsequent_mask(25) # (1, N, N)
# batch_mask = batch_mask.to(device)
batch_ldmk = batch_ldmk.float().to(device)
batch_mfcc = batch_mfcc.float().to(device)
(B, N, *_) = batch_ldmk.shape
batch_predt = torch.zeros((B, N+1, 68, 2)).float().to(device) # (1, N, 68, 2)
batch_predt[:, :25, :, : ] = batch_ldmk[:, :25, :, :]
print(f"ldmk={batch_ldmk.shape}, mfcc={batch_mfcc.shape}, predt={batch_predt.shape}")
for j in range(24, N):
if j == 0:
jbatch_ldmk = batch_ldmk[:, :1, :, :] # (1, 1, 68, 2)
jbatch_mfcc = batch_mfcc[:, :4, :] # (1, 4, 13)
batch_mask = get_subsequent_mask(1).to(device) # (1, 1, 1)
elif j < 25:
jbatch_ldmk = batch_predt[:, :(j+1), :, :] # (1, J, 68, 2)
jbatch_mfcc = batch_mfcc[:, :4*(j+1), :] # (1, 4J, 13)
batch_mask = get_subsequent_mask(j+1).to(device) # (1, N, N)
else:
jbatch_ldmk = batch_predt[:, j-24 :(j+1), :, :] # (1, 25, 68, 2)
jbatch_mfcc = batch_mfcc[:, 4*j-96 :4*(j+1), :] # (1, 100, 13)
batch_mask = get_subsequent_mask(25).to(device) # (1, N, N)
y = netG(jbatch_mfcc, None, jbatch_ldmk, batch_mask, shift=False) # (1, j, 68, 2)
batch_predt[:, j+1, :, :] = y[:, -1, :, :] # The last one
metr_dict = {}
# reconstruction loss
predt = batch_predt[:, 1:, :, :].reshape(-1, 68, 2) # (BN, 68, 2)
targt = batch_ldmk.reshape(-1, 68, 2) # (BN, 68, 2)
diff = (predt - targt) * (predt - targt) # (BN, 68, 2)
diff = torch.sqrt( diff[:, :, 0] + diff[:, :, 1]) # (NB, 68,)
metr_dict["metric_rec"] = torch.mean(torch.sum(diff, dim=1)) # (1,)
metr_dict["metric_mae"] = F.l1_loss(predt, targt, reduce="mean")
# show image
if i % 10 == 0 and opt.verbose:
frames = []
for j in range(24, N):
img = landmark_to_image(batch_ldmk[0, j, :, :], text=f"frame-{j:02}-render")
img_predt = landmark_to_image(batch_predt[0, j+1, :, :], text=f"frame-{j:02}-render")
frames.append(np.concatenate([img, img_predt], axis=1)) # (2W, H, 3)
jpath_save_img = path_save.joinpath(f"Epoch-{epoch}-Batch-{i:03d}-GIF.gif")
# duration = (N-25) / 30.0
imageio.mimsave(str(jpath_save_img), frames, 'GIF', duration=0.25)
# jpath_save_pdt = path_save.joinpath(f"Epoch-{epoch}-Batch-{i:03d}-predt", f"frame-{j:05d}.jpg")
# jpath_save_img.parent.mkdir(exist_ok=True, parents=True)
# jpath_save_pdt.parent.mkdir(exist_ok=True, parents=True)
# save_image(img, jpath_save_img)
# save_image(img_predt, jpath_save_pdt)
# update
avg_meter.update(metr_dict)
if i% 10 == 0:
print(f"batch {i:03d}:", avg_meter.print_msg())
print(f"Epoch {epoch} validation:\n\t", avg_meter.print_msg())
+143
View File
@@ -0,0 +1,143 @@
import os
from pathlib import Path
import shutil
UNZIP_FILES = False
MV_AUDIO_FILES = False
MV_VIDEO_FILES = False
EXTRACT_AUDIO = True
total_pid = ["s1.", "s2.", "s3.", "s4.", "s5.", "s6.", "s7.", "s8.", "s9.", "s10." ]
# total_pid = [ "s6.", "s7.", "s8.", "s9.", "s21."]
def is_exist_pid(file_name):
for iid in total_pid:
if str(iid) in str(file_name.name):
return True
return False
if __name__ == '__main__':
path_root = Path("/yrfs/lsen/DATA/GRID/")
if UNZIP_FILES:
path_zip = path_root.joinpath("zip_data")
path_data = path_root.joinpath("unzip_data")
path_data.mkdir(parents=True, exist_ok=True)
v_zip_files = sorted(path_zip.glob("./*.tar"))
print(f"Have {len(v_zip_files)} zip files, \n {v_zip_files[:10]}")
for i, izip in enumerate(v_zip_files):
if not is_exist_pid(izip): continue
ipath_data = path_data.joinpath(str(izip.stem))
# if not ipath_data.exists():
cmd = f"cd {str(path_zip)}; tar -xf {str(izip)} -C {str(path_data)}"
print(f"RUN: {cmd}")
os.system(cmd)
#break
if MV_AUDIO_FILES:
path_unzip = path_root.joinpath("unzip_data")
v_ids_file = sorted(path_unzip.glob("*"))
print(f"Have {len(v_ids_file)} persons files, \n {v_ids_file[:10]}")
for i, iid in enumerate(v_ids_file):
cmd = f"cd {str(iid)}; mkdir audio; mv *.wav audio"
print(f"RUN: {cmd}")
os.system(cmd)
#break
if MV_VIDEO_FILES:
path_data = path_root.joinpath("unzip_data")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name, "video/mpg_6000")
v_dir_videos = sorted(dir_video.glob("*.mpg"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for ipath_videos in v_dir_videos:
ivideo_name = ipath_videos.stem
# copy video
ipath_video_target = path_root.joinpath("processing", id_name, ivideo_name, "video/video_orignal.mp4")
if not ipath_video_target.exists():
ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
#print(f"copy {ipath_videos} --> {ipath_video_target}")
# # copy audio
# ipath_audio_source = path_data.joinpath(id_name, f"audio/{ivideo_name}.wav")
# ipath_audio_target = path_root.joinpath("processing", id_name, ivideo_name, "audio/audio_orignal.wav")
# if not ipath_audio_target.exists():
# ipath_audio_target.parent.mkdir(parents=True, exist_ok=True)
# shutil.copy(src=str(ipath_audio_source), dst=str(ipath_audio_target))
# #print(f"copy {ipath_audio_source} --> {ipath_audio_target}")
# break
if EXTRACT_AUDIO:
path_data = path_root.joinpath("processing")
vpath_ids = sorted(path_data.glob("*"))
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
for i, ipath_id in enumerate(vpath_ids):
pid = ipath_id.stem # person id
# if pid in ["s1", "s10", "s11", "s12", "s13", "s14"]:
# continue
# video
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
# for each video
list_dict = []
for iv, ipath_video in enumerate(vpath_videos):
vid = ipath_video.parent.parent.stem # video id
if iv % 50 == 0:
print(f"--> processing the {iv}-th video --> {ipath_video}")
ipath_audio = ipath_video.parent.parent.joinpath("audio/audio_extract.wav")
ipath_audio.parent.mkdir(parents=True, exist_ok=True)
if ipath_audio.exists():
continue
# extract audio
cmd = f'ffmpeg -y -i {str(ipath_video)} -vn -acodec pcm_s16le -ac 1 -ar 16000 {str(ipath_audio)}'
# print(f"RUN: {cmd}")
os.system(cmd)
# break
#break
@@ -0,0 +1,73 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing') # '../data/trinity/source'
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy")
if ipath_save_feat.exists() or not ipath_audio.exists():
continue
# load trim audio
fps = 25
data, sr = librosa.load(str(ipath_audio), sr=16000) # 16000 = fps * 640 让这个sr是fps的整数,
hop_len = int(sr / fps)
n_fft = int(sr * 0.13) # default 2048
# print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
# melspectrogram
mel = librosa.feature.melspectrogram(y=data, sr=sr,
n_fft=n_fft, # FFT窗口的长度
hop_length=hop_len, # 帧移
win_length=n_fft, # 窗口长度,默认=n_fft
window="hann", # 加hanming窗
n_mels=27, # 滤波器组
fmin=0.0, fmax=8000)
mel = np.log(mel+1).T
print(f"sr={sr}, data ={data.shape}, mel = {mel.shape}, frames = {(len(data) / sr) * fps}, (min,max)=({np.min(mel), np.max(mel)}")
# align to video
if mel.shape[0] < 75:
print(f"\n skip, mel shape ={mel.shape}, frames={(len(data) / sr) * fps}")
else:
mel_align = mel[:75, :]
# save
np.save(ipath_save_feat, mel_align)
@@ -0,0 +1,82 @@
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
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing') # '../data/trinity/source'
# STFT model
model = TacotronSTFT(filter_length=1024,
hop_length=256,
win_length=1024,
sampling_rate=22050,
mel_fmin=0.0, mel_fmax=8000)
# dataset load
v_ids = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
ipath_save = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy") # feat_mel_trim_split
if ipath_save.exists(): continue
if not ipath_audio.exists():
print(f"ERROR: NOT Exist {ipath_audio}")
continue
# load trim audio
audio, sr = librosa.load(str(ipath_audio), mono=True) # 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})")
audio[audio > 1.0] = 1.0
audio[audio < -1.0] = -1.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] / 75}")
# save
melspec = melspec.permute(1,0) # (nsplits, nsteps, 80)
np.save(ipath_save, melspec) # (nsplit, 173, 80)
print(f"melspec shape = {melspec.shape}, save to --> {ipath_save}")
# break
+68
View File
@@ -0,0 +1,68 @@
import cv2
import os, sys
import glob
import numpy as np
import time
import pdb
import argparse
from pathlib2 import Path
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path("/yrfs/lsen/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
# create data path
path_save_frames = ipath_video.parent.parent.joinpath("frames")
# if already exists frames
if path_save_frames.exists():
if len(list(path_save_frames.glob("*.jpg"))) > 10:
continue
path_save_frames.mkdir(parents=True, exist_ok=True)
#print("save frames dir = ", {path_save_frames})
# STEP1: extract frames
count = 0
cap = cv2.VideoCapture(str(ipath_video))
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while True:
success, image = cap.read()
if not success:
break
ipath_frame = path_save_frames.joinpath(f"frame-{count:04d}.jpg")
if not ipath_frame.exists():
cv2.imwrite(str(ipath_frame), image)
count += 1
if iv % 50 == 0:
print(f"--> Extract {iv}-th video, have {length} frames, {ipath_video}")
#print(f"extract and save the {count}/{length}-th frame --> {ipath_frame}")
#break
#break
+82
View File
@@ -0,0 +1,82 @@
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
def select_ldmk(ladmks):
ladmks = np.array(ladmks)
area = []
for i in range(ladmks.shape[0]):
lands = ladmks[i, ...]
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
area.append((xmax - xmin) * (ymax-ymin))
print("area = ", area, "select = ", np.argmax(area))
return ladmks[np.argmax(area), :, :]
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
model = FaceAlignment(LandmarksType._2D, flip_input=False, device="cuda:0")
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
#if id_name != "s29": continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_landmk.mkdir(parents=True, exist_ok=True)
# STEP1: get frames
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark: have {len(v_path_frames)} frames in {ipath_frames}")
# STEP2: extract landmarks
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
if not ipath_landmk_frame.exists():
# detect image
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
ldmk_pred = model.get_landmarks(np.array(image))
if ldmk_pred is None:
continue
# select the first one or the bigger one face
if len(ldmk_pred) > 1:
ldmk_pred = select_ldmk(ldmk_pred)
else:
ldmk_pred = ldmk_pred[0]
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
#break
#break
@@ -0,0 +1,93 @@
import os
import numpy as np
import librosa
import python_speech_features
from pathlib import Path
import multiprocessing
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
# def func_processing(path_audio):
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
# if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_audio = jpath_data.joinpath("audio/audio_extract.wav")
ipath_feat = jpath_data.joinpath("audio/mfcc_feat.npy")
ipath_feat_align = jpath_data.joinpath("audio/mfcc_feat_align.npy")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_feat_align.exists():
continue
# extarct mfcc feature
audio, sr = librosa.load(str(ipath_audio), sr=16000) # 16000, (69760, )
mfcc = python_speech_features.mfcc(audio, 16000, winstep=0.01) # seqlen1 x 13
np.save(ipath_feat, mfcc)
# splited by windows (to fit video frame with fps 25)
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
## seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
mfcc_align = splited_by_windows(mfcc, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
np.save(ipath_feat_align, mfcc_align)
if j % 50 == 0:
print(f"--> Extract {j}-th video landmark: audio shape={audio.shape}, mfcc shape={mfcc.shape}, mfcc_align = {mfcc_align.shape} duration={len(audio) / sr}")
# break
# break
Whitespace-only changes.
+98
View File
@@ -0,0 +1,98 @@
import os,sys
import cv2
import math
import numpy as np
from pathlib import Path
import torch
from PIL import Image
from reconstruction import Reconstruction
def get_rect(lands):
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
length = 1.2 * math.sqrt((xmax - xmin) * (xmax - xmin) + (ymax - ymin) * (ymax - ymin))
left = (xmax + xmin) / 2 - length / 2
top = (ymax + ymin) / 2 - length / 2
rect = np.array([left, top, length], dtype=np.float)
return rect
def show_landmarks(path_img, path_save, lands):
img = cv2.imread(str(path_img))
for i in range(68):
cv2.circle(img, (lands[i,0], lands[i,1]), 2, (255,0,0))
ipath_save = path_save.joinpath(path_img.stem + "_land.jpg")
cv2.imwrite(str(ipath_save), img)
if __name__ == "__main__":
# load Reconstruction
model = Reconstruction()
# load data
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
# print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark in {ipath_video}")
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_ladmks = ipath_data.joinpath("landmk")
ipath_coeffs = ipath_data.joinpath("coeff")
# STEP1: get frames and landmark
vpath_frames = sorted(ipath_frames.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
vpath_ladmks = list(ipath_ladmks.glob("*.txt"))
vpath_coeffs = list(ipath_coeffs.glob("*.txt"))
if len(vpath_frames) != len(vpath_ladmks) or len(vpath_frames) ==0: # if missing landmark data
continue
if ipath_coeffs.exists() and len(vpath_coeffs) == len(vpath_frames): # if have already reconstruction
continue
# STEP2: reconstruction
for ik, ipath_frame in enumerate(vpath_frames):
fid = int(ipath_frame.stem[-4:])
ipath_ladmk = ipath_ladmks.joinpath(f"frame-{fid:04d}.txt") # get landmark path
if not ipath_ladmk.exists():
continue
# read image and landmark
image = Image.open(str(ipath_frame)).convert('RGB') # (h, w, 3)
ladmk = np.loadtxt(ipath_ladmk, dtype=int) # (68, 2)
bbox = get_rect(ladmk)
# show_landmarks(image, path_save, ildmk)
# reconstruction
model.eval_rgb(image, ladmk, bbox, iname=ipath_ladmk.stem, path_save=ipath_ladmks.parent)
if ik % 100 == 99:
print(f"reconstruction {ik+1:04} ..., -> {ipath_ladmk}")
@@ -0,0 +1,98 @@
import os,sys
import numpy as np
import librosa
import python_speech_features
from pathlib import Path
import multiprocessing
path_work = "/mnt/data/CODE/Audio-driven-TalkingFace-HeadPose/audio-to-expression"
sys.path.insert(0, path_work)
from src.tools.audio import get_melspec
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
# def func_processing(path_audio):
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
# if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_audio = jpath_data.joinpath("audio/audio_extract.wav")
ipath_feat_save = jpath_data.joinpath("audio/melspec_feat.npy")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_feat_save.exists():
print(f"EXSTING, {ipath_feat_save}")
continue
# extarct mfcc feature
audio, sr = librosa.load(str(ipath_audio), sr=16000) #16000, (69760, )
mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
y, sr = librosa.load(str(ipath_audio), sr=44100)
melFrames = np.transpose(get_melspec(y, sr, wsize=0.04, hsize=0.04)) # (n_frame, 64)
melDelta = np.insert(np.diff(melFrames, n=1, axis=0), 0, np.zeros((1, 64)), axis=0) # (n_frame - 1 , 64) + (1, 64) --> (n_frame, 64)
melDDelta = np.insert(np.diff(melFrames, n=2, axis=0), 0, np.zeros((2, 64)), axis=0) # (n_frame - 2 , 64) + (2, 64) --> (n_frame, 64)
data_audio = np.concatenate((melDelta, melDDelta), axis=1) # (n_frame, 128)
# save
np.save(str(ipath_feat_save), data_audio)
# print(f"SAVE: mfcc size={data_audio.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
# break
# break
+69
View File
@@ -0,0 +1,69 @@
import os
import glob
import pdb
import numpy as np
from pathlib import Path
from scipy.io import loadmat,savemat
COMBINE_COEFF_RBGFACE = True
COMBINE_LAMDK_RBGFACE = False
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each person
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
# if (j+1) % 100 == 100: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
jpath_ladmk = jpath_data.joinpath("landmk")
jpath_ladmk_save = jpath_data.joinpath("video/landmark.npy")
jpath_ladmk_save.parent.mkdir(parents=True, exist_ok=True)
v_frames = sorted(jpath_frame.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
v_ladmks = sorted(jpath_ladmk.glob("*.txt"), key=lambda x: int(x.stem[-4:]))
# print(f"contain {len(v_frames)} frames in {str(jpath_data)} -> {v_frames[:5]}")
if len(v_ladmks) != len(v_frames):
print(f"\t ERROR && Continue: This video have missing landmark, {str(jpath_ladmk)}")
continue
elif jpath_ladmk_save.exists():
continue
else:
ladmk_all = np.zeros((len(v_frames), 68, 2), np.float32)
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_proj = jpath_ladmk.joinpath(f"frame-{fid:04d}.txt")
ladmk_all[k, :, :] = np.loadtxt(str(kpath_proj)) # (68, 2)
# save combine data
np.save(str(jpath_ladmk_save), ladmk_all)
# print(f"combine the coeff: {str(jpath_videos)} --> {str(jpath_ladmk_save)}")
# break
# break
View File
Whitespace-only changes.
+113
View File
@@ -0,0 +1,113 @@
"""
generated train annotation data
"""
import os
import pickle
import numpy as np
from pathlib import Path
from collections import OrderedDict
from common.landmark import landmark_normalize
pid_for_train = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
"s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20",
"s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30"]
pid_for_test = ["s31", "s32", "s33", "s34"]
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
path_anno = Path("data/GRID/anno_test_half.pickle")
annodb = OrderedDict()
# if not existing
vpath_ids = sorted(path_data.glob("*"))
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
# iter
for i, ipath_id in enumerate(vpath_ids):
pid = ipath_id.stem # person id
# select train pid
if pid not in pid_for_test:
continue
# video
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
# for each video
list_dict = []
for iv, ipath_video in enumerate(vpath_videos):
vid = ipath_video.parent.parent.stem # video id
if iv % 50 == 0:
print(f"--> processing the {iv}-th video --> {ipath_video}")
ipath_data = ipath_video.parent.parent
ipath_frame = ipath_data.joinpath("frames")
ipath_ladmk = ipath_data.joinpath("landmk")
# ipath_coeff = ipath_data.joinpath("coeff")
ipath_mfccs = ipath_data.joinpath("audio/mfcc_feat.npy")
# STEP1: check if missing data
vpath_frame = sorted(ipath_frame.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
# vpath_coeff = sorted(ipath_coeff.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
vpath_ladmk = sorted(ipath_ladmk.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
nframes = len(vpath_frame)
# assert
if (nframes < 25) or (nframes != len(vpath_ladmk)) : # or (nframes != len(vpath_coeff)):
print(f"DEBUG: nframes={nframes}, nladmk={len(vpath_ladmk)}, --> {ipath_video}") # ncoeff={len(vpath_coeff)}
continue
# load mfcc
list_mfcc = np.load(ipath_mfccs) # nframes x 28 x 12
# # load 3DMM & landmarks
# list_idn = np.zeros((nframes, 100), dtype=float) # coeff idn, nframes x 100
# list_exp = np.zeros((nframes, 79), dtype=float) # coeff exp, nframes x 79
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(vpath_frame):
fid = int(kpath_frame.stem[-4:]) # frame id
# # 3dmm
# kpath_3dmm = ipath_coeff.joinpath(f"frame-{fid:04d}.txt")
# coeff = np.loadtxt(kpath_3dmm, dtype=float) # 316: idn-100, exp-79, tex-100, euler-3, trans-3, illum-27, camr-4
# list_idn[k, :] = coeff[:100] # 100 identity coeff
# list_exp[k, :] = coeff[100:100+79] # 79 expression coeff
# ldmk
kpath_ldmk = ipath_ladmk.joinpath(f"frame-{fid:04d}.txt")
ldmk = np.loadtxt(kpath_ldmk) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
# STEP 3: concat data
list_dict.append({"pid": pid, "vid": vid,
"mfcc": list_mfcc,
# "exp": list_exp, "idn":list_idn,
"ldmk": v_ldmk, "ldmk_norm": v_ldmk_norm, "ldmk_auxs":v_ldmk_auxs
})
annodb[pid] = list_dict
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)} item anno, save to --> {path_anno}")
+117
View File
@@ -0,0 +1,117 @@
"""
generated train annotation data
"""
import os
import pickle
import numpy as np
from pathlib import Path
from collections import OrderedDict
from common.landmark import landmark_normalize
pid_for_train = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
"s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20",
"s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30"]
pid_for_test = ["s31", "s32", "s33", "s34"]
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/GRID/processing")
path_anno = Path("data/GRID/anno_train_full.pickle")
annodb = OrderedDict()
# if not existing
vpath_ids = sorted(path_data.glob("*"))
print(f"Have {len(vpath_ids)} person folders --> {vpath_ids[0]}")
# iter
n_videos = 0
for i, ipath_id in enumerate(vpath_ids):
pid = ipath_id.stem # person id
# select train pid
if pid not in pid_for_train:
continue
# video
vpath_videos = sorted(ipath_id.glob("*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, --> {vpath_videos[0]}")
# for each video
list_dict = []
for iv, ipath_video in enumerate(vpath_videos):
vid = ipath_video.parent.parent.stem # video id
if iv % 50 == 0:
print(f"--> processing the {iv}-th video --> {ipath_video}")
ipath_data = ipath_video.parent.parent
ipath_frame = ipath_data.joinpath("frames")
ipath_ladmk = ipath_data.joinpath("landmk")
# ipath_coeff = ipath_data.joinpath("coeff")
ipath_mfccs = ipath_data.joinpath("audio/mfcc_feat.npy")
# STEP1: check if missing data
vpath_frame = sorted(ipath_frame.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
# vpath_coeff = sorted(ipath_coeff.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
vpath_ladmk = sorted(ipath_ladmk.glob("*.txt"), key=lambda ipath: int(ipath.stem[-4:]))
nframes = len(vpath_frame)
# assert
if (nframes < 60) or (nframes != len(vpath_ladmk)) : # or (nframes != len(vpath_coeff)):
print(f"DEBUG: nframes={nframes}, nladmk={len(vpath_ladmk)}, --> {ipath_video}") # ncoeff={len(vpath_coeff)}
continue
# load mfcc
# list_mfcc = np.load(ipath_mfccs) # nframes x 28 x 12
# # load 3DMM & landmarks
# list_idn = np.zeros((nframes, 100), dtype=float) # coeff idn, nframes x 100
# list_exp = np.zeros((nframes, 79), dtype=float) # coeff exp, nframes x 79
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(vpath_frame):
fid = int(kpath_frame.stem[-4:]) # frame id
# # 3dmm
# kpath_3dmm = ipath_coeff.joinpath(f"frame-{fid:04d}.txt")
# coeff = np.loadtxt(kpath_3dmm, dtype=float) # 316: idn-100, exp-79, tex-100, euler-3, trans-3, illum-27, camr-4
# list_idn[k, :] = coeff[:100] # 100 identity coeff
# list_exp[k, :] = coeff[100:100+79] # 79 expression coeff
# ldmk
kpath_ldmk = ipath_ladmk.joinpath(f"frame-{fid:04d}.txt")
ldmk = np.loadtxt(kpath_ldmk) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
# STEP 3: concat data
list_dict.append({"pid": pid, "vid": vid,
# "mfcc": list_mfcc,
# "exp": list_exp, "idn":list_idn,
# "ldmk_norm": v_ldmk_norm, "ldmk_auxs":v_ldmk_auxs
"ldmk": v_ldmk,
})
n_videos += 1
# add to annodb
annodb[pid] = list_dict
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {n_video} video items, save to --> {path_anno}")
@@ -0,0 +1,82 @@
import os
import sys
import json
import numpy as np
from pathlib2 import Path
import sys
sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Expression")
from common.landmark import landmark_normalize
# from common.animation import save_animation, save_animation_with_gt
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing')
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
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 landmark
feat_ldmk = []
prev_ldmk = None
nContinue = 0
for j in range(75):
jpath_ldmk = ipath_ldmk.joinpath(f"frame-{j:04d}.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)
# save
feat_ldmk = np.array(feat_ldmk) # (N, 68, 2)
if nContinue <= 2 and feat_ldmk.shape[0] == 75:
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}")
+71
View File
@@ -0,0 +1,71 @@
import os
import sys
from pathlib2 import Path
import shutil
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing/s1')
v_dir_videos = sorted(path_data.glob("*/audio/feat_ldmk_trim_norm.npy"))
path_audio_wav = Path("data/paper_GRID_gt/audio_wav")
path_ldmk_25fps = Path("data/paper_GRID_gt/ldmk_25fps")
path_audio_feat = Path("data/paper_GRID_gt/feat_mel_no_align")
path_video_25fps = Path("data/paper_GRID_gt/video_25fps")
path_audio_wav.mkdir(parents=True, exist_ok=True)
path_ldmk_25fps.mkdir(parents=True, exist_ok=True)
path_video_25fps.mkdir(parents=True, exist_ok=True)
path_audio_feat.mkdir(parents=True, exist_ok=True)
ncount = 0
for i, ipath in enumerate(v_dir_videos):
ipath_data = ipath.parent.parent
print(f"ipath_data = {ipath_data}")
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
ipath_ldmks = ipath_data.joinpath("audio/feat_ldmk_trim_norm.npy")
ipath_video = ipath_data.joinpath("video/video_orignal.mp4")
ipath_audio_feat = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy")
# skip if not exsits
if not ipath_ldmks.exists(): continue
if not ipath_audio.exists(): continue
if not ipath_video.exists(): continue
# copy to
# ipath_audio_target = path_audio_wav.joinpath(f"clips_{ncount:03d}.wav")
# shutil.copy(src=str(ipath_audio), dst=str(ipath_audio_target))
# print(f"copy {ipath_audio} --> {ipath_audio_target}")
# ipath_ldmks_target = path_ldmk_25fps.joinpath(f"clips_{ncount:03d}.npy")
# shutil.copy(src=str(ipath_ldmks), dst=str(ipath_ldmks_target))
# print(f"copy {ipath_ldmks} --> {ipath_ldmks_target}")
# ipath_video_target = path_video_25fps.joinpath(f"clips_{ncount:03d}.mp4")
# shutil.copy(src=str(ipath_video), dst=str(ipath_video_target))
# print(f"copy {ipath_video} --> {ipath_video_target}")
ipath_audio_feat_tgt = path_audio_feat.joinpath(f"clips_{ncount:03d}.npy")
shutil.copy(src=str(ipath_audio_feat), dst=str(ipath_audio_feat_tgt))
print(f"copy {ipath_audio_feat} --> {ipath_audio_feat_tgt}")
ncount += 1
if ncount >= 100: break
+102
View File
@@ -0,0 +1,102 @@
import os
import cv2
from pathlib import Path
import shutil
# UNZIP_FILES = False
MV_VIDEO_FILES = False
# RESAMPLE_FPS = True
# RESAMPLE_RATE = False
if __name__ == '__main__':
path_root = Path("/mnt/data2/DATA/LRW/")
if MV_VIDEO_FILES:
path_data = path_root.joinpath("lipread_mp4")
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each word
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_root.joinpath("lipread_mp4", id_name)
v_dir_videos = sorted(dir_video.glob("**/*.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for ipath_videos in v_dir_videos:
ivideo_name = ipath_videos.stem
itrain_test = ipath_videos.parent.name
# copy video
ipath_video_target = path_root.joinpath("processing", id_name, itrain_test, ivideo_name, "video/video_orignal.mp4")
if not ipath_video_target.exists():
ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
#print(f"copy {ipath_videos} --> {ipath_video_target}")
# copy audio
ipath_audio_source = path_root.joinpath("lipread_wav", id_name, itrain_test, ivideo_name+".wav")
ipath_audio_target = path_root.joinpath("processing", id_name, itrain_test, ivideo_name, "audio/audio_orignal.wav")
if not ipath_audio_target.exists():
ipath_audio_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(src=str(ipath_audio_source), dst=str(ipath_audio_target))
#print(f"copy {ipath_audio_source} --> {ipath_audio_target}")
# if RESAMPLE_FPS:
# path_data = path_root.joinpath("processing")
# v_ids = sorted(path_data.glob("*"))
# print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# # for each word
# for i, ipath_id in enumerate(v_ids):
# id_name = ipath_id.stem
# dir_video = path_data.joinpath(id_name)
# v_dir_videos = sorted(dir_video.glob("**/*.mp4"))
# print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# # for each video
# for ipath_videos in v_dir_videos:
# ivideo_name = ipath_videos.stem
# itrain_test = ipath_videos.parent.name
# # copy video
# ipath_video_target = ipath_videos.parent.joinpath("video_25fps.mp4")
# cap = cv2.VideoCapture(str(ipath_videos))
# nframe = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# nfps = int(cap.get(cv2.CAP_PROP_FPS))
# w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# print(f"FPS = {nfps}, length = {nframe}, (w,h)=({w}, {h})")
# if not ipath_video_target.exists():
# #ipath_video_target.parent.mkdir(parents=True, exist_ok=True)
# #shutil.copy(src=str(ipath_videos), dst=str(ipath_video_target))
# pass
# #print(f"convert {ipath_videos} --> {ipath_video_target}")
+66
View File
@@ -0,0 +1,66 @@
import cv2
import os, sys
import glob
import numpy as np
import time
import pdb
import argparse
from pathlib2 import Path
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/processing")
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:10]}")
# for each word
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("**/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ivideo_name = ipath_video.stem
itrain_test = ipath_video.parent.name
# create data path
path_save_frames = ipath_video.parent.parent.joinpath("frames")
# if already exists frames
if path_save_frames.exists():
if len(list(path_save_frames.glob("*.jpg"))) > 20:
continue
path_save_frames.mkdir(parents=True, exist_ok=True)
#print("save frames dir = ", {path_save_frames})
# STEP1: extract frames
count = 0
cap = cv2.VideoCapture(str(ipath_video))
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while True:
success, image = cap.read()
if not success:
break
ipath_frame = path_save_frames.joinpath(f"frame-{count:04d}.jpg")
if not ipath_frame.exists():
cv2.imwrite(str(ipath_frame), image)
count += 1
if iv % 50 == 0:
print(f"--> Extract {iv}-th video, have {length} frames, {ipath_video}")
#print(f"extract and save the {count}/{length}-th frame --> {ipath_frame}")
#break
#break
+83
View File
@@ -0,0 +1,83 @@
import numpy as np
from PIL import Image
from pathlib2 import Path
from face_alignment import FaceAlignment, LandmarksType
def select_ldmk(ladmks):
ladmks = np.array(ladmks)
area = []
for i in range(ladmks.shape[0]):
lands = ladmks[i, ...]
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
area.append((xmax - xmin) * (ymax-ymin))
print("area = ", area, "select = ", np.argmax(area))
return ladmks[np.argmax(area), :, :]
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/processing")
model = FaceAlignment(LandmarksType._2D, flip_input=False)
v_ids = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each word
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
# if id_name not in ["ABUSE", "ACCESS", "ACCORDING", "ACCUSED", "ACROSS"]:
# continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("**/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
#print(f"ipath_data = {ipath_data}")
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_landmk.mkdir(parents=True, exist_ok=True)
# STEP1: get frames
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
if iv % 50 == 0:
print(f"--> Extract {iv}-th video landmark: have {len(v_path_frames)} frames in {ipath_frames}")
# STEP2: extract landmarks
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
if not ipath_landmk_frame.exists():
# detect image
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
ldmk_pred = model.get_landmarks(np.array(image))
if ldmk_pred is None:
continue
# select the first one or the bigger one face
if len(ldmk_pred) > 1:
ldmk_pred = select_ldmk(ldmk_pred)
else:
ldmk_pred = ldmk_pred[0]
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
# break
# break
+125
View File
@@ -0,0 +1,125 @@
import os
import glob
import pdb
import numpy as np
from pathlib import Path
from scipy.io import loadmat,savemat
COMBINE_COEFF_RBGFACE = True
COMBINE_LAMDK_RBGFACE = False
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/LRW/processing")
#num_train_file = 3000
#num_train_count = 0
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
if (j+1) % 100 == 100: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
#print(f"jpath_data = {jpath_data}")
jpath_frames = jpath_data.joinpath("frames")
v_frames = sorted(jpath_frames.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
#print(f"contain {len(v_frames)} frames in {str(jpath_data)}")
#
if COMBINE_COEFF_RBGFACE:
jpath_coeff = jpath_data.joinpath("rgbface/coeff")
jpath_coeff_save = jpath_data.joinpath("video/coeff_rgbface2.npy")
jpath_coeff_save.parent.mkdir(parents=True, exist_ok=True)
v_coeff = sorted(jpath_coeff.glob("*.txt"))
#print(f"contain {len(v_coeff)} reconstruction/tans in {str(jpath_data)}")
if len(v_coeff) != len(v_frames):
print(f"\t ERROR && Continue: This video missing coeff{len(v_coeff)}/{len(v_frames)}, {str(jpath_coeff)} ")
continue
# elif jpath_coeff_save.exists():
# continue
else:
coeff_all = np.zeros((len(v_frames), 61), np.float32) # 55 + 3 + 3
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_coeff = jpath_coeff.joinpath(f"frame-{fid:04d}.txt")
kk_coeff = np.loadtxt(str(kpath_coeff)).reshape(-1)
kk_coeff_expr = kk_coeff[100:155] # (55, ) , identity-100, expression-55 ==> (55, )
kk_coeff_rts = kk_coeff[155:161] # (6) , rotation-3, translation-3, scale-1 ==> (6, )
coeff_all[k, :] = np.r_[kk_coeff_expr, kk_coeff_rts] # (61, ) expression-55 + rotation-3 + trans-3
# save combine data
np.save(str(jpath_coeff_save), coeff_all)
#print(f"combine the coeff: {str(jpath_coeff)} --> {str(jpath_coeff_save)}")
# combine landmark of RGBFaceNet
if COMBINE_LAMDK_RBGFACE:
jpath_ladmk_proj = jpath_data.joinpath("rgbface/landmark_proj")
jpath_ladmk_crop = jpath_data.joinpath("rgbface/landmark_crop")
jpath_proj_save = jpath_data.joinpath("video/landmark_rgbface_proj.npy")
jpath_crop_save = jpath_data.joinpath("video/landmark_rgbface_crop.npy")
jpath_crop_save.parent.mkdir(parents=True, exist_ok=True)
v_ladmk_proj = sorted(jpath_ladmk_proj.glob("*.txt"))
v_ladmk_crop = sorted(jpath_ladmk_crop.glob("*.txt"))
#print(f"contain {len(v_ladmk_proj)} / {len(v_ladmk_crop)} landmark proj/crop in {str(jpath_data)}")
if len(v_ladmk_proj) != len(v_frames) or len(v_ladmk_crop) != len(v_frames):
print(f"\t ERROR && Continue: This video missing landmark, {str(jpath_ladmk_proj)} ")
continue
elif jpath_proj_save.exists() and jpath_crop_save.exists():
continue
else:
ladmk_proj_all = np.zeros((len(v_frames), 68, 2), np.float32)
ladmk_crop_all = np.zeros((len(v_frames), 68, 2), np.float32)
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_proj = jpath_ladmk_proj.joinpath(f"frame-{fid:04d}.txt")
kpath_crop = jpath_ladmk_crop.joinpath(f"frame-{fid:04d}.txt")
ladmk_proj_all[k, :, :] = np.loadtxt(str(kpath_proj)) # (68, 2)
ladmk_crop_all[k, :, :] = np.loadtxt(str(kpath_crop)) # (68, 2)
# save combine data
np.save(str(jpath_proj_save), ladmk_proj_all)
np.save(str(jpath_crop_save), ladmk_crop_all)
#print(f"combine the coeff: {str(jpath_ladmk_proj)} --> {str(jpath_proj_save)}")
#break
#break
# combine 3dmm
#
@@ -0,0 +1,77 @@
import os
import numpy as np
from pathlib import Path
from scipy.io import loadmat,savemat
COMBINE_COEFF_RBGFACE = True
COMBINE_LAMDK_RBGFACE = True
if __name__ == "__main__":
path_data = Path("/mnt/data/DATA/LRW/processing")
#num_train_file = 3000
#num_train_count = 0
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
jpath_data = jpath_videos.parent.parent
#print(f"jpath_data = {jpath_data}")
jpath_frames = jpath_data.joinpath("frames")
v_frames = sorted(jpath_frames.glob("*.jpg"), key=lambda x: int(x.stem[-4:]))
n_frames = len(v_frames)
#print(f"contain {len(v_frames)} frames in {str(jpath_data)}")
jpath_coeff = jpath_data.joinpath("reconstruction/coeff")
jpath_coeff_save = jpath_data.joinpath("video/coeff_reconstruction.npy")
jpath_coeff_save.parent.mkdir(parents=True, exist_ok=True)
n_coeff = len(list(jpath_coeff.glob("*.txt")))
#print(f"contain {len(v_coeff)} reconstruction/tans in {str(jpath_data)}")
if n_frames != n_coeff:
print(f"\t ERROR && Continue: This video missing coeff {n_coeff}/{n_frames}, {str(jpath_coeff)}")
continue
# elif jpath_coeff_save.exists():
# continue
else:
coeff_all = np.zeros((n_frames, 70), np.float32) # 80 identity + 64 expression + 80 texture + 3 rot + 27 light + 3 trans
for k, iframe in enumerate(v_frames):
fid = int(iframe.stem[-4:])
# load data
kpath_coeff = jpath_coeff.joinpath(f"frame-{fid:04d}.txt")
kk_coeff = np.loadtxt(str(kpath_coeff)).reshape(-1)
kk_coeff_exp = kk_coeff[ 80:144] # (64, ) , expression-64 ==> (55, )
kk_coeff_rot = kk_coeff[224:227] # (3, ), rotation-3,
kk_coeff_tra = kk_coeff[254:257] # (3, ), translation - 3
coeff_all[k, :] = np.r_[kk_coeff_exp, kk_coeff_rot, kk_coeff_tra] # (70, ) expression-55 + rotation-3 + trans-3
#print(f"coef shape={coeff_all.shape}, path = {kpath_coeff}")
# save combine data
np.save(str(jpath_coeff_save), coeff_all)
if j % 100 == 99:
print(f"processing {j+1}/{len(v_dir_videos)}, shape={coeff_all.shape} --> {str(jpath_coeff_save)}")
+85
View File
@@ -0,0 +1,85 @@
import os
import pickle
import numpy as np
from pathlib import Path
from collections import OrderedDict
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_anno = Path("data/LRW/anno_LRW_test_full.pickle")
annodb = OrderedDict()
nvideo = 0
# nvideo_target = 5000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
# if nvideo > nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("test/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files")
for iv, ipath_video in enumerate(vpath_videos):
# if nvideo > nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes > 20 and nframes== len(v_path_ladmks)):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
continue
if iv % 50 == 0:
print(f"--> picking the {iv}-th video landmark: vid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
dict_anno = {
"pid": pid,
"vid":vid,
# "ldmk": v_ldmk,
"ldmk_norm": v_ldmk_norm,
# "ldmk_auxs":v_ldmk_auxs
}
# count video numbers
nvideo += 1
annodb[vid] = dict_anno
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
+86
View File
@@ -0,0 +1,86 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_anno = Path("data/LRW/anno_train_full.pickle")
annodb = []
nvideo = 0
nvideo_target = 5000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
# if nvideo > nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
for iv, ipath_video in enumerate(vpath_videos):
# if nvideo > nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes > 20 and nframes== len(v_path_ladmks)):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
dict_anno = {
"pid": pid,
"vid":vid,
# "ldmk": v_ldmk,
"ldmk_norm": v_ldmk_norm,
# "ldmk_auxs":v_ldmk_auxs
}
# count video numbers
nvideo += 1
annodb.append(dict_anno)
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
+89
View File
@@ -0,0 +1,89 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_anno = Path("data/LRW/anno_valid_full.pickle")
annodb = []
nvideo = 0
nvideo_target = 50000000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
# if nvideo > nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("val/*/video/video_orignal.mp4"))
if len(vpath_videos) <= 0: continue
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
for iv, ipath_video in enumerate(vpath_videos):
# if nvideo > nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes > 20 and nframes== len(v_path_ladmks)):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
dict_anno = {
"pid": pid,
"vid":vid,
# "ldmk": v_ldmk,
"ldmk_norm": v_ldmk_norm,
# "ldmk_auxs":v_ldmk_auxs
}
# count video numbers
nvideo += 1
annodb.append(dict_anno)
# pickle and save
with open(str(path_anno), "wb") as f:
pickle.dump(annodb, f)
print(f"Total have {len(annodb)}/{nvideo} items anno, save to --> {path_anno}")
@@ -0,0 +1,95 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_save = Path('data/LRW') # processing
path_save.mkdir(parents=True, exist_ok=True)
nvideo = 0
nvideo_target = 1000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
motion_test = []
speech_test = []
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
if nvideo >= nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("test/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
if len(vpath_videos) <= 0: continue
for iv, ipath_video in enumerate(vpath_videos):
if nvideo >= nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_mfcc = ipath_data.joinpath("audio/feat_mfcc_align.npy")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
if not ipath_mfcc.exists(): continue
# load speech
mfcc = np.load(ipath_mfcc) # 29 x 27
nframes = len(v_path_frames)
if not (nframes == 29 and len(v_path_ladmks) ==29 and mfcc.shape[0] == 29):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks, {mfcc.shape[0]} mfcc")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
motion_test.append(v_ldmk_norm) # (29, 68, 2)
speech_test.append(mfcc) # (29, 27)
# count video numbers
nvideo += 1
motion_test = np.array(motion_test) # (N, 29, 68, 2)
speech_test = np.array(speech_test) # (N, 29, 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 train data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}")
@@ -0,0 +1,95 @@
import os
import pickle
import numpy as np
from pathlib import Path
import sys
sys.path.insert(0, "/mnt/data/CODE/FaceDisentangleNetwork")
from common.landmark import landmark_normalize
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
path_save = Path('data/LRW') # processing
path_save.mkdir(parents=True, exist_ok=True)
nvideo = 0
nvideo_target = 100000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
motion_train, motion_valid, motion_test = [], [], []
speech_train, speech_valid, speech_test = [], [], []
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
if nvideo >= nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
if len(vpath_videos) <= 0: continue
for iv, ipath_video in enumerate(vpath_videos):
if nvideo >= nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk = ipath_data.joinpath("landmk")
ipath_mfcc = ipath_data.joinpath("audio/feat_mfcc_align.npy")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks = sorted(ipath_landmk.glob("*.txt"))
if not ipath_mfcc.exists(): continue
# load speech
mfcc = np.load(ipath_mfcc) # 29 x 27
nframes = len(v_path_frames)
if not (nframes == 29 and len(v_path_ladmks) ==29 and mfcc.shape[0] == 29):
print(f"have {nframes} frames, and {len(v_path_ladmks)} landmarks, {mfcc.shape[0]} mfcc")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
v_ldmk = np.zeros((nframes, 68, 2), dtype=int)
v_ldmk_norm = np.zeros((nframes, 68, 2), dtype=float) # normalize
v_ldmk_auxs = np.zeros((nframes, 3), dtype=float) # [x_mean, y_mean, side]
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = ipath_landmk.joinpath(f"frame-{frame_id:04d}.txt")
ldmk = np.loadtxt(ipath_landmk_frame) # shape = (68, 2)
ldmk_norm, pos_mean, side = landmark_normalize(ldmk)
v_ldmk[k, :, :] = ldmk
v_ldmk_norm[k, :, :] = ldmk_norm
v_ldmk_auxs[k, :] = np.array([pos_mean[0], pos_mean[1], side])
motion_train.append(v_ldmk_norm) # (29, 68, 2)
speech_train.append(mfcc) # (29, 27)
# count video numbers
nvideo += 1
motion_train = np.array(motion_train) # (N, 29, 68, 2)
speech_train = np.array(speech_train) # (N, 29, 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}")
+101
View File
@@ -0,0 +1,101 @@
import os
import numpy as np
import librosa
import python_speech_features
from pathlib import Path
import multiprocessing
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
# def func_processing(path_audio):
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_audio = jpath_data.joinpath("audio/audio_orignal.wav")
ipath_feat_save = jpath_data.joinpath("audio/mfcc_feat.npy")
ipath_feat_orignal_save = jpath_data.joinpath("audio/mfcc_feat_orignal.npy")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_feat_orignal_save.exists():
print(f"EXSTING, {ipath_feat_orignal_save}")
continue
# extarct mfcc feature
audio, sr = librosa.load(str(ipath_audio), sr=16000) # (69760, )
mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
#duration = len(audio) / sr
#print(f"audio shape={audio.shape}, mfcc shape={mfcc_orig.shape}, duration={duration}")
# splited by windows (to fit video frame with fps 25)
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
# seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
mfcc = splited_by_windows(mfcc_orig, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
#print(f"MFCC input size (splited by windows) ={mfcc.shape}")
# save files
np.save(str(ipath_feat_orignal_save), mfcc_orig)
# np.save(str(ipath_feat_save), mfcc)
# print(f"SAVE: mfcc size={mfcc.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
# print(f"SAVE: mfcc size={mfcc_orig.shape} --> {str(ipath_feat_orignal_save)}") # mfcc size=(31, 28, 12)
#break
#break
+113
View File
@@ -0,0 +1,113 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip
if __name__ == "__main__":
path_data = Path("/mnt/data2/DATA/LRW/processing")
# for each word
v_ids = sorted(path_data.glob("*"))
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:3]}")
# for each video
for j, jpath_videos in enumerate(v_dir_videos):
if (j+1) % 100 == 0: print(f"processing {j+1}/{len(v_dir_videos)}")
jpath_data = jpath_videos.parent.parent
jpath_frame = jpath_data.joinpath("frames")
nframes = len(sorted(jpath_frame.glob("*.jpg")))
#print(f"jpath_data = {jpath_data}, nframe = {nframes}")
ipath_video = jpath_data.joinpath("video/video_orignal.mp4")
ipath_audio = jpath_data.joinpath("audio/audio_orignal.wav")
ipath_save_feat = jpath_data.joinpath("audio/feat_mfcc_align.npy")
video = VideoFileClip(str(ipath_video))
# print(f"\nvideo duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
audio = AudioFileClip(str(ipath_audio))
# print(f"audio duration = {audio.duration}, fps = {audio.fps}, (start, end)=({audio.start},{audio.end}), nframes={int(audio.duration * audio.fps)}")
# for some data not have .wav files
if not ipath_audio.exists():
print(f"NOT EXISTING: {ipath_audio}")
continue
if ipath_save_feat.exists():
print(f"EXSTING, {ipath_save_feat}")
continue
fps = video.fps
data, sr = librosa.load(str(ipath_audio), sr=16000) # 16000 = fps * 550 让这个sr是fps的整数,
hop_len = int(sr / fps) # 640
n_fft = int(sr * 0.1) # 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)}")
mfcc = librosa.feature.mfcc(y=data, sr=sr,
n_fft=n_fft, # FFT窗口的长度
hop_length=hop_len, # 帧移
win_length=n_fft, # 窗口长度,默认=n_fft
window="hann", # 加hanming窗
n_mfcc=27,
fmin=0.0, fmax=8000)
# mfcc = np.log(mfcc+1).T
mfcc = mfcc.T
# print(f"sr={sr}, data ={data.shape}, mfcc = {mfcc.shape}, (min,max)=({np.min(mfcc), np.max(mfcc)}")
if mfcc.shape[0] < nframes:
print(f"\nERROR:")
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
print(f"audio duration = {audio.duration}, fps = {audio.fps}, (start, end)=({audio.start},{audio.end}), nframes={int(audio.duration * audio.fps)}")
print(f"sr={sr}, data ={data.shape}, mfcc = {mfcc.shape}, (min,max)=({np.min(mfcc), np.max(mfcc)}")
print(f"mfcc length(={mfcc.shape[0]}) can not < nframe {nframes} ")
continue
else:
# save
mfcc_align = mfcc[:nframes, :]
np.save(str(ipath_save_feat), mfcc_align)
# # extarct mfcc feature
# audio, sr = librosa.load(str(ipath_audio), sr=16000) # (69760, )
# mfcc_orig = python_speech_features.mfcc(audio, 16000, winstep=0.01)
# #duration = len(audio) / sr
# #print(f"audio shape={audio.shape}, mfcc shape={mfcc_orig.shape}, duration={duration}")
# # splited by windows (to fit video frame with fps 25)
# wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
# wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
# # seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
# mfcc = splited_by_windows(mfcc_orig, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
# #print(f"MFCC input size (splited by windows) ={mfcc.shape}")
# save files
# np.save(str(ipath_feat_orignal_save), mfcc_orig)
# np.save(str(ipath_feat_save), mfcc)
# print(f"SAVE: mfcc size={mfcc.shape} --> {str(ipath_feat_save)}") # mfcc size=(31, 28, 12)
# print(f"SAVE: mfcc size={mfcc_orig.shape} --> {str(ipath_feat_orignal_save)}") # mfcc size=(31, 28, 12)
#break
#break
+86
View File
@@ -0,0 +1,86 @@
import os
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/LRW/processing")
path_save = Path('data/LRW') # processing
path_save.mkdir(parents=True, exist_ok=True)
nvideo = 0
nvideo_target = 100000
# if not existing
vpath_words = sorted(path_data.glob("*"))
print(f"Have {len(vpath_words)} words folders, {vpath_words[0]}")
for i, ipath_wd in enumerate(vpath_words):
pid = ipath_wd.stem
if nvideo >= nvideo_target: break
# video
vpath_videos = sorted(ipath_wd.glob("train/*/video/video_orignal.mp4"))
print(f"\nid= {pid}, Have {len(vpath_videos)} video files, \n {vpath_videos[0]}")
if len(vpath_videos) <= 0: continue
for iv, ipath_video in enumerate(vpath_videos):
if nvideo >= nvideo_target: break
ipath_data = ipath_video.parent.parent
vid = ipath_data.stem
ipath_frames = ipath_data.joinpath("frames")
ipath_landmk_dlib = ipath_data.joinpath("landmk")
ipath_landmk_pfld = ipath_data.joinpath("landmk-PFLD")
v_path_frames = sorted(ipath_frames.glob("*.jpg"))
v_path_ladmks_dlib = sorted(ipath_landmk_dlib.glob("*.txt"))
v_path_ladmks_pfld = sorted(ipath_landmk_pfld.glob("*.txt"))
nframes = len(v_path_frames)
if not (nframes == 29 and len(v_path_ladmks_dlib) ==29 and len(v_path_ladmks_pfld) ==29):
print(f"have {nframes} frames, and {len(v_path_ladmks_dlib)} / {len(v_path_ladmks_pfld)} landmarks, ")
continue
if iv % 50 == 0:
print(f"--> pickling the {iv}-th video landmark: pid({vid}) have {len(v_path_frames)} frames in {ipath_frames}")
# frames --> read landmarks
vldmk_dlib = np.zeros((1, nframes, 68, 2), dtype=float)
vldmk_pfld = np.zeros((1, nframes, 68, 2), dtype=float)
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
kpath_landmk_dlib = ipath_landmk_dlib.joinpath(f"frame-{frame_id:04d}.txt")
kpath_landmk_pfld = ipath_landmk_pfld.joinpath(f"frame-{frame_id:04d}.txt")
ldmk_dlib = np.loadtxt(kpath_landmk_dlib) # shape = (68, 2)
ldmk_dlib, _, _ = landmark_normalize(ldmk_dlib)
vldmk_dlib[0, k, :, :] = ldmk_dlib
ldmk_pfld = np.loadtxt(kpath_landmk_pfld) # shape = (68, 2)
ldmk_pfld, _, _ = landmark_normalize(ldmk_pfld)
vldmk_pfld[0, k, :, :] = ldmk_pfld
# 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)
+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}")
+87
View File
@@ -0,0 +1,87 @@
import moviepy
import numpy as np
from pathlib import Path
from moviepy.editor import *
STEP_VIDEO = False
STEP_CONCATE = True
if __name__ == "__main__":
video_name = "test_video"
path_root = Path("/mnt/data/CODE/Audio2Expression")
#path_data = path_root.joinpath(f"data/processing/{video_name}")
path_data = path_root.joinpath(f"data/processing/{video_name}/result-weight-3000")
# # to video
# if STEP_VIDEO:
# path_image = path_data.joinpath("frames_crop")
# path_image_save = path_data.joinpath("images.mp4")
# clip_image = ImageSequenceClip(path_image, fps=25, load_images=True)
# clip_image.write_videofile(str(path_image_save), fps=25)
# path_frame = path_data.joinpath("render")
# path_frame_save = path_data.joinpath("render.mp4")
# clip_render = ImageSequenceClip(path_frame, fps=25, load_images=True)
# clip_render.write_videofile(str(path_frame_save), fps=25)
# path_frame = path_data.joinpath("render_pt")
# path_frame_save = path_data.joinpath("render_pt.mp4")
# clip_render_pt = ImageSequenceClip(path_frame, fps=25, load_images=True)
# clip_render_pt.write_videofile(str(path_frame_save), fps=25)
# path_frame = path_data.joinpath("render_pt_fix_idn")
# path_frame_save = path_data.joinpath("render_pt_fix_idn.mp4")
# clip_render_pt2 = ImageSequenceClip(path_frame, fps=25, load_images=True)
# clip_render_pt2.write_videofile(str(path_frame_save), fps=25)
# concate
if STEP_CONCATE:
# image
clip_image = VideoFileClip(str(path_data.joinpath("images.mp4"))).margin(10)
clip_text = TextClip("Crop Image", fontsize = 14, color = 'white', stroke_width=3)
clip_text = clip_text.set_pos((0.4, 0.9), relative=True).set_duration(clip_image.duration)
clip_image = CompositeVideoClip([clip_image, clip_text])
# render
clip_render = VideoFileClip(str(path_data.joinpath("render.mp4"))).margin(10)
clip_text = TextClip("Render GT", fontsize = 14, color = 'white', stroke_width=3)
clip_text = clip_text.set_pos((0.4,0.9), relative=True).set_duration(clip_render.duration)
clip_render = CompositeVideoClip([clip_render, clip_text])
# render with specific identiy
clip_render2 = VideoFileClip(str(path_data.joinpath("render_pt.mp4"))).margin(10)
clip_text = TextClip("Render PT fix identity", fontsize = 14, color = 'white', stroke_width=3)
clip_text = clip_text.set_pos((0.2,0.9), relative=True).set_duration(clip_render2.duration)
clip_render2 = CompositeVideoClip([clip_render2, clip_text])
# # render with specific identiy
# clip_render3 = VideoFileClip(str(path_data.joinpath("render_pt_fix_idn.mp4"))).margin(10)
# # clip_text = TextClip("Render PT with fixed identity", fontsize = 14, color = 'red')
# # clip_text = clip_text.set_pos("center", "top").set_duration(clip_render3.duration)
# # clip_render3 = CompositeVideoClip([clip_render3, clip_text])
# audio
path_audio = path_data.joinpath("../audio/test_video.wav")
clip_audio = AudioFileClip(str(path_audio))
# concate
# concate_clips = clips_array([[clip_image, clip_render],
# [clip_render2, clip_render3]])
concate_clips = clips_array([[clip_image, clip_render, clip_render2]])
concate_clips = concate_clips.set_audio(clip_audio)
# save
path_concate_save = path_data.joinpath("concate4.mp4")
#concate_clips = concate_clips.resize(width=720)
concate_clips.write_videofile(str(path_concate_save), fps=25)
+194
View File
@@ -0,0 +1,194 @@
import cv2
import math
import numpy as np
from pathlib import Path
from PIL import Image
import librosa
import python_speech_features
from reconstruction import Reconstruction
from face_alignment import FaceAlignment, LandmarksType
STEP_EXTRACT_FRAMES = False
STEP_EXTRACT_LANDMK = False
STEP_EXTRACT_MFCC = True
STEP_EXTRACT_3DMM = True
def select_ldmk(ladmks):
ladmks = np.array(ladmks)
area = []
for i in range(ladmks.shape[0]):
lands = ladmks[i, ...]
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
area.append((xmax - xmin) * (ymax-ymin))
print("area = ", area, "select = ", np.argmax(area))
return ladmks[np.argmax(area), :, :]
def splited_by_windows(data, wind_stride, wind_length, padding=True):
"""
data: seq_len1 x dim1
return: seq_len2 x wind_length x dim1
where seq_len2 = (L + 2p - k) // wind_stride + 1
"""
seq_len1, dim1 = data.shape
seq_len2 = seq_len1 // wind_stride + 1
#print("DATA befor shape=", data.shape) # DATA befor shape= (121, 13)
data = np.pad(data, pad_width=((wind_length//2,wind_length//2), (0,0)), mode="reflect")
#print("DATA after shape=", data.shape) # DATA after shape= (149, 13)
data_output = np.zeros((seq_len2, wind_length, dim1-1), dtype=float)
for i in range(seq_len2):
ibeg = i * wind_stride
iend = i * wind_stride + wind_length
data_output[i, :, :] = data[ibeg : iend, 1:] # TODO: why form 1:
return data_output
def get_rect(lands):
xmin, xmax = np.min(lands[:, 0]), np.max(lands[:, 0])
ymin, ymax = np.min(lands[:, 1]), np.max(lands[:, 1])
length = 1.2 * math.sqrt((xmax - xmin) * (xmax - xmin) + (ymax - ymin) * (ymax - ymin))
left = (xmax + xmin) / 2 - length / 2
top = (ymax + ymin) / 2 - length / 2
rect = np.array([left, top, length], dtype=np.float)
return rect
if __name__ == "__main__":
path_root = Path("/mnt/data/CODE/Audio2Expression")
path_data = path_root.joinpath("data")
path_audio = path_data.joinpath('input/test_video.wav') # 03Fsi1201.wav,5_00006,03Fsi1201
path_video = path_data.joinpath('input/test_video.mp4') # 31.mp4 ken
video_name = path_video.stem
audio_name = path_audio.stem
path_save = path_data.joinpath(f"processing/{video_name}")
path_save.mkdir(parents=True, exist_ok=True)
# ======================================
# STEP 1: extract frames
# ======================================
path_frames = path_save.joinpath("frames")
path_frames.mkdir(parents=True, exist_ok=True)
if STEP_EXTRACT_FRAMES:
print("STEP 1: extract frames...")
count = 0
cap = cv2.VideoCapture(str(path_video))
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while True:
success, image = cap.read()
if not success:
break
ipath_frame = path_frames.joinpath(f"frame-{count:04d}.jpg")
cv2.imwrite(str(ipath_frame), image)
count += 1
print(f"--> Extract video, have {length}/{count} frames, {path_video}")
# ======================================
# STEP 2: extract landmark
# ======================================
path_landmk = path_save.joinpath("landmk")
path_landmk.mkdir(parents=True, exist_ok=True)
if STEP_EXTRACT_LANDMK:
print("STEP 2: extract landmark...")
model = FaceAlignment(LandmarksType._2D, flip_input=False, device="cuda:0")
v_path_frames = sorted(path_frames.glob("*.jpg"))
for k, kpath_frame in enumerate(v_path_frames):
frame_id = int(kpath_frame.stem[-4:])
ipath_landmk_frame = path_landmk.joinpath(f"frame-{frame_id:04d}.txt")
if not ipath_landmk_frame.exists():
# detect image
image = Image.open(str(kpath_frame)).convert('RGB') # (h, w, 3)
ldmk_pred = model.get_landmarks(np.array(image))
if ldmk_pred is None:
continue
# select the first one or the bigger one face
if len(ldmk_pred) > 1:
ldmk_pred = select_ldmk(ldmk_pred)
else:
ldmk_pred = ldmk_pred[0]
np.savetxt(str(ipath_landmk_frame), ldmk_pred, fmt=" %3d")
# ======================================
# STEP 3: extract mfcc
# ======================================
if STEP_EXTRACT_MFCC:
print("STEP 3: extract mfcc...")
path_save_audio = path_save.joinpath("audio")
path_save_audio.mkdir(parents=True, exist_ok=True)
path_feat = path_save_audio.joinpath("mfcc_feat.npy")
path_feat_align = path_save_audio.joinpath("mfcc_feat_align.npy")
# extarct mfcc feature
audio, sr = librosa.load(str(path_audio), sr=16000) # 16000, (69760, )
mfcc = python_speech_features.mfcc(audio, 16000, winstep=0.01) # seqlen1 x 13
np.save(path_feat, mfcc)
# splited by windows (to fit video frame with fps 25)
wind_stride = 4 # 4 x 10ms = 40 ms, video(25fps) frame = 1/25s = 40ms
wind_length = 28 # 28 x 10ms = 280 ms, = 7 frames * 40 ms
## seq_len2 = (seq_len1 + 2*pad - wind_length) // wind_stride + 1
mfcc_align = splited_by_windows(mfcc, wind_stride, wind_length, padding=True) # seq_len2 x 28 x 12,
np.save(path_feat_align, mfcc_align)
print(f"audio shape={audio.shape}, mfcc shape={mfcc.shape}, mfcc_align = {mfcc_align.shape} duration={len(audio) / sr}")
# ======================================
# STEP 4: extract 3dmm
# ======================================
path_coeffs = path_save.joinpath("coeff")
path_coeffs.mkdir(parents=True, exist_ok=True)
if STEP_EXTRACT_3DMM:
print("STEP 4: extract 3dmm...")
model = Reconstruction()
vpath_frames = sorted(path_frames.glob("*.jpg"), key=lambda ipath: int(ipath.stem[-4:]))
for ik, ipath_frame in enumerate(vpath_frames):
fid = int(ipath_frame.stem[-4:])
ipath_ladmk = path_landmk.joinpath(f"frame-{fid:04d}.txt") # get landmark path
if not ipath_ladmk.exists():
continue
# read image and landmark
image = Image.open(str(ipath_frame)).convert('RGB') # (h, w, 3)
ladmk = np.loadtxt(ipath_ladmk, dtype=int) # (68, 2)
bbox = get_rect(ladmk)
# reconstruction
model.eval_rgb(image, ladmk, bbox, iname=ipath_ladmk.stem, path_save=path_save)
if ik % 100 == 99:
print(f"reconstruction {ik+1:04} ..., -> {ipath_ladmk}")
+45
View File
@@ -0,0 +1,45 @@
import os
import numpy as np
import moviepy.editor as mpy
from pathlib import Path
if __name__ == "__main__":
path_TalkingGlow1 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100/video_25fps')
path_TalkingGlow2 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100-1/video_25fps')
path_TalkingGlow3 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100-2/video_25fps')
path_TalkingGlow4 = Path('/mnt/data/CODE/Audio2Expression/data/paper/20210918-22H20M48S-epoch100-3/video_25fps')
path_audio = Path('/mnt/data/CODE/Audio2Expression/data/paper_gt/audio_wav')
path_save = Path('/mnt/data/CODE/Audio2Expression/data/paper/stack_video_diverse')
path_save.mkdir(parents=True, exist_ok=True)
for i in range(43):
clip_A = mpy.VideoFileClip(str(path_TalkingGlow1.joinpath(f"clips_{i:03d}.mp4")))
clip_B = mpy.VideoFileClip(str(path_TalkingGlow2.joinpath(f"clips_{i:03d}.mp4")))
clip_C = mpy.VideoFileClip(str(path_TalkingGlow3.joinpath(f"clips_{i:03d}.mp4")))
clip_D = mpy.VideoFileClip(str(path_TalkingGlow4.joinpath(f"clips_{i:03d}.mp4")))
audio = mpy.AudioFileClip(str(path_audio.joinpath(f"clips_{i:03d}.wav")))
# align to clipGT
duration = clip_A.duration
clip_B = clip_B.set_duration(duration)
clip_C = clip_C.set_duration(duration)
clip_D = clip_D.set_duration(duration)
audio = audio.set_duration(duration)
# stack
video = mpy.clips_array([[clip_A, clip_B, clip_C, clip_D]])
video = video.set_audio(audio) # audd audio
# save
ipath_save = path_save.joinpath(f"clips_{i:03d}.mp4")
video.write_videofile(str(ipath_save), fps=25, logger=None)