cozyclay 2.1.0 → 3.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 (583) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +12 -30
  3. package/bin/agent/agent-routes.mjs +40 -113
  4. package/bin/agent/agent-runner.mjs +9 -10
  5. package/bin/agent/cliproxy-provider.mjs +135 -0
  6. package/bin/agent/credential-store.mjs +30 -7
  7. package/bin/agent/pi-tools.mjs +4 -1
  8. package/bin/agent/provider-keys.mjs +32 -0
  9. package/bin/agent/provider-login.mjs +110 -0
  10. package/bin/agent/provider-routes.mjs +99 -0
  11. package/bin/agent/providers.mjs +19 -97
  12. package/bin/agent/script-tool.mjs +17 -4
  13. package/bin/agent/studio-motion-reference.mjs +23 -0
  14. package/bin/agent/studio-prompt.mjs +1 -1
  15. package/bin/agent/studio-rebase-text.mjs +32 -0
  16. package/bin/agent/studio-rebase.mjs +26 -39
  17. package/bin/agent/studio-tools.mjs +9 -28
  18. package/bin/agent/tool-arguments.mjs +49 -0
  19. package/bin/agent/turn-frames.mjs +66 -0
  20. package/bin/codex-auth.mjs +9 -2
  21. package/bin/cozyclay.mjs +10 -116
  22. package/bin/live/cli.mjs +22 -6
  23. package/bin/mcp-runtime.mjs +2 -12
  24. package/bin/package-signature.mjs +0 -4
  25. package/dist/app/index.html +7 -6
  26. package/dist/assets/EXRLoader-CvVIvGVE.js +1 -0
  27. package/dist/assets/analytics-C9sUnndd.js +1 -0
  28. package/dist/assets/app-CCh--1Hc.js +5087 -0
  29. package/dist/assets/app-f-fkV5uP.css +1 -0
  30. package/dist/assets/compile-worker-CkxiD6lH.js +5 -0
  31. package/dist/assets/fflate.module-KbGj5-H6.js +5 -0
  32. package/dist/assets/{first-shot-handoff-BlT33CGf.js → first-shot-handoff-CC4xe4HM.js} +1 -1
  33. package/dist/assets/{landing-BSesrCpL.js → landing-DjHD8u7k.js} +1 -1
  34. package/dist/assets/scene-asset-sync-Hx_FzdOH.js +20 -0
  35. package/dist/assets/scene-asset-sync-_S8NQl5B.css +1 -0
  36. package/dist/assets/workflow-C4yKH1p4.js +179 -0
  37. package/dist/cozyclay-package.json +1 -1
  38. package/dist/index.html +3 -3
  39. package/dist/llms.txt +14 -0
  40. package/dist/sw.js +3 -6
  41. package/dist/workflow/index.html +5 -4
  42. package/mcp/LIVE-PROTOCOL.md +7 -47
  43. package/mcp/README.md +16 -26
  44. package/mcp/live-hub.mjs +6 -10
  45. package/mcp/package.json +1 -3
  46. package/mcp/tool-handlers.mjs +4 -168
  47. package/package.json +3 -22
  48. package/src/App.jsx +174 -2639
  49. package/src/agent-progress.js +79 -0
  50. package/src/agent-turn-mark.js +30 -0
  51. package/src/analytics.js +1 -19
  52. package/src/app-context.js +5 -0
  53. package/src/app-stage.jsx +2 -34
  54. package/src/asset-pane.jsx +6 -5
  55. package/src/camera-block.js +21 -0
  56. package/src/camera-direction.js +120 -0
  57. package/src/character-kind.js +3 -9
  58. package/src/command-bus.js +8 -6
  59. package/src/commands/cast.js +5 -34
  60. package/src/commands/elements/character.js +1 -1
  61. package/src/commands/elements/motion.js +1 -6
  62. package/src/commands/elements/object.js +6 -2
  63. package/src/commands/elements/shot.js +4 -1
  64. package/src/commands/elements.js +38 -14
  65. package/src/commands/index.js +3 -1
  66. package/src/commands/kits.js +37 -0
  67. package/src/commands/motion-timing.js +57 -0
  68. package/src/commands/motion.js +9 -152
  69. package/src/commands/motion3-compile.js +65 -0
  70. package/src/commands/motion3.js +207 -0
  71. package/src/commands/objects.js +6 -4
  72. package/src/commands/shot.js +49 -11
  73. package/src/commands/stage.js +14 -1
  74. package/src/commands/view.js +4 -1
  75. package/src/document-mirrors.js +42 -0
  76. package/src/document-store.js +4 -0
  77. package/src/domains/cast.js +19 -194
  78. package/src/domains/motion/motion-range-pin-rules.js +1 -1
  79. package/src/domains/motion/take-source.js +51 -0
  80. package/src/domains/motion.js +60 -1838
  81. package/src/domains/scenes.js +12 -55
  82. package/src/domains/shots.js +2 -2
  83. package/src/domains/stage.js +4 -2
  84. package/src/draft-ghost.js +46 -0
  85. package/src/draft-ghost.jsx +129 -0
  86. package/src/dualview.jsx +4 -3
  87. package/src/effects/EffectsLayer.jsx +112 -0
  88. package/src/effects/effect-meshes.js +232 -0
  89. package/src/effects/effect-record.js +103 -0
  90. package/src/effects/emitter.js +59 -0
  91. package/src/effects/simulate.js +261 -0
  92. package/src/effects/state.js +59 -0
  93. package/src/execution-telemetry.js +2 -3
  94. package/src/first-success-guide.jsx +5 -5
  95. package/src/ghost-set.js +257 -0
  96. package/src/held-object-edit.jsx +113 -0
  97. package/src/held-object-pose.js +175 -0
  98. package/src/hierarchy-model.js +1 -1
  99. package/src/hierarchy-panel.jsx +1 -1
  100. package/src/imported-mesh.jsx +103 -0
  101. package/src/kits/held.js +84 -0
  102. package/src/kits/index.js +70 -0
  103. package/src/kits/smoking.js +57 -0
  104. package/src/light-blockers.js +93 -0
  105. package/src/motion/beat-board-model.js +84 -0
  106. package/src/motion/beat-board.css +124 -0
  107. package/src/motion/beat-board.jsx +59 -0
  108. package/src/motion/center-of-mass.js +66 -0
  109. package/src/motion/fix-collisions.js +850 -0
  110. package/src/motion/physics-review.js +118 -0
  111. package/src/{ardy → motion}/physics-support.js +1 -76
  112. package/src/motion/rig-snapshot.js +22 -0
  113. package/src/motion/take-segments.jsx +140 -0
  114. package/src/{ardy → motion}/timeline-coordinates.js +0 -21
  115. package/src/{ardy → motion}/timeline.css +1 -2
  116. package/src/{ardy → motion}/timeline.jsx +48 -419
  117. package/src/motion/waypoints.js +76 -0
  118. package/src/motion3/beats.js +83 -0
  119. package/src/motion3/body.js +158 -0
  120. package/src/motion3/bones.js +47 -0
  121. package/src/motion3/carried.js +47 -0
  122. package/src/motion3/compile-job.js +75 -0
  123. package/src/motion3/compile-worker.js +10 -0
  124. package/src/motion3/compiler/anchors.js +105 -0
  125. package/src/motion3/compiler/arm-orient.js +128 -0
  126. package/src/motion3/compiler/channels.js +125 -0
  127. package/src/motion3/compiler/compile.js +205 -0
  128. package/src/motion3/compiler/gait-rhythm.js +97 -0
  129. package/src/motion3/compiler/grip.js +171 -0
  130. package/src/motion3/compiler/head-steady.js +48 -0
  131. package/src/motion3/compiler/hold.js +134 -0
  132. package/src/motion3/compiler/idle.js +113 -0
  133. package/src/motion3/compiler/limbs.js +170 -0
  134. package/src/motion3/compiler/math.js +72 -0
  135. package/src/motion3/compiler/pose.js +162 -0
  136. package/src/motion3/compiler/quat.js +49 -0
  137. package/src/motion3/compiler/skeleton.js +74 -0
  138. package/src/motion3/compiler/validate-common.js +32 -0
  139. package/src/motion3/compiler/validate-goals.js +118 -0
  140. package/src/motion3/compiler/validate-objects.js +143 -0
  141. package/src/motion3/compiler/validate-parts.js +116 -0
  142. package/src/motion3/compiler/validate.js +122 -0
  143. package/src/motion3/compiler/vocab.js +73 -0
  144. package/src/motion3/compiler/walk-pelvis.js +275 -0
  145. package/src/motion3/compiler/walk.js +207 -0
  146. package/src/motion3/compiler/wrist-clamp.js +32 -0
  147. package/src/motion3/delta.js +47 -0
  148. package/src/motion3/describe.js +174 -0
  149. package/src/motion3/docs.js +27 -0
  150. package/src/motion3/edit-carry.js +21 -0
  151. package/src/motion3/fix/ease.js +16 -0
  152. package/src/motion3/fix/ground.js +37 -0
  153. package/src/motion3/fix/index.js +52 -0
  154. package/src/motion3/fix/push.js +71 -0
  155. package/src/motion3/fix/reach.js +46 -0
  156. package/src/motion3/fix/retime.js +79 -0
  157. package/src/motion3/fix/self.js +211 -0
  158. package/src/motion3/fix/slide.js +70 -0
  159. package/src/motion3/fix/turn.js +51 -0
  160. package/src/motion3/follow.js +39 -0
  161. package/src/motion3/free-motion.js +173 -0
  162. package/src/motion3/grip-choice.js +130 -0
  163. package/src/motion3/hold-plan.js +157 -0
  164. package/src/motion3/json-patch.js +77 -0
  165. package/src/motion3/key-aim.js +105 -0
  166. package/src/motion3/key-edit.js +82 -0
  167. package/src/motion3/lenient.js +127 -0
  168. package/src/motion3/object-keys.js +236 -0
  169. package/src/motion3/object-pose.js +182 -0
  170. package/src/motion3/object-tracks.js +12 -0
  171. package/src/motion3/pipeline.js +102 -0
  172. package/src/motion3/playback.js +51 -0
  173. package/src/motion3/probes.js +91 -0
  174. package/src/motion3/qa/body-checks.js +34 -0
  175. package/src/motion3/qa/check-names.js +14 -0
  176. package/src/motion3/qa/checks.js +121 -0
  177. package/src/motion3/qa/contact-checks.js +51 -0
  178. package/src/motion3/qa/explain.js +80 -0
  179. package/src/motion3/qa/fmt.js +5 -0
  180. package/src/motion3/qa/foot-checks.js +72 -0
  181. package/src/motion3/qa/geometry.js +77 -0
  182. package/src/motion3/qa/goals.js +191 -0
  183. package/src/motion3/qa/ground.js +60 -0
  184. package/src/motion3/qa/hints-contact.js +179 -0
  185. package/src/motion3/qa/hints-goal.js +160 -0
  186. package/src/motion3/qa/hints-knee.js +24 -0
  187. package/src/motion3/qa/hints-motion.js +209 -0
  188. package/src/motion3/qa/hints-object.js +91 -0
  189. package/src/motion3/qa/index.js +42 -0
  190. package/src/motion3/qa/key-checks.js +82 -0
  191. package/src/motion3/qa/near.js +96 -0
  192. package/src/motion3/qa/object-checks.js +135 -0
  193. package/src/motion3/qa/patch.js +161 -0
  194. package/src/motion3/qa/severity.js +38 -0
  195. package/src/motion3/qa/spec-checks.js +65 -0
  196. package/src/motion3/qa/style.js +218 -0
  197. package/src/motion3/qa/wrist-checks.js +69 -0
  198. package/src/motion3/qa/wrist-obs.js +60 -0
  199. package/src/motion3/refs.js +120 -0
  200. package/src/motion3/repair-tune.js +121 -0
  201. package/src/motion3/repair.js +83 -0
  202. package/src/motion3/report.js +67 -0
  203. package/src/motion3/rigs/index.js +14 -0
  204. package/src/motion3/rigs/x-bot-tpose-body.json +1 -0
  205. package/src/motion3/rigs/x-bot-tpose.json +1 -0
  206. package/src/motion3/rigs/y-bot-tpose-body.json +1 -0
  207. package/src/motion3/rigs/y-bot-tpose.json +1 -0
  208. package/src/motion3/scene.js +60 -0
  209. package/src/motion3/schema/brief.js +89 -0
  210. package/src/motion3/schema/fields.js +44 -0
  211. package/src/motion3/schema/spec-examples.js +46 -0
  212. package/src/motion3/schema/topics.js +111 -0
  213. package/src/motion3/schema/types.js +147 -0
  214. package/src/motion3/search.js +117 -0
  215. package/src/motion3/second-hand.js +112 -0
  216. package/src/motion3/skills/basic.js +82 -0
  217. package/src/motion3/skills/book.js +76 -0
  218. package/src/motion3/skills/car.js +145 -0
  219. package/src/motion3/skills/frames-auto.js +29 -0
  220. package/src/motion3/skills/index.js +83 -0
  221. package/src/motion3/skills/info.js +65 -0
  222. package/src/motion3/skills/smoke-kit.js +109 -0
  223. package/src/motion3/skills/smoke.js +160 -0
  224. package/src/motion3/spec-store.js +59 -0
  225. package/src/motion3/take-edit.js +155 -0
  226. package/src/motion3/take.js +63 -0
  227. package/src/motion3/timeline.js +127 -0
  228. package/src/motion3/views.js +121 -0
  229. package/src/motion3/walk-plan.js +119 -0
  230. package/src/object-catalog.jsx +7 -1
  231. package/src/object-colors.js +98 -0
  232. package/src/object-gizmo-parts.js +115 -0
  233. package/src/object-gizmo.jsx +37 -122
  234. package/src/object-glow.js +139 -0
  235. package/src/object-hidden.js +33 -0
  236. package/src/object-look.js +196 -0
  237. package/src/object-size.js +10 -0
  238. package/src/object-travel.js +71 -6
  239. package/src/panels/CameraPanel.jsx +7 -7
  240. package/src/panels/HdrEnvironmentControls.jsx +59 -0
  241. package/src/panels/LightPanel.jsx +25 -4
  242. package/src/panels/ObjectLookPanel.jsx +88 -0
  243. package/src/panels/PoseImagePanel.jsx +1 -1
  244. package/src/panels/PosePanel.jsx +2 -17
  245. package/src/panels/RigControlPanel.jsx +5 -53
  246. package/src/panels/SubjectBox.jsx +4 -1
  247. package/src/panels/details.css +14 -0
  248. package/src/posestudio.jsx +4 -27
  249. package/src/project-browser.jsx +3 -4
  250. package/src/project-resources.js +18 -31
  251. package/src/project.js +13 -104
  252. package/src/props.jsx +25 -280
  253. package/src/rail-dot-drag.js +23 -0
  254. package/src/render-passes.js +10 -0
  255. package/src/resource-status.jsx +1 -0
  256. package/src/result-modal.jsx +4 -19
  257. package/src/room.jsx +20 -12
  258. package/src/scene-assets.js +8 -6
  259. package/src/scene-light-place.js +72 -0
  260. package/src/scene-lights.jsx +148 -0
  261. package/src/scene-objects.js +31 -139
  262. package/src/scenes.js +15 -105
  263. package/src/semantic-edit.js +2 -5
  264. package/src/set-pieces.jsx +183 -0
  265. package/src/settings-menu.jsx +3 -11
  266. package/src/shell/BottomDock.jsx +11 -53
  267. package/src/shell/CompositionGuideButton.jsx +20 -0
  268. package/src/shell/DetailsSlot.jsx +16 -200
  269. package/src/shell/GhostsMenuGroup.jsx +74 -0
  270. package/src/shell/LibrarySlot.jsx +1 -3
  271. package/src/shell/MenuBar.jsx +3 -3
  272. package/src/shell/PreferencesDialog.jsx +15 -264
  273. package/src/shell/PreferencesSlot.jsx +2 -8
  274. package/src/shell/ShotPreviewHeader.jsx +17 -0
  275. package/src/shell/TopBar.jsx +5 -83
  276. package/src/shell/ViewportToolbar.jsx +23 -93
  277. package/src/shell/agent-glass.css +19 -6
  278. package/src/shell/details-selection.js +42 -0
  279. package/src/shell/ghosts-menu.css +22 -0
  280. package/src/shell/glass-regions.css +29 -3
  281. package/src/shell/preferences.css +6 -1
  282. package/src/shell/viewport.css +12 -0
  283. package/src/shot-authoring.js +4 -7
  284. package/src/soft-shadows.js +37 -0
  285. package/src/stage-attach-frames.js +12 -12
  286. package/src/stage-canvas-rigs.jsx +3 -3
  287. package/src/stage-capture.jsx +42 -8
  288. package/src/stage-characters.jsx +22 -216
  289. package/src/stage-editor-gizmos.jsx +6 -6
  290. package/src/stage-environment.js +93 -0
  291. package/src/stage-hdr-builtins.js +107 -0
  292. package/src/stage-hdr-image.js +116 -0
  293. package/src/stage-hdr-library.js +70 -0
  294. package/src/stage-hdr-map.js +94 -0
  295. package/src/stage-hdr.js +130 -0
  296. package/src/stage-lighting.js +149 -0
  297. package/src/stage-occlusion.js +210 -0
  298. package/src/stage-sky.jsx +159 -0
  299. package/src/stage-startup-defaults.js +5 -9
  300. package/src/studio-actions.js +12 -14
  301. package/src/studio-agent-commands.js +46 -16
  302. package/src/studio-agent-motion.js +9 -9
  303. package/src/studio-agent-protocol.js +46 -73
  304. package/src/studio-app-binding.js +29 -45
  305. package/src/studio-asset-list.js +17 -0
  306. package/src/studio-contact-sheet.js +37 -5
  307. package/src/studio-elements.js +27 -7
  308. package/src/studio-entity-bounds.js +18 -0
  309. package/src/studio-error-codes.js +8 -0
  310. package/src/studio-export-framing.js +152 -0
  311. package/src/studio-lighting-check.js +103 -0
  312. package/src/studio-motion-visual.js +150 -0
  313. package/src/studio-schema-errors.js +80 -0
  314. package/src/studio-support-gap.js +74 -0
  315. package/src/styles.css +1 -19
  316. package/src/timeline-defaults.js +5 -0
  317. package/src/timeline-extent.js +8 -20
  318. package/src/tutorial-walk.js +17 -0
  319. package/src/ui-scrub.js +1 -1
  320. package/src/use-shot-camera-tracks.js +12 -0
  321. package/src/view-ghosts.js +97 -0
  322. package/src/view-ghosts.jsx +49 -0
  323. package/src/workflow/AgentPanel.jsx +47 -166
  324. package/src/workflow/AgentProgressCard.jsx +107 -0
  325. package/src/workflow/AgentReplyText.jsx +37 -0
  326. package/src/workflow/AgentTurnSteps.jsx +84 -0
  327. package/src/workflow/LoginPanel.jsx +140 -0
  328. package/src/workflow/WorkflowBuilder.jsx +7 -23
  329. package/src/workflow/agent-client.js +54 -51
  330. package/src/workflow/agent-panel.css +71 -1
  331. package/src/workflow/agent-progress-card.css +167 -0
  332. package/src/workflow/agent-progress-view.js +47 -0
  333. package/src/workflow/agent-turn-steps.css +113 -0
  334. package/src/workflow/agent-turn.js +191 -0
  335. package/src/workflow/login-client.js +34 -0
  336. package/src/workflow/motion-input.js +18 -31
  337. package/src/workflow/node-schema.js +1 -1
  338. package/src/workflow/reply-markdown.js +69 -0
  339. package/src/workflow/scene-asset-sync.js +8 -8
  340. package/tools/agent-session-stats.mjs +61 -0
  341. package/tools/dev-full.mjs +5 -56
  342. package/tools/eslint-baseline.json +12 -13
  343. package/tools/headless-studio.mjs +85 -0
  344. package/tools/knip-baseline.json +0 -179
  345. package/tools/loc-baseline.json +33 -83
  346. package/tools/motion3/extract-body.mjs +103 -0
  347. package/tools/motion3/extract-rig.mjs +85 -0
  348. package/tools/process-supervisor.mjs +0 -88
  349. package/tools/run-tests.mjs +9 -124
  350. package/bin/agent/motion-runtime.mjs +0 -76
  351. package/dist/ardy/cskel27-rest.json +0 -557
  352. package/dist/assets/analytics-B41FmPYI.js +0 -1
  353. package/dist/assets/app-Do-Og5Pu.css +0 -1
  354. package/dist/assets/app-DwP-tl2x.js +0 -4920
  355. package/dist/assets/config-Bx7pYsD9.js +0 -1
  356. package/dist/assets/config-DeoFTYzb.css +0 -1
  357. package/dist/assets/demo-Dt0qZfS7.js +0 -1
  358. package/dist/assets/scene-asset-sync-BCWDJB1d.js +0 -19
  359. package/dist/assets/scene-asset-sync-DjJ_cJ2R.css +0 -1
  360. package/dist/assets/ticket-jqMhqL88.js +0 -1
  361. package/dist/assets/workflow-Br-K7Srs.js +0 -179
  362. package/dist/demo/walk-then-stop.npz +0 -0
  363. package/mcp/ardy-prompts.mjs +0 -218
  364. package/src/ardy/auto-fix-panel.css +0 -108
  365. package/src/ardy/auto-physics.js +0 -1194
  366. package/src/ardy/client.js +0 -153
  367. package/src/ardy/convert.js +0 -313
  368. package/src/ardy/cskel27-neutral.js +0 -39
  369. package/src/ardy/cskel27.js +0 -77
  370. package/src/ardy/export.js +0 -165
  371. package/src/ardy/fix-collisions.js +0 -2257
  372. package/src/ardy/foot-lock.js +0 -230
  373. package/src/ardy/motion-calibration.js +0 -118
  374. package/src/ardy/motion-edit.js +0 -213
  375. package/src/ardy/motion-url.js +0 -55
  376. package/src/ardy/mp4-duration.js +0 -102
  377. package/src/ardy/npz.js +0 -595
  378. package/src/ardy/physics-panel.css +0 -21
  379. package/src/ardy/physics-panel.jsx +0 -89
  380. package/src/ardy/physics-refine.js +0 -111
  381. package/src/ardy/physics-review.js +0 -567
  382. package/src/ardy/physics-temporal.js +0 -54
  383. package/src/ardy/platform-fit-panel.css +0 -64
  384. package/src/ardy/platform-fit-panel.jsx +0 -41
  385. package/src/ardy/platform-fit.js +0 -326
  386. package/src/ardy/playback.js +0 -711
  387. package/src/ardy/pose-pin.js +0 -97
  388. package/src/ardy/prompt-clips.js +0 -30
  389. package/src/ardy/retime.js +0 -211
  390. package/src/ardy/root-drop.js +0 -369
  391. package/src/ardy/timeline-resize.js +0 -13
  392. package/src/ardy/to-cskel27.js +0 -225
  393. package/src/ardy/trim.js +0 -33
  394. package/src/ardy/waypoints.js +0 -369
  395. package/src/ardy-bridge-contract.js +0 -281
  396. package/src/domains/motion/motion-video-capture.js +0 -664
  397. package/src/i2v-motion-client.js +0 -77
  398. package/src/i2v-motion-studio.jsx +0 -180
  399. package/src/line-edit.js +0 -1348
  400. package/src/motion/generation.js +0 -105
  401. package/src/motion-readiness-ui.jsx +0 -67
  402. package/src/motion-readiness.js +0 -40
  403. package/src/motion-resources.js +0 -177
  404. package/src/motion-store.js +0 -65
  405. package/src/motion-trail.js +0 -601
  406. package/src/multimodel-ingest.js +0 -394
  407. package/src/panels/PromptBlocksPanel.jsx +0 -444
  408. package/src/panels/VideoCapturePanel.jsx +0 -181
  409. package/src/pose-extract/browser.js +0 -42
  410. package/src/pose-extract/detector.js +0 -100
  411. package/src/pose-extract/fit.js +0 -227
  412. package/src/pose-extract/image-frame.js +0 -51
  413. package/src/pose-extract/index.js +0 -58
  414. package/src/pose-extract/keyframes.js +0 -74
  415. package/src/pose-extract/landmarks.js +0 -162
  416. package/src/pose-extract/mirror.js +0 -153
  417. package/src/pose-extract/take.js +0 -131
  418. package/src/pose-extract/video-frames.js +0 -91
  419. package/src/take-recipe.js +0 -165
  420. package/src/trail-key-conflicts.js +0 -39
  421. package/src/trail-pick.js +0 -59
  422. package/src/use-i2v-capture-modal.js +0 -15
  423. package/tools/ardy/BRIDGE.md +0 -37
  424. package/tools/ardy/GVHMR-NPZ.md +0 -68
  425. package/tools/ardy/README.md +0 -124
  426. package/tools/ardy/__pycache__/cclay_gvhmr_worker.cpython-313.pyc +0 -0
  427. package/tools/ardy/artifacts.mjs +0 -34
  428. package/tools/ardy/bridge.mjs +0 -1732
  429. package/tools/ardy/bvh-cskel27.mjs +0 -1265
  430. package/tools/ardy/cclay_constrained_generate.py +0 -561
  431. package/tools/ardy/cclay_gvhmr_worker.py +0 -264
  432. package/tools/ardy/cclay_motion_edit.py +0 -510
  433. package/tools/ardy/cclay_sequence_generate.py +0 -705
  434. package/tools/ardy/cclay_worker.py +0 -304
  435. package/tools/ardy/dump-npz.py +0 -205
  436. package/tools/ardy/extract-rest.mjs +0 -299
  437. package/tools/ardy/extract.mjs +0 -507
  438. package/tools/ardy/footage.mjs +0 -467
  439. package/tools/ardy/gvhmr-floor.mjs +0 -102
  440. package/tools/ardy/gvhmr-to-cskel27.mjs +0 -21
  441. package/tools/ardy/gvhmr_fastpath.py +0 -168
  442. package/tools/ardy/gvhmr_trajectory.py +0 -240
  443. package/tools/ardy/merge-text-encoder.py +0 -160
  444. package/tools/ardy/mocap-metrics.mjs +0 -200
  445. package/tools/ardy/mocap-quality-gate.mjs +0 -110
  446. package/tools/ardy/motion-stabilize.mjs +0 -348
  447. package/tools/ardy/npz.mjs +0 -414
  448. package/tools/ardy/pose-to-npz.mjs +0 -106
  449. package/tools/ardy/prompt-limits.mjs +0 -5
  450. package/tools/ardy/run-edit-on-box.sh +0 -73
  451. package/tools/ardy/run-local.mjs +0 -233
  452. package/tools/ardy/run-on-box.sh +0 -593
  453. package/tools/ardy/run-sequence-on-box.sh +0 -177
  454. package/tools/ardy/runners/gvhmr-worker.mjs +0 -206
  455. package/tools/ardy/runners/index.mjs +0 -18
  456. package/tools/ardy/runners/local.mjs +0 -455
  457. package/tools/ardy/runners/proc.mjs +0 -125
  458. package/tools/ardy/runners/remote.mjs +0 -252
  459. package/tools/ardy/setup-local.mjs +0 -189
  460. package/tools/ardy/setup-text-encoder-on-box.sh +0 -93
  461. package/tools/ardy/setup-text-encoder.py +0 -306
  462. package/tools/ardy/smpl-cskel27.mjs +0 -178
  463. package/tools/ardy/visual-qa.mjs +0 -196
  464. package/tools/ardy/vq-car.mjs +0 -52
  465. package/tools/bench/EXP3.md +0 -61
  466. package/tools/bench/cclay_bench_extract_incam.py +0 -125
  467. package/tools/bench/cclay_bench_extract_obs.py +0 -204
  468. package/tools/bench/cclay_bench_runner.py +0 -42
  469. package/tools/bench/cube-contact.mjs +0 -162
  470. package/tools/bench/exp3.mjs +0 -152
  471. package/tools/bench/extract-bench-lib.mjs +0 -216
  472. package/tools/bench/extract-bench.mjs +0 -302
  473. package/tools/bench/fal-generate.mjs +0 -88
  474. package/tools/bench/fit/README.md +0 -189
  475. package/tools/bench/fit/camera.mjs +0 -59
  476. package/tools/bench/fit/contact.mjs +0 -419
  477. package/tools/bench/fit/footlock.mjs +0 -234
  478. package/tools/bench/fit/motion.mjs +0 -85
  479. package/tools/bench/fit/pin.mjs +0 -27
  480. package/tools/bench/fit/remote.mjs +0 -105
  481. package/tools/bench/fit-bench.mjs +0 -126
  482. package/tools/bench/fit-sanity.mjs +0 -45
  483. package/tools/bench/metrics.mjs +0 -313
  484. package/tools/bench/obs/depth.mjs +0 -258
  485. package/tools/bench/obs/extrinsics.mjs +0 -175
  486. package/tools/bench/obs/fit_mannequin_betas.py +0 -340
  487. package/tools/bench/obs/ground.mjs +0 -294
  488. package/tools/bench/obs/heading.mjs +0 -151
  489. package/tools/bench/obs/ladder.mjs +0 -555
  490. package/tools/bench/obs/mannequin-betas.json +0 -124
  491. package/tools/bench/obs/remote.mjs +0 -83
  492. package/tools/bench/obs/rest_joints.py +0 -52
  493. package/tools/bench/obs/ybot-targets.mjs +0 -49
  494. package/tools/bench/obs-bench.mjs +0 -520
  495. package/tools/bench/score.mjs +0 -343
  496. package/tools/bench/summarize.mjs +0 -86
  497. package/tools/demo-worker/README.md +0 -137
  498. package/tools/demo-worker/api-client.mjs +0 -233
  499. package/tools/demo-worker/generate.mjs +0 -301
  500. package/tools/demo-worker/index.mjs +0 -466
  501. package/tools/demo-worker/sign-core.mjs +0 -112
  502. package/tools/demo-worker/sign.mjs +0 -161
  503. package/tools/gt-render/browser.mjs +0 -159
  504. package/tools/gt-render/camera-math.mjs +0 -276
  505. package/tools/gt-render/page.mjs +0 -267
  506. package/tools/gt-render/render.mjs +0 -514
  507. package/tools/gt-render/scene-box.mjs +0 -31
  508. package/tools/gt-render/take-transform.mjs +0 -87
  509. package/tools/kimodo/compare-seam.mjs +0 -108
  510. package/tools/kimodo/constraints.mjs +0 -244
  511. package/tools/kimodo/edit.mjs +0 -259
  512. package/tools/kimodo/effector-constraints.mjs +0 -200
  513. package/tools/kimodo/generate.mjs +0 -646
  514. package/tools/kimodo/local-output.mjs +0 -265
  515. package/tools/kimodo/measure-pose.mjs +0 -65
  516. package/tools/kimodo/measure-preserve.mjs +0 -899
  517. package/tools/kimodo/measure-waypoints.mjs +0 -55
  518. package/tools/kimodo/mlx-generate.py +0 -111
  519. package/tools/kimodo/pose-constraints.mjs +0 -248
  520. package/tools/kimodo/preserve-mask.mjs +0 -543
  521. package/tools/kimodo/read-npz.mjs +0 -189
  522. package/tools/kimodo/run-edit-on-box.mjs +0 -155
  523. package/tools/kimodo/run-sequence-on-box.mjs +0 -178
  524. package/tools/kimodo/runner.mjs +0 -284
  525. package/tools/kimodo/seam-batch.mjs +0 -77
  526. package/tools/kimodo/setup-local.mjs +0 -30
  527. package/tools/kimodo/setup-on-box.sh +0 -339
  528. package/tools/kimodo/soma77-to-cskel27.mjs +0 -305
  529. package/tools/morphgs/assets/gen_truth.py +0 -39
  530. package/tools/morphgs/assets/mesh_ori_rig.txt +0 -27
  531. package/tools/morphgs/assets/playback-check.mjs +0 -30
  532. package/tools/morphgs/demo-gate.sh +0 -26
  533. package/tools/morphgs/fbx2morphgs.mjs +0 -68
  534. package/tools/morphgs/morphgs-to-cskel27.mjs +0 -105
  535. package/tools/morphgs/patches/preprocess_src-none-mode.patch +0 -76
  536. package/tools/morphgs/setup-on-cluster.sh +0 -126
  537. package/tools/projflow/driver.py +0 -1069
  538. package/tools/projflow/generate.mjs +0 -805
  539. package/tools/projflow/hml22-to-cskel27.mjs +0 -735
  540. package/tools/projflow/line-edit-job.mjs +0 -547
  541. package/tools/projflow/replay.mjs +0 -452
  542. package/tools/projflow/runner.mjs +0 -269
  543. package/tools/projflow/service.mjs +0 -742
  544. package/tools/track/DESIGN.md +0 -513
  545. package/tools/track/backfill-provenance.mjs +0 -116
  546. package/tools/track/budget.mjs +0 -8
  547. package/tools/track/check-rig.mjs +0 -209
  548. package/tools/track/diagnostics.schema.json +0 -60
  549. package/tools/track/export-rig.mjs +0 -256
  550. package/tools/track/fallback.mjs +0 -7
  551. package/tools/track/fk-parity-fixture.mjs +0 -161
  552. package/tools/track/gate.mjs +0 -349
  553. package/tools/track/masks.mjs +0 -318
  554. package/tools/track/metrics.mjs +0 -201
  555. package/tools/track/publish-obs.mjs +0 -108
  556. package/tools/track/py/check_env.py +0 -61
  557. package/tools/track/py/eval_lr.py +0 -229
  558. package/tools/track/py/lr_viterbi.py +0 -294
  559. package/tools/track/py/masks.py +0 -405
  560. package/tools/track/py/objective.py +0 -382
  561. package/tools/track/py/rig.py +0 -508
  562. package/tools/track/py/scene.py +0 -326
  563. package/tools/track/py/test_joint_indices.py +0 -123
  564. package/tools/track/py/test_lr_viterbi.py +0 -195
  565. package/tools/track/py/test_masks.py +0 -229
  566. package/tools/track/py/test_rig.py +0 -288
  567. package/tools/track/py/test_scene.py +0 -354
  568. package/tools/track/py/test_track.py +0 -328
  569. package/tools/track/py/track.py +0 -411
  570. package/tools/track/remote.mjs +0 -140
  571. package/tools/track/rig-dump.mjs +0 -227
  572. package/tools/track/run-box-tests.mjs +0 -14
  573. package/tools/track/run-box.mjs +0 -168
  574. package/tools/track/setup-box.sh +0 -59
  575. package/tools/track/study-2d.mjs +0 -728
  576. /package/src/{ardy → motion}/collision-blockers.js +0 -0
  577. /package/src/{ardy → motion}/ground.js +0 -0
  578. /package/src/{ardy → motion}/ik-drag.js +0 -0
  579. /package/src/{ardy → motion}/ik-key-json.js +0 -0
  580. /package/src/{ardy → motion}/ik.js +0 -0
  581. /package/src/{ardy → motion}/physics-surface.js +0 -0
  582. /package/src/{ardy → motion}/playback-clock.js +0 -0
  583. /package/src/{ardy → motion}/range-pin.js +0 -0
@@ -1,411 +0,0 @@
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()))
@@ -1,140 +0,0 @@
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
- }