File size: 9,337 Bytes
cdd65f2 | 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 | """
Auto-extract L1 action labels from filenames/metadata for datasets without text.
Outputs: data/processed/{dataset}/labels.json
Format: { "motion_id": {"L1_action": "walk", "L1_style": "happy", "source_file": "..."}, ... }
"""
import sys
import os
import re
import json
from pathlib import Path
import numpy as np
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
def extract_lafan1():
"""LAFAN1: filename = {theme}{take}_{subject}.bvh → L1 = theme"""
labels = {}
mdir = project_root / 'data' / 'processed' / 'lafan1' / 'motions'
for f in sorted(os.listdir(mdir)):
d = dict(np.load(mdir / f, allow_pickle=True))
src = str(d.get('source_file', f))
# "aiming1_subject1.bvh" → "aiming"
match = re.match(r'([a-zA-Z]+)\d*_', src)
action = match.group(1).lower() if match else 'unknown'
labels[f.replace('.npz', '')] = {
'L1_action': action,
'source_file': src,
}
return labels
def extract_100style():
"""100Style: filename = {StyleName}_{MovementType}.bvh"""
movement_map = {
'FW': 'walk forward', 'BW': 'walk backward',
'FR': 'run forward', 'BR': 'run backward',
'SW': 'sidestep walk', 'SR': 'sidestep run',
'ID': 'idle',
'TR1': 'transition 1', 'TR2': 'transition 2',
'TR3': 'transition 3', 'TR4': 'transition 4',
}
labels = {}
mdir = project_root / 'data' / 'processed' / '100style' / 'motions'
for f in sorted(os.listdir(mdir)):
d = dict(np.load(mdir / f, allow_pickle=True))
src = str(d.get('source_file', f))
# "Happy_FW.bvh" → style="happy", movement="walk forward"
parts = src.replace('.bvh', '').split('_')
style = parts[0].lower() if parts else 'unknown'
movement_code = parts[1] if len(parts) > 1 else ''
movement = movement_map.get(movement_code, movement_code.lower())
action = movement.split()[0] if movement else 'unknown' # first word
labels[f.replace('.npz', '')] = {
'L1_action': action,
'L1_movement': movement,
'L1_style': style,
'source_file': src,
}
return labels
def extract_bandai_namco():
"""Bandai Namco: has JSON metadata in original repo."""
labels = {}
mdir = project_root / 'data' / 'processed' / 'bandai_namco' / 'motions'
# Try to load from original JSON metadata
bn_meta = {}
meta_dirs = [
project_root / 'data' / 'raw' / 'BandaiNamco' / 'dataset',
]
for meta_dir in meta_dirs:
for json_file in meta_dir.rglob('*.json'):
try:
with open(json_file) as jf:
data = json.load(jf)
if isinstance(data, list):
for item in data:
if 'file' in item and 'content' in item:
bn_meta[item['file']] = item
except Exception:
continue
for f in sorted(os.listdir(mdir)):
d = dict(np.load(mdir / f, allow_pickle=True))
src = str(d.get('source_file', f))
# Try metadata lookup
action = 'unknown'
style = ''
if src in bn_meta:
meta = bn_meta[src]
action = meta.get('content', 'unknown').lower()
style = meta.get('style', '').lower()
else:
# Fallback: parse filename
name = src.replace('.bvh', '').lower()
# Common patterns: walk, run, kick, punch, etc.
for keyword in ['walk', 'run', 'kick', 'punch', 'jump', 'dance', 'idle', 'turn',
'throw', 'catch', 'wave', 'bow', 'sit', 'stand', 'crouch', 'crawl']:
if keyword in name:
action = keyword
break
labels[f.replace('.npz', '')] = {
'L1_action': action,
'L1_style': style,
'source_file': src,
}
return labels
def extract_cmu_mocap():
"""CMU MoCap: directory structure = subject/action."""
labels = {}
mdir = project_root / 'data' / 'processed' / 'cmu_mocap' / 'motions'
for f in sorted(os.listdir(mdir)):
d = dict(np.load(mdir / f, allow_pickle=True))
src = str(d.get('source_file', f))
# "01_01.bvh" → subject=01, sequence=01
parts = src.replace('.bvh', '').split('_')
subject = parts[0] if parts else '?'
seq = parts[1] if len(parts) > 1 else '?'
labels[f.replace('.npz', '')] = {
'L1_action': 'motion', # CMU doesn't have action labels in filenames
'L1_subject': subject,
'L1_sequence': seq,
'source_file': src,
}
return labels
def extract_mixamo():
"""Mixamo: hash filenames → no meaningful labels from filename alone."""
labels = {}
mdir = project_root / 'data' / 'processed' / 'mixamo' / 'motions'
# Try to load animation name mapping if available
anim_map = {}
anim_json = project_root / 'data' / 'raw' / 'Mixamo' / 'animation_frames.json'
if anim_json.exists():
try:
with open(anim_json) as jf:
data = json.load(jf)
for name, info in data.items():
# name is like "Aim_Pistol" with frame count as value
anim_map[name.lower()] = name
except Exception:
pass
for f in sorted(os.listdir(mdir)):
d = dict(np.load(mdir / f, allow_pickle=True))
src = str(d.get('source_file', f)).replace('.bvh', '').replace('.fbx', '')
# Try to match hash to animation name
action = 'motion'
labels[f.replace('.npz', '')] = {
'L1_action': action,
'source_file': src,
}
return labels
def extract_truebones_zoo():
"""Truebones Zoo: already has some text; extract L1 from species + filename."""
labels = {}
mdir = project_root / 'data' / 'processed' / 'truebones_zoo' / 'motions'
for f in sorted(os.listdir(mdir)):
d = dict(np.load(mdir / f, allow_pickle=True))
species = str(d.get('species', ''))
src = str(d.get('source_file', f))
texts = str(d.get('texts', ''))
# Extract action from filename: "__Attack1.bvh" → "attack"
name = src.replace('.bvh', '').strip('_').lower()
action = 'motion'
for keyword in ['attack', 'walk', 'run', 'idle', 'die', 'death', 'eat', 'bite',
'jump', 'fly', 'swim', 'crawl', 'sleep', 'sit', 'stand', 'turn',
'howl', 'bark', 'roar', 'hit', 'charge', 'gallop', 'trot', 'strike',
'breath', 'wing', 'tail', 'shake', 'scratch', 'pounce', 'retreat']:
if keyword in name:
action = keyword
break
labels[f.replace('.npz', '')] = {
'L1_action': action,
'L1_species': species,
'L1_species_category': _species_category(species),
'has_L2': bool(texts and texts not in ('', "b''")),
'source_file': src,
}
return labels
def _species_category(species):
"""Map species to category."""
quadrupeds = {'Dog', 'Dog-2', 'Cat', 'Horse', 'Bear', 'BrownBear', 'PolarBear', 'PolarBearB',
'Buffalo', 'Camel', 'Coyote', 'Deer', 'Elephant', 'Fox', 'Gazelle', 'Goat',
'Hamster', 'Hippopotamus', 'Hound', 'Jaguar', 'Leapord', 'Lion', 'Lynx',
'Mammoth', 'Monkey', 'Puppy', 'Raindeer', 'Rat', 'Rhino', 'SabreToothTiger',
'SandMouse', 'Skunk'}
flying = {'Bat', 'Bird', 'Buzzard', 'Chicken', 'Crow', 'Eagle', 'Flamingo', 'Giantbee',
'Ostrich', 'Parrot', 'Parrot2', 'Pigeon', 'Pteranodon', 'Tukan'}
reptile = {'Alligator', 'Comodoa', 'Crocodile', 'Stego', 'Trex', 'Tricera', 'Tyranno'}
insect = {'Ant', 'Centipede', 'Cricket', 'FireAnt', 'Isopetra', 'Roach', 'Scorpion',
'Scorpion-2', 'Spider', 'SpiderG'}
snake = {'Anaconda', 'KingCobra'}
aquatic = {'Crab', 'HermitCrab', 'Jaws', 'Pirrana', 'Turtle'}
fantasy = {'Dragon', 'Raptor', 'Raptor2', 'Raptor3'}
if species in quadrupeds: return 'quadruped'
if species in flying: return 'flying'
if species in reptile: return 'reptile'
if species in insect: return 'insect'
if species in snake: return 'snake'
if species in aquatic: return 'aquatic'
if species in fantasy: return 'fantasy'
return 'other'
def main():
extractors = {
'lafan1': extract_lafan1,
'100style': extract_100style,
'bandai_namco': extract_bandai_namco,
'cmu_mocap': extract_cmu_mocap,
'mixamo': extract_mixamo,
'truebones_zoo': extract_truebones_zoo,
}
for ds, extractor in extractors.items():
labels = extractor()
out_path = project_root / 'data' / 'processed' / ds / 'labels.json'
with open(out_path, 'w') as f:
json.dump(labels, f, indent=2, ensure_ascii=False)
# Stats
actions = [v.get('L1_action', '?') for v in labels.values()]
from collections import Counter
top = Counter(actions).most_common(5)
print(f'{ds:15s}: {len(labels)} labels, top actions: {top}')
if __name__ == '__main__':
main()
|