cozyclay 1.9.0 → 2.0.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 (286) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/bin/agent/agent-routes.mjs +74 -70
  3. package/bin/agent/agent-runner.mjs +10 -3
  4. package/bin/agent/motion-runtime.mjs +32 -260
  5. package/bin/agent/providers.mjs +46 -3
  6. package/bin/agent/session-store.mjs +41 -5
  7. package/bin/agent/studio-prompt.mjs +1 -1
  8. package/bin/agent/studio-tools.mjs +48 -11
  9. package/bin/cozyclay.mjs +26 -8
  10. package/bin/live/cli.mjs +22 -3
  11. package/bin/mcp-runtime.mjs +35 -20
  12. package/bin/telemetry-state.mjs +5 -2
  13. package/bin/update-check.mjs +15 -0
  14. package/dist/app/index.html +6 -6
  15. package/dist/assets/analytics-MVZOEW8O.js +1 -0
  16. package/dist/assets/app-C1sdVbg4.css +1 -0
  17. package/dist/assets/app-CA55tcI3.js +4876 -0
  18. package/dist/assets/{demo-B-eg1CT8.js → demo-ByeYp-dY.js} +1 -1
  19. package/dist/assets/{first-shot-handoff-CGgnvNu8.js → first-shot-handoff-DgT28ZiV.js} +1 -1
  20. package/dist/assets/{landing-IbRp3FnQ.js → landing-BaXkpFip.js} +1 -1
  21. package/dist/assets/shot-prompt-CbqWcWYi.css +1 -0
  22. package/dist/assets/shot-prompt-Yrt99wZx.js +17 -0
  23. package/dist/assets/{ticket-BgIzOBOf.js → ticket-BcmsnHn5.js} +1 -1
  24. package/dist/assets/workflow-DRdwoDBT.css +1 -0
  25. package/dist/assets/workflow-dNPGY9xz.js +179 -0
  26. package/dist/cozyclay-package.json +1 -1
  27. package/dist/fonts/IBM-Plex-Sans-OFL.txt +92 -0
  28. package/dist/fonts/JetBrains-Mono-OFL.txt +93 -0
  29. package/dist/fonts/README.md +13 -9
  30. package/dist/fonts/ibm-plex-sans-400-latin.woff2 +0 -0
  31. package/dist/fonts/ibm-plex-sans-500-latin.woff2 +0 -0
  32. package/dist/fonts/ibm-plex-sans-600-latin.woff2 +0 -0
  33. package/dist/fonts/jetbrains-mono-400-latin.woff2 +0 -0
  34. package/dist/fonts/jetbrains-mono-500-latin.woff2 +0 -0
  35. package/dist/index.html +7 -7
  36. package/dist/privacy/index.html +13 -8
  37. package/dist/sitemap.xml +6 -6
  38. package/dist/workflow/index.html +5 -5
  39. package/mcp/LIVE-PROTOCOL.md +1 -1
  40. package/mcp/live-hub.mjs +35 -93
  41. package/mcp/mesh-file.mjs +48 -0
  42. package/mcp/server.mjs +6 -77
  43. package/mcp/tool-handlers.mjs +224 -377
  44. package/package.json +2 -1
  45. package/src/App.jsx +1273 -9075
  46. package/src/analytics.js +393 -9
  47. package/src/app-context.js +211 -0
  48. package/src/app-stage.jsx +25 -24
  49. package/src/ardy/auto-fix-panel.css +108 -0
  50. package/src/ardy/collision-blockers.js +9 -3
  51. package/src/ardy/fix-collisions.js +10 -66
  52. package/src/ardy/ground.js +4 -4
  53. package/src/ardy/ik-drag.js +101 -0
  54. package/src/ardy/ik-key-json.js +43 -0
  55. package/src/ardy/ik.js +122 -76
  56. package/src/ardy/physics-panel.css +2 -0
  57. package/src/ardy/physics-panel.jsx +17 -5
  58. package/src/ardy/platform-fit-panel.css +64 -0
  59. package/src/ardy/platform-fit-panel.jsx +40 -0
  60. package/src/ardy/platform-fit.js +326 -0
  61. package/src/ardy/playback.js +166 -20
  62. package/src/ardy/range-pin.js +299 -0
  63. package/src/ardy/timeline-coordinates.js +26 -0
  64. package/src/ardy/timeline.css +1199 -0
  65. package/src/ardy/timeline.jsx +149 -41
  66. package/src/ardy/waypoints.js +2 -2
  67. package/src/asset-pane.css +462 -0
  68. package/src/asset-pane.jsx +461 -232
  69. package/src/command-bus.js +349 -0
  70. package/src/commands/ai.js +31 -0
  71. package/src/commands/cast.js +140 -0
  72. package/src/commands/elements/character.js +13 -0
  73. package/src/commands/elements/motion.js +14 -0
  74. package/src/commands/elements/object.js +22 -0
  75. package/src/commands/elements/scene.js +16 -0
  76. package/src/commands/elements/shot.js +9 -0
  77. package/src/commands/elements/stage.js +11 -0
  78. package/src/commands/elements.js +155 -0
  79. package/src/commands/export.js +20 -0
  80. package/src/commands/index.js +40 -0
  81. package/src/commands/motion.js +231 -0
  82. package/src/commands/objects.js +174 -0
  83. package/src/commands/project.js +53 -0
  84. package/src/commands/scene.js +81 -0
  85. package/src/commands/shared.js +19 -0
  86. package/src/commands/shot.js +103 -0
  87. package/src/commands/stage.js +17 -0
  88. package/src/commands/view.js +42 -0
  89. package/src/document-store.js +144 -0
  90. package/src/domains/cast.js +1007 -0
  91. package/src/domains/motion.js +3219 -0
  92. package/src/domains/objects.js +932 -0
  93. package/src/domains/scenes.js +817 -0
  94. package/src/domains/shots.js +404 -0
  95. package/src/domains/stage.js +93 -0
  96. package/src/dualview.jsx +113 -57
  97. package/src/facing-marks.js +3 -0
  98. package/src/first-success-guide.jsx +14 -14
  99. package/src/grid-view.js +18 -5
  100. package/src/hierarchy-model.js +24 -16
  101. package/src/hierarchy-panel.css +386 -0
  102. package/src/hierarchy-panel.jsx +150 -21
  103. package/src/{fal-motion-client.js → i2v-motion-client.js} +13 -13
  104. package/src/i2v-motion-studio.jsx +180 -0
  105. package/src/ik-camera.js +3 -0
  106. package/src/main.jsx +6 -0
  107. package/src/motion/generation.js +105 -0
  108. package/src/motion-readiness-ui.jsx +4 -4
  109. package/src/motion-readiness.js +11 -0
  110. package/src/motion-trail.js +366 -9
  111. package/src/object-gizmo.jsx +7 -1
  112. package/src/otio.js +2 -1
  113. package/src/panels/CameraPanel.jsx +60 -0
  114. package/src/panels/CharacterTransformPanel.jsx +48 -0
  115. package/src/panels/EnvironmentPanel.jsx +40 -0
  116. package/src/panels/Foldout.jsx +32 -0
  117. package/src/panels/LightPanel.jsx +24 -0
  118. package/src/panels/ObjectTransformPanel.jsx +554 -0
  119. package/src/panels/PosePanel.jsx +97 -0
  120. package/src/panels/ProjectPanel.jsx +33 -0
  121. package/src/panels/PromptBlocksPanel.jsx +442 -0
  122. package/src/panels/PropsPanel.jsx +70 -0
  123. package/src/panels/ReferenceImageField.jsx +91 -0
  124. package/src/panels/RigControlPanel.jsx +78 -0
  125. package/src/panels/RigPanel.jsx +37 -0
  126. package/src/panels/SubjectBox.jsx +47 -0
  127. package/src/panels/SubjectsPanel.jsx +39 -0
  128. package/src/panels/VideoCapturePanel.jsx +180 -0
  129. package/src/panels/details.css +1171 -0
  130. package/src/panels/motion.css +197 -0
  131. package/src/panels/pose.css +39 -0
  132. package/src/planview.jsx +60 -31
  133. package/src/posestudio.jsx +59 -4
  134. package/src/project-browser.css +1073 -0
  135. package/src/project-browser.jsx +284 -123
  136. package/src/range-pin-object-transform.js +19 -0
  137. package/src/range-pin-panel.css +518 -0
  138. package/src/range-pin-panel.jsx +344 -0
  139. package/src/result-modal.jsx +5 -5
  140. package/src/room.jsx +79 -51
  141. package/src/scene-objects.js +37 -1
  142. package/src/scenes.js +5 -0
  143. package/src/semantic-edit.js +2 -0
  144. package/src/settings-menu.jsx +39 -105
  145. package/src/shell/BottomDock.jsx +450 -0
  146. package/src/shell/DetailsSlot.jsx +513 -0
  147. package/src/shell/LibrarySlot.jsx +86 -0
  148. package/src/shell/MenuBar.jsx +601 -0
  149. package/src/shell/OutlinerSlot.jsx +50 -0
  150. package/src/shell/PreferencesDialog.jsx +538 -0
  151. package/src/shell/PreferencesSlot.jsx +40 -0
  152. package/src/shell/StatusBar.jsx +125 -0
  153. package/src/shell/StudioShell.jsx +92 -0
  154. package/src/shell/TopBar.jsx +129 -0
  155. package/src/shell/ViewportToolbar.jsx +656 -0
  156. package/src/shell/agent-glass.css +296 -0
  157. package/src/shell/dock.css +93 -0
  158. package/src/shell/glass-regions.css +985 -0
  159. package/src/shell/glass.css +687 -0
  160. package/src/shell/log-store.js +52 -0
  161. package/src/shell/mode.css +9 -0
  162. package/src/shell/preferences.css +651 -0
  163. package/src/shell/shell.css +282 -0
  164. package/src/shell/studio-shell-context.js +19 -0
  165. package/src/shell/topbar.css +435 -0
  166. package/src/shell/viewport.css +451 -0
  167. package/src/store/authored-intent.js +22 -0
  168. package/src/store/runtime-adapters.js +92 -0
  169. package/src/store/scene-stage.js +21 -0
  170. package/src/store/use-document-store.js +14 -0
  171. package/src/studio-actions.js +210 -0
  172. package/src/studio-agent-commands.js +41 -271
  173. package/src/studio-agent-context.js +39 -10
  174. package/src/studio-agent-motion.js +122 -373
  175. package/src/studio-agent-protocol.js +67 -31
  176. package/src/studio-app-binding.js +379 -0
  177. package/src/studio-contact-sheet.js +73 -0
  178. package/src/studio-elements.js +58 -51
  179. package/src/styles/themes.css +200 -0
  180. package/src/styles/tokens.css +69 -0
  181. package/src/styles.css +460 -1742
  182. package/src/theme.js +44 -0
  183. package/src/timeline-extent.js +16 -0
  184. package/src/trail-key-conflicts.js +39 -0
  185. package/src/trail-pick.js +59 -0
  186. package/src/ui.jsx +8 -8
  187. package/src/use-case-question.jsx +66 -0
  188. package/src/workflow/AgentPanel.jsx +82 -69
  189. package/src/workflow/agent-client.js +12 -2
  190. package/src/workflow/agent-panel.css +34 -32
  191. package/src/workflow/cozy-scene-node.css +2 -0
  192. package/src/workflow/workflow.css +2 -0
  193. package/tools/ardy/__pycache__/cclay_gvhmr_worker.cpython-313.pyc +0 -0
  194. package/tools/ardy/bridge.mjs +164 -146
  195. package/tools/ardy/visual-qa.mjs +5 -5
  196. package/tools/bench/EXP3.md +61 -0
  197. package/tools/bench/cclay_bench_extract_incam.py +125 -0
  198. package/tools/bench/cclay_bench_extract_obs.py +204 -0
  199. package/tools/bench/cclay_bench_runner.py +42 -0
  200. package/tools/bench/cube-contact.mjs +162 -0
  201. package/tools/bench/exp3.mjs +152 -0
  202. package/tools/bench/extract-bench-lib.mjs +216 -0
  203. package/tools/bench/extract-bench.mjs +302 -0
  204. package/tools/bench/fal-generate.mjs +88 -0
  205. package/tools/bench/fit/README.md +189 -0
  206. package/tools/bench/fit/camera.mjs +59 -0
  207. package/tools/bench/fit/contact.mjs +419 -0
  208. package/tools/bench/fit/footlock.mjs +234 -0
  209. package/tools/bench/fit/motion.mjs +85 -0
  210. package/tools/bench/fit/pin.mjs +27 -0
  211. package/tools/bench/fit/remote.mjs +105 -0
  212. package/tools/bench/fit-bench.mjs +126 -0
  213. package/tools/bench/fit-sanity.mjs +45 -0
  214. package/tools/bench/metrics.mjs +313 -0
  215. package/tools/bench/obs/depth.mjs +258 -0
  216. package/tools/bench/obs/extrinsics.mjs +175 -0
  217. package/tools/bench/obs/fit_mannequin_betas.py +340 -0
  218. package/tools/bench/obs/ground.mjs +294 -0
  219. package/tools/bench/obs/heading.mjs +151 -0
  220. package/tools/bench/obs/ladder.mjs +555 -0
  221. package/tools/bench/obs/mannequin-betas.json +124 -0
  222. package/tools/bench/obs/remote.mjs +83 -0
  223. package/tools/bench/obs/rest_joints.py +52 -0
  224. package/tools/bench/obs/ybot-targets.mjs +49 -0
  225. package/tools/bench/obs-bench.mjs +520 -0
  226. package/tools/bench/score.mjs +343 -0
  227. package/tools/bench/summarize.mjs +86 -0
  228. package/tools/dev/pages/privacy.html +13 -8
  229. package/tools/gt-render/browser.mjs +159 -0
  230. package/tools/gt-render/camera-math.mjs +276 -0
  231. package/tools/gt-render/page.mjs +267 -0
  232. package/tools/gt-render/render.mjs +514 -0
  233. package/tools/gt-render/scene-box.mjs +31 -0
  234. package/tools/gt-render/take-transform.mjs +87 -0
  235. package/tools/morphgs/assets/gen_truth.py +39 -0
  236. package/tools/morphgs/assets/mesh_ori_rig.txt +27 -0
  237. package/tools/morphgs/assets/playback-check.mjs +30 -0
  238. package/tools/morphgs/demo-gate.sh +26 -0
  239. package/tools/morphgs/fbx2morphgs.mjs +68 -0
  240. package/tools/morphgs/morphgs-to-cskel27.mjs +105 -0
  241. package/tools/morphgs/patches/preprocess_src-none-mode.patch +76 -0
  242. package/tools/morphgs/setup-on-cluster.sh +126 -0
  243. package/tools/qa/css-rule-usage.mjs +283 -0
  244. package/tools/qa/studio-control-count.mjs +70 -32
  245. package/tools/run-tests.mjs +134 -12
  246. package/tools/track/DESIGN.md +513 -0
  247. package/tools/track/backfill-provenance.mjs +116 -0
  248. package/tools/track/budget.mjs +8 -0
  249. package/tools/track/check-rig.mjs +209 -0
  250. package/tools/track/diagnostics.schema.json +60 -0
  251. package/tools/track/export-rig.mjs +256 -0
  252. package/tools/track/fallback.mjs +7 -0
  253. package/tools/track/fk-parity-fixture.mjs +161 -0
  254. package/tools/track/gate.mjs +349 -0
  255. package/tools/track/masks.mjs +318 -0
  256. package/tools/track/metrics.mjs +201 -0
  257. package/tools/track/publish-obs.mjs +108 -0
  258. package/tools/track/py/check_env.py +61 -0
  259. package/tools/track/py/eval_lr.py +229 -0
  260. package/tools/track/py/lr_viterbi.py +294 -0
  261. package/tools/track/py/masks.py +405 -0
  262. package/tools/track/py/objective.py +382 -0
  263. package/tools/track/py/rig.py +508 -0
  264. package/tools/track/py/scene.py +326 -0
  265. package/tools/track/py/test_joint_indices.py +123 -0
  266. package/tools/track/py/test_lr_viterbi.py +195 -0
  267. package/tools/track/py/test_masks.py +229 -0
  268. package/tools/track/py/test_rig.py +288 -0
  269. package/tools/track/py/test_scene.py +354 -0
  270. package/tools/track/py/test_track.py +328 -0
  271. package/tools/track/py/track.py +411 -0
  272. package/tools/track/remote.mjs +140 -0
  273. package/tools/track/rig-dump.mjs +227 -0
  274. package/tools/track/run-box-tests.mjs +14 -0
  275. package/tools/track/run-box.mjs +168 -0
  276. package/tools/track/setup-box.sh +59 -0
  277. package/tools/track/study-2d.mjs +728 -0
  278. package/dist/assets/analytics-B1hnH66c.js +0 -1
  279. package/dist/assets/app-BWusbqgO.js +0 -4861
  280. package/dist/assets/app-qKDo4PBX.css +0 -1
  281. package/dist/assets/shot-prompt-CHUtw6af.js +0 -17
  282. package/dist/assets/shot-prompt-C_g2BHVc.css +0 -1
  283. package/dist/assets/workflow-CVwzMhz2.js +0 -179
  284. package/dist/assets/workflow-DsudxKHF.css +0 -1
  285. package/src/fal-motion-studio.jsx +0 -180
  286. package/src/scene-history.js +0 -129
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/env python3
2
+ """Known-character whole-clip fit in the initializer's Studio world frame.
3
+
4
+ Calibration travels with camera.json as tracker.{deltaPx,cameraFixed,endpoints}.
5
+ Endpoints, when supplied, are {a:{rotMats,rootPos}, b:{rotMats,rootPos}} in that
6
+ same frame. No re-anchoring or endpoint fabrication occurs at this boundary.
7
+ Exit 0: motion and diagnostics; exit 3: failed fit, diagnostics only;
8
+ exit 2: malformed input, diagnostics only. --iterations 0 is an exact NPZ
9
+ round-trip for coordinate-contract QA, not an optimized-fit acceptance test.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
15
+
16
+ import argparse
17
+ import json
18
+ from pathlib import Path
19
+ import random
20
+ import sys
21
+ import time
22
+
23
+ import cv2
24
+ import numpy as np
25
+ import torch
26
+
27
+ from lr_viterbi import STATE_NAMES, solve_lr_viterbi
28
+ from objective import (ABLATIONS, COCO_JOINTS, ClipObjective, MaskEvidence,
29
+ project, slice_boxes)
30
+ from rig import RigError, State, cskel27_fk, load_rig
31
+ from scene import (SceneError, box_tensors, foot_points, load_scene,
32
+ penetration_stats, ray_occlusion, stance_hmm)
33
+
34
+ SCHEDULE = (('root', 150, 1e-2, 10), ('pose', 300, 5e-3, 10), ('refine', 200, 1e-3, 30))
35
+ MAX_RESERVED_MIB = 5632
36
+
37
+
38
+ class TrackError(ValueError):
39
+ def __init__(self, code, detail):
40
+ super().__init__(f'{code}: {detail}')
41
+ self.code = code
42
+
43
+
44
+ def finite_array(value, shape, label):
45
+ a = np.asarray(value, dtype=np.float32)
46
+ if a.shape != shape or not np.isfinite(a).all():
47
+ raise TrackError('bad-input', f'{label}: expected finite {shape}, got {a.shape}')
48
+ return a
49
+
50
+
51
+ def read_inputs(args):
52
+ with np.load(args.obs, allow_pickle=False) as z:
53
+ kp = np.asarray(z['kp2d'], dtype=np.float32)
54
+ if kp.ndim != 3 or kp.shape[1:] != (17, 3) or len(kp) < 1:
55
+ raise TrackError('bad-input', 'kp2d must be nonempty T x 17 x 3')
56
+ frames = len(kp)
57
+ finite_array(kp[..., :2], (frames, 17, 2), 'kp2d coordinates')
58
+ # ViTPose confidence is the raw (flip-averaged) heatmap peak, a Gaussian
59
+ # regression target of height 1, not a probability: it can overshoot 1.
60
+ # Only the weight is repaired; coordinates stay strictly validated.
61
+ conf = kp[..., 2]
62
+ finite = np.isfinite(conf)
63
+ sanitized = {'input.confidenceNonFinite': int((~finite).sum()),
64
+ 'input.confidenceAboveOne': int((finite & (conf > 1)).sum()),
65
+ 'input.confidenceBelowZero': int((finite & (conf < 0)).sum())}
66
+ kp[..., 2] = np.clip(np.where(finite, conf, 0), 0, 1)
67
+ fps = float(np.asarray(z['fps']).item())
68
+ if not np.isfinite(fps) or fps <= 0 or not fps.is_integer():
69
+ raise TrackError('bad-input', 'fps must be a positive integer')
70
+ finite_array(z['K'], (3, 3), 'obs.K')
71
+ bbx = finite_array(z['bbx_xys'], (frames, 3), 'bbx_xys')
72
+ if (bbx[:, 2] <= 0).any():
73
+ raise TrackError('bad-input', 'bbx size must be positive')
74
+ with np.load(args.init, allow_pickle=False) as z:
75
+ motion = {k: z[k].copy() for k in z.files}
76
+ finite_array(motion['local_rot_mats'], (frames, 27, 3, 3), 'local_rot_mats')
77
+ finite_array(motion['root_positions'], (frames, 3), 'root_positions')
78
+ finite_array(motion['posed_joints'], (frames, 27, 3), 'posed_joints')
79
+ rot = motion['local_rot_mats']
80
+ if not np.allclose(rot.swapaxes(-1, -2) @ rot, np.eye(3), atol=1e-3) or (np.linalg.det(rot) < 0.99).any():
81
+ raise TrackError('bad-input', 'local_rot_mats must lie on SO(3)')
82
+ bone_scale = motion.get('bone_scale')
83
+ if bone_scale is not None:
84
+ finite_array(bone_scale, (27,), 'bone_scale')
85
+ if (bone_scale <= 0).any():
86
+ raise TrackError('bad-input', 'bone_scale must be positive')
87
+ camera = json.loads(Path(args.camera).read_text())
88
+ K = finite_array(camera['K'], (3, 3), 'camera.K')
89
+ w = finite_array(camera['worldToCamera'], (4, 4), 'worldToCamera')
90
+ if not np.allclose(w[3], [0, 0, 0, 1]) or not np.allclose(w[:3, :3].T @ w[:3, :3], np.eye(3), atol=1e-5):
91
+ raise TrackError('bad-input', 'camera extrinsics must be rigid')
92
+ if K[0, 0] <= 0 or K[1, 1] <= 0:
93
+ raise TrackError('bad-input', 'camera focal length must be positive')
94
+ width, height = camera['width'], camera['height']
95
+ if not isinstance(width, int) or not isinstance(height, int) or min(width, height) < 4:
96
+ raise TrackError('bad-input', 'camera dimensions must be positive integers >=4')
97
+ config = camera.get('tracker', {})
98
+ delta = args.delta_px if args.delta_px is not None else config.get('deltaPx', 5.708)
99
+ if not isinstance(delta, (int, float)) or not np.isfinite(delta) or delta <= 0:
100
+ raise TrackError('bad-input', 'deltaPx must be finite and positive')
101
+ fixed = config.get('cameraFixed', True)
102
+ if not isinstance(fixed, bool):
103
+ raise TrackError('bad-input', 'cameraFixed must be boolean')
104
+ with np.load(args.masks, allow_pickle=False) as z:
105
+ prob = finite_array(z['prob'], (frames, height // 2, width // 2), 'prob')
106
+ if ((prob < 0) | (prob > 1)).any():
107
+ raise TrackError('bad-input', 'mask probabilities must lie in [0,1]')
108
+ if not Path(args.video).is_file():
109
+ raise TrackError('bad-input', 'video file does not exist')
110
+ endpoints = {}
111
+ ep = config.get('endpoints', {})
112
+ if not isinstance(ep, dict):
113
+ raise TrackError('bad-input', 'endpoints must be an object with a and/or b')
114
+ for name, frame in [('a', 0), ('b', frames - 1)]:
115
+ if name in ep:
116
+ e = ep[name]
117
+ endpoints[frame] = (finite_array(e['rootPos'], (3,), f'{name}.rootPos'),
118
+ finite_array(np.asarray(e['rotMats']).reshape(27, 3, 3), (27, 3, 3), f'{name}.rotMats'))
119
+ kp[:, :5, 2] = 0
120
+ return kp, fps, motion, bone_scale, camera, prob, delta, fixed, endpoints, sanitized
121
+
122
+
123
+ def blank_diagnostics(frames=1, fps=24):
124
+ return dict(version=1, frames=frames, fps=fps,
125
+ occluded=[[False] * 27 for _ in range(frames)],
126
+ lrState=['identity'] * frames, lrMargin=[0.0] * frames,
127
+ ambiguous=[True] * frames,
128
+ stance=dict(left=[False] * frames, right=[False] * frames),
129
+ penetration=dict(maxBoxCm=0.0, maxFloorCm=0.0, frames=[]),
130
+ nuisance=dict(scale=1.0, cameraDeltaDeg=[0.0, 0.0], fovDeltaPct=0.0),
131
+ stageLosses={}, runtime=dict(trackerSeconds=0.0, peakReservedMiB=0.0), failure=None)
132
+
133
+
134
+ def windows(frames):
135
+ if frames <= 240:
136
+ return [(0, frames)]
137
+ out, start = [], 0
138
+ while start < frames:
139
+ end = min(start + 120, frames)
140
+ out.append((start, end))
141
+ if end == frames:
142
+ break
143
+ start = end - 16
144
+ return out
145
+
146
+
147
+ def schedule(iterations):
148
+ if iterations is None:
149
+ return SCHEDULE
150
+ counts = [iterations * 150 // 650, iterations * 450 // 650]
151
+ lengths = [counts[0], counts[1] - counts[0], iterations - counts[1]]
152
+ return tuple((name, n, lr, pen) for (name, _, lr, pen), n in zip(SCHEDULE, lengths))
153
+
154
+
155
+ def identity_labels(frames):
156
+ """The detector's own left/right labelling, used when Viterbi is ablated."""
157
+ return dict(path=np.full(frames, STATE_NAMES.index('identity')),
158
+ assignments=np.tile(np.arange(17), (frames, 1)),
159
+ margins=np.zeros(frames), ambiguous=np.zeros(frames, dtype=bool))
160
+
161
+
162
+ @torch.no_grad()
163
+ def labels(objective, state, nuisance, kp, start, end):
164
+ joints, _ = cskel27_fk(state, objective.bone_scale, objective.rig)
165
+ joints = state.transl[:, None] + (joints - state.transl[:, None]) * (1 + nuisance[0])
166
+ uv, depth = project(joints[:, COCO_JOINTS], objective.camera, nuisance)
167
+ # Geometric box occlusion is always reported; the fit uses it only when
168
+ # the 'occlusion' component is enabled.
169
+ hidden = ray_occlusion(joints, objective.camera_pos, slice_boxes(objective.boxes, start, end))
170
+ visible = depth > 0
171
+ if 'occlusion' in objective.components:
172
+ visible = ~hidden[:, COCO_JOINTS] & visible
173
+ if 'viterbi' in objective.components:
174
+ result = solve_lr_viterbi(kp, uv.cpu().numpy(), visibility=visible.cpu().numpy(), deltaPx=objective.delta)
175
+ else:
176
+ result = identity_labels(end - start)
177
+ assigned = kp[np.arange(end - start)[:, None], result['assignments']]
178
+ stance = stance_hmm(foot_points(joints).cpu(), objective.fps, slice_boxes(objective.boxes, start, end))
179
+ return (torch.as_tensor(assigned, device=joints.device),
180
+ torch.as_tensor(stance, device=joints.device), result, hidden)
181
+
182
+
183
+ def optimize(objective, state, nuisance, kp, masks, fixed, iterations, diagnostics, started):
184
+ frames = len(kp)
185
+ for stage, steps, lr, pen in schedule(iterations):
186
+ if not steps:
187
+ continue
188
+ # One shared per-clip nuisance tensor, even when trajectories use windows.
189
+ # A complete stage visits all windows before the next discrete update.
190
+ chunks = windows(frames)
191
+ total_steps = steps * len(chunks)
192
+ print(f'[track] stage {stage} 0/{total_steps}', flush=True)
193
+ assigned_all, stance_all, _, hidden = labels(objective, state, nuisance, kp, 0, frames)
194
+ articulation_all = None if stage == 'root' else objective.articulation_observation(
195
+ state, nuisance, assigned_all)
196
+ support_all = None
197
+ if stage != 'root' and 'contacts' in objective.components:
198
+ support_all = objective.support_observation(state, nuisance, assigned_all, stance_all, hidden)
199
+ diagnostics['stageLosses'][f'{stage}.supportFootFramesTotal'] = float(support_all[1].sum())
200
+ for window_index, (start, end) in enumerate(chunks):
201
+ local = State(*(getattr(state, name)[start:end].detach().clone().requires_grad_(True)
202
+ for name in ('transl', 'root6d', 'local6d')))
203
+ local.local6d.requires_grad_(stage != 'root')
204
+ objective.masks = masks.window(start, end, state.transl.device)
205
+ assigned, stance = assigned_all[start:end], stance_all[start:end]
206
+ support = None if support_all is None else tuple(x[start:end] for x in support_all)
207
+ articulation = None if articulation_all is None else tuple(x[start:end] for x in articulation_all)
208
+ params = [local.transl, local.root6d]
209
+ if stage != 'root':
210
+ params.append(local.local6d)
211
+ if not fixed:
212
+ params.append(nuisance)
213
+ optimizer = torch.optim.Adam(params, lr=lr)
214
+ for iteration in range(steps):
215
+ optimizer.zero_grad(set_to_none=True)
216
+ trust_weight = 0.0 if stage == 'root' else 0.1
217
+ if stage == 'refine':
218
+ trust_weight *= 1 - iteration / max(1, steps - 1)
219
+ loss, terms = objective(local, nuisance, start, end, assigned, stance, pen,
220
+ trust_weight, support=support, articulation=articulation)
221
+ if not torch.isfinite(loss):
222
+ raise TrackError('non-finite', 'objective is not finite')
223
+ loss.backward()
224
+ if not all(p.grad is not None and torch.isfinite(p.grad).all() for p in params):
225
+ raise TrackError('non-finite', 'gradient is not finite')
226
+ optimizer.step()
227
+ with torch.no_grad():
228
+ nuisance.clamp_(nuisance.new_tensor([-0.1, -2, -2, -2]), nuisance.new_tensor([0.1, 2, 2, 2]))
229
+ done = window_index * steps + iteration + 1
230
+ if done % 50 == 0 or iteration == steps - 1:
231
+ print(f'[track] stage {stage} {done}/{total_steps}', flush=True)
232
+ if time.monotonic() - started > max(300, 1.5 * frames + 120):
233
+ raise TrackError('runtime-budget', 'tracker time budget exhausted')
234
+ if state.transl.is_cuda and torch.cuda.max_memory_reserved() > MAX_RESERVED_MIB * 1024 ** 2:
235
+ raise TrackError('memory-budget', 'reserved memory exceeded 5632 MiB')
236
+ diagnostics['stageLosses'].update({f'{stage}.{k}': float(v.detach()) for k, v in terms.items()})
237
+ with torch.no_grad():
238
+ for name in ('transl', 'root6d', 'local6d'):
239
+ destination, source = getattr(state, name), getattr(local, name)
240
+ if window_index:
241
+ ramp = torch.arange(1, 17, device=source.device, dtype=source.dtype) / 17
242
+ ramp = ramp.reshape((16,) + (1,) * (source.ndim - 1))
243
+ destination[start:start + 16].lerp_(source[:16], ramp)
244
+ destination[start + 16:end].copy_(source[16:])
245
+ else:
246
+ destination[start:end].copy_(source)
247
+ print(f'[track] {end} / {frames}', flush=True)
248
+
249
+
250
+ def sample_iou(uv, visible, mask):
251
+ """Non-rendering occupancy estimate for rejection only, not a fitted loss.
252
+
253
+ Dense surface point splats with a one-pixel footprint approximate the
254
+ half-resolution occupied region; this statistic is explicitly named in
255
+ stageLosses and is not the independent benchmark silhouette score.
256
+ """
257
+ h, w = mask.shape
258
+ image = np.zeros((h, w), np.uint8)
259
+ xy = np.floor(uv[visible]).astype(np.int64)
260
+ inside = (xy[:, 0] >= 0) & (xy[:, 0] < w) & (xy[:, 1] >= 0) & (xy[:, 1] < h)
261
+ xy = xy[inside]
262
+ image[xy[:, 1], xy[:, 0]] = 1
263
+ image = cv2.dilate(image, np.ones((3, 3), np.uint8)).astype(bool)
264
+ union = (image | mask).sum()
265
+ return float((image & mask).sum() / union) if union else 0.0
266
+
267
+
268
+ @torch.no_grad()
269
+ def finish(objective, state, nuisance, kp, masks, diagnostics):
270
+ joints_out, errors, ious, max_box, max_floor, pen_frames = [], [], [], 0.0, 0.0, []
271
+ assigned_all, stance, lr, hidden_all = labels(objective, state, nuisance, kp, 0, len(kp))
272
+ diagnostics['occluded'] = hidden_all.cpu().tolist()
273
+ diagnostics['lrState'] = [STATE_NAMES[i] for i in lr['path']]
274
+ diagnostics['lrMargin'] = lr['margins'].tolist()
275
+ diagnostics['ambiguous'] = lr['ambiguous'].tolist()
276
+ diagnostics['stance']['left'] = stance[:, 0].cpu().tolist()
277
+ diagnostics['stance']['right'] = stance[:, 1].cpu().tolist()
278
+ for start, end in windows(len(kp)):
279
+ local = State(*(getattr(state, name)[start:end] for name in ('transl', 'root6d', 'local6d')))
280
+ joints, verts = objective.geometry(local, nuisance)
281
+ assigned, hidden = assigned_all[start:end], hidden_all[start:end]
282
+ uv, depth = project(joints[:, COCO_JOINTS], objective.camera, nuisance)
283
+ active = (~hidden[:, COCO_JOINTS] & (depth > 0) & (assigned[..., 2] > 0)).cpu().numpy()
284
+ errors.extend((uv - assigned[..., :2]).norm(dim=-1).cpu().numpy()[active].tolist())
285
+ samples = (verts[:, objective.faces] * objective.bary[None, :, :, None]).sum(-2)
286
+ pixels, depth = project(samples, objective.camera, nuisance)
287
+ visible = (~ray_occlusion(samples, objective.camera_pos, slice_boxes(objective.boxes, start, end)) & (depth > 0)).cpu().numpy()
288
+ pixels = pixels.cpu().numpy() * masks.ratio
289
+ offset = 0 if start == 0 else 16
290
+ ious.extend(sample_iou(pixels[t], visible[t], masks.binary[start + t]) for t in range(offset, end - start))
291
+ joints_out.append(joints[offset:].cpu().numpy())
292
+ stats = penetration_stats(verts, slice_boxes(objective.boxes, start, end))
293
+ max_box, max_floor = max(max_box, stats['maxBoxCm']), max(max_floor, stats['maxFloorCm'])
294
+ pen_frames.extend(start + i for i in stats['frames'])
295
+ diagnostics['penetration'] = dict(maxBoxCm=max_box, maxFloorCm=max_floor, frames=sorted(set(pen_frames)))
296
+ diagnostics['stageLosses']['visibleKeypointMedianPx'] = float(np.median(errors)) if errors else 0.0
297
+ diagnostics['stageLosses']['sampleMaskIoUMean'] = float(np.mean(ious))
298
+ diagnostics['nuisance'] = dict(scale=1 + float(nuisance[0]), cameraDeltaDeg=nuisance[1:3].cpu().tolist(), fovDeltaPct=float(nuisance[3]))
299
+ if not errors:
300
+ diagnostics['failure'] = 'no-evidence'
301
+ elif np.median(errors) > 3 * objective.delta:
302
+ diagnostics['failure'] = 'keypoint-residual'
303
+ elif np.mean(ious) < 0.5:
304
+ diagnostics['failure'] = 'mask-mismatch'
305
+ return np.concatenate(joints_out)
306
+
307
+
308
+ def run(args):
309
+ started = time.monotonic()
310
+ out = Path(args.out)
311
+ out.mkdir(parents=True, exist_ok=True)
312
+ # A failed request cannot leave a previous successful motion behind.
313
+ (out / 'motion.npz').unlink(missing_ok=True)
314
+ diagnostics = blank_diagnostics()
315
+ ablation = {f'ablation.{args.track_ablate}': 1.0}
316
+ diagnostics['stageLosses'].update(ablation)
317
+ code = 0
318
+ try:
319
+ random.seed(0)
320
+ np.random.seed(0)
321
+ torch.manual_seed(0)
322
+ torch.use_deterministic_algorithms(True, warn_only=True)
323
+ torch.set_num_threads(4)
324
+ torch.backends.cuda.matmul.allow_tf32 = False
325
+ torch.backends.cudnn.allow_tf32 = False
326
+ torch.backends.cudnn.benchmark = False
327
+ kp, fps, motion, bone_scale, camera, prob, delta, fixed, endpoints, sanitized = read_inputs(args)
328
+ diagnostics = blank_diagnostics(len(kp), fps)
329
+ diagnostics['stageLosses'].update(ablation, **sanitized)
330
+ if any(sanitized.values()):
331
+ print('[track] sanitized keypoint confidences ' + json.dumps(sanitized), flush=True)
332
+ if not (kp[..., 2] > 0).any():
333
+ raise TrackError('no-evidence', 'no confident body observations')
334
+ device = 'cuda' if torch.cuda.is_available() and args.device != 'cpu' else 'cpu'
335
+ if args.device == 'cuda' and device != 'cuda':
336
+ raise TrackError('device-unavailable', 'CUDA requested but unavailable')
337
+ if device == 'cuda':
338
+ torch.cuda.empty_cache()
339
+ torch.cuda.reset_peak_memory_stats()
340
+ torch.cuda.set_per_process_memory_fraction(MAX_RESERVED_MIB * 1024 ** 2 / torch.cuda.get_device_properties(0).total_memory)
341
+ rig = load_rig(args.rig, device=device)
342
+ state = State.from_motion(motion['local_rot_mats'], motion['root_positions'], device=device)
343
+ boxes = box_tensors(load_scene(args.scene), len(kp), device=device)
344
+ masks = MaskEvidence(prob, camera['width'], camera['height'])
345
+ endpoints = {t: tuple(torch.as_tensor(p, device=device) for p in pose) for t, pose in endpoints.items()}
346
+ nuisance = torch.zeros(4, device=device, requires_grad=not fixed)
347
+ objective = ClipObjective(rig, bone_scale, camera, boxes, None, kp, fps, delta, endpoints, state,
348
+ components=ABLATIONS[args.track_ablate])
349
+ optimize(objective, state, nuisance, kp, masks, fixed, args.iterations, diagnostics, started)
350
+ posed = finish(objective, state, nuisance, kp, masks, diagnostics)
351
+ if args.iterations == 0:
352
+ diagnostics['failure'] = None
353
+ elif not diagnostics['failure']:
354
+ motion['local_rot_mats'] = state.local_rot_mats().detach().cpu().numpy().astype(np.float32)
355
+ motion['root_positions'] = state.transl.cpu().numpy().astype(np.float32)
356
+ motion['posed_joints'] = posed.astype(np.float32)
357
+ if float(nuisance[0]) != 0:
358
+ motion['bone_scale'] = np.asarray(bone_scale if bone_scale is not None else np.ones(27), np.float32) * (1 + float(nuisance[0]))
359
+ motion['fps'] = np.asarray(int(fps), dtype=np.int32)
360
+ if not diagnostics['failure']:
361
+ np.savez(out / 'motion.npz', **motion)
362
+ else:
363
+ code = 3
364
+ except (TrackError, RigError, SceneError) as error:
365
+ diagnostics['failure'] = error.code
366
+ code = 3 if error.code in ('no-evidence', 'non-finite', 'runtime-budget', 'memory-budget', 'device-unavailable') else 2
367
+ print(f'[track] {error}', file=sys.stderr, flush=True)
368
+ except (OSError, ValueError, KeyError, TypeError) as error:
369
+ diagnostics['failure'] = 'bad-input'
370
+ code = 2
371
+ print(f'[track] bad-input: {error}', file=sys.stderr, flush=True)
372
+ except torch.cuda.OutOfMemoryError as error:
373
+ diagnostics['failure'] = 'memory-budget'
374
+ code = 3
375
+ print(f'[track] memory-budget: {error}', file=sys.stderr, flush=True)
376
+ except Exception:
377
+ # Preserve a failed transaction even for an unexpected dependency bug;
378
+ # the traceback is surfaced, never converted into a successful report.
379
+ import traceback
380
+ diagnostics['failure'] = 'internal-error'
381
+ code = 3
382
+ traceback.print_exc()
383
+ finally:
384
+ if code:
385
+ (out / 'motion.npz').unlink(missing_ok=True)
386
+ if torch.cuda.is_initialized():
387
+ torch.cuda.synchronize()
388
+ diagnostics['runtime']['peakReservedMiB'] = torch.cuda.max_memory_reserved() / 1024 ** 2
389
+ diagnostics['runtime']['trackerSeconds'] = time.monotonic() - started
390
+ (out / 'diagnostics.json').write_text(json.dumps(diagnostics, allow_nan=False, indent=2) + '\n')
391
+ print('[track] result ' + json.dumps(dict(failure=diagnostics['failure'], **diagnostics['runtime'])), flush=True)
392
+ return code
393
+
394
+
395
+ def parse_args(argv=None):
396
+ parser = argparse.ArgumentParser(description=__doc__)
397
+ for name in ('video', 'obs', 'masks', 'init', 'camera', 'scene', 'rig', 'out'):
398
+ parser.add_argument('--' + name, required=True)
399
+ parser.add_argument('--iterations', type=int, default=None)
400
+ parser.add_argument('--delta-px', type=float)
401
+ parser.add_argument('--device', choices=('auto', 'cpu', 'cuda'), default='auto')
402
+ parser.add_argument('--track-ablate', choices=tuple(ABLATIONS), default='full',
403
+ help='fit components: kp-only < silhouette < viterbi < contacts < full')
404
+ args = parser.parse_args(argv)
405
+ if args.iterations is not None and args.iterations < 0:
406
+ parser.error('--iterations must be nonnegative')
407
+ return args
408
+
409
+
410
+ if __name__ == '__main__':
411
+ raise SystemExit(run(parse_args()))
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ /** Remote execution boundary for the known-character tracker. */
3
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+ import { runBox } from "./run-box.mjs";
6
+ import { trackerBudgetMs } from "./budget.mjs";
7
+
8
+ /** Parse the two progress formats emitted by track.py. */
9
+ export function parseProgressLine(line) {
10
+ const text = String(line).trim();
11
+ let match = /^\[track\]\s+stage\s+(\S+)\s+(\d+)\/(\d+)\s*$/.exec(text);
12
+ if (match) {
13
+ const current = Number(match[2]), total = Number(match[3]);
14
+ return { kind: "stage", stage: match[1], current, total, fraction: total > 0 ? current / total : 0 };
15
+ }
16
+ match = /^\[track\]\s+(\d+)\s*\/\s*(\d+)\s*$/.exec(text);
17
+ if (match) {
18
+ const current = Number(match[1]), total = Number(match[2]);
19
+ return { kind: "frame", current, total, fraction: total > 0 ? current / total : 0 };
20
+ }
21
+ return null;
22
+ }
23
+
24
+ /** track.py --track-ablate levels, cumulative from kp-only to full (the default fit). */
25
+ export const TRACK_ABLATIONS = Object.freeze(["kp-only", "silhouette", "viterbi", "contacts", "full"]);
26
+
27
+ export const trackerInputNames = Object.freeze(["video", "obs", "masks", "init", "camera", "scene", "rig"]);
28
+ export function trackerUploadPlan({ video, obsPath, masksPath, initMotionPath, cameraPath, scenePath, rigPath } = {}) {
29
+ return Object.fromEntries(Object.entries({ video, obs: obsPath, masks: masksPath, init: initMotionPath, camera: cameraPath, scene: scenePath, rig: rigPath }));
30
+ }
31
+
32
+ function requiredFile(path, name) {
33
+ if (typeof path !== "string" || !path) throw new Error(`${name}: path is required`);
34
+ return path;
35
+ }
36
+ function lineParser(onLine, progress) {
37
+ return (text) => {
38
+ const parsed = parseProgressLine(text);
39
+ if (parsed) progress.push(parsed);
40
+ onLine?.(text, parsed);
41
+ };
42
+ }
43
+ function withTimeout(promise, timeoutMs) {
44
+ let timer;
45
+ const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`tracker timeout after ${timeoutMs} ms`)), timeoutMs); });
46
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
47
+ }
48
+
49
+ /**
50
+ * Delegate all transfer and remote execution to run-box.mjs. The only
51
+ * caller-owned data transfer entries are the seven declared tracker inputs;
52
+ * run-box separately uploads the Python implementation.
53
+ */
54
+ export async function runTracker({ host, video, obsPath, masksPath, initMotionPath, cameraPath, scenePath, rigPath, outDir, onLine, transport, ablate } = {}) {
55
+ if (typeof host !== "string" || !host.trim()) throw new Error("host is required");
56
+ if (ablate !== undefined && !TRACK_ABLATIONS.includes(ablate)) throw new Error(`ablate must be one of ${TRACK_ABLATIONS.join(",")}`);
57
+ const files = trackerUploadPlan({ video, obsPath, masksPath, initMotionPath, cameraPath, scenePath, rigPath });
58
+ for (const [name, path] of Object.entries(files)) requiredFile(path, name);
59
+ if (typeof outDir !== "string" || !outDir) throw new Error("outDir is required");
60
+ mkdirSync(outDir, { recursive: true });
61
+ const motionPath = `${outDir}/motion.npz`, diagnosticsPath = `${outDir}/diagnostics.json`;
62
+ for (const path of [motionPath, diagnosticsPath]) rmSync(path, { force: true });
63
+ const progress = [];
64
+ const runner = transport?.runBox ?? runBox;
65
+ const upload = Object.entries(files).map(([name, localPath]) => ({ localPath, remoteRelPath: name }));
66
+ const fetch = [
67
+ { remoteRelPath: "motion.npz", localPath: motionPath },
68
+ { remoteRelPath: "diagnostics.json", localPath: diagnosticsPath },
69
+ ];
70
+ const frames = await inferFrames(obsPath);
71
+ const args = [
72
+ "--video", "video", "--obs", "obs", "--masks", "masks", "--init", "init", "--camera", "camera", "--scene", "scene", "--rig", "rig", "--out", ".",
73
+ ...(ablate === undefined ? [] : ["--track-ablate", ablate]),
74
+ ];
75
+ try {
76
+ await withTimeout(Promise.resolve(runner({ entry: "track.py", args, hostName: host, onLine: lineParser(onLine, progress), upload, fetch })), trackerBudgetMs(frames));
77
+ } catch (error) {
78
+ // track.py exits 2/3 with diagnostics only; hand them to the caller on the
79
+ // original error. Unreadable diagnostics never replace that error.
80
+ if (existsSync(diagnosticsPath)) {
81
+ try {
82
+ error.diagnostics = validateDiagnostics(JSON.parse(readFileSync(diagnosticsPath, "utf8")));
83
+ error.diagnosticsPath = diagnosticsPath;
84
+ } catch (diagnosticsError) {
85
+ error.diagnosticsError = diagnosticsError.message;
86
+ }
87
+ }
88
+ error.progress = progress;
89
+ throw error;
90
+ }
91
+ const diagnostics = JSON.parse(readFileSync(diagnosticsPath, "utf8"));
92
+ validateDiagnostics(diagnostics);
93
+ return { motionPath, diagnosticsPath, diagnostics, progress };
94
+ }
95
+
96
+ function finite(value, label) {
97
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`diagnostics: ${label} must be finite`);
98
+ }
99
+
100
+ /** Structural validation kept dependency-free because the bench has no schema package. */
101
+ export function validateDiagnostics(value) {
102
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("diagnostics: expected an object");
103
+ const required = ["version", "frames", "fps", "occluded", "lrState", "lrMargin", "ambiguous", "stance", "penetration", "nuisance", "stageLosses", "runtime", "failure"];
104
+ const rootKeys = new Set(required);
105
+ for (const key of required) if (!(key in value)) throw new Error(`diagnostics: missing ${key}`);
106
+ for (const key of Object.keys(value)) if (!rootKeys.has(key)) throw new Error(`diagnostics: unknown property ${key}`);
107
+ if (value.version !== 1 || !Number.isInteger(value.frames) || value.frames < 1) throw new Error("diagnostics: invalid version or frames");
108
+ finite(value.fps, "fps");
109
+ if (!(value.fps > 0)) throw new Error("diagnostics: fps must be positive");
110
+ const arrays = [["occluded", value.occluded], ["lrState", value.lrState], ["lrMargin", value.lrMargin], ["ambiguous", value.ambiguous], ["stance.left", value.stance?.left], ["stance.right", value.stance?.right]];
111
+ for (const [name, array] of arrays) if (!Array.isArray(array) || array.length !== value.frames) throw new Error(`diagnostics: ${name} must have ${value.frames} frames`);
112
+ value.occluded.forEach((row, t) => { if (!Array.isArray(row) || row.length !== 27 || row.some(v => typeof v !== "boolean")) throw new Error(`diagnostics: occluded[${t}] must contain 27 booleans`); });
113
+ value.lrState.forEach((v, t) => { if (typeof v !== "string") throw new Error(`diagnostics: lrState[${t}] must be a string`); });
114
+ value.lrMargin.forEach((v, t) => finite(v, `lrMargin[${t}]`));
115
+ value.ambiguous.forEach((v, t) => { if (typeof v !== "boolean") throw new Error(`diagnostics: ambiguous[${t}] must be boolean`); });
116
+ if (!value.stance || typeof value.stance !== "object" || Object.keys(value.stance).some(key => !["left", "right"].includes(key))) throw new Error("diagnostics: invalid stance");
117
+ for (const side of ["left", "right"]) value.stance[side].forEach((v, t) => { if (typeof v !== "boolean") throw new Error(`diagnostics: stance.${side}[${t}] must be boolean at ${t}`); });
118
+ if (!value.penetration || typeof value.penetration !== "object" || Object.keys(value.penetration).some(key => !["maxBoxCm", "maxFloorCm", "frames"].includes(key)) || !Array.isArray(value.penetration.frames)) throw new Error("diagnostics: invalid penetration");
119
+ finite(value.penetration.maxBoxCm, "penetration.maxBoxCm"); finite(value.penetration.maxFloorCm, "penetration.maxFloorCm");
120
+ if (value.penetration.maxBoxCm < 0 || value.penetration.maxFloorCm < 0 || value.penetration.frames.some(v => !Number.isInteger(v) || v < 0)) throw new Error("diagnostics: invalid penetration values");
121
+ if (!value.nuisance || typeof value.nuisance !== "object" || Object.keys(value.nuisance).some(key => !["scale", "cameraDeltaDeg", "fovDeltaPct"].includes(key)) || !Number.isFinite(value.nuisance.scale) || !(value.nuisance.scale > 0) || !Array.isArray(value.nuisance.cameraDeltaDeg) || value.nuisance.cameraDeltaDeg.length !== 2 || value.nuisance.cameraDeltaDeg.some(v => !Number.isFinite(v)) || !Number.isFinite(value.nuisance.fovDeltaPct)) throw new Error("diagnostics: invalid nuisance");
122
+ if (!value.stageLosses || typeof value.stageLosses !== "object" || Array.isArray(value.stageLosses) || Object.values(value.stageLosses).some(v => !Number.isFinite(v))) throw new Error("diagnostics: invalid stageLosses");
123
+ if (!value.runtime || typeof value.runtime !== "object" || Object.keys(value.runtime).some(key => !["trackerSeconds", "peakReservedMiB"].includes(key)) || !Number.isFinite(value.runtime.trackerSeconds) || value.runtime.trackerSeconds < 0 || !Number.isFinite(value.runtime.peakReservedMiB) || value.runtime.peakReservedMiB < 0) throw new Error("diagnostics: invalid runtime");
124
+ if (value.failure !== null && typeof value.failure !== "string") throw new Error("diagnostics: failure must be null or string");
125
+ return value;
126
+ }
127
+
128
+ async function inferFrames(path) {
129
+ try {
130
+ const { readNpz } = await import("../kimodo/read-npz.mjs");
131
+ const shape = readNpz(path).kp2d?.shape;
132
+ if (shape && Number.isInteger(shape[0]) && shape[0] > 0) return shape[0];
133
+ } catch { /* track.py reports malformed input; retain the safe minimum */ }
134
+ return 1;
135
+ }
136
+
137
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
138
+ console.error("remote.mjs exports runTracker; call it from the bench or bridge runner");
139
+ process.exitCode = 2;
140
+ }