agent-manifesto-kit 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +38 -0
  2. package/collection/NOTICE.md +8 -0
  3. package/collection/bundles/blender-3d/README.md +7 -2
  4. package/collection/bundles/blender-3d/agents/visual-reviewer.md +8 -2
  5. package/collection/bundles/blender-3d/skills/blender-asset/SKILL.md +23 -1
  6. package/collection/bundles/blender-3d/skills/blender-asset/workflows/asset.yml +5 -0
  7. package/collection/bundles/blender-3d/skills/blender-mocap-retarget/SKILL.md +25 -0
  8. package/collection/bundles/blender-3d/skills/blender-reference-model/SKILL.md +52 -8
  9. package/collection/bundles/blender-3d/skills/blender-reference-model/scripts/mesh_report.py +62 -8
  10. package/collection/skills/astro-preview/SKILL.md +60 -0
  11. package/collection/skills/kimodo-motion/SKILL.md +101 -0
  12. package/collection/skills/kimodo-motion/agents/openai.yaml +4 -0
  13. package/collection/skills/kimodo-motion/patches/kimodo-cpp-keyposes.patch +398 -0
  14. package/collection/skills/kimodo-motion/scripts/kimodo_motion.py +459 -0
  15. package/collection/skills/kimodo-motion/scripts/kimodo_retarget.py +280 -0
  16. package/collection/skills/kimodo-motion/tests/blender_roundtrip.py +105 -0
  17. package/collection/skills/kimodo-motion/tests/test_kimodo_motion.py +183 -0
  18. package/collection/skills/self-reflection/SKILL.md +121 -0
  19. package/collection/skills/self-reflection/agents/openai.yaml +4 -0
  20. package/collection/skills/self-reflection/assets/report-template.json +8 -0
  21. package/collection/skills/self-reflection/assets/report.html +64 -0
  22. package/collection/skills/self-reflection/references/report-format.md +42 -0
  23. package/collection/skills/self-reflection/scripts/export_claude.py +59 -0
  24. package/collection/skills/self-reflection/scripts/reflect.py +320 -0
  25. package/collection/skills/self-reflection/scripts/report.py +322 -0
  26. package/collection/skills/self-reflection/tests/test_export_claude.py +83 -0
  27. package/collection/skills/self-reflection/tests/test_reflect.py +189 -0
  28. package/collection/skills/self-reflection/tests/test_report.py +250 -0
  29. package/package.json +1 -1
@@ -0,0 +1,459 @@
1
+ #!/usr/bin/env python3
2
+ """Kimodo (NVIDIA text-to-motion, native kimodo.cpp build) motions on Kimodo's own SOMA30 skeleton.
3
+
4
+ python3 kimodo_motion.py generate --prompt TEXT --out DIR [--name NAME] [--seeds 1,2,3] [--frames 75]
5
+ [--start POSES.json:POSE] [--end POSES.json:POSE] [--hold N] [--post S] [--no-effectors]
6
+ DIR/NAME_s<seed>/: the motion, prompt.txt, constraints.json (upstream's key-pose JSON), keypose_error.json
7
+ (the model's own take on its keys, then after post), raw/ (the model's take before post); DIR/provenance.json
8
+ python3 kimodo_motion.py check MOTION_DIR [--constraints FILE] [--model]
9
+ joint-position error on every key frame (world rotations reported); fails above KEY_POS_TOL_M on any joint, or
10
+ with --model (the model's own take: MOTION_DIR/raw when present) above KEY_MEAN_TOL_M on the joints' mean
11
+ python3 kimodo_motion.py sheet MOTION_DIR [...] --out SHEET.png [--frames 8 | --span A:B] [--keys CONSTRAINTS.json]
12
+ front and right views per motion at evenly spaced frames (or every frame A..B: the junction strips), the right
13
+ hand's path, the key poses grey under their frames (the dir's constraints.json, else --keys); needs Pillow
14
+ python3 kimodo_motion.py stats MOTION_DIR
15
+ frames, seconds, root travel, and for reach/draw clips the right hand's closest approach to the right hip
16
+ python3 kimodo_motion.py keypose --rig RIG.blend NAME=ACTION.blend[@FRAME] [...] --out POSES.json [--toe-y M]
17
+ [--prefix mixamorig:]
18
+ game poses as Kimodo key poses: runs kimodo_retarget.py keypose in Blender (see its docstring)
19
+
20
+ A motion dir is what kmd-generate writes: root_positions.f32 (frames x 3, metres, Y up, little-endian f32) and
21
+ local_rotations_xyzw.f32 (frames x 30 x 4, each joint against its parent; identity is the T-pose of OFFSETS). The body
22
+ faces +Z, its left side is +X. Configuration (environment): KIMODO_ROOT (the kimodo.cpp checkout), KIMODO_GENERATE
23
+ (its kmd-generate, default build/kmd-generate), KIMODO_MOTION_GGUF / KIMODO_TEXT_GGUF (model files; these three
24
+ relative to KIMODO_ROOT or absolute), KIMODO_EXPORT_GLB (optional: kimodo.cpp's scripts/export_glb.py, writes animation.glb beside each take),
25
+ BLENDER (executable). Standard library only, except sheet (Pillow).
26
+
27
+ Key poses (the build needs the key-pose patch, see the skill): each key is a `fullbody` entry (every joint's FK
28
+ position, the root height and heading) plus an `end-effector` one on the same frames (EFFECTORS: the hands' and
29
+ feet's global turn; positions alone left the hands 24-39 deg off). Keys are held HOLD frames at either end (a single
30
+ key let a take leave a still pose at full speed). The model still misses its keys by about 2 cm, so post eases
31
+ each key's residual out over POST_S (an offset; a blend toward the static key moved joints 14-20 cm mid-motion).
32
+ """
33
+ import json
34
+ import math
35
+ import os
36
+ import struct
37
+ import subprocess
38
+ import sys
39
+
40
+ FPS = 30
41
+ HERE = os.path.dirname(os.path.abspath(__file__))
42
+ KIMODO_ROOT = os.environ.get("KIMODO_ROOT", "")
43
+ GENERATE = os.environ.get("KIMODO_GENERATE", "build/kmd-generate")
44
+ MOTION_GGUF = os.environ.get("KIMODO_MOTION_GGUF", "models/kimodo-soma-rp-v1.1-f32.gguf")
45
+ TEXT_GGUF = os.environ.get("KIMODO_TEXT_GGUF", "models/Llama-3-Kimodo-Q8_0.gguf")
46
+ BLENDER = os.environ.get("BLENDER", "blender")
47
+ STEPS = 100
48
+ HOLD = 3 # key poses held over this many frames at either end
49
+ EFFECTORS = ["LeftHand", "RightHand", "LeftFoot", "RightFoot"]
50
+ POST_S = 0.3 # post: the model's residual on its keys eased out over this on either side
51
+ KEY_MEAN_TOL_M = 0.03 # the model's own take on its key frames: joints' mean distance off the key (constraints took:
52
+ # about 19 mm measured; the same prompt without keys, 79-289 mm)
53
+ KEY_POS_TOL_M = 0.005 # after post: any joint off its key pose
54
+ TOE_Y = 0.015 # keypose default: Kimodo's own standing takes keep ToeBase about this high
55
+
56
+ # SOMA30 (Kimodo SOMA RP v1.1), copied from kimodo.cpp scripts/export_glb.py (Apache-2.0; names and parents from
57
+ # NVIDIA Kimodo's skeleton definitions). Offsets are parent-local, metres; the Hips entry is its rest height.
58
+ NAMES = ["Hips", "Spine1", "Spine2", "Chest", "Neck1", "Neck2", "Head", "Jaw", "LeftEye", "RightEye", "LeftShoulder",
59
+ "LeftArm", "LeftForeArm", "LeftHand", "LeftHandThumbEnd", "LeftHandMiddleEnd", "RightShoulder", "RightArm",
60
+ "RightForeArm", "RightHand", "RightHandThumbEnd", "RightHandMiddleEnd", "LeftLeg", "LeftShin", "LeftFoot",
61
+ "LeftToeBase", "RightLeg", "RightShin", "RightFoot", "RightToeBase"]
62
+ PARENTS = [-1, 0, 1, 2, 3, 4, 5, 6, 6, 6, 3, 10, 11, 12, 13, 13, 3, 16, 17, 18, 19, 19, 0, 22, 23, 24, 0, 26, 27, 28]
63
+ OFFSETS = [(0.0, 0.988, 0.0), (-0.00013727, 0.0500376256, -0.00053726669), (-1.86574103e-09, 0.0712530139, -0.000298248546),
64
+ (-5.75188398e-09, 0.0755006305, -0.00815970992), (-0.00181676517, 0.263112953, -0.00553348292),
65
+ (-2.85102231e-08, 0.0770939664, 0.0230258546), (-4.5975437e-08, 0.0612891595, 0.0195370861),
66
+ (2.63687901e-05, 0.0047559225, 0.0309494062), (0.0320638079, 0.0538020513, 0.0758688308),
67
+ (-0.0322244017, 0.05361869, 0.0755823359), (0.0162165175, 0.232371641, 0.0511341324),
68
+ (0.149198457, 2.19397873e-08, -0.0550232576), (0.287393078, 2.50268389e-09, -2.58787737e-05),
69
+ (0.270939812, -7.06625108e-09, 2.60897248e-05), (0.122686267, -0.0322017573, 0.0483306876),
70
+ (0.190119595, -0.00312878387, -0.000339570373), (-0.0138011824, 0.231803086, 0.0521415786),
71
+ (-0.150371962, 1.17387901e-07, -0.0554560437), (-0.287366393, 1.87628082e-08, -2.59709359e-05),
72
+ (-0.271336198, -1.16767401e-09, 2.61269368e-05), (-0.122642483, -0.0321145448, 0.0480403904),
73
+ (-0.190005945, -0.00306615542, -0.0003157343), (0.10043214, -0.0843452671, 0.0259565473),
74
+ (-1e-08, -0.432217537, -0.00802912805), (1e-08, -0.421550959, -0.0348152298), (0.0, -0.0505947206, 0.132315294),
75
+ (-0.10047278, -0.0829525995, 0.0262031695), (1e-08, -0.433622059, -0.00805555828),
76
+ (2e-08, -0.421173943, -0.0347839785), (-3.42907669e-09, -0.0507960932, 0.132841956)]
77
+ INDEX = {n: i for i, n in enumerate(NAMES)}
78
+ IDENTITY = (0.0, 0.0, 0.0, 1.0)
79
+
80
+
81
+ def qmul(a, b):
82
+ ax, ay, az, aw = a
83
+ bx, by, bz, bw = b
84
+ return (aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx,
85
+ aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz)
86
+
87
+
88
+ def qinv(q):
89
+ return (-q[0], -q[1], -q[2], q[3])
90
+
91
+
92
+ def qrot(q, v):
93
+ x, y, z, w = q
94
+ vx, vy, vz = v
95
+ tx, ty, tz = 2 * (y * vz - z * vy), 2 * (z * vx - x * vz), 2 * (x * vy - y * vx)
96
+ return (vx + w * tx + y * tz - z * ty, vy + w * ty + z * tx - x * tz, vz + w * tz + x * ty - y * tx)
97
+
98
+
99
+ def qangle(a, b):
100
+ """Degrees between two rotations."""
101
+ return math.degrees(2 * math.acos(min(1.0, abs(sum(x * y for x, y in zip(a, b))))))
102
+
103
+
104
+ def axis_angle(q):
105
+ x, y, z, w = q
106
+ if w < 0:
107
+ x, y, z, w = -x, -y, -z, -w
108
+ n = math.sqrt(x * x + y * y + z * z)
109
+ a = 2 * math.atan2(n, w)
110
+ return (0.0, 0.0, 0.0) if n < 1e-12 else (x / n * a, y / n * a, z / n * a)
111
+
112
+
113
+ def quat(v):
114
+ a = math.sqrt(sum(c * c for c in v))
115
+ if a < 1e-12:
116
+ return IDENTITY
117
+ s = math.sin(a / 2) / a
118
+ return (v[0] * s, v[1] * s, v[2] * s, math.cos(a / 2))
119
+
120
+
121
+ def slerp(a, b, w):
122
+ d = sum(x * y for x, y in zip(a, b))
123
+ if d < 0:
124
+ b, d = tuple(-x for x in b), -d
125
+ if d > 0.9995:
126
+ q = tuple(x + (y - x) * w for x, y in zip(a, b))
127
+ else:
128
+ th = math.acos(d)
129
+ q = tuple((math.sin((1 - w) * th) * x + math.sin(w * th) * y) / math.sin(th) for x, y in zip(a, b))
130
+ n = math.sqrt(sum(x * x for x in q))
131
+ return tuple(x / n for x in q)
132
+
133
+
134
+ def read(path, mode="r"):
135
+ with open(path, mode) as fh:
136
+ return fh.read()
137
+
138
+
139
+ def read_json(path):
140
+ return json.loads(read(path))
141
+
142
+
143
+ def load(motion_dir):
144
+ """(roots [(x, y, z)], rotations [[(x, y, z, w)] * 30]) per frame."""
145
+ raw = read(os.path.join(motion_dir, "root_positions.f32"), "rb")
146
+ roots = [struct.unpack_from("<3f", raw, 12 * f) for f in range(len(raw) // 12)]
147
+ raw = read(os.path.join(motion_dir, "local_rotations_xyzw.f32"), "rb")
148
+ n = len(NAMES)
149
+ rots = [[struct.unpack_from("<4f", raw, 16 * (f * n + j)) for j in range(n)] for f in range(len(raw) // (16 * n))]
150
+ if len(rots) != len(roots):
151
+ raise SystemExit(f"{motion_dir}: {len(roots)} roots but {len(rots)} rotation frames")
152
+ return roots, rots
153
+
154
+
155
+ def save(motion_dir, roots, rots):
156
+ with open(os.path.join(motion_dir, "root_positions.f32"), "wb") as fh:
157
+ fh.write(b"".join(struct.pack("<3f", *r) for r in roots))
158
+ with open(os.path.join(motion_dir, "local_rotations_xyzw.f32"), "wb") as fh:
159
+ fh.write(b"".join(struct.pack("<4f", *q) for frame in rots for q in frame))
160
+
161
+
162
+ def fk(root, rots):
163
+ """World rotations (xyzw) and positions of every joint for one frame."""
164
+ world, pos = [None] * len(NAMES), [None] * len(NAMES)
165
+ for j, p in enumerate(PARENTS):
166
+ if p < 0:
167
+ world[j], pos[j] = tuple(rots[j]), tuple(root)
168
+ else:
169
+ world[j] = qmul(world[p], rots[j])
170
+ o = qrot(world[p], OFFSETS[j])
171
+ pos[j] = (pos[p][0] + o[0], pos[p][1] + o[1], pos[p][2] + o[2])
172
+ return world, pos
173
+
174
+
175
+ def stats(motion_dir):
176
+ roots, rots = load(motion_dir)
177
+ best = (1e9, 0)
178
+ for f in range(len(roots)):
179
+ _, pos = fk(roots[f], rots[f])
180
+ best = min(best, (math.dist(pos[INDEX["RightHand"]], pos[INDEX["RightLeg"]]), f))
181
+ travel = math.dist((roots[0][0], roots[0][2]), (roots[-1][0], roots[-1][2]))
182
+ return {"frames": len(roots), "seconds": round((len(roots) - 1) / FPS, 3), "root_travel_m": round(travel, 3),
183
+ "hand_to_hip_min_m": round(best[0], 3), "hand_to_hip_frame": best[1],
184
+ "hand_to_hip_s": round(best[1] / FPS, 3)}
185
+
186
+
187
+ def pick_pose(spec):
188
+ """POSES.json:NAME -> {"root": [x, y, z], "local_xyzw": [[x, y, z, w] * 30], ...}"""
189
+ path, name = spec.rsplit(":", 1)
190
+ return read_json(path)["poses"][name]
191
+
192
+
193
+ def constraints(keys, effectors=EFFECTORS):
194
+ """[(frame, pose)] as upstream's key-pose JSON: a fullbody entry and, with effectors, an end-effector entry on the
195
+ same frames. XZ relative to the first key's root (upstream canonicalises the first frame to the origin)."""
196
+ x0, z0 = keys[0][1]["root"][0], keys[0][1]["root"][2]
197
+ full = {"type": "fullbody", "frame_indices": [f for f, _ in keys],
198
+ "root_positions": [[p["root"][0] - x0, p["root"][1], p["root"][2] - z0] for _, p in keys],
199
+ "local_joints_rot": [[list(axis_angle(q)) for q in p["local_xyzw"]] for _, p in keys]}
200
+ return [full, dict(full, type="end-effector", joint_names=list(effectors))] if effectors else [full]
201
+
202
+
203
+ def key_poses(path):
204
+ """{frame: (root, local xyzw)} of a constraints file (the last entry wins a frame keyed twice)."""
205
+ return {f: (c["root_positions"][i], [quat(v) for v in c["local_joints_rot"][i]])
206
+ for c in read_json(path) for i, f in enumerate(c["frame_indices"])}
207
+
208
+
209
+ def check(motion_dir, path=None, tol_m=KEY_POS_TOL_M, stat="pos_max_mm"):
210
+ """Per key frame: the generated joint positions against the key's (FK of both) and world rotations. Passes when
211
+ stat stays within tol_m for every key entry; a frame keyed twice reports its worse key."""
212
+ path = path or os.path.join(motion_dir, "constraints.json")
213
+ roots, rots = load(motion_dir)
214
+ report, every = {}, []
215
+ for c in read_json(path):
216
+ for i, f in enumerate(c["frame_indices"]):
217
+ kw, kp = fk(c["root_positions"][i], [quat(v) for v in c["local_joints_rot"][i]])
218
+ gw, gp = fk(roots[f], rots[f])
219
+ err = [math.dist(a, b) for a, b in zip(kp, gp)]
220
+ ang = [qangle(a, b) for a, b in zip(kw, gw)]
221
+ worst, wa = max(range(len(err)), key=err.__getitem__), max(range(len(ang)), key=ang.__getitem__)
222
+ entry = {"pos_max_mm": round(err[worst] * 1000, 1), "pos_max_joint": NAMES[worst],
223
+ "pos_mean_mm": round(sum(err) / len(err) * 1000, 1), "root_mm": round(err[0] * 1000, 1),
224
+ "rot_max_deg": round(ang[wa], 1), "rot_max_joint": NAMES[wa],
225
+ "right_hand_rot_deg": round(ang[INDEX["RightHand"]], 1)}
226
+ every.append(entry)
227
+ if f not in report or entry[stat] > report[f][stat]:
228
+ report[f] = entry
229
+ return all(r[stat] <= tol_m * 1000 for r in every), report
230
+
231
+
232
+ def ease_onto(roots, rots, keys, span):
233
+ """roots/rots moved onto keys {frame: (root, local xyzw)} in place: each key's residual (every joint's local turn,
234
+ the root's offset) added around it, weight 1 on the key falling smoothly to 0 span frames away (or at the next
235
+ key); between two keys the residuals mix by those weights, so the result is continuous and exact on every key.
236
+ Returns the largest joint move (metres)."""
237
+ res = {f: ([a - b for a, b in zip(root, roots[f])], [qmul(k, qinv(q)) for k, q in zip(local, rots[f])])
238
+ for f, (root, local) in keys.items()}
239
+ order = sorted(res)
240
+
241
+ def weight(d, reach):
242
+ x = min(1.0, d / reach)
243
+ return 1.0 - x * x * (3 - 2 * x)
244
+
245
+ moved = 0.0
246
+ for t in range(len(roots)):
247
+ prev = max((f for f in order if f <= t), default=None)
248
+ nxt = min((f for f in order if f >= t), default=None)
249
+ gap = nxt - prev if prev is not None and nxt is not None else None
250
+ reach = min(span, gap) if gap else span
251
+ wp = weight(t - prev, reach) if prev is not None else 0.0
252
+ wn = weight(nxt - t, reach) if nxt is not None and nxt != prev else 0.0
253
+ if wp + wn <= 0.0:
254
+ continue
255
+ a, mix = max(wp, wn), wn / (wp + wn)
256
+ sp, tp = res[prev] if prev is not None else res[nxt]
257
+ sn, tn = res[nxt] if nxt is not None else res[prev]
258
+ before = fk(roots[t], rots[t])[1]
259
+ roots[t] = tuple(r + a * (x + (y - x) * mix) for r, x, y in zip(roots[t], sp, sn))
260
+ rots[t] = [qmul(slerp(IDENTITY, slerp(dp, dn, mix), a), q) for dp, dn, q in zip(tp, tn, rots[t])]
261
+ moved = max(moved, *(math.dist(p, q) for p, q in zip(before, fk(roots[t], rots[t])[1])))
262
+ return moved
263
+
264
+
265
+ def post(motion_dir, window_s=POST_S):
266
+ """The model's take (kept in raw/) eased onto its key poses over window_s. Returns the largest joint move (mm)."""
267
+ raw = os.path.join(motion_dir, "raw")
268
+ os.makedirs(raw)
269
+ for f in ("root_positions.f32", "local_rotations_xyzw.f32"):
270
+ os.replace(os.path.join(motion_dir, f), os.path.join(raw, f))
271
+ roots, rots = load(raw)
272
+ moved = ease_onto(roots, rots, key_poses(os.path.join(motion_dir, "constraints.json")), window_s * FPS)
273
+ save(motion_dir, roots, rots)
274
+ return round(moved * 1000, 1)
275
+
276
+
277
+ def kimodo_path(rel):
278
+ return rel if os.path.isabs(rel) else os.path.join(KIMODO_ROOT, rel)
279
+
280
+
281
+ def generate(prompt, out, name, seeds, frames, start=None, end=None, steps=STEPS, post_s=POST_S, hold=HOLD,
282
+ effectors=EFFECTORS):
283
+ """One motion dir per seed through the local build, with key poses when given (then post); returns
284
+ {dir: (pass, report)} for keyed takes."""
285
+ if not KIMODO_ROOT:
286
+ raise SystemExit("set KIMODO_ROOT to the kimodo.cpp install (build/kmd-generate, models/)")
287
+ if start and end and frames < 2 * hold:
288
+ raise SystemExit(f"{frames} frames cannot hold the start and the end pose {hold} frames each")
289
+ keys = [(f, pick_pose(start)) for f in range(hold)] if start else []
290
+ if end:
291
+ keys += [(frames - hold + f, pick_pose(end)) for f in range(hold)]
292
+ os.makedirs(out, exist_ok=True)
293
+ prov_path = os.path.join(out, "provenance.json")
294
+ prov = read_json(prov_path) if os.path.exists(prov_path) else {
295
+ "generator": "Kimodo (NVIDIA), local kimodo.cpp build with the kimodo-motion key-pose patch",
296
+ "motion_model": MOTION_GGUF, "text_model": TEXT_GGUF, "candidates": {}}
297
+ command = (f"build/kmd-generate MOTION.gguf TEXT.gguf <dir>/prompt.txt {frames} {steps} <seed> <dir>"
298
+ + (" --constraints <dir>/constraints.json" if keys else ""))
299
+ results = {}
300
+ for seed in seeds:
301
+ d = os.path.join(out, f"{name}_s{seed}")
302
+ if os.path.exists(d):
303
+ raise SystemExit(f"exists, choose a new --name: {d}")
304
+ os.makedirs(d)
305
+ with open(os.path.join(d, "prompt.txt"), "w") as fh:
306
+ fh.write(prompt + "\n")
307
+ cmd = [kimodo_path(GENERATE), kimodo_path(MOTION_GGUF), kimodo_path(TEXT_GGUF),
308
+ os.path.join(d, "prompt.txt"), str(frames), str(steps), str(seed), d]
309
+ if keys:
310
+ with open(os.path.join(d, "constraints.json"), "w") as fh:
311
+ json.dump(constraints(keys, effectors), fh)
312
+ cmd += ["--constraints", os.path.join(d, "constraints.json")]
313
+ run = subprocess.run(cmd, capture_output=True, text=True)
314
+ if run.returncode:
315
+ raise SystemExit(f"kmd-generate failed ({run.returncode}): {run.stderr[-2000:]}")
316
+ entry = {"seed": seed, "command": command, "used_as": None}
317
+ if keys:
318
+ entry["keys"] = {"start": start, "end": end, "hold": hold, "effectors": list(effectors)}
319
+ raw_ok, raw = check(d, tol_m=KEY_MEAN_TOL_M, stat="pos_mean_mm")
320
+ moved = post(d, post_s) if post_s else 0.0
321
+ post_ok, final = check(d)
322
+ ok = raw_ok and post_ok
323
+ with open(os.path.join(d, "keypose_error.json"), "w") as fh:
324
+ json.dump({"model": {"tolerance_mean_mm": KEY_MEAN_TOL_M * 1000, "pass": raw_ok, "frames": raw},
325
+ "post": {"window_s": post_s, "largest_move_mm": moved,
326
+ "tolerance_max_mm": KEY_POS_TOL_M * 1000, "pass": post_ok, "frames": final}},
327
+ fh, indent=1)
328
+ entry["keypose_pass"] = ok
329
+ results[d] = (ok, {"model": raw, "post_move_mm": moved, "post": final})
330
+ print(f"{'PASS' if ok else 'FAIL'} {os.path.basename(d)}: model {json.dumps(raw)}; post moved {moved} mm, "
331
+ f"{json.dumps(final)}")
332
+ else:
333
+ print("MOTION", d)
334
+ prov["candidates"][f"{name}_s{seed}"] = entry
335
+ with open(prov_path, "w") as fh: # after each seed: a later failure keeps the earlier entries
336
+ json.dump(prov, fh, indent=2)
337
+ exporter = os.environ.get("KIMODO_EXPORT_GLB")
338
+ if exporter:
339
+ run = subprocess.run([sys.executable, exporter, "--motion-dir", d, "--output",
340
+ os.path.join(d, "animation.glb"), "--model", "soma30", "--fps", str(FPS)],
341
+ capture_output=True, text=True)
342
+ if run.returncode:
343
+ raise SystemExit(f"export_glb failed ({run.returncode}): {run.stderr[-2000:]}")
344
+ return results
345
+
346
+
347
+ def keypose(rig, specs, out, toe_y=TOE_Y, prefix="mixamorig:"):
348
+ """Runs kimodo_retarget.py keypose in Blender on the rig. A separate script on purpose: a launcher that re-ran
349
+ itself in Blender from an `except ImportError` relaunched Blender hundreds of times on one missing module."""
350
+ cmd = [BLENDER, "-b", rig, "--factory-startup", "--python-exit-code", "1", "--python",
351
+ os.path.join(HERE, "kimodo_retarget.py"), "--", "keypose", *specs, "--out", os.path.abspath(out),
352
+ "--toe-y", str(toe_y), "--prefix", prefix]
353
+ run = subprocess.run(cmd, capture_output=True, text=True)
354
+ for line in run.stdout.splitlines():
355
+ if line.startswith(("KEYPOSE", "POSES", "FAIL", "Traceback")) or run.returncode:
356
+ print(line)
357
+ if run.returncode:
358
+ print(run.stderr[-3000:])
359
+ raise SystemExit(run.returncode)
360
+
361
+
362
+ BONES = [(j, p) for j, p in enumerate(PARENTS) if p >= 0 and NAMES[j] not in ("Jaw", "LeftEye", "RightEye")]
363
+
364
+
365
+ def sheet(dirs, out, frames=8, keys_path=None, span=None):
366
+ from PIL import Image, ImageDraw, ImageFont
367
+ cell, pad = 190, 6
368
+ font = ImageFont.load_default()
369
+ rows = []
370
+ for d in dirs:
371
+ roots, rots = load(d)
372
+ own = os.path.join(d, "constraints.json")
373
+ path_ = own if os.path.exists(own) else keys_path
374
+ keys = {f: fk(*k)[1] for f, k in key_poses(path_).items()} if path_ else {}
375
+ picks = (list(range(span[0], min(span[1], len(roots) - 1) + 1)) if span else
376
+ [round(i * (len(roots) - 1) / (frames - 1)) for i in range(frames)])
377
+ prompt_file = os.path.join(d, "prompt.txt")
378
+ prompt = read(prompt_file).strip() if os.path.exists(prompt_file) else ""
379
+ hand = [fk(roots[f], rots[f])[1][INDEX["RightHand"]] for f in range(len(roots))]
380
+ label = os.path.basename(os.path.normpath(d))
381
+ if label == "raw": # generate's raw/ beside its eased take
382
+ label = os.path.basename(os.path.dirname(os.path.normpath(d))) + "/raw"
383
+ row = Image.new("RGB", (cell * (len(picks) + 1), 2 * cell + 28), "white")
384
+ dr = ImageDraw.Draw(row)
385
+ dr.text((4, 4), f"{label}: {prompt}", fill="black", font=font)
386
+ for view in (0, 1): # 0 front (looking at the +Z face: screen x = -X), 1 right side (screen x = +Z)
387
+ def px(p, i, f0):
388
+ sx = -(p[0] - f0[0]) if view == 0 else (p[2] - f0[2])
389
+ return (cell * i + cell / 2 + sx * cell / 2.1, 28 + cell * view + cell - 8 - p[1] * cell / 2.1)
390
+ f0 = roots[0]
391
+ for i, f in enumerate(picks):
392
+ _, pos = fk(roots[f], rots[f])
393
+ floor = 28 + cell * view + cell - 8
394
+ dr.line([(cell * i, floor), (cell * (i + 1) - pad, floor)], fill=(200, 200, 200))
395
+ for j, p in BONES if f in keys else (): # the key pose under its frame, grey
396
+ dr.line([px(keys[f][p], i, f0), px(keys[f][j], i, f0)], fill=(185, 185, 185), width=7)
397
+ for j, p in BONES:
398
+ side = NAMES[j]
399
+ colour = (200, 40, 40) if side.startswith("Right") else (40, 90, 200) if side.startswith("Left") \
400
+ else (40, 40, 40)
401
+ dr.line([px(pos[p], i, f0), px(pos[j], i, f0)], fill=colour, width=3)
402
+ dr.text((cell * i + 4, 28 + cell * view + 4),
403
+ f"{f / FPS:.2f}s f{f} {'front' if view == 0 else 'right'}", fill="black", font=font)
404
+ dr.line([px(p, len(picks), f0) for p in hand], fill=(200, 40, 40), width=2)
405
+ dr.text((cell * len(picks) + 4, 28 + cell * view + 4), "right hand path", fill="black", font=font)
406
+ rows.append(row)
407
+ width = max(r.width for r in rows)
408
+ img = Image.new("RGB", (width, sum(r.height for r in rows)), "white")
409
+ y = 0
410
+ for r in rows:
411
+ img.paste(r, (0, y))
412
+ y += r.height
413
+ img.save(out)
414
+ print("SHEET", out)
415
+
416
+
417
+ def flag(args, name, default=None):
418
+ return args[args.index(name) + 1] if name in args else default
419
+
420
+
421
+ def main(args):
422
+ takes_value = ("--out", "--frames", "--keys", "--span", "--constraints", "--rig", "--toe-y", "--prefix", "--prompt",
423
+ "--name", "--seeds", "--start", "--end", "--hold", "--post")
424
+ positional = [a for i, a in enumerate(args[1:], 1) if not a.startswith("--") and args[i - 1] not in takes_value]
425
+ cmd = args[0] if args else ""
426
+ if cmd == "generate":
427
+ results = generate(flag(args, "--prompt"), flag(args, "--out"), flag(args, "--name", "k"),
428
+ [int(s) for s in flag(args, "--seeds", "1,2,3").split(",")], int(flag(args, "--frames", 75)),
429
+ flag(args, "--start"), flag(args, "--end"), post_s=float(flag(args, "--post", POST_S)),
430
+ hold=int(flag(args, "--hold", HOLD)), effectors=[] if "--no-effectors" in args else EFFECTORS)
431
+ return 0 if all(ok for ok, _ in results.values()) else 1
432
+ if cmd == "check":
433
+ take, cons = positional[0], flag(args, "--constraints")
434
+ if "--model" in args:
435
+ raw = os.path.join(take, "raw")
436
+ cons = cons or os.path.join(take, "constraints.json")
437
+ ok, report = check(raw if os.path.isdir(raw) else take, cons, KEY_MEAN_TOL_M, "pos_mean_mm")
438
+ else:
439
+ ok, report = check(take, cons)
440
+ print("PASS" if ok else "FAIL", json.dumps(report))
441
+ return 0 if ok else 1
442
+ if cmd == "stats":
443
+ for d in positional:
444
+ print(os.path.basename(os.path.normpath(d)), stats(d))
445
+ return 0
446
+ if cmd == "sheet":
447
+ span = tuple(int(v) for v in flag(args, "--span").split(":")) if "--span" in args else None
448
+ sheet(positional, flag(args, "--out"), int(flag(args, "--frames", 8)), flag(args, "--keys"), span)
449
+ return 0
450
+ if cmd == "keypose":
451
+ keypose(flag(args, "--rig"), positional, flag(args, "--out"), float(flag(args, "--toe-y", TOE_Y)),
452
+ flag(args, "--prefix", "mixamorig:"))
453
+ return 0
454
+ print(__doc__)
455
+ return 2
456
+
457
+
458
+ if __name__ == "__main__":
459
+ sys.exit(main(sys.argv[1:]))