"""Canonical joint name mappings for Truebones Zoo animal skeletons (73 species). Rule-based + lookup mapper that converts diverse Truebones naming conventions (Bip01_, BN_, jt_, Japanese romaji, Sabrecat_, NPC_, game-engine names) into standardised lowercase English anatomical labels. Generated: 2026-03-18 Dataset: truebones_zoo (73 species, 1193 unique raw joint names) """ from __future__ import annotations import re from typing import Callable # --------------------------------------------------------------------------- # Pattern 4: Japanese romaji -> English lookup # --------------------------------------------------------------------------- JAPANESE_MAP: dict[str, str] = { # Torso / core "koshi": "pelvis", "kosi": "pelvis", # alternate romanisation "hara": "abdomen", "mune": "chest", "kubi": "neck", "atama": "head", "kao": "face", "ago": "jaw", # Limbs (bare form, without L_/R_ prefix) "kata": "shoulder", "hiji": "elbow", "te": "hand", "momo": "thigh", "hiza": "knee", "ashi": "foot", # Tail "sippo": "tail", # numbered variants handled by regex # Fish-specific (Pirrana / Tukan) "obire": "tail fin", "obireA": "tail fin upper", "obireB": "tail fin lower", "sebire": "dorsal fin", "harabireR": "right pectoral fin", "harabireL": "left pectoral fin", "munabireR": "right pectoral fin upper", "munabireL": "left pectoral fin upper", "eraR": "right gill", "eraL": "left gill", "shiribire": "anal fin", "shiribireA": "anal fin upper", "shirihireB": "anal fin lower", # note: typo in original data "shippoA": "tail upper", "shippoB": "tail lower", # Misc "o": "tail base", } # --------------------------------------------------------------------------- # Lookup tables for non-regex special cases # --------------------------------------------------------------------------- _STANDALONE_MAP: dict[str, str] = { # Root / global joints "Hips": "hips", "locator": "root", "locator2": "root", "Trajectory": "trajectory", "Head": "head", "Spine": "spine", "Handle": "handle", "Saddle": "saddle", "MESH": "mesh", "N_ALL": "root all", "MagicEffectsNode": "effects node", "EyesBlue": "right eye", "EyesBlue_2": "left eye", "ElkJaw": "jaw", "C_ctrl": "center control", "BN_P": "pelvis", "BN_Shell": "shell", "BN_Down": "lower body", "BN_Downbody": "lower body", # Standalone sided "LeftArm": "left arm", "RightArm": "right arm", "LeftForeArm": "left forearm", "RightForeArm": "right forearm", "LeftHand": "left hand", "RightHand": "right hand", "LeftFoot": "left foot", "RightFoot": "right foot", "LeftLeg": "left leg", "RightLeg": "right leg", "LeftUpLeg": "left upper leg", "RightUpLeg": "right upper leg", } # Body part name normalisation for Bip01_ / BN_ / jt_ suffixes _BODY_PART_MAP: dict[str, str] = { # Core "pelvis": "pelvis", "spine": "spine", "neck": "neck", "head": "head", "jaw": "jaw", "ribcage": "ribcage", # Upper limb "clavicle": "clavicle", "upperarm": "upper arm", "forearm": "forearm", "hand": "hand", "finger": "finger", "thumb": "thumb", "wrist": "wrist", "palm": "palm", # Lower limb "thigh": "thigh", "calf": "calf", "horselink": "pastern", # extra joint in digitigrade legs "foot": "foot", "toe": "toe", "ankle": "ankle", "knee": "knee", "hip": "hip", # Tail "tail": "tail", "tai": "tail", # BN_Tai variants # Face / head "ear": "ear", "eye": "eye", "eyeball": "eyeball", "eyebrow": "eyebrow", "eyelid": "eyelid", "nose": "nose", "mouth": "mouth", "lip": "lip", "beard": "beard", "chin": "chin", "tongue": "tongue", "thouge": "tongue", # typo in original data "tone": "tongue", # BN_Tone (Anaconda typo for tongue) "mascara": "eyelash", # Appendages "wing": "wing", "feeler": "feeler", "feelers": "feeler", "clip": "claw", # BN_Clip = pincers "claw": "claw", "pincers": "pincer", "tentacles": "tentacle", "piers": "pincer", # BN_Piers = pincers (typo) "pliers": "pincer", # BN_Pliers (typo variant) # Fur / mane / hair "fur": "fur", "mane": "mane", "hair": "hair", "ponytail": "ponytail", "ponitail": "ponytail", # typo in original data # Armour / tack "halter": "halter", "reins": "reins", "shall": "shell plate", # BN_Shall (shell plates) # Anatomy "shoulder": "shoulder", "elbow": "elbow", # Dinosaur-specific "cog": "center of gravity", "spline": "spine", # BN_Spline = spine segments # Body "body": "body", "dorsal": "dorsal", "leg": "leg", "arm": "arm", "collarbone": "collarbone", "fang": "fang", # Index / middle / ring / pinky "index": "index", "middle": "middle", "ring": "ring", "pinky": "pinky", } # --------------------------------------------------------------------------- # Helper: CamelCase splitter # --------------------------------------------------------------------------- _CAMEL_RE = re.compile(r"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])") def _camel_to_words(s: str) -> str: """Split CamelCase into lowercase space-separated words.""" return _CAMEL_RE.sub(" ", s).lower() # --------------------------------------------------------------------------- # Helper: side detection # --------------------------------------------------------------------------- def _detect_side(name: str) -> tuple[str, str]: """Return (side_prefix, name_without_side). side_prefix is "left ", "right ", "center ", or "". """ # _L, _R, _C suffixes (jt_ style) m = re.match(r"^(.+?)_(L|R|C)$", name) if m: sides = {"L": "left ", "R": "right ", "C": "center "} return sides[m.group(2)], m.group(1) # L_ or R_ prefix m = re.match(r"^(L|R)_(.+)$", name) if m: sides = {"L": "left ", "R": "right "} return sides[m.group(1)], m.group(2) # Embedded _L_ or _R_ or _C_ m = re.match(r"^(.+?)_(L|R|C)_(.+)$", name) if m: sides = {"L": "left ", "R": "right ", "C": "center "} return sides[m.group(2)], m.group(1) + "_" + m.group(3) return "", name # --------------------------------------------------------------------------- # Helper: trailing number extractor # --------------------------------------------------------------------------- def _extract_trailing_number(s: str) -> tuple[str, str]: """Split 'Foo02' -> ('Foo', ' 2') or 'Foo' -> ('Foo', '').""" m = re.match(r"^(.*?)(\d+)$", s) if m: base = m.group(1).rstrip("_") num = str(int(m.group(2))) # strip leading zeros return base, f" {num}" return s, "" # --------------------------------------------------------------------------- # PREFIX_RULES: list of (regex, handler) applied in priority order # --------------------------------------------------------------------------- def _handle_bip01(raw: str) -> str | None: """Pattern 1: Bip01_ prefix (most common, ~1900 occurrences).""" m = re.match(r"^_?Bip01_(.+)$", raw) if not m: return None rest = m.group(1).lstrip("_") # strip stray leading underscores # Detect Nub suffix (leaf joint) is_nub = False if rest.endswith("Nub"): is_nub = True rest = rest[:-3] # Detect side side, rest = _detect_side(rest) # Handle trailing L/R side markers without underscore (SpineL, SpineR) if not side: side_suffix_m = re.match(r"^(.+?)(L|R)$", rest) if side_suffix_m: candidate = side_suffix_m.group(1).lower() if candidate in _BODY_PART_MAP or candidate.rstrip("_") in _BODY_PART_MAP: side = "left " if side_suffix_m.group(2) == "L" else "right " rest = side_suffix_m.group(1) # Special compound names (check BEFORE number extraction so # Spine0_Tail matches correctly) rest_lower_full = rest.lower().rstrip("_") compound_map = { "horselink": "pastern", "head_jaw": "jaw", "head1_jaw": "jaw", "head_muzzle": "muzzle", "head_brain": "brain", "head2_eyeleds": "eyelid", "head11_tungecontroler": "tongue controller", "ponytail3_tunge": "tongue", "xtra_spine": "extra spine", "xtra_neck": "extra neck", "arm_nub": "arm end", "leg_mid_nub": "mid leg end", "leg_rear_nub": "rear leg end", } if rest_lower_full in compound_map: base = compound_map[rest_lower_full] result = f"{side}{base}" if is_nub and "end" not in result: result += " end" return result.strip() # Compound: Spine0_Tail, Spine0_Tail1, etc. spine_tail_m = re.match( r"^Spine\d+_Tail(\d*)$", rest, re.IGNORECASE ) if spine_tail_m: num = spine_tail_m.group(1) suffix = f" {int(num)}" if num else "" result = f"{side}tail base{suffix}" if is_nub: result += " end" return result.strip() # Compound: Spine1_LWing, Spine1_RWing spine_wing_m = re.match( r"^Spine\d+_(L|R)Wing$", rest, re.IGNORECASE ) if spine_wing_m: wing_side = "left " if spine_wing_m.group(1) == "L" else "right " return f"{wing_side}wing root" # Compound: Calf_Mid, Calf_Rear, Thigh_Mid, Foot_Mid, etc. qual_m = re.match(r"^(\w+?)_(Mid|Rear)$", rest, re.IGNORECASE) if qual_m: part = qual_m.group(1).lower() qualifier = qual_m.group(2).lower() canonical_part = _BODY_PART_MAP.get(part, part) result = f"{side}{qualifier} {canonical_part}" if is_nub: result += " end" return result.strip() # Compound: Foot_1, Foot_2, FootNub_1, Thigh_1, Thigh1_1, etc. # Only match limb segment patterns (not Ear_01, Ponytail_L01, etc.) _SEGMENT_PARTS = { "foot", "calf", "thigh", "toe", "finger", "thigh1", "calf1", "foot1", } part_sub_m = re.match(r"^(\w+?)(\d*)_(\d+)$", rest) if part_sub_m: part_raw = part_sub_m.group(1).lower() if part_raw in _SEGMENT_PARTS: group_num = part_sub_m.group(2) sub_num = str(int(part_sub_m.group(3))) canonical_part = _BODY_PART_MAP.get(part_raw, part_raw) group_str = f" {int(group_num)}" if group_num else "" result = f"{side}{canonical_part}{group_str} segment {sub_num}" if is_nub: result += " end" return result.strip() # Handle Xtra (extra bone) -- BEFORE general number extraction rest_lower_pre = rest.lower().rstrip("_") if rest_lower_pre.startswith("xtra"): # Parse: Xtra[NN][Opp][Nub], Xtra_Spine, Xtra_Neck01, etc. # The index is typically 2 digits (01-08), use \d{0,2} to avoid # swallowing sub-numbers (e.g. Xtra0102 = Xtra01 + sub 02) xtra_m = re.match( r"^Xtra_?(\d{0,2})(?:_?([A-Za-z]+?))?(\d*)$", rest, re.IGNORECASE ) if xtra_m: xtra_num = xtra_m.group(1) xtra_part = (xtra_m.group(2) or "").lower() xtra_num2 = xtra_m.group(3) n = f" {int(xtra_num)}" if xtra_num else "" n2 = f" {int(xtra_num2)}" if xtra_num2 else "" if xtra_part == "opp": result = f"extra opposite{n}" elif xtra_part == "oppnub": # Already handled by Nub stripping result = f"extra opposite{n}" elif xtra_part in _BODY_PART_MAP: result = f"extra {_BODY_PART_MAP[xtra_part]}{n2}{n}" elif xtra_part: result = f"extra {xtra_part}{n2}{n}" else: result = f"extra{n}" else: result = "extra" result = f"{side}{result}" if is_nub: result += " end" return result.strip() # Handle Ponytail with embedded antenna/mandible # Must be checked BEFORE general number extraction because # the side may already have been extracted from embedded _L_/_R_ rest_lower_check = rest.lower().rstrip("_") if rest_lower_check.startswith("ponytail"): # Parse: Ponytail[NN][_]?[L|R][_]?PartName[NN] pony_m = re.match( r"^Ponytail(\d*)[_]?(?:(L|R)[_]?)?([A-Za-z_]*?)(\d*)$", rest, re.IGNORECASE ) if pony_m: pony_idx = pony_m.group(1) # ponytail index pony_side_char = pony_m.group(2) # L or R pony_part = pony_m.group(3).lower().rstrip("_") if pony_m.group(3) else "" pony_num = pony_m.group(4) # trailing number on part # Determine effective side if pony_side_char: eff_side = "left " if pony_side_char.upper() == "L" else "right " else: eff_side = side if pony_part and pony_part not in ("ponytail", ""): # Embedded body part: antenna, mandible, etc. part = _BODY_PART_MAP.get(pony_part, pony_part) p_num = f" {int(pony_num)}" if pony_num else "" result = f"{eff_side}{part}{p_num}" else: # Pure sided ponytail: Ponytail_L01, Ponytail_R03 if pony_num: p_num = f" {int(pony_num)}" elif pony_idx: p_num = f" {int(pony_idx)}" else: p_num = "" result = f"{eff_side}ponytail{p_num}" else: # Simple ponytail with number _, p_num_suffix = _extract_trailing_number(rest) result = f"{side}ponytail{p_num_suffix}" if is_nub: result += " end" return result.strip() # Now extract trailing number for simple names rest_stripped, num_suffix = _extract_trailing_number(rest) rest_lower = rest_stripped.lower().rstrip("_") # Handle Ear (Bip01_R_Ear_01, Bip01__L_Ear_01) if rest_lower.startswith("ear") or rest_lower_check.startswith("ear"): # rest may be 'Ear_01' or 'Ear01' ear_m = re.match(r"^Ear[_]?(\d+)$", rest, re.IGNORECASE) if ear_m: n = str(int(ear_m.group(1))) result = f"{side}ear {n}" else: result = f"{side}ear{num_suffix}" if is_nub: result += " end" return result.strip() # Standard body part lookup part_name = rest_stripped.rstrip("_") part_lower = part_name.lower() # Try direct lookup (rest is already number-stripped, e.g. "Spine") canonical_part = _BODY_PART_MAP.get(part_lower, None) if canonical_part is None: # Try with an inner trailing number: e.g. "Finger01" where # rest_stripped="Finger01" (Nub suffix was the only thing stripped) inner_base, inner_num = _extract_trailing_number(part_lower) canonical_inner = _BODY_PART_MAP.get(inner_base, None) if canonical_inner is not None: canonical_part = canonical_inner num_suffix = inner_num + num_suffix # combine inner + outer else: # CamelCase split: e.g. "UpperArm" -> "upper arm" canonical_part = _camel_to_words(part_name).strip() # Re-extract number from the camel-split result words = canonical_part.split() if words and words[-1].isdigit(): extra_num = f" {int(words[-1])}" canonical_part = " ".join(words[:-1]) num_suffix = extra_num + num_suffix result = f"{side}{canonical_part}{num_suffix}" if is_nub: result += " end" return result.strip() def _handle_bn(raw: str) -> str | None: """Pattern 2: BN_ / Bn_ prefix (~900 occurrences).""" m = re.match(r"^[Bb][Nn]_(.+)$", raw) if not m: return None rest = m.group(1) # Detect Nub suffix is_nub = False if rest.endswith("Nub"): is_nub = True rest = rest[:-3] # Handle BN_Bip01_Pelvis style (nested prefix) if rest.startswith("Bip01_"): inner = _handle_bip01("Bip01_" + rest[6:]) return inner # Handle BN_LWing / BN_RWing (no underscore side marker) wing_m = re.match(r"^(L|R)(Wing)(\d+)$", rest) if wing_m: side = "left " if wing_m.group(1) == "L" else "right " num = str(int(wing_m.group(3))) return f"{side}wing {num}" # Handle BN_LBeard / BN_RBeard / BN_FBeard beard_m = re.match(r"^(L|R|F)(Beard|Eyeball)(\d*)$", rest) if beard_m: side_map = {"L": "left ", "R": "right ", "F": "front "} side = side_map[beard_m.group(1)] part = beard_m.group(2).lower() part = _BODY_PART_MAP.get(part, part) num = f" {int(beard_m.group(3))}" if beard_m.group(3) else "" return f"{side}{part}{num}" # Handle BN_Crab_pincers_L_01 style crab_m = re.match(r"^Crab_pincers_(L|R)_(\d+)$", rest) if crab_m: side = "left " if crab_m.group(1) == "L" else "right " num = str(int(crab_m.group(2))) return f"{side}pincer {num}" # Handle double-underscore: BN__Forearm_L_01, BN__Neck_01, BN__UpperArm_R_01 if rest.startswith("_"): rest = rest.lstrip("_") # Detect side side, rest = _detect_side(rest) # Extract trailing number rest, num_suffix = _extract_trailing_number(rest) # Lookup body part rest_clean = rest.rstrip("_").lower() # Handle compound: Toe01, Toe0, Foot # Strip inner number: Toe01 -> Toe + 1 inner_num_m = re.match(r"^(\w+?)(\d+)$", rest_clean) if inner_num_m: inner_base = inner_num_m.group(1) inner_num = str(int(inner_num_m.group(2))) canonical_part = _BODY_PART_MAP.get(inner_base, inner_base) result = f"{side}{canonical_part} {inner_num}{num_suffix}" else: canonical_part = _BODY_PART_MAP.get(rest_clean, None) if canonical_part is None: canonical_part = _camel_to_words(rest.rstrip("_")).strip() result = f"{side}{canonical_part}{num_suffix}" if is_nub: result += " end" return result.strip() def _handle_jt(raw: str) -> str | None: """Pattern 3: jt_ prefix (Trex, Raptor2/3, ~286 occurrences).""" m = re.match(r"^jt_(.+)$", raw) if not m: return None rest = m.group(1) # Detect side (_L, _R, _C suffix) side, rest = _detect_side(rest) # Extract trailing number rest, num_suffix = _extract_trailing_number(rest) # Handle compound names with CamelCase: ToeMiddle, ClawInner, etc. words = _camel_to_words(rest.rstrip("_")).strip() # Remap known parts tokens = words.split() mapped_tokens = [] for t in tokens: mapped_tokens.append(_BODY_PART_MAP.get(t, t)) canonical = " ".join(mapped_tokens) # Special: "x" suffix on tail (jt_Tail01x_C -> tail 1 secondary) if canonical.endswith("x"): canonical = canonical[:-1].rstrip() + " secondary" result = f"{side}{canonical}{num_suffix}" return result.strip() def _handle_japanese(raw: str) -> str | None: """Pattern 4: Japanese romaji (Alligator, Pirrana, Tukan).""" # Direct match if raw in JAPANESE_MAP: return JAPANESE_MAP[raw] # L_/R_ prefixed romaji: L_kata -> left shoulder m = re.match(r"^(L|R)_(.+)$", raw) if m: side = "left " if m.group(1) == "L" else "right " base = m.group(2) # Try with trailing number: sippo01 -> tail 1 base_word, num = _extract_trailing_number(base) if base_word in JAPANESE_MAP: return f"{side}{JAPANESE_MAP[base_word]}{num}" if base in JAPANESE_MAP: return f"{side}{JAPANESE_MAP[base]}" return None # Numbered romaji: sippo01 -> tail 1 base_word, num = _extract_trailing_number(raw) if base_word in JAPANESE_MAP: return f"{JAPANESE_MAP[base_word]}{num}" return None def _handle_npc(raw: str) -> str | None: """Pattern 5a: NPC_ prefix (SabreToothTiger reskin, ~77 occurrences).""" m = re.match(r"^NPC_(.+)$", raw) if not m: return None rest = m.group(1) # Strip trailing short-code markers like __Head_, __LMag_ (max 6 chars) rest = re.sub(r"__\w{1,6}_$", "", rest) # Detect side via L/R prefix in subname side = "" side_m = re.match(r"^(L|R)_?(.+)$", rest) if side_m and len(side_m.group(2)) > 1: # avoid matching single chars side = "left " if side_m.group(1) == "L" else "right " rest = side_m.group(2) # Special: magic node if "MagicNode" in rest or "MagicEffects" in rest: return f"{side}magic node".strip() # Extract trailing number rest, num_suffix = _extract_trailing_number(rest) # Handle specific NPC compound names rest_lower = rest.rstrip("_").lower() npc_special = { "head": "head", "jaw": "jaw", "nose": "nose", "pelvis": "pelvis", "ribcage": "ribcage", "neckjiggle": "neck jiggle", "armjiggle": "arm jiggle", "armpalm": "palm", "armball": "arm ball", "armcollarbone": "collarbone", "thighjiggle": "thigh jiggle", "legankle": "ankle", "legball": "leg ball", "upperlip": "upper lip", "upperleftlip": "upper left lip", "upperrightlip": "upper right lip", "lowerfrontlip": "lower front lip", "lowerleftlip": "lower left lip", "lowerrightlip": "lower right lip", "eyebrow": "eyebrow", "spine1backjiggle": "spine 1 back jiggle", "spine1jiggle": "spine 1 jiggle", "spine4jiggle": "spine 4 jiggle", } if rest_lower in npc_special: result = f"{side}{npc_special[rest_lower]}{num_suffix}" return result.strip() # CamelCase split and map words = _camel_to_words(rest.rstrip("_")).strip() # Handle embedded side markers: LArm1, RLeg2, etc. inner_side_m = re.match(r"^(l|r)(\w+)$", words.replace(" ", "")) if inner_side_m and not side: inner_s = inner_side_m.group(1) side = "left " if inner_s == "l" else "right " words = _camel_to_words(rest.rstrip("_")[1:]).strip() tokens = words.split() mapped = [] skip_next = False for i, t in enumerate(tokens): if skip_next: skip_next = False continue # Handle "upper arm twist 1" -> "upper arm twist 1" mapped.append(_BODY_PART_MAP.get(t, t)) canonical = " ".join(mapped) result = f"{side}{canonical}{num_suffix}" return result.strip() def _handle_sabrecat(raw: str) -> str | None: """Pattern 5b: Sabrecat_ prefix (SabreToothTiger, ~63 occurrences).""" m = re.match(r"^Sabrecat_(.+)$", raw) if not m: return None rest = m.group(1) # Special: _pelv_ (pelvis) -- check BEFORE stripping short codes if rest.lstrip("_").startswith("pelv"): return "pelvis" # Handle Head sub-parts BEFORE short-code stripping (the trailing # codes carry the actual sub-part info for Head joints) # Patterns: Head__LEye_, Head__REye_, Head__RChk_, Head__LChk_, # Head_Head__LChk_, Head_jaw_, Head_LM01_, Head_RM01_, # HeadLeftEar_LEar_, HeadRightEar_REar_, # Head_EyeLid_HELT_, HeadEyeLid__HELB_ rest_for_head = rest if rest_for_head.startswith("Head"): sub = rest_for_head[4:].strip("_") if not sub: return "head" sub_lower = sub.lower().strip("_") # Try to interpret the head sub-part head_sabrecat_map = { "jaw": "jaw", "leye": "left eye", "reye": "right eye", "lchk": "left cheek", "rchk": "right cheek", "lm01": "left muzzle 1", "rm01": "right muzzle 1", "helt": "upper eyelid", "helb": "lower eyelid", } # Extract the short code from the full sub-part # e.g. "Head__LChk_" -> sub = "Head__LChk", look at last code codes = [c for c in sub.split("_") if c] if codes: last_code = codes[-1].lower() if last_code in head_sabrecat_map: return head_sabrecat_map[last_code] # Check all codes for known head parts for code in codes: cl = code.lower() if cl in head_sabrecat_map: return head_sabrecat_map[cl] # EyeLid patterns if "eyelid" in sub_lower: return "eyelid" # Jaw if "jaw" in sub_lower: return "jaw" # Head (identity) if sub_lower.startswith("head"): inner = sub_lower[4:].strip("_") if not inner: return "head" # Fallback for head sub-parts inner = _camel_to_words(sub.split("_")[0]) return f"head {inner}".strip() # HeadLeftEar / HeadRightEar (without leading Sabrecat_) if rest_for_head.startswith("HeadLeft"): part = rest_for_head[8:].split("_")[0].lower() return f"left {part}" if rest_for_head.startswith("HeadRight"): part = rest_for_head[9:].split("_")[0].lower() return f"right {part}" if rest_for_head.startswith("HeadEyeLid"): return "eyelid" # Extract side and number from trailing short code before stripping code_side = "" code_num = "" code_m = re.search(r"_([LR]?)(\w*?)(\d+)_$", rest) if code_m: if code_m.group(1): code_side = "left " if code_m.group(1) == "L" else "right " code_num = f" {int(code_m.group(3))}" # Strip trailing short code: _LThi_, _RClf_, _Spn0_ etc. rest = re.sub(r"_\w{2,5}_$", "", rest) # Detect side via Left/Right in name, with fallback to short code side side = "" if rest.startswith("Left"): side = "left " rest = rest[4:] elif rest.startswith("Right"): side = "right " rest = rest[5:] elif code_side: side = code_side # Handle Neck, Spine, Ribcage, Tail, Finger, Toe rest, num_suffix = _extract_trailing_number(rest) # Use short-code number as fallback if no number in the main part if not num_suffix and code_num: num_suffix = code_num words = _camel_to_words(rest.rstrip("_")).strip() tokens = words.split() mapped = [] for t in tokens: mapped.append(_BODY_PART_MAP.get(t, t)) canonical = " ".join(mapped) result = f"{side}{canonical}{num_suffix}" return result.strip() def _handle_game_engine(raw: str) -> str | None: """Pattern 5c: Game-engine names (Spider, etc.).""" # Arm[LR]Collarbone, Arm[LR]Claw, Arm[LR]_01_ arm_m = re.match(r"^Arm(L|R)(\w+?)_?$", raw) if arm_m: side = "left " if arm_m.group(1) == "L" else "right " rest = arm_m.group(2) rest, num = _extract_trailing_number(rest) part = _BODY_PART_MAP.get(rest.lower(), _camel_to_words(rest)) return f"{side}arm {part}{num}".strip() # Leg_[LR]_NN_ leg_m = re.match(r"^Leg_(L|R)_(\d+)_$", raw) if leg_m: side = "left " if leg_m.group(1) == "L" else "right " idx = int(leg_m.group(2)) leg_group = idx // 10 seg = idx % 10 return f"{side}leg {leg_group} segment {seg}" # Fang[LR]_NN_ fang_m = re.match(r"^Fang(L|R)_(\d+)_$", raw) if fang_m: side = "left " if fang_m.group(1) == "L" else "right " num = str(int(fang_m.group(2))) return f"{side}fang {num}" # _[LR]Toe[N]_ or _[LR]Jaw_ toe_m = re.match(r"^_(L|R)(Toe|Jaw)(\d*)_$", raw) if toe_m: side = "left " if toe_m.group(1) == "L" else "right " part = toe_m.group(2).lower() num = f" {int(toe_m.group(3))}" if toe_m.group(3) else "" return f"{side}{part}{num}" # _body_ if raw == "_body_": return "body" # NPC_Head__Head_ if raw == "NPC_Head__Head_": return "head" # Elk* prefix (Raindeer-like) elk_m = re.match(r"^Elk(L|R)?(.+)$", raw) if elk_m: side = "" if elk_m.group(1): side = "left " if elk_m.group(1) == "L" else "right " rest = elk_m.group(2) # Handle compound: UpperLip, FrontHoof, etc. rest_lower = rest.lower().rstrip("_") elk_parts = { "pelvis": "pelvis", "ribcage": "ribcage", "scull": "skull", "scullbase": "skull base", "jaw": "jaw", "ear": "ear", "femur": "femur", "tibia": "tibia", "humerus": "humerus", "radius": "radius", "scapula": "scapula", "metacarpus": "metacarpus", "phalanxprima": "phalanx prima", "phalangesmanus": "phalanges manus", "largecannon": "cannon bone", "fronthoof": "front hoof", "rearhoof": "rear hoof", "upperlip": "upper lip", } rest_clean, num = _extract_trailing_number(rest_lower) part = elk_parts.get(rest_clean, None) if part is None: part = elk_parts.get(rest_lower, None) if part is None: part = _camel_to_words(rest).strip() rest_clean2, num = _extract_trailing_number(part) part = rest_clean2 return f"{side}{part}{num}".strip() # Bone[NN] (generic unnamed bones) bone_m = re.match(r"^Bone(\d+)$", raw) if bone_m: return f"bone {int(bone_m.group(1))}" # Tail[NN] standalone tail_m = re.match(r"^Tail(\d+)$", raw) if tail_m: return f"tail {int(tail_m.group(1))}" # body01 body_m = re.match(r"^body(\d+)$", raw) if body_m: return f"body {int(body_m.group(1))}" # Pure numbered: _00, _01, ..., _23 num_m = re.match(r"^_(\d+)$", raw) if num_m: return f"joint {int(num_m.group(1))}" return None def _handle_misc(raw: str) -> str | None: """Catch-all for remaining patterns.""" # IK_Chain01, Dummy01_*, ESI1_*, ProjectileNode_* if raw.startswith("IK_"): return "ik " + _camel_to_words(raw[3:]).strip() if raw.startswith("Dummy01_"): return "dummy " + _camel_to_words(raw[8:]).strip().rstrip("_") if raw.startswith("ESI1_"): return _camel_to_words(raw[5:]).strip() if raw.startswith("ProjectileNode_"): return "projectile " + raw[15:].lower().rstrip("_") # NPC_L_MagicNode__LMag_ if "MagicNode" in raw or "MagicEffects" in raw: side = "left " if "_L_" in raw or "NPC_L" in raw else ( "right " if "_R_" in raw else "") return f"{side}magic node".strip() # BN_center if raw == "BN_center": return "center" return None # --------------------------------------------------------------------------- # PREFIX_RULES: ordered list of (pattern_regex, handler_function) # --------------------------------------------------------------------------- PREFIX_RULES: list[tuple[str, Callable[[str], str | None]]] = [ # Highest priority: exact matches (standalone + Japanese) (r"^(Hips|locator2?|Trajectory|Head|Spine|Handle|Saddle|MESH|N_ALL|" r"MagicEffectsNode|EyesBlue|EyesBlue_2|C_ctrl|BN_P|BN_Shell|BN_Down|" r"BN_Downbody|BN_center|Left\w+|Right\w+)$", lambda raw: _STANDALONE_MAP.get(raw)), # Japanese romaji (check before Bip01 since L_/R_ prefix overlaps) (r"^(?:[LR]_)?(?:koshi|kosi|hara|mune|kubi|atama|kao|ago|kata|hiji|te|" r"momo|hiza|ashi|sippo|obire|sebire|harabire|munabire|era|shiribire|" r"shirihire|shippo|o)\w*$", _handle_japanese), # Bip01_ prefix (most common) (r"^_?Bip01_", _handle_bip01), # BN_ / Bn_ prefix (r"^[Bb][Nn]_", _handle_bn), # jt_ prefix (r"^jt_", _handle_jt), # NPC_ prefix (r"^NPC_", _handle_npc), # Sabrecat_ prefix (r"^Sabrecat_", _handle_sabrecat), # Game-engine patterns (Spider, Elk, Bone, etc.) (r"^(?:Arm[LR]|Leg_[LR]|Fang[LR]|_[LR](?:Toe|Jaw)|_body_|_\d+$|" r"Elk[LR]?|Bone\d|Tail\d|body\d|NPC_Head__Head_)", _handle_game_engine), # Miscellaneous catch-all (r".", _handle_misc), ] # Pre-compile regexes _COMPILED_RULES: list[tuple[re.Pattern, Callable[[str], str | None]]] = [ (re.compile(pattern), handler) for pattern, handler in PREFIX_RULES ] # --------------------------------------------------------------------------- # Main API # --------------------------------------------------------------------------- def canonicalize_zoo_joint(name: str) -> str: """Convert a single Truebones Zoo raw joint name to canonical form. Parameters ---------- name : str Raw joint name as stored in the skeleton .npz file. Returns ------- str Lowercase canonical English name. Falls back to lowercased + cleaned version of the input if no rule matches. """ # Try each rule in priority order for pattern, handler in _COMPILED_RULES: if pattern.search(name): result = handler(name) if result is not None: # Final cleanup: collapse whitespace, strip result = re.sub(r"\s+", " ", result).strip() return result # Fallback: lowercase, strip underscores/trailing _ fallback = name.strip("_").lower() fallback = re.sub(r"[_]+", " ", fallback).strip() return fallback def get_zoo_canonical_names(joint_names: list[str]) -> list[str]: """Map a list of raw Truebones Zoo joint names to canonical form. Parameters ---------- joint_names : list[str] Raw joint names from a skeleton .npz file. Returns ------- list[str] Canonical names in the same order as *joint_names*. """ return [canonicalize_zoo_joint(n) for n in joint_names] # --------------------------------------------------------------------------- # CLI: quick self-test # --------------------------------------------------------------------------- if __name__ == "__main__": import numpy as np from pathlib import Path skel_dir = Path(__file__).resolve().parents[2] / "data" / "processed" / "truebones_zoo" / "skeletons" test_species = ["Dog", "Cat", "Horse", "Eagle", "Anaconda", "Trex", "Spider", "Ant", "Dragon", "Crab"] for species in test_species: skel_path = skel_dir / f"{species}.npz" if not skel_path.exists(): print(f"[SKIP] {species}: file not found") continue data = np.load(str(skel_path), allow_pickle=True) raw_names = [str(n) for n in data["joint_names"]] canonical = get_zoo_canonical_names(raw_names) print(f"\n{'='*60}") print(f" {species} ({len(raw_names)} joints)") print(f"{'='*60}") for r, c in zip(raw_names, canonical): print(f" {r:45s} -> {c}")