Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.
Python
Add PEAR multiview tracking and adaptive FlowHMR batches
toyxyz828ec93727cf
diff --git a/README.md b/README.mdindex b858a9e..7f3af84 100644--- a/README.md+++ b/README.md@@ -122,7 +122,7 @@ do not put passwords or account tokens in the agent chat.- Export source animation as FBX; export characters as FBX with or without meshes,or PMX character motion as VMD for MMD.- Save projects with separate results for each AI model.-- Preview one person's live body/finger bones from a webcam or video with PEAR.+- Track webcam or video input in real time with PEAR's experimental body/finger bone preview; tracking and poses may be unstable.## How it works@@ -137,8 +137,11 @@ do not put passwords or account tokens in the agent chat.3. Review the motion, edit contacts if needed and **Apply Correction**.4. Export FBX, or import a character, retarget the motion and export it.-For **PEAR · Live (Experimental)**, choose a webcam or open a video, then click **Start Live-Tracking**. It provides a bone preview without recording, correction or export.+**PEAR · Live (Experimental)** tracks webcam or video input in real time. Tracking+and pose estimates may be unstable. Click **Start Live Tracking** to attempt camera+alignment and begin the bone preview. If alignment fails, tracking continues from+the selected camera with a warning; camera fusion and aligned foot lock are unavailable.+Recording, offline correction and export are unavailable in this live mode.See the [PEAR guide](docs/models/PEAR.md) for its controls.## Supported AI models@@ -169,10 +172,11 @@ projects, caches or retained downloads; shared files are counted once.| MAMMA additional files | 6.11 GiB | 3.42 GiB | 9.54 GiB || PromptHMR additional files | 6.22 GiB | 6.13 GiB | 12.34 GiB || **Five offline models** | **24.68 GiB** | **38.44 GiB** | **63.11 GiB** |-| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.84 GiB | ~2.84 GiB |+| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.95 GiB | ~2.96 GiB |Including PEAR, the estimated combined model/runtime total is about-**65.95 GiB (70.8 GB)**, before the additional space listed below.+**66.07 GiB (70.9 GB)**, before the additional space listed below. PEAR includes about **0.11 GiB** for GeoCalib weights and reuses VGGT; see its+[detailed guide](docs/models/PEAR.md#multiple-fixed-cameras-and-camera-align).**MAMMA and PromptHMR require separate runtime installation:** run`Setup_MAMMA.cmd` or `Setup_PromptHMR.cmd` after `install.cmd`, as described@@ -200,6 +204,11 @@ with unchanged measured peak VRAM. These are different tests, not full-jobspeed guarantees. See [resource modes, measured savings and acceleration](docs/PERFORMANCE.md)for conditions, per-model results and output differences.+FlowHMR's **Adaptive Batching** selects 1–16 Fast SAM frames from available memory;+Low Memory uses one. Warm feature tests took 16–23% less time at batch 16 than at+batch 4, with peak allocated VRAM rising from 3.84 to 5.43 GiB. Whole-job gains can+be smaller. Batch selection and OOM retry messages appear in Console and CMD.+## Documentation- [User guide: installation, controls and settings](docs/USER_GUIDE.md)diff --git a/RGBMoCap.cmd b/RGBMoCap.cmdindex 09f065c..e72cb7d 100644--- a/RGBMoCap.cmd+++ b/RGBMoCap.cmd@@ -1,5 +1,5 @@@echo off-setlocal+setlocal DisableDelayedExpansioncd /d "%~dp0"if not exist "runtime\python.exe" (echo RGB MoCap is not installed. Run install.cmd first.@@ -13,4 +13,4 @@ if not "%app_exit%"=="0" (echo RGB MoCap exited with code %app_exit%. See the messages above.pause)-exit /b %app_exit%+exit /b %app_exit%diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.jsonindex 6209eb4..1f8b3d6 100644--- a/SOURCE_MANIFEST.json+++ b/SOURCE_MANIFEST.json@@ -1,6 +1,6 @@{"schema": 1,- "date": "2026-11-01",+ "date": "2026-11-02","purpose": "Public source distribution; excludes model weights and runtime binaries","version": "git-source","files": [@@ -26,13 +26,13 @@},{"path": "README.md",- "bytes": 10232,- "sha256": "63d449f2040bcb70642bf99b40b94b5dff917aa4b59036899abb71f302bc8d3f"+ "bytes": 11014,+ "sha256": "eb050623300c8060384c946c1e4b9dedb257c0e72fc4477751b9af3c38ee175f"},{"path": "RGBMoCap.cmd",- "bytes": 382,- "sha256": "8c925029ce80ff6c73854ce05b9c22f566fb9f631cb8481f1e6577a969ab70a1"+ "bytes": 405,+ "sha256": "15a022a9c3c7ff5ec43bd55e35c46ea2befb1ae01953e67529b6dc1c8ded30f0"},{"path": "Setup_MAMMA.cmd",@@ -46,13 +46,13 @@},{"path": "THIRD_PARTY_NOTICES.md",- "bytes": 8568,- "sha256": "fdab2c03d661bd7cefc11c180a4d3f298beaa50d2ff012848d5c7ae3997bbf89"+ "bytes": 9190,+ "sha256": "12fdb67ddce790b575bcd94e4e584d959617761cbebae0d0def6c69c00bc7450"},{"path": "app.py",- "bytes": 4294,- "sha256": "9eac82d35698e304cb8e85424f4cf517cf29187f4a56ac1b4a210a922af846c1"+ "bytes": 4655,+ "sha256": "5f3bba99d4ca9580c970a47a0c393853ac8a077e81b4d489442f31a4e53c72d7"},{"path": "assets/fonts/NotoSansKR.ttf",@@ -96,18 +96,18 @@},{"path": "docs/AGENT_GUIDE.md",- "bytes": 39037,- "sha256": "069de4070e7163226aaa76aa14b4887f83949d57980ccd291cf515c94f4dc665"+ "bytes": 49676,+ "sha256": "52244d5b7802e92b077248c0cb4b795119db079bb99ca99369bbc3f0ffc9f531"},{"path": "docs/BUILD.md",- "bytes": 11607,- "sha256": "ff2c901d948748e6d477127418b6f5c227d64d509bde5d7eb7f1145e4697fa0a"+ "bytes": 12130,+ "sha256": "35bbd75bd41239ed1919ad2c2cac911daf84737856385f4b53ad507eefbe2c1b"},{"path": "docs/CITATIONS.md",- "bytes": 5656,- "sha256": "ecc6c91a14a4dbf91677c2b0833e3744d37afc0069f46af3c64860cbce02cd4c"+ "bytes": 6463,+ "sha256": "f244bc8076ab740be6ca58f567009b6a7d9d37b3d7aee68182d7e0005e07032e"},{"path": "docs/MAMMA.md",@@ -121,18 +121,18 @@},{"path": "docs/PERFORMANCE.md",- "bytes": 14223,- "sha256": "55951143f07abd21f5fbe7c2f26e12278fcfaaf41334048fbedb1ad7449a42b9"+ "bytes": 17525,+ "sha256": "faa8145338009ec53f7ccac644e183fb66f24eb748e64d1a0b2eca77b899d197"},{"path": "docs/USER_GUIDE.md",- "bytes": 46042,- "sha256": "5f94910678bf6defa3cc0b4fa4c4bffdf9e3c0e5d488425f3627ebce17b7c78e"+ "bytes": 49391,+ "sha256": "ba20ad84994aa955a60e339b838fc94b58716113d94475130b3d5468da84d34a"},{"path": "docs/VALIDATION.md",- "bytes": 85264,- "sha256": "030f68f98c92efc1003635bfe060ec184596bff8b885f5e77a7b5bbd9792319e"+ "bytes": 105423,+ "sha256": "caddc91166f8d58fb661ee5d2fca9604ef0dddcd8731f080e6370d1776e36fcd"},{"path": "docs/images/exmr-interaction-contact.png",@@ -161,8 +161,8 @@},{"path": "docs/models/FLOWHMR.md",- "bytes": 8328,- "sha256": "0ca09d89c3a6a9fff248b2014a2f4d588be771203d43aa22e00be29ad4128332"+ "bytes": 11720,+ "sha256": "9d246602b7a60009690eb57060cc9c07536004d4ab9b93e45a87b310c1e94d05"},{"path": "docs/models/GVHMR.md",@@ -171,8 +171,8 @@},{"path": "docs/models/PEAR.md",- "bytes": 11738,- "sha256": "57a26ed95be324d184ea9dc582db733553ee83429f727e99634c2dfb675db809"+ "bytes": 23860,+ "sha256": "b924da77cb6687dfa8cd4edfa5444b782bf90a45a500ee070c9d288554dba698"},{"path": "docs/models/PROMPTHMR.md",@@ -181,8 +181,8 @@},{"path": "docs/models/README.md",- "bytes": 5922,- "sha256": "3be817b61b7bc4d955796957990cb34e400e184c5fd02a72d30de616f391a358"+ "bytes": 6195,+ "sha256": "b898a9b0a9401337577bb0e34d8a83b7dd22f01667c86d9fdd4eb1d02be6d817"},{"path": "docs/samples/character-retargeting.jpg",@@ -216,8 +216,8 @@},{"path": "install.cmd",- "bytes": 285,- "sha256": "c3e66f0f3bae8fcc814042317079a755501d8d634e655c141a456f425aaedec0"+ "bytes": 309,+ "sha256": "517627faf9f08a4834341c3666b408d52128e6776d5b2ac12cce36192e389b46"},{"path": "installer/FolderPicker.cs",@@ -236,8 +236,8 @@},{"path": "installer/engine.py",- "bytes": 18328,- "sha256": "3564bf7b2efab40ff8964e0ed7da48c96096249492857b83a92d5a88c4af0454"+ "bytes": 18340,+ "sha256": "f285199581bff1154a84da727a0b5b32ae19d52c1fb9b2b3b9e571fe516cd554"},{"path": "installer/external-assets.json",@@ -289,6 +289,11 @@"bytes": 3725,"sha256": "bbea620bc10c7d922720096a2f19892f8dbaadae17a03a4a25b61691a6a5141b"},+ {+ "path": "installer/pear-alignment.json",+ "bytes": 1030,+ "sha256": "fd7d46998004697333a2af9c8023581531ef248211728dfe0efa32006a377adc"+ },{"path": "installer/pear-assets.json","bytes": 5612,@@ -317,7 +322,7 @@{"path": "installer/runtime-lock.json","bytes": 117713,- "sha256": "0a3c03e42a954debef5dbfa36d495499f903c7cca064ac3da3ecc02724980aac"+ "sha256": "5a3e3bb2e6315b467d0a15a6f6066cf5bab8d98c26ccbfff0413d83b99ace123"},{"path": "installer/runtime_sources/antlr4_python3_runtime-4.9.3-py3-none-any/SOURCE_WHEEL.json",@@ -1121,8 +1126,8 @@},{"path": "mocap/character_ui.py",- "bytes": 20360,- "sha256": "afbf6182f4dbf6377268aa1dc22515b06e658387eebf4ebd803f43be26b8ccd5"+ "bytes": 20764,+ "sha256": "e1da3682bd95867c10dbcf5d7ca023e8e07c895da3590c513d6e97b7d5b5d21a"},{"path": "mocap/compute_policy.py",@@ -1181,8 +1186,8 @@},{"path": "mocap/exmr_backend.py",- "bytes": 20661,- "sha256": "6d7c85ad5ee1341338be8375136808d5ea93adabbac3d6dc63fd9d6c178a1678"+ "bytes": 20709,+ "sha256": "77c7162093f5bbf9b4dba46287f6542d5069cd3aef24444f531eac94335bd82f"},{"path": "mocap/exmr_camera.py",@@ -1226,8 +1231,8 @@},{"path": "mocap/flow_backend.py",- "bytes": 25866,- "sha256": "088ec2ac27a23f255ca6d06da783a31d52a207fea8ac671de32bb215a02ade88"+ "bytes": 26391,+ "sha256": "35a4308ee1908cd5eae7799ac5bba0b4ff13fd45c411b33ecbbe7d76e4b2046a"},{"path": "mocap/flow_camera.py",@@ -1246,8 +1251,8 @@},{"path": "mocap/flow_fast_sam.py",- "bytes": 3926,- "sha256": "319f211033a21d0fa1a83dd01a45676844df93cf95680e0d9fb7242883e3ba42"+ "bytes": 3948,+ "sha256": "dd4fabe790e4f5a021a5507adf372668931264fe4d57abd47ea820149a43fe6c"},{"path": "mocap/flow_floor.py",@@ -1261,8 +1266,13 @@},{"path": "mocap/flow_sam.py",- "bytes": 6547,- "sha256": "c1abd10ec3143cfa7d7b97283a461fa858b73f55338cde7d7842cf030eff0b95"+ "bytes": 6582,+ "sha256": "db6fd57ca78c6dfab27142b9e99db207fcc1021933f1c4cfeb599c5fdad321ed"+ },+ {+ "path": "mocap/flow_sam_batch.py",+ "bytes": 3002,+ "sha256": "e02e6a75f7aa4a8055ff2894f70e9db34e5aca02b05c76cb08247c2a03e196b3"},{"path": "mocap/flow_scene.py",@@ -1281,8 +1291,8 @@},{"path": "mocap/footmr.py",- "bytes": 10133,- "sha256": "a427f13181af20c2ded61a704a3c797bb8b9c3c298a73f54a7c48684d5e6f3bf"+ "bytes": 10149,+ "sha256": "5ce6cb19edfb4c3398afa382c2e1f0d235c55c2a3def17841dd4ea9d5c3a8234"},{"path": "mocap/gpu_offload.py",@@ -1291,8 +1301,8 @@},{"path": "mocap/gui.py",- "bytes": 100901,- "sha256": "5c994e4750e8ada6d23dbf76a13e9434d29c7b1bede9ec6fd10edc9bbd76e2cc"+ "bytes": 102188,+ "sha256": "94f53dbedf05a733894bfe38047d3d6737baf14f3dc78d25221c8a850f239546"},{"path": "mocap/gvhmr_attention.py",@@ -1324,6 +1334,11 @@"bytes": 11206,"sha256": "7d1061f7f56e6c47a7a9660979616fb751dd8da36f39f0f4ed72a3b81135e04d"},+ {+ "path": "mocap/image_io.py",+ "bytes": 1554,+ "sha256": "55d75ef4c5b9aa5e16ef53ffef1dc95c47ced51b531453e5afb2310d43225888"+ },{"path": "mocap/inference_data.py","bytes": 6610,@@ -1336,8 +1351,8 @@},{"path": "mocap/mamma_camera.py",- "bytes": 8530,- "sha256": "52588cf37f4082d89a40b7d425e5f0b02f9fe230defb57bf79a0b6f445d57c6e"+ "bytes": 8576,+ "sha256": "f56120436807a44ca4f6bc6e52a33876754d11bf7c9e86745a64eab1f21a4a5a"},{"path": "mocap/mamma_inputs.py",@@ -1356,8 +1371,8 @@},{"path": "mocap/mamma_pipeline.py",- "bytes": 18768,- "sha256": "9330a1e4d7ba4cf633d29d1266e963d429fd081c046c60b01cba3b54ee08b3d9"+ "bytes": 18885,+ "sha256": "e120762e7c7cc06cd203e052e1c3f0c43328af19d416f2c3ce66ae33389a95b2"},{"path": "mocap/mamma_publish.py",@@ -1366,8 +1381,8 @@},{"path": "mocap/mamma_runtime.py",- "bytes": 5788,- "sha256": "e849655d639e8b7c2b42922d10130ee5636bd88d75eb8e843a98b9387a8b2a03"+ "bytes": 5812,+ "sha256": "2e69b856b0969aed3b1e34b02130432f35c3fa434d4e669f11e40943aa6d9757"},{"path": "mocap/mamma_scene.py",@@ -1376,8 +1391,8 @@},{"path": "mocap/mamma_ui.py",- "bytes": 29355,- "sha256": "7de3de21fd0b3499fa39c410e0fd66681f9f116f592d75835b539eec8c77e41e"+ "bytes": 29451,+ "sha256": "ce76f0722729c9730e2318a2de41831744367a9dbaa24eb5949d70c13117f04d"},{"path": "mocap/memory_mode.py",@@ -1411,8 +1426,8 @@},{"path": "mocap/model_guide.py",- "bytes": 9267,- "sha256": "57aae368202a75f565168d9dff6c98154d306f9b099c2d1d4bd86f199ea07e44"+ "bytes": 11197,+ "sha256": "68237776b415954cfc862689d3c82c6cae295fec73c010f05ef1f48f812c28bc"},{"path": "mocap/model_session.py",@@ -1421,8 +1436,8 @@},{"path": "mocap/models.py",- "bytes": 31459,- "sha256": "197eb545df73c7d4027696de69c96acea369411f87c1285e5ebeb82c436a1ca2"+ "bytes": 32610,+ "sha256": "790613eab917ca5d6cc7652b78c89a895de1fa47ce367ea3367767fb3b0e91eb"},{"path": "mocap/motion_tools.py",@@ -1459,11 +1474,36 @@"bytes": 4050,"sha256": "fb59a655440bd0f2faddddbb776fe1bdb1d635c961e02c08615810b874651e53"},+ {+ "path": "mocap/pear/align_worker.py",+ "bytes": 10739,+ "sha256": "acd9de6feda1bbbe76e36e588997bc4cc49a09b726ab5edeceddb4c24561fc96"+ },+ {+ "path": "mocap/pear/alignment_support.py",+ "bytes": 1168,+ "sha256": "c181e2025b6491a80f68f3c954806a63cd280dcf1d9735ac2a5d2d7e4d4b0b09"+ },+ {+ "path": "mocap/pear/batch.py",+ "bytes": 8851,+ "sha256": "df58da66e955b9168704c5ef5d1c21de077a64a3bce8b3f72d37c8d141fc2404"+ },{"path": "mocap/pear/bone_roll.py","bytes": 6416,"sha256": "f3027754de5f0dd9c6d456f28570ec8a960d291f8feda87c996288f28a9eda23"},+ {+ "path": "mocap/pear/camera_preview.py",+ "bytes": 5557,+ "sha256": "278f1173531a1ed3efaaf4c18aa75568cc70835bf6eb323af166f01674a84fed"+ },+ {+ "path": "mocap/pear/camera_stream.py",+ "bytes": 6004,+ "sha256": "50853ff066aa6930a6f9c72ccac7f27c9e8a452df86b5eddc0fa3f59c868443d"+ },{"path": "mocap/pear/core.py","bytes": 9245,@@ -1471,8 +1511,13 @@},{"path": "mocap/pear/fixed_rig.py",- "bytes": 4919,- "sha256": "419dad6e47bf7428902ec877095b5edb69ba8ee6636d74b18bae0d8ff829915e"+ "bytes": 5536,+ "sha256": "0cbc01f81d02ad1e77565ad0e7106772f90b4c0cba2572d81a8a8b888b7cf0fa"+ },+ {+ "path": "mocap/pear/foot_lock.py",+ "bytes": 7940,+ "sha256": "45297770df2dc6f9a0c4abe894179def40ce1914ab2daff5fe09bcfff352a11e"},{"path": "mocap/pear/geometry_compat.py",@@ -1481,14 +1526,24 @@},{"path": "mocap/pear/input_transform.py",- "bytes": 1011,- "sha256": "fd0378f1bb9face1b52a05f24f32a5dc5a2cea99311ccef3b88ebffe3757f9d5"+ "bytes": 1578,+ "sha256": "5d90913d388d5149e39e74bd10f65f7faf8e652395050a060bb4bc9d8da3aed1"},{"path": "mocap/pear/live_view.py","bytes": 3998,"sha256": "cf7606a417d0e174a61ff65aa42c7efbd2b9cbab870948543855b774d17136c6"},+ {+ "path": "mocap/pear/multi_worker.py",+ "bytes": 17008,+ "sha256": "9f514e14860f64e3f249a87c8176adaf49d18b1ba9faac06c804b818afc42f97"+ },+ {+ "path": "mocap/pear/multiview.py",+ "bytes": 5958,+ "sha256": "bc2e5e8ba7646e136f7774a6e601bd80b2e8872d6f93c4dcb5481d0a99ae7532"+ },{"path": "mocap/pear/parameter_io.py","bytes": 1631,@@ -1506,28 +1561,38 @@},{"path": "mocap/pear/session.py",- "bytes": 3216,- "sha256": "1276c11df0d5d83115d643edae98596a0c557964608e6b7f020d87a3bf9f0eba"+ "bytes": 3244,+ "sha256": "257a961856a8d048f08000d13a59bf3786d4c6138da79694ec0fecadd43791ae"+ },+ {+ "path": "mocap/pear/single_alignment.py",+ "bytes": 2179,+ "sha256": "915cedb377a6ee805a9230edf26f5bb4b16fdeb002f2bd95d9511a95bb96aa32"},{"path": "mocap/pear/temporal_filter.py",- "bytes": 5059,- "sha256": "af829508790c84edc732808dcd6dd97175a508fdd9cdbdf77c75d4af74aca08a"+ "bytes": 5330,+ "sha256": "f9909debc7201454576b73d0b7f66f505490639d90f43eb8c9ad9239ba9573d6"},{"path": "mocap/pear/wire.py",- "bytes": 4666,- "sha256": "8e0cc9cafdc374c5dcad0621357456e30f75341449c0ca6f07a9d9ba313d1f0a"+ "bytes": 4896,+ "sha256": "e8e02ba2957cfd9e6e8d49fac1d8c99364b702ffd6bfea50eff5e352f2575ad1"},{"path": "mocap/pear/worker.py",- "bytes": 12549,- "sha256": "60f325208c2224d25b273258e2f1a4cba683625d4f16d9d31ae3c348ac761709"+ "bytes": 15037,+ "sha256": "5622087c5a224cb1670206aa11aebfeca8e22c4b54eb3c034c48594b0d4ca856"},{"path": "mocap/pear_models.py",- "bytes": 4863,- "sha256": "b620d9eb9333a15706daaccd343a8dac851098c4324b7da5ee8ef2c8445d1f62"+ "bytes": 5732,+ "sha256": "3f4ec4ff81d1e5eab20009bb95482c114b0e4e95ff1d89e61de46652e5103555"+ },+ {+ "path": "mocap/pear_multi_ui.py",+ "bytes": 28274,+ "sha256": "2569abcef4a05f3b8b6db27b678626d3104707e07cf85799d1507fde0647f406"},{"path": "mocap/pear_runtime.py",@@ -1536,8 +1601,8 @@},{"path": "mocap/pear_ui.py",- "bytes": 29236,- "sha256": "686bf359438d8175419bf76f6749780c0f2a36960a0a30df01393c65695cd4b8"+ "bytes": 34895,+ "sha256": "1f933754b51420bd7f4ae23905bf8ed2f0cf0a1f7b46e014a0a40cf79c866d1a"},{"path": "mocap/people_store.py",@@ -1546,8 +1611,8 @@},{"path": "mocap/people_ui.py",- "bytes": 38359,- "sha256": "87ad12ccdd1008316afea8a673689c3e758aded846f8fdc15abe4789500db744"+ "bytes": 38409,+ "sha256": "b7adcc7fe5f28593bdf3dabc09aff7212e75a9e669742e50e2d8811ac8caab64"},{"path": "mocap/person_names.py",@@ -1626,8 +1691,8 @@},{"path": "mocap/prompthmr_pipeline.py",- "bytes": 11400,- "sha256": "ec35c9d1871a6fa992ec269b324cefd8a2100cfb2f02d9ab7ad1ccc8415556b1"+ "bytes": 11515,+ "sha256": "b3098bbc038f9f5e25c9b9e96c9ec4fa2116226f74c645089bd328014f024e7d"},{"path": "mocap/prompthmr_publish.py",@@ -1636,8 +1701,8 @@},{"path": "mocap/prompthmr_runtime.py",- "bytes": 3378,- "sha256": "6a2c9d06a77f49f337f61aa1b1210a9b42557849b32ff022c33f83727cf3333b"+ "bytes": 3390,+ "sha256": "3d2daddc130be6c24115e5f14bffe222df1d1364f34c051791cbede3188af8d6"},{"path": "mocap/prompthmr_scene.py",@@ -1656,8 +1721,8 @@},{"path": "mocap/resource_cache.py",- "bytes": 1776,- "sha256": "128666deaa628e32f8d0089338c8d85f16eb7c344a0820e87e19bcc8cf08189c"+ "bytes": 2246,+ "sha256": "4184520af56fe2fb21c4866cf978dfd5d817132142fe9d419b02695adbd1d82b"},{"path": "mocap/result_artifacts.py",@@ -1671,13 +1736,13 @@},{"path": "mocap/retarget/blender_bake.py",- "bytes": 8296,- "sha256": "bde63f85766f36611a5b488f59ad4c11e73d1324528af18a8ac994ca58e7daa3"+ "bytes": 8312,+ "sha256": "fe707ad285f1e0e0a07efcef695ef67f0e0c83aeae3219cb2408e16da18e4384"},{"path": "mocap/retarget/blender_entry.py",- "bytes": 301,- "sha256": "899cd9204837f654eccbb5b06e06e692ec11998ee9403e0b8e8820d276662d0a"+ "bytes": 453,+ "sha256": "51f8a75eabb71738a3b005bd2ad2cba055b52fb3a01fa94029b456e9144ea4bf"},{"path": "mocap/retarget/blender_geometry.py",@@ -1686,8 +1751,8 @@},{"path": "mocap/retarget/blender_io.py",- "bytes": 13050,- "sha256": "fd5a61ade1be86471e90f6f8c6aa743d74614b5d33fcaf7ead9fe5058936055c"+ "bytes": 13066,+ "sha256": "33c49e594bf0502e1e07cd1930751fa6974aed8ec62b73944ae3116ef8753a60"},{"path": "mocap/retarget/blender_textures.py",@@ -1751,8 +1816,8 @@},{"path": "mocap/retarget/source.py",- "bytes": 7136,- "sha256": "93f416e1464408724ed9a1bc0eba59fe97424ef9107164f95106f2f71f5bfb4f"+ "bytes": 7152,+ "sha256": "0eb427f251e258d5103885514e64b2f2a4f43d5505bee40d054580cf07d2e261"},{"path": "mocap/retarget/stabilize.py",@@ -1771,8 +1836,8 @@},{"path": "mocap/retarget/worker.py",- "bytes": 4180,- "sha256": "028aaf016d08aec6e4a0d9d24ff369979934ab16d046e8c57202959a45a3d6cb"+ "bytes": 4196,+ "sha256": "0d23504f5437cf36764eb0d69d9a23613707719e8c6d8650d0f6e8fe4a91626f"},{"path": "mocap/rig_gl.py",@@ -1791,8 +1856,8 @@},{"path": "mocap/runtime_registry.py",- "bytes": 4747,- "sha256": "5e56f969d2509a4200a02911d1d801bf5b43fc50cbb03f6b903879a90533ff20"+ "bytes": 4846,+ "sha256": "68ae06b6c230612066591c2380506dae6886b2ccb779d79c938ff14cb9894b0d"},{"path": "mocap/scene_camera.py",@@ -1801,8 +1866,8 @@},{"path": "mocap/scene_data.py",- "bytes": 19021,- "sha256": "9144d3f5456f220c7bbb5950fe09e3028eb7cd017fd121254f9d284964224567"+ "bytes": 19045,+ "sha256": "a6e7c168de35a73cb0fa2f3b06b2bc4324c6a11c8be4528821f13337cf011529"},{"path": "mocap/scene_export.py",@@ -1906,13 +1971,13 @@},{"path": "mocap/viewer.py",- "bytes": 10547,- "sha256": "d0e0011b4580d2413f65b59d59216e5aadf0cb86a86afbccd51b7b533975bc87"+ "bytes": 11271,+ "sha256": "b12b101f208ce6fbf26aa2bd0f04fd9495aa3917565b1c07c3783d1fdc0910a1"},{"path": "mocap/viewport.py",- "bytes": 52101,- "sha256": "d34193b8f8119014ebcd2f88f6fa84a8b83e9eaa7671f8c871656c6f18c48ef7"+ "bytes": 53337,+ "sha256": "645166692f27f2500b8d3341341c90386311ae0214d21e30ae64a34e4f7e1613"},{"path": "mocap/worker.py",@@ -1921,13 +1986,13 @@},{"path": "mocap/worker_progress.py",- "bytes": 1952,- "sha256": "3ffc6fba68cd26a6a733ce0f7d58b9ee0b34b33756492769cfe4dab2bf9cdbe0"+ "bytes": 2198,+ "sha256": "36901d810180105953dbea6004ba15965a3fce001616dee51c9cce42bbffe789"},{"path": "mocap/workspace_ui.py",- "bytes": 36159,- "sha256": "e31dc3e99adb6fd84bf6c36e4b6a9436b3182e550822deeba1efafd62ee3ae92"+ "bytes": 36206,+ "sha256": "95bb0d45ab7ab5dd3b3b2e561ca09e8b490b323eea677f1d094709a7065f9b02"},{"path": "native_compat/LICENSE",@@ -12611,18 +12676,18 @@},{"path": "tools/build_release.py",- "bytes": 6615,- "sha256": "bee0c764b65b3d5753aeb8c516ec97214dabeb5a7bb7c7b8ba38e84810c6167b"+ "bytes": 6719,+ "sha256": "9572ae86aea8d6f71a9065d69ccdd41c20ba092ccbddfde59432c000a84034d4"},{"path": "tools/build_setup.py",- "bytes": 4972,- "sha256": "8807d02599895c468f4185cb825eddc9bef9892264638ea1750715461c81deb4"+ "bytes": 5006,+ "sha256": "14315f9b1017ec76595f310a41a32c347faec556ba894a29938407ddbdba720f"},{"path": "tools/check_source.py",- "bytes": 3971,- "sha256": "2c65548b8abe5d4893c191a7caaea03076b17ab5f6bed26235af3143ac60106e"+ "bytes": 4019,+ "sha256": "7b4c884279fefffc0e683842886eaed67e9a801a7e9ad9c5a7cea44ec9664340"},{"path": "tools/configure_mamma.py",@@ -12636,8 +12701,8 @@},{"path": "tools/git_bootstrap.ps1",- "bytes": 2195,- "sha256": "2cccf41fcc5d5795356218e222f5cc3e3934510d0fd937921c5fe2c0dbb20cb9"+ "bytes": 2218,+ "sha256": "caf08f71f08681a64f0bf99a8cb10f98a3020a9288d58d297d98e4ee8cbcdd17"},{"path": "tools/git_managed_install.py",@@ -12676,23 +12741,28 @@},{"path": "tools/setup_mamma.py",- "bytes": 14090,- "sha256": "783731563bc03da8302d0a6bf2c2d433232b3d76f06a61063e56511d42fe076f"+ "bytes": 14196,+ "sha256": "f8dac206e723e7ba80feede624c7c9c5d1e69f697fc9b1476c313b7cbd3b67cb"},{"path": "tools/setup_pear.py",- "bytes": 4947,- "sha256": "ff9be39a046f9afa0c083cd0afc175ccde0e2241ea1e6eb1b692230b262e73bc"+ "bytes": 5179,+ "sha256": "bcd4d2e0dbbb6ecb5dfa75455d5a0d0d0f11f50ea99cf79e7973c50c8cbb18ee"+ },+ {+ "path": "tools/setup_pear_alignment.py",+ "bytes": 2836,+ "sha256": "bc43c636f0256898e4dc14731677348464a194bd055ffdaa33c13ace684e3545"},{"path": "tools/setup_prompthmr.py",- "bytes": 9016,- "sha256": "97565c79a0c07160a03397e76617333c2c63ce1014638d9e4c032db654c295d6"+ "bytes": 9108,+ "sha256": "76cab672a109aaf69431d26d1b69939048324dee2055d367f47c46da3d7fe194"},{"path": "tools/stage_assets.py",- "bytes": 2482,- "sha256": "50c92dca840e1f7cd745ca4e10fc6c0b8aef10f3bc634d64d0664dc743f2dfa3"+ "bytes": 2498,+ "sha256": "f72da26c448b83805f159a97dce84f4ad99c93c374b17eab377b68c2090e127e"},{"path": "tools/support_components.py",@@ -12701,8 +12771,8 @@},{"path": "update.cmd",- "bytes": 315,- "sha256": "a1beb113cead13b350e2aa4208b9dcdebe36de6fe26a261b7a2416290e1ca3e5"+ "bytes": 347,+ "sha256": "4cf4ca78309a4e6c4b0decf8995fb4dc227e1702b664180fb5ab0c9481faae08"},{"path": "worker_boot.py",diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 6a7f382..1ad0f5a 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -83,3 +83,13 @@ YOLOv8s/Ultralytics retain their existing AGPL/provider terms. PEAR weights,SMPL-X 2020 and FLAME geometry retain separate provider conditions; registeredbody data is neither committed nor redistributed by RGB MoCap. See the[PEAR guide](docs/models/PEAR.md) and [PEAR paper citation](docs/CITATIONS.md#pear).+++PEAR's automatic Camera Align uses [GeoCalib](https://github.com/cvg/GeoCalib)+(Apache-2.0), with original license retained beside the downloaded source;+Kornia/Kornia-rs keep their wheel licenses. Setup pins sources/wheels in+`installer/pear-alignment.json` and installs a separate support overlay over the+existing Flow runtime. VGGT retains its existing upstream/model terms; its weight+file is reused, not bundled again. GeoCalib's public checkpoint is obtained+separately through Model Manager under CC BY 4.0; the upstream+LICENSE-WEIGHTS is retained with support files. No TensorRT engine/runtime is distributed.diff --git a/app.py b/app.pyindex 53ee69b..b137226 100644--- a/app.py+++ b/app.py@@ -29,10 +29,16 @@ def main():except (AttributeError, OSError):passfrom PySide6.QtWidgets import QApplication- from PySide6.QtGui import QIcon+ from PySide6.QtGui import QIcon, QSurfaceFormatfrom PySide6.QtCore import QTimerfrom mocap.gui import MainWindowfrom mocap.theme import configure_application+ # QOpenGLWidget's private FBO format does not configure the top-level+ # window's composition context. Avoid blocking input on that context's+ # default swap interval; camera redraws are paced in MotionView.+ surface = QSurfaceFormat.defaultFormat()+ surface.setSwapInterval(0)+ QSurfaceFormat.setDefaultFormat(surface)app = QApplication(sys.argv[:1])app.setWindowIcon(QIcon(str(Path(__file__).resolve().parent / "assets" / "rgbmocap-icon.png")))configure_application(app)diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.mdindex 63ea135..31412f9 100644--- a/docs/AGENT_GUIDE.md+++ b/docs/AGENT_GUIDE.md@@ -7,6 +7,7 @@ This guide is for agents helping users operate or modify RGB MoCap. It describes- Windows 64-bit, compatible NVIDIA GPU/driver and OpenGL 4.3 are required for the documented inference workflow. Other systems and GPUs were not comprehensively verified; see [validation](VALIDATION.md).- In a writable checkout, run `install.cmd` once. It sets up separate pinned profiles for ExMR, FlowHMR and GVHMR and their supported add-ons, PEAR support over the shared runtime, Blender 4.5, FFmpeg and the prebuilt native motion-correction module. It does not install only the selected model's runtime or obtain AI weights/body data. Downloading and disk space are required. Models are obtained separately; optional MAMMA uses Setup_MAMMA.cmd and PromptHMR uses Setup_PromptHMR.cmd.- Run `RGBMoCap.cmd`. Keep its command window open; launch errors, processing messages and app Console output are also sent there, but long messages can be truncated and a saturated output queue can drop messages. Within the GUI, **Help > Check System** checks the system.+- Base worker commands use explicit `-X utf8`, including isolated `-I` launches. Isolated mode ignores `PYTHONIOENCODING`/`PYTHONUTF8` from the parent environment. Any redirected/discarded text log stream must also specify UTF-8. Keep byte-oriented PEAR IPC unchanged.- 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; ExMR/FlowHMR/GVHMR and add-ons were previously measured around 29 GiB of weights. Optional MAMMA and PromptHMR add separate runtimes and model files; see [MAMMA](MAMMA.md) and [PromptHMR](models/PROMPTHMR.md). The five offline model/runtime sets total about **63.11 GiB (67.8 GB)** excluding caches, projects, downloads and compiler tools, counting shared files once. See the [installed-size table](USER_GUIDE.md#installed-size); installed size and temporary setup headroom are different. Measurements are not guarantees.@@ -57,6 +58,12 @@ revision as the weights, with SHA-256 validation and a separate import row.It is checkpoint metadata, not app settings. Existing weight and runtime pinsare unchanged. See [validation](VALIDATION.md#exmr-public-api-and-bounded-toe-ik-2026-10-31).+FlowHMR Model Manager also exposes `models/flowhmr/config.json` (25 bytes),+downloaded with the checkpoint from the same pinned Hugging Face revision and+SHA-256 checked. It is download-accounting metadata, separate from the inference+`config.yml`; it is not a new weight, runtime dependency or inference receipt+input. Do not replace the YAML or invalidate motion to add this metadata.+| Model | Practical use | Hands / options || --- | --- | --- || ExMR | Default; generally fast, good quality in the project's subjective tests. SMPL-X. | Fingers included; static/moving camera and smoothing options. |@@ -64,7 +71,7 @@ are unchanged. See [validation](VALIDATION.md#exmr-public-api-and-bounded-toe-ik| GVHMR | Lower overall quality in those tests but sometimes better for unusual poses such as backflips. SMPL-X. | Fingers via optional HandFlow. HTD refines body motion; FootMR refines ankles. Both are separate from contact correction. || MAMMA | Optional multi-view SMPL-X capture from two or more synchronized fixed cameras, without a fixed camera-count maximum. Practical capacity depends on RAM/VRAM. Not part of the single-video quality ranking. | Fingers included; separate setup and locked-head body assets. VGGT or compatible manual calibration. || PromptHMR | Multiple people reconstructed jointly from one video; can improve relative placement and interactions. Overall motion quality was lower than ExMR in our subjective tests. Fixed-camera Windows path, up to eight people; placement can still be wrong. | No finger tracking; fixed neutral fingers. Setup_PromptHMR.cmd; People defaults to 2, Interaction Prompt on. |-| PEAR | Live single-person bone preview from a webcam or the video timeline; transient, with no recording/export or contact correction. | Fingers included; Start/Stop, fixed lengths/Reset Bones, One Euro filter, Rotation and default-on World Position. Shared support is installed by install.cmd. |+| PEAR | Live single-person bone preview from a webcam or the video timeline; transient, with lightweight live foot lock and no recording/export or offline correction. | Fingers included; Start/Stop, fixed lengths/Reset Bones, One Euro filter, Rotation and default-on World Position. Shared support is installed by install.cmd. |Start with the [model guide index](models/README.md), then [ExMR](models/EXMR.md), [FlowHMR](models/FLOWHMR.md), [GVHMR](models/GVHMR.md), [MAMMA](MAMMA.md) or [PromptHMR](models/PROMPTHMR.md) for exact setup and controls. The [user guide](USER_GUIDE.md#recorded-processing-time-and-vram) includes observed timings, conditions and VRAM; these are historical measurements, not minimum specifications. FlowHMR has a 5,000-frame per-take limit and available memory may require less. MAMMA retains its 4–1,800-frame common trim and eight-person limits; there is no fixed camera-count maximum. Four-column thumbnails are a layout, not admission control. Do not change numerical precision, temporal context or model settings merely to improve a benchmark.@@ -240,10 +247,32 @@ The mode checks predate the latest acceleration. Low Memory saves GPU memory,not necessarily RAM; individual CPU-loaded models can add several GiB of hostworking set. Automatic selects a path per operation, not from a guaranteedwhole-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 saved Adaptive 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).+FlowHMR's `flow_sam_batch.py` selects 1/2/4/8/16 frames from current allocation+headroom, free RAM and resolution after loading. Preserve the legacy+`sam_batch4` boolean key so saved off values stay off. The 16-frame ceiling is+a measured efficiency choice, not an upstream model limit. Recheck memory+between prepared batches; retry an unpublished chunk at a smaller batch only+after releasing its OOM traceback. Keep one-frame failures connected to the+existing scoped Low Memory retry. Do not grow queues, change precision, drop+frames or lose the first 30 placement anchors. Include the helper in feature+cache identities; metadata downloads must not invalidate other AI stages.+The 2026-11-02 tests found 16–23% less warm feature time than batch 4, allocated+VRAM 3.84 → 5.43 GiB and about 0.20 GiB more warm RAM. Fresh short app jobs+benefited much less because loading dominated. Official Lite SAM and the combined+GPU body/hand-crop trial were slower here and remain experimental; body-only+cropping was not isolated. Do not silently replace the active+Fast SAM package. See [the full scope](PERFORMANCE.md#flowhmr-adaptive-batches-2026-11-02).++The selected Fast SAM batch upper bound, GPU Hand Crops state, Low Memory+single-frame choice and OOM batch-retry messages are shown in Console and CMD.+Available-memory checks and a final partial batch can lower the effective size;+cached features do not select a new batch. Keep worker `info` events routed through+the console mirror without replacing processing progress or changing inference.+When reporting new tests, keep inputs, model files, settings and timing scopefixed. Separate cold worker startup from warm inference, allocated from reservedVRAM, and working set from private/system RAM. Do not sum speedups from different@@ -272,7 +301,8 @@ Inspect [BUILD.md](BUILD.md), [VALIDATION.md](VALIDATION.md) and relevant code b## PEAR live mode-PEAR support is **experimental**. Tracking and pose estimates may be unstable;+PEAR tracks webcam or video input in real time. Support is **experimental**;+tracking and pose estimates may be unstable;describe it as an experimental preview, not a production-ready capture workflow.Close the app and run `install.cmd`. The base installer also downloads@@ -289,7 +319,7 @@ Manager downloads. MAMMA and PromptHMR still use their separate setup commands.This is a transient single-person preview, not a saved offline project model.`None` in the webcam selector uses video timeline frames; a named camera selects-the webcam input. Neither loads models until Start Live Tracking is pressed. No recording, Find person, contact correction, retargeting or+the webcam input. Neither loads models until Start Live Tracking is pressed. No recording, Find person, offline contact correction, retargeting orexport is available. Preserve offline projects and camera views when switching.Keep requests and output mailboxes bounded/latest-only, run native imports andwarmup before the Windows blocking stdin reader, and release only the worker@@ -312,7 +342,7 @@ stopped. Start Live Tracking explicitly enables loading/warmup and tracking;the same button becomes Stop immediately, including during loading. Stopinvalidates pending output, stops playback and closes only this session's worker,capture and GPU data off the GUI thread. Disable Start until the old worker exits;-never overlap workers or automatically restart after Stop/error/leave/reselect.+never overlap model workers or automatically restart them after Stop/error/leave/reselect.A new Start loads a fresh worker. While running, input changes reuse its model.PEAR alone uses the pinned YOLOv8s asset (`pear_yolo`, `models/yolo/yolov8s.pt`).Keep its size/hash-checked Model Manager download/import and trusted loader.@@ -321,6 +351,28 @@ can alter pose predictions; detection success is not an accuracy measurement.Idle acknowledgement keeps a deliberately waiting started worker from appearingstalled. Keep RAM/VRAM monitoring and bounded mailboxes while it is running.+Selecting a webcam may create the separate `pear_camera_preview` capture worker.+It imports OpenCV/NumPy, not PEAR or Torch, and uses bounded latest-frame buffers+with a bounded 1280x720 displayed image.+Partial slot assignment is previewable; tracking still requires distinct devices+in every slot. Keep per-device rotation and thumbnail selection active. This+worker alone owns the physical devices and remains connected during Start and+Camera Align. `pear/camera_stream.py` publishes one fixed-size Windows shared+frame per device under a named mutex; model workers use independent RemoteCamera+readers and never reopen those devices. Validate descriptors/device identities,+retain bounded copy/age checks and release reader handles on worker replacement.+Shared raw frames have a 64 MiB per-frame / 512 MiB aggregate allocation limit;+these are not whole-process RAM limits or silent downsampling. No per-frame file+writes are introduced. Keep PEAR and calibration GPU models sequential while+capture and image preview continue. Stop suspends automatic camera+preview until device/rotation/resolution changes or Refresh. None/leave/app close+release preview capture too. Failure stays visible without an automatic restart+loop. Preview does not need model weights or an installed PEAR support overlay.+Video decoding/playback remains available while models load or cameras align.+Freeze alignment sample frame/generation at the click, separately from later+seek epochs. Raw preview rotation is painting-only; completed rotated image/pose+pairs must not be rotated twice. Reset the raw-preview rotation on leaving PEAR.+During PEAR video playback, present each completed image/pose pair together,accepting monotonically newer results within the current source/seek epoch.Never require a playing result to equal the newest outstanding request: inference@@ -367,7 +419,16 @@ paused output immediately. Reset Bones keeps the anchor; a new input or Stopclears it and releases the cached pose. On restores the raw estimated position,so a position change is expected. This is pelvis locking, not foot locking.-PEAR's **One Euro Filter** and **Rotation** apply to webcam and video inputs. Rotate+PEAR's **One Euro Filter** and **Rotation** apply to webcam and video inputs.+All webcam slots belong in one numbered Camera / Device / Rotation table below+the video, with Count/Refresh in that panel and a bounded vertical scroll area.+Do not split camera 1 into the video header. Rotation is independent for each+device; do not restore a shared right-sidebar rotation. In video mode,+the first field edits the selected thumbnail's video, retaining other inputs'+values. Pass ordered per-input `rotations` through ordinary tracking and Camera+Align sampling, invalidate alignment after any angle change, and preserve values+on thumbnail/device refresh. The worker accepts the older scalar `rotation` only+as a compatibility fallback when the ordered list is absent. Rotatepixels before detection/inference, then display the matching rotated image evenwhen paused. Source files are never rewritten. Smoothing is a causal adaptiveparameter filter on rotations/shape/face plus a vector-speed root filter; it changes@@ -386,7 +447,85 @@ Reset temporal state on missing people, input/rotation/enable changes, reverse tlong gaps; preserve the existing placement origin during same-source seeks.Retain the last matched image/pose while a seek, pause or smoothing toggle computesits replacement; clear it for a real missing-person result, error or changed input.+Under One Euro Filter, Bone Rotation and World Position are separate default-on+component switches. Requests carry `smooth_rotations` and `smooth_position`;+absent fields retain the previous both-on behavior. The parent `smoothing` flag+gates both. The position-filter switch does not disable world movement or Foot+Lock. Reset only the disabled component; retain the other filter history and+strength. Repeated timestamps from paused control refreshes retain the unaffected+filtered value instead of reseeding it. Actual seeks/gaps still reset normally.A smoothing-only toggle must not reopen capture, reacquire identity, reframe thecamera or reset the placement origin. It is not an offline full-sequence smootheror a guarantee of identical live/seek history.Keep the one resident model, latest-only controls and fixed memory bounds.+++### PEAR multiview fixed-camera preview++PEAR now accepts multiple video files through File > Open Video using the MAMMA+input inspector/thumbnail style. The common 30 fps timeline trims every view;+inputs must already be synchronized. Webcam camera-count slots require distinct+devices, with thumbnails selecting the main preview. Start/Stop remains explicit.+Start Live Tracking attempts Camera Align first for one or more cameras. A failure+continues tracking in the selected camera without fusion or aligned foot lock,+with a persistent visible warning and a console message. Missing alignment-only+support/models must not block otherwise-ready PEAR tracking. After alignment,+`pear/multiview.py` fuses rotations on one fixed rig and solves root position from+reprojection. Default-on lightweight Foot Lock uses pre-correction contact evidence, smooth activation/release and fixed-length two-bone leg adjustments. Preserve ankle/toe world rotations and the inferred bend side; cap pelvis shift at 4 cm and allow residual reach error. World Position off prohibits pelvis movement. Reset lock state on missing input, discontinuity or calibration changes; never feed corrected positions into contact detection. No offline correction, recording, retargeting or export is run.++`pear_multi_ui.py` manages transient inputs and calibration. `pear/multi_worker.py`+uses a four-thread CPU pool, bounded capture buffers and GPU batches of at most+four. YOLOv8s stays FP32; PEAR retains its validated FP16 encoder/FP32 decoder.+The graph path has no TensorRT dependency. Camera Align uses a separate+`flow_pear_align` worker over the pinned Flow runtime, sequential VGGT and GeoCalib+GPU stages, and a small GeoCalib/Kornia support overlay from install.cmd/update.cmd.+Model Manager reuses `flow_vggt` and separately obtains SHA-256 checked+`pear_geocalib`. Both weights are required for automatic alignment, including single-view alignment. Missing weights must show an actionable warning while allowing selected-camera tracking. Unaligned placement is approximate; do not claim fused/calibrated output.++Preserve shared runtime packages. `installer/pear-alignment.json` pins the source+and wheels; `tools/setup_pear_alignment.py` installs them under runtime_pear with a+separate inventory receipt. Re-run install.cmd after support changes; never forge+receipts. Initial pose is not an upright constraint. Background geometry supplies+camera orientation/floor; metric scale is inferred from fixed bone lengths.+Changed inputs/rotation/resolution and successful Reset Bones trigger another alignment attempt; failure continues with the selected camera and a warning. Physical camera movement needs an explicit Camera Align. Single-view scale uses inferred metric limb geometry and predicted person depth, so it remains an estimate.+Webcam host-arrival pairing is approximate (80 ms skew bound), not hardware sync.++Keep samples/benchmarks under an ignored/private experiment directory, not Git.+Alignment samples live only in cache/pear/alignment; successful jobs remove images.+Cancel stale alignments and reject mismatched receipts. Preserve offline media,+selection, trims and camera on leaving PEAR. Test paired playback, seeks, thumbnail+switches, cancellation, Stop/reopen and source replacement; actual multiple-webcam+performance requires physical devices and must not be claimed from video simulation.+++## International Windows filenames and text output++Use UTF-8 explicitly for application JSON, text logs and subprocess text pipes.+Launch every isolated/development Python worker and setup verifier with+`-X utf8`; `-I` ignores the parent's `PYTHONUTF8` and `PYTHONIOENCODING` settings.+The GUI uses separate incremental UTF-8 decoders for each worker channel and+character job. Preserve decoder state between pipe chunks and flush at EOF;+never decode each arbitrary chunk independently. Keep existing buffer limits.+PEAR's binary IPC remains binary and must not pass through these decoders.++Use `mocap.image_io.read_image` / `write_image` for filesystem-backed OpenCV+images on Windows. They retain the existing codec and pixels, while Python+handles Unicode filenames. MAMMA's upstream-script calls and PromptHMR's isolated+worker use the temporary `unicode_image_paths` scope. It restores OpenCV entry+points even on errors. Do not apply this process-wide scope in the GUI or in a+process running concurrent unrelated jobs. Include this helper in affected+inference receipts; never bypass generation validation.++Pass filesystem paths as argument-list elements rather than shell fragments.+Keep delayed expansion disabled in entry-point CMD files so exclamation marks+in installation paths survive. Generated UTF-8 native-build CMD files must+select code page 65001 before reading non-ASCII command lines. Do not change+model versions, regional Windows settings or source motion to repair text.+VMD's specified CP932 fields remain CP932; an international file path does not+make that legacy file format capable of storing every Unicode label.++The 2026-11-02 checks covered English, Western European accents, Japanese,+Cyrillic, Korean, Chinese, combining accents and emoji paths on one Windows PC.+Hostile parent encodings were simulated; different OS languages, clean installs+and fresh CUDA compilation in every such path were not independently tested.+See the [validation record](VALIDATION.md#international-windows-paths-and-output-2026-11-02).diff --git a/docs/BUILD.md b/docs/BUILD.mdindex 83e4a7a..8b492f9 100644--- a/docs/BUILD.md+++ b/docs/BUILD.md@@ -202,6 +202,14 @@ a source/base change or damaged support stages and CUDA-verifies a new generatiobefore replacing the pointer. Failure leaves prior support and the install retrymarker intact. No weights or registered geometry are acquired by this step.+`tools/setup_pear_alignment.py` additionally stages the pinned GeoCalib/Kornia+support from `installer/pear-alignment.json`, over the existing Flow runtime,+without upgrading shared packages. It verifies imports/CUDA availability and+writes a separate `.setup/pear-alignment.json` inventory. VGGT/GeoCalib model+weights are obtained in Model Manager. This support enables camera alignment;+if it is unavailable, PEAR can still track the selected camera with a warning,+provided its base support and model files are ready.+Changed upstream files receive an adaptation notice. Each support generationalso records pinned source URLs/hashes and the adapter hash in`RGB_MOCAP_PROVENANCE.json`, alongside the retained provider license files.diff --git a/docs/CITATIONS.md b/docs/CITATIONS.mdindex 01e0849..ac835a1 100644--- a/docs/CITATIONS.md+++ b/docs/CITATIONS.md@@ -143,3 +143,23 @@ When using ExMR, also cite FootMR and the original GVHMR work.Cite optional HTD-Refine and HandFlow when using those add-ons. Theapplication's use of Kimodo MotionCorrection does not imply use of the Kimodotext-to-motion generator.+++## GeoCalib (PEAR Camera Align)++[Original project and citation](https://github.com/cvg/GeoCalib) ·+[Code license](https://github.com/cvg/GeoCalib/blob/1dedb29f94fc11b896c5f572005978aeebccd67f/LICENSE) ·+[Weight license](https://github.com/cvg/GeoCalib/blob/1dedb29f94fc11b896c5f572005978aeebccd67f/LICENSE-WEIGHTS)++```bibtex+@inproceedings{veicht2024geocalib,+ author = {Alexander Veicht and Paul-Edouard Sarlin and Philipp Lindenberger and Marc Pollefeys},+ title = {{GeoCalib: Single-image Calibration with Geometric Optimization}},+ booktitle = {ECCV},+ year = {2024}+}+```++Camera Align also uses VGGT-Omega with its existing source/model acknowledgements.+Its background-floor estimation and fixed-rig multiview fusion are application+features, not an official PEAR multiview inference mode.diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.mdindex 75b830c..38d3550 100644--- a/docs/PERFORMANCE.md+++ b/docs/PERFORMANCE.md@@ -185,7 +185,9 @@ output disagreements, not accuracy against ground-truth capture.### FlowHMR Fast SAM switchesBoth switches default on for new work; saved off settings remain off. They work-only with Fast SAM and can be controlled independently:+only with Fast SAM and can be controlled independently. The following records+describe the earlier 4-frame implementation; the current Adaptive Batching+policy and its additional measurements follow below:- **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@@ -202,6 +204,57 @@ differs from CPU OpenCV cropping; combined output differences reached abouttested clips. This is a separate comparison from the sub-millimetre prefetchtest above. Inspect your motion/contact timings rather than assuming bit identity.+### FlowHMR adaptive batches (2026-11-02)++**Adaptive Batching** replaces the 4-Frame Batching label while retaining its+saved boolean. Automatic checks free VRAM, reusable allocator cache, the process+allocation cap, free RAM and image dimensions after model loading. It selects+1/2/4/8/16 frames and rechecks headroom between prepared batches. The existing+Windows GPU reserve is retained, not subtracted twice. Low Memory and a disabled+batching checkbox always use one frame. Decoder precision, crop resolution,+temporal context, frame count and the first 30 placement anchors are unchanged.++On the same RTX 5090/Windows test PC, two 1080p landscape/portrait clips gave:++| Measurement | Previous batch 4 | Batch 16 |+| --- | ---: | ---: |+| Warm features, 60 frames | 4.71 s | 3.98 s |+| Warm features, 120 frames | 9.86 s | 7.63 s |+| Peak allocated VRAM | 3.84 GiB | 5.43 GiB |+| Peak reserved VRAM | 4.34 GiB | 6.81 GiB |+| Warm RAM working set, 60 frames | 2.54 GiB | 2.74 GiB |+| Warm RAM working set, 120 frames | 2.89 GiB | 3.08 GiB |++Warm timers exclude initialization and decoding; they are the second complete+sequence pass after warmup, not full-job acceleration guarantees. Fresh app+feature jobs including initialization were 34.80 → 34.88 s and+39.77 → 38.74 s; their RAM peaks remained about 6.5 GiB. At batch 32, allocated+VRAM reached 7.56 GiB and the 120-frame warm pass took 7.32 s, only about 4%+less than 16. The current ceiling therefore favors 16's measured efficiency.+Other GPUs, drivers, inputs and concurrent applications can differ.++Across the actual app paths, final joint disagreements against the previous+batch-4 output were p95/max **0.15/0.59 mm** and **0.44/1.63 mm**. Placement+offset changes were below 0.08 mm. Existing repeat extractions also had small+numerical differences; these are output disagreements, not ground-truth error.+Low Memory remained one frame and measured 1.91 GiB allocated in both versions.+Cache reuse, sequential actor/model reuse and interrupted-job recovery were+exercised. A controlled 4.4 GiB allocator cap triggered 16 → 8 → 4 retries+without dropping frames or publishing a partial feature file. This is a local+allocation-failure test, not a clean-PC or physically exhausted-GPU test.++The [FlowHMR team's performance proposal](https://github.com/toyxyz/toyxyz_RGBMocap/issues/17)+and [upstream measurements](https://github.com/flowhmr/flowhmr/blob/main/docs/performance.md)+also motivated separate Lite SAM and OpenCV-style GPU body/hand crop tests.+At batch 16, official Lite GPU extraction took 4.11/8.69 s on the two clips,+versus Fast SAM's 3.98/7.63 s. Its full-output placement path was also slower.+The exact-coordinate crop candidate over the existing Fast path took 4.50 s+on the 60-frame clip. Neither candidate is enabled; Fast SAM remains the app+backend. Body-only cropping was not isolated in that combined crop test.+Compilation, TensorRT, model weights and installed dependencies are+unchanged. The upstream A100 report compares against an unaccelerated original+baseline, so its 5–10× claim must not be applied to this app's previous Fast path.+### MAMMAThe current MAMMA adapter uses exact-coordinate ROI preprocessing, CPU checkpointdiff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 155b028..82a1bff 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -183,10 +183,12 @@ Shared model files and hardlinks are counted once.| MAMMA additional files | 6.11 GiB | 3.42 GiB | 9.54 GiB || PromptHMR additional files | 6.22 GiB | 6.13 GiB | 12.34 GiB || **Five offline models** | **24.68 GiB** | **38.44 GiB** | **63.11 GiB** |-| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.84 GiB | ~2.84 GiB |+| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.95 GiB | ~2.96 GiB |Adding PEAR to all five offline sets gives an estimated combined total of about-**65.95 GiB (70.8 GB)**. Its original geometry ZIP needs additional download space.+**66.07 GiB (70.9 GB)**. This includes about **0.11 GiB** of required GeoCalib weights; existing VGGT weights are reused. The approximately+11.3 MiB support overlay is included in base setup. Its original+geometry ZIP needs additional download space.Totals use unrounded bytes; rounded cells may not sum exactly. These are localobservations, not universal requirements. App source files add space beyond this@@ -227,7 +229,7 @@ may be outside the installation folder.| `<install folder>\.setup\downloads\`, `.setup\uv-cache\` and `.setup\tmp\` | Downloaded wheels and temporary cache can be removed only after installation or update completes. They are reused for repair and updates; deleting them may require downloading files again. Keep the rest of `.setup`, including the private Python and installation state. || `<install folder>\.setup\mamma-downloads\` | Optional MAMMA package/source download cache. Its contents can be removed after MAMMA setup finishes; repair may need to download them again. Keep `runtime_mamma` and `.setup/mamma-runtime.json`. || `<install folder>\.setup\prompthmr-downloads\` | Optional PromptHMR package/source download cache. Remove contents only after setup finishes; repair may need to download them again. Keep `runtime_prompthmr` and `.setup/prompthmr-runtime.json`. |-| `<install folder>\.setup\pear-downloads\` | PEAR source/support archives. Contents can be removed after installation/update finishes; repair may download them again. Keep `runtime_pear` and `.setup/pear-runtime.json`. |+| `<install folder>\.setup\pear-downloads\` | PEAR source/support and camera-alignment archives. Contents can be removed after installation/update finishes; repair may download them again. Keep `runtime_pear`, `.setup/pear-runtime.json` and `.setup/pear-alignment.json`. || `<install folder>\temp\` | Local PEAR Torch/kernel temporary cache. Contents can be removed after closing the app and its workers; the next run can recreate them. |Repeated work mainly grows project data: each model has its own result folder.@@ -318,7 +320,7 @@ opening a project restores its saved model. **Prepare Preview**, below| **GVHMR** | Lowest overall quality in our tests, but sometimes better for unusual poses such as backflips. | Optional **HandFlow**; not inferred by GVHMR itself. || **MAMMA** | Multi-view capture of human motion and interactions. Needs separate setup and overlapping synchronized views; outside the quality ranking above. | Included. || **PromptHMR** | Can improve relative placement and interactions between multiple people in one fixed-camera video. Overall motion quality was lower than ExMR in our subjective tests; contacts and depth can still be wrong. Separate setup. | No finger tracking; fixed neutral pose. |-| **PEAR** | Live single-person bone preview from a webcam or video. No motion recording, correction, retargeting or export in this mode. | Included. |+| **PEAR** | Live single-person bone preview from a webcam or video. Lightweight live foot lock; no offline correction, recording, retargeting or export. | Included. |The five offline models support contact correction, a 52-bone overlay and FBX export.ExMR/FlowHMR/GVHMR use **Find person** for explicit people selection; MAMMA@@ -484,7 +486,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 → Fast SAM Acceleration** | Two independent, default-on switches: **Adaptive Batching** and **GPU Hand Crops**. Automatic selects 1, 2, 4, 8 or 16 frames from memory headroom and image size; Low Memory or disabling batching uses one frame. Used only with Fast SAM, on Reconstruct 3D. Tooltips and the [FlowHMR guide](models/FLOWHMR.md#controls) explain speed, VRAM and output differences. Batch selection and OOM retry messages appear in Console and CMD. || **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. |@@ -638,17 +640,55 @@ terms; see [Third-party notices](../THIRD_PARTY_NOTICES.md).Run `install.cmd` with the app closed; PEAR support is included. PEAR reusesthe shared runtime and adds only pinned source/utilities; no compiler is required.-Prepare its checkpoint and registered SMPL-X 2020/FLAME bundle in Model Manager.-Select **PEAR · Live (Experimental)** and click **Start Live Tracking** to load the models.+PEAR tracks webcam or video input in real time; it may skip frames to limit delay.+Prepare its checkpoint, detector and registered SMPL-X 2020/FLAME bundle in Model+Manager. VGGT and GeoCalib are additional files for Camera Align.+Select **PEAR · Live (Experimental)** and click **Start Live Tracking**. It attempts+to align one or more fixed cameras before tracking; keep the person and floor+visible during alignment. If alignment fails or its support/models are missing,+tracking continues from the selected camera with a visible warning. It does not+fuse unaligned views or apply aligned live foot lock. Retry with **Camera Align**.**Stop** ends tracking and releases the models and webcam. With **Webcam: None**,open a video and seek/play its timeline to infer the current frame. Alternatively,select a connected webcam before starting. While tracking is running, input-changes reuse the loaded models. Rotation and smoothing apply to both sources.+changes automatically align the new configuration. Ordinary seeks and thumbnail changes reuse the loaded tracking model. Rotation and smoothing apply to both sources. Under **One Euro Filter**, select+**Bone Rotation** and **World Position** independently (both default on). Its+World Position checkbox controls position smoothing; the separate top-level+World Position switch controls whether the pelvis moves at all.+Selecting a webcam shows an image preview without loading PEAR; Start is needed+for pose tracking. After Stop, reselect a webcam or Refresh to preview again.+Webcam capture stays connected during Start, model loading and Camera Align.+Opened videos can play, pause and seek during loading/alignment; alignment uses+the sample time selected when Camera Align was clicked.+All webcam selectors are grouped below the video in a numbered Camera / Device /+Rotation table, with Count and Refresh together above it. Each webcam has its own+Rotation field beside its selector. For+videos, select a thumbnail and use the first Rotation field; other videos retain+their angles. Changing any angle requires Camera Align again.The live view shows fixed-length body and finger bones without per-frame bodymesh calculation. **Reset Bones** recalibrates their lengths from the displayed-pose, pauses video playback and retains the loaded models and viewport camera.+pose, pauses video playback and realigns cameras while preserving the viewport camera.**World Position** is on by default. Turn it off to hold the pelvis at its currentposition, including height, while retaining pelvis rotation and joint motion.-There is no Find person, recording, correction, retargeting or animation export+**Foot Lock** defaults on, becomes active after successful alignment and applies small causal leg/pelvis corrections with smooth lock/release transitions. Fixed lengths and ankle/toe orientations remain; turning World Position off keeps the pelvis fixed, even if a foot cannot reach. Poor calibration and source jitter can still cause sliding. There is no Find person, recording, offline correction, retargeting or animation exportin this live mode. Switching models releases the live worker and device.-See the [PEAR guide](models/PEAR.md) for setup, resources and limitations.+For multiple fixed views, select several synchronized videos or set the webcam+**Count** and assign distinct devices to its slots. Thumbnails select the main+preview. Start attempts **Camera Align** using VGGT/GeoCalib, including one camera;+alignment errors no longer block selected-camera tracking. Reset Bones also+triggers an alignment attempt. Synchronization and+background camera/floor estimates are approximate. See the+[PEAR guide](models/PEAR.md) for setup, resources and limitations.+++## International filenames++Video, project, character and export paths support Unicode filenames, including+Japanese, Korean, Chinese, Cyrillic and Western European accents. The Windows+launchers and Python workers use explicit UTF-8, and image file I/O avoids+OpenCV's Windows filename code-page limitation. The interface remains English.++If a text-encoding error occurs, record the complete error and the operation+that triggered it. Updating code is preferable to renaming all files or changing+the Windows system language. VMD retains its format-defined CP932 name fields;+this restriction is separate from the filename used to save it.diff --git a/docs/VALIDATION.md b/docs/VALIDATION.mdindex fce74e0..0a4cd4e 100644--- a/docs/VALIDATION.md+++ b/docs/VALIDATION.md@@ -458,51 +458,51 @@ disablement, Fast SAM off, and all four model pages at short/tall window heightsThe settings use consistent top-down spacing and scroll when needed; hiddenmodel pages no longer reserve the tallest page's height. Test files and logsremain 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.+++## 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)@@ -680,97 +680,97 @@ unmaterialized-meta rejection. Test files, raw logs and assets stay outside the- Test programs, source videos, model weights and outputs were kept outside thepublic source file list. Restricted upstream PromptHMR source is downloadedlocally by setup, rather than bundled into the source distribution.---## PromptHMR untracked hand placeholders (2026-10-31)--The pinned native video path writes zero 3×3 matrices for all 30 untracked finger-joints. They are not rotation matrices; subsequent axis-angle conversion produced-a fixed 120-degree rotation at every joint. Earlier native-mesh equivalence checks-preserved that invalid posture and did not establish a valid hand default.--Publication now uses the registered relaxed hand mean for this all-zero missing-hand case, while keeping raw native inference files intact. Valid native hand-rotations keep their prior conversion; inconsistent invalid matrices are rejected.-Receipts record the hand policy. Older published results show a refresh notice.--Private copies of two two-person clips (32 and 85 frames) were republished from-cached inference. Original and corrected body/root/shape tensors were exact;-the first 22 body/wrist joint positions were unchanged. Four original/corrected-FBXs imported into Blender with 52 bones and 30 finger bones. Local finger-rotation variation across the 32 frames was zero. Source projects/raw caches were-not changed. The runtime and AI inference calculations were not modified.---## ExMR public API and bounded toe IK (2026-10-31)--The integrated upstream source is v0.1.5, commit-`57e4824b9c532b52ed1c8b12c44000ad41ef4c4c`, retaining the documented Windows,-Low Memory, bounded prefetch and stage-scoped reuse adaptations. Public-`hand_boxes`, `model_inputs`, `ExMR.from_pretrained` and direct model forward-replace private pipeline calls. Upstream toe IK now limits its target offset to-0.03 m per axis. Existing weights, runtime package pins and other model backends-are unchanged.--Only those numerical changes were adopted. The app keeps its existing world-frame through an explicit local `normalize_world=False` option (generic upstream-default remains enabled). The upstream Boolean foot-contact detector is not-used by app correction. Shared contact code and manual timing precedence remain-unchanged. Source/API/solver hashes invalidate outdated ExMR stage receipts;-opening saved projects does not initiate reconstruction.--- Seven cached-feature actor segments from five real scenes (997 actor frames)- produced tensor-exact camera/world parameters and static-confidence logits- against the independently verified toe-only reference. Scenes included two- dancers, burpees, stairs, moving-camera motion and two-person interaction.-- Fresh 60- and 45-frame actors passed keypoint, body-feature, hand-feature and- motion stages in Automatic and Low Memory. Model instances were reused- sequentially within each phase and released on session exit. Observed stage- sums were 46.69 and 53.00 seconds; these single runs are not a controlled- speedup benchmark or universal performance promise.-- Original/corrected meshes, paired shared cameras and shared-floor correction- completed. Eight actual app FBX exports imported in Blender 4.5 with 52 bones,- Hips root, finite bone-only keys and rest geometry distinct from animation.-- The new SimpleVO JPEG-input path differed substantially on a moving-camera- sample. A small explicit frame-reader/count adapter retains the old canonical- video pixels without extracting another JPEG sequence. A 267-frame Unicode-path- test reproduced old rotations within 0.0000014 degrees; repeated calls reused- the cache without rewriting it. Neither estimate was scored against camera- ground truth.-- Updated stale inference receipts recomputed successfully; an immediate repeat- hit the cache without rewriting motion. Changing the solver hash invalidated- the stage identity. Manual intervals remained authoritative when automatic- confidence was zero.--The separate contact-policy comparison did not justify replacing shared contact-detection. On the stairs segment, maximum frame-to-frame change of *added knee-flexion* decreased from 3.553 to 1.983 degrees with the new toe IK and current-contact policy, but rose to 4.114 degrees with the official Boolean timings used-directly. This is not total knee jitter or error against motion ground truth.-The body-height-only gate excluded just two frames across the tested segments;-the existing large burpee transition remained. No blanket contact-quality claim-is made. No clean Windows installation or second GPU was tested, and the other-four models were not fully reinferred for this ExMR-only integration. Private-test programs, footage, registered bodies and outputs remain outside the public-source distribution.---## Official ExMR checkpoint metadata (2026-10-31)--Model Manager includes `ExMR configuration` (`models/exmr/config.json`, 180-bytes), pinned to the same Hugging Face revision as the existing ExMR weights.-Download All and the row's Auto Download use the official HTTPS endpoint and-SHA-256 validation. Manual Download and Import use that same revision. It is-checkpoint metadata; it does not alter model architecture or app settings.--The actual download passed size/hash checks in an isolated data folder. A second-call performed no network request or file rewrite. Invalid manual imports were-rejected while preserving the valid file; a valid import succeeded. Offscreen-Qt checks confirmed the row only appears for ExMR, changes to Ready after-validation and leaves other model scopes unchanged. The development app also-downloaded and verified its own copy. Test artifacts and model files remain-outside the public source manifest. This metadata-only registration does not-require a runtime reinstall or a new checkpoint.+++## PromptHMR untracked hand placeholders (2026-10-31)++The pinned native video path writes zero 3×3 matrices for all 30 untracked finger+joints. They are not rotation matrices; subsequent axis-angle conversion produced+a fixed 120-degree rotation at every joint. Earlier native-mesh equivalence checks+preserved that invalid posture and did not establish a valid hand default.++Publication now uses the registered relaxed hand mean for this all-zero missing+hand case, while keeping raw native inference files intact. Valid native hand+rotations keep their prior conversion; inconsistent invalid matrices are rejected.+Receipts record the hand policy. Older published results show a refresh notice.++Private copies of two two-person clips (32 and 85 frames) were republished from+cached inference. Original and corrected body/root/shape tensors were exact;+the first 22 body/wrist joint positions were unchanged. Four original/corrected+FBXs imported into Blender with 52 bones and 30 finger bones. Local finger+rotation variation across the 32 frames was zero. Source projects/raw caches were+not changed. The runtime and AI inference calculations were not modified.+++## ExMR public API and bounded toe IK (2026-10-31)++The integrated upstream source is v0.1.5, commit+`57e4824b9c532b52ed1c8b12c44000ad41ef4c4c`, retaining the documented Windows,+Low Memory, bounded prefetch and stage-scoped reuse adaptations. Public+`hand_boxes`, `model_inputs`, `ExMR.from_pretrained` and direct model forward+replace private pipeline calls. Upstream toe IK now limits its target offset to+0.03 m per axis. Existing weights, runtime package pins and other model backends+are unchanged.++Only those numerical changes were adopted. The app keeps its existing world+frame through an explicit local `normalize_world=False` option (generic upstream+default remains enabled). The upstream Boolean foot-contact detector is not+used by app correction. Shared contact code and manual timing precedence remain+unchanged. Source/API/solver hashes invalidate outdated ExMR stage receipts;+opening saved projects does not initiate reconstruction.++- Seven cached-feature actor segments from five real scenes (997 actor frames)+ produced tensor-exact camera/world parameters and static-confidence logits+ against the independently verified toe-only reference. Scenes included two+ dancers, burpees, stairs, moving-camera motion and two-person interaction.+- Fresh 60- and 45-frame actors passed keypoint, body-feature, hand-feature and+ motion stages in Automatic and Low Memory. Model instances were reused+ sequentially within each phase and released on session exit. Observed stage+ sums were 46.69 and 53.00 seconds; these single runs are not a controlled+ speedup benchmark or universal performance promise.+- Original/corrected meshes, paired shared cameras and shared-floor correction+ completed. Eight actual app FBX exports imported in Blender 4.5 with 52 bones,+ Hips root, finite bone-only keys and rest geometry distinct from animation.+- The new SimpleVO JPEG-input path differed substantially on a moving-camera+ sample. A small explicit frame-reader/count adapter retains the old canonical+ video pixels without extracting another JPEG sequence. A 267-frame Unicode-path+ test reproduced old rotations within 0.0000014 degrees; repeated calls reused+ the cache without rewriting it. Neither estimate was scored against camera+ ground truth.+- Updated stale inference receipts recomputed successfully; an immediate repeat+ hit the cache without rewriting motion. Changing the solver hash invalidated+ the stage identity. Manual intervals remained authoritative when automatic+ confidence was zero.++The separate contact-policy comparison did not justify replacing shared contact+detection. On the stairs segment, maximum frame-to-frame change of *added knee+flexion* decreased from 3.553 to 1.983 degrees with the new toe IK and current+contact policy, but rose to 4.114 degrees with the official Boolean timings used+directly. This is not total knee jitter or error against motion ground truth.+The body-height-only gate excluded just two frames across the tested segments;+the existing large burpee transition remained. No blanket contact-quality claim+is made. No clean Windows installation or second GPU was tested, and the other+four models were not fully reinferred for this ExMR-only integration. Private+test programs, footage, registered bodies and outputs remain outside the public+source distribution.+++## Official ExMR checkpoint metadata (2026-10-31)++Model Manager includes `ExMR configuration` (`models/exmr/config.json`, 180+bytes), pinned to the same Hugging Face revision as the existing ExMR weights.+Download All and the row's Auto Download use the official HTTPS endpoint and+SHA-256 validation. Manual Download and Import use that same revision. It is+checkpoint metadata; it does not alter model architecture or app settings.++The actual download passed size/hash checks in an isolated data folder. A second+call performed no network request or file rewrite. Invalid manual imports were+rejected while preserving the valid file; a valid import succeeded. Offscreen+Qt checks confirmed the row only appears for ExMR, changes to Ready after+validation and leaves other model scopes unchanged. The development app also+downloaded and verified its own copy. Test artifacts and model files remain+outside the public source manifest. This metadata-only registration does not+require a runtime reinstall or a new checkpoint.## PEAR live integration (2026-10-31)@@ -1281,3 +1281,318 @@ and credential candidates, and excluded runtime/model/project/test payloads.Private tests and derived files remain outside the source checkout. These aretests on the existing Windows PC, not a fresh OS, alternate GPU or new physicalwebcam certification. Short playback checks do not establish long-term leak freedom.+++## PEAR fixed-camera multiview preview (2026-11-01)++Added multiple synchronized video inputs with a common 30 fps trim, four-column+preview thumbnails, distinct webcam assignment slots, and explicit Camera Align.+The latter runs person-masked VGGT camera/depth and GeoCalib gravity sequentially+in a separate Flow-profile worker, then restarts PEAR to avoid GPU overlap.+Scale is inferred from fixed bone lengths; background depth estimates the floor.+No upright-pose constraint or foot lock is added. These are estimates, not measured+calibration. More physical webcams and other GPUs remain unverified.++The production multiview path uses FP32 YOLOv8s, exact BGR crops, four bounded CPU+threads and at most four GPU rows, with the existing FP16 PEAR encoder/FP32 head.+Fixed-size padded rows avoid graph recapture during occlusion; they are excluded+from output/fusion. No TensorRT package or engine is required. Setup staged the+pinned GeoCalib/Kornia overlay and verified imports on the existing Windows Flow+runtime. SHA-256 checked model import, optional manager rows and existing base+PEAR startup were exercised; this is not a clean-PC installation test.++On the previously documented RTX 5090 test PC, a 12-frame/four-view port check+against cached single-view PEAR predictions measured root-relative joint+position differences of 0.755 mm p95 / 2.871 mm maximum and local rotation+0.101 degrees p95 / 0.408 degrees maximum. Detector-box differences were at most+0.0292 pixels. This compares predictions, not ground-truth accuracy. Warm batched+prediction/crop time was 21.37 ms median / 22.04 ms p95, excluding decode, fusion,+IPC and GUI; peak PyTorch allocated memory was 1.524 GiB in that run.++A native GUI run completed alignment and tracking restart, displayed 168 paired+frames in eight seconds, switched the preview without reloading the resident+model, invalidated calibration on rotation change, and exercised cancel/Stop.+During that playback sample the GUI timer had 15.90 ms median, 23.25 ms p95 and+141.46 ms maximum spacing. Startup and calibration were excluded from this timer+sample. One cold alignment-plus-tracking-restart took 81.3 seconds; VGGT/GeoCalib+work alone was approximately 26 seconds in a separate run, with respective peak+allocated CUDA memory around 6.54/0.59 GiB. Scope and startup costs differ.++A separate paced video-backed simulation exercised four camera capture slots,+one continuing command and temporary loss of a view. It delivered 203 paired+sets in 8.016 seconds; processing time was 34.42 ms mean, 40.19 ms p95 and 46.40 ms+maximum after warmup. Three/four available views remained explicit. Sampled peak+worker working set was about 5.65 GiB; the worker exited normally. This is not+physical-webcam FPS, synchronization accuracy or camera-driver validation.++Five repeated four-decoder open/seek/close cycles retained 555 handles after each+cycle. Partial camera-open failure cleanup, bounded parameter archives, malformed+calibration/path rejection, thumbnail/slot validation and selected-pose bone-tail+errors (below 0.000001 m) passed. These short tests do not prove universal leak+freedom. Cached ExMR, FlowHMR, GVHMR, MAMMA and PromptHMR projects retained their+project/result, frame, trim and viewport camera after opening PEAR multi-inputs+and returning. No new offline AI-inference/export equivalence claim is made.++Reset Bones followed by 4-to-2-to-1-to-4 input switching retained the resident+worker and accepted the new rig baseline. Stop/restart after a reset also+passed without replaying an expired displayed-pose reset.++### Independent input rotation controls++Rotation now sits beside each webcam selector. Native and offscreen GUI checks+verified independent angles, preservation by device identity after refresh and+slot reordering/resizing, selected-video angle restoration, and camera-alignment+invalidation after editing any input angle. Thumbnail selection retained valid+alignment; no tracking was automatically started by editing controls.++Four real video decoders and four simulated webcam slots applied 0/90/180/-90+degrees independently, with exact pixel agreement against the existing rotation+operation. Both Camera Align sample times retained each input's angle and rotated+dimensions. A real CUDA worker displayed all four rotated inputs, returned to a+single input and exited normally while retaining one resident model process.+These are input-routing checks, not physical multi-webcam driver certification+or a new pose-accuracy/performance benchmark.++### Webcam image preview before tracking++Webcam selection now opens a separate capture-only worker before Start, without+loading PEAR, its weights or Torch. A native GUI test with video-backed simulated+cameras verified partial four-slot assignment, all four thumbnail images,+per-device rotation and preview switching without reopening the capture process,+capture shutdown before model handoff, Stop remaining stopped, None releasing+devices, offline return and a visible failure without automatic retry loops.+Worker logs confirmed Torch was not imported. Sampled preview working set was+about 191 MiB; a three-second GUI timer sample measured 16 ms median, 31 ms p95+and 141 ms maximum spacing. Five separate 30-frame open/close cycles retained+219 parent-process handles and 27 threads after each close; delivered packet+spacing ranged up to 94 ms in that simulation. These short tests are not physical+webcam FPS or long-term leak certification. The screenshot's NDI Webcam was not+present in the subsequent device probe, so its driver/feed was not verified.++The webcam controls were subsequently consolidated below the video into one+Camera / Device / Rotation table, with Count and Refresh in the same panel.+Native layout checks covered 1, 2, 4, 8 and 32 slots and shrinking back to one:+columns/row centres aligned, one-camera selection remained visible, horizontal+scrolling stayed unnecessary and longer lists scrolled within a 220-pixel table.+The camera-only preview, thumbnail, rotation, Start/Stop handoff and failure-path+simulation passed again after moving the controls. Capture/inference math and+worker ownership were unchanged by this layout edit.++### Continuous capture through Start and Camera Align++This supersedes the earlier capture-worker handoff. The capture-only process+now remains the sole owner of webcams during model loading and alignment.+Independent model readers copy its latest raw BGR frames through fixed Windows+shared-memory allocations protected by named mutexes; no per-frame disk cache+is introduced. Stop/None/leave still release capture. Device/resolution changes+may reopen it; an inference or calibration restart does not.++A native two-view GUI test used deterministic initial dataset frames repeatedly+published by simulated camera producers, plus a changing corner marker. Actual+PEAR inference, VGGT/GeoCalib alignment and the following PEAR restart succeeded.+The capture PID and shared-frame names remained unchanged: two device opens,+zero device closes during Start/alignment, and zero blank-image observations.+Image updates continued through loading, sample preparation, GPU shutdown and+alignment. Calibration completed in about 36 seconds and the first aligned pose+after restart arrived around 73 seconds after the click in that run. These are+workflow checks, not physical-camera timing, pose accuracy or universal FPS.++Five repeated shared-frame reader open/close cycles retained 224 parent handles;+frames remained complete under concurrent publishing, and a closed owner was+rejected. A native real-video decoder test with delayed mocked model/alignment+workers displayed 62 distinct frames during loading and 91 during the alignment+phase, retained play/pause/seek and fixed the alignment sample at the click's+frame/epoch. Its GUI timer measured 16 ms median, 31 ms p95 and 203 ms maximum+spacing in that short test. Raw-preview rotation and reset on leaving PEAR passed.+An injected sample failure exited alignment, retained its error notice and kept+the same capture process displaying frames (29 image updates in one second).+Physical multi-webcam drivers and long-duration behavior remain unverified.+++## PEAR automatic alignment and causal live Foot Lock (2026-11-01)++This revision supersedes the earlier optional/manual-only Camera Align and+no-live-contact behavior. Start aligns one or more fixed views before tracking.+VGGT and GeoCalib are required; their model-manager readiness is checked.+Single-view scale is estimated from inferred body geometry and person depth,+not a triangulation baseline. Failed alignment keeps an actionable error.++Validation used private tests outside the repository and preserved source videos:++- Real PEAR + VGGT + GeoCalib completed automatic Start for one and two simulated+ camera streams. Capture process/shared buffers were retained and no blank+ preview samples were observed. These were dataset frames through the capture+ protocol, not physical webcams.+- Four real synchronized video files aligned and played in the app. The eight-+ second observation contained 180 paired results. Worker median/p95/max were+ 39.56/44.72/692.92 ms, including first-frame overhead. Tracking peak CUDA+ allocation/RSS were 1.57/2.32 GiB. Calibration VGGT peak allocation was 6.53 GiB;+ tracking and alignment GPU models run sequentially.+- A final 450-frame cached four-view replay reduced locked-frame mean ankle+ displacement from 3.46 to 1.95 mm; knee-angle second-difference p95 stayed+ 4.02 degrees. Single-view replay had only seven contact frames, so its contact+ improvement is not broad evidence. Original pose noise remains.+- Fixed leg/toe lengths, ankle/toe world rotations, finite orthogonal rotations,+ input-array immutability, root-fixed behavior, seek/disabled reset and invalid+ single-camera depth rejection passed. A 240-frame near-straight perturbation+ case had 0.17 mm maximum knee step after extension resistance was added.+- Real video decoding continued during mocked alignment/loading, including seeks,+ input rotation and a frozen alignment sample time. GUI timer p95 was 31 ms;+ its maximum was 422 ms including startup/transition work. This does not prove+ stutter-free playback on other systems.+- Intentional sampling failure exited alignment and kept its error visible while+ camera preview continued. Stop during alignment and Reset Bones triggering+ realignment passed UI contract checks.+- Existing ExMR, PromptHMR, FlowHMR, GVHMR and MAMMA cached projects retained+ selection, timeline trim, displayed result and viewport camera after entering+ and leaving PEAR. Their AI inference was not rerun for this isolated change.++The live constraint is deliberately conservative: it allows reach/floor residuals+instead of stretching bones or forcing nearly straight knees to bend. World+Position off prohibits pelvis translation. It does not replace offline contact+editing, solve bad calibration or guarantee removal of inferred motion jitter.+++## PEAR independent One Euro components (2026-11-02)++One Euro Filter now exposes default-on Bone Rotation and World Position+checkboxes. The parent switch gates both; their selections are retained while+it is off. World-position filtering is separate from the world-movement switch+and from lightweight Foot Lock. Runtime flags default to both on when absent.+Changing a component does not change source epoch, camera calibration, resident+model, capture identity or the other component's filter history.++A cached replay tested all four component combinations for 120 frames each with+one, two and four views. Both-on results exactly matched the previous solver+and temporal filter reconstructed and verified against the prior source-manifest+hashes (maximum numeric difference zero). Both-off matched the parent-disabled+path. Position-filter selection left rotation outputs and root-relative pose+unchanged. Fixed lengths, valid rotation matrices, missing-input resets,+re-enable behavior and same-timestamp history retention passed. No AI inference+was rerun; these are filter/fusion regression checks, not a new inference or+webcam throughput benchmark.++Native UI checks passed for component defaults, request forwarding, master-off+selection retention, Filter Strength availability, no model reload/realignment,+and layout at 1100/1500-pixel window widths. The five offline models' cached+project restoration checks also passed. Test scripts and cached data remain+outside the source distribution. Source inference, calibration, foot-lock math+and installed dependencies are unchanged by this component split.+++## FlowHMR Unicode progress output fix (2026-11-02)++Fast SAM loading, single-frame and four-frame wrappers now explicitly open+UTF-8 discard streams. Base managed/development worker commands select Python+UTF-8 mode; `-I` otherwise ignores parent UTF-8 environment variables. Standard+worker stdout/stderr already had UTF-8 reconfiguration, so the independently+opened locale-encoded discard stream was the critical remaining failure path.++Private regression checks reproduced all three prior discard-stream failures+with simulated cp1252 defaults and box-drawing output. All corrected paths+passed, including collector cleanup. Actual managed interpreter probes verified+UTF-8 mode despite hostile cp1252 environment variables for shared, Flow, Hand,+HTD and ExMR profiles; their runtime boots passed. Binary pipe bytes were retained.+Development command construction was checked separately.++Real CUDA Fast SAM extraction passed for one frame and four-frame batches with+CPU/GPU hand crops. Same-input repeat controls showed existing token variation:+single-frame patched/control maximum difference was below 1e-6; batch differences+were within the observed baseline repeat maxima (0.01623 with CPU hand crops and+0.00750 with GPU crops). This was a feature-extraction check, not a full motion+quality or timing benchmark. SAM syntax trees differ only in the log encoding+keywords; model operations, precision and input settings are unchanged.++The full feature cache identity matched before/after on a private cached project.+Two complete-byte source aliases preserve valid preprocessing caches for this+logging-only change; unknown subsequent source edits still invalidate them.+Runtime package/profile pins remain unchanged; the reviewed registry hash and+source-lock identity were updated for the new worker launch flags. Tests, images,+models and cached project data remain outside the source distribution.++The normal managed installer reused all six verified base profiles, refreshed+the source/launch receipts and passed PEAR CUDA support verification. The actual+launch-source admission checks passed with GUI main stubbed, and the Flow feature+identity remained unchanged after installation. No inference dependency versions+or model files were replaced.+++## International Windows paths and output (2026-11-02)++The encoding audit expanded beyond Fast SAM to optional MAMMA/PromptHMR workers,+scene-camera preparation, setup/verifier commands, character jobs, JSON metadata+and chunked GUI process output. Python launches explicitly select UTF-8 even+under isolated mode. CMD entry points disable delayed expansion; PromptHMR's+generated UTF-8 native-build script now selects code page 65001, as MAMMA's did.+Dependency/package pins and optional runtime identities remain unchanged.++Seven independent path cases covered ASCII English, Western European accents,+Japanese, Russian Cyrillic, Korean, Chinese and combining-accent/emoji names with+spaces, brackets, ampersand, exclamation mark and percent sign. Each passed real+FFmpeg probing/preparation/trimming, PyAV/OpenCV video decoding, UTF-8 metadata,+NumPy archive/mapping reads and project Save As/reopen checks. Fifty interpreter+probes passed with hostile parent encodings (CP1252, CP932, CP1251, CP949, CP936+and ASCII), including separate optional-runtime probes. Byte-fragmented GUI+protocol and character-progress messages retained complete Unicode values and+EOF tails. Model import/hash rejection and Torch tensor file round trips passed.++The old native OpenCV image path API failed in twelve non-ASCII RGB/mask cases+on this PC. Python byte I/O plus the same OpenCV codecs passed all cases and+preserved PNG bytes/pixels, uint16 masks and RGBA data. Upstream image entry+points are bridged only within isolated MAMMA/PromptHMR scopes and restored on+errors. A 1080p PNG read check measured 9.31 ms median, 10.57 ms p95 and 11.32 ms+maximum versus 10.87 ms native ASCII-path median in this short run. Fifty reads+showed zero net handle growth and about 0.004 MiB retained RSS growth after+warm-up. This is not a universal speed or long-session leak guarantee.++Real Blender FBX/VRM/PMX imports passed in ASCII and mixed-language output+folders, with identical compared numerical canonical rig arrays. The existing+PMX motion exported to mixed-language FBX paths both with and without mesh, and+to VMD. Reimport/parsing passed: FBX retained its Unicode armature name and+bone-only animation channels; VMD retained its specified CP932 data encoding.+Twenty-one entry-point CMD path-dispatch tests passed under inherited delayed+expansion, using private standard-library-only runtime copies and stubbed app,+installer and updater bodies. These do not constitute clean installation or+remote-update tests. Restricted data and original user projects were not changed+or included in source; private fixtures, logs and generated files remain outside+the distribution.++The contact solver source, numerical inference settings, body data and source+motion were retained. New image adapters participate in MAMMA/PromptHMR cache+identities, so new inference validates the changed connector instead of silently+reusing a receipt for different code. Existing committed results are preserved.+These checks used one Windows PC without changing its system locale. They do+not certify every Windows language edition, GPU, new native build or third-party+file format. No full-model inference benchmark was repeated for this text/I/O+change.++## PEAR alignment fallback and single-view scale (2026-11-02)++Camera Align is attempted before tracking; failures now retain a visible warning+and continue with the selected camera, without calibrated fusion or aligned foot+lock. GUI checks covered missing alignment prerequisites, sample/solve/launch+failures, explicit retry, successful calibration and Stop. Actual PEAR workers+returned finite poses from an unaligned single video and from selected view 2 of+a two-slot input. The latter reused one source video to exercise dispatch, not+independent-view reconstruction quality. The worker exited after testing.++In a real single-view alignment, the old whole-image confidence percentile+discarded all 24 person-depth samples despite passing reprojection checks+(95th-percentile errors about 11 pixels, limit 38.4 pixels). Ranking confidence+within valid person samples retained 18, with a relative scale spread of 4.7%.+The complete VGGT/GeoCalib/floor run then succeeded; estimated floor residual+p95 was 15.9 mm. This is internal consistency, not ground-truth camera accuracy.+Missing depth, nonfinite/constant confidence, invalid observations and inconsistent+scale remained rejected. Multi-view calibration/fusion math was unchanged.+No clean-install, physical-webcam or sustained-playback benchmark was repeated+for this change. Private samples and test code remain outside the distribution.++The final publish check separated PEAR's core required assets (checkpoint,+geometry and YOLOv8s) from optional Camera Align weights. Missing VGGT/GeoCalib+now reaches the warning/fallback path rather than failing the core-model check.+GUI checks used the real stage dependency lookup with only model readiness+simulated: absent alignment weights allowed tracking, an absent PEAR checkpoint+still blocked Start, and all five Model Manager rows remained available with+alignment rows marked optional. Console/CMD routing, alignment failures, retry+and Stop regression checks were repeated. This does not make alignment optional+for calibrated fusion or live foot locking, and is not a new inference benchmark.diff --git a/docs/models/FLOWHMR.md b/docs/models/FLOWHMR.mdindex b44b7d0..a58576d 100644--- a/docs/models/FLOWHMR.md+++ b/docs/models/FLOWHMR.md@@ -15,6 +15,7 @@ C++/CUDA native-build prerequisites. Key assets are:| Asset | Location under the app's `models/` folder || --- | --- || Supported FlowHMR latest checkpoint and configuration | `flowhmr/flowhmr_latest.ckpt`, `flowhmr/config.yml` |+| Official checkpoint metadata (public automatic download) | `flowhmr/config.json` || SAM 3D Body model, configuration and MHR | `flowhmr/sam/model.ckpt`, `flowhmr/sam/model_config.yaml`, `flowhmr/sam/assets/mhr_model.pt` || AMASS SMPL-H neutral body, 16 shape components | `body_models/smplh/neutral/model.npz` || VGGT-Omega 512, for camera estimation | `flowhmr/vggt_omega_1b_512.pt` |@@ -26,12 +27,18 @@ registration/access steps; use **Manual Download... > Import...** for the exactfile. The current checkpoint is `flowhmr_latest`, not an arbitrary base model.See [model preparation](../USER_GUIDE.md#prepare-models).+Downloading the FlowHMR checkpoint also fetches the official 25-byte+`config.json` from the same pinned Hugging Face revision, with SHA-256 checking.+Existing installations can obtain it using its separate Model Manager row.+It identifies the checkpoint for Hugging Face download accounting; it does not+replace `config.yml`, change inference settings or invalidate existing motion.+## Controls| 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 > Adaptive Batching** | On | Automatic selects 1, 2, 4, 8 or 16 frames from current GPU allocation headroom, free RAM and image size. Short tests of 4 to 16 frames reduced warm feature time by 16–23%; allocated VRAM rose from 3.84 to 5.43 GiB. Off and Low Memory use one frame. Small numerical differences are possible. || **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. |@@ -51,6 +58,15 @@ accuracy against ground truth. Speed figures describe feature extraction afterwarm-up, not the whole reconstruction, and vary with the PC and video. CUDAmemory pressure can retry with Low Memory and a smaller batch.+Adaptive Batching preserves the previous batching checkbox's saved on/off value.+Memory is checked again between prepared batches. CUDA allocation failures retry+only unpublished frames with a smaller batch after releasing the failed call;+if one frame still fails, the existing Automatic-to-Low-Memory retry applies.+RAM/prefetch limits, full resolution, original precision, every motion frame and+the first 30 placement-anchor frames are retained. The 16-frame ceiling favors+measured efficiency: 32 added only about 4% over 16 on the longer short clip but+used another 2.13 GiB of allocated VRAM. These are one-PC observations.+## Capture and export1. Select FlowHMR and **File > Open Video**, then trim the **Video** track.@@ -78,6 +94,24 @@ overlap. This does not change the Fast SAM switches, resolution or precision.### Measured effects+The 2026-11-02 paired checks used 60- and 120-frame 1080p landscape/portrait+clips on the test PC below. Warm feature-only time changed **4.71 → 3.98 s**+and **9.86 → 7.63 s** for 4 → 16 frames; peak allocated VRAM was+**3.84 → 5.43 GiB**, reserved VRAM **4.34 → 6.81 GiB**, and warm worker RAM+increased by about **0.20 GiB**. Fresh app feature jobs, including initialization,+took **34.80 → 34.88 s** and **39.77 → 38.74 s**: short whole jobs benefit much+less than warm extraction. Final joint disagreements were **0.15 / 0.44 mm at+the 95th percentile**, with maxima **0.59 / 1.63 mm**. These are differences+from the previous implementation, not ground-truth accuracy. Low Memory's+peak allocated VRAM remained **1.91 GiB** in its paired 60-frame check.++The newer official Lite SAM and OpenCV-style GPU body/hand crops were also+tested as separate candidates. The crop trial changed body and hand crops together;+body-only cropping was not isolated. Both candidates were slower than the existing+optimized Fast SAM path on this PC, so they are not substituted into the app. No new package,+model, TensorRT engine or compilation step is required. See+[the adaptive-batch review](../PERFORMANCE.md#flowhmr-adaptive-batches-2026-11-02).+Automatic's VGGT camera-only loader skips temporary initial weights using metainitialization and direct checkpoint assignment. A paired camera-component testreduced loading from **7.24 to 2.34 s**, with identical camera outputs and peak@@ -115,6 +149,22 @@ include camera estimation and predate Fast SAM; they are not predictions orminimum specifications. See [validation](../VALIDATION.md) and[upstream licenses](../../THIRD_PARTY_NOTICES.md).+## Windows console encoding++The app Console and the CMD window report the selected Fast SAM batch size, GPU+hand-crop setting and Low Memory single-frame selection. CUDA OOM retries report+the reduced batch size. Available memory can further reduce the effective batch;+the selected size is an upper bound, and a final partial batch may be smaller.+Cached features skip extraction, so they do not select a new SAM batch.++A `UnicodeEncodeError` mentioning `cp1252` and SAM timing/box-drawing output+is a log-encoding failure. The corrected version starts base workers in explicit+UTF-8 mode and uses UTF-8 for discarded Fast SAM logs, including batched+batches. Windows language/console code-page changes are not required. Close the+app and use `update.cmd` to install a version containing the fix; for an already+updated source checkout, `install.cmd` refreshes runtime verification. Matching+package profiles and model files are retained. Valid feature caches remain usable.+## Citation[FlowHMR paper](https://arxiv.org/abs/2610.03691) · [Research citations and BibTeX](../CITATIONS.md#flowhmr)diff --git a/docs/models/PEAR.md b/docs/models/PEAR.mdindex 064b9f6..aa988b9 100644--- a/docs/models/PEAR.md+++ b/docs/models/PEAR.md@@ -6,19 +6,32 @@[Paper and BibTeX](../CITATIONS.md#pear) · [Upstream source license](https://github.com/Pixel-Talk/PEAR/blob/8e915f8c3dfae4063d66763e6296b2b0b02eb303/LICENSE.txt)-PEAR displays fixed-length body and finger bones for one visible person, from a-webcam or the current frame of an opened video. Body mesh and face geometry are+PEAR tracks webcam or video input in real time and displays fixed-length body and+finger bones for one visible person. For video input, seek or play the timeline+to track its current frames. Multiple fixed views of the same+person can be aligned and fused; single-view preview remains available. Body mesh and face geometry arenot calculated for each live frame. It is a live preview tool. It does not use-Find person, record motion, run contact correction, retarget characters or export+Find person, record motion, run the offline Motion Correction pipeline, retarget characters or exportanimation in this integration. Use an offline reconstruction model for those tasks.Selecting PEAR only shows its controls. Click **Start Live Tracking** to load and-warm the models, then track the selected webcam or video. The button becomes+warm the models, attempt Camera Align for one or more cameras, then track the selected webcam or video. Show the person and visible floor during alignment. If alignment fails or its support/models are missing, tracking continues in the selected camera view with a visible warning. Unaligned views are not fused, and aligned Foot Lock is unavailable. Camera Align can be retried later. The button becomes**Stop**, including during loading. Stop ends tracking and releases the worker,models and camera; wait for shutdown before starting again.+Selecting a webcam opens a lightweight image preview before Start, without PEAR+or Torch loading. After Stop, reselect a camera or click Refresh to reopen image+preview; selecting None for all slots releases the cameras.While tracking is started, opening another video or switching webcams replaces-only the input. Models remain loaded until Stop, leaving PEAR or app close.+the input and automatically recalibrates the changed camera configuration. Changing physical cameras requires calibration; ordinary seeks and thumbnail changes reuse the loaded tracking model.+Camera Align temporarily releases PEAR while its separate calibration worker runs,+then reloads tracking to avoid overlapping their GPU allocations.+The separate camera-capture worker remains connected throughout Start, model+loading and Camera Align. It supplies bounded raw frames to tracking through+Windows shared memory, so those operations do not reopen the webcams. Image+preview continues while pose processing is busy; ordinary tracking displays the+completed image/pose pair. Stop, None, leaving PEAR or closing the app release+capture. Changing device assignment or requested resolution can reopen capture.## Setup@@ -30,7 +43,8 @@ only the input. Models remain loaded until Stop, leaving PEAR or app close.2. Open `RGBMoCap.cmd`, select **PEAR · Live (Experimental)**, and open **Model Manager**.3. Download/import `pear_model.pt` and **PEAR Person Detection / YOLOv8s**(`yolov8s.pt`). Model Manager verifies the supported official files.-4. In the geometry row, use **Manual Download**. Follow the upstream Preparation+4. Prepare the VGGT and GeoCalib rows for automatic camera alignment. VGGT reuses the FlowHMR/MAMMA model file.+5. In the geometry row, use **Manual Download**. Follow the upstream Preparationinstructions, review the SMPL-X/FLAME provider terms, and obtain the original`assets.zip`. Import that ZIP without editing it. Import validates its SHA-256and extracts only required files. The source ZIP is preserved.@@ -42,7 +56,10 @@ by setup. The PEAR source license does not replace body-data or weight licenses.The checkpoint is approximately **2.50 GiB**. Selected geometry occupies about**0.32 GiB** logically (about **0.27 GiB** when duplicate files can be hardlinked).-The installed support source/utilities were about **0.87 MiB** on the test PC. The original+The original PEAR source/utilities were about **0.87 MiB** on the test PC.+Camera alignment support adds about **11.35 MiB** of GeoCalib/Kornia files, over+the existing Flow runtime, without upgrading shared packages. GeoCalib weights+are about **110.7 MiB**; VGGT reuses the existing FlowHMR/MAMMA weight file (about **4.26 GiB** if not already present). Both are required for alignment, including one camera; unaligned tracking can run without them. The originalgeometry ZIP download is about **1.48 GiB** and needs separate temporary space.PEAR also uses the official YOLOv8s detector (about 21.5 MiB), downloaded orimported through its Model Manager. The larger YOLOv8x used by offline models@@ -50,7 +67,10 @@ is unchanged. These are additional to the base installation, not a new runtime.## Video and webcam controls-- **File > Open Video**: choose a video. Leave **Webcam** at **None — use video**.+- **File > Open Video**: choose one or multiple synchronized camera videos.+ With multiple files, the timeline uses their common duration at 30 fps; a trim+ applies to all views. Thumbnails use up to four columns, adding rows as needed.+ Click a thumbnail to change only the main camera preview. Leave **Webcam** at **None — use video**.Click **Start Live Tracking**, then seek or play to process the requested frame. Requests arecoalesced to the latest frame, so scrubbing does not create an inference queue.During playback, the completed video frame and its pose are displayed together.@@ -59,14 +79,26 @@ is unchanged. These are additional to the base installation, not a new runtime.Pause or seek for the exact selected frame. Live video images are bounded to1280 × 720 for transfer. Rotation is applied before inference and this transferresize; the original video file is unchanged.-- **Webcam**, above the video: select a connected device. Camera capture and PEAR- tracking begin after **Start Live Tracking**. The displayed image and pose belong to the+- **Webcams**, below the video: **Count** and Refresh sit above one table with+ **Camera / Device / Rotation** columns. All slots, including camera 1, appear+ here in numerical order; longer lists scroll vertically. **Count** sets 1–32+ assignment slots. Assign a different+ connected device to every slot. Set all slots to None to return to video inputs.+ Thumbnails select the displayed webcam. Assigned devices show image previews+ even while other slots are still None; fill every slot before starting tracking.+ **Start Live Tracking** leaves the capture worker connected; the model reads+ its shared frames instead of opening the devices again. During tracking the+ displayed image and pose belong to thesame processed frame. Old camera frames are dropped to bound latency.- **Refresh**: rescan connected cameras. Close other apps using the device if itcannot open. Choose **None** to release it and return to the video.-- **Rotation**: clockwise degrees applied to video or webcam images before display- and inference. `90` turns right; `-90` turns left. Arbitrary angles expand the- image to avoid clipping. The source file is unchanged.+- **Rotation**, beside each webcam selector on the left: clockwise degrees for+ that device only, applied before display, detection and camera alignment.+ Each selected webcam retains its own value when devices are refreshed or moved+ between slots within the session. For videos, select a thumbnail and edit the+ first Rotation field; each video retains its own value. `90` turns right;+ `-90` turns left. Arbitrary angles expand the image to avoid clipping.+ The source file is unchanged. Changing a rotation invalidates Camera Align.- **One Euro Filter**: applies to both webcam and video. Adaptive filtering stabilizesquiet poses, follows moving poses faster, and caps its response to noisy speedestimates. Rotations remain valid rotations; the fixed rig follows the smoothed@@ -78,6 +110,13 @@ is unchanged. These are additional to the base installation, not a new runtime.subsequent playback is smoothed. The last matching image/pose pair stays visiblewhile a replacement is computed. Turn smoothing off for unfiltered predictedrotations; fixed bone lengths remain. Switching it does not reload models or reframe the view.+- Under **One Euro Filter**, **Bone Rotation** smooths body/finger rotations and+ **World Position** smooths estimated root translation. Both default on and can+ be selected independently. The parent switch disables both while retaining+ their selections. Filter Strength is shared. Changing a component does not+ reload models or run Camera Align, and preserves the other filter history.+ This position-filter checkbox is separate from the top-level **World Position**+ movement switch. Foot Lock remains independently enabled/disabled.- **Filter Strength**: 1–100, default 50 (the previous filter setting). Higher valuesreduce jitter but add delay. Applies to pose and root placement; filtered shapeparameters are used only when bone lengths are calibrated.@@ -86,17 +125,18 @@ is unchanged. These are additional to the base installation, not a new runtime.fixes all three position coordinates, including height, at the currentlydisplayed pelvis position. If turned off before tracking, the first valid posesupplies that position. Pelvis rotation and joint motion continue normally.- Switching it does not reload models, rerun inference or reset bone lengths.+ Switching it does not reload models or reset bone lengths; a paused frame may be processed again.Turning it back on restores estimated position; this may move the character.-- **Start Live Tracking / Stop**: load the models and begin tracking, or stop and+- **Foot Lock**: on by default and active only after successful Camera Align. Low, slow feet can hold an estimated ground point. A small causal leg correction and bounded pelvis adjustment ease in and out; fixed bone lengths and ankle/toe world rotations are preserved. Turn it off for uncorrected live placement. With World Position off, pelvis translation stays fixed; unreachable feet are allowed to miss the floor instead of stretching legs or forcing the pose. Incorrect floor estimates, fast jitter and missed contacts can still cause sliding; this is not a full offline correction solver.+- **Start Live Tracking / Stop**: attempt alignment and begin tracking, or stop andrelease the models and webcam. Stop also cancels model loading. Selecting a new- input or changing settings while stopped does not start tracking.+ input or changing settings while stopped does not start pose tracking. Webcam+ selection, rotation/resolution changes or Refresh can reopen image preview.- **Reset Bones**: recalculate bone lengths and neutral axes from the pose currentlydisplayed. Video playback pauses on that frame. For a webcam, its displayed- pose parameters are used rather than an unrelated newer camera frame. Models- remain loaded and the viewport camera is preserved. Choose a frame where the+ pose parameters are used rather than an unrelated newer camera frame. Automatic realignment temporarily releases and reloads the tracking model; the viewport camera is preserved. Choose a frame where theperson is clearly visible. If the displayed pose has expired, try again; the- existing rig is retained. Changing input calibrates a new rig automatically.+ existing rig is retained. After a successful reset, Camera Align runs again for the new body scale. Changing input calibrates a new rig automatically.- **Bone Overlay** uses the same octahedra, joint caps and outlines as the othermodels. Its 52 body/finger bones form a fixed-length FK rig; jaw and eye control bonesare hidden. This is a live display, not a committed offline export skeleton.@@ -114,15 +154,76 @@ The largest detected person is selected initially and followed while visible.There is no manual person selection in this live mode. Occlusion, leaving theimage and multiple people can cause loss or reacquisition of identity.+## Multiple fixed cameras and Camera Align++1. Run `install.cmd` after updating; its pinned GeoCalib/Kornia support requires+ no extra Torch installation, TensorRT, CUDA compiler or separate PEAR setup CMD.+ GeoCalib code uses Apache-2.0 and its checkpoint uses CC BY 4.0; see+ [citation and licenses](../CITATIONS.md#geocalib-pear-camera-align).+2. In PEAR **Model Manager**, prepare **VGGT** and **GeoCalib**.+ Both are required for automatic alignment, including a single camera.+3. Open synchronized views of the same performance, or assign every webcam slot.+ PEAR still tracks **one person**, not multiple identities. Use views showing+ that same person and overlapping background. Video starts must already match;+ this feature does not automatically synchronize audio/video.+4. Put the playhead at a clearly visible moment with background floor, then click+ **Start Live Tracking**. It runs Camera Align automatically; use the separate+ **Camera Align** button to recalibrate while tracking. For videos it samples that time and up to two seconds later;+ leave at least two frames after the playhead. Webcam calibration samples two+ recent frame sets about a second apart. Keep cameras stationary.+5. Wait for preparation, VGGT, GeoCalib and tracking restart. **Cancel Camera Align**+ cancels the operation; **Stop** also cancels tracking and releases workers.+ Webcam preview remains live. Opened videos can play, pause and seek during+ model loading and alignment. Alignment samples use the playhead position at+ the time of the click, independently of later playback/seeks. Background+ alignment is still a fixed-camera assumption; playback does not recalibrate+ moving cameras. Rotation remains visible while ordinary video decoding runs.++Start attempts alignment first and continues with the selected camera if it fails. This fallback uses camera-relative placement, so floor tilt and world scale may be inaccurate. A single aligned view uses background gravity/depth and an inferred body-to-depth scale, not multi-view triangulation. Alignment does not assume that the person starts upright. Person depth confidence is compared within the person samples rather than against easier background surfaces; reprojection, minimum sample count and scale-consistency checks remain. No live pose is published from the sampling stage. After successful alignment, a causal rotation+blend, analytic visibility/foreshortening weights and reprojection-based root+placement combine available views on one fixed-length rig. These weights are+heuristics, not measured confidence. Alignment uses GeoCalib gravity and background floor geometry, with actor masks for floor/gravity. Multiview camera estimation masks the actor; single-view VGGT retains the person to estimate body-to-depth scale;+it does not require an upright initial pose. Scale and floor are estimates, not+calibrated measurements. Lightweight live Foot Lock can reduce planted-foot movement; it cannot repair incorrect calibration or guarantee exact sole contact.++Changing inputs, device assignment, input rotation, requested webcam resolution+invalidates alignment and automatically aligns again while tracking. Reset Bones also recalibrates before continuing. Moving physical cameras cannot be detected+reliably: click Camera Align again. A thumbnail change retains alignment. Current+alignment is transient and is not a saved offline project. World Position and+One Euro controls also apply to the fused pose. Camera alignment does not fix+wrong identity matches, bad crops or severe occlusion.++Webcam frames are paired by host arrival time with an 80 ms skew limit, using+bounded latest-frame buffers. This is approximate software synchronization, not+hardware synchronization or latency calibration. A delayed/disconnected device+produces a waiting/error notice; frames do not accumulate indefinitely. Four+views are the measured optimization case; more slots increase processing and+calibration cost and may not fit available memory.+## Placement and performance+### Alignment and setup failures++Alignment is optional for tracking. A failed alignment, missing alignment support+or missing VGGT/GeoCalib files produces a warning in the sidebar, Console and CMD,+then starts camera-relative tracking from the selected view. Other views remain+selectable, but their poses are not fused and aligned Foot Lock is inactive.+Use **Camera Align** to retry after improving the view or preparing its models.+The warning clears when a new alignment attempt starts. Ordinary pose tracking+still requires PEAR's own installed support, checkpoint, detector and geometry.++If the app reports that PEAR support needs installation, close it and rerun+`install.cmd`. A support-script update can require refreshing the verified support+generation even when model files are already ready. Existing verified model+files and projects are retained; do not edit setup receipts manually.++### Placement and measured speed+Pelvis movement is enabled by default through **World Position**. Turning it offholds pelvis translation in place; it does not lock feet to the ground.-Placement uses the crop camera with an assumed fixed-full-image camera and one initial reference height. It is **not calibrated world-motion**, camera-motion tracking or foot locking. Feet may float or slide.+Camera Align estimates a static world frame; it is not measured camera calibration or camera-motion tracking. Foot Lock only acts near that estimated floor. Its contact evidence comes from pre-correction motion. Correction rotations and lock transitions are smoothed causally; no future frames or iterative physics are used. Inferred pose jitter can remain.-The fast path uses SDPA, an FP16 encoder, FP32 decoder, encoder CUDA Graphs,+The single-view fast path uses SDPA, an FP16 encoder, FP32 decoder, encoder CUDA Graphs,fixed-length CPU FK and YOLOv8s person detection. A reusable CPU body modelcalibrates neutral anatomy on the first valid frame and on Reset Bones; bodyskinning is not evaluated on each subsequent frame. It detects every processed@@ -152,8 +253,13 @@ allocation limits; it has no block-offload or automatic Low Memory retry.`runtime_pear/` contains pinned support source/packages; `.setup/pear-runtime.json`is the setup receipt. `models/pear/` contains checkpoint and imported geometry.-Recent worker diagnostics are in `cache/pear/sessions/`; no captured video or motion-archive is created there. Close the app before deleting support files. Rerun+Recent worker diagnostics are in `cache/pear/sessions/`; no motion archive is+created there. Camera Align temporarily writes sampled images/observations under+`cache/pear/alignment/`; successful jobs remove sampled images and retain small+camera/rig receipts. Failed or cancelled jobs are disposable caches; at most four recent job folders+are retained, including the current calibration. Close PEAR+before clearing these folders. Camera alignment support has its own+`.setup/pear-alignment.json` receipt and `installer/pear-alignment.json` source pins. Close the app before deleting support files. Rerun`install.cmd` after support-source changes; `update.cmd` also prepares/verifiesthis support. Matching verified files are reused. Preserve model files and projects.@@ -168,3 +274,33 @@ The One Euro filter follows the [original method](https://gery.casiez.net/1euro/with adaptive rotation and placement filtering in the live worker. The optionalpelvis-position control also draws on the [PoseCap](https://github.com/CorridorTech/PoseCap)workflow; RGB MoCap implements its own preview controls and fixed-position anchor.++## Live Foot Lock validation (2026-11-01)++The default-on live lock is separate from the offline Kimodo correction path.+It has two constant-size contact states, velocity/height hysteresis, inertialized+lock/release targets, continuous pelvis handoff and source-relative correction+filtering. Nearly straight legs retain the source bend instead of turning tiny+floor errors into crouching. It preserves lengths and ankle/toe world frames;+reach failures remain residuals, with a visible notice for larger errors.+One Euro filtering remains responsible for reducing inferred pose jitter.++On the test PC, a 450-frame four-view cached replay reduced mean ankle movement+between consecutive locked frames from 3.46 to 1.95 mm. The knee-angle second+frame difference p95 remained 4.02 degrees: the source itself still contained+jitter, and this is not a ground-truth accuracy measurement. A separate near-+extension perturbation test limited maximum knee movement to 0.17 mm/frame.+The lightweight solver used roughly 0.2–0.3 ms median and 0.3–0.4 ms p95.++A real four-video app test completed automatic alignment and presented 180+paired frames in an eight-second observation. Worker time was 39.56 ms median,+44.72 ms p95 and 692.92 ms maximum including the first post-alignment frame.+Tracking peak PyTorch allocation was 1.57 GiB and worker RSS about 2.32 GiB.+Calibration is a separate startup cost: the four-view VGGT stage used about+6.53 GiB peak allocation, and PEAR is released before it runs. These short tests+are not universal FPS, physical multi-webcam synchronization or leak guarantees.++The transition design uses standard causal foot-lock/analytic IK ideas discussed+in [Inverse Kinematics and Foot Locking](https://theorangeduck.com/page/inverse-kinematics-foot-locking).+RGB MoCap implements its own lightweight preview solver; no additional model,+physics simulation, future-frame window or TensorRT installation is used.diff --git a/docs/models/README.md b/docs/models/README.mdindex 89bc963..e079260 100644--- a/docs/models/README.md+++ b/docs/models/README.md@@ -11,7 +11,7 @@ saved selection. Only implemented tools appear in the list.| GVHMR | One video; SMPL-X | Optional HandFlow | [GVHMR](GVHMR.md) || MAMMA | Two or more synchronized fixed-camera videos; SMPL-X | Included | [MAMMA](../MAMMA.md) || PromptHMR | One fixed-camera video; jointly reconstructed people; SMPL-X | Not generated | [PromptHMR](PROMPTHMR.md) |-| PEAR | Experimental live preview of one person from a webcam or video timeline; may be unstable | Included | [PEAR](PEAR.md) |+| PEAR | Experimental real-time tracking from webcam or video input; one person, one or multiple fixed views; may be unstable | Included | [PEAR](PEAR.md) |One-video input does not mean one-person output. ExMR, FlowHMR and GVHMR canprocess checked people independently after **Find person**. Without discovery,@@ -23,7 +23,9 @@ and Interaction Prompt on; see its guide for setup and fixed-camera limits.For manual MAMMA cameras, see the [calibration format and JSON example](../MAMMA.md#manual-cameras).PEAR support is prepared by `install.cmd` and `update.cmd` over the shared runtime;its weights/body data are obtained separately. It is a live preview without motion-recording, contact correction, retargeting or export.+recording, offline contact correction, retargeting or export. Camera Align is+attempted first; if it fails, tracking continues from the selected camera with a+warning, without camera fusion or aligned live foot lock.In this project's subjective tests, ExMR was generally fast with good quality;FlowHMR was slower with the best overall quality; GVHMR was less consistent@@ -54,7 +56,8 @@ MAMMA is a separate multi-view workflow rather than another single-video option.For PEAR, use **Start Live Tracking** instead of reconstruction. It displayslive bones only; offline contact, project-save, retarget and export steps do not-apply. See its guide for filtering, World Position and Reset Bones.+apply. Multiple synchronized files/webcam slots and Camera Align are described+in its guide, along with filtering, World Position and Reset Bones.Model-specific settings affect reconstruction; they are separate from contactcorrection and display-only viewport controls. Original and corrected resultsdiff --git a/install.cmd b/install.cmdindex 1be84f9..2919db1 100644--- a/install.cmd+++ b/install.cmd@@ -1,5 +1,5 @@@echo off-setlocal+setlocal DisableDelayedExpansioncd /d "%~dp0"powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\git_bootstrap.ps1" %*set "result=%ERRORLEVEL%"diff --git a/installer/engine.py b/installer/engine.pyindex bea0ed3..c7e58ae 100644--- a/installer/engine.py+++ b/installer/engine.py@@ -121,7 +121,7 @@ def verify_group(stage,group,root,cancel,logs):report=logs/(group['key']+'-verify.log')scripts=Path(__file__).resolve().parentrequest=logs/(group['key']+'-verify-input.json');atomic_json(request,group)- run([py,'-I',scripts/'verify_runtime.py',stage,request,scripts/'runtime_registry.py',root],root,cancel,report)+ run([py,'-I','-X','utf8',scripts/'verify_runtime.py',stage,request,scripts/'runtime_registry.py',root],root,cancel,report)lines=report.read_text(encoding='utf8').strip().splitlines();return json.loads(lines[-1])diff --git a/installer/pear-alignment.json b/installer/pear-alignment.jsonnew file mode 100644index 0000000..98ad28a--- /dev/null+++ b/installer/pear-alignment.json@@ -0,0 +1,23 @@+{+ "version": 1,+ "sources": {+ "kornia": {+ "url": "https://files.pythonhosted.org/packages/d8/cf/a61ef6f7faf98edadf4ce8094873d298f8582a3ec59b65c9174c516926e8/kornia-0.7.4-py2.py3-none-any.whl",+ "filename": "kornia-0.7.4-py2.py3-none-any.whl",+ "bytes": 899442,+ "sha256": "1b816b4c45878a73531a500a46dbf61e646ec7a749bf8a4dd7a5833a04e28808"+ },+ "kornia_rs": {+ "url": "https://files.pythonhosted.org/packages/77/81/53c882f3b93474a025302aead72b361128a0620dd629a17c86408fadfe31/kornia_rs-0.1.9-cp310-cp310-win_amd64.whl",+ "filename": "kornia_rs-0.1.9-cp310-cp310-win_amd64.whl",+ "bytes": 2276544,+ "sha256": "511d0487c853792f816c3a8bc8edbd550fe9160c6de0a22423c2161fac29d814"+ },+ "geocalib": {+ "url": "https://codeload.github.com/cvg/GeoCalib/zip/1dedb29f94fc11b896c5f572005978aeebccd67f",+ "filename": "geocalib.zip",+ "bytes": 24657350,+ "sha256": "8d1d32af3782b95a3f8215b8214159728d4e7ef4b1bfe2943d6ad785d15be08a"+ }+ }+}\ No newline at end of filediff --git a/installer/runtime-lock.json b/installer/runtime-lock.jsonindex 511bfc8..47c10e3 100644--- a/installer/runtime-lock.json+++ b/installer/runtime-lock.json@@ -2244,6 +2244,6 @@"uv_sha256": "4075a09490327d2bedfacc807fa48252fb93647c5bd7ef28f00e579160ea3fb5","all_runtimes": true,"models_included": false,- "registry_sha256": "5e56f969d2509a4200a02911d1d801bf5b43fc50cbb03f6b903879a90533ff20",- "id": "c156b3130b170cdf1bcbb27f2d928e35d0952ca81f7208dc0c734f09fc346290"+ "registry_sha256": "68ae06b6c230612066591c2380506dae6886b2ccb779d79c938ff14cb9894b0d",+ "id": "a898d13996810090315fc482c85fbae3537c70ea1fca23dd47d0823c78e06eba"}diff --git a/mocap/character_ui.py b/mocap/character_ui.pyindex c065029..7c2378e 100644--- a/mocap/character_ui.py+++ b/mocap/character_ui.py@@ -1,5 +1,5 @@"""Imported targets are distinct from source people and extraction selections."""-import json,os,sys,time,uuid,shutil+import json,os,sys,time,uuid,shutil,codecsfrom pathlib import Pathimport numpy as npfrom PySide6.QtCore import Qt,QProcess,QTimer,QProcessEnvironment@@ -244,6 +244,7 @@ class CharacterWorkspace:self.character_refresh_queue=[]self.status.setText(str(exc));returnself.stop_playback();self.character_job=job;self.character_started=time.monotonic();self.character_line='Starting character processing...';self.character_buffer='';self.character_cancelled=False+ self._character_decoder=codecs.getincrementaldecoder("utf-8")("replace");self._character_pending=""p=QProcess(self);self.character_process=penv=QProcessEnvironment.systemEnvironment();env.insert('PYTHONUTF8','1');env.insert('PYTHONIOENCODING','utf-8');p.setProcessEnvironment(env)p.setWorkingDirectory(str(ROOT));p.setProcessChannelMode(QProcess.MergedChannels)@@ -253,13 +254,16 @@ class CharacterWorkspace:self.busy=True;self.progress.setRange(0,0);self.character_timer.start();self.character_progress();self.update_readiness()p.start(cmd[0],cmd[1:])- def character_output(self):+ def character_output(self, final=False):if not self.character_process:return- text=bytes(self.character_process.readAllStandardOutput()).decode('utf8',errors='replace')+ text=self._character_decoder.decode(bytes(self.character_process.readAllStandardOutput()),final=final)self.character_buffer=(self.character_buffer+text)[-16000:]- for line in text.splitlines():- if line.startswith('CHARACTER:'):- self.character_line=line.partition(':')[2].strip()+ self._character_pending=(self._character_pending+text)[-16000:]+ lines=self._character_pending.split("\n");self._character_pending=lines.pop()+ if final and self._character_pending:lines.append(self._character_pending);self._character_pending=""+ for line in lines:+ if line.startswith('CHARACTER:'):+ self.character_line=line.partition(':')[2].strip()self.log.status_terminal(line.strip())self.character_progress()@@ -270,7 +274,7 @@ class CharacterWorkspace:def character_finished(self,code,*args):if self.character_process is None:return- self.character_output();p=self.character_process;self.character_process=None;p.deleteLater();self.character_timer.stop();self.busy=False+ self.character_output(final=True);p=self.character_process;self.character_process=None;p.deleteLater();self.character_timer.stop();self.busy=Falsejob=self.character_job;complete=Path(job['output'])/'complete.json'if code==0 and complete.is_file() and not self.character_cancelled:result=json.loads(complete.read_text(encoding='utf8'))diff --git a/mocap/exmr_backend.py b/mocap/exmr_backend.pyindex ae78cbf..73519d9 100644--- a/mocap/exmr_backend.py+++ b/mocap/exmr_backend.py@@ -104,7 +104,7 @@ def camera(project,emit):config=saved(root,state);context=dict(input=file_stat(root/'input.mp4'),frames=state['frames'],static=config['static_camera'],version=3,odometry=sha256(UPSTREAM/'ExMR/exmr/preprocessing/visual_odometry.py'),reader=sha256(Path(__file__).with_name('exmr_camera.py')))receipt=root/'exmr_camera.json';path=root/'exmr_camera.npy'valid=False- try:valid=json.loads(receipt.read_text())['identity']==context and json.loads(receipt.read_text())['output']==file_stat(path)+ try:valid=json.loads(receipt.read_text(encoding='utf-8'))['identity']==context and json.loads(receipt.read_text(encoding='utf-8'))['output']==file_stat(path)except (OSError,ValueError,KeyError):passif valid:rotations=np.load(path,allow_pickle=False)@@ -159,7 +159,7 @@ def frame_dir(project,n):directory=project/'exmr_frames';directory.mkdir(exist_ok=True)identity=dict(input=file_stat(project/'input.mp4'),frames=n,version=1)try:- if json.loads((directory/'receipt.json').read_text())==identity and len(list(directory.glob('*.jpg')))==n:return directory+ if json.loads((directory/'receipt.json').read_text(encoding='utf-8'))==identity and len(list(directory.glob('*.jpg')))==n:return directoryexcept (OSError,ValueError):passfor path in directory.glob('*.jpg'):path.unlink()subprocess.run([executable('ffmpeg'),'-v','error','-i',str(project/'input.mp4'),'-vsync','0','-q:v','2','-start_number','0','-threads','2','-y',str(directory/'%06d.jpg')],check=True,creationflags=0x08000000)diff --git a/mocap/flow_backend.py b/mocap/flow_backend.pyindex 7c62630..bc0cd5b 100644--- a/mocap/flow_backend.py+++ b/mocap/flow_backend.py@@ -11,6 +11,7 @@ from .storage import atomic_json, sha256from .model_session import set_memory_budgetfrom .compute_policy import gpu_memory_fractionfrom .result_artifacts import file_stat+from .resource_cache import code_hashVERSION=1MAX_FRAMES=5000 # Pinned FlowHMR per-branch RoPE table; 30 fps.@@ -128,7 +129,7 @@ def identity(project,stage):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)+ for name in ('flow_sam.py','flow_fast_sam.py','flow_sam_batch.py','batch_prefetch.py'):code[name]=code_hash(ROOT/'mocap'/name)if stage=='flow_features':from .flow_sam import saved_fast_sam, source_identity, acceleration_optionscode['sam_source']=source_identity(saved_fast_sam(project,state))@@ -200,7 +201,7 @@ def features(project,emit):from .memory_mode import run as memory_runfrom .flow_sam import acceleration_optionsstate=json.loads((project/'project.json').read_text(encoding='utf-8'))- estimate=5.5 if acceleration_options(project,state)['sam_batch4'] else 4.5+ estimate=4.5 # Admission for the one-frame fast path; batching adapts after loading.return memory_run('FlowHMR SAM features',lambda low:_features(project,emit,low),estimate,emit)@@ -222,7 +223,10 @@ def _features(project,emit,low_memory):from .flow_sam import extract_tokenstokens=torch.empty((n,3072),dtype=torch.float32);anchors=[]try:- batch_size = 4 if options['sam_batch4'] and not low_memory else 1+ from .flow_sam_batch import current_batch_size, extract_bounded+ batch_size = current_batch_size(n,state['width'],state['height'],enabled=options['sam_batch4'],+ low_memory=low_memory,gpu_crops=options['sam_gpu_crop'])+ batch_limit = batch_sizeif 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:@@ -239,9 +243,11 @@ def _features(project,emit,low_memory):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)+ batch_limit = min(batch_limit,current_batch_size(n,state['width'],state['height'],+ enabled=options['sam_batch4'],low_memory=low_memory,gpu_crops=options['sam_gpu_crop']))+ values, outputs, batch_limit = extract_bounded(extractor, images, boxes[begin:begin+count],+ torch.from_numpy(k[None]), gpu_crops=options['sam_gpu_crop'], placement=begin<30,+ limit=batch_limit,emit=emit)else:token, outputs = extract_tokens(extractor, images[0], boxes[begin:begin+1],torch.from_numpy(k[None]), placement=begin<30)diff --git a/mocap/flow_fast_sam.py b/mocap/flow_fast_sam.pyindex 0068356..ce7ecb6 100644--- a/mocap/flow_fast_sam.py+++ b/mocap/flow_fast_sam.py@@ -30,8 +30,8 @@ def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placemefrom sam_3d_body.models.meta_arch.sam3d_body import _prepare_hand_batches_gpucount = 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 not 1 <= count <= 16 or len(boxes) != count:+ raise ValueError('Fast SAM requires one tracked body per frame, in batches of at most sixteen')if any(image.shape != images[0].shape for image in images):raise ValueError('Fast SAM frame sizes must match')estimator = extractor.estimator@@ -56,7 +56,7 @@ def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placemereturn recursive_to(left_batch, camera.device), recursive_to(right_batch, camera.device), flippedtry:- with torch.no_grad(), open(os.devnull, 'w') as quiet, contextlib.redirect_stdout(quiet):+ with torch.no_grad(), open(os.devnull, 'w', encoding='utf-8') 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')diff --git a/mocap/flow_sam.py b/mocap/flow_sam.pyindex 1a7121f..7c7f106 100644--- a/mocap/flow_sam.py+++ b/mocap/flow_sam.py@@ -85,7 +85,7 @@ def build_extractor(device, fast=True, low_memory=False):raise RuntimeError('The selected SAM package could not be activated.')# 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):+ with open(os.devnull, 'w', encoding='utf-8') as quiet, contextlib.redirect_stdout(quiet):if not low_memory:extractor = build_sam3d_extractor(device)else:@@ -121,7 +121,7 @@ def extract_tokens(extractor, img, boxes, k, placement=False):body.clear()hands.clear()try:- with torch.no_grad(), open(os.devnull, 'w') as quiet, contextlib.redirect_stdout(quiet):+ with torch.no_grad(), open(os.devnull, 'w', encoding='utf-8') as quiet, contextlib.redirect_stdout(quiet):outputs = extractor.estimator.process_one_image(img, bboxes=boxes, cam_int=k, inference_type='full')if not body or len(hands) != 1 or hands[0].shape[0] != 2:raise ValueError('Fast SAM did not return the expected body and left/right hand tokens')@@ -138,4 +138,4 @@ def extract_tokens(extractor, img, boxes, k, placement=False):return extractor.extract_frame(img, bboxes=boxes, cam_int=k, inference_type='full')finally:model._flow_tokens_only = previous-+diff --git a/mocap/flow_sam_batch.py b/mocap/flow_sam_batch.pynew file mode 100644index 0000000..08d8b3d--- /dev/null+++ b/mocap/flow_sam_batch.py@@ -0,0 +1,63 @@+"""Measured-throughput SAM batches; no precision or temporal changes."""+GIB = 1024**3+MAX_BATCH = 16+++def working_bytes(batch, width, height, gpu_crops):+ # In addition to loaded weights: decoder activations and (when selected)+ # vectorised full-resolution left/right GPU crop inputs. Calibrated at+ # 1080p on RTX 5090; larger images scale their upload/float workspace.+ # At 1080p the decoder peak dominates even with CPU crops. Do not mistake+ # disabling GPU crops for removing those per-frame activations.+ image_extra=max(0,36*(width*height-1920*1080)) if gpu_crops else 0+ return int(.25*GIB + batch*(.13*GIB + image_extra))+++def choose_batch_size(frames, width, height, available_gpu, available_ram,+ *, enabled=True, low_memory=False, gpu_crops=True):+ if not enabled or low_memory:return 1+ # Current + two prepared batches + a crop stack, independent of clip length.+ for batch in (MAX_BATCH, 8, 4, 2):+ if (batch <= frames and working_bytes(batch,width,height,gpu_crops) <= available_gpu+ and 4*batch*width*height*3 <= available_ram):+ return batch+ return 1+++def current_batch_size(frames, width, height, *, enabled=True, low_memory=False,+ gpu_crops=True):+ if not enabled or low_memory:return 1+ import torch,psutil+ from .compute_policy import gpu_reserve,ram_reserve+ free,total=torch.cuda.mem_get_info()+ allocated=torch.cuda.memory_allocated()+ cached=max(0,torch.cuda.memory_reserved()-allocated)+ cap=torch.cuda.get_per_process_memory_fraction()*total+ available=max(0,min(free+cached-gpu_reserve(total),cap-allocated))+ ram=psutil.virtual_memory()+ return choose_batch_size(frames,width,height,available,max(0,ram.available-ram_reserve(ram.total)),+ enabled=enabled,low_memory=low_memory,gpu_crops=gpu_crops)+++def extract_bounded(extractor,images,boxes,intrinsics,*,gpu_crops,placement,limit,emit):+ """Retry only an unpublished sub-batch after releasing the OOM traceback."""+ import torch,gc+ from .flow_fast_sam import extract_batch+ values=[];people=[];offset=0+ while offset<len(images):+ count=min(limit,len(images)-offset)+ failed=False+ try:+ value,output=extract_batch(extractor,images[offset:offset+count],boxes[offset:offset+count],+ intrinsics,gpu_crops=gpu_crops,placement=placement)+ except torch.cuda.OutOfMemoryError:+ if count==1:raise+ failed=True+ if failed:+ # The exception and its activation references are gone here.+ gc.collect();torch.cuda.empty_cache()+ limit=max(1,min(limit//2,count//2))+ emit('info',message=f'SAM GPU memory pressure: retrying unpublished frames with batch {limit}.')+ continue+ values.append(value);people.extend(output);offset+=count+ return torch.cat(values),people,limitdiff --git a/mocap/footmr.py b/mocap/footmr.pyindex 1e1e699..11786be 100644--- a/mocap/footmr.py+++ b/mocap/footmr.py@@ -64,7 +64,7 @@ def extract_keypoints(project, plan, emit):from .paths import UPSTREAMsignature.append(sha256(UPSTREAM / "FootMR/hmr4d/utils/preproc/vitpose_pytorch/src/vitpose_infer/model_builder.py"))signature = json.loads(json.dumps(signature))- if target.exists() and info_path.exists() and json.loads(info_path.read_text()) == signature:+ if target.exists() and info_path.exists() and json.loads(info_path.read_text(encoding='utf-8')) == signature:return torch.load(target, map_location="cpu", weights_only=False), Truewith np.load(project / "tracking.npz") as tracking:boxes = get_bbx_xys_from_xyxy(torch.from_numpy(tracking["boxes"]), base_enlarge=1.2)diff --git a/mocap/gui.py b/mocap/gui.pyindex 6eb0a32..bb83afe 100644--- a/mocap/gui.py+++ b/mocap/gui.py@@ -4,6 +4,7 @@ from .ui_refresh import batch_readinessfrom .validation_snapshot import read_only_checksimport json+import codecsimport mathimport osfrom collections import deque@@ -129,6 +130,8 @@ class ModelsDialog(QDialog):from .models import STAGE_REQUIREMENTSkeys = ({key for key in STAGE_REQUIREMENTS[self.tool.key+'_assets']} if self.tool.key in ('mamma','prompthmr','pear') else{key for stage in (*self.tool.stages(refine=True, footmr=True, handflow=True),'people') for key in STAGE_REQUIREMENTS.get(stage, ())})+ if self.tool.key=='pear':keys.update(STAGE_REQUIREMENTS['pear_align'])+ if self.tool.key=='flowhmr':keys.add('flow_metadata')# 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),@@ -147,7 +150,7 @@ class ModelsDialog(QDialog):layout.addWidget(runtime_panel(self))elif self.tool.key=='pear':from .pear_runtime import status- note=QLabel(status()[1]+'\nPEAR support is included in install.cmd and update.cmd. Uses the existing shared runtime; no CUDA compiler is needed. Model files are prepared separately below.')+ note=QLabel(status()[1]+'\nPEAR support is included in install.cmd and update.cmd. Uses the existing shared runtime; Camera Align uses a small Flow-runtime support overlay. No CUDA compiler is needed. VGGT and GeoCalib are optional for multiple fixed views; model files are prepared separately below.')note.setWordWrap(True);layout.addWidget(note)self.table = QTableWidget(len(self.models), 3)self.table.setHorizontalHeaderLabels(["Model", "Status", "Action"])@@ -194,8 +197,10 @@ class ModelsDialog(QDialog):self.refresh()def refresh(self):+ from .models import STAGE_REQUIREMENTSfor i, model in enumerate(self.models):name = model.name + (" (Optional: HTD / 2D)" if self.tool.key == "gvhmr" and model.key == "pva" else "")+ if self.tool.key=='pear' and model.key in STAGE_REQUIREMENTS['pear_align']:name+=' (Optional: Camera Align)'available = ready(model)for column, text in ((0, name), (1, "Ready" if available else "Missing")):item = self.table.item(i, column)@@ -635,6 +640,10 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspself.update_readiness()def choose_video(self):+ if self._pear_active:+ names,_=QFileDialog.getOpenFileNames(self,'Open PEAR Camera Videos','', 'Videos (*.mp4 *.mov *.avi *.mkv *.webm)')+ if names:self.load_pear_videos(names)+ returnif 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)@@ -644,13 +653,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspself.load_video(Path(name))def load_video(self, path):- if self._pear_active:- self.stop_playback()- self.pear_camera.blockSignals(True)- self.pear_camera.setCurrentIndex(0)- self.pear_camera.blockSignals(False)- self.video_readable=False- self.pear_source_changed()+ if self._pear_active:return self.load_pear_videos([path])if self.model_choice.currentData()=='mamma':return self.load_mamma_videos([path])try:@@ -689,6 +692,8 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspQMessageBox.warning(self, "Video Error", str(error))def video_ready(self, info):+ if self.pear_restore_media_ready():return+ if self.pear_video_ready(info):returnif self.mamma_video_ready(info):returnself.video_readable = Trueself.slider.set_media(self.info["fps"] if self.info else info["fps"])@@ -898,12 +903,12 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspself.play_button.setAccessibleName(label)def step_frames(self, amount):- if self._pear_active and self.pear_camera.currentData() is not None:return+ if self._pear_active and self.pear_using_webcams():returnself.stop_playback()self.slider.setValue(max(0, min(self.slider.maximum(), self.slider.value() + amount)))def toggle_play(self):- if self._pear_active and self.pear_camera.currentData() is not None:return+ if self._pear_active and self.pear_using_webcams():returnif self.timer.isActive():self.stop_playback()elif self.video_path and self.info and self.video_readable:@@ -1317,6 +1322,9 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspself.task_timer.start();self.update_task_progress()self.progress.setRange(0, 0)self.buffer = ""+ self._stdout_decoder = codecs.getincrementaldecoder("utf-8")("replace")+ self._stderr_decoder = codecs.getincrementaldecoder("utf-8")("replace")+ self._stderr_buffer = ""if stage in ('flow_batch','exmr_batch','gvhmr_batch'):from .queue_groups import write_requesttry:@@ -1371,9 +1379,10 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspatomic_json(path,state)except (OSError,ValueError) as error:self.log.append('Could not save stopped stage: '+str(error))- def read_stdout(self):+ def read_stdout(self, final=False):if self.processing_guard:self.processing_guard.output()- self.buffer += bytes(self.process.readAllStandardOutput()).decode("utf-8", errors="replace")+ self.buffer += self._stdout_decoder.decode(bytes(self.process.readAllStandardOutput()), final=final)+ if final and self.buffer and not self.buffer.endswith("\n"):self.buffer += "\n"if len(self.buffer) > 65536 and "\n" not in self.buffer:self.buffer = self.buffer[-65536:]while "\n" in self.buffer:@@ -1386,9 +1395,14 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspelif line.strip():self.log.append(line.rstrip())- def read_stderr(self):+ def read_stderr(self, final=False):if self.processing_guard:self.processing_guard.output()- self.log.append(bytes(self.process.readAllStandardError()).decode("utf-8", errors="replace").strip()[-8192:])+ text = self._stderr_decoder.decode(bytes(self.process.readAllStandardError()), final=final)+ self._stderr_buffer = (self._stderr_buffer + text.replace("\r", "\n"))[-65536:]+ lines = self._stderr_buffer.split("\n");self._stderr_buffer = lines.pop()+ if final and self._stderr_buffer:lines.append(self._stderr_buffer);self._stderr_buffer = ""+ for line in lines:+ if line.strip():self.log.append(line[-8192:])def handle_event(self, event):kind = event["type"]@@ -1423,7 +1437,7 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspelif kind == 'save_cancelled':self.cancelled=Trueself.status.setText(event['message'])- elif kind == 'resource_mode':+ elif kind in ('resource_mode', 'info'):self.log.append(event['message'])elif kind == "progress":message=event.get('message','Processing...')@@ -1447,8 +1461,8 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspself.log.ensureCursorVisible()def process_finished(self, code, _):- self.read_stdout()- self.read_stderr()+ self.read_stdout(final=True)+ self.read_stderr(final=True)if code != 0 and not self.cancelled:self.failed = Trueif "failed" not in self.status.text():@@ -1756,7 +1770,8 @@ class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspdef 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])+ if self._pear_active:self.load_pear_videos([Path(url.toLocalFile()) for url in urls])+ elif 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):diff --git a/mocap/image_io.py b/mocap/image_io.pynew file mode 100644index 0000000..93fe393--- /dev/null+++ b/mocap/image_io.py@@ -0,0 +1,54 @@+"""Unicode filesystem paths with OpenCV's unchanged image codecs.++Use Python for file I/O on Windows, where OpenCV's narrow filename API can+depend on the system code page. No resize, colour conversion or lossy recode+is introduced. The compatibility scope is only for isolated upstream workers.+"""+from contextlib import contextmanager+from pathlib import Path+++def read_image(filename, flags=1):+ import cv2+ import numpy as np+ try:+ data = Path(filename).read_bytes()+ except OSError:+ return None+ if not data:+ return None+ return cv2.imdecode(np.frombuffer(data, dtype=np.uint8), flags)+++def write_image(filename, image, params=None):+ import cv2+ path = Path(filename)+ ok, data = cv2.imencode(path.suffix, image, [] if params is None else params)+ if not ok:+ return False+ try:+ with path.open('wb') as stream:+ stream.write(memoryview(data))+ except OSError:+ return False+ return True+++@contextmanager+def unicode_image_paths():+ """Bridge upstream cv2 reads/writes in one dedicated Windows worker.++ Restore functions even on cancellation/errors. Never use this scope in+ the editor or a process running concurrent inference jobs.+ """+ import os+ if os.name != 'nt':+ yield+ return+ import cv2+ original_read, original_write = cv2.imread, cv2.imwrite+ cv2.imread, cv2.imwrite = read_image, write_image+ try:+ yield+ finally:+ cv2.imread, cv2.imwrite = original_read, original_writediff --git a/mocap/mamma_camera.py b/mocap/mamma_camera.pyindex b63a6b6..f959204 100644--- a/mocap/mamma_camera.py+++ b/mocap/mamma_camera.py@@ -9,6 +9,7 @@ import sysimport numpy as npfrom scipy.spatial.transform import Rotationfrom .storage import atomic_json+from .image_io import read_image, write_imagedef infer(work,job,emit):@@ -39,12 +40,12 @@ def infer(work,job,emit):im=frame(entry,f);h,w=im.shape[:2]if not .5<=h/w<=2:raise ValueError('VGGT camera calibration currently requires image aspect ratios between 1:2 and 2:1.')for mask in (work/'clean-masks/motion'/entry['id']/'masks').glob(f'mask_{f:04}_*.png'):- m=cv2.imread(str(mask),0)+ m=read_image(str(mask),0)if m is None:raise ValueError('Unreadable camera exclusion mask.')y,x=np.where(m>127)if len(x):im[max(0,y.min()-18):min(h,y.max()+19),max(0,x.min()-18):min(w,x.max()+19)]=0path=images_dir/f'{f:06}-{c}.png'- if not cv2.imwrite(str(path),im):raise OSError('Cannot prepare a VGGT input image.')+ if not write_image(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')from .memory_mode import run as memory_rundiff --git a/mocap/mamma_pipeline.py b/mocap/mamma_pipeline.pyindex 39ce0c5..4f072de 100644--- a/mocap/mamma_pipeline.py+++ b/mocap/mamma_pipeline.py@@ -15,6 +15,7 @@ import timeimport tracebackimport uuidfrom .storage import atomic_json+from .image_io import read_image, write_image, unicode_image_pathsfrom .result_artifacts import file_statSTAGES = ('mamma_prepare', 'mamma_masks', 'mamma_landmarks', 'mamma_camera', 'mamma_fit', 'mamma_publish')@@ -99,7 +100,7 @@ def prepare(path, job):# All connector code contributes, not just the model prediction script.from .paths import ROOTfrom .storage import sha256- 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')}+ identity['code']={name:sha256(ROOT/'mocap'/name) for name in ('mamma_pipeline.py','mamma_camera.py','mamma_inputs.py','image_io.py','memory_mode.py','gpu_offload.py')}token=hashlib.sha256(json.dumps(identity,sort_keys=True).encode()).hexdigest()[:24]slot=job['root']/'mamma'/'inference'/tokencached=False@@ -148,7 +149,8 @@ def run_script(engine, section, filename, args):sys.path[:0]=[str(directory),str(engine)]os.chdir(directory)sys.argv=[str(directory/filename),*map(str,args)]- runpy.run_path(sys.argv[0],run_name='__main__')+ with unicode_image_paths():+ runpy.run_path(sys.argv[0],run_name='__main__')def masks(engine, work, job):@@ -173,7 +175,7 @@ def masks(engine, work, job):dest.mkdir(parents=True,exist_ok=True)for i in range(len(frames)):if i%30==0:emit('progress',current=i,total=len(frames),message='Prepare SAM frames: '+frames.cam_name)- if not cv2.imwrite(str(dest/f'{i:06}.png'),frames.reader.read_bgr(i)):+ if not write_image(str(dest/f'{i:06}.png'),frames.reader.read_bgr(i)):raise OSError('Cannot write a lossless SAM input frame.')return str(dest)SegmentMultipleFrames._resolve_sam_video_source=resolve@@ -201,14 +203,14 @@ def masks(engine, work, job):count=0import numpy as npfor path in raw.glob('*/masks/*.png'):- im=cv2.imread(str(path),0)+ im=read_image(str(path),0)if im is None:raise ValueError('MAMMA produced an unreadable mask.')_,labels,stats,_=cv2.connectedComponentsWithStats((im>127).astype('uint8'),connectivity=8)sizes=stats[1:,cv2.CC_STAT_AREA]if len(sizes) and sizes.max()>=128:im[np.isin(labels,np.flatnonzero(sizes<8)+1)]=0out=cleaned/path.relative_to(raw);out.parent.mkdir(parents=True,exist_ok=True)- if not cv2.imwrite(str(out),im):raise OSError('Cannot write cleaned MAMMA mask.')+ if not write_image(str(out),im):raise OSError('Cannot write cleaned MAMMA mask.')count+=1if not count:raise ValueError('MAMMA produced no person masks. Check visibility and the initial camera.')diff --git a/mocap/mamma_runtime.py b/mocap/mamma_runtime.pyindex a35317c..30f31fa 100644--- a/mocap/mamma_runtime.py+++ b/mocap/mamma_runtime.py@@ -41,7 +41,7 @@ def configuration(root=ROOT):def command(stage, args):cfg = configuration()- return [cfg['python'], '-I', '-u', str(ROOT/'mamma_worker_boot.py'), stage, *map(str, args)]+ return [cfg['python'], '-I','-X','utf8', '-u', str(ROOT/'mamma_worker_boot.py'), stage, *map(str, args)]def activate():@@ -88,7 +88,7 @@ def configure(python, engine, root=ROOT, managed_id=None):code = ('import sys,json,importlib.metadata as m;''import torch,numpy,scipy,smplx,timm,torchvision,sam2,pytorch_sdf,open_clip;''print(json.dumps(dict(python=list(sys.version_info[:3]),packages={n:m.version(n) for n in '+repr(list(PACKAGES))+'},cuda=torch.cuda.is_available(),compute_capability=list(torch.cuda.get_device_capability()) if torch.cuda.is_available() else None)))')- result = subprocess.run([str(python), '-I', '-c', code], capture_output=True, text=True,+ result = subprocess.run([str(python), '-I','-X','utf8', '-c', code], capture_output=True, text=True,encoding='utf-8', errors='replace', timeout=120, creationflags=0x08000000)if result.returncode:raise RuntimeError('MAMMA runtime import check failed:\n'+result.stderr[-4000:])diff --git a/mocap/mamma_ui.py b/mocap/mamma_ui.pyindex 7727c5b..dc23827 100644--- a/mocap/mamma_ui.py+++ b/mocap/mamma_ui.py@@ -67,7 +67,7 @@ class InputInspector(QThread):im=cv2.resize(im,(max(1,round(w*scale)),max(1,round(h*scale))))im=cv2.cvtColor(im,cv2.COLOR_BGR2RGB)image=QImage(im.data,im.shape[1],im.shape[0],im.strides[0],QImage.Format_RGB888).copy()- result.append((dict(id=path.stem,path=str(path),metadata=dict(width=w,height=h,fps=fps,frames=frames,duration=frames/fps)),image))+ result.append((dict(id=path.stem,path=str(path),**({'file_stamp':[path.stat().st_size,path.stat().st_mtime_ns]} if kind=='pear_videos' else {}),metadata=dict(width=w,height=h,fps=fps,frames=frames,duration=frames/fps)),image))finally:cap.release()if not self.obsolete(kind,token):common_media([e for e,image in result])if not self.obsolete(kind,token):self.finished_input.emit(kind,token,result)diff --git a/mocap/model_guide.py b/mocap/model_guide.pyindex cde7560..58e22d1 100644--- a/mocap/model_guide.py+++ b/mocap/model_guide.py@@ -25,12 +25,12 @@ PROJECT_URLS = {'exmr': 'https://github.com/twehrbein/ExMR',}DESCRIPTIONS = {- 'pear':'Experimental support. Tracking and pose estimates may be unstable. Live single-person body and finger bone preview from a webcam or the current video frame. Fixed bone lengths are calibrated once; Reset Bones recalibrates from the displayed pose without reloading models. World Position is on by default; off fixes pelvis translation while preserving rotation. Body mesh is not computed per live frame. Select a webcam above the video, or choose None for video, then click Start Live Tracking. Stop releases models and the webcam. Uses YOLOv8s person detection; detector boxes can affect the resulting pose. Rotation and One Euro Filter apply to both sources. Adjustable One Euro smoothing reduces tremors with some motion-dependent lag and no extra inference. Seeks start from the selected frame; filtering continues during playback. No Find person, recording, Motion Correction, retargeting or motion export in this live mode. Pelvis placement assumes a fixed camera, not a calibrated world. Support files are included in install.cmd and update.cmd, reusing the shared runtime without upgrading its packages or requiring a CUDA compiler. Prepare the checkpoint and registered SMPL-X 2020/FLAME geometry bundle in Model Manager. See docs/models/PEAR.md.',+ 'pear':'Experimental support. Tracking and pose estimates may be unstable. Real-time tracking of webcam or video input, with a single-person body and finger bone preview from one or multiple fixed-camera views. Select synchronized videos with Open Video, or assign distinct webcam devices using the camera-count slots and thumbnails. Start Live Tracking attempts Camera Align first, including one camera; VGGT and GeoCalib are needed for alignment. A single view uses estimated body/depth scale; multiple views use triangulation. If alignment fails or its support/models are missing, tracking continues from the selected camera with a visible warning, without camera fusion or aligned foot lock. Use Camera Align to retry. Fixed bone lengths are calibrated once; Reset Bones recalibrates from the displayed pose, then aligns cameras again. World Position is on by default; off fixes pelvis translation while preserving rotation. Body mesh is not computed per live frame. Select a webcam in the table below the video for image preview without loading PEAR; click Start Live Tracking to attempt alignment and begin tracking. Capture stays connected during Start and Camera Align; opened videos can play while models load or align. Choose None for video. Stop releases models and the webcam. Uses YOLOv8s person detection; detector boxes can affect the resulting pose. Rotation and One Euro Filter apply to both sources. One Euro Filter has independent Bone Rotation and World Position checkboxes, both on by default, with shared Filter Strength. The position-filter checkbox is separate from the World Position movement switch. Filtering reduces tremors with some motion-dependent lag and no extra inference. Seeks start from the selected frame; filtering continues during playback. After successful alignment, default-on lightweight Foot Lock stabilizes low, slow feet with smooth causal transitions, fixed lengths and preserved ankle/toe directions. Reach limits and incorrect ground estimates can leave residual sliding. No Find person, recording, offline Motion Correction, retargeting or motion export in this live mode. Single-view pelvis placement assumes a fixed camera. Camera Align estimates background gravity, camera positions, scale and floor; these are not measured calibration and feet can still slide. Changed inputs and Reset Bones trigger realignment. After moving physical cameras, click Camera Align again. Webcam arrival-time pairing is approximate, not hardware sync. Support files are included in install.cmd and update.cmd, reusing the shared runtime without upgrading its packages or requiring a CUDA compiler. Prepare the checkpoint and registered SMPL-X 2020/FLAME geometry bundle in Model Manager. See docs/models/PEAR.md.','prompthmr': 'Reconstructs multiple people together from one video. In our subjective tests, it could give more accurate relative placement and interactions, but overall motion quality was lower than ExMR. Contacts, depth and intersections can still be wrong. Fixed cameras only in this Windows integration. People defaults to 2; 0 detects automatically, up to 8. Find person is not needed. Interaction Prompt defaults on; off follows the official default video path. Body motion uses SMPL-X. No finger tracking; untracked fingers use a fixed neutral pose. Supports the usual optional foot/hand contact correction, retargeting and FBX export. Requires Setup_PromptHMR.cmd and separate weights. Non-commercial scientific research license. See docs/models/PROMPTHMR.md.','mamma': 'Multi-view reconstruction of one or several people from two or more synchronized fixed-camera videos of the same performance. No fixed camera-count maximum; practical capacity depends on available RAM and VRAM. Detects people automatically; Find person is not needed. Uses SAM 2.1 masks, FP32 landmarks and VGGT cameras, or your compatible camera calibration. Body and finger motion, original results and contact-corrected results are preserved. Best suited to views that complement each other; occlusion and bad masks can cause errors. Slower than single-video methods. Requires the separate Setup_MAMMA.cmd runtime and registered restricted-use models. See Model Manager > Runtime Setup and docs/MAMMA.md.','gvhmr': 'Lowest overall motion quality in our tests, but sometimes better for unusual poses such as backflips. ''No native finger tracking. Optional HandFlow adds finger motion; FootMR refines ankles, and HTD refines body motion. These add processing time.',- 'flowhmr': 'Slow, but the best overall motion quality in our tests. Tracks body and fingers together without a separate finger add-on.',+ 'flowhmr': 'Slow, but the best overall motion quality in our tests. Tracks body and fingers together without a separate finger add-on. With Fast SAM and Adaptive Batching on, Automatic selects 1-16 frames from available memory and image size; Low Memory uses one. Tests of 4 to 16 frames reduced warm feature time by 16-23%, with allocated VRAM 3.84 to 5.43 GiB and small numerical motion differences. Short whole jobs benefit much less because model loading dominates. Batch selection, GPU Hand Crops and OOM batch retries appear in Console and CMD. See docs/models/FLOWHMR.md.','exmr': 'Generally fast, with good motion quality in our tests. A practical choice for a first attempt. Tracks body and fingers together without a separate finger add-on.',}diff --git a/mocap/models.py b/mocap/models.pyindex b10673a..bc4115b 100644--- a/mocap/models.py+++ b/mocap/models.py@@ -55,6 +55,8 @@ MODELS_LIST.extend([download_url=f'https://huggingface.co/fafsaf1/flowhmr-0.46B/resolve/{FLOW_REV}/flowhmr_latest/flowhmr_latest.ckpt', expected_sha256='b7eb06b119feaf5ad7287bafdb2fff38d42dfc22ea9d256f8cdd2ada26dfc53a'),Model('flow_config', 'FlowHMR configuration', 'flowhmr/config.yml', 'https://github.com/flowhmr/flowhmr', minimum_bytes=3067,download_url=f'https://huggingface.co/fafsaf1/flowhmr-0.46B/resolve/{FLOW_REV}/flowhmr_latest/config.yml', expected_sha256='5deae01800c031975558bf9675819e8d1e24803414f692b8b5c2196b266c64d7'),+ Model('flow_metadata', 'FlowHMR checkpoint metadata', 'flowhmr/config.json', 'https://huggingface.co/fafsaf1/flowhmr-0.46B', minimum_bytes=25,+ download_url=f'https://huggingface.co/fafsaf1/flowhmr-0.46B/resolve/{FLOW_REV}/config.json', expected_sha256='dd387080edacff4092e6d663e3d7ff04b848700711b113ad3cec9681bf11b8c1'),Model('flow_sam', 'Body / Hand Features / SAM 3D Body', 'flowhmr/sam/model.ckpt', 'https://huggingface.co/facebook/sam-3d-body-dinov3', minimum_bytes=2109129346,expected_sha256='b5a2f9d305dd02626b967aa2e86021fba07065df66ce7a7e00ffb9664f150abf'),Model('flow_sam_config', 'SAM 3D Body configuration', 'flowhmr/sam/model_config.yaml', 'https://huggingface.co/facebook/sam-3d-body-dinov3', minimum_bytes=1488,@@ -104,6 +106,7 @@ MODELS_LIST.extend(Model(**entry) for entry in PHMR_ASSETS)BY_KEY = {model.key: model for model in MODELS_LIST}if len(BY_KEY)!=len(MODELS_LIST):raise ValueError('Duplicate model identifiers in the model registry.')MANUAL_INSTRUCTIONS = {+ 'flow_metadata': 'Download config.json from the root of the supported FlowHMR Hugging Face revision. Auto Download can fetch this small public file. Import the original JSON in this row. This checkpoint metadata is separate from flowhmr_latest/config.yml; do not replace the inference YAML with it.','exmr_config': 'Download config.json using the Supported file link below. It is the official ExMR checkpoint metadata, pinned to the same revision as exmr.safetensors. Return to the ExMR configuration row and click Import. Import the original JSON file without editing or renaming it. Auto Download can obtain this small public file directly.','mano_right': '1. Open the Recommended download link below, or click Open Download Page. This opens the official download server for the exact archive. Sign in and accept the provider terms; register on the official MANO website if needed.\n2. Download mano_v1_2.zip. If browsing the MANO website instead, this is Models & Code > Models & Code.\n3. Extract the ZIP and open mano_v1_2/models.\n4. Return to Hand Model / MANO Right, click Import and select MANO_RIGHT.pkl. Keep this PKL file intact.\nHandFlow uses a right-hand canonical model for both hands, reflecting the left result back. The separate SMPL-H downloads cannot replace this hand model.','smplx': '1. Open the SMPL-X download page below. Register or sign in and accept the provider terms.\n2. In the "SMPL-X Model" section, choose "Download SMPL-X v1.1 (NPZ+PKL, 830 MB)". Choose the standard v1.1 download listed above.\n3. Download models_smplx_v1_1.zip and extract the outer ZIP archive.\n4. Inside the extracted folder, open models, then smplx. Choose SMPLX_NEUTRAL.npz. Leave this NPZ file intact.\n5. Return to the Body Model / SMPL-X Neutral row and click Import. Select that single NPZ file; Missing changes to Ready after validation.',@@ -151,6 +154,8 @@ MANUAL_DETAILS = {location='flowhmr_latest/flowhmr_latest.ckpt',avoid='flowhmr_base or another checkpoint revision.'),'flow_config': dict(selection='flowhmr_latest > config.yml',location='flowhmr_latest/config.yml',avoid='The flowhmr_base configuration, config.json, an HTML page, or a configuration from a different revision.'),+ 'flow_metadata': dict(selection='Files and versions > config.json (repository root)',+ location='config.json',avoid='config.yml, edited JSON, an HTML page, or a different revision.'),}for _key, _file in SAM_MANUAL_FILES.items():MANUAL_DETAILS[_key] = dict(selection='facebook/sam-3d-body-dinov3 > ' + _file,@@ -223,7 +228,8 @@ def manual_instructions_html(key: str) -> str:STAGE_REQUIREMENTS = {- 'pear_assets': PEAR_KEYS,+ 'pear_assets': ('pear','pear_geometry','pear_yolo'),+ 'pear_align': ('flow_vggt','pear_geocalib'),"people": ("yolo", "person_reid"),"track": ("yolo",), "pva": ("pva",),"features": ("hmr2", "vitpose"),@@ -271,6 +277,10 @@ def missing(stage: str,tool=None) -> list[Model]:def download(key: str, progress=None) -> Path:import gdown+ if key == 'flowhmr':+ # Hugging Face checkpoint metadata uses the same pinned revision. It is+ # not the inference YAML and must not invalidate existing motion caches.+ download('flow_metadata', progress)model = BY_KEY[key]if not model.drive_id and not model.download_url:raise ValueError("Obtain this model from its official website, then import it.")diff --git a/mocap/pear/align_worker.py b/mocap/pear/align_worker.pynew file mode 100644index 0000000..3303e8b--- /dev/null+++ b/mocap/pear/align_worker.py@@ -0,0 +1,148 @@+"""One-shot fixed-camera background alignment in a separate Flow-profile process."""+import sys,json,time,traceback,struct++def main():+ import os+ for key in ('OMP_NUM_THREADS','MKL_NUM_THREADS','OPENBLAS_NUM_THREADS'):os.environ.setdefault(key,'4')+ pipe=sys.stdout.buffer;sys.stdout=sys.stderr+ from .wire import send+ def progress(text):send(pipe,dict(type='status',text=text))+ try:+ request=json.loads(sys.stdin.buffer.readline(65537));folder=request['folder']+ align(folder,progress)+ send(pipe,dict(type='alignment',phase='complete',folder=folder))+ except Exception as exc:+ traceback.print_exc();send(pipe,dict(type='error',text='Camera Align failed: '+str(exc)))++def align(path,progress):+ from .multi_worker import owned_folder,read_parameters,write_sample+ from .alignment_support import activate+ activate()+ from ..paths import ROOT+ from ..storage import atomic_json,sha256+ from ..models import BY_KEY+ import numpy as np,torch,cv2,gc+ from scipy.spatial.transform import Rotation+ sys.path.insert(0,str(ROOT/'third_party/FlowHMR/third_party/vggt-omega'))+ from vggt_omega.utils.load_fn import load_and_preprocess_images+ from vggt_omega.utils.pose_enc import encoding_to_camera+ from ..gpu_offload import load_vggt,release+ from geocalib import GeoCalib+ from ..compute_policy import gpu_reserve+ torch.set_num_threads(4);cv2.setNumThreads(2)+ folder=owned_folder(path);job=json.loads((folder/'job.json').read_text('utf8'));n=int(job['count'])+ if not 1<=n<=32 or len(job['images'])!=2*n:raise ValueError('Invalid camera alignment job')+ for key in ('flow_vggt','pear_geocalib'):+ m=BY_KEY[key]+ if sha256(m.path)!=m.expected_sha256:raise ValueError('Prepare '+m.name+' in Model Manager.')+ if job.get('rig_sha256')!=sha256(folder/'rig.npz') or job.get('observations_sha256')!=sha256(folder/'observations.npz'):raise ValueError('Alignment samples changed; run Camera Align again')+ z=read_parameters(folder/'observations.npz')+ uv=z['uv'];boxes=z['boxes'];sizes=z['sizes'];rest=z['rest']+ if uv.shape!=(2,n,145,2) or boxes.shape!=(2,n,4) or sizes.shape!=(n,2) or rest.shape!=(55,3):raise ValueError('Invalid alignment observations')+ images=[];masks=[];paths=[]+ for i,name in enumerate(job['images']):+ if name!=f'sample-{i//n}-{i%n}.png':raise ValueError('Invalid calibration image path')+ image_path=folder/name+ if image_path.stat().st_size>32*1024**2:raise ValueError('Calibration image too large')+ encoded=image_path.read_bytes()+ if len(encoded)<24 or encoded[:8]!=b'\x89PNG\r\n\x1a\n':raise ValueError('Invalid calibration PNG')+ width,height=struct.unpack('>II',encoded[16:24])+ if not 0<width<=1920 or not 0<height<=1080:raise ValueError('Calibration image dimensions exceed the bounded sample size')+ im=cv2.imdecode(np.frombuffer(encoded,np.uint8),cv2.IMREAD_COLOR)+ if im is None:raise ValueError('Missing calibration sample')+ h,w=im.shape[:2];mask=np.ones((h,w),np.uint8);box=boxes[i//n,i%n].copy()+ if np.isfinite(box).all():+ box*=np.tile(np.array([w,h])/sizes[i%n],2);dx=(box[2]-box[0])*.12;dy=(box[3]-box[1])*.08+ x0,y0,x1,y1=np.rint(box+[-dx,-dy,dx,dy]).astype(int);mask[max(0,y0):min(h,y1),max(0,x0):min(w,x1)]=0+ bg=im.copy();bg[mask==0]=0;p=folder/f'background-{i}.png'+ write_sample(p,bg,cv2)+ # One view has no triangulation baseline. Keep actual person depth for+ # its rig-to-depth scale fit; floor/gravity still exclude the person.+ paths.append(image_path if n==1 else p);images.append(im);masks.append(mask)+ start=time.perf_counter();free,total=torch.cuda.mem_get_info()+ torch.cuda.set_per_process_memory_fraction(max(.001,min(1.,(free-gpu_reserve(total))/total)))+ stages=[];progress('Camera Align · Loading VGGT camera/depth model…')+ torch.cuda.reset_peak_memory_stats();t=time.perf_counter();model=load_vggt(BY_KEY['flow_vggt'].path,'cuda',camera_only=False)+ progress('Camera Align · VGGT background cameras and depth…')+ inputs=load_and_preprocess_images([str(p) for p in paths],mode='balanced',image_resolution=512).cuda()+ with torch.inference_mode():pred=model(inputs);E,K=encoding_to_camera(pred['pose_enc'],inputs.shape[-2:])+ torch.cuda.synchronize();E=E[0].cpu().numpy();small=K[0].cpu().numpy();H,W=inputs.shape[-2:];K=small.copy()+ for i in range(2*n):K[i,0,:]*=sizes[i%n,0]/W;K[i,1,:]*=sizes[i%n,1]/H+ depth=pred['depth'][0].cpu().numpy().squeeze(-1);confidence=pred['depth_conf'][0].cpu().numpy()+ pixels=inputs.cpu().numpy();stages.append(dict(stage='VGGT',seconds=time.perf_counter()-t,peak_vram_gib=torch.cuda.max_memory_allocated()/2**30))+ del pred,inputs;release(model);del model;gc.collect();torch.cuda.empty_cache()+ RR=[];tt=[];KK=[]+ for c in range(n):+ es=E[[c,c+n]];r=Rotation.from_matrix(es[:,:,:3]).mean().as_matrix()+ centres=-np.einsum('nij,nj->ni',es[:,:,:3].transpose(0,2,1),es[:,:,3]);RR.append(r);tt.append([email protected](centres,axis=0));KK.append(np.median(K[[c,c+n]],axis=0))+ RR,tt,KK=np.array(RR),np.array(tt),np.array(KK);[email protected]([RR,tt[...,None]],axis=-1)+ progress('Camera Align · GeoCalib background gravity…');t=time.perf_counter();torch.cuda.reset_peak_memory_stats()+ model=GeoCalib(str(BY_KEY['pear_geocalib'].path)).cuda().eval();gravity=[];active_mask=None+ def exclude_actor(module,args,out):+ for key in ('up_confidence','latitude_confidence'):+ mask=torch.nn.functional.interpolate(active_mask,size=out[key].shape[-2:],mode='nearest')+ out[key]=out[key]*(mask[:,0] if out[key].ndim==3 else mask)+ return out+ hook=model.model.perspective_decoder.register_forward_hook(exclude_actor)+ with torch.inference_mode():+ for i,(im,mask) in enumerate(zip(images,masks)):+ progress(f'Camera Align · GeoCalib {i+1}/{2*n}')+ tensor=torch.from_numpy(im[...,::-1].copy()).permute(2,0,1).float().cuda()/255+ active_mask=model.image_processor(torch.from_numpy(mask.astype('float32')).cuda()[None,None])['image']+ # The focal prior is in sample pixels, not the original 4K dimensions.+ focal=KK[i%n,1,1]*im.shape[0]/sizes[i%n,1]+ result=model.calibrate(tensor,priors={'focal':tensor.new_tensor(float(focal))})+ g=result['gravity'].vec3d[0].cpu().numpy();gravity.append(E[i,:,:3].T@g)+ stages.append(dict(stage='GeoCalib',seconds=time.perf_counter()-t,peak_vram_gib=torch.cuda.max_memory_allocated()/2**30))+ hook.remove();del model,result,tensor;gc.collect();torch.cuda.empty_cache()+ progress('Camera Align · Fixed-rig scale and background floor…')+ ratios=[]+ for sample in range(2):+ views=[c for c in range(n) if np.isfinite(uv[sample,c,:55]).all()]+ if len(views)<2:continue+ X=[]+ for k in range(55):+ a=np.stack([v for c in views for v in (uv[sample,c,k,0]*P[c,2]-P[c,0],uv[sample,c,k,1]*P[c,2]-P[c,1])])+ _,_,vh=np.linalg.svd(a);X.append(vh[-1,:3]/vh[-1,3])+ X=np.array(X)+ for a,b in ((1,4),(4,7),(2,5),(5,8),(16,18),(18,20),(17,19),(19,21)):+ d=np.linalg.norm(X[a]-X[b])+ if np.isfinite(d) and d>1e-5:ratios.append(np.linalg.norm(rest[a]-rest[b])/d)+ if n==1:+ from .single_alignment import metric_scale+ ratios=metric_scale(z,KK[0],depth,confidence)+ if not ratios:raise ValueError('Insufficient person observations for estimated metric scale')+ scale=float(np.median(ratios))+ if not .01<scale<100:raise ValueError('Unstable camera scale; use clearer, overlapping fixed views')+ up=np.mean(gravity,axis=0);up/=np.linalg.norm(up)+ scatter=float(np.degrees(np.arccos(np.clip(np.asarray(gravity)@up,-1,1))).max())+ if not np.isfinite(up).all() or scatter>30:raise ValueError('Background gravity estimates disagree. Try another calibration time.')+ forward=RR[0][email protected]([0.,0.,1.]);forward-=up*np.dot(forward,up)+ if np.linalg.norm(forward)<.05:raise ValueError('Reference camera is too close to vertical')+ forward/=np.linalg.norm(forward);right=np.cross(forward,up);Q=np.stack([right,forward,up]);origin=-scale*Q@(-RR[0].T@tt[0]);heights=[]+ for i in range(2*n):+ h,w=depth[i].shape;yy,xx=np.mgrid[:h,:w];rays=np.stack([xx,yy,np.ones_like(xx)],-1)@np.linalg.inv(small[i]).T+ X=scale*((rays*depth[i][...,None]-E[i,:,3])@E[i,:,:3]@Q.T)+origin+ normal=np.cross(X[1:-1,2:]-X[1:-1,:-2],X[2:,1:-1]-X[:-2,1:-1]);normal/=np.maximum(np.linalg.norm(normal,axis=-1,keepdims=True),1e-9)+ dot=np.zeros((h,w));dot[1:-1,1:-1]=abs(normal[...,2])+ background=cv2.resize(masks[i],(w,h),interpolation=cv2.INTER_NEAREST)>0+ valid=(yy>h*.65)&background&(dot>.95)&(confidence[i]>np.percentile(confidence[i],35))&(pixels[i].max(0)>.04)&np.isfinite(X).all(-1)+ heights.extend(X[valid,2])+ heights=np.array(heights)+ if len(heights)<100:raise ValueError('Not enough visible horizontal background floor. Choose a frame showing the floor.')+ # Fixed bin budget avoids pathological predicted depth ranges allocating huge histograms.+ low,high=np.percentile(heights,[1,99]);bins=min(8192,max(2,int((high-low)/.025)+1))+ hist,edges=np.histogram(heights,bins=bins,range=(low,high));mode=(edges[hist.argmax()]+edges[hist.argmax()+1])/2+ selected=heights[abs(heights-mode)<.06]+ if len(selected)<100:raise ValueError('Background floor estimate is unstable')+ floor=float(np.median(selected));origin[2]-=floor+ extrinsics=np.array([np.c_[[email protected],scale*t-([email protected])@origin] for r,t in zip(RR,tt)])+ if not np.isfinite(extrinsics).all():raise ValueError('Nonfinite camera calibration')+ record=dict(version=1,signature=job['signature'],rig_sha256=job['rig_sha256'],intrinsics=KK.tolist(),extrinsics=extrinsics.tolist(),sizes=sizes.tolist(),+ seconds=time.perf_counter()-start,stages=stages,gravity_scatter_deg=scatter,scale=scale,+ floor_residual_p95_m=float(np.percentile(abs(selected-floor),95)),scale_is_estimated=True,+ scale_method='single-view inferred metric rig / predicted person depth' if n==1 else 'multi-view body triangulation')+ atomic_json(folder/'cameras.json',record)+ # Retain only tiny calibration/rig data after success, not captured personal images.+ for p in folder.glob('*.png'):p.unlink()+ progress(f'Camera Align complete · {record["seconds"]:.1f} s')diff --git a/mocap/pear/alignment_support.py b/mocap/pear/alignment_support.pynew file mode 100644index 0000000..37c6b1e--- /dev/null+++ b/mocap/pear/alignment_support.py@@ -0,0 +1,19 @@+"""Optional camera-align support over the pinned Flow runtime, without upgrades."""+from pathlib import Path+import json,hashlib,sys+from ..paths import ROOT++def identity():return hashlib.sha256((ROOT/'installer/pear-alignment.json').read_bytes()+(ROOT/'tools/setup_pear_alignment.py').read_bytes()).hexdigest()+def configuration():+ data=json.loads((ROOT/'.setup/pear-alignment.json').read_text('utf8'));folder=(ROOT/data['folder']).resolve()+ if not folder.is_relative_to((ROOT/'runtime_pear').resolve()) or data['identity']!=identity():raise ValueError('Camera alignment support needs install.cmd')+ for name,stamp in data['files'].items():+ p=(folder/name).resolve()+ if not p.is_relative_to(folder):raise ValueError('Invalid alignment support path')+ st=p.stat()+ if [st.st_size,st.st_mtime_ns]!=stamp:raise ValueError('Camera alignment support changed; run install.cmd')+ if not (folder/'geocalib/__init__.py').is_file():raise ValueError('Missing GeoCalib support')+ return folder+def activate():+ folder=configuration();sys.dont_write_bytecode=True;sys.path.insert(0,str(folder));return folder+diff --git a/mocap/pear/batch.py b/mocap/pear/batch.pynew file mode 100644index 0000000..071d440--- /dev/null+++ b/mocap/pear/batch.py@@ -0,0 +1,141 @@+"""Bounded FP32 detector batches and exact BGR crops; no TensorRT dependency.++Uses the existing pinned Ultralytics model/operators and PEAR preprocessing.+One graph per current batch shape, at most four images; CPU work uses four threads.+"""+import ast,copy,types,sys+from pathlib import Path+from .core import torch,np,cv2,CROP+from ultralytics.data.augment import LetterBox+from ultralytics.utils import ops+import torchvision+WARM_STREAM=None+def warm_stream():+ global WARM_STREAM+ if WARM_STREAM is None:WARM_STREAM=torch.cuda.Stream()+ return WARM_STREAM++def hoisted_method(head,name):+ """Only replace two literal CUDA constants; preserve all numerical operations."""+ module=sys.modules[type(head).__module__];tree=ast.parse(Path(module.__file__).read_text('utf8'));cls=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name==type(head).__name__);fn=copy.deepcopy(next(n for n in cls.body if isinstance(n,ast.FunctionDef) and n.name==name))+ class Constants(ast.NodeTransformer):+ def visit_Call(self,node):+ if isinstance(node.func,ast.Attribute) and isinstance(node.func.value,ast.Name) and node.func.value.id=='torch' and node.func.attr=='tensor' and node.args and isinstance(node.args[0],ast.List):+ return ast.copy_location(ast.Attribute(ast.Name('self',ast.Load()),'_graph_R' if isinstance(node.args[0].elts[0],ast.List) else '_graph_bias',ast.Load()),node)+ return self.generic_visit(node)+ fn=Constants().visit(fn);scope=dict(module.__dict__);exec(compile(ast.fix_missing_locations(ast.Module(body=[fn],type_ignores=[])),'<PEAR fixed CUDA constants>','exec'),scope);return types.MethodType(scope[name],head)++class Net(torch.nn.Module):+ def __init__(self,base):+ super().__init__();self.base=base;self.static=None;self.graph=None;self.output=None+ def body(self,x):return self.base.head(self.base.backbone(x).float())+ def forward(self,x):+ x=self.base.normalize(x)[:,:,:,32:-32].half().contiguous()+ if self.static is not None and self.static.shape!=x.shape:self.static=None;self.graph=None;self.output=None+ if self.graph is None:+ self.static=torch.empty_like(x);self.static.copy_(x);stream=warm_stream();stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(3):self.body(self.static)+ torch.cuda.current_stream().wait_stream(stream);self.graph=torch.cuda.CUDAGraph()+ with torch.cuda.graph(self.graph):self.output=self.body(self.static)+ self.static.copy_(x);self.graph.replay();return self.output+++def leaves(out):+ return [('camera',out['pd_cam'])]+[(group+'_'+k,v) for group in ('body_param','flame_param') for k,v in out[group].items() if torch.is_tensor(v)]++def cpu_output(out,packed=False):+ items=leaves(out)+ if not packed:return {k:v.detach().float().cpu().numpy().copy() for k,v in items}+ sizes=[v.numel() for _,v in items];flat=torch.cat([v.float().reshape(-1) for _,v in items]).cpu().numpy();result={};start=0+ for (k,v),size in zip(items,sizes):result[k]=flat[start:start+size].reshape(tuple(v.shape)).copy();start+=size+ return result+def select(boxes,previous):+ if not len(boxes):return None+ if previous is None:return max(boxes,key=lambda b:(b[2]-b[0])*(b[3]-b[1])).copy()+ a=np.maximum(0,np.minimum(boxes[:,2:],previous[2:])-np.maximum(boxes[:,:2],previous[:2])).prod(1)+ iou=a/np.maximum(1,(boxes[:,2:]-boxes[:,:2]).prod(1)+(previous[2:]-previous[:2]).prod()-a)+ return boxes[iou.argmax()].copy() if iou.max()>=.1 else None++def crop(im,box,bgr=False,nocopy=False):+ x,y,x2,y2=box+ bbox=CROP['process_bbox'](np.array([x,y,x2-x,y2-y]),im.shape[1],im.shape[0],[256,256],ratio=1.25)+ if bbox is None:return None+ rgb=im if bgr else cv2.cvtColor(im,cv2.COLOR_BGR2RGB)+ if nocopy:+ x0=float(bbox[0]+.5*bbox[2]);y0=float(bbox[1]+.5*bbox[3])+ trans=CROP['gen_trans_from_patch_cv'](x0,y0,float(bbox[2]),float(bbox[3]),256,256,1.,0.)+ patch=cv2.warpAffine(rgb,trans,(256,256),flags=cv2.INTER_LINEAR).astype(np.float32)+ else:patch,_,_=CROP['generate_patch_image'](rgb,bbox,1.,0.,False,[256,256])+ if bgr:patch=patch[...,::-1]+ return patch.transpose(2,0,1).copy(),bbox.copy()++class BatchRunner:+ def __init__(self,pear,pool):+ self.pear=pear;self.pool=pool;self.previous=[];self.detector_shape=None;self.graph=None+ self.base=pear.model.original+ # Release the previous single-frame encoder graph before taking ownership.+ pear.model.static=None;pear.model.graphed=None+ if hasattr(pear.model,"graph"):pear.model.graph=None+ head=self.base.head+ head._graph_R=torch.tensor([[-1.,0.,0.],[0.,-1.,0.],[0.,0.,1.]],device='cuda')+ head._graph_bias=torch.tensor([0.,0.,1.5],device='cuda')+ head.forward=hoisted_method(head,'forward');head.get_full_proj=hoisted_method(head,'get_full_proj')+ self.net=Net(self.base).eval()+ self.lb=LetterBox([640,640],auto=False,stride=32)+ self.raw=None;self.static=None;self.gout=None+ def reset(self,count):self.previous=[None]*count+ def pre(self,im):return self.lb(image=im)[...,::-1].transpose(2,0,1).copy()+ @torch.inference_mode()+ def detect(self,images):+ if self.raw is None:+ self.pear.detector.predict(images[0],device=0,classes=[0],conf=.5,imgsz=640,verbose=False)+ self.raw=self.pear.detector.predictor.model.model.float().eval()+ # Auto letterbox is exact for a homogeneous batch; square padding for mixed aspects.+ self.lb.auto=self.auto_letterbox+ x=torch.from_numpy(np.stack(list(self.pool.map(self.pre,images)))).cuda().float()/255+ shape=tuple(x.shape)+ if shape!=self.detector_shape:+ self.graph=None;self.gout=None;self.static=x.clone();self.detector_shape=shape+ for _ in range(4):self.raw(x)+ stream=warm_stream();stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(3):self.raw(self.static)+ torch.cuda.current_stream().wait_stream(stream)+ self.graph=torch.cuda.CUDAGraph()+ with torch.cuda.graph(self.graph):self.gout=self.raw(self.static)+ self.static.copy_(x);self.graph.replay();pred=self.gout[0] if isinstance(self.gout,(tuple,list)) else self.gout+ p=pred.transpose(1,2);conf,cls=p[:,:,4:].max(-1);mask=(conf>.5)&(cls==0);ix=mask.nonzero()+ coords=ops.xywh2xyxy(p[ix[:,0],ix[:,1],:4]);scores=conf[mask]+ keep=torchvision.ops.batched_nms(coords.float(),scores.float(),ix[:,0],.7)+ result=[]+ for c,im in enumerate(images):+ ids=keep[ix[keep,0]==c][:300];result.append(ops.scale_boxes(x.shape[2:],coords[ids].clone(),im.shape))+ lengths=[len(v) for v in result];allboxes=torch.cat(result).cpu().numpy()+ return list(np.split(allboxes,np.cumsum(lengths)[:-1]))+ @torch.inference_mode()+ def run(self,images):+ if len(self.previous)!=len(images):self.reset(len(images))+ packets=[None]*len(images);batch_size=min(4,len(images))+ self.auto_letterbox=len({im.shape[:2] for im in images})==1+ # GPU batch size stays bounded independently of camera count. Only valid views enter PEAR.+ for start in range(0,len(images),4):+ group=images[start:start+4]+ detector_images=group+[group[-1]]*(batch_size-len(group))+ detections=self.detect(detector_images)[:len(group)]+ selected=[select(boxes,self.previous[start+i]) for i,boxes in enumerate(detections)]+ for i,box in enumerate(selected):self.previous[start+i]=box+ ids=[i for i,b in enumerate(selected) if b is not None]+ crops=list(self.pool.map(lambda i:crop(group[i],selected[i],True,True),ids))+ valid=[(i,c) for i,c in zip(ids,crops) if c is not None]+ ids=[i for i,c in valid];crops=[c for i,c in valid]+ if not ids:continue+ # Keep the graph's batch shape stable through occlusion. Padded rows+ # are never emitted as observations or included in fusion.+ patches=[v[0] for v in crops];patches+= [patches[-1]]*(batch_size-len(patches))+ out=cpu_output(self.net(torch.from_numpy(np.stack(patches)).cuda()/255),True)+ for j,i in enumerate(ids):+ packets[start+i]=dict(body={k[11:]:v[j:j+1] for k,v in out.items() if k.startswith('body_param_')},+ flame={k[12:]:v[j:j+1] for k,v in out.items() if k.startswith('flame_param_')},+ camera=out['camera'][j].copy(),bbox=selected[i].copy(),crop_bbox=crops[j][1],image_size=np.array(group[i].shape[1::-1]))+ return packetsdiff --git a/mocap/pear/camera_preview.py b/mocap/pear/camera_preview.pynew file mode 100644index 0000000..afc63de--- /dev/null+++ b/mocap/pear/camera_preview.py@@ -0,0 +1,100 @@+"""Camera-only preview: bounded latest frames, no PEAR/Torch/model loading."""+import sys,json,threading,time,traceback++class CameraPreview:+ def __init__(self,cv):+ self.cv=cv;self.cameras=[];self.sources=None;self.latest=[]+ self.publishers=[];self.publish_lock=threading.Lock();self.closing=False+ def close(self):+ self.closing=True;cameras=self.cameras;self.cameras=[];self.sources=None;self.latest=[]+ errors=[]+ for camera in cameras:+ try:camera.close()+ except Exception as exc:errors.append(exc)+ if errors:raise errors[0]+ for publisher in self.publishers:+ if publisher:publisher.close()+ self.publishers=[]+ def publish(self,index,image,timestamp):+ from .camera_stream import FrameWriter,MAX_TOTAL+ with self.publish_lock:+ if self.closing:return+ if self.publishers[index] is None:+ if sum(p.size for p in self.publishers if p)+image.nbytes>MAX_TOTAL:raise RuntimeError('Shared webcam frames exceed 512 MiB. Choose a lower webcam resolution.')+ self.publishers[index]=FrameWriter(image.shape)+ publisher=self.publishers[index]+ publisher.publish(image,timestamp)+ def update(self,request,force=False):+ import numpy as np+ from .worker import LatestCamera+ from .input_transform import rotate_frame,input_rotations+ sources=request['sources'];slots=request['slots'];count=int(request['slot_count'])+ if not 1<=len(sources)<=count<=32 or len(slots)!=len(sources) or len(set(slots))!=len(slots) or any(not 0<=s<count for s in slots):raise ValueError('Invalid webcam preview slots')+ if len({s['id'] for s in sources})!=len(sources):raise ValueError('Each webcam slot must use a different device.')+ angles=input_rotations(request,len(sources))+ key=json.dumps([sources,request['resolution']],sort_keys=True)+ if key!=self.sources:+ self.close()+ self.closing=False;self.publishers=[None]*len(sources)+ try:+ for i,device in enumerate(sources):self.cameras.append(LatestCamera(device,request['resolution'],self.cv,on_frame=lambda im,t,i=i:self.publish(i,im,t)))+ except Exception:self.close();raise+ self.sources=key;self.latest=[None]*len(sources);force=True+ fresh=False+ for i,camera in enumerate(self.cameras):+ try:item=camera.take(timeout=0.)+ except Exception as exc:raise RuntimeError(sources[i]['name']+': '+str(exc)) from exc+ if item is not None:self.latest[i]=item[0];fresh=True+ if not fresh and not force:return None+ thumbs=np.zeros((count,72,128,3),np.uint8);arrays={};selected=int(request['preview'])+ for slot,raw,angle in zip(slots,self.latest,angles):+ if raw is None:continue+ image=rotate_frame(raw,angle);h,w=image.shape[:2];scale=min(128/w,72/h)+ small=self.cv.resize(image,(max(1,round(w*scale)),max(1,round(h*scale))))+ thumbs[slot,:small.shape[0],:small.shape[1]]=small[...,::-1]+ if slot==selected:+ scale=min(1,1280/w,720/h)+ if scale<1:image=self.cv.resize(image,(round(w*scale),round(h*scale)))+ arrays['image']=np.ascontiguousarray(image[...,::-1])+ if count>1:arrays['thumbnails']=thumbs+ with self.publish_lock:+ streams=[dict(p.descriptor(),slot=slot,device_id=device['id']) for slot,device,p in zip(slots,sources,self.publishers) if p is not None]+ return dict(type='camera_preview',generation=request['generation'],preview=selected,ready='image' in arrays,streams=streams),arrays++def main():+ pipe=sys.stdout.buffer;sys.stdout=sys.stderr+ from .wire import send+ condition=threading.Condition();state={'request':None,'serial':0,'stop':False}+ def controls():+ try:+ while True:+ line=sys.stdin.buffer.readline(65537)+ if not line or len(line)>65536:break+ request=json.loads(line)+ with condition:+ if request.get('stop'):break+ state['request']=request;state['serial']+=1;condition.notify_all()+ finally:+ with condition:state['stop']=True;condition.notify_all()+ threading.Thread(target=controls,daemon=True).start()+ preview=None+ try:+ import cv2+ cv2.setNumThreads(2);preview=CameraPreview(cv2);seen=-1;notice=0;last_frame=time.monotonic()+ while True:+ started=time.monotonic()+ with condition:+ while not state['stop'] and state['request'] is None:condition.wait(.1)+ if state['stop']:break+ request=dict(state['request']);force=seen!=state['serial'];seen=state['serial']+ packet=preview.update(request,force)+ if packet:+ meta,arrays=packet;send(pipe,meta,**arrays)+ if meta['ready']:last_frame=time.monotonic()+ elif time.monotonic()-last_frame>2 and time.monotonic()-notice>1:+ notice=time.monotonic();send(pipe,dict(type='status',generation=request['generation'],text='Waiting for webcam frames…'))+ with condition:condition.wait(max(.001,1/30-(time.monotonic()-started)))+ except Exception as exc:+ traceback.print_exc();send(pipe,dict(type='error',text='Webcam preview: '+str(exc)))+ finally:+ if preview:preview.close()diff --git a/mocap/pear/camera_stream.py b/mocap/pear/camera_stream.pynew file mode 100644index 0000000..3dcae1b--- /dev/null+++ b/mocap/pear/camera_stream.py@@ -0,0 +1,101 @@+"""Windows shared camera frames. One capture owner, bounded independent readers."""+import ctypes,os,re,struct,time,uuid,math+from multiprocessing import shared_memory+import numpy as np++HEADER=64+MAX_FRAME=64*1024**2+MAX_TOTAL=512*1024**2+FORMAT=struct.Struct('<QdI')++class Mutex:+ def __init__(self,name,create):+ if os.name!='nt':raise RuntimeError('Live shared camera streams require Windows.')+ dll=ctypes.WinDLL('kernel32',use_last_error=True)+ dll.CreateMutexW.argtypes=[ctypes.c_void_p,ctypes.c_int,ctypes.c_wchar_p];dll.CreateMutexW.restype=ctypes.c_void_p+ dll.OpenMutexW.argtypes=[ctypes.c_ulong,ctypes.c_int,ctypes.c_wchar_p];dll.OpenMutexW.restype=ctypes.c_void_p+ dll.WaitForSingleObject.argtypes=[ctypes.c_void_p,ctypes.c_ulong];dll.WaitForSingleObject.restype=ctypes.c_ulong+ dll.ReleaseMutex.argtypes=[ctypes.c_void_p];dll.ReleaseMutex.restype=ctypes.c_int+ dll.CloseHandle.argtypes=[ctypes.c_void_p];dll.CloseHandle.restype=ctypes.c_int+ self.dll=dll;self.handle=dll.CreateMutexW(None,False,name) if create else dll.OpenMutexW(0x100001,False,name)+ if not self.handle:raise ctypes.WinError(ctypes.get_last_error())+ def acquire(self,milliseconds=0):+ result=self.dll.WaitForSingleObject(self.handle,milliseconds)+ if result==258:return False+ if result==128:+ self.release();raise RuntimeError('Camera stream owner stopped while updating a frame.')+ if result!=0:raise ctypes.WinError(ctypes.get_last_error())+ return True+ def release(self):self.dll.ReleaseMutex(self.handle)+ def close(self):+ if self.handle:self.dll.CloseHandle(self.handle);self.handle=None++class FrameWriter:+ def __init__(self,shape):+ shape=tuple(int(v) for v in shape)+ if len(shape)!=3 or shape[2]!=3 or min(shape)<1 or max(shape[:2])>8192:raise ValueError('Invalid webcam frame shape')+ self.shape=shape;self.size=math.prod(shape)+ if self.size>MAX_FRAME:raise ValueError('Webcam frame exceeds the shared capture limit; choose a lower capture resolution.')+ self.name='rgbmocap-pear-'+uuid.uuid4().hex;self.memory=None;self.mutex=None;self.pixels=None;self.sequence=0+ try:+ self.mutex=Mutex(self.name+'-lock',True)+ self.memory=shared_memory.SharedMemory(name=self.name,create=True,size=HEADER+self.size)+ self.pixels=np.ndarray(shape,np.uint8,buffer=self.memory.buf,offset=HEADER)+ FORMAT.pack_into(self.memory.buf,0,0,0.,0)+ except Exception:self.close();raise+ def descriptor(self):return dict(name=self.name,shape=list(self.shape),bytes=self.size)+ def publish(self,image,timestamp):+ if image.dtype!=np.uint8 or image.shape!=self.shape:raise ValueError('Webcam frame dimensions changed. Select the camera again.')+ if not math.isfinite(timestamp):raise ValueError('Invalid webcam timestamp')+ if not self.mutex.acquire():return+ try:+ np.copyto(self.pixels,image);self.sequence+=1+ FORMAT.pack_into(self.memory.buf,0,self.sequence,float(timestamp),0)+ finally:self.mutex.release()+ def close(self):+ if self.memory:+ if self.mutex and self.mutex.acquire(50):+ try:FORMAT.pack_into(self.memory.buf,0,self.sequence,time.monotonic(),1)+ finally:self.mutex.release()+ self.pixels=None;self.memory.close();self.memory.unlink();self.memory=None+ if self.mutex:self.mutex.close();self.mutex=None++class RemoteCamera:+ def __init__(self,descriptor):+ name=descriptor['name'];shape=descriptor['shape']+ if not isinstance(name,str) or not re.fullmatch(r'rgbmocap-pear-[0-9a-f]{32}',name):raise ValueError('Invalid shared webcam stream')+ if not isinstance(shape,list) or len(shape)!=3 or any(type(v)!=int or v<1 for v in shape) or shape[2]!=3 or max(shape[:2])>8192:raise ValueError('Invalid shared webcam dimensions')+ size=math.prod(shape)+ if size>MAX_FRAME or descriptor.get('bytes')!=size:raise ValueError('Invalid shared webcam size')+ self.memory=None;self.mutex=None;self.pixels=None;self.sequence=0+ try:+ self.mutex=Mutex(name+'-lock',False);self.memory=shared_memory.SharedMemory(name=name,create=False)+ if not HEADER+size<=self.memory.size<=HEADER+MAX_FRAME+65536:raise ValueError('Shared webcam allocation size changed')+ self.pixels=np.ndarray(tuple(shape),np.uint8,buffer=self.memory.buf,offset=HEADER)+ self.pixels.setflags(write=False)+ except Exception:self.close();raise+ def take(self,timeout=.2):+ deadline=time.monotonic()+max(0.,timeout)+ while True:+ if self.mutex.acquire():+ try:+ sequence,stamp,closed=FORMAT.unpack_from(self.memory.buf)+ if closed:raise RuntimeError('Webcam capture was closed. Select the device again.')+ if sequence and (not math.isfinite(stamp) or stamp>time.monotonic()+1):raise RuntimeError('Invalid webcam stream timestamp')+ if sequence and time.monotonic()-stamp>5:raise RuntimeError('Webcam stopped delivering fresh frames.')+ if sequence!=self.sequence and sequence:+ image=self.pixels.copy();self.sequence=sequence;return image,stamp+ finally:self.mutex.release()+ if time.monotonic()>=deadline:return None+ time.sleep(.003)+ def close(self):+ self.pixels=None+ if self.memory:self.memory.close();self.memory=None+ if self.mutex:self.mutex.close();self.mutex=None++def open_camera(device,height,cv,stream=None):+ if stream is not None:+ if stream.get('device_id')!=device['id']:raise ValueError('Webcam stream does not match the selected device')+ return RemoteCamera(stream)+ from .worker import LatestCamera+ return LatestCamera(device,height,cv)diff --git a/mocap/pear/fixed_rig.py b/mocap/pear/fixed_rig.pyindex 8fa76a0..7916cc6 100644--- a/mocap/pear/fixed_rig.py+++ b/mocap/pear/fixed_rig.py@@ -33,7 +33,7 @@ class FixedRig(SkeletonLayout):self.revision=0;self.clear()def clear(self):- self.rest=None;self.tip_offsets=None;self.basis=None+ self.rest=None;self.tip_offsets=None;self.basis=None;self.sole_offsets=Nonedef calibrate(self,body,flame):"""Publish a complete replacement only after validating the current pose's anatomy."""@@ -62,6 +62,15 @@ class FixedRig(SkeletonLayout):offsets={native:(j[tip]-rest[native]).astype('float32') for native,tip in TIPS.items()}if not np.isfinite(basis).all() or np.max(abs(basis.swapaxes(-1,-2)@basis-np.eye(3)))>1e-4:raise ValueError('Invalid bone calibration. Try Reset Bones on another frame.')+ # One neutral rigid sole proxy per foot; no skin evaluation at runtime.+ weights=self.calibrator.smplx.lbs_weights.detach().cpu().numpy()+ sole=[];up=unit(rest[3]-rest[0])+ for ankle,toe in ((7,10),(8,11)):+ patch=v[(weights[:,ankle]+weights[:,toe])>.65]+ if len(patch)<8:raise ValueError('Cannot calibrate the foot sole from this body model.')+ height=patch@up;low=patch[height<=np.percentile(height,8)]+ sole.append(np.median(low,axis=0)-rest[ankle])+ self.sole_offsets=np.asarray(sole,dtype='float32')self.rest=rest.astype('float32');self.tip_offsets=offsets;self.basis=basis;self.revision+=1def pose(self,body,camera):diff --git a/mocap/pear/foot_lock.py b/mocap/pear/foot_lock.pynew file mode 100644index 0000000..82abfd9--- /dev/null+++ b/mocap/pear/foot_lock.py@@ -0,0 +1,130 @@+"""Small causal live-foot constraint. No meshes, inference, recording or lookahead."""+import time+import numpy as np+from scipy.spatial.transform import Rotation+from .bone_roll import JOINTS,TIPS+++def unit(v):+ return v / max(float(np.linalg.norm(v)), 1e-12)+++def aim(a,b):+ a,b=unit(a),unit(b);v=np.cross(a,b);c=float(np.clip(a@b,-1,1))+ if c < -.99999:+ axis=unit(np.cross(a,np.eye(3)[np.argmin(abs(a))]));return 2*np.outer(axis,axis)-np.eye(3)+ k=np.array([[0,-v[2],v[1]],[v[2],0,-v[0]],[-v[1],v[0],0]])+ return np.eye(3)+k+k@k/max(1+c,1e-12)+++class Contact:+ def __init__(self):+ self.locked=False;self.candidate=0.;self.age=1.;self.offset=np.zeros(3);self.offset_v=np.zeros(3)+ self.anchor=None;self.position=None;self.velocity=np.zeros(3);self.input=None;self.speed=0.+ self.strength=0.;self.strength_v=0.++ def update(self,p,dt,enabled=True):+ velocity=(p-self.input)/dt if self.input is not None else np.zeros(3)+ self.input=p.copy();self.speed+=(1-np.exp(-dt/.045))*(np.linalg.norm(velocity)-self.speed)+ # Contact evidence always comes from the uncorrected input, never the lock.+ self.candidate=self.candidate+dt if enabled and -.06<p[1]<.045 and self.speed<.18 else 0.+ locked=self.locked+ if not locked and self.candidate>=.075:locked=True+ if locked and (not enabled or p[1]>.065 or self.speed>.30 or (self.anchor is not None and np.linalg.norm(p-self.anchor)>.12)):locked=False+ base=self.anchor if self.locked else p;base_v=np.zeros(3) if self.locked else velocity+ duration=.16;self.age+=dt;t=min(1.,self.age/duration)+ h0=2*t**3-3*t*t+1;h1=t**3-2*t*t+t+ value=base+h0*self.offset+h1*duration*self.offset_v+ speed=base_v+(6*t*t-6*t)/duration*self.offset+(3*t*t-4*t+1)*self.offset_v+ if locked!=self.locked:+ self.locked=locked+ if locked:self.anchor=p.copy();self.anchor[1]=0.+ base=self.anchor if locked else p;base_v=np.zeros(3) if locked else velocity+ self.offset=value-base;self.offset_v=speed-base_v;self.age=0.+ # A separate continuous activation also hands pelvis displacement back+ # to free feet; ending an IK pass must not drop that displacement.+ goal=float(locked);omega=24.;decay=np.exp(-omega*dt);x=self.strength-goal;v=self.strength_v+ self.strength=goal+(x+(v+omega*x)*dt)*decay+ self.strength_v=(v-omega*(v+omega*x)*dt)*decay+ self.position=value;self.velocity=speed+ return value+++class LiveFootLock:+ def __init__(self):self.reset()+ def reset(self):+ self.time=None;self.feet=[Contact(),Contact()];self.shift=0.;self.shift_v=0.;self.last=None;self.poles=[None,None]+ self.corrections=np.tile(np.eye(3),(2,2,1,1))++ def smooth_correction(self,side,bone,target,dt):+ previous=self.corrections[side,bone]+ error=Rotation.from_matrix([email protected]).as_rotvec()+ value=Rotation.from_rotvec(error*(1-np.exp(-dt/.05))).as_matrix()@previous+ self.corrections[side,bone]=value+ return value++ def apply(self,pose,rig,timestamp,enabled=True,move_root=True):+ started=time.perf_counter();dt=timestamp-self.time if self.time is not None else 0.+ if not enabled or rig.sole_offsets is None:+ self.reset();return pose,dict(enabled=False,ms=(time.perf_counter()-started)*1000)+ if dt==0 and self.last is not None:return self.last+ if not 0<dt<=.25:self.reset();dt=1/30+ self.time=timestamp+ source=np.asarray(pose['joints'],dtype=float);rot=np.asarray(pose['rotations'],dtype=float)+ points=np.array([source[a]+rot[a]@offset for a,offset in zip((7,8),rig.sole_offsets)])+ # High feet never become contacts, including a held pose in mid-air.+ targets=np.array([f.update(p,dt) for f,p in zip(self.feet,points)])+ reach=[];limit=0.+ for side,(hip,knee,ankle) in enumerate(((1,4,7),(2,5,8))):+ a,b,c=source[[hip,knee,ankle]];length=np.linalg.norm(b-a)+np.linalg.norm(c-b)+ maximum=min(length-1e-7,np.linalg.norm(c-a))+ reach.append(maximum)+ if self.feet[side].strength>1e-4:+ target=targets[side]-rot[ankle]@rig.sole_offsets[side]+ horizontal=np.linalg.norm((target-a)[[0,2]])+ if horizontal<maximum:limit=min(limit,(target[1]+np.sqrt(maximum**2-horizontal**2)-a[1])*self.feet[side].strength)+ goal=max(-.04,limit) if move_root else 0.+ # Critically damped, bounded pelvis compensation. It cannot oscillate.+ omega=12.;decay=np.exp(-omega*dt);x=self.shift-goal;v=self.shift_v+ self.shift=goal+(x+(v+omega*x)*dt)*decay+ self.shift_v=(v-omega*(v+omega*x)*dt)*decay+ j=source.copy();j[:,1]+=self.shift if move_root else 0.+ r=rot.copy();facing=np.asarray(pose['bone_facing'],dtype=float).copy();errors=[]+ for side,(hip,knee,ankle,toe) in enumerate(((1,4,7,10),(2,5,8,11))):+ # Fade-out targets remain active until their inertial offset expires.+ contact=self.feet[side]+ inactive=not contact.locked and contact.age>=.16 and contact.strength<1e-4+ a,b,c=j[[hip,knee,ankle]].copy();target=targets[side]-rot[ankle]@rig.sole_offsets[side]+ if move_root:target[1]+=self.shift*(1-contact.strength)+ l1,l2=np.linalg.norm(b-a),np.linalg.norm(c-b)+ if min(l1,l2)<1e-7 or reach[side]<abs(l1-l2)+1e-7 or np.linalg.norm(target-a)<1e-8:+ errors.append(float(np.linalg.norm(c-target)));continue+ axis=unit(target-a)+ distance=np.clip(np.linalg.norm(target-a),abs(l1-l2)+1e-7,reach[side])+ # Near full extension, tiny height errors otherwise become a large+ # square-root knee displacement. Retain the source bend there and+ # accept foot residual instead of manufacturing crouch/extension.+ cosine=np.clip((l1*l1+l2*l2-reach[side]**2)/(2*l1*l2),-1.,1.)+ flex=180-np.degrees(np.arccos(cosine));observable=np.clip((flex-6)/12,0.,1.)+ observable=observable*observable*(3-2*observable)+ distance=reach[side]+observable*(distance-reach[side])+ knee_side=b-a-axis*np.dot(b-a,axis)+ if np.linalg.norm(knee_side)<.001:+ knee_side=self.poles[side] if self.poles[side] is not None else pose['bone_facing'][hip,:,2]+ knee_side=knee_side-axis*np.dot(knee_side,axis)+ if np.linalg.norm(knee_side)<1e-8:knee_side=np.cross(axis,np.eye(3)[np.argmin(abs(axis))])+ pole=unit(knee_side);self.poles[side]=pole+ along=(l1*l1-l2*l2+distance*distance)/(2*distance)+ new_b=a+axis*along+pole*np.sqrt(max(0,l1*l1-along*along));new_c=a+axis*distance+ desired=(aim(b-a,new_b-a),aim(c-b,new_c-new_b)) if not inactive else (np.eye(3),np.eye(3))+ applied=[self.smooth_correction(side,k,value,dt) for k,value in enumerate(desired)]+ new_b=a+applied[0]@(b-a);new_c=new_b+applied[1]@(c-b)+ for bone,correction in zip((hip,knee),applied):+ r[bone]=correction@r[bone]+ facing[int(np.flatnonzero(JOINTS==bone)[0])]=correction@facing[int(np.flatnonzero(JOINTS==bone)[0])]+ delta=new_c-c;j[knee]=new_b;j[ankle]=new_c;j[toe]+=delta;j[TIPS[toe]]+=delta+ errors.append(float(np.linalg.norm(new_c-target)))+ result=dict(pose,joints=j.astype('float32'),rotations=r.astype('float32'),bone_facing=facing.astype('float32'))+ result['bounds']=np.ascontiguousarray(j[np.r_[JOINTS,list(TIPS.values())]],dtype='float32')+ metrics=dict(enabled=True,locked=[f.locked for f in self.feet],residual_mm=[e*1000 for e in errors],pelvis_mm=float(self.shift*1000),ms=(time.perf_counter()-started)*1000)+ self.last=(result,metrics);return self.lastdiff --git a/mocap/pear/input_transform.py b/mocap/pear/input_transform.pyindex 38ee190..d01b6f8 100644--- a/mocap/pear/input_transform.py+++ b/mocap/pear/input_transform.py@@ -2,6 +2,15 @@import mathimport cv2+def input_rotations(request,count):+ """Normalize per-input angles; retain scalar compatibility for old requests."""+ values=request.get('rotations')+ if values is None:values=[request.get('rotation',0.)]*count+ if not isinstance(values,(list,tuple)) or len(values)!=count:raise ValueError('Each input needs its own rotation value')+ values=tuple(float(v) for v in values)+ if not all(math.isfinite(v) and -360<=v<=360 for v in values):raise ValueError('Input rotation must be finite and between −360 and 360 degrees')+ return values+def rotate_frame(frame, clockwise_degrees):angle=float(clockwise_degrees)if not math.isfinite(angle):raise ValueError('Input rotation must be finite')diff --git a/mocap/pear/multi_worker.py b/mocap/pear/multi_worker.pynew file mode 100644index 0000000..2b64ebc--- /dev/null+++ b/mocap/pear/multi_worker.py@@ -0,0 +1,237 @@+"""Resident multiview inputs; bounded capture buffers, parallel CPU decode/crops."""+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+import json,time,uuid,re,shutil,zipfile+import numpy as np+from .input_transform import rotate_frame,input_rotations+from .multiview import Fusion,observations,local_matrices,fk,CV+from .projection import Placement+from .fixed_rig import CalibrationFrames+from .temporal_filter import ParameterFilter+from ..paths import ROOT+from ..storage import atomic_json,sha256++def owned_folder(path):+ p=Path(path).resolve();root=(ROOT/'cache/pear/alignment').resolve()+ if not p.is_relative_to(root) or p==root:raise ValueError('Invalid PEAR alignment cache path')+ return p++def write_sample(path,image,cv):+ ok,encoded=cv.imencode('.png',image)+ if not ok:raise OSError('Cannot encode camera alignment sample')+ Path(path).write_bytes(encoded.tobytes())++def read_parameters(path):+ if path.stat().st_size>2*1024**2:raise ValueError('Alignment parameter file is too large')+ with zipfile.ZipFile(path) as z:+ entries=z.infolist()+ if len(entries)>64 or sum(p.file_size for p in entries)>2*1024**2:raise ValueError('Invalid alignment parameter archive')+ with np.load(path,allow_pickle=False) as z:return {k:z[k].copy() for k in z.files}++def prune_samples(keep=None):+ """At most four private jobs; never follow links or delete non-job paths."""+ root=ROOT/'cache/pear/alignment';root.mkdir(parents=True,exist_ok=True)+ jobs=[p for p in root.iterdir() if p.is_dir() and re.fullmatch(r'[0-9a-f]{32}',p.name) and not p.is_symlink() and not (getattr(p.lstat(),'st_file_attributes',0)&0x400)]+ ordered=sorted(jobs,key=lambda p:p.stat().st_mtime,reverse=True)+ retained=ordered[:3]+ protected=next((p for p in ordered if keep and p.resolve()==Path(keep).resolve()),None)+ if protected is not None and protected not in retained:retained=retained[:2]+[protected]+ for p in ordered:+ if p not in retained:owned_folder(p);shutil.rmtree(p)++class Inputs:+ def __init__(self,sources,mode,height,pool,cv,streams=None):+ self.sources=sources;self.mode=mode;self.pool=pool;self.cv=cv;self.caps=[];self.last=[None]*len(sources)+ try:+ if streams is not None and len(streams)!=len(sources):raise ValueError('Shared camera count changed')+ for i,s in enumerate(sources):+ if mode=='camera':+ from .camera_stream import open_camera+ cap=open_camera(s,height,cv,streams[i] if streams is not None else None)+ else:+ cap=cv.VideoCapture(s['path'],cv.CAP_FFMPEG,[cv.CAP_PROP_N_THREADS,1,cv.CAP_PROP_OPEN_TIMEOUT_MSEC,2000,cv.CAP_PROP_READ_TIMEOUT_MSEC,2000])+ if not cap.isOpened():cap.release();raise ValueError('Cannot open camera video: '+Path(s['path']).name)+ self.caps.append(cap)+ except Exception:self.close();raise+ def read(self,timestamp,rotation):+ angles=input_rotations({'rotations':rotation},len(self.caps)) if isinstance(rotation,(list,tuple)) else input_rotations({'rotation':rotation},len(self.caps))+ def one(i):+ cap=self.caps[i]+ if self.mode=='camera':+ item=cap.take()+ return None if item is None else (rotate_frame(item[0],angles[i]),item[1])+ fps=float(cap.get(self.cv.CAP_PROP_FPS))+ if not np.isfinite(fps) or fps<=0:raise ValueError('Camera video has invalid timing')+ index=round(timestamp*fps);last=self.last[i]+ if last is None or not last<index<=last+8:cap.set(self.cv.CAP_PROP_POS_FRAMES,index)+ else:+ for _ in range(index-last-1):cap.grab()+ ok,im=cap.read();self.last[i]=index+ if not ok:raise ValueError('Cannot decode camera '+str(i+1)+' at this time.')+ return rotate_frame(im,angles[i]),index/max(fps,1.)+ items=list(self.pool.map(one,range(len(self.caps))))+ if any(v is None for v in items):return None+ if self.mode=='camera':+ # Arrival-time synchronization is approximate: no claim of hardware genlock.+ times=[v[1] for v in items]+ if max(times)-min(times)>.08:return None+ return [v[0] for v in items],float(np.mean([v[1] for v in items]))+ def close(self):+ errors=[]+ for cap in self.caps:+ try:cap.close() if self.mode=='camera' else cap.release()+ except Exception as e:errors.append(e)+ self.caps=[]+ if errors:raise errors[0]++class MultiPreview:+ def __init__(self,model,cv,send):+ from .batch import BatchRunner+ self.pool=ThreadPoolExecutor(4,thread_name_prefix='pear-cameras');self.batch=BatchRunner(model,self.pool)+ self.model=model;self.cv=cv;self.send=send;self.inputs=None;self.key=None;self.fusion=None;self.align_key=None;self.calibration_sizes=None+ from .foot_lock import LiveFootLock+ self.foot_lock=LiveFootLock();self.lock_options=None;self.position_anchor=None+ self.placement=Placement();self.filter=ParameterFilter();self.last_time=None;self.last_generation=None;self.pose_id=0;self.reference=None;self.reset_handled=0;self.references=CalibrationFrames()+ def close(self):+ try:+ if self.inputs:self.inputs.close();self.inputs=None+ finally:self.pool.shutdown(wait=True,cancel_futures=True)+ def configure(self,request):+ sources=request['sources'];mode=request['mode']+ if not 1<=len(sources)<=32:raise ValueError('PEAR needs 1–32 input slots.')+ if mode=='video':+ for entry in sources:+ st=Path(entry['path']).stat()+ if entry.get('file_stamp') and entry['file_stamp']!=[st.st_size,st.st_mtime_ns]:raise ValueError('A camera video changed. Open the videos again before tracking.')+ self.rotations=input_rotations(request,len(sources))+ key=json.dumps([mode,sources,request['resolution'],self.rotations,request.get('camera_streams')],sort_keys=True)+ if key!=self.key:+ if self.inputs:self.inputs.close();self.inputs=None+ self.inputs=Inputs(sources,mode,request['resolution'],self.pool,self.cv,request.get('camera_streams'));self.key=key+ self.batch.reset(len(sources));self.model.rig.clear();self.fusion=None;self.align_key=None+ self.filter.reset();self.placement.reset();self.last_time=None;self.reference=None;self.references.clear();self.reset_handled=int(request.get('bone_reset',0))+ calibration=request.get('calibration')+ if calibration!=self.align_key:+ self.fusion=None;self.align_key=None;self.calibration_sizes=None+ if calibration:+ folder=owned_folder(calibration);data=json.loads((folder/'cameras.json').read_text('utf8'))+ if data['signature']!=request['signature'] or len(data['intrinsics'])!=len(sources):raise ValueError('Camera alignment no longer matches these inputs.')+ if data.get('rig_sha256')!=sha256(folder/'rig.npz'):raise ValueError('Camera alignment rig changed. Run Camera Align again.')+ z=read_parameters(folder/'rig.npz')+ body={k[5:]:v for k,v in z.items() if k.startswith('body_')}+ flame={k[6:]:v for k,v in z.items() if k.startswith('flame_')}+ self.send({'type':'status','text':'Restoring aligned fixed-rig calibration…','generation':request['generation']})+ self.model.rig.calibrate(body,flame);self.reference=(body,flame)+ self.fusion=Fusion(self.model.rig,data);self.align_key=calibration;self.calibration_sizes=data['sizes']+ def thumbnails(self,images):+ out=[]+ for im in images:+ h,w=im.shape[:2];s=min(128/w,72/h);thumb=np.zeros((72,128,3),np.uint8)+ small=self.cv.resize(im,(max(1,round(w*s)),max(1,round(h*s))))+ thumb[:small.shape[0],:small.shape[1]]=small[...,::-1];out.append(thumb)+ return np.stack(out)+ def prepare_alignment(self,request,images,packets,timestamp):+ prune_samples(request.get('calibration'))+ folder=ROOT/'cache/pear/alignment'/uuid.uuid4().hex;folder.mkdir(parents=True)+ n=len(images);samples=[];uv=[];boxes=[];sizes=[];paths=[];camera_relative=[]+ for sample in range(2):+ if sample:+ if request['mode']=='camera':+ until=time.monotonic()+1.;fresh=None+ while time.monotonic()<until:+ item=self.inputs.read(timestamp,self.rotations)+ if item:fresh=item+ if fresh is None:raise ValueError('Webcams did not deliver synchronized fresh samples. Check connections.')+ images,_=fresh;packets=self.batch.run(images)+ else:+ end=float(request.get('duration',timestamp+2))-1/float(request.get('fps',30))+ next_time=min(timestamp+2,end)+ if next_time<=timestamp:raise ValueError('Leave at least two video frames after the playhead for Camera Align.')+ images,_=self.inputs.read(next_time,self.rotations);packets=self.batch.run(images)+ if sum(p is not None for p in packets)<min(2,n):raise ValueError('Camera Align needs the same person visible in the selected views. Choose another time.')+ obs=np.full((n,145,2),np.nan);bb=np.full((n,4),np.nan);relative=np.full((n,55,3),np.nan)+ for c,(im,p) in enumerate(zip(images,packets)):+ path=folder/f'sample-{sample}-{c}.png'+ # Limit calibration source pixels; intrinsics are returned in original dimensions.+ h,w=im.shape[:2];scale=min(1.,1920/w,1080/h);small=self.cv.resize(im,(round(w*scale),round(h*scale))) if scale<1 else im+ write_sample(path,small,self.cv)+ paths.append(path.name)+ if p is not None:+ obs[c]=observations(p,self.model.rig);bb[c]=p['bbox']+ local,_=fk(local_matrices(p['body']),self.model.rig)+ relative[c]=local[:55]@(CV@p['camera'][:3,:3]).T+ if sample==0:sizes.append([w,h])+ elif sizes[c]!=[w,h]:raise ValueError('Camera dimensions changed during alignment.')+ uv.append(obs);boxes.append(bb);camera_relative.append(relative)+ body,flame=self.reference+ np.savez(folder/'rig.npz',**{'body_'+k:v for k,v in body.items()},**{'flame_'+k:v for k,v in flame.items()})+ np.savez(folder/'observations.npz',uv=np.asarray(uv),boxes=np.asarray(boxes),sizes=np.asarray(sizes),rest=self.model.rig.rest,camera_relative=np.asarray(camera_relative))+ atomic_json(folder/'job.json',dict(version=1,signature=request['signature'],images=paths,count=n,+ rig_sha256=sha256(folder/'rig.npz'),observations_sha256=sha256(folder/'observations.npz')))+ self.send({'type':'alignment','phase':'prepared','folder':str(folder),'generation':request['generation']})+ def process(self,request):+ started=time.perf_counter();self.configure(request)+ timestamp=float(request.get('timeline_frame',0))/float(request.get('fps',30))+ item=self.inputs.read(timestamp,self.rotations)+ if item is None:+ if self.inputs.mode=='camera':self.send({'type':'status','text':'Waiting for synchronized camera frames (arrival skew ≤80 ms)…','generation':request['generation']})+ return+ images,source_time=item+ if self.fusion and [list(im.shape[1::-1]) for im in images]!=self.calibration_sizes:raise ValueError('Camera image dimensions changed. Run Camera Align again.')+ if request['mode']=='camera':timestamp=source_time+ continuous=self.last_time is not None and 0<timestamp-self.last_time<=.25 and self.last_generation==request['generation']+ if not continuous:+ self.filter.reset();self.placement.reset_filter();self.foot_lock.reset();self.position_anchor=None+ if self.fusion:self.fusion.reset()+ if self.last_time!=timestamp:self.batch.reset(len(images))+ self.last_time=timestamp;self.last_generation=request['generation']+ packets=self.batch.run(images);rig=self.model.rig+ available=[p for p in packets if p is not None]+ if rig.rest is None and available:+ rig.calibrate(available[0]['body'],available[0]['flame']);self.reference=(available[0]['body'],available[0]['flame'])+ if request.get('align_job'):+ if not available:raise ValueError('No person visible for Camera Align.')+ self.prepare_alignment(request,images,packets,timestamp);return 'prepared'+ reset=int(request.get('bone_reset',0))+ if reset>self.reset_handled:+ # UI invalidates camera calibration before allowing a new body scale.+ self.reset_handled=reset+ reference=self.references.get(request.get('reset_pose'))+ if reference is None:raise ValueError('Reset Bones: displayed pose expired. Pause and try again.')+ rig.calibrate(*reference);self.reference=reference;self.filter.reset();self.placement.reset_filter()+ selected=int(request.get('preview',0));selected=max(0,min(selected,len(images)-1));arrays={}+ smooth_rotations=bool(request['smoothing'] and request.get('smooth_rotations',True))+ smooth_position=bool(request['smoothing'] and request.get('smooth_position',True))+ if self.fusion:arrays=self.fusion.run(packets,timestamp,request['smoothing'],request['smoothing_strength'],+ smooth_rotations=request.get('smooth_rotations',True),smooth_position=request.get('smooth_position',True)) or {}+ elif packets[selected] is not None:+ p=packets[selected];body=p['body'];self.filter.set_strength(request['smoothing_strength'])+ if smooth_rotations:body,_=self.filter.update(body,p['flame'],timestamp)+ else:self.filter.reset()+ v,j,r,f=rig.pose(body,p['camera']);v,j=self.placement.points(v,j,p['camera'],p['crop_bbox'],p['image_size'],smooth_position,timestamp,strength=request['smoothing_strength'])+ arrays=dict(bounds=np.ascontiguousarray(v[:,[0,2,1]]*[1,1,-1],dtype='float32'),joints=np.ascontiguousarray(j[:,[0,2,1]]*[1,1,-1],dtype='float32'),rotations=r,bone_facing=f)+ foot_metrics={}+ options=(request.get('foot_lock',True),request.get('world_position',True),rig.revision,self.align_key)+ if options!=self.lock_options:self.foot_lock.reset();self.position_anchor=None;self.lock_options=options+ if arrays:+ if not request.get('world_position',True):+ from .projection import lock_position+ anchor=request.get('position_anchor')+ if anchor is not None:self.position_anchor=np.asarray(anchor,dtype='float32')+ if self.position_anchor is None:self.position_anchor=arrays['joints'][0].copy()+ arrays=lock_position(arrays,self.position_anchor)+ arrays,foot_metrics=self.foot_lock.apply(arrays,rig,timestamp,+ enabled=bool(request.get('foot_lock',True) and self.fusion is not None),move_root=request.get('world_position',True))+ else:self.foot_lock.reset()+ valid=bool(arrays);self.pose_id+=1+ reference_packet=packets[selected] or (available[0] if available else None)+ if reference_packet:self.references.remember(self.pose_id,reference_packet['body'],reference_packet['flame'])+ im=images[selected];h,w=im.shape[:2];s=min(1,1280/w,720/h)+ if s<1:im=self.cv.resize(im,(round(w*s),round(h*s)))+ arrays['image']=np.ascontiguousarray(im[...,::-1]);arrays['thumbnails']=self.thumbnails(images)+ self.send(dict(type='frame' if valid else 'missing',generation=request['generation'],request=request['request'],mode=request['mode'],+ preview=selected,frame=self.pose_id if request['mode']=='camera' else request.get('timeline_frame',0),timeline_frame=request.get('timeline_frame',0),pair_video=request.get('pair_video',False),+ requested_at=request.get('requested_at',time.monotonic()),render_mode='bones',pose_id=self.pose_id,bone_revision=rig.revision,+ bone_reset_handled=self.reset_handled,ms=(time.perf_counter()-started)*1000,views=len(images),available_views=len(available),+ aligned=self.fusion is not None,smooth_rotations=smooth_rotations,smooth_position=smooth_position,+ foot_lock=foot_metrics,text='' if valid else 'No person visible in the selected inputs.'),**arrays)diff --git a/mocap/pear/multiview.py b/mocap/pear/multiview.pynew file mode 100644index 0000000..f2f708b--- /dev/null+++ b/mocap/pear/multiview.py@@ -0,0 +1,89 @@+"""Fixed-rig, causal multiview fusion. No mesh solve or per-frame calibration."""+import numpy as np+from scipy.spatial.transform import Rotation+from .bone_roll import JOINTS,TIPS+from .temporal_filter import ParameterFilter,AdaptiveFilter,strength_scale++CV=np.diag([-1.,-1.,1.])+DISPLAY=np.array([[1.,0,0],[0,0,1.],[0,-1.,0]])+BODY_IDS=np.array([16,17,18,19,20,21,1,2,4,5,7,8])++def local_matrices(body):+ return np.concatenate([body['global_pose'].reshape(1,3,3),body['body_pose'].reshape(21,3,3),+ np.tile(np.eye(3),(3,1,1)),body['left_hand_pose'].reshape(15,3,3),body['right_hand_pose'].reshape(15,3,3)])++def fk(local,rig):+ rotations=local.copy();joints=np.zeros((145,3));rest=rig.rest+ for k in range(1,55):+ p=int(rig.native_parents[k]);rotations[k]=rotations[p]@local[k]+ joints[k]=joints[p]+rotations[p]@(rest[k]-rest[p])+ for k,offset in rig.tip_offsets.items():joints[TIPS[k]]=joints[k]+rotations[k]@offset+ return joints,rotations++def observations(packet,rig):+ joints,_=fk(local_matrices(packet['body']),rig);joints+=rig.rest[0]+ cam=packet['camera'];q=joints@cam[:3,:3].T+cam[:3,3];crop=packet['crop_bbox']+ if np.any(q[:55,2]<=.01):raise ValueError('Invalid PEAR crop-camera depth')+ return crop[:2]+crop[2:]/2-12*crop[2:]*q[:,:2]/q[:,2:]++class Fusion:+ def __init__(self,rig,cameras):+ self.rig=rig;self.K=np.asarray(cameras['intrinsics']);self.E=np.asarray(cameras['extrinsics'])+ n=len(self.K)+ if self.K.shape!=(n,3,3) or self.E.shape!=(n,3,4) or not 1<=n<=32 or not np.isfinite(self.K).all() or not np.isfinite(self.E).all():raise ValueError('Invalid camera alignment arrays')+ rr=self.E[:,:,:3]+ if np.any(self.K[:,[0,1],[0,1]]<=0) or np.max(abs(rr.swapaxes(-1,-2)@rr-np.eye(3)))>1e-4 or np.min(np.linalg.det(rr))<.999:raise ValueError('Invalid camera alignment rotations or intrinsics')+ [email protected];self.children=[np.flatnonzero(rig.native_parents==i) for i in range(55)]+ self.filter=ParameterFilter();self.root_filter=AdaptiveFilter(1.2,4.,vector=True);self.reset()+ def reset(self):+ self.filter.reset();self.root_filter.reset();self.weights=None;self.time=None+ def quality(self,c,j,uv,packet):+ q=np.empty(55);rr=self.E[c,:,:3];box=packet['bbox'];size=packet['image_size']+ scale=np.clip(np.sqrt(max(box[3]-box[1],1)/420),.45,1.5)+ cam=j[:55]@rr.T;torso=(uv[3]+uv[9])/2;radius=max(12,np.linalg.norm(uv[16]-uv[17])*.38)+ for k in range(55):+ child=self.children[k];delta=j[child].mean(0)-j[k] if len(child) else j[k]-j[max(0,int(self.rig.native_parents[k]))]+ d=rr@delta;observable=np.sqrt(max(0.,1-(d[2]/max(np.linalg.norm(d),1e-6))**2))+ inside=np.clip(np.minimum(np.minimum(uv[k],size-uv[k]),40).min()/40,.05,1.)+ occluded=k in (18,19,20,21,4,5,7,8) and np.linalg.norm(uv[k]-torso)<radius and cam[k,2]>cam[9,2]+.08+ q[k]=scale*(.15+.85*observable)*inside*(.25 if occluded else 1.)+ q[25:40]=q[20];q[40:55]=q[21]+ return q+ def run(self,packets,timestamp,smoothing=True,strength=50,smooth_rotations=True,smooth_position=True):+ available=[i for i,p in enumerate(packets) if p is not None]+ if not available:self.reset();return None+ obs={};quality=np.zeros((len(packets),55));locals=[]+ for c in available:+ p=packets[c];L=local_matrices(p['body']);obs[c]=observations(p,self.rig)+ L[0]=self.E[c,:,:3].T@CV@p['camera'][:3,:3]@L[0]+ j,_=fk(L,self.rig);locals.append(L);quality[c]=self.quality(c,j,obs[c],p)+ weights=quality/np.maximum(quality.sum(0),1e-8);dt=0 if self.time is None else timestamp-self.time+ if self.weights is not None and 0<dt<=.25:weights=self.weights+(1-np.exp(-dt/.1))*(weights-self.weights)+ weights[[i for i in range(len(packets)) if i not in available]]=0+ weights/=np.maximum(weights.sum(0),1e-8);self.weights=weights;self.time=timestamp+ L=locals[0].copy();A=np.asarray(locals)+ for _ in range(3):+ delta=Rotation.from_matrix((L.swapaxes(-1,-2)[None]@A).reshape(-1,3,3)).as_rotvec().reshape(len(available),55,3)+ [email protected]_rotvec((weights[available,:,None]*delta).sum(0)).as_matrix()+ if smoothing and smooth_rotations:+ self.filter.set_strength(strength)+ b=dict(global_pose=L[:1][None],body_pose=L[1:22][None],left_hand_pose=L[25:40][None],right_hand_pose=L[40:55][None])+ b,_=self.filter.update(b,{},timestamp);L=local_matrices(b)+ else:self.filter.reset()+ j,r=fk(L,self.rig);aa=[];bb=[]+ for c in available:+ for k in BODY_IDS:+ u,v=obs[c][k];p=self.P[c];mat=np.stack([p[0,:3]-u*p[2,:3],p[1,:3]-v*p[2,:3]])+ w=np.sqrt(max(.02,quality[c,k]));aa.append(mat*w)+ bb.append((-mat@j[k]-[p[0,3]-u*p[2,3],p[1,3]-v*p[2,3]])*w)+ a=np.concatenate(aa);b=np.concatenate(bb);root,_,rank,_=np.linalg.lstsq(a,b,rcond=None)+ if rank<3 or not np.isfinite(root).all() or np.linalg.norm(root)>1000:raise ValueError('Camera geometry cannot determine a stable position. Run Camera Align again.')+ if smoothing and smooth_position:+ scale=strength_scale(strength);self.root_filter.min_cutoff=1.2/scale;self.root_filter.beta=4/scale;self.root_filter.max_cutoff=8/scale+ root=self.root_filter.update(root,dt)+ else:self.root_filter.reset()+ j+=root+ return dict(joints=np.ascontiguousarray([email protected],dtype='float32'),+ bounds=np.ascontiguousarray(j[np.r_[JOINTS,list(TIPS.values())]]@DISPLAY.T,dtype='float32'),+ rotations=np.ascontiguousarray(DISPLAY@r,dtype='float32'),+ bone_facing=np.ascontiguousarray(DISPLAY@(r[JOINTS]@self.rig.basis),dtype='float32'))diff --git a/mocap/pear/session.py b/mocap/pear/session.pyindex ea0de85..99d51cf 100644--- a/mocap/pear/session.py+++ b/mocap/pear/session.py@@ -5,7 +5,7 @@ from ..paths import ROOT,worker_commandfrom .wire import receiveclass Session:- def __init__(self):+ def __init__(self,stage="pear_live"):self.lock=threading.Condition();self.latest=None;self.command=None;self.closed=False;self.topology=Nonefolder=ROOT/'cache/pear/sessions';folder.mkdir(parents=True,exist_ok=True)# One bounded log per session; retain only the most recent eight sessions.@@ -14,7 +14,7 @@ class Session:except OSError:passself.log=folder/(uuid.uuid4().hex+'.log')log=self.log.open('wb');env=os.environ.copy();env['PYTHONDONTWRITEBYTECODE']='1';env['PYTHONUNBUFFERED']='1'- try:self.process=subprocess.Popen(worker_command('pear_live'),cwd=ROOT,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ try:self.process=subprocess.Popen(worker_command(stage),cwd=ROOT,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))finally:log.close()from ..processing_guard import ProcessingGuardself.guard=ProcessingGuard(self.process.pid)@@ -29,7 +29,7 @@ class Session:else:self.latest=(meta,arrays)except Exception as exc:with self.lock:- if not self.closed and not (self.latest and self.latest[0]['type']=='error'):+ if not self.closed and not (self.latest and self.latest[0]['type'] in ('error','alignment')):self.latest=({'type':'error','text':'PEAR worker stopped. See '+str(self.log)}, {})finally:self.process.stdout.close()def write(self):diff --git a/mocap/pear/single_alignment.py b/mocap/pear/single_alignment.pynew file mode 100644index 0000000..b3fb051--- /dev/null+++ b/mocap/pear/single_alignment.py@@ -0,0 +1,36 @@+"""Single-view scale estimate, not a triangulation or measured camera baseline."""+import numpy as np+from .multiview import BODY_IDS+++def metric_scale(samples,K,depth,confidence):+ relatives=samples.get('camera_relative')+ if relatives is None or relatives.shape!=(2,1,55,3):raise ValueError('Single-camera samples need a new Camera Align.')+ ratios=[]+ for s in range(2):+ uv=samples['uv'][s,0,BODY_IDS];j=relatives[s,0,BODY_IDS]+ if not np.isfinite(uv).all() or not np.isfinite(j).all():continue+ rays=np.c_[uv,np.ones(len(uv))]@np.linalg.inv(K).T+ A=np.zeros((len(j),2,3));A[:,0,0]=1;A[:,1,1]=1;A[:,:,2]=-rays[:,:2]+ b=rays[:,:2]*j[:,2,None]-j[:,:2]+ translation,_,rank,_=np.linalg.lstsq(A.reshape(-1,3),b.reshape(-1),rcond=None)+ if rank!=3 or translation[2]<=.1:continue+ predicted=j+translation+ [email protected];reprojection=reprojection[:,:2]/reprojection[:,2,None]+ if np.percentile(np.linalg.norm(reprojection-uv,axis=1),95)>max(samples['sizes'][0])*.02:continue+ h,w=depth[s].shape;size=samples['sizes'][0]+ pixels=np.rint(uv*np.array([w,h])/size).astype(int)+ valid=(pixels[:,0]>=0)&(pixels[:,0]<w)&(pixels[:,1]>=0)&(pixels[:,1]<h)+ pixels=pixels[valid];metric=predicted[valid,2]+ d=depth[s,pixels[:,1],pixels[:,0]];c=confidence[s,pixels[:,1],pixels[:,0]]+ good=np.isfinite(d)&(d>1e-5)&(metric>.1)&np.isfinite(c)+ if np.count_nonzero(good)<6:continue+ # VGGT confidence varies with scene content. Easy walls/floors must not+ # disqualify every person sample; rank only the depth evidence used here.+ good&=c>np.percentile(c[good],20)+ ratio=metric[good]/d[good]+ if len(ratio)>=6:ratios.extend(ratio)+ if len(ratios)<12:raise ValueError('Single-camera scale has insufficient valid person-depth samples. Try another calibration time or add a camera.')+ ratios=np.asarray(ratios);median=np.median(ratios)+ if np.percentile(abs(ratios-median),90)>median*.45:raise ValueError('Single-camera depth scale is inconsistent. Choose a clearer calibration time.')+ return ratios.tolist()diff --git a/mocap/pear/temporal_filter.py b/mocap/pear/temporal_filter.pyindex d9ec8b6..c40ec60 100644--- a/mocap/pear/temporal_filter.py+++ b/mocap/pear/temporal_filter.py@@ -22,6 +22,9 @@ class AdaptiveFilter:def reset(self):self.raw=None;self.value=None;self.derivative=Nonedef update(self,value,dt):x=np.asarray(value,dtype=np.float64)+ # A paused frame/control refresh has no elapsed source time. Retain the+ # unaffected channel instead of reseeding it from an unsmoothed sample.+ if self.raw is not None and dt==0 and self.raw.shape==x.shape:return self.value.astype(np.float32)if self.raw is None or not 0<dt<=.25 or self.raw.shape!=x.shape:self.raw=x.copy();self.value=x.copy()self.derivative=np.zeros(x.shape[:-2]+(3,)) if self.rotation else np.zeros_like(x)@@ -63,7 +66,7 @@ class ParameterFilter:if axis_angle:x=Rotation.from_rotvec(x.reshape(-1,3)).as_matrix()entries.append((prefix,key,x,original,axis_angle,x.shape[-2:]==(3,3)))schema=tuple((p,k,x.shape,shape,aa,rot) for p,k,x,shape,aa,rot in entries)- if not 0<dt<=.25 or schema!=self.schema:self.filters={};dt=0.+ if not 0<=dt<=.25 or schema!=self.schema:self.filters={};dt=0.self.last_time=timestamp;self.schema=schemaresult={'body':{},'flame':{}}for rotation in (True,False):diff --git a/mocap/pear/wire.py b/mocap/pear/wire.pyindex 9a405e0..58086e0 100644--- a/mocap/pear/wire.py+++ b/mocap/pear/wire.py@@ -38,7 +38,7 @@ def receive(stream):if a.dtype.kind=='f' and not np.isfinite(a).all():raise ValueError('Nonfinite live array')arrays[key]=akind=meta.get('type') if isinstance(meta,dict) else None- if kind not in ('status','topology','frame','missing','error'):raise ValueError('Unknown live packet')+ if kind not in ('status','topology','frame','missing','error','alignment','camera_preview'):raise ValueError('Unknown live packet')if kind=='topology':p=arrays['parents']if p.dtype!=np.int32 or p.shape!=(55,) or p[0]!=-1 or np.any(p[1:]<0) or np.any(p[1:]>=np.arange(1,55)):raise ValueError('Invalid PEAR hierarchy')@@ -65,6 +65,9 @@ def receive(stream):r=arrays['bone_facing']if r.dtype!=np.float32 or r.shape!=(52,3,3) or np.max(abs(r.swapaxes(-1,-2)@r-np.eye(3)))>.005 or np.linalg.det(r).min()<.99:raise ValueError('Invalid live bone facing')+ if 'thumbnails' in arrays:+ a=arrays['thumbnails']+ if a.dtype!=np.uint8 or a.ndim!=4 or not 1<=len(a)<=32 or a.shape[1:]!=(72,128,3):raise ValueError('Invalid camera thumbnails')if 'image' in arrays:a=arrays['image']if a.dtype!=np.uint8 or a.ndim!=3 or a.shape[2]!=3 or not 0<a.shape[0]<=720 or not 0<a.shape[1]<=1280:raise ValueError('Invalid camera image')diff --git a/mocap/pear/worker.py b/mocap/pear/worker.pyindex a59a1ae..fe02b1f 100644--- a/mocap/pear/worker.py+++ b/mocap/pear/worker.py@@ -2,6 +2,8 @@import sys,threading,json,time,tracebackdef main():+ import os+ for key in ('OMP_NUM_THREADS','MKL_NUM_THREADS','OPENBLAS_NUM_THREADS'):os.environ.setdefault(key,'4')pipe=sys.stdout.buffersys.stdout=sys.stderrimport faulthandler@@ -20,7 +22,7 @@ def main():state['value']=value;state['serial']+=1;condition.notify_all()finally:with condition:state['stop']=True;condition.notify_all()- cap=None;camera=None+ cap=None;camera=None;multi=Nonedef release_inputs():nonlocal cap,cameracurrent=camera;camera=None@@ -31,9 +33,10 @@ def main():try:send(pipe,{'type':'status','text':'Loading PEAR models…'})from .core import Pear,cv2,np,torch+ cv2.setNumThreads(2)from .projection import Placementfrom .temporal_filter import ParameterFilter- from .input_transform import rotate_frame+ from .input_transform import rotate_frame,input_rotationsif not torch.cuda.is_available():raise RuntimeError('PEAR requires a compatible NVIDIA GPU.')from ..compute_policy import gpu_reservefree,total=torch.cuda.mem_get_info()@@ -56,22 +59,50 @@ def main():seen=-1;source=None;last_index=None;last_options=None;last_epoch=None;last_playing=False;frame_number=0while True:with condition:- while not state['stop'] and (state['value'] is None or (state['serial']==seen and camera is None)):+ while not state['stop'] and (state['value'] is None or (state['serial']==seen and camera is None and not (multi and multi.inputs and multi.inputs.mode=='camera'))):condition.wait(.25)if state['stop']:breakrequest=dict(state['value']);seen=state['serial']mode=request.get('mode','video');generation=int(request['generation'])- options=(float(request.get('rotation',0)),bool(request.get('smoothing',True)))+ if len(request.get('sources',[]))>1 or request.get('align_job') or request.get('calibration'):+ if multi is None:+ release_inputs()+ from .multi_worker import MultiPreview+ send(pipe,{'type':'status','text':'Preparing bounded multi-camera inference…','generation':generation})+ multi=MultiPreview(model,cv2,lambda meta,**a:send(pipe,meta,**a))+ try:+ prepared=multi.process(request)=='prepared'+ except (ValueError,OSError) as exc:+ send(pipe,{'type':'error','recoverable':True,'text':str(exc),'generation':generation,'request':request['request']})+ prepared=False+ if prepared:+ # Preserve the prepared event until the GUI closes this worker.+ with condition:+ while not state['stop']:condition.wait(.2)+ break+ continue+ if multi is not None:+ multi.close();multi=None+ # The batched path owns the full network graph; use its eager+ # original after switching back, rather than an obsolete encoder graph.+ model.model.config=dict(model.model.config,graph=False)+ source=None+ angles=input_rotations(request,0 if mode=='idle' else 1)+ smoothing=bool(request.get('smoothing',True))+ options=(angles[0] if angles else 0.,smoothing and bool(request.get('smooth_rotations',True)),+ smoothing and bool(request.get('smooth_position',True)))strength=float(request.get('smoothing_strength',50.))if strength!=smooth.strength:smooth.set_strength(strength)- desired=(mode,request.get('camera'),request.get('path'),request.get('resolution'),request.get('restart',0))+ desired=(mode,request.get('camera'),request.get('path'),request.get('resolution'),request.get('restart',0),request.get('camera_streams'))if desired!=source:release_inputs()- model.previous=None;placement.reset();smooth.reset();rig.clear();references.clear();reset_warning='';calibration_pose=None;last_index=None;last_epoch=None;source=desired+ model.previous=None;placement.reset();smooth.reset();rig.clear();references.clear();reset_warning='';calibration_pose=None;last_index=None;last_epoch=None;source=desired;reset_handled=int(request.get('bone_reset',0))try:if mode=='camera':send(pipe,{'type':'status','text':'Opening camera…','generation':generation})- camera=LatestCamera(request['camera'],request.get('resolution',720),cv2)+ from .camera_stream import open_camera+ streams=request.get('camera_streams')+ camera=open_camera(request['camera'],request.get('resolution',720),cv2,streams[0] if streams else None)elif mode=='video' and request.get('path'):cap=cv2.VideoCapture(request['path'])if not cap.isOpened():raise RuntimeError('Cannot open the selected video.')@@ -82,9 +113,11 @@ def main():send(pipe,{'type':'status','idle':True,'text':'PEAR ready · Open a video or select a webcam.','generation':generation,'request':request['request']});continueif options!=last_options:if last_options is None or options[0]!=last_options[0]:- model.previous=None;placement.reset();references.clear()- else:placement.reset_filter()- smooth.reset();last_options=options+ model.previous=None;placement.reset();references.clear();smooth.reset()+ else:+ if options[1]!=last_options[1]:smooth.reset()+ if options[2]!=last_options[2]:placement.reset_filter()+ last_options=optionsreset_id=int(request.get('bone_reset',0))if reset_id>reset_handled:reset_handled=reset_id;reset_warning=''@@ -126,7 +159,8 @@ def main():result=model.run(image,parameter_filter=smooth if options[1] else None,timestamp=timestamp)meta={'type':'frame' if result else 'missing','generation':generation,'request':request['request'],'frame':index,'mode':mode,'pair_video':bool(request.get('pair_video')),'timeline_frame':request.get('timeline_frame',index),'requested_at':request.get('requested_at',time.monotonic()),'timestamp':timestamp,- 'smoothing':options[1],'smoothing_strength':strength,'rotation':options[0],'context_frames':0,'inference_frames':1}+ 'smoothing':smoothing,'smooth_rotations':options[1],'smooth_position':options[2],+ 'smoothing_strength':strength,'rotation':options[0],'context_frames':0,'inference_frames':1}arrays={}if result:pose_id+=1@@ -134,7 +168,7 @@ def main():send(pipe,{'type':'status','text':'Calibrating fixed bone lengths…','generation':generation})rig.calibrate(result['body'],result['flame']);calibration_pose=pose_idv,j,rot,facing=rig.pose(result['body'],result['camera'])- v,j=placement.points(v,j,result['camera'],result['crop_bbox'],result['image_size'],smoothing=options[1],timestamp=timestamp,strength=strength)+ v,j=placement.points(v,j,result['camera'],result['crop_bbox'],result['image_size'],smoothing=options[2],timestamp=timestamp,strength=strength)arrays.update(bounds=np.ascontiguousarray(v[:,[0,2,1]]*[1,1,-1],dtype='float32'),joints=np.ascontiguousarray(j[:,[0,2,1]]*[1,1,-1],dtype='float32'),rotations=rot,bone_facing=facing)references.remember(pose_id,result['body'],result['flame'])meta.update(render_mode='bones',pose_id=pose_id,bone_revision=rig.revision,calibration_pose=calibration_pose,@@ -154,10 +188,12 @@ def main():except (OSError,EOFError):passfinally:release_inputs()+ if multi is not None:multi.close()class LatestCamera:- def __init__(self,device,height,cv):+ def __init__(self,device,height,cv,on_frame=None):self.cv=cv;self.condition=threading.Condition();self.latest=None;self.error=None;self.stop=False;self.cap=None+ self.on_frame=on_frameself.thread=threading.Thread(target=self.run,args=(device,height),daemon=True);self.thread.start()def run(self,device,height):try:@@ -175,16 +211,18 @@ class LatestCamera:if cap:cap.release()if self.cap is None:raise RuntimeError('Cannot open this webcam. Close other camera applications and try again.')while not self.stop:- with self.condition:self.latest=(im,time.monotonic());self.condition.notify_all()+ timestamp=time.monotonic()+ if self.on_frame:self.on_frame(im,timestamp)+ with self.condition:self.latest=(im,timestamp);self.condition.notify_all()ok,im=self.cap.read()if not ok:raise RuntimeError('Webcam disconnected or stopped delivering frames.')except Exception as e:with self.condition:self.error=str(e);self.condition.notify_all()finally:if self.cap:self.cap.release()- def take(self):+ def take(self,timeout=.2):with self.condition:- if self.latest is None and not self.error:self.condition.wait(.2)+ if self.latest is None and not self.error:self.condition.wait(timeout)if self.error:raise RuntimeError(self.error)item=self.latest;self.latest=None;return itemdef close(self):diff --git a/mocap/pear_models.py b/mocap/pear_models.pyindex 23c3fae..817bda4 100644--- a/mocap/pear_models.py+++ b/mocap/pear_models.py@@ -13,8 +13,10 @@ ASSETS=[dict(key='pear',name='Live Pose / PEAR',relative='pear/pear_model.pt',urdownload_url='https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov8s.pt',expected_sha256='1f47a78bf100391c2a140b7ac73a1caae18c32779be7d310658112f7ac9aa78a'),dict(key='pear_geometry',name='PEAR / SMPL-X 2020 + FLAME Geometry',relative='pear/geometry.json',url='https://github.com/Pixel-Talk/PEAR#-preparation',minimum_bytes=1)]-KEYS=('pear','pear_geometry','pear_yolo')-INSTRUCTIONS={'pear':'Download pear_model.pt from the linked official checkpoint, then import it here.',+ASSETS.append(dict(key='pear_geocalib',name='PEAR Camera Align / GeoCalib',relative='pear/geocalib-pinhole.tar',url='https://github.com/cvg/GeoCalib',minimum_bytes=116074121,download_url='https://github.com/cvg/GeoCalib/releases/download/v1.0/geocalib-pinhole.tar',expected_sha256='86d6aeacd8bbd974c59ce39f61854e00d36911c732ad89be471476fd708722ac'))+KEYS=('pear','pear_geometry','pear_yolo','flow_vggt','pear_geocalib')+INSTRUCTIONS={'pear_geocalib':'Used by automatic Camera Align, including one camera. Alignment is optional for tracking: if its support or models are missing, PEAR continues in the selected camera view with a warning, without fusion or aligned foot lock. Download geocalib-pinhole.tar from the official v1.0 release, then import the original TAR file here without extracting it. Code: Apache-2.0; checkpoint: CC BY 4.0. See the official GeoCalib LICENSE-WEIGHTS. Existing VGGT weights are reused.',+ 'pear':'Download pear_model.pt from the linked official checkpoint, then import it here.','pear_geometry':'1. Review and accept the SMPL-X and FLAME provider terms; register or sign in where required. PEAR needs SMPL-X 2020 and FLAME 2020, not the standard SMPL-X v1.1 or MAMMA locked-head models.\n2. Open PEAR Preparation below. Use its official Google Drive assets bundle link to obtain assets.zip.\n3. Import the original assets.zip here. The app validates its SHA-256 and extracts only the required geometry files. The source ZIP is left unchanged and is not copied into the models folder.\n4. The geometry bundle has separate provider restrictions; it is not redistributed by RGB MoCap.'}def spec():return json.loads((ROOT/'installer/pear-assets.json').read_text(encoding='utf8'))diff --git a/mocap/pear_multi_ui.py b/mocap/pear_multi_ui.pynew file mode 100644index 0000000..9109030--- /dev/null+++ b/mocap/pear_multi_ui.py@@ -0,0 +1,348 @@+"""PEAR multiview input controls; inference/calibration never run on the GUI thread."""+from pathlib import Path+import json,hashlib,time,math+from PySide6.QtCore import Qt,QSize+from PySide6.QtGui import QImage,QIcon,QPixmap+from PySide6.QtWidgets import QWidget,QGridLayout,QHBoxLayout,QScrollArea,QComboBox,QSpinBox,QDoubleSpinBox,QLabel,QPushButton,QSizePolicy+from .mamma_ui import InputInspector,CameraThumbnail++class PearMultiWorkspace:+ def init_pear_multi(self):+ self.pear_inputs=[];self.pear_preview=0;self.pear_cameras=[];self.pear_devices=[]+ self.pear_rotations=[];self.pear_slot_rows=[];self.pear_device_rotations={};self.pear_video_rotations={}+ self.pear_capture=None;self.pear_capture_key=None;self.pear_capture_command=None;self.pear_capture_generation=0;self.pear_capture_failed=None;self.pear_capture_suspended=None;self.pear_capture_guard_at=0+ self.pear_capture_streams={};self.pear_align_frame=0;self.pear_align_generation=0+ self.pear_inspector=None;self.pear_input_token=0;self.pear_input_pending=False;self.pear_switching=False;self.pear_resume=False+ self.pear_calibration=None;self.pear_alignment=None;self.pear_align_phase=None;self.pear_align_folder=None;self.pear_align_signature=None+ self.pear_align_started=0;self.pear_align_text="Camera Align";self.pear_align_guard_at=0;self.pear_thumb_at=0;self.pear_thumbnails=None;self._pear_media_restore=None;self._pear_restoring_media=False+ def build_pear_multi_header(self,row):+ row.addWidget(QLabel('Webcams'));row.addSpacing(8);row.addWidget(QLabel('Count'))+ self.pear_camera_count=QSpinBox();self.pear_camera_count.setRange(1,32);self.pear_camera_count.setValue(1);self.pear_camera_count.setFixedWidth(48)+ self.pear_camera_count.setToolTip('Number of webcam slots. Assign a different device to every slot. Video files determine their own camera count.')+ row.addWidget(self.pear_camera_count)+ self.pear_refresh=QPushButton('↻');self.pear_refresh.setFixedWidth(28);self.pear_refresh.setToolTip('Refresh connected webcams.')+ row.addWidget(self.pear_refresh);row.addStretch();self.pear_refresh.clicked.connect(lambda:self.pear_scan_cameras(force=True))+ def build_pear_thumbnails(self,parent):+ self.pear_input_panel=QWidget();outer=QGridLayout(self.pear_input_panel);outer.setContentsMargins(0,0,0,0)+ outer.setVerticalSpacing(4)+ self.pear_header=QWidget();self.pear_header.setObjectName('editorHeader')+ controls=QHBoxLayout(self.pear_header);controls.setContentsMargins(7,3,7,3);controls.setSpacing(6)+ self.build_pear_multi_header(controls);outer.addWidget(self.pear_header,0,0)+ self.pear_slot_widget=QScrollArea();self.pear_slot_widget.setWidgetResizable(True);self.pear_slot_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)+ slots=QWidget();self.pear_slot_grid=QGridLayout(slots);self.pear_slot_grid.setContentsMargins(7,4,7,4);self.pear_slot_grid.setHorizontalSpacing(8);self.pear_slot_grid.setVerticalSpacing(4);self.pear_slot_grid.setAlignment(Qt.AlignTop);self.pear_slot_widget.setWidget(slots)+ for col,title in enumerate(('Camera','Device','Rotation')):+ label=QLabel(title);label.setObjectName('muted');self.pear_slot_grid.addWidget(label,0,col)+ self.pear_slot_grid.setColumnStretch(1,1);outer.addWidget(self.pear_slot_widget,1,0)+ self.pear_resize_slots(1);self.pear_camera_count.valueChanged.connect(self.pear_resize_slots)+ self.pear_thumbnails=QScrollArea();self.pear_thumbnails.setWidgetResizable(True);self.pear_thumbnails.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)+ self.pear_thumbnails.setAccessibleName('PEAR camera thumbnails');inner=QWidget();self.pear_thumbnail_grid=QGridLayout(inner)+ self.pear_thumbnail_grid.setContentsMargins(4,4,4,4);self.pear_thumbnail_grid.setSpacing(4)+ for c in range(4):self.pear_thumbnail_grid.setColumnStretch(c,1)+ self.pear_thumbnails.setWidget(inner);outer.addWidget(self.pear_thumbnails,2,0);parent.addWidget(self.pear_input_panel)+ self.pear_thumbnail_buttons=[];self.pear_input_panel.hide();self.pear_thumbnails.hide();self.pear_slot_widget.hide()+ def pear_resize_slots(self,count):+ if not hasattr(self,'pear_slot_grid'):return+ while len(self.pear_cameras)>count:+ self.pear_cameras.pop();self.pear_rotations.pop()+ for widget in self.pear_slot_rows.pop():self.pear_slot_grid.removeWidget(widget);widget.deleteLater()+ while len(self.pear_cameras)<count:+ combo=QComboBox();combo.setMinimumWidth(100);combo.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed)+ combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon);combo.setMinimumContentsLength(10)+ combo.addItem('None — use video' if not self.pear_cameras else 'None',None)+ for d in self.pear_devices:combo.addItem(d['name'],d)+ i=len(self.pear_cameras);combo.setToolTip(f'Webcam slot {i+1}');combo.currentIndexChanged.connect(lambda _,i=i:self.pear_camera_slot_changed(i))+ label=QLabel(str(i+1));rotation=self.pear_make_rotation(i)+ for col,widget in enumerate((label,combo,rotation)):self.pear_slot_grid.addWidget(widget,i+1,col)+ self.pear_slot_rows.append((label,combo,rotation));self.pear_cameras.append(combo);self.pear_rotations.append(rotation)+ self.pear_camera=self.pear_cameras[0];self.pear_rotation=self.pear_rotations[0]+ row_height=max(self.pear_camera.sizeHint().height(),self.pear_rotation.sizeHint().height())+ self.pear_slot_widget.setFixedHeight(min(220,12+self.pear_slot_grid.itemAtPosition(0,0).widget().sizeHint().height()+count*(row_height+4)))+ self.pear_slot_widget.show();self.pear_preview=min(self.pear_preview,count-1)+ self.pear_sync_rotations()+ self.pear_source_changed()+ def pear_make_rotation(self,index):+ control=QDoubleSpinBox();control.setRange(-360,360);control.setDecimals(1);control.setSingleStep(90);control.setSuffix('°');control.setFixedWidth(88)+ control.setAccessibleName(f'Camera {index+1} rotation');control.setToolTip('Rotate this input clockwise before display and tracking. 90 turns right; −90 turns left.')+ control.valueChanged.connect(lambda _,i=index:self.pear_rotation_changed(i));return control+ def pear_video_rotation_key(self):+ if self.pear_inputs:return self.pear_inputs[min(self.pear_preview,len(self.pear_inputs)-1)]['path']+ view=self.video_view+ return view._source_key[0] if view._source_key and self.video_readable else None+ def pear_sync_rotations(self):+ webcam=self.pear_using_webcams()+ if not webcam and self.pear_inputs:self.pear_preview=min(self.pear_preview,len(self.pear_inputs)-1)+ for i,(combo,control) in enumerate(zip(self.pear_cameras,self.pear_rotations)):+ device=combo.currentData()+ if webcam:+ value=self.pear_device_rotations.get(device['id'],0.) if device else 0.+ enabled=device is not None+ else:+ key=self.pear_video_rotation_key() if i==0 else None+ value=self.pear_video_rotations.get(key,0.);enabled=key is not None+ control.blockSignals(True);control.setValue(value);control.blockSignals(False);control.setEnabled(enabled)+ control.setAccessibleName(f'Webcam {i+1} rotation' if webcam else 'Selected video rotation')+ self.video_view.set_preview_rotation(self.pear_rotation.value() if self._pear_active and not webcam else 0.)+ def pear_camera_slot_changed(self,index):+ self.pear_sync_rotations();self.pear_source_changed()+ def pear_rotation_changed(self,index):+ if self.pear_using_webcams():+ device=self.pear_cameras[index].currentData()+ if device:self.pear_device_rotations[device['id']]=self.pear_rotations[index].value()+ elif index==0:+ key=self.pear_video_rotation_key()+ if key:self.pear_video_rotations[key]=self.pear_rotation.value()+ self.pear_source_changed()+ def pear_input_rotations(self):+ if self.pear_using_webcams():return [self.pear_device_rotations.get(c.currentData()['id'],0.) if c.currentData() else 0. for c in self.pear_cameras]+ return [self.pear_video_rotations.get(s['path'],0.) for s in self.pear_sources()]+ def pear_using_webcams(self):return any(c.currentData() is not None for c in self.pear_cameras)+ def pear_fill_devices(self,devices):+ changed=False;self.pear_devices=devices+ for combo in self.pear_cameras:+ current=combo.currentData();combo.blockSignals(True);combo.clear();combo.addItem('None — use video' if combo is self.pear_camera else 'None',None)+ for d in devices:combo.addItem(d['name'],d)+ index=next((i for i in range(1,combo.count()) if current and combo.itemData(i)['id']==current['id']),0)+ combo.setCurrentIndex(index);combo.blockSignals(False);changed|=current!=combo.currentData()+ self.pear_sync_rotations()+ if changed:self.pear_source_changed()+ def pear_sources(self):+ if self.pear_using_webcams():+ devices=[c.currentData() for c in self.pear_cameras]+ if any(d is None for d in devices):raise ValueError('Assign a webcam to every slot, or set all slots to None to use videos.')+ if len({d['id'] for d in devices})!=len(devices):raise ValueError('Each webcam slot must use a different device.')+ return devices+ if self.pear_inputs:return self.pear_inputs+ view=self.video_view+ return [dict(path=view._source_key[0])] if view._source_key and self.video_readable else []+ def pear_input_signature(self):+ sources=self.pear_sources();stamps=[]+ for s in sources:+ if 'path' in s:+ stamps.append([s['path'],s.get('file_stamp')])+ else:stamps.append(s)+ value=[stamps,self.pear_input_rotations(),self.pear_resolution.currentData() if self.pear_using_webcams() else None]+ return hashlib.sha256(json.dumps(value,sort_keys=True,ensure_ascii=False).encode('utf8')).hexdigest()+ def pear_multi_invalidate(self):+ try:signature=self.pear_input_signature()+ except (ValueError,OSError):signature=None+ if self.pear_calibration and self.pear_calibration[0]!=signature:self.pear_calibration=None+ if self.pear_align_phase and signature!=self.pear_align_signature:self.pear_cancel_alignment('Inputs changed; camera alignment cancelled.')+ def pear_make_thumbnails(self,entries):+ if self.pear_thumbnails is None:return+ while self.pear_thumbnail_grid.count():+ w=self.pear_thumbnail_grid.takeAt(0).widget()+ if w:w.deleteLater()+ self.pear_thumbnail_buttons=[]+ for i,(title,image) in enumerate(entries):+ button=CameraThumbnail();button.setCheckable(True);button.setAutoExclusive(True);button.setText(str(i+1))+ button.setFixedHeight(88);button.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed);button.setMinimumWidth(0)+ button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon);button.setToolTip(title)+ if image is not None:button.setIcon(QIcon(QPixmap.fromImage(image)));button.setIconSize(QSize(100,48))+ button.setStyleSheet('QToolButton{background:#303030;border:1px solid #555;color:#ddd}QToolButton:checked{border:2px solid #8ac1ff;background:#385571}')+ button.clicked.connect(lambda checked=False,i=i:self.pear_select_preview(i))+ self.pear_thumbnail_grid.addWidget(button,i//4,i%4);self.pear_thumbnail_buttons.append(button)+ self.pear_preview=min(self.pear_preview,max(0,len(entries)-1))+ if entries:self.pear_thumbnail_buttons[self.pear_preview].setChecked(True)+ self.pear_thumbnails.setFixedHeight(min(220,8+math.ceil(len(entries)/4)*92));self.pear_thumbnails.setVisible(len(entries)>1)+ def pear_select_preview(self,index):+ if index==self.pear_preview:return+ self.pear_preview=index;self._pear_last=None;self.pear_sync_rotations()+ if self.pear_using_webcams():self.pear_submit();return+ if not self.pear_inputs:return+ self.pear_resume=self.timer.isActive();self.stop_playback();self.pear_switching=True;self.video_readable=False+ self.video_view.open(Path(self.pear_inputs[index]['path']),timeline_fps=self.info['fps'],reuse=True)+ def load_pear_videos(self,paths):+ if not 1<=len(paths)<=32:self.pear_status.setText('Choose 1–32 PEAR camera videos.');return+ self.stop_playback();self.pear_cancel_alignment('Camera inputs replaced.');self.pear_calibration=None+ for combo in self.pear_cameras:combo.blockSignals(True);combo.setCurrentIndex(0);combo.blockSignals(False)+ if self.pear_inspector is None:+ self.pear_inspector=InputInspector(self);self.pear_inspector.finished_input.connect(self.pear_inputs_ready);self.pear_inspector.failed_input.connect(self.pear_inputs_failed);self.pear_inspector.start()+ self.pear_input_pending=True;self.pear_input_token=self.pear_inspector.request('pear_videos',list(map(str,paths)))+ self.pear_status.setText('Opening PEAR camera videos…')+ def pear_inputs_ready(self,kind,token,result):+ if not self._pear_active or token!=self.pear_input_token:return+ from .mamma_inputs import common_media+ self.pear_input_pending=False;self.pear_inputs=[e for e,image in result];self.info=common_media(self.pear_inputs)+ self.video_path=Path(self.pear_inputs[0]['path'])+ self.source_offset=0.;self.source_end=self.info['duration'];self.slider.set_media(self.info['fps']);self.slider.setRange(0,self.info['frames']-1);self.slider.reset_trim()+ self.slider.video_track_label=f'{len(result)} PEAR cameras · common trim';self.slider._cache_key=None+ self.pear_preview=0;self.pear_sync_rotations();self.pear_make_thumbnails([(e['id'],im) for e,im in result]);self.pear_switching=True;self.video_readable=False+ self.video_view.open(Path(self.pear_inputs[0]['path']),timeline_fps=self.info['fps'],reuse=True)+ self.filename.setText(f'{len(result)} PEAR camera videos · synchronized starts required · common range {self.info["duration"]:.2f} s')+ self.pear_source_changed()+ def pear_inputs_failed(self,kind,token,error):+ if token==self.pear_input_token:self.pear_input_pending=False;self.pear_status.setText(error)+ def pear_restore_media_ready(self):+ if not self._pear_restoring_media:return False+ self._pear_restoring_media=False;self.video_readable=True+ if self._pear_media_restore['info'] is None:return False+ self.seek(self._pear_media_restore['value']);return True+ def pear_video_ready(self,info):+ if not self._pear_active or not self.pear_inputs:return False+ self.pear_switching=False;self.video_readable=True+ self.fps_label.setText(f'Camera {self.pear_preview+1} · Source {info["fps"]:.2f} | Timeline {self.info["fps"]:.0f} fps')+ self.seek(self.slider.value());self.pear_source_changed()+ if self.pear_resume:self.pear_resume=False;self.toggle_play()+ return True+ def pear_camera_align(self):+ if self.pear_align_phase:self.pear_cancel_alignment('Camera alignment cancelled.');return+ if not self._pear_running:self.pear_toggle_tracking();return+ self.pear_begin_alignment()+ def pear_check_alignment(self):+ from .models import missing+ from .pear.alignment_support import configuration+ if not self.pear_sources():raise ValueError('Open a video or assign a webcam before Camera Align.')+ configuration()+ if missing('pear_align'):raise ValueError('Prepare VGGT and GeoCalib in PEAR Model Manager first.')+ def pear_begin_alignment(self):+ self.pear_alignment_warning.clear();self.pear_alignment_warning.hide()+ try:+ self.pear_check_alignment()+ self._pear_failed=False;self.pear_calibration=None+ if not self.pear_using_webcams() and not self.slider.clip_in<=self.slider.value()<self.slider.clip_out:+ self.slider.setValue(self.slider.clip_in);self.seek(self.slider.clip_in)+ self.pear_align_frame=self.slider.value();self.pear_align_generation=self.pear_generation+ if not self.pear_using_webcams():self.video_view.set_external_frame(None)+ self.pear_align_signature=self.pear_input_signature();self.pear_align_phase='samples'+ self.pear_align_started=time.monotonic();self.pear_align_text='Camera Align · Preparing background samples';self._pear_last=None;self.pear_status.setText('Camera Align · Preparing background and body-scale samples…');self.pear_submit()+ except (ValueError,OSError,KeyError) as e:+ self.pear_alignment_failed('Camera Align failed: '+str(e))+ def pear_cancel_alignment(self,message):+ if self.pear_alignment:self._pear_closing.append(self.pear_alignment);self.pear_alignment.close();self.pear_alignment=None+ if self.pear_align_phase=='samples' and self.pear_session:self.pear_close_session()+ self.pear_align_phase=None;self.pear_align_folder=None+ if hasattr(self,'pear_align_button'):+ self.pear_align_button.setText('Camera Align');self.pear_align_button.setToolTip(self.pear_align_tooltip)+ if hasattr(self,'pear_status'):self.pear_status.setText(message)+ def pear_alignment_failed(self,message):+ self.pear_cancel_alignment(message);self.pear_calibration=None+ self._pear_running=True;self._pear_failed=False;self._pear_start_align=False+ self.pear_generation+=1;self._pear_last=None;self._pear_ready=False;self._pear_probe_at=0+ warning=message+' Tracking continues in the selected camera view without alignment; aligned foot lock is unavailable.'+ self.pear_alignment_warning.setText(warning);self.pear_alignment_warning.show()+ self.pear_status.setText('Starting tracking without camera alignment…')+ self.motion_view.live_message=self.pear_status.text();self.motion_view.update()+ self.pear_update_tracking_button()+ self.log.append(warning)+ def pear_alignment_poll(self):+ if not self.pear_align_phase:return False+ self.pear_align_button.setText('Cancel Camera Align')+ self.pear_status.setText(self.pear_align_text+f' · {time.monotonic()-self.pear_align_started:.0f} s')+ if self.pear_align_phase=='closing':+ if any(s.process.poll() is None for s in self._pear_closing):return True+ from .pear.session import Session+ try:+ self.pear_alignment=Session('flow_pear_align');self.pear_alignment.submit(dict(folder=self.pear_align_folder));self.pear_align_phase='solve'+ except (OSError,RuntimeError,ValueError) as exc:+ self.pear_alignment_failed('Camera Align failed: '+str(exc));return True+ if self.pear_align_phase=='solve':+ if time.monotonic()-self.pear_align_guard_at>.5:+ self.pear_align_guard_at=time.monotonic();warning=self.pear_alignment.guard.check()+ if warning:self.pear_alignment_failed(warning);return True+ _,packet=self.pear_alignment.poll()+ if packet:+ meta,_=packet+ if meta['type']=='error':self.pear_alignment_failed(meta['text']);return True+ if meta['type']=='status':self.pear_align_text=meta['text']+ if meta['type']=='alignment' and meta.get('phase')=='complete':+ if self.pear_input_signature()!=self.pear_align_signature:self.pear_cancel_alignment('Inputs changed; alignment discarded.');return True+ self.pear_calibration=(self.pear_align_signature,self.pear_align_folder)+ self.log.append(f'PEAR Camera Align: {time.monotonic()-self.pear_align_started:.1f} s · '+self.pear_align_folder)+ self.pear_cancel_alignment('Camera alignment complete. Restarting tracking…');self.pear_generation+=1;self._pear_running=True;self._pear_failed=False;self._pear_last=None;self._pear_probe_at=0+ elif self.pear_alignment:self.pear_align_button.setToolTip(f'Aligning fixed cameras · {time.monotonic()-self.pear_align_started:.0f} s elapsed. Click to cancel.')+ return True+ return self.pear_align_phase=='closing'+ def pear_multi_request(self,value):+ sources=self.pear_sources();rotations=self.pear_input_rotations();value.update(sources=sources,preview=self.pear_preview,signature=self.pear_input_signature(),rotations=rotations,rotation=rotations[0] if rotations else 0.,+ fps=self.info['fps'] if self.info else 30.,duration=self.slider.clip_out/self.info['fps'] if self.info else 0.,+ calibration=self.pear_calibration[1] if self.pear_calibration else None,align_job=self.pear_align_phase=='samples')+ if len(sources)>1:value['frame']=value['timeline_frame']+ if self.pear_using_webcams():+ capture=self.pear_capture_request()+ if not self.pear_capture or self.pear_capture.process.poll() is not None or self.pear_capture_key!=self.pear_capture_session_key(capture):raise ValueError('Waiting for webcam capture streams…')+ streams=[self.pear_capture_streams.get(i) for i in range(len(sources))]+ if any(s is None or s.get('device_id')!=d['id'] for s,d in zip(streams,sources)):+ raise ValueError('Waiting for webcam capture streams…')+ value['camera_streams']=streams+ if self.pear_align_phase=='samples':+ value['generation']=self.pear_align_generation+ if not self.pear_using_webcams():value['frame']=self.pear_align_frame;value['timeline_frame']=self.pear_align_frame+ return value+ def pear_multi_packet(self,meta,arrays):+ if meta['type']=='alignment' and meta.get('phase')=='prepared':+ if self.pear_align_phase!='samples' or meta['generation']!=self.pear_align_generation:return True+ self.pear_align_folder=meta['folder'];self.pear_close_session();self.pear_align_phase='closing';return True+ if self.pear_align_phase=='samples' and meta['type'] in ('frame','missing'):return True+ if 'thumbnails' in arrays and time.monotonic()-self.pear_thumb_at>.25:+ self.pear_thumb_at=time.monotonic()+ for b,im in zip(self.pear_thumbnail_buttons,arrays['thumbnails']):+ h,w,_=im.shape;b.setIcon(QIcon(QPixmap.fromImage(QImage(im.data,w,h,im.strides[0],QImage.Format_RGB888).copy())))+ return False+ def pear_shutdown_multi(self):+ self.pear_close_capture()+ self.pear_cancel_alignment('Tracking stopped.')+ if self.pear_inspector:self.pear_inspector.stop();self.pear_inspector.wait(4000);self.pear_inspector=None+ if self.pear_thumbnails:self.pear_input_panel.hide()+ def pear_capture_request(self):+ sources=[];slots=[];angles=[]+ for i,(combo,angle) in enumerate(zip(self.pear_cameras,self.pear_input_rotations())):+ device=combo.currentData()+ if device:sources.append(device);slots.append(i);angles.append(angle)+ if not sources:return None+ if len({s['id'] for s in sources})!=len(sources):raise ValueError('Each webcam slot must use a different device.')+ return dict(sources=sources,slots=slots,slot_count=len(self.pear_cameras),rotations=angles,resolution=self.pear_resolution.currentData())+ def pear_close_capture(self):+ if self.pear_capture:self._pear_closing.append(self.pear_capture);self.pear_capture.close();self.pear_capture=None+ self.pear_capture_key=None;self.pear_capture_command=None;self.pear_capture_streams={}+ def pear_capture_session_key(self,request):+ return json.dumps([request['sources'],request['slots'],request['slot_count'],request['resolution']],sort_keys=True)+ def pear_capture_error(self,message,key):+ self.pear_cancel_alignment(message);self.pear_close_session();self.pear_close_capture()+ self.pear_capture_failed=key;self._pear_failed=True;self.video_view.set_external_frame(QImage())+ self.pear_status.setText(message);self.motion_view.live_message=message;self.motion_view.update();self.log.append(message)+ def pear_capture_poll(self):+ try:request=self.pear_capture_request()+ except ValueError as exc:+ self.pear_close_capture()+ if not self._pear_running:self.video_view.set_external_frame(QImage());self.pear_status.setText(str(exc))+ return+ key=json.dumps(request,sort_keys=True) if request else None+ if request is None:+ self.pear_close_capture();return+ if key in (self.pear_capture_failed,self.pear_capture_suspended):return+ session_key=self.pear_capture_session_key(request)+ if self.pear_capture_key!=session_key:+ self.pear_close_capture()+ if any(s.process.poll() is None for s in self._pear_closing):return+ from .pear.session import Session+ try:self.pear_capture=Session('pear_camera_preview')+ except Exception as exc:self.pear_capture_failed=key;self.pear_status.setText(str(exc));return+ self.pear_capture_key=session_key+ self.video_view.set_external_frame(QImage())+ if not self._pear_running and not self.pear_align_phase and not self._pear_failed:self.pear_status.setText('Opening webcam preview…')+ command=dict(request,preview=self.pear_preview)+ if command!=self.pear_capture_command:+ self.pear_capture_generation+=1;self.pear_capture.submit(dict(command,generation=self.pear_capture_generation));self.pear_capture_command=command+ if time.monotonic()-self.pear_capture_guard_at>.5:+ self.pear_capture_guard_at=time.monotonic();warning=self.pear_capture.guard.check()+ if warning:self.pear_capture_error(warning,key);return+ _,packet=self.pear_capture.poll()+ if not packet:return+ meta,arrays=packet+ if meta['type']=='error':+ self.pear_capture_error(meta['text'],key);return+ if meta.get('generation')!=self.pear_capture_generation:return+ if meta['type']=='camera_preview':+ self.pear_capture_streams={s['slot']:s for s in meta.get('streams',[])}+ self.pear_multi_packet(meta,arrays)+ if meta['preview']!=self.pear_preview:return+ if self._pear_running and self._pear_ready and not self.pear_align_phase and not self._pear_failed:return+ im=arrays.get('image')+ if im is not None:+ h,w,_=im.shape;self.video_view.set_external_frame(QImage(im.data,w,h,im.strides[0],QImage.Format_RGB888).copy())+ if not self._pear_running and not self.pear_align_phase and not self._pear_failed:self.pear_status.setText('Webcam preview · '+('Assign every slot before starting tracking.' if len(request['sources'])<request['slot_count'] else 'Click Start Live Tracking for pose tracking.'))+ self.fps_label.setText('Webcam preview')+ else:+ self.video_view.set_external_frame(QImage())+ if not self._pear_running and not self.pear_align_phase and not self._pear_failed:self.pear_status.setText('Waiting for webcam frames…' if self.pear_preview in request['slots'] else 'Choose an assigned webcam thumbnail to preview it.')+ elif meta['type']=='status' and not self._pear_running and not self.pear_align_phase and not self._pear_failed:self.pear_status.setText(meta['text'])diff --git a/mocap/pear_ui.py b/mocap/pear_ui.pyindex a6bb61c..7e0d345 100644--- a/mocap/pear_ui.py+++ b/mocap/pear_ui.py@@ -1,5 +1,6 @@"""Transient live tool; offline projects and committed motion remain untouched."""-import time,subprocess,re,threading+import time,subprocess,re,threading,json+from pathlib import Pathimport numpy as npfrom PySide6.QtCore import Qt,QTimerfrom PySide6.QtGui import QImage@@ -36,8 +37,11 @@ class CameraScan:self.cancel();self.process.communicate()finally:self.devices=devices-class PearWorkspace:+from .pear_multi_ui import PearMultiWorkspace++class PearWorkspace(PearMultiWorkspace):def init_pear(self):+ self.init_pear_multi()self._pear_active=False;self._pear_failed=False;self.pear_session=None;self.pear_generation=0;self.pear_request=0;self._pear_last=Noneself._pear_scan_cache_at=0;self._pear_probe_at=0;self._pear_guard_at=0;self._pear_camera_state=None;self._pear_camera_scan=None;self._pear_closing=[]self._pear_presented_request=-1@@ -47,18 +51,10 @@ class PearWorkspace:self._pear_source_signature=Noneself._pear_bone_reset=0;self._pear_reset_pose=None;self._pear_reset_pending=Falseself._pear_raw_pose=None;self._pear_world_anchor=None;self._pear_position_revision=0+ self._pear_start_align=Falsedef build_pear_header(self,header):- self.pear_header=QWidget();row=QHBoxLayout(self.pear_header);row.setContentsMargins(0,0,0,0)- row.addWidget(QLabel('Webcam'))- self.pear_camera=QComboBox();self.pear_camera.setMinimumWidth(130);self.pear_camera.setMaximumWidth(260)- self.pear_camera.addItem('None — use video',None)- self.pear_camera.setToolTip('Choose video or a webcam, then click Start Live Tracking. Close other camera apps first.')- row.addWidget(self.pear_camera)- self.pear_refresh=QPushButton('↻');self.pear_refresh.setFixedWidth(28);self.pear_refresh.setToolTip('Refresh connected webcams.')- row.addWidget(self.pear_refresh);self.pear_refresh.clicked.connect(lambda:self.pear_scan_cameras(force=True))- self.pear_camera.currentIndexChanged.connect(self.pear_source_changed)- header.insertWidget(1,self.pear_header);self.pear_header.hide()+ # Camera controls are built together below the video, never in its header.self.pear_scan_timer=QTimer(self);self.pear_scan_timer.setInterval(100);self.pear_scan_timer.timeout.connect(self.pear_finish_scan)def build_pear_settings(self):@@ -68,34 +64,47 @@ class PearWorkspace:self.pear_world_position=QCheckBox('World Position');self.pear_world_position.setChecked(True)self.pear_world_position.setToolTip('Move the pelvis using estimated position. Off fixes its current position, including height; rotation is unchanged.')layout.addWidget(self.pear_world_position);self.pear_world_position.toggled.connect(self.pear_position_changed)+ self.pear_foot_lock=QCheckBox('Foot Lock');self.pear_foot_lock.setChecked(True)+ self.pear_foot_lock.setToolTip('Stabilize planted feet with small, smooth leg corrections. Camera alignment is required.')+ layout.addWidget(self.pear_foot_lock);self.pear_foot_lock.toggled.connect(self.pear_filter_changed)self.pear_smoothing=QCheckBox('One Euro Filter');self.pear_smoothing.setChecked(True)self.pear_smoothing.setToolTip('Reduce motion jitter in video and webcam input.')layout.addWidget(self.pear_smoothing)+ components=QVBoxLayout();components.setContentsMargins(16,0,0,0);components.setSpacing(4)+ self.pear_smooth_rotations=QCheckBox('Bone Rotation');self.pear_smooth_rotations.setChecked(True)+ self.pear_smooth_rotations.setToolTip('Smooth body and finger rotations.')+ self.pear_smooth_position=QCheckBox('World Position');self.pear_smooth_position.setChecked(True)+ self.pear_smooth_position.setToolTip('Smooth estimated world position.')+ components.addWidget(self.pear_smooth_rotations);components.addWidget(self.pear_smooth_position)+ layout.addLayout(components)strength_row=QHBoxLayout();strength_row.addWidget(QLabel('Filter Strength'))self.pear_strength=QDoubleSpinBox();self.pear_strength.setRange(1,100);self.pear_strength.setDecimals(0);self.pear_strength.setValue(50);self.pear_strength.setSingleStep(5)self.pear_strength.setToolTip('Higher values reduce jitter but add more delay.')strength_row.addWidget(self.pear_strength);layout.addLayout(strength_row)- self.pear_smoothing.toggled.connect(self.pear_strength.setEnabled)+ for control in (self.pear_smoothing,self.pear_smooth_rotations,self.pear_smooth_position):+ control.toggled.connect(self.pear_filter_controls_changed)self.pear_strength.valueChanged.connect(self.pear_filter_changed)- layout.addWidget(QLabel('Rotation (degrees)'))- self.pear_rotation=QDoubleSpinBox();self.pear_rotation.setRange(-360,360);self.pear_rotation.setDecimals(1);self.pear_rotation.setSingleStep(90)- self.pear_rotation.setToolTip('Rotate video or webcam images before display and tracking. Positive values turn clockwise; 90 turns right, −90 turns left. The original video file is unchanged.')- layout.addWidget(self.pear_rotation)self.pear_resolution=QComboBox();self.pear_resolution.addItem('Webcam 1280 × 720',720);self.pear_resolution.addItem('Webcam 640 × 480',480)self.pear_resolution.setToolTip('Requested webcam capture size. Actual size depends on the driver. Lower resolution may reduce camera and detector cost.')layout.addWidget(self.pear_resolution)self.pear_status=QLabel('Click Start Live Tracking to begin.');self.pear_status.setWordWrap(True);layout.addWidget(self.pear_status)- self.pear_status.setToolTip('Fixed-length body and finger bones, without per-frame body mesh calculation. Live preview only; no recording, correction, retargeting or export. Pelvis placement assumes a fixed camera.')+ self.pear_status.setToolTip('Fixed-length body and finger bones with lightweight live foot locking. No per-frame body mesh, recording, offline correction, retargeting or export. Keep cameras fixed.')+ self.pear_alignment_warning=QLabel();self.pear_alignment_warning.setWordWrap(True);self.pear_alignment_warning.hide();layout.addWidget(self.pear_alignment_warning)self.pear_tracking_button=QPushButton('Start Live Tracking');layout.addWidget(self.pear_tracking_button);self.pear_tracking_button.clicked.connect(self.pear_toggle_tracking)- self.pear_tracking_button.setToolTip('Start tracking, or stop and release the models and webcam.')+ self.pear_tracking_button.setToolTip('Try camera alignment, then start tracking. If alignment fails, track the selected camera without fusion. Stop releases the models and webcam.')self.pear_reset_button=QPushButton('Reset Bones');self.pear_reset_button.setEnabled(False);layout.addWidget(self.pear_reset_button)- self.pear_reset_button.setToolTip('Recalculate fixed bone lengths from the displayed pose. Video playback pauses. Models stay loaded.')+ self.pear_reset_button.setToolTip('Recalculate bones from the displayed pose, then align cameras again. Video playback pauses.')self.pear_reset_button.clicked.connect(self.pear_reset_bones)- for signal in (self.pear_smoothing.toggled,self.pear_rotation.valueChanged,self.pear_resolution.currentIndexChanged):signal.connect(self.pear_source_changed)+ self.pear_resolution.currentIndexChanged.connect(self.pear_source_changed)+ self.pear_align_button=QPushButton('Camera Align');layout.addWidget(self.pear_align_button)+ self.pear_align_button.setToolTip('Align one or more fixed views using VGGT and GeoCalib. A single view uses an estimated body-to-depth scale. Show the person and floor; multiple videos must be synchronized. Start Live Tracking aligns automatically.')+ self.pear_align_tooltip=self.pear_align_button.toolTip()+ self.pear_align_button.clicked.connect(self.pear_camera_align)self.model_pages.addWidget(self.pear_page)self.pear_poll_timer=QTimer(self);self.pear_poll_timer.setInterval(16);self.pear_poll_timer.timeout.connect(self.pear_poll)def pear_scan_cameras(self,force=False):+ if force:self.pear_capture_failed=None;self.pear_capture_suspended=Noneif not force and time.monotonic()-self._pear_scan_cache_at<5:returnif self._pear_camera_scan is not None:returnself._pear_camera_scan=CameraScan();self.pear_refresh.setEnabled(False)@@ -105,11 +114,7 @@ class PearWorkspace:scan=self._pear_camera_scanif scan is None or scan.devices is None:returndevices=scan.devices;self._pear_scan_cache_at=time.monotonic();self._pear_camera_scan=None;self.pear_scan_timer.stop()- current=self.pear_camera.currentData();self.pear_camera.blockSignals(True);self.pear_camera.clear();self.pear_camera.addItem('None — use video',None)- for device in devices:self.pear_camera.addItem(device['name'],device)- index=next((i for i in range(1,self.pear_camera.count()) if current and self.pear_camera.itemData(i).get('id')==current.get('id')),0)- self.pear_camera.setCurrentIndex(index);self.pear_camera.blockSignals(False);self.pear_refresh.setEnabled(True)- if current and current!=self.pear_camera.currentData():self.pear_source_changed()+ self.pear_fill_devices(devices);self.pear_refresh.setEnabled(True)def pear_stop_scan(self):self.pear_scan_timer.stop()@@ -119,11 +124,14 @@ class PearWorkspace:def pear_select_model(self):selected=self.model_choice.currentData()=='pear'if selected:- if self.busy or self.contact_saving:+ if self.busy or self.contact_saving or self.mamma_pending or self._mamma_switching:self.model_choice.blockSignals(True);self.model_choice.setCurrentIndex(self.model_choice.findData(self._selected_tool));self.model_choice.blockSignals(False);return Trueif not self._pear_active:self.stop_playback();self.remember_workspace_model()self._pear_active=True;self._pear_running=False;self._pear_last=None+ self._pear_media_restore=dict(info=self.info,video_path=self.video_path,source_offset=self.source_offset,source_end=self.source_end,+ value=self.slider.value(),minimum=self.slider.minimum(),maximum=self.slider.maximum(),clip_in=self.slider.clip_in,clip_out=self.slider.clip_out,+ filename=self.filename.text(),fps_label=self.fps_label.text(),track=self.slider.video_track_label,source_key=self.video_view._source_key,path=self.video_view._source_key[0] if self.video_view._source_key else None)m=self.motion_viewself._pear_camera_state={k:np.copy(getattr(m,k)) if isinstance(getattr(m,k),np.ndarray) else getattr(m,k) for k in ('yaw','pitch','distance','pan','scene_center','body_height','scene_span','auto_fit')}self._pear_contact_edit=self.slider.contact_edit_enabled;self._pear_status_text=self.status.text();self._pear_bone_tooltip=self.bone_overlay.toolTip();self._pear_timeline_help=self.timeline_help_dialog.text()@@ -137,7 +145,22 @@ class PearWorkspace:def pear_leave(self):if not self._pear_active:return- self._pear_active=False;self.pear_poll_timer.stop();self.pear_close_session()+ self._pear_active=False;self.pear_poll_timer.stop();self.pear_close_session();self.pear_shutdown_multi()+ if self.pear_inputs and self._pear_media_restore:+ saved=self._pear_media_restore;self.info=saved['info'];self.video_path=saved['video_path'];self.source_offset=saved['source_offset'];self.source_end=saved['source_end']+ self.slider.setRange(saved['minimum'],saved['maximum']);self.slider.clip_in=saved['clip_in'];self.slider.clip_out=saved['clip_out'];self.slider.video_track_label=saved['track'];self.slider.setValue(saved['value'])+ self.filename.setText(saved['filename']);self.fps_label.setText(saved['fps_label'])+ if self.info:self.slider.set_media(self.info['fps'])+ self.clip_changed(self.slider.clip_in,self.slider.clip_out)+ self.video_view.set_external_frame(None)+ if saved['path']:+ key=saved['source_key'];self._pear_restoring_media=True+ opened=self.video_view.open(Path(saved['path']),source_size=key[3],timeline_fps=key[4],timeline_start=key[5],reuse=True)+ if not opened:self.pear_restore_media_ready()+ else:+ self.video_readable=False;self.video_view.shutdown();self.video_view.update()+ self.pear_inputs=[];self.pear_calibration=None+ self.video_view.set_preview_rotation(0.)self.pear_header.hide();self.timeline_panel.setEnabled(True);self.video_view.set_external_frame(None)self.video_view.show_observations=self._pear_observationsself.video_overlay.show();self.status.setText(self._pear_status_text)@@ -166,14 +189,18 @@ class PearWorkspace:def pear_update_tracking_button(self):closing=any(s.process.poll() is None for s in self._pear_closing)- self.pear_tracking_button.setText('Stop' if self._pear_running else 'Stopping…' if closing else 'Start Live Tracking')- self.pear_tracking_button.setEnabled(self._pear_running or not closing)- self.pear_reset_button.setEnabled(self._pear_running and self._pear_ready and self.motion_view.live_data is not None and not self._pear_reset_pending)+ active=self._pear_running or bool(self.pear_align_phase)+ self.pear_tracking_button.setText('Stop' if active else 'Stopping…' if closing else 'Start Live Tracking')+ self.pear_tracking_button.setEnabled(active or not closing)+ self.pear_reset_button.setEnabled(self._pear_running and not self.pear_align_phase and self._pear_ready and self.motion_view.live_data is not None and not self._pear_reset_pending)def pear_reset_bones(self):if not self.pear_reset_button.isEnabled():return+ if self.pear_calibration:+ self.pear_calibration=None+ self.pear_status.setText('Bone scale changed; run Camera Align again.')meta=self.pear_last_metrics- if self.pear_camera.currentData() is None:+ if not self.pear_using_webcams():frame=int(meta['timeline_frame']);self.stop_playback();self.slider.setValue(frame);self.seek(frame)self._pear_bone_reset+=1;self._pear_reset_pose=meta['pose_id'];self._pear_reset_pending=Trueself._pear_last=None;self.pear_status.setText('Resetting bones from the displayed pose…')@@ -187,6 +214,7 @@ class PearWorkspace:self.pear_position_pose(self._pear_raw_pose)self.motion_view.live_key=('pear-position',self.pear_generation,self._pear_position_revision,self._pear_presented_request)self.motion_view.update()+ if self._pear_active:self._pear_last=None;self.pear_submit()def pear_position_pose(self,pose):self._pear_raw_pose=pose@@ -198,8 +226,13 @@ class PearWorkspace:def pear_toggle_tracking(self):if not self._pear_active:return- if self._pear_running:+ if self._pear_running or self.pear_align_phase:+ try:self.pear_capture_suspended=json.dumps(self.pear_capture_request(),sort_keys=True)+ except ValueError:self.pear_capture_suspended=None+ self.pear_cancel_alignment("Tracking stopped.")+ self.pear_close_capture()self._pear_running=False;self.pear_generation+=1+ self.pear_alignment_warning.clear();self.pear_alignment_warning.hide()self.stop_playback();self.pear_close_session()self.video_view.set_external_frame(None)self.pear_status.setText('Tracking stopped.')@@ -207,12 +240,17 @@ class PearWorkspace:if self.info:self.fps_label.setText(f"Source {self.info['fps']:.2f} fps")returnif any(s.process.poll() is None for s in self._pear_closing):return+ try:+ if not self.pear_sources():raise ValueError('Open a video or assign a webcam before starting.')+ except (ValueError,OSError) as e:self.pear_status.setText(str(e));returnfrom .pear_runtime import statusfrom .models import missingok,message=status()if not ok or missing('pear_assets'):self.pear_status.setText(message if not ok else 'Prepare missing PEAR models in Model Manager.');return+ self.pear_capture_suspended=None;self.pear_capture_failed=Noneself._pear_running=True;self._pear_failed=False;self._pear_probe_at=0+ self._pear_start_align=Trueself._pear_restart+=1;self.pear_update_tracking_button();self.pear_source_changed()def pear_sync_controls(self):@@ -223,6 +261,7 @@ class PearWorkspace:for key,check in self.viewport_checks.items():check.setVisible(key=='show_grid')self.bone_overlay.setToolTip('Show fixed-length PEAR body and finger bones. Use Reset Bones to recalibrate their lengths from the displayed pose. Display only; no animation export in this mode.')self.mamma_thumbnails.hide()+ self.pear_input_panel.show();self.pear_slot_widget.show()self.timeline_help_dialog.setText("PEAR live video preview\n\nOpen a video or select a webcam, then click Start Live Tracking. Stop releases the models and webcam.\n\nFor video, click or drag the frame ruler to infer the current frame. During playback, the processed video frame and its pose appear together with a small delay. Old requests are skipped. Pause or seek to inspect an exact frame.\n\nSelecting a webcam disables video timeline controls. No motion is recorded or exported in this mode.")self.video_overlay.hide();self.slider.contact_edit_enabled=Falseself.status.setText("PEAR experimental preview · Tracking and pose estimates may be unstable.")@@ -232,7 +271,7 @@ class PearWorkspace:self.readiness.setToolTip(message)self.export_action.setEnabled(False);self.save_project_action.setEnabled(False);self.import_character_action.setEnabled(False)self.slider.contacts_supported=False;self.slider.live_preview=True;self.slider._cache_key=None;self.slider.update()- self.play_button.setEnabled(self.info is not None and self.video_readable and self.pear_camera.currentData() is None)+ self.play_button.setEnabled(self.info is not None and self.video_readable and not self.pear_using_webcams())if not ok or unavailable:self.pear_status.setText(message if not ok else 'Prepare missing PEAR models in Model Manager.')self.motion_view.live_message=self.pear_status.text();self.motion_view.update()@@ -244,9 +283,17 @@ class PearWorkspace:def pear_source_changed(self,*_):if not self._pear_active:returnself._pear_failed=False- camera=self.pear_camera.currentData()+ camera=self.pear_camera.currentData() if self.pear_using_webcams() else None+ if self.pear_using_webcams() and camera is None:camera=Truepath=self.video_view._source_key[0] if self.video_view._source_key and self.video_readable and camera is None else None- signature=(camera,path,self.pear_rotation.value(),self.pear_resolution.currentData() if camera else None,self._pear_restart)+ self.pear_multi_invalidate()+ if camera:+ self.pear_make_thumbnails([(f'Camera {i+1}: '+(c.currentData()['name'] if c.currentData() else 'None'),None) for i,c in enumerate(self.pear_cameras)])+ self.timeline_panel.setEnabled(camera is None);self.pear_resolution.setEnabled(camera is not None)+ try:+ sources=self.pear_sources();signature=(self.pear_input_signature(),self._pear_restart)+ except (ValueError,OSError) as e:+ self.pear_status.setText(str(e));self.pear_generation+=1;self.pear_close_session();returnkeep_pair=signature==self._pear_source_signature and self.motion_view.live_data is not Noneself._pear_source_signature=signatureself.pear_generation+=1;self._pear_last=None@@ -256,7 +303,7 @@ class PearWorkspace:self.motion_view.live_data=None;self.motion_view.live_frame_first=Trueself.motion_view.live_message='Waiting for live tracking…';self.motion_view.update()self.timeline_panel.setEnabled(camera is None)- self.pear_rotation.setEnabled(True);self.pear_smoothing.setEnabled(True);self.pear_resolution.setEnabled(camera is not None)+ self.pear_sync_rotations();self.pear_smoothing.setEnabled(True);self.pear_resolution.setEnabled(camera is not None)if not self._pear_running:self.video_view.set_external_frame(None)self.pear_status.setText('Click Start Live Tracking to begin.')@@ -264,25 +311,45 @@ class PearWorkspace:self.pear_sync_controls();returnif not keep_pair:if camera:- self.stop_playback();self.video_view.set_external_frame(QImage())- elif self.video_readable:self.video_view.set_external_frame(QImage())+ self.stop_playback()+ if not self.video_view.external_mode:self.video_view.set_external_frame(QImage())+ elif self.video_readable:self.video_view.set_external_frame(None)else:self.video_view.set_external_frame(None)- self.pear_sync_controls();self.pear_submit()+ self.pear_sync_controls()+ if self._pear_start_align or (not self.pear_calibration and not self.pear_align_phase):+ self._pear_start_align=False;self.pear_begin_alignment()+ else:self.pear_submit()def pear_filter_changed(self,*_):if self._pear_active:self._pear_last=None;self.pear_submit()+ def pear_filter_controls_changed(self,*_):+ enabled=self.pear_smoothing.isChecked()+ self.pear_smooth_rotations.setEnabled(enabled);self.pear_smooth_position.setEnabled(enabled)+ self.pear_strength.setEnabled(enabled and (self.pear_smooth_rotations.isChecked() or self.pear_smooth_position.isChecked()))+ self.pear_filter_changed()+def pear_submit(self):if not self._pear_active or not self._pear_running or self._pear_failed or self.busy:return- camera=self.pear_camera.currentData();view=self.video_view+ if self.pear_input_pending or self.pear_switching or self.pear_align_phase in ('closing','solve'):return+ try:sources=self.pear_sources()+ except (ValueError,OSError):return+ camera=(sources[0] if sources else None) if self.pear_using_webcams() else None;view=self.video_viewpath=view._source_key[0] if view._source_key and self.video_readable else Noneplaying=self.timer.isActive() and camera is Nonevalue=dict(generation=self.pear_generation,mode='camera' if camera else 'video' if path else 'idle',camera=camera,path=None if camera else path,frame=view.requested_index,timeline_frame=view.timeline_requested_index,pair_video=playing,restart=self._pear_restart,rotation=self.pear_rotation.value(),smoothing=self.pear_smoothing.isChecked(),smoothing_strength=self.pear_strength.value(),resolution=self.pear_resolution.currentData())+ value.update(smooth_rotations=self.pear_smooth_rotations.isChecked(),smooth_position=self.pear_smooth_position.isChecked())value.update(bone_reset=self._pear_bone_reset,reset_pose=self._pear_reset_pose)+ value.update(foot_lock=self.pear_foot_lock.isChecked(),world_position=self.pear_world_position.isChecked(),+ position_anchor=self._pear_world_anchor.tolist() if self._pear_world_anchor is not None else None)+ try:self.pear_multi_request(value)+ except (ValueError,OSError) as exc:+ if not self.pear_align_phase:self.pear_status.setText(str(exc))+ returnif value==self._pear_last:return- self._pear_source_signature=(camera,value['path'],value['rotation'],value['resolution'] if camera else None,value['restart'])+if not self.pear_session:if any(s.process.poll() is None for s in self._pear_closing):self.pear_status.setText('Stopping previous PEAR session…');return@@ -297,7 +364,6 @@ class PearWorkspace:self._pear_running=False;self.pear_update_tracking_button();self.pear_status.setText(str(e));returnself.pear_started=time.monotonic();self._pear_failed=False;self._pear_ready=Falseself._pear_last=value.copy();self.pear_request+=1;value['request']=self.pear_request;value['requested_at']=time.monotonic()- if path and not view.external_mode:view.set_external_frame(view.frame if view.frame is not None else QImage())self.pear_session.submit(value)if not camera and not playing:if self.motion_view.live_data is None:self.motion_view.live_message='Tracking current video frame…' if path else 'Open a video or select a webcam.'@@ -305,7 +371,7 @@ class PearWorkspace:self.motion_view.update()def pear_seek(self,index):- if not self._pear_active or not self._pear_running or self.pear_camera.currentData() is not None:return+ if not self._pear_active or not self._pear_running or self.pear_using_webcams():return# Ordinary forward playback accepts completed frames with bounded delay.# A scrub or loop starts a new epoch: old results must not cross it.if index!=self.video_view.timeline_requested_index and (not self.playback_tick or index<self.video_view.timeline_requested_index):@@ -316,7 +382,7 @@ class PearWorkspace:self.motion_view.update()def pear_playback_stopped(self):- if not self._pear_active or not self._pear_running or self.pear_camera.currentData() is not None:return+ if not self._pear_active or not self._pear_running or self.pear_using_webcams():returnif self.info:self.fps_label.setText(f"Source {self.info['fps']:.2f} fps")if self.video_view.external_mode:self.pear_generation+=1;self._pear_last=None@@ -329,16 +395,19 @@ class PearWorkspace:def pear_poll(self):self._pear_closing=[s for s in self._pear_closing if s.process.poll() is None]if not self._pear_active:return+ self.pear_capture_poll()+ if self.pear_alignment_poll():returnself.pear_update_tracking_button()if not self._pear_running:returnself.pear_submit()if not self.pear_session:returnif time.monotonic()-self._pear_guard_at>.5:self._pear_guard_at=time.monotonic()- idle=self._pear_ready and (self._pear_failed or (self.pear_camera.currentData() is None and not self.timer.isActive() and self._pear_presented_request==self.pear_request))+ idle=self._pear_ready and (self._pear_failed or (not self.pear_using_webcams() and not self.timer.isActive() and self._pear_presented_request==self.pear_request))if idle:self.pear_session.guard.output()warning=self.pear_session.guard.check()if warning:+ if self.pear_align_phase=='samples':self.pear_alignment_failed('Camera Align failed: '+warning);returnself._pear_raw_pose=Noneself.pear_status.setText(warning);self.motion_view.live_data=None;self.motion_view.live_message=warningself.pear_close_session();self._pear_failed=True;self.log.append('PEAR: '+warning);self.motion_view.update();return@@ -350,10 +419,13 @@ class PearWorkspace:self.motion_view.live_parents=a['parents']if packet:meta,a=packet;kind=meta['type']+ if self.pear_multi_packet(meta,a):return+ if 'preview' in meta and meta['preview']!=self.pear_preview:returnif kind=='error':if meta.get('generation') is not None and meta['generation']!=self.pear_generation:if meta.get('recoverable'):returnself.pear_close_session();return+ if self.pear_align_phase=='samples':self.pear_alignment_failed(meta['text']);returnself._pear_raw_pose=Noneself.pear_status.setText(meta['text']);self.motion_view.live_data=None;self.motion_view.live_message=meta['text'];self.motion_view.update()if meta.get('recoverable'):@@ -365,7 +437,7 @@ class PearWorkspace:self.pear_status.setText(meta['text']);self.motion_view.live_message=meta['text'];self.motion_view.update();returnif meta.get('generation')!=self.pear_generation:returnif meta.get('mode')=='video':- playing=self.timer.isActive() and self.pear_camera.currentData() is None+ playing=self.timer.isActive() and not self.pear_using_webcams()if bool(meta.get('pair_video'))!=playing:returnif playing:if meta.get('request',-1)<=self._pear_presented_request or ('image' not in a and kind!='missing'):return@@ -379,9 +451,14 @@ class PearWorkspace:self.motion_view.live_key=(self.pear_generation,meta.get('frame'),meta.get('request'),self._pear_position_revision)self.motion_view.live_message=meta.get('text','')if kind=='frame':- if meta.get('bone_reset_handled',-1)>=self._pear_bone_reset:self._pear_reset_pending=False+ if self._pear_reset_pending and meta.get('bone_reset_handled',-1)>=self._pear_bone_reset:+ self._pear_reset_pending=False;self.pear_last_metrics=meta+ self.pear_begin_alignment();returnself.pear_last_metrics=meta- ms=meta['ms'];self.pear_status.setText(meta.get('bone_reset_warning') or f'Live tracking · {ms:.0f} ms/frame · {1000/max(ms,1):.1f} inference fps')+ ms=meta['ms'];extra=(f" · {meta['available_views']}/{meta['views']} views" if meta.get('views') else '')+ if meta.get('views') and not meta.get('aligned'):extra+=' · Camera Align required to combine views'+ if max(meta.get('foot_lock',{}).get('residual_mm',[0.]))>30:extra+=' · Foot lock limited by reach'+ self.pear_status.setText(meta.get('bone_reset_warning') or f'Live tracking · {ms:.0f} ms/frame · {1000/max(ms,1):.1f} inference fps'+extra)if meta.get('pair_video'):delay=max(0,(time.monotonic()-meta['requested_at'])*1000)self.pear_last_metrics['display_delay_ms']=delaydiff --git a/mocap/people_ui.py b/mocap/people_ui.pyindex d2470c2..31ff682 100644--- a/mocap/people_ui.py+++ b/mocap/people_ui.py@@ -285,6 +285,7 @@ class PeopleWorkspace:video.setMinimumWidth(260)movie_layout.addWidget(video,1)self.build_mamma_thumbnails(movie_layout)+ self.build_pear_thumbnails(movie_layout)footer = QWidget();footer.setObjectName('editorHeader')bar = QHBoxLayout(footer);bar.setContentsMargins(7,3,7,3)self.find_person_button = QPushButton('Find person')diff --git a/mocap/prompthmr_pipeline.py b/mocap/prompthmr_pipeline.pyindex 9610346..229ee2b 100644--- a/mocap/prompthmr_pipeline.py+++ b/mocap/prompthmr_pipeline.py@@ -62,7 +62,7 @@ def prepare(path,job):raise ValueError('Use a trim of 4–1,800 frames (at 30 fps) within the source video. No frames were dropped.')identity=dict(version=1,input=dict(path=job['video'],stat=file_stat(job['video'])),start=job['start'],frames=n,options=job['options'],models={k:file_stat(BY_KEY[k].path) for k in KEYS},runtime=cfg['managed_id'],engine=cfg['engine_files'],- code={'prompthmr_pipeline.py':sha256(ROOT/'mocap/prompthmr_pipeline.py')})+ code={name:sha256(ROOT/'mocap'/name) for name in ('prompthmr_pipeline.py','image_io.py')})token=hashlib.sha256(json.dumps(identity,sort_keys=True).encode()).hexdigest()[:24]work=job['root']/'prompthmr/inference'/token;cached=Falsetry:@@ -187,7 +187,10 @@ def _run(argv=None,engine=None):def main(argv=None,engine=None):- try:return _run(argv,engine)+ try:+ from .image_io import unicode_image_paths+ with unicode_image_paths():+ return _run(argv,engine)except Exception as error:import tracebacktraceback.print_exc()diff --git a/mocap/prompthmr_runtime.py b/mocap/prompthmr_runtime.pyindex 9f19bc0..7ca472c 100644--- a/mocap/prompthmr_runtime.py+++ b/mocap/prompthmr_runtime.py@@ -59,4 +59,4 @@ def activate():def command(stage,args):- return [configuration()['python'],'-I','-u',str(ROOT/'prompthmr_worker_boot.py'),stage,*map(str,args)]+ return [configuration()['python'],'-I','-X','utf8','-u',str(ROOT/'prompthmr_worker_boot.py'),stage,*map(str,args)]diff --git a/mocap/resource_cache.py b/mocap/resource_cache.pyindex 636403c..08233dd 100644--- a/mocap/resource_cache.py+++ b/mocap/resource_cache.py@@ -1,4 +1,4 @@-"""Cache aliases for the reviewed memory-policy-only transition.+"""Cache aliases for reviewed policy/logging-only changes.Match complete file bytes: later numerical edits automatically invalidate caches.Do not add aliases for changed inference algorithms or settings.@@ -19,6 +19,14 @@ POLICY_ONLY = {}+# UTF-8 log streams change no SAM features. Complete-byte matching means+# any subsequent numerical edit still invalidates the affected cache.+LOGGING_ONLY = {+ "db6fd57ca78c6dfab27142b9e99db207fcc1021933f1c4cfeb599c5fdad321ed": "c1abd10ec3143cfa7d7b97283a461fa858b73f55338cde7d7842cf030eff0b95",+ "141809da55236c2cbbf3f26f9e925362bcac6197d3883406347fa6b3ac7b7174": "319f211033a21d0fa1a83dd01a45676844df93cf95680e0d9fb7242883e3ba42"+}++def code_hash(path):actual=sha256(path)- return POLICY_ONLY.get(actual,actual)+ return LOGGING_ONLY.get(actual,POLICY_ONLY.get(actual,actual))diff --git a/mocap/retarget/blender_bake.py b/mocap/retarget/blender_bake.pyindex 75b71e3..383ce5c 100644--- a/mocap/retarget/blender_bake.py+++ b/mocap/retarget/blender_bake.py@@ -52,7 +52,7 @@ def bake(kind, label, method):rest = np.array([arm.matrix_world @ b.head_local for b in bones])R0 = np.array([rotation(np.array(arm.matrix_world @ b.matrix_local)[:3, :3]) for b in bones])parents = np.array([indices[b.parent.name] if b.parent else -1 for b in bones])- source_entry = next((e for e in json.loads(Path(io_path(OUT / 'sources.json')).read_text()) if e['label'] == label))+ source_entry = next((e for e in json.loads(Path(io_path(OUT / 'sources.json')).read_text(encoding='utf-8')) if e['label'] == label))folder = Path(source_entry['folder'])info = source_entry['info']source_frames = np.load(io_path(folder / info['frames_file']), mmap_mode='r')diff --git a/mocap/retarget/blender_entry.py b/mocap/retarget/blender_entry.pyindex 2fd3a8c..0f5874c 100644--- a/mocap/retarget/blender_entry.py+++ b/mocap/retarget/blender_entry.py@@ -4,6 +4,10 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[2]))+for stream in (sys.stdout, sys.stderr):+ if hasattr(stream, 'reconfigure'):+ stream.reconfigure(encoding='utf-8', errors='backslashreplace')+if __name__ == '__main__':from mocap.retarget.blender_io import mainmain(sys.argv[sys.argv.index('--')+1:])diff --git a/mocap/retarget/blender_io.py b/mocap/retarget/blender_io.pyindex 4a97505..5b77483 100644--- a/mocap/retarget/blender_io.py+++ b/mocap/retarget/blender_io.py@@ -132,7 +132,7 @@ def vertex_colors(obj):def preview(out,arm,keyed,n):from .selective_fbx import body_dependenciesmetadata=Path(io_path(out/'import.json'))- kind=json.loads(metadata.read_text())['kind'] if metadata.exists() else next(p.stem.split('-')[0] for p in Path(io_path(out)).glob('*-rig.json'))+ kind=json.loads(metadata.read_text(encoding='utf-8'))['kind'] if metadata.exists() else next(p.stem.split('-')[0] for p in Path(io_path(out)).glob('*-rig.json'))dynamic=set(keyed or [])|body_dependencies(kind,arm)if not keyed:dynamic={b.name for b in arm.data.bones}dynamic={name for name in dynamic if name in arm.data.bones}diff --git a/mocap/retarget/source.py b/mocap/retarget/source.pyindex 0ab7426..decf4d3 100644--- a/mocap/retarget/source.py+++ b/mocap/retarget/source.py@@ -88,7 +88,7 @@ def prepare(project,kind,out):raw._mmap.close()else:ep,_=smplx_endpoints(project,kind,n)- mi=json.loads((project/(kind+'_mesh.json')).read_text());ma=np.load(resolve_reference(project,mi['asset']));mf=np.load(project/mi['frames_file'],mmap_mode='r')+ mi=json.loads((project/(kind+'_mesh.json')).read_text(encoding='utf-8'));ma=np.load(resolve_reference(project,mi['asset']));mf=np.load(project/mi['frames_file'],mmap_mode='r')ids=[np.flatnonzero(weights[:,[7+s,10+s]].sum(1)>.7) for s in [0,1]]for i in range(n):v=reference_vertices(ma['packed'],mf[i],int(ma['vertex_count']))diff --git a/mocap/retarget/worker.py b/mocap/retarget/worker.pyindex 58601fc..ab162c4 100644--- a/mocap/retarget/worker.py+++ b/mocap/retarget/worker.py@@ -46,7 +46,7 @@ def main(args):else:from .source import prepare,stampfrom .pipeline import run- asset=Path(job['asset']);kind=json.loads((asset/'import.json').read_text())['kind'];takes=[]+ asset=Path(job['asset']);kind=json.loads((asset/'import.json').read_text(encoding='utf-8'))['kind'];takes=[]for i,take in enumerate(job['takes']):folder=out/f'take-{i}';folder.mkdir()report(f'Take {i+1}/{len(job["takes"])}: preparing selected source')diff --git a/mocap/runtime_registry.py b/mocap/runtime_registry.pyindex 842b7c4..97ed940 100644--- a/mocap/runtime_registry.py+++ b/mocap/runtime_registry.py@@ -39,10 +39,11 @@ def command(root,stage,args=(),*,frozen):python=root/base['folder']/'python.exe'if not (root/spec['folder']).is_dir() or not python.is_file():raise RuntimeError(key+' runtime is missing. Run Setup to repair this installation.')- return [str(python),'-I',str(root/'worker_boot.py'),stage,*map(str,args)]+ # Isolated mode ignores PYTHONIOENCODING/PYTHONUTF8 from the GUI.+ return [str(python),'-I','-X','utf8',str(root/'worker_boot.py'),stage,*map(str,args)]python=root/spec['dev']/'Scripts/python.exe'if not python.is_file(): raise RuntimeError(key+' development runtime is missing. Prepare its pinned environment.')- return [str(python),'-m','mocap.worker_progress',stage,*map(str,args)]+ return [str(python),'-X','utf8','-m','mocap.worker_progress',stage,*map(str,args)]def activate(root,key,base_root=None):"""Validate effective imports before loading model or CUDA modules."""diff --git a/mocap/scene_data.py b/mocap/scene_data.pyindex 0609ce0..e77fb28 100644--- a/mocap/scene_data.py+++ b/mocap/scene_data.py@@ -127,8 +127,8 @@ class PeopleScene:def prepare_camera_process(root,cancelled):from .paths import ROOT- if getattr(sys,'frozen',False) or __import__('os').environ.get('RGB_MOCAP_MANAGED') == '1':command=[str(ROOT/'runtime/python.exe'),'-I',str(ROOT/'scene_boot.py'),str(root)]- else:command=[sys.executable,'-m','mocap.scene_camera',str(root)]+ if getattr(sys,'frozen',False) or __import__('os').environ.get('RGB_MOCAP_MANAGED') == '1':command=[str(ROOT/'runtime/python.exe'),'-I','-X','utf8',str(ROOT/'scene_boot.py'),str(root)]+ else:command=[sys.executable,'-X','utf8','-m','mocap.scene_camera',str(root)]log=root/'.scene_camera.log'with log.open('wb') as output:child=subprocess.Popen(command,stdout=output,stderr=output,cwd=str(ROOT),diff --git a/mocap/viewer.py b/mocap/viewer.pyindex 73915f8..9f1c3f9 100644--- a/mocap/viewer.py+++ b/mocap/viewer.py@@ -25,6 +25,7 @@ class VideoView(QWidget):self.setMinimumSize(440, 280)cv2.setNumThreads(1) # Preview uses one decoder, not a pool for each resize.self.external_mode=False+ self.preview_rotation=0.self._external_saved=Noneself.frame = Noneself.boxes = self.observed = self.keypoints = self.confidence = None@@ -53,11 +54,18 @@ class VideoView(QWidget):def image_rect(self):"""One source-coordinate mapping for the image and every observation."""w, h = self.source_size+ angle=0. if self.external_mode else self.preview_rotation%360+ if angle:+ a=math.radians(angle);w,h=abs(w*math.cos(a))+abs(h*math.sin(a)),abs(w*math.sin(a))+abs(h*math.cos(a))scale = min(self.width() / w, self.height() / h) * self.zoomreturn QRectF((self.width() - w * scale) / 2 + self.pan.x(),(self.height() - h * scale) / 2 + self.pan.y(),w * scale, h * scale)+ def set_preview_rotation(self,angle):+ angle=float(angle)+ if angle!=self.preview_rotation:self.preview_rotation=angle;self.update()+def wheelEvent(self, event):if self.frame is None:event.ignore()@@ -225,7 +233,11 @@ class VideoView(QWidget):painter.drawText(self.rect(), Qt.AlignCenter, "Open a video to begin\nMP4 · MOV · AVI")returnrect = self.image_rect()- ratio = rect.width() / self.source_size[0]+ angle=0. if self.external_mode else self.preview_rotation%360+ if angle:+ w,h=self.source_size;a=math.radians(angle);ratio=rect.width()/(abs(w*math.cos(a))+abs(h*math.sin(a)))+ painter.translate(rect.center());painter.rotate(angle);rect=QRectF(-w*ratio/2,-h*ratio/2,w*ratio,h*ratio)+ else:ratio = rect.width() / self.source_size[0]offset_x, offset_y = rect.x(), rect.y()painter.drawImage(rect, self.frame)if self.show_observations and self.boxes is not None and self.index < len(self.boxes):diff --git a/mocap/viewport.py b/mocap/viewport.pyindex 7c53a75..96dfec9 100644--- a/mocap/viewport.py+++ b/mocap/viewport.py@@ -3,11 +3,12 @@ from __future__ import annotationsimport mathimport os+import timeimport zipfilefrom pathlib import Pathimport numpy as np-from PySide6.QtCore import Qt, QPointF, QRectF, QLineF, Signal+from PySide6.QtCore import Qt, QPointF, QRectF, QLineF, Signal, QTimerfrom PySide6.QtGui import QColor, QFont, QPainter, QPen, QPolygonF, QRadialGradient, QSurfaceFormatfrom PySide6.QtWidgets import QWidget,QLabelfrom PySide6.QtOpenGLWidgets import QOpenGLWidget@@ -68,6 +69,11 @@ class MotionView(ViewportBase):self.body_height = 1.7self.scene_center = np.zeros(3)self.drag_point = None+ self._camera_paint_at = 0.+ self._camera_update_timer = QTimer(self)+ self._camera_update_timer.setSingleShot(True)+ self._camera_update_timer.setTimerType(Qt.PreciseTimer)+ self._camera_update_timer.timeout.connect(self.update)self.auto_fit = Trueself.view_name = "Perspective"self.show_grid = True@@ -404,6 +410,22 @@ class MotionView(ViewportBase):def mouseReleaseEvent(self, event):self.drag_point = None+ if self._camera_update_timer.isActive():+ self._camera_update_timer.stop()+ self.update()++ def request_camera_update(self):+ # Keep every input delta, but submit only the latest camera per display+ # interval. A single timer bounds work without an idle render loop.+ screen = self.screen()+ rate = screen.refreshRate() if screen is not None else 60.+ rate = min(240., max(30., rate if math.isfinite(rate) and rate > 0 else 60.))+ remaining = 1. / rate - (time.monotonic() - self._camera_paint_at)+ if remaining <= 0:+ self._camera_update_timer.stop()+ self.update()+ elif not self._camera_update_timer.isActive():+ self._camera_update_timer.start(max(1, math.ceil(remaining * 1000)))def mouseMoveEvent(self, event):if self.drag_point is None:@@ -424,12 +446,12 @@ class MotionView(ViewportBase):self.pan += (-basis[0] * delta.x() + basis[1] * delta.y()) * scaleself.auto_fit = Falseself.drag_point = event.position()- self.update()+ self.request_camera_update()def wheelEvent(self, event):self.distance = np.clip(self.distance * math.exp(-event.angleDelta().y() / 120 * 0.12), 0.4, 80)self.auto_fit = False- self.update()+ self.request_camera_update()event.accept()def mouseDoubleClickEvent(self, event):@@ -441,6 +463,7 @@ class MotionView(ViewportBase):super().resizeEvent(event)def closeEvent(self, event):+ self._camera_update_timer.stop()self.set_motion(None)self.cleanup_gl()super().closeEvent(event)@@ -502,6 +525,7 @@ class MotionView(ViewportBase):return drawndef paintEvent(self,event):+ self._camera_paint_at = time.monotonic()if OPENGL_VIEW:super().paintEvent(event)else:diff --git a/mocap/worker_progress.py b/mocap/worker_progress.pyindex a2ac6d1..a167d1c 100644--- a/mocap/worker_progress.py+++ b/mocap/worker_progress.py@@ -12,6 +12,12 @@ def emit(kind,**value):def main():stage=sys.argv[1] if len(sys.argv)>1 else ''+ if stage=='pear_camera_preview':+ from .pear.camera_preview import main as camera_main+ return camera_main()+ if stage=='flow_pear_align':+ from .pear.align_worker import main as align_main+ return align_main()if stage=='pear_live':from .pear.worker import main as live_mainreturn live_main()diff --git a/mocap/workspace_ui.py b/mocap/workspace_ui.pyindex 04b250e..86dc87b 100644--- a/mocap/workspace_ui.py+++ b/mocap/workspace_ui.py@@ -376,9 +376,9 @@ def build_workspace(w):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_batch4=QCheckBox('Adaptive 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_batch4.setToolTip(tooltip_text('Automatic selects 1-16 frames from available VRAM/RAM and image size. Tests of 4 to 16 frames reduced warm SAM feature time by 16-23%, with allocated VRAM about 3.84 to 5.43 GiB. Low Memory and this option off use one frame. Small numerical motion differences are possible. Applies on Reconstruct 3D; whole-job gains vary.'))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)diff --git a/tools/build_release.py b/tools/build_release.pyindex db0e069..3b53ba8 100644--- a/tools/build_release.py+++ b/tools/build_release.py@@ -7,7 +7,7 @@ from build_setup import build as setupfrom build_character_runtime import discover as discover_blender,stage as stage_blenderdef source_resources():- rows=json.loads((ROOT/'installer/source-resources.json').read_text())['files']+ rows=json.loads((ROOT/'installer/source-resources.json').read_text(encoding='utf-8'))['files']allowed=set()for row in rows:path=(ROOT/row['path']).resolve()@@ -77,14 +77,14 @@ def main():source=(a.ffmpeg_dir/(name+'.exe')) if a.ffmpeg_dir else Path(shutil.which(name) or '')if not source.is_file():raise FileNotFoundError('Install FFmpeg and put ffmpeg/ffprobe on PATH, or use --ffmpeg-dir')shutil.copy2(source,video/(name+'.exe'))- commit=subprocess.run(['git','rev-parse','HEAD'],cwd=ROOT,capture_output=True,text=True)+ commit=subprocess.run(['git','rev-parse','HEAD'],cwd=ROOT,capture_output=True,text=True,encoding='utf-8',errors='replace')source_commit=commit.stdout.strip() if commit.returncode==0 else None- (app/'BUILD_INFO.json').write_text(json.dumps(dict(version=version,source_build=True,source_commit=source_commit,runtime_setup=True,models_bundled=False,character_runtime=character),indent=2))+ (app/'BUILD_INFO.json').write_text(json.dumps(dict(version=version,source_build=True,source_commit=source_commit,runtime_setup=True,models_bundled=False,character_runtime=character),indent=2), encoding='utf-8')manifest=[dict(path=f.relative_to(app).as_posix(),bytes=f.stat().st_size,sha256=sha(f)) for f in app.rglob('*') if f.is_file()]- (work/'application-manifest.json').write_text(json.dumps(dict(app=str(app),files=manifest),indent=2))+ (work/'application-manifest.json').write_text(json.dumps(dict(app=str(app),files=manifest),indent=2), encoding='utf-8')print('APP_READY',app,flush=True)if not a.app_only:report=setup(app,a.output,work/'setup',a.uv)- (work/'build-report.json').write_text(json.dumps(report,indent=2));print(json.dumps(report,indent=2))+ (work/'build-report.json').write_text(json.dumps(report,indent=2), encoding='utf-8');print(json.dumps(report,indent=2))if __name__=='__main__':main()diff --git a/tools/build_setup.py b/tools/build_setup.pyindex f288877..df3c991 100644--- a/tools/build_setup.py+++ b/tools/build_setup.py@@ -8,7 +8,7 @@ def build(app,output,work,uv=None):if not (app/'RGBMoCap.exe').is_file():raise FileNotFoundError('Build the GUI application first')cache_dependency_files(app)version=application_version()- if json.loads((app/'BUILD_INFO.json').read_text())['version']!=version:raise ValueError('Application and installer versions do not match')+ if json.loads((app/'BUILD_INFO.json').read_text(encoding='utf-8'))['version']!=version:raise ValueError('Application and installer versions do not match')lock=prepared_lock(work/'resources');uv=find_uv(uv)if lock['version']!=version:raise ValueError('Release metadata and runtime lock versions do not match')if sha(uv)!=lock['uv_sha256']:raise ValueError('Pinned uv helper hash mismatch')@@ -32,7 +32,7 @@ def build(app,output,work,uv=None):character_bytes=sum(row['bytes'] for row in manifest if row['path'].startswith('runtime_character/'))summary['installed_bytes_estimate']+=character_bytessummary['fresh_free_bytes_required']+=character_bytes*2- (work/'setup.json').write_text(json.dumps(summary))+ (work/'setup.json').write_text(json.dumps(summary), encoding='utf-8')compiler=Path('C:/Windows/Microsoft.NET/Framework64/v4.0.30319/csc.exe')if not compiler.is_file():raise FileNotFoundError('The Windows .NET Framework C# compiler is required')stub=work/'Setup.stub.exe'diff --git a/tools/check_source.py b/tools/check_source.pyindex bd911dd..0a35e8d 100644--- a/tools/check_source.py+++ b/tools/check_source.py@@ -12,8 +12,8 @@ def main():errors=[];count=0try:cache_dependency_files(ROOT)except (OSError,ValueError) as exc:errors.append(str(exc))- resources={r['path']:r for r in json.loads((ROOT/'installer/source-resources.json').read_text())['files']}- auxiliary={r['path']:r for r in json.loads((ROOT/'installer/external-assets.json').read_text())['files']}+ resources={r['path']:r for r in json.loads((ROOT/'installer/source-resources.json').read_text(encoding='utf-8'))['files']}+ auxiliary={r['path']:r for r in json.loads((ROOT/'installer/external-assets.json').read_text(encoding='utf-8'))['files']}def files():# Audit the publishable checkout, not ignored local runtime/model data.# Source ZIPs have no Git metadata and are scanned in full below.@@ -44,7 +44,7 @@ def main():except (SyntaxError,UnicodeError) as exc:errors.append(str(exc))for name in ['README.md','LICENSE','THIRD_PARTY_NOTICES.md','docs/USER_GUIDE.md','docs/BUILD.md','installer/runtime-lock.json','installer/external-assets.json']:if not (ROOT/name).is_file():errors.append('Missing '+name)- lock=json.loads((ROOT/'installer/runtime-lock.json').read_text())+ lock=json.loads((ROOT/'installer/runtime-lock.json').read_text(encoding='utf-8'))registry=ROOT/'mocap/runtime_registry.py'if not registry.is_file() or hashlib.sha256(registry.read_bytes()).hexdigest()!=lock.get('registry_sha256'):errors.append('Runtime registry differs from installer/runtime-lock.json. Review the registry change and update its locked hash before distributing.')diff --git a/tools/git_bootstrap.ps1 b/tools/git_bootstrap.ps1index 2751abb..d4ca1ea 100644--- a/tools/git_bootstrap.ps1+++ b/tools/git_bootstrap.ps1@@ -3,7 +3,7 @@ $root = Split-Path -Parent $PSScriptRoot$setup = Join-Path $root '.setup'$resources = Join-Path $setup 'bootstrap-git'New-Item -ItemType Directory -Force -Path $resources | Out-Null-$lock = Get-Content -LiteralPath (Join-Path $root 'installer/runtime-lock.json') -Raw | ConvertFrom-Json+$lock = Get-Content -LiteralPath (Join-Path $root 'installer/runtime-lock.json') -Encoding UTF8 -Raw | ConvertFrom-Json$uv = Join-Path $resources 'uv.exe'function Get-Sha256([string]$path) {$stream = [System.IO.File]::OpenRead($path)@@ -33,5 +33,5 @@ $env:PYTHONUTF8 = '1'& $uv python install 3.10.22 --install-dir $pythonDir --no-bin --no-registry --no-config --cache-dir $env:UV_CACHE_DIRif ($LASTEXITCODE -ne 0) { throw 'Private Python setup failed.' }$python = Join-Path $pythonDir 'cpython-3.10.22-windows-x86_64-none/python.exe'-& $python -I -B (Join-Path $root 'tools/git_managed_install.py') @args+& $python -I -X utf8 -B (Join-Path $root 'tools/git_managed_install.py') @argsexit $LASTEXITCODEdiff --git a/tools/setup_mamma.py b/tools/setup_mamma.pyindex 37097fa..7709edc 100644--- a/tools/setup_mamma.py+++ b/tools/setup_mamma.py@@ -122,7 +122,7 @@ def extract_source(archive_path,spec,destination):def setup(args):- lock=json.loads((ROOT/'installer/mamma-runtime-lock.json').read_text())+ lock=json.loads((ROOT/'installer/mamma-runtime-lock.json').read_text(encoding='utf-8'))uv=ROOT/'.setup/bootstrap-git/uv.exe'if not uv.is_file() or engine.sha(uv)!=lock['uv_sha256']:raise RuntimeError('Run install.cmd first to prepare the verified setup helper.')@@ -131,7 +131,7 @@ def setup(args):configuration=ROOT/'.setup/mamma-runtime.json'if configuration.is_file():try:- previous=json.loads(configuration.read_text())+ previous=json.loads(configuration.read_text(encoding='utf-8'))candidate=Path(previous['python']).parentif previous.get('managed_id')==tag and candidate.is_relative_to(ROOT/'runtime_mamma'):dest=candidate@@ -176,8 +176,8 @@ def setup(args):adapt_engine(sources/'mamma',ROOT/'installer/mamma_helpers')adapt_sdf(sources/'sdf')os.replace(sources/'mamma',stage/'engine')- cap=subprocess.run([str(py),'-I','-c',"import torch;assert torch.cuda.is_available();print('.'.join(map(str,torch.cuda.get_device_capability())))"],- capture_output=True,text=True,check=True,creationflags=0x08000000).stdout.strip()+ cap=subprocess.run([str(py),'-I','-X','utf8','-c',"import torch;assert torch.cuda.is_available();print('.'.join(map(str,torch.cuda.get_device_capability())))"],+ capture_output=True,text=True,encoding='utf-8',errors='replace',check=True,creationflags=0x08000000).stdout.strip()if not __import__('re').fullmatch(r'\d+\.\d+',cap):raise ValueError('Invalid CUDA architecture.')build=stage/'build-native.cmd'lines=['@echo off','setlocal DisableDelayedExpansion','chcp 65001 >nul','call '+quoted(vc),'if errorlevel 1 exit /b 1',@@ -215,9 +215,9 @@ def setup(args):def verify(folder,lock):report=folder/'verification.json'- run_step([folder/'python.exe','-I',ROOT/'installer/verify_mamma.py','--lock',ROOT/'installer/mamma-runtime-lock.json',+ run_step([folder/'python.exe','-I','-X','utf8',ROOT/'installer/verify_mamma.py','--lock',ROOT/'installer/mamma-runtime-lock.json','--output',report],ROOT,None,ROOT/'.setup/logs/mamma-verify.log')- return json.loads(report.read_text())+ return json.loads(report.read_text(encoding='utf-8'))if __name__=='__main__':diff --git a/tools/setup_pear.py b/tools/setup_pear.pyindex e765383..7fe84f1 100644--- a/tools/setup_pear.py+++ b/tools/setup_pear.py@@ -10,13 +10,14 @@ from tools.session_lock import app_lockdef prepare(cache=None):"""Called under the installer lock, after committing the shared base."""from tools.support_components import download- lock=json.loads((ROOT/'installer/pear-sources.json').read_text())+ lock=json.loads((ROOT/'installer/pear-sources.json').read_text(encoding='utf-8'))if not (ROOT/'runtime/python.exe').is_file():raise RuntimeError('Run install.cmd first.')try:current=configuration()except (OSError,ValueError,KeyError,TypeError):current=Noneif current is not None:print('Keeping verified PEAR support over the shared runtime.',flush=True)- return current+ from tools.setup_pear_alignment import prepare as prepare_alignment+ prepare_alignment(cache);return currentbase=base_identity()folder=ROOT/'runtime_pear'/('support-'+identity()[:20]+'-'+uuid.uuid4().hex[:8]);folder.mkdir(parents=True)cache=Path(cache) if cache else ROOT/'.setup/pear-downloads';cache.mkdir(parents=True,exist_ok=True)@@ -45,11 +46,12 @@ def prepare(cache=None):changes='Windows live-inference imports; shared runtime and pure-Python geometry constructor helpers. Original licenses retained.'))print('Verifying PEAR shared-runtime imports and CUDA kernels...',flush=True)code='import sys; sys.path[:0]='+repr([str(ROOT),str(folder/'packages'),str(folder/'engine')])+'; from mocap.runtime_registry import activate; activate('+repr(str(ROOT))+', "shared"); import torch, numpy, scipy, timm, cv2, roma; from pytorch3d.transforms import axis_angle_to_matrix; from torchvision.ops import nms; assert torch.cuda.is_available(), \"Compatible NVIDIA GPU required\"; x=torch.zeros((1,3),device=\"cuda\"); assert axis_angle_to_matrix(x).isfinite().all(); assert nms(torch.tensor([[0.,0.,1.,1.]],device=\"cuda\"),torch.ones(1,device=\"cuda\"),.5).numel()==1; print(\"PEAR CUDA verification passed\")'- subprocess.run([str(ROOT/'runtime/python.exe'),'-I','-B','-c',code],check=True,timeout=180)+ subprocess.run([str(ROOT/'runtime/python.exe'),'-I','-X','utf8','-B','-c',code],check=True,timeout=180)files={p.relative_to(folder).as_posix():[p.stat().st_size,p.stat().st_mtime_ns] for p in folder.rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc','.pyo')}atomic_json(ROOT/'.setup/pear-runtime.json',dict(version=2,identity=identity(),base_identity=base,folder=folder.relative_to(ROOT).as_posix(),files=files))print('PEAR support ready. Existing runtime packages, models and projects were not changed.',flush=True)- return folder+ from tools.setup_pear_alignment import prepare as prepare_alignment+ prepare_alignment(cache);return folderexcept Exception:# Keep failed staging for diagnosis; no previous configuration is overwritten.print('PEAR setup failed. Existing support generations were preserved.',flush=True);raisediff --git a/tools/setup_pear_alignment.py b/tools/setup_pear_alignment.pynew file mode 100644index 0000000..7ed9f64--- /dev/null+++ b/tools/setup_pear_alignment.py@@ -0,0 +1,35 @@+"""Download pinned GeoCalib/Kornia support; no pip install or shared-package changes."""+from pathlib import Path+import json,zipfile,stat,uuid,subprocess+from mocap.paths import ROOT+from mocap.storage import atomic_json+from mocap.pear.alignment_support import identity,configuration++def prepare(cache=None):+ from tools.support_components import download+ try:+ current=configuration();print('Keeping verified PEAR camera alignment support.',flush=True);return current+ except (OSError,ValueError,KeyError,TypeError):pass+ lock=json.loads((ROOT/'installer/pear-alignment.json').read_text('utf8'))+ cache=Path(cache) if cache else ROOT/'.setup/pear-downloads';cache.mkdir(parents=True,exist_ok=True)+ folder=ROOT/'runtime_pear'/('alignment-'+identity()[:16]+'-'+uuid.uuid4().hex[:8]);folder.mkdir(parents=True)+ for name,row in lock['sources'].items():+ print('Preparing PEAR camera alignment: '+name,flush=True)+ archive=download(cache,name,row)+ with zipfile.ZipFile(archive) as z:+ for info in z.infolist():+ p=Path(info.filename)+ if p.is_absolute() or '..' in p.parts or '\\' in info.filename or ':' in info.filename or stat.S_ISLNK(info.external_attr>>16):raise ValueError('Unsafe alignment archive')+ if info.file_size>128*1024**2:raise ValueError('Alignment support file too large')+ if info.is_dir() or '__pycache__' in p.parts or p.suffix in ('.pyc','.pyo'):continue+ if name=='geocalib':+ p=Path(*p.parts[1:])+ if not p.parts or (p.parts[0]!='geocalib' and p.name not in ('LICENSE','NOTICE','LICENSE-WEIGHTS')):continue+ if p.name in ('LICENSE','NOTICE','LICENSE-WEIGHTS'):p=Path('licenses/geocalib')/p+ target=folder/p;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(z.read(info))+ code='import sys;sys.path.insert(0,'+repr(str(ROOT))+');from mocap.runtime_registry import activate;activate('+repr(str(ROOT))+',"flow");sys.path.insert(0,'+repr(str(folder))+');import torch,kornia,kornia_rs;from geocalib import GeoCalib;assert kornia.__version__=="0.7.4";assert torch.cuda.is_available();print("PEAR camera alignment imports verified")'+ subprocess.run([str(ROOT/'runtime/python.exe'),'-I','-X','utf8','-B','-c',code],check=True,timeout=180)+ atomic_json(folder/'PROVENANCE.json',lock)+ files={p.relative_to(folder).as_posix():[p.stat().st_size,p.stat().st_mtime_ns] for p in folder.rglob('*') if p.is_file()}+ atomic_json(ROOT/'.setup/pear-alignment.json',dict(identity=identity(),folder=folder.relative_to(ROOT).as_posix(),files=files))+ print('PEAR camera alignment support ready; model weights remain separate.',flush=True);return folderdiff --git a/tools/setup_prompthmr.py b/tools/setup_prompthmr.pyindex 236aedd..2ec812b 100644--- a/tools/setup_prompthmr.py+++ b/tools/setup_prompthmr.py@@ -38,12 +38,12 @@ def run(command,log):def verify(folder):report=folder/'verification.json'- run([folder/'python.exe','-I',ROOT/'installer/verify_prompthmr.py','--lock',ROOT/'installer/prompthmr-runtime-lock.json','--output',report],ROOT/'.setup/logs/prompthmr-verify.log')+ run([folder/'python.exe','-I','-X','utf8',ROOT/'installer/verify_prompthmr.py','--lock',ROOT/'installer/prompthmr-runtime-lock.json','--output',report],ROOT/'.setup/logs/prompthmr-verify.log')return json.loads(report.read_text(encoding='utf8'))def setup():- lock=json.loads((ROOT/'installer/prompthmr-runtime-lock.json').read_text())+ lock=json.loads((ROOT/'installer/prompthmr-runtime-lock.json').read_text(encoding='utf-8'))uv=ROOT/'.setup/bootstrap-git/uv.exe'if not uv.is_file() or engine.sha(uv)!=lock['uv_sha256']:raise RuntimeError('Run install.cmd first.')with app_lock(ROOT):@@ -92,10 +92,10 @@ def setup():adapt_engine(sources/'prompthmr');os.replace(sources/'prompthmr',stage/'engine')install_python_source(sources/'detectron2',target,'detectron2')run([uv,'pip','install','--python',py,'--target',target,'--no-deps','--no-build-isolation','--no-index','--offline','--link-mode','copy',sources/'chumpy'],logs/'prompthmr-chumpy.log')- cap=subprocess.run([str(py),'-I','-c',"import torch;assert torch.cuda.is_available();print('.'.join(map(str,torch.cuda.get_device_capability())))"],capture_output=True,text=True,check=True,creationflags=0x08000000).stdout.strip()+ cap=subprocess.run([str(py),'-I','-X','utf8','-c',"import torch;assert torch.cuda.is_available();print('.'.join(map(str,torch.cuda.get_device_capability())))"],capture_output=True,text=True,encoding='utf-8',errors='replace',check=True,creationflags=0x08000000).stdout.strip()if not __import__('re').fullmatch(r'\d+\.\d+',cap):raise ValueError('Invalid CUDA architecture.')build=stage/'build-native.cmd'- lines=['@echo off','setlocal DisableDelayedExpansion','call '+quoted(vc),'if errorlevel 1 exit /b 1',+ lines=['@echo off','setlocal DisableDelayedExpansion','chcp 65001 >nul','call '+quoted(vc),'if errorlevel 1 exit /b 1','set "CUDA_HOME='+str(cuda).replace('%','%%')+'"','set "TORCH_CUDA_ARCH_LIST='+cap+'"','set "MAX_JOBS=2"','set "DISTUTILS_USE_SDK=1"','set "MSSdk=1"','set "FORCE_CUDA=1"','set "SAM2_BUILD_ALLOW_ERRORS=0"','set "SAM2_BUILD_CUDA=1"',' '.join(quoted(x) for x in [uv,'pip','install','--python',py,'--target',target,'--no-deps','--no-build-isolation','--no-index','--offline','--no-cache','--link-mode','copy',sources/'sam2']),'if errorlevel 1 exit /b 1','exit /b 0']diff --git a/tools/stage_assets.py b/tools/stage_assets.pyindex 0e7f2c6..4f2395e 100644--- a/tools/stage_assets.py+++ b/tools/stage_assets.py@@ -4,7 +4,7 @@ import argparse,json,shutil,urllib.requestfrom runtime_support import ROOT,shadef stage(source,dest,download=False):- source=Path(source).resolve() if source else None;dest=Path(dest).resolve();rows=json.loads((ROOT/'installer/external-assets.json').read_text())['files'];copied=[]+ source=Path(source).resolve() if source else None;dest=Path(dest).resolve();rows=json.loads((ROOT/'installer/external-assets.json').read_text(encoding='utf-8'))['files'];copied=[]for r in rows:target=dest/r['path'];original=(source/r['path']) if source else targetif not target.resolve().is_relative_to(dest) or (source and not original.resolve().is_relative_to(source)):raise ValueError('Auxiliary asset leaves its root')diff --git a/update.cmd b/update.cmdindex d9ad3bc..97aacc8 100644--- a/update.cmd+++ b/update.cmd@@ -1,12 +1,12 @@@echo off-setlocal+setlocal DisableDelayedExpansioncd /d "%~dp0"if not exist "runtime\python.exe" (echo Run install.cmd first.pauseexit /b 1)-"%~dp0runtime\python.exe" -I -B "%~dp0tools\git_update.py" %*+"%~dp0runtime\python.exe" -I -X utf8 -B "%~dp0tools\git_update.py" %*set "result=%ERRORLEVEL%"if not "%result%"=="0" echo Update stopped; review the message above.if "%~1"=="" pause