Files
audio2motion/src/datasets/motion_live.py
T
2022-08-11 15:50:30 +08:00

176 lines
7.2 KiB
Python

import imp
import numpy as np
import time
import random
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
# common
from common.resampling import resample_by_nsteps
from audiomentations import Compose, AddGaussianNoise, TimeStretch, PitchShift, Shift
class MotionLiveDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
"""
phase = "train | valid | test "
"""
super(MotionLiveDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
assert phase == "train"
print(f"[{self.phase}] load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
self.audio_augment = Compose([
AddGaussianNoise(min_amplitude=0.001, max_amplitude=0.015, p=0.2),
PitchShift(min_semitones=-4, max_semitones=4, p=0.2),
])
def __len__(self):
return self.opt.DATASET.num_train_items # 20000
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
if self.phase == "train" and self.opt.DATASET.shifting_speed and random.random() < 0.3:
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
beg_frame = np.random.randint(nframe - int(self.nsteps_frame * speed) - 10) + 5 # select from (5:-5)
end_frame = beg_frame + int(self.nsteps_frame * speed)
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + int(self.nsteps_segmt * speed)
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, int(self.nsteps_segmt * speed) = {int(self.nsteps_segmt * speed)}, vid={vid}"
assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}"
# print(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}")
# resample to same nsteps
data_motion = resample_by_nsteps(data_motion, nsteps_tgt=self.nsteps_frame)
data_speech = resample_by_nsteps(data_speech, nsteps_tgt=self.nsteps_segmt)
# print(f"resampling > data_speech shape={data_speech.shape} data_motion shape={data_motion.shape} \n")
else:
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
# audio augment
data_speech = self.audio_augment(samples=data_speech, sample_rate=self.sr )
# print(f"after augment data speech = {data_speech.shape}, before nsegmt = {nsegmt}, nframe={nframe}")
# assert data_speech.shape[0] == (end_segmt-beg_segmt), f"after augment data speech {data_speech.shape} should = {end_segmt-beg_segmt}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: reverse
if self.phase == "train" and self.opt.DATASET.flip:
data_motion, data_speech = self.make_auguments_flip(data_motion, data_speech, p=0.3)
# print(f"flip: data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# random augments: shuffle speed
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def make_auguments_flip(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1].copy()
data_speech = data_speech[::-1].copy()
return data_motion, data_speech
def make_auguments_speed(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() > p:
return data_motion, data_speech
nsteps_motion = data_motion.shape[0]
nsteps_speech = data_speech.shape[0]
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
if speed < 0:
data_motion = data_motion[:nsteps_motion*speed]
data_speech = data_speech[:nsteps_speech*speed]
return data_motion, data_speech