Skip to content

Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.

Python

Improve resource selection, multi-person throughput and contact stability

toyxyz941acffbd761
diff --git a/README.md b/README.md
index c0d17e1..0dea601 100644
--- a/README.md
+++ b/README.md
@@ -140,10 +140,25 @@ archives need additional space. See the [storage details](docs/USER_GUIDE.md#ins
[Cache and project cleanup: paths and deletion effects](docs/USER_GUIDE.md#storage-and-cleanup).
+## Resources and speed
+
+Start with **Resource Mode > Automatic**. It uses the fast supported path when
+memory permits and falls back to Low Memory when needed. **Low Memory** trades
+loading/transfers for lower VRAM use; system RAM may increase.
+
+Short paired tests reduced peak allocated VRAM from **5.68 to 3.87 GiB** for ExMR
+and **6.10 to 2.77 GiB** for FlowHMR. Separate short-clip tests of connected
+processing phases cut worker time by **44% for ExMR** and **24% for FlowHMR**,
+with unchanged measured peak VRAM. These are different tests, not full-job
+speed guarantees. See [resource modes, measured savings and acceleration](docs/PERFORMANCE.md)
+for conditions, per-model results and output differences.
+
## Documentation
- [User guide: installation, controls and settings](docs/USER_GUIDE.md)
- [Model guides: files, defaults, options and limitations](docs/models/README.md)
+- [Recorded processing time, VRAM and RAM](docs/USER_GUIDE.md#recorded-processing-time-and-vram)
+- [Resource modes and measured optimizations](docs/PERFORMANCE.md)
- [MAMMA: additional installation, model files and multi-video workflow](docs/MAMMA.md)
- [Development and builds](docs/BUILD.md)
- [Agent operating and development guide](docs/AGENT_GUIDE.md)
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index c1632a2..bf5a8b2 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -26,8 +26,8 @@
},
{
"path": "README.md",
- "bytes": 6502,
- "sha256": "70af93cdc43e4c31c7c986da69e22c7163a74c369df78fcd96830edd4ab9bca9"
+ "bytes": 7379,
+ "sha256": "3f64c511c2f0a87f0c47b88ad10c19ad1e84ec50d8ac1e0da2982c2d260ed2a4"
},
{
"path": "RGBMoCap.cmd",
@@ -91,8 +91,8 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 15780,
- "sha256": "8181dd263a7f81860a47971cb8498ccbab9afec9aa0992d75415854738056d0d"
+ "bytes": 21841,
+ "sha256": "475ca8a1ce0706c0937bd89080a509c6eb61934cf4b4e22b86ed2996b3ce0973"
},
{
"path": "docs/BUILD.md",
@@ -101,23 +101,28 @@
},
{
"path": "docs/MAMMA.md",
- "bytes": 18819,
- "sha256": "9c60a075b66cf7294603101004c71d471bfed439e135e7bedd93a60a56f1a8d9"
+ "bytes": 22348,
+ "sha256": "87e50f7cbcc0b1bf1a683039c7f3cb1388fb928dc5667e79ba2964d75065b9e5"
},
{
"path": "docs/MAMMA_AGENT_SETUP.md",
"bytes": 22119,
"sha256": "8f832c9403cf067b773f71b18321b8b31400ec629d9b3c25fd37917a5c945368"
},
+ {
+ "path": "docs/PERFORMANCE.md",
+ "bytes": 11860,
+ "sha256": "d945c44e31393092d5b116f34323562495d2f79ec8203e7a9d90b537d669a226"
+ },
{
"path": "docs/USER_GUIDE.md",
- "bytes": 35154,
- "sha256": "7eb658306567125bd4db873fa202b140fd17aef0121b212bc24853956b23a80e"
+ "bytes": 38944,
+ "sha256": "69a86b5e4f660a49cfd860f505bdaafd6ebac9b00cd200861634818cf270c444"
},
{
"path": "docs/VALIDATION.md",
- "bytes": 27775,
- "sha256": "9c5c454544097864efed20d6733a9e510720a8eae2e342589795b9f1c2a67151"
+ "bytes": 42142,
+ "sha256": "abc00662fc334b6a5c49a712a37d9fa8610e3926c5cf6b9072268be0dc8381ce"
},
{
"path": "docs/images/rgbmocap-workspace.png",
@@ -126,23 +131,23 @@
},
{
"path": "docs/models/EXMR.md",
- "bytes": 3943,
- "sha256": "5ae467efb2c55aa31aab2d0325070593d47f6bdb4cb7f59a44174adaaa3fdc66"
+ "bytes": 6040,
+ "sha256": "9f04b8d02ebe7cb87f8ef0487f76e944a8337d5f572372f5e8fee45cb9917030"
},
{
"path": "docs/models/FLOWHMR.md",
- "bytes": 4116,
- "sha256": "ef73ee4fd10f889c36c59c1ba7e0785f9021338e773b86a158df6ec8a53c8049"
+ "bytes": 7457,
+ "sha256": "4934536f41a3821c9039e300a5aec96b2ac256b8a97e7f952c851f693392cdac"
},
{
"path": "docs/models/GVHMR.md",
- "bytes": 4344,
- "sha256": "d313f99f84dd6dd110ee5d72f58ad8f58e6b344bf3bd15b322a3f4623567854c"
+ "bytes": 5580,
+ "sha256": "b77a14af2d2a4a61208cfca385d63aedec9e4aaa7fbe8732dc3ee45fd9f30b0c"
},
{
"path": "docs/models/README.md",
- "bytes": 3450,
- "sha256": "8b05a5469f3e3609992a0d686aae7e0fcfecd76dd3e12b8572f284a667f1f44d"
+ "bytes": 4264,
+ "sha256": "5785e524ffb190c2ebf025d4668588ba3b2647afd4560fad2ac197ff4a002e33"
},
{
"path": "docs/samples/character-retargeting.jpg",
@@ -984,6 +989,16 @@
"bytes": 4652,
"sha256": "960fa6f0b59f70ceeaeceae1fe9fde4a05c20fa22a169f01a68b7f6f9c6c50a9"
},
+ {
+ "path": "mocap/batch_prefetch.py",
+ "bytes": 2185,
+ "sha256": "6fb62194c76d0423ee2eef55e7ee690baf27aef3ce61fa2230b940830c46178e"
+ },
+ {
+ "path": "mocap/batch_worker.py",
+ "bytes": 5752,
+ "sha256": "c9f04c44545987ca88880b2c3a7c68035b6b1a24646c6fd0c7e228958f3d9b7e"
+ },
{
"path": "mocap/bone_gl.py",
"bytes": 1193,
@@ -1046,8 +1061,8 @@
},
{
"path": "mocap/compute_policy.py",
- "bytes": 5723,
- "sha256": "f47c0da4b7f7671931174e2aaf8ed09a7d1fde1047fd3c07d96065b8cc14425b"
+ "bytes": 6073,
+ "sha256": "d355f7b37c395c9c745774399846880659b9b6a29d281ab5151480c2be4b6b3c"
},
{
"path": "mocap/console_log.py",
@@ -1061,8 +1076,8 @@
},
{
"path": "mocap/contact_pose_plan.py",
- "bytes": 12652,
- "sha256": "ba5972c5b3f6161ae98d29ceebdf8ec283dfeb06c5edde5d3ca4f78d0d185a8f"
+ "bytes": 13742,
+ "sha256": "c442252def49642c97925da0ea06d0f4aa1c61560629ff3e5bcd70b8aeb7cb6b"
},
{
"path": "mocap/contact_temporal_root.py",
@@ -1071,8 +1086,8 @@
},
{
"path": "mocap/contact_trajectory.py",
- "bytes": 11551,
- "sha256": "4e4edb1b20d0b3b4873b62c369aa5822e029302d03d4a92ff13626a798443c51"
+ "bytes": 12124,
+ "sha256": "3a28da4a3b7e10ce1d0b453f3e5791638dfd64df8f62535137cd267c354c9c55"
},
{
"path": "mocap/contact_writer.py",
@@ -1081,8 +1096,8 @@
},
{
"path": "mocap/correction.py",
- "bytes": 45959,
- "sha256": "a9399bb6e66506981d76113f433f012223b172aec245554c692334d7233f9150"
+ "bytes": 46583,
+ "sha256": "7b25e1eb57ed810bdf995a918d7b7633e7e558c25f982ba273f7d64783105ec3"
},
{
"path": "mocap/correction_settings.py",
@@ -1096,13 +1111,13 @@
},
{
"path": "mocap/engines.py",
- "bytes": 14967,
- "sha256": "05bfa80b429131fc7079b40b89e9daf9018b9c664fbd91fcae6199aa91436b79"
+ "bytes": 15987,
+ "sha256": "f72dc055843514632c84bd226f1828d0482a88e9bbf4037471379eb99076c5c8"
},
{
"path": "mocap/exmr_backend.py",
- "bytes": 17106,
- "sha256": "6d2702884592ca28a6fba2875b24dc2afd7ef149f8bfb24ac11acb95d9c60f0f"
+ "bytes": 20444,
+ "sha256": "97247aaa6ad6901f2bee1dac4ee47e6372f35db1068492241121cd57dadb1432"
},
{
"path": "mocap/exmr_options.py",
@@ -1141,8 +1156,8 @@
},
{
"path": "mocap/flow_backend.py",
- "bytes": 22729,
- "sha256": "7204c9d6f0fab769e6440a740d7fb0309e53f1c80644f70fa80e0e62712b3567"
+ "bytes": 25866,
+ "sha256": "088ec2ac27a23f255ca6d06da783a31d52a207fea8ac671de32bb215a02ade88"
},
{
"path": "mocap/flow_camera.py",
@@ -1159,6 +1174,11 @@
"bytes": 15329,
"sha256": "e2af2c1ab04f09af16e15be5b5c8238c4950ea16fafef2e4f9be5580b02cde8c"
},
+ {
+ "path": "mocap/flow_fast_sam.py",
+ "bytes": 3926,
+ "sha256": "319f211033a21d0fa1a83dd01a45676844df93cf95680e0d9fb7242883e3ba42"
+ },
{
"path": "mocap/flow_floor.py",
"bytes": 2009,
@@ -1171,8 +1191,8 @@
},
{
"path": "mocap/flow_sam.py",
- "bytes": 5416,
- "sha256": "124423486da76ea75d86a6274b71a4b40837761087930617ed8a00394d1e6b46"
+ "bytes": 6547,
+ "sha256": "c1abd10ec3143cfa7d7b97283a461fa858b73f55338cde7d7842cf030eff0b95"
},
{
"path": "mocap/flow_scene.py",
@@ -1194,15 +1214,20 @@
"bytes": 10133,
"sha256": "a427f13181af20c2ded61a704a3c797bb8b9c3c298a73f54a7c48684d5e6f3bf"
},
+ {
+ "path": "mocap/gpu_offload.py",
+ "bytes": 3099,
+ "sha256": "278b8b4c935d8ee01527e481a58566c618d7b7997cf479be2100982af2eedeef"
+ },
{
"path": "mocap/gui.py",
- "bytes": 97146,
- "sha256": "61d97281a4f1b167fe987daaa6661566168e38972f4fec280cd33653f21260da"
+ "bytes": 98245,
+ "sha256": "a30b06ec0887f1e329f130f9bfbe8fbb8520e2eb1e1e9c1c14a6521005eeb8e3"
},
{
"path": "mocap/gvhmr_attention.py",
- "bytes": 4747,
- "sha256": "a0fa66d293dde00400c3367fc68cb6b9faeae591c87cabeeb8e06a0bf9f5feaa"
+ "bytes": 4918,
+ "sha256": "d70ff976907917224f93960f4e92732cbd65833483a15e5da7513b3d0f46bf0f"
},
{
"path": "mocap/gvhmr_preprocess.py",
@@ -1241,8 +1266,8 @@
},
{
"path": "mocap/mamma_camera.py",
- "bytes": 8501,
- "sha256": "d9ecc05c5b05175a531a0f2926d3269cb887b3bf6b0a98e27549130e86d40b9d"
+ "bytes": 8530,
+ "sha256": "52588cf37f4082d89a40b7d425e5f0b02f9fe230defb57bf79a0b6f445d57c6e"
},
{
"path": "mocap/mamma_inputs.py",
@@ -1261,8 +1286,8 @@
},
{
"path": "mocap/mamma_pipeline.py",
- "bytes": 18335,
- "sha256": "f8e1649d642536bfa43842aee970b44be569cab388e65828544ecbd86b861407"
+ "bytes": 18768,
+ "sha256": "9330a1e4d7ba4cf633d29d1266e963d429fd081c046c60b01cba3b54ee08b3d9"
},
{
"path": "mocap/mamma_publish.py",
@@ -1281,8 +1306,13 @@
},
{
"path": "mocap/mamma_ui.py",
- "bytes": 29297,
- "sha256": "7f9cce88e6c9842ba6a47001dda2f19d446f0ac4b61d77d8cbdd898a0e6a9510"
+ "bytes": 29355,
+ "sha256": "7de3de21fd0b3499fa39c410e0fd66681f9f116f592d75835b539eec8c77e41e"
+ },
+ {
+ "path": "mocap/memory_mode.py",
+ "bytes": 4515,
+ "sha256": "72e21407be64ccffd9d231fab50ca75f86b30341c5b7e8625c6475c7d8f7a48a"
},
{
"path": "mocap/mesh_data.py",
@@ -1311,8 +1341,13 @@
},
{
"path": "mocap/model_guide.py",
- "bytes": 5689,
- "sha256": "00702e0789973047bd654381ffdf250092904ae633c8d2306f8656a73cf1adf2"
+ "bytes": 6054,
+ "sha256": "fb67dea5a7ff240a4a0c630e53a95786d23931b894b71afb2ea4909d1e8f1772"
+ },
+ {
+ "path": "mocap/model_session.py",
+ "bytes": 3711,
+ "sha256": "5926fbd67ba0b04d207ea17649b8d58b5f801b38d18693453ca8a4fa7e6a8e25"
},
{
"path": "mocap/models.py",
@@ -1351,8 +1386,8 @@
},
{
"path": "mocap/people_ui.py",
- "bytes": 37776,
- "sha256": "1d5d66d7357f1cc3878fd13d7abc6816d8b27d01adfc5c50241be1539ae4517e"
+ "bytes": 38359,
+ "sha256": "87ad12ccdd1008316afea8a673689c3e758aded846f8fdc15abe4789500db744"
},
{
"path": "mocap/person_names.py",
@@ -1361,8 +1396,8 @@
},
{
"path": "mocap/person_tracking.py",
- "bytes": 22670,
- "sha256": "096f62724e78996b2c944db45a2a3151e03a5a72d92ea7aad2ae000c796e2135"
+ "bytes": 22695,
+ "sha256": "39f6422998f9d77a501cd4ac88c2a62cf312cf2be0f01129e9c0e7b8a0dd2b5f"
},
{
"path": "mocap/playback.py",
@@ -1401,8 +1436,8 @@
},
{
"path": "mocap/project_save_ui.py",
- "bytes": 5012,
- "sha256": "697f6918422e6f72611670b4689d1046b623b7fc74d8eb38a211bcc9941296e5"
+ "bytes": 4951,
+ "sha256": "f22116a2031bc6e5a27a3c58fa1125fa0e295c8cbc17fa6612b39661c696950e"
},
{
"path": "mocap/project_storage.py",
@@ -1416,8 +1451,13 @@
},
{
"path": "mocap/project_workspace_ui.py",
- "bytes": 9524,
- "sha256": "f10ff648688a9c4fcb834eae1e5694afaa1e54d574495ed338c3cbc485a70b5d"
+ "bytes": 9847,
+ "sha256": "7248694929c1d209537782cbb922b1348a3702b7a0850c4870fa1f796a03647a"
+ },
+ {
+ "path": "mocap/queue_groups.py",
+ "bytes": 6796,
+ "sha256": "2046210f29db88c43fcd9c7604d864755f17605db84dbe88ce1ac2a6caf62b8a"
},
{
"path": "mocap/resource_cache.py",
@@ -1681,18 +1721,18 @@
},
{
"path": "mocap/worker.py",
- "bytes": 27136,
- "sha256": "50bb259235b7b1d48e95da577941675b2c05576b8888a7f2750d1252b24b52a7"
+ "bytes": 27780,
+ "sha256": "c0d85378bb9361f9ee90a89a1b14445b7e2799cc90ef7973d0e82c614787aaf4"
},
{
"path": "mocap/worker_progress.py",
- "bytes": 1369,
- "sha256": "5d29bc7bf8e461277d0f1f16b7887a69e7693e8288ab60f6fb66bcce4314046a"
+ "bytes": 1602,
+ "sha256": "b98de3237969151882f238ffd50b456910d8517174e08ac58dfddab69d2e2726"
},
{
"path": "mocap/workspace_ui.py",
- "bytes": 33759,
- "sha256": "4fddab25454524539bbaac0f97cc3d60e2bdedf006e7cdd5a3f15d2706daa328"
+ "bytes": 35958,
+ "sha256": "03c4deb4ee046e14cb8a66d09722f6c112d6f518d1aa9b28f3cf16703f490704"
},
{
"path": "native_compat/LICENSE",
@@ -1836,8 +1876,8 @@
},
{
"path": "third_party/ExMR/RGB_MOCAP_PROVENANCE.json",
- "bytes": 349,
- "sha256": "56339cc186743dc33431956dcef40b83fd1b6381af0c22715c75e54432a7a3bc"
+ "bytes": 695,
+ "sha256": "3322623b08c6c8d72d396d61a45371293462d9b9eb1e896045dbaea85f6e7ee1"
},
{
"path": "third_party/ExMR/THIRD_PARTY_NOTICES.md",
@@ -1951,8 +1991,8 @@
},
{
"path": "third_party/ExMR/exmr/pipeline.py",
- "bytes": 12706,
- "sha256": "f6e73bae0f2ce1d6877392a05ef7f6fb134a7b746bb393cb810b82e7c625a8ce"
+ "bytes": 12737,
+ "sha256": "3c6af5830f41eae7641ad5f7b0cce57533393c77ce738af9e4bc1e82ea9ee608"
},
{
"path": "third_party/ExMR/exmr/preprocessing/__init__.py",
@@ -1961,13 +2001,13 @@
},
{
"path": "third_party/ExMR/exmr/preprocessing/body_features.py",
- "bytes": 7052,
- "sha256": "4e020996b920be9ec64677dff9f7a03901c70e98199bc3722d8c3e5370450f74"
+ "bytes": 7654,
+ "sha256": "0c1185773cf2664bea2bab6cb91f32da9b83d709fde81cdfc63c5da9752dd308"
},
{
"path": "third_party/ExMR/exmr/preprocessing/hand_features.py",
- "bytes": 8338,
- "sha256": "781a2b2e658e4817da619acd967361249c8f444717750c557e47039a7b12b113"
+ "bytes": 8651,
+ "sha256": "d2d1af59b5c0e2edb44932262625d24db1e20b887beda510b0f437bf6806a39c"
},
{
"path": "third_party/ExMR/exmr/preprocessing/image_io.py",
@@ -1991,8 +2031,8 @@
},
{
"path": "third_party/ExMR/exmr/preprocessing/keypoints/sapiens2.py",
- "bytes": 9300,
- "sha256": "1eecc3f92b4ee2c7cbd32234736927f934b76ac2820bb44ef563e02ce2a7bf8e"
+ "bytes": 9674,
+ "sha256": "d3a7364e0e50efca09f83843ee2ad95a06d38a458c34df04498c97b8d691c1b9"
},
{
"path": "third_party/ExMR/exmr/preprocessing/tracker.py",
@@ -3626,8 +3666,8 @@
},
{
"path": "third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/decoders/promptable_decoder.py",
- "bytes": 7389,
- "sha256": "73c1219c176478e52358d9448d8087017e8294202653ca9fb62e2c964f7c363a"
+ "bytes": 7473,
+ "sha256": "0d909d2f1f9710e36a06209995e5885f3176594d4fb9f8ccc9d4f099bb34a65b"
},
{
"path": "third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/heads/__init__.py",
@@ -3661,8 +3701,8 @@
},
{
"path": "third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py",
- "bytes": 80820,
- "sha256": "851b7475f18b56891aa02606e7c0ee9e03120fa208cc85df5127b792e1abfeee"
+ "bytes": 80890,
+ "sha256": "577a570d35889939bd3b0aacef4faa30598ec246b97b8f37b70c247d3fa0aa4f"
},
{
"path": "third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/modules/__init__.py",
@@ -5331,8 +5371,8 @@
},
{
"path": "third_party/FlowHMR/flowhmr/utils/runtime_vggt_camera.py",
- "bytes": 14558,
- "sha256": "a0ef0f3bf6d4df8554dd8771334309d79f90ecf02f128e7ef521fe148408df71"
+ "bytes": 14600,
+ "sha256": "0793265c936d39afea38ed8730a45f3b20d083ba0169519ebd7b6c7e378b1fbe"
},
{
"path": "third_party/FlowHMR/flowhmr/utils/runtime_video_processing.py",
@@ -6816,8 +6856,8 @@
},
{
"path": "third_party/FlowHMR/third_party/fast-sam-3d-body/RGB_MOCAP_PROVENANCE.json",
- "bytes": 211,
- "sha256": "50fd567e730dc8aabdeb4b7cb1da79324f9e6d57491ffb768fb5d974ae22653d"
+ "bytes": 468,
+ "sha256": "8ac46280fc2ffd75e3d441deba84acf897777c52f640dba9a607a5a74fb876e4"
},
{
"path": "third_party/FlowHMR/third_party/fast-sam-3d-body/SAM_LICENSE",
@@ -6951,8 +6991,8 @@
},
{
"path": "third_party/FlowHMR/third_party/fast-sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py",
- "bytes": 176166,
- "sha256": "33d6c8969d69d3b6185df831986387f76f888293eebb7378d30ba29cbb4e8a40"
+ "bytes": 177095,
+ "sha256": "87c933f34ba98e1c277963120264b63fc94bd55e6df584d796d2bb26f317b803"
},
{
"path": "third_party/FlowHMR/third_party/fast-sam-3d-body/sam_3d_body/models/modules/__init__.py",
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index cc5be98..ee0c422 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -10,6 +10,35 @@ This guide is for agents helping users operate or modify RGB MoCap. It describes
- Close the app before `update.cmd`. The updater requires a clean tracked worktree and the `main` branch, uses `git pull --ff-only`, then verifies/repairs runtime configuration. It refuses tracked local edits. A plain `git pull` does not perform runtime repair; use `install.cmd` after dependency changes when needed. Do not discard local edits or force an update.
- For setup failure, read the message, check connectivity and free space, then retry `install.cmd`. Preserve models, projects and `.setup` state. Do not repeatedly reinstall or redownload models without evidence.
- Base installation currently estimates at least 32.4 GiB free before models; the three single-video models and add-ons were previously measured around 29 GiB of weights. Optional MAMMA adds a separate runtime and model files; see [its setup guide](MAMMA.md). Project data and download caches add space. Measurements are not guarantees. See [user guide](USER_GUIDE.md#install).
+
+Multi-person reconstruction groups supported ExMR, FlowHMR and GVHMR phases
+into sequential, bounded worker requests. `mocap/queue_groups.py` builds the queue;
+`batch_worker.py` validates explicit project paths and runs one `ModelSession`
+per phase. ExMR connects its keypoint, body-feature, hand-feature and motion
+phases in one worker, for one or multiple actors. FlowHMR connects features and
+motion for one actor; its existing multi-person phase grouping remains separate.
+GVHMR runs its phases in one worker with a new closed scope for each.
+The session retains at most one model and clears transient tokens.
+It closes on completion/error; cancellation terminates the worker tree. Keep
+per-actor receipts and pending markers, separate runtimes, precision, full temporal
+context and optional add-on behavior intact. A fresh CUDA OOM recovery discards
+the cached model before its one supported Low Memory retry. Do not replace this
+with an indefinite global pool or parallel GPU workers.
+
+`mocap/batch_prefetch.py` overlaps CPU image preparation with inference using
+one producer thread and at most two prepared batches. Automatic enables it only
+with sufficient CPU/RAM headroom; Low Memory disables it. Prepared batch storage
+is additionally bounded by a 256 MiB estimate. Always close the producer before
+closing its video capture or retrying an operation. ExMR body feature extraction
+skips only the final unused pose readouts after the collected token is complete;
+keep intermediate pose feedback, keypoint-token updates and the generic SAM path.
+HaMeR's normal decoder/readout path remains intact. Do not change precision,
+batch size, resolution or temporal context to claim further speedups.
+
+This overlaps existing reads/crops; it does not introduce a persistent disk
+cache. The two prepared batches are in addition to the batch being consumed.
+The 256 MiB prepared-storage estimate is not a hard cap on whole-process RAM;
+retain actual memory monitoring and deterministic producer cleanup.
## Models and model files
@@ -49,7 +78,7 @@ verification, registration and rollback, use the
validate actual native CUDA operations. Do not overwrite a working runtime to
test a new native module, or use cached inference as evidence of a new build.
-1. **File > Open Video**, optionally trim the Video track; select an AI Motion Model and prepare its models. New work defaults to ExMR.
+1. Select an AI Motion Model and prepare its models, then **File > Open Video** and optionally trim the Video track. Select MAMMA before opening multiple videos. New work defaults to ExMR.
2. For single-video models with multiple people, use **Find person** and check the desired rows; without it, automatic tracking selects one person and can switch identity on overlap. MAMMA instead detects and matches people during reconstruction; Find person is hidden and its People setting controls the count. A checked row controls visibility and single-video processing targets; the selected row controls the current timeline and contact edits.
3. Choose camera and processing settings, then **Reconstruct 3D**. Processing runs on a 30 fps working clip, without changing the original video. Progress and cancellation are in the app. **Prepare Preview** rebuilds previews from existing motion without rerunning inference.
4. Review motion and contacts. **Enable Correction** selects corrected output; Foot defaults on and Hand off for new work. Flat Ground uses a common floor; Multi Level retains inferred contact heights and does not reconstruct terrain. Inspect automatic contacts; hand contacts represent support, not hanging/object tracking.
@@ -58,6 +87,15 @@ test a new native module, or use cached inference as evidence of a new build.
See [the full workflow and controls](USER_GUIDE.md#start-here). Do not confuse viewport toggles, automatic detection and applied motion corrections. No general scene geometry or collision reconstruction is implied.
+Contact correction v9 joins free-foot transitions to the final planned root
+and evaluates floor clearance continuously inside the bounded trajectory plan.
+Keep stance anchors/timings and source ankle frames fixed; do not smooth final
+leg quaternions or add a second IK pass. The native anatomical solver remains
+the only publisher of leg rotations. Planning-limit warnings are real residual
+notices. Existing saved previews are not automatically replaced; use Apply
+Correction to recompute without inference. See the v9 measurements and limits
+in [validation](VALIDATION.md#contact-correction-v9-coherent-root-and-swing-transitions-2026-10-30).
+
## Character retargeting and export
- **File > Import Character...** accepts Mixamo-style FBX, VRM and PMX, and adds the character in rest pose below people. Up to eight characters per project are supported.
@@ -76,9 +114,44 @@ See [the full workflow and controls](USER_GUIDE.md#start-here). Do not confuse v
## Resources and performance
-Use **Resource Mode > Automatic** by default. **Low Memory** uses smaller image batches in supported single-video stages; it is a separate choice, not a promise every clip will fit. MAMMA retains its pinned masks/landmark/fitting settings: Low Memory does not reduce its view count, fitting iterations or precision. GPU/CPU memory availability, resolution, clip duration and camera settings affect workloads. Model processing is not rejected using predicted RAM/VRAM requirements. The desktop checks actual available RAM and Windows allocation headroom every 0.5 seconds and stops the worker tree when these become low; actual allocation failures also produce an error. Close competing applications or shorten the clip after a memory-related stop. Keep genuine model frame limits, bounded buffers and adaptive batch/attention choices; do not silently change model quality or truncate motion. Avoid expensive AI reruns for operations that can use existing results.
-
-GPU allocator limits share ComfyUI's external-use margin: 600 MiB on Windows, 700 MiB above 15 GiB GPU capacity (400 MiB on other systems). Subtract it from actual free VRAM without an additional percentage cap or fixed FlowHMR/ExMR 3/2 GiB reserve. This margin is separate from inference working space, which stays inside the allocator budget. Do not copy ComfyUI's model offload or quality-changing policies into these models.
+Use **Resource Mode > Automatic** by default. It keeps the fast path when the current GPU budget is sufficient and selects supported Low Memory paths per operation when needed. A supported fast operation that raises CUDA OOM is released and retried once in Low Memory. ExMR Low Memory uses CPU-first body/hand loading and converts Sapiens' existing FP16 layers before GPU transfer; ExMR body/hand batches stay 8. FlowHMR offloads SAM/VGGT blocks; MAMMA offloads VGGT camera blocks while retaining its pinned masks/landmark/fitting settings. GVHMR/add-ons retain adaptive image batches and full-context attention. The saved Automatic selection is not changed. Resource decisions and memory advice appear in the app Console and CMD. Model precision, frame count, resolution and iterations are not reduced. CPU loading/offloading can be slower and use more RAM; it is not a promise every clip will fit. Estimates select a path, never reject a job. The desktop still checks actual RAM and Windows allocation headroom every 0.5 seconds and stops workers when these become low. Preserve completed stages, genuine model limits and original motion. Do not rerun inference for operations that can use existing results.
+
+GPU allocator limits share ComfyUI's external-use margin: 600 MiB on Windows, 700 MiB above 15 GiB GPU capacity (400 MiB on other systems). Subtract it from actual free VRAM without an additional percentage cap or fixed FlowHMR/ExMR 3/2 GiB reserve. This margin is separate from inference working space. Keep offloading in the app's validated `memory_mode.py` / `gpu_offload.py` adapters, without importing ComfyUI or changing model precision. Offload is inference-only, synchronous and unpinned; close hooks/models on success and failure. Actual RAM pressure remains a stop condition because offloading can increase host memory.
+
+### Measured savings and acceleration
+
+Use [PERFORMANCE.md](PERFORMANCE.md) for recorded conditions and current applied
+methods, and [older processing records](USER_GUIDE.md#recorded-processing-time-and-vram)
+for historical long-clip observations. Do not present old timings as a current
+release forecast. On the documented RTX 5090 PC:
+
+| Observation | Result and scope |
+| --- | --- |
+| ExMR Automatic → Low Memory | Allocated VRAM **5.68 → 3.87 GiB**, RAM working set **11.88 → 11.94 GiB**, **89.01 → 94.78 s**; earlier 60-frame app-mode check. |
+| FlowHMR Automatic → Low Memory | Allocated VRAM **6.10 → 2.77 GiB**, RAM **8.42 → 8.75 GiB**, **95.24 → 96.15 s**; earlier 60-frame app-mode check. |
+| GVHMR + add-ons, same short mode check | No meaningful whole-job saving: **4.204 → 4.203 GiB** allocated VRAM. Low Memory need not benefit a short job that already fits. |
+| MAMMA | Whole-pipeline paired VRAM saving was not recorded. Shared VGGT component offload saved **52%** allocated VRAM but took **3.3×** as long in warm inference; it is not whole-MAMMA offloading. |
+| Connected phase workers | One-person / 60-frame worker time fell **44% for ExMR**, **24% for FlowHMR**, with unchanged measured peak VRAM. Excludes discovery, cameras, correction and export. |
+| Bounded prefetch / warm feature stages | Flow Fast SAM about **5% less time**; ExMR Sapiens/hand about **25% less**, body with unused readouts omitted **29% less**. Similar VRAM, sometimes slightly more RAM. |
+
+The mode checks predate the latest acceleration. Low Memory saves GPU memory,
+not necessarily RAM; individual CPU-loaded models can add several GiB of host
+working set. Automatic selects a path per operation, not from a guaranteed
+whole-job capacity prediction. FlowHMR's Low Memory SAM batch is one even when
+the saved 4-Frame Batching box is on; its GPU Hand Crops selection is retained.
+The two Fast SAM switches default on for new work, preserve saved off settings,
+and only apply with Fast SAM. See [their separate measurements and output differences](PERFORMANCE.md#flowhmr-fast-sam-switches).
+
+When reporting new tests, keep inputs, model files, settings and timing scope
+fixed. Separate cold worker startup from warm inference, allocated from reserved
+VRAM, and working set from private/system RAM. Do not sum speedups from different
+baselines or use sampled worker peaks as whole-PC usage/minimum requirements.
+Fixed-feature motion was exact in the latest validation; fresh preprocessing
+had maximum joint differences below 0.9 mm, with baseline repeats also varying.
+The GPU-crop comparison is separate and reached 4.8 mm maximum. Neither measures
+accuracy against ground truth. Preserve these distinctions and numerical paths.
+Keep private benchmark projects, raw logs, account details, machine paths and
+licensed assets out of public documentation; publish only curated measurements.
The app uses separate runtime profiles to maintain compatibility, with bounded batches, previews and background workers. Keep video decoding, large I/O and numerical work off the GUI thread. Playback responsiveness, synchronization and resource cleanup are correctness requirements. If changes affect these, measure frame-time outliers and repeated open/close behavior; do not infer universal performance from a short test.
diff --git a/docs/MAMMA.md b/docs/MAMMA.md
index 8724d28..b26bcb3 100644
--- a/docs/MAMMA.md
+++ b/docs/MAMMA.md
@@ -177,9 +177,49 @@ standalone tests remain separate. No quantization, TF32, iteration reduction or
physics simulation is enabled in this path.
Low Memory does not select smaller MAMMA camera sets, fewer fitting iterations
-or a lower-precision model. The shared allocator budget and system-memory guard
+or a lower-precision model. It keeps VGGT camera transformer blocks on CPU and
+transfers them for inference. Automatic uses the fast camera path when GPU memory
+is sufficient, selects offloading when needed, and can recover once from a camera
+CUDA OOM. Decisions and Low Memory advice appear in Console and the CMD window.
+Offloading may be slower and use more RAM; masks, landmarks and fitting retain
+their existing bounded settings. The shared allocator budget and system-memory guard
still apply; shorten the common clip or reduce input views yourself if needed.
+## Applied acceleration and resource modes
+
+The supported path uses exact-coordinate ROI landmark preprocessing, CPU
+checkpoint loading and the supplied masks instead of an unnecessary landmark
+detector. It omits unused mask/collage/debug videos and reduces fitting
+diagnostics. VGGT samples up to three times per fixed camera at its 512 input
+setting and omits unneeded depth output. Matching completed inference is reused;
+contact edits and correction do not require another MAMMA inference.
+
+Earlier four-view, two-person, 30-frame tests on the RTX 5090 test PC measured:
+
+| Applied change | Stage time before → after | Time reduction |
+| --- | ---: | ---: |
+| Exact ROI preprocessing + CPU checkpoint loading, FP32 landmarks | 104.43 → 57.18 s | 45% |
+| Omit unused outputs during mask processing | 129.02 → 92.39 s | 28% |
+
+These isolated stage gains must not be added together or treated as a whole-job
+speedup. Reducing fitting diagnostics did not show a reliable fitting-stage gain.
+The latest ExMR/FlowHMR CPU prefetch and connected-worker changes do not apply
+to MAMMA, which already processes multiple people together.
+
+**Low Memory offloads VGGT only**, not the full landmark/fitting pipeline. A
+controlled shared-VGGT test with nine images from three cameras measured
+allocated VRAM **6.47 → 3.14 GiB** (52% less), RAM working set **8.75 → 8.85 GiB**,
+and warm inference **0.225 → 0.751 s** (3.3× as long). That is a camera-component
+measurement, not a 52% saving for all of MAMMA.
+
+A separate paired app-mode check used two views, two people and 30 frames:
+RAM was **8.15 → 8.12 GiB**, and total time **241.61 → 222.00 s**. Whole-pipeline
+VRAM was not recorded for that pair, so its VRAM saving is **not established**.
+Startup/cache variation affects these single-pass times; Low Memory is not a
+reliable speed improvement. It can require more RAM. The mode does not reduce
+views, fitting iterations or precision, and cannot guarantee that fitting fits.
+See [common benchmark conditions and memory definitions](PERFORMANCE.md).
+
## Manual cameras
Selecting Manual Camera Data disables the reference-height control: metric
@@ -202,7 +242,7 @@ does not calibrate a video; use VGGT when you do not have matching calibration.
| `extrinsics_convention` | `"world_to_camera"`. |
| `cameras` | Object containing one entry for every opened video. Each key must exactly match its filename without the extension: `A001.mp4` → `A001`. Remove unused camera entries when opening only a subset of views. |
| `intrinsic_matrix` | 3×3 matrix `[[fx,0,cx],[0,fy,cy],[0,0,1]]`. Focal lengths `fx,fy` and optical center `cx,cy` are in pixels for the original input resolution. |
-| `extrinsics_matrix` | 3×4 matrix `[R | t]`, or 4×4 with last row `[0,0,0,1]`. `R` is a proper rotation; `t` is a translation in metres. Maps a world point to camera coordinates: `p_camera = R @ p_world + t`. |
+| `extrinsics_matrix` | 3×4 matrix `[R \| t]`, or 4×4 with last row `[0,0,0,1]`. `R` is a proper rotation; `t` is a translation in metres. Maps a world point to camera coordinates: `p_camera = R @ p_world + t`. |
| `image_size` | `[width,height]` in pixels, matching the original opened video, not the app's resized working copy. |
| `distortion_coeffs` | Optional `[k1,k2,p1,p2]` or `[k1,k2,p1,p2,k3]`. Omitted means zero. The current app adapter requires all zeros and undistorted pinhole footage. |
@@ -241,6 +281,29 @@ converts this to world-to-camera matrices. JSON uses the matrix convention above
MAMMA's `configs/examples/captures/*.json` files describe input datasets and
processing paths; they are **not camera calibration files** for this button.
+## Recorded processing time and memory
+
+On the tested RTX 5090 32 GB / Ryzen 9 9950X / 96 GB RAM PC, a manual app test
+used three synchronized camera videos resized within 1920×1080, two people,
+SAM 2.1 masks and automatic VGGT cameras. The common trim was 413 frames at
+30 fps (13.77 seconds).
+
+| Input length | Videos | People | Total through correction/preview | Peak VRAM (GiB) | Peak RAM (GiB) |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| 13.8 seconds | 3 | 2 | 11m 52s | 6.47 | 9.11 |
+
+Masks took 257.80 s, landmarks 89.72 s, cameras 14.42 s, 3D fitting 294.42 s,
+and correction/preview 31.97 s. The 712.08-second total also includes video
+preparation/startup. Peak VRAM is PyTorch allocated memory; peak RAM is worker
+working set, measured across masks, landmarks, cameras and fitting. They exclude
+unmeasured preparation/correction/preview peaks and are not whole-PC usage.
+No fatal traceback or OOM appeared in that log.
+
+This historical run predates the latest Low Memory changes. It uses different
+input and stages from the [single-video model records](USER_GUIDE.md#recorded-processing-time-and-vram),
+so it is not a direct speed ranking or a minimum hardware requirement. Camera
+count, resolution, clip length, people and hardware can change both time and memory.
+
## Saved data and limitations
**Save Project As** copies all camera videos and project-private body data.
@@ -269,12 +332,9 @@ require reconstruction and leave the previous displayed motion in place.
Occlusion, segmentation/identity mistakes, weak camera baselines and uncertain
scale can still produce poor poses. Contact correction reduces sliding but does
not repair lost identities, bad camera geometry or missing observations. This
-integration was tested on one Windows/NVIDIA PC. A three-view, two-person manual
-test processed 413 frames at 30 fps through correction/preview in **712.08 s**:
-masks 257.80 s, landmarks 89.72 s, cameras 14.42 s, fitting 294.42 s and final
-correction/preview 31.97 s; the remainder was video preparation/startup.
-No fatal traceback or OOM appeared in that log. This is one observation, not a
-speed guarantee. Clean Windows, other GPUs and the full 60-second limit have
+integration was tested on one Windows/NVIDIA PC; see the
+[recorded processing and memory](#recorded-processing-time-and-memory).
+Clean Windows, other GPUs and the full 60-second limit have
not been validated.
## Updates and troubleshooting
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
new file mode 100644
index 0000000..a9c9211
--- /dev/null
+++ b/docs/PERFORMANCE.md
@@ -0,0 +1,186 @@
+# Resource modes and measured optimizations
+
+These are measurements on one Windows PC: RTX 5090 32 GB, Ryzen 9 9950X,
+96 GB RAM. They are observations, not minimum hardware requirements or promised
+speedups. No clean-Windows or other-GPU certification is implied. Source videos,
+private projects and benchmark scripts are not included in this repository.
+
+## Automatic or Low Memory?
+
+| Mode | Behavior | Trade-off |
+| --- | --- | --- |
+| **Automatic** — default | Uses the fast supported path when the current GPU budget is sufficient. Selects the supported Low Memory path per operation when needed; supported fast operations can release their failed allocation and retry once after CUDA OOM. | Usually the best starting point. The saved selection stays Automatic even when one operation falls back. |
+| **Low Memory** | Requests CPU-first loading, block offloading or bounded image work, depending on the model. Disables the new CPU batch prefetch. FlowHMR SAM uses one frame per batch. | Reduces some VRAM peaks, but transfers/loading can take longer and system RAM can increase. It does not guarantee that a model or long sequence fits. |
+
+Neither mode deliberately lowers the existing model-native precision, input
+resolution, motion frame count or temporal context. MAMMA keeps the selected
+views and fitting iterations. Existing native mixed precision remains in use;
+this is not a claim that every model layer is FP32.
+
+**Low Memory is primarily a VRAM-saving mode, not a system-RAM-saving mode.**
+Actual RAM and Windows allocation headroom are monitored in both modes. Work
+stops with an error when memory becomes insufficient; close other applications
+or shorten the clip if necessary. Decisions and memory advice appear in both
+the app Console and CMD window.
+
+### What changes for each model
+
+| Model | Low Memory behavior |
+| --- | --- |
+| ExMR | Load body/hand checkpoints on CPU before GPU transfer; prepare Sapiens' existing FP16 layers on CPU. Body/hand batches remain 8. |
+| FlowHMR | Offload SAM/VGGT transformer blocks to CPU and transfer them for inference. SAM uses one frame per batch; the saved GPU Hand Crops selection is retained. |
+| GVHMR and add-ons | Use existing adaptive image batches and bounded processing. Preserve full-context FP32 attention; use the validated query split only when dense attention does not fit or after its supported OOM recovery. |
+| MAMMA | Offload the VGGT camera transformer blocks. Masks, FP32 landmarks and 3D fitting keep their current settings; this is not full-MAMMA model offloading. |
+
+## Measured memory savings
+
+### Paired application runs
+
+The following earlier mode-validation runs used 60 frames at 30 fps per
+single-video model, including correction and preview/export preparation.
+GVHMR included HTD, FootMR and HandFlow; FlowHMR included camera estimation.
+They **predate the latest batching/prefetch and connected-worker changes**,
+so their times are historical mode checks, not the current release's speed.
+Both modes used the same clip/settings for each model.
+
+| Model | Peak VRAM: Automatic → Low Memory | VRAM reduction | Peak RAM: Automatic → Low Memory | Time: Automatic → Low Memory |
+| --- | ---: | ---: | ---: | ---: |
+| ExMR | 5.68 → 3.87 GiB | 1.81 GiB / 32% | 11.88 → 11.94 GiB | 89.01 → 94.78 s |
+| FlowHMR | 6.10 → 2.77 GiB | 3.33 GiB / 55% | 8.42 → 8.75 GiB | 95.24 → 96.15 s |
+| GVHMR + add-ons | 4.204 → 4.203 GiB | No meaningful reduction on this short clip | 6.87 → 6.85 GiB | 127.53 → 113.28 s |
+| MAMMA, 2 views / 2 people / 30 frames | Not recorded in this paired run | Not established for the whole pipeline | 8.15 → 8.12 GiB | 241.61 → 222.00 s |
+
+VRAM means maximum recorded **PyTorch allocated** memory across workers, not
+reserved memory or whole-board usage. RAM is sampled process-tree working set;
+shared pages can be counted more than once. The table does not report total
+system memory. Startup, kernel initialization and filesystem caching affect
+these single-pass times; lower times in a Low Memory row do not establish that
+Low Memory is faster. Stage-specific savings can disappear from the whole-job
+peak when another stage uses more memory.
+
+### Loading/offload trade-offs measured separately
+
+These controlled component tests help explain where memory is saved. They are
+not additional whole-application savings to add to the preceding table.
+
+| Component / change | Peak allocated VRAM, whole component run | Peak process RAM working set | Measured time scope |
+| --- | ---: | ---: | --- |
+| ExMR Sapiens: prepare existing FP16 layers before GPU transfer | 5.68 → 3.10 GiB | 11.91 → 11.96 GiB | Loading: 12.24 → 12.63 s; warm inference: 1.47 → 1.45 s |
+| ExMR body: CPU-first checkpoint loading | 4.91 → 3.77 GiB | 5.32 → 6.84 GiB | Loading: 4.28 → 9.97 s |
+| ExMR hand: CPU-first checkpoint loading | 5.14 → 3.87 GiB | 1.54 → 5.79 GiB | Loading: 2.46 → 3.21 s |
+| Shared VGGT camera component: block offload | 6.47 → 3.14 GiB | 8.75 → 8.85 GiB | Warm inference: 0.225 → 0.751 s |
+
+ExMR used a 60-frame clip. VGGT used nine images from three cameras, at its
+512 input setting; its shared component is used by FlowHMR and MAMMA. Offload
+cut that component's peak by about **3.33 GiB / 52%**, but warm inference took
+about **3.3 times as long**. This does not establish a 52% reduction for MAMMA's
+full fitting pipeline. For that pipeline, see the separate
+[MAMMA processing records](MAMMA.md#recorded-processing-time-and-memory).
+
+## Applied speed improvements
+
+The following methods are enabled by the current app. Their measurements use
+different stages and baselines; **do not add or multiply the speedups** to
+estimate a complete job. No extra packages, quantization, TensorRT engine or
+user compilation is needed for these optimizations. MAMMA's optional runtime
+still has its separately documented installation/build requirements.
+
+### Model reuse and connected workers
+
+One resident model serves actors sequentially, then is released before the next
+phase. This avoids repeatedly loading the same weights without making a larger
+multi-person GPU batch. A first two-person test used 60+45 frames, static cameras,
+and feature/core stages only, with one timing trial:
+
+| Model | Independent actor workers → model reuse | Time reduction | Peak allocated VRAM before → after |
+| --- | ---: | ---: | ---: |
+| FlowHMR | 108.69 → 65.34 s | 40% | 3.84 → 3.84 GiB |
+| ExMR | 161.08 → 106.51 s | 34% | 5.68 → 5.68 GiB |
+| GVHMR, without add-ons in this timing | 56.02 → 22.97 s | 59% | About 2.82 GiB in both |
+
+A later two-trial comparison connected phases after phase-scoped reuse was
+already available. Values below are means; worker startup and result saving
+are included, while discovery, camera estimation, correction and export are not.
+
+| Model / people | Separate phase workers → connected phases | Time reduction | Peak allocated VRAM | Peak RAM working set before → after |
+| --- | ---: | ---: | ---: | ---: |
+| FlowHMR / 1 / 60 frames | 55.99 → 42.65 s | 24% | 3.84 GiB in both | 6.75 → 6.81 GiB |
+| ExMR / 1 / 60 frames | 83.86 → 46.66 s | 44% | 5.68 GiB in both | 11.92 → 11.74 GiB |
+| ExMR / 2 / 60+45 frames | 92.83 → 53.29 s | 43% | 5.68 GiB in both | 11.77 → 11.81 GiB |
+
+ExMR now connects keypoint, body-feature, hand-feature and motion phases.
+FlowHMR connects features and motion for one actor; its two-person connection
+gain was smaller than trial variability, so the existing multi-person phase
+grouping remains. GVHMR already connects its observation/core phases. Short-clip
+startup gains do not predict the same percentages on long footage.
+
+### Bounded CPU preparation and unused body readouts
+
+Automatic prepares at most two CPU batches ahead when CPU/RAM headroom permits;
+Low Memory disables it. There is one producer thread and an additional 256 MiB
+limit on estimated prepared storage, in addition to the batch being consumed.
+This is not a whole-process RAM cap. It overlaps reading/cropping with GPU work, without
+writing an extra disk cache. Actual RAM monitoring remains active.
+
+Warm tests processed 60-, 45- and 120-frame inputs twice: **450 frames per
+variant**. The first two inputs were 720x1280; the third was 1080x1920, at 30 fps.
+Times exclude model loading/warm-up, and RAM is sampled process working set.
+
+| Stage / applied optimization | Time before → after | Reduction | Peak VRAM before → after | Peak RAM before → after |
+| --- | ---: | ---: | ---: | ---: |
+| Flow Fast SAM / CPU prefetch | 42.96 → 40.79 s | 5% | 3.84 → 3.84 GiB | 2.45 → 2.49 GiB |
+| ExMR Sapiens / CPU prefetch | 11.53 → 8.63 s | 25% | 3.10 → 3.10 GiB | 4.07 → 4.10 GiB |
+| ExMR body / prefetch + unused final pose-readout omission | 18.57 → 13.15 s | 29% | 3.80 → 3.80 GiB | 5.43 → 5.42 GiB |
+| ExMR hand / CPU prefetch | 7.50 → 5.63 s | 25% | 3.87 → 3.87 GiB | 1.67 → 1.67 GiB |
+
+Body-readout omission alone reduced 18.57 to 16.63 s, about 10%. Intermediate
+pose feedback and keypoint-token updates remain. Hand-readout omission had no
+clear benefit and was not adopted. Small RAM decreases in this table are sample
+variation, not a RAM-saving feature.
+
+Fixed-feature motion comparisons were tensor-exact. With fresh optimized image
+preprocessing, maximum joint differences were 0.83 mm for FlowHMR and 0.88 mm
+for ExMR; baseline repeats also differed, up to 0.77 and 0.69 mm. These are
+output disagreements, not accuracy against ground-truth capture.
+
+### FlowHMR Fast SAM switches
+
+Both switches default on for new work; saved off settings remain off. They work
+only with Fast SAM and can be controlled independently:
+
+- **4-Frame Batching:** warm feature extraction was about **2.0–2.4 times faster**
+ than one-frame processing. Peak allocated VRAM rose **3.44 → 3.84 GiB** and
+ reserved VRAM **3.74 → 4.45 GiB**; RAM working set was about 6.47 GiB in both.
+ Low Memory uses one-frame batches.
+- **GPU Hand Crops:** on top of batching, separate short clips took
+ **6.10 → 5.44 s** and **10.87 → 9.81 s**, roughly 10% less feature time,
+ with unchanged 3.84 GiB allocated VRAM and about 6.47 GiB RAM. An alternating
+ repeated test found a smaller 8% median time reduction, showing variability.
+
+These are warm feature-stage results, not whole-job speedups. GPU interpolation
+differs from CPU OpenCV cropping; combined output differences reached about
+1.1–1.3 mm at the 95th percentile and 4.8 mm maximum joint displacement in the
+tested clips. This is a separate comparison from the sub-millimetre prefetch
+test above. Inspect your motion/contact timings rather than assuming bit identity.
+
+### MAMMA
+
+The current MAMMA adapter uses exact-coordinate ROI preprocessing, CPU checkpoint
+loading, a mask-based landmark path without an unnecessary detector, fewer
+unused video/debug outputs and reduced fitting diagnostics. Fixed-camera VGGT
+uses up to three sampled times per camera at its 512 input setting and omits
+unneeded depth output. Completed inference is reused when identities/receipts
+match; changing only contact correction does not run MAMMA again.
+
+Earlier four-camera, two-person, 30-frame FP32 tests measured landmark processing
+**104.43 → 57.18 s** (45% less time) with exact ROI/CPU loading, and mask
+processing **129.02 → 92.39 s** (28% less time) after omitting unused outputs.
+Reduced fitting logs did not show a reliable fitting-stage speedup. These are
+stage measurements, not a prediction for a complete capture.
+
+MAMMA uses SAM 2.1 and FP32 landmarks/fitting in the app. SAM 3.1, quantization,
+additional TF32, reduced fitting iterations and full fitting-model offload
+remain outside the supported app path. The latest ExMR/FlowHMR prefetch and
+connected-worker changes were not added to MAMMA.
+
+For remaining scope and actual checks, see [validation](VALIDATION.md).
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 15f51d4..35aa31f 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -227,6 +227,20 @@ Model weights remain in the app's model
library. Trimming does not modify the original video. Processing uses a
30 fps working clip; camera sampling does not reduce its motion frame count.
+When reconstructing several people or visible takes with ExMR, FlowHMR or
+GVHMR, RGB MoCap processes the same stage for each actor in turn using one loaded
+model, then releases it before the next stage. ExMR connects keypoint, body/hand
+features and motion phases in one worker. FlowHMR connects features and motion
+for one person; its multi-person jobs retain separate phase grouping. GVHMR keeps
+its observation and motion stages in one worker. Each actor keeps separate
+motion, contacts and exports. This reduces repeated model loading; it does not
+combine people into a larger GPU batch. Automatic and Low Memory still apply.
+Optional GVHMR refinement/add-ons use their existing separate workers.
+
+Automatic can overlap bounded CPU image preparation with GPU work when CPU/RAM
+headroom permits; Low Memory disables that prefetch. For measured worker-startup
+and feature-stage gains, see [resource modes and optimizations](PERFORMANCE.md).
+
## Choose a model
Each model has a [detailed guide](models/README.md): [ExMR](models/EXMR.md),
@@ -269,7 +283,7 @@ Run **Setup_MAMMA.cmd** separately after the base installation; Model Manager >
**Runtime Setup...** explains its compiler prerequisites, disk use and restricted
licenses. Prepare the nine model assets through Model Manager. MAMMA detects and
matches people during reconstruction, so **Find person** is hidden. **People** can
-be Auto or a fixed count. Enter only the number in **Reference Height (m)**; this
+be **0** for automatic detection or a fixed count. Enter only the number in **Reference Height (m)**; this
sets approximate VGGT scale and is unused with metric camera calibration.
For example, enter `1.70` for 170 cm; it does not force all actors to the same
height. Input videos must already start in sync and show the same performance.
@@ -278,27 +292,42 @@ The app uses SAM 2.1 and FP32 fitting; SAM 3.1 research tests remain separate.
## Recorded processing time and VRAM
-Historical measurements on the tested PC above (30 fps inputs, October 2026),
-recorded before the current Git-based installation was tested.
-Each duration uses the same input across all three models.
-
-| Video length | Model | Processing time | Peak VRAM (GiB) |
-| --- | --- | ---: | ---: |
-| 7 seconds | ExMR | 1m 08s | 11.32 |
-| 7 seconds | FlowHMR | 2m 49s | 14.89 |
-| 7 seconds | GVHMR | 2m 01s | 5.08 |
-| 15 seconds | ExMR | 1m 47s | 11.32 |
-| 15 seconds | FlowHMR | 5m 16s | 10.79 |
-| 15 seconds | GVHMR | 2m 45s | 5.08 |
-| 25.7 seconds | ExMR | 1m 44s | 11.32 |
-| 25.7 seconds | FlowHMR | 7m 32s | 10.67 |
-| 25.7 seconds | GVHMR | 3m 00s | 5.08 |
-
-Times cover the recorded model-processing stages, excluding shared person
+Historical measurements on the tested PC above (30 fps inputs, October 2026).
+Each single-video duration uses the same input across ExMR, FlowHMR and GVHMR.
+MAMMA uses a different multi-view clip and includes more processing stages;
+its row is not a direct speed comparison. These records predate the latest
+Low Memory changes.
+
+For mode comparisons and the latest applied acceleration, see
+[measured memory savings and speedups](PERFORMANCE.md). Those tests use different
+clips and timing scopes from this historical table.
+
+| Video length | Model | Input videos | Processing time | Peak VRAM (GiB) | Peak RAM (GiB) |
+| --- | --- | ---: | ---: | ---: | ---: |
+| 7 seconds | ExMR | 1 | 1m 08s | 11.32 | 19.31 |
+| 7 seconds | FlowHMR | 1 | 2m 49s | 14.89 | 22.19 |
+| 7 seconds | GVHMR | 1 | 2m 01s | 5.08 | 12.47 |
+| 15 seconds | ExMR | 1 | 1m 47s | 11.32 | 19.31 |
+| 15 seconds | FlowHMR | 1 | 5m 16s | 10.79 | 16.97 |
+| 15 seconds | GVHMR | 1 | 2m 45s | 5.08 | 11.06 |
+| 25.7 seconds | ExMR | 1 | 1m 44s | 11.32 | 19.31 |
+| 25.7 seconds | FlowHMR | 1 | 7m 32s | 10.67 | 16.94 |
+| 25.7 seconds | GVHMR | 1 | 3m 00s | 5.08 | 12.42 |
+| 13.8 seconds | MAMMA | 3 | 11m 52s | 6.47 | 9.11 |
+
+For the three single-video models, times cover model-processing stages, excluding shared person
tracking, app contact correction and preview/export. GVHMR includes HTD, FootMR
and HandFlow. FlowHMR includes camera estimation and the original SAM path;
-these timings predate Fast SAM. VRAM is peak PyTorch **allocated** memory across
-workers, not total GPU usage or reserved memory. These are individual test runs,
+these timings predate Fast SAM. MAMMA used three synchronized videos resized
+within 1920×1080, two people, SAM 2.1 and VGGT, with 413 frames at 30 fps
+(13.77 seconds). Its 712.08-second total includes preparation, correction and
+preview; memory peaks cover the four inference stages. See the
+[MAMMA stage breakdown](MAMMA.md#recorded-processing-time-and-memory).
+
+VRAM is peak PyTorch **allocated** memory across workers, not total GPU usage
+or reserved memory. RAM for the single-video models is peak private memory;
+MAMMA RAM is peak worker working set. Neither is total system RAM usage.
+These are individual test runs,
not minimum hardware requirements or predictions for every video. Resolution,
camera motion, settings and available memory also affect results; a longer
video does not always use more VRAM or take proportionally longer.
@@ -358,8 +387,8 @@ installation folder, beside the new **RGBMoCap.cmd**:
Old installation/models/ → New installation/models/
```
-For example, copy `D:\RGBMoCap-Old\models` into `E:\RGBMoCap` so the result is
-`E:\RGBMoCap\models`, not `E:\RGBMoCap\models\models`. Keep all subfolders,
+The destination must be `<new installation>/models/`, not
+`<new installation>/models/models/`. Keep all subfolders,
configuration files, `.receipt.json` files and license files together. Copy
first and keep the old files until the new installation works.
@@ -385,6 +414,7 @@ selected result is missing, reconstruct it; the app reports it as unavailable.
| **ExMR → Camera** | Static Camera for a camera that stays still without zooming; Moving Camera / SimpleVO when it moves. |
| **ExMR → Smooth Motion** | Reduce small changes between frames. Off keeps the unsmoothed result. |
| **FlowHMR → Fast SAM** | Speed up body/hand image processing with the same model files. Small numerical differences can affect motion and automatic contacts. |
+| **FlowHMR → Fast SAM Acceleration** | Two independent, default-on switches: **4-Frame Batching** and **GPU Hand Crops**. Use them only with Fast SAM. Tooltips explain measured speed, VRAM and output differences; see the [FlowHMR guide](models/FLOWHMR.md#controls). Low Memory reduces the batch to one frame. Applies on Reconstruct 3D. |
| **FlowHMR → Camera / Sampling** | Start with Moving / Unknown - Auto for moving or uncertain cameras. Static Camera skips camera estimation for locked footage. Explicit frame intervals control camera analysis only; denser sampling uses more memory. |
| **GVHMR → HTD Refine** | Improve body-motion consistency over time. Runs before FootMR when both are enabled. |
| **GVHMR → FootMR** | Refine ankle angles from foot observations. Separate from foot contact locking. |
@@ -394,7 +424,7 @@ selected result is missing, reconstruct it; the app reports it as unavailable.
| **MAMMA → Import Camera Data...** | Import calibration with camera names matching video filenames without extensions, original pixel intrinsics and metric translations. See the exact [camera format](MAMMA.md#manual-cameras). |
| **MAMMA → People** | Default 0 automatically detects people during reconstruction; set 1–8 if someone is missed or background people are included. Count each person once across all cameras. Find person is hidden. |
| **MAMMA → Reference Height (m)** | Numeric approximate standing height, default 1.70 m. Sets VGGT scene scale, not every actor's height; unused with metric manual calibration. |
-| **Resource Mode** | For supported single-video stages, Automatic balances throughput and memory; Low Memory uses smaller image batches. MAMMA keeps its pinned processing settings and shared memory protections. |
+| **Resource Mode** | Automatic uses the fast path when GPU memory is sufficient and selects supported Low Memory paths when needed. Low Memory uses CPU loading/offloading and existing bounded image processing; it can be slower and use more RAM. The selection and reason appear in Console and the CMD window. |
| **Prepare Preview** | Rebuild mesh/skeleton previews from existing motion without running the AI model again. Useful for older projects. |
| **Cancel Job** | Stop queued processing; completed results are kept. |
@@ -412,10 +442,28 @@ Processing is allowed to start without a predicted RAM/VRAM minimum. While it
runs, the app monitors actual available RAM and Windows allocation headroom.
If either becomes low, it stops the processing job and shows the available memory
in the error message. The app also reports actual CPU/GPU allocation failures.
-Completed stages are retained for retry. Low Memory can reduce supported batch
-sizes, but cannot guarantee that every model or video fits. A sudden large
+Completed stages are retained for retry. ExMR Low Memory prepares Sapiens' existing
+FP16 layers on CPU and loads body/hand weights on CPU before GPU transfer; its
+body/hand feature batches remain 8. FlowHMR Low Memory offloads SAM and VGGT
+transformer blocks. MAMMA Low Memory offloads VGGT camera blocks; its masks,
+landmarks and fitting retain their existing bounded settings. GVHMR and add-ons
+retain their adaptive image batches and full-context attention handling.
+Automatic chooses these paths per operation from the current GPU budget and
+can retry a supported operation once after CUDA OOM. It does not change the
+saved Automatic selection, precision, video resolution, frame count or fitting
+iterations. CPU offloading needs RAM: actual RAM shortage can still stop the job.
+No mode guarantees that every model or video fits. A sudden large
allocation can still fail before the next monitor check.
+Low Memory primarily reduces **VRAM**, not system RAM. In earlier short paired
+checks, ExMR fell **5.68 → 3.87 GiB** allocated VRAM while RAM working set changed
+**11.88 → 11.94 GiB**; FlowHMR fell **6.10 → 2.77 GiB** while RAM rose
+**8.42 → 8.75 GiB**. GVHMR's short test had no meaningful whole-job saving.
+MAMMA's paired full-pipeline saving was not recorded; only the shared VGGT
+component has a controlled offload comparison. See [conditions, times and component measurements](PERFORMANCE.md).
+These are observations, not minimum requirements. The newest CPU prefetch is
+disabled in Low Memory; FlowHMR SAM also uses one-frame batches in that mode.
+
GPU allocator budgets use ComfyUI's external-use margin: 600 MiB on Windows,
or 700 MiB on GPUs larger than 15 GiB, subtracted from currently free VRAM.
All four model paths use this rule; FlowHMR/ExMR no longer subtract fixed
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index e29c498..11b7f42 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -127,7 +127,7 @@ interactive playback, standalone MMD playback or testing on other GPUs.
The old FlowHMR/ExMR fixed 3/2 GiB deductions and extra 95/90% caps are removed.
ComfyUI's separate 0.8 GiB inference planning allowance is not another allocator
deduction: weights, activations and temporary buffers share the allowed budget.
- This does not implement ComfyUI's offloading or guarantee free memory against
+ This margin alone does not implement offloading or guarantee free memory against
other applications or non-PyTorch allocations.
- Boundary checks covered simulated 4/8/12/15/16/24/32 GiB capacities, the exact
15 GiB transition, exhausted free memory and all four allocator call sites.
@@ -397,3 +397,228 @@ Four-second CMD playback samples across the four models measured 29.74–29.82 f
with frame-interval p95 34.71–35.04 ms and maxima 35.86–36.73 ms. Video/3D and
mesh/video frame differences were zero. GVHMR finished one queued frame just
after Stop; a separate settled two-second pause recorded zero skin dispatches.
+
+### Automatic / Low Memory routing (2026-10-30)
+
+Fresh independent runs on the tested Windows/RTX 5090 PC covered both modes:
+ExMR and FlowHMR each processed 60 frames through correction and export; GVHMR
+also ran HTD, FootMR and HandFlow. MAMMA processed two synchronized views,
+two people and 30 frames through fresh masks, landmarks, VGGT, fitting and
+correction. Existing separate pinned runtimes were reused, not reinstalled.
+FlowHMR's Original SAM (Fast SAM off) also completed both modes on an independent
+eight-frame feature-extraction fixture.
+
+Automatic selected fast paths with spare GPU memory. Allocator-budget tests
+selected Low Memory and completed ExMR preprocessing at 3.9 GiB, body/hand
+features at 4.5 GiB, FlowHMR camera at 3.5 GiB, and SAM features/motion at 3 GiB.
+A real fast-loading CUDA OOM was released and retried once successfully in
+Low Memory. ExMR features at 4.1 GiB still failed safely with memory advice;
+the batch remained 8. These are caps on a 5090, not validation of real 3–4 GiB
+GPUs. Models and full-sequence context can still exceed available memory.
+
+Automatic versus Low Memory body-joint differences in the three single-video
+samples were at most 0.84 mm before correction and 0.53 mm after correction;
+separate inference runs are not bit-identical. MAMMA camera matrices and both
+actors' sampled exported joints/rotations were identical in this comparison.
+Ten corrected-source FBX files imported in Blender 4.5 with 52 Hips-root bones,
+bone-only animation and sampled positions within 0.2 mm of committed frames.
+Seven policy/retry/hook-lifecycle checks and actual Console/CMD mirroring passed;
+the saved Automatic selection was retained. A short hook test does not prove
+long-run leak freedom. Playback/rendering code was unchanged in this revision.
+
+ExMR Sapiens peak PyTorch allocation decreased from 5.68 to 3.10 GiB; combined
+body/hand feature-stage peak decreased from 5.15 to 3.87 GiB. These exclude
+driver/display allocations. Low Memory can increase elapsed time and host RAM;
+single-pass cold-start timings are not speed benchmarks. Precision, frame count,
+resolution, temporal context and fitting iterations were retained. RAM/Windows
+allocation-headroom monitoring remains a stop condition. Test scripts, weights,
+logs, motion and temporary fixtures remain outside the publishable checkout.
+
+### FlowHMR Fast SAM acceleration controls (2026-10-30)
+
+The app now saves two independent, default-on switches for bounded four-frame
+batching and GPU hand crops. Four combinations completed a real 60-frame input
+with 30 valid pelvis anchors each. Against both switches off, final joint-position
+differences were 0.21 mm at the 95th percentile / 1.52 mm maximum for batching,
+and 1.23 mm / 2.45 mm with both switches on. These measure output disagreement,
+not ground-truth accuracy. The separate earlier short-clip speed tests remain
+the basis of the tooltip estimates; this integration check is not a new paired
+speed benchmark.
+
+Peak PyTorch allocation was 3.44 GiB without batching and 3.84 GiB with batching.
+A seven-frame Low Memory run used one-frame batches with GPU crops and peaked
+at 1.92 GiB. Original SAM completed three frames with acceleration flags ignored.
+One-, two- and three-frame partial batches completed with finite outputs. CUDA
+calls are not claimed bit-identical. Precision, crop resolution and the 20-step
+FlowHMR generator were retained. No new packages or runtime installation were
+needed; no forced physical OOM test was performed in this integration check.
+
+Qt checks covered defaults, all four saved option combinations, busy-state
+disablement, Fast SAM off, and all four model pages at short/tall window heights.
+The settings use consistent top-down spacing and scroll when needed; hidden
+model pages no longer reserve the tallest page's height. Test files and logs
+remain outside the app checkout.
+
+
+## Sequential multi-person model reuse (2026-10-30)
+
+The app now groups ExMR, FlowHMR and GVHMR actor/take jobs by supported stage.
+One model serves actors sequentially, with explicit actor paths and separate
+receipts. GVHMR runs its observation and core phases in one worker, closing each
+model scope before the next phase. Optional HTD, FootMR and HandFlow keep their
+existing separate workers. Single-actor jobs keep their previous queue.
+
+App-path measurements on the documented Windows RTX 5090 PC used two tracked
+people with 60 and 45 frames at 30 fps and static cameras. Timings include feature
+and core worker startup, excluding discovery, camera estimation, correction,
+export and optional add-ons. These are one-trial observations, not universal
+speedups; import and filesystem warm-up vary.
+
+| Model | Separate actor workers | Stage reuse | Peak PyTorch allocated VRAM, before → after |
+| --- | ---: | ---: | ---: |
+| FlowHMR | 108.69 s | 65.34 s | 3.84 → 3.84 GiB |
+| ExMR | 161.08 s | 106.51 s | 5.68 → 5.68 GiB |
+| GVHMR | 56.02 s | 22.97 s | 2.82 → 2.82 GiB |
+
+All six fixed-input actor/model comparisons were tensor-exact. With fresh image
+preprocessing, maximum joint differences against the preceding experiment were
+0.344 mm for FlowHMR, 0.242 mm for ExMR and zero for GVHMR; upstream preprocessing
+roundoff is not a claim of improved or degraded accuracy.
+
+Sixteen unit checks covered model lifetime, replacement, error cleanup, allocator
+budgeting, OOM retry, queue ordering, bounded requests and path/runtime validation.
+Real workers checked cache hits without model construction, two-frame Low Memory
+feature extraction for FlowHMR/ExMR, Original SAM, corrupt ExMR hand-feature
+recovery, and correction/derived export for all three models. The app writer also
+saved three binary FBX files; Blender reimport was not repeated for this change.
+A controlled real CUDA allocator OOM in a separate 1%-capped test process recovered
+once in Low Memory and ended with zero allocated tensor bytes. This is not a
+full-model OOM stress test on another GPU.
+
+Actual GUI QProcess runs checked repeated cached queues and cancellation during
+actor B, followed by reuse of completed actor A and reconstruction of B. A 20 ms
+GUI timer had a recorded worst delay of 45 ms during that cancellation/retry test;
+this measures offscreen event-loop responsiveness, not viewport FPS. Repeat checks
+were short and do not establish universal leak freedom. GVHMR retained a stable
+32 MiB PyTorch allocation between phases and its worker then exited. No new
+runtime packages or changes to the pinned runtime registry were needed. Private
+fixtures, model links and test scripts remain outside the application checkout.
+
+## Pipeline and CPU preparation follow-up (2026-10-30)
+
+A separate Windows RTX 5090 experiment retained the pinned runtimes, native
+precision, batch sizes, resolution and temporal context. Two trials reversed
+execution order; stages released their model before the next stage loaded.
+AI worker times include startup and saved results but exclude discovery,
+camera estimation, correction and export.
+
+| Model / people | Separate phase workers, two trials | Connected phases, two trials | Peak allocated VRAM |
+| --- | ---: | ---: | ---: |
+| FlowHMR / 1 | 58.65, 53.33 s | 41.12, 44.18 s | 3.84 GiB in both |
+| ExMR / 1 | 84.83, 82.88 s | 46.32, 46.99 s | 5.68 GiB in both |
+| ExMR / 2 | 94.90, 90.76 s | 52.78, 53.81 s | 5.68 GiB in both |
+
+Inputs were 60 frames for one actor and 60+45 frames for two actors, at 30 fps
+and 720x1280. FlowHMR's two-person connected-phase benefit was smaller than
+trial variability, so its existing multi-person phase grouping was retained.
+Short-clip startup gains do not predict the same percentage on long footage.
+
+Warm per-stage tests used those clips plus a separate 120-frame 1080x1920 clip,
+each processed twice: 450 frames per variant. CPU preparation ahead by at most
+two batches reduced total measured Sapiens time from 11.53 to 8.63 s, ExMR body
+features from 18.57 to 13.75 s, and hand features from 7.50 to 5.63 s. Flow Fast
+SAM changed from 42.96 to 40.79 s. Peak CUDA allocation was unchanged and sampled
+RAM growth was small. ExMR final body-readout omission alone took 16.63 s; with
+preparation overlap it took 13.15 s. The analogous hand-readout omission had no
+clear benefit and was not adopted. These stage gains cannot be added together
+to claim a whole-job speedup.
+
+Sapiens and hand features were tensor-exact; ExMR body features differed by up
+to 4.8e-6, versus 3.9e-6 on baseline repeats. Optimized final motion differed by
+at most 0.83 mm / 0.306 degrees for FlowHMR and 0.88 mm / 0.068 degrees for ExMR.
+Baseline repeats also differed, by up to 0.77 mm / 0.217 degrees and 0.69 mm /
+0.047 degrees respectively. This is an output-preservation check without ground
+truth, not a claim of improved or degraded tracking accuracy. Fixed feature
+inputs produced tensor-exact motion when phases were connected.
+
+Automatic CPU preparation is limited to one producer and two prepared batches,
+with an additional 256 MiB prepared-storage estimate. It is disabled in Low
+Memory or with insufficient CPU/RAM headroom. Existing OOM recovery and actual
+system-memory monitoring remain active. No new runtime packages were added.
+
+The integrated app code passed 25 focused policy/lifetime checks and five
+tensor-exact grouped-versus-independent motion comparisons on fixed features.
+Real one-/two-person worker runs verified model release and cached reruns without
+loading a model. Offscreen GUI QProcess checks covered automatic single-person
+phase joining, cancellation in the second actor's body extraction and retry
+using completed preprocessing. A 20 ms GUI timer had a maximum observed delay
+of 44.92 ms during that cancellation/retry run; this is not a viewport FPS test.
+Eight-frame real clips checked Low Memory for FlowHMR/ExMR and FlowHMR Original
+SAM. A damaged private ExMR hand-feature cache recovered without recomputing
+valid body features. Correction and binary FBX saving were checked for both
+models; Blender reimport was not repeated for this optimization.
+
+## Contact correction v9: coherent root and swing transitions (2026-10-30)
+
+Cached-source regression covered ten sequences / 10,121 actor frames: two
+MAMMA actors, ExMR slow motion and stairs, FlowHMR long motion and backflip,
+GVHMR dance, and pushups from all three single-video models. No AI inference
+was rerun. Contact timings and stance ankle targets were retained. This is a
+correction comparison without motion-capture ground truth.
+
+The planner now joins swing targets to the final root-shifted free trajectory,
+fades its extra target adjustment at the free boundary, and evaluates a smooth
+floor-clearance constraint inside the root search. Native anatomical IK still
+publishes leg rotations once. Existing 1,024-frame cores, four-second halos,
+2 cm planning budgets, 60-evaluation cap, source ankle frames and hand solver
+remain. Jacobian column scaling improves numerical conditioning. An exhausted
+planning window is reported explicitly; it is not a convergence claim.
+
+For the first MAMMA actor, pooled knee short-period RMS fell from 0.935 to
+0.332 degrees (64.5%); the second fell from 0.390 to 0.329 degrees (15.6%).
+The identified free-leg join's added bend step fell from +14.22 to -0.41
+degrees. Short-period RMS subtracts a nine-frame degree-two Savitzky-Golay
+trace; it is a diagnostic, not ground-truth error. Source-relative knee
+second-difference RMS decreased on all ten sequences. Individual metrics do
+not all improve: backflip total short-period RMS increased by about 2%, and
+the stairs' worst added step increased by about 0.23 degrees. Residual source
+noise, incompatible/unreachable pins and rapid intended movement remain.
+
+MAMMA full-contact skinned sole height error stayed within 1.36 mm; across the
+other tested foot contacts it stayed within 1.14 mm. Stance ankle positions
+changed by less than 0.001 mm, fixed lengths and source ankle orientation were
+retained, and torso world rotations were preserved. Hand timings and arm-only
+behavior were checked; existing unreachable-palm residuals remain explicitly
+reported. The backflip retained 103 contact-free flight poses exactly. Manual
+intervals, disabled feet, empty timings, one-frame bypass and native window
+sizes 64 versus 1,024 were checked. Two-, three- and seven-frame contact clips
+remained finite. An intentionally exhausted planning cap produced its warning.
+
+CPU correction-only measurements, excluding body sampling, hands, inference,
+rendering and export: the MAMMA pair changed from 1.42 to 1.07 s (sum of three-run
+medians); the long FlowHMR case increased from 1.34 to 1.53 s. Other long cases
+were faster in these runs. Sampled process peak working set stayed below
+300 MiB for these numeric-input tests; this is not whole-app RAM usage. No GPU
+allocation or additional dependency is introduced by this change.
+
+A separate copied MAMMA project completed the installed correction, preview
+and binary FBX workers. Ordinary Blender 4.5 import checked all 422 frames,
+52 bones, rest transforms, terminal tips and sampled half frames: maximum
+joint error 0.0044 mm and fractional rotation error 0.0028 degrees against the
+committed export. This was not a new playback-cadence or clean-install test.
+User projects were not recalculated or replaced; Apply Correction is required
+to obtain the new result. Private fixtures and media are outside the checkout.
+
+## Final pre-publication review (2026-10-30)
+
+Rechecked the 25 queue/prefetch/model-lifetime tests, four-model settings layouts,
+Fast SAM option persistence and a real GUI connected-worker cache rerun. Current
+correction code also passed the short-clip, contact/flight and installed-versus-
+isolated checks above. Two-actor application-worker smoke tests completed for
+FlowHMR, ExMR and GVHMR using private projects; these included fresh ExMR/GVHMR
+processing and a FlowHMR cache hit. GVHMR retained 32 MiB of cuBLAS workspace
+after releasing its model: a separate diagnostic cleared that library workspace
+and measured zero remaining allocation. This is not a model leak or a guarantee
+of zero CUDA context memory. No new runtime packages or clean-PC tests were added.
+Source syntax, manifest hashes, local documentation links and publishable file
+composition were checked; private tests, assets and logs remain outside the repo.
diff --git a/docs/models/EXMR.md b/docs/models/EXMR.md
index 8db7faf..ec89d25 100644
--- a/docs/models/EXMR.md
+++ b/docs/models/EXMR.md
@@ -34,7 +34,7 @@ standard body. See [model download and reuse](../USER_GUIDE.md#prepare-models).
| --- | --- | --- |
| **Camera** | Static Camera | Use for a camera that stays still without zooming. Choose Moving Camera / SimpleVO when it moves. ExMR does not use FlowHMR's VGGT camera stage. |
| **Smooth Motion** | On | Reduce small frame-to-frame changes; off preserves the unsmoothed result. |
-| **Resource Mode** | Automatic | Adapt supported work batches to available memory. Low Memory is a separate option. |
+| **Resource Mode** | Automatic | Use fast loading when GPU memory is sufficient; otherwise use CPU-first body/hand loading and prepare Sapiens' existing FP16 layers before GPU transfer. Low Memory forces these paths. Body/hand batches remain 8. CPU loading can be slower and use more RAM. |
Camera and smoothing changes take effect on **Reconstruct 3D**, not on
**Apply Correction**. Existing projects retain saved settings.
@@ -57,6 +57,31 @@ another's. **Save Project As** copies saved work to the selected location.
## Limitations and resources
+Reconstruction reuses one model at a time across selected people and connects
+its processing phases in one worker. With enough CPU/RAM headroom, Automatic
+prepares up to two image batches ahead; Low Memory disables this overlap.
+The body feature extractor omits unused final pose readouts while retaining
+intermediate feedback. Precision, image resolution and motion context are unchanged.
+
+### Measured effects
+
+Measurements below used an RTX 5090 32 GB, Ryzen 9 9950X and 96 GB RAM on
+Windows. They use different baselines and must not be added together:
+
+| Comparison | Measured change |
+| --- | --- |
+| Automatic → Low Memory, 60 frames including correction/preview preparation | Allocated VRAM **5.68 → 3.87 GiB** (32% less); RAM working set **11.88 → 11.94 GiB**; **89.01 → 94.78 s**. This mode check predates the latest acceleration. |
+| Connected phases, one person / 60 frames | Worker time **83.86 → 46.66 s** (44% less); peak allocated VRAM **5.68 GiB** in both. Includes worker startup/saving, not discovery, correction or export. |
+| Connected phases, two people / 60+45 frames | **92.83 → 53.29 s** (43% less); peak allocated VRAM unchanged at **5.68 GiB**. |
+| CPU preparation overlap, warm feature stages | About **25% less time** for Sapiens and hand features; **29% less** for body features with unused final readouts omitted. Measured VRAM was unchanged; RAM was similar, with small increases in some stages. |
+
+CPU-first loading can increase RAM substantially: the isolated hand-model test
+rose from **1.54 to 5.79 GiB** working set. It is not a host-memory-saving feature.
+Fixed-feature motion comparisons were exact; fresh optimized preprocessing
+produced maximum joint differences of **0.88 mm**, with baseline repeats also
+differing by up to 0.69 mm. These are output differences, not ground-truth accuracy.
+See [full conditions, loading trade-offs and measurements](../PERFORMANCE.md).
+
Occlusion, motion blur, poor visibility and identity changes can produce wrong
poses or fingers. Automatic contact detection can also miss intentional support;
edit its timings rather than expecting correction to recover missing evidence.
diff --git a/docs/models/FLOWHMR.md b/docs/models/FLOWHMR.md
index cecbef8..6c95114 100644
--- a/docs/models/FLOWHMR.md
+++ b/docs/models/FLOWHMR.md
@@ -30,14 +30,25 @@ See [model preparation](../USER_GUIDE.md#prepare-models).
| Control | Default for new work | Meaning |
| --- | --- | --- |
| **Fast SAM** | On | Speed up feature extraction using the same supported weights. Small numerical differences can affect motion or automatic contact timings. |
+| **Fast SAM Acceleration > 4-Frame Batching** | On | Process up to four frames together. Short tests measured about 2–2.4× faster SAM features, with about 0.4 GiB more allocated VRAM (0.7 GiB more reserved). Small numerical differences are possible. Low Memory uses one frame per batch. |
+| **Fast SAM Acceleration > GPU Hand Crops** | On | Prepare hand crops on the GPU. Tests on top of 4-frame batching measured about 8–11% less feature time, with unchanged allocated VRAM at that batch size. Image interpolation differs from CPU crops, so the resulting motion can differ slightly. |
| **Camera / Sampling** | Moving / Unknown - Auto | Automatically choose camera-estimation sampling when the camera moves or its behavior is uncertain. |
| **Camera / Sampling > Static Camera** | Optional | Skip camera estimation for a fixed camera without zooming. This path does not require the VGGT weight. |
| **Camera / Sampling > Every ... Frames** | Optional | Analyze the camera every 1, 2, 5, 10 or 30 frames. Denser camera sampling uses more memory. It does not reduce motion frame count. |
-| **Resource Mode** | Automatic | Adapt supported image batches to current memory; Low Memory is separately selectable. |
+| **Resource Mode** | Automatic | Use the fast GPU path when memory is sufficient; otherwise offload SAM/VGGT transformer blocks to CPU. Low Memory forces offloading. This can be slower and use more RAM; precision and motion frame count stay unchanged. |
These options apply on **Reconstruct 3D**. Fast SAM is an extraction option,
not MAMMA's SAM 2.1 mask stage or the standalone SAM 3.1 experiments.
+The two acceleration switches work independently and are saved with the project.
+They are used only while **Fast SAM** is on. They do not lower model precision,
+reduce image resolution or skip motion frames. In the short validation clips,
+GPU crops changed final joint positions by about 1 mm at the 95th percentile,
+with differences up to 5 mm; this measures disagreement with CPU crops, not
+accuracy against ground truth. Speed figures describe feature extraction after
+warm-up, not the whole reconstruction, and vary with the PC and video. CUDA
+memory pressure can retry with Low Memory and a smaller batch.
+
## Capture and export
1. Select FlowHMR and **File > Open Video**, then trim the **Video** track.
@@ -57,6 +68,31 @@ results separate.
## Limitations and resources
+Single-person reconstruction connects feature extraction and motion generation
+in one worker, releasing the feature model before loading the motion model.
+Multiple people retain stage-scoped model reuse. Automatic may prepare up to
+two CPU image batches ahead when memory is available; Low Memory disables this
+overlap. This does not change the Fast SAM switches, resolution or precision.
+
+### Measured effects
+
+Measured on Windows with RTX 5090 32 GB, Ryzen 9 9950X and 96 GB RAM.
+The rows use different stages/baselines; do not combine their speedups.
+
+| Comparison | Measured change |
+| --- | --- |
+| Automatic → Low Memory, 60 frames including cameras/correction/preview preparation | Allocated VRAM **6.10 → 2.77 GiB** (55% less); RAM working set **8.42 → 8.75 GiB**; **95.24 → 96.15 s**. This mode check predates the latest acceleration. |
+| 4-frame batching, warm SAM features | About **2.0–2.4× faster**; allocated VRAM **3.44 → 3.84 GiB**, reserved VRAM **3.74 → 4.45 GiB**; RAM about **6.47 GiB** in both. |
+| GPU hand crops on top of 4-frame batching | Two clips: **6.10 → 5.44 s** and **10.87 → 9.81 s**, about 10% less feature time; a repeated alternating test found 8%. Allocated VRAM remained **3.84 GiB**. |
+| Connected phases, one person / 60 frames | **55.99 → 42.65 s** (24% less); allocated VRAM **3.84 GiB** in both. Includes worker startup/saving, not discovery, cameras, correction or export. |
+| Bounded CPU prefetch, warm SAM features / 450 frames | **42.96 → 40.79 s** (5% less); VRAM unchanged at **3.84 GiB**; RAM **2.45 → 2.49 GiB**. Disabled in Low Memory. |
+
+Offloading can noticeably slow individual stages despite similar whole-job
+times in a single short mode check. The shared VGGT component's warm inference
+took about **3.3× as long** with offloading while its peak VRAM fell by 52%.
+For model reuse across people, exact test scopes and separate output-difference
+checks, see [resource modes and measured optimizations](../PERFORMANCE.md).
+
Camera estimation, occlusion and image features can introduce pose, trajectory
or finger errors. A fixed-camera option cannot compensate for a camera that
actually moves. Contact correction reduces supported-foot/palm sliding but does
diff --git a/docs/models/GVHMR.md b/docs/models/GVHMR.md
index 4eebab0..7fec0f5 100644
--- a/docs/models/GVHMR.md
+++ b/docs/models/GVHMR.md
@@ -67,7 +67,29 @@ HandFlow can still make finger mistakes, and neither add-on fixes a wrong person
or an unobserved pose. Correction retains original motion for comparison.
RAM/Windows allocation-headroom monitoring, adaptive supported GPU work and
-allocation-error reporting stay active. Long-sequence context can still fail
+allocation-error reporting stay active. Automatic keeps the fast path when GPU
+memory is sufficient and selects existing Low Memory image processing when
+needed. Full temporal context is preserved; dense attention remains enabled
+when it fits. Resource decisions and memory advice appear in Console and CMD.
+
+### Measured effects
+
+On Windows with RTX 5090 32 GB, Ryzen 9 9950X and 96 GB RAM:
+
+- A short 60-frame mode check with HTD, FootMR and HandFlow showed **no meaningful
+ whole-job VRAM saving**: Automatic **4.204 GiB**, Low Memory **4.203 GiB**.
+ RAM working set was **6.87 → 6.85 GiB**. Times were **127.53 → 113.28 s**, but
+ single-pass startup/cache variation does not establish that Low Memory is faster.
+- A separate two-person, 60+45-frame test of feature/core processing **without
+ add-ons** reduced **56.02 → 22.97 s** (59% less time) through model reuse.
+ Allocated VRAM stayed about **2.82 GiB**. This was one timing trial, excluding
+ discovery, camera estimation, correction and export.
+
+Low Memory does not force slower query splitting when dense attention already
+fits. Full-sequence motion context still consumes memory, so these short tests
+do not establish long-video capacity. See [shared measurements and limitations](../PERFORMANCE.md).
+
+Long-sequence context can still fail
to fit; no option guarantees a particular duration on every PC. Historical
[time/VRAM measurements](../USER_GUIDE.md#recorded-processing-time-and-vram)
include HTD, FootMR and HandFlow and are individual observations, not minimum
diff --git a/docs/models/README.md b/docs/models/README.md
index 6347851..b8ddb7d 100644
--- a/docs/models/README.md
+++ b/docs/models/README.md
@@ -46,11 +46,23 @@ all of its camera videos with **Save Project As**.
Use **Resource Mode > Automatic** initially. Actual RAM/Windows allocation
headroom monitoring, CUDA allocator budgets and allocation-error reporting remain
active. More frames, pixels, people or views can increase work; no setting
-guarantees that every clip fits. Low Memory adjusts supported single-video
-batches; it does not select a reduced-view or lower-quality MAMMA preset.
+guarantees that every clip fits. Automatic selects supported Low Memory paths
+when the GPU budget is low; a supported operation can recover once after CUDA
+OOM. Low Memory uses CPU loading/offloading and existing bounded image batches,
+which can be slower and need more RAM. It does not reduce model precision,
+motion frame count or MAMMA view count/iterations. Decisions appear in Console
+and the CMD window.
See [resources](../USER_GUIDE.md#model-and-processing-settings)
and [measured validation scope](../VALIDATION.md).
+Low Memory primarily saves **VRAM**, not system RAM. Short paired mode checks
+measured ExMR at **5.68 → 3.87 GiB** and FlowHMR at **6.10 → 2.77 GiB** allocated
+VRAM; GVHMR's short test had no meaningful whole-job reduction. MAMMA's paired
+whole-pipeline VRAM saving was not recorded; only its shared VGGT offload
+component has a controlled comparison. See [measured savings and speedups](../PERFORMANCE.md)
+for RAM, timing, test scope and numerical differences. These figures are not
+minimum requirements or predictions for every clip.
+
See the [user guide](../USER_GUIDE.md) for shared controls, contacts, retargeting,
FBX/VMD export, storage and cleanup. For agent-assisted setup and diagnostics,
use [the agent guide](../AGENT_GUIDE.md). Model code, weights and body data retain
diff --git a/mocap/batch_prefetch.py b/mocap/batch_prefetch.py
new file mode 100644
index 0000000..cde35e9
--- /dev/null
+++ b/mocap/batch_prefetch.py
@@ -0,0 +1,71 @@
+"""Bounded CPU preparation; inference stays on the consuming worker thread."""
+from collections import deque
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+
+MAX_PREPARED_BYTES = 256 * 1024**2
+
+
+def preparation_depth(batch_bytes=0):
+ import psutil
+ from .compute_policy import prefetch_plan
+ memory = psutil.virtual_memory()
+ depth = prefetch_plan(memory.available, memory.total)
+ if batch_bytes > 0:
+ depth = min(depth, MAX_PREPARED_BYTES // batch_bytes)
+ return max(0, min(2, depth))
+
+
+class _PreparedBatches:
+ def __init__(self, source, depth):
+ # DataLoader iterator creation can draw a seed. Keep it on the consumer
+ # before starting CPU work so model randomness retains its ordering.
+ self.source = iter(source)
+ self.pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix='cpu-prep')
+ self.pending = deque()
+ self.closed = False
+ try:
+ for _ in range(depth):
+ self.pending.append(self.pool.submit(next, self.source))
+ except BaseException:
+ self.close()
+ raise
+
+ def __iter__(self):
+ try:
+ while self.pending:
+ future = self.pending.popleft()
+ try:
+ value = future.result()
+ except StopIteration:
+ return
+ self.pending.append(self.pool.submit(next, self.source))
+ yield value
+ del value
+ finally:
+ self.close()
+
+ def close(self):
+ if self.closed:
+ return
+ self.closed = True
+ for future in self.pending:
+ future.cancel()
+ self.pool.shutdown(wait=True, cancel_futures=True)
+ self.pending.clear()
+ close = getattr(self.source, 'close', None)
+ if close is not None:
+ close()
+
+
+@contextmanager
+def batch_source(source, *, batch_bytes=0):
+ depth = preparation_depth(batch_bytes)
+ if not depth:
+ yield source
+ return
+ prepared = _PreparedBatches(source, depth)
+ try:
+ yield prepared
+ finally:
+ prepared.close()
diff --git a/mocap/batch_worker.py b/mocap/batch_worker.py
new file mode 100644
index 0000000..2aa3071
--- /dev/null
+++ b/mocap/batch_worker.py
@@ -0,0 +1,99 @@
+"""Sequential actor work within one stage-scoped resident model session."""
+from pathlib import Path
+import argparse
+import gc
+import json
+import os
+import sys
+import time
+import traceback
+
+
+def main(argv, emit):
+ parser = argparse.ArgumentParser()
+ parser.add_argument('stage')
+ parser.add_argument('--request',type=Path,required=True)
+ parser.add_argument('--project') # Explicit routing context, validated below.
+ parser.add_argument('--result')
+ args = parser.parse_args(argv)
+ from .queue_groups import validate,MAX_BYTES,PHASES
+ if args.request.stat().st_size>MAX_BYTES:raise ValueError('Batch request is too large')
+ phase,jobs = validate(json.loads(args.request.read_text(encoding='utf-8')),args.stage)
+ from .compute_policy import configure_worker_cpu
+ threads=configure_worker_cpu(PHASES[args.stage][phase])
+ from .model_session import ModelSession,set_memory_budget
+ from .storage import atomic_json
+ import torch
+ torch.set_num_threads(threads)
+ os.environ['RGB_MOCAP_STAGE']=PHASES[args.stage][phase]
+ started=time.monotonic();all_cached=True;active=None
+ try:
+ phases=({'gvhmr_batch':('pose','features','gvhmr'),
+ 'flow_batch':('flow_features','flowhmr'),
+ 'exmr_batch':('exmr_preprocess','body','hand','exmr')}[args.stage]
+ if phase=='all' else (phase,))
+ for phase in phases:
+ os.environ['RGB_MOCAP_STAGE']=PHASES[args.stage][phase]
+ with ModelSession().activate() as session:
+ for index,job in enumerate(jobs,1):
+ active=job['project'];stage=PHASES[args.stage][phase]
+ emit('batch_item_start',stage=stage,phase=phase,index=index,count=len(jobs),project=str(active))
+ cached=False
+ def observe(kind,**value):
+ nonlocal cached
+ if kind=='complete':
+ cached=bool(value.get('cached',False));value['batch_inner']=True
+ if kind=='progress':value['phase']=f'{phase}:{index}:'+str(value.get('phase',value.get('message','')))
+ emit(kind,**value)
+ options=dict(force=job['force'])
+ # Reset per-actor randomness, not the loaded model or its weights.
+ torch.manual_seed(0)
+ if args.stage=='exmr_batch':
+ from . import exmr_backend as backend
+ backend.run_stage(active,stage,job['result'],observe,
+ feature_phase=phase if phase in ('body','hand') else None,**options)
+ elif args.stage=='flow_batch':
+ from . import flow_backend as backend
+ backend.run_stage(active,stage,job['result'],observe,**options)
+ elif phase in ('pose','features'):
+ import psutil
+ from .memory_mode import select_stage
+ if not torch.cuda.is_available():raise RuntimeError('GVHMR requires a supported NVIDIA CUDA GPU')
+ free,total=torch.cuda.mem_get_info();set_memory_budget(free,total)
+ select_stage('features',free+session.resident_bytes,total,0,observe)
+ from . import engines
+ # Per-file receipts permit interrupted observation phases to resume.
+ output=engines.features(active,observe,phase=phase)
+ else:
+ from . import worker
+ saved_argv=sys.argv;saved_emit=worker.emit
+ sys.argv=['mocap.worker','gvhmr','--project',str(active),'--result',job['result']]+(['--force'] if job['force'] else [])
+ worker.emit=observe
+ try:
+ code=worker.main()
+ if code:return code
+ finally:sys.argv=saved_argv;worker.emit=saved_emit
+ all_cached &= cached
+ gc.collect()
+ if torch.cuda.is_initialized():torch.cuda.empty_cache()
+ import psutil
+ emit('batch_item_done',stage=stage,project=str(active),index=index,count=len(jobs),
+ resident_models=int(session.value is not None),resident_allocated_bytes=torch.cuda.memory_allocated() if torch.cuda.is_initialized() else 0,
+ peak_cuda_allocated_bytes=torch.cuda.max_memory_allocated() if torch.cuda.is_initialized() else 0,
+ rss_bytes=psutil.Process().memory_info().rss,handles=psutil.Process().num_handles())
+ emit('batch_phase_released',phase=phase,allocated_bytes=torch.cuda.memory_allocated() if torch.cuda.is_initialized() else 0)
+ emit('complete',stage=args.stage,output=str(jobs[-1]['project']),cached=all_cached,elapsed=time.monotonic()-started)
+ return 0
+ except Exception as error:
+ details=traceback.format_exc();print(details,file=sys.stderr,flush=True)
+ if active is not None:
+ state=json.loads((active/'project.json').read_text(encoding='utf-8'))
+ state.setdefault('stages',{})[PHASES[args.stage][phase]]=dict(status='failed',error=str(error))
+ atomic_json(active/'project.json',state)
+ (active/(args.stage+'_error.log')).write_text(details,encoding='utf-8')
+ message=str(error)
+ if isinstance(error,MemoryError) or 'out of memory' in message.lower():
+ from .memory_mode import GUIDANCE
+ message+=' '+GUIDANCE
+ emit('failed',message=message)
+ return 1
diff --git a/mocap/compute_policy.py b/mocap/compute_policy.py
index 7e9874d..1b46988 100644
--- a/mocap/compute_policy.py
+++ b/mocap/compute_policy.py
@@ -43,7 +43,8 @@ def configure_worker_cpu(stage):
def prefetch_plan(available_ram,total_ram,logical=None,mode=None):
"""Overlap CPU crops only when the desktop has spare CPU and RAM."""
logical=logical or os.cpu_count() or 1
- mode=mode or os.environ.get('RGB_MOCAP_COMPUTE_MODE','auto')
+ from .memory_mode import effective_mode
+ mode=mode or effective_mode()
return 2 if (mode!='low_memory' and logical>=8 and
available_ram-ram_reserve(total_ram)>=6*GIB) else 0
@@ -68,7 +69,8 @@ def gvhmr_plan(frames,free_vram,total_vram):
def image_plan(stage,free_vram,available_ram,mode=None):
- mode=mode or os.environ.get('RGB_MOCAP_COMPUTE_MODE','auto')
+ from .memory_mode import effective_mode
+ mode=mode or effective_mode()
if mode not in MODES:mode='auto'
import sys
torch=sys.modules.get('torch')
@@ -97,8 +99,9 @@ def memory_pressure_message(available,total,commit=None):
if available>=reserve and (commit is None or commit>=GIB):return None
detail=f'Available RAM {available/GIB:.2f} GiB (system reserve {reserve/GIB:.2f} GiB)'
if commit is not None:detail+=f'; Windows allocation headroom {commit/GIB:.2f} GiB'
+ from .memory_mode import GUIDANCE
return ('Processing stopped because available system memory is low. '+detail+
- '. Close other apps or use a shorter clip. Completed stages can be reused.')
+ '. '+GUIDANCE+' Completed stages can be reused.')
def retry_cuda(operation,batch,on_retry,oom_type=None,cleanup=None):
@@ -119,6 +122,10 @@ def retry_cuda(operation,batch,on_retry,oom_type=None,cleanup=None):
import gc,torch
gc.collect();torch.cuda.empty_cache()
else:cleanup()
+ from .memory_mode import effective_mode,announce
+ if effective_mode()!='low_memory':
+ os.environ['RGB_MOCAP_EFFECTIVE_MODE']='low_memory'
+ announce('GPU inference','low_memory','Automatic recovery: reducing the image batch after CUDA memory pressure.')
on_retry(batch)
diff --git a/mocap/contact_pose_plan.py b/mocap/contact_pose_plan.py
index b80d0cc..8db0252 100644
--- a/mocap/contact_pose_plan.py
+++ b/mocap/contact_pose_plan.py
@@ -2,7 +2,8 @@
The native solver remains the sole publisher of hip/knee/ankle rotations.
This module predicts its response while planning root Y and swing-target Y.
-Contact labels, full-contact targets, XZ targets and ankle frames are fixed.
+Contact labels, stance targets and ankle frames are fixed. Free trajectories
+follow the final planned root at their finite transition boundaries.
"""
import time
import numpy as np
@@ -12,7 +13,7 @@ from scipy.spatial.transform import Rotation
CONFIG = dict(root_free=True, hip_weight=0.5,
target_limit=.02, target_sigma=.02, root_sigma=.01,
- pose_sigma=.175, velocity_sigma=.025, acceleration_sigma=.004,
+ pose_sigma=.175, velocity_sigma=.025, acceleration_sigma=.002,
root_acceleration_sigma=.0004, iterations=60)
def _optimise_window(rest, root, quat, probes, shift, target_shift, offsets, active,
@@ -31,27 +32,31 @@ def _optimise_window(rest, root, quat, probes, shift, target_shift, offsets, act
if not active.any():
return warm, previous
j, g = fk(rest, root, quat)
+ from .contact_trajectory import free_follow_weights
+ follow = free_follow_weights(active, transition)
+ reference_shift = np.broadcast_to(target_shift[:, None], (n, 2, 3)).copy()
planned = (active | transition).copy()
targets = j[:, [7, 8]] + target_shift[:, None] + offsets
height = probes[..., 1].reshape(n, 2, 2).min(2)
expected = height + targets[..., 1] - j[:, [7, 8], 1]
targets[..., 1] += np.where(active,
np.minimum(np.maximum(floor - expected, 0), .12), 0) if mode=="flat" else 0
- # Match the native invocation's existing free-foot floor guard before
- # predicting the solve. This is clearance, never an added contact label.
- free_height = height + np.where(planned,
- targets[..., 1] - j[:, [7, 8], 1], warm[:, 1, None])
- guard = ~active & ~flight[:, None] & (free_height < floor - .01) & (mode=="flat")
- free = np.where(planned[..., None], targets,
- j[:, [7, 8]] + warm[:, None])
- free[..., 1] += np.where(guard,
- np.minimum(np.maximum(floor - free_height, 0), .12), 0)
- targets = np.where(guard[..., None], free, targets)
+ # Admit every free frame that could need clearance inside the bounded
+ # root search. The smooth unilateral constraint is evaluated at each
+ # trial root, rather than switching a 1 cm correction on after planning.
+ original_planned = planned.copy()
+ free_base = j[:, [7, 8]] + warm[:, None]
+ targets = np.where(planned[..., None], targets, free_base)
+ follow[~planned] = 1.
+ reference_shift[~planned] = np.broadcast_to(warm[:, None], (n, 2, 3))[~planned]
+ possible_height = height + np.minimum(targets[..., 1]-j[:, [7, 8], 1], base[:, 1, None]-.02)
+ guard = ~active & ~flight[:, None] & (possible_height < floor+.01) & (mode=="flat")
planned |= guard
- expected = height + targets[..., 1] - j[:, [7, 8], 1]
- movable = planned & ~active & ~flight[:, None]
+ movable = original_planned & ~active & ~flight[:, None]
ti, fi = np.nonzero(movable)
m = len(ti)
+ # A finite approach/release parameter must vanish at its free boundary.
+ target_gain = 1.-follow[ti, fi]
distance_xz = ((j[:, [1, 2]][..., [0, 2]] + base[:, None, [0, 2]] -
targets[..., [0, 2]]) ** 2).sum(2)
high_reach = reach_lengths(rest, g) * .9995
@@ -67,14 +72,10 @@ def _optimise_window(rest, root, quat, probes, shift, target_shift, offsets, act
fixed = warm[:, 1].astype('float64')
lo[freeze] = fixed[freeze] - 1e-10
hi[freeze] = fixed[freeze] + 1e-10
- # Do not lower a transition sole through the known floor. Lifted source
- # motion is retained by a small source-relative target budget.
- clearance = np.where(guard[ti,fi],floor,floor-.009)
- tlo = np.maximum(-cfg['target_limit'], clearance-expected[ti, fi]) if mode=="flat" else np.full(m,-cfg['target_limit'])
+ # Keep the existing 2 cm source-relative budget. Flat-floor clearance is
+ # applied continuously in predict(), after the bounded target adjustment.
+ tlo = np.full(m, -cfg['target_limit'])
thi = np.full(m, cfg['target_limit'])
- bad = tlo > thi-1e-8
- tlo[bad] = -1e-10
- thi[bad] = 1e-10
lower = np.r_[lo, tlo]
upper = np.r_[hi, thi]
x0 = np.r_[np.clip(warm[:, 1], lo+1e-11, hi-1e-11),
@@ -115,8 +116,16 @@ def _optimise_window(rest, root, quat, probes, shift, target_shift, offsets, act
channel = np.array([1., cfg['hip_weight'],cfg['hip_weight'],cfg['hip_weight']])
def predict(x, return_geometry=False):
- goal = targets.copy()
- goal[ti,fi,1] += x[n:]
+ # Keep finite-difference trial values in float64; storing them in the
+ # float32 input shift would quantize away root derivatives.
+ dynamic_shift = base.astype(np.float64, copy=True)
+ dynamic_shift[:, 1] = x[:n]
+ goal = targets + follow[..., None]*(dynamic_shift[:, None]-reference_shift)
+ goal[ti,fi,1] += x[n:]*target_gain
+ if mode == 'flat':
+ gap = floor-(height+goal[..., 1]-j[:, [7, 8], 1])
+ lift = np.where(gap>=.01, gap, np.where(gap<=-.01, 0., (gap+.01)**2/.04))
+ goal[..., 1] += np.where(planned & ~active & ~flight[:, None], np.minimum(lift,.12), 0.)
origin = hips.copy()
origin[...,1] += x[:n,None]
delta = goal-origin
@@ -178,8 +187,10 @@ def _optimise_window(rest, root, quat, probes, shift, target_shift, offsets, act
block(np.arange(n),2)
sparsity=coo_matrix((np.ones(sum(map(len,rows))), (np.concatenate(rows),np.concatenate(cols))),shape=(cursor,n+m)).tocsr()
before=residual(x0)
+ # Column scaling improves conditioning without increasing the iteration
+ # cap, changing the objective or introducing dense recording-sized work.
result=least_squares(residual,x0,jac_sparsity=sparsity,bounds=(lower,upper),
- max_nfev=cfg['iterations'],ftol=2e-5,xtol=2e-6,gtol=1e-5,tr_solver='lsmr',
+ x_scale='jac',max_nfev=cfg['iterations'],ftol=2e-5,xtol=2e-6,gtol=1e-5,tr_solver='lsmr',
tr_options={'maxiter':100})
state,goal,_,_=predict(result.x,True)
out=warm.copy();out[:,1]=result.x[:n]
@@ -190,7 +201,9 @@ def _optimise_window(rest, root, quat, probes, shift, target_shift, offsets, act
cost_before=float(before@before/2),cost_after=float(result.cost),
root_freeze_frames=int(freeze.sum()),transition_variables=m,
planned_free_foot_clearance_frames=int(guard.sum()),
- target_y_extra_max_m=float(abs(result.x[n:]).max(initial=0)),
+ target_y_extra_max_m=float(abs(result.x[n:]*target_gain).max(initial=0)),
+ trial_scaling='sparse Jacobian column norms',
+ free_goal_basis='final planned root with finite C1 joins',
root_extra_from_app_max_m=float(abs(result.x[:n]-base[:,1]).max()),
source_speed_method='relative SO(3)',physics_simulation=False)
return out,previous
diff --git a/mocap/contact_trajectory.py b/mocap/contact_trajectory.py
index f992d3a..db6d43b 100644
--- a/mocap/contact_trajectory.py
+++ b/mocap/contact_trajectory.py
@@ -230,3 +230,16 @@ def material_slip(before, after, active, weights, fps):
result['support_material_speed_'+label+'_max_mps'] = float(speed.max()) if len(speed) else None
result['support_material_speed_'+label+'_p95_mps'] = float(np.quantile(speed, .95)) if len(speed) else None
return result
+
+
+def free_follow_weights(active, transition):
+ """Finite C1 blend to the actual free trajectory outside contact."""
+ out = np.zeros(active.shape, dtype=np.float64)
+ for foot in (0, 1):
+ for a, b in runs(transition[:, foot] & ~active[:, foot]):
+ left = a > 0 and active[a-1, foot]
+ right = b < len(active) and active[b, foot]
+ t = np.arange(1, b-a+1, dtype=np.float64)/(b-a+1)
+ smooth = t*t*(3-2*t)
+ out[a:b, foot] = 0 if left and right else smooth if left else 1-smooth if right else 1
+ return out
diff --git a/mocap/correction.py b/mocap/correction.py
index f49dfec..59210f2 100644
--- a/mocap/correction.py
+++ b/mocap/correction.py
@@ -18,7 +18,7 @@ from scipy.linalg import solve_banded
from .correction_settings import PRESETS
PARENTS = [-1,0,0,0,1,2,3,4,5,6,7,8,9,9,9,12,13,14,16,17,18,19]
-VERSION = 8
+VERSION = 9
CORE = 1024
HALO_SECONDS = 4.0
@@ -487,6 +487,14 @@ def correct_arrays(rest, root, quat, probes, probabilities, fps=30., floor=None,
report['warning']=' '.join(filter(None,(report['warning'],
'Multi Level estimates contacts from motion. Terrain and object collisions are not solved.')))
report.update(temporal_report)
+ plans = ([temporal_report['contact_chain_plan']] if 'contact_chain_plan' in temporal_report else
+ [tile['report']['contact_chain_plan'] for tile in
+ temporal_report.get('bounded_contact_plan', {}).get('windows', [])
+ if 'contact_chain_plan' in tile['report']])
+ report['contact_plan_limit_windows'] = sum(not plan['success'] for plan in plans)
+ if report['contact_plan_limit_windows']:
+ report['warning'] = ' '.join(filter(None, (report['warning'],
+ 'Some contact-transition windows reached the planning limit; inspect motion and contact timing.')))
return out_root,out_quat,report
diff --git a/mocap/engines.py b/mocap/engines.py
index 07b6f51..4c0be15 100644
--- a/mocap/engines.py
+++ b/mocap/engines.py
@@ -22,7 +22,7 @@ def activate(name: str) -> Path:
# and timm version never leak into the GUI or another model.
root = UPSTREAM / name
for path in (root, COMPAT):
- sys.path.insert(0, str(path))
+ if str(path) not in sys.path:sys.path.insert(0, str(path))
os.chdir(root)
os.environ.setdefault("YOLO_CONFIG_DIR", str(MODELS / "yolo" / "settings"))
import torch
@@ -193,7 +193,11 @@ def pva(project: Path, emit) -> Path:
return target
-def features(project: Path, emit) -> Path:
+def features(project: Path, emit, phase=None) -> Path:
+ import time
+ started=time.monotonic()
+ if phase not in (None,'pose','features'):raise ValueError('Invalid GVHMR feature phase')
+ from .model_session import acquire,model_key,reusable_bytes
root = activate("GVHMR")
link_models(root)
import numpy as np
@@ -206,9 +210,9 @@ def features(project: Path, emit) -> Path:
from .inference_data import streamed_features
from .compute_policy import image_plan,prefetch_plan
import psutil
- tracking = np.load(project / "tracking.npz")
- bbx = get_bbx_xys_from_xyxy(torch.from_numpy(tracking["boxes"]), base_enlarge=1.2)
- plan=image_plan('gvhmr',torch.cuda.mem_get_info()[0],psutil.virtual_memory().available)
+ with np.load(project / "tracking.npz") as tracking:boxes=tracking["boxes"].copy()
+ bbx = get_bbx_xys_from_xyxy(torch.from_numpy(boxes), base_enlarge=1.2)
+ plan=image_plan('gvhmr',torch.cuda.mem_get_info()[0]+reusable_bytes(),psutil.virtual_memory().available)
memory=psutil.virtual_memory()
plan['prefetch_batches']=prefetch_plan(memory.available,memory.total)
plan.update(deterministic_conv=True,tf32=False)
@@ -220,10 +224,11 @@ def features(project: Path, emit) -> Path:
return lambda current,total:emit('progress',stage='features',message=message,current=current,total=total)
emit("progress", stage="gvhmr", message="Computing GVHMR joint observations", current=0, total=3)
keypoint_path = project / "gvhmr_keypoints.pt"
- if cached(project,state,keypoint_path.name):
+ pose_cached=cached(project,state,keypoint_path.name)
+ if pose_cached:
kp = torch.load(keypoint_path, map_location="cpu", weights_only=False)
else:
- pose = VitPoseExtractor()
+ pose = acquire(model_key("gv_pose",BY_KEY["vitpose"].path),VitPoseExtractor)
kp = streamed_features(project,bbx,pose.extract,plan['image_batch'],plan['prefetch_batches'],
progress('Computing GVHMR joint observations'))
save_tensor(kp, keypoint_path)
@@ -231,12 +236,16 @@ def features(project: Path, emit) -> Path:
del pose
gc.collect()
torch.cuda.empty_cache()
+ if phase=='pose':
+ emit('complete',stage='features',output=str(keypoint_path),cached=pose_cached,elapsed=time.monotonic()-started)
+ return keypoint_path
emit("progress", stage="gvhmr", message="Computing image features", current=1, total=3)
feature_path = project / "features.pt"
- if cached(project,state,feature_path.name):
+ feature_cached=cached(project,state,feature_path.name)
+ if feature_cached:
features = torch.load(feature_path, map_location="cpu", weights_only=False)
else:
- extractor = Extractor()
+ extractor = acquire(model_key("gv_features",BY_KEY["hmr2"].path),Extractor)
features = streamed_features(project,bbx,lambda images,boxes: extractor.extract_video_features(images,boxes),
plan['image_batch'],plan['prefetch_batches'],progress('Computing GVHMR image features'))
save_tensor(features, feature_path)
@@ -244,6 +253,7 @@ def features(project: Path, emit) -> Path:
del extractor
gc.collect()
torch.cuda.empty_cache()
+ if phase=='features':emit('complete',stage='features',output=str(feature_path),cached=pose_cached and feature_cached,elapsed=time.monotonic()-started)
return feature_path
@@ -258,14 +268,18 @@ def gvhmr(project: Path, emit) -> Path:
import hmr4d.model.gvhmr.utils.endecoder
from hmr4d.model.gvhmr.gvhmr_pl_demo import DemoPL
from hydra import compose, initialize_config_module
- tracking = np.load(project / "tracking.npz")
+ with np.load(project / "tracking.npz") as tracking:tracking={key:tracking[key].copy() for key in tracking.files}
bbx = get_bbx_xys_from_xyxy(torch.from_numpy(tracking["boxes"]), base_enlarge=1.2)
kp = torch.load(project / "gvhmr_keypoints.pt", map_location="cpu", weights_only=False)
features_tensor = torch.load(project / "features.pt", map_location="cpu", weights_only=False)
with initialize_config_module(version_base="1.3", config_module="hmr4d.configs"):
cfg = compose(config_name="demo")
- model = DemoPL(cfg.pipeline).eval().cuda()
- model.load_pretrained_model(BY_KEY["gvhmr"].path)
+ from .model_session import acquire,model_key
+ def build():
+ model = DemoPL(cfg.pipeline).eval().cuda()
+ model.load_pretrained_model(BY_KEY["gvhmr"].path)
+ return model
+ model = acquire(model_key('gvhmr',BY_KEY['gvhmr'].path),build)
data = {"length": torch.tensor(len(bbx)), "bbx_xys": bbx, "kp2d": kp,
"K_fullimg": torch.from_numpy(tracking["K"])[None].expand(len(bbx), 3, 3),
"cam_angvel": torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float32)[None].expand(len(bbx), 6),
diff --git a/mocap/exmr_backend.py b/mocap/exmr_backend.py
index 8c4792d..114ad4f 100644
--- a/mocap/exmr_backend.py
+++ b/mocap/exmr_backend.py
@@ -9,6 +9,7 @@ import numpy as np
from .paths import ROOT, HOME, UPSTREAM
from .storage import atomic_json, sha256
from .resource_cache import code_hash
+from .model_session import set_memory_budget
from .compute_policy import gpu_memory_fraction
from .result_artifacts import file_stat
from .exmr_options import saved
@@ -45,7 +46,7 @@ def activate():
for name in ('exmr','third_party/sapiens2/sapiens','third_party/hamer/hamer','third_party/dinov3'):
if not (root/name).is_dir():raise RuntimeError('ExMR runtime is missing. Repair the application installation.')
for path in (root,root/'third_party/sapiens2',root/'third_party/hamer'):
- sys.path.insert(0,str(path))
+ if str(path) not in sys.path:sys.path.insert(0,str(path))
os.environ.update(PYOPENGL_PLATFORM='win32',WANDB_MODE='disabled',PYTHONNOUSERSITE='1')
weights=HOME/'cache/exmr/assets';weights.mkdir(parents=True,exist_ok=True)
for key,name in LINKS.items():
@@ -63,7 +64,9 @@ def activate():
if repository=='facebookresearch/dinov3':
repository=str(root/'third_party/dinov3');kwargs['source']='local'
return original(repository,*args,**kwargs)
- torch.hub.load=local_hub
+ if not getattr(original, '_rgb_exmr', False):
+ local_hub._rgb_exmr=True
+ torch.hub.load=local_hub
config=root/'configs/hamer_model_config.yaml'
if sha256(config)!='0e5eeb82752e47dfd01db8e13ccc4c5eba9bf83f53da8285523b8d3e87247aa3':
raise RuntimeError('ExMR HaMeR configuration is damaged. Repair the application.')
@@ -132,6 +135,7 @@ def identity(project,stage):
'exmr':['tracking.npz','exmr_keypoints.pt','exmr_body_features.pt','exmr_hand_features.pt']}[stage]
root=scene_root(project);root_state=json.loads((root/'project.json').read_text(encoding='utf-8'))
return dict(version=VERSION,stage=stage,inputs={name:file_stat(project/name) for name in files},
+ memory_policy={name:sha256(ROOT/'mocap'/name) for name in ('memory_mode.py','gpu_offload.py','model_session.py','batch_prefetch.py')},
root_input=file_stat(root/'input.mp4'),take=state.get('person_frames'),frames=state['frames'],fps=state['fps'],
options=saved(root,root_state) if stage=='exmr' else {'pose':'Sapiens2-1B 448x336'},
models={key:file_stat(BY_KEY[key].path) for key in STAGE_REQUIREMENTS[stage]},
@@ -140,6 +144,8 @@ def identity(project,stage):
'exmr_features':('image_io.py','body_features.py','hand_features.py'),
'exmr':(),
}[stage]},
+ feature_decoder={name:sha256(UPSTREAM/'ExMR/third_party/sam-3d-body/sam_3d_body/models'/name)
+ for name in ('decoders/promptable_decoder.py','meta_arch/sam3d_body.py')} if stage=='exmr_features' else {},
code=code_hash(Path(__file__)),upstream=sha256(UPSTREAM/'ExMR/RGB_MOCAP_PROVENANCE.json'))
@@ -187,12 +193,13 @@ def complete_stage(project,stage,output,elapsed,cached,emit):
emit('complete',stage=stage,cached=cached,elapsed=0 if cached else elapsed,output=str(output))
-def run_stage(project,stage,result,emit,force=False):
+def run_stage(project,stage,result,emit,force=False,feature_phase=None):
import torch,cv2,psutil
from .models import missing,BY_KEY
from .engines import save_tensor
project=Path(project);state=json.loads((project/'project.json').read_text(encoding='utf-8'));n=state['frames']
if stage not in STAGES or result not in ('auto','initial','corrected_initial'):raise ValueError('Unsupported ExMR stage/result')
+ if feature_phase not in (None,'body','hand') or (feature_phase and stage!='exmr_features'):raise ValueError('Invalid ExMR feature phase')
if n<1:raise ValueError('ExMR clip is empty')
absent=missing(stage)
if absent:raise ValueError('Open ExMR Model Manager and prepare: '+', '.join(m.name for m in absent))
@@ -214,12 +221,13 @@ def run_stage(project,stage,result,emit,force=False):
complete_stage(project,stage,project/outputs[0],old.get('elapsed',0),True,emit);return
if not torch.cuda.is_available():raise RuntimeError('ExMR requires a supported NVIDIA CUDA GPU. Check System in Help for details.')
started=time.monotonic()
- free,total=torch.cuda.mem_get_info();torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
+ free,total=torch.cuda.mem_get_info();set_memory_budget(free,total)
torch.set_num_threads(4);cv2.setNumThreads(2);torch.manual_seed(0);np.random.seed(0)
torch.cuda.reset_peak_memory_stats();atomic_json(pending,dict(identity=signature))
# Invalidate the old source generation as soon as new observations begin.
atomic_json(project/'exmr_pending.json',dict(stage=stage,identity=signature))
root,weights=activate()
+ from .model_session import acquire,model_key,release
from exmr import pipeline as P
from exmr.assets import Assets
with np.load(project/'tracking.npz',allow_pickle=False) as tracking:
@@ -231,21 +239,58 @@ def run_stage(project,stage,result,emit,force=False):
if stage=='exmr_preprocess':
from exmr.preprocessing.keypoints.sapiens2 import Sapiens2Keypoints
emit('progress',current=0,total=n,message='ExMR: body, hand and foot keypoints (Balanced)')
- values=Sapiens2Keypoints(BY_KEY['exmr_sapiens'].path,resolution='448x336',num_workers=0)(frame_dir(project,n),boxes)
+ from .memory_mode import run as memory_run
+ directory=frame_dir(project,n)
+ def keypoints(low):
+ model=acquire(model_key('sapiens',BY_KEY['exmr_sapiens'].path,low_memory=low),
+ lambda:Sapiens2Keypoints(BY_KEY['exmr_sapiens'].path,resolution='448x336',num_workers=0,low_memory=low))
+ try:return model(directory,boxes)
+ finally:release(model)
+ values=memory_run('ExMR Sapiens',keypoints,6.,emit)
save_tensor(values,project/outputs[0])
elif stage=='exmr_features':
directory=frame_dir(project,n)
from exmr.preprocessing.body_features import SamBodyFeatures
- emit('progress',current=0,total=n,message='ExMR: SAM body features')
- values=SamBodyFeatures(weights/'sam-3d-body-dinov3',batch_size=8,num_workers=0)(directory,boxes,k)
- save_tensor(values,project/'exmr_body_features.pt');del values;gc.collect();torch.cuda.empty_cache()
+ from .memory_mode import run as memory_run
+ def body_features(low):
+ model=acquire(model_key('exmr_sam',*[BY_KEY[key].path for key in ('flow_sam','flow_sam_config','flow_mhr')],low_memory=low),
+ lambda:SamBodyFeatures(weights/'sam-3d-body-dinov3',batch_size=8,num_workers=0,low_memory=low))
+ try:return model(directory,boxes,k)
+ finally:release(model)
+ body_receipt=project/'exmr_body_partial.json'
+ body_valid=False
+ # A hand-only phase reuses the validated body partial, including after
+ # a forced body phase in this same pipeline. Force still rebuilds hands.
+ if feature_phase is not None and (not force or feature_phase=='hand'):
+ try:
+ partial=json.loads(body_receipt.read_text(encoding='utf-8'))
+ body_valid=partial['identity']==signature and partial['output']==file_stat(project/'exmr_body_features.pt')
+ if body_valid:
+ values=load(project/'exmr_body_features.pt')
+ body_valid=tuple(values.shape)==(n,1024) and bool(torch.isfinite(values).all())
+ del values
+ except (OSError,ValueError,KeyError,RuntimeError,EOFError):pass
+ if not body_valid:
+ emit('progress',current=0,total=n,message='ExMR: SAM body features')
+ values=memory_run('ExMR body features',body_features,5.5,emit)
+ save_tensor(values,project/'exmr_body_features.pt');del values;gc.collect();torch.cuda.empty_cache()
+ if identity(project,stage)!=signature:raise ValueError('ExMR inputs changed during body feature extraction')
+ atomic_json(body_receipt,dict(identity=signature,output=file_stat(project/'exmr_body_features.pt')))
+ if feature_phase=='body':
+ emit('complete',stage=stage,output=str(project/'exmr_body_features.pt'),cached=body_valid,elapsed=time.monotonic()-started)
+ return
prepare_mano(root,weights)
from exmr.preprocessing.hand_features import HamerHandFeatures,hand_boxes_from_keypoints
from exmr.preprocessing.keypoints import VISIBILITY_THRESHOLD
points=load(project/'exmr_keypoints.pt');threshold=VISIBILITY_THRESHOLD['sapiens2']
hand_boxes=torch.stack([hand_boxes_from_keypoints(points[:,COCO63_LEFT_HAND],threshold),hand_boxes_from_keypoints(points[:,COCO63_RIGHT_HAND],threshold)],1)
emit('progress',current=0,total=n,message='ExMR: left and right hand features')
- values=HamerHandFeatures(weights/'hamer',batch_size=8,num_workers=0)(directory,hand_boxes)
+ def hand_features(low):
+ model=acquire(model_key('hamer',*[BY_KEY[key].path for key in ('hand_hamer','hand_mean','mano_right')],low_memory=low),
+ lambda:HamerHandFeatures(weights/'hamer',batch_size=8,num_workers=0,low_memory=low))
+ try:return model(directory,hand_boxes)
+ finally:release(model)
+ values=memory_run('ExMR hand features',hand_features,5.5,emit)
save_tensor(values,project/'exmr_hand_features.pt')
else:
from exmr.geometry.camera import bbx_xys_from_xyxy,cam_angvel_from_rotations
@@ -255,7 +300,14 @@ def run_stage(project,stage,result,emit,force=False):
bbx_xyxy=boxes,K_fullimg=k,cam_angvel=cam_angvel_from_rotations(rotations),
body_feat=load(project/'exmr_body_features.pt'),hand_feat=load(project/'exmr_hand_features.pt'))
emit('progress',current=0,total=n,message='ExMR: reconstruct and refine full body, feet and fingers')
- native=P._run_model(data,P.Options(static_cam=config['static_camera'],smoothing=config['smoothing'],snap_to_ground=False,render=False),state['fps'],Assets(weights))
+ from exmr.model.exmr import ExMR
+ assets=Assets(weights)
+ model=acquire(model_key('exmr',BY_KEY['exmr'].path,BY_KEY['smplx'].path),
+ lambda:ExMR.from_pretrained(assets.exmr,assets.smplx))
+ try:
+ native=P._run_model(data,P.Options(static_cam=config['static_camera'],smoothing=config['smoothing'],snap_to_ground=False,render=False),state['fps'],assets,model=model)
+ finally:release(model)
+ del model
native['fps']=state['fps'];validate_native(native,n)
import smplx
body=smplx.SMPLX(str(BY_KEY['smplx'].path),flat_hand_mean=False,use_pca=False).eval()
diff --git a/mocap/flow_backend.py b/mocap/flow_backend.py
index 8599f8a..7c62630 100644
--- a/mocap/flow_backend.py
+++ b/mocap/flow_backend.py
@@ -1,373 +1,435 @@
-"""Isolated official FlowHMR inference. Never imported by viewport painting.
-
-Native SMPL-H is retained. The upstream generator conditions on camera rotation,
-not metric camera translation; scene placement is a separate constant offset.
-"""
-from pathlib import Path
-import gc, hashlib, json, math, os, sys, uuid
-import numpy as np
-from .paths import ROOT, UPSTREAM
-from .storage import atomic_json, sha256
-from .compute_policy import gpu_memory_fraction
-from .result_artifacts import file_stat
-
-VERSION=1
-MAX_FRAMES=5000 # Pinned FlowHMR per-branch RoPE table; 30 fps.
-ASSET_LINKS={
- 'flowhmr':'checkpoints/flowhmr_latest/flowhmr_latest.ckpt',
- 'flow_config':'checkpoints/flowhmr_latest/config.yml',
- 'flow_sam':'ckpts/sam-3d-body-dinov3/model.ckpt',
- 'flow_sam_config':'ckpts/sam-3d-body-dinov3/model_config.yaml',
- 'flow_mhr':'ckpts/sam-3d-body-dinov3/assets/mhr_model.pt',
- 'flow_vggt':'ckpts/vggt-omega/vggt_omega_1b_512.pt',
- 'smplh':'assets/body_models/smplh/neutral/model.npz',
-}
-
-
-def scene_root(project):
- state=json.loads((project/'project.json').read_text(encoding='utf-8'))
- if state.get('people_root'):
- root=(project/state['people_root']).resolve()
- if not project.resolve().is_relative_to(root) or not (root/'people.json').is_file():
- raise ValueError('Invalid FlowHMR people scene path')
- return root
- return project
-
-
-def camera_interval(frames,requested=0):
- if requested not in (-1,0,1,2,5,10,30):raise ValueError('Unsupported camera sampling interval')
- return requested or max(1,math.ceil((frames-1)/127))
-
-
-def validate_length(frames):
- """Retain the pinned model's real context limit, without memory estimates."""
- if frames<1:raise ValueError('The motion clip is empty')
- if frames>MAX_FRAMES:
- raise ValueError(f'FlowHMR supports up to {MAX_FRAMES:,} frames ({MAX_FRAMES/30:.1f} seconds at 30 fps). Trim the timeline clip; full temporal context is retained.')
-
-
-def activate():
- import torch
- from .models import BY_KEY,ready
- root=UPSTREAM/'FlowHMR'
- if not (root/'flowhmr/pipeline/v2m_inference.py').is_file():
- raise RuntimeError('The FlowHMR runtime is missing. Repair or reinstall RGB MoCap.')
- for key,name in ASSET_LINKS.items():
- model=BY_KEY[key]
- if not ready(model):continue
- target=root/name;target.parent.mkdir(parents=True,exist_ok=True)
- if target.exists() and target.samefile(model.path):continue
- if target.exists():target.unlink()
- try:os.link(model.path,target)
- except OSError:
- # Models may live on another drive. Copy only during explicit setup,
- # never unexpectedly duplicate multi-GB weights at inference time.
- try:target.symlink_to(model.path)
- except OSError as error:raise RuntimeError('Keep the app and its models on the same drive, or enable Windows symbolic links.') from error
- os.chdir(root);sys.path.insert(0,str(root))
- os.environ.setdefault('WANDB_MODE','disabled')
- # An upstream hub import would otherwise require a first-run network fetch.
- original=torch.hub.load
- def local_hub(repo,model,*args,**kwargs):
- if repo=='facebookresearch/dinov3':
- repo=str(root/'third_party/dinov3');kwargs['source']='local'
- return original(repo,model,*args,**kwargs)
- torch.hub.load=local_hub
- upstream_load=torch.load
- allowed={str((root/name).resolve()) for name in ASSET_LINKS.values()}
- def official_load(path,*args,**kwargs):
- if isinstance(path,(str,Path)) and str(Path(path).resolve()) in allowed:
- kwargs.setdefault('weights_only',False)
- return upstream_load(path,*args,**kwargs)
- torch.load=official_load
- return root
-
-
-def load_tensor(path):
- import torch
- return torch.load(path,map_location='cpu',weights_only=False,mmap=True)
-
-
-def save_tensor(path,value):
- import torch
- temporary=path.with_name(path.name+'.'+uuid.uuid4().hex+'.tmp')
- try:torch.save(value,temporary);os.replace(temporary,path)
- finally:temporary.unlink(missing_ok=True)
-
-
-def identity(project,stage):
- from .models import BY_KEY,STAGE_REQUIREMENTS
- state=json.loads((project/'project.json').read_text(encoding='utf-8'))
- names={'flow_camera':['input.mp4'], 'flow_features':['input.mp4','tracking.npz'],
- 'flowhmr':['flow_tokens.pt','flow_camera.npz','flow_placement.json','tracking.npz'],
- 'flow_export':['hmr4d_results.pt']}[stage]
- root=scene_root(project)
- root_state=json.loads((root/'project.json').read_text(encoding='utf-8'))
- selected=root_state.get('flow_options',{}).get('camera_interval',0)
- files={name:file_stat(project/name) for name in names if (project/name).exists()}
- # Full-scene camera is shared even when each person has shorter visible takes.
- if stage=='flow_camera':
- files={'root_input':file_stat(root/'input.mp4')}
- if root!=project and (root/'flow_camera.npz').exists():files['root_camera']=file_stat(root/'flow_camera.npz')
- import inspect
- # Export/rig improvements must not discard expensive camera/SAM/inference.
- functions={'flow_camera':(camera,camera_interval), 'flow_features':(features,), 'flowhmr':(infer,validate_motion)}
- if stage=='flow_export':
- code={name:sha256(ROOT/'mocap'/name) for name in ('flow_export.py','source_pose_fit.py','mixamo_rig.py','bvh_bind.py','mixamo_data.py')}
- else:
- code={'adapter':hashlib.sha256(''.join(inspect.getsource(f) for f in (*functions[stage],activate,load_tensor,save_tensor)).encode()).hexdigest()}
- upstream={'flow_camera':'flowhmr/utils/runtime_vggt_camera.py','flow_features':'flowhmr/utils/runtime_sam_features.py','flowhmr':'flowhmr/pipeline/pipeline_v2m.py'}.get(stage)
- if upstream:code[upstream]=sha256(UPSTREAM/'FlowHMR'/upstream)
- if stage in ('flow_camera','flowhmr'):code['flow_camera.py']=sha256(ROOT/'mocap/flow_camera.py')
- if stage=='flow_features':code['flow_sam.py']=sha256(ROOT/'mocap/flow_sam.py')
- if stage=='flow_features':
- from .flow_sam import saved_fast_sam, source_identity
- code['sam_source']=source_identity(saved_fast_sam(project,state))
- import torch
- return dict(version=VERSION,stage=stage,inputs=files,camera_interval=selected if stage=='flow_camera' else None,
- models={key:file_stat(BY_KEY[key].path) for key in STAGE_REQUIREMENTS[stage] if not (stage=='flow_camera' and selected==-1)},
- code=code,runtime=[str(torch.__version__),torch.version.cuda],frames=state['frames'],fps=state['fps'],take=state.get('person_frames'))
-
-
-def validate_motion(output,n):
- import torch
- for key,shape in [('rot6d',(1,n,52,6)),('trans',(1,n,3))]:
- if key not in output or tuple(output[key].shape)!=shape or not torch.isfinite(output[key]).all():
- raise ValueError('FlowHMR returned invalid '+key)
- if tuple(output['shapes'].shape)!=(1,1,16) or not torch.isfinite(output['shapes']).all():
- raise ValueError('FlowHMR requires 16 finite SMPL-H shape coefficients')
-
-
-def camera(project,emit,force=False):
- import torch
- root=scene_root(project)
- state=json.loads((root/'project.json').read_text(encoding='utf-8'));n=state['frames']
- interval=camera_interval(n,state.get('flow_options',{}).get('camera_interval',0))
- if root!=project:
- run_stage(root,'flow_camera','initial',emit,force=force)
- begin,end=json.loads((project/'project.json').read_text(encoding='utf-8'))['person_frames']
- with np.load(root/'flow_camera.npz',allow_pickle=False) as data:
- values={key:data[key][begin:end] for key in ('camera_RT_yup','K')}
- temporary=project/'flow_camera.partial.npz';np.savez(temporary,**values);os.replace(temporary,project/'flow_camera.npz')
- atomic_json(project/'flow_camera_sources.json',{'root_camera':file_stat(root/'flow_camera.npz')})
- return project/'flow_camera.npz'
- if interval==-1:
- from .flow_camera import static_camera
- emit('progress',current=n,total=n,message='Use explicit locked static camera; VGGT skipped')
- target=project/'flow_camera.partial.npz'
- np.savez(target,**static_camera(n,state['width'],state['height']))
- os.replace(target,project/'flow_camera.npz')
- return project/'flow_camera.npz'
- emit('progress',current=0,total=0,message=f'Estimate one scene camera ({interval}-frame sampling)')
- from flowhmr.utils.runtime_vggt_camera import extract_vggt_camera
- target=project/'flow_camera.partial.npz'
- target.unlink(missing_ok=True) # upstream must not reuse a partial extraction
- extract_vggt_camera(str(project/'input.mp4'),output_npz=str(target),frame_range=(0,n-1),
- expected_len=n,frame_interval=interval,keep_frames=False,camera_only=True)
- with np.load(target,allow_pickle=False) as data:
- if data['camera_RT_yup'].shape!=(n,4,4) or data['K'].shape!=(n,3,3) or not all(np.isfinite(data[k]).all() for k in ('camera_RT_yup','K')):
- raise ValueError('VGGT-Omega returned incomplete camera data')
- r=data['camera_RT_yup'][:,:3,:3]
- if not np.allclose(r.swapaxes(-1,-2)@r,np.eye(3),atol=2e-4):raise ValueError('Invalid camera rotations')
- os.replace(target,project/'flow_camera.npz')
- return project/'flow_camera.npz'
-
-
-def features(project,emit):
- import cv2, torch
- from .flow_sam import build_extractor, saved_fast_sam
- state=json.loads((project/'project.json').read_text(encoding='utf-8'));n=state['frames']
- with np.load(project/'tracking.npz',allow_pickle=False) as data:boxes=data['boxes'].copy()
- if boxes.shape!=(n,4):raise ValueError('Tracking and video frame counts differ')
- k=np.array([[math.hypot(state['width'],state['height']),0,state['width']/2],
- [0,math.hypot(state['width'],state['height']),state['height']/2],[0,0,1]],np.float32)
- fast=saved_fast_sam(project,state)
- extractor=build_extractor(torch.device('cuda'),fast=fast)
- cap=cv2.VideoCapture(str(project/'input.mp4'));cap.set(cv2.CAP_PROP_N_THREADS,2) if hasattr(cv2,'CAP_PROP_N_THREADS') else None
- from .flow_sam import extract_tokens
- tokens=torch.empty((n,3072),dtype=torch.float32);anchors=[]
- try:
- for index in range(n):
- ok,frame=cap.read()
- if not ok:raise ValueError(f'Cannot decode FlowHMR frame {index+1}')
- token,outputs=extract_tokens(extractor,cv2.cvtColor(frame,cv2.COLOR_BGR2RGB),boxes[index:index+1],torch.from_numpy(k[None]),placement=index<min(n,30))
- if token.shape!=(3072,) or not torch.isfinite(token).all():raise ValueError(f'Body/hand feature extraction failed at frame {index+1}')
- tokens[index]=token.float()
- if index<min(n,30) and outputs:
- # MHR70 defines hips at 9/10, in metres in OpenCV camera space.
- person=outputs[0]
- pelvis=person['pred_keypoints_3d'][[9,10]].mean(0)+person['pred_cam_t']
- if np.isfinite(pelvis).all() and pelvis[2]>.05:anchors.append([index,*pelvis.tolist()])
- if index%10==0 or index==n-1:emit('progress',current=index+1,total=n,message='Extract body and hand features (Fast SAM)' if fast else 'Extract body and hand features (Original SAM)')
- if cap.read()[0]:raise ValueError('Video contains more frames than its project manifest')
- finally:
- cap.release()
- for hook in extractor._hooks:hook.remove()
- save_tensor(project/'flow_tokens.pt',tokens)
- atomic_json(project/'flow_placement.json',dict(camera_pelvis=anchors,intrinsics=k.tolist(),method='Constant X/Z placement from SAM MHR70 pelvis; native FlowHMR height and motion retained'))
- return project/'flow_tokens.pt'
-
-
-def infer(project,emit):
- import torch
- from flowhmr.pipeline.v2m_inference import build_pipeline,load_yaml,build_feature_dict
- from flowhmr.core.bodymodels.smpl_skeleton import SMPLSkeleton
- from .models import BY_KEY
- checkpoint=BY_KEY['flowhmr'].path
- tokens=load_tensor(project/'flow_tokens.pt');n=len(tokens)
- if tokens.shape!=(n,3072) or not torch.isfinite(tokens).all():raise ValueError('Invalid cached SAM features; rerun feature extraction.')
- with np.load(project/'flow_camera.npz',allow_pickle=False) as data:rt=torch.from_numpy(data['camera_RT_yup'].copy())
- if tuple(rt.shape)!=(n,4,4):raise ValueError('Camera and body frame counts differ')
- pipeline=build_pipeline(load_yaml(str(BY_KEY['flow_config'].path)),device='cuda',ckpt=str(checkpoint),validation_steps=20)
- weights=load_tensor(checkpoint)
- weights=weights.get('model_state_dict',weights.get('state_dict',weights))
- if any(name not in weights or tuple(weights[name].shape)!=tuple(value.shape) for name,value in pipeline.named_parameters()):
- raise ValueError('FlowHMR checkpoint is missing required learned parameters. Repair its checkpoint and configuration.')
- del weights
- emit('progress',current=0,total=20,message='FlowHMR: integrate 20 ODE steps')
- from .flow_camera import relative_camera
- with torch.inference_mode():
- output=pipeline.generate(feature=build_feature_dict(tokens,relative_camera(rt),torch.device('cuda')),seeds=[0],length=n,cfg_scale=1.0)
- output={key:value.detach().cpu() if isinstance(value,torch.Tensor) else value for key,value in output.items()}
- validate_motion(output,n)
- save_tensor(project/'flow_prediction.pt',output) # untouched official prediction
- del pipeline;gc.collect();torch.cuda.empty_cache()
- placement=json.loads((project/'flow_placement.json').read_text(encoding='utf-8'))
- anchors=np.asarray(placement['camera_pelvis'],float)
- offset=np.zeros(3,np.float32)
- if len(anchors):
- skeleton=SMPLSkeleton(model_path=str(BY_KEY['smplh'].path))
- count=min(n,30)
- with torch.no_grad():
- joints=skeleton(dict(rot6d=output['rot6d'][0,:count],shapes=output['shapes'].reshape(1,16),trans=output['trans'][0,:count]))['keypoints3d'].numpy()
- differences=[]
- for row in anchors:
- index=int(row[0]);r=rt[index,:3,:3].numpy()
- differences.append(r.T@row[1:]-joints[index,0])
- offset[[0,2]]=np.median(differences,axis=0)[[0,2]]
- placed={key:value.clone() if isinstance(value,torch.Tensor) else value for key,value in output.items()}
- placed['trans']=placed['trans']+torch.from_numpy(offset)[None,None]
- placed['scene_offset']=torch.from_numpy(offset)
- placed['source_representation']='smplh';placed['flow_version']=VERSION
- save_tensor(project/'hmr4d_results.pt',placed)
- atomic_json(project/'initial_sources.json',{name:file_stat(project/name) for name in ('flow_prediction.pt','flow_tokens.pt','flow_camera.npz','flow_placement.json','tracking.npz')})
- return project/'hmr4d_results.pt'
-
-
-def run_stage(project,stage,result,emit,force=False):
- import time,torch,psutil
- from .models import missing
- project=Path(project);started=time.monotonic()
- torch.set_num_threads(4)
- if stage in ('correct','rig','mesh','export','flow_export'):
- return run_post(project,stage,result,emit,force)
- if stage in ('rig','mesh','export'):stage='flow_export'
- if stage not in ('flow_camera','flow_features','flowhmr','flow_export'):
- raise ValueError('This processing stage is not compatible with FlowHMR')
- if result not in ('auto','initial','corrected_initial'):raise ValueError('FlowHMR supports original or corrected original motion only')
- static=(stage=='flow_camera' and json.loads((scene_root(project)/'project.json').read_text(encoding='utf-8')).get('flow_options',{}).get('camera_interval',0)==-1)
- absent=[] if static else missing(stage)
- if absent:raise ValueError('Open FlowHMR Model Manager and prepare: '+', '.join(m.name for m in absent))
- state=json.loads((project/'project.json').read_text(encoding='utf-8'))
- signature=identity(project,stage)
- receipt_path=project/(stage+'_receipt.json');pending=project/(stage+'_pending.json')
- cached=False
- if not force and not pending.exists() and receipt_path.exists():
- try:
- receipt=json.loads(receipt_path.read_text(encoding='utf-8'))
- cached=receipt['identity']==signature and all(Path(name).name==name and file_stat(project/name)==stamp for name,stamp in receipt['outputs'].items())
- if cached and stage=='flow_export':
- from .mixamo_data import current
- from .result_artifacts import artifacts_current
- cached=current(project,'initial') and artifacts_current(project,'initial')
- if cached and stage=='flowhmr':validate_motion(load_tensor(project/'hmr4d_results.pt'),state['frames'])
- except Exception:cached=False # A damaged cached tensor must recover without AI inference.
- if stage=='flowhmr' and not force:
- from .flow_placement import prediction_current,ensure
- if prediction_current(project):
- activate();ensure(project);cached=True
- if cached:
- emit('complete',stage=stage,output=str(project/next(iter(receipt['outputs']))),cached=True,elapsed=0);return
- root=scene_root(project);root_state=json.loads((root/'project.json').read_text(encoding='utf-8'))
- n=root_state['frames'] if stage=='flow_camera' else state['frames']
- interval=camera_interval(n,root_state.get('flow_options',{}).get('camera_interval',0))
- free=total=None
- if stage!='flow_export' and not static:
- if not torch.cuda.is_available():raise RuntimeError('FlowHMR requires a supported NVIDIA CUDA GPU.')
- free,total=torch.cuda.mem_get_info()
- validate_length(n)
- if free is not None:torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
- if not static:activate()
- atomic_json(pending,dict(stage=stage,started=time.time()))
- if stage=='flow_camera':output=camera(project,emit,force=force)
- elif stage=='flow_features':output=features(project,emit)
- elif stage=='flowhmr':
- output=infer(project,emit)
- from .flow_placement import ensure
- ensure(project,generated=True)
- else:
- from .flow_export import prepare
- output=prepare(project,emit)
- outputs=[output.name]
- if stage=='flow_camera' and root!=project:outputs.append('flow_camera_sources.json')
- if stage=='flow_features':outputs.append('flow_placement.json')
- if stage=='flowhmr':outputs+=['flow_prediction.pt','initial_sources.json','flow_world.json']
- committed_identity=identity(project,stage)
- if stage=='flow_features' and committed_identity!=signature:
- raise RuntimeError('SAM inputs or settings changed during extraction. Reconstruct 3D again; this extraction was not committed.')
- receipt=dict(identity=committed_identity,outputs={name:file_stat(project/name) for name in outputs})
- atomic_json(receipt_path,receipt);pending.unlink(missing_ok=True)
- latest=json.loads((project/'project.json').read_text(encoding='utf-8'))
- latest.setdefault('pipeline',{}).update(model='flowhmr',result='initial',htd_refine=False,footmr=False)
- latest.setdefault('stages',{})[stage]=dict(status='complete',elapsed=time.monotonic()-started,output=str(output))
- atomic_json(project/'project.json',latest)
- emit('complete',stage=stage,output=str(output),cached=False,elapsed=time.monotonic()-started,
- peak_ram_gib=psutil.Process().memory_info().peak_wset/1024**3,
- peak_cuda_allocated_gib=torch.cuda.max_memory_allocated()/1024**3 if torch.cuda.is_initialized() else 0)
-
-
-def run_post(project,stage,result,emit,force=False):
- """CPU-only contact/export stages, separately validated from AI caches."""
- import time,torch,psutil
- from .models import missing
- from .motion_tools import result_is_current,selected_export
- from .flow_export import prepare
- from .flow_correction import run,code_identity
- kind='initial' if result=='auto' else result
- if kind not in ('initial','corrected_initial'):raise ValueError('FlowHMR supports original or corrected original motion only')
- absent=missing('flow_export')
- if absent:raise ValueError('Import the SMPL-H neutral body model in FlowHMR Model Manager.')
- validate_length(json.loads((project/'project.json').read_text(encoding='utf-8'))['frames'])
- activate()
- from .flow_placement import ensure_group
- ensure_group(project)
- started=time.monotonic();cached=False
- if stage=='correct':
- if kind!='corrected_initial':raise ValueError('Select a corrected result')
- try:
- report=json.loads((project/(kind+'_correction.json')).read_text(encoding='utf-8'))
- from .correction import backend
- cached=(not force and result_is_current(project,kind) and report.get('code')==code_identity()
- and report.get('backend_sha256')==sha256(Path(backend().__file__)))
- if cached:validate_motion(load_tensor(project/(kind+'.pt')),report['frames'])
- except Exception:cached=False # Cache decoding failure is recoverable, not an inference failure.
- if not cached:
- activate();output=run(project,emit,kind)
- else:output=project/(kind+'.pt')
- else:
- if kind=='corrected_initial' and not result_is_current(project,kind):
- run(project,emit,kind)
- # Keep both selections available. Missing/corrupt payloads rebuild only
- # this inexpensive derived preview; source inference is never rerun.
- activate()
- for selected in (('initial',kind) if kind!='initial' else ('initial',)):
- current=selected_export(project,selected)
- if force or current is None:output=prepare(project,emit,selected)
- else:output=current
- latest=json.loads((project/'project.json').read_text(encoding='utf-8'))
- latest.setdefault('pipeline',{}).update(model='flowhmr',result=kind,htd_refine=False,footmr=False)
- latest.setdefault('stages',{})[stage]=dict(status='complete',elapsed=time.monotonic()-started,output=str(output))
- atomic_json(project/'project.json',latest)
- if stage in ('export','flow_export','rig','mesh'):(project/'flow_export_pending.json').unlink(missing_ok=True)
- emit('complete',stage=stage,output=str(output),cached=cached,elapsed=time.monotonic()-started,
- peak_ram_gib=psutil.Process().memory_info().peak_wset/1024**3)
+"""Isolated official FlowHMR inference. Never imported by viewport painting.
+
+Native SMPL-H is retained. The upstream generator conditions on camera rotation,
+not metric camera translation; scene placement is a separate constant offset.
+"""
+from pathlib import Path
+import gc, hashlib, json, math, os, sys, uuid
+import numpy as np
+from .paths import ROOT, UPSTREAM
+from .storage import atomic_json, sha256
+from .model_session import set_memory_budget
+from .compute_policy import gpu_memory_fraction
+from .result_artifacts import file_stat
+
+VERSION=1
+MAX_FRAMES=5000 # Pinned FlowHMR per-branch RoPE table; 30 fps.
+ASSET_LINKS={
+ 'flowhmr':'checkpoints/flowhmr_latest/flowhmr_latest.ckpt',
+ 'flow_config':'checkpoints/flowhmr_latest/config.yml',
+ 'flow_sam':'ckpts/sam-3d-body-dinov3/model.ckpt',
+ 'flow_sam_config':'ckpts/sam-3d-body-dinov3/model_config.yaml',
+ 'flow_mhr':'ckpts/sam-3d-body-dinov3/assets/mhr_model.pt',
+ 'flow_vggt':'ckpts/vggt-omega/vggt_omega_1b_512.pt',
+ 'smplh':'assets/body_models/smplh/neutral/model.npz',
+}
+
+
+def scene_root(project):
+ state=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ if state.get('people_root'):
+ root=(project/state['people_root']).resolve()
+ if not project.resolve().is_relative_to(root) or not (root/'people.json').is_file():
+ raise ValueError('Invalid FlowHMR people scene path')
+ return root
+ return project
+
+
+def camera_interval(frames,requested=0):
+ if requested not in (-1,0,1,2,5,10,30):raise ValueError('Unsupported camera sampling interval')
+ return requested or max(1,math.ceil((frames-1)/127))
+
+
+def validate_length(frames):
+ """Retain the pinned model's real context limit, without memory estimates."""
+ if frames<1:raise ValueError('The motion clip is empty')
+ if frames>MAX_FRAMES:
+ raise ValueError(f'FlowHMR supports up to {MAX_FRAMES:,} frames ({MAX_FRAMES/30:.1f} seconds at 30 fps). Trim the timeline clip; full temporal context is retained.')
+
+
+def activate():
+ import torch
+ from .models import BY_KEY,ready
+ root=UPSTREAM/'FlowHMR'
+ if not (root/'flowhmr/pipeline/v2m_inference.py').is_file():
+ raise RuntimeError('The FlowHMR runtime is missing. Repair or reinstall RGB MoCap.')
+ for key,name in ASSET_LINKS.items():
+ model=BY_KEY[key]
+ if not ready(model):continue
+ target=root/name;target.parent.mkdir(parents=True,exist_ok=True)
+ if target.exists() and target.samefile(model.path):continue
+ if target.exists():target.unlink()
+ try:os.link(model.path,target)
+ except OSError:
+ # Models may live on another drive. Copy only during explicit setup,
+ # never unexpectedly duplicate multi-GB weights at inference time.
+ try:target.symlink_to(model.path)
+ except OSError as error:raise RuntimeError('Keep the app and its models on the same drive, or enable Windows symbolic links.') from error
+ os.chdir(root)
+ if str(root) not in sys.path:sys.path.insert(0,str(root))
+ os.environ.setdefault('WANDB_MODE','disabled')
+ # An upstream hub import would otherwise require a first-run network fetch.
+ original=torch.hub.load
+ def local_hub(repo,model,*args,**kwargs):
+ if repo=='facebookresearch/dinov3':
+ repo=str(root/'third_party/dinov3');kwargs['source']='local'
+ return original(repo,model,*args,**kwargs)
+ if not getattr(original, '_rgb_flow', False):
+ local_hub._rgb_flow=True
+ torch.hub.load=local_hub
+ upstream_load=torch.load
+ allowed={str((root/name).resolve()) for name in ASSET_LINKS.values()}
+ def official_load(path,*args,**kwargs):
+ if isinstance(path,(str,Path)) and str(Path(path).resolve()) in allowed:
+ kwargs.setdefault('weights_only',False)
+ return upstream_load(path,*args,**kwargs)
+ if not getattr(upstream_load, '_rgb_flow', False):
+ official_load._rgb_flow=True
+ torch.load=official_load
+ return root
+
+
+def load_tensor(path):
+ import torch
+ return torch.load(path,map_location='cpu',weights_only=False,mmap=True)
+
+
+def save_tensor(path,value):
+ import torch
+ temporary=path.with_name(path.name+'.'+uuid.uuid4().hex+'.tmp')
+ try:torch.save(value,temporary);os.replace(temporary,path)
+ finally:temporary.unlink(missing_ok=True)
+
+
+def identity(project,stage):
+ from .models import BY_KEY,STAGE_REQUIREMENTS
+ state=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ names={'flow_camera':['input.mp4'], 'flow_features':['input.mp4','tracking.npz'],
+ 'flowhmr':['flow_tokens.pt','flow_camera.npz','flow_placement.json','tracking.npz'],
+ 'flow_export':['hmr4d_results.pt']}[stage]
+ root=scene_root(project)
+ root_state=json.loads((root/'project.json').read_text(encoding='utf-8'))
+ selected=root_state.get('flow_options',{}).get('camera_interval',0)
+ files={name:file_stat(project/name) for name in names if (project/name).exists()}
+ # Full-scene camera is shared even when each person has shorter visible takes.
+ if stage=='flow_camera':
+ files={'root_input':file_stat(root/'input.mp4')}
+ if root!=project and (root/'flow_camera.npz').exists():files['root_camera']=file_stat(root/'flow_camera.npz')
+ import inspect
+ # Export/rig improvements must not discard expensive camera/SAM/inference.
+ functions={'flow_camera':(camera,camera_interval), 'flow_features':(features,_features), 'flowhmr':(infer,validate_motion)}
+ if stage=='flow_export':
+ code={name:sha256(ROOT/'mocap'/name) for name in ('flow_export.py','source_pose_fit.py','mixamo_rig.py','bvh_bind.py','mixamo_data.py')}
+ else:
+ code={'adapter':hashlib.sha256(''.join(inspect.getsource(f) for f in (*functions[stage],activate,load_tensor,save_tensor)).encode()).hexdigest()}
+ upstream={'flow_camera':'flowhmr/utils/runtime_vggt_camera.py','flow_features':'flowhmr/utils/runtime_sam_features.py','flowhmr':'flowhmr/pipeline/pipeline_v2m.py'}.get(stage)
+ if upstream:code[upstream]=sha256(UPSTREAM/'FlowHMR'/upstream)
+ if stage in ('flow_camera','flow_features'):
+ for name in ('memory_mode.py','gpu_offload.py','model_session.py'):code[name]=sha256(ROOT/'mocap'/name)
+ if stage in ('flow_camera','flowhmr'):code['flow_camera.py']=sha256(ROOT/'mocap/flow_camera.py')
+ if stage=='flow_features':
+ for name in ('flow_sam.py','flow_fast_sam.py','batch_prefetch.py'):code[name]=sha256(ROOT/'mocap'/name)
+ if stage=='flow_features':
+ from .flow_sam import saved_fast_sam, source_identity, acceleration_options
+ code['sam_source']=source_identity(saved_fast_sam(project,state))
+ code['sam_acceleration']=acceleration_options(project,state)
+ import torch
+ return dict(version=VERSION,stage=stage,inputs=files,camera_interval=selected if stage=='flow_camera' else None,
+ models={key:file_stat(BY_KEY[key].path) for key in STAGE_REQUIREMENTS[stage] if not (stage=='flow_camera' and selected==-1)},
+ code=code,runtime=[str(torch.__version__),torch.version.cuda],frames=state['frames'],fps=state['fps'],take=state.get('person_frames'))
+
+
+def validate_motion(output,n):
+ import torch
+ for key,shape in [('rot6d',(1,n,52,6)),('trans',(1,n,3))]:
+ if key not in output or tuple(output[key].shape)!=shape or not torch.isfinite(output[key]).all():
+ raise ValueError('FlowHMR returned invalid '+key)
+ if tuple(output['shapes'].shape)!=(1,1,16) or not torch.isfinite(output['shapes']).all():
+ raise ValueError('FlowHMR requires 16 finite SMPL-H shape coefficients')
+
+
+def camera(project,emit,force=False):
+ import torch
+ root=scene_root(project)
+ state=json.loads((root/'project.json').read_text(encoding='utf-8'));n=state['frames']
+ interval=camera_interval(n,state.get('flow_options',{}).get('camera_interval',0))
+ if root!=project:
+ run_stage(root,'flow_camera','initial',emit,force=force)
+ begin,end=json.loads((project/'project.json').read_text(encoding='utf-8'))['person_frames']
+ with np.load(root/'flow_camera.npz',allow_pickle=False) as data:
+ values={key:data[key][begin:end] for key in ('camera_RT_yup','K')}
+ temporary=project/'flow_camera.partial.npz';np.savez(temporary,**values);os.replace(temporary,project/'flow_camera.npz')
+ atomic_json(project/'flow_camera_sources.json',{'root_camera':file_stat(root/'flow_camera.npz')})
+ return project/'flow_camera.npz'
+ if interval==-1:
+ from .flow_camera import static_camera
+ emit('progress',current=n,total=n,message='Use explicit locked static camera; VGGT skipped')
+ target=project/'flow_camera.partial.npz'
+ np.savez(target,**static_camera(n,state['width'],state['height']))
+ os.replace(target,project/'flow_camera.npz')
+ return project/'flow_camera.npz'
+ emit('progress',current=0,total=0,message=f'Estimate one scene camera ({interval}-frame sampling)')
+ from flowhmr.utils.runtime_vggt_camera import extract_vggt_camera
+ target=project/'flow_camera.partial.npz'
+ target.unlink(missing_ok=True) # upstream must not reuse a partial extraction
+ from .memory_mode import run as memory_run
+ from .gpu_offload import load_vggt,release
+ def estimate(low):
+ models=[]
+ def loader(path,device,camera_only=True):
+ model=load_vggt(path,device,camera_only,low_memory=low);models.append(model);return model
+ try:
+ target.unlink(missing_ok=True)
+ return extract_vggt_camera(str(project/'input.mp4'),output_npz=str(target),frame_range=(0,n-1),
+ expected_len=n,frame_interval=interval,keep_frames=False,camera_only=True,model_loader=loader)
+ finally:
+ for model in models:release(model)
+ models.clear()
+ samples=len(set(range(0,n,interval))|{n-1})
+ memory_run('FlowHMR VGGT camera',estimate,6.+.1*samples,emit)
+ with np.load(target,allow_pickle=False) as data:
+ if data['camera_RT_yup'].shape!=(n,4,4) or data['K'].shape!=(n,3,3) or not all(np.isfinite(data[k]).all() for k in ('camera_RT_yup','K')):
+ raise ValueError('VGGT-Omega returned incomplete camera data')
+ r=data['camera_RT_yup'][:,:3,:3]
+ if not np.allclose(r.swapaxes(-1,-2)@r,np.eye(3),atol=2e-4):raise ValueError('Invalid camera rotations')
+ os.replace(target,project/'flow_camera.npz')
+ return project/'flow_camera.npz'
+
+
+def features(project,emit):
+ from .memory_mode import run as memory_run
+ from .flow_sam import acceleration_options
+ state=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ estimate=5.5 if acceleration_options(project,state)['sam_batch4'] else 4.5
+ return memory_run('FlowHMR SAM features',lambda low:_features(project,emit,low),estimate,emit)
+
+
+def _features(project,emit,low_memory):
+ import cv2, torch
+ from .flow_sam import build_extractor, saved_fast_sam, acceleration_options
+ state=json.loads((project/'project.json').read_text(encoding='utf-8'));n=state['frames']
+ with np.load(project/'tracking.npz',allow_pickle=False) as data:boxes=data['boxes'].copy()
+ if boxes.shape!=(n,4):raise ValueError('Tracking and video frame counts differ')
+ k=np.array([[math.hypot(state['width'],state['height']),0,state['width']/2],
+ [0,math.hypot(state['width'],state['height']),state['height']/2],[0,0,1]],np.float32)
+ fast=saved_fast_sam(project,state)
+ options=acceleration_options(project,state)
+ from .model_session import acquire, model_key
+ from .models import BY_KEY
+ extractor=acquire(model_key('flow_sam',*[BY_KEY[k].path for k in ('flow_sam','flow_sam_config','flow_mhr')],fast=fast,low_memory=low_memory),
+ lambda:build_extractor(torch.device('cuda'),fast=fast,low_memory=low_memory))
+ cap=cv2.VideoCapture(str(project/'input.mp4'));cap.set(cv2.CAP_PROP_N_THREADS,2) if hasattr(cv2,'CAP_PROP_N_THREADS') else None
+ from .flow_sam import extract_tokens
+ tokens=torch.empty((n,3072),dtype=torch.float32);anchors=[]
+ try:
+ batch_size = 4 if options['sam_batch4'] and not low_memory else 1
+ if fast:
+ emit('info', message=f"Fast SAM acceleration: {batch_size} frame(s) per batch; GPU hand crops {'on' if options['sam_gpu_crop'] else 'off'}.")
+ if options['sam_batch4'] and low_memory:
+ emit('info', message='Low Memory: using one frame per SAM batch to reduce VRAM. GPU hand crop selection is retained.')
+ def cpu_batches():
+ for begin in range(0,n,batch_size):
+ count=min(batch_size,n-begin);images=[]
+ for index in range(begin,begin+count):
+ ok,frame=cap.read()
+ if not ok:raise ValueError(f'Cannot decode FlowHMR frame {index+1}')
+ images.append(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
+ yield begin,count,images
+ from .batch_prefetch import batch_source
+ with batch_source(cpu_batches(), batch_bytes=batch_size*state['width']*state['height']*3) as batches:
+ for begin,count,images in batches:
+ if any(options.values()):
+ from .flow_fast_sam import extract_batch
+ values, outputs = extract_batch(extractor, images, boxes[begin:begin+count],
+ torch.from_numpy(k[None]), gpu_crops=options['sam_gpu_crop'], placement=begin<30)
+ else:
+ token, outputs = extract_tokens(extractor, images[0], boxes[begin:begin+1],
+ torch.from_numpy(k[None]), placement=begin<30)
+ values = token[None]
+ if values.shape != (count,3072) or not torch.isfinite(values).all():
+ raise ValueError(f'Body/hand feature extraction failed at frame {begin+1}')
+ tokens[begin:begin+count] = values.float()
+ for offset, person in enumerate(outputs):
+ index = begin+offset
+ if index >= min(n,30):break
+ # MHR70 hips, metres in original OpenCV camera coordinates.
+ pelvis = person['pred_keypoints_3d'][[9,10]].mean(0)+person['pred_cam_t']
+ if np.isfinite(pelvis).all() and pelvis[2]>.05:anchors.append([index,*pelvis.tolist()])
+ if begin//10 != (begin+count)//10 or begin+count==n:
+ emit('progress',current=begin+count,total=n,message='Extract body and hand features (Fast SAM)' if fast else 'Extract body and hand features (Original SAM)')
+ if cap.read()[0]:raise ValueError('Video contains more frames than its project manifest')
+ finally:
+ cap.release()
+ from .model_session import release
+ release(extractor)
+ save_tensor(project/'flow_tokens.pt',tokens)
+ atomic_json(project/'flow_placement.json',dict(camera_pelvis=anchors,intrinsics=k.tolist(),method='Constant X/Z placement from SAM MHR70 pelvis; native FlowHMR height and motion retained'))
+ return project/'flow_tokens.pt'
+
+
+def infer(project,emit):
+ import torch
+ from flowhmr.pipeline.v2m_inference import build_pipeline,load_yaml,build_feature_dict
+ from flowhmr.core.bodymodels.smpl_skeleton import SMPLSkeleton
+ from .models import BY_KEY
+ checkpoint=BY_KEY['flowhmr'].path
+ tokens=load_tensor(project/'flow_tokens.pt');n=len(tokens)
+ if tokens.shape!=(n,3072) or not torch.isfinite(tokens).all():raise ValueError('Invalid cached SAM features; rerun feature extraction.')
+ with np.load(project/'flow_camera.npz',allow_pickle=False) as data:rt=torch.from_numpy(data['camera_RT_yup'].copy())
+ if tuple(rt.shape)!=(n,4,4):raise ValueError('Camera and body frame counts differ')
+ from .model_session import acquire,model_key
+ def build():
+ pipeline=build_pipeline(load_yaml(str(BY_KEY['flow_config'].path)),device='cuda',ckpt=str(checkpoint),validation_steps=20)
+ weights=load_tensor(checkpoint)
+ weights=weights.get('model_state_dict',weights.get('state_dict',weights))
+ if any(name not in weights or tuple(weights[name].shape)!=tuple(value.shape) for name,value in pipeline.named_parameters()):
+ raise ValueError('FlowHMR checkpoint is missing required learned parameters. Repair its checkpoint and configuration.')
+ return pipeline
+ pipeline=acquire(model_key('flowhmr',checkpoint,BY_KEY['flow_config'].path),build)
+ emit('progress',current=0,total=20,message='FlowHMR: integrate 20 ODE steps')
+ from .flow_camera import relative_camera
+ with torch.inference_mode():
+ output=pipeline.generate(feature=build_feature_dict(tokens,relative_camera(rt),torch.device('cuda')),seeds=[0],length=n,cfg_scale=1.0)
+ output={key:value.detach().cpu() if isinstance(value,torch.Tensor) else value for key,value in output.items()}
+ validate_motion(output,n)
+ save_tensor(project/'flow_prediction.pt',output) # untouched official prediction
+ del pipeline;gc.collect();torch.cuda.empty_cache()
+ placement=json.loads((project/'flow_placement.json').read_text(encoding='utf-8'))
+ anchors=np.asarray(placement['camera_pelvis'],float)
+ offset=np.zeros(3,np.float32)
+ if len(anchors):
+ skeleton=SMPLSkeleton(model_path=str(BY_KEY['smplh'].path))
+ count=min(n,30)
+ with torch.no_grad():
+ joints=skeleton(dict(rot6d=output['rot6d'][0,:count],shapes=output['shapes'].reshape(1,16),trans=output['trans'][0,:count]))['keypoints3d'].numpy()
+ differences=[]
+ for row in anchors:
+ index=int(row[0]);r=rt[index,:3,:3].numpy()
+ differences.append(r.T@row[1:]-joints[index,0])
+ offset[[0,2]]=np.median(differences,axis=0)[[0,2]]
+ placed={key:value.clone() if isinstance(value,torch.Tensor) else value for key,value in output.items()}
+ placed['trans']=placed['trans']+torch.from_numpy(offset)[None,None]
+ placed['scene_offset']=torch.from_numpy(offset)
+ placed['source_representation']='smplh';placed['flow_version']=VERSION
+ save_tensor(project/'hmr4d_results.pt',placed)
+ atomic_json(project/'initial_sources.json',{name:file_stat(project/name) for name in ('flow_prediction.pt','flow_tokens.pt','flow_camera.npz','flow_placement.json','tracking.npz')})
+ return project/'hmr4d_results.pt'
+
+
+def run_stage(project,stage,result,emit,force=False):
+ import time,torch,psutil
+ from .models import missing
+ project=Path(project);started=time.monotonic()
+ torch.set_num_threads(4)
+ if stage in ('correct','rig','mesh','export','flow_export'):
+ return run_post(project,stage,result,emit,force)
+ if stage in ('rig','mesh','export'):stage='flow_export'
+ if stage not in ('flow_camera','flow_features','flowhmr','flow_export'):
+ raise ValueError('This processing stage is not compatible with FlowHMR')
+ if result not in ('auto','initial','corrected_initial'):raise ValueError('FlowHMR supports original or corrected original motion only')
+ static=(stage=='flow_camera' and json.loads((scene_root(project)/'project.json').read_text(encoding='utf-8')).get('flow_options',{}).get('camera_interval',0)==-1)
+ absent=[] if static else missing(stage)
+ if absent:raise ValueError('Open FlowHMR Model Manager and prepare: '+', '.join(m.name for m in absent))
+ state=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ signature=identity(project,stage)
+ receipt_path=project/(stage+'_receipt.json');pending=project/(stage+'_pending.json')
+ cached=False
+ if not force and not pending.exists() and receipt_path.exists():
+ try:
+ receipt=json.loads(receipt_path.read_text(encoding='utf-8'))
+ cached=receipt['identity']==signature and all(Path(name).name==name and file_stat(project/name)==stamp for name,stamp in receipt['outputs'].items())
+ if cached and stage=='flow_export':
+ from .mixamo_data import current
+ from .result_artifacts import artifacts_current
+ cached=current(project,'initial') and artifacts_current(project,'initial')
+ if cached and stage=='flowhmr':validate_motion(load_tensor(project/'hmr4d_results.pt'),state['frames'])
+ except Exception:cached=False # A damaged cached tensor must recover without AI inference.
+ if stage=='flowhmr' and not force:
+ from .flow_placement import prediction_current,ensure
+ if prediction_current(project):
+ activate();ensure(project);cached=True
+ if cached:
+ emit('complete',stage=stage,output=str(project/next(iter(receipt['outputs']))),cached=True,elapsed=0);return
+ root=scene_root(project);root_state=json.loads((root/'project.json').read_text(encoding='utf-8'))
+ n=root_state['frames'] if stage=='flow_camera' else state['frames']
+ interval=camera_interval(n,root_state.get('flow_options',{}).get('camera_interval',0))
+ free=total=None
+ if stage!='flow_export' and not static:
+ if not torch.cuda.is_available():raise RuntimeError('FlowHMR requires a supported NVIDIA CUDA GPU.')
+ free,total=torch.cuda.mem_get_info()
+ validate_length(n)
+ if free is not None:set_memory_budget(free,total)
+ if not static:activate()
+ atomic_json(pending,dict(stage=stage,started=time.time()))
+ if stage=='flow_camera':output=camera(project,emit,force=force)
+ elif stage=='flow_features':output=features(project,emit)
+ elif stage=='flowhmr':
+ output=infer(project,emit)
+ from .flow_placement import ensure
+ ensure(project,generated=True)
+ else:
+ from .flow_export import prepare
+ output=prepare(project,emit)
+ outputs=[output.name]
+ if stage=='flow_camera' and root!=project:outputs.append('flow_camera_sources.json')
+ if stage=='flow_features':outputs.append('flow_placement.json')
+ if stage=='flowhmr':outputs+=['flow_prediction.pt','initial_sources.json','flow_world.json']
+ committed_identity=identity(project,stage)
+ if stage=='flow_features' and committed_identity!=signature:
+ raise RuntimeError('SAM inputs or settings changed during extraction. Reconstruct 3D again; this extraction was not committed.')
+ receipt=dict(identity=committed_identity,outputs={name:file_stat(project/name) for name in outputs})
+ atomic_json(receipt_path,receipt);pending.unlink(missing_ok=True)
+ latest=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ latest.setdefault('pipeline',{}).update(model='flowhmr',result='initial',htd_refine=False,footmr=False)
+ latest.setdefault('stages',{})[stage]=dict(status='complete',elapsed=time.monotonic()-started,output=str(output))
+ atomic_json(project/'project.json',latest)
+ emit('complete',stage=stage,output=str(output),cached=False,elapsed=time.monotonic()-started,
+ peak_ram_gib=psutil.Process().memory_info().peak_wset/1024**3,
+ peak_cuda_allocated_gib=torch.cuda.max_memory_allocated()/1024**3 if torch.cuda.is_initialized() else 0)
+
+
+def run_post(project,stage,result,emit,force=False):
+ """CPU-only contact/export stages, separately validated from AI caches."""
+ import time,torch,psutil
+ from .models import missing
+ from .motion_tools import result_is_current,selected_export
+ from .flow_export import prepare
+ from .flow_correction import run,code_identity
+ kind='initial' if result=='auto' else result
+ if kind not in ('initial','corrected_initial'):raise ValueError('FlowHMR supports original or corrected original motion only')
+ absent=missing('flow_export')
+ if absent:raise ValueError('Import the SMPL-H neutral body model in FlowHMR Model Manager.')
+ validate_length(json.loads((project/'project.json').read_text(encoding='utf-8'))['frames'])
+ activate()
+ from .flow_placement import ensure_group
+ ensure_group(project)
+ started=time.monotonic();cached=False
+ if stage=='correct':
+ if kind!='corrected_initial':raise ValueError('Select a corrected result')
+ try:
+ report=json.loads((project/(kind+'_correction.json')).read_text(encoding='utf-8'))
+ from .correction import backend
+ cached=(not force and result_is_current(project,kind) and report.get('code')==code_identity()
+ and report.get('backend_sha256')==sha256(Path(backend().__file__)))
+ if cached:validate_motion(load_tensor(project/(kind+'.pt')),report['frames'])
+ except Exception:cached=False # Cache decoding failure is recoverable, not an inference failure.
+ if not cached:
+ activate();output=run(project,emit,kind)
+ else:output=project/(kind+'.pt')
+ else:
+ if kind=='corrected_initial' and not result_is_current(project,kind):
+ run(project,emit,kind)
+ # Keep both selections available. Missing/corrupt payloads rebuild only
+ # this inexpensive derived preview; source inference is never rerun.
+ activate()
+ for selected in (('initial',kind) if kind!='initial' else ('initial',)):
+ current=selected_export(project,selected)
+ if force or current is None:output=prepare(project,emit,selected)
+ else:output=current
+ latest=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ latest.setdefault('pipeline',{}).update(model='flowhmr',result=kind,htd_refine=False,footmr=False)
+ latest.setdefault('stages',{})[stage]=dict(status='complete',elapsed=time.monotonic()-started,output=str(output))
+ atomic_json(project/'project.json',latest)
+ if stage in ('export','flow_export','rig','mesh'):(project/'flow_export_pending.json').unlink(missing_ok=True)
+ emit('complete',stage=stage,output=str(output),cached=cached,elapsed=time.monotonic()-started,
+ peak_ram_gib=psutil.Process().memory_info().peak_wset/1024**3)
diff --git a/mocap/flow_fast_sam.py b/mocap/flow_fast_sam.py
new file mode 100644
index 0000000..0068356
--- /dev/null
+++ b/mocap/flow_fast_sam.py
@@ -0,0 +1,81 @@
+"""Bounded frame batching and optional GPU crops for Fast SAM conditioning.
+
+Each frame keeps its own body-derived hand boxes. Precision, resolution and
+decoder layers are unchanged. GPU crops use upstream's bilinear sampler.
+"""
+import contextlib
+import os
+
+
+def merge_batches(batches):
+ import torch
+ person_keys = {'img', 'img_size', 'ori_img_size', 'bbox_center', 'bbox_scale',
+ 'bbox', 'affine_trans', 'mask', 'mask_score', 'person_valid'}
+ merged = {}
+ for key in batches[0]:
+ values = [batch[key] for batch in batches]
+ if key in ('cam_int', 'img_ori'):
+ merged[key] = values[0]
+ elif torch.is_tensor(values[0]):
+ merged[key] = torch.cat(values, dim=1 if key in person_keys else 0)
+ else:
+ merged[key] = values[0]
+ return merged
+
+
+def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placement=False):
+ import numpy as np
+ import torch
+ from sam_3d_body.sam_3d_body_estimator import prepare_batch, recursive_to
+ from sam_3d_body.models.meta_arch.sam3d_body import _prepare_hand_batches_gpu
+
+ count = len(images)
+ if not 1 <= count <= 4 or len(boxes) != count:
+ raise ValueError('Fast SAM requires one tracked body per frame, in batches of at most four')
+ if any(image.shape != images[0].shape for image in images):
+ raise ValueError('Fast SAM frame sizes must match')
+ estimator = extractor.estimator
+ model = estimator.model
+ body, hands = extractor._flow_fast_collectors
+ body.clear()
+ hands.clear()
+
+ def prepare_hands(image, left, right, camera):
+ if gpu_crops:
+ return _prepare_hand_batches_gpu(np.stack(images), left, right, camera,
+ output_size=(model.cfg.MODEL.IMAGE_SIZE[1], model.cfg.MODEL.IMAGE_SIZE[0]), padding=.9,
+ device=camera.device)
+ flipped = left.copy()
+ width = images[0].shape[1]
+ flipped[:, 0] = width - left[:, 2] - 1
+ flipped[:, 2] = width - left[:, 0] - 1
+ left_batch = merge_batches([prepare_batch(frame[:, ::-1], estimator.transform_hand,
+ flipped[i:i+1], cam_int=camera.clone()) for i, frame in enumerate(images)])
+ right_batch = merge_batches([prepare_batch(frame, estimator.transform_hand,
+ right[i:i+1], cam_int=camera.clone()) for i, frame in enumerate(images)])
+ return recursive_to(left_batch, camera.device), recursive_to(right_batch, camera.device), flipped
+
+ try:
+ with torch.no_grad(), open(os.devnull, 'w') as quiet, contextlib.redirect_stdout(quiet):
+ batch = merge_batches([prepare_batch(frame, estimator.transform, boxes[i:i+1],
+ cam_int=intrinsics) for i, frame in enumerate(images)])
+ batch = recursive_to(batch, 'cuda')
+ model._initialize_batch(batch)
+ batch['cam_int'] = intrinsics.to(batch['img']).clone()
+ output = model.run_inference(images[0], batch, inference_type='full',
+ transform_hand=estimator.transform_hand, thresh_wrist_angle=estimator.thresh_wrist_angle,
+ hand_batch_preparer=prepare_hands, features_only=not placement)
+ if len(body) != 1 or len(hands) != 1 or len(body[0]) != count or len(hands[0]) != count * 2:
+ raise ValueError('Fast SAM returned incomplete body/hand features')
+ tokens = torch.stack([torch.cat((body[0][i, 0], hands[0][i, 0], hands[0][count+i, 0]))
+ for i in range(count)]).float().cpu()
+ people = []
+ if placement:
+ pose = output[0]['mhr']
+ joints = pose['pred_keypoints_3d'].detach().cpu().numpy()
+ camera = pose['pred_cam_t'].detach().cpu().numpy()
+ people = [dict(pred_keypoints_3d=joints[i], pred_cam_t=camera[i]) for i in range(count)]
+ return tokens, people
+ finally:
+ body.clear()
+ hands.clear()
diff --git a/mocap/flow_sam.py b/mocap/flow_sam.py
index 98b9037..1a7121f 100644
--- a/mocap/flow_sam.py
+++ b/mocap/flow_sam.py
@@ -13,7 +13,7 @@ import sys
FAST_COMMIT = 'd72aa36913a1673ace029d345f437561a85ec9e2'
-def saved_fast_sam(project, state):
+def saved_options(project, state):
"""New processing defaults on; saved off is retained, including scene takes."""
import json
project = Path(project)
@@ -22,10 +22,22 @@ def saved_fast_sam(project, state):
root = (project / state['people_root']).resolve()
if project.resolve().is_relative_to(root) and (root / 'people.json').is_file():
options = json.loads((root / 'project.json').read_text(encoding='utf-8')).get('flow_options', options)
- value = options.get('fast_sam', True)
- if not isinstance(value, bool):
- raise ValueError('Invalid Fast SAM setting; expected on or off')
- return value
+ result = {}
+ for key in ('fast_sam', 'sam_batch4', 'sam_gpu_crop'):
+ value = options.get(key, True)
+ if not isinstance(value, bool):
+ raise ValueError('Invalid FlowHMR setting: '+key+'; expected on or off')
+ result[key] = value
+ return result
+
+
+def saved_fast_sam(project, state):
+ return saved_options(project, state)['fast_sam']
+
+
+def acceleration_options(project, state):
+ options = saved_options(project, state)
+ return {key: options['fast_sam'] and options[key] for key in ('sam_batch4', 'sam_gpu_crop')}
def source_root(fast):
@@ -58,7 +70,7 @@ def configure_fast_environment():
KEYPOINT_PROMPT_INTERM_INTERVAL='999')
-def build_extractor(device, fast=True):
+def build_extractor(device, fast=True, low_memory=False):
root = source_root(fast).resolve()
if not (root / 'sam_3d_body/__init__.py').is_file():
raise RuntimeError('The selected SAM runtime is missing. Repair or reinstall RGB MoCap.')
@@ -74,7 +86,21 @@ def build_extractor(device, fast=True):
# Preimport chooses the package before FlowHMR inserts its original path.
from flowhmr.utils.runtime_sam_features import build_sam3d_extractor
with open(os.devnull, 'w') as quiet, contextlib.redirect_stdout(quiet):
- extractor = build_sam3d_extractor(device)
+ if not low_memory:
+ extractor = build_sam3d_extractor(device)
+ else:
+ from flowhmr.utils import runtime_sam_features as runtime
+ from .gpu_offload import BlockOffload, release
+ model, config = package.load_sam_3d_body(checkpoint_path=runtime.SAM3D_CKPT_PATH,
+ mhr_path=runtime.SAM3D_MHR_PATH, device='cpu')
+ try:
+ runtime._maybe_convert_backbone_to_fp16(model, device)
+ model._mocap_offload = BlockOffload(model, device)
+ extractor = runtime.Sam3DTokenExtractor(package.SAM3DBodyEstimator(
+ sam_3d_body_model=model, model_cfg=config))
+ except BaseException:
+ release(model)
+ raise
if fast:
for hook in extractor._hooks:
hook.remove()
diff --git a/mocap/gpu_offload.py b/mocap/gpu_offload.py
new file mode 100644
index 0000000..a40a0e3
--- /dev/null
+++ b/mocap/gpu_offload.py
@@ -0,0 +1,85 @@
+"""Bounded synchronous transformer-block offload for inference-only workers.
+
+Weights keep their existing dtype. No pinned-memory pool or background copy
+threads are created. The owner closes hooks before discarding/replacing a model.
+"""
+
+
+def groups(model):
+ import torch
+ found = []
+ for name, module in model.named_modules():
+ if isinstance(module, torch.nn.ModuleList) and name.endswith(
+ ('blocks', 'frame_blocks', 'inter_frame_blocks')) and len(module):
+ if not any(name.startswith(parent + '.') for parent, _ in found):
+ found.append((name, module))
+ if not found:raise RuntimeError('This model does not support the validated Low Memory block layout.')
+ return found
+
+
+class BlockOffload:
+ def __init__(self, model, device):
+ self.handles = []
+ self.model = model
+ self.device = device
+ self.closed = False
+ selected = groups(model)
+ removed = []
+ try:
+ for name, group in selected:
+ parent_name, _, key = name.rpartition('.')
+ parent = model.get_submodule(parent_name) if parent_name else model
+ del parent._modules[key]
+ removed.append((parent, key, group))
+ # Offloaded blocks are never temporarily uploaded during loading.
+ model.to(device)
+ finally:
+ for parent, key, group in removed:parent._modules[key] = group
+ try:
+ for _, group in selected:
+ for block in group:
+ block.cpu()
+ self.handles.append(block.register_forward_pre_hook(self._before))
+ self.handles.append(block.register_forward_hook(self._after, always_call=True))
+ except BaseException:
+ self.close()
+ raise
+
+ def _before(self, module, args):
+ import torch
+ if module.training or torch.is_grad_enabled():
+ raise RuntimeError('Low Memory block offload requires evaluation without gradients.')
+ module.to(self.device)
+
+ def _after(self, module, args, output):
+ module.cpu()
+
+ def close(self):
+ if self.closed:return
+ self.closed = True
+ for handle in self.handles:handle.remove()
+ self.handles.clear()
+ if self.model is not None:self.model.cpu()
+ self.model = None
+
+
+def load_vggt(checkpoint, device, camera_only=True, low_memory=False):
+ import gc
+ import torch
+ from vggt_omega.models import VGGTOmega
+ model = VGGTOmega(enable_depth=not camera_only).eval()
+ state = torch.load(checkpoint, map_location='cpu', mmap=True, weights_only=False)
+ if camera_only:state = {k:v for k,v in state.items() if not k.startswith('dense_head.')}
+ model.load_state_dict(state)
+ del state
+ gc.collect()
+ if low_memory:model._mocap_offload = BlockOffload(model, device)
+ else:model.to(device)
+ return model
+
+
+def release(model):
+ manager = getattr(model, '_mocap_offload', None)
+ if manager is not None:
+ manager.close()
+ del model._mocap_offload
diff --git a/mocap/gui.py b/mocap/gui.py
index 2fd3e42..6f130d0 100644
--- a/mocap/gui.py
+++ b/mocap/gui.py
@@ -1,1696 +1,1740 @@
-from __future__ import annotations
-from .tooltips import tooltip_text
-from .ui_refresh import batch_readiness
-from .validation_snapshot import read_only_checks
-
-import json
-import math
-import os
-from collections import deque
-from pathlib import Path
-import time
-
-from PySide6.QtCore import QElapsedTimer, QEvent, QProcess, QProcessEnvironment, QTimer, Qt, QUrl
-from PySide6.QtGui import QColor, QDesktopServices, QKeySequence, QShortcut, QTextOption
-from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialog, QFileDialog,
- QFrame, QHBoxLayout, QLabel, QMainWindow, QMessageBox, QProgressBar, QPushButton,
- QSplitter, QTableWidget, QTableWidgetItem, QTextBrowser, QTextEdit, QVBoxLayout, QWidget)
-
-from .models import MODELS_LIST, import_body_model, missing, ready
-from .paths import ROOT, PROJECTS, worker_command
-from .video import select_preview
-from .viewer import VideoView, MotionView
-from .playback import playback_frame, PlaybackTimerResolution
-from .timeline import TimelineSlider
-from .preview_data import PreviewDataLoader, project_signature
-from .motion_tools import MOTION_TOOLS, selected_export, RESULTS, result_kind, result_options, result_is_current, base_result, body_result, has_handflow
-
-STAGES = {"prepare": "Prepare Video", "track": "Track Actor", "pva": "Analyze 2D", "gvhmr": "Initial 3D Reconstruction", "refine": "Refine Motion", "export": "Export", "download": "Model Manager", "diagnose": "Check System"}
-
-from .theme import STYLE
-STAGES["mesh"] = "Prepare SMPL-X Mesh"
-STAGES['rig']='Prepare Bone Preview'
-STAGES['save_fbx']='Save FBX'
-STAGES["footmr"] = "Refine Ankles / FootMR"
-STAGES["handflow"] = "Infer Fingers / HandFlow"
-STAGES['correct'] = 'Motion Correction'
-from .workspace_ui import build_workspace
-from .people_ui import PeopleWorkspace
-from .project_save_ui import ProjectSaving
-from .project_workspace_ui import ModelWorkspace
-STAGES.update(mamma_prepare='Prepare Multi-view Videos',mamma_masks='MAMMA Person Masks',mamma_landmarks='MAMMA Surface Landmarks',mamma_camera='MAMMA Cameras',mamma_fit='MAMMA 3D Fit',mamma_publish='MAMMA Motion Correction and Preview')
-STAGES['save_project']='Save Project As'
-STAGES.update(people='Find People',person='Prepare Person Motion')
-STAGES.update(flow_camera='Estimate Scene Camera / VGGT-Omega', flow_features='Extract Body and Hand Features / SAM', flowhmr='Reconstruct Motion / FlowHMR', flow_export='Prepare FlowHMR Preview and FBX', import_model='Import Model')
-STAGES.update(exmr_preprocess='ExMR Body, Hand and Foot Keypoints',exmr_features='ExMR Body and Hand Features',exmr='Reconstruct Motion / ExMR')
-
-class ModelDownloadDialog(QDialog):
- """Readable, selectable provider instructions with bounded scrolling."""
- def __init__(self, parent, key, manager=None):
- super().__init__(parent)
- self.manager = manager
- self.model_key = key
- from .models import BY_KEY, manual_download_page, manual_instructions_html
- self.setWindowTitle(BY_KEY[key].name + " - Manual Download")
- self.setMinimumSize(360, 260)
- area = self.screen().availableGeometry()
- self.resize(min(680, max(360, area.width() - 80)),
- min(560, max(260, area.height() - 100)))
- layout = QVBoxLayout(self)
- self.browser = QTextBrowser()
- self.browser.setStyleSheet(
- 'QTextBrowser { font-family:"' + QApplication.font().family() + '"; font-size:12px; padding:6px; }')
- self.browser.setOpenLinks(False)
- self.browser.setOpenExternalLinks(False)
- self.browser.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
- self.browser.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- self.browser.setTextInteractionFlags(Qt.TextBrowserInteraction)
- self.browser.setHtml(manual_instructions_html(key))
- self.browser.anchorClicked.connect(QDesktopServices.openUrl)
- layout.addWidget(self.browser)
- self.import_status = QLabel()
- self.import_status.setWordWrap(True)
- self.import_status.setMaximumHeight(64)
- self.import_status.hide()
- layout.addWidget(self.import_status)
- actions = QHBoxLayout(); actions.addStretch()
- self.website = QPushButton("Open Download Page")
- self.website.setToolTip('Open the model provider website in your browser.')
- self.website.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(manual_download_page(key))))
- actions.addWidget(self.website)
- self.import_file = QPushButton("Import...")
- self.import_file.setToolTip('Select the downloaded model file to check and import it. These instructions stay open.')
- self.import_file.clicked.connect(self.import_download)
- actions.addWidget(self.import_file)
- close = QPushButton("Close"); close.clicked.connect(self.accept)
- close.setToolTip('Close these download instructions.')
- actions.addWidget(close); layout.addLayout(actions)
- self.status_timer = QTimer(self)
- self.status_timer.setInterval(100)
- self.status_timer.timeout.connect(self.sync_import_status)
- self.sync_import_status()
-
- def showEvent(self, event):
- super().showEvent(event)
- self.sync_import_status()
- self.status_timer.start()
-
- def hideEvent(self, event):
- self.status_timer.stop()
- super().hideEvent(event)
-
- def import_download(self):
- if self.manager is not None:
- self.manager.import_local_model(self.model_key, picker_parent=self)
- self.sync_import_status()
-
- def sync_import_status(self):
- manager = self.manager
- self.import_file.setEnabled(manager is not None and not manager.window.busy)
- if manager is None:
- return
- manager.sync_task_status()
- message = manager.task_status.toPlainText() if manager._observing_setup or manager.window.busy else ''
- if self.import_status.toolTip() != message:
- self.import_status.setTextFormat(Qt.PlainText)
- self.import_status.setText(message[:500])
- self.import_status.setToolTip(message)
- self.import_status.setVisible(bool(message))
-
-
-class ModelsDialog(QDialog):
- def __init__(self, window, tool_key=None):
- super().__init__(window)
- self.window = window
- self.tool = MOTION_TOOLS[tool_key or window.model_choice.currentData()]
- from .models import STAGE_REQUIREMENTS
- keys = ({key for key in STAGE_REQUIREMENTS['mamma_assets']} if self.tool.key=='mamma' else
- {key for stage in (*self.tool.stages(refine=True, footmr=True, handflow=True),'people') for key in STAGE_REQUIREMENTS.get(stage, ())})
- # Keep public automatic downloads together, followed by manual-only files.
- # Stable sorting preserves the existing component order within each group.
- self.models = sorted((model for model in MODELS_LIST if model.key in keys),
- key=lambda model: not bool(model.drive_id or model.download_url))
- self.setWindowTitle(f"{self.tool.label} Model Manager")
- self.resize(850, min(540, max(360, self.screen().availableGeometry().height() - 80)))
- layout = QVBoxLayout(self)
- description = QLabel(f"Models for {self.tool.label} and compatible add-ons.\nUse Auto Download for public files, or Manual Download and Import for any model.\nRegistered body model files are not redistributed by this app.")
- description.setWordWrap(True)
- layout.addWidget(description)
- if self.tool.key=='mamma':
- from .mamma_manager import runtime_panel
- layout.addWidget(runtime_panel(self))
- self.table = QTableWidget(len(self.models), 3)
- self.table.setHorizontalHeaderLabels(["Model", "Status", "Action"])
- self.table.horizontalHeader().setStretchLastSection(True)
- self.table.setColumnWidth(0, 300)
- self.table.setColumnWidth(1, 130)
- layout.addWidget(self.table)
- self.task_status = QTextBrowser()
- self.task_status.setFixedHeight(64)
- self.task_status.setOpenLinks(False)
- self.task_status.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
- self.task_status.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- self.task_status.setStyleSheet(
- 'QTextBrowser { font-family:"' + QApplication.font().family() + '"; font-size:12px; padding:4px; }')
- self.task_status.setPlainText("Ready to download or import models.")
- layout.addWidget(self.task_status)
- self.task_progress = QProgressBar()
- self.task_progress.setTextVisible(False)
- self.task_progress.setRange(0, 100); self.task_progress.setValue(0)
- layout.addWidget(self.task_progress)
- actions = QHBoxLayout()
- self.cancel_task = QPushButton("Cancel")
- self.cancel_task.setToolTip('Stop the current download or import queue. Completed files are kept.')
- self.cancel_task.setEnabled(False)
- self.cancel_task.clicked.connect(self.cancel_model_job)
- actions.addWidget(self.cancel_task)
- actions.addStretch()
- self.download_all = QPushButton("Download All")
- self.download_all.setToolTip(tooltip_text(
- "Download missing public model files. Files requiring registration must be downloaded manually and imported. Completed downloads are kept if you cancel or retry."))
- self.download_all.clicked.connect(self.start_download_all)
- actions.addWidget(self.download_all)
- close = QPushButton("Close")
- close.setToolTip(tooltip_text("Close Model Manager. Any running download or import continues in the main workspace."))
- close.clicked.connect(self.accept); actions.addWidget(close)
- layout.addLayout(actions)
- self._batch_total = 0
- self._observing_setup = False
- self._row_state = None
- self._status_state = None
- self.status_timer = QTimer(self)
- self.status_timer.setInterval(100)
- self.status_timer.timeout.connect(self.sync_task_status)
- self.refresh()
-
- def refresh(self):
- for i, model in enumerate(self.models):
- name = model.name + (" (Optional: HTD / 2D)" if self.tool.key == "gvhmr" and model.key == "pva" else "")
- available = ready(model)
- for column, text in ((0, name), (1, "Ready" if available else "Missing")):
- item = self.table.item(i, column)
- if item is None:
- item = QTableWidgetItem(); self.table.setItem(i, column, item)
- item.setText(text)
- if column==0:item.setToolTip(str(model.path))
- item.setForeground(QColor("#d5d5d5" if available else "#ffb45c"))
- font = item.font(); font.setBold(not available); item.setFont(font)
- cell = self.table.cellWidget(i, 2)
- if cell is None or cell.property("model_key") != model.key:
- cell = QWidget(); cell.setProperty("model_key", model.key)
- row = QHBoxLayout(cell); row.setContentsMargins(0, 0, 0, 0)
- cell.automatic = None
- if model.drive_id or model.download_url:
- cell.automatic = QPushButton("Auto Download")
- cell.automatic.setToolTip(tooltip_text("Download this file automatically. If it fails, use Manual Download or Import an existing copy."))
- cell.automatic.clicked.connect(lambda checked=False, key=model.key: self.start_download(key))
- row.addWidget(cell.automatic)
- cell.manual = QPushButton("Manual Download...")
- cell.manual.setToolTip(tooltip_text("Show download links and instructions. Download in your browser, then use Import in the instructions or this row."))
- cell.manual.clicked.connect(lambda checked=False, key=model.key: self.manual_setup(key))
- row.addWidget(cell.manual)
- cell.local = QPushButton("Import...")
- cell.local.setToolTip(tooltip_text("Choose a model file you already downloaded. The app checks it before replacing any existing file."))
- cell.local.clicked.connect(lambda checked=False, key=model.key: self.import_local_model(key))
- row.addWidget(cell.local)
- self.table.setCellWidget(i, 2, cell)
- if cell.automatic is not None:
- cell.automatic.setEnabled(not self.window.busy and not available)
- cell.manual.setEnabled(True)
- cell.local.setEnabled(not self.window.busy)
- self.download_all.setEnabled(not self.window.busy and bool(self.pending_downloads()))
- self._row_state = (self.window.busy, id(self.window.process))
-
- def showEvent(self, event):
- super().showEvent(event)
- self.refresh(); self.sync_task_status()
- self.status_timer.start()
-
- def hideEvent(self, event):
- self.status_timer.stop()
- super().hideEvent(event)
-
- def sync_task_status(self):
- # Poll only cheap GUI state; filesystem readiness is refreshed once per
- # worker transition, never on each progress update or every timer tick.
- w = self.window
- row_state = (w.busy, id(w.process))
- if row_state != self._row_state:
- self.refresh()
- setup = w.current_stage in {"download", "import_model"}
- if w.busy and setup:
- self._observing_setup = True
- state = (w.busy, setup, w.cancelled, w.failed, w.status.text(),w.task_info.text(),
- w.progress.minimum(), w.progress.maximum(), w.progress.value(), len(w.jobs))
- if state == self._status_state:
- return
- self._status_state = state
- active = w.busy and setup
- self.cancel_task.setEnabled(active and not w.cancelled)
- if setup and self._observing_setup:
- message = w.status.text()
- if active:message+='\n'+w.task_info.text()
- if active and self._batch_total > 1 and not w.cancelled and not w.failed:
- index = min(self._batch_total, max(1, self._batch_total - len(w.jobs)))
- message = f"Model {index}/{self._batch_total}: " + message
- self.task_status.setPlainText(message if len(message) <= 4096 else message[:4096] + "\nSee Console for the complete message.")
- self.task_status.setStyleSheet(
- 'QTextBrowser { font-family:"' + QApplication.font().family() +
- '"; font-size:12px; padding:4px;' +
- ('color:#ffb45c;' if w.failed else '') + ' }')
- if active:
- self.task_progress.setRange(w.progress.minimum(), w.progress.maximum())
- self.task_progress.setValue(w.progress.value())
- else:
- self.task_progress.setRange(0, 100)
- self.task_progress.setValue(0 if w.failed or w.cancelled else 100)
- elif w.busy:
- self.task_status.setPlainText("Another task is running. You can still open manual download instructions.")
- self.task_progress.setRange(0, 0)
- else:
- self.task_status.setPlainText("Ready to download or import models.")
- self.task_progress.setRange(0, 100); self.task_progress.setValue(0)
-
- def start_model_jobs(self, jobs):
- if self.window.busy:
- return
- self._batch_total = len(jobs)
- self._observing_setup = True
- self._status_state = None
- self.window.start_jobs(jobs)
- self.sync_task_status()
-
- def cancel_model_job(self):
- if self.window.busy and self.window.current_stage in {"download", "import_model"}:
- self.window.cancel_job()
- self.sync_task_status()
-
- def pending_downloads(self):
- return [model for model in self.models
- if (model.drive_id or model.download_url) and not ready(model)]
-
- def start_download_all(self):
- if self.window.busy:
- return
- jobs = [("download", ["--model", model.key]) for model in self.pending_downloads()]
- if not jobs:
- self.refresh()
- return
- self.start_model_jobs(jobs)
-
- def start_download(self, key):
- if key not in {model.key for model in self.models}:
- raise ValueError("This model is not part of the selected motion tool.")
- self.start_model_jobs([("download", ["--model", key])])
-
- def manual_setup(self, key):
- if key not in {model.key for model in self.models}:
- raise ValueError("This model is not part of the selected motion tool.")
- dialog = ModelDownloadDialog(self, key, manager=self)
- try:
- dialog.exec()
- finally:
- dialog.deleteLater()
-
- def import_local_model(self, key, picker_parent=None):
- from .models import BY_KEY
- if self.window.busy:
- return
- if key not in {model.key for model in self.models}:
- raise ValueError("This model is not part of the selected motion tool.")
- model = BY_KEY[key]
- name, _ = QFileDialog.getOpenFileName(picker_parent or self, 'Import ' + model.name, '',
- f'Model file ({model.path.name});;All files (*)')
- if name:
- self.start_model_jobs([('import_model', ['--model', key, '--video', name])])
-
-
-
-from .character_ui import CharacterWorkspace
-from .mamma_ui import MammaWorkspace
-
-class MainWindow(MammaWorkspace,CharacterWorkspace,ModelWorkspace,ProjectSaving,PeopleWorkspace,QMainWindow):
- def __init__(self, video: Path | None = None):
- super().__init__()
- self.setWindowTitle("RGB MoCap | Motion Workspace")
- self.resize(1440, 880)
- self.setMinimumSize(1100, 700)
- self.video_path = None
- self.init_mamma()
- self.project = None
- self.workspace_root=None
- self._workspace_loading=False
- self._workspace_video_reference=False
- self._workspace_camera=None
- self.init_people()
- self.active_result = "corrected_footmr_refined"
- self.info = None
- self.source_offset = 0.0
- self.source_end = 0.0
- self.video_readable = False
- self.busy = False
- self.jobs = []
- self.process = None
- self.cancel_process = None
- self.buffer = ""
- self.failed = False
- self.cancelled = False
- self.hardware_summary = None
- self.current_stage = None
- self._batch_started_at = None
- self._batch_has_motion = False
- from .task_progress import TaskProgress
- self.task_state=TaskProgress()
- self._task_manifests={};self._queued_task_estimates=[]
- self.play_clock = QElapsedTimer()
- self.timer_resolution = PlaybackTimerResolution()
- self.play_anchor = 0
- self.playback_tick = False
- self.presented_times = deque()
- self.preview_data = None
- self.preview_signature = None
- from .contact_writer import ContactWriter
- self.contact_tracks={};self.contact_saving=False;self.contact_save_token=0
- self.contact_writer=ContactWriter(self)
- self.contact_writer.saved.connect(self.foot_contacts_saved)
- self.contact_writer.failed.connect(self.foot_contacts_failed)
- self.contact_writer.settled.connect(self.foot_contacts_settled)
- self.data_loader = PreviewDataLoader(self)
- self.data_loader.ready.connect(self.preview_ready)
- self.data_loader.failed.connect(self.preview_failed)
- self.data_loader.tracked_actor_ready.connect(self.tracked_actor_ready)
- build_workspace(self)
- self.init_characters()
- self.timer = QTimer(self)
- self.timer.setTimerType(Qt.PreciseTimer)
- self.timer.setInterval(33)
- self.timer.timeout.connect(self.next_frame)
- self.shortcuts = []
- for key, action in [("Space", self.toggle_play), ("Left", lambda: self.step_frames(-1)),
- ("Right", lambda: self.step_frames(1)),
- ("Shift+Left", lambda: self.step_frames(-round(self.info['fps']) if self.info else -30)),
- ("Shift+Right", lambda: self.step_frames(round(self.info['fps']) if self.info else 30)),
- ("Home", lambda: self.step_frames(-self.slider.maximum())),
- ("End", lambda: self.step_frames(self.slider.maximum()))]:
- shortcut = QShortcut(QKeySequence(key), self)
- shortcut.activated.connect(action)
- self.shortcuts.append(shortcut)
- self.setAcceptDrops(True)
- self.data_loader.start()
- self.contact_writer.start()
- self.processing_guard = None
- self.guard_timer = QTimer(self)
- self.guard_timer.setInterval(500)
- self.guard_timer.timeout.connect(self.check_processing_resources)
- self.task_timer=QTimer(self)
- self.task_timer.setInterval(500)
- self.task_timer.timeout.connect(self.update_task_progress)
- # Initialize the same model-specific visibility used on selector changes.
- # Otherwise the empty GVHMR stack reserves the FlowHMR page height.
- self.select_model()
- if video:
- self.load_video(video)
-
- @read_only_checks
- def update_readiness(self):
- if getattr(self,'_readiness_depth',0):
- self._readiness_pending=True
- return
- if hasattr(self,'character_loader'):self.sync_characters()
- self.update_people_readiness()
- tool = MOTION_TOOLS[self.model_choice.currentData()]
- self.compute_mode.setEnabled(not self.busy)
- stages = tool.stages(self.htd_refine.isChecked(), self.footmr_refine.isChecked(), handflow=self.handflow_refine.isChecked())
- from .models import STAGE_REQUIREMENTS, BY_KEY
- required = {key for stage in stages for key in STAGE_REQUIREMENTS.get(stage, ())}
- if tool.key=='flowhmr' and self.flow_sampling.currentData()==-1:required.discard('flow_vggt')
- if tool.key=='mamma' and self.mamma_camera_mode.currentData()=='manual':required.discard('flow_vggt')
- unavailable = [BY_KEY[key] for key in sorted(required) if not ready(BY_KEY[key])]
- count = len(required) - len(unavailable)
- text = f"{tool.label}: {count}/{len(required)} models ready"
- if unavailable:
- noun = "model" if len(unavailable) == 1 else "models"
- text += f"\nWarning: {len(unavailable)} required {noun} missing.\nOpen Model Manager to download or import."
- self.readiness.setStyleSheet("color:#ffb45c; font-weight:600;" if unavailable else "")
- self.readiness.setToolTip(tooltip_text("Missing required models:\n" + "\n".join(model.name for model in unavailable) if unavailable else ""))
- self.readiness.setText(text)
- for button in (self.models_button, self.analyze_button, self.run_button):
- button.setEnabled(not self.busy)
- self.cancel_button.setEnabled(self.busy)
- self.check_system_action.setEnabled(not self.busy)
- self.model_choice.setEnabled(not self.busy and not self.contact_saving)
- self.htd_refine.setEnabled(not self.busy)
- self.footmr_refine.setEnabled(not self.busy)
- self.handflow_refine.setEnabled(not self.busy)
- self.motion_correction.setEnabled(not self.busy)
- self.correction_controls.setEnabled(not self.busy and self.motion_correction.isChecked())
- flat=self.correction_mode.currentData()=='flat'
- self.auto_floor.setEnabled(not self.busy and flat)
- self.floor_height.setEnabled(not self.busy and flat and not self.auto_floor.isChecked())
- self.correction_button.setEnabled(not self.busy and not self.contact_saving and self.project is not None and
- (self.project/RESULTS[base_result(self.active_result)][0]).exists())
- self.slider.trim_enabled = not self.busy and self.info is not None
- self.slider.contact_edit_enabled=not self.busy and not self.contact_saving and self.motion_correction.isChecked() and self.slider.contacts_available
- self.slider.contact_track_enabled=(self.foot_lock.isChecked(),)*2+(self.hand_lock.isChecked(),)*2
- self.slider.update()
- self.reset_footlocks_button.setEnabled(self.slider.contact_edit_enabled)
- self.reset_trim_button.setEnabled(self.slider.trim_enabled)
- character=self.selected_character()
- self.export_action.setText('Export Character...' if character else 'Export FBX...')
- self.export_action.setEnabled(not self.busy and (bool(character.get('takes')) and not character.get('needs_retarget') if character else self.project is not None and self.current_export() is not None))
- self.export_action.setToolTip(tooltip_text("Choose a character export format and whether to include its mesh. PMX characters also support VMD motion." if character else "Save the displayed skeleton animation as FBX. For multiple people, each checked person gets a separate named file and rig."))
- self.play_button.setEnabled(self.info is not None and self.video_readable)
- for action in self.open_actions:
- action.setEnabled(not self.busy)
- self.save_project_action.setEnabled(not self.busy and not self.contact_saving and self.video_path is not None and self.info is not None)
- self.mesh_button.setEnabled(self.preview_preparation_available())
- self.import_character_action.setEnabled(not self.busy and not self.contact_saving)
- self.flow_sampling.setEnabled(not self.busy)
- self.fast_sam.setEnabled(not self.busy)
- self.exmr_camera.setEnabled(not self.busy)
- self.exmr_smoothing.setEnabled(not self.busy)
- self.analyze_button.setVisible(tool.key=='gvhmr')
- self.sync_correction_floor_preview()
- self.sync_mamma_controls()
-
- def sync_correction_floor_preview(self):
- self.motion_view.correction_floor_applicable=self.correction_mode.currentData()=='flat'
- enabled=self.motion_correction.isChecked() and self.correction_mode.currentData()=='flat'
- pending=bool(self.project is not None and enabled and
- not result_is_current(self.project,'corrected_'+base_result(self.active_result)))
- self.motion_view.set_correction_floor(self.floor_height.value() if self.project is not None else None,
- automatic=self.auto_floor.isChecked(),pending=pending,enabled=enabled)
-
- def show_model_guide(self):
- from .model_guide import ModelGuideDialog
- dialog = ModelGuideDialog(self, self.model_choice.currentData())
- try:
- dialog.exec()
- finally:
- dialog.deleteLater()
-
- def select_model(self, *_):
- tool = MOTION_TOOLS[self.model_choice.currentData()]
- if self.workspace_root is not None and not self._workspace_loading and tool.key!=getattr(self,'_selected_tool',None):
- if self.busy or self.contact_saving:
- self.model_choice.blockSignals(True)
- self.model_choice.setCurrentIndex(self.model_choice.findData(self._selected_tool))
- self.model_choice.blockSignals(False)
- return
- self.switch_workspace_model(tool.key)
- return
- previous=getattr(self,'_selected_tool','gvhmr')
- choices=getattr(self,'_tool_refinement',{'gvhmr':(True,True,True,True)})
- if previous!=tool.key:
- if previous=='gvhmr':choices['gvhmr']=(self.htd_refine.isChecked(),self.footmr_refine.isChecked(),self.motion_correction.isChecked(),self.handflow_refine.isChecked())
- else:choices[previous]=(False,False,self.motion_correction.isChecked(),False)
- values=choices.get(tool.key,(tool.key=='gvhmr',tool.key=='gvhmr',True,tool.key=='gvhmr'))
- for control,value in zip((self.htd_refine,self.footmr_refine,self.motion_correction,self.handflow_refine),values):
- control.blockSignals(True);control.setChecked(value);control.blockSignals(False)
- self._selected_tool=tool.key;self._tool_refinement=choices
- self.active_result=self.selected_result()
- if self.project is not None:
- state=json.loads((self.project/'project.json').read_text(encoding='utf-8'))
- if state.get('pipeline',{}).get('model','gvhmr')!=tool.key:
- # Keep source timing/camera but never show another engine's result.
- self.stop_playback();self.clear_preview();self.reset_people()
- self.project=None
- self.active_result=self.selected_result()
- self.status.setText(f'{tool.label} selected. Reconstruct this clip or open a {tool.label} project.')
- for index in range(self.model_pages.count()):
- if self.model_pages.widget(index).property("motion_tool") == tool.key:
- self.model_pages.setCurrentIndex(index)
- break
- self.model_pages.setVisible(tool.key!='gvhmr')
- self.htd_refine.setVisible(bool(tool.refinement))
- self.refine_description.setVisible(bool(tool.refinement))
- self.footmr_refine.setVisible(tool.key == "gvhmr")
- self.handflow_refine.setVisible(tool.key == "gvhmr")
- self.footmr_description.setVisible(tool.key == "gvhmr")
- if not tool.refinement:
- self.refine_preview_note.hide()
- self.models_group.setTitle(tool.label+' Models')
- self.correction_group.setVisible(True)
- self.slider.contacts_supported=True
- self.slider._cache_key=None
- self.slider.update()
- self.correction_description.setText('Only checked contact types are corrected. Uses the selected '+tool.label+' result.')
- self.analyze_button.setToolTip(tooltip_text('Find body points in the video for GVHMR refinement. Reconstruct 3D normally includes this step when needed.'))
- self.mamma_mode_changed(previous,tool.key)
- self.update_readiness()
-
- def selected_result(self, correction=None):
- gvhmr=self.model_choice.currentData()=='gvhmr'
- return result_kind(gvhmr and self.htd_refine.isChecked(),gvhmr and self.footmr_refine.isChecked(),
- self.motion_correction.isChecked() if correction is None else correction,
- handflow=gvhmr and self.handflow_refine.isChecked())
-
- def refinement_changed(self, enabled):
- self.set_active_result(self.selected_result())
-
- def current_export(self):
- info=self.contact_tracks.get(base_result(self.active_result))
- if self.active_result.startswith('corrected_') and (self.contact_saving or (info and info.get('unsaved'))):return None
- # selected_export checks source, correction and target receipts itself.
- if self.project is not None:
- return selected_export(self.project, self.active_result)
- return None
-
- def render_changed(self):
- self.motion_view.show_bones=self.bone_overlay.isChecked()
- self.motion_view.update()
-
- def preview_preparation_available(self):
- if self.project is None or self.busy or self.contact_saving:return False
- if not (self.project/RESULTS[base_result(self.active_result)][0]).is_file():return False
- info=self.contact_tracks.get(base_result(self.active_result),{})
- if self.active_result.startswith('corrected_') and info.get('unsaved'):return False
- if self.model_choice.currentData()=='flowhmr':
- from .flow_placement import needs_update
- if needs_update(self.project):return True
- return ((self.project/RESULTS[self.active_result][0]).is_file()
- and result_is_current(self.project,self.active_result))
-
- def prepare_target_preview(self):
- if self.project is None or self.busy or self.contact_saving:return
- from .mixamo_data import current
- projects=[self.project]
- if self.people_state:
- from .people_store import safe_child
- projects += [safe_child(self.people_root,take['project']) for person in self.people_state['people']
- if person.get('checked') for take in person.get('takes',[])]
- jobs=[]
- for project in dict.fromkeys(projects):
- from .flow_placement import needs_update
- placement_old=self.model_choice.currentData()=='flowhmr' and needs_update(project)
- if (project/RESULTS[base_result(self.active_result)][0]).is_file() and (placement_old or result_is_current(project,self.active_result) and not current(project,self.active_result)):
- jobs.append(('rig',['--project',str(project),'--result',self.active_result]))
- if jobs:self.start_jobs(jobs)
-
- def open_model_manager(self):
- dialog = ModelsDialog(self)
- try:
- dialog.exec()
- finally:
- dialog.deleteLater()
-
- def set_active_result(self, kind):
- """Select the cached preview and sync the HTD option without inference."""
- htd, foot = result_options(kind)
- self.active_result = kind
- self.handflow_refine.blockSignals(True)
- self.handflow_refine.setChecked(has_handflow(kind))
- self.handflow_refine.blockSignals(False)
- self.htd_refine.blockSignals(True)
- self.htd_refine.setChecked(htd)
- self.htd_refine.blockSignals(False)
- self.footmr_refine.blockSignals(True)
- self.footmr_refine.setChecked(foot)
- self.footmr_refine.blockSignals(False)
- self.motion_correction.blockSignals(True)
- self.motion_correction.setChecked(kind.startswith('corrected_'))
- self.motion_correction.blockSignals(False)
- self.refresh_results()
- self.request_people_scene()
- self.update_readiness()
-
- def choose_video(self):
- if self.model_choice.currentData()=='mamma':
- names,_=QFileDialog.getOpenFileNames(self,'Open MAMMA Camera Videos','', 'Videos (*.mp4 *.mov *.avi *.mkv *.webm)')
- if names:self.load_mamma_videos(names)
- return
- name, _ = QFileDialog.getOpenFileName(self, "Open Video", "", "Videos (*.mp4 *.mov *.avi *.mkv *.webm)")
- if name:
- self.load_video(Path(name))
-
- def load_video(self, path):
- if self.model_choice.currentData()=='mamma':
- return self.load_mamma_videos([path])
- try:
- if self.workspace_root is not None:self.remember_workspace_model()
- self.clear_mamma_inputs()
- self.workspace_root=None;self._workspace_video_reference=False;self._workspace_camera=None
- self.stop_playback()
- self.clear_preview()
- self.reset_people()
- self.motion_view.auto_fit = True
- self.video_path, self.project, self.info = path, None, None
- self.setWindowTitle('RGB MoCap | Motion Workspace')
- self.flow_sampling.setCurrentIndex(self.flow_sampling.findData(0))
- self.fast_sam.setChecked(True)
- self.exmr_camera.setCurrentIndex(0)
- self.exmr_smoothing.setChecked(True)
- self.handflow_refine.blockSignals(True)
- self.handflow_refine.setChecked(self.model_choice.currentData()=='gvhmr')
- self.handflow_refine.blockSignals(False)
- self._tool_refinement={'gvhmr':(True,True,True,True)}
- for option in (self.htd_refine, self.footmr_refine, self.motion_correction):
- option.blockSignals(True)
- option.setChecked(True)
- option.blockSignals(False)
- self.active_result = self.selected_result()
- self.restore_correction_options({})
- self.source_offset = self.source_end = 0.0
- self.video_readable = False
- self.slider.setRange(0, 0)
- self.filename.setText(f"{path.name} · Opening video...")
- self.video_view.open(path)
- self.update_readiness()
- except Exception as error:
- QMessageBox.warning(self, "Video Error", str(error))
-
- def video_ready(self, info):
- if self.mamma_video_ready(info):return
- self.video_readable = True
- self.slider.set_media(self.info["fps"] if self.info else info["fps"])
- if self.project is None and not self._workspace_video_reference:
- self.info = info
- self.slider.setRange(0, max(0, info["frames"] - 1))
- self.source_offset, self.source_end = 0.0, info["duration"]
- self.slider.reset_trim()
- self.clip_changed(self.slider.clip_in, self.slider.clip_out)
- self.filename.setText(f"{self.video_path.name} · {info['width']}×{info['height']} · {info['fps']:.2f}fps · {info['duration']:.2f} s")
- self.fps_label.setText(f"Source {info['fps']:.2f} fps")
- self.seek(0)
- if self.workspace_root is not None:
- from .project_workspace import read
- self.source_offset=float(read(self.workspace_root).get('time_offset',0.))
- self.source_end=self.source_offset+info['duration']
- self.restore_workspace_view(getattr(self,'_workspace_pending_view',{}))
- self.update_readiness()
-
- def video_failed(self, message):
- self.video_readable = False
- self.stop_playback()
- self.status.setText("Video preview: " + message)
- self.update_readiness()
-
- def choose_project(self):
- name, _ = QFileDialog.getOpenFileName(self, "Open Project", str(PROJECTS), "Project (project.json)")
- if name:
- from .project_workspace import root_for
- try:
- project=Path(name).parent
- if root_for(project) is None:
- raise ValueError('This project uses the previous folder format. Open its video to create a new model-folder project.')
- self.load_project(project)
- except (OSError,ValueError,KeyError) as error:self.status.setText('Cannot open project: '+str(error))
-
- @batch_readiness
- def load_project(self, project):
- from .project_workspace import is_workspace
- if is_workspace(project):return self.open_workspace(project)
- from .project_storage import project_to_open, source_video
- try:
- project, workspace = project_to_open(project)
- except (OSError, ValueError) as error:
- self.status.setText('Cannot open project: '+str(error));return False
- from .motion_tools import require_supported_project, UnsupportedMotionTool
- try:
- require_supported_project(project)
- except UnsupportedMotionTool as error:
- self.status.setText(str(error))
- return False
- manifest = json.loads((project / "project.json").read_text(encoding="utf-8"))
- if manifest.get('pipeline',{}).get('model')=='mamma':
- group=(project/manifest.get('people_root','.')).resolve()
- if (group/'mamma_pending.json').exists():
- self.status.setText('MAMMA publication is incomplete. Reconstruct again to finish; previous projects were preserved.')
- return False
- self.stop_playback()
- self.clear_preview()
- self.motion_view.auto_fit = True
- self.project = project
- self.workspace_project_loaded(project,manifest)
- from .project_storage import storage_root
- saved_root=storage_root(project,manifest)
- self.setWindowTitle('RGB MoCap | '+(saved_root.name if saved_root else 'Motion Workspace'))
- pipeline = manifest.get("pipeline", {})
- from .flow_camera import saved_interval
- from .flow_sam import saved_fast_sam
- self.fast_sam.setChecked(saved_fast_sam(project,manifest))
- from .exmr_options import saved as saved_exmr
- exmr=saved_exmr(project,manifest)
- self.exmr_camera.setCurrentIndex(self.exmr_camera.findData(exmr['static_camera']))
- self.exmr_smoothing.setChecked(exmr['smoothing']=='global')
- self.flow_sampling.setCurrentIndex(max(0,self.flow_sampling.findData(saved_interval(project,manifest))))
- self.model_choice.blockSignals(True)
- self.model_choice.setCurrentIndex(self.model_choice.findData(pipeline.get('model','gvhmr')))
- self.model_choice.blockSignals(False)
- opening=self._workspace_loading;self._workspace_loading=True
- try:self.select_model()
- finally:self._workspace_loading=opening
- has_refined = any((project / name).exists() for name in ("opt_results.pt", "refined_joints.npz", "refined_mesh.json"))
- has_motion = has_refined or any((project / name).exists() for name in ("hmr4d_results.pt", "initial_joints.npz"))
- result = pipeline.get("result", "refined" if has_refined else "initial")
- saved_selection=bool(pipeline.get('result'))
- self.handflow_refine.blockSignals(True)
- self.handflow_refine.setChecked(has_handflow(result) if has_motion or saved_selection else pipeline.get('model','gvhmr')=='gvhmr')
- self.handflow_refine.blockSignals(False)
- self.htd_refine.blockSignals(True)
- self.htd_refine.setChecked(result_options(result)[0] if has_motion or saved_selection else True)
- self.htd_refine.blockSignals(False)
- self.footmr_refine.blockSignals(True)
- # Existing projects keep their saved selection; new reconstructions default all on.
- self.footmr_refine.setChecked(result_options(result)[1] if has_motion or saved_selection else True)
- self.footmr_refine.blockSignals(False)
- self.motion_correction.blockSignals(True)
- self.motion_correction.setChecked(result.startswith('corrected_') if has_motion or saved_selection else True)
- self.motion_correction.blockSignals(False)
- self.restore_correction_options(manifest.get('correction',{}))
- self.active_result = self.selected_result()
- self.video_path = source_video(project, manifest)
- self.video_readable = False
- fps = manifest.get("fps", 30)
- self.info = {"fps": fps, "frames": manifest["frames"], "duration": manifest["frames"] / fps}
- self.source_offset, self.source_end = manifest["start"], manifest["end"]
- self.slider.set_media(fps)
- # MAMMA restores its selected camera below. Opening the actor's default
- # clip first discards that decoder and its cache on every row selection.
- if not (pipeline.get('model')=='mamma' and self.mamma_inputs and self.mamma_thumbnail_buttons):
- self.video_view.open(select_preview(project), (manifest["width"], manifest["height"]))
- self.slider.setRange(0, manifest["frames"] - 1)
- self.filename.setText(f"{self.video_path.name} · Project loaded · {manifest['frames']} frames")
- self.slider.reset_trim()
- self.clip_changed(self.slider.clip_in, self.slider.clip_out)
- self.refresh_results()
- self.seek(0)
- self.fps_label.setText(f"Source {fps:.2f} fps")
- if (project / "motion.bvh").exists():
- self.status.setText("Motion loaded. Play the animation or adjust the video clip range.")
- if (project / "keypoints.npz").exists() and not (project / "hmr4d_results.pt").exists():
- self.status.setText("2D observations loaded. Prepare the body model to reconstruct full-body motion.")
- self.sync_people(project,manifest)
- if workspace:
- trim=workspace.get('trim')
- if trim and 0<=trim[0]<trim[1]<=manifest['frames']:
- self.slider.clip_in,self.slider.clip_out=trim
- self.clip_changed(*trim)
- self.slider.setValue(max(0,min(int(workspace.get('frame',0)),manifest['frames']-1)))
- self.seek(self.slider.value())
- self.update_readiness()
- self.mamma_project_loaded(project,manifest)
- return True
-
- def seek(self, index):
- self.frame_number.blockSignals(True)
- self.frame_number.setValue(index + 1)
- self.frame_number.blockSignals(False)
- if self.timer.isActive() and not self.playback_tick:
- self.reset_play_clock()
- self.video_view.seek(index)
- fps = self.info["fps"] if self.info else 30
- total = self.info["duration"] if self.info else 0
- self.time_label.setText(f"{index/fps:05.2f} / {total:05.2f} s")
-
- def processing_range(self):
- """Map preview-local trim edges to the unchanged original source."""
- fps = self.info["fps"]
- first = self.source_offset + self.slider.clip_in / fps
- end = min(self.source_end, self.source_offset + self.slider.clip_out / fps)
- return first, end
-
- def clip_changed(self, first, end):
- if hasattr(self, "timer"):
- self.stop_playback()
- if self.info:
- start_seconds, end_seconds = self.processing_range()
- text = f"Clip: {first + 1}–{end} | {end_seconds-start_seconds:.2f} s"
- self.clip_label.setText(text)
- self.clip_label.setToolTip(tooltip_text(f"Video range: {start_seconds:.3f}–{end_seconds:.3f} s\nDrag the video track edges to trim playback and reconstruction. Existing motion files stay unchanged until you reconstruct again."))
- else:
- self.clip_label.setText("Clip: no video")
-
- def present_frame(self, index):
- # 3D and overlays advance only when the corresponding decoded image is ready.
- self.motion_view.index = index
- self.motion_view.scene_time=self.source_offset+index/(self.info['fps'] if self.info else 30)
- self.motion_view.update()
- if self.timer.isActive():
- now = time.perf_counter()
- self.presented_times.append(now)
- while self.presented_times and now - self.presented_times[0] > 2:
- self.presented_times.popleft()
- if len(self.presented_times) > 2 and now - self.presented_times[0] >= 0.5:
- actual = (len(self.presented_times) - 1) / (now - self.presented_times[0])
- self.fps_label.setText(f"Source {self.info['fps']:.2f} | Play {actual:.1f} fps")
-
- def reset_play_clock(self, *_):
- self.play_anchor = self.slider.value()
- self.play_clock.start()
- self.presented_times.clear()
- if self.timer.isActive() and self.info:
- self.timer.start(max(1, math.ceil(1000 / (self.info['fps'] * self.play_speed.currentData()))))
-
- def stop_playback(self):
- self.timer.stop()
- self.timer_resolution.release()
- self.set_playback_indicator(False)
-
- def set_playback_indicator(self, playing):
- label = "Pause" if playing else "Play"
- self.play_button.setIcon(self.pause_icon if playing else self.play_icon)
- self.play_button.setToolTip(tooltip_text(label + " (Space)"))
- self.play_button.setAccessibleName(label)
-
- def step_frames(self, amount):
- self.stop_playback()
- self.slider.setValue(max(0, min(self.slider.maximum(), self.slider.value() + amount)))
-
- def toggle_play(self):
- if self.timer.isActive():
- self.stop_playback()
- elif self.video_path and self.info and self.video_readable:
- if not self.slider.clip_in <= self.slider.value() < self.slider.clip_out:
- self.slider.setValue(self.slider.clip_in)
- self.timer_resolution.acquire()
- self.reset_play_clock()
- self.timer.start(max(1, math.ceil(1000 / (self.info['fps'] * self.play_speed.currentData()))))
- self.set_playback_indicator(True)
-
- def next_frame(self):
- if not self.timer.isActive() or self.info is None or not self.video_readable:
- return
- elapsed = self.play_clock.nsecsElapsed() / 1e9
- rate = self.info["fps"] * self.play_speed.currentData()
- target = self.slider.clip_in + playback_frame(self.play_anchor - self.slider.clip_in,
- elapsed, self.info["fps"], self.slider.clip_out - self.slider.clip_in,
- self.play_speed.currentData())
- self.playback_tick = True
- try:
- self.slider.setValue(target)
- finally:
- self.playback_tick = False
- next_deadline = (math.floor(elapsed * rate + 1e-8) + 1) / rate
- remaining = next_deadline - self.play_clock.nsecsElapsed() / 1e9
- self.timer.start(max(1, math.ceil(remaining * 1000)))
-
- def shutdown_preview(self):
- self.shutdown_mamma()
- self.stop_playback()
- if hasattr(self,'character_loader'):
- self.character_loader.close();self.character_assets.clear()
- self.scene_loader.stop()
- self.scene_loader.wait()
- self.clear_people_scene()
- self.clear_preview()
- self.data_loader.stop()
- self.data_loader.wait()
- self.contact_writer.stop()
- self.contact_writer.wait()
- self.video_view.shutdown()
- self.motion_view.cleanup_gl()
-
- def changeEvent(self, event):
- if event.type() == QEvent.WindowStateChange and self.isMinimized() and hasattr(self, "timer"):
- self.stop_playback()
- super().changeEvent(event)
-
- def hideEvent(self, event):
- if hasattr(self, "timer"):
- self.stop_playback()
- super().hideEvent(event)
-
- def input_jobs(self, stages, result=None):
- if MOTION_TOOLS[self.model_choice.currentData()].input_setup_only:
- self.status.setText('MAMMA camera input setup is available; reconstruction is not integrated yet.')
- return
- if self.video_path is None:
- self.choose_video()
- return
- if self.info is None or not self.video_readable:
- self.status.setText("Wait for the video preview to finish opening.")
- return
- if 'people' not in stages and self._single_actor and not self._single_actor['checked']:
- self.status.setText('Check Person 1 in the People list to reconstruct it.')
- return
- if 'people' not in stages and self.input_person_jobs(stages,result):
- return
- unavailable = [model for stage in stages for model in ([] if self.model_choice.currentData()=='flowhmr' and stage=='flow_camera' and self.flow_sampling.currentData()==-1 else missing('flow_export' if self.model_choice.currentData()=='flowhmr' and stage in ('correct','export') else stage))]
- if unavailable:
- names = ", ".join(dict.fromkeys(model.name for model in unavailable))
- self.status.setText(f"Prepare these models first: {names}")
- self.open_model_manager()
- return
- first, end = self.processing_range()
- prepare_args = ["--video", str(self.video_path), "--start", str(first), "--end", str(end)]
- if self.workspace_root is not None:
- prepare_args += ['--project',str(self.workspace_root)]
- elif self.project is not None:
- from .project_storage import storage_root
- if storage_root(self.project) is not None:
- prepare_args += ['--project', str(self.project)]
- if result or self.model_choice.currentData()!='gvhmr':
- prepare_args+=['--motion-tool',self.model_choice.currentData()]
- if result:
- prepare_args += ["--result", result]
- if result.startswith('corrected_') and not self.auto_floor.isChecked():
- prepare_args += ['--floor',str(self.floor_height.value())]
- if result.startswith('corrected_'):
- prepare_args += ['--correction-preset',self.correction_preset.currentData(),
- '--correction-mode',self.correction_mode.currentData(),
- '--foot-lock',str(int(self.foot_lock.isChecked())),'--hand-lock',str(int(self.hand_lock.isChecked())),
- '--pelvis-offset',str(self.pelvis_offset.value())]
- self.start_jobs([("prepare", prepare_args)]
- + [(stage, ["--result", result] if stage in {"export", "flow_export", "footmr", "handflow", "correct"} and result else None) for stage in stages])
-
- def run_analysis(self):
- self.input_jobs(["track", "pva"])
-
- def run_full(self):
- tool = MOTION_TOOLS[self.model_choice.currentData()]
- if tool.key=='mamma':return self.run_mamma()
- if tool.key=='exmr' and self.people_root is not None:
- from .storage import atomic_json
- path=self.people_root/'project.json';state=json.loads(path.read_text(encoding='utf-8'))
- state['exmr_options']={'static_camera':self.exmr_camera.currentData(),'smoothing':'global' if self.exmr_smoothing.isChecked() else 'none'}
- atomic_json(path,state)
- if tool.key=='flowhmr' and self.people_root is not None:
- from .storage import atomic_json
- path=self.people_root/'project.json';state=json.loads(path.read_text(encoding='utf-8'))
- state['flow_options']={**state.get('flow_options',{}),'camera_interval':self.flow_sampling.currentData(),'fast_sam':self.fast_sam.isChecked()}
- atomic_json(path,state)
- refine = bool(tool.refinement) and self.htd_refine.isChecked()
- foot = tool.key=='gvhmr' and self.footmr_refine.isChecked()
- correction=self.motion_correction.isChecked()
- if correction:self.save_correction_options()
- hand=tool.key=='gvhmr' and self.handflow_refine.isChecked()
- self.input_jobs(tool.stages(refine, foot,correction,handflow=hand), result=result_kind(refine, foot,correction,handflow=hand))
-
- def save_correction_options(self):
- if self.project is not None:
- if self.people_root is not None:
- from .scene_floor import save_config
- save_config(self.people_root,self.selected_correction_options())
- from .storage import atomic_json
- path=self.project/'project.json';state=json.loads(path.read_text(encoding='utf-8'))
- state['correction']=self.selected_correction_options()
- atomic_json(path,state)
-
- def selected_correction_options(self):
- from .correction_settings import correction_options
- return correction_options({'auto_floor':self.auto_floor.isChecked(),'floor':self.floor_height.value(),
- 'mode':self.correction_mode.currentData(),'foot_lock':self.foot_lock.isChecked(),'hand_lock':self.hand_lock.isChecked(),
- 'preset':self.correction_preset.currentData(),'pelvis_offset':self.pelvis_offset.value()})
-
- def update_correction_description(self):
- descriptions = {
- 'weak': 'Gentler correction, with some sliding allowed to preserve more of the original movement.',
- 'normal': 'Balanced contact correction. Holds stable contacts while keeping transitions smooth.',
- 'strong': 'Firmer holds, including less certain contacts. May resist intentional slides; review the result.',
- }
- self.preset_description.setText(descriptions[self.correction_preset.currentData()])
- if self.correction_mode.currentData()=='multi_level':
- self.floor_description.setText('Multi Level uses the inferred height of each foot contact. This floor value is unused; switch to Flat Ground to edit it.')
- else:
- self.floor_description.setText('Higher values raise the correction floor. Use the Correction Floor checkbox to preview it; Apply Correction updates the motion.')
-
- def restore_correction_options(self, options):
- from .correction_settings import correction_options
- options=correction_options(options)
- controls=(self.correction_mode,self.correction_preset,self.auto_floor,self.floor_height,self.pelvis_offset,self.foot_lock,self.hand_lock)
- for control in controls:control.blockSignals(True)
- try:
- self.correction_preset.setCurrentIndex(self.correction_preset.findData(options['preset']))
- self.correction_mode.setCurrentIndex(self.correction_mode.findData(options['mode']))
- self.foot_lock.setChecked(options['foot_lock']);self.hand_lock.setChecked(options['hand_lock'])
- self.auto_floor.setChecked(options['auto_floor']);self.floor_height.setValue(options['floor'])
- self.pelvis_offset.setValue(options['pelvis_offset'])
- finally:
- for control in controls:control.blockSignals(False)
- self.update_correction_description()
-
- def correction_settings_changed(self, *_):
- if self.sender() is self.floor_height and self.auto_floor.isChecked():return
- self.update_correction_description()
- self.save_correction_options()
- if self.sender() is self.correction_preset:
- self.request_people_scene(force=True)
- if self.preview_data is not None:self.apply_preview()
- self.update_readiness()
- return
- # Keep the last committed pose visible while editing the reference
- # plane. Only Apply Correction changes motion; stale export stays blocked.
- if self.preview_data is not None:
- self.correction_note.setText('Correction settings changed. Preview shows the last applied motion.\nApply Correction to update the pelvis, contacts and FBX.')
- self.correction_note.show()
- self.update_readiness()
-
- def apply_correction(self):
- if self.project is None or self.busy or self.contact_saving:return
- info=self.contact_tracks.get(base_result(self.active_result))
- if info and info.get('unsaved'):
- self.status.setText('Contact-lock timing was not saved. Edit or reset the tracks to retry saving.');return
- self.save_correction_options()
- kind=self.selected_result(True)
- self.set_active_result(kind)
- if self.people_root is not None:
- self.apply_scene_correction(kind);return
- self.start_jobs([('correct',['--result',kind]),('export',['--result',kind])], refresh_characters=True)
-
- def update_foot_contacts(self):
- base=base_result(self.active_result)
- info=self.contact_tracks.get(base)
- if info and self.info and (info['context']['frames']!=self.info['frames'] or info['context']['fps']!=self.info['fps']):info=None
- self.slider.set_contacts(info['ranges'] if info else None,info['automatic'] if info else None,
- editable=not self.busy and not self.contact_saving and self.motion_correction.isChecked(),
- identity=(str(self.project),base),token=id(info))
- from .foot_contacts import contact_levels
- self.motion_view.foot_lock_levels=lambda frame:contact_levels(info,frame)
-
- def foot_contacts_changed(self,ranges):
- self.save_foot_contacts(ranges)
-
- def reset_foot_contacts(self):
- self.save_foot_contacts(None)
-
- def save_foot_contacts(self,ranges):
- if self.project is None or self.busy or self.contact_saving:return
- base=base_result(self.active_result);info=self.contact_tracks.get(base)
- if info is None:return
- self.stop_playback();self.contact_saving=True
- try:self.contact_save_token=self.contact_writer.request(self.project,base,ranges,info['context'])
- except Exception as error:
- self.contact_saving=False;self.status.setText('Cannot save contact-lock timing: '+str(error));return
- # Keep immutable metadata while the writer commits off the GUI thread.
- self.contact_tracks[base]={**info,'ranges':ranges if ranges is not None else info['automatic'],'manual':ranges is not None,'unsaved':True}
- self.status.setText('Saving contact-lock timing...')
- self.update_readiness()
-
- def foot_contacts_saved(self,sequence,record):
- if self.project is None or str(self.project.resolve())!=record['project']:return
- info=self.contact_tracks.get(record['base'])
- if info is None:return
- self.contact_tracks[record['base']]={**info,'revision':record['state']['revision'],'unsaved':False}
- for key,scene in self.scene_cache.items():
- if base_result(key[1])==record['base']:
- take=scene.by_project.get(self.project)
- if take:
- take.set_contacts(info['ranges'])
- take.contact_revision=record['state']['revision']
- if sequence==self.contact_save_token:
- if self.preview_data is not None:self.apply_preview()
- self.status.setText('Contact-lock timing saved. Apply Correction to update the motion and FBX.')
-
- def foot_contacts_failed(self,sequence,message):
- if sequence==self.contact_save_token:self.status.setText('Cannot save contact-lock timing: '+message)
-
- def foot_contacts_settled(self,sequence):
- if sequence==self.contact_save_token:
- self.contact_saving=False;self.update_readiness()
-
- def prepare_mesh(self):
- if self.project is not None and not self.busy:
- self.prepare_target_preview()
-
- def start_jobs(self, jobs, refresh_characters=False):
- if self.busy:
- return
- jobs=list(jobs)
- self.character_refresh_queue=[]
- if refresh_characters:
- try:
- self.prepare_character_refresh(jobs)
- except (OSError, ValueError, KeyError) as exc:
- self.character_refresh_queue=[]
- self.status.setText(f'Cannot update linked characters: {exc}')
- self.update_readiness()
- return
- self._batch_started_at = time.monotonic()
- self._batch_has_motion = False
- self.task_state.reset(self._batch_started_at)
- self._task_manifests={}
- self.jobs, self.busy, self.cancelled, self.failed = list(jobs), True, False, False
- self._task_preparing=any(stage=='prepare' for stage,_ in self.jobs)
- self.update_readiness()
- self.next_job()
-
- def task_descriptor(self,stage,arguments):
- """Small metadata once per transition; no filesystem access on ticks."""
- arguments=arguments or []
- project=(Path(arguments[arguments.index('--project')+1]) if '--project' in arguments else
- None if getattr(self,'_task_preparing',False) else self.project)
- tool=self.model_choice.currentData();state={};estimate=None
- if project is not None:
- project=Path(project)
- if project not in self._task_manifests:
- try:
- file=project/'project.json'
- state=json.loads(file.read_text(encoding='utf-8')) if file.stat().st_size<=1024**2 else {}
- except (OSError,ValueError):state={}
- if len(self._task_manifests)>=32:self._task_manifests.pop(next(iter(self._task_manifests)))
- self._task_manifests[project]=state
- state=self._task_manifests[project];tool=state.get('pipeline',{}).get('model',tool)
- estimate=state.get('stages',{}).get(stage,{}).get('elapsed')
- if stage.startswith('exmr'):
- try:
- file=project/(stage+'_receipt.json')
- if file.stat().st_size<=65536:estimate=json.loads(file.read_text(encoding='utf-8')).get('elapsed')
- except (OSError,ValueError):pass
- frames=state.get('frames',self.info.get('frames',0) if self.info else 0)
- if '--first-frame' in arguments and '--end-frame' in arguments:
- frames=int(arguments[arguments.index('--end-frame')+1])-int(arguments[arguments.index('--first-frame')+1])
- model=arguments[arguments.index('--model')+1] if '--model' in arguments else ''
- result=arguments[arguments.index('--result')+1] if '--result' in arguments else self.active_result
- key=(stage,tool,frames,model,result,self.compute_mode.currentData(),self.fast_sam.isChecked(),self.flow_sampling.currentData(),self.exmr_camera.currentData())
- if not isinstance(estimate,(int,float)) or not math.isfinite(estimate) or not 1<=estimate<=7*86400:estimate=None
- estimate=self.task_state.history.get(key,estimate)
- return key,estimate
-
- def update_task_progress(self):
- if not self.busy or self.failed or self.cancelled or not self.task_state.active:return
- text,percent=self.task_state.status(time.monotonic(),self._queued_task_estimates)
- self.task_info.setText(text)
- # A real 0/N observation is loading, not a stationary empty bar.
- if percent is None:self.progress.setRange(0,0)
- else:
- total=self.task_state.total;current=self.task_state.current
- if total<=2147483647 and total.is_integer():
- self.progress.setRange(0,int(total));self.progress.setValue(int(current))
- else:
- self.progress.setRange(0,1000);self.progress.setValue(round(1000*current/total))
-
- def next_job(self):
- self.guard_timer.stop()
- self.processing_guard = None
- if not self.jobs or self.failed or self.cancelled:
- self.task_timer.stop()
- elapsed = (max(0., time.monotonic() - self._batch_started_at)
- if self._batch_started_at is not None else None)
- self._batch_started_at = None
- self.busy = False
- self.finish_single_tracking()
- self.task_state.active=False
- from .task_progress import duration
- self.task_info.setText(('Stopped' if self.failed or self.cancelled else 'Done')+
- (f' · Elapsed {duration(elapsed)}' if elapsed is not None else ''))
- self.progress.setRange(0, 100)
- self.progress.setValue(0 if self.failed or self.cancelled else 100)
- if self.current_stage=='save_fbx':
- # Saving a derived file does not replace scene/preview data.
- # Reloading the people scene here moves a following camera.
- if not self.failed and not self.cancelled:self.status.setText('FBX export complete.')
- self.update_readiness()
- return
- if self.current_stage=='save_project':
- self.finish_project_save()
- return
- person_batch=self._people_batch
- completion_message=self.status.text()
- self.finish_people_jobs()
- if self.failed or self.cancelled:self.status.setText(completion_message)
- if not self.failed and not self.cancelled:
- if self.current_stage in ("export",'flow_export') and self.project is not None and not person_batch:
- metadata = json.loads((self.project / "export.json").read_text(encoding="utf-8"))
- self.set_active_result(metadata.get("result_kind", "refined"))
- if self.current_stage == "diagnose" and self.hardware_summary:
- self.status.setText(self.hardware_summary)
- elif self.current_stage == "pva":
- self.status.setText("2D analysis complete. View the estimated joints over the video.")
- elif self.current_stage == "download":
- self.status.setText("Downloads complete. Check Model Manager for any required imports.")
- elif self.current_stage == "import_model":
- self.status.setText("Model setup complete.")
- elif self.current_stage not in ('people','person'):
- self.status.setText("Complete. Play the result or open the project folder.")
- if self._batch_has_motion and elapsed is not None:
- seconds = round(elapsed)
- minutes, seconds = divmod(seconds, 60)
- hours, minutes = divmod(minutes, 60)
- duration = (f'{hours}h {minutes:02d}m {seconds:02d}s' if hours else
- f'{minutes}m {seconds:02d}s' if minutes else f'{elapsed:.1f} s')
- self.status.setText(f'Complete. Total time: {duration}. Play the result or open the project folder.')
- self.log.append(f'Total motion processing time: {elapsed:.2f} s')
- self.refresh_results()
- self.update_readiness()
- if self.failed or self.cancelled:
- self.character_refresh_queue=[]
- else:
- self.next_character_refresh()
- return
- stage, arguments = self.jobs.pop(0)
- if stage in {'gvhmr', 'refine', 'footmr', 'handflow', 'correct',
- 'flow_camera', 'flow_features', 'flowhmr',
- 'exmr_preprocess', 'exmr_features', 'exmr'}:
- self._batch_has_motion = True
- if stage.startswith('mamma_'):self._batch_has_motion=True
- self.current_stage = stage
- if arguments is None:
- arguments = ["--project", str(self.project)]
- elif stage in {"export", "footmr", "handflow", "correct", 'flow_export'} and "--project" not in arguments:
- arguments = ["--project", str(self.project), *arguments]
- self.job_project = Path(arguments[arguments.index('--project')+1]) if '--project' in arguments else None
- if stage=='track':self.begin_single_tracking(self.job_project)
- if stage in {"download", "import_model"} and "--model" in arguments:
- from .models import BY_KEY
- model_key = arguments[arguments.index("--model") + 1]
- self.status.setText(("Downloading " if stage == "download" else "Importing ") + BY_KEY[model_key].name + "...")
- else:
- self.status.setText(STAGES[stage] + "...")
- key,estimate=self.task_descriptor(stage,arguments)
- self.task_state.begin(time.monotonic(),key,self.status.text(),estimate)
- actor=next((part for part in self.job_project.parts if part.startswith('person_')),'') if self.job_project else ''
- self._task_actor=actor.replace('_',' ').title().replace('000','')
- self._queued_task_estimates=[self.task_descriptor(s,a) for s,a in self.jobs]
- self.task_timer.start();self.update_task_progress()
- self.progress.setRange(0, 0)
- self.buffer = ""
- command = worker_command(stage, *arguments)
- self.process = QProcess(self)
- self.process.setWorkingDirectory(str(ROOT))
- environment = QProcessEnvironment.systemEnvironment()
- environment.insert("PYTHONIOENCODING", "utf-8")
- environment.insert("PYTHONUNBUFFERED", "1")
- environment.insert("RGB_MOCAP_COMPUTE_MODE", self.compute_mode.currentData())
- environment.insert('RGB_MOCAP_FLOW_INTERVAL',str(self.flow_sampling.currentData()))
- environment.insert('RGB_MOCAP_FLOW_FAST_SAM','1' if self.fast_sam.isChecked() else '0')
- environment.insert('RGB_MOCAP_EXMR_OPTIONS',json.dumps({'static_camera':self.exmr_camera.currentData(),'smoothing':'global' if self.exmr_smoothing.isChecked() else 'none'}))
- self.process.setProcessEnvironment(environment)
- self.process.readyReadStandardOutput.connect(self.read_stdout)
- self.process.readyReadStandardError.connect(self.read_stderr)
- self.process.finished.connect(self.process_finished)
- self.process.errorOccurred.connect(self.process_error)
- self.process.started.connect(self.start_processing_guard)
- self.process.start(command[0], command[1:])
-
- def start_processing_guard(self):
- from .processing_guard import ProcessingGuard
- try:
- self.processing_guard = ProcessingGuard(self.process.processId())
- self.guard_timer.start()
- except Exception as error:
- self.log.append('Resource monitor unavailable: ' + str(error))
-
- def check_processing_resources(self):
- if not self.processing_guard or not self.process:return
- message = self.processing_guard.check()
- if message:
- self.failed = True
- self.cancel_job()
- self.status.setText(message)
- self.log.append(message)
- self.guard_timer.stop()
- if getattr(self,'job_project',None) is not None:
- from .storage import atomic_json
- path=self.job_project/'project.json'
- try:
- state=json.loads(path.read_text(encoding='utf-8'))
- state.setdefault('stages',{})[self.current_stage]={'status':'failed','error':message}
- atomic_json(path,state)
- except (OSError,ValueError) as error:self.log.append('Could not save stopped stage: '+str(error))
-
- def read_stdout(self):
- if self.processing_guard:self.processing_guard.output()
- self.buffer += bytes(self.process.readAllStandardOutput()).decode("utf-8", errors="replace")
- if len(self.buffer) > 65536 and "\n" not in self.buffer:
- self.buffer = self.buffer[-65536:]
- while "\n" in self.buffer:
- line, self.buffer = self.buffer.split("\n", 1)
- if line.startswith("@@MOCAP@@"):
- try:
- self.handle_event(json.loads(line[len("@@MOCAP@@"):]))
- except (ValueError, KeyError) as error:
- self.log.append(str(error))
- elif line.strip():
- self.log.append(line.rstrip())
-
- def read_stderr(self):
- if self.processing_guard:self.processing_guard.output()
- self.log.append(bytes(self.process.readAllStandardError()).decode("utf-8", errors="replace").strip()[-8192:])
-
- def handle_event(self, event):
- kind = event["type"]
- self.single_tracking_event(event)
- if self.people_event(event):
- self._queued_task_estimates=[self.task_descriptor(s,a) for s,a in self.jobs]
- self.update_task_progress();return
- if kind=='mamma_ready':
- self.workspace_root=Path(event['root'])
- self.load_project(Path(event['project']))
- self.set_active_result(event['result'])
- elif kind == "prepared":
- self._task_preparing=False
- self._task_manifests={}
- self.project = Path(event["project"])
- from .project_storage import storage_root
- saved_root=storage_root(self.project)
- from .project_workspace import is_workspace
- if saved_root is not None and not is_workspace(saved_root):
- from .storage import atomic_json
- atomic_json(saved_root/'workspace_state.json',dict(version=1,name=saved_root.name,
- active=self.project.resolve().relative_to(saved_root).as_posix(),frame=0,trim=None))
- self.load_project(self.project)
- elif kind == 'project_saved':
- self._project_saved_root=Path(event['root'])
- elif kind == 'save_cancelled':
- self.cancelled=True
- self.status.setText(event['message'])
- elif kind == "progress":
- message=event.get('message','Processing...')
- self.log.status_terminal(message)
- self.status.setText((self._task_actor+' · ' if getattr(self,'_task_actor','') else '')+message)
- self.task_state.update(event,time.monotonic())
- self.update_task_progress()
- elif kind == "diagnostics":
- data = event["result"]
- self.log.append(json.dumps(data, ensure_ascii=False, indent=2))
- self.hardware_summary = f"{data.get('gpu', 'GPU unavailable')} · RAM {data.get('ram_gib', '?')}GB · CUDA check {'Passed' if data.get('cuda_matmul_verified') else 'Unavailable'}"
- self.status.setText(self.hardware_summary)
- elif kind in {"failed", "blocked"}:
- self.failed = True
- self.task_timer.stop();self.task_info.setText('Failed')
- self.status.setText("Processing failed. " + event.get("message", "See the console for details."))
- self.log.write_terminal(self.status.text())
- elif kind == "complete":
- self.task_state.cached|=bool(event.get('cached',False))
- self.log.append(f"{STAGES.get(event['stage'])}: {event.get('elapsed', 0):.2f} s · {event.get('output')}")
- self.log.ensureCursorVisible()
-
- def process_finished(self, code, _):
- self.read_stdout()
- self.read_stderr()
- if code != 0 and not self.cancelled:
- self.failed = True
- if "failed" not in self.status.text():
- self.status.setText("Processing stopped. See the console for details.")
- self.process.deleteLater()
- self.process = None
- self.task_state.finish(time.monotonic(),not self.failed and not self.cancelled and code==0)
- self.cleanup_fbx_export()
- self.next_job()
-
- def process_error(self, error):
- if error == QProcess.FailedToStart:
- self.character_refresh_queue=[]
- self.task_timer.stop();self.task_state.active=False;self.task_info.setText('Failed to start')
- self.guard_timer.stop()
- self.processing_guard = None
- if self.process is not None:
- self.process.deleteLater()
- self.process = None
- self.jobs.clear()
- self.cleanup_fbx_export()
- self.cleanup_project_save()
- self.failed = True
- self.busy = False
- self.finish_single_tracking()
- self.status.setText("Cannot start the processing engine. Check the app installation.")
- self.update_readiness()
-
- def cancel_job(self):
- if self.character_process is not None:
- self.cancel_character();return
- if self.current_stage=='save_project' and getattr(self,'_project_save_request',None):
- self._project_save_request.with_suffix('.cancel').touch()
- self.task_info.setText('Stopping...')
- self.status.setText('Cancelling project save...')
- self.cancel_button.setEnabled(False)
- return
- from shiboken6 import isValid
- pending=getattr(self,'cancel_process',None)
- if pending is not None and isValid(pending) and pending.state()!=QProcess.NotRunning:
- return
- self.task_timer.stop();self.task_state.active=False;self.task_info.setText('Stopping...')
- self.guard_timer.stop()
- self.cancelled = True
- self.jobs.clear()
- worker = self.process
- if worker and isValid(worker) and worker.processId():
- if os.name == "nt":
- # Stop FFmpeg/other descendants before losing their parent PID.
- helper = QProcess(self)
- self.cancel_process = helper
- def fallback(error):
- if error == QProcess.FailedToStart and self.process is worker and isValid(worker):
- worker.kill()
- if error == QProcess.FailedToStart:
- if self.cancel_process is helper:self.cancel_process=None
- if isValid(helper):helper.deleteLater()
- helper.errorOccurred.connect(fallback)
- def cancelled(code, _):
- if code and self.process is worker and isValid(worker):
- worker.kill()
- if self.cancel_process is helper:self.cancel_process=None
- if isValid(helper):helper.deleteLater()
- helper.finished.connect(cancelled)
- helper.start("taskkill.exe", ["/PID", str(worker.processId()), "/T", "/F"])
- else:
- worker.kill()
- self.status.setText("Cancelled. Completed stages will be reused next time.")
-
- def refresh_results(self):
- if self.project:
- signature = project_signature(self.project)
- if signature != self.preview_signature:
- self.preview_signature = signature
- self.data_loader.request(self.project)
- elif self.preview_data is not None:
- self.apply_preview()
-
- def clear_preview(self):
- self.preview_help.setText('')
- self.pelvis_auto_note.setText('Automatic lowering varies by frame.')
- self.data_loader.cancel()
- self.preview_signature = None
- self.slider.has_motion = False
- self.slider.update()
- self.video_view.set_observations({})
- self.motion_view.set_motion(None)
- self.refine_preview_note.hide()
- self.correction_note.hide()
- self.contact_tracks.clear()
- self.slider.set_contacts(None,identity=None,token=None)
- if self.preview_data is not None:
- self.preview_data.close()
- self.preview_data = None
-
- @batch_readiness
- def preview_ready(self, generation, result):
- if generation != self.data_loader.generation:
- result.close()
- return
- if result.signature != project_signature(result.project):
- # The worker committed another generation during loading. Never
- # pair these arrays with the new on-disk receipts.
- result.close()
- self.preview_signature=None
- self.refresh_results()
- return
- self.video_view.set_observations({})
- previous=self.preview_data
- preserve_view=previous is not None and previous.project==result.project
- auto_fit=self.motion_view.auto_fit
- if preserve_view:self.motion_view.auto_fit=False
- self.preview_data = result
- self.contact_tracks=dict(getattr(result,'contact_tracks',{}))
- try:self.apply_preview()
- finally:
- self.motion_view.auto_fit=auto_fit
- self.restore_workspace_camera(consume=True)
- if previous is not None:previous.close()
-
- @batch_readiness
- @read_only_checks
- def apply_preview(self):
- data = self.preview_data
- signature=project_signature(data.project)
- if data.signature != signature:
- # Hide stale payloads without forgetting this project's camera
- # anchor while the next committed correction is loading.
- self.motion_view.set_motion(None,path=data.project/(self.active_result+'_joints.npz'))
- self.slider.has_motion=False;self.slider.update()
- if not self.busy and signature!=self.preview_signature:self.refresh_results()
- return
- self.video_view.set_observations(data.arrays)
- display_kind=self.active_result
- name = display_kind + "_joints"
- corrected=self.active_result.startswith('corrected_')
- from .result_artifacts import artifacts_current
- coherent=artifacts_current(self.project,display_kind)
- current=coherent and result_is_current(self.project,display_kind)
- pending=coherent and corrected and not current and result_is_current(self.project,display_kind,ignore_contacts=True)
- available = name in data.arrays and (current or pending)
- self.correction_note.hide()
- self.refine_preview_note.hide()
- if not available:
- result = {"initial":MOTION_TOOLS[self.model_choice.currentData()].label, "refined":"HTD", "footmr_initial":"FootMR", "footmr_refined":"HTD + FootMR"}[body_result(self.active_result)]
- if has_handflow(self.active_result):result += " + HandFlow"
- note=self.correction_note if corrected else self.refine_preview_note
- missing_hand=has_handflow(self.active_result) and not result_is_current(self.project,base_result(self.active_result))
- note.setText('No current HandFlow preview. Run Reconstruct 3D to infer finger motion.' if missing_hand else
- 'Correction settings changed or result unavailable.\nUse Apply Correction to update the preview.' if corrected else f"No {result} preview yet. Run Reconstruct 3D to create it.")
- note.show()
- warning=' '.join(filter(None,(data.summaries.get(name,{}).get('correction_warning',''),data.summaries.get(name,{}).get('handflow_warning',''))))
- pelvis_summary=data.summaries.get(name,{})
- auto_drop=pelvis_summary.get('pelvis_auto_drop') if corrected else None
- self.pelvis_auto_note.setText('Automatic lowering varies by frame.' if auto_drop is None else
- f'Last applied: automatic lowering up to {auto_drop*100:.1f} cm; '
- f'automatic crouch lift up to {pelvis_summary.get("pelvis_auto_raise",0.)*100:.1f} cm; '
- f'user lift up to {pelvis_summary.get("pelvis_applied_lift",0.)*100:.1f} cm.')
- if self.people_root is not None:
- self.sync_shared_floor_controls()
- elif available and self.auto_floor.isChecked():
- self.floor_height.blockSignals(True)
- self.floor_height.setValue(float(data.summaries[name]['floor']))
- self.floor_height.blockSignals(False)
- if available and warning:
- self.correction_note.setText(warning);self.correction_note.show()
- if available and pending:
- self.correction_note.setText('Contact-lock timing changed. Preview shows the last applied correction.\nApply Correction to update the motion and FBX.');self.correction_note.show()
- self.slider.has_motion = available
- self.slider.update()
- overlay_name=self.active_result+'_joints'
- overlay_current=artifacts_current(self.project,self.active_result) and result_is_current(self.project,self.active_result,ignore_contacts=True)
- overlay_available=overlay_current and overlay_name in data.arrays
- from .bone_overlay import preview_current
- target_current=overlay_available and preview_current(self.project,self.active_result,data.target_info.get(self.active_result))
- camera_name=name if available else overlay_name
- rig_points=data.arrays.get(camera_name)
- # Source pose is the comparison reference. Never deform this surface
- # to make an imperfect export skeleton appear to fit it exactly.
- selected_mesh=None
- # Preserve a selected legacy baked preview if the export skin has not
- # been prepared yet. Never pair it with a different result's bones.
- self.motion_view.set_motion((rig_points if rig_points is not None else data.arrays.get(camera_name)) if available or overlay_available else None,
- data.summaries.get(camera_name),data.project/(camera_name+'.npz'),
- rotations=data.arrays.get(camera_name.replace('_joints','_rotations')) if available or overlay_available else None,
- mesh_frames=(selected_mesh if selected_mesh is not None else data.arrays.get(name.replace('_joints','_mesh'))) if available else None,mesh_asset=data.mesh_asset)
- self.motion_view.target_frames=data.arrays.get(self.active_result+'_rig') if target_current else None
- self.motion_view.target_asset=data.target_assets.get(self.active_result) if target_current else None
- self.motion_view.mesh_binding=self.motion_view.target_asset.get('binding') if selected_mesh is not None and self.motion_view.target_asset else None
- self.motion_view.raw_asset=None
- self.motion_view.native_vertices=None
- self.motion_view.native_required=False
- if self.model_choice.currentData()=='flowhmr':
- self.motion_view.raw_asset=self.motion_view.target_asset
- self.motion_view.native_vertices=data.arrays.get(self.active_result+'_native') if target_current else None
- self.motion_view.native_required=True
- info=data.target_info.get(self.active_result,{})
- warning=info.get('correction',{}).get('warning','')
- source_warning=data.summaries.get(name,{}).get('correction_warning','') if corrected else ''
- if source_warning and source_warning not in warning:warning=' '.join(filter(None,(warning,source_warning)))
- help_text='The skeleton is fitted to the selected motion mesh. Small differences may remain.'
- if info.get('fit_version',0)>=15:
- help_text='The skeleton follows the selected motion mesh, with steadier arm and leg directions. Errors in the AI motion may remain.'
- if corrected:
- short=int(pelvis_summary.get('short_contact_segments',0))
- if short:help_text+=f'\n{short} short foot-lock intervals never reach full strength because of boundary blending.'
- notices=[]
- if not available and corrected:notices.append('Selected motion unavailable. Use Apply Correction to update the preview.')
- if warning:notices.append(warning)
- selected_fit=info.get('selected_source_fit',{})
- if selected_fit:
- help_text+=f'\nSkeleton fit: mean {selected_fit["mean_m"]*100:.1f} cm; max {selected_fit["max_m"]*100:.1f} cm.'
- facing=selected_fit.get('anatomical_facing_deg',{})
- for label,joints in (('Knee',('LeftLeg','RightLeg')),('Elbow',('LeftForeArm','RightForeArm'))):
- values=[facing[j] for j in joints if j in facing]
- if values:help_text+=f'\n{label} anatomical axis vs AI source: mean {sum(v["mean"] for v in values)/len(values):.1f}°; max {max(v["max"] for v in values):.1f}°.'
- fitted=info.get('selected_source_fit',info.get('source_fit',{})).get('joints',{})
- elbow_offset=max((fitted.get(side+'ForeArm',fitted.get('mixamorig:'+side+'ForeArm',{})).get('max_m',0.) for side in ('Left','Right')),default=0.)
- if elbow_offset>.08:
- notices.append(f'Elbow pose differs from AI source (up to {elbow_offset*100:.1f} cm) after anatomical alignment.')
- if self.model_choice.currentData()=='flowhmr':
- from .flow_placement import needs_update
- if needs_update(self.project):notices.append('FlowHMR scene placement needs updating. Use Prepare Preview; no AI inference is required.')
- knee_offset=max((fitted.get(side+'Leg',{}).get('max_m',0.) for side in ('Left','Right')),default=0.)
- if knee_offset>.08:notices.append(f'Knee pose differs from AI source (up to {knee_offset*100:.1f} cm) after anatomical alignment.')
- self.bone_overlay.setToolTip(tooltip_text('Show the skeleton used for FBX export. Display only.\n'
- 'In Blender, use Scale 1 and leave Automatic Bone Orientation off to keep its axes.\n'+help_text))
- if available and pending:notices.append('Contact-lock timing changed. Preview shows the last applied correction. Apply Correction to update the motion and FBX.')
- if corrected and available and not pending and not result_is_current(self.project,self.active_result):notices.append('The last applied correction is outdated or unavailable. Apply Correction before export.')
- self.preview_help.setText(help_text)
- self.correction_note.setText('\n'.join(dict.fromkeys(notices)));self.correction_note.setVisible(bool(notices))
- if available and self.motion_view.target_asset is None and not self.busy and os.environ.get('QT_QPA_PLATFORM')!='offscreen' and (self.project/RESULTS[base_result(self.active_result)][0]).is_file():
- token=(str(self.project),self.active_result,self.preview_signature)
- attempts=getattr(self,'_rig_attempts',deque(maxlen=16))
- if token not in attempts:
- attempts.append(token);self._rig_attempts=attempts
- QTimer.singleShot(0,self.prepare_target_preview)
- self.update_foot_contacts()
- self.update_readiness()
-
- def preview_failed(self, generation, message):
- if generation == self.data_loader.generation:
- changed=self.project is not None and self.preview_signature!=project_signature(self.project)
- self.preview_signature = None
- if changed:
- self.refresh_results()
- return
- self.status.setText("Cannot load the motion preview. " + message)
-
- def save_fbx(self):
- if self.selected_character() is not None:
- self.export_character(self.selected_character());return
- if self.export_checked_people():return
- source = self.current_export()
- if source:
- from .person_names import export_stem
- default=export_stem(self.export_person_name(self.project))+'.fbx'
- name, _ = QFileDialog.getSaveFileName(self, "Export FBX", default, "FBX (*.fbx)")
- if name:
- self.submit_fbx_exports([(self.project,self.active_result,source,Path(name))])
-
- def submit_fbx_exports(self,files):
- if self.busy:return
- import uuid
- from .storage import atomic_json
- request=self.project/('.fbx-export-'+uuid.uuid4().hex+'.json')
- rows=[]
- try:
- for project,kind,source,target in files:
- row=dict(project=str(project),kind=kind,source=str(source),target=str(target))
- row['rig_name']=self.export_person_name(project)
- if self.people_root is not None:
- from .scene_export import context
- row['scene']=context(self.people_root,project)
- rows.append(row)
- except (OSError,ValueError,KeyError) as error:
- self.status.setText('Cannot export shared scene: '+str(error));return
- atomic_json(request,rows)
- self._fbx_export_cleanup=(request,[target.with_name('.'+target.name+'.rgbmocap-'+request.stem+'.partial') for _,_,_,target in files])
- self.start_jobs([('save_fbx',['--project',str(self.project),'--output',str(request)])])
-
- def cleanup_fbx_export(self):
- pending=getattr(self,'_fbx_export_cleanup',None)
- if pending:
- request,paths=pending
- for path in [request,*paths]:
- try:path.unlink(missing_ok=True)
- except OSError:pass
- self._fbx_export_cleanup=None
-
- def open_folder(self):
- from .project_storage import storage_root
- target = self.workspace_root or ((storage_root(self.project) or self.project) if self.project else PROJECTS)
- target.mkdir(parents=True, exist_ok=True)
- QDesktopServices.openUrl(QUrl.fromLocalFile(str(target)))
-
- def dragEnterEvent(self, event):
- if event.mimeData().hasUrls() and not self.busy:
- event.acceptProposedAction()
-
- def dropEvent(self, event):
- urls = event.mimeData().urls()
- if urls and not self.busy:
- if self.model_choice.currentData()=='mamma':self.load_mamma_videos([Path(url.toLocalFile()) for url in urls])
- else:self.load_video(Path(urls[0].toLocalFile()))
-
- def closeEvent(self, event):
- if self.busy and self.process:
- answer = QMessageBox.question(self, "Processing", "Cancel the current job and close the application?")
- if answer != QMessageBox.Yes:
- event.ignore()
- return
- self.cancel_job()
- worker = self.process
- if worker:
- worker.waitForFinished(3000)
- if self.character_process is not None:
- self.cancel_character();self.character_process.waitForFinished(5000)
- self.character_loader.close()
- self.task_timer.stop()
- if self.workspace_root is not None:
- try:self.remember_workspace_model()
- except (OSError,ValueError) as error:self.log.append('Could not save project view: '+str(error))
- self.shutdown_preview()
- event.accept()
+from __future__ import annotations
+from .tooltips import tooltip_text
+from .ui_refresh import batch_readiness
+from .validation_snapshot import read_only_checks
+
+import json
+import math
+import os
+from collections import deque
+from pathlib import Path
+import time
+
+from PySide6.QtCore import QElapsedTimer, QEvent, QProcess, QProcessEnvironment, QTimer, Qt, QUrl
+from PySide6.QtGui import QColor, QDesktopServices, QKeySequence, QShortcut, QTextOption
+from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialog, QFileDialog,
+ QFrame, QHBoxLayout, QLabel, QMainWindow, QMessageBox, QProgressBar, QPushButton,
+ QSplitter, QTableWidget, QTableWidgetItem, QTextBrowser, QTextEdit, QVBoxLayout, QWidget)
+
+from .models import MODELS_LIST, import_body_model, missing, ready
+from .paths import ROOT, PROJECTS, worker_command
+from .video import select_preview
+from .viewer import VideoView, MotionView
+from .playback import playback_frame, PlaybackTimerResolution
+from .timeline import TimelineSlider
+from .preview_data import PreviewDataLoader, project_signature
+from .motion_tools import MOTION_TOOLS, selected_export, RESULTS, result_kind, result_options, result_is_current, base_result, body_result, has_handflow
+
+STAGES = {"prepare": "Prepare Video", "track": "Track Actor", "pva": "Analyze 2D", "gvhmr": "Initial 3D Reconstruction", "refine": "Refine Motion", "export": "Export", "download": "Model Manager", "diagnose": "Check System"}
+
+from .theme import STYLE
+STAGES["mesh"] = "Prepare SMPL-X Mesh"
+STAGES['rig']='Prepare Bone Preview'
+STAGES['save_fbx']='Save FBX'
+STAGES["footmr"] = "Refine Ankles / FootMR"
+STAGES["handflow"] = "Infer Fingers / HandFlow"
+STAGES['correct'] = 'Motion Correction'
+from .workspace_ui import build_workspace
+from .people_ui import PeopleWorkspace
+from .project_save_ui import ProjectSaving
+from .project_workspace_ui import ModelWorkspace
+STAGES.update(mamma_prepare='Prepare Multi-view Videos',mamma_masks='MAMMA Person Masks',mamma_landmarks='MAMMA Surface Landmarks',mamma_camera='MAMMA Cameras',mamma_fit='MAMMA 3D Fit',mamma_publish='MAMMA Motion Correction and Preview')
+STAGES['save_project']='Save Project As'
+STAGES.update(people='Find People',person='Prepare Person Motion')
+STAGES.update(flow_camera='Estimate Scene Camera / VGGT-Omega', flow_features='Extract Body and Hand Features / SAM', flowhmr='Reconstruct Motion / FlowHMR', flow_export='Prepare FlowHMR Preview and FBX', import_model='Import Model')
+STAGES.update(exmr_preprocess='ExMR Body, Hand and Foot Keypoints',exmr_features='ExMR Body and Hand Features',exmr='Reconstruct Motion / ExMR')
+
+STAGES.update(flow_batch='Process FlowHMR Motion',exmr_batch='Process ExMR Motion',gvhmr_batch='GVHMR Multi-person',features='GVHMR Image Observations')
+
+class ModelDownloadDialog(QDialog):
+ """Readable, selectable provider instructions with bounded scrolling."""
+ def __init__(self, parent, key, manager=None):
+ super().__init__(parent)
+ self.manager = manager
+ self.model_key = key
+ from .models import BY_KEY, manual_download_page, manual_instructions_html
+ self.setWindowTitle(BY_KEY[key].name + " - Manual Download")
+ self.setMinimumSize(360, 260)
+ area = self.screen().availableGeometry()
+ self.resize(min(680, max(360, area.width() - 80)),
+ min(560, max(260, area.height() - 100)))
+ layout = QVBoxLayout(self)
+ self.browser = QTextBrowser()
+ self.browser.setStyleSheet(
+ 'QTextBrowser { font-family:"' + QApplication.font().family() + '"; font-size:12px; padding:6px; }')
+ self.browser.setOpenLinks(False)
+ self.browser.setOpenExternalLinks(False)
+ self.browser.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
+ self.browser.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
+ self.browser.setTextInteractionFlags(Qt.TextBrowserInteraction)
+ self.browser.setHtml(manual_instructions_html(key))
+ self.browser.anchorClicked.connect(QDesktopServices.openUrl)
+ layout.addWidget(self.browser)
+ self.import_status = QLabel()
+ self.import_status.setWordWrap(True)
+ self.import_status.setMaximumHeight(64)
+ self.import_status.hide()
+ layout.addWidget(self.import_status)
+ actions = QHBoxLayout(); actions.addStretch()
+ self.website = QPushButton("Open Download Page")
+ self.website.setToolTip('Open the model provider website in your browser.')
+ self.website.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(manual_download_page(key))))
+ actions.addWidget(self.website)
+ self.import_file = QPushButton("Import...")
+ self.import_file.setToolTip('Select the downloaded model file to check and import it. These instructions stay open.')
+ self.import_file.clicked.connect(self.import_download)
+ actions.addWidget(self.import_file)
+ close = QPushButton("Close"); close.clicked.connect(self.accept)
+ close.setToolTip('Close these download instructions.')
+ actions.addWidget(close); layout.addLayout(actions)
+ self.status_timer = QTimer(self)
+ self.status_timer.setInterval(100)
+ self.status_timer.timeout.connect(self.sync_import_status)
+ self.sync_import_status()
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ self.sync_import_status()
+ self.status_timer.start()
+
+ def hideEvent(self, event):
+ self.status_timer.stop()
+ super().hideEvent(event)
+
+ def import_download(self):
+ if self.manager is not None:
+ self.manager.import_local_model(self.model_key, picker_parent=self)
+ self.sync_import_status()
+
+ def sync_import_status(self):
+ manager = self.manager
+ self.import_file.setEnabled(manager is not None and not manager.window.busy)
+ if manager is None:
+ return
+ manager.sync_task_status()
+ message = manager.task_status.toPlainText() if manager._observing_setup or manager.window.busy else ''
+ if self.import_status.toolTip() != message:
+ self.import_status.setTextFormat(Qt.PlainText)
+ self.import_status.setText(message[:500])
+ self.import_status.setToolTip(message)
+ self.import_status.setVisible(bool(message))
+
+
+class ModelsDialog(QDialog):
+ def __init__(self, window, tool_key=None):
+ super().__init__(window)
+ self.window = window
+ self.tool = MOTION_TOOLS[tool_key or window.model_choice.currentData()]
+ from .models import STAGE_REQUIREMENTS
+ keys = ({key for key in STAGE_REQUIREMENTS['mamma_assets']} if self.tool.key=='mamma' else
+ {key for stage in (*self.tool.stages(refine=True, footmr=True, handflow=True),'people') for key in STAGE_REQUIREMENTS.get(stage, ())})
+ # Keep public automatic downloads together, followed by manual-only files.
+ # Stable sorting preserves the existing component order within each group.
+ self.models = sorted((model for model in MODELS_LIST if model.key in keys),
+ key=lambda model: not bool(model.drive_id or model.download_url))
+ self.setWindowTitle(f"{self.tool.label} Model Manager")
+ self.resize(850, min(540, max(360, self.screen().availableGeometry().height() - 80)))
+ layout = QVBoxLayout(self)
+ description = QLabel(f"Models for {self.tool.label} and compatible add-ons.\nUse Auto Download for public files, or Manual Download and Import for any model.\nRegistered body model files are not redistributed by this app.")
+ description.setWordWrap(True)
+ layout.addWidget(description)
+ if self.tool.key=='mamma':
+ from .mamma_manager import runtime_panel
+ layout.addWidget(runtime_panel(self))
+ self.table = QTableWidget(len(self.models), 3)
+ self.table.setHorizontalHeaderLabels(["Model", "Status", "Action"])
+ self.table.horizontalHeader().setStretchLastSection(True)
+ self.table.setColumnWidth(0, 300)
+ self.table.setColumnWidth(1, 130)
+ layout.addWidget(self.table)
+ self.task_status = QTextBrowser()
+ self.task_status.setFixedHeight(64)
+ self.task_status.setOpenLinks(False)
+ self.task_status.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
+ self.task_status.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
+ self.task_status.setStyleSheet(
+ 'QTextBrowser { font-family:"' + QApplication.font().family() + '"; font-size:12px; padding:4px; }')
+ self.task_status.setPlainText("Ready to download or import models.")
+ layout.addWidget(self.task_status)
+ self.task_progress = QProgressBar()
+ self.task_progress.setTextVisible(False)
+ self.task_progress.setRange(0, 100); self.task_progress.setValue(0)
+ layout.addWidget(self.task_progress)
+ actions = QHBoxLayout()
+ self.cancel_task = QPushButton("Cancel")
+ self.cancel_task.setToolTip('Stop the current download or import queue. Completed files are kept.')
+ self.cancel_task.setEnabled(False)
+ self.cancel_task.clicked.connect(self.cancel_model_job)
+ actions.addWidget(self.cancel_task)
+ actions.addStretch()
+ self.download_all = QPushButton("Download All")
+ self.download_all.setToolTip(tooltip_text(
+ "Download missing public model files. Files requiring registration must be downloaded manually and imported. Completed downloads are kept if you cancel or retry."))
+ self.download_all.clicked.connect(self.start_download_all)
+ actions.addWidget(self.download_all)
+ close = QPushButton("Close")
+ close.setToolTip(tooltip_text("Close Model Manager. Any running download or import continues in the main workspace."))
+ close.clicked.connect(self.accept); actions.addWidget(close)
+ layout.addLayout(actions)
+ self._batch_total = 0
+ self._observing_setup = False
+ self._row_state = None
+ self._status_state = None
+ self.status_timer = QTimer(self)
+ self.status_timer.setInterval(100)
+ self.status_timer.timeout.connect(self.sync_task_status)
+ self.refresh()
+
+ def refresh(self):
+ for i, model in enumerate(self.models):
+ name = model.name + (" (Optional: HTD / 2D)" if self.tool.key == "gvhmr" and model.key == "pva" else "")
+ available = ready(model)
+ for column, text in ((0, name), (1, "Ready" if available else "Missing")):
+ item = self.table.item(i, column)
+ if item is None:
+ item = QTableWidgetItem(); self.table.setItem(i, column, item)
+ item.setText(text)
+ if column==0:item.setToolTip(str(model.path))
+ item.setForeground(QColor("#d5d5d5" if available else "#ffb45c"))
+ font = item.font(); font.setBold(not available); item.setFont(font)
+ cell = self.table.cellWidget(i, 2)
+ if cell is None or cell.property("model_key") != model.key:
+ cell = QWidget(); cell.setProperty("model_key", model.key)
+ row = QHBoxLayout(cell); row.setContentsMargins(0, 0, 0, 0)
+ cell.automatic = None
+ if model.drive_id or model.download_url:
+ cell.automatic = QPushButton("Auto Download")
+ cell.automatic.setToolTip(tooltip_text("Download this file automatically. If it fails, use Manual Download or Import an existing copy."))
+ cell.automatic.clicked.connect(lambda checked=False, key=model.key: self.start_download(key))
+ row.addWidget(cell.automatic)
+ cell.manual = QPushButton("Manual Download...")
+ cell.manual.setToolTip(tooltip_text("Show download links and instructions. Download in your browser, then use Import in the instructions or this row."))
+ cell.manual.clicked.connect(lambda checked=False, key=model.key: self.manual_setup(key))
+ row.addWidget(cell.manual)
+ cell.local = QPushButton("Import...")
+ cell.local.setToolTip(tooltip_text("Choose a model file you already downloaded. The app checks it before replacing any existing file."))
+ cell.local.clicked.connect(lambda checked=False, key=model.key: self.import_local_model(key))
+ row.addWidget(cell.local)
+ self.table.setCellWidget(i, 2, cell)
+ if cell.automatic is not None:
+ cell.automatic.setEnabled(not self.window.busy and not available)
+ cell.manual.setEnabled(True)
+ cell.local.setEnabled(not self.window.busy)
+ self.download_all.setEnabled(not self.window.busy and bool(self.pending_downloads()))
+ self._row_state = (self.window.busy, id(self.window.process))
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ self.refresh(); self.sync_task_status()
+ self.status_timer.start()
+
+ def hideEvent(self, event):
+ self.status_timer.stop()
+ super().hideEvent(event)
+
+ def sync_task_status(self):
+ # Poll only cheap GUI state; filesystem readiness is refreshed once per
+ # worker transition, never on each progress update or every timer tick.
+ w = self.window
+ row_state = (w.busy, id(w.process))
+ if row_state != self._row_state:
+ self.refresh()
+ setup = w.current_stage in {"download", "import_model"}
+ if w.busy and setup:
+ self._observing_setup = True
+ state = (w.busy, setup, w.cancelled, w.failed, w.status.text(),w.task_info.text(),
+ w.progress.minimum(), w.progress.maximum(), w.progress.value(), len(w.jobs))
+ if state == self._status_state:
+ return
+ self._status_state = state
+ active = w.busy and setup
+ self.cancel_task.setEnabled(active and not w.cancelled)
+ if setup and self._observing_setup:
+ message = w.status.text()
+ if active:message+='\n'+w.task_info.text()
+ if active and self._batch_total > 1 and not w.cancelled and not w.failed:
+ index = min(self._batch_total, max(1, self._batch_total - len(w.jobs)))
+ message = f"Model {index}/{self._batch_total}: " + message
+ self.task_status.setPlainText(message if len(message) <= 4096 else message[:4096] + "\nSee Console for the complete message.")
+ self.task_status.setStyleSheet(
+ 'QTextBrowser { font-family:"' + QApplication.font().family() +
+ '"; font-size:12px; padding:4px;' +
+ ('color:#ffb45c;' if w.failed else '') + ' }')
+ if active:
+ self.task_progress.setRange(w.progress.minimum(), w.progress.maximum())
+ self.task_progress.setValue(w.progress.value())
+ else:
+ self.task_progress.setRange(0, 100)
+ self.task_progress.setValue(0 if w.failed or w.cancelled else 100)
+ elif w.busy:
+ self.task_status.setPlainText("Another task is running. You can still open manual download instructions.")
+ self.task_progress.setRange(0, 0)
+ else:
+ self.task_status.setPlainText("Ready to download or import models.")
+ self.task_progress.setRange(0, 100); self.task_progress.setValue(0)
+
+ def start_model_jobs(self, jobs):
+ if self.window.busy:
+ return
+ self._batch_total = len(jobs)
+ self._observing_setup = True
+ self._status_state = None
+ self.window.start_jobs(jobs)
+ self.sync_task_status()
+
+ def cancel_model_job(self):
+ if self.window.busy and self.window.current_stage in {"download", "import_model"}:
+ self.window.cancel_job()
+ self.sync_task_status()
+
+ def pending_downloads(self):
+ return [model for model in self.models
+ if (model.drive_id or model.download_url) and not ready(model)]
+
+ def start_download_all(self):
+ if self.window.busy:
+ return
+ jobs = [("download", ["--model", model.key]) for model in self.pending_downloads()]
+ if not jobs:
+ self.refresh()
+ return
+ self.start_model_jobs(jobs)
+
+ def start_download(self, key):
+ if key not in {model.key for model in self.models}:
+ raise ValueError("This model is not part of the selected motion tool.")
+ self.start_model_jobs([("download", ["--model", key])])
+
+ def manual_setup(self, key):
+ if key not in {model.key for model in self.models}:
+ raise ValueError("This model is not part of the selected motion tool.")
+ dialog = ModelDownloadDialog(self, key, manager=self)
+ try:
+ dialog.exec()
+ finally:
+ dialog.deleteLater()
+
+ def import_local_model(self, key, picker_parent=None):
+ from .models import BY_KEY
+ if self.window.busy:
+ return
+ if key not in {model.key for model in self.models}:
+ raise ValueError("This model is not part of the selected motion tool.")
+ model = BY_KEY[key]
+ name, _ = QFileDialog.getOpenFileName(picker_parent or self, 'Import ' + model.name, '',
+ f'Model file ({model.path.name});;All files (*)')
+ if name:
+ self.start_model_jobs([('import_model', ['--model', key, '--video', name])])
+
+
+
+from .character_ui import CharacterWorkspace
+from .mamma_ui import MammaWorkspace
+
+class MainWindow(MammaWorkspace,CharacterWorkspace,ModelWorkspace,ProjectSaving,PeopleWorkspace,QMainWindow):
+ def __init__(self, video: Path | None = None):
+ super().__init__()
+ self.setWindowTitle("RGB MoCap | Motion Workspace")
+ self.resize(1440, 880)
+ self.setMinimumSize(1100, 700)
+ self.video_path = None
+ self.init_mamma()
+ self.project = None
+ self.workspace_root=None
+ self._workspace_loading=False
+ self._workspace_video_reference=False
+ self._workspace_camera=None
+ self.init_people()
+ self.active_result = "corrected_footmr_refined"
+ self.info = None
+ self.source_offset = 0.0
+ self.source_end = 0.0
+ self.video_readable = False
+ self.busy = False
+ self.jobs = []
+ self.process = None
+ self.cancel_process = None
+ self.buffer = ""
+ self.failed = False
+ self.cancelled = False
+ self.hardware_summary = None
+ self.current_stage = None
+ self._batch_started_at = None
+ self._batch_has_motion = False
+ from .task_progress import TaskProgress
+ self.task_state=TaskProgress()
+ self._task_manifests={};self._queued_task_estimates=[]
+ self.play_clock = QElapsedTimer()
+ self.timer_resolution = PlaybackTimerResolution()
+ self.play_anchor = 0
+ self.playback_tick = False
+ self.presented_times = deque()
+ self.preview_data = None
+ self.preview_signature = None
+ from .contact_writer import ContactWriter
+ self.contact_tracks={};self.contact_saving=False;self.contact_save_token=0
+ self.contact_writer=ContactWriter(self)
+ self.contact_writer.saved.connect(self.foot_contacts_saved)
+ self.contact_writer.failed.connect(self.foot_contacts_failed)
+ self.contact_writer.settled.connect(self.foot_contacts_settled)
+ self.data_loader = PreviewDataLoader(self)
+ self.data_loader.ready.connect(self.preview_ready)
+ self.data_loader.failed.connect(self.preview_failed)
+ self.data_loader.tracked_actor_ready.connect(self.tracked_actor_ready)
+ build_workspace(self)
+ self.init_characters()
+ self.timer = QTimer(self)
+ self.timer.setTimerType(Qt.PreciseTimer)
+ self.timer.setInterval(33)
+ self.timer.timeout.connect(self.next_frame)
+ self.shortcuts = []
+ for key, action in [("Space", self.toggle_play), ("Left", lambda: self.step_frames(-1)),
+ ("Right", lambda: self.step_frames(1)),
+ ("Shift+Left", lambda: self.step_frames(-round(self.info['fps']) if self.info else -30)),
+ ("Shift+Right", lambda: self.step_frames(round(self.info['fps']) if self.info else 30)),
+ ("Home", lambda: self.step_frames(-self.slider.maximum())),
+ ("End", lambda: self.step_frames(self.slider.maximum()))]:
+ shortcut = QShortcut(QKeySequence(key), self)
+ shortcut.activated.connect(action)
+ self.shortcuts.append(shortcut)
+ self.setAcceptDrops(True)
+ self.data_loader.start()
+ self.contact_writer.start()
+ self.processing_guard = None
+ self.guard_timer = QTimer(self)
+ self.guard_timer.setInterval(500)
+ self.guard_timer.timeout.connect(self.check_processing_resources)
+ self.task_timer=QTimer(self)
+ self.task_timer.setInterval(500)
+ self.task_timer.timeout.connect(self.update_task_progress)
+ # Initialize the same model-specific visibility used on selector changes.
+ # Otherwise the empty GVHMR stack reserves the FlowHMR page height.
+ self.select_model()
+ if video:
+ self.load_video(video)
+
+ @read_only_checks
+ def update_readiness(self):
+ if getattr(self,'_readiness_depth',0):
+ self._readiness_pending=True
+ return
+ if hasattr(self,'character_loader'):self.sync_characters()
+ self.update_people_readiness()
+ tool = MOTION_TOOLS[self.model_choice.currentData()]
+ self.compute_mode.setEnabled(not self.busy)
+ stages = tool.stages(self.htd_refine.isChecked(), self.footmr_refine.isChecked(), handflow=self.handflow_refine.isChecked())
+ from .models import STAGE_REQUIREMENTS, BY_KEY
+ required = {key for stage in stages for key in STAGE_REQUIREMENTS.get(stage, ())}
+ if tool.key=='flowhmr' and self.flow_sampling.currentData()==-1:required.discard('flow_vggt')
+ if tool.key=='mamma' and self.mamma_camera_mode.currentData()=='manual':required.discard('flow_vggt')
+ unavailable = [BY_KEY[key] for key in sorted(required) if not ready(BY_KEY[key])]
+ count = len(required) - len(unavailable)
+ text = f"{tool.label}: {count}/{len(required)} models ready"
+ if unavailable:
+ noun = "model" if len(unavailable) == 1 else "models"
+ text += f"\nWarning: {len(unavailable)} required {noun} missing.\nOpen Model Manager to download or import."
+ self.readiness.setStyleSheet("color:#ffb45c; font-weight:600;" if unavailable else "")
+ self.readiness.setToolTip(tooltip_text("Missing required models:\n" + "\n".join(model.name for model in unavailable) if unavailable else ""))
+ self.readiness.setText(text)
+ for button in (self.models_button, self.analyze_button, self.run_button):
+ button.setEnabled(not self.busy)
+ self.cancel_button.setEnabled(self.busy)
+ self.check_system_action.setEnabled(not self.busy)
+ self.model_choice.setEnabled(not self.busy and not self.contact_saving)
+ self.htd_refine.setEnabled(not self.busy)
+ self.footmr_refine.setEnabled(not self.busy)
+ self.handflow_refine.setEnabled(not self.busy)
+ self.motion_correction.setEnabled(not self.busy)
+ self.correction_controls.setEnabled(not self.busy and self.motion_correction.isChecked())
+ flat=self.correction_mode.currentData()=='flat'
+ self.auto_floor.setEnabled(not self.busy and flat)
+ self.floor_height.setEnabled(not self.busy and flat and not self.auto_floor.isChecked())
+ self.correction_button.setEnabled(not self.busy and not self.contact_saving and self.project is not None and
+ (self.project/RESULTS[base_result(self.active_result)][0]).exists())
+ self.slider.trim_enabled = not self.busy and self.info is not None
+ self.slider.contact_edit_enabled=not self.busy and not self.contact_saving and self.motion_correction.isChecked() and self.slider.contacts_available
+ self.slider.contact_track_enabled=(self.foot_lock.isChecked(),)*2+(self.hand_lock.isChecked(),)*2
+ self.slider.update()
+ self.reset_footlocks_button.setEnabled(self.slider.contact_edit_enabled)
+ self.reset_trim_button.setEnabled(self.slider.trim_enabled)
+ character=self.selected_character()
+ self.export_action.setText('Export Character...' if character else 'Export FBX...')
+ self.export_action.setEnabled(not self.busy and (bool(character.get('takes')) and not character.get('needs_retarget') if character else self.project is not None and self.current_export() is not None))
+ self.export_action.setToolTip(tooltip_text("Choose a character export format and whether to include its mesh. PMX characters also support VMD motion." if character else "Save the displayed skeleton animation as FBX. For multiple people, each checked person gets a separate named file and rig."))
+ self.play_button.setEnabled(self.info is not None and self.video_readable)
+ for action in self.open_actions:
+ action.setEnabled(not self.busy)
+ self.save_project_action.setEnabled(not self.busy and not self.contact_saving and self.video_path is not None and self.info is not None)
+ self.mesh_button.setEnabled(self.preview_preparation_available())
+ self.import_character_action.setEnabled(not self.busy and not self.contact_saving)
+ self.flow_sampling.setEnabled(not self.busy)
+ self.fast_sam.setEnabled(not self.busy)
+ self.flow_acceleration.setVisible(self.fast_sam.isChecked())
+ self.flow_acceleration.setEnabled(not self.busy)
+ self.exmr_camera.setEnabled(not self.busy)
+ self.exmr_smoothing.setEnabled(not self.busy)
+ self.analyze_button.setVisible(tool.key=='gvhmr')
+ self.sync_correction_floor_preview()
+ self.sync_mamma_controls()
+
+ def sync_correction_floor_preview(self):
+ self.motion_view.correction_floor_applicable=self.correction_mode.currentData()=='flat'
+ enabled=self.motion_correction.isChecked() and self.correction_mode.currentData()=='flat'
+ pending=bool(self.project is not None and enabled and
+ not result_is_current(self.project,'corrected_'+base_result(self.active_result)))
+ self.motion_view.set_correction_floor(self.floor_height.value() if self.project is not None else None,
+ automatic=self.auto_floor.isChecked(),pending=pending,enabled=enabled)
+
+ def show_model_guide(self):
+ from .model_guide import ModelGuideDialog
+ dialog = ModelGuideDialog(self, self.model_choice.currentData())
+ try:
+ dialog.exec()
+ finally:
+ dialog.deleteLater()
+
+ def select_model(self, *_):
+ tool = MOTION_TOOLS[self.model_choice.currentData()]
+ if self.workspace_root is not None and not self._workspace_loading and tool.key!=getattr(self,'_selected_tool',None):
+ if self.busy or self.contact_saving:
+ self.model_choice.blockSignals(True)
+ self.model_choice.setCurrentIndex(self.model_choice.findData(self._selected_tool))
+ self.model_choice.blockSignals(False)
+ return
+ self.switch_workspace_model(tool.key)
+ return
+ previous=getattr(self,'_selected_tool','gvhmr')
+ choices=getattr(self,'_tool_refinement',{'gvhmr':(True,True,True,True)})
+ if previous!=tool.key:
+ if previous=='gvhmr':choices['gvhmr']=(self.htd_refine.isChecked(),self.footmr_refine.isChecked(),self.motion_correction.isChecked(),self.handflow_refine.isChecked())
+ else:choices[previous]=(False,False,self.motion_correction.isChecked(),False)
+ values=choices.get(tool.key,(tool.key=='gvhmr',tool.key=='gvhmr',True,tool.key=='gvhmr'))
+ for control,value in zip((self.htd_refine,self.footmr_refine,self.motion_correction,self.handflow_refine),values):
+ control.blockSignals(True);control.setChecked(value);control.blockSignals(False)
+ self._selected_tool=tool.key;self._tool_refinement=choices
+ self.active_result=self.selected_result()
+ if self.project is not None:
+ state=json.loads((self.project/'project.json').read_text(encoding='utf-8'))
+ if state.get('pipeline',{}).get('model','gvhmr')!=tool.key:
+ # Keep source timing/camera but never show another engine's result.
+ self.stop_playback();self.clear_preview();self.reset_people()
+ self.project=None
+ self.active_result=self.selected_result()
+ self.status.setText(f'{tool.label} selected. Reconstruct this clip or open a {tool.label} project.')
+ for index in range(self.model_pages.count()):
+ if self.model_pages.widget(index).property("motion_tool") == tool.key:
+ self.model_pages.setCurrentIndex(index)
+ break
+ self.model_pages.setVisible(tool.key!='gvhmr')
+ self.htd_refine.setVisible(bool(tool.refinement))
+ self.refine_description.setVisible(bool(tool.refinement))
+ self.footmr_refine.setVisible(tool.key == "gvhmr")
+ self.handflow_refine.setVisible(tool.key == "gvhmr")
+ self.footmr_description.setVisible(tool.key == "gvhmr")
+ if not tool.refinement:
+ self.refine_preview_note.hide()
+ self.models_group.setTitle(tool.label+' Models')
+ self.correction_group.setVisible(True)
+ self.slider.contacts_supported=True
+ self.slider._cache_key=None
+ self.slider.update()
+ self.correction_description.setText('Only checked contact types are corrected. Uses the selected '+tool.label+' result.')
+ self.analyze_button.setToolTip(tooltip_text('Find body points in the video for GVHMR refinement. Reconstruct 3D normally includes this step when needed.'))
+ self.mamma_mode_changed(previous,tool.key)
+ self.update_readiness()
+
+ def selected_result(self, correction=None):
+ gvhmr=self.model_choice.currentData()=='gvhmr'
+ return result_kind(gvhmr and self.htd_refine.isChecked(),gvhmr and self.footmr_refine.isChecked(),
+ self.motion_correction.isChecked() if correction is None else correction,
+ handflow=gvhmr and self.handflow_refine.isChecked())
+
+ def refinement_changed(self, enabled):
+ self.set_active_result(self.selected_result())
+
+ def current_export(self):
+ info=self.contact_tracks.get(base_result(self.active_result))
+ if self.active_result.startswith('corrected_') and (self.contact_saving or (info and info.get('unsaved'))):return None
+ # selected_export checks source, correction and target receipts itself.
+ if self.project is not None:
+ return selected_export(self.project, self.active_result)
+ return None
+
+ def render_changed(self):
+ self.motion_view.show_bones=self.bone_overlay.isChecked()
+ self.motion_view.update()
+
+ def preview_preparation_available(self):
+ if self.project is None or self.busy or self.contact_saving:return False
+ if not (self.project/RESULTS[base_result(self.active_result)][0]).is_file():return False
+ info=self.contact_tracks.get(base_result(self.active_result),{})
+ if self.active_result.startswith('corrected_') and info.get('unsaved'):return False
+ if self.model_choice.currentData()=='flowhmr':
+ from .flow_placement import needs_update
+ if needs_update(self.project):return True
+ return ((self.project/RESULTS[self.active_result][0]).is_file()
+ and result_is_current(self.project,self.active_result))
+
+ def prepare_target_preview(self):
+ if self.project is None or self.busy or self.contact_saving:return
+ from .mixamo_data import current
+ projects=[self.project]
+ if self.people_state:
+ from .people_store import safe_child
+ projects += [safe_child(self.people_root,take['project']) for person in self.people_state['people']
+ if person.get('checked') for take in person.get('takes',[])]
+ jobs=[]
+ for project in dict.fromkeys(projects):
+ from .flow_placement import needs_update
+ placement_old=self.model_choice.currentData()=='flowhmr' and needs_update(project)
+ if (project/RESULTS[base_result(self.active_result)][0]).is_file() and (placement_old or result_is_current(project,self.active_result) and not current(project,self.active_result)):
+ jobs.append(('rig',['--project',str(project),'--result',self.active_result]))
+ if jobs:self.start_jobs(jobs)
+
+ def open_model_manager(self):
+ dialog = ModelsDialog(self)
+ try:
+ dialog.exec()
+ finally:
+ dialog.deleteLater()
+
+ def set_active_result(self, kind):
+ """Select the cached preview and sync the HTD option without inference."""
+ htd, foot = result_options(kind)
+ self.active_result = kind
+ self.handflow_refine.blockSignals(True)
+ self.handflow_refine.setChecked(has_handflow(kind))
+ self.handflow_refine.blockSignals(False)
+ self.htd_refine.blockSignals(True)
+ self.htd_refine.setChecked(htd)
+ self.htd_refine.blockSignals(False)
+ self.footmr_refine.blockSignals(True)
+ self.footmr_refine.setChecked(foot)
+ self.footmr_refine.blockSignals(False)
+ self.motion_correction.blockSignals(True)
+ self.motion_correction.setChecked(kind.startswith('corrected_'))
+ self.motion_correction.blockSignals(False)
+ self.refresh_results()
+ self.request_people_scene()
+ self.update_readiness()
+
+ def choose_video(self):
+ if self.model_choice.currentData()=='mamma':
+ names,_=QFileDialog.getOpenFileNames(self,'Open MAMMA Camera Videos','', 'Videos (*.mp4 *.mov *.avi *.mkv *.webm)')
+ if names:self.load_mamma_videos(names)
+ return
+ name, _ = QFileDialog.getOpenFileName(self, "Open Video", "", "Videos (*.mp4 *.mov *.avi *.mkv *.webm)")
+ if name:
+ self.load_video(Path(name))
+
+ def load_video(self, path):
+ if self.model_choice.currentData()=='mamma':
+ return self.load_mamma_videos([path])
+ try:
+ if self.workspace_root is not None:self.remember_workspace_model()
+ self.clear_mamma_inputs()
+ self.workspace_root=None;self._workspace_video_reference=False;self._workspace_camera=None
+ self.stop_playback()
+ self.clear_preview()
+ self.reset_people()
+ self.motion_view.auto_fit = True
+ self.video_path, self.project, self.info = path, None, None
+ self.setWindowTitle('RGB MoCap | Motion Workspace')
+ self.flow_sampling.setCurrentIndex(self.flow_sampling.findData(0))
+ self.fast_sam.setChecked(True)
+ self.flow_batch4.setChecked(True)
+ self.flow_gpu_crop.setChecked(True)
+ self.exmr_camera.setCurrentIndex(0)
+ self.exmr_smoothing.setChecked(True)
+ self.handflow_refine.blockSignals(True)
+ self.handflow_refine.setChecked(self.model_choice.currentData()=='gvhmr')
+ self.handflow_refine.blockSignals(False)
+ self._tool_refinement={'gvhmr':(True,True,True,True)}
+ for option in (self.htd_refine, self.footmr_refine, self.motion_correction):
+ option.blockSignals(True)
+ option.setChecked(True)
+ option.blockSignals(False)
+ self.active_result = self.selected_result()
+ self.restore_correction_options({})
+ self.source_offset = self.source_end = 0.0
+ self.video_readable = False
+ self.slider.setRange(0, 0)
+ self.filename.setText(f"{path.name} · Opening video...")
+ self.video_view.open(path)
+ self.update_readiness()
+ except Exception as error:
+ QMessageBox.warning(self, "Video Error", str(error))
+
+ def video_ready(self, info):
+ if self.mamma_video_ready(info):return
+ self.video_readable = True
+ self.slider.set_media(self.info["fps"] if self.info else info["fps"])
+ if self.project is None and not self._workspace_video_reference:
+ self.info = info
+ self.slider.setRange(0, max(0, info["frames"] - 1))
+ self.source_offset, self.source_end = 0.0, info["duration"]
+ self.slider.reset_trim()
+ self.clip_changed(self.slider.clip_in, self.slider.clip_out)
+ self.filename.setText(f"{self.video_path.name} · {info['width']}×{info['height']} · {info['fps']:.2f}fps · {info['duration']:.2f} s")
+ self.fps_label.setText(f"Source {info['fps']:.2f} fps")
+ self.seek(0)
+ if self.workspace_root is not None:
+ from .project_workspace import read
+ self.source_offset=float(read(self.workspace_root).get('time_offset',0.))
+ self.source_end=self.source_offset+info['duration']
+ self.restore_workspace_view(getattr(self,'_workspace_pending_view',{}))
+ self.update_readiness()
+
+ def video_failed(self, message):
+ self.video_readable = False
+ self.stop_playback()
+ self.status.setText("Video preview: " + message)
+ self.update_readiness()
+
+ def choose_project(self):
+ name, _ = QFileDialog.getOpenFileName(self, "Open Project", str(PROJECTS), "Project (project.json)")
+ if name:
+ from .project_workspace import root_for
+ try:
+ project=Path(name).parent
+ if root_for(project) is None:
+ raise ValueError('This project uses the previous folder format. Open its video to create a new model-folder project.')
+ self.load_project(project)
+ except (OSError,ValueError,KeyError) as error:self.status.setText('Cannot open project: '+str(error))
+
+ @batch_readiness
+ def load_project(self, project):
+ from .project_workspace import is_workspace
+ if is_workspace(project):return self.open_workspace(project)
+ from .project_storage import project_to_open, source_video
+ try:
+ project, workspace = project_to_open(project)
+ except (OSError, ValueError) as error:
+ self.status.setText('Cannot open project: '+str(error));return False
+ from .motion_tools import require_supported_project, UnsupportedMotionTool
+ try:
+ require_supported_project(project)
+ except UnsupportedMotionTool as error:
+ self.status.setText(str(error))
+ return False
+ manifest = json.loads((project / "project.json").read_text(encoding="utf-8"))
+ if manifest.get('pipeline',{}).get('model')=='mamma':
+ group=(project/manifest.get('people_root','.')).resolve()
+ if (group/'mamma_pending.json').exists():
+ self.status.setText('MAMMA publication is incomplete. Reconstruct again to finish; previous projects were preserved.')
+ return False
+ self.stop_playback()
+ self.clear_preview()
+ self.motion_view.auto_fit = True
+ self.project = project
+ self.workspace_project_loaded(project,manifest)
+ from .project_storage import storage_root
+ saved_root=storage_root(project,manifest)
+ self.setWindowTitle('RGB MoCap | '+(saved_root.name if saved_root else 'Motion Workspace'))
+ pipeline = manifest.get("pipeline", {})
+ from .flow_camera import saved_interval
+ from .flow_sam import saved_options
+ flow=saved_options(project,manifest)
+ self.fast_sam.setChecked(flow['fast_sam'])
+ self.flow_batch4.setChecked(flow['sam_batch4'])
+ self.flow_gpu_crop.setChecked(flow['sam_gpu_crop'])
+ from .exmr_options import saved as saved_exmr
+ exmr=saved_exmr(project,manifest)
+ self.exmr_camera.setCurrentIndex(self.exmr_camera.findData(exmr['static_camera']))
+ self.exmr_smoothing.setChecked(exmr['smoothing']=='global')
+ self.flow_sampling.setCurrentIndex(max(0,self.flow_sampling.findData(saved_interval(project,manifest))))
+ self.model_choice.blockSignals(True)
+ self.model_choice.setCurrentIndex(self.model_choice.findData(pipeline.get('model','gvhmr')))
+ self.model_choice.blockSignals(False)
+ opening=self._workspace_loading;self._workspace_loading=True
+ try:self.select_model()
+ finally:self._workspace_loading=opening
+ has_refined = any((project / name).exists() for name in ("opt_results.pt", "refined_joints.npz", "refined_mesh.json"))
+ has_motion = has_refined or any((project / name).exists() for name in ("hmr4d_results.pt", "initial_joints.npz"))
+ result = pipeline.get("result", "refined" if has_refined else "initial")
+ saved_selection=bool(pipeline.get('result'))
+ self.handflow_refine.blockSignals(True)
+ self.handflow_refine.setChecked(has_handflow(result) if has_motion or saved_selection else pipeline.get('model','gvhmr')=='gvhmr')
+ self.handflow_refine.blockSignals(False)
+ self.htd_refine.blockSignals(True)
+ self.htd_refine.setChecked(result_options(result)[0] if has_motion or saved_selection else True)
+ self.htd_refine.blockSignals(False)
+ self.footmr_refine.blockSignals(True)
+ # Existing projects keep their saved selection; new reconstructions default all on.
+ self.footmr_refine.setChecked(result_options(result)[1] if has_motion or saved_selection else True)
+ self.footmr_refine.blockSignals(False)
+ self.motion_correction.blockSignals(True)
+ self.motion_correction.setChecked(result.startswith('corrected_') if has_motion or saved_selection else True)
+ self.motion_correction.blockSignals(False)
+ self.restore_correction_options(manifest.get('correction',{}))
+ self.active_result = self.selected_result()
+ self.video_path = source_video(project, manifest)
+ self.video_readable = False
+ fps = manifest.get("fps", 30)
+ self.info = {"fps": fps, "frames": manifest["frames"], "duration": manifest["frames"] / fps}
+ self.source_offset, self.source_end = manifest["start"], manifest["end"]
+ self.slider.set_media(fps)
+ # MAMMA restores its selected camera below. Opening the actor's default
+ # clip first discards that decoder and its cache on every row selection.
+ if not (pipeline.get('model')=='mamma' and self.mamma_inputs and self.mamma_thumbnail_buttons):
+ self.video_view.open(select_preview(project), (manifest["width"], manifest["height"]))
+ self.slider.setRange(0, manifest["frames"] - 1)
+ self.filename.setText(f"{self.video_path.name} · Project loaded · {manifest['frames']} frames")
+ self.slider.reset_trim()
+ self.clip_changed(self.slider.clip_in, self.slider.clip_out)
+ self.refresh_results()
+ self.seek(0)
+ self.fps_label.setText(f"Source {fps:.2f} fps")
+ if (project / "motion.bvh").exists():
+ self.status.setText("Motion loaded. Play the animation or adjust the video clip range.")
+ if (project / "keypoints.npz").exists() and not (project / "hmr4d_results.pt").exists():
+ self.status.setText("2D observations loaded. Prepare the body model to reconstruct full-body motion.")
+ self.sync_people(project,manifest)
+ if workspace:
+ trim=workspace.get('trim')
+ if trim and 0<=trim[0]<trim[1]<=manifest['frames']:
+ self.slider.clip_in,self.slider.clip_out=trim
+ self.clip_changed(*trim)
+ self.slider.setValue(max(0,min(int(workspace.get('frame',0)),manifest['frames']-1)))
+ self.seek(self.slider.value())
+ self.update_readiness()
+ self.mamma_project_loaded(project,manifest)
+ return True
+
+ def seek(self, index):
+ self.frame_number.blockSignals(True)
+ self.frame_number.setValue(index + 1)
+ self.frame_number.blockSignals(False)
+ if self.timer.isActive() and not self.playback_tick:
+ self.reset_play_clock()
+ self.video_view.seek(index)
+ fps = self.info["fps"] if self.info else 30
+ total = self.info["duration"] if self.info else 0
+ self.time_label.setText(f"{index/fps:05.2f} / {total:05.2f} s")
+
+ def processing_range(self):
+ """Map preview-local trim edges to the unchanged original source."""
+ fps = self.info["fps"]
+ first = self.source_offset + self.slider.clip_in / fps
+ end = min(self.source_end, self.source_offset + self.slider.clip_out / fps)
+ return first, end
+
+ def clip_changed(self, first, end):
+ if hasattr(self, "timer"):
+ self.stop_playback()
+ if self.info:
+ start_seconds, end_seconds = self.processing_range()
+ text = f"Clip: {first + 1}–{end} | {end_seconds-start_seconds:.2f} s"
+ self.clip_label.setText(text)
+ self.clip_label.setToolTip(tooltip_text(f"Video range: {start_seconds:.3f}–{end_seconds:.3f} s\nDrag the video track edges to trim playback and reconstruction. Existing motion files stay unchanged until you reconstruct again."))
+ else:
+ self.clip_label.setText("Clip: no video")
+
+ def present_frame(self, index):
+ # 3D and overlays advance only when the corresponding decoded image is ready.
+ self.motion_view.index = index
+ self.motion_view.scene_time=self.source_offset+index/(self.info['fps'] if self.info else 30)
+ self.motion_view.update()
+ if self.timer.isActive():
+ now = time.perf_counter()
+ self.presented_times.append(now)
+ while self.presented_times and now - self.presented_times[0] > 2:
+ self.presented_times.popleft()
+ if len(self.presented_times) > 2 and now - self.presented_times[0] >= 0.5:
+ actual = (len(self.presented_times) - 1) / (now - self.presented_times[0])
+ self.fps_label.setText(f"Source {self.info['fps']:.2f} | Play {actual:.1f} fps")
+
+ def reset_play_clock(self, *_):
+ self.play_anchor = self.slider.value()
+ self.play_clock.start()
+ self.presented_times.clear()
+ if self.timer.isActive() and self.info:
+ self.timer.start(max(1, math.ceil(1000 / (self.info['fps'] * self.play_speed.currentData()))))
+
+ def stop_playback(self):
+ self.timer.stop()
+ self.timer_resolution.release()
+ self.set_playback_indicator(False)
+
+ def set_playback_indicator(self, playing):
+ label = "Pause" if playing else "Play"
+ self.play_button.setIcon(self.pause_icon if playing else self.play_icon)
+ self.play_button.setToolTip(tooltip_text(label + " (Space)"))
+ self.play_button.setAccessibleName(label)
+
+ def step_frames(self, amount):
+ self.stop_playback()
+ self.slider.setValue(max(0, min(self.slider.maximum(), self.slider.value() + amount)))
+
+ def toggle_play(self):
+ if self.timer.isActive():
+ self.stop_playback()
+ elif self.video_path and self.info and self.video_readable:
+ if not self.slider.clip_in <= self.slider.value() < self.slider.clip_out:
+ self.slider.setValue(self.slider.clip_in)
+ self.timer_resolution.acquire()
+ self.reset_play_clock()
+ self.timer.start(max(1, math.ceil(1000 / (self.info['fps'] * self.play_speed.currentData()))))
+ self.set_playback_indicator(True)
+
+ def next_frame(self):
+ if not self.timer.isActive() or self.info is None or not self.video_readable:
+ return
+ elapsed = self.play_clock.nsecsElapsed() / 1e9
+ rate = self.info["fps"] * self.play_speed.currentData()
+ target = self.slider.clip_in + playback_frame(self.play_anchor - self.slider.clip_in,
+ elapsed, self.info["fps"], self.slider.clip_out - self.slider.clip_in,
+ self.play_speed.currentData())
+ self.playback_tick = True
+ try:
+ self.slider.setValue(target)
+ finally:
+ self.playback_tick = False
+ next_deadline = (math.floor(elapsed * rate + 1e-8) + 1) / rate
+ remaining = next_deadline - self.play_clock.nsecsElapsed() / 1e9
+ self.timer.start(max(1, math.ceil(remaining * 1000)))
+
+ def shutdown_preview(self):
+ self.shutdown_mamma()
+ self.stop_playback()
+ if hasattr(self,'character_loader'):
+ self.character_loader.close();self.character_assets.clear()
+ self.scene_loader.stop()
+ self.scene_loader.wait()
+ self.clear_people_scene()
+ self.clear_preview()
+ self.data_loader.stop()
+ self.data_loader.wait()
+ self.contact_writer.stop()
+ self.contact_writer.wait()
+ self.video_view.shutdown()
+ self.motion_view.cleanup_gl()
+
+ def changeEvent(self, event):
+ if event.type() == QEvent.WindowStateChange and self.isMinimized() and hasattr(self, "timer"):
+ self.stop_playback()
+ super().changeEvent(event)
+
+ def hideEvent(self, event):
+ if hasattr(self, "timer"):
+ self.stop_playback()
+ super().hideEvent(event)
+
+ def input_jobs(self, stages, result=None):
+ if MOTION_TOOLS[self.model_choice.currentData()].input_setup_only:
+ self.status.setText('MAMMA camera input setup is available; reconstruction is not integrated yet.')
+ return
+ if self.video_path is None:
+ self.choose_video()
+ return
+ if self.info is None or not self.video_readable:
+ self.status.setText("Wait for the video preview to finish opening.")
+ return
+ if 'people' not in stages and self._single_actor and not self._single_actor['checked']:
+ self.status.setText('Check Person 1 in the People list to reconstruct it.')
+ return
+ if 'people' not in stages and self.input_person_jobs(stages,result):
+ return
+ unavailable = [model for stage in stages for model in ([] if self.model_choice.currentData()=='flowhmr' and stage=='flow_camera' and self.flow_sampling.currentData()==-1 else missing('flow_export' if self.model_choice.currentData()=='flowhmr' and stage in ('correct','export') else stage))]
+ if unavailable:
+ names = ", ".join(dict.fromkeys(model.name for model in unavailable))
+ self.status.setText(f"Prepare these models first: {names}")
+ self.open_model_manager()
+ return
+ first, end = self.processing_range()
+ prepare_args = ["--video", str(self.video_path), "--start", str(first), "--end", str(end)]
+ if self.workspace_root is not None:
+ prepare_args += ['--project',str(self.workspace_root)]
+ elif self.project is not None:
+ from .project_storage import storage_root
+ if storage_root(self.project) is not None:
+ prepare_args += ['--project', str(self.project)]
+ if result or self.model_choice.currentData()!='gvhmr':
+ prepare_args+=['--motion-tool',self.model_choice.currentData()]
+ if result:
+ prepare_args += ["--result", result]
+ if result.startswith('corrected_') and not self.auto_floor.isChecked():
+ prepare_args += ['--floor',str(self.floor_height.value())]
+ if result.startswith('corrected_'):
+ prepare_args += ['--correction-preset',self.correction_preset.currentData(),
+ '--correction-mode',self.correction_mode.currentData(),
+ '--foot-lock',str(int(self.foot_lock.isChecked())),'--hand-lock',str(int(self.hand_lock.isChecked())),
+ '--pelvis-offset',str(self.pelvis_offset.value())]
+ self.start_jobs([("prepare", prepare_args)]
+ + [(stage, ["--result", result] if stage in {"export", "flow_export", "footmr", "handflow", "correct"} and result else None) for stage in stages])
+
+ def run_analysis(self):
+ self.input_jobs(["track", "pva"])
+
+ def run_full(self):
+ tool = MOTION_TOOLS[self.model_choice.currentData()]
+ if tool.key=='mamma':return self.run_mamma()
+ if tool.key=='exmr' and self.people_root is not None:
+ from .storage import atomic_json
+ path=self.people_root/'project.json';state=json.loads(path.read_text(encoding='utf-8'))
+ state['exmr_options']={'static_camera':self.exmr_camera.currentData(),'smoothing':'global' if self.exmr_smoothing.isChecked() else 'none'}
+ atomic_json(path,state)
+ if tool.key=='flowhmr' and self.people_root is not None:
+ from .storage import atomic_json
+ path=self.people_root/'project.json';state=json.loads(path.read_text(encoding='utf-8'))
+ state['flow_options']={**state.get('flow_options',{}),**self.selected_flow_options()}
+ atomic_json(path,state)
+ refine = bool(tool.refinement) and self.htd_refine.isChecked()
+ foot = tool.key=='gvhmr' and self.footmr_refine.isChecked()
+ correction=self.motion_correction.isChecked()
+ if correction:self.save_correction_options()
+ hand=tool.key=='gvhmr' and self.handflow_refine.isChecked()
+ self.input_jobs(tool.stages(refine, foot,correction,handflow=hand), result=result_kind(refine, foot,correction,handflow=hand))
+
+ def save_correction_options(self):
+ if self.project is not None:
+ if self.people_root is not None:
+ from .scene_floor import save_config
+ save_config(self.people_root,self.selected_correction_options())
+ from .storage import atomic_json
+ path=self.project/'project.json';state=json.loads(path.read_text(encoding='utf-8'))
+ state['correction']=self.selected_correction_options()
+ atomic_json(path,state)
+
+ def selected_correction_options(self):
+ from .correction_settings import correction_options
+ return correction_options({'auto_floor':self.auto_floor.isChecked(),'floor':self.floor_height.value(),
+ 'mode':self.correction_mode.currentData(),'foot_lock':self.foot_lock.isChecked(),'hand_lock':self.hand_lock.isChecked(),
+ 'preset':self.correction_preset.currentData(),'pelvis_offset':self.pelvis_offset.value()})
+
+ def update_correction_description(self):
+ descriptions = {
+ 'weak': 'Gentler correction, with some sliding allowed to preserve more of the original movement.',
+ 'normal': 'Balanced contact correction. Holds stable contacts while keeping transitions smooth.',
+ 'strong': 'Firmer holds, including less certain contacts. May resist intentional slides; review the result.',
+ }
+ self.preset_description.setText(descriptions[self.correction_preset.currentData()])
+ if self.correction_mode.currentData()=='multi_level':
+ self.floor_description.setText('Multi Level uses the inferred height of each foot contact. This floor value is unused; switch to Flat Ground to edit it.')
+ else:
+ self.floor_description.setText('Higher values raise the correction floor. Use the Correction Floor checkbox to preview it; Apply Correction updates the motion.')
+
+ def restore_correction_options(self, options):
+ from .correction_settings import correction_options
+ options=correction_options(options)
+ controls=(self.correction_mode,self.correction_preset,self.auto_floor,self.floor_height,self.pelvis_offset,self.foot_lock,self.hand_lock)
+ for control in controls:control.blockSignals(True)
+ try:
+ self.correction_preset.setCurrentIndex(self.correction_preset.findData(options['preset']))
+ self.correction_mode.setCurrentIndex(self.correction_mode.findData(options['mode']))
+ self.foot_lock.setChecked(options['foot_lock']);self.hand_lock.setChecked(options['hand_lock'])
+ self.auto_floor.setChecked(options['auto_floor']);self.floor_height.setValue(options['floor'])
+ self.pelvis_offset.setValue(options['pelvis_offset'])
+ finally:
+ for control in controls:control.blockSignals(False)
+ self.update_correction_description()
+
+ def correction_settings_changed(self, *_):
+ if self.sender() is self.floor_height and self.auto_floor.isChecked():return
+ self.update_correction_description()
+ self.save_correction_options()
+ if self.sender() is self.correction_preset:
+ self.request_people_scene(force=True)
+ if self.preview_data is not None:self.apply_preview()
+ self.update_readiness()
+ return
+ # Keep the last committed pose visible while editing the reference
+ # plane. Only Apply Correction changes motion; stale export stays blocked.
+ if self.preview_data is not None:
+ self.correction_note.setText('Correction settings changed. Preview shows the last applied motion.\nApply Correction to update the pelvis, contacts and FBX.')
+ self.correction_note.show()
+ self.update_readiness()
+
+ def apply_correction(self):
+ if self.project is None or self.busy or self.contact_saving:return
+ info=self.contact_tracks.get(base_result(self.active_result))
+ if info and info.get('unsaved'):
+ self.status.setText('Contact-lock timing was not saved. Edit or reset the tracks to retry saving.');return
+ self.save_correction_options()
+ kind=self.selected_result(True)
+ self.set_active_result(kind)
+ if self.people_root is not None:
+ self.apply_scene_correction(kind);return
+ self.start_jobs([('correct',['--result',kind]),('export',['--result',kind])], refresh_characters=True)
+
+ def update_foot_contacts(self):
+ base=base_result(self.active_result)
+ info=self.contact_tracks.get(base)
+ if info and self.info and (info['context']['frames']!=self.info['frames'] or info['context']['fps']!=self.info['fps']):info=None
+ self.slider.set_contacts(info['ranges'] if info else None,info['automatic'] if info else None,
+ editable=not self.busy and not self.contact_saving and self.motion_correction.isChecked(),
+ identity=(str(self.project),base),token=id(info))
+ from .foot_contacts import contact_levels
+ self.motion_view.foot_lock_levels=lambda frame:contact_levels(info,frame)
+
+ def foot_contacts_changed(self,ranges):
+ self.save_foot_contacts(ranges)
+
+ def reset_foot_contacts(self):
+ self.save_foot_contacts(None)
+
+ def save_foot_contacts(self,ranges):
+ if self.project is None or self.busy or self.contact_saving:return
+ base=base_result(self.active_result);info=self.contact_tracks.get(base)
+ if info is None:return
+ self.stop_playback();self.contact_saving=True
+ try:self.contact_save_token=self.contact_writer.request(self.project,base,ranges,info['context'])
+ except Exception as error:
+ self.contact_saving=False;self.status.setText('Cannot save contact-lock timing: '+str(error));return
+ # Keep immutable metadata while the writer commits off the GUI thread.
+ self.contact_tracks[base]={**info,'ranges':ranges if ranges is not None else info['automatic'],'manual':ranges is not None,'unsaved':True}
+ self.status.setText('Saving contact-lock timing...')
+ self.update_readiness()
+
+ def foot_contacts_saved(self,sequence,record):
+ if self.project is None or str(self.project.resolve())!=record['project']:return
+ info=self.contact_tracks.get(record['base'])
+ if info is None:return
+ self.contact_tracks[record['base']]={**info,'revision':record['state']['revision'],'unsaved':False}
+ for key,scene in self.scene_cache.items():
+ if base_result(key[1])==record['base']:
+ take=scene.by_project.get(self.project)
+ if take:
+ take.set_contacts(info['ranges'])
+ take.contact_revision=record['state']['revision']
+ if sequence==self.contact_save_token:
+ if self.preview_data is not None:self.apply_preview()
+ self.status.setText('Contact-lock timing saved. Apply Correction to update the motion and FBX.')
+
+ def foot_contacts_failed(self,sequence,message):
+ if sequence==self.contact_save_token:self.status.setText('Cannot save contact-lock timing: '+message)
+
+ def foot_contacts_settled(self,sequence):
+ if sequence==self.contact_save_token:
+ self.contact_saving=False;self.update_readiness()
+
+ def prepare_mesh(self):
+ if self.project is not None and not self.busy:
+ self.prepare_target_preview()
+
+ def start_jobs(self, jobs, refresh_characters=False):
+ if self.busy:
+ return
+ jobs=list(jobs)
+ self.character_refresh_queue=[]
+ if refresh_characters:
+ try:
+ self.prepare_character_refresh(jobs)
+ except (OSError, ValueError, KeyError) as exc:
+ self.character_refresh_queue=[]
+ self.status.setText(f'Cannot update linked characters: {exc}')
+ self.update_readiness()
+ return
+ self._batch_started_at = time.monotonic()
+ self._batch_has_motion = False
+ self.task_state.reset(self._batch_started_at)
+ self._task_manifests={}
+ self.jobs, self.busy, self.cancelled, self.failed = list(jobs), True, False, False
+ self._task_preparing=any(stage=='prepare' for stage,_ in self.jobs)
+ self.update_readiness()
+ self.next_job()
+
+ def task_descriptor(self,stage,arguments):
+ """Small metadata once per transition; no filesystem access on ticks."""
+ arguments=arguments or []
+ project=(Path(arguments[arguments.index('--project')+1]) if '--project' in arguments else
+ None if getattr(self,'_task_preparing',False) else self.project)
+ tool=self.model_choice.currentData();state={};estimate=None
+ if project is not None:
+ project=Path(project)
+ if project not in self._task_manifests:
+ try:
+ file=project/'project.json'
+ state=json.loads(file.read_text(encoding='utf-8')) if file.stat().st_size<=1024**2 else {}
+ except (OSError,ValueError):state={}
+ if len(self._task_manifests)>=32:self._task_manifests.pop(next(iter(self._task_manifests)))
+ self._task_manifests[project]=state
+ state=self._task_manifests[project];tool=state.get('pipeline',{}).get('model',tool)
+ estimate=state.get('stages',{}).get(stage,{}).get('elapsed')
+ if stage.startswith('exmr'):
+ try:
+ file=project/(stage+'_receipt.json')
+ if file.stat().st_size<=65536:estimate=json.loads(file.read_text(encoding='utf-8')).get('elapsed')
+ except (OSError,ValueError):pass
+ frames=state.get('frames',self.info.get('frames',0) if self.info else 0)
+ if '--first-frame' in arguments and '--end-frame' in arguments:
+ frames=int(arguments[arguments.index('--end-frame')+1])-int(arguments[arguments.index('--first-frame')+1])
+ model=arguments[arguments.index('--model')+1] if '--model' in arguments else ''
+ result=arguments[arguments.index('--result')+1] if '--result' in arguments else self.active_result
+ key=(stage,tool,frames,model,result,self.compute_mode.currentData(),self.fast_sam.isChecked(),self.flow_batch4.isChecked(),self.flow_gpu_crop.isChecked(),self.flow_sampling.currentData(),self.exmr_camera.currentData())
+ if not isinstance(estimate,(int,float)) or not math.isfinite(estimate) or not 1<=estimate<=7*86400:estimate=None
+ if stage in ('flow_batch','exmr_batch','gvhmr_batch'):
+ from .queue_groups import argument
+ items=json.loads(argument(arguments,'--batch-items'))
+ key=(*key,argument(arguments,'--batch-phase'),tuple((item['project'],item['result']) for item in items),len(items))
+ estimate=None
+ estimate=self.task_state.history.get(key,estimate)
+ return key,estimate
+
+ def update_task_progress(self):
+ if not self.busy or self.failed or self.cancelled or not self.task_state.active:return
+ text,percent=self.task_state.status(time.monotonic(),self._queued_task_estimates)
+ self.task_info.setText(text)
+ # A real 0/N observation is loading, not a stationary empty bar.
+ if percent is None:self.progress.setRange(0,0)
+ else:
+ total=self.task_state.total;current=self.task_state.current
+ if total<=2147483647 and total.is_integer():
+ self.progress.setRange(0,int(total));self.progress.setValue(int(current))
+ else:
+ self.progress.setRange(0,1000);self.progress.setValue(round(1000*current/total))
+
+ def cleanup_batch_request(self):
+ from .queue_groups import remove_request
+ path=getattr(self,'_batch_request',None);self._batch_request=None
+ try:remove_request(path)
+ except OSError as error:self.log.append('Could not remove worker request: '+str(error))
+
+ def next_job(self):
+ self.cleanup_batch_request()
+ self.guard_timer.stop()
+ self.processing_guard = None
+ if not self.jobs or self.failed or self.cancelled:
+ self.task_timer.stop()
+ elapsed = (max(0., time.monotonic() - self._batch_started_at)
+ if self._batch_started_at is not None else None)
+ self._batch_started_at = None
+ self.busy = False
+ self.finish_single_tracking()
+ self.task_state.active=False
+ from .task_progress import duration
+ self.task_info.setText(('Stopped' if self.failed or self.cancelled else 'Done')+
+ (f' · Elapsed {duration(elapsed)}' if elapsed is not None else ''))
+ self.progress.setRange(0, 100)
+ self.progress.setValue(0 if self.failed or self.cancelled else 100)
+ if self.current_stage=='save_fbx':
+ # Saving a derived file does not replace scene/preview data.
+ # Reloading the people scene here moves a following camera.
+ if not self.failed and not self.cancelled:self.status.setText('FBX export complete.')
+ self.update_readiness()
+ return
+ if self.current_stage=='save_project':
+ self.finish_project_save()
+ return
+ person_batch=self._people_batch
+ completion_message=self.status.text()
+ self.finish_people_jobs()
+ if self.failed or self.cancelled:self.status.setText(completion_message)
+ if not self.failed and not self.cancelled:
+ if self.current_stage in ("export",'flow_export') and self.project is not None and not person_batch:
+ metadata = json.loads((self.project / "export.json").read_text(encoding="utf-8"))
+ self.set_active_result(metadata.get("result_kind", "refined"))
+ if self.current_stage == "diagnose" and self.hardware_summary:
+ self.status.setText(self.hardware_summary)
+ elif self.current_stage == "pva":
+ self.status.setText("2D analysis complete. View the estimated joints over the video.")
+ elif self.current_stage == "download":
+ self.status.setText("Downloads complete. Check Model Manager for any required imports.")
+ elif self.current_stage == "import_model":
+ self.status.setText("Model setup complete.")
+ elif self.current_stage not in ('people','person'):
+ self.status.setText("Complete. Play the result or open the project folder.")
+ if self._batch_has_motion and elapsed is not None:
+ seconds = round(elapsed)
+ minutes, seconds = divmod(seconds, 60)
+ hours, minutes = divmod(minutes, 60)
+ duration = (f'{hours}h {minutes:02d}m {seconds:02d}s' if hours else
+ f'{minutes}m {seconds:02d}s' if minutes else f'{elapsed:.1f} s')
+ self.status.setText(f'Complete. Total time: {duration}. Play the result or open the project folder.')
+ self.log.append(f'Total motion processing time: {elapsed:.2f} s')
+ self.refresh_results()
+ self.update_readiness()
+ if self.failed or self.cancelled:
+ self.character_refresh_queue=[]
+ else:
+ self.next_character_refresh()
+ return
+ from .queue_groups import join_single_pipeline
+ self.jobs = join_single_pipeline(self.jobs, self.project)
+ stage, arguments = self.jobs.pop(0)
+ if stage in {'gvhmr', 'refine', 'footmr', 'handflow', 'correct',
+ 'flow_camera', 'flow_features', 'flowhmr',
+ 'exmr_preprocess', 'exmr_features', 'exmr'}:
+ self._batch_has_motion = True
+ if stage.startswith('mamma_') or stage in ('flow_batch','exmr_batch','gvhmr_batch'):self._batch_has_motion=True
+ self.current_stage = stage
+ self._batch_inner_stage=stage
+ if arguments is None:
+ arguments = ["--project", str(self.project)]
+ elif stage in {"export", "footmr", "handflow", "correct", 'flow_export'} and "--project" not in arguments:
+ arguments = ["--project", str(self.project), *arguments]
+ self.job_project = Path(arguments[arguments.index('--project')+1]) if '--project' in arguments else None
+ if stage=='track':self.begin_single_tracking(self.job_project)
+ if stage in {"download", "import_model"} and "--model" in arguments:
+ from .models import BY_KEY
+ model_key = arguments[arguments.index("--model") + 1]
+ self.status.setText(("Downloading " if stage == "download" else "Importing ") + BY_KEY[model_key].name + "...")
+ else:
+ self.status.setText(STAGES[stage] + "...")
+ key,estimate=self.task_descriptor(stage,arguments)
+ self.task_state.begin(time.monotonic(),key,self.status.text(),estimate)
+ actor=next((part for part in self.job_project.parts if part.startswith('person_')),'') if self.job_project else ''
+ self._task_actor=actor.replace('_',' ').title().replace('000','')
+ self._queued_task_estimates=[self.task_descriptor(s,a) for s,a in self.jobs]
+ self.task_timer.start();self.update_task_progress()
+ self.progress.setRange(0, 0)
+ self.buffer = ""
+ if stage in ('flow_batch','exmr_batch','gvhmr_batch'):
+ from .queue_groups import write_request
+ try:
+ self._batch_request=write_request(stage,arguments)
+ except (OSError,ValueError) as error:
+ self.failed=True;self.log.append(str(error));self.status.setText('Cannot prepare people processing: '+str(error))
+ self.next_job();return
+ arguments=['--request',str(self._batch_request),'--project',str(self.job_project)]
+ command = worker_command(stage, *arguments)
+ self.process = QProcess(self)
+ self.process.setWorkingDirectory(str(ROOT))
+ environment = QProcessEnvironment.systemEnvironment()
+ environment.insert("PYTHONIOENCODING", "utf-8")
+ environment.insert("PYTHONUNBUFFERED", "1")
+ environment.insert("RGB_MOCAP_COMPUTE_MODE", self.compute_mode.currentData())
+ environment.insert('RGB_MOCAP_FLOW_INTERVAL',str(self.flow_sampling.currentData()))
+ environment.insert('RGB_MOCAP_FLOW_FAST_SAM','1' if self.fast_sam.isChecked() else '0')
+ environment.insert('RGB_MOCAP_FLOW_BATCH4','1' if self.flow_batch4.isChecked() else '0')
+ environment.insert('RGB_MOCAP_FLOW_GPU_CROP','1' if self.flow_gpu_crop.isChecked() else '0')
+ environment.insert('RGB_MOCAP_EXMR_OPTIONS',json.dumps({'static_camera':self.exmr_camera.currentData(),'smoothing':'global' if self.exmr_smoothing.isChecked() else 'none'}))
+ self.process.setProcessEnvironment(environment)
+ self.process.readyReadStandardOutput.connect(self.read_stdout)
+ self.process.readyReadStandardError.connect(self.read_stderr)
+ self.process.finished.connect(self.process_finished)
+ self.process.errorOccurred.connect(self.process_error)
+ self.process.started.connect(self.start_processing_guard)
+ self.process.start(command[0], command[1:])
+
+ def start_processing_guard(self):
+ from .processing_guard import ProcessingGuard
+ try:
+ self.processing_guard = ProcessingGuard(self.process.processId())
+ self.guard_timer.start()
+ except Exception as error:
+ self.log.append('Resource monitor unavailable: ' + str(error))
+
+ def check_processing_resources(self):
+ if not self.processing_guard or not self.process:return
+ message = self.processing_guard.check()
+ if message:
+ self.failed = True
+ self.cancel_job()
+ self.status.setText(message)
+ self.log.append(message)
+ self.guard_timer.stop()
+ if getattr(self,'job_project',None) is not None:
+ from .storage import atomic_json
+ path=self.job_project/'project.json'
+ try:
+ state=json.loads(path.read_text(encoding='utf-8'))
+ state.setdefault('stages',{})[self._batch_inner_stage]={'status':'failed','error':message}
+ atomic_json(path,state)
+ except (OSError,ValueError) as error:self.log.append('Could not save stopped stage: '+str(error))
+
+ def read_stdout(self):
+ if self.processing_guard:self.processing_guard.output()
+ self.buffer += bytes(self.process.readAllStandardOutput()).decode("utf-8", errors="replace")
+ if len(self.buffer) > 65536 and "\n" not in self.buffer:
+ self.buffer = self.buffer[-65536:]
+ while "\n" in self.buffer:
+ line, self.buffer = self.buffer.split("\n", 1)
+ if line.startswith("@@MOCAP@@"):
+ try:
+ self.handle_event(json.loads(line[len("@@MOCAP@@"):]))
+ except (ValueError, KeyError) as error:
+ self.log.append(str(error))
+ elif line.strip():
+ self.log.append(line.rstrip())
+
+ def read_stderr(self):
+ if self.processing_guard:self.processing_guard.output()
+ self.log.append(bytes(self.process.readAllStandardError()).decode("utf-8", errors="replace").strip()[-8192:])
+
+ def handle_event(self, event):
+ kind = event["type"]
+ self.single_tracking_event(event)
+ if self.people_event(event):
+ self._queued_task_estimates=[self.task_descriptor(s,a) for s,a in self.jobs]
+ self.update_task_progress();return
+ if kind=='batch_item_start':
+ self.job_project=Path(event['project']);self._batch_inner_stage=event['stage']
+ self._task_actor=f"Actor/take {event['index']}/{event['count']}"
+ self.task_state.update(dict(current=0,total=0,phase=f"batch:{event['phase']}:{event['index']}",message='Loading actor data'),time.monotonic())
+ self.status.setText(self._task_actor+' · '+STAGES.get(event['stage'],event['stage']))
+ self.update_task_progress()
+ elif kind=='mamma_ready':
+ self.workspace_root=Path(event['root'])
+ self.load_project(Path(event['project']))
+ self.set_active_result(event['result'])
+ elif kind == "prepared":
+ self._task_preparing=False
+ self._task_manifests={}
+ self.project = Path(event["project"])
+ from .project_storage import storage_root
+ saved_root=storage_root(self.project)
+ from .project_workspace import is_workspace
+ if saved_root is not None and not is_workspace(saved_root):
+ from .storage import atomic_json
+ atomic_json(saved_root/'workspace_state.json',dict(version=1,name=saved_root.name,
+ active=self.project.resolve().relative_to(saved_root).as_posix(),frame=0,trim=None))
+ self.load_project(self.project)
+ elif kind == 'project_saved':
+ self._project_saved_root=Path(event['root'])
+ elif kind == 'save_cancelled':
+ self.cancelled=True
+ self.status.setText(event['message'])
+ elif kind == 'resource_mode':
+ self.log.append(event['message'])
+ elif kind == "progress":
+ message=event.get('message','Processing...')
+ self.log.status_terminal(message)
+ self.status.setText((self._task_actor+' · ' if getattr(self,'_task_actor','') else '')+message)
+ self.task_state.update(event,time.monotonic())
+ self.update_task_progress()
+ elif kind == "diagnostics":
+ data = event["result"]
+ self.log.append(json.dumps(data, ensure_ascii=False, indent=2))
+ self.hardware_summary = f"{data.get('gpu', 'GPU unavailable')} · RAM {data.get('ram_gib', '?')}GB · CUDA check {'Passed' if data.get('cuda_matmul_verified') else 'Unavailable'}"
+ self.status.setText(self.hardware_summary)
+ elif kind in {"failed", "blocked"}:
+ self.failed = True
+ self.task_timer.stop();self.task_info.setText('Failed')
+ self.status.setText("Processing failed. " + event.get("message", "See the console for details."))
+ self.log.append(self.status.text())
+ elif kind == "complete":
+ if not event.get('batch_inner'):self.task_state.cached|=bool(event.get('cached',False))
+ self.log.append(f"{STAGES.get(event['stage'])}: {event.get('elapsed', 0):.2f} s · {event.get('output')}")
+ self.log.ensureCursorVisible()
+
+ def process_finished(self, code, _):
+ self.read_stdout()
+ self.read_stderr()
+ if code != 0 and not self.cancelled:
+ self.failed = True
+ if "failed" not in self.status.text():
+ self.status.setText("Processing stopped. See the console for details.")
+ self.process.deleteLater()
+ self.process = None
+ self.task_state.finish(time.monotonic(),not self.failed and not self.cancelled and code==0)
+ self.cleanup_fbx_export()
+ self.next_job()
+
+ def process_error(self, error):
+ if error == QProcess.FailedToStart:
+ self.character_refresh_queue=[]
+ self.task_timer.stop();self.task_state.active=False;self.task_info.setText('Failed to start')
+ self.guard_timer.stop()
+ self.processing_guard = None
+ if self.process is not None:
+ self.process.deleteLater()
+ self.process = None
+ self.jobs.clear()
+ self.cleanup_fbx_export()
+ self.cleanup_batch_request()
+ self.cleanup_project_save()
+ self.failed = True
+ self.busy = False
+ self.finish_single_tracking()
+ self.finish_people_jobs()
+ self.status.setText("Cannot start the processing engine. Check the app installation.")
+ self.update_readiness()
+
+ def cancel_job(self):
+ if self.character_process is not None:
+ self.cancel_character();return
+ if self.current_stage=='save_project' and getattr(self,'_project_save_request',None):
+ self._project_save_request.with_suffix('.cancel').touch()
+ self.task_info.setText('Stopping...')
+ self.status.setText('Cancelling project save...')
+ self.cancel_button.setEnabled(False)
+ return
+ from shiboken6 import isValid
+ pending=getattr(self,'cancel_process',None)
+ if pending is not None and isValid(pending) and pending.state()!=QProcess.NotRunning:
+ return
+ self.task_timer.stop();self.task_state.active=False;self.task_info.setText('Stopping...')
+ self.guard_timer.stop()
+ self.cancelled = True
+ self.jobs.clear()
+ worker = self.process
+ if worker and isValid(worker) and worker.processId():
+ if os.name == "nt":
+ # Stop FFmpeg/other descendants before losing their parent PID.
+ helper = QProcess(self)
+ self.cancel_process = helper
+ def fallback(error):
+ if error == QProcess.FailedToStart and self.process is worker and isValid(worker):
+ worker.kill()
+ if error == QProcess.FailedToStart:
+ if self.cancel_process is helper:self.cancel_process=None
+ if isValid(helper):helper.deleteLater()
+ helper.errorOccurred.connect(fallback)
+ def cancelled(code, _):
+ if code and self.process is worker and isValid(worker):
+ worker.kill()
+ if self.cancel_process is helper:self.cancel_process=None
+ if isValid(helper):helper.deleteLater()
+ helper.finished.connect(cancelled)
+ helper.start("taskkill.exe", ["/PID", str(worker.processId()), "/T", "/F"])
+ else:
+ worker.kill()
+ self.status.setText("Cancelled. Completed stages will be reused next time.")
+
+ def refresh_results(self):
+ if self.project:
+ signature = project_signature(self.project)
+ if signature != self.preview_signature:
+ self.preview_signature = signature
+ self.data_loader.request(self.project)
+ elif self.preview_data is not None:
+ self.apply_preview()
+
+ def clear_preview(self):
+ self.preview_help.setText('')
+ self.pelvis_auto_note.setText('Automatic lowering varies by frame.')
+ self.data_loader.cancel()
+ self.preview_signature = None
+ self.slider.has_motion = False
+ self.slider.update()
+ self.video_view.set_observations({})
+ self.motion_view.set_motion(None)
+ self.refine_preview_note.hide()
+ self.correction_note.hide()
+ self.contact_tracks.clear()
+ self.slider.set_contacts(None,identity=None,token=None)
+ if self.preview_data is not None:
+ self.preview_data.close()
+ self.preview_data = None
+
+ @batch_readiness
+ def preview_ready(self, generation, result):
+ if generation != self.data_loader.generation:
+ result.close()
+ return
+ if result.signature != project_signature(result.project):
+ # The worker committed another generation during loading. Never
+ # pair these arrays with the new on-disk receipts.
+ result.close()
+ self.preview_signature=None
+ self.refresh_results()
+ return
+ self.video_view.set_observations({})
+ previous=self.preview_data
+ preserve_view=previous is not None and previous.project==result.project
+ auto_fit=self.motion_view.auto_fit
+ if preserve_view:self.motion_view.auto_fit=False
+ self.preview_data = result
+ self.contact_tracks=dict(getattr(result,'contact_tracks',{}))
+ try:self.apply_preview()
+ finally:
+ self.motion_view.auto_fit=auto_fit
+ self.restore_workspace_camera(consume=True)
+ if previous is not None:previous.close()
+
+ @batch_readiness
+ @read_only_checks
+ def apply_preview(self):
+ data = self.preview_data
+ signature=project_signature(data.project)
+ if data.signature != signature:
+ # Hide stale payloads without forgetting this project's camera
+ # anchor while the next committed correction is loading.
+ self.motion_view.set_motion(None,path=data.project/(self.active_result+'_joints.npz'))
+ self.slider.has_motion=False;self.slider.update()
+ if not self.busy and signature!=self.preview_signature:self.refresh_results()
+ return
+ self.video_view.set_observations(data.arrays)
+ display_kind=self.active_result
+ name = display_kind + "_joints"
+ corrected=self.active_result.startswith('corrected_')
+ from .result_artifacts import artifacts_current
+ coherent=artifacts_current(self.project,display_kind)
+ current=coherent and result_is_current(self.project,display_kind)
+ pending=coherent and corrected and not current and result_is_current(self.project,display_kind,ignore_contacts=True)
+ available = name in data.arrays and (current or pending)
+ self.correction_note.hide()
+ self.refine_preview_note.hide()
+ if not available:
+ result = {"initial":MOTION_TOOLS[self.model_choice.currentData()].label, "refined":"HTD", "footmr_initial":"FootMR", "footmr_refined":"HTD + FootMR"}[body_result(self.active_result)]
+ if has_handflow(self.active_result):result += " + HandFlow"
+ note=self.correction_note if corrected else self.refine_preview_note
+ missing_hand=has_handflow(self.active_result) and not result_is_current(self.project,base_result(self.active_result))
+ note.setText('No current HandFlow preview. Run Reconstruct 3D to infer finger motion.' if missing_hand else
+ 'Correction settings changed or result unavailable.\nUse Apply Correction to update the preview.' if corrected else f"No {result} preview yet. Run Reconstruct 3D to create it.")
+ note.show()
+ warning=' '.join(filter(None,(data.summaries.get(name,{}).get('correction_warning',''),data.summaries.get(name,{}).get('handflow_warning',''))))
+ pelvis_summary=data.summaries.get(name,{})
+ auto_drop=pelvis_summary.get('pelvis_auto_drop') if corrected else None
+ self.pelvis_auto_note.setText('Automatic lowering varies by frame.' if auto_drop is None else
+ f'Last applied: automatic lowering up to {auto_drop*100:.1f} cm; '
+ f'automatic crouch lift up to {pelvis_summary.get("pelvis_auto_raise",0.)*100:.1f} cm; '
+ f'user lift up to {pelvis_summary.get("pelvis_applied_lift",0.)*100:.1f} cm.')
+ if self.people_root is not None:
+ self.sync_shared_floor_controls()
+ elif available and self.auto_floor.isChecked():
+ self.floor_height.blockSignals(True)
+ self.floor_height.setValue(float(data.summaries[name]['floor']))
+ self.floor_height.blockSignals(False)
+ if available and warning:
+ self.correction_note.setText(warning);self.correction_note.show()
+ if available and pending:
+ self.correction_note.setText('Contact-lock timing changed. Preview shows the last applied correction.\nApply Correction to update the motion and FBX.');self.correction_note.show()
+ self.slider.has_motion = available
+ self.slider.update()
+ overlay_name=self.active_result+'_joints'
+ overlay_current=artifacts_current(self.project,self.active_result) and result_is_current(self.project,self.active_result,ignore_contacts=True)
+ overlay_available=overlay_current and overlay_name in data.arrays
+ from .bone_overlay import preview_current
+ target_current=overlay_available and preview_current(self.project,self.active_result,data.target_info.get(self.active_result))
+ camera_name=name if available else overlay_name
+ rig_points=data.arrays.get(camera_name)
+ # Source pose is the comparison reference. Never deform this surface
+ # to make an imperfect export skeleton appear to fit it exactly.
+ selected_mesh=None
+ # Preserve a selected legacy baked preview if the export skin has not
+ # been prepared yet. Never pair it with a different result's bones.
+ self.motion_view.set_motion((rig_points if rig_points is not None else data.arrays.get(camera_name)) if available or overlay_available else None,
+ data.summaries.get(camera_name),data.project/(camera_name+'.npz'),
+ rotations=data.arrays.get(camera_name.replace('_joints','_rotations')) if available or overlay_available else None,
+ mesh_frames=(selected_mesh if selected_mesh is not None else data.arrays.get(name.replace('_joints','_mesh'))) if available else None,mesh_asset=data.mesh_asset)
+ self.motion_view.target_frames=data.arrays.get(self.active_result+'_rig') if target_current else None
+ self.motion_view.target_asset=data.target_assets.get(self.active_result) if target_current else None
+ self.motion_view.mesh_binding=self.motion_view.target_asset.get('binding') if selected_mesh is not None and self.motion_view.target_asset else None
+ self.motion_view.raw_asset=None
+ self.motion_view.native_vertices=None
+ self.motion_view.native_required=False
+ if self.model_choice.currentData()=='flowhmr':
+ self.motion_view.raw_asset=self.motion_view.target_asset
+ self.motion_view.native_vertices=data.arrays.get(self.active_result+'_native') if target_current else None
+ self.motion_view.native_required=True
+ info=data.target_info.get(self.active_result,{})
+ warning=info.get('correction',{}).get('warning','')
+ source_warning=data.summaries.get(name,{}).get('correction_warning','') if corrected else ''
+ if source_warning and source_warning not in warning:warning=' '.join(filter(None,(warning,source_warning)))
+ help_text='The skeleton is fitted to the selected motion mesh. Small differences may remain.'
+ if info.get('fit_version',0)>=15:
+ help_text='The skeleton follows the selected motion mesh, with steadier arm and leg directions. Errors in the AI motion may remain.'
+ if corrected:
+ short=int(pelvis_summary.get('short_contact_segments',0))
+ if short:help_text+=f'\n{short} short foot-lock intervals never reach full strength because of boundary blending.'
+ notices=[]
+ if not available and corrected:notices.append('Selected motion unavailable. Use Apply Correction to update the preview.')
+ if warning:notices.append(warning)
+ selected_fit=info.get('selected_source_fit',{})
+ if selected_fit:
+ help_text+=f'\nSkeleton fit: mean {selected_fit["mean_m"]*100:.1f} cm; max {selected_fit["max_m"]*100:.1f} cm.'
+ facing=selected_fit.get('anatomical_facing_deg',{})
+ for label,joints in (('Knee',('LeftLeg','RightLeg')),('Elbow',('LeftForeArm','RightForeArm'))):
+ values=[facing[j] for j in joints if j in facing]
+ if values:help_text+=f'\n{label} anatomical axis vs AI source: mean {sum(v["mean"] for v in values)/len(values):.1f}°; max {max(v["max"] for v in values):.1f}°.'
+ fitted=info.get('selected_source_fit',info.get('source_fit',{})).get('joints',{})
+ elbow_offset=max((fitted.get(side+'ForeArm',fitted.get('mixamorig:'+side+'ForeArm',{})).get('max_m',0.) for side in ('Left','Right')),default=0.)
+ if elbow_offset>.08:
+ notices.append(f'Elbow pose differs from AI source (up to {elbow_offset*100:.1f} cm) after anatomical alignment.')
+ if self.model_choice.currentData()=='flowhmr':
+ from .flow_placement import needs_update
+ if needs_update(self.project):notices.append('FlowHMR scene placement needs updating. Use Prepare Preview; no AI inference is required.')
+ knee_offset=max((fitted.get(side+'Leg',{}).get('max_m',0.) for side in ('Left','Right')),default=0.)
+ if knee_offset>.08:notices.append(f'Knee pose differs from AI source (up to {knee_offset*100:.1f} cm) after anatomical alignment.')
+ self.bone_overlay.setToolTip(tooltip_text('Show the skeleton used for FBX export. Display only.\n'
+ 'In Blender, use Scale 1 and leave Automatic Bone Orientation off to keep its axes.\n'+help_text))
+ if available and pending:notices.append('Contact-lock timing changed. Preview shows the last applied correction. Apply Correction to update the motion and FBX.')
+ if corrected and available and not pending and not result_is_current(self.project,self.active_result):notices.append('The last applied correction is outdated or unavailable. Apply Correction before export.')
+ self.preview_help.setText(help_text)
+ self.correction_note.setText('\n'.join(dict.fromkeys(notices)));self.correction_note.setVisible(bool(notices))
+ if available and self.motion_view.target_asset is None and not self.busy and os.environ.get('QT_QPA_PLATFORM')!='offscreen' and (self.project/RESULTS[base_result(self.active_result)][0]).is_file():
+ token=(str(self.project),self.active_result,self.preview_signature)
+ attempts=getattr(self,'_rig_attempts',deque(maxlen=16))
+ if token not in attempts:
+ attempts.append(token);self._rig_attempts=attempts
+ QTimer.singleShot(0,self.prepare_target_preview)
+ self.update_foot_contacts()
+ self.update_readiness()
+
+ def preview_failed(self, generation, message):
+ if generation == self.data_loader.generation:
+ changed=self.project is not None and self.preview_signature!=project_signature(self.project)
+ self.preview_signature = None
+ if changed:
+ self.refresh_results()
+ return
+ self.status.setText("Cannot load the motion preview. " + message)
+
+ def save_fbx(self):
+ if self.selected_character() is not None:
+ self.export_character(self.selected_character());return
+ if self.export_checked_people():return
+ source = self.current_export()
+ if source:
+ from .person_names import export_stem
+ default=export_stem(self.export_person_name(self.project))+'.fbx'
+ name, _ = QFileDialog.getSaveFileName(self, "Export FBX", default, "FBX (*.fbx)")
+ if name:
+ self.submit_fbx_exports([(self.project,self.active_result,source,Path(name))])
+
+ def submit_fbx_exports(self,files):
+ if self.busy:return
+ import uuid
+ from .storage import atomic_json
+ request=self.project/('.fbx-export-'+uuid.uuid4().hex+'.json')
+ rows=[]
+ try:
+ for project,kind,source,target in files:
+ row=dict(project=str(project),kind=kind,source=str(source),target=str(target))
+ row['rig_name']=self.export_person_name(project)
+ if self.people_root is not None:
+ from .scene_export import context
+ row['scene']=context(self.people_root,project)
+ rows.append(row)
+ except (OSError,ValueError,KeyError) as error:
+ self.status.setText('Cannot export shared scene: '+str(error));return
+ atomic_json(request,rows)
+ self._fbx_export_cleanup=(request,[target.with_name('.'+target.name+'.rgbmocap-'+request.stem+'.partial') for _,_,_,target in files])
+ self.start_jobs([('save_fbx',['--project',str(self.project),'--output',str(request)])])
+
+ def cleanup_fbx_export(self):
+ pending=getattr(self,'_fbx_export_cleanup',None)
+ if pending:
+ request,paths=pending
+ for path in [request,*paths]:
+ try:path.unlink(missing_ok=True)
+ except OSError:pass
+ self._fbx_export_cleanup=None
+
+ def open_folder(self):
+ from .project_storage import storage_root
+ target = self.workspace_root or ((storage_root(self.project) or self.project) if self.project else PROJECTS)
+ target.mkdir(parents=True, exist_ok=True)
+ QDesktopServices.openUrl(QUrl.fromLocalFile(str(target)))
+
+ def dragEnterEvent(self, event):
+ if event.mimeData().hasUrls() and not self.busy:
+ event.acceptProposedAction()
+
+ def dropEvent(self, event):
+ urls = event.mimeData().urls()
+ if urls and not self.busy:
+ if self.model_choice.currentData()=='mamma':self.load_mamma_videos([Path(url.toLocalFile()) for url in urls])
+ else:self.load_video(Path(urls[0].toLocalFile()))
+
+ def closeEvent(self, event):
+ if self.busy and self.process:
+ answer = QMessageBox.question(self, "Processing", "Cancel the current job and close the application?")
+ if answer != QMessageBox.Yes:
+ event.ignore()
+ return
+ self.cancel_job()
+ worker = self.process
+ if worker:
+ worker.waitForFinished(3000)
+ if self.character_process is not None:
+ self.cancel_character();self.character_process.waitForFinished(5000)
+ self.character_loader.close()
+ self.task_timer.stop()
+ if self.workspace_root is not None:
+ try:self.remember_workspace_model()
+ except (OSError,ValueError) as error:self.log.append('Could not save project view: '+str(error))
+ self.shutdown_preview()
+ event.accept()
diff --git a/mocap/gvhmr_attention.py b/mocap/gvhmr_attention.py
index c3cc7c8..e4b4d9d 100644
--- a/mocap/gvhmr_attention.py
+++ b/mocap/gvhmr_attention.py
@@ -36,6 +36,8 @@ def predict(model,data,project,emit):
if not failed:return result
# Never shrink the temporal/key context or move silently to a CPU backend.
gc.collect();torch.cuda.empty_cache()
+ from .memory_mode import announce
+ announce('GVHMR temporal attention','low_memory','Automatic full-context query-split recovery after CUDA memory pressure.',emit)
free,total=capacity()
low=gvhmr_plan(frames,0,total)
if frames<=2048:
diff --git a/mocap/mamma_camera.py b/mocap/mamma_camera.py
index f0099e5..b63a6b6 100644
--- a/mocap/mamma_camera.py
+++ b/mocap/mamma_camera.py
@@ -47,19 +47,22 @@ def infer(work,job,emit):
if not cv2.imwrite(str(path),im):raise OSError('Cannot prepare a VGGT input image.')
paths.append(str(path));sizes.append((w,h,_balanced_target_shape(h/w,512,16)));camera_ids.append(c)
emit('progress',current=0,total=0,message=f'VGGT: estimate {len(entries)} fixed cameras from {len(paths)} background images')
- model=VGGTOmega(enable_depth=False).eval()
- state=torch.load(BY_KEY['flow_vggt'].path,map_location='cpu',mmap=True,weights_only=False)
- model.load_state_dict({k:v for k,v in state.items() if not k.startswith('dense_head.')})
- del state;gc.collect();model=model.cuda()
- images=load_and_preprocess_images(paths,mode='balanced',image_resolution=512).cuda()
- with torch.inference_mode():
- prediction=model(images);E,K=encoding_to_camera(prediction['pose_enc'],images.shape[-2:])
- E=E[0].cpu().numpy();K=K[0].cpu().numpy();H,W=images.shape[-2:]
+ from .memory_mode import run as memory_run
+ from .gpu_offload import load_vggt,release
+ def predict(low):
+ model=load_vggt(BY_KEY['flow_vggt'].path,'cuda',low_memory=low)
+ try:
+ images=load_and_preprocess_images(paths,mode='balanced',image_resolution=512).cuda()
+ with torch.inference_mode():
+ prediction=model(images);E,K=encoding_to_camera(prediction['pose_enc'],images.shape[-2:])
+ return E[0].cpu().numpy(),K[0].cpu().numpy(),*images.shape[-2:]
+ finally:release(model)
+ E,K,H,W=memory_run('MAMMA VGGT camera',predict,6.+.1*len(paths),emit)
for i,(w,h,(hh,ww)) in enumerate(sizes):
K[i,0,2]-=(W-ww)//2;K[i,1,2]-=(H-hh)//2
K[i,0,:]*=w/ww;K[i,1,:]*=h/hh
if not np.isfinite(E).all() or not np.isfinite(K).all():raise ValueError('VGGT returned invalid cameras.')
- del model,images,prediction;gc.collect();torch.cuda.empty_cache()
+ gc.collect();torch.cuda.empty_cache()
ci=np.array(camera_ids);RR=[];tt=[];KK=[]
for c in range(len(entries)):
es=E[ci==c];r=Rotation.from_matrix(es[:,:,:3]).mean().as_matrix()
diff --git a/mocap/mamma_pipeline.py b/mocap/mamma_pipeline.py
index a6e5068..39ce0c5 100644
--- a/mocap/mamma_pipeline.py
+++ b/mocap/mamma_pipeline.py
@@ -99,7 +99,7 @@ def prepare(path, job):
# All connector code contributes, not just the model prediction script.
from .paths import ROOT
from .storage import sha256
- identity['code']={name:sha256(ROOT/'mocap'/name) for name in ('mamma_pipeline.py','mamma_camera.py','mamma_inputs.py')}
+ identity['code']={name:sha256(ROOT/'mocap'/name) for name in ('mamma_pipeline.py','mamma_camera.py','mamma_inputs.py','memory_mode.py','gpu_offload.py')}
token=hashlib.sha256(json.dumps(identity,sort_keys=True).encode()).hexdigest()[:24]
slot=job['root']/'mamma'/'inference'/token
cached=False
@@ -308,6 +308,9 @@ def main(argv=None,engine=None):
torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
if not torch.cuda.is_available():raise RuntimeError('MAMMA requires a supported CUDA GPU.')
free,total=torch.cuda.mem_get_info();torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
+ if args.stage!='mamma_camera':
+ from .memory_mode import select_stage
+ select_stage(args.stage,free,total,job['frames'],emit)
work=work_for(job)
if args.stage=='mamma_masks':masks(engine,work,job)
elif args.stage=='mamma_landmarks':landmarks(engine,work,job)
@@ -320,5 +323,9 @@ def main(argv=None,engine=None):
return 0
except Exception as error:
traceback.print_exc()
- emit('failed',message=str(error))
+ message=str(error)
+ if isinstance(error,MemoryError) or 'out of memory' in message.lower():
+ from .memory_mode import GUIDANCE
+ message='Processing ran out of memory and stopped safely. '+GUIDANCE
+ emit('failed',message=message)
return 1
diff --git a/mocap/mamma_ui.py b/mocap/mamma_ui.py
index e56b1f8..7727c5b 100644
--- a/mocap/mamma_ui.py
+++ b/mocap/mamma_ui.py
@@ -98,7 +98,8 @@ class MammaWorkspace:
def build_mamma_settings(self):
page=QWidget();page.setProperty('motion_tool','mamma')
- box=QVBoxLayout(page);box.setContentsMargins(8,0,8,0)
+ box=QVBoxLayout(page);box.setContentsMargins(0,0,0,0)
+ box.setSpacing(10);box.setAlignment(Qt.AlignTop)
box.addWidget(QLabel('Camera Calibration'))
self.mamma_camera_mode=QComboBox()
self.mamma_camera_mode.addItem('VGGT (Automatic)','vggt')
diff --git a/mocap/memory_mode.py b/mocap/memory_mode.py
new file mode 100644
index 0000000..d29dce2
--- /dev/null
+++ b/mocap/memory_mode.py
@@ -0,0 +1,108 @@
+"""Per-operation resource selection; never changes precision or saved UI settings."""
+import gc
+import os
+from contextlib import contextmanager
+from .compute_policy import GIB, gpu_reserve
+
+VERSION = 1
+GUIDANCE = ('For memory shortages, select Processing Resources > Resource Mode > Low Memory. '
+ 'CPU loading/offloading can be slower and use more RAM. Close other apps '
+ 'or trim the clip if memory is still insufficient.')
+
+
+def requested_mode():
+ return 'low_memory' if os.environ.get('RGB_MOCAP_COMPUTE_MODE') == 'low_memory' else 'auto'
+
+
+def effective_mode():
+ return os.environ.get('RGB_MOCAP_EFFECTIVE_MODE', requested_mode())
+
+
+def decide(requested, available, required):
+ """Advisory routing only: insufficient estimates never reject a job."""
+ return 'low_memory' if requested == 'low_memory' or available < required else 'auto'
+
+
+def available_vram():
+ import torch
+ free, total = torch.cuda.mem_get_info()
+ # The allocator cap was chosen when this worker started. Other apps can
+ # change free memory later; respect both limits without subtracting twice.
+ cap = torch.cuda.get_per_process_memory_fraction() * total
+ alloc = torch.cuda.memory_allocated()
+ from .model_session import current
+ session = current()
+ if session is not None:
+ cached = max(0, torch.cuda.memory_reserved() - alloc)
+ additional = max(0, min(free + cached - gpu_reserve(total), cap - alloc))
+ return additional + session.resident_bytes
+ room = cap - torch.cuda.memory_reserved() + alloc
+ return max(0, min(free - gpu_reserve(total), room))
+
+
+def announce(stage, mode, reason, emit=None):
+ selected = 'Low Memory' if mode == 'low_memory' else 'Automatic / fast path'
+ message = f'Resources [{stage}]: {selected}. {reason}'
+ if mode == 'low_memory':
+ message += ' ' + GUIDANCE
+ if emit:
+ emit('resource_mode', stage=stage, mode=mode, requested=requested_mode(), message=message)
+ else:
+ import json
+ print('@@MOCAP@@' + json.dumps(dict(type='resource_mode', stage=stage, mode=mode,
+ requested=requested_mode(), message=message)), flush=True)
+
+
+@contextmanager
+def effective(mode):
+ previous = os.environ.get('RGB_MOCAP_EFFECTIVE_MODE')
+ os.environ['RGB_MOCAP_EFFECTIVE_MODE'] = mode
+ try:
+ yield
+ finally:
+ if previous is None:os.environ.pop('RGB_MOCAP_EFFECTIVE_MODE', None)
+ else:os.environ['RGB_MOCAP_EFFECTIVE_MODE'] = previous
+
+
+def run(stage, operation, fast_gib, emit=None):
+ """Retry a fresh, scoped operation once after leaving the OOM traceback.
+
+ operation(low_memory) must own its models/captures and publish no partial
+ result. The caller commits only the returned complete CPU output.
+ """
+ import torch
+ available = available_vram()
+ from .model_session import current
+ session = current()
+ selected = decide('low_memory' if session is not None and session.force_low else requested_mode(), available, fast_gib * GIB)
+ reason = ('Selected by the user.' if requested_mode() == 'low_memory' else
+ f'Available GPU budget {available/GIB:.2f} GiB; fast-path estimate {fast_gib:.2f} GiB.')
+ announce(stage, selected, reason, emit)
+ failed = False
+ try:
+ with effective(selected):
+ return operation(selected == 'low_memory')
+ except torch.cuda.OutOfMemoryError:
+ if selected == 'low_memory':raise
+ failed = True
+ if failed:
+ if session is not None:
+ session.discard()
+ session.force_low = True
+ gc.collect()
+ torch.cuda.empty_cache()
+ announce(stage, 'low_memory', 'Automatic recovery after CUDA ran out of memory; retrying once.', emit)
+ with effective('low_memory'):
+ return operation(True)
+
+
+def select_stage(stage, free, total, frames, emit):
+ """Existing GVHMR/add-on policies keep full temporal/precision settings."""
+ from .compute_policy import gvhmr_plan
+ estimate = {'track':1., 'people':1.5, 'pva':5.5, 'features':4.5,
+ 'refine':3., 'footmr':5., 'handflow':5.}.get(stage, 3.) * GIB
+ if stage == 'gvhmr':estimate = gvhmr_plan(frames, free, total)['dense_estimated_bytes']
+ mode = decide(requested_mode(), max(0, free - gpu_reserve(total)), estimate)
+ os.environ['RGB_MOCAP_EFFECTIVE_MODE'] = mode
+ announce(stage, mode, 'Using the stage memory budget; model precision and temporal context are unchanged.', emit)
+ return mode
diff --git a/mocap/model_guide.py b/mocap/model_guide.py
index 01ac680..9a283b2 100644
--- a/mocap/model_guide.py
+++ b/mocap/model_guide.py
@@ -1,4 +1,4 @@
-"""Compact model comparison using the same recorded seven-second clip."""
+"""Compact model comparison with recorded input and measurement conditions."""
from PySide6.QtCore import Qt
from PySide6.QtGui import QDesktopServices, QTextOption
from PySide6.QtWidgets import QApplication, QDialog, QHBoxLayout, QPushButton, QTextBrowser, QVBoxLayout
@@ -6,10 +6,13 @@ from .motion_tools import MOTION_TOOLS
# exmr-eval-2026-10-22/summary-body.json, clip_01 (210 frames at 30 fps).
# Historical processing-only runs; FlowHMR predates Fast SAM.
+# MAMMA: separate 413-frame/three-view manual run (SAM 2.1, VGGT, two people).
+# Time includes correction/preview; memory is measured across four inference workers.
BENCHMARKS = {
- 'gvhmr': ('2m 01s', '5.08', '12.47'),
- 'flowhmr': ('2m 49s', '14.89', '22.19'),
- 'exmr': ('1m 08s', '11.32', '19.31'),
+ 'gvhmr': ('7s<br>1 video', '2m 01s', '5.08', '12.47'),
+ 'flowhmr': ('7s<br>1 video', '2m 49s', '14.89', '22.19'),
+ 'exmr': ('7s<br>1 video', '1m 08s', '11.32', '19.31'),
+ 'mamma': ('13.8s<br>3 videos<br>2 people', '11m 52s', '6.47', '9.11'),
}
PROJECT_URLS = {
'mamma': 'https://mamma.is.tue.mpg.de/',
@@ -42,18 +45,19 @@ th { text-align:left; background-color:#333333; } td, th { padding:7px; }
<h3>Choosing a model</h3>
<p>These are subjective observations from our test videos, not a universal ranking or accuracy benchmark.
Try another model if a particular movement looks wrong.</p>""" + descriptions + """
-<h3>Recorded speed test: HIGHEST BACKFLIP · 7 seconds</h3>
-<table width="100%" border="0" cellspacing="1" cellpadding="7">
-<tr><th>Model</th><th>Processing time</th><th>Peak VRAM (GiB)</th><th>Peak RAM (GiB)</th></tr>""" + rows + """</table>
+<h3>Recorded processing time and memory</h3>
+<table width="98%" border="0" cellspacing="1" cellpadding="7">
+<tr><th>Model</th><th>Input</th><th>Processing time</th><th>Peak VRAM (GiB)</th><th>Peak RAM (GiB)</th></tr>""" + rows + """</table>
<p>Test PC: RTX 5090 32 GB · Ryzen 9 9950X · 96 GB RAM.</p>
<p>GVHMR: HTD + FootMR + HandFlow on. FlowHMR: original SAM; today's Fast SAM can
-be faster. Recorded processing only, excluding tracking, app correction and export.
-Memory shows measured worker peaks, not minimum requirements. Results vary by video and PC.</p>
-<h3>MAMMA: separate multi-view workflow</h3>
-<p>A manual app test with three 1080p-bounded camera videos, two people and 413 frames at 30 fps
-took 11m 52s through correction and preview on the test PC. Masks: 4m 18s; landmarks: 1m 30s;
-VGGT cameras: 14s; 3D fitting: 4m 54s; correction/preview: 32s. This is a different clip and workflow
-from the table above, so it is not a direct speed comparison. Start with a short common trim.</p>
+be faster. These three models used the same seven-second clip; their times exclude
+tracking, app correction and preview/export.</p>
+<p>MAMMA used a different clip: three synchronized videos resized within 1920×1080,
+two people and 413 frames at 30 fps. Its time includes preparation, correction and preview;
+memory covers masks, landmarks, VGGT and 3D fitting. This is not a direct speed comparison.</p>
+<p>VRAM is peak PyTorch allocated memory, not total GPU usage. Single-video RAM is peak
+private memory; MAMMA RAM is peak worker working set. These historical measurements predate
+the latest Low Memory changes and are not minimum requirements. Results vary by input and PC.</p>
<p>All four support Motion Correction for foot and hand contacts. Contact correction reduces sliding;
it is separate from tracking fingers or refining ankle angles.</p></body></html>"""
diff --git a/mocap/model_session.py b/mocap/model_session.py
new file mode 100644
index 0000000..2c58264
--- /dev/null
+++ b/mocap/model_session.py
@@ -0,0 +1,108 @@
+"""One resident model per worker phase; no cross-tool or cross-job global pool."""
+from contextvars import ContextVar
+from contextlib import contextmanager
+import gc
+
+_active = ContextVar('mocap_model_session', default=None)
+
+
+def current():
+ return _active.get()
+
+
+def model_key(name, *paths, **settings):
+ from pathlib import Path
+ files = []
+ for path in paths:
+ path = Path(path).resolve()
+ stat = path.stat()
+ files.append((str(path), stat.st_size, stat.st_mtime_ns))
+ return name, tuple(files), tuple(sorted(settings.items()))
+
+
+def dispose(model):
+ # Feature collectors must not retain GPU activations or form a hook cycle.
+ for hook in getattr(model, '_hooks', ()):
+ hook.remove()
+ for name in ('_body_tokens','_hand_tokens'):
+ values=getattr(model,name,None)
+ if values is not None:values.clear()
+ for values in getattr(model, '_flow_fast_collectors', ()):
+ values.clear()
+ close = getattr(model, 'close', None)
+ if close is not None:close()
+ inner = getattr(getattr(model, 'estimator', None), 'model', model)
+ from .gpu_offload import release
+ release(inner)
+
+
+class ModelSession:
+ def __init__(self):
+ self.key = self.value = None
+ self.resident_bytes = 0
+ self.cap_set = False
+ self.force_low = False
+
+ def acquire(self, key, factory):
+ if self.value is not None and key == self.key:return self.value
+ self.discard()
+ import torch
+ before = torch.cuda.memory_allocated() if torch.cuda.is_initialized() else 0
+ value = factory()
+ self.key, self.value = key, value
+ self.resident_bytes = max(0, torch.cuda.memory_allocated() - before) if torch.cuda.is_initialized() else 0
+ return value
+
+ def discard(self):
+ value, self.value = self.value, None
+ self.key = None
+ self.resident_bytes = 0
+ try:
+ if value is not None:dispose(value)
+ finally:
+ del value
+ gc.collect()
+ import torch
+ if torch.cuda.is_initialized():torch.cuda.empty_cache()
+
+ @contextmanager
+ def activate(self):
+ if current() is not None:raise RuntimeError('Nested model sessions are not supported')
+ token = _active.set(self)
+ try:yield self
+ finally:
+ try:self.discard()
+ finally:_active.reset(token)
+
+
+def acquire(key, factory):
+ session = current()
+ return factory() if session is None else session.acquire(key, factory)
+
+
+def release(model):
+ session = current()
+ if session is None or session.value is not model:dispose(model)
+ else:
+ # Clear only transient tokens; the weights and their one hook stay live.
+ if hasattr(model, '_tokens'):model._tokens = None
+ for name in ('_body_tokens','_hand_tokens'):
+ values=getattr(model,name,None)
+ if values is not None:values.clear()
+ for values in getattr(model, '_flow_fast_collectors', ()):values.clear()
+
+
+def reusable_bytes():
+ session = current()
+ return session.resident_bytes if session is not None else 0
+
+
+def set_memory_budget(free, total):
+ import torch
+ from .compute_policy import gpu_memory_fraction
+ session = current()
+ # Fix the allocator cap once per phase. Reapplying a cap from free memory
+ # after each actor would subtract the retained weights repeatedly.
+ if session is None or not session.cap_set:
+ torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free, total))
+ if session is not None:session.cap_set = True
diff --git a/mocap/people_ui.py b/mocap/people_ui.py
index 2a15bdb..d2470c2 100644
--- a/mocap/people_ui.py
+++ b/mocap/people_ui.py
@@ -212,7 +212,9 @@ class PeopleWorkspace:
jobs.extend((stage,['--project',str(project),'--result',kind]) for stage in ('correct','export'))
if not jobs:
self.status.setText('Reconstruct a person before applying the shared scene floor.');return
- self._people_batch=True;self._people_return_id=self.active_person_id
+ self._people_batch=True
+ self._people_inference_jobs=[]
+ self._people_post_jobs=[];self._people_return_id=self.active_person_id
self._people_return_project=self.project
self.start_jobs(jobs, refresh_characters=True)
@@ -628,6 +630,7 @@ class PeopleWorkspace:
finish=round((end-root_manifest['start'])*fps)
self._people_stages=[s for s in stages if s!='track']
self._people_batch=True
+ self._people_inference_jobs=[];self._people_post_jobs=[]
self._people_return_id=self.active_person_id if any(p['id']==self.active_person_id for p in selected) else selected[0]['id']
self._people_return_project=None
self._people_result=result or self.active_result
@@ -654,7 +657,12 @@ class PeopleWorkspace:
for path in event['projects'] for stage in post]
# Prepare every actor's original camera/motion before resolving the
# one automatic scene plane or committing any corrected exports.
- self.jobs=jobs+self.jobs+deferred
+ self._people_inference_jobs.extend(jobs)
+ self._people_post_jobs.extend(deferred)
+ if not any(stage=='person' for stage,_ in self.jobs):
+ from .queue_groups import grouped_jobs
+ self.jobs=grouped_jobs(self._people_inference_jobs,self.people_root)+self.jobs+self._people_post_jobs
+ self._people_inference_jobs=[];self._people_post_jobs=[]
return True
if event['type']=='people_found':
self._people_found_root=Path(event['project'])
@@ -670,6 +678,7 @@ class PeopleWorkspace:
self.status.setText(f'{self.people_list.count()} people found. Check people to extract; select a row to preview.')
if not self._people_batch:return
self._people_batch=False
+ self._people_inference_jobs=[];self._people_post_jobs=[]
root=self.people_root
ident=self._people_return_id
if root:
diff --git a/mocap/person_tracking.py b/mocap/person_tracking.py
index 5a39fd8..ed89146 100644
--- a/mocap/person_tracking.py
+++ b/mocap/person_tracking.py
@@ -53,7 +53,8 @@ class AppearanceEncoder:
embedding = torch.nn.functional.normalize(self.model((tensor-self.mean)/self.std), dim=1)
return embedding.cpu().numpy()
# A small model; bounded batches and retry outside the OOM exception scope.
- batch = 4 if os.environ.get('RGB_MOCAP_COMPUTE_MODE') == 'low_memory' else 16
+ from .memory_mode import effective_mode
+ batch = 4 if effective_mode() == 'low_memory' else 16
first = 0
while first < len(boxes):
failed = False
diff --git a/mocap/project_save_ui.py b/mocap/project_save_ui.py
index aa08978..120ce63 100644
--- a/mocap/project_save_ui.py
+++ b/mocap/project_save_ui.py
@@ -48,7 +48,7 @@ class ProjectSaving:
workspace_settings=self.workspace_settings(),
mamma_inputs=self.mamma_inputs,
mamma_active_camera=self.mamma_active_camera,
- flow_options={'camera_interval':self.flow_sampling.currentData(),'fast_sam':self.fast_sam.isChecked()},
+ flow_options=self.selected_flow_options(),
exmr_options={'static_camera':self.exmr_camera.currentData(),'smoothing':'global' if self.exmr_smoothing.isChecked() else 'none'},
correction=self.selected_correction_options(), frame=self.slider.value(),
trim=[self.slider.clip_in, self.slider.clip_out]))
diff --git a/mocap/project_workspace_ui.py b/mocap/project_workspace_ui.py
index 84f9f29..0c4ea79 100644
--- a/mocap/project_workspace_ui.py
+++ b/mocap/project_workspace_ui.py
@@ -9,10 +9,14 @@ from .video import select_preview
class ModelWorkspace:
+ def selected_flow_options(self):
+ return dict(camera_interval=self.flow_sampling.currentData(), fast_sam=self.fast_sam.isChecked(),
+ sam_batch4=self.flow_batch4.isChecked(), sam_gpu_crop=self.flow_gpu_crop.isChecked())
+
def workspace_settings(self):
return dict(result=self.active_result,correction=self.selected_correction_options(),
mamma_options=self.mamma_options(),
- flow_options={'camera_interval':self.flow_sampling.currentData(),'fast_sam':self.fast_sam.isChecked()},
+ flow_options=self.selected_flow_options(),
exmr_options={'static_camera':self.exmr_camera.currentData(),'smoothing':'global' if self.exmr_smoothing.isChecked() else 'none'})
def restore_workspace_settings(self,settings):
@@ -26,6 +30,8 @@ class ModelWorkspace:
flow=settings.get('flow_options',{})
self.flow_sampling.setCurrentIndex(max(0,self.flow_sampling.findData(flow.get('camera_interval',0))))
self.fast_sam.setChecked(flow.get('fast_sam',True))
+ self.flow_batch4.setChecked(flow.get('sam_batch4',True))
+ self.flow_gpu_crop.setChecked(flow.get('sam_gpu_crop',True))
exmr=settings.get('exmr_options',{})
self.exmr_camera.setCurrentIndex(self.exmr_camera.findData(exmr.get('static_camera',True)))
self.exmr_smoothing.setChecked(exmr.get('smoothing','global')=='global')
diff --git a/mocap/queue_groups.py b/mocap/queue_groups.py
new file mode 100644
index 0000000..54005bd
--- /dev/null
+++ b/mocap/queue_groups.py
@@ -0,0 +1,142 @@
+"""Bounded stage queues and request files; safe to import in the GUI."""
+from pathlib import Path
+import json
+import uuid
+
+BATCH_STAGES = {'flow_batch','exmr_batch','gvhmr_batch'}
+PHASES = {
+ 'flow_batch': {'flow_features':'flow_features','flowhmr':'flowhmr','all':'flowhmr'},
+ 'exmr_batch': {'exmr_preprocess':'exmr_preprocess','body':'exmr_features','hand':'exmr_features','exmr':'exmr','all':'exmr'},
+ 'gvhmr_batch': {'pose':'features','features':'features','gvhmr':'gvhmr','all':'gvhmr'},
+}
+MAX_ITEMS = 128
+MAX_BYTES = 512 * 1024
+
+
+def argument(args, name):
+ return args[args.index(name)+1]
+
+
+def grouped_jobs(jobs, root):
+ projects = {argument(args,'--project') for _,args in jobs}
+ buckets = {}
+ for stage,args in jobs:
+ buckets.setdefault(stage,[]).append(args)
+ # ExMR benefits for both one and multiple actors. FlowHMR's measured gain
+ # is for one actor; retain its existing two-phase multi-person scheduling.
+ joined = {}
+ for stages,batch in [(('exmr_preprocess','exmr_features','exmr'),'exmr_batch'),
+ (('flow_features','flowhmr'),'flow_batch')]:
+ if batch=='flow_batch' and len(projects)!=1:continue
+ if not all(stage in buckets for stage in stages):continue
+ items=[[_item(a) for a in buckets[stage]] for stage in stages]
+ if any(item is None for group in items for item in group):continue
+ if any(group!=items[0] for group in items[1:]):continue
+ joined[stages[0]]=(batch,items[0])
+ for stage in stages[1:]:del buckets[stage]
+ result = []
+ for stage,items in buckets.items():
+ if stage in joined:
+ batch,requests=joined[stage]
+ for begin in range(0,len(requests),MAX_ITEMS):
+ result.append((batch,_batch_args(root,'all',requests[begin:begin+MAX_ITEMS])))
+ continue
+ spec = {'flow_features':('flow_batch',['flow_features']),
+ 'flowhmr':('flow_batch',['flowhmr']),
+ 'exmr_preprocess':('exmr_batch',['exmr_preprocess']),
+ 'exmr_features':('exmr_batch',['body','hand']),
+ 'exmr':('exmr_batch',['exmr']),
+ 'gvhmr':('gvhmr_batch',['all'])}.get(stage)
+ if spec is None or len(items)<2 or any(_item(a) is None for a in items):
+ result.extend((stage,args) for args in items)
+ continue
+ batch,phases = spec
+ for phase in phases:
+ for begin in range(0,len(items),MAX_ITEMS):
+ chunk = items[begin:begin+MAX_ITEMS]
+ # Only explicit actor paths, selected results and force survive.
+ requests = [dict(project=argument(a,'--project'),result=argument(a,'--result'),force='--force' in a) for a in chunk]
+ result.append((batch,['--batch-root',str(root),'--batch-phase',phase,
+ '--batch-items',json.dumps(requests),'--project',requests[0]['project'],
+ '--result',requests[0]['result']]))
+ return result
+
+
+def _item(args):
+ # Do not drop unrecognized processing options when combining jobs.
+ allowed = {'--project', '--result', '--force'}
+ if any(a.startswith('--') and a not in allowed for a in args):return None
+ try:
+ return dict(project=argument(args,'--project'),
+ result=argument(args,'--result') if '--result' in args else 'auto',
+ force='--force' in args)
+ except (ValueError, IndexError):return None
+
+
+def _batch_args(root, phase, items):
+ return ['--batch-root',str(root),'--batch-phase',phase,
+ '--batch-items',json.dumps(items),'--project',items[0]['project'],
+ '--result',items[0]['result']]
+
+
+def join_single_pipeline(jobs, project):
+ """Join only the ready queue head, after prepare/track chose its project."""
+ if project is None or not jobs:return jobs
+ stage = jobs[0][0]
+ stages = {'exmr_preprocess':('exmr_preprocess','exmr_features','exmr'),
+ 'flow_features':('flow_features','flowhmr')}.get(stage)
+ if stages is None or tuple(s for s,_ in jobs[:len(stages)])!=stages:return jobs
+ items = []
+ for _,args in jobs[:len(stages)]:
+ args=list(args or [])
+ if '--project' not in args:args=['--project',str(project),*args]
+ item=_item(args)
+ if item is None or Path(item['project'])!=Path(project):return jobs
+ items.append(item)
+ if any(item!=items[0] for item in items[1:]):return jobs
+ batch='exmr_batch' if stage=='exmr_preprocess' else 'flow_batch'
+ return [(batch,_batch_args(project,'all',[items[0]])),*jobs[len(stages):]]
+
+
+def validate(request, stage):
+ if stage not in PHASES or request.get('version')!=1:raise ValueError('Invalid batch worker request')
+ phase = request.get('phase')
+ if phase not in PHASES[stage]:raise ValueError('Unsupported batch phase')
+ root = Path(request['root']).resolve(strict=True)
+ jobs = request.get('jobs')
+ if not isinstance(jobs,list) or not 1<=len(jobs)<=MAX_ITEMS:raise ValueError('Invalid batch size')
+ model = {'flow_batch':'flowhmr','exmr_batch':'exmr','gvhmr_batch':'gvhmr'}[stage]
+ from .motion_tools import RESULTS
+ clean = []
+ for job in jobs:
+ project = Path(job['project']).resolve(strict=True)
+ if not project.is_relative_to(root):raise ValueError('Batch project is outside its scene')
+ metadata = project/'project.json'
+ if metadata.stat().st_size>1024**2:raise ValueError('Project metadata is too large')
+ state = json.loads(metadata.read_text(encoding='utf-8'))
+ if state.get('pipeline',{}).get('model','gvhmr')!=model:raise ValueError('Batch motion model does not match its runtime')
+ selected = job['result']
+ if selected not in ('auto',*RESULTS):raise ValueError('Invalid batch result')
+ clean.append(dict(project=project,result=selected,force=bool(job.get('force',False))))
+ return phase,clean
+
+
+def write_request(stage, args):
+ from .paths import HOME
+ from .storage import atomic_json
+ value = dict(version=1,root=argument(args,'--batch-root'),phase=argument(args,'--batch-phase'),
+ jobs=json.loads(argument(args,'--batch-items')))
+ if len(json.dumps(value).encode('utf-8'))>MAX_BYTES:raise ValueError('Batch request is too large')
+ # Worker validates model metadata off the GUI thread; only serialize here.
+ folder = HOME/'cache/worker_jobs';folder.mkdir(parents=True,exist_ok=True)
+ path = folder/(uuid.uuid4().hex+'.json')
+ atomic_json(path,value)
+ return path
+
+
+def remove_request(path):
+ if path is None:return
+ from .paths import HOME
+ folder = (HOME/'cache/worker_jobs').resolve()
+ path = Path(path).resolve()
+ if path.parent==folder and path.suffix=='.json':path.unlink(missing_ok=True)
diff --git a/mocap/worker.py b/mocap/worker.py
index a3596f2..852b136 100644
--- a/mocap/worker.py
+++ b/mocap/worker.py
@@ -54,6 +54,8 @@ def fingerprint(stage, project, result="auto", _worker_hash=None, _legacy_routin
elif result_options(selected)[0]:
inputs[stage].append("opt_results.pt")
sources = [Path(__file__), Path(__file__).with_name("engines.py"), Path(__file__).with_name("export.py"), Path(__file__).with_name("mesh_data.py"), ROOT / "requirements-windows.txt",Path(__file__).with_name('compute_policy.py')]
+ if stage in ('track','pva','features','gvhmr','refine','footmr','handflow'):
+ sources.append(Path(__file__).with_name('memory_mode.py'))
if stage == "footmr":
sources.append(Path(__file__).with_name("footmr.py"))
sources.append(ROOT / "third_party/FootMR/hmr4d/utils/preproc/vitpose_pytorch/src/vitpose_infer/model_builder.py")
@@ -80,6 +82,7 @@ def fingerprint(stage, project, result="auto", _worker_hash=None, _legacy_routin
sources.extend(ROOT/'third_party/HTD-Refine'/name for name in (
'optimization/camera_alignment.py','optimization/pipeline.py','scripts/demo_optimization.py'))
if stage in ('gvhmr','features'):
+ sources.append(Path(__file__).with_name('model_session.py'))
sources.extend((Path(__file__).with_name('inference_data.py'),
Path(__file__).with_name('gvhmr_preprocess.py'),Path(__file__).with_name('gvhmr_attention.py'),
ROOT/'third_party/GVHMR/hmr4d/network/gvhmr/relative_transformer.py',
@@ -151,6 +154,7 @@ def main() -> int:
parser.add_argument('--correction-mode',choices=['flat','multi_level'],default='flat')
parser.add_argument('--pelvis-offset',type=float,default=0.)
args = parser.parse_args()
+ from .model_session import set_memory_budget
from .compute_policy import configure_worker_cpu,gpu_memory_fraction,GIB
threads=configure_worker_cpu(args.stage)
os.environ['RGB_MOCAP_STAGE']=args.stage
@@ -170,7 +174,7 @@ def main() -> int:
project = prepare(args.video.resolve(), args.start, args.end,motion_tool=args.motion_tool or 'gvhmr',project=args.project)
manifest = json.loads((project / "project.json").read_text(encoding="utf-8"))
if args.motion_tool=='flowhmr':
- manifest['flow_options']={**manifest.get('flow_options',{}),'camera_interval':int(os.environ.get('RGB_MOCAP_FLOW_INTERVAL','0')),'fast_sam':os.environ.get('RGB_MOCAP_FLOW_FAST_SAM','1')=='1'}
+ manifest['flow_options']={**manifest.get('flow_options',{}),'camera_interval':int(os.environ.get('RGB_MOCAP_FLOW_INTERVAL','0')),'fast_sam':os.environ.get('RGB_MOCAP_FLOW_FAST_SAM','1')=='1','sam_batch4':os.environ.get('RGB_MOCAP_FLOW_BATCH4','1')=='1','sam_gpu_crop':os.environ.get('RGB_MOCAP_FLOW_GPU_CROP','1')=='1'}
if args.motion_tool=='exmr':
from .exmr_options import options
manifest['exmr_options']=options(json.loads(os.environ.get('RGB_MOCAP_EXMR_OPTIONS','{}')))
@@ -271,7 +275,9 @@ def main() -> int:
if not torch.cuda.is_available():raise RuntimeError('A supported NVIDIA CUDA GPU is required for person detection.')
free,total=torch.cuda.mem_get_info()
if free is not None:
- torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
+ set_memory_budget(free,total)
+ from .memory_mode import select_stage
+ select_stage(args.stage,free,total,manifest.get('frames',0),emit)
from .person_tracking import discover,prepare_person
if args.stage=='people':
output=discover(project,emit)
@@ -341,8 +347,11 @@ def main() -> int:
free,total=torch.cuda.mem_get_info()
memory=psutil.virtual_memory()
if free is not None:
- torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
- plan=dict(stage=args.stage,threads=threads,mode=os.environ.get('RGB_MOCAP_COMPUTE_MODE','auto'),
+ set_memory_budget(free,total)
+ from .memory_mode import select_stage
+ select_stage(args.stage,free,total,manifest.get('frames',0),emit)
+ from .memory_mode import effective_mode,requested_mode
+ plan=dict(stage=args.stage,threads=threads,mode=effective_mode(),requested_mode=requested_mode(),
frames=manifest.get('frames',0),available_ram_gib=round(memory.available/GIB,2),
free_vram_gib=round(free/GIB,2) if free is not None else None)
atomic_json(project/f'{args.stage}_resources.json',plan)
@@ -391,7 +400,8 @@ def main() -> int:
atomic_json(state_path, state)
message=str(error)
if isinstance(error,MemoryError) or 'out of memory' in message.lower():
- message='Processing ran out of memory and stopped safely. Select Low Memory, close other apps, or trim the clip. Completed stages can be reused.'
+ from .memory_mode import GUIDANCE
+ message='Processing ran out of memory and stopped safely. '+GUIDANCE+' Completed stages can be reused.'
emit("failed", stage=args.stage, message=message)
return 1
diff --git a/mocap/worker_progress.py b/mocap/worker_progress.py
index 5cdb34d..28d8599 100644
--- a/mocap/worker_progress.py
+++ b/mocap/worker_progress.py
@@ -12,6 +12,10 @@ def emit(kind,**value):
def main():
stage=sys.argv[1] if len(sys.argv)>1 else ''
+ if stage in ('flow_batch','exmr_batch','gvhmr_batch'):
+ from .batch_worker import main as batch_main
+ from .progress_events import tqdm_events
+ with tqdm_events(emit):return batch_main(sys.argv[1:],emit)
if stage in ('mamma_prepare','mamma_publish'):
from .compute_policy import configure_worker_cpu
configure_worker_cpu(stage)
diff --git a/mocap/workspace_ui.py b/mocap/workspace_ui.py
index e4b3e66..22b5b3f 100644
--- a/mocap/workspace_ui.py
+++ b/mocap/workspace_ui.py
@@ -55,6 +55,21 @@ class TooltipHelp(WrappedLabel):
super().setVisible(False)
+class SettingsStack(QStackedWidget):
+ """Hidden model pages must not reserve their height in the sidebar."""
+ def __init__(self):
+ super().__init__()
+ self.currentChanged.connect(lambda _: self.updateGeometry())
+
+ def sizeHint(self):
+ page=self.currentWidget()
+ return page.sizeHint() if page else QSize(0,0)
+
+ def minimumSizeHint(self):
+ page=self.currentWidget()
+ return page.minimumSizeHint() if page else QSize(0,0)
+
+
def build_workspace(w):
def button(text, callback, parent_layout):
control = QPushButton(text)
@@ -287,7 +302,15 @@ def build_workspace(w):
side_layout = QVBoxLayout(sidebar)
side_layout.setContentsMargins(4, 0, 4, 0)
side_layout.setSpacing(7)
- selector = group("AI Motion Model", side_layout)
+ scroll = QScrollArea()
+ scroll.setObjectName("modelSettings")
+ scroll.viewport().setObjectName("modelSettingsViewport")
+ scroll.setWidgetResizable(True)
+ scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
+ content=QWidget();content_layout=QVBoxLayout(content)
+ content_layout.setContentsMargins(4,4,4,8)
+ content_layout.setSpacing(10)
+ selector = group("AI Motion Model", content_layout)
w.model_choice = QComboBox()
w.model_choice.setToolTip(tooltip_text('Choose the AI model used to create motion. Open Model Guide for a comparison.'))
for tool in MOTION_TOOLS.values():
@@ -330,7 +353,7 @@ def build_workspace(w):
selector.addLayout(model_help_row)
w.htd_refine.toggled.connect(w.refinement_changed)
w.footmr_refine.toggled.connect(w.refinement_changed)
- w.model_pages = QStackedWidget()
+ w.model_pages = SettingsStack()
w.model_pages.setObjectName("modelPages")
w.model_pages.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Maximum)
w.gvhmr_page = QWidget()
@@ -339,18 +362,31 @@ def build_workspace(w):
w.flow_page = QWidget()
w.flow_page.setProperty('motion_tool', 'flowhmr')
flow_settings = QVBoxLayout(w.flow_page)
- flow_settings.setContentsMargins(8, 0, 8, 0)
+ flow_settings.setContentsMargins(0, 0, 0, 0)
+ flow_settings.setSpacing(10)
+ flow_settings.setAlignment(Qt.AlignTop)
flow_camera = group('FlowHMR Settings', flow_settings)
w.fast_sam = QCheckBox('Fast SAM')
w.fast_sam.setChecked(True)
w.fast_sam.setToolTip(tooltip_text('Speed up image processing with the same model files. Small differences in motion and automatic contacts are possible. Applies next time you run Reconstruct 3D.'))
flow_camera.addWidget(w.fast_sam)
+ acceleration=group('Fast SAM Acceleration',flow_camera)
+ w.flow_acceleration=acceleration.parentWidget()
+ w.flow_batch4=QCheckBox('4-Frame Batching')
+ w.flow_gpu_crop=QCheckBox('GPU Hand Crops')
+ w.flow_batch4.setToolTip(tooltip_text('Process up to four frames together. Short tests: about 2-2.4x faster SAM features, with about 0.4 GiB more allocated VRAM (0.7 GiB more reserved). Small numerical pose differences are possible. Low Memory uses one frame. Applies on Reconstruct 3D; speed varies by PC and clip.'))
+ w.flow_gpu_crop.setToolTip(tooltip_text('Prepare hand crops on the GPU. Short tests: about 10-15% faster SAM features, with little extra VRAM beyond the selected batch size. Different image interpolation can change motion (about 1 mm at the 95th percentile; up to 5 mm in these tests). Model precision stays unchanged. Applies on Reconstruct 3D; results vary.'))
+ for check in (w.flow_batch4,w.flow_gpu_crop):
+ check.setChecked(True)
+ acceleration.addWidget(check)
+ check.toggled.connect(lambda _: w.update_readiness())
+ w.fast_sam.toggled.connect(lambda _: w.update_readiness())
flow_camera.addWidget(QLabel('Camera / Sampling'))
w.flow_sampling = QComboBox()
for label, interval in [('Moving / Unknown - Auto', 0), ('Static Camera', -1), ('Every Frame', 1), ('Every 2 Frames', 2), ('Every 5 Frames', 5), ('Every 10 Frames', 10), ('Every 30 Frames', 30)]:
w.flow_sampling.addItem(label, interval)
w.flow_sampling.setToolTip(tooltip_text('Choose Static Camera only if the camera stays still without zooming. Otherwise start with Moving / Unknown - Auto. Frame intervals control camera analysis only; shorter intervals use more memory. Applies on Reconstruct 3D.'))
- w.flow_sampling.currentIndexChanged.connect(w.update_readiness)
+ w.flow_sampling.currentIndexChanged.connect(lambda _: w.update_readiness())
flow_camera.addWidget(w.flow_sampling)
flow_help = QLabel('Native SMPL-H body and hands')
flow_help.setToolTip(tooltip_text('FlowHMR: body and finger tracking. Slow, with the best overall motion quality in our subjective tests.'))
@@ -361,7 +397,9 @@ def build_workspace(w):
w.exmr_page=QWidget()
w.exmr_page.setProperty('motion_tool','exmr')
exmr_settings=QVBoxLayout(w.exmr_page)
- exmr_settings.setContentsMargins(8,0,8,0)
+ exmr_settings.setContentsMargins(0,0,0,0)
+ exmr_settings.setSpacing(10)
+ exmr_settings.setAlignment(Qt.AlignTop)
exmr=group('ExMR Settings',exmr_settings)
exmr.addWidget(QLabel('Camera'))
w.exmr_camera=QComboBox()
@@ -378,8 +416,9 @@ def build_workspace(w):
w.build_mamma_settings()
shared_settings=QWidget()
settings = QVBoxLayout(shared_settings)
- settings.setContentsMargins(8, 0, 8, 8)
- settings.setSpacing(7)
+ settings.setContentsMargins(0, 0, 0, 0)
+ settings.setSpacing(10)
+ settings.setAlignment(Qt.AlignTop)
correction=group('Motion Correction',settings)
w.correction_group=correction.parentWidget()
w.motion_correction=QCheckBox('Enable Correction')
@@ -452,7 +491,7 @@ def build_workspace(w):
w.compute_mode = QComboBox()
w.compute_mode.addItem("Automatic", "auto")
w.compute_mode.addItem("Low Memory", "low_memory")
- w.compute_mode.setToolTip(tooltip_text("Automatic balances speed and available memory. Low Memory processes smaller image batches while keeping the same motion quality."))
+ w.compute_mode.setToolTip(tooltip_text("Automatic uses the fast path when memory is available and switches supported stages to Low Memory when needed. Low Memory uses CPU loading and offloading; it can be slower and use more RAM. Model precision and video frames are unchanged."))
processing.addWidget(w.compute_mode)
resource_description=TooltipHelp('',w.compute_mode)
resource_description.setObjectName('muted');resource_description.setWordWrap(True);processing.addWidget(resource_description)
@@ -464,22 +503,16 @@ def build_workspace(w):
setup.addWidget(w.readiness)
w.models_button = button("Model Manager", w.open_model_manager, setup)
w.models_button.setToolTip('Download or import the files needed by the selected AI model.')
- settings.addStretch()
- scroll = QScrollArea()
- scroll.setObjectName("modelSettings")
- scroll.viewport().setObjectName("modelSettingsViewport")
- scroll.setWidgetResizable(True)
- scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- content=QWidget();content_layout=QVBoxLayout(content)
- content_layout.setContentsMargins(0,0,0,0);content_layout.setSpacing(0)
+ shared_settings.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Maximum)
content_layout.addWidget(w.model_pages)
- content_layout.addWidget(shared_settings,1)
+ content_layout.addWidget(shared_settings)
scroll.setWidget(content)
side_layout.addWidget(scroll, 1)
w.model_actions = QFrame()
w.model_actions.setObjectName("modelActions")
action_buttons = QVBoxLayout(w.model_actions)
- action_buttons.setContentsMargins(9, 7, 9, 7)
+ action_buttons.setContentsMargins(0, 0, 0, 0)
+ action_buttons.setSpacing(7)
w.analyze_button = button("Analyze 2D", w.run_analysis, action_buttons)
w.analyze_button.setToolTip(tooltip_text("Find body points in the video for GVHMR refinement. Reconstruct 3D normally includes this step when needed."))
w.run_button = button("Reconstruct 3D", w.run_full, action_buttons)
@@ -490,7 +523,10 @@ def build_workspace(w):
w.cancel_button = button("Cancel Job", w.cancel_job, action_buttons)
w.cancel_button.setToolTip('Stop the current processing queue. Completed results are kept.')
w.cancel_button.setEnabled(False)
- side_layout.addWidget(w.model_actions)
+ w.model_actions.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Maximum)
+ content_layout.addWidget(w.model_actions)
+ content_layout.addStretch()
+ w.settings_scroll=scroll
w.model_choice.currentIndexChanged.connect(w.select_model)
main.addWidget(sidebar)
main.setSizes([1120, 260])
diff --git a/third_party/ExMR/RGB_MOCAP_PROVENANCE.json b/third_party/ExMR/RGB_MOCAP_PROVENANCE.json
index 1a29f63..3fd8e43 100644
--- a/third_party/ExMR/RGB_MOCAP_PROVENANCE.json
+++ b/third_party/ExMR/RGB_MOCAP_PROVENANCE.json
@@ -1,7 +1,7 @@
-{
- "repository": "https://github.com/twehrbein/ExMR",
- "commit": "f031badd0488bf5d50b8eba2e722c5a55f323e3f",
- "runtime": "Native Windows Python 3.12 / Torch 2.8.0+cu128",
- "weights_bundled": false,
- "compatibility": "Bounded sequential loaders, local DINOv3 source, Unicode-safe OpenCV JPEG IO; network and native precision unchanged"
-}
+{
+ "repository": "https://github.com/twehrbein/ExMR",
+ "commit": "f031badd0488bf5d50b8eba2e722c5a55f323e3f",
+ "runtime": "Native Windows Python 3.12 / Torch 2.8.0+cu128",
+ "weights_bundled": false,
+ "compatibility": "Bounded sequential loaders, optional CPU-first body/hand loading and pre-transfer Sapiens FP16 conversion, local DINOv3 source, Unicode-safe OpenCV JPEG IO; explicit optional model injection and removable feature-token hooks for stage-scoped sequential actor reuse; network and native precision unchanged; bounded CPU batch prefetch; unused final body-pose readouts omitted only after collected decoder features, retaining intermediate feedback and the generic SAM path"
+}
diff --git a/third_party/ExMR/exmr/pipeline.py b/third_party/ExMR/exmr/pipeline.py
index 0e75a5d..0961536 100644
--- a/third_party/ExMR/exmr/pipeline.py
+++ b/third_party/ExMR/exmr/pipeline.py
@@ -203,10 +203,10 @@ def _simplevo_rotations(video_path):
return SimpleVO(progress=False)(video_path).numpy()
-def _run_model(data, options, fps, assets):
+def _run_model(data, options, fps, assets, model=None):
from exmr.model.exmr import ExMR
- model = ExMR.from_pretrained(assets.exmr, assets.smplx)
+ if model is None:model = ExMR.from_pretrained(assets.exmr, assets.smplx)
inputs = {
k: data[k][None].cuda()
for k in ("kp2d", "bbx_xys", "K_fullimg", "cam_angvel", "body_feat", "hand_feat")
diff --git a/third_party/ExMR/exmr/preprocessing/body_features.py b/third_party/ExMR/exmr/preprocessing/body_features.py
index 951f2a9..4f4c82f 100644
--- a/third_party/ExMR/exmr/preprocessing/body_features.py
+++ b/third_party/ExMR/exmr/preprocessing/body_features.py
@@ -8,6 +8,8 @@ import sys
import warnings
from pathlib import Path
+from mocap.batch_prefetch import batch_source
+
import torch
from torch.utils.data import DataLoader
from torchvision.transforms import ToTensor
@@ -90,27 +92,32 @@ class SamBodyFeatures:
TOKEN_DIM = 1024
- def __init__(self, checkpoint_dir, batch_size=32, num_workers=8, device="cuda"):
+ def __init__(self, checkpoint_dir, batch_size=32, num_workers=8, device="cuda", low_memory=False):
sam_3d_body, self._transforms, self._load_image, self._prepare_batch, self._to = (
_import_sam_3d_body()
)
checkpoint_dir = Path(checkpoint_dir)
- # built on the GPU: initializing the weights on the CPU takes ~5 s, and the checkpoint
- # replaces them anyway
- with _quiet_model_loading(), torch.device(device):
+ # Fast loading initializes on GPU; Low Memory accepts slower CPU
+ # initialization to avoid holding temporary checkpoint/model copies in VRAM.
+ load_device = "cpu" if low_memory else device
+ with _quiet_model_loading(), torch.device(load_device):
model, model_cfg = sam_3d_body.load_sam_3d_body(
str(checkpoint_dir / "model.ckpt"),
- device=device,
+ device=load_device,
mhr_path=str(checkpoint_dir / "assets" / "mhr_model.pt"),
)
assert model.cfg.MODEL.DECODER.DO_HAND_DETECT_TOKENS
- self.model = model.eval()
+ self.model = model.eval().to(device)
self.input_size = model_cfg.MODEL.IMAGE_SIZE
self.batch_size, self.num_workers, self.device = batch_size, num_workers, device
# the decoder returns (tokens, pose_output); token 0 is the pose token
self._tokens = None
- self.model.decoder.register_forward_hook(self._store_tokens)
+ self._token_hook = self.model.decoder.register_forward_hook(self._store_tokens)
+
+ def close(self):
+ self._token_hook.remove()
+ self._tokens = None
def _store_tokens(self, _module, _inputs, output):
self._tokens = output[0].detach()
@@ -118,6 +125,10 @@ class SamBodyFeatures:
@torch.no_grad()
def __call__(self, frame_dir, bbx_xyxy, K_fullimg):
"""frame_dir with %06d.jpg frames, bbx_xyxy (L, 4), K_fullimg (L, 3, 3) -> (L, 1024)"""
+ # Final pose readouts are unused after the collected body token.
+ # Intermediate pose feedback and keypoint-token updates remain active.
+ self.model._mocap_features_only=True
+ self.model.decoder._mocap_features_only=True
t = self._transforms
transform = t.Compose(
[
@@ -138,8 +149,8 @@ class SamBodyFeatures:
)
tokens = torch.zeros((len(dataset), self.TOKEN_DIM), dtype=torch.float32)
i = 0
- with tqdm(total=len(dataset), desc="SAM 3D Body features", unit="frame") as pbar:
- for batch in loader:
+ with batch_source(loader, batch_bytes=self.batch_size*3*1024*1024*4) as batches, tqdm(total=len(dataset), desc="SAM 3D Body features", unit="frame") as pbar:
+ for batch in batches:
bs = batch["img"].shape[0]
batch = self._to(batch, self.device)
self.model._initialize_batch(batch)
diff --git a/third_party/ExMR/exmr/preprocessing/hand_features.py b/third_party/ExMR/exmr/preprocessing/hand_features.py
index ed5523a..79a5a38 100644
--- a/third_party/ExMR/exmr/preprocessing/hand_features.py
+++ b/third_party/ExMR/exmr/preprocessing/hand_features.py
@@ -7,6 +7,8 @@ Pavlakos), see THIRD_PARTY_NOTICES.md.
from pathlib import Path
+from mocap.batch_prefetch import batch_source
+
import cv2
import numpy as np
import torch
@@ -59,7 +61,7 @@ class HamerHandFeatures:
TOKEN_DIM = 1024
- def __init__(self, data_dir, fp16=True, batch_size=16, num_workers=8, device="cuda"):
+ def __init__(self, data_dir, fp16=True, batch_size=16, num_workers=8, device="cuda", low_memory=False):
data_dir = Path(data_dir)
cfg = get_config(str(data_dir / "hamer_ckpts" / "model_config.yaml"))
cfg.defrost()
@@ -70,12 +72,13 @@ class HamerHandFeatures:
cfg.MODEL.BACKBONE.pop("PRETRAINED_WEIGHTS", None)
cfg.freeze()
self.cfg = cfg
- # like hamer.models.load_hamer, without the renderer; built on the GPU: initializing the
- # weights on the CPU takes ~2 s, and the checkpoint replaces them anyway
- with torch.device(device):
+ # Fast loading initializes on GPU, without the unused renderer. Low
+ # Memory loads on CPU first to avoid a duplicate GPU checkpoint copy.
+ with torch.device("cpu" if low_memory else device):
self.model = HAMER.load_from_checkpoint(
str(data_dir / "hamer_ckpts" / "checkpoints" / "hamer.ckpt"),
strict=False,
+ **({"map_location": "cpu"} if low_memory else {}),
cfg=cfg,
init_renderer=False,
)
@@ -84,7 +87,11 @@ class HamerHandFeatures:
fp16, batch_size, num_workers, device
) # fmt: skip
self._tokens = None
- self.model.mano_head.transformer.register_forward_hook(self._store_tokens)
+ self._token_hook = self.model.mano_head.transformer.register_forward_hook(self._store_tokens)
+
+ def close(self):
+ self._token_hook.remove()
+ self._tokens = None
def _store_tokens(self, _module, _inputs, output):
self._tokens = output.squeeze(1)
@@ -103,8 +110,8 @@ class HamerHandFeatures:
)
tokens = torch.zeros((len(dataset), 2, self.TOKEN_DIM), dtype=torch.float32)
i = 0
- with tqdm(total=len(dataset), desc="HaMeR hand features", unit="frame") as pbar:
- for crops in loader:
+ with batch_source(loader, batch_bytes=self.batch_size*2*3*256*256*4) as batches, tqdm(total=len(dataset), desc="HaMeR hand features", unit="frame") as pbar:
+ for crops in batches:
bs = crops.shape[0]
tokens[i : i + bs] = (
self._forward(crops.reshape(-1, 3, 256, 256))
diff --git a/third_party/ExMR/exmr/preprocessing/keypoints/sapiens2.py b/third_party/ExMR/exmr/preprocessing/keypoints/sapiens2.py
index b076a41..9e42692 100644
--- a/third_party/ExMR/exmr/preprocessing/keypoints/sapiens2.py
+++ b/third_party/ExMR/exmr/preprocessing/keypoints/sapiens2.py
@@ -18,6 +18,7 @@ from safetensors.torch import load_file
from sapiens.engine.datasets import Compose
from sapiens.pose.datasets import UDPHeatmap
from sapiens.registry import MODELS
+from mocap.batch_prefetch import batch_source
from tqdm import tqdm
from exmr.preprocessing.keypoints.mappings import SAPIENS2_TO_COCO63
@@ -66,7 +67,7 @@ class Sapiens2Keypoints:
resolution: crop resolution "height x width", one of RESOLUTIONS
"""
- def __init__(self, checkpoint, resolution="1024x768", num_workers=2, device="cuda:0"):
+ def __init__(self, checkpoint, resolution="1024x768", num_workers=2, device="cuda:0", low_memory=False):
if resolution not in RESOLUTIONS:
raise ValueError(f"Sapiens2 resolution must be one of {list(RESOLUTIONS)}")
self.batch_size = RESOLUTIONS[resolution]
@@ -80,9 +81,15 @@ class Sapiens2Keypoints:
model = MODELS.build(copy.deepcopy(MODEL_CFG))
model.load_state_dict(load_file(str(checkpoint), device="cpu"))
model.data_preprocessor = MODELS.build(copy.deepcopy(DATA_PREPROCESSOR_CFG))
- model.to(device).eval()
- model.backbone.half()
- model.decode_head.half()
+ if low_memory:
+ # Same final FP16 layers, without a temporary full FP32 GPU copy.
+ model.backbone.half()
+ model.decode_head.half()
+ model.to(device).eval()
+ else:
+ model.to(device).eval()
+ model.backbone.half()
+ model.decode_head.half()
self.model = model
self.pipeline = Compose(
[
@@ -107,8 +114,8 @@ class Sapiens2Keypoints:
)
output = np.empty((len(boxes), 63, 3), dtype=np.float32)
cursor = 0
- with tqdm(total=len(boxes), desc="Sapiens2 keypoints", unit="frame") as pbar:
- for batch in loader:
+ with batch_source(loader, batch_bytes=self.batch_size*3*1024*768*4) as batches, tqdm(total=len(boxes), desc="Sapiens2 keypoints", unit="frame") as pbar:
+ for batch in batches:
prediction = _predict(
batch["inputs"].cuda().half(), self.model, self.codec, batch["data_samples"]
)
diff --git a/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/decoders/promptable_decoder.py b/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/decoders/promptable_decoder.py
index 7db2596..b747301 100644
--- a/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/decoders/promptable_decoder.py
+++ b/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/decoders/promptable_decoder.py
@@ -161,6 +161,8 @@ class PromptableDecoder(nn.Module):
)
out = self.norm_final(token_embedding)
+ if getattr(self, "_mocap_features_only", False):
+ return out, []
if self.do_interm_preds:
curr_pose_output = token_to_pose_output_fn(
diff --git a/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py b/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py
index 165106f..4760c3a 100644
--- a/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py
+++ b/third_party/ExMR/third_party/sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py
@@ -1129,6 +1129,7 @@ class SAM3DBody(BaseModel):
condition_info=condition_info[self.body_batch_idx],
batch=batch,
)
+ if getattr(self, "_mocap_features_only", False):return {}
pose_output = pose_output[-1]
if len(self.hand_batch_idx):
tokens_output_hand, pose_output_hand = self.forward_decoder_hand(
diff --git a/third_party/FlowHMR/flowhmr/utils/runtime_vggt_camera.py b/third_party/FlowHMR/flowhmr/utils/runtime_vggt_camera.py
index c32ea8d..8a24e73 100644
--- a/third_party/FlowHMR/flowhmr/utils/runtime_vggt_camera.py
+++ b/third_party/FlowHMR/flowhmr/utils/runtime_vggt_camera.py
@@ -189,6 +189,7 @@ def extract_vggt_camera(
camera_only: bool = False,
keep_frames: bool = False,
frame_interval: int = 1,
+ model_loader=None,
) -> VGGTCameraResult:
frame_interval = max(1, int(frame_interval))
if output_npz and osp.exists(output_npz):
@@ -253,7 +254,7 @@ def extract_vggt_camera(
target_len = sample_indices[-1] + 1
print(f" [vggt] sampled {len(frame_paths)}/{target_len} frames (interval={frame_interval})")
- model = _load_vggt_model(checkpoint_path, device_obj, camera_only=camera_only)
+ model = (model_loader or _load_vggt_model)(checkpoint_path, device_obj, camera_only=camera_only)
images = load_and_preprocess_images(
frame_paths,
mode=preprocess_mode,
diff --git a/third_party/FlowHMR/third_party/fast-sam-3d-body/RGB_MOCAP_PROVENANCE.json b/third_party/FlowHMR/third_party/fast-sam-3d-body/RGB_MOCAP_PROVENANCE.json
index 5ed87ac..7ac86cc 100644
--- a/third_party/FlowHMR/third_party/fast-sam-3d-body/RGB_MOCAP_PROVENANCE.json
+++ b/third_party/FlowHMR/third_party/fast-sam-3d-body/RGB_MOCAP_PROVENANCE.json
@@ -1,7 +1,8 @@
{
"repository": "https://github.com/yangtiming/Fast-SAM-3D-Body",
"commit": "d72aa36913a1673ace029d345f437561a85ec9e2",
- "local_source_changes": false,
+ "local_source_changes": true,
+ "local_changes": "Optional bounded video-frame hand-crop callback, multi-image GPU crop support, and token-only return after complete body/hand decoders. Default upstream inference remains available; model precision and crop resolution are unchanged.",
"compile": false,
"weights_bundled": false
-}
\ No newline at end of file
+}
diff --git a/third_party/FlowHMR/third_party/fast-sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py b/third_party/FlowHMR/third_party/fast-sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py
index 07f6d27..415100f 100644
--- a/third_party/FlowHMR/third_party/fast-sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py
+++ b/third_party/FlowHMR/third_party/fast-sam-3d-body/sam_3d_body/models/meta_arch/sam3d_body.py
@@ -243,7 +243,7 @@ def _prepare_hand_batches_gpu(img, left_xyxy, right_xyxy, cam_int, output_size=(
Supports multi-person batch processing.
Args:
- img: (H, W, 3) numpy array or tensor
+ img: (H, W, 3), or (N, H, W, 3) for one tracked body per video frame
left_xyxy: (N, 4) left hand bbox (original image coordinates, will be flipped)
right_xyxy: (N, 4) right hand bbox
cam_int: (1, 3, 3) camera intrinsics
@@ -257,7 +257,7 @@ def _prepare_hand_batches_gpu(img, left_xyxy, right_xyxy, cam_int, output_size=(
left_xyxy_flipped: flipped left hand bbox (numpy array)
"""
out_h, out_w = output_size
- H, W = img.shape[:2]
+ H, W = img.shape[1:3] if img.ndim == 4 else img.shape[:2]
# 1. Upload image to GPU (once)
if isinstance(img, np.ndarray):
@@ -266,11 +266,13 @@ def _prepare_hand_batches_gpu(img, left_xyxy, right_xyxy, cam_int, output_size=(
img_tensor = img.to(device)
# Convert to (3, H, W) format
- if img_tensor.dim() == 3 and img_tensor.shape[-1] == 3:
+ if img_tensor.dim() == 4 and img_tensor.shape[-1] == 3:
+ img_tensor = img_tensor.permute(0, 3, 1, 2)
+ elif img_tensor.dim() == 3 and img_tensor.shape[-1] == 3:
img_tensor = img_tensor.permute(2, 0, 1) # (H, W, 3) -> (3, H, W)
# 2. Flip image for left hand (GPU operation)
- img_flipped = torch.flip(img_tensor, dims=[2]) # Horizontal flip
+ img_flipped = torch.flip(img_tensor, dims=[-1]) # Horizontal flip
# 3. Compute flipped left hand bbox
left_xyxy_t = torch.as_tensor(left_xyxy, dtype=torch.float32, device=device)
@@ -280,6 +282,8 @@ def _prepare_hand_batches_gpu(img, left_xyxy, right_xyxy, cam_int, output_size=(
# Get number of persons
N = left_xyxy_t.shape[0]
+ if img_tensor.dim() == 4 and img_tensor.shape[0] != N:
+ raise ValueError("Each frame must have its own hand boxes")
# 4. Apply padding and compute final crop_size (matching CPU version's transform chain)
# CPU version processing flow:
@@ -355,8 +359,8 @@ def _prepare_hand_batches_gpu(img, left_xyxy, right_xyxy, cam_int, output_size=(
# 6. GPU crop - need to expand image to batch form
# grid_sample requires input: (N, C, H, W), grid: (N, out_h, out_w, 2)
- img_flipped_batch = img_flipped.unsqueeze(0).expand(N, -1, -1, -1).float() # (N, 3, H, W)
- img_tensor_batch = img_tensor.unsqueeze(0).expand(N, -1, -1, -1).float() # (N, 3, H, W)
+ img_flipped_batch = (img_flipped if img_flipped.dim() == 4 else img_flipped.unsqueeze(0).expand(N, -1, -1, -1)).float() # (N, 3, H, W)
+ img_tensor_batch = (img_tensor if img_tensor.dim() == 4 else img_tensor.unsqueeze(0).expand(N, -1, -1, -1)).float() # (N, 3, H, W)
cropped_left = F.grid_sample(
img_flipped_batch, grid_left,
@@ -2562,6 +2566,8 @@ class SAM3DBody(BaseModel):
yolo_pose_keypoints: Optional[np.ndarray] = None, # YOLO-Pose keypoints [N, 17, 3]
yolo_pose_body_boxes: Optional[np.ndarray] = None, # YOLO-Pose body boxes [N, 4]
parallel_decoders: bool = True, # Enable merged batch execution for shared backbone
+ hand_batch_preparer=None, # RGB MoCap: optional bounded video-frame crops
+ features_only=False, # Decoder tokens only; no downstream pose assembly needed
):
"""
Run 3DB inference (optionally with hand detector).
@@ -2799,21 +2805,25 @@ class SAM3DBody(BaseModel):
t0 = time.time()
## Prepare left hand batch (flip image & box)
- flipped_img = img[:, ::-1]
- tmp = left_xyxy.copy()
- left_xyxy[:, 0] = width - tmp[:, 2] - 1
- left_xyxy[:, 2] = width - tmp[:, 0] - 1
+ if hand_batch_preparer is not None:
+ batch_lhand, batch_rhand, left_xyxy = hand_batch_preparer(
+ img, left_xyxy, right_xyxy, cam_int)
+ else:
+ flipped_img = img[:, ::-1]
+ tmp = left_xyxy.copy()
+ left_xyxy[:, 0] = width - tmp[:, 2] - 1
+ left_xyxy[:, 2] = width - tmp[:, 0] - 1
- batch_lhand = prepare_batch(
- flipped_img, transform_hand, left_xyxy, cam_int=cam_int.clone()
- )
- batch_lhand = recursive_to(batch_lhand, "cuda")
+ batch_lhand = prepare_batch(
+ flipped_img, transform_hand, left_xyxy, cam_int=cam_int.clone()
+ )
+ batch_lhand = recursive_to(batch_lhand, "cuda")
- ## Prepare right hand batch
- batch_rhand = prepare_batch(
- img, transform_hand, right_xyxy, cam_int=cam_int.clone()
- )
- batch_rhand = recursive_to(batch_rhand, "cuda")
+ ## Prepare right hand batch
+ batch_rhand = prepare_batch(
+ img, transform_hand, right_xyxy, cam_int=cam_int.clone()
+ )
+ batch_rhand = recursive_to(batch_rhand, "cuda")
## Merge both hand batches and run single forward pass
batch_hands = self._merge_hand_batches(batch_lhand, batch_rhand)
@@ -2823,6 +2833,9 @@ class SAM3DBody(BaseModel):
torch.cuda.synchronize()
print(f" [run_inference] step2_hands_merged_decoder: {time.time() - t0:.4f}s")
+ if features_only:
+ return pose_output, batch_lhand, batch_rhand, None, None
+
## Split output back to left and right
# Get number of persons for correct splitting
num_persons = batch["img"].shape[1]