Tevior commited on
Commit
3a78f46
·
verified ·
1 Parent(s): f2244d1

Upload src/data/humanml3d_converter.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/data/humanml3d_converter.py +363 -0
src/data/humanml3d_converter.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert HumanML3D data (SMPL-based .npy format) into our unified representation.
3
+
4
+ HumanML3D stores motions as:
5
+ - new_joints/XXXXXX.npy: [T, 22, 3] joint positions (SMPL 22-joint skeleton)
6
+ - new_joint_vecs/XXXXXX.npy: [T, 263] rotation-invariant features
7
+ - texts/XXXXXX.txt: text descriptions (multiple per motion)
8
+
9
+ We convert to:
10
+ - SkeletonGraph (fixed SMPL-22 topology)
11
+ - Motion dict with positions, velocities, and text annotations
12
+ """
13
+
14
+ import numpy as np
15
+ from pathlib import Path
16
+ from typing import Optional
17
+
18
+ from .skeleton_graph import SkeletonGraph
19
+
20
+
21
+ # SMPL 22-joint skeleton definition
22
+ SMPL_22_JOINT_NAMES = [
23
+ 'pelvis', # 0
24
+ 'left_hip', # 1
25
+ 'right_hip', # 2
26
+ 'spine1', # 3
27
+ 'left_knee', # 4
28
+ 'right_knee', # 5
29
+ 'spine2', # 6
30
+ 'left_ankle', # 7
31
+ 'right_ankle', # 8
32
+ 'spine3', # 9
33
+ 'left_foot', # 10
34
+ 'right_foot', # 11
35
+ 'neck', # 12
36
+ 'left_collar', # 13
37
+ 'right_collar', # 14
38
+ 'head', # 15
39
+ 'left_shoulder', # 16
40
+ 'right_shoulder', # 17
41
+ 'left_elbow', # 18
42
+ 'right_elbow', # 19
43
+ 'left_wrist', # 20
44
+ 'right_wrist', # 21
45
+ ]
46
+
47
+ SMPL_22_PARENTS = [
48
+ -1, # 0 pelvis (root)
49
+ 0, # 1 left_hip -> pelvis
50
+ 0, # 2 right_hip -> pelvis
51
+ 0, # 3 spine1 -> pelvis
52
+ 1, # 4 left_knee -> left_hip
53
+ 2, # 5 right_knee -> right_hip
54
+ 3, # 6 spine2 -> spine1
55
+ 4, # 7 left_ankle -> left_knee
56
+ 5, # 8 right_ankle -> right_knee
57
+ 6, # 9 spine3 -> spine2
58
+ 7, # 10 left_foot -> left_ankle
59
+ 8, # 11 right_foot -> right_ankle
60
+ 9, # 12 neck -> spine3
61
+ 9, # 13 left_collar -> spine3
62
+ 9, # 14 right_collar -> spine3
63
+ 12, # 15 head -> neck
64
+ 13, # 16 left_shoulder -> left_collar
65
+ 14, # 17 right_shoulder -> right_collar
66
+ 16, # 18 left_elbow -> left_shoulder
67
+ 17, # 19 right_elbow -> right_shoulder
68
+ 18, # 20 left_wrist -> left_elbow
69
+ 19, # 21 right_wrist -> right_elbow
70
+ ]
71
+
72
+
73
+ def get_smpl22_skeleton(rest_pose: Optional[np.ndarray] = None) -> SkeletonGraph:
74
+ """
75
+ Get the SMPL 22-joint skeleton graph.
76
+
77
+ Args:
78
+ rest_pose: [22, 3] rest-pose joint positions. If None, uses default T-pose offsets.
79
+
80
+ Returns:
81
+ SkeletonGraph for SMPL-22.
82
+ """
83
+ if rest_pose is None:
84
+ # Default T-pose offsets (approximate, from HumanML3D average)
85
+ rest_pose = np.array([
86
+ [0.0, 0.0, 0.0], # pelvis
87
+ [0.08, -0.05, 0.0], # left_hip
88
+ [-0.08, -0.05, 0.0], # right_hip
89
+ [0.0, 0.1, 0.0], # spine1
90
+ [0.0, -0.4, 0.0], # left_knee
91
+ [0.0, -0.4, 0.0], # right_knee
92
+ [0.0, 0.15, 0.0], # spine2
93
+ [0.0, -0.4, 0.0], # left_ankle
94
+ [0.0, -0.4, 0.0], # right_ankle
95
+ [0.0, 0.15, 0.0], # spine3
96
+ [0.0, -0.05, 0.1], # left_foot
97
+ [0.0, -0.05, 0.1], # right_foot
98
+ [0.0, 0.12, 0.0], # neck
99
+ [0.05, 0.0, 0.0], # left_collar
100
+ [-0.05, 0.0, 0.0], # right_collar
101
+ [0.0, 0.12, 0.0], # head
102
+ [0.15, 0.0, 0.0], # left_shoulder
103
+ [-0.15, 0.0, 0.0], # right_shoulder
104
+ [0.25, 0.0, 0.0], # left_elbow
105
+ [-0.25, 0.0, 0.0], # right_elbow
106
+ [0.25, 0.0, 0.0], # left_wrist
107
+ [-0.25, 0.0, 0.0], # right_wrist
108
+ ], dtype=np.float32)
109
+
110
+ # Compute offsets from parent
111
+ offsets = np.zeros_like(rest_pose)
112
+ for j in range(len(SMPL_22_PARENTS)):
113
+ p = SMPL_22_PARENTS[j]
114
+ if p >= 0:
115
+ offsets[j] = rest_pose[j] - rest_pose[p]
116
+ else:
117
+ offsets[j] = rest_pose[j]
118
+
119
+ return SkeletonGraph(
120
+ joint_names=SMPL_22_JOINT_NAMES,
121
+ parent_indices=SMPL_22_PARENTS,
122
+ rest_offsets=offsets,
123
+ )
124
+
125
+
126
+ def load_humanml3d_motion(
127
+ motion_id: str,
128
+ data_dir: str | Path,
129
+ ) -> dict:
130
+ """
131
+ Load a single HumanML3D motion sample.
132
+
133
+ Args:
134
+ motion_id: e.g., '000000'
135
+ data_dir: path to HumanML3D directory
136
+
137
+ Returns:
138
+ dict with keys:
139
+ - 'joint_positions': [T, 22, 3] global joint positions
140
+ - 'joint_vecs': [T, 263] rotation-invariant features (if available)
141
+ - 'texts': list of text descriptions
142
+ - 'motion_id': str
143
+ """
144
+ data_dir = Path(data_dir)
145
+
146
+ # Load joint positions
147
+ joints_path = data_dir / 'new_joints' / f'{motion_id}.npy'
148
+ joint_positions = np.load(joints_path) # [T, 22, 3]
149
+
150
+ # Load joint vectors (rotation-invariant features) if available
151
+ vecs_path = data_dir / 'new_joint_vecs' / f'{motion_id}.npy'
152
+ joint_vecs = None
153
+ if vecs_path.exists():
154
+ joint_vecs = np.load(vecs_path) # [T, 263]
155
+
156
+ # Load text descriptions
157
+ text_path = data_dir / 'texts' / f'{motion_id}.txt'
158
+ texts = []
159
+ if text_path.exists():
160
+ with open(text_path, 'r') as f:
161
+ for line in f:
162
+ line = line.strip()
163
+ if line:
164
+ # Format: "text#token1 token2#start#end"
165
+ parts = line.split('#')
166
+ if parts:
167
+ texts.append(parts[0].strip())
168
+
169
+ return {
170
+ 'joint_positions': joint_positions.astype(np.float32),
171
+ 'joint_vecs': joint_vecs,
172
+ 'texts': texts,
173
+ 'motion_id': motion_id,
174
+ }
175
+
176
+
177
+ def compute_motion_features(
178
+ joint_positions: np.ndarray,
179
+ skeleton: SkeletonGraph,
180
+ fps: float = 20.0,
181
+ ) -> dict:
182
+ """
183
+ Compute motion features from joint positions for TopoSlots (Scheme C).
184
+
185
+ Scheme C:
186
+ - Slot tokens: per-joint [local_pos(3) + velocity(3)] = 6D (cross-skeleton compatible)
187
+ - Decoder GT: per-joint rotations via FK supervision (skeleton-specific)
188
+ - Root trajectory: separate track
189
+ - Foot contact: auxiliary loss
190
+
191
+ Args:
192
+ joint_positions: [T, J, 3] global joint positions
193
+ skeleton: SkeletonGraph
194
+ fps: frames per second
195
+
196
+ Returns:
197
+ dict with:
198
+ - 'root_position': [T, 3]
199
+ - 'root_velocity': [T, 3]
200
+ - 'local_positions': [T, J, 3] root-relative joint positions
201
+ - 'velocities': [T, J, 3] joint velocities
202
+ - 'accelerations': [T, J, 3] joint accelerations
203
+ - 'bone_lengths': [T, J] per-frame bone lengths
204
+ - 'foot_contact': [T, 4] 4-channel (l_heel, l_toe, r_heel, r_toe)
205
+ """
206
+ T, J, _ = joint_positions.shape
207
+
208
+ # Root position (joint 0)
209
+ root_pos = joint_positions[:, 0, :] # [T, 3]
210
+
211
+ # Local positions (relative to root)
212
+ local_pos = joint_positions - root_pos[:, None, :] # [T, J, 3]
213
+
214
+ # Velocities (finite difference)
215
+ vel = np.zeros_like(joint_positions)
216
+ vel[1:] = (joint_positions[1:] - joint_positions[:-1]) * fps
217
+ vel[0] = vel[1]
218
+
219
+ root_vel = vel[:, 0, :] # [T, 3]
220
+
221
+ # Accelerations (finite difference of velocity)
222
+ acc = np.zeros_like(vel)
223
+ acc[1:] = (vel[1:] - vel[:-1]) * fps
224
+ acc[0] = acc[1]
225
+
226
+ # Bone lengths per frame
227
+ bone_lengths = np.zeros((T, J), dtype=np.float32)
228
+ for j in range(J):
229
+ p = skeleton.parent_indices[j]
230
+ if p >= 0:
231
+ bone_lengths[:, j] = np.linalg.norm(
232
+ joint_positions[:, j] - joint_positions[:, p], axis=-1
233
+ )
234
+
235
+ # Foot contact: 4-channel detection via velocity + height
236
+ foot_contact = _detect_foot_contact(joint_positions, vel, skeleton)
237
+
238
+ return {
239
+ 'root_position': root_pos,
240
+ 'root_velocity': root_vel,
241
+ 'local_positions': local_pos,
242
+ 'velocities': vel,
243
+ 'accelerations': acc,
244
+ 'bone_lengths': bone_lengths,
245
+ 'foot_contact': foot_contact,
246
+ }
247
+
248
+
249
+ def _detect_foot_contact(
250
+ positions: np.ndarray,
251
+ velocities: np.ndarray,
252
+ skeleton: SkeletonGraph,
253
+ vel_thresh: float = None,
254
+ ) -> np.ndarray:
255
+ """
256
+ Detect 4-channel foot contact: [l_heel, l_toe, r_heel, r_toe].
257
+
258
+ Auto-adapts thresholds based on data scale (meters vs centimeters).
259
+ """
260
+ T = positions.shape[0]
261
+ foot_contact = np.zeros((T, 4), dtype=np.float32)
262
+
263
+ # Auto-detect scale for thresholds
264
+ body_height = positions[0, :, 1].max() - positions[0, :, 1].min()
265
+ if body_height < 0.01:
266
+ return foot_contact # degenerate
267
+ # Velocity threshold proportional to body height
268
+ # ~0.5 m/s for 1.7m human → 0.3 * body_height
269
+ if vel_thresh is None:
270
+ vel_thresh = 0.3 * body_height
271
+ height_margin = 0.03 * body_height # ~5cm for 1.7m human
272
+
273
+ names_lower = [n.lower() for n in skeleton.joint_names]
274
+
275
+ # Find foot-related joints with broader matching
276
+ joint_map = {
277
+ 'l_heel': None, 'l_toe': None,
278
+ 'r_heel': None, 'r_toe': None,
279
+ }
280
+ for j, n in enumerate(names_lower):
281
+ is_left = 'left' in n or n.startswith('l_') or n.startswith('l ') or 'leftfoot' in n.replace(' ', '')
282
+ is_right = 'right' in n or n.startswith('r_') or n.startswith('r ') or 'rightfoot' in n.replace(' ', '')
283
+ is_ankle = 'ankle' in n or 'heel' in n
284
+ is_foot = 'foot' in n or 'toe' in n
285
+
286
+ if is_left and is_ankle and joint_map['l_heel'] is None:
287
+ joint_map['l_heel'] = j
288
+ elif is_left and is_foot and joint_map['l_toe'] is None:
289
+ joint_map['l_toe'] = j
290
+ elif is_right and is_ankle and joint_map['r_heel'] is None:
291
+ joint_map['r_heel'] = j
292
+ elif is_right and is_foot and joint_map['r_toe'] is None:
293
+ joint_map['r_toe'] = j
294
+
295
+ channels = ['l_heel', 'l_toe', 'r_heel', 'r_toe']
296
+ for ch_idx, ch_name in enumerate(channels):
297
+ jidx = joint_map[ch_name]
298
+ if jidx is None:
299
+ continue
300
+ jvel = np.linalg.norm(velocities[:, jidx, :], axis=-1)
301
+ jheight = positions[:, jidx, 1]
302
+ height_thresh = np.percentile(jheight, 10) + height_margin
303
+ foot_contact[:, ch_idx] = (
304
+ (jvel < vel_thresh) & (jheight < height_thresh)
305
+ ).astype(np.float32)
306
+
307
+ return foot_contact
308
+
309
+
310
+ def extract_rotations_from_263d(joint_vecs: np.ndarray) -> dict:
311
+ """
312
+ Extract structured features from HumanML3D 263D vector.
313
+
314
+ Layout (22-joint SMPL):
315
+ [0:1] root angular velocity (y-axis)
316
+ [1:3] root linear velocity (xz)
317
+ [3:4] root height (y)
318
+ [4:67] joint positions relative to root (21 × 3 = 63)
319
+ [67:193] joint 6D continuous rotations (21 × 6 = 126)
320
+ [193:259] joint velocities (22 × 3 = 66)
321
+ [259:263] foot contact (4 channels)
322
+
323
+ Returns:
324
+ dict with:
325
+ - 'root_angular_vel': [T, 1]
326
+ - 'root_linear_vel': [T, 2]
327
+ - 'root_height': [T, 1]
328
+ - 'ric_positions': [T, 21, 3]
329
+ - 'local_rotations_6d': [T, 21, 6]
330
+ - 'joint_velocities': [T, 22, 3]
331
+ - 'foot_contact_4ch': [T, 4]
332
+ """
333
+ T = joint_vecs.shape[0]
334
+ return {
335
+ 'root_angular_vel': joint_vecs[:, 0:1],
336
+ 'root_linear_vel': joint_vecs[:, 1:3],
337
+ 'root_height': joint_vecs[:, 3:4],
338
+ 'ric_positions': joint_vecs[:, 4:67].reshape(T, 21, 3),
339
+ 'local_rotations_6d': joint_vecs[:, 67:193].reshape(T, 21, 6),
340
+ 'joint_velocities': joint_vecs[:, 193:259].reshape(T, 22, 3),
341
+ 'foot_contact_4ch': joint_vecs[:, 259:263],
342
+ }
343
+
344
+
345
+ def load_humanml3d_split(
346
+ data_dir: str | Path,
347
+ split: str = 'train',
348
+ ) -> list[str]:
349
+ """Load motion IDs for a data split."""
350
+ data_dir = Path(data_dir)
351
+ split_file = data_dir / f'{split}.txt'
352
+
353
+ if not split_file.exists():
354
+ raise FileNotFoundError(f"Split file not found: {split_file}")
355
+
356
+ motion_ids = []
357
+ with open(split_file, 'r') as f:
358
+ for line in f:
359
+ line = line.strip()
360
+ if line:
361
+ motion_ids.append(line)
362
+
363
+ return motion_ids