Spaces:
Build error
Build error
File size: 15,327 Bytes
865fd8a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
import pickle
import sys
import os
sys.path.append(os.getcwd())
import json
from glob import glob
from data_utils.utils import *
import torch.utils.data as data
from data_utils.consts import speaker_id
from data_utils.lower_body import count_part
import random
from data_utils.rotation_conversion import axis_angle_to_matrix, matrix_to_rotation_6d
with open('data_utils/hand_component.json') as file_obj:
comp = json.load(file_obj)
left_hand_c = np.asarray(comp['left'])
right_hand_c = np.asarray(comp['right'])
def to3d(data):
left_hand_pose = np.einsum('bi,ij->bj', data[:, 75:87], left_hand_c[:12, :])
right_hand_pose = np.einsum('bi,ij->bj', data[:, 87:99], right_hand_c[:12, :])
data = np.concatenate((data[:, :75], left_hand_pose, right_hand_pose), axis=-1)
return data
class SmplxDataset():
'''
creat a dataset for every segment and concat.
'''
def __init__(self,
data_root,
speaker,
motion_fn,
audio_fn,
audio_sr,
fps,
feat_method='mel_spec',
audio_feat_dim=64,
audio_feat_win_size=None,
train=True,
load_all=False,
split_trans_zero=False,
limbscaling=False,
num_frames=25,
num_pre_frames=25,
num_generate_length=25,
context_info=False,
convert_to_6d=False,
expression=False,
config=None,
am=None,
am_sr=None,
whole_video=False
):
self.data_root = data_root
self.speaker = speaker
self.feat_method = feat_method
self.audio_fn = audio_fn
self.audio_sr = audio_sr
self.fps = fps
self.audio_feat_dim = audio_feat_dim
self.audio_feat_win_size = audio_feat_win_size
self.context_info = context_info # for aud feat
self.convert_to_6d = convert_to_6d
self.expression = expression
self.train = train
self.load_all = load_all
self.split_trans_zero = split_trans_zero
self.limbscaling = limbscaling
self.num_frames = num_frames
self.num_pre_frames = num_pre_frames
self.num_generate_length = num_generate_length
# print('num_generate_length ', self.num_generate_length)
self.config = config
self.am_sr = am_sr
self.whole_video = whole_video
load_mode = self.config.dataset_load_mode
if load_mode == 'pickle':
raise NotImplementedError
elif load_mode == 'csv':
import pickle
with open(data_root, 'rb') as f:
u = pickle._Unpickler(f)
data = u.load()
self.data = data[0]
if self.load_all:
self._load_npz_all()
elif load_mode == 'json':
self.annotations = glob(data_root + '/*pkl')
if len(self.annotations) == 0:
raise FileNotFoundError(data_root + ' are empty')
self.annotations = sorted(self.annotations)
self.img_name_list = self.annotations
if self.load_all:
self._load_them_all(am, am_sr, motion_fn)
def _load_npz_all(self):
self.loaded_data = {}
self.complete_data = []
data = self.data
shape = data['body_pose_axis'].shape[0]
self.betas = data['betas']
self.img_name_list = []
for index in range(shape):
img_name = f'{index:6d}'
self.img_name_list.append(img_name)
jaw_pose = data['jaw_pose'][index]
leye_pose = data['leye_pose'][index]
reye_pose = data['reye_pose'][index]
global_orient = data['global_orient'][index]
body_pose = data['body_pose_axis'][index]
left_hand_pose = data['left_hand_pose'][index]
right_hand_pose = data['right_hand_pose'][index]
full_body = np.concatenate(
(jaw_pose, leye_pose, reye_pose, global_orient, body_pose, left_hand_pose, right_hand_pose))
assert full_body.shape[0] == 99
if self.convert_to_6d:
full_body = to3d(full_body)
full_body = torch.from_numpy(full_body)
full_body = matrix_to_rotation_6d(axis_angle_to_matrix(full_body))
full_body = np.asarray(full_body)
if self.expression:
expression = data['expression'][index]
full_body = np.concatenate((full_body, expression))
# full_body = np.concatenate((full_body, non_zero))
else:
full_body = to3d(full_body)
if self.expression:
expression = data['expression'][index]
full_body = np.concatenate((full_body, expression))
self.loaded_data[img_name] = full_body.reshape(-1)
self.complete_data.append(full_body.reshape(-1))
self.complete_data = np.array(self.complete_data)
if self.audio_feat_win_size is not None:
self.audio_feat = get_mfcc_old(self.audio_fn).transpose(1, 0)
# print(self.audio_feat.shape)
else:
if self.feat_method == 'mel_spec':
self.audio_feat = get_melspec(self.audio_fn, fps=self.fps, sr=self.audio_sr, n_mels=self.audio_feat_dim)
elif self.feat_method == 'mfcc':
self.audio_feat = get_mfcc(self.audio_fn,
smlpx=True,
sr=self.audio_sr,
n_mfcc=self.audio_feat_dim,
win_size=self.audio_feat_win_size
)
def _load_them_all(self, am, am_sr, motion_fn):
self.loaded_data = {}
self.complete_data = []
f = open(motion_fn, 'rb+')
data = pickle.load(f)
self.betas = np.array(data['betas'])
jaw_pose = np.array(data['jaw_pose'])
leye_pose = np.array(data['leye_pose'])
reye_pose = np.array(data['reye_pose'])
global_orient = np.array(data['global_orient']).squeeze()
body_pose = np.array(data['body_pose_axis'])
left_hand_pose = np.array(data['left_hand_pose'])
right_hand_pose = np.array(data['right_hand_pose'])
full_body = np.concatenate(
(jaw_pose, leye_pose, reye_pose, global_orient, body_pose, left_hand_pose, right_hand_pose), axis=1)
assert full_body.shape[1] == 99
if self.convert_to_6d:
full_body = to3d(full_body)
full_body = torch.from_numpy(full_body)
full_body = matrix_to_rotation_6d(axis_angle_to_matrix(full_body.reshape(-1, 55, 3))).reshape(-1, 330)
full_body = np.asarray(full_body)
if self.expression:
expression = np.array(data['expression'])
full_body = np.concatenate((full_body, expression), axis=1)
else:
full_body = to3d(full_body)
expression = np.array(data['expression'])
full_body = np.concatenate((full_body, expression), axis=1)
self.complete_data = full_body
self.complete_data = np.array(self.complete_data)
if self.audio_feat_win_size is not None:
self.audio_feat = get_mfcc_old(self.audio_fn).transpose(1, 0)
else:
# if self.feat_method == 'mel_spec':
# self.audio_feat = get_melspec(self.audio_fn, fps=self.fps, sr=self.audio_sr, n_mels=self.audio_feat_dim)
# elif self.feat_method == 'mfcc':
self.audio_feat = get_mfcc_ta(self.audio_fn,
smlpx=True,
fps=30,
sr=self.audio_sr,
n_mfcc=self.audio_feat_dim,
win_size=self.audio_feat_win_size,
type=self.feat_method,
am=am,
am_sr=am_sr,
encoder_choice=self.config.Model.encoder_choice,
)
# with open(audio_file, 'w', encoding='utf-8') as file:
# file.write(json.dumps(self.audio_feat.__array__().tolist(), indent=0, ensure_ascii=False))
def get_dataset(self, normalization=False, normalize_stats=None, split='train'):
class __Worker__(data.Dataset):
def __init__(child, index_list, normalization, normalize_stats, split='train') -> None:
super().__init__()
child.index_list = index_list
child.normalization = normalization
child.normalize_stats = normalize_stats
child.split = split
def __getitem__(child, index):
num_generate_length = self.num_generate_length
num_pre_frames = self.num_pre_frames
seq_len = num_generate_length + num_pre_frames
# print(num_generate_length)
index = child.index_list[index]
index_new = index + random.randrange(0, 5, 3)
if index_new + seq_len > self.complete_data.shape[0]:
index_new = index
index = index_new
if child.split in ['val', 'pre', 'test'] or self.whole_video:
index = 0
seq_len = self.complete_data.shape[0]
seq_data = []
assert index + seq_len <= self.complete_data.shape[0]
# print(seq_len)
seq_data = self.complete_data[index:(index + seq_len), :]
seq_data = np.array(seq_data)
'''
audio feature,
'''
if not self.context_info:
if not self.whole_video:
audio_feat = self.audio_feat[index:index + seq_len, ...]
if audio_feat.shape[0] < seq_len:
audio_feat = np.pad(audio_feat, [[0, seq_len - audio_feat.shape[0]], [0, 0]],
mode='reflect')
assert audio_feat.shape[0] == seq_len and audio_feat.shape[1] == self.audio_feat_dim
else:
audio_feat = self.audio_feat
else: # including feature and history
if self.audio_feat_win_size is None:
audio_feat = self.audio_feat[index:index + seq_len + num_pre_frames, ...]
if audio_feat.shape[0] < seq_len + num_pre_frames:
audio_feat = np.pad(audio_feat,
[[0, seq_len + self.num_frames - audio_feat.shape[0]], [0, 0]],
mode='constant')
assert audio_feat.shape[0] == self.num_frames + seq_len and audio_feat.shape[
1] == self.audio_feat_dim
if child.normalization:
data_mean = child.normalize_stats['mean'].reshape(1, -1)
data_std = child.normalize_stats['std'].reshape(1, -1)
seq_data[:, :330] = (seq_data[:, :330] - data_mean) / data_std
if child.split in['train', 'test']:
if self.convert_to_6d:
if self.expression:
data_sample = {
'poses': seq_data[:, :330].astype(np.float).transpose(1, 0),
'expression': seq_data[:, 330:].astype(np.float).transpose(1, 0),
# 'nzero': seq_data[:, 375:].astype(np.float).transpose(1, 0),
'aud_feat': audio_feat.astype(np.float).transpose(1, 0),
'speaker': speaker_id[self.speaker],
'betas': self.betas,
'aud_file': self.audio_fn,
}
else:
data_sample = {
'poses': seq_data[:, :330].astype(np.float).transpose(1, 0),
'nzero': seq_data[:, 330:].astype(np.float).transpose(1, 0),
'aud_feat': audio_feat.astype(np.float).transpose(1, 0),
'speaker': speaker_id[self.speaker],
'betas': self.betas
}
else:
if self.expression:
data_sample = {
'poses': seq_data[:, :165].astype(np.float).transpose(1, 0),
'expression': seq_data[:, 165:].astype(np.float).transpose(1, 0),
'aud_feat': audio_feat.astype(np.float).transpose(1, 0),
# 'wv2_feat': wv2_feat.astype(np.float).transpose(1, 0),
'speaker': speaker_id[self.speaker],
'aud_file': self.audio_fn,
'betas': self.betas
}
else:
data_sample = {
'poses': seq_data.astype(np.float).transpose(1, 0),
'aud_feat': audio_feat.astype(np.float).transpose(1, 0),
'speaker': speaker_id[self.speaker],
'betas': self.betas
}
return data_sample
else:
data_sample = {
'poses': seq_data[:, :330].astype(np.float).transpose(1, 0),
'expression': seq_data[:, 330:].astype(np.float).transpose(1, 0),
# 'nzero': seq_data[:, 325:].astype(np.float).transpose(1, 0),
'aud_feat': audio_feat.astype(np.float).transpose(1, 0),
'aud_file': self.audio_fn,
'speaker': speaker_id[self.speaker],
'betas': self.betas
}
return data_sample
def __len__(child):
return len(child.index_list)
if split == 'train':
index_list = list(
range(0, min(self.complete_data.shape[0], self.audio_feat.shape[0]) - self.num_generate_length - self.num_pre_frames,
6))
elif split in ['val', 'test']:
index_list = list([0])
if self.whole_video:
index_list = list([0])
self.all_dataset = __Worker__(index_list, normalization, normalize_stats, split)
def __len__(self):
return len(self.img_name_list)
|