Download scripts/pipeline/normalize.py from Linzhan/Truebones-ZOO-Annotations: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/Linzhan/Truebones-ZOO-Annotations/resolve/main/scripts/pipeline/normalize.py
- Command line
-
hf download hf://datasets/Linzhan/Truebones-ZOO-Annotations/scripts/pipeline/normalize.py
-
curl -L -o normalize.py https://huggingface.co/datasets/Linzhan/Truebones-ZOO-Annotations/resolve/main/scripts/pipeline/normalize.py
12.2 kB
| #!/usr/bin/env python3 | |
| """Name every source motion uniformly, and record the name in clips.csv. | |
| <Species>-<Action>.fbx | |
| Step 2. Creates no files: it fills the `normalized_name` column, and | |
| `build_animation.py` is what puts those names on disk. Naming rule: the species | |
| travels with the file rather than living in a directory, and the action never | |
| contains a hyphen, so `name.split("-", 1)` recovers both parts. | |
| Spaces, source hyphens and stray punctuation become underscores and runs of | |
| underscores collapse, leaving names that are safe as identifiers, in shell | |
| globs and on any filesystem. | |
| Trex/T-Rex-Big roar step.fbx -> Trex-Big_Roar_Step.fbx | |
| Dog-2/DOG-Attack.fbx -> Dog2-Attack.fbx | |
| A species prefix already present in the source name is stripped so it is not | |
| repeated. Folders whose files are named after something else — an abbreviation, | |
| a synonym, or a misspelling — are handled by inferring each folder's dominant | |
| filename prefix from the data rather than by string-matching the folder name. Files are hardlinked, so this costs no extra disk; `Truebone_Z-OO/` keeps the | |
| original layout and names, and `clips.csv` carries both paths. | |
| """ | |
| import collections, csv, os, re, sys | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| SCRIPTS = os.path.dirname(HERE) | |
| ROOT = os.path.dirname(SCRIPTS) | |
| sys.path[:0] = [HERE, os.path.join(SCRIPTS, "probes")] | |
| from fbx_motion import probe as motion_probe | |
| def _alnum(s): | |
| return re.sub(r"[^A-Za-z0-9]", "", s).upper() | |
| def norm_species(group): | |
| """Species names are joined straight through: `Dog-2` -> `Dog2`.""" | |
| return re.sub(r"[^A-Za-z0-9]", "", group) | |
| def _base_species(sp): | |
| """`Scorpion2` -> `Scorpion`, `SpiderG` -> `Spider`: drop a trailing variant marker.""" | |
| b = re.sub(r"\d+$", "", sp) | |
| if len(b) > 4 and b[-1].isupper() and b[-2].islower(): | |
| b = b[:-1] | |
| return b | |
| def _eat(s, prefix): | |
| """Drop as many alphanumeric characters from the front of s as prefix has.""" | |
| i = cnt = 0 | |
| while i < len(s) and cnt < len(prefix): | |
| if s[i].isalnum(): cnt += 1 | |
| i += 1 | |
| return s[i:] | |
| def infer_aliases(rows, min_share=0.6, min_len=3): | |
| """Per (species, format), the prefix its filenames actually use. | |
| Folder names do not always match what is inside them: `Leapord/` holds | |
| `Leopard-*.fbx`, `Jaws/` holds `Shark-*.fbx`, `SabreToothTiger/` holds | |
| `SABREALL-*.fbx`. String-matching the folder name cannot catch synonyms, | |
| abbreviations or misspellings, so the dominant leading token is taken from | |
| the files themselves. A trailing `ALL` is left off the alias so that variant | |
| marker survives into the action, and aliases shorter than `min_len` are | |
| ignored so single-letter markers (`PolarBearB`, `Giantbee`) are not eaten. | |
| """ | |
| by = {} | |
| for r in rows: | |
| key = (norm_species(r["group"]), r["format"]) | |
| stem = os.path.splitext(os.path.basename(r["file"]))[0].lstrip("_") | |
| by.setdefault(key, []).append(stem) | |
| alias = {} | |
| for key, stems in by.items(): | |
| toks = [re.split(r"[\s\-_]+", s)[0] for s in stems if s] | |
| if not toks: | |
| continue | |
| top, n = collections.Counter(toks).most_common(1)[0] | |
| if n / len(toks) < min_share: | |
| continue | |
| a = _alnum(top) | |
| if a.endswith("ALL") and len(a) > 4: | |
| a = a[:-3] | |
| sp = _alnum(key[0]) | |
| if len(a) >= min_len and a != sp and not a.startswith(sp): | |
| alias[key] = a | |
| return alias | |
| def norm_action(stem, group, alias=None, fmt=None): | |
| """Strip a repeated species prefix, then normalize what is left. | |
| The full species name is tried first, then the base name, so a group whose | |
| files are named after the base (`Scorpion-Back Up.fbx` inside `Scorpion-2/`) | |
| does not end up with the species twice. Matching consumes characters rather | |
| than whole tokens, so a variant marker fused to the species survives: | |
| `AlligatorALL-BigMouth` keeps its `ALL`. | |
| """ | |
| s = stem.strip().lstrip("_") | |
| sp = norm_species(group) | |
| cands = [_alnum(sp), _alnum(_base_species(sp))] | |
| if alias: | |
| a = alias.get((sp, fmt)) | |
| if a: | |
| cands.append(a) | |
| cands += EXTRA_ALIASES.get(sp, []) | |
| for cand in cands: | |
| if cand and _alnum(s).startswith(cand): | |
| s = _eat(s, cand); break | |
| s = re.sub(r"[\s\-]+", "_", s) | |
| s = re.sub(r"[^A-Za-z0-9_]", "_", s) | |
| # A name that is nothing but the species belongs to that group's combined file, | |
| # the same role `<Species>ALL.fbx` plays elsewhere, so it lands on ALL too. | |
| s = re.sub(r"_+", "_", s).strip("_") or "ALL" | |
| # The `ALL` export marker is only meaningful on the combined take, which has | |
| # no action of its own. On a single clip it says nothing, so drop it there. | |
| m = re.match(r"^[Aa][Ll][Ll]_(.+)$", s) | |
| s = m.group(1) if m else s | |
| for pat, rep in WORD_FIXES.get(norm_species(group), []): | |
| s = re.sub(pat, rep, s) | |
| return s | |
| RESERVED = {"ALL", "TPOSE"} | |
| # Spelling variants the dominant-prefix inference cannot see, because they occur | |
| # on a single file while a different spelling dominates the folder. `Pirrana/` | |
| # holds eleven `Piranna-*.fbx` plus one `PirhannaALL.fbx` — a third spelling of | |
| # the same species. Fuzzy matching was tried and rejected: at an edit distance | |
| # loose enough to catch this, it also swallowed the real action `Shiver` in | |
| # `SpiderG/`. Listed explicitly instead. | |
| EXTRA_ALIASES = {"Pirrana": ["PIRHANNA"]} | |
| # Groups whose combined ALL file spells an action out while the standalone clips | |
| # abbreviate it. Folding the abbreviation into the full word makes the two agree, | |
| # so `ALL` lists exactly the clips the folder holds. Scoped per group: `Gazelle` | |
| # is left alone because it ships `Attack_1` and `Atk_1` as separate motions, and | |
| # `Monkey` because its ALL diverges for other reasons besides spelling. | |
| WORD_FIXES = { | |
| # Matched case-insensitively: the source spells it `atk 1.fbx` in lower case, | |
| # and capitalisation only happens further down the pipeline. | |
| "Elephant": [(r"(?<![A-Za-z])[Aa][Tt][Kk](?![A-Za-z])", "Attack")], | |
| "Fox": [(r"(?<![A-Za-z])[Aa][Tt][Kk](?![A-Za-z])", "Attack")], | |
| "Monkey": [(r"(?<![A-Za-z])[Aa][Tt][Kk](?![A-Za-z])", "Attack")], | |
| } | |
| # Source files deliberately left out of fbx/. `Bird/Bird.fbx` rigs a second, | |
| # unrelated bird: 36 joints over 390 vertices with `Bone*` names, against the | |
| # 62 joints over 2,173 vertices with `BN_*` names used by every other Bird clip. | |
| # It shares no bone name with any of the 74 groups and appears in no BVH, so it | |
| # is an orphan model rather than a variant, and keeping it would break the one- | |
| # skeleton-per-species-folder assumption. | |
| EXCLUDE_SOURCES = {"Truebone_Z-OO/Bird/Bird.fbx"} | |
| # Compound words the source ran together with no camel-case boundary to split on | |
| # (`Roarforward`, `Walkbackward`). Automatic word segmentation against a | |
| # vocabulary built from the library both missed cases and produced false splits | |
| # (`Layout` -> `Lay_out`), so these are listed explicitly instead. Group context | |
| # resolved the odd ones: `Flamingo-OneLEgBEnt` is a flamingo on one leg. | |
| COMPOUNDS = { | |
| "Injuredwalk": "Injured_Walk", "Landflap": "Land_Flap", | |
| "Leashjump": "Leash_Jump", "MeanLEft": "Mean_Left", | |
| "OneLEgBEnt": "One_Leg_Bent", "Roarforward": "Roar_Forward", | |
| "Runleft": "Run_Left", "Slowtail": "Slow_Tail", | |
| "Startwalk": "Start_Walk", "Swimturn": "Swim_Turn", | |
| "Twistrattle": "Twist_Rattle", "WalkSLow": "Walk_Slow", | |
| "Walkbackward": "Walk_Backward", "Walkleft": "Walk_Left", | |
| } | |
| def mixamo_style(action): | |
| """Underscore-separated words, each capitalised, trailing variant as `_2`. | |
| Matches the convention used by the Mixamo animation set: `Bite_Arm_Shake`, | |
| `Walk_Loop`, `Attack_1`. Word boundaries are taken from camel case and from | |
| letter/digit transitions. A split that would leave a one-character fragment | |
| is skipped, so source typos and variant codes are not mangled — `180RIght` | |
| (a misspelling of Right) and `CarrionC_A02` stay intact rather than becoming | |
| `180_R_Ight` and `Carrion_C_A_02`. The `ALL` and `TPOSE` markers are left uppercase. | |
| """ | |
| if action in RESERVED: | |
| return action | |
| if action in COMPOUNDS: | |
| return COMPOUNDS[action] | |
| words = [] | |
| for seg in action.split("_"): | |
| if not seg: | |
| continue | |
| t = seg | |
| t = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "\x00", t) | |
| t = re.sub(r"(?<=[A-Z])(?=[A-Z][a-z])", "\x00", t) | |
| t = re.sub(r"(?<=[A-Za-z])(?=\d)", "\x00", t) | |
| t = re.sub(r"(?<=\d)(?=[A-Za-z])", "\x00", t) | |
| parts = [p for p in t.split("\x00") if p] | |
| if len(seg) > 2 and any(len(p) == 1 and p.isalpha() for p in parts): | |
| parts = [seg] | |
| words += parts | |
| return "_".join(w[0].upper() + w[1:] for w in words) or action | |
| def canonical_case(actions): | |
| """One spelling per action across the whole library. | |
| Source casing is inconsistent — `TPOSE`/`Tpose`, `Idle`/`IDLE`/`idle`, | |
| `WalkLoop`/`walkloop` all occur. For each action the most frequent spelling | |
| wins, which keeps well-formed internal capitals (`WalkLoop`, not | |
| `Walkloop`). An all-caps spelling is left alone so markers like `ALL` and | |
| `TPOSE` stay markers; anything else gets its first letter capitalised so no | |
| lowercase-only names survive. | |
| """ | |
| counts = collections.defaultdict(collections.Counter) | |
| for a in actions: | |
| counts[a.lower()][a] += 1 | |
| canon = {} | |
| for key, variants in counts.items(): | |
| best = sorted(variants.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] | |
| if not best.isupper() and best and best[0].islower(): | |
| best = best[0].upper() + best[1:] | |
| canon[key] = best | |
| return canon | |
| def main(): | |
| rows = list(csv.DictReader(open(os.path.join(ROOT, "clips.csv")))) | |
| rows.sort(key=lambda r: r["file"]) # deterministic disambiguation order | |
| alias = infer_aliases(rows) | |
| taken, made, renamed = set(), {"bvh": 0, "fbx": 0}, [] | |
| prelim = [] | |
| for r in rows: | |
| stem = os.path.splitext(os.path.basename(r["file"]))[0] | |
| prelim.append(norm_action(stem, r["group"], alias, r["format"])) | |
| canon = canonical_case(prelim) | |
| for r, raw_act in zip(rows, prelim): | |
| r["normalized_name"] = "" | |
| if r["format"] != "fbx": # bvh is not part of the clip set | |
| continue | |
| if r["file"] in EXCLUDE_SOURCES: | |
| continue | |
| # Skip FBX that carry no motion at all: keyframes whose values never | |
| # change (including every TPOSE) and files with no animation curves. | |
| try: | |
| m = motion_probe(os.path.join(ROOT, r["file"])) | |
| if m["static"] or m["no_curves"]: | |
| continue | |
| except Exception: | |
| pass | |
| sp = norm_species(r["group"]) | |
| act = mixamo_style(canon[raw_act.lower()]) | |
| name = "%s-%s.fbx" % (sp, act) | |
| # macOS/Windows filesystems are case-insensitive: `Gazelle-run.fbx` and | |
| # `Gazelle-Run.fbx` are the same path there, so compare case-folded and | |
| # give the later file a numeric suffix instead of silently losing it. | |
| n = 2 | |
| while name.lower() in taken: | |
| name = "%s-%s_%d.fbx" % (sp, act, n); n += 1 | |
| if n == 3: renamed.append(name) | |
| taken.add(name.lower()) | |
| r["normalized_name"] = name | |
| made["fbx"] += 1 | |
| # `normalized_file` is what this column used to be called, back when the | |
| # names were also written out as an `fbx/` tree; drop it if an older | |
| # clips.csv is being re-normalized in place. | |
| cols = [c for c in rows[0] if c not in ("normalized_name", "normalized_file")] | |
| cols.insert(1, "normalized_name") | |
| for r in rows: | |
| r.pop("normalized_file", None) | |
| with open(os.path.join(ROOT, "clips.csv"), "w", newline="", encoding="utf-8") as fh: | |
| w = csv.DictWriter(fh, fieldnames=cols); w.writeheader(); w.writerows(rows) | |
| print("named %d clips | case-disambiguated: %d" % (made["fbx"], len(renamed))) | |
| for x in renamed[:10]: | |
| print(" suffixed:", os.path.basename(x)) | |
| if __name__ == "__main__": | |
| main() | |