File size: 9,499 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
"""Build animation_prompts.json: a text prompt for every clip in animation/.

Step 5, optional. Pulls the human-written captions of T2M4LVO — the annotation
set from *How to Move Your Dragon* (ICML 2025), which describes Truebones
motions but ships no motion data — and attaches them to this dataset's clips.

    https://huggingface.co/datasets/1Konny/t2m4lvo-truebones-zoo

Captions are keyed by the original Truebones filename, so `clips.csv` is what
makes the join exact: source path -> animation clip. 1,088 of the 1,099 clips
get a prompt; the rest are written out with nulls rather than dropped.

Organised like `animation_prompts.json` in the Mixamo set: a flat map from
filename to a small flat record, sorted by key, with absent fields left out
rather than set to null. Which source file was annotated is not repeated here —
`clips.csv` already maps every path in `Truebone_Z-OO/` onto its clip.

One prompt per clip — the source's `short` length and `original` phrasing, in
the wording that names the species. The source also carries three longer
lengths, six further phrasings, and each sentence rewritten with six more
general object labels; `--full` adds all of that to the same file for anyone
who wants it as caption augmentation.

T2M4LVO does not describe nine of the clips — most of them near-motionless
idles, which is what an annotator skips. Those carry a caption written here
instead and are marked `prompt_source: "inferred"` so they can be filtered out.
They are not human annotations and should not be evaluated as if they were.

Each was written from two things: a rendered strip of the clip, and a per-frame
profile of the posed skeleton — every joint's world-space path length over the
whole timeline, split into six spans so the order of events is visible. The
profile is measured on the posed rig rather than read off the rotation curves,
because an Euler channel wrapping from 180 to -180 reads as an enormous move
while the bone barely turns, and several of these clips are quiet enough for that
artefact to dominate. Phrasing follows the same species' existing captions, and each names at
most two things: the pose the animal holds and the one part that moves most.

T2M4LVO is CC-BY-NC-4.0: non-commercial use only, which is narrower than the
rest of this repository.
"""
import collections, csv, difflib, json, os, re, sys
from huggingface_hub import snapshot_download

HERE = os.path.dirname(os.path.abspath(__file__))
SCRIPTS = os.path.dirname(HERE)
ROOT = os.path.dirname(SCRIPTS)

CAPTIONS_REPO = "1Konny/t2m4lvo-truebones-zoo"
# Written from rendered frames, not by an annotator watching playback. Kept in
# the source so a rebuild reproduces them; `prompt_source` marks them apart.
INFERRED = {
    "Ant-Idle_3.fbx":
        "An ant stands in place, working its mandibles.",
    "Centipede-Idle_3.fbx":
        "A centipede stays on the ground, stirring its legs.",
    "Cricket-Idle.fbx":
        "A cricket stands still, slowly sweeping its antennae.",
    "Cricket-Idle_Pissed.fbx":
        "A cricket bristles in place, whipping its antennae.",
    "Fox-Idle_2.fbx":
        "A fox stands still, gently swaying its tail.",
    "Hound-Idle.fbx":
        "A hound stands at attention, almost motionless.",
    "KingCobra-Steady.fbx":
        "A king cobra holds still, flicking its tongue out midway.",
    "KingCobra-Walk.fbx":
        "A king cobra winds its body and tail from side to side.",
    "Trex-Look_Forward.fbx":
        "A tyrannosaurus rex stands facing forward, swinging its tail.",
}

LEVELS = ("short", "mid", "long", "long_rich")
STYLES = ("original", "synonyms", "structure", "voice", "detail", "action", "figurative")
alnum = lambda s: re.sub(r"[^A-Za-z0-9]", "", s).upper()


def slot_of(js, level, style):
    """Index of the sentence that names the actual species, not the alphabetically-first label."""
    pat = re.compile(r"\b%s\b" % re.escape(js["object_name"].strip().lower()))
    hit = [i for i, s in enumerate(js["captions"][level][style]) if pat.search(s.lower())]
    if len(hit) != 1:                       # synonyms/figurative swap the noun ~1-5% of the time
        hit = [i for i, s in enumerate(js["captions"][level]["original"]) if pat.search(s.lower())]
    return hit[0]


def name_variants(sentences, i):
    """The seven object labels the same sentence is written with.

    All seven differ only in the noun phrase, so each is diffed word-wise against
    the one naming the species — whose label is known — and the first replaced
    span is the label. Diffing rather than taking a common prefix keeps names of
    different word counts intact (`hoofed mammal`) and copes with sentences that
    name the animal twice (`a deer ... pushed back by another deer`), where a
    prefix/suffix cut would swallow the whole middle.
    """
    ref = sentences[i].split()
    out = []
    for k, s in enumerate(sentences):
        if k == i:
            out.append(" ".join(ref[1:]).split(" ")[0] if False else None)
            continue
        w = s.split()
        blocks = [b for b in difflib.SequenceMatcher(None, ref, w).get_opcodes()
                  if b[0] == "replace"]
        label = " ".join(w[blocks[0][3]:blocks[0][4]]).strip(" ,.") if blocks else ""
        # `A deer` against `An animal` differs in the article too, so the diff
        # block can start one word early; the article is not part of the label.
        out.append(re.sub(r"^(?:an?|the)\s+", "", label, flags=re.I))
    # the species sentence keeps the label already known for it
    out[i] = None
    return out


def main():
    CAP = os.path.join(snapshot_download(CAPTIONS_REPO, repo_type="dataset",
                                         allow_patterns=["captions/**"]), "captions")
    clips = list(csv.DictReader(open(os.path.join(ROOT, "clips.csv"))))
    src_index = {(alnum(os.path.basename(os.path.dirname(r["file"]))),
                  alnum(os.path.splitext(os.path.basename(r["file"]))[0])): r
                 for r in clips if r["format"] == "fbx"}

    # caption file -> the animation clip it describes, via clips.csv
    hits = collections.defaultdict(list)
    for dp, dn, fn in os.walk(CAP):
        for f in sorted(fn):
            if not f.endswith(".json"):
                continue
            row = src_index.get((alnum(os.path.basename(dp)), alnum(f[:-5])))
            if row and row["animation_file"]:      # skips ALL files and the one T-pose caption
                hits[os.path.basename(row["animation_file"])].append(
                    (os.path.join(dp, f), row["file"]))

    out = {}
    for f in sorted(os.listdir(os.path.join(ROOT, "animation"))):
        if not f.endswith(".fbx"):
            continue
        species = f[:-4].split("-", 1)[0]
        entry = {"species": species, "action": f[:-4].split("-", 1)[1],
                 "object_name": None, "orientation": None, "prompt": None,
                 "prompts": None, "object_name_variants": None,
                 "source_fbx": [], "source_caption": []}
        for path, srcfbx in hits.get(f, []):
            js = json.load(open(path))
            entry["source_caption"].append("captions/" + os.path.relpath(path, CAP))
            entry["source_fbx"].append(srcfbx)
            if entry["prompt"]:                    # a second annotation of the same motion
                entry.setdefault("alt_prompts", []).append(
                    js["captions"]["short"]["original"][slot_of(js, "short", "original")])
                continue
            entry["object_name"] = js["object_name"]
            entry["orientation"] = js["orientation"]
            entry["prompts"] = {lv: {st: js["captions"][lv][st][slot_of(js, lv, st)]
                                     for st in STYLES} for lv in LEVELS}
            entry["prompt"] = entry["prompts"]["short"]["original"]
            v = name_variants(js["captions"]["short"]["original"], slot_of(js, "short", "original"))
            v[v.index(None)] = js["object_name"].strip().lower()
            entry["object_name_variants"] = v
        out[f] = entry

    full = "--full" in sys.argv
    slim = {}
    for k in sorted(out):
        v = out[k]
        rec = {}
        if not v["prompt"] and k in INFERRED:
            rec["prompt"] = INFERRED[k]
            rec["prompt_source"] = "inferred"
        elif v["prompt"]:
            rec["object_name"] = v["object_name"]
            rec["prompt"] = v["prompt"]
            rec["prompt_source"] = "t2m4lvo"
            if v.get("alt_prompts"):
                rec["alt_prompt"] = v["alt_prompts"][0]
            if full:
                rec["object_name_variants"] = v["object_name_variants"]
                rec["prompts"] = v["prompts"]
        slim[k] = dict(sorted(rec.items()))

    dst = os.path.join(ROOT, "animation_prompts.json")
    json.dump(slim, open(dst, "w"), indent=1, ensure_ascii=False)
    have = [k for k, v in slim.items() if v]
    inf = [k for k, v in slim.items() if v.get("prompt_source") == "inferred"]
    print("clips: %d | with a prompt: %d (%d inferred) | without: %d"
          % (len(slim), len(have), len(inf), len(slim) - len(have)))
    print("second annotation:", sum(1 for v in slim.values() if "alt_prompt" in v))
    print("mode: %s" % ("full - all 4 levels x 7 styles" if full else "short/original only"))
    print("written: %s  %.2f MB" % (dst, os.path.getsize(dst) / 1e6))
    print("\nno prompt:", [k for k, v in slim.items() if not v])


if __name__ == "__main__":
    main()