File size: 12,177 Bytes
a84fca7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()