diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9425097e1b9e82e6d464828f283613e297aadb41 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# RoboHomeGen Public Asset Bundles + +This repository is the public RoboParty release of redistributable RoboHomeGen asset bundles and provenance. + +Large sources are delivered as `bundles/*.tar.zst` to keep the Git repository below file-count and single-commit limits. Each bundle has a `.sha256` sidecar. Extract a bundle into an empty directory and preserve the archive's top-level dataset directory. + +Included bundles are HSSD, ArtVIP, ReplicaCAD, Lightwheel, GSO, Poly Haven/YCB converted assets, HSSD public repair outputs, and the allowed MolmoSpaces extraction. `docs/reproduction/` contains download receipts, conversion code, RPLAN rebuild recipes, and release scope. + +The public release excludes InteriorAgent geometry and derived geometry, commercial interior Blender materials, kitchen upload materials of unclear provenance, Poliigon, PG Skies, NVIDIA MDL copies, and complete scenes whose embedded geometry or external materials are restricted. Those require independent downloads or internal access. + +Verify an archive before extraction: + +```bash +sha256sum -c bundles/.tar.zst.sha256 +tar --zstd -xf bundles/.tar.zst +``` + +The bundles are source/derived archives, not a replacement for the full main-branch runtime. Reproduction also needs the project code, indexes, runtime environment, and the source-specific licenses. diff --git a/bundles/README_PARTS.md b/bundles/README_PARTS.md new file mode 100644 index 0000000000000000000000000000000000000000..7444b95c61f8592502aaa99c3ca2014cdf2f57ee --- /dev/null +++ b/bundles/README_PARTS.md @@ -0,0 +1,14 @@ +# Split bundle files + +Three large archives are stored as 512 MiB parts so that downloads can run in parallel and remain below Hub single-file limits. Reassemble each archive in lexical order, then verify the resulting archive with its `.parts.sha256` manifest. + +```bash +cat bundles/hssd_derived_public.tar.zst.part-* > hssd_derived_public.tar.zst +sha256sum hssd_derived_public.tar.zst +cat bundles/hssd_original.tar.zst.part-* > hssd_original.tar.zst +sha256sum hssd_original.tar.zst +cat bundles/artvip_original.tar.zst.part-* > artvip_original.tar.zst +sha256sum artvip_original.tar.zst +``` + +The first line in each `.parts.sha256` file is the expected SHA-256 for the reconstructed archive. The later lines contain the per-part hashes. diff --git a/bundles/converted_public.tar.zst b/bundles/converted_public.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..b0565a1f1e4a2cd480ed21feec4d8ada1be32cfa --- /dev/null +++ b/bundles/converted_public.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e018622fb958ee98b13364e0892944d618b81a53a68f861ccd0ccf3028003f2 +size 10757089 diff --git a/bundles/converted_public.tar.zst.sha256 b/bundles/converted_public.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..e1030a9c821437aff38d386262f5b9bfb4f17c96 --- /dev/null +++ b/bundles/converted_public.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:902cc5e325f7c4128deb27be787f137943be6fd53c1bb83cf11e0673e8d9d644 +size 142 diff --git a/bundles/gso_derived_public.tar.zst b/bundles/gso_derived_public.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..c78cdb6db27b5482248882e8107b037471e58fe0 --- /dev/null +++ b/bundles/gso_derived_public.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7c6f37cb7159b930647cef61f611b65fbb82dc36dc73eff209064f57c6ee273 +size 11453865 diff --git a/bundles/gso_derived_public.tar.zst.sha256 b/bundles/gso_derived_public.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..24b59eb61d54ba7738614444e563ef4d115be4f6 --- /dev/null +++ b/bundles/gso_derived_public.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b0205e8adac0b1e452b584c58adf6385098c50d882f539a92dfb4070697066b +size 144 diff --git a/bundles/gso_original.tar.zst b/bundles/gso_original.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..ca9ca7f62cac59e6a69af81c5ac9ebe9e97f896b --- /dev/null +++ b/bundles/gso_original.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eeb6cb3cdc87b9f647e406f11e217fe4fb66242978bf8958e8b950fa5e5540df +size 11451772 diff --git a/bundles/gso_original.tar.zst.sha256 b/bundles/gso_original.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..3b6a186c658d26720778399a6d5107ced8b3c1f3 --- /dev/null +++ b/bundles/gso_original.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad6f445f9e4bd56a6edf6516c54364516efb8a4bb6c8e9d8eaf1c44c91ca50ae +size 138 diff --git a/bundles/hssd_metadata_fixed.tar.zst b/bundles/hssd_metadata_fixed.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..f2b235710f34f3e78c9841ee682fb3d032dc0dca --- /dev/null +++ b/bundles/hssd_metadata_fixed.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4248294578329e6bc97216c4fc782321f1d2e7032ec708ab608de9b88d52927d +size 546208773 diff --git a/bundles/hssd_metadata_fixed.tar.zst.sha256 b/bundles/hssd_metadata_fixed.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..0994f102ce6bf5868fb201b07c573fd1963e67ea --- /dev/null +++ b/bundles/hssd_metadata_fixed.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c17423492e17f5f618dd823f940e901f9e67d6d3dbf55fade9619c473f4b502 +size 145 diff --git a/bundles/hssd_original_variants.tar.zst b/bundles/hssd_original_variants.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..f9ab7d10d85031ccc7a540d03a6d9409f8747d3f --- /dev/null +++ b/bundles/hssd_original_variants.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52c04ad61a8852f7d6cdb2cc5c7beabba0e50a2ec964454ff9e2326a9f67f2b7 +size 300862512 diff --git a/bundles/hssd_original_variants.tar.zst.sha256 b/bundles/hssd_original_variants.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..120a9ce457ab411325b578594e38c53d897aa5b7 --- /dev/null +++ b/bundles/hssd_original_variants.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d41d7f7c9678f3e10230fee87c28db825aa5b3c0874f66a927aecbfb047ebde9 +size 148 diff --git a/bundles/lightwheel_original.tar.zst b/bundles/lightwheel_original.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..3f9fdde91c5088e5318992df027964847240ae12 --- /dev/null +++ b/bundles/lightwheel_original.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5187a073a6a515b76b2a4dc6b5bc30f2ba60f9b27667ecbb58783f18a65db8d4 +size 236439581 diff --git a/bundles/lightwheel_original.tar.zst.sha256 b/bundles/lightwheel_original.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..9a53542a487449c4aec95a2537e94c8cf2352bc2 --- /dev/null +++ b/bundles/lightwheel_original.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:095d2025fd6d06d52c2f8e2719738c9ab9c8603a687a3f430a86b264f2ce2126 +size 145 diff --git a/bundles/molmospaces_extracted.tar.zst b/bundles/molmospaces_extracted.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..870aab48d8c0fe97393283587c273f02371496d4 --- /dev/null +++ b/bundles/molmospaces_extracted.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2af763aedc69ad5bad2f3f0da7b91c3de07cab304e5bc2329e32149646055184 +size 831422559 diff --git a/bundles/molmospaces_extracted.tar.zst.sha256 b/bundles/molmospaces_extracted.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..9bf5b01990c60a0470b41ee3d25e8dbf273ed446 --- /dev/null +++ b/bundles/molmospaces_extracted.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7079c1156781f5aeb0d393719e1c8d340c82b5844467dffe24326a59b269db7d +size 147 diff --git a/bundles/polyhaven_original.tar.zst b/bundles/polyhaven_original.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..a0cae9d9060a3fe6330a3f75d8379ae4892a1612 --- /dev/null +++ b/bundles/polyhaven_original.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1c2532d2766aa6ca57f952a617cbdfc73aa9cfd0a43786715a5d13d8d31f799 +size 18491217 diff --git a/bundles/polyhaven_original.tar.zst.sha256 b/bundles/polyhaven_original.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..4903f39b4fa10238f8bc92def172567128f0826d --- /dev/null +++ b/bundles/polyhaven_original.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b52e15e2540f9d9d74325ad87c1eaa5b39e8d7cccf2287d4a832046b0104d97 +size 144 diff --git a/bundles/replicacad_original.tar.zst b/bundles/replicacad_original.tar.zst new file mode 100644 index 0000000000000000000000000000000000000000..ea943e18fc171a966597d7e12238969a2c4ef324 --- /dev/null +++ b/bundles/replicacad_original.tar.zst @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2dc4f25c2a068527ab32f5ec29d3d6062c32eb0b890525a9a625973edcdc7144 +size 11420075 diff --git a/bundles/replicacad_original.tar.zst.sha256 b/bundles/replicacad_original.tar.zst.sha256 new file mode 100644 index 0000000000000000000000000000000000000000..d45275b80554f56eacb0cb91b02658372dfb1a21 --- /dev/null +++ b/bundles/replicacad_original.tar.zst.sha256 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:616b1d2ed458b19f11207f6e4ccc8826ec902153d77408ec42f7b88e25066a99 +size 145 diff --git a/docs/reproduction/asset_release_plan/hf_upload_manifest.tsv b/docs/reproduction/asset_release_plan/hf_upload_manifest.tsv new file mode 100644 index 0000000000000000000000000000000000000000..4996c6c71ed25decdade9df28db6883b83721b3d --- /dev/null +++ b/docs/reproduction/asset_release_plan/hf_upload_manifest.tsv @@ -0,0 +1,17 @@ +class bundle_id repository content canonical_source format conversion_or_materialization license_or_access action status +code main-code ORG/robohomegen candidate19 code, runner, adapter, score scripts, release docs local rphome_scripts + RP-RoboHavenGen Python/JSON/MD remove caches, logs, backups, secrets; preserve source hashes project-owned GitHub + HF metadata prepared +index main-retrieval-index ORG/robohomegen-assets-private full_matrix_reviewed_compatibility.sqlite3; annotation_index.sqlite3; prepared pool indexes H200-1 scene_evidence_repair_20261103; current_vs_v31_20261031 SQLite copy bytes; emit sha256 and SQLite schema report project-owned, paths may reference restricted sources HF private manifest required +metadata main-annotation-release ORG/robohomegen-assets-private records.jsonl, front audit, furniture usability, style attributes, provenance H200-1/NAS zhf annotation trees JSONL/JSON/CSV no geometry conversion; normalize paths in sidecar only project-owned; may contain third-party identifiers HF private license review required +inputs cases20-rebuild ORG/robohomegen-reproduction cases20_public.json, recipes_cases20.json, rebuild script local release_prep/cases20_floorplans JSON/Python publish identifiers and recipes; rebuild RPLAN-derived geometry locally; do not include rooms.json RPLAN/Graph2Plan non-redistribution HF public metadata + source download ready +public-assets hssd ORG/robohomegen-public-assets HSSD original download receipt, selected public files, repaired-file manifest H200-2 public_assets_20261115; NAS public source GLB/URDF/JSON BasisU decode/repair only in derived namespace; keep original immutable HSSD CC BY-NC 4.0; verify terms HF public if allowed; repaired subset only license check +public-assets artvip ORG/robohomegen-public-assets ArtVIP source and conversion receipts H20-96-2 public_assets_20261115 USD/texture/JSON preserve USD relative references; no flattening ArtVIP repository terms HF public if license permits license check +public-assets interioragent ORG/robohomegen-public-assets download receipt and non-restricted metadata only H20-96-3 public_assets_20261115 USD/texture/JSON preserve Materials/Textures/Meshes tree; do not upload geometry without redistribution permission InteriorAgent terms prohibit redistribution HF metadata only; private internal copy blocked by license +public-assets molmospaces ORG/robohomegen-public-assets download receipt, unpack script, metadata and allowed derived files H20-96-1 public_assets_20261115 USD/USDA/TAR/JSON unpack tar/zst into canonical tree; preserve archive member map ODC-By/CC BY; verify exact dataset terms HF public if license permits license check +public-assets replicacad ORG/robohomegen-public-assets ReplicaCAD download receipt and converted metadata H20-96-4 public_assets_20261115 GLB/URDF/JSON no geometry conversion beyond source package format ReplicaCAD terms HF public if license permits prepared +public-assets gso-ycb-polyhaven ORG/robohomegen-public-assets download receipts, source archives, converted USD and manifests H20-96-4/H200-1 public_assets_20261115 ZIP/GLB/USD/HDR/JSON GSO/Poly Haven canonical preprocessing; YCB author conversion; keep raw and derived namespaces per-dataset licenses HF public if allowed license check +public-assets lightwheel ORG/robohomegen-public-assets download receipt, 378-file MD5 index, unpacked USD H200-1 public_assets_20261115 USD/JSON ZIP extraction only; source USD unchanged Lightwheel CC BY-NC 4.0 HF public if allowed license check +derived main-repaired-assets ORG/robohomegen-assets-private HSSD repaired GLB, Molmo extracted USD, USD path repairs, prepared indexes NAS zhf/rhg_asset_audit_20261013_v1 and rhg_asset_repair_20261013_v2 GLB/USD/JSON/SQLite BasisU decode, archive extraction, absolute-to-release path repair; every derived file gets source hash and recipe project-derived; underlying licenses apply HF private needs provenance bundle +materials mdl-offline ORG/robohomegen-assets-private material acceptance indexes, prepared libraries, bake cache, normal_dx_to_gl NAS zhf/rhg_style_joint_20261013; H200-1 caches BLEND/EXR/PNG/JSON MDL compile/distill/bake; DX-to-GL normal conversion; native graphs preserved mixed; NVIDIA/InteriorAgent restrictions HF private only where permitted; otherwise internal download recipe license split +nonpublic main-scenes ORG/robohomegen-scenes-private 55 candidate19 scene packages and manifests H20-96-1 candidate19_replay_20261115_1647 BLEND/JSON no scene-format conversion; materialize external dependencies or ship dependency manifest contains restricted geometry/materials HF private only after rights review prepare private mirror +links main-link-map ORG/robohomegen-assets-private all project symlink records with target hashes and target class H200-1 nas_mirror and asset_library JSONL materialize project-owned targets; retain original link path in symlinks.jsonl; never upload dangling links alone project-owned or third-party dependent HF private manifest prepared +restricted commercial-materials ORG/robohomegen-internal interior Blender materials, kitchen PBR, Poliigon, PG Skies, NVIDIA MDL copies NAS zhf/rp_robohavengen and rhg_style_joint_20261013 BLEND/MDL/HDR/TEXTURE no conversion for archive; public replacement would require new validation commercial / restricted internal private storage; no public HF blocked diff --git "a/docs/reproduction/asset_release_plan/\344\270\273\345\210\206\346\224\257\350\265\204\344\272\247\347\261\273\345\210\253\344\270\216\350\256\272\346\226\207\346\225\260\345\255\227\345\257\271\347\205\247_20261121.md" "b/docs/reproduction/asset_release_plan/\344\270\273\345\210\206\346\224\257\350\265\204\344\272\247\347\261\273\345\210\253\344\270\216\350\256\272\346\226\207\346\225\260\345\255\227\345\257\271\347\205\247_20261121.md" new file mode 100644 index 0000000000000000000000000000000000000000..b6d751ce6dd6a870f6fe9fe6c78dadd7b759bb06 --- /dev/null +++ "b/docs/reproduction/asset_release_plan/\344\270\273\345\210\206\346\224\257\350\265\204\344\272\247\347\261\273\345\210\253\344\270\216\350\256\272\346\226\207\346\225\260\345\255\227\345\257\271\347\205\247_20261121.md" @@ -0,0 +1,147 @@ +# 主分支资产类别与论文数字对照 + +核对日期:2026-11-21。对照对象: + +- 已提交正文 / `CVPR2027/RoboHome_tasks_restored_8page_under50MB.pdf` +- 待提交附录 / `CVPR2027/RoboHome_supplementary.pdf` +- 主分支检索库:H200-1 `/data/tutu/robohomegen/scene_evidence_repair_20261103/full_matrix_reviewed_compatibility.sqlite3` + +## 结论 + +论文与索引数字**不是同一层级,不能直接逐项相等比较**: + +| 论文 / 实际数字 | 数量 | 口径 | +|---|---:|---| +| 论文:Multi-source assets | 120K+ | 原始多源资产库 / 数据集规模,论文附录 Table S3 的构建漏斗入口 | +| 论文:Materials | 3,728 | 室内 Blender 材质库条目;与索引中的 `interior_blender_20261009` 3,728 条一致 | +| 论文:Usable models after repair and pre-screening | 23,221 | 修复和预筛后的模型漏斗中间层,不是当前 SQLite 的全部 descriptor 行 | +| 论文:Runtime-qualified assets | 19,795 | 运行时资格门之后的资产集,不是当前 SQLite 的全部 descriptor 行 | +| 主分支 SQLite:`asset_descriptors` | **37,279** | 主分支检索描述条目,含对象、材质、片段、房间/整场景、灯光等混合类型 | +| 主分支 SQLite:唯一 `asset_id` | **37,279** | 当前表中每个 asset_id 一行;不等于 37,279 个可下载几何文件 | +| 主分支外部物理闭包 | **约 324 GiB** | 原件、修复件、索引/缓存、主分支场景的磁盘闭包,不是论文资产数量 | + +因此:**120K+ 是原始资产来源规模,23,221/19,795 是构建漏斗数字,37,279 是主分支兼容性检索索引,324 GiB 是磁盘占用。** 这四个数字不应放在同一列互相替代。 + +当前附录 PDF 的来源文字只列 HSSD、Objaverse 1.0、ArtVIP、ReplicaCAD、YCB 和 3,728 materials;项目实际主分支 SQLite 还包含 InteriorAgent、MolmoSpaces、Lightwheel、Poly Haven、GSO、ambientCG 等来源。若附录要解释主分支检索库,应补一句“the compatibility index contains additional derived and auxiliary sources”并给出完整 source table。 + +## 来源分布:37,279 条 descriptor + +| `asset_descriptors.source` | 条目 | +|---|---:| +| HSSD | 18,228 | +| InteriorAgent | 6,174 | +| molmospaces | 5,841 | +| interior_blender_20261009 | 3,728 | +| ArtVIP | 2,152 | +| MolmoSpaces | 502 | +| Lightwheel SimReady | 378 | +| ReplicaCAD | 185 | +| Poly Haven | 45 | +| GoogleResearch on Gazebo Fuel | 24 | +| ambientCG | 17 | +| 空值/其他 | 5 | +| **合计** | **37,279** | + +大小方面,主分支逻辑闭包约 **324 GiB**:公开原件 43.4 GiB、受限原件 45.1 GiB、项目衍生件 131.5 GiB、索引/标注/缓存 42.9 GiB、主分支运行目录 61.4 GiB。这里的 43.4 GiB 是资产原件分类总量,不是 37,279 条 descriptor 的逐条文件大小之和;修复件、重复副本和缓存必须单独计量。 + +## 类别分布:主分支检索索引 + +下面是 `asset_descriptors.category` 的原始类别计数。类别是检索/资格标签,不是把每个条目都视为独立最终家具实例。 + +### 家具与大件 + +| 类别 | 条目 | 主要含义 | +|---|---:|---| +| cabinet | 1,578 | 柜体、通用柜 | +| shelf | 1,511 | 架子/搁板 | +| bed | 572 | 床 | +| armchair | 568 | 扶手椅 | +| sofa | 533 | 沙发 | +| desk | 464 | 书桌/工作桌 | +| stool | 433 | 凳子 | +| wardrobe | 403 | 衣柜 | +| mirror | 364 | 镜子 | +| dresser | 362 | 斗柜 | +| table | 343 | 通用桌 | +| coffee_table | 289 | 茶几 | +| bookcase | 271 | 书柜 | +| dining_table | 240 | 餐桌 | +| dining_chair | 233 | 餐椅 | +| chair | 219 | 通用椅 | +| kitchen_counter | 186 | 厨房台面/柜体 | +| toilet | 162 | 马桶 | +| bench | 155 | 长凳 | +| desk_chair | 143 | 工作椅 | +| planter | 142 | 花盆 | +| kitchen_sink | 125 | 厨房水槽 | +| oven | 124 | 烤箱/炉具类别 | +| shower | 100 | 淋浴 | +| bathtub | 91 | 浴缸 | + +### 家电与冰箱 + +主分支索引中 `category=refrigerator` 有 **308 条 descriptor**;这 308 条的 `asset_id` 和 `canonical_path` 当前都是一对一,因此在索引口径下也是 308 个唯一来源路径条目。它们不是 308 个已经同时摆入论文场景的实例。按来源分布如下: + +| 来源 | refrigerator 条目 | 备注 | +|---|---:|---| +| HSSD | 97 | GLB/URDF 及 HSSD 修复路径 | +| molmospaces | 90 | 原始/派生命名空间,常见 `thor_Fridge_*` | +| ArtVIP | 51 | USD/ArtVIP articulated 资产及组件型记录 | +| MolmoSpaces | 30 | 归档或解包后的另一种 source 标记;与小写 `molmospaces` 不是简单相加的唯一模型数 | +| Lightwheel SimReady | 26 | `Refrigerator031`–`Refrigerator057` 等 USD/修复 USD | +| InteriorAgent | 10 | `kujiale_*/Meshes/fridge_0000.usd` | +| ReplicaCAD | 4 | ReplicaCAD fridge 资产 | +| **索引行合计** | **308** | 也是 308 个唯一 `asset_id` / `canonical_path`,但不是场景实例数 | + +冰箱的可复现来源路径示例: + +```text +HSSD -> assets/high_quality/hssd-hab/{objects,urdf}/... +InteriorAgent -> assets/high_quality/InteriorAgent/kujiale_*/Meshes/fridge_0000.usd +MolmoSpaces -> repairs/molmo_extracted//Fridge_*/.usda +Lightwheel -> repairs/usd_dependency_paths/.usdc +ArtVIP -> ArtVIP/ +ReplicaCAD -> ReplicaCAD/{glb,urdf}/... +``` + +### 桌、椅、灯、楼梯和其他场景物件 + +| 族 | 主要类别 | 计数 | +|---|---|---:| +| 桌类 | `table` 343、`side_table` 700、`coffee_table` 289、`dining_table` 240、`console_table` 29、`bar_table` 8、`vanity_table` 12、`mobile_worktable` 2、`changing_table` 1 | **约 1,624**(不含 `table_lamp`) | +| 椅类 | `armchair` 568、`chair` 219、`dining_chair` 233、`desk_chair` 143,另有 lounge/wheelchair 等 | **1,165**(包含细分类别) | +| 灯具 | `ceiling_light` 656、`table_lamp` 304、`floor_lamp` 277、`wall_light` 134、`light` 21、`lamp` 14 | **1,406**(灯光相关类别) | +| 植物 | `plant` 719、`planter` 142 | **861** | +| 楼梯 | `stair` | **32** HSSD 条目;另有 1 条 Poly Haven 名称中含 stair 的记录 | +| 卫浴 | `toilet` 162、`bathroom_sink` 363、`kitchen_sink` 125、`shower` 100、`bathtub` 91 | 类别可重叠于功能契约,不应简单视为可互换资产 | +| 厨房 | `kitchen_counter` 186、`oven` 124、`cooktop` 41、`range_hood` 81、`dishwasher` 12、`microwave` 103 | 还包含从来源描述归一化到 `small_appliance` 的条目 | + +`table`/`chair`/`lamp` 等是类别族统计,不是论文中“一个场景里实际摆了多少张桌子/椅子”。论文的 120K+、23,221、19,795 也不是这些细分类别之和。 + +## 与当前正文/附录的对照结论 + +| 论文写法 | 与实际是否一致 | 说明 | +|---|---|---| +| 120K+ multi-source assets | **口径可成立** | 应解释为原始多源资产库规模,而不是当前 compatibility SQLite 的行数 | +| 3,728 materials | **一致** | 对应 `interior_blender_20261009` 材质条目 | +| 23,221 usable models | **需注明阶段** | 是修复/预筛漏斗中间层,不是 37,279 descriptor 数 | +| 19,795 runtime-qualified assets | **需注明阶段** | 是运行时资格层;当前索引仍包含不同类型、来源和派生记录 | +| 37,279 compatible assets | **一致但需定义** | 应写成 “37,279 compatibility-index entries/descriptors”,不要写成 37,279 个原始几何文件 | +| 46,910 assets | **当前正文/附录 PDF 未见该表述** | 如果后续草稿出现,应先说明它对应哪个漏斗阶段;当前可核实的主分支索引是 37,279 | +| 324 GiB asset closure | **论文未报告** | 这是服务器发布/复现清点量,不是论文数据集规模 | +| HSSD/Objaverse/ArtVIP/ReplicaCAD/YCB | **论文来源摘要不完整** | 主分支 compatibility index 还包含 InteriorAgent、MolmoSpaces、Lightwheel、Poly Haven、GSO、ambientCG;附录可补完整 source table | + +## 建议补充文字 + +```text +The asset counts in this supplement refer to different stages of the asset +funnel. The 120K+ figure denotes the raw multi-source asset pool. After repair +and pre-screening, 23,221 usable models remained, of which 19,795 passed the +runtime qualification gate. The main-branch compatibility index contains +37,279 indexed descriptors, including object, material, fragment, room/scene, +and lighting records from HSSD, InteriorAgent, MolmoSpaces, ArtVIP, Lightwheel, +ReplicaCAD, Poly Haven, GSO, YCB, ambientCG, and the indoor material library. +These are index entries rather than 37,279 unique downloadable geometry files. +``` + +若论文需要给出类别实例数,应把它标成“主分支 compatibility-index category counts”,不要把 308 个 refrigerator descriptor、1,624 个 table-like descriptor 或 1,165 个 chair-related descriptor写成数据集中实际摆放的物体数。 diff --git "a/docs/reproduction/asset_release_plan/\350\265\204\344\272\247\345\274\200\346\272\220\344\270\216\345\244\215\347\216\260\345\207\206\345\244\207_\344\270\273\345\210\206\346\224\257_20261121.html" "b/docs/reproduction/asset_release_plan/\350\265\204\344\272\247\345\274\200\346\272\220\344\270\216\345\244\215\347\216\260\345\207\206\345\244\207_\344\270\273\345\210\206\346\224\257_20261121.html" new file mode 100644 index 0000000000000000000000000000000000000000..4e44ab30bee37579cbd4bdfcdb922027c436c8bc --- /dev/null +++ "b/docs/reproduction/asset_release_plan/\350\265\204\344\272\247\345\274\200\346\272\220\344\270\216\345\244\215\347\216\260\345\207\206\345\244\207_\344\270\273\345\210\206\346\224\257_20261121.html" @@ -0,0 +1,80 @@ + +RoboHomeGen 主分支资产开源与复现准备 +
+
ROBOHOMEGEN · MAIN BRANCH RELEASE PREPARATION

主分支资产开源、复现准备与服务器清点

打印 / 导出 PDF

清点日期:2026-11-21(Asia/Shanghai)。范围:candidate19 / config-F / replay-20261115-1647。

+
范围声明:本文件只保留论文最终主分支。1110、1113、residential replay、消融、去包络 200 次运行均为清理候选,不进入发布树;本次没有删除或移动远程数据。HF token 尚未提供,因此没有执行上传。
+

1. 资产分布

主机关键目录作用
H200-1/data/RPHomeGen/candidate19_replay_20261115_1647/
/data/tutu/robohomegen/scene_evidence_repair_20261103/
/data/RPHomeGen/nas_mirror/
主代码运行副本、37,279 条检索/外观索引、NAS 本地镜像、prepared pool 和 runtime 闭包。
H200-2/data/zhf/rparen_eval_ws/wholehouse_generation_20261023_fusion/inputs/runtime_data/
/data/RPHomeGen/public_assets_20261115/
运行时副本、basisu、来源清单、公开资产下载控制目录。
H20-96-1/data/RPHomeGen/candidate19_replay_20261115_1647/tree/engine/runs/60 次主分支 case,55 个场景包。
NAS/mnt/nas-h/zhf/rp_robohavengen/asset_library/
/mnt/nas-h/zhf/rhg_asset_audit_20261013_v1/
/mnt/nas-h/zhf/rhg_style_joint_20261013/
公开数据入口、非公开材质/厨房/HDRI、HSSD/Molmo 修复、MDL/material acceptance。
+

当前只读探测:H200-1 可用约 1.2 TiB,H200-2 约 559 GiB,H20-96-1 约 1.3 TiB。NAS 11-19 清单记录约剩 6 TiB;NAS 本次未通过 SSH alias 重新探测。

+

2. 主分支 tree

candidate19_replay_20261115_1647/
+├── tree/                         # 生成器源码、engine、tools
+│   ├── scene_workflow.py
+│   ├── engine/
+│   ├── tools/
+│   └── source_manifest.json      # 冻结源码 SHA256
+├── attribute_index_cache/        # 可重建缓存
+├── registration.json
+└── README.md
+
+scene_evidence_repair_20261103/
+├── full_matrix_reviewed_compatibility.sqlite3  # 37,279 descriptors
+├── front_probe/published/.../records.jsonl     # 属性发布记录
+└── final-source-hashes.json
+
+rebuild_current_pool_v2/
+├── full/prepared_assets.sqlite3       # 309 candidates
+├── supplement/prepared_assets.sqlite3  # 102 candidates
+└── ready.json
+
+nas_mirror/
+├── RPHome -> /data/RPHome
+├── zhf/rp_robohavengen/asset_library/
+├── zhf/rhg_asset_audit_20261013_v1/
+├── zhf/rhg_asset_repair_20261013_v2/
+└── zhf/rhg_style_joint_20261013/
+

3. 公开资产 tree 与转换

asset-bundles/
+├── hssd/
+│   ├── original/              # 原始 GLB/URDF
+│   ├── derived/basis-decode/  # BasisU 解码/修复 GLB
+│   └── manifests/             # source/derived hash + repair recipe
+├── artvip/
+│   ├── original/              # USD / Materials / Textures
+│   └── manifests/
+├── interioragent/
+│   ├── original/              # 内部保存,公开版不含几何
+│   └── manifests/             # 下载和许可信息
+├── molmospaces/
+│   ├── archives/              # tar / tar.zst
+│   ├── unpacked/              # USD/USDA 展开件
+│   └── manifests/archive_members.jsonl
+├── gso/ polyhaven/ ycb/
+│   ├── original/
+│   ├── canonical/usd/
+│   └── manifests/
+├── lightwheel/
+│   ├── original/usd/
+│   └── manifests/md5.jsonl
+└── replicacad/
+    ├── original/{glb,urdf}/
+    └── manifests/
+
数据转换项目内脚本 / 说明
HSSD原始 GLB 保留;BasisU 解码、GLB/JSON 修复件独立命名并绑定源 hash。rphome_scripts/asset_downloads_20261115/control/downloader.py、HSSD control manifests、NAS repairs。
MolmoSpacestar/tar.zst 解包;生成 archive-member 映射;部分 USD 做依赖路径修复。rphome_scripts/asset_downloads_20261115/conversion_reference/README.md;rhg_asset_audit_20261013_v1/repairs/。
GSO / Poly Havenraw 不改;生成 canonical USD、材质/纹理索引、preprocess plan 和 validation manifest。rphome_scripts/matrix/rph_readme_asset_conversion.py;conversion_reference/scripts/preprocess_high_fidelity_assets.py。
YCB / ReplicaCAD / Lightwheel按来源控制文件转换或解包;Lightwheel 原生 USD 不改,保留 378 项 MD5。public_assets_20261115/control/ 及对应日志。
RPLAN不上传房间几何;只上传 case 编号、recipes、重建脚本,用户自行下载 Graph2Plan Data.zip。release_prep/cases20_floorplans/rebuild_cases20_floorplans.py;scene_018 有独立重转换。
MDL / 材质MDL distill/bake;DX→GL 法线转换;native graph 保持;所有结果写 acceptance manifest。rphome_scripts/asset_downloads_20261115/conversion_reference/docs/official-mdl-pipeline.md。
+

4. 非公开资产与软链接规则

restricted-internal/
+├── interior_blender_materials/
+├── kitchen_upload/ + pbr_upload_20261005/
+├── poliigon_supplement/
+├── sky_collection_20261004/
+├── interioragent_derived/
+├── nvidia_mdl/
+├── main-scenes/
+└── link-map/symlinks.jsonl

项目自有软链接:上传实体 target + symlinks.jsonl(link_path、target_path、target_sha256、class)。第三方软链接:不上传 dangling link,发布来源 URL、版本、hash、许可和重建脚本。HF Git/LFS 不被当作跨主机软链接系统。

+

5. Hugging Face 仓库规划

仓库内容访问
ORG/robohomegen-public-assets许可允许的公开原件、转换件、下载收据、manifest、NOTICE。public dataset
ORG/robohomegen-reproduction代码侧 manifest、cases20 rebuild、下载/转换脚本、环境说明。public dataset / code companion
ORG/robohomegen-assets-private索引、标注、修复件、软链接 map、项目自有硬资产。private dataset
ORG/robohomegen-scenes-private主分支场景和外链依赖,仅在权利允许时使用。private dataset
许可证边界:“私有 HF”不是许可证豁免。InteriorAgent、商业材质、PG Skies、Poliigon、NVIDIA 受限材料不能因为有 token 就上传;这些仓库只能放 metadata、link-map、版本和下载/转换说明。项目自有索引和修复件可以放私有仓库。

每个仓库统一:

repo/
+├── README.md  LICENSE  NOTICE/
+├── manifests/{asset_manifest.jsonl,symlinks.jsonl,source_revisions.json,sha256sums.txt}
+├── datasets/<dataset>/{original,derived/<recipe_id>}/
+├── indexes/<name>/
+├── converters/<dataset>/
+└── configs/

当前未上传。拿到 token 后先创建 private/public repo,再用 manifest 分批上传,上传前执行许可证扫描、密钥扫描、SHA256 校验和 SQLite 路径闭包检查。

+

6. 主分支最小复现路径

  1. 下载代码、reproduction manifest 和公开数据;用户自行获得 RPLAN/Graph2Plan。
  2. 按 recipes 重建 20 个输入和户型,并验证 hash。
  3. 恢复公开索引、prepared pool 和运行时模板。
  4. 若要复现论文主分支的原始资产选择,再获得 private assets、annotation release、MDL acceptance 和 link-map。
  5. 受限资产缺失时只能称为公开资产路径复现;不能称为主分支字节级复现。
+

7. 当前附件

Markdown 版本 · HF 上传 manifest · 2026-11-19 原始清点底稿。

+
diff --git "a/docs/reproduction/asset_release_plan/\350\265\204\344\272\247\345\274\200\346\272\220\344\270\216\345\244\215\347\216\260\345\207\206\345\244\207_\344\270\273\345\210\206\346\224\257_20261121.md" "b/docs/reproduction/asset_release_plan/\350\265\204\344\272\247\345\274\200\346\272\220\344\270\216\345\244\215\347\216\260\345\207\206\345\244\207_\344\270\273\345\210\206\346\224\257_20261121.md" new file mode 100644 index 0000000000000000000000000000000000000000..32a55a4ae99070c1a218ff1546754dac868595aa --- /dev/null +++ "b/docs/reproduction/asset_release_plan/\350\265\204\344\272\247\345\274\200\346\272\220\344\270\216\345\244\215\347\216\260\345\207\206\345\244\207_\344\270\273\345\210\206\346\224\257_20261121.md" @@ -0,0 +1,290 @@ +# RoboHomeGen 主分支资产清点、复现准备与 Hugging Face 发布计划 + +清点日期:2026-11-21(Asia/Shanghai)。本文件只保留论文最终使用的主分支: + +- `candidate19 replay` +- 标签:`robohomegen__candidate19-20261112__config-F__replay-20261115-1647` +- 60 次生成尝试,55 个保存场景 + +1110、1113、`residential_replay_20261115_1705`、三个消融、去包络 200 次等都不进入主分支发布树,只保留为服务器清理候选。原始资产没有删除、移动或覆盖;本次只做只读清点和发布规划。 + +## 先看总量 + +这里区分“主分支逻辑资产闭包”和“服务器物理副本”。副本之间有大量重复,不能把所有服务器数字直接相加。 + +### 主分支逻辑资产闭包:约 324 GiB + +| 类别 | 大小 | 包含内容 | +|---|---:|---| +| 公开数据集原件 | **43.4 GiB** | HSSD、ArtVIP、InteriorAgent、Lightwheel、MolmoSpaces、ReplicaCAD、YCB、GSO、Poly Haven、ambientCG | +| 非公开/受限原件 | **45.1 GiB** | 室内 Blender 材质库、厨房模型与 PBR、商业材质、PG Skies HDRI | +| 项目衍生件 | **131.5 GiB** | HSSD/Molmo/USD 修复件、MDL 烘焙件、prepared_D、下载解包/转换件 | +| 索引、标注、prepared pool、artifact/法线缓存 | **42.9 GiB** | 37,279 条检索矩阵、属性发布记录、家具审计、资产池、artifact cache、normal_dx_to_gl | +| 主分支 60 次运行目录 | **61.4 GiB** | 55 个保存场景及 5 个失败尝试的运行记录 | +| **逻辑闭包合计** | **约 324 GiB** | 2026-11-19 `du` 清点 | + +### 当前主要物理副本 + +| 位置 | 大小 | 与上表关系 | +|---|---:|---| +| H20-96-1 candidate19 场景 | **62 GiB** | 主分支场景目录,已计入闭包 | +| H200-1 `/data/RPHomeGen/nas_mirror` | **约 271 GiB** | NAS 资产镜像,包含公开、受限和衍生副本 | +| H200-1 candidate19 运行副本 | **329 MiB** | 代码树、manifest、attribute cache | +| H200-2 `public_assets_20261115` | **约 12 GiB** | 下载控制目录和部分公开资产;大目录当前是 NAS 软链接 | +| H200-1 主分支槽位缓存 | **约 85 GiB** | 可重建缓存,部分材质/法线文件被场景外链引用 | + +### 发布量预估 + +- 公开/可再分发包:预计 **70–90 GiB**。 +- 项目自有私有索引、标注、修复件和 link-map:预计 **40–70 GiB**。 +- 受限内部资产与完整主分支场景:约 **113 GiB 以上**。 +- 这些是发布包估算,不与 324 GiB 再相加;最终 HF 大小以实际 LFS 对象和 `sha256sums.txt` 为准。 + +## 结论 + +1. 主分支不是一个自包含的 62 GB 场景目录。`.blend` 中含部分导入后的几何,但贴图、材质库、HDRI、MDL 产物、索引和 SQLite 中仍有外部绝对路径。 +2. 主分支的复现闭包分布在 H200-1、H200-2、H20-96-1、NAS 四处;H200-1 的 `/data/RPHomeGen/nas_mirror` 是 NAS 资产的本地镜像,不是独立的公开发行包。 +3. 公开数据可下载,但“下载原始数据”不能自动得到主分支使用的修复件、索引和 prepared pool。主分支检索库约 37,279 条描述,其中约 17,727 条指向修复/转换产物。 +4. 后续 HF 发布应采用三个层次: + - **公开仓库**:代码、复现脚本、下载收据、允许再分发的公开资产和索引。 + - **私有仓库**:项目自有索引、标注、修复件、软链接映射和在许可允许时的主分支场景。 + - **不可上传目录**:InteriorAgent、商业材质、PG Skies、Poliigon、NVIDIA 受限材料等只发布下载说明、版本和校验方法。 + +用户要求“非公开资产也上传 HF”可以落地为 **私有 HF 仓库**,但不能绕过原始数据集许可;私有仓库也不自动获得再分发权。当前没有 HF token,本次没有执行任何上传。 + +## 服务器分布 + +| 主机 | 主分支相关位置 | 当前用途 | +|---|---|---| +| H200-1 / `zp-nc67` | `/data/RPHomeGen/candidate19_replay_20261115_1647/` | candidate19 运行副本:`tree/`、`source_manifest.json`、`attribute_index_cache/` | +| H200-1 | `/data/tutu/robohomegen/scene_evidence_repair_20261103/` | 37,279 条检索/外观 SQLite、front probe、发布记录 | +| H200-1 | `/data/tutu/robohomegen/current_vs_v31_20261031/rebuild_current_pool_v2/` | prepared pool:full 309、supplement 102 | +| H200-1 | `/data/tutu/wholehouse_taskinput_20261028_v26/portable_inputs/bundle/rootfs/` | 便携 rootfs 与运行输入 | +| H200-1 | `/data/zhf/wholehouse_input_cache/` | runtime template 与 blobs | +| H200-1 | `/data/RPHomeGen/nas_mirror/` | NAS 的本地镜像,约 271 GiB;通过软链接/路径兼容主线依赖 | +| H200-1 | `/data/RPHomeGen/public_assets_20261115/` | 公开数据下载、转换控制文件;当前目录约 12 GiB,`archives`、`conversion_inputs`、`derived` 是指向 NAS 的软链接 | +| H200-2 / `zp-nc68` | `/data/zhf/rparen_eval_ws/wholehouse_generation_20261023_fusion/inputs/runtime_data/` | runtime_data、basisu、来源清单、运行时副本 | +| H200-2 | `/data/zhf/rhg_rplan_expansion_20261013/` | RPLAN 派生转换记录和 source receipts | +| H20-96-1 | `/data/RPHomeGen/candidate19_replay_20261115_1647/tree/engine/runs/` | 主分支 60 个 case 目录,55 个包含最终 `.blend` | +| NAS `/mnt/nas-h` | `/mnt/nas-h/zhf/rp_robohavengen/asset_library/` | 主资产库:公开资产软链、非公开材质、厨房模型、HDRI、注册表 | +| NAS | `/mnt/nas-h/zhf/rhg_asset_audit_20261013_v1/`、`rhg_asset_repair_20261013_v2/` | HSSD、MolmoSpaces、USD 路径修复及来源审计 | +| NAS | `/mnt/nas-h/zhf/rhg_style_joint_20261013/` | MDL SDK、material acceptance、prepared_D、bake cache、材质库 | + +当前只读核对的磁盘状态:H200-1 `/data` 约 1.2 TiB 可用,H200-2 约 559 GiB 可用,H20-96-1 约 1.3 TiB 可用。H200-2 和 H200-1 的大目录存在 `tutu` 专属临时目录,普通用户 `du` 会出现权限错误;发布前应由目录所有者生成最终清单。 + +## 主分支运行闭包 + +```text +candidate19_replay_20261115_1647/ +├── tree/ +│ ├── scene_workflow.py +│ ├── engine/ # 主生成器源码 +│ ├── tools/ # 路径迁移、验证、辅助工具 +│ └── source_manifest.json # 冻结源码哈希 +├── attribute_index_cache/ # 可重建缓存;不作为唯一发布依赖 +├── registration.json +├── README.md +└── runner.log + +/data/tutu/robohomegen/scene_evidence_repair_20261103/ +├── full_matrix_reviewed_compatibility.sqlite3 # 37,279 descriptors +├── front_probe/published/.../records.jsonl # 专家属性发布记录 +├── compatibility-publication.json +└── final-source-hashes.json + +/data/tutu/robohomegen/current_vs_v31_20261031/rebuild_current_pool_v2/ +├── full/prepared_assets.sqlite3 # 309 candidates +├── supplement/prepared_assets.sqlite3 # 102 candidates +└── ready.json + +/data/RPHomeGen/nas_mirror/ +├── RPHome -> /data/RPHome # 项目路径兼容链接 +├── zhf/rp_robohavengen/asset_library/ # 公开资产 + 非公开材质的注册树 +├── zhf/rhg_asset_audit_20261013_v1/ # audit / repairs / molmo_extracted +├── zhf/rhg_asset_repair_20261013_v2/ # 二次修复、variants、plants +├── zhf/rhg_style_joint_20261013/ # MDL / material acceptance / bake cache +└── zhf/h200_1_organized_20261120/ # 迁移整理副本 +``` + +## 公开资产与格式转换 + +### HSSD + +```text +public_assets_20261115/ +├── assets/high_quality/hssd-hab/ # 原始下载快照(Hugging Face) +├── control/ +│ ├── hssd.files.json +│ ├── hssd.verified.jsonl +│ ├── hssd_models_priority.files.json +│ └── hssd.status.json +├── conversion_code/ # 下载/校验/转换控制脚本 +└── derived/ # HSSD 修复/解码产物,当前多为 NAS 软链接 +``` + +主线需要的 HSSD 条目包含原始 GLB/URDF、BasisU 解码后可读 GLB、JSON 元数据修复件和来源哈希。公开版必须同时保留 `source_sha256`、`derived_sha256`、修复原因和脚本版本。修复后的 GLB 不是原始文件,不能覆盖原始文件名。 + +### ArtVIP / InteriorAgent / MolmoSpaces + +```text +asset-bundles/ +├── artvip/ +│ ├── original/ # USD、Textures、Materials、相对引用 +│ ├── manifests/ # 下载、SHA256、license +│ └── derived/ # 仅项目自有路径修复 +├── interioragent/ +│ ├── original/ # 只在内部保存 +│ ├── manifests/ # 可公开元数据与下载说明 +│ └── derived/ # 不公开几何/材质派生件 +└── molmospaces/ + ├── archives/ # tar / tar.zst 原始包 + ├── unpacked/ # 按归档成员展开的 USD + ├── manifests/archive_members.jsonl + └── derived/path-repaired/ +``` + +MolmoSpaces 做的是归档解包和 USD 依赖路径修复;InteriorAgent 做的是 Materials/Textures/Meshes 相对路径保持和必要的路径派生。InteriorAgent 条款禁止通过其他媒介再分发下载数据,因此只能上传索引、版本、来源、转换脚本和内部私有清单,不能把几何打进公共 HF 仓库。 + +### GSO / Poly Haven / YCB / Lightwheel / ReplicaCAD + +```text +asset-bundles/ +├── gso/ +│ ├── original/archives/*.zip +│ ├── canonical/usd/*.usdc +│ └── manifests/{source,conversion,validation}.jsonl +├── polyhaven/ +│ ├── original/{models,materials,hdri}/ +│ ├── canonical/usd/ +│ └── manifests/ +├── ycb/ +│ ├── original/{obj,texture}/ +│ ├── canonical/usd/ +│ └── manifests/ +├── lightwheel/ +│ ├── original/usd/ +│ └── manifests/md5.jsonl +└── replicacad/ + ├── original/{glb,urdf}/ + └── manifests/ +``` + +转换记录: + +| 来源 | 实际转换 | 脚本位置 | +|---|---|---| +| GSO / Poly Haven | 保留 raw;通过项目的 high-fidelity preprocessing 生成 canonical USD、材质/纹理索引和验证 manifest;不改 raw | `rphome_scripts/asset_downloads_20261115/conversion_reference/scripts/preprocess_high_fidelity_assets.py`(说明入口:同目录 `README.md`);主控:`rphome_scripts/matrix/rph_readme_asset_conversion.py` | +| YCB | 从作者模型转换为项目使用的 USD 表示,保留来源文件与作者哈希 | `rphome_scripts/asset_downloads_20261115/control/prepare_archives.py` 与对应控制日志 | +| Lightwheel | ZIP 解包;原生 USD 不改写;用 378 项 MD5 清单验收 | `rphome_scripts/asset_downloads_20261115/control/downloader.py` | +| MolmoSpaces | tar/tar.zst 解包;成员映射写入 archive manifest;部分 USD 依赖路径修复 | `rphome_scripts/asset_downloads_20261115/conversion_reference/README.md`;修复记录在 `rhg_asset_audit_20261013_v1/repairs/` | +| HSSD | BasisU 解码/GLB 修复/JSON 元数据修复;原始 GLB 保留 | 下载与修复回执:`public_assets_20261115/control/hssd.*`;主线派生件在 `rhg_asset_audit_20261013_v1/repairs/` | +| RPLAN | 不是资产上传;只发布 case 编号、recipes 和重建脚本,用户自行下载 Graph2Plan `Data.zip` | `release_prep/cases20_floorplans/rebuild_cases20_floorplans.py`;分组 A/B/C 与 scene_018 双版本见其 README | +| MDL / 材质 | MDL SDK distill/bake;法线贴图做 DX→GL 转换;native graph 保持不变;写入 acceptance manifest | `rphome_scripts/asset_downloads_20261115/conversion_reference/docs/official-mdl-pipeline.md`;`rphome_scripts/matrix/rph_readme_asset_conversion.py` | + +## 非公开资产组织形式 + +```text +restricted-internal/ +├── interior_blender_materials/ # 38.87G,非公开材质库 +├── kitchen_upload/ # 厨房模型 +├── pbr_upload_20261005/ # 厨房 PBR +├── poliigon_supplement/ # 商业材质 +├── sky_collection_20261004/ # PG Skies HDRI +├── interioragent_derived/ # InteriorAgent 派生 USD / variants / bake +├── nvidia_mdl/ # NVIDIA MDL / IsaacSim 材质副本 +├── main-scenes/ # 55 个主分支场景与外链依赖 +└── link-map/ + ├── symlinks.jsonl # 原始 link_path、target_path、target_sha256、class + └── materialized_targets/ # 项目自有目标的实体文件 +``` + +软链接发布规则: + +1. 对项目自有目标:上传实体目标文件,并额外上传 `symlinks.jsonl` 还原原始逻辑路径。 +2. 对第三方目标:不上传 dangling symlink;上传 link record、原始来源 URL、版本、SHA256、许可和重建脚本。 +3. HF Git/LFS 不应被当作跨主机软链接存储。发布树必须能在干净机器解包后独立校验;软链接只作为 provenance,不作为唯一数据载体。 +4. 主分支 `.blend` 若引用了受限纹理/材质,不能放入公共仓库。公共版提供 manifest、渲染图、场景实体清单和重建脚本;私有版在权利允许时才放完整 `.blend` 与依赖。 + +## Hugging Face 发布组织 + +建议使用以下仓库,而不是把所有东西塞进一个仓库: + +```text +ORG/robohomegen-public-assets/ # public, only redistributable data and receipts +ORG/robohomegen-reproduction/ # public, code-side manifests, cases20 rebuild, converters +ORG/robohomegen-assets-private/ # private, project-owned indexes, annotations, repairs, link maps +ORG/robohomegen-scenes-private/ # private, if rights permit; otherwise internal NAS only +``` + +每个仓库顶层建议统一为: + +```text +repo/ +├── README.md +├── LICENSE +├── NOTICE/ +├── manifests/ +│ ├── asset_manifest.jsonl +│ ├── symlinks.jsonl +│ ├── source_revisions.json +│ └── sha256sums.txt +├── datasets//original/ +├── datasets//derived// +├── indexes// +├── converters// +├── configs/ +└── docs/ +``` + +HF 上传必须保留:原始来源、版本/commit、文件 SHA256、格式、单位、坐标系、转换 recipe、转换脚本相对路径、许可和是否被主分支实际引用。HF LFS 用于大文件;SQLite、JSONL 和 manifest 应保持可直接 diff 的小文件形式。 + +当前阶段只生成上传清单,没有 HF token,因此**没有执行上传**。拿到 token 后按以下顺序: + +```bash +# 仅示例;先确认 repo 权限和许可证,再执行 +huggingface-cli repo create ORG/robohomegen-public-assets --type dataset +git clone https://huggingface.co/datasets/ORG/robohomegen-public-assets +rsync -a --delete --exclude='*.tmp' prepared_release/public-assets/ repo/datasets/ +sha256sum -c manifests/sha256sums.txt +git lfs install && git add . && git commit -m "release public assets and provenance" && git push +``` + +私有仓库采用相同 tree,但额外保留 `access.md` 和每个第三方数据集的许可证明。即使拥有 HF token,也不能上传被原始条款禁止再分发的 InteriorAgent、商业材质或 NVIDIA 受限文件。 + +## 不应纳入主分支发布集的目录 + +只作为服务器清理候选,不进入上面的 tree: + +- H20-96-1:`scenes_nas_restored_20261115_080049`(1110)、`production_residential_20261113_run_20261115_1810`(1113)、`residential_replay_20261115_1705`。 +- H200-1:`backups/rhg_before_stable_replay_20261115_163637`、旧 `experiments/multiroom*`、旧分支渲染和试跑目录。 +- H200-2 / H20-96-1:消融运行树、去包络 200 次运行、消融渲染 staging。 + +这些目录尚未删除,清理前仍需确认没有线程、评测或论文附件引用。 + +## 复现者最小路径 + +### 公开路径 + +1. 克隆代码。 +2. 从 `ORG/robohomegen-reproduction` 获取 `cases20_public.json`、`recipes_cases20.json` 和 conversion scripts。 +3. 用户自行下载 Graph2Plan/RPLAN、HSSD、ArtVIP、ReplicaCAD 等公开数据,按下载 manifest 校验。 +4. 运行转换脚本生成 canonical USD/GLB 和本地索引。 +5. 用公开可复现的 index 和 `COMPARISON_CONFIG.json` 生成 1 个 case。 + +### 完整内部路径 + +1. 额外获得 `robohomegen-assets-private` 和内部 link-map。 +2. 将 `/mnt/nas-h` 逻辑前缀映射为本地 release root,或运行 SQLite 路径重写器。 +3. 安装 Blender 5.2.1、Python 3.11/Isaac Lab runtime、MDL SDK 2026.0.2 和材质 acceptance 库。 +4. 恢复 `full_matrix_reviewed_compatibility.sqlite3`、prepared pool、annotation release、rootfs 与 runtime blobs。 +5. 运行主线 candidate19 的固定输入和 seed;保留 `source_manifest.json`、所有 manifest、link map、conversion receipts。 + +完整复现需要非公开资产或替代材质时,结果只能称为“代码路径复现”或“公开资产复现”,不能声称与论文主分支字节级一致。 + +## 当前已生成的附件 + +- `hf_upload_manifest.tsv`:按 bundle 列出的 HF 上传清单、许可证类别、转换和状态。 +- 本 Markdown:服务器位置、tree、复现闭包、格式转换和 HF 组织方案。 +- `资产开源与复现准备_主分支_20261121.html`:适合浏览和后续打印的 HTML 版本。 +- `主分支资产类别与论文数字对照_20261121.md`:论文正文/附录数字、SQLite 来源分布、家具类别和冰箱来源的逐项对照。 + diff --git a/docs/reproduction/cases20_floorplans/README.md b/docs/reproduction/cases20_floorplans/README.md new file mode 100644 index 0000000000000000000000000000000000000000..08d4eebcd75ba84811848f3584a441861296932e --- /dev/null +++ b/docs/reproduction/cases20_floorplans/README.md @@ -0,0 +1,74 @@ +# Rebuilding the 20 RoboHome benchmark floor plans + +The multi-room benchmark uses 20 floor plans taken from RPLAN (Wu et al., SIGGRAPH Asia 2019). RPLAN may only be used for non-commercial research and may not be redistributed, in whole or in part. This release therefore contains **no room geometry**. It contains only: + +| File | Content | +|---|---| +| `recipes_cases20.json` | For each case: the Graph2Plan record name, the conversion method and parameters, the millimetre residuals of the five hand-adjusted plans, and the sha256 values a rebuild must reproduce | +| `cases20_public.json` | The 20 case texts: request, entity list, seeds and target area, without rooms | +| `rebuild_cases20_floorplans.py` | Rebuilds the plans and the shared per-case inputs from your own copy of the data, then checks every hash | + +## What you need + +1. **Graph2Plan's `Data.zip`.** Download it from the authors' release at https://github.com/HanHan55/Graph2plan/releases/download/data/Data.zip and accept the RPLAN/Graph2Plan terms. + - Archive sha256: `e88f1c52eb065a4441f9675f6f5401e3e46add4b3ae6ad96f63fb527b6958cd3` + - The script reads the member `Network/data.mat`, sha256 `ce1e9c7fc2846c2d5a36485c8fa4d16df9b7de0ccda31581fe76fc2fa6f28adc`. +2. **The RoboHome code tree**, which provides `tools/rplan/` and the scene-generation engine. +3. **Optional: the October 2026 snapshot of the v16.1p scene-generation helpers** (`--legacy-generator`). Without it, everything is still checked except the doors and windows of the 14 group-B libraries. +4. **Python 3.10 or newer** with numpy, scipy and shapely. Pillow is optional and only used for `floorplan.png`. + +## Run + +```bash +python3 rebuild_cases20_floorplans.py --graph2plan Data.zip --robohome-tree /path/to/robohome \ + [--legacy-generator /path/to/legacy_v16_1p_20261013] --out rebuilt/ +``` + +The script takes about 10 s and writes: + +- `rebuilt/ext_libs/x_.json`: one single-plan library per case. RoboHome reads it through `RHG_RPLAN_SEEDS`; it is each job's `plan_library`. +- `rebuilt/inputs/cases20//{request.txt, entities.json, rooms.json, floorplan.svg, floorplan.png, case.json}` and `rebuilt/inputs/cases20.json`: the inputs every method receives. +- `rebuilt/verification.json`: one entry per check. The script exits with status 1 if a required check fails. + +## Conversion groups + +| Group | Cases | Method | +|---|---|---| +| A | scene_000–004 | The five original plans. Room boxes are the exclusive source boxes, shifted to the house corner and scaled by the recorded factor. The living room is split 34 % / 66 % on the recorded side. The published residuals then restore the hand adjustments (minimum bathroom and balcony sizes, dining widths) exactly. | +| B | scene_005–017, scene_019 | October conversion: source boxes, scaled to 90 m² (longest side at most 14.8 m), living room split 34 % / 66 % on the recorded side. | +| C | scene_018 | Re-converted with `tools/rplan/convert_rplan.py` and screened with `tools/rplan/screen_library.py`, using the recorded options. | + +Doors, windows and the room topology of groups A and B come from the generator's `add_plan_topology`. RoboHome recomputes doors and windows from the rooms whenever it builds a scene, so the benchmark depends on the rooms. + +- **Group B:** reproduces the doors and windows of the original files exactly only with the October snapshot. +- **Group A:** the original doors and windows came from an older code version and are not reproduced. Their `plan_sha256` therefore leaves out the topology keys. + +**scene_018 uses two versions of record 26376.** + +- The shared input (`rooms.json`, `floorplan.svg/png`, used by every baseline) keeps the October conversion. +- RoboHome reads the re-converted library `x_26376.json`, because the October plan was dropped for a door defect. + +The script rebuilds both versions and checks each against its own hash. + +## Hashes + +`canonical(x)` means `json.dumps(x, sort_keys=True, ensure_ascii=False, separators=(",", ":"))`, encoded as UTF-8. + +| Hash | Covers | +|---|---| +| `rooms_sha256` | `canonical(plan["rooms"])` | +| `plan_core_sha256` | The plan without the provenance keys (`rplan_source_png`, `rplan_source_file`, `local_fallback_seed_manifest`) and without the topology keys (`topology_adjacencies`, `doors`, `windows`, `wall_generation`, `window_rules`) | +| `plan_sha256` | The plan without the provenance keys; for group A, also without the topology keys | + +The provenance keys only record where a file was made; the generator does not read them. The rebuilt files carry neutral strings there. + +Input files (`rooms.json`, `request.txt`, `entities.json`, `floorplan.svg`, `floorplan.png`) are compared byte for byte. A PNG mismatch is only a warning, because PNG encoding depends on the Pillow and zlib versions. + +**Tested** with Python 3.10.12, numpy 2.2.6, scipy 1.15.3, shapely 2.1.2 and Pillow 12.3.0: + +- With `--legacy-generator`: all 141 checks pass. +- Without it: 127 pass and 14 are skipped. + +## Terms + +The rebuilt files contain RPLAN-derived geometry and fall under the RPLAN and Graph2Plan terms. Use them for non-commercial research only and do not redistribute them. Cite RPLAN (Wu et al., ACM TOG 38(6), 2019) and Graph2Plan (Hu et al., ACM TOG 39(4), 2020) together with RoboHome. diff --git a/docs/reproduction/cases20_floorplans/cases20_public.json b/docs/reproduction/cases20_floorplans/cases20_public.json new file mode 100644 index 0000000000000000000000000000000000000000..434c8ad71c8f2b8d630ea3c54c51a96fd4280475 --- /dev/null +++ b/docs/reproduction/cases20_floorplans/cases20_public.json @@ -0,0 +1,1751 @@ +{ + "schema": "robohome.cases20_public.v1", + "note": "The 20 shared inputs without room geometry. Rooms are rebuilt from the Graph2Plan release by rebuild_cases20_floorplans.py.", + "source_manifest": { + "name": "cases_oct50.json", + "sha256": "e73c65bd6dec990f5fb7115b6f42468edaf9b9cdd8c5b5011b48de5d27b3ac3e", + "first_n": 20 + }, + "cases": [ + { + "id": "scene_000", + "k": 0, + "seed": 2026101600, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 81 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "fcbc4a808a181841d2f2d18c0057881e5720e1e037040c48fd21fa0e35005970", + "floor_plan_id": "rplan_constrained_45966_scene_010_v16_task_contract", + "rplan_index": 0, + "target_floor_area_m2": 81, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_45966.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_001", + "k": 1, + "seed": 2026101601, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 83 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "16a6487bd2ab701d7980bf21be073c80261e7c491b7098ca9c88e74ff4ce9e22", + "floor_plan_id": "rplan_constrained_78215_scene_011_v16_task_contract", + "rplan_index": 1, + "target_floor_area_m2": 83, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_78215.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_002", + "k": 2, + "seed": 2026101602, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 95 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "15f81f4fd2b50b288a238129cd505bda724d3640b2eca710a3a2864e98300d8d", + "floor_plan_id": "rplan_constrained_44500_scene_002_v16_task_contract", + "rplan_index": 2, + "target_floor_area_m2": 95, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_44500.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_003", + "k": 3, + "seed": 2026101603, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 86 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "98171012a4f1a6aec530925e3e22b515dff8a796797fbfb396bb31871fb8837d", + "floor_plan_id": "rplan_constrained_24777_scene_003_v16_task_contract", + "rplan_index": 3, + "target_floor_area_m2": 86, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_24777.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_004", + "k": 4, + "seed": 2026101604, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 88 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "3aa3ad025ff7677fad3f04ac1e5072917c647e2a9b86c114bd5ee407881e3cd9", + "floor_plan_id": "rplan_constrained_42920_scene_009_v16_task_contract", + "rplan_index": 4, + "target_floor_area_m2": 88, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_42920.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_005", + "k": 5, + "seed": 2026101605, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_44838", + "rplan_index": 5, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_44838.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_006", + "k": 6, + "seed": 2026101606, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_65877", + "rplan_index": 6, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_65877.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_007", + "k": 7, + "seed": 2026101607, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_66696", + "rplan_index": 7, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_66696.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_008", + "k": 8, + "seed": 2026101608, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_71597", + "rplan_index": 8, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_71597.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_009", + "k": 9, + "seed": 2026101609, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_778", + "rplan_index": 9, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_778.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_010", + "k": 10, + "seed": 2026101610, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_7591", + "rplan_index": 10, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_7591.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_011", + "k": 11, + "seed": 2026101611, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_7688", + "rplan_index": 11, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_7688.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_012", + "k": 12, + "seed": 2026101612, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_9771", + "rplan_index": 12, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_9771.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_013", + "k": 13, + "seed": 2026101613, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 85 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "030f1d4084558f435ba53d34ba45f2810a114462db03bacda9263022d572cba5", + "floor_plan_id": "rplan_graph2plan_13395", + "rplan_index": 13, + "target_floor_area_m2": 85, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_13395.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_014", + "k": 14, + "seed": 2026101614, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 83 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "16a6487bd2ab701d7980bf21be073c80261e7c491b7098ca9c88e74ff4ce9e22", + "floor_plan_id": "rplan_graph2plan_14143", + "rplan_index": 14, + "target_floor_area_m2": 83, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_14143.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_015", + "k": 15, + "seed": 2026101615, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_14903", + "rplan_index": 15, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_14903.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_016", + "k": 16, + "seed": 2026101616, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 85 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "030f1d4084558f435ba53d34ba45f2810a114462db03bacda9263022d572cba5", + "floor_plan_id": "rplan_graph2plan_19207", + "rplan_index": 16, + "target_floor_area_m2": 85, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_19207.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_017", + "k": 17, + "seed": 2026101617, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_24727", + "rplan_index": 17, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_24727.json", + "plan_source": "rplan_production_25.json (October conversion)" + }, + { + "id": "scene_018", + "k": 18, + "seed": 2026101618, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_26376", + "rplan_index": 18, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_26376.json", + "plan_source": "full_v8_balanced/hall.screened.json (new converter; plan dropped from production library for a door defect)" + }, + { + "id": "scene_019", + "k": 19, + "seed": 2026101619, + "prompt": "Generate a complete connected single-storey multi-room apartment with real-scale textured furniture, solid walls, doors and windows, about 90 square metres in total. Keep furniture inside its assigned room, avoid intersections, and preserve door access. The requested rooms and furnishings are: kitchen, containing refrigerator, cabinet; dining room, containing dining table, dining chair; bathroom, containing toilet; master bedroom, containing bed, side table; living room, containing sofa, coffee table; guest bedroom, containing bed, desk; balcony, containing plant. Furniture colours and arrangements may vary. Keep all requested rooms and furniture.", + "prompt_sha256": "2baa81f896d413d459925315dea797d0cce1b96d4c9e7bbab0ddec6cf0ed7034", + "floor_plan_id": "rplan_graph2plan_28571", + "rplan_index": 19, + "target_floor_area_m2": 90, + "entities": [ + { + "entity_id": "living__sofa__01__real_sofa", + "room_id": "living", + "role": "sofa", + "layout_slot_id": "sofa" + }, + { + "entity_id": "living__coffee_table__01__real_low_coffee_table", + "room_id": "living", + "role": "coffee_table", + "layout_slot_id": "coffee_table" + }, + { + "entity_id": "master__bed__01__real_bed", + "room_id": "master", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "master__side_table__01__real_left_nightstand", + "room_id": "master", + "role": "side_table", + "layout_slot_id": "side_table" + }, + { + "entity_id": "guest__bed__02__real_bed", + "room_id": "guest", + "role": "bed", + "layout_slot_id": "bed" + }, + { + "entity_id": "guest__desk__02__real_wall_desk", + "room_id": "guest", + "role": "desk", + "layout_slot_id": "desk" + }, + { + "entity_id": "kitchen__refrigerator__01__real_fridge_wallface", + "room_id": "kitchen", + "role": "refrigerator", + "layout_slot_id": "refrigerator" + }, + { + "entity_id": "kitchen__cabinet__01__real_counter_run", + "room_id": "kitchen", + "role": "cabinet", + "layout_slot_id": "cabinet" + }, + { + "entity_id": "dining__dining_table__01__real_dining_table", + "room_id": "dining", + "role": "dining_table", + "layout_slot_id": "dining_table" + }, + { + "entity_id": "dining__dining_chair__02__real_ch3", + "room_id": "dining", + "role": "dining_chair", + "layout_slot_id": "dining_chair" + }, + { + "entity_id": "bath__toilet__01__real_toilet_wallface", + "room_id": "bath", + "role": "toilet", + "layout_slot_id": "toilet" + }, + { + "entity_id": "balcony__plant__04__balcony_plant", + "room_id": "balcony", + "role": "plant", + "layout_slot_id": "plant" + } + ], + "furniture_count": 12, + "plan_library": "ext_libs/x_28571.json", + "plan_source": "rplan_production_25.json (October conversion)" + } + ] +} diff --git a/docs/reproduction/cases20_floorplans/rebuild_cases20_floorplans.py b/docs/reproduction/cases20_floorplans/rebuild_cases20_floorplans.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3fe6ac10b95bcaaea656332b557827fbb0da9d --- /dev/null +++ b/docs/reproduction/cases20_floorplans/rebuild_cases20_floorplans.py @@ -0,0 +1,418 @@ +#!/usr/bin/env python3 +"""Rebuild the 20 floor plans of the RoboHome multi-room benchmark, and the shared per-case inputs, from the Graph2Plan release. + +The floor plans are derived from RPLAN. RPLAN's terms forbid redistributing the data or anything containing part of it, so the RoboHome +release ships no room geometry: only the Graph2Plan record names, the conversion methods and parameters (recipes_cases20.json), the +case texts (cases20_public.json) and the hashes the rebuilt files must reproduce. Download Graph2Plan's Data.zip from the authors yourself +(https://github.com/HanHan55/Graph2plan, release "data"), then run: + + python3 rebuild_cases20_floorplans.py --graph2plan Data.zip --robohome-tree --out rebuilt/ \ + [--legacy-generator ] [--recipes recipes_cases20.json] [--cases cases20_public.json] + +Outputs: + rebuilt/ext_libs/x_.json one single-plan library per case: the file RoboHome reads through RHG_RPLAN_SEEDS + rebuilt/inputs/cases20// request.txt, entities.json, rooms.json, floorplan.svg, floorplan.png, case.json (all methods) + rebuilt/inputs/cases20.json index of the 20 inputs + rebuilt/verification.json every hash check; the exit status is 1 when a required check fails + +Three conversion groups (see recipes_cases20.json): + A 5 plans first converted from the RPLAN images by hand-tuned code: exclusive source boxes, 34 % living/dining split, then the + published millimetre residuals (bathroom and balcony minimum sizes, dining widths) reproduce the rooms exactly; + B 14 plans of the October conversion (source boxes, 90 m2 scaling, 34 % living/dining split on the recorded side); + C 1 plan re-converted by tools/rplan/convert_rplan.py and screened by tools/rplan/screen_library.py of the RoboHome tree. +Doors, windows and the topology of groups A and B come from the generator's add_plan_topology. The 14 group B plans match the +distributed hashes exactly only with the October generator snapshot (--legacy-generator); without it the rooms and every other field +are still checked. RoboHome's own native shell builder recomputes doors and windows from the rooms when a scene is generated, so the +rooms are what the benchmark depends on. + +Needs Python 3.10+ with numpy, scipy (scipy.io.loadmat) and shapely; Pillow is optional (floorplan.png). +""" +import argparse +import copy +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +import zipfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PROVENANCE_KEYS = ('rplan_source_png', 'rplan_source_file', 'local_fallback_seed_manifest') +TOPOLOGY_KEYS = ('topology_adjacencies', 'doors', 'windows', 'wall_generation', 'window_rules') +ROOM_TYPES = {0: ('living', 'living_room'), 1: ('master', 'master_bedroom'), 2: ('kitchen', 'kitchen'), 3: ('bath', 'bathroom'), + 7: ('guest', 'guest_bedroom'), 9: ('balcony', 'balcony')} +ORDER = ['kitchen', 'dining', 'bath', 'master', 'living', 'guest', 'balcony'] +NEUTRAL_SOURCE_FILE = 'Graph2Plan Data.zip: Network/data.mat' +SCALE = 40 # px per metre in the input schematics (as in rphome_scripts/inputs/build_inputs.py) + + +# ----------------------------------------------------------------------------------------------------------------------- helpers +def sha256_bytes(data): + return hashlib.sha256(data).hexdigest() + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, 'rb') as f: + for block in iter(lambda: f.read(1 << 20), b''): + h.update(block) + return h.hexdigest() + + +def canon(obj): + return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')) + + +def digest(plan, drop=()): + return sha256_bytes(canon({k: v for k, v in plan.items() if k not in drop}).encode()) + + +def ordered(d, order): + out = {k: d[k] for k in order if k in d} + out.update({k: v for k, v in d.items() if k not in out}) + return out + + +# ----------------------------------------------------------------------------------------------------------------------- source data +def prepare_source(path, recipes, workdir): + """Return the path of a verified Network/data.mat, extracted from Data.zip when needed.""" + src = recipes['source'] + path = Path(path) + if path.suffix.lower() == '.zip': + got = sha256_file(path) + if got != src['archive_sha256']: + sys.exit('%s: sha256 %s, expected %s (Graph2Plan Data.zip)' % (path, got, src['archive_sha256'])) + mat = workdir / 'data.mat' + with zipfile.ZipFile(path) as z, z.open(src['member']) as f, open(mat, 'wb') as out: + shutil.copyfileobj(f, out) + else: + mat = path + got = sha256_file(mat) + if got != src['member_sha256']: + sys.exit('%s: sha256 %s, expected %s (%s)' % (mat, got, src['member_sha256'], src['member'])) + return mat + + +def load_boxes(mat, names): + import numpy as np + import scipy.io as sio + data = sio.loadmat(str(mat), squeeze_me=False, struct_as_record=False)['data'] + out = {} + for i in range(data.shape[0]): + e = data[i, 0][0, 0] + name = str(e.name[0]) + if name in names: + out[name] = dict(rType=[int(x) for x in e.rType.ravel()], gtBox=np.asarray(e.gtBox).astype(int).tolist()) + missing = sorted(set(names) - set(out)) + if missing: + sys.exit('records not found in data.mat: %s' % missing) + return out + + +# ----------------------------------------------------------------------------------------------------------------------- conversions +def split_living(box, side, fraction=.34): + a, b, c, d = box + living, dining = [a, b, c, d], [a, b, c, d] + if side == 'left': + cut = round(a + (c - a) * fraction, 3); dining[2] = cut; living[0] = cut + elif side == 'right': + cut = round(c - (c - a) * fraction, 3); dining[0] = cut; living[2] = cut + elif side == 'bottom': + cut = round(b + (d - b) * fraction, 3); dining[3] = cut; living[1] = cut + else: + cut = round(d - (d - b) * fraction, 3); dining[1] = cut; living[3] = cut + return living, dining + + +def plan_group_b(record, rec, side, source_file): + """October conversion: source gtBox rows (y0, x0, y1, x1), uniform scale to 90 m2 (longest side at most 14.8 m), living split.""" + import math + labels = rec['rType'] + boxes = [[float(b[1]), float(b[0]), float(b[3]), float(b[2])] for b in rec['gtBox'][:len(labels)]] + area = sum((b[2] - b[0]) * (b[3] - b[1]) for b in boxes) + x0 = min(b[0] for b in boxes); y0 = min(b[1] for b in boxes) + extent = max(max(b[2] for b in boxes) - x0, max(b[3] for b in boxes) - y0) + scale = min(math.sqrt(90.0 / area), 14.8 / extent) + rooms = [{'room_id': ROOM_TYPES[t][0], 'room_type': ROOM_TYPES[t][1], + 'bounds_m': [round((b[0] - x0) * scale, 3), round((b[1] - y0) * scale, 3), round((b[2] - x0) * scale, 3), round((b[3] - y0) * scale, 3)]} + for t, b in zip(labels, boxes)] + living = next(r for r in rooms if r['room_id'] == 'living') + living['bounds_m'], dining = split_living(living['bounds_m'], side) + rooms.append({'room_id': 'dining', 'room_type': 'dining_room', 'bounds_m': dining}) + return {'plan_id': 'rplan_graph2plan_%s' % record, 'rplan_source_file': source_file, 'rplan_source_id': record, 'rplan_labels_present': labels, + 'rplan_conversion': {'method': 'source_gtBox_nonoverlap_then_living_dining_split', 'scale_m_per_px': scale, 'target_area_m2_before_clamp': 90, + 'raw_bbox_overlap_score': 0, 'dining_source': 'split_living', 'dining_side': side, 'dining_fraction': .34}, + 'rooms': sorted(rooms, key=lambda r: ORDER.index(r['room_id'])), + 'open_room_type_pairs': [['kitchen', 'dining_room'], ['dining_room', 'living_room']], 'wall_thickness_m': .2, 'wall_height_m': 3.0} + + +def plan_group_a(entry, rec, provenance_fields): + """Original plans: exclusive source boxes at the house corner, recorded scale, 34 % living split, then the millimetre residuals.""" + conv = dict(entry['rplan_conversion']) + scale = conv['scale_m_per_px'] + labels = rec['rType'] + px = {label: [b[1], b[0], b[3] + 1, b[2] + 1] for label, b in zip(labels, rec['gtBox'][:len(labels)])} + ox = min(v[0] for v in px.values()); oy = min(v[1] for v in px.values()) + metres = {label: [round((v[0] - ox) * scale, 3), round((v[1] - oy) * scale, 3), round((v[2] - ox) * scale, 3), round((v[3] - oy) * scale, 3)] + for label, v in px.items()} + living, dining = split_living(metres[0], entry['dining_side']) + rooms = [] + for room in entry['rooms_recipe']: + base = dining if room['room_id'] == 'dining' else living if room['room_id'] == 'living' else metres[room['source_label']] + rooms.append({'room_id': room['room_id'], 'room_type': room['room_type'], + 'bounds_m': [round(b + r / 1000.0, 3) for b, r in zip(base, room['residual_mm'])]}) + conv['outline_px'] = [ox, oy, max(v[2] for v in px.values()), max(v[3] for v in px.values())] + plan = dict(entry['plan_fields']) + plan.update(rplan_conversion=ordered(conv, entry['rplan_conversion_key_order']), rplan_labels_present=sorted(labels), rooms=rooms) + neutral = {'rplan_source_png': 'RPLAN image %s.png (not distributed)' % entry['record'], + 'rplan_source_file': 'RoboHome internal record (not distributed)', + 'local_fallback_seed_manifest': 'RoboHome internal record (not distributed)'} + plan.update({k: provenance_fields.get(k, neutral[k]) for k in PROVENANCE_KEYS if k in entry['plan_key_order']}) + return plan + + +# ----------------------------------------------------------------------------------------------------------------------- workers +# The generator modules of the legacy snapshot and of the RoboHome tree share module names, so each runs in its own process. +def worker_main(mode, args_path): + job = json.loads(Path(args_path).read_text()) + tmp = Path(job['tmp']) + os.environ.update(XDG_CACHE_HOME=str(tmp), RHG_RUNTIME_ROOT=str(tmp / 'runtime'), RHG_ASTRA_CACHE_DIR=str(tmp / 'astra'), TMPDIR=str(tmp), + RHG_OUT_ROOT=str(tmp), RHG_CANDIDATE_CACHE_DIR=str(tmp), RHG_WALL_HEIGHT_M='3.0', RHG_DOOR_WIDTH_M='1.0', + RHG_DOOR_HEIGHT_M='2.4', RHG_TEST_SCENE_COUNT='1') + tempfile.tempdir = str(tmp) + tree = Path(job['tree']) + if mode == 'topology': + helpers = Path(job['generator']) + os.environ['RHG_BASE_SCRIPT'] = str(helpers / 'base/rhg_fullhome_test_generate_v2.py') + sys.path[:0] = [str(helpers), str(tree / 'engine/supervisor_site')] + if job['generator_is_tree']: + sys.path[:0] = [str(tree), str(tree / 'engine/source')] + import importlib + g = importlib.import_module('rhg_task_contract_generate_v16_1p_procedural_pure') + result = {key: g.add_plan_topology(copy.deepcopy(plan)) for key, plan in job['plans'].items()} + elif mode == 'convert': + sys.path[:0] = [str(tree / 'tools/rplan'), str(tree / 'engine/supervisor_site')] + import convert_rplan + import screen_library + wanted = {c['record']: c for c in job['conversions']} + records = {r['name']: r for r in convert_rplan.load_records(job['mat']) if r['name'] in wanted} + screen_library.init_worker(str(tree)) + result = {} + for record, c in wanted.items(): + plan, reason = convert_rplan.convert(records[record], **c['options']) + if plan is None: + result[record] = {'error': 'convert: %s' % reason} + continue + _, screened, why = screen_library.screen_one((plan, c['screening_options'])) + result[record] = screened if screened else {'error': 'screen: %s' % why} + else: + raise SystemExit('unknown worker mode %s' % mode) + Path(job['out']).write_text(json.dumps(result, ensure_ascii=False)) + + +def run_worker(mode, job, tmp): + job = dict(job, tmp=str(tmp), out=str(tmp / ('%s.out.json' % mode))) + args_path = tmp / ('%s.job.json' % mode) + args_path.write_text(json.dumps(job, ensure_ascii=False)) + env = dict(os.environ, PYTHONDONTWRITEBYTECODE='1') + subprocess.run([sys.executable, str(Path(__file__).resolve()), '--_worker', mode, str(args_path)], check=True, env=env, cwd=str(tmp)) + return json.loads(Path(job['out']).read_text()) + + +# ----------------------------------------------------------------------------------------------------------------------- inputs +def floorplan_svg(rooms): + x1 = max(r['bounds_m'][2] for r in rooms) + y1 = max(r['bounds_m'][3] for r in rooms) + pad = 20 + w, h = int(x1 * SCALE) + 2 * pad, int(y1 * SCALE) + 2 * pad + 30 + parts = [f'', + ''] + for r in rooms: + a, b, c, d = r['bounds_m'] + px, py = pad + a * SCALE, pad + (y1 - d) * SCALE + pw, ph = (c - a) * SCALE, (d - b) * SCALE + parts.append(f'') + label = r['room_type'].replace('_', ' ') + area = (c - a) * (d - b) + parts.append(f'{label}') + parts.append(f'{area:.1f} m2') + yb = h - 18 + parts.append(f'') + parts.append(f'2 m') + parts.append('') + return '\n'.join(parts) + '\n' + + +def floorplan_png(rooms, path): + try: + from PIL import Image, ImageDraw + except ImportError: + return False + x1 = max(r['bounds_m'][2] for r in rooms) + y1 = max(r['bounds_m'][3] for r in rooms) + pad = 20 + img = Image.new('RGB', (int(x1 * SCALE) + 2 * pad, int(y1 * SCALE) + 2 * pad + 30), 'white') + draw = ImageDraw.Draw(img) + for r in rooms: + a, b, c, d = r['bounds_m'] + box = [pad + a * SCALE, pad + (y1 - d) * SCALE, pad + c * SCALE, pad + (y1 - b) * SCALE] + draw.rectangle(box, fill=(244, 244, 244), outline='black', width=2) + cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 + draw.text((cx, cy), r['room_type'].replace('_', ' '), fill='black', anchor='mm') + yb = img.height - 18 + draw.line([pad, yb, pad + 2 * SCALE, yb], fill='black', width=3) + draw.text((pad + 2 * SCALE + 6, yb), '2 m', fill='black', anchor='lm') + img.save(path) + return True + + +def write_inputs(cases_doc, rooms_by_case, out, plan_library_of): + root = out / 'inputs' + base = root / 'cases20' + base.mkdir(parents=True, exist_ok=True) + manifest = cases_doc['source_manifest'] + index = [] + for case in cases_doc['cases']: + cid, k = case['id'], case['k'] + rooms = rooms_by_case[cid] + d = base / cid + d.mkdir(exist_ok=True) + library = plan_library_of(case) + record = dict(case=cid, k=k, prompt=case['prompt'], prompt_sha256=case['prompt_sha256'], floor_plan_id=case['floor_plan_id'], + rplan_index=case['rplan_index'], target_floor_area_m2=case['target_floor_area_m2'], rooms=rooms, + entities=case['entities'], furniture_count=case['furniture_count'], plan_library=library, plan_source=case['plan_source'], + october_seed=case['seed'], source='%s (sha256 %s)' % (manifest['name'], manifest['sha256'][:12])) + (d / 'request.txt').write_text(case['prompt'] + '\n', encoding='utf-8') + (d / 'entities.json').write_text(json.dumps(case['entities'], indent=1, ensure_ascii=False) + '\n', encoding='utf-8') + (d / 'rooms.json').write_text(json.dumps(dict(target_floor_area_m2=case['target_floor_area_m2'], floor_plan_id=case['floor_plan_id'], + rooms=rooms), indent=1, ensure_ascii=False) + '\n', encoding='utf-8') + (d / 'floorplan.svg').write_text(floorplan_svg(rooms), encoding='utf-8') + png = floorplan_png(rooms, d / 'floorplan.png') + (d / 'case.json').write_text(json.dumps(record, indent=1, ensure_ascii=False) + '\n', encoding='utf-8') + index.append(dict(case=cid, k=k, dir='inputs/cases20/%s' % cid, floor_plan_id=case['floor_plan_id'], plan_library=library, + prompt_sha256=case['prompt_sha256'], rooms=len(rooms), entities=len(case['entities']), floorplan_png=png)) + (root / 'cases20.json').write_text(json.dumps(dict(schema='rphome.inputs.v1', n=len(index), cases_sha256=manifest['sha256'], cases=index), + indent=1, ensure_ascii=False) + '\n', encoding='utf-8') + return root + + +# ----------------------------------------------------------------------------------------------------------------------- main +def main(argv=None): + argv = sys.argv[1:] if argv is None else argv + if argv[:1] == ['--_worker']: + return worker_main(argv[1], argv[2]) + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--graph2plan', required=True, help="Graph2Plan's Data.zip, or the Network/data.mat extracted from it") + ap.add_argument('--robohome-tree', required=True, type=Path, help='RoboHome code tree (tools/rplan and the scene-generation engine)') + ap.add_argument('--legacy-generator', type=Path, + help='October 2026 snapshot of the v16.1p scene-generation helpers: reproduces the doors and windows of the group B libraries exactly') + ap.add_argument('--out', required=True, type=Path) + ap.add_argument('--recipes', type=Path, default=HERE / 'recipes_cases20.json') + ap.add_argument('--cases', type=Path, default=HERE / 'cases20_public.json') + ap.add_argument('--provenance', type=Path, help=argparse.SUPPRESS) # RoboHome-internal: restores original path strings for byte-exact checks + args = ap.parse_args(argv) + args.out, args.robohome_tree = args.out.resolve(), args.robohome_tree.resolve() + if args.legacy_generator: + args.legacy_generator = args.legacy_generator.resolve() + args.graph2plan = str(Path(args.graph2plan).resolve()) + + recipes = json.loads(args.recipes.read_text()) + cases_doc = json.loads(args.cases.read_text()) + internal = json.loads(args.provenance.read_text()) if args.provenance else None + out = args.out + (out / 'ext_libs').mkdir(parents=True, exist_ok=True) + tmp = Path(tempfile.mkdtemp(prefix='rebuild_cases20_', dir=str(out))) + checks = [] + + def check(name, got, expected, required=True): + ok = got == expected + checks.append(dict(check=name, ok=ok, required=required, got=got, expected=expected)) + return ok + + try: + mat = prepare_source(args.graph2plan, recipes, tmp) + libraries = recipes['libraries'] + shared = recipes['shared_input_overrides'] + boxes = load_boxes(mat, {e['record'] for e in libraries if e['group'] in 'AB'} | {s['record'] for s in shared}) + prov = {p['case']: p for p in internal['libraries']} if internal else {} + wrappers = internal['wrappers'] if internal else recipes['wrappers'] + + plans, pending = {}, {} + for e in libraries: + fields = prov.get(e['case'], {}).get('fields', {}) + if e['group'] == 'B': + plans[e['case']] = plan_group_b(e['record'], boxes[e['record']], e['dining_side'], fields.get('rplan_source_file', NEUTRAL_SOURCE_FILE)) + pending[e['case']] = plans[e['case']] + elif e['group'] == 'A': + plans[e['case']] = plan_group_a(e, boxes[e['record']], fields) + pending[e['case']] = plans[e['case']] + generator = args.legacy_generator or (args.robohome_tree / 'engine/source/scripts/internal/scene_generation') + topo = run_worker('topology', dict(tree=str(args.robohome_tree), generator=str(generator), generator_is_tree=args.legacy_generator is None, + plans=pending), tmp) + for case, plan in topo.items(): + plans[case] = plan + conversions = [dict(record=e['record'], options=wrappers[e['wrapper']]['options'], screening_options=wrappers[e['wrapper']]['screening_options']) + for e in libraries if e['group'] == 'C'] + converted = run_worker('convert', dict(tree=str(args.robohome_tree), mat=str(mat), conversions=conversions), tmp) if conversions else {} + for e in libraries: + if e['group'] == 'C': + plan = converted[e['record']] + if 'error' in plan: + sys.exit('%s: %s' % (e['case'], plan['error'])) + plans[e['case']] = plan + + rooms_by_case = {} + for e in libraries: + plan = ordered(plans[e['case']], e['plan_key_order']) + name = e['case'] + ' ' + e['plan_id'] + check(name + ' rooms', sha256_bytes(canon(plan['rooms']).encode()), e['expected']['rooms_sha256']) + check(name + ' plan core', digest(plan, PROVENANCE_KEYS + TOPOLOGY_KEYS), e['expected']['plan_core_sha256']) + if e['group'] == 'B' and not args.legacy_generator: + checks.append(dict(check=name + ' plan with doors/windows', ok=None, required=False, + note='skipped: needs --legacy-generator (RoboHome recomputes doors and windows at generation time)')) + else: + drop = PROVENANCE_KEYS + (TOPOLOGY_KEYS if e['group'] == 'A' else ()) + check(name + ' plan', digest(plan, drop), e['expected']['plan_sha256']) + library = ordered(dict(wrappers[e['wrapper']], plans=[plan]), e['library_key_order']) + ensure_ascii = prov.get(e['case'], {}).get('ensure_ascii', True) + data = json.dumps(library, ensure_ascii=ensure_ascii).encode() + (out / 'ext_libs' / e['library_file']).write_bytes(data) + if internal: + check(name + ' file bytes (internal)', sha256_bytes(data), prov[e['case']]['file_sha256'], required=e['group'] != 'A') + rooms_by_case[e['case']] = plan['rooms'] + for s in shared: + plan = plan_group_b(s['record'], boxes[s['record']], s['dining_side'], NEUTRAL_SOURCE_FILE) + check(s['case'] + ' shared-input rooms (October %s)' % s['plan_id'], sha256_bytes(canon(plan['rooms']).encode()), s['expected']['rooms_sha256']) + rooms_by_case[s['case']] = plan['rooms'] + + internal_paths = {p['case']: p['library_path'] for p in internal['libraries']} if internal else {} + root = write_inputs(cases_doc, rooms_by_case, out, + lambda case: internal_paths.get(case['id'], case['plan_library'])) + expected_inputs = dict(recipes['expected_inputs_sha256'], **(internal['expected_inputs_sha256'] if internal else {})) + for rel, expected in sorted(expected_inputs.items()): + path = root / rel + if not path.exists(): + checks.append(dict(check='input ' + rel, ok=False, required=not rel.endswith('.png'), note='not written')) + continue + # The original cases20.json index records floorplan_png=false (written where Pillow was missing) although the PNG files exist. + check('input ' + rel, sha256_file(path), expected, required=not rel.endswith('.png') and rel != 'cases20.json') + finally: + shutil.rmtree(tmp, ignore_errors=True) + + failed = [c for c in checks if c['ok'] is False and c['required']] + soft = [c for c in checks if c['ok'] is False and not c['required']] + report = dict(passed=sum(1 for c in checks if c['ok']), failed_required=len(failed), failed_optional=len(soft), + skipped=sum(1 for c in checks if c['ok'] is None), checks=checks) + (out / 'verification.json').write_text(json.dumps(report, ensure_ascii=False, indent=1) + '\n') + print('%d checks passed, %d required failed, %d optional failed, %d skipped -> %s' + % (report['passed'], report['failed_required'], report['failed_optional'], report['skipped'], out / 'verification.json')) + for c in failed + soft: + print(' %s %s' % ('FAIL' if c['required'] else 'warn', c['check'])) + return 1 if failed else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/docs/reproduction/cases20_floorplans/recipes_cases20.json b/docs/reproduction/cases20_floorplans/recipes_cases20.json new file mode 100644 index 0000000000000000000000000000000000000000..1fb5ee1c3ebfa67a2d0de87e3366c3006439a26a --- /dev/null +++ b/docs/reproduction/cases20_floorplans/recipes_cases20.json @@ -0,0 +1,1528 @@ +{ + "schema": "robohome.cases20_floorplan_recipes.v1", + "source": { + "name": "Graph2Plan author release (RPLAN-derived data, obtain it yourself)", + "url": "https://github.com/HanHan55/Graph2plan/releases/download/data/Data.zip", + "archive_sha256": "e88f1c52eb065a4441f9675f6f5401e3e46add4b3ae6ad96f63fb527b6958cd3", + "member": "Network/data.mat", + "member_sha256": "ce1e9c7fc2846c2d5a36485c8fa4d16df9b7de0ccda31581fe76fc2fa6f28adc" + }, + "hash_definitions": { + "canonical": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(\",\", \":\")) encoded as UTF-8", + "provenance_keys": [ + "rplan_source_png", + "rplan_source_file", + "local_fallback_seed_manifest" + ], + "topology_keys": [ + "topology_adjacencies", + "doors", + "windows", + "wall_generation", + "window_rules" + ], + "rooms_sha256": "sha256 of canonical plan[\"rooms\"]", + "plan_core_sha256": "sha256 of canonical plan without provenance and topology keys", + "plan_sha256": "sha256 of canonical plan without provenance keys (group A also without topology keys)" + }, + "wrappers": { + "w_1e0513e7d441": { + "schema": "robohousegen.rplan_seed_file.expanded25.qualified_v1", + "source": "original five unchanged plus twenty independently generated and verified Graph2Plan/RPLAN source layouts", + "provenance": { + "source_receipt": "internal RoboHome record, not distributed", + "selection_report": "internal RoboHome record, not distributed", + "candidate_ledger": "internal RoboHome record, not distributed", + "geometry_verification": "internal RoboHome record, not distributed", + "source_url": "https://github.com/HanHan55/Graph2plan/releases/download/data/Data.zip" + }, + "plan_count": 1 + }, + "w_3b47d637bcdc": { + "schema": "robohousegen.rplan_seed_file.screened_v1", + "source": "Graph2Plan RPLAN release, room polygons reduced to rectangles", + "source_record_count": 80788, + "options": { + "scale_target": 100.0, + "min_retained": 0.0, + "extra_bedroom_area": 10.0, + "min_side": { + "living": 2.8, + "bedroom": 2.5, + "dining": 2.0, + "kitchen": 1.8, + "bath": 1.5, + "balcony": 1.0, + "default": 1.8 + }, + "repair": true, + "max_aspect": 5.0, + "max_growth": 2.5, + "require_guest": true, + "strict_access": false, + "drop_balcony": true, + "candidates_per_room": 8, + "hallways": true + }, + "screened_count": 46353, + "screening_options": { + "min_score": null, + "allow_missing_windows": false, + "topology_gate": false, + "fix": true, + "limits": { + "kitchen": 1.8, + "bath": 1.5, + "balcony": 1.0, + "hallway": 1.0, + "default": 1.8, + "living": 2.8, + "bedroom": 2.5, + "dining": 2.0 + } + }, + "plan_count": 1 + } + }, + "libraries": [ + { + "case": "scene_000", + "plan_id": "rplan_constrained_45966_scene_010_v16_task_contract", + "group": "A", + "library_file": "x_45966.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_png", + "rplan_source_file", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows", + "local_fallback_seed_manifest" + ], + "expected": { + "rooms_sha256": "423e28d6baff9fcc3828b78fbdeaabf07b5a9e471ef0ac7a327f9423be788f3f", + "plan_core_sha256": "b7383685ce7200a81ffaed3516352d57e7f50497760315bdf03e9d0d01bd2d52", + "plan_sha256": "b7383685ce7200a81ffaed3516352d57e7f50497760315bdf03e9d0d01bd2d52" + }, + "record": "45966", + "dining_side": "left", + "rplan_conversion": { + "method": "semantic_room_bbox_low_overlap_then_living_dining_split", + "rank": 0, + "scale_m_per_px": 0.07437, + "target_area_m2_before_clamp": 90.07, + "room_pixel_area": 14345, + "outline_m": [ + 0.0, + 0.0, + 7.065, + 14.8 + ], + "raw_bbox_overlap_score": 0.0, + "final_bbox_overlap_score": 0.0, + "dining_source": "split_living", + "aspect_bin": "tall" + }, + "rplan_conversion_key_order": [ + "method", + "rank", + "scale_m_per_px", + "target_area_m2_before_clamp", + "room_pixel_area", + "outline_px", + "outline_m", + "raw_bbox_overlap_score", + "final_bbox_overlap_score", + "dining_source", + "aspect_bin" + ], + "rooms_recipe": [ + { + "room_id": "kitchen", + "room_type": "kitchen", + "source_label": 2, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "dining", + "room_type": "dining_room", + "source_label": 0, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "bath", + "room_type": "bathroom", + "source_label": 3, + "residual_mm": [ + -6, + 0, + 7, + 0 + ] + }, + { + "room_id": "master", + "room_type": "master_bedroom", + "source_label": 1, + "residual_mm": [ + 0, + 1, + 0, + 1 + ] + }, + { + "room_id": "living", + "room_type": "living_room", + "source_label": 0, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "guest", + "room_type": "guest_bedroom", + "source_label": 7, + "residual_mm": [ + 0, + 1, + 0, + 1 + ] + }, + { + "room_id": "balcony", + "room_type": "balcony", + "source_label": 9, + "residual_mm": [ + 0, + 1, + 0, + 0 + ] + } + ], + "plan_fields": { + "plan_id": "rplan_constrained_45966_scene_010_v16_task_contract", + "open_room_type_pairs": [ + [ + "kitchen", + "dining_room" + ], + [ + "dining_room", + "living_room" + ] + ], + "wall_thickness_m": 0.2, + "wall_height_m": 1.35 + } + }, + { + "case": "scene_001", + "plan_id": "rplan_constrained_78215_scene_011_v16_task_contract", + "group": "A", + "library_file": "x_78215.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_png", + "rplan_source_file", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows", + "local_fallback_seed_manifest" + ], + "expected": { + "rooms_sha256": "32ba4c45ad03d048e85e88475dbf25e926a24f8b1b0c516faef5a581ed4ec2a0", + "plan_core_sha256": "7bb8ad5f630360bff7e70d0824cf148fbb6fcb205f7bbd0ca21ab8f92d283d46", + "plan_sha256": "7bb8ad5f630360bff7e70d0824cf148fbb6fcb205f7bbd0ca21ab8f92d283d46" + }, + "record": "78215", + "dining_side": "top", + "rplan_conversion": { + "method": "semantic_room_bbox_low_overlap_then_living_dining_split", + "rank": 1, + "scale_m_per_px": 0.07146, + "target_area_m2_before_clamp": 82.66, + "room_pixel_area": 16188, + "outline_m": [ + 0.0, + 0.0, + 10.933, + 8.932 + ], + "raw_bbox_overlap_score": 0.0, + "final_bbox_overlap_score": 0.0, + "dining_source": "split_living", + "aspect_bin": "balanced" + }, + "rplan_conversion_key_order": [ + "method", + "rank", + "scale_m_per_px", + "target_area_m2_before_clamp", + "room_pixel_area", + "outline_px", + "outline_m", + "raw_bbox_overlap_score", + "final_bbox_overlap_score", + "dining_source", + "aspect_bin" + ], + "rooms_recipe": [ + { + "room_id": "kitchen", + "room_type": "kitchen", + "source_label": 2, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "dining", + "room_type": "dining_room", + "source_label": 0, + "residual_mm": [ + 0, + -304, + -1, + 0 + ] + }, + { + "room_id": "bath", + "room_type": "bathroom", + "source_label": 3, + "residual_mm": [ + 0, + -75, + 0, + 75 + ] + }, + { + "room_id": "master", + "room_type": "master_bedroom", + "source_label": 1, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "living", + "room_type": "living_room", + "source_label": 0, + "residual_mm": [ + 0, + -1, + -1, + -304 + ] + }, + { + "room_id": "guest", + "room_type": "guest_bedroom", + "source_label": 7, + "residual_mm": [ + 0, + 0, + -1, + 0 + ] + }, + { + "room_id": "balcony", + "room_type": "balcony", + "source_label": 9, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + } + ], + "plan_fields": { + "plan_id": "rplan_constrained_78215_scene_011_v16_task_contract", + "open_room_type_pairs": [ + [ + "kitchen", + "dining_room" + ], + [ + "dining_room", + "living_room" + ] + ], + "wall_thickness_m": 0.2, + "wall_height_m": 1.35 + } + }, + { + "case": "scene_002", + "plan_id": "rplan_constrained_44500_scene_002_v16_task_contract", + "group": "A", + "library_file": "x_44500.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_png", + "rplan_source_file", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows", + "local_fallback_seed_manifest" + ], + "expected": { + "rooms_sha256": "c41fd9ed3edf9617495f1ca156f5dc5d60a60008f1fba6b391fc7f379f79c354", + "plan_core_sha256": "a550ebd87626bab12e30c92dda116396efa271967399907fcc8d25e9208228c7", + "plan_sha256": "a550ebd87626bab12e30c92dda116396efa271967399907fcc8d25e9208228c7" + }, + "record": "44500", + "dining_side": "left", + "rplan_conversion": { + "method": "semantic_room_bbox_low_overlap_then_living_dining_split", + "rank": 2, + "scale_m_per_px": 0.08757, + "target_area_m2_before_clamp": 102.45, + "room_pixel_area": 13277, + "outline_m": [ + 0.0, + 0.0, + 8.845, + 14.8 + ], + "raw_bbox_overlap_score": 0.0, + "final_bbox_overlap_score": 0.0, + "dining_source": "split_living", + "aspect_bin": "tall" + }, + "rplan_conversion_key_order": [ + "method", + "rank", + "scale_m_per_px", + "target_area_m2_before_clamp", + "room_pixel_area", + "outline_px", + "outline_m", + "raw_bbox_overlap_score", + "final_bbox_overlap_score", + "dining_source", + "aspect_bin" + ], + "rooms_recipe": [ + { + "room_id": "kitchen", + "room_type": "kitchen", + "source_label": 2, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "dining", + "room_type": "dining_room", + "source_label": 0, + "residual_mm": [ + 0, + 1, + 325, + 1 + ] + }, + { + "room_id": "bath", + "room_type": "bathroom", + "source_label": 3, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "master", + "room_type": "master_bedroom", + "source_label": 1, + "residual_mm": [ + 0, + 0, + 0, + 1 + ] + }, + { + "room_id": "living", + "room_type": "living_room", + "source_label": 0, + "residual_mm": [ + 325, + 1, + 0, + 1 + ] + }, + { + "room_id": "guest", + "room_type": "guest_bedroom", + "source_label": 7, + "residual_mm": [ + 1, + 0, + 0, + 0 + ] + }, + { + "room_id": "balcony", + "room_type": "balcony", + "source_label": 9, + "residual_mm": [ + 1, + 1, + 0, + 1 + ] + } + ], + "plan_fields": { + "plan_id": "rplan_constrained_44500_scene_002_v16_task_contract", + "open_room_type_pairs": [ + [ + "kitchen", + "dining_room" + ], + [ + "dining_room", + "living_room" + ] + ], + "wall_thickness_m": 0.2, + "wall_height_m": 1.35 + } + }, + { + "case": "scene_003", + "plan_id": "rplan_constrained_24777_scene_003_v16_task_contract", + "group": "A", + "library_file": "x_24777.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_png", + "rplan_source_file", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows", + "local_fallback_seed_manifest" + ], + "expected": { + "rooms_sha256": "413b9acd1788c80490bf7b5670fbc9fcd900087cf969112dc56b313081151511", + "plan_core_sha256": "7cd596fa0e45b8d7ee0959003ef9beb213321949df3268e7d2590edf818e292a", + "plan_sha256": "7cd596fa0e45b8d7ee0959003ef9beb213321949df3268e7d2590edf818e292a" + }, + "record": "24777", + "dining_side": "bottom", + "rplan_conversion": { + "method": "semantic_room_bbox_low_overlap_then_living_dining_split", + "rank": 3, + "scale_m_per_px": 0.0759, + "target_area_m2_before_clamp": 97.25, + "room_pixel_area": 14637, + "outline_m": [ + 0.0, + 0.0, + 9.639, + 14.8 + ], + "raw_bbox_overlap_score": 0.0, + "final_bbox_overlap_score": 0.06, + "dining_source": "split_living", + "aspect_bin": "tall" + }, + "rplan_conversion_key_order": [ + "method", + "rank", + "scale_m_per_px", + "target_area_m2_before_clamp", + "room_pixel_area", + "outline_px", + "outline_m", + "raw_bbox_overlap_score", + "final_bbox_overlap_score", + "dining_source", + "aspect_bin" + ], + "rooms_recipe": [ + { + "room_id": "kitchen", + "room_type": "kitchen", + "source_label": 2, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "dining", + "room_type": "dining_room", + "source_label": 0, + "residual_mm": [ + -1, + 0, + 0, + 0 + ] + }, + { + "room_id": "bath", + "room_type": "bathroom", + "source_label": 3, + "residual_mm": [ + -67, + 0, + 65, + 0 + ] + }, + { + "room_id": "master", + "room_type": "master_bedroom", + "source_label": 1, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "living", + "room_type": "living_room", + "source_label": 0, + "residual_mm": [ + -1, + 0, + 0, + -1 + ] + }, + { + "room_id": "guest", + "room_type": "guest_bedroom", + "source_label": 7, + "residual_mm": [ + 0, + 0, + 0, + -1 + ] + }, + { + "room_id": "balcony", + "room_type": "balcony", + "source_label": 9, + "residual_mm": [ + 0, + -291, + 0, + 0 + ] + } + ], + "plan_fields": { + "plan_id": "rplan_constrained_24777_scene_003_v16_task_contract", + "open_room_type_pairs": [ + [ + "kitchen", + "dining_room" + ], + [ + "dining_room", + "living_room" + ] + ], + "wall_thickness_m": 0.2, + "wall_height_m": 1.35 + } + }, + { + "case": "scene_004", + "plan_id": "rplan_constrained_42920_scene_009_v16_task_contract", + "group": "A", + "library_file": "x_42920.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_png", + "rplan_source_file", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows", + "local_fallback_seed_manifest" + ], + "expected": { + "rooms_sha256": "f840c247ec70ad557c896f37f5abb16a395af9fabd5887c60119f28b852e189c", + "plan_core_sha256": "e885612fccf4361b1d60c8963450cc837312f74d62f9928d0863489f22de574a", + "plan_sha256": "e885612fccf4361b1d60c8963450cc837312f74d62f9928d0863489f22de574a" + }, + "record": "42920", + "dining_side": "left", + "rplan_conversion": { + "method": "semantic_room_bbox_low_overlap_then_living_dining_split", + "rank": 4, + "scale_m_per_px": 0.08177, + "target_area_m2_before_clamp": 88.15, + "room_pixel_area": 13184, + "outline_m": [ + 0.0, + 0.0, + 8.422, + 13.819 + ], + "raw_bbox_overlap_score": 0.0, + "final_bbox_overlap_score": 0.0, + "dining_source": "split_living", + "aspect_bin": "tall" + }, + "rplan_conversion_key_order": [ + "method", + "rank", + "scale_m_per_px", + "target_area_m2_before_clamp", + "room_pixel_area", + "outline_px", + "outline_m", + "raw_bbox_overlap_score", + "final_bbox_overlap_score", + "dining_source", + "aspect_bin" + ], + "rooms_recipe": [ + { + "room_id": "kitchen", + "room_type": "kitchen", + "source_label": 2, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "dining", + "room_type": "dining_room", + "source_label": 0, + "residual_mm": [ + 0, + 0, + 70, + 0 + ] + }, + { + "room_id": "bath", + "room_type": "bathroom", + "source_label": 3, + "residual_mm": [ + 0, + 0, + -1, + 0 + ] + }, + { + "room_id": "master", + "room_type": "master_bedroom", + "source_label": 1, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "living", + "room_type": "living_room", + "source_label": 0, + "residual_mm": [ + 70, + 0, + 0, + 0 + ] + }, + { + "room_id": "guest", + "room_type": "guest_bedroom", + "source_label": 7, + "residual_mm": [ + 0, + 0, + 0, + 0 + ] + }, + { + "room_id": "balcony", + "room_type": "balcony", + "source_label": 9, + "residual_mm": [ + 0, + 0, + 0, + 69 + ] + } + ], + "plan_fields": { + "plan_id": "rplan_constrained_42920_scene_009_v16_task_contract", + "open_room_type_pairs": [ + [ + "kitchen", + "dining_room" + ], + [ + "dining_room", + "living_room" + ] + ], + "wall_thickness_m": 0.2, + "wall_height_m": 1.35 + } + }, + { + "case": "scene_005", + "plan_id": "rplan_graph2plan_44838", + "group": "B", + "library_file": "x_44838.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "c91bbd8644731b5608475051e41f808824511eb816ffdfefa2447a5b579b9bd9", + "plan_core_sha256": "366f15722bb68a585c656bd243e8409d7c12132ea36aa5d2223435f1318888b0", + "plan_sha256": "7b75ed1f9355de6a6404ee864816a9c960c0c36a470171b1f811d0e806d53097" + }, + "record": "44838", + "dining_side": "right" + }, + { + "case": "scene_006", + "plan_id": "rplan_graph2plan_65877", + "group": "B", + "library_file": "x_65877.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "bbc59aa84353678f54d0886c4c5b3657db262283f36abb6ad24affaf6b04852c", + "plan_core_sha256": "f097cb892e99c2123c04dfaaa1a18a0f7f7aafea48f4b07b74761fd36908a0a1", + "plan_sha256": "59abc4f3f085565fb9cfa7181bd8c27117b76bae1ef88a1151d7dac9fb4d85f9" + }, + "record": "65877", + "dining_side": "top" + }, + { + "case": "scene_007", + "plan_id": "rplan_graph2plan_66696", + "group": "B", + "library_file": "x_66696.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "02e5daa0bf38b1dceb5bc11f65e1f7b98b322a7762cd27a0fae1eb4f886efc69", + "plan_core_sha256": "95f48c386833d7e1c34771a85a30a6d9cb15604ca080dbb4a96cdfe6c7300a9d", + "plan_sha256": "0e395648c7a57bdd89dda11b2a89556fd3773674f1aafff4c3ad68cc965d205b" + }, + "record": "66696", + "dining_side": "left" + }, + { + "case": "scene_008", + "plan_id": "rplan_graph2plan_71597", + "group": "B", + "library_file": "x_71597.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "d2e27bcc432a6d063a9a93f4378bb23ed6a144231c7e10e35773813f2b67cfc5", + "plan_core_sha256": "b7d962c459026b82ee346046736ae2139eb839c5cf344a9bd147e4095d304a2b", + "plan_sha256": "7da759d727e22e752b9216af691459e71138304e5864e2bd05fdd815877381f5" + }, + "record": "71597", + "dining_side": "bottom" + }, + { + "case": "scene_009", + "plan_id": "rplan_graph2plan_778", + "group": "B", + "library_file": "x_778.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "6a9443d48e698871a316687bd97bf547f623e18d4404d2d974c005134ce410fc", + "plan_core_sha256": "f4d19f75b0c5567187abc1a9d133d06ead5ad62ab1160fc3531a323e96a1185c", + "plan_sha256": "852d6b1fdde62c09e0207054667b62d5e107753a59fd516aff87e0120d3ab78e" + }, + "record": "778", + "dining_side": "left" + }, + { + "case": "scene_010", + "plan_id": "rplan_graph2plan_7591", + "group": "B", + "library_file": "x_7591.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "f0911bcc01b9d21790216f888ea3e376196e080dc7a9d77d7dcc2419c2f36f42", + "plan_core_sha256": "a631d7ba061da0a075da090819f0ae08cd9b529d3ac2b0fb61df596710f39445", + "plan_sha256": "960c44e94c283cec0e326cdb55f55e1bd819851da178858a2d99b69142941b58" + }, + "record": "7591", + "dining_side": "right" + }, + { + "case": "scene_011", + "plan_id": "rplan_graph2plan_7688", + "group": "B", + "library_file": "x_7688.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "d83a6e70da8b762785722c1e0661b49b932140cd685f69df799367f0b90367d1", + "plan_core_sha256": "5eeab5b014a74902ff650952d587b0a33689834c5658a4e47610ea26e6e5b96b", + "plan_sha256": "a038aa2830f0eb6359c80be11c2d3b880f2805d943c26b98c0baed54a7e7b1fb" + }, + "record": "7688", + "dining_side": "left" + }, + { + "case": "scene_012", + "plan_id": "rplan_graph2plan_9771", + "group": "B", + "library_file": "x_9771.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "5134583bf753d46e17aaf9804c0604841d6b7bb9b0c74aa7583107d1887e0c0d", + "plan_core_sha256": "db245c413cf669b02e3d912bd55820b15b38eea8636e4ad5adb312faff5f210c", + "plan_sha256": "282fd8cce11384cfade45b2a700b6c6b6e4a67bbc8fadee847dabbcf44c1e0e3" + }, + "record": "9771", + "dining_side": "bottom" + }, + { + "case": "scene_013", + "plan_id": "rplan_graph2plan_13395", + "group": "B", + "library_file": "x_13395.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "48a319449f68a58dafe6c432bfb71a0aa0b4ceb6a429d5445983104f3b99947a", + "plan_core_sha256": "ff45e1be3c06e331901a6c85c86f8c545f8c3d5da82f1a212318d1c3ddcac0a6", + "plan_sha256": "4cf06967b7a499e60a45ade357a11b169e3ac28146f89d808bccff54d0d21d21" + }, + "record": "13395", + "dining_side": "left" + }, + { + "case": "scene_014", + "plan_id": "rplan_graph2plan_14143", + "group": "B", + "library_file": "x_14143.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "a664fece7cf955c8f2d5755072f7a41bbc6931a44c728f11e8be9474b18245b8", + "plan_core_sha256": "339a1ff19b41e7b34883119c88dd92922591c7696e34d5745dd5a8e014c0b5af", + "plan_sha256": "5a06cf5367c6cc1b7d8b44829bbf8b6e07eb66947b6b86d671d34ddc07606dca" + }, + "record": "14143", + "dining_side": "bottom" + }, + { + "case": "scene_015", + "plan_id": "rplan_graph2plan_14903", + "group": "B", + "library_file": "x_14903.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "37ecbd89811ee1249c8ad81972096a3ad99290e42ff22893633dc7eae265d201", + "plan_core_sha256": "3ef031ef08a6e180bb1f38c52083d65005407e98bae1474a24c938b22cf6370d", + "plan_sha256": "89bf0363f5a4b0de0c7665daac3adabe5fcc5275d4d3d74bd4777a24724ec461" + }, + "record": "14903", + "dining_side": "right" + }, + { + "case": "scene_016", + "plan_id": "rplan_graph2plan_19207", + "group": "B", + "library_file": "x_19207.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "0274c0539ae96190c8d3703f01b9b907a779e99429e3c238825fe7ff8bf9dd64", + "plan_core_sha256": "0b9a22933137cff00006000f9228fa0a0405495c8dff88864f25510ae48208d7", + "plan_sha256": "aec23e1030198590f016c3e1230648f58d724537d60843a44d1f11e190ca8671" + }, + "record": "19207", + "dining_side": "top" + }, + { + "case": "scene_017", + "plan_id": "rplan_graph2plan_24727", + "group": "B", + "library_file": "x_24727.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "5496c3a0b7e748782159f48bebb094d118ac95dc0a1286561526288a91ee69bf", + "plan_core_sha256": "0f82fb01bfb2d9e9383d98d4fb73a8292b3802a29983f8371df7e7174b1558b4", + "plan_sha256": "eca417d728d339606af53b3c678161b38e31556f51c629225fbd4e55f8e41168" + }, + "record": "24727", + "dining_side": "right" + }, + { + "case": "scene_018", + "plan_id": "rplan_graph2plan_26376", + "group": "C", + "library_file": "x_26376.json", + "wrapper": "w_3b47d637bcdc", + "library_key_order": [ + "schema", + "source", + "source_record_count", + "options", + "screened_count", + "screening_options", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "rplan_screening" + ], + "expected": { + "rooms_sha256": "44505d1d05e2e597b267726f519453a7e0cf1dc0bec9a49f6c08b9405b05a681", + "plan_core_sha256": "f78afb21898a759fc4287dd46ec71f377238a11b1552abbd6a1d5a7d473e2a9d", + "plan_sha256": "f78afb21898a759fc4287dd46ec71f377238a11b1552abbd6a1d5a7d473e2a9d" + }, + "record": "26376" + }, + { + "case": "scene_019", + "plan_id": "rplan_graph2plan_28571", + "group": "B", + "library_file": "x_28571.json", + "wrapper": "w_1e0513e7d441", + "library_key_order": [ + "schema", + "source", + "provenance", + "plan_count", + "plans" + ], + "plan_key_order": [ + "plan_id", + "rplan_source_file", + "rplan_source_id", + "rplan_labels_present", + "rplan_conversion", + "rooms", + "open_room_type_pairs", + "wall_thickness_m", + "wall_height_m", + "topology_adjacencies", + "doors", + "wall_generation", + "windows" + ], + "expected": { + "rooms_sha256": "06c6823aad8424ceab612147dfbaed9f6c90471621a89ac2b94fa14285c80e87", + "plan_core_sha256": "5dd0c2cc42985b48137118c5591988c9f3cbd1fa4e707834064399c39d5d3743", + "plan_sha256": "b7e934e598f9b6ff0292abee0f766cf38470c4ac4c63d06e180e2f2f9aefdaea" + }, + "record": "28571", + "dining_side": "bottom" + } + ], + "shared_input_overrides": [ + { + "case": "scene_018", + "plan_id": "rplan_graph2plan_26376", + "record": "26376", + "group": "B", + "dining_side": "bottom", + "note": "The shared scene_018 input (rooms.json, floorplan.svg/png, used by every baseline) keeps the October conversion of record 26376; RoboHome reads the re-converted library x_26376.json because the October plan was dropped for a door defect.", + "expected": { + "rooms_sha256": "63ebcdaf17a36a8c3c4d48ab0f9298810251b077d8fc3a9487d3c3b12a995a61" + } + } + ], + "expected_inputs_sha256": { + "cases20/scene_000/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_000/floorplan.svg": "4c2871016441773012996728733c6b2416ea469084d3627ce225dc138b0b9c48", + "cases20/scene_000/request.txt": "2fc2a511afe2df55454e26f89cd3f34071850142ef7e566f23d593dd60726141", + "cases20/scene_000/rooms.json": "1bbedf9202c61f577ef22ccf8687b3ccb16b8a1e2014e6b45f45d5b910746817", + "cases20/scene_001/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_001/floorplan.svg": "0418982eb31f88d527cd9de68c54ba19f8894abea93a3ae102ecad2612bd8ec7", + "cases20/scene_001/request.txt": "95c3c17f1c61edc59032873461dd2553867d7363cb669a1202a881585feefbd8", + "cases20/scene_001/rooms.json": "b2b4bad0590ae33f61fa38463c88cdfebaa54f852e6866e078eb5e3fc50a0fb3", + "cases20/scene_002/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_002/floorplan.svg": "0879ce0ff48259a0414daa23f9ff66fcb185a1c23d68bf09ce33b5472615bb61", + "cases20/scene_002/request.txt": "b01692372576ef3422758c63aefd81c721823ec51db49894dca10b1087e132b4", + "cases20/scene_002/rooms.json": "2368d96e56f81b9c8494bfb4fef536a29c168768359c72980dc297bfe5310499", + "cases20/scene_003/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_003/floorplan.svg": "8e41a0b69d170613e4e1d777e41ed9945498b26120aa69a6eb8cfecef382d85e", + "cases20/scene_003/request.txt": "2163f91f467090e4875b549d411af7239948c39889e97eeff27c5b96e433be35", + "cases20/scene_003/rooms.json": "aa0764965ee8b9b2afca4d60bded71bb262564f41ab0743b2e154d64909135b7", + "cases20/scene_004/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_004/floorplan.svg": "01990e933100c813c9431646012db285cc4f9d85ba6568106a4ec46e7d6528b8", + "cases20/scene_004/request.txt": "92f06da0c945c52565004b2dadd0697132f125eeac050b984d87e672231ec925", + "cases20/scene_004/rooms.json": "2ed0209a7c0ba5560be5e8fe67906a4aa278b199b4af32ba6e378f267f03e677", + "cases20/scene_005/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_005/floorplan.svg": "a9412908d4dba2cdb2eb343cf87bb666d0a679e68773b550c228e0d5995c0e88", + "cases20/scene_005/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_005/rooms.json": "39212b009ec25adc12ee7cc415c828a2a7606d5fddf568eb57b6efb35bd6313b", + "cases20/scene_006/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_006/floorplan.svg": "4e3178aa57c7dea3d264f33af3eee15d56fa80790cc80ff1cc8d4c58e2f32fd3", + "cases20/scene_006/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_006/rooms.json": "6fc1d03f117c7a384338ebc1e48e2c9676d8937e2f05799fac5966378bfb31a5", + "cases20/scene_007/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_007/floorplan.svg": "935305e1f0076f8dfbd14cc3fcc54b4eeb7a021c46ba029a17ddbb3e62f86b47", + "cases20/scene_007/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_007/rooms.json": "f1dfab4b842c212d78d653836d6a9c0574d13e3604fb9ef8086ef1fc19388e83", + "cases20/scene_008/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_008/floorplan.svg": "f5f66da0770283daf7283a7c616cafa0109f2e4d6699ee38efdf1aa488303079", + "cases20/scene_008/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_008/rooms.json": "cf2c7781ecc90ac1790a42f1f0cdd1ae549a21c8c4b4880ed739d5ae47435eb7", + "cases20/scene_009/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_009/floorplan.svg": "0b357921aafc17ead25473c906947290d43d129c270555b8b176729e3685550d", + "cases20/scene_009/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_009/rooms.json": "508fc76ac59cf8541b240fc81c517a303c44da2601711c00cd0c922abf0305bc", + "cases20/scene_010/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_010/floorplan.svg": "23f7fdfdfe179b4570084913cb9dbc2004b661f17f47a518918ba72a67d31e7a", + "cases20/scene_010/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_010/rooms.json": "da280fe8bbac0bc7455afd06c8c8b9214b942c50a9600e532abfc55ea6866e87", + "cases20/scene_011/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_011/floorplan.svg": "b78b13b8717d7eef4bbacda00c3bb6ba37042568f99c15e6f14aee81f8456fb9", + "cases20/scene_011/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_011/rooms.json": "7543a1d2973ef547db66a051c34f6e1a6b9f176cc8149d1c7e38a2fa4f03af4b", + "cases20/scene_012/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_012/floorplan.svg": "96dd8257f1c4643f3a83496cd0545532aacd88ecd10456cecd8325000ea9e6ef", + "cases20/scene_012/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_012/rooms.json": "e2a465a304e649a5a2a482ba1fa04b80a4aa7fa15ee0aa07c336c6e52ff38722", + "cases20/scene_013/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_013/floorplan.svg": "36a20ca40170aa20ac75a95aafaf071a221932b0eb03ea9b377492a842bb052e", + "cases20/scene_013/request.txt": "c508c1397f328ba9af29523d9c061ae1fd1385b0100b0afe7e6882ac46dd16ff", + "cases20/scene_013/rooms.json": "02e71ae85bbeb70da836ac28394bf675ead74292a2971b01c8d6a6c400d53693", + "cases20/scene_014/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_014/floorplan.svg": "f3efb568beefbe00fee63ebb04a1fb9f669309013fba40f24a8f61af9d5de367", + "cases20/scene_014/request.txt": "95c3c17f1c61edc59032873461dd2553867d7363cb669a1202a881585feefbd8", + "cases20/scene_014/rooms.json": "de9b9d56fe0a45865624bc96aae732eda556a12a4683775a7a61c59004a01f31", + "cases20/scene_015/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_015/floorplan.svg": "0e225259fc27f8a0732e852e2eae84a19b7d6270cee3ff72e84e9ed6f63e8d72", + "cases20/scene_015/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_015/rooms.json": "7346fdd181373930491d7951ee16f10181a55b070e7a33ef00ea8dab231615e5", + "cases20/scene_016/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_016/floorplan.svg": "2354e481936fadc10a0fd1c19fb538fb30f3f92466e5bdf902a1da24f2b995d3", + "cases20/scene_016/request.txt": "c508c1397f328ba9af29523d9c061ae1fd1385b0100b0afe7e6882ac46dd16ff", + "cases20/scene_016/rooms.json": "4398e04b86689aec0065b1f73fcbb8e9031bfc585c56e4a497e1bc7aa0c588a1", + "cases20/scene_017/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_017/floorplan.svg": "5611c9e5cb94f1b12d21540c7f075b7cc4935b7f96d4ad1bda7252729746700a", + "cases20/scene_017/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_017/rooms.json": "74c56026ee8d4ddf8052cd645b62939757ed5227721b2269484945c63c2b6ed8", + "cases20/scene_018/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_018/floorplan.svg": "e07b65fe62ff69236de0b5cb067f9a0324323a6fe203b9f2983b38cd0ad1d9be", + "cases20/scene_018/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_018/rooms.json": "e5dffc701661c37a0e2a300bee634ab6fef805541c752525e4d49a8f2ce67589", + "cases20/scene_019/entities.json": "f12719254275e455f1adee1d3b98b525115f569460b7efc5eb5ff4a1768d473e", + "cases20/scene_019/floorplan.svg": "ecc771b025a68c7cc42a9d77b9f1416a635ff075db49c119a35a5b51668befe9", + "cases20/scene_019/request.txt": "82bf1fe0c435a6ab4cb1f7f6747e73643fc05a3ed693177933844697231cdee6", + "cases20/scene_019/rooms.json": "eecdabaf2ffd6d5db42273783dfc2dbc279c66ad076202c43f1e693733e38220" + } +} diff --git a/docs/reproduction/public_conversion_code/README.md b/docs/reproduction/public_conversion_code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..262ee920b92d8473919101f9916aefb55199a204 --- /dev/null +++ b/docs/reproduction/public_conversion_code/README.md @@ -0,0 +1,391 @@ +# RoboHouseGen + +2026-10-26: [Wholehouse V25 handoff](releases/wholehouse-v25/README.md) provides the +frozen seven-room generation chain, sealed example inputs, configurable runtime +mounts, indoor rendering and actual door dynamics behind one runnable entrypoint. +See its setup and verified-scope notes before running a new environment. + +2026-10-21:交付烘焙增加默认 6GiB 场景贴图预算,源 PBR 与预算结果分目录保存。 +预算包默认导出 BC7 颜色与 PNG8 非颜色通道;实际消费显存需独立验证。 +参数和显式旧行为对照见[纹理预算策略](docs/texture-fidelity-policy.md)。 + +The real-asset household generator defaults to the verified joint layout/assembly chain. It requires an explicit request; [automatic request/evidence completion remains a separate integration](docs/joint-default-generation.md). + +For the real-asset household scene pipeline, see [the pipeline guide](README_PIPELINE.md), +[automatic per-server asset setup](docs/asset-bundle-setup.md), +[offline prepared asset pools](docs/prepared_asset_pool.md), +[automatic native cabinet and drawer joints](docs/native-articulations.md), +[the offline upper-cabinet hinge pilot](docs/upper-cabinet-pilot-20261015.md), +[the reviewed static-cabinet expansion](docs/cabinet-expansion-20261016.md), +[the minimal cabinet repair results](docs/cabinet-minimal-repair-20261016.md), +[the 23-cabinet root-cause follow-up](docs/cabinet-root-cause-20261017.md), +[the 52-source native-cabinet acceptance](docs/native-cabinets-52-20261018.md), +[the GPT-6 batch articulation workflow](docs/articulation-auto.md), +[official MDL SDK setup and material conversion](docs/official-mdl-pipeline.md), +[native-size joint layout and publication rendering](docs/style_joint_generation.md), and +[the 2026-10-13 acceptance results](docs/prepared-pool-results-20261013.md). +The [2026-10-14 per-asset usability release](docs/asset-usability-20261014/README.md) +publishes category counts, the qualified furniture index, attribute schema and sealed +code/evidence receipts for 29,577 inspected records, including 5,715 usable furniture +and furniture-set records. This is static asset qualification, not robot physics approval. +The [asset expansion dashboard](docs/asset-expansion-20261022/README.md) +now includes 63 additional source model packages for offices, classrooms, libraries, +homes and lobbies, with bilingual rich descriptions, evidence-bound style labels, +room filters and separate glTF/USD source checks. One shelf has a recorded glTF scale +discrepancy and remains blocked for placement. Download and reproduction scripts are +in [the multi-scene supplement](scripts/asset_multiscene_20261030/README.md). +These candidates are not new sealed-pool admissions. +The [full-inventory style catalog](docs/asset-expansion-20261022/style_catalog/README.md) +adds evidence-bound `style` and `style_tags` metadata across registered assets, +archive members, materials, environment maps and new candidates. Unknown and +conflicting styles remain explicit. Optional `query_assets.py --style` filtering +uses a separate read-only index and preserves existing source and geometry checks. +Default generation also reuses selected, prepared native furniture joints, +validates their motion in the full house, and packages the resulting runtime. +This pipeline requires the external asset libraries and runtime paths described in its guide; +generated scenes, asset payloads, and prepared database files are stored separately. + +Current product release: **fast**. The public benchmark/API compatibility version remains +`0.1.0`; `fast` names the optimized product implementation, not generated scenes. Scene and +case identifiers therefore use ordinary semantic names without release or host prefixes. + +RoboHouseGen is an open-set humanoid benchmark generator. It retrieves and composes +verified task skills, asks SceneSmith for a task-compatible household scene, overlays a +robot embodiment, validates the result in Isaac Lab-Arena, and compiles deterministic +simulator-truth evaluators. + +**Start here:** [`docs/INPUT_OUTPUT_CONTRACT.md`](docs/INPUT_OUTPUT_CONTRACT.md) defines the +complete user input, internal contracts, output directory, preview/timing artifacts, and +portable delivery format. New benchmark scenes are YAML/JSON configuration; they do not +require changes to Python source files. + +## Benchmark previews + +### Bedroom transfer + +![Bedroom transfer benchmark preview](videos/bedroom/preview.gif) + +### Reading-room bottle disposal + +![Reading-room bottle disposal benchmark preview](videos/reading-room/preview.gif) + +The initial embodiment catalog contains Unitree G1, Fourier GR1T2, and RP1.3. Tasks are +robot-independent: a capability matcher decides whether an embodiment can instantiate a +task and records the reason when it cannot. + +## Local development + +```bash +uv sync --extra dev +uv run rhg doctor +uv run rhg catalog stats +uv run rhg task generate --prompt "carry a box to a table" +uv run uvicorn apps.api.main:app --reload +``` + +For a Conda-based host environment: + +```bash +conda env create -f environment.yml +conda run -n robothousegen python -m pip install -e ".[dev]" +conda run -n robothousegen pytest -q +``` + +The API serves the built web catalog from `web/dist` when it exists. During frontend +development, run `npm install && npm run dev` in `web/`. +The asset contract and RoboLab scene-gen compatibility profile are available at +`/docs/assets` or directly in `docs/ASSET_INTERFACE.html`. + +## Quality checks + +```bash +uv run ruff check . +uv run ruff format --check . +uv run mypy apps packages +uv run pytest -q +``` + +GPU and Isaac tests are separate because SceneSmith, EmbodiedGen, and Isaac Sim must not +be installed into the core Python environment. + +## Relay media and curated assets + +The OpenAI-compatible relay reads credentials only from `IMAGE2_API_KEY`; see +`.env.example` for non-secret settings. Generate, edit, or inspect an image with +`uv run python scripts/relay_media.py`. `MULTIMODAL_API=auto` prefers Responses and +falls back to Chat Completions for relays that do not expose Responses. + +The same operations are available through `rhg media` and the `/v1/generative/*` API. +`GET /v1/generative/status` reports configuration without returning credentials. +SAM 3D Objects is integrated as an isolated worker through `rhg sam3d`; run +`rhg sam3d doctor` before generation. The adapter requires both the SAM3 checkpoint and +the SAM 3D Objects `pipeline.yaml`. `SAM3D_MEMORY_STRATEGY=staged_process` runs SAM3 +segmentation and SAM3D reconstruction in isolated processes, optionally on two GPUs, so +the segmentation model and CUDA context are fully released before reconstruction. This +reduces peak residency but does not pretend that two 24 GB cards are one 48 GB card. +FSDP is rejected explicitly because the upstream custom sparse inference pipeline is not +rank-synchronous or FSDP-safe. The staged path remains experimental until it passes a full +reconstruction on an idle RTX 4090. +`scripts/sam3d_worker.py` implements the protocol against SceneSmith and exports a validated +GLB plus `sam3d_manifest.json`; invoke it from the isolated SceneSmith Conda environment. + +`rhg benchmark build --backend scenesmith` runs the strict end-to-end scene path. The core +agent compiles a `TaskSpec`, `SceneRequestCompiler` creates the RoboLab-compatible request, +and `scripts/scenesmith_worker.py` enriches it with the merged retrieval catalog before +running all SceneSmith stages. The worker exports the final Blender scene to USD and only +returns success when every requested task entity is bound to a generated SceneSmith object. +Use `scripts/run_remote_benchmark.sh` on the deployed host to load the relay credentials, +force strict SceneSmith mode, and enable Poly Haven preview lighting/materials. +Use `rhg scene doctor` to inspect the isolated runtime and `rhg scene compile-request` to +inspect the exact wire request without launching generation. Deployment details and failure +semantics are documented in `docs/SCENE_GENERATION_PIPELINE.md`. + +New scenes are declarative. Use a benchmark YAML instead of adding a Python scenario: + +```bash +RHG_TASK_AGENT=generative rhg benchmark build \ + --spec examples/bedroom_transfer.yaml \ + --out runs/bedroom-transfer +``` + +### Prompt-to-scene remote runner + +For manual remote generation, use `scripts/prompt_to_scene.py`. It accepts one natural-language +request, asks the Scene Design Agent to fill the structured benchmark contract, validates the +result, and then invokes the existing benchmark builder. Users do not need to author separate +task, scene, asset, and iteration YAML files. + +On 4090-5: + +```bash +cd /data/wyc/RoboHouseGen +source configs/runtime/4090-5.env + +# 4090-5.env provides the GPT Responses planner and the separate Image2 relay. +echo "$RHG_PLANNER_BASE_URL $RHG_PLANNER_MODEL $RHG_PLANNER_API" + +$RHG_CORE_PYTHON scripts/prompt_to_scene.py \ + --prompt "生成一个办公室,机器人把木桌上的纸箱双手抱起,经过门进入另一间房,放到圆桌上" \ + --out /data/wyc/RoboHouseGenData/runs/prompt-office-box-transfer +``` + +The default is a fast single-attempt build. Use a prompt file, a full Supervisor campaign, or a +design-only validation as follows: + +The default `--pipeline asset_first` is the real visual-scene path: it performs ACTIVE asset +retrieval, metric placement, Blender composition, five-view checks, and MP4 publication. The +legacy structured benchmark path is still available explicitly with `--pipeline benchmark`. + +Prompt generation uses two Agent layers by default. The first Agent freezes the task, rooms, +supports and manipulated object. The second Enrichment Agent applies the room-motif priors +aligned from the 4090-14 main project and adds up to five realistic context objects such as a +bed/nightstand/lamp grouping, sofa/side-table grouping, armchair and potted plant. Directional +storage enrichment remains disabled until the certified-front index has broader coverage. +It cannot modify task entities or architecture, and enriched furniture must still pass ACTIVE +asset retrieval, front certification, collision, route and Prompt-fidelity gates. At least one +plant and one practical lamp are required unless the Prompt explicitly forbids them. + +Use `--no-enrichment` for sparse task-only scenes, `--context-object-limit 2..6` to control +density, or `--enrichment-attempts N` to change the correction budget. Each run records the +second Agent under `inputs/generated_enrichment.json` and in +`prompt_to_scene_manifest.json.enrichment_audit`. + +```bash +$RHG_CORE_PYTHON scripts/prompt_to_scene.py \ + --prompt-file request.txt \ + --out /data/wyc/RoboHouseGenData/runs/prompt-case \ + --no-single-attempt \ + --max-total-attempts 10 \ + --time-budget 7200 + +$RHG_CORE_PYTHON scripts/prompt_to_scene.py \ + --prompt "生成一个带门的双房间箱子搬运任务" \ + --out /data/wyc/RoboHouseGenData/runs/design-only \ + --dry-run + +# Legacy lightweight benchmark manifest only (no asset-first Blender render): +$RHG_CORE_PYTHON scripts/prompt_to_scene.py \ + --pipeline benchmark \ + --prompt "生成一个办公室并把箱子从木桌搬到圆桌" \ + --out /data/wyc/RoboHouseGenData/runs/legacy-case +``` + +Useful controls include `--backend`, `--generation-profile`, `--orchestration-mode`, +`--max-parallel-attempts`, `--critic-min-score`, `--design-attempts`, `--design-timeout`, +`--planner-base-url`, `--planner-model`, `--planner-api-key-file`, and +`--skip-model-check`. `--overwrite` is enabled by default, so an existing exact `--out` +directory is replaced immediately before the build starts; use `--no-overwrite` to preserve +the previous refusal behavior. Project, data-root, runs-root, filesystem-root, and symlink +targets are always rejected by the safety guard. The generated +structured inputs and planner audit are stored at `inputs/generated_case.yaml`, +`inputs/generated_case.json`, and `prompt_to_scene_manifest.json`. + +When the Agent declares two or more required rooms, the asset-first path promotes the +validated furniture placement to Metric V3. The run then contains +`metric_layout_spec_v3.json` with explicit `rooms[]`, `portals[]`, room ownership and the +cross-room route, plus `multi_room_validation.json` and `prompt_fidelity_report.json`. +Interior doors are structural portal geometry; they never enter furniture retrieval and +cannot replace a source support that happens to share the `CONTEXT` role. + +Without an explicit `--seed`, each invocation draws a new system-random 32-bit seed. That +seed controls the room split axis, furniture placement preference, full asset-candidate +rotation, material palette, lighting preset and camera side, so repeated runs of the same +Prompt are diverse by default. Pass `--seed N` for exact reproduction, or use +`--seed-mode prompt` to derive a stable seed from the Prompt as in older releases. +Explicit material and shape words such as `wood`, `cardboard`, and `round` are hard retrieval +constraints. Verified canonical USD assets can be imported directly alongside GLB/GLTF; +post-import dimensions, footprints and yaw must still pass the same geometry checks. + +Every successful asset-first output also contains `reports/`. The `layout/` subdirectory +holds the Metric V3 2D layout, the actual rendered orthographic top view, and the +asset-placement blueprint. `asset_dashboard.html` is self-contained and reports assets used +by the scene, ACTIVE inventory by source library and category, average geometry/material/ +realism quality, A-D quality distribution, formats, licenses, and Isaac-ready coverage. The +same machine-readable data is stored in `asset_inventory.json`; `report_manifest.json` +records hashes for every report artifact. + +Each successful run writes `randomization_manifest.json` with its effective seed, seed +source, selected assets, entity poses, split axis, materials, lighting, cameras, final-frame +hashes and a complete scene fingerprint. Verify repeated-run diversity with: + +```bash +$RHG_CORE_PYTHON scripts/compare_scene_diversity.py \ + /data/wyc/RoboHouseGenData/runs/repeat-a \ + /data/wyc/RoboHouseGenData/runs/repeat-b \ + --output /data/wyc/RoboHouseGenData/runs/repeat-diversity.json +``` + +The comparison requires unique seeds/fingerprints, different final frames, and differences +in at least two of asset selection, layout/poses, materials/lighting, and cameras. + +The runtime keeps two independent API identities: `IMAGE2_*` uses `gpt-image-2` for image +generation, while `OPENAI_*`/`RHG_PLANNER_*` uses `gpt-6-astra` over the Responses wire API with +`xhigh` reasoning and response storage disabled. Use `--skip-model-check` only when a custom +planner endpoint intentionally omits `/models`. + +Full option and contract details are in [`docs/PROMPT_TO_SCENE.md`](docs/PROMPT_TO_SCENE.md). + +Build a multi-episode suite with one shared scene in the same way: + +```bash +rhg benchmark build-suite \ + --spec examples/all_tasks_shared_scene_v1.yaml \ + --out runs/all-tasks-shared-scene +``` + +Validate all YAML/JSON references, task templates, factors, entity IDs, asset locks and +domain-randomization operations without starting a GPU backend: + +```bash +rhg benchmark validate-suite --spec examples/all_tasks_shared_scene_v1.yaml +``` + +The suite YAML owns the scene, matrix, robot, evaluator, runtime, output policy, and asset +lock. Its external task library owns entities, skills, stages, predicates, factor bindings, +and per-condition overlays. Adding a scene or task must not add a Python branch. Python is +only required for a genuinely new backend, controller primitive, asset decoder, or physical +predicate implementation. + +Natural-language aliases and task compilation profiles live in +`configs/task_agent/compiler_v1.yaml`. Per-episode domain-randomization operations live in +`configs/scene_generation/domain_randomization_v1.yaml`; the builder validates them before +scene generation and authors them into the stronger `layers/episode_overrides.usda` layer. +Every suite freezes the effective policy under `inputs/`, so the generated benchmark remains +auditable and portable. + +Before SceneSmith starts, the worker compiles task predicates and declarative context assets +into `scene_dependency_graph.json`. Independent dependency subtrees retain ownership through +asset generation, manipulation placement, local critique, and physics checks; topology waves +prevent a child from running before its supports exist. Defaults live in +`configs/scene_generation/dependency_graph_v1.yaml`, while benchmark-specific dependency and +scheduler overrides live in context/asset-lock JSON. No room-specific Python branch is needed. + +`rhg schema export --out schemas` exports `BenchmarkSuiteBuildRequest.schema.json` alongside +the runtime contracts. Unknown `scene`, `runtime`, and `output` keys are rejected before any +run directory or SceneSmith process is created; evaluator-specific thresholds remain an +explicitly extensible policy map. + +Room vocabulary, source priorities, and visual quality rules are configured in +`configs/generation_policy.yaml`. New assets are `AssetCatalog` JSON records and can be merged +with `scripts/merge_asset_catalogs.py`; neither operation requires a Python import or branch. + +Download the CC0 visual catalog with +`uv run python scripts/download_polyhaven_assets.py --root /path/to/data/assets`. +The resulting `catalog.json` can be passed to both isolated upstream adapters. New assets +remain Tier B and cannot be used for formal scoring until Isaac scale, collision, mass, +and articulation QA promotes them. `scripts/convert_asset.py` converts common mesh +formats to USD, and `scripts/render_scene_preview.py` creates an orbit MP4. + +## High-fidelity asset preprocessing + +`scripts/preprocess_high_fidelity_assets.py` converts the complete managed GSO and +PolyHaven source packages into a separate canonical USD library. It never modifies the +immutable `assets/raw` or `assets/staged` packages. The canonical copies use Z-up metres, +have explicit `UsdPhysics.CollisionAPI` on each mesh, retain PBR texture packages, and are +validated through the USD runtime before descriptor release. + +The release adds searchable rich tags for source/category/subcategory, PBR channels, +quality scores, width/depth/height, footprint, size class, support type, collision type, +articulation, canonical coordinate frame, and functional-front confidence. Only assets that +pass the full geometry, dependency, collision, dimensions, orientation and multiview checks +become `ACTIVE`; failures stay in the versioned plan with an explicit reason. + +Each `rich_retrieval_documents.json` entry also contains an `orientation` contract. It states +the canonical `+Z`/`-Z` frame, certified functional front, back/right/left axes when known, +confidence/evidence provenance, symmetry, and a placement policy. Asset selection may use +`directional_placement_allowed` for chairs, storage, beds, and displays only when the +functional front is certified. `directional_placement_blocked` is fail-closed: the asset may +remain searchable but cannot be requested to face a target or wall. Direction-neutral assets +use either `rotationally_symmetric_no_front_required` or `visual_orientation_optional`; their +geometric yaw is not reported as a verified semantic direction. All placement rejects roll, +pitch, and inversion, preserving canonical Z-up. + +To enrich an already released index without reconverting or moving any asset files, derive a +new immutable index and source its activation file: + +```bash +$RHG_CORE_PYTHON scripts/enrich_asset_orientation_index.py \ + --input-index "$RHG_ASSET_INDEX" \ + --output "$RHG_ASSETS_ROOT/high_quality/h20-aligned/index-v12-rich-orientation-4090-5-20260901" +source "$RHG_ASSETS_ROOT/high_quality/h20-aligned/index-v12-rich-orientation-4090-5-20260901/activate_runtime.env" +``` + +This only rewrites index metadata in the new output directory. It preserves the input index, +asset paths, hashes, and ACTIVE/QUARANTINED status unchanged. + +On 4090-5, the full run is resumable. Re-running the same command reuses completed canonical +assets and continues failed or pending work: + +```bash +cd /data/wyc/RoboHouseGen +source configs/runtime/4090-5.env + +$RHG_CORE_PYTHON scripts/preprocess_high_fidelity_assets.py \ + --asset-root "$RHG_ASSETS_ROOT" \ + --output "$RHG_ASSETS_ROOT/certified/high_fidelity_complete_20260901" \ + --base-index "$RHG_ASSET_INDEX" \ + --stage all \ + --include-base-active \ + --blender "$BLENDER" \ + --usd-python "$RHG_USD_PYTHON" \ + --blender-batch-size 24 \ + --usd-batch-size 128 \ + --release-workers 8 +``` + +Use `--stage discover`, `--stage convert`, or `--stage release` to run a single phase. Use +`--sources gso`, `--sources polyhaven`, and `--limit N` for a bounded smoke run. Do not pass +`--allow-partial-release` for a production index: it exists only for diagnosing a subset. + +The complete run writes `preprocess_plan.json`, `prepared_catalog.json`, conversion jobs, +`descriptor_release/`, `active_index/asset_descriptor_index.sqlite3`, and +`active_index/rich_retrieval_documents.json` below the chosen output directory. The generated +ACTIVE index is a new version; it does not overwrite the previous directional index. +After a complete release, `/activate_runtime.env` is written. Source this file after +`configs/runtime/4090-5.env` to opt into the newly promoted high-fidelity index. + +Robot-aware asset-first task generation is enabled by default. Select Luna, G1 or +RP1; omit the choice for their strict common constraints. The web form, API and +CLI expose the selection and adaptation summary. See the +[robot task constraints guide](docs/robot-task-constraints.md) for geometry-only +complete generation, explicit legacy controls and independent verification. diff --git a/docs/reproduction/public_conversion_code/configs/assets/front_axis_overrides_v1.json b/docs/reproduction/public_conversion_code/configs/assets/front_axis_overrides_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..1b1ea3627adf9df2ce53e7c5d12b02f2f64d574b --- /dev/null +++ b/docs/reproduction/public_conversion_code/configs/assets/front_axis_overrides_v1.json @@ -0,0 +1,42 @@ +{ + "schema_version": "1.0", + "description": "Hash-bound semantic-front certifications from material-aware cardinal-view inspection. These change metadata only; source geometry and canonical transforms remain immutable.", + "overrides": [ + { + "asset_id": "hssd:objects/8/8a6d4da5fe54288ffdebffb09bce0005cbc2c0eb", + "asset_sha256": "ffd3bf8afffd587171c2134f7aa5228df4a230d796a2dd94fc58358bbc216f8e", + "front_axis": "-Y", + "source": "multiview_verified", + "confidence": 0.99, + "evidence": [ + "/data/wqz/robothousegen-wyc-runs/asset-first-mediterranean-lounge-front-aware-20260827-001/front_direction_diagnostic/lounge_chair_a__certified_front.png", + "/data/wqz/robothousegen-wyc-runs/asset-first-mediterranean-lounge-front-aware-20260827-001/front_direction_diagnostic/lounge_chair_a__certified_back.png" + ], + "note": "The seat opening and usable sitting direction are visible from canonical -Y; canonical +Y shows the solid rear shell." + }, + { + "asset_id": "hssd:objects/6/650eafedcc551cb48130abb49b7343157db87f87", + "asset_sha256": "0130b8127e3da58dfda8acd36fa2cf66cfd0f2e6e5db68a14482cc74ddf375e1", + "front_axis": "-Y", + "source": "multiview_verified", + "confidence": 0.99, + "evidence": [ + "/data/wqz/robothousegen-wyc-runs/asset-first-mediterranean-lounge-front-aware-20260827-001/front_direction_diagnostic/lounge_chair_b__certified_front.png", + "/data/wqz/robothousegen-wyc-runs/asset-first-mediterranean-lounge-front-aware-20260827-001/front_direction_diagnostic/lounge_chair_b__certified_back.png" + ], + "note": "The seat opening and usable sitting direction are visible from canonical -Y; canonical +Y shows the solid rear shell." + }, + { + "asset_id": "hssd:objects/f/ffdeb9fd68534d011e087672596421f9d00dada0", + "asset_sha256": "c7868bc8f12dac5f2eccad3326f21b137901489d3e8918976e6d04d6a5d26b7d", + "front_axis": "-Y", + "source": "multiview_verified", + "confidence": 0.99, + "evidence": [ + "/data/wqz/robothousegen-wyc-runs/asset-first-mediterranean-lounge-front-aware-20260827-001/front_direction_diagnostic/floor_speaker__certified_front.png", + "/data/wqz/robothousegen-wyc-runs/asset-first-mediterranean-lounge-front-aware-20260827-001/front_direction_diagnostic/floor_speaker__certified_back.png" + ], + "note": "The acoustic grille is visible from canonical -Y; canonical +Y shows the plain rear cabinet panel." + } + ] +} diff --git a/docs/reproduction/public_conversion_code/docs/asset-bundle-setup.md b/docs/reproduction/public_conversion_code/docs/asset-bundle-setup.md new file mode 100644 index 0000000000000000000000000000000000000000..7bbf00fa85af79d579bde7799371065d12bb4b94 --- /dev/null +++ b/docs/reproduction/public_conversion_code/docs/asset-bundle-setup.md @@ -0,0 +1,84 @@ +# 自动适配的资产配套 + +默认场景入口使用 `configs/asset_bundle.release.json` 固定资产配套版本。 +代码按清单哈希识别配套,不用服务器名称或目录存在与否推断兼容性。 +当前配套是 `rhg_asset_bundle_20261013_v2`:31 类角色、3,556 个合格候选版本, +15,859 个载荷文件,约 11.94 GB;压缩传输约 6.58 GB。 + +## 已配置的服务器 + +下载代码后直接运行: + +```bash +python3 scripts/query_assets.py --stats +python3 scripts/run_generate_scene.py +``` + +入口读取个人配置 `~/.config/rhg/asset_bundle.json`,没有个人配置时读取 +`/etc/rhg/asset_bundle.json`。配置记录该服务器实际可读的 NAS 或镜像位置。 +Python、Blender、标注索引、离线池和户型输入从固定清单解析;新场景的输出、 +缓存、使用历史及临时文件放在当前账号可写的位置。 + +机器安装和验收状态见 [服务器部署记录](asset-bundle-servers-20261013.md)。 +个人可用 `RHG_BUNDLE_REGISTRATION` 指定另一份安装配置。 + +## 配置新机器 + +已有同版本共享配套时: + +```bash +python3 scripts/setup_asset_bundle.py --nas-root /path/to/NAS-H-Share \ + --state-root /path/to/writable/local/state --install-system-deps +``` + +没有共享存储时,使用有权限的远端源直接传输: + +```bash +python3 scripts/setup_asset_bundle.py --sync \ + --source USER@HOST --ssh-command 'ssh -p PORT -i KEY -o BatchMode=yes' \ + --destination /path/to/local/bundles/rhg_asset_bundle_20261013_v2 \ + --state-root /path/to/writable/local/state --install-system-deps +``` + +源需提供该配套的 `download.json` 和 `payload.tar.gz`。部署中的 SSH 账号被限制为 +只读此版本的分发目录;不在 GitHub 分发私钥或资产访问凭据。 +普通 SSH 源可用 `--source-path` 指定远端配套目录。默认传输限制为 16 MiB/s, +可用 `--bandwidth-kib` 调整。未完成的传输保留,重新执行可续传。 + +安装校验代码锁定的下载回执、压缩包以及每一个解包文件,再恢复相对链接。 +共享镜像的其他消费者复用该安装校验记录;每次生成仍校验池身份和选中来源的依赖。 +出现哈希变化会停止,不会改用同名旧库或临时挑选未经准备的资产。 + +## 主机运行时 + +支持 Linux x86-64。配套包含已验证的 Python、Pillow、Blender、BasisU 和必要 MDL +文件;显卡驱动属于主机环境。`--install-system-deps` 只安装识别到的缺失系统库, +当前支持 `libxkbcommon0`、`libxfixes3`,不会升级驱动。 + +网络存储上的 Blender 启动超时时,安装器会将同哈希的运行时复制到本机缓存。 +也可主动指定 `--runtime-cache /path/to/local/runtime`。复制按固定清单校验,不改 +Blender 版本、资产导入规则或验收阈值。 + +原资产记录中的路径通过进程自己的只读挂载空间提供。需要路径别名的账号需有 +`sudo -n unshare` 权限;已有全部匹配原路径的主机可直接执行。原系统挂载和其他任务 +不被覆盖。不要只手工改 SQLite 内的路径,这会破坏已封存的来源和材料身份。 + +## 范围与版本 + +这是合格家庭场景生成的运行配套,包含候选来源、结构材质、HDRI、索引和运行时, +不是整个历史资产库的完整归档。未合格候选、隔离项及元数据待补状态保持原记录; +完整离线诊断历史仍在源存储。新增角色或更换导入实现需离线生成新的封存版本。 + +生产默认户型为仓库内 `configs/floorplans/rplan_production_25.json` 的全部 25 个户型, +随代码发布;资产配套中冻结的旧户型输入不再覆盖这个默认值。 +`qualified_random` 从这 25 个户型中选择,显式 `--rplan-seeds` 仍可指定其他输入。 +此前电视越界的失败和旧户型验收结果保留;设为生产输入不代表 25 个户型的每个 +资产组合都已通过完整生成。资产配套和机器人完整物理任务的验收分开记录。 + +旧任务继续使用其保存的配置。显式配置 `"asset_bundle": null` 可停用自动适配, +此时必须提供完整的原有路径设置。不要将新安装配置覆盖到历史场景的冻结配置中。 + +本次切换已核对 25 个唯一户型、25 个均无拓扑硬拒绝,固定种子的 25 次选择覆盖全部户型。 +4090-13 使用新默认输入完成一轮完整场景生成(组装、保存读回、GPU 渲染、打包), +退出码 0,耗时 292.88 秒;这不等同于 25 轮完整生成。 +详见 [生产户型切换回执](evidence/production-floorplans-25-20261013.json)。 diff --git a/docs/reproduction/public_conversion_code/docs/official-mdl-pipeline.md b/docs/reproduction/public_conversion_code/docs/official-mdl-pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..693431e32e96ba590149ce19048e4fc13ca09316 --- /dev/null +++ b/docs/reproduction/public_conversion_code/docs/official-mdl-pipeline.md @@ -0,0 +1,270 @@ +# Official MDL material pipeline + +When Blender leaves an authored USD MDL material unconnected, the pipeline uses +NVIDIA MDL SDK to load the module, construct its typed call graph, compile it, +distill it to `transmissive_pbr`, and bake channels before building Blender +nodes **during offline asset preparation**. Connected native material graphs remain unchanged. Missing inputs or +resources produce explicit failures; there is no gray fallback or substituted +material. + +## Remote setup + +The pinned worker currently targets Linux x86-64 and the official CPython 3.10 +binding. Install on the rendering server; the archive is about 315 MB. + +```bash +python scripts/setup_mdl_sdk.py \ + --install-root /remote/tools/mdl-sdk/2026.0.2 \ + --worker-python /remote/python310/bin/python +``` + +The installer verifies the official archive SHA256 and prints configuration +fields. Add those fields to the offline preparation configuration. The scene +configuration retains the producer identity for verification, but the whole-house +process cannot compile or bake MDL: + +```bash +python scripts/prepare_asset_pool.py worker --pool /remote/new-pool \ + --lookup /remote/annotation-lookup.sqlite3 + +python scripts/validate_material_assets.py init \ + --pool /remote/new-pool --out /remote/material-validation +python scripts/validate_material_assets.py worker \ + --out /remote/material-validation --gpu 0 +``` + +The default bake resolution is 1024. `mdl_search_paths` must contain the actual +source module packages and their dependencies. Module filenames and loaded SDK +module identities must agree. Authored texture filenames are imported through +the SDK image database; they are not confused with absolute MDL resource names. +An authored color-space declaration takes priority; otherwise the SDK's typed +parameter default supplies texture gamma. + +`mdl_backend: legacy` is an explicit compatibility control. It preserves the +former limited translator for frozen comparisons and is never an automatic +fallback after an SDK error. This control also prepares its material libraries +offline. + +The worker writes packed `.blend` material libraries and immutable manifests. +Each manifest binds source/runtime hashes, the canonical matrix, Blender +version, source mesh topology, UVs, polygon material indices, ordered material +slots, normalized node graphs and decoded image pixels. It reloads the saved +library before accepting serialization. Native graphs are preserved. + +Run independent image review on the four views of each material-validation case. +Save a `results//appearance_review.json` with `passed: true` only after +acceptance and `render_sha256` equal to that case's `render.json` SHA256; include +the reviewer, method, criteria and findings. A readability review does not certify +lossless MDL equivalence. Failed and pending reviews remain outside the sealed +pool. Then seal the evidence and pool: + +```bash +python scripts/seal_material_acceptance.py --bench /remote/material-validation \ + --out /remote/material-acceptance +python scripts/prepare_asset_pool.py finalize --pool /remote/new-pool \ + --material-artifact-index /remote/material-acceptance/index.json +``` + +An explicit `--allow-visual-adjudications` option can include separately recorded +`visual_adjudication.json` decisions. Such a decision must name the reviewer and +reason and bind the original rejected review, current render report and reviewed +image sheet by SHA256. The automated rejection remains in the evidence and the +summary reports adjudicated acceptances separately. + +For assets already prepared and reviewed independently, pass that same index to +`prepare_asset_pool.py worker --material-artifact-index ...` to reuse the exact +library. Whole-house execution always forces `scene_load_only`, verifies the +manifest, library, acceptance evidence and source identity, and binds the saved +materials to their original slots. Missing results fail explicitly. The assembly +audit records zero MDL compile requests and library graph/pixel checks; subsequent +save/reopen/render checks test integration, not asset material acceptance. + +## Separate gates + +1. **Compile:** module and typed parameter resolution, source/runtime identity, + connected calls, dependency and active-resource hashes. +2. **Distill and bake:** target name, SDK version/binaries, worker code, + constant/texture results, linear EXR hashes, UV range and state dependencies. +3. **Bind:** exact USD mesh/material bindings, preservation of native graphs, + Blender node reconstruction and unchanged source geometry. +4. **Appearance:** independent review of actual images. Successful compilation, + a connected graph, or a nonblank image does not pass this gate automatically. + +Distillation is an approximation. Principled reflection/transmission tint and +thin-wall differences are recorded; they are not called lossless. Source volume +absorption/scattering coefficients are baked directly and mapped to volume +nodes. Nonzero displacement requires explicit geometry preparation. Unsupported +state dependencies, scene data, animation and UDIM contracts remain failures +instead of silently becoming constants. + +## Prepared pools and shared attributes + +Create a new prepared-pool directory and cache when the runtime or material +pipeline changes. SDK code, binaries, bake resolution and search paths are part +of translated-material preparation identity. Old translated probes do not +become SDK-qualified by changing a path or copying a success flag. Native graph +preparation retains its separate identity. + +```bash +python scripts/prepare_asset_pool.py init --pool /remote/new-pool \ + --catalog /remote/frozen-catalog.sqlite3 --config /remote/runtime.json +python scripts/prepare_asset_pool.py worker --pool /remote/new-pool \ + --lookup /remote/annotation-index.sqlite3 +# After independent asset validation and sealing described above: +python scripts/prepare_asset_pool.py finalize --pool /remote/new-pool \ + --material-artifact-index /remote/material-acceptance/index.json +``` + +Repaired source variants keep their own runtime hashes and derivation records. +Shared style evidence must match the selected source, canonical frame and +material pipeline. The consumer does not edit the shared attribute release. + +To prepare a released repair manifest, add +`--runtime-release-manifest /remote/release/available_models.jsonl` to the pool +`init` command. This freezes the release, original source, derived runtime and +repair-provenance hashes. Changed bytes receive a distinct candidate key and +fresh geometry, material and support measurements. The release's historical +`source_runtime_eligibility` flag is recorded as context; the new preparation +results determine qualification. An absent or ambiguous release match remains +an explicit failed candidate. The original source file stays unchanged. + +Material substitutions are rejected unless `--allow-material-substitutes` is +explicitly passed. That flag admits a labelled variant for testing; it does not +certify recovery of the original material. Old shared appearance records cannot +qualify a changed runtime identity. + +Changed runtimes also require an independent source/runtime pair check: + +```bash +python scripts/qualify_runtime_release.py init --pool /remote/new-pool --out /remote/pairs +python scripts/qualify_runtime_release.py worker --pool /remote/new-pool --out /remote/pairs \ + --material-artifact-index /remote/material-acceptance/index.json +python scripts/prepare_asset_pool.py worker --pool /remote/new-pool \ + --lookup /remote/annotation-lookup.sqlite3 --runtime-material-pairs /remote/pairs +``` + +Run multiple pair workers to claim independent cases. Each pair imports both +runtimes and compares geometry, UVs, corner normals, polygon material indices, +node graphs, and decoded image pixels. Exact agreement is relative to the +configured importer and SDK mapping, and is not a lossless MDL certificate. +Missing original resources or unequal contracts remain unqualified. A render +pass or a file-integrity flag cannot replace this check. Keep pair results and +their dependencies available for preparation and provenance readback. + +After preparing a repair release, `validate_material_assets.py init +--runtime-changes-only` limits new independent image review to the changed +runtimes. The manifest still records every original pool candidate and its +disposition. Merge the new acceptance references with the unchanged libraries' +existing references before finalization; the option does not exempt unchanged +translated materials from acceptance verification. + +Functional front defaults to `functional_front_policy: legacy_strict`, preserving +the existing conflict-rejection rule. The explicit `prefer_visual` research +option consumes a hash-bound axis in a labelled canonical frame and retains both +axes and their resolution. Its current shared-evidence trial reversed the sofa +and television in a complete scene; that functional result is rejected even +though material preservation passed. It is not a qualified default. The canonical +matrix is unchanged and solver yaw is applied once. `ambiguous`, `no_unique_front`, +`not_applicable` and `unknown` remain distinct; unknown opening envelopes never +become zero clearance. + +See [NVIDIA MDL SDK](https://github.com/NVIDIA/MDL-SDK/releases/tag/2026.0.2) and +the [third-party notice](mdl-sdk-third-party-notice.md). + +## Frozen asset validation, 2026-10-13 + +The fixed primary benchmark contains 545 original asset cases. All cases reached +a terminal result: 416 passed material-library serialization/readback and four-view +readability acceptance; 129 failed execution (111 explicit errors and 18 importer +process crashes). The independent model accepted 412; four further acceptances +have separate, hash-bound visual adjudications with the original rejections kept. +These numbers describe the configured SDK-to-Blender mapping, not lossless source +MDL reproduction. + +The separate baseline-compatibility scope contains 268 additional variants: +268 passed technical readback, 264 passed appearance acceptance (261 model +acceptances and three documented adjudications), and four TV variants remained +rejected for visibly washed-out screens. They were not repaired by changing the +frozen exposure or replacing their images. The legacy control independently +accepted all 299 of its translated variants, including 15 documented adjudications. + +The immutable evidence is retained on the remote experiment volume under +`rhg_style_joint_20261013/mdl_offline_assets_c15`, `mdl_offline_B_c16`, and +`material_acceptance_{B,C}_final`. The accepted index retains every accepted case's +own manifest and certificate, including distinct exports with equal source/runtime +identities. An identity with both a passing and a failing case remains excluded +from admission; per-case outcomes stay unchanged. + +## Whole-house integration and retained failures, 2026-10-14 + +The merged SDK snapshot `bc486e3`, before the later upstream strict task-binding +check, passed the technical scene pipeline for both original 52-entity cases: binding, +assembly, saved reopening, independent static geometry, all 15 diagnostic views +at 1920 × 1280 / 256 samples, packaging and package validation. Every imported +material was either an accepted offline library or an unchanged native graph. +Both runs recorded zero MDL compile requests and no online bake-cache directory. +These two seeded cases use one source floor plan, 42920. + +After merging upstream strict task binding, snapshot `55ae981` reran the same +52-entity requests. Both completed the scene pipeline, all 15 rendered views and +package validation, with zero online MDL compilation. Both correctly failed the +task-binding gate because no eligible kitchen-counter cup existed in the frozen +entity scope. The requests were not rewritten and robot execution was not run. +See the [strict-task validation receipt](offline-material-strict-task-validation-20261014.json). + +The earlier frozen control matrix completed six material-integration runs, each +with 16 presentation views. All six first reached the effective 1,800-second CPU +render deadline; those failures remain in the original logs and run history. +Each subsequent GPU attempt rendered all views from the same verified, unchanged +scene and produced its own validated package. No views were selected across +attempts. The two legacy-control cases retained the original assets, runtime +hashes, native dimensions and poses. The publication entry and render handoff now +preserve a configured deadline longer than 1,800 seconds; focused CLI/configuration +and resume checks reproduced and verified this fix. + +Two additional findings remain explicit failures: + +- The `prefer_visual` extension preserved materials, but direct inspection of + both full scenes found reversed sofas and televisions. It remains an explicit + research option; `legacy_strict` is the default. +- The repaired-runtime condition passed 186 of 396 source/runtime pair checks. + All 186 then passed independent material validation (184 model acceptances and + two separate visual adjudications). Its complete pool qualified 882 of 1277 + candidates. Both full-house cases still failed at the required countertop + cooktop: the release had no unique `Stovetop012` match, and the alternative whole + electric oven could not fill that relation. No old-source fallback was used. + +See the [validation receipt](offline-material-validation-20261014.json) for +separate denominators, hashes, failed attempts, source-pool identities and remote +evidence locations. Large models, material libraries and scene packages stay on +the remote experiment volume. + +The earlier 52-entity image sheets remain available for +[case 00](images/offline-mdl-20261014/case_00.jpg) and +[case 01](images/offline-mdl-20261014/case_01.jpg). + +## Integration with required-entity completion + +After upstream `6a3a9d1` added `task_entity_policy: complete_required`, merged +snapshot `791200d` ran two **derived 53-entity cases**. Each retains its original +52-entity source/request hashes and adds `kitchen__cup__task_pickup` as a separate +task-compiler decision. The original 52-entity failures above remain failures. + +Both derived cases passed material integration, saved reopening, independent +static geometry, strict entity/asset/anchor binding, all 15 diagnostic views and +package validation. Both recorded zero online MDL compile requests and no online +bake-cache directory. The added cup is a measured, unscaled real asset on the +kitchen counter. Robot execution and physical grasp qualification were not run. + +Already prepared structural-material caches were copied into independent run +directories, with 382 copied-content hash checks per case and unchanged original +source stats. The normal pipeline validated and used both copies as cache hits; +the source caches were not rewritten. This reuse does not alter asset acceptance +or material/render criteria. + +See the [derived-case validation receipt](offline-material-completed-task-validation-20261014.json) +and the [kitchen view showing the added cup](images/offline-mdl-20261014/completed_kitchen_00.jpg). + +![Derived SDK case 00: all 15 diagnostic views](images/offline-mdl-20261014/completed_case_00.jpg) + +![Derived SDK case 01: all 15 diagnostic views](images/offline-mdl-20261014/completed_case_01.jpg) diff --git a/docs/reproduction/public_conversion_code/packages/__init__.py b/docs/reproduction/public_conversion_code/packages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1e318fc3dae0776874cb9cabf115ef448c78308 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/__init__.py @@ -0,0 +1 @@ +"""RoboHouseGen implementation packages.""" diff --git a/docs/reproduction/public_conversion_code/packages/adapters/__init__.py b/docs/reproduction/public_conversion_code/packages/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85f8b37b9480e9ebb95675882a10b6803d26fbaa --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/__init__.py @@ -0,0 +1,31 @@ +"""External runtime adapters.""" + +from packages.adapters.embodiedgen import ( + EmbodiedGenAdapter, + EmbodiedGenSettings, + probe_embodiedgen, +) +from packages.adapters.sam3d import Sam3DAdapter, Sam3DSettings, probe_sam3d +from packages.adapters.scenesmith import ( + RoboLabSceneObject, + RoboLabScenePredicate, + RoboLabSceneRequest, + SceneSmithAdapter, + SceneSmithSettings, + probe_scenesmith, +) + +__all__ = [ + "RoboLabSceneObject", + "RoboLabScenePredicate", + "RoboLabSceneRequest", + "EmbodiedGenAdapter", + "EmbodiedGenSettings", + "Sam3DAdapter", + "Sam3DSettings", + "SceneSmithAdapter", + "SceneSmithSettings", + "probe_sam3d", + "probe_embodiedgen", + "probe_scenesmith", +] diff --git a/docs/reproduction/public_conversion_code/packages/adapters/arena.py b/docs/reproduction/public_conversion_code/packages/adapters/arena.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c51b3782b5ee1bb87a83a93ec4b3eba1600ee0 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/arena.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +import importlib.util + +from packages.adapters.protocols import NotConfiguredError + +ARENA_RELEASE = "release/0.2.1" +ISAAC_SIM_VERSION = "5.1" + + +def probe_arena() -> dict[str, str | bool]: + available = importlib.util.find_spec("isaaclab_arena") is not None + return { + "available": available, + "required_release": ARENA_RELEASE, + "isaac_sim_version": ISAAC_SIM_VERSION, + } + + +def require_arena() -> None: + if not probe_arena()["available"]: + raise NotConfiguredError( + "Isaac Lab-Arena is unavailable; run this command in the pinned Isaac Sim 5.1 worker" + ) diff --git a/docs/reproduction/public_conversion_code/packages/adapters/embodiedgen.py b/docs/reproduction/public_conversion_code/packages/adapters/embodiedgen.py new file mode 100644 index 0000000000000000000000000000000000000000..8e52044d2be702c5cde0f472710749560455ec41 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/embodiedgen.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import json +import os +import shlex +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path + +from packages.adapters.protocols import NotConfiguredError +from packages.core.files import atomic_write_text +from packages.schemas.models import TaskSpec + +EMBODIEDGEN_VERSION = "v2.0.0" + + +@dataclass(frozen=True, slots=True) +class EmbodiedGenSettings: + command: tuple[str, ...] + asset_catalog: Path | None = None + timeout_s: int = 3600 + + @classmethod + def from_env(cls) -> EmbodiedGenSettings: + command = tuple(shlex.split(os.environ.get("EMBODIEDGEN_COMMAND", ""))) + catalog = os.environ.get("EMBODIEDGEN_ASSET_CATALOG") + timeout_s = int(os.environ.get("EMBODIEDGEN_TIMEOUT_S", "3600")) + if timeout_s <= 0: + raise ValueError("EMBODIEDGEN_TIMEOUT_S must be positive") + return cls(command, Path(catalog) if catalog else None, timeout_s) + + +def probe_embodiedgen(settings: EmbodiedGenSettings | None = None) -> dict[str, object]: + settings = settings or EmbodiedGenSettings.from_env() + executable = settings.command[0] if settings.command else "" + command_ready = bool(executable) and ( + Path(executable).is_file() or shutil.which(executable) is not None + ) + catalog_ready = settings.asset_catalog is None or settings.asset_catalog.is_file() + return { + "configured": bool(settings.command), + "ready": command_ready and catalog_ready, + "command": list(settings.command), + "command_ready": command_ready, + "asset_catalog": str(settings.asset_catalog) if settings.asset_catalog else None, + "asset_catalog_ready": catalog_ready, + "timeout_s": settings.timeout_s, + "version": EMBODIEDGEN_VERSION, + } + + +class EmbodiedGenAdapter: + """File-protocol task/affordance adapter for the isolated upstream environment.""" + + def __init__( + self, + command: list[str] | tuple[str, ...] | None = None, + asset_catalog: Path | None = None, + timeout_s: int | None = None, + ) -> None: + if command is None: + settings = EmbodiedGenSettings.from_env() + self.command = list(settings.command) + self.asset_catalog = asset_catalog or settings.asset_catalog + self.timeout_s = timeout_s or settings.timeout_s + else: + self.command = list(command) + self.asset_catalog = asset_catalog + self.timeout_s = timeout_s or 3600 + + def version(self) -> str: + return EMBODIEDGEN_VERSION + + def compile(self, task: TaskSpec, output_dir: Path) -> Path: + if not self.command: + raise NotConfiguredError("EmbodiedGen command is not configured") + output_dir.mkdir(parents=True, exist_ok=True) + request = output_dir / "embodiedgen_request.json" + atomic_write_text(request, task.model_dump_json(indent=2)) + command = [*self.command, "--request", str(request), "--output", str(output_dir)] + if self.asset_catalog is not None: + if not self.asset_catalog.is_file(): + raise FileNotFoundError(self.asset_catalog) + command.extend(["--asset-catalog", str(self.asset_catalog.resolve())]) + result = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + timeout=self.timeout_s, + ) + manifest = output_dir / "task_manifest.json" + if result.returncode != 0: + raise RuntimeError(f"EmbodiedGen failed ({result.returncode}): {result.stderr[-2000:]}") + if not manifest.exists(): + raise RuntimeError("EmbodiedGen did not produce task_manifest.json") + payload = json.loads(manifest.read_text(encoding="utf-8")) + if payload.get("status") != "complete": + raise RuntimeError("EmbodiedGen task stage did not report complete status") + if payload.get("backend") != "embodiedgen-v2": + raise RuntimeError("EmbodiedGen task stage reported an unexpected backend") + if payload.get("task_id") != task.task_id: + raise RuntimeError("EmbodiedGen task stage task_id does not match the request") + return manifest diff --git a/docs/reproduction/public_conversion_code/packages/adapters/protocols.py b/docs/reproduction/public_conversion_code/packages/adapters/protocols.py new file mode 100644 index 0000000000000000000000000000000000000000..6d4422dbb521d7f24194e2108436e77a554ff525 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/protocols.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Protocol + +from packages.schemas.models import RobotCapabilityProfile + + +class NotConfiguredError(RuntimeError): + pass + + +class SceneAuthoringProvider(Protocol): + def version(self) -> str: ... + + def author(self, scene: object, output_dir: Path) -> Path: ... + + +class RobotEmbodimentProvider(Protocol): + def profile(self) -> RobotCapabilityProfile: ... + + def compose_robot_layer(self, output_dir: Path) -> Path: ... + + def validate(self, root_usd: Path) -> dict[str, object]: ... diff --git a/docs/reproduction/public_conversion_code/packages/adapters/rp1.py b/docs/reproduction/public_conversion_code/packages/adapters/rp1.py new file mode 100644 index 0000000000000000000000000000000000000000..1004c60b7d0ab15c2f0c2618a57da1c5e4421985 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/rp1.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +from packages.adapters.arena import require_arena +from packages.robots.profiles import get_robot_profile +from packages.schemas.models import RobotCapabilityProfile + + +class RP13EmbodimentProvider: + """RP1.3 provider boundary for the Isaac worker. + + USD conversion and articulation validation execute only inside the Arena worker. The + core environment can still inspect the capability contract without importing Isaac. + """ + + def __init__( + self, + converter_command: list[str] | None = None, + validator_command: list[str] | None = None, + ) -> None: + self.converter_command = converter_command + self.validator_command = validator_command + + def profile(self) -> RobotCapabilityProfile: + return get_robot_profile("rp1_3") + + def compose_robot_layer(self, output_dir: Path) -> Path: + require_arena() + if not self.converter_command: + raise RuntimeError("RP1.3 converter command is not configured") + output_dir.mkdir(parents=True, exist_ok=True) + target = output_dir / "robot.usda" + result = subprocess.run( + [*self.converter_command, "--robot", "rp1_3", "--output", str(target)], + check=False, + capture_output=True, + text=True, + ) + if result.returncode or not target.exists(): + raise RuntimeError(f"RP1.3 conversion failed: {result.stderr[-2000:]}") + return target + + def validate(self, root_usd: Path) -> dict[str, object]: + require_arena() + if not self.validator_command: + raise RuntimeError("RP1.3 validator command is not configured") + result = subprocess.run( + [*self.validator_command, "--robot", "rp1_3", "--scene", str(root_usd)], + check=False, + capture_output=True, + text=True, + ) + if result.returncode: + raise RuntimeError(f"RP1.3 validation failed: {result.stderr[-2000:]}") + report: dict[str, object] = json.loads(result.stdout) + return report diff --git a/docs/reproduction/public_conversion_code/packages/adapters/rparena.py b/docs/reproduction/public_conversion_code/packages/adapters/rparena.py new file mode 100644 index 0000000000000000000000000000000000000000..8246227d39697bb8ed823545315ff11a19b38aa6 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/rparena.py @@ -0,0 +1,823 @@ +"""Export RoboHouseGen outputs through the RPArena generator interface v1.""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.benchmark.packager import BenchmarkPackager +from packages.core.files import atomic_write_text +from packages.scene_generation.pick_move_place import PickMovePlaceTask +from packages.schemas.models import ( + DifficultyVector, + PredicateSpec, + SceneLayerPlan, + SceneManifest, + SkillInvocation, + TaskEntity, + TaskPlan, + TaskSpec, +) +from packages.version import API_COMPAT_VERSION + +INTERFACE_SCHEMA_VERSION = "rparena.generator-interface/1.0" +INTERFACE_MANIFEST = "manifests/rparena_interface.json" +ADAPTER_VERSION = "robothousegen.asset-first-pick-move-place/1.0" +EXPORT_RESULT_SCHEMA_VERSION = "robothousegen.rparena-export-result/1.0" +USD_INSPECTION_SCHEMA_VERSION = "robothousegen.rparena-usd-inspection/1.0" + +_SHA256 = re.compile(r"^[0-9a-f]{64}$") +_NonEmptyString = Annotated[str, Field(min_length=1)] + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class RPArenaProducer(_StrictModel): + name: str = Field(min_length=1) + version: str = Field(min_length=1) + adapter: str = Field(min_length=1) + + +class RPArenaBundlePaths(_StrictModel): + root_usd: Literal["root.usda"] + scene_usd: Literal["scenesmith/scene.usdc"] + scene_manifest: Literal["manifests/scene.json"] + task_manifest: Literal["manifests/task.json"] + episode_manifest: Literal["manifests/episode.json"] + evaluator_manifest: Literal["manifests/evaluator.json"] + robot_manifest: Literal["manifests/robot.json"] + + +class RPArenaContract(_StrictModel): + bundle_type: Literal["single_episode"] + task_type: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + evaluator: Literal["predicate_graph_v1"] + entity_binding: Literal["absolute_world_prim_paths"] + physics_authoring: Literal["consumer"] + robot_embodiment: Literal["consumer"] + coordinate_system: Literal["usd_z_up_right_handed_metres"] + checksums: Literal["sha256_complete"] + + +class RPArenaIdentity(_StrictModel): + scene_id: str = Field(min_length=1) + task_id: str = Field(min_length=1) + episode_id: str = Field(min_length=1) + entity_ids: list[_NonEmptyString] = Field( + min_length=1, + json_schema_extra={"uniqueItems": True}, + ) + manipulated_entity_ids: list[_NonEmptyString] = Field( + min_length=1, + json_schema_extra={"uniqueItems": True}, + ) + + @model_validator(mode="after") + def validate_entity_ids(self) -> RPArenaIdentity: + if self.entity_ids != sorted(set(self.entity_ids)): + raise ValueError("entity_ids must be sorted and unique") + if self.manipulated_entity_ids != sorted(set(self.manipulated_entity_ids)): + raise ValueError("manipulated_entity_ids must be sorted and unique") + if not set(self.manipulated_entity_ids).issubset(self.entity_ids): + raise ValueError("manipulated_entity_ids must be scene entities") + return self + + +class RPArenaSource(_StrictModel): + kind: str = Field(min_length=1) + source_task_id: str = Field(min_length=1) + source_digest: str = Field(pattern=r"^[0-9a-f]{64}$") + + +class RPArenaInterfaceV1(_StrictModel): + model_config = ConfigDict( + extra="forbid", + json_schema_extra={"$schema": "https://json-schema.org/draft/2020-12/schema"}, + ) + + schema_version: Literal["rparena.generator-interface/1.0"] + producer: RPArenaProducer + bundle: RPArenaBundlePaths + contract: RPArenaContract + identity: RPArenaIdentity + source: RPArenaSource + + +class RPArenaExportResult(_StrictModel): + schema_version: Literal["robothousegen.rparena-export-result/1.0"] = ( + "robothousegen.rparena-export-result/1.0" + ) + bundle_root: Path + interface_manifest: Path + scene_id: str + task_id: str + episode_id: str + source_digest: str + scene_usd_sha256: str + entity_prim_paths: dict[str, str] + checksummed_file_count: int + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _canonical_sha256(value: object) -> str: + payload = json.dumps( + value, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def _reject_constant(value: str) -> None: + raise ValueError(f"JSON contains non-finite value {value!r}") + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + value: dict[str, Any] = {} + for key, item in pairs: + if key in value: + raise ValueError(f"JSON contains duplicate key {key!r}") + value[key] = item + return value + + +def _regular_file(path: Path, *, label: str) -> Path: + unresolved = path.expanduser() + if unresolved.is_symlink(): + raise ValueError(f"{label} must be a non-symlink regular file: {path}") + resolved = unresolved.resolve(strict=True) + if not resolved.is_file(): + raise ValueError(f"{label} must be a non-symlink regular file: {path}") + return resolved + + +def _executable_file(path: Path, *, label: str) -> Path: + executable = path.expanduser().absolute() + if not executable.is_file() or not os.access(executable, os.X_OK): + raise ValueError(f"{label} must resolve to an executable file: {path}") + return executable + + +def _source_directory(path: str | Path) -> Path: + unresolved = Path(path).expanduser() + if unresolved.is_symlink(): + raise ValueError(f"source must be a non-symlink directory: {path}") + source = unresolved.resolve(strict=True) + if not source.is_dir(): + raise ValueError(f"source must be a non-symlink directory: {path}") + return source + + +def _json_object(path: Path, *, label: str) -> dict[str, Any]: + source = _regular_file(path, label=label) + try: + value = json.loads( + source.read_text(encoding="utf-8"), + object_pairs_hook=_unique_object, + parse_constant=_reject_constant, + ) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise ValueError(f"{label} is not valid UTF-8 JSON: {source}") from exc + if not isinstance(value, dict): + raise ValueError(f"{label} must contain a JSON object") + return value + + +def _nonempty(value: object, *, field: str) -> str: + text = value.strip() if isinstance(value, str) else "" + if not text: + raise ValueError(f"{field} must be a non-empty string") + return text + + +def _finite(value: object, *, field: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{field} must be a finite number") + result = float(value) + if not math.isfinite(result): + raise ValueError(f"{field} must be a finite number") + return result + + +def _vector(value: object, *, field: str, length: int) -> list[float]: + if not isinstance(value, (list, tuple)) or len(value) != length: + raise ValueError(f"{field} must contain exactly {length} numbers") + return [_finite(item, field=f"{field}[{index}]") for index, item in enumerate(value)] + + +def _slug(value: object) -> str: + result = re.sub(r"[^a-z0-9]+", "-", _nonempty(value, field="id").casefold()).strip("-") + if not result: + raise ValueError("id cannot be normalized to an empty slug") + return result + + +def _write_json(path: Path, value: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + payload: Any + if isinstance(value, BaseModel): + payload = value.model_dump(mode="json") + else: + payload = value + atomic_write_text( + path, + json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + + +def _validate_source( + source: Path, +) -> tuple[dict[str, Any], PickMovePlaceTask, list[dict[str, Any]], dict[str, str], str]: + composition_path = source / "composition_manifest.json" + task_path = source / "pick_move_place_task.json" + blend_path = source / "asset_first_scene.blend" + composition = _json_object(composition_path, label="asset-first composition manifest") + if composition.get("schema_version") != "2.0": + raise ValueError("composition_manifest.json schema_version must be 2.0") + task_value = _json_object(task_path, label="asset-first pick-move-place task") + task = PickMovePlaceTask.model_validate(task_value) + if composition.get("task") != task.model_dump(mode="json"): + raise ValueError("composition embedded task differs from pick_move_place_task.json") + if task.passed is not True: + raise ValueError("asset-first task did not pass its declared validation") + + raw_entities = composition.get("entities") + if not isinstance(raw_entities, list) or not raw_entities: + raise ValueError("composition manifest must contain entities") + entities: list[dict[str, Any]] = [] + entity_ids: list[str] = [] + for index, raw_entity in enumerate(raw_entities): + if not isinstance(raw_entity, dict): + raise ValueError(f"composition entities[{index}] must be an object") + entity = dict(raw_entity) + entity_id = _nonempty(entity.get("entity_id"), field=f"entities[{index}].entity_id") + dimensions = _vector( + entity.get("dimensions_m"), + field=f"{entity_id}.dimensions_m", + length=3, + ) + if any(value <= 0.0 for value in dimensions): + raise ValueError(f"{entity_id}.dimensions_m must be positive") + _vector(entity.get("center_xy_m"), field=f"{entity_id}.center_xy_m", length=2) + _finite(entity.get("base_z_m"), field=f"{entity_id}.base_z_m") + _finite(entity.get("yaw_deg"), field=f"{entity_id}.yaw_deg") + for digest_field in ("asset_sha256", "runtime_sha256"): + digest = entity.get(digest_field) + if digest is not None and _SHA256.fullmatch(str(digest)) is None: + raise ValueError(f"{entity_id}.{digest_field} must be a SHA-256 digest") + entity_ids.append(entity_id) + entities.append(entity) + if entity_ids != list(dict.fromkeys(entity_ids)) or len(entity_ids) != len(set(entity_ids)): + raise ValueError("composition entity IDs must be unique") + + critical = { + task.movable_object_entity_id, + task.source_support_entity_id, + task.target_support_entity_id, + } + if len(critical) != 3 or not critical.issubset(entity_ids): + raise ValueError("task critical entities are missing or not distinct") + by_id = {str(item["entity_id"]): item for item in entities} + if by_id[task.movable_object_entity_id].get("parent_entity_id") != ( + task.source_support_entity_id + ): + raise ValueError("movable object is not parented to the declared source support") + + source_hashes = { + "asset_first_scene.blend": _sha256( + _regular_file(blend_path, label="asset-first Blender scene") + ), + "composition_manifest.json": _sha256(composition_path), + "pick_move_place_task.json": _sha256(task_path), + } + metric_path = source / "metric_layout_spec.json" + if metric_path.exists() or metric_path.is_symlink(): + metric = _regular_file(metric_path, label="asset-first metric layout") + metric_digest = _sha256(metric) + declared_digest = composition.get("metric_layout_spec_sha256") + if declared_digest is not None and declared_digest != metric_digest: + raise ValueError("metric_layout_spec.json differs from composition identity") + source_hashes["metric_layout_spec.json"] = metric_digest + source_digest = _canonical_sha256(source_hashes) + return composition, task, entities, source_hashes, source_digest + + +def _run_blender_export( + source: Path, + destination_scene: Path, + *, + blender_executable: str | Path, + blender_export_script: str | Path, + timeout_s: float, +) -> dict[str, Any]: + blender = _executable_file(Path(blender_executable), label="Blender executable") + exporter = _regular_file(Path(blender_export_script), label="Blender export script") + blend = _regular_file(source / "asset_first_scene.blend", label="asset-first Blender scene") + destination_scene.parent.mkdir(parents=True, exist_ok=True) + command = [ + str(blender), + "--background", + "--python", + str(exporter), + "--", + str(blend), + str(destination_scene), + ] + completed = subprocess.run( + command, + cwd=source, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=timeout_s, + check=False, + ) + if completed.returncode != 0: + raise RuntimeError( + "Blender USD export failed with exit code " + f"{completed.returncode}:\n{completed.stderr[-4000:]}" + ) + if not destination_scene.is_file() or destination_scene.stat().st_size == 0: + raise RuntimeError("Blender exited successfully without producing scene.usdc") + def sanitize(text: str) -> str: + return text.replace(str(source), "").replace( + str(destination_scene.parent.parent), "" + ) + return { + "blender_sha256": _sha256(blender), + "export_script_sha256": _sha256(exporter), + "return_code": completed.returncode, + "stdout_tail": sanitize(completed.stdout[-4000:]), + "stderr_tail": sanitize(completed.stderr[-4000:]), + } + + +def _run_usd_inspection( + scene_usd: Path, + cleanup_layer: Path, + entity_ids: list[str], + *, + usd_python: str | Path | None, + timeout_s: float, +) -> dict[str, Any]: + executable = _executable_file( + Path(usd_python or os.environ.get("RHG_USD_PYTHON") or sys.executable), + label="OpenUSD Python executable", + ) + request_path = cleanup_layer.parent / ".rparena_usd_request.json" + _write_json( + request_path, + { + "scene_usd": str(scene_usd.resolve()), + "cleanup_layer": str(cleanup_layer.resolve(strict=False)), + "entity_ids": sorted(entity_ids), + }, + ) + project_root = Path(__file__).resolve().parents[2] + worker_script = Path(__file__).with_name("rparena_usd_worker.py").resolve(strict=True) + try: + completed = subprocess.run( + [ + str(executable), + str(worker_script), + "--request", + str(request_path), + ], + cwd=project_root, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=timeout_s, + check=False, + ) + finally: + request_path.unlink(missing_ok=True) + if completed.returncode != 0: + detail = completed.stderr.strip() or completed.stdout.strip() or "unknown error" + raise RuntimeError(f"RPArena OpenUSD inspection failed: {detail[-4000:]}") + try: + report = json.loads(completed.stdout.strip().splitlines()[-1]) + except (IndexError, json.JSONDecodeError) as exc: + raise RuntimeError("RPArena OpenUSD inspection returned invalid JSON") from exc + if ( + not isinstance(report, dict) + or report.get("schema_version") != USD_INSPECTION_SCHEMA_VERSION + ): + raise RuntimeError("RPArena OpenUSD inspection returned an unsupported schema") + bindings = report.get("entity_prim_paths") + if not isinstance(bindings, dict) or sorted(bindings) != sorted(entity_ids): + raise RuntimeError("RPArena OpenUSD inspection returned incomplete entity bindings") + if not cleanup_layer.is_file(): + raise RuntimeError("RPArena OpenUSD inspection did not create the cleanup layer") + return report + + +def _task_spec( + task: PickMovePlaceTask, + entities: list[dict[str, Any]], + *, + task_id: str, + seed: int, + manipulated_mass_kg: float, +) -> TaskSpec: + movable = task.movable_object_entity_id + source_support = task.source_support_entity_id + target_support = task.target_support_entity_id + task_entities: list[TaskEntity] = [] + for entity in entities: + entity_id = str(entity["entity_id"]) + role: Literal["MANIPULATED", "TARGET", "CONTEXT"] = ( + "MANIPULATED" + if entity_id == movable + else "TARGET" + if entity_id == target_support + else "CONTEXT" + ) + attributes = { + key: entity[key] + for key in ( + "asset_id", + "asset_sha256", + "runtime_sha256", + "dimensions_m", + "center_xy_m", + "base_z_m", + "yaw_deg", + "parent_entity_id", + "support_type", + ) + if entity.get(key) is not None + } + if role == "MANIPULATED": + attributes.update( + { + "mass_kg": manipulated_mass_kg, + "rigid_body": True, + "collision": "convex_hull", + "require_collision": True, + } + ) + task_entities.append( + TaskEntity( + entity_id=entity_id, + role=role, + category=_nonempty(entity.get("category"), field=f"{entity_id}.category"), + attributes=attributes, + required=True, + ) + ) + + instruction = ( + f"Navigate from the generated start pose to {source_support}, grasp {movable}, " + f"follow the generated route, place it on {target_support}, release it, and " + "finish in a stable stance." + ) + plan = TaskPlan( + plan_id=f"plan-{task_id.removeprefix('task-')}", + natural_language=instruction, + skills=[ + SkillInvocation( + invocation_id="navigate_to_source", + skill_id="navigate", + parameters={"target": source_support}, + ), + SkillInvocation( + invocation_id="grasp_object", + skill_id="grasp", + parameters={"object": movable}, + depends_on=["navigate_to_source"], + ), + SkillInvocation( + invocation_id="carry_to_target", + skill_id="carry", + parameters={"object": movable, "target": target_support}, + depends_on=["grasp_object"], + ), + SkillInvocation( + invocation_id="place_object", + skill_id="place", + parameters={"object": movable, "support": target_support}, + depends_on=["carry_to_target"], + ), + SkillInvocation( + invocation_id="release_object", + skill_id="release", + parameters={"object": movable}, + depends_on=["place_object"], + ), + ], + required_capabilities={"locomotion", "grasp", "carry", "place", "release"}, + difficulty=DifficultyVector( + body=0.65, + manipulation=0.8, + cognition=0.35, + body_reason="Navigate a generated indoor route while carrying an object.", + manipulation_reason="Grasp, transport, place, and release a generated object.", + cognition_reason="Follow a fixed pick-move-place sequence.", + ), + ) + return TaskSpec( + task_id=task_id, + natural_language=instruction, + task_type="object_transfer", + required_rooms=["generated_room"], + entities=task_entities, + initial_predicates=[ + PredicateSpec(name="supported_by", subject=movable, object=source_support) + ], + goal_predicates=[ + PredicateSpec( + name="supported_by", + subject=movable, + object=target_support, + hold_seconds=2.0, + ), + PredicateSpec(name="released", subject=movable), + PredicateSpec(name="stable", subject=movable, hold_seconds=1.0), + PredicateSpec(name="robot_stable", subject="robot", hold_seconds=1.0), + ], + safety_predicates=[PredicateSpec(name="no_safety_event", subject="robot")], + plan=plan, + random_seed=seed, + metadata={ + "generator": "RoboHouseGen", + "source_task_id": task.task_id, + "source_task_type": task.task_type, + "description_en": task.description_en, + "description_zh": task.description_zh, + "route_waypoints_xy_m": task.route_waypoints_xy_m, + "route_length_m": task.route_length_m, + "pick": task.pick.model_dump(mode="json"), + "place": task.place.model_dump(mode="json"), + }, + ) + + +def _write_complete_checksums(root: Path) -> int: + checksum_path = root / "checksums.sha256" + checksum_path.unlink(missing_ok=True) + entries: list[str] = [] + for path in sorted(root.rglob("*")): + if path.is_symlink(): + raise ValueError(f"RPArena export contains a symlink: {path}") + if path.is_file(): + relative = path.relative_to(root).as_posix() + entries.append(f"{_sha256(path)} {relative}") + atomic_write_text(checksum_path, "\n".join(entries) + "\n") + return len(entries) + + +def export_asset_first_rparena_bundle( + source_dir: str | Path, + output_dir: str | Path, + *, + blender_executable: str | Path, + usd_python: str | Path | None = None, + blender_export_script: str | Path | None = None, + robot_profile: str = "unitree_g1_43dof", + robot_base_height_m: float = 0.78, + manipulated_mass_kg: float = 0.25, + max_duration_s: float = 180.0, + seed: int = 0, + timeout_s: float = 900.0, +) -> RPArenaExportResult: + """Export one certified asset-first task as a standard RPArena bundle.""" + + source = _source_directory(source_dir) + output = Path(output_dir).expanduser().resolve(strict=False) + if output.exists(): + raise FileExistsError(f"output already exists: {output}") + output.parent.mkdir(parents=True, exist_ok=True) + height = _finite(robot_base_height_m, field="robot_base_height_m") + mass = _finite(manipulated_mass_kg, field="manipulated_mass_kg") + duration = _finite(max_duration_s, field="max_duration_s") + timeout = _finite(timeout_s, field="timeout_s") + if height <= 0.0 or mass <= 0.0 or duration <= 0.0 or timeout <= 0.0: + raise ValueError("robot height, mass, duration, and timeout must be positive") + if isinstance(seed, bool) or not isinstance(seed, int): + raise ValueError("seed must be an integer") + profile = _nonempty(robot_profile, field="robot_profile") + composition, source_task, entities, source_hashes, source_digest = _validate_source(source) + + project_root = Path(__file__).resolve().parents[2] + export_script = blender_export_script or project_root / "scripts/blender_export_usd.py" + source_slug = _slug(source_task.task_id) + task_id = f"task-rhg-{source_slug}-v1" + scene_id = f"scene-rhg-{source_slug}-v1" + episode_id = f"episode-rhg-{source_slug}-{_slug(profile)}" + + with tempfile.TemporaryDirectory(prefix=f".{output.name}.staging-", dir=output.parent) as temp: + staging = Path(temp) / "bundle" + scene_usd = staging / "scenesmith/scene.usdc" + export_evidence = _run_blender_export( + source, + scene_usd, + blender_executable=blender_executable, + blender_export_script=export_script, + timeout_s=timeout, + ) + cleanup_layer = staging / "layers/asset_first_cleanup.usda" + usd_report = _run_usd_inspection( + scene_usd, + cleanup_layer, + [str(entity["entity_id"]) for entity in entities], + usd_python=usd_python, + timeout_s=timeout, + ) + bindings = {str(key): str(value) for key, value in usd_report["entity_prim_paths"].items()} + scene_usd_sha256 = _sha256(scene_usd) + root_usd = staging / "root.usda" + atomic_write_text( + root_usd, + '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' + ' upAxis = "Z"\n subLayers = [\n' + ' @layers/asset_first_cleanup.usda@,\n' + ' @scenesmith/scene.usdc@\n ]\n)\n', + ) + + task = _task_spec( + source_task, + entities, + task_id=task_id, + seed=seed, + manipulated_mass_kg=mass, + ) + content_hash = _canonical_sha256( + { + "entity_prim_paths": bindings, + "scene_usd_sha256": scene_usd_sha256, + "source_digest": source_digest, + "task_visual_roots_disabled": usd_report["task_visual_roots_disabled"], + } + ) + scene = SceneManifest( + scene_id=scene_id, + task_id=task_id, + random_seed=seed, + layer_plan=SceneLayerPlan( + root_layer="root.usda", + layers={ + "asset_first_cleanup": "layers/asset_first_cleanup.usda", + "scene": "scenesmith/scene.usdc", + }, + ), + entity_prim_paths=bindings, + robot_prim_path="/World/Robot", + source_checkpoints={ + "adapter": ADAPTER_VERSION, + "generator": "RoboHouseGen", + "source_digest": source_digest, + }, + content_hash=content_hash, + ) + episode = BenchmarkPackager().package( + task, + scene, + profile, + staging, + episode_id=episode_id, + max_duration_s=duration, + split="test", + factor_values={ + "source_task_id": source_task.task_id, + "source_digest": source_digest, + }, + ) + _write_json(staging / "manifests/scene.json", scene) + _write_json( + staging / "manifests/robot.json", + { + "schema_version": "1.0", + "translation_m": [ + source_task.robot_start_pose.x_m, + source_task.robot_start_pose.y_m, + height, + ], + "rotation_rpy_deg": [0.0, 0.0, source_task.robot_start_pose.yaw_deg], + }, + ) + + provenance = staging / "provenance" + provenance.mkdir(parents=True, exist_ok=True) + shutil.copy2(source / "composition_manifest.json", provenance / "composition_manifest.json") + shutil.copy2( + source / "pick_move_place_task.json", + provenance / "pick_move_place_task.json", + ) + metric_path = source / "metric_layout_spec.json" + if metric_path.is_file() and not metric_path.is_symlink(): + shutil.copy2(metric_path, provenance / "metric_layout_spec.json") + texture_files = sorted( + path.relative_to(staging).as_posix() + for path in (scene_usd.parent / "textures").rglob("*") + if path.is_file() and not path.is_symlink() + ) if (scene_usd.parent / "textures").is_dir() else [] + export_report = { + "schema_version": "robothousegen.rparena-export/1.0", + "adapter": ADAPTER_VERSION, + "source_hashes": source_hashes, + "source_digest": source_digest, + "scene_usd_sha256": scene_usd_sha256, + "entity_prim_paths": bindings, + "entity_mesh_counts": usd_report["entity_mesh_counts"], + "task_visual_roots_disabled": usd_report["task_visual_roots_disabled"], + "source_default_prim": usd_report["source_default_prim"], + "copied_textures": texture_files, + "blender": export_evidence, + "assumptions": { + "robot_base_height_m": height, + "manipulated_mass_kg": mass, + "physics_authoring": "consumer", + "robot_embodiment": "consumer", + }, + "room_dimensions_m": composition.get("room_dimensions_m"), + } + _write_json(provenance / "rparena_export.json", export_report) + + interface = RPArenaInterfaceV1( + schema_version="rparena.generator-interface/1.0", + producer=RPArenaProducer( + name="RoboHouseGen", + version=API_COMPAT_VERSION, + adapter=ADAPTER_VERSION, + ), + bundle=RPArenaBundlePaths( + root_usd="root.usda", + scene_usd="scenesmith/scene.usdc", + scene_manifest="manifests/scene.json", + task_manifest="manifests/task.json", + episode_manifest="manifests/episode.json", + evaluator_manifest="manifests/evaluator.json", + robot_manifest="manifests/robot.json", + ), + contract=RPArenaContract( + bundle_type="single_episode", + task_type=task.task_type, + evaluator="predicate_graph_v1", + entity_binding="absolute_world_prim_paths", + physics_authoring="consumer", + robot_embodiment="consumer", + coordinate_system="usd_z_up_right_handed_metres", + checksums="sha256_complete", + ), + identity=RPArenaIdentity( + scene_id=scene.scene_id, + task_id=task.task_id, + episode_id=episode.episode_id, + entity_ids=sorted(bindings), + manipulated_entity_ids=[source_task.movable_object_entity_id], + ), + source=RPArenaSource( + kind="robothousegen.asset-first", + source_task_id=source_task.task_id, + source_digest=source_digest, + ), + ) + _write_json(staging / INTERFACE_MANIFEST, interface) + checksummed_file_count = _write_complete_checksums(staging) + staging.replace(output) + + return RPArenaExportResult( + bundle_root=output, + interface_manifest=output / INTERFACE_MANIFEST, + scene_id=scene_id, + task_id=task_id, + episode_id=episode_id, + source_digest=source_digest, + scene_usd_sha256=scene_usd_sha256, + entity_prim_paths=bindings, + checksummed_file_count=checksummed_file_count, + ) + + +__all__ = [ + "ADAPTER_VERSION", + "EXPORT_RESULT_SCHEMA_VERSION", + "INTERFACE_MANIFEST", + "INTERFACE_SCHEMA_VERSION", + "RPArenaExportResult", + "RPArenaInterfaceV1", + "export_asset_first_rparena_bundle", +] diff --git a/docs/reproduction/public_conversion_code/packages/adapters/rparena_baked.py b/docs/reproduction/public_conversion_code/packages/adapters/rparena_baked.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc093b29c484fe02866f2b2b53400595a9c23de --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/rparena_baked.py @@ -0,0 +1,118 @@ +"""RHG-side final material conversion from the PMP20 channel bake receipt.""" +import importlib.util,json,sys,math +from pathlib import Path + + +def verify_images(transfer,reference,texture_contract=None): + from .texture_metrics import compare, CONTRACT + contract_path=Path(texture_contract) if texture_contract is not None else CONTRACT + contract=json.loads(contract_path.read_text(encoding='utf-8')) + import numpy as np + from PIL import Image + receipt=json.loads((transfer/'bake-receipt.json').read_text());rows=[] + for frame in receipt['converted']: + name=frame['camera'].removeprefix('transfer_view_') + original=np.asarray(Image.open(reference/(name+'.png')).convert('RGB'),dtype=float) + converted=np.asarray(Image.open(transfer/frame['path']).convert('RGB'),dtype=float) + if original.shape!=converted.shape:raise ValueError('Source/baked camera image dimensions differ') + error=abs(original-converted) + clarity=(compare(reference/(name+'.png'),transfer/frame['path'],name,contract) + if name in contract['regions'] and original.shape[:2]==(720,960) + else dict(clarity_passed=False,available=False,reason='No frozen ROI for this camera/resolution')) + rows.append(dict(view=name,mae=float(error.mean()),p95=float(np.percentile(error,95)),clarity=clarity)) + mean_passed=len(rows)==len(receipt['views']) and all(r['mae']<=5. for r in rows) + clarity_passed=bool(rows) and all(r['clarity']['clarity_passed'] for r in rows) + return dict(passed=mean_passed and clarity_passed,mean_error_passed=mean_passed, + threshold_mae=5.,threshold_source='PMP20 source conversion contract', + registration_or_exposure_fitting=False,views=rows, + clarity_passed=clarity_passed,texture_contract=contract) + + +def apply_baked(stage,transfer,output,shared): + from pxr import Gf,Sdf,UsdGeom,UsdShade,Tf + from .rparena_v16 import intern,sha + worker=Path(__file__).resolve().parents[2]/'scripts/source_transfer' + sys.path.insert(0,str(worker)) + from usd_scene_transfer_worker import MDL_SCALARS,MDL_COLORS,MDL_MAPS + receipt=json.loads((transfer/'bake-receipt.json').read_text());records={r['usd_material_name']:r for r in receipt['materials']} + if 'texture_budget' in receipt: + budget=receipt['texture_budget'] + if budget['estimated_resident_bytes']>budget['budget_bytes']:raise ValueError('Scene texture budget exceeded') + (output/'texture-budget.json').write_text(json.dumps(budget,indent=2)) + spec=importlib.util.find_spec('isaacsim');base=Path(spec.origin).parent + mdl=base/'kit/mdl/core/Base/OmniSurface.mdl' + if not mdl.is_file():raise FileNotFoundError(mdl) + changes=[];ray_changes=[] + rays=json.loads((output/'source-ray-visibility.json').read_text())['objects'] + ray_lookup=dict(rays) + for name,value in rays.items(): + key=Tf.MakeValidIdentifier(name) + if key in ray_lookup and ray_lookup[key]!=value:raise ValueError('Ambiguous sanitized source visibility name') + ray_lookup[key]=value + for name,values in rays.items(): + if not values['hide_render'] and any(not values[k] for k in ['visible_camera','visible_diffuse','visible_glossy','visible_transmission','visible_volume_scatter']): + raise ValueError('Unsupported non-shadow source ray visibility: '+name) + for p in stage.Traverse(): + if p.IsA(UsdGeom.Mesh): + q=p;names=[];settings=None + while q: + names=[q.GetName(),str(q.GetMetadata('displayName')),*[str(a.Get()) for a in q.GetAttributes() if a.GetName().endswith('object_name')]] + settings=next((ray_lookup[n] for n in names if n in ray_lookup),None) + if settings is not None:break + q=q.GetParent() + if settings is None:raise ValueError('Mesh has no source ray-visibility owner: '+str(p.GetPath())) + p.CreateAttribute('primvars:doNotCastShadows',Sdf.ValueTypeNames.Bool).Set(not settings['visible_shadow']) + if settings['hide_render']:UsdGeom.Imageable(p).CreateVisibilityAttr('invisible') + if not settings['visible_shadow']:ray_changes.append(str(p.GetPath())) + if p.GetName() in receipt['hidden_source_objects']: + UsdGeom.Imageable(p).CreateVisibilityAttr('invisible') + if p.IsA(UsdShade.Shader): + sh=UsdShade.Shader(p);ior=sh.GetInput('ior') + if sh.GetIdAttr().Get()=='UsdPreviewSurface' and ior and ior.Get() is not None and ior.Get()<1.: + changes.append(dict(shader=str(p.GetPath()),source_ior=ior.Get(),ior=1.5,policy='PMP20_explicit_compatibility')) + ior.Set(1.5) + mdl_count=0;specular_mappings=[] + for p in list(stage.Traverse()): + if not p.IsA(UsdShade.Material) or p.GetName() not in records:continue + r=records[p.GetName()] + c=dict(r['constants']);level=float(c.get('Specular IOR Level',.5));source_ior=float(c.get('IOR',1.5)) + opaque=c.get('Transmission Weight',0.)==0. and 'transmission' not in r['maps'] + effective_ior=None + if opaque and 'specular_weight' not in r['maps'] and abs(level-.5)>1e-6: + # Cycles Principled adjusts dielectric F0, then converts back to + # reflection IOR. A nonstandard PreviewSurface "specular" input + # cannot preserve this value. Refraction is excluded from this path. + f0=((source_ior-1.)/(source_ior+1.))**2*2.*max(level,0.) + if not 0<=f0<1:raise ValueError('Unsupported source dielectric F0') + root=math.sqrt(f0);effective_ior=(1.+root)/(1.-root) + needs_separate_coat=effective_ior is not None and c.get('Coat Weight',0.)>0. + if r['target_shader']!='OmniSurface' and not needs_separate_coat: + if effective_ior is not None: + from pxr import Usd + shaders=[UsdShade.Shader(q) for q in Usd.PrimRange(p) if q.IsA(UsdShade.Shader) and UsdShade.Shader(q).GetIdAttr().Get()=='UsdPreviewSurface'] + if len(shaders)!=1:raise ValueError('Ambiguous PreviewSurface source') + shaders[0].CreateInput('ior',Sdf.ValueTypeNames.Float).Set(effective_ior) + specular_mappings.append(dict(material=str(p.GetPath()),source_ior=source_ior,source_level=level,reflection_ior=effective_ior,shader='UsdPreviewSurface')) + continue + if needs_separate_coat and r['target_shader']!='OmniSurface': + from scene_transfer import CHANNELS + if any(channel not in r['maps'] and name not in c for channel,name in CHANNELS.items()): + raise ValueError('Separate coat/base IOR requires complete source channel data: '+r['source_material']) + m=UsdShade.Material(p);sh=UsdShade.Shader.Define(stage,str(p.GetPath())+'/RHGSourceSurface') + sh.CreateImplementationSourceAttr(UsdShade.Tokens.sourceAsset);sh.SetSourceAsset(Sdf.AssetPath(str(mdl)),'mdl');sh.SetSourceAssetSubIdentifier('OmniSurface','mdl');sh.CreateOutput('out',Sdf.ValueTypeNames.Token) + sh.CreateInput('diffuse_reflection_weight',Sdf.ValueTypeNames.Float).Set(1.);sh.CreateInput('enable_specular_transmission',Sdf.ValueTypeNames.Bool).Set(bool(c.get('Transmission Weight',0)>0 or 'transmission' in r['maps']));sh.CreateInput('specular_reflection_weight',Sdf.ValueTypeNames.Float).Set(1. if effective_ior is not None else min(1.,2.*level));sh.CreateInput('thin_walled',Sdf.ValueTypeNames.Bool).Set(False) + for src,dest in MDL_SCALARS.items(): + if src in c: + v=float(c[src]);v=1.5 if src in ('IOR','Coat IOR') and v<1 else v + sh.CreateInput(dest,Sdf.ValueTypeNames.Float).Set(v) + for src,dest in MDL_COLORS.items(): + if src in c:sh.CreateInput(dest,Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*c[src][:3])) + if effective_ior is not None: + sh.GetInput('specular_reflection_ior').Set(effective_ior) + specular_mappings.append(dict(material=str(p.GetPath()),source_ior=source_ior,source_level=level,reflection_ior=effective_ior,shader='OmniSurface',coat_ior=c.get('Coat IOR'))) + if c.get('Emission Strength',0)>0 or 'emission_strength' in r['maps']:sh.CreateInput('emission_weight',Sdf.ValueTypeNames.Float).Set(1.) + for ch,image in r['maps'].items(): + f=transfer/image.get('native_path',image['path']);name=sha(f)+f.suffix.lower();intern(f,output/'assets'/name,shared/name) + sh.CreateInput(MDL_MAPS[ch],Sdf.ValueTypeNames.Asset).Set(Sdf.AssetPath('assets/'+name));sh.GetInput(MDL_MAPS[ch]).GetAttr().SetColorSpace('sRGB' if image['color_space']=='sRGB' else 'raw') + m.CreateSurfaceOutput('mdl').ConnectToSource(sh.ConnectableAPI(),'out');m.CreateVolumeOutput('mdl').ConnectToSource(sh.ConnectableAPI(),'out');mdl_count+=1 + return dict(source_bake_sha256=sha(transfer/'bake-receipt.json'),mdl_materials=mdl_count,ior_compatibility=changes,specular_ior_mappings=specular_mappings,source_no_shadow_meshes=ray_changes,runtime_dependencies={'OmniSurface.mdl':dict(path=str(mdl),sha256=sha(mdl))}) diff --git a/docs/reproduction/public_conversion_code/packages/adapters/rparena_native.py b/docs/reproduction/public_conversion_code/packages/adapters/rparena_native.py new file mode 100644 index 0000000000000000000000000000000000000000..1b791ff134dc2f1bedba655b158e2266dcedb77b --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/rparena_native.py @@ -0,0 +1,150 @@ +"""Carry verified source articulation graphs into the delivered house.""" +import json +from pathlib import Path +import sys + + +def transfer_baked_surface(source_stage,native_stage,source_root,native_root): + """Copy baked material/UVs by verified world-space face correspondence. + + Native points, topology, rigid bodies and collisions remain untouched. + A failed or ambiguous correspondence is an export failure, not a fallback. + """ + import numpy as np + from scipy.spatial import cKDTree + from pxr import Gf,Sdf,Usd,UsdGeom,UsdShade,UsdPhysics,Vt + source_cache=UsdGeom.XformCache();native_cache=UsdGeom.XformCache() + def points(stage_cache,p): + xf=stage_cache.GetLocalToWorldTransform(p) + return np.array([list(xf.Transform(Gf.Vec3d(v))) for v in UsdGeom.Mesh(p).GetPointsAttr().Get()]) + candidates=[] + for p in Usd.PrimRange(source_stage.GetPrimAtPath(source_root)): + if p.IsA(UsdGeom.Mesh): + xyz=points(source_cache,p) + if len(xyz):candidates.append((p,xyz,xyz.min(0),xyz.max(0))) + records=[] + for p in Usd.PrimRange(native_stage.GetPrimAtPath(native_root)): + if not p.IsA(UsdGeom.Mesh) or UsdGeom.Imageable(p).ComputePurpose()=='guide':continue + xyz=points(native_cache,p);matches=[] + if not len(xyz):continue + for q,coords,lo,hi in candidates: + if max(abs(xyz.min(0)-lo).max(),abs(xyz.max(0)-hi).max())>.001:continue + distance,ids=cKDTree(coords).query(xyz) + reverse=cKDTree(xyz).query(coords)[0] + error=max(float(distance.max()),float(reverse.max())) + if error<=.001:matches.append((q,ids,error)) + if len(matches)!=1:raise ValueError('Baked/native visual correspondence is not unique: '+str(p.GetPath())+' '+str(len(matches))) + q,ids,error=matches[0];sm=UsdGeom.Mesh(q);nm=UsdGeom.Mesh(p) + shadow=q.GetAttribute('primvars:doNotCastShadows') + if shadow and shadow.Get() is not None:p.CreateAttribute('primvars:doNotCastShadows',Sdf.ValueTypeNames.Bool).Set(shadow.Get()) + UsdGeom.Imageable(p).CreateVisibilityAttr(UsdGeom.Imageable(q).ComputeVisibility()) + physics_material=UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial('physics')[0] + if physics_material and physics_material.GetPrim().HasAPI(UsdPhysics.MaterialAPI): + p.CreateRelationship('material:binding:physics').SetTargets([physics_material.GetPath()]) + coords=points(source_cache,q);tree=cKDTree(coords) + canonical={i:min(tree.query_ball_point(v,1e-5)) for i,v in enumerate(coords)} + ids=np.asarray([canonical[int(i)] for i in ids]) + src_idx=list(sm.GetFaceVertexIndicesAttr().Get());src_counts=list(sm.GetFaceVertexCountsAttr().Get()) + faces=[];offset=0;by_vertex={} + for face,count in enumerate(src_counts): + corners=list(range(offset,offset+count));verts={canonical[src_idx[k]] for k in corners};faces.append((verts,corners)) + for v in verts:by_vertex.setdefault(v,[]).append(face) + offset+=count + dst_idx=list(nm.GetFaceVertexIndicesAttr().Get());dst_counts=list(nm.GetFaceVertexCountsAttr().Get());corner_map=[];face_map=[];offset=0 + for count in dst_counts: + mapped=[int(ids[v]) for v in dst_idx[offset:offset+count]];members=set(mapped) + selected=sorted({f for v in members for f in by_vertex.get(v,[]) if faces[f][0].issubset(members)}) + if not selected:raise ValueError('Native face has no baked source correspondence') + for v in mapped: + choices=[k for f in selected for k in faces[f][1] if canonical[src_idx[k]]==v] + if not choices:raise ValueError('Native UV corner has no source correspondence') + corner_map.append(choices[0]) + face_map.append(selected);offset+=count + uv_names=[] + for uv in UsdGeom.PrimvarsAPI(q).GetPrimvars(): + if uv.GetTypeName() not in (Sdf.ValueTypeNames.TexCoord2fArray,Sdf.ValueTypeNames.Float2Array):continue + values=uv.ComputeFlattened() + if values is None:continue + interpolation=uv.GetInterpolation() + if interpolation=='faceVarying':mapped=[values[k] for k in corner_map] + elif interpolation in ('vertex','varying'):mapped=[values[src_idx[k]] for k in corner_map] + else:raise ValueError('Unsupported baked UV interpolation: '+str(interpolation)) + target=UsdGeom.PrimvarsAPI(p).CreatePrimvar(uv.GetPrimvarName(),uv.GetTypeName(),'faceVarying');target.Set(Vt.Vec2fArray(mapped));target.GetIndicesAttr().Clear();uv_names.append(uv.GetPrimvarName()) + base=UsdShade.MaterialBindingAPI(q).ComputeBoundMaterial()[0] + source_materials=[str(base.GetPath()) if base else None]*len(faces) + for subset in UsdGeom.Subset.GetAllGeomSubsets(sm): + material=UsdShade.MaterialBindingAPI(subset.GetPrim()).ComputeBoundMaterial()[0] + if material: + for index in subset.GetIndicesAttr().Get():source_materials[index]=str(material.GetPath()) + physical_faces=[str(physics_material.GetPath()) if physics_material and physics_material.GetPrim().HasAPI(UsdPhysics.MaterialAPI) else None]*len(dst_counts) + for subset in UsdGeom.Subset.GetAllGeomSubsets(nm): + bound=UsdShade.MaterialBindingAPI(subset.GetPrim()).ComputeBoundMaterial('physics')[0] + if bound and bound.GetPrim().HasAPI(UsdPhysics.MaterialAPI): + for face in subset.GetIndicesAttr().Get():physical_faces[face]=str(bound.GetPath()) + groups={} + for index,selected in enumerate(face_map): + materials={source_materials[f] for f in selected} + if len(materials)!=1 or None in materials:raise ValueError('Ambiguous baked face material') + groups.setdefault((next(iter(materials)),physical_faces[index]),[]).append(index) + # Block inherited source bindings/subsets when installing the baked skin. + for subset in UsdGeom.Subset.GetAllGeomSubsets(nm):subset.GetPrim().SetActive(False) + for i,((material,physical),indices) in enumerate(sorted(groups.items(),key=lambda item:str(item[0]))): + if len(groups)==1:target=p + else: + subset=UsdGeom.Subset.Define(native_stage,str(p.GetPath())+'/RHGBaked_'+str(i));subset.CreateElementTypeAttr('face');subset.CreateFamilyNameAttr('materialBind');subset.CreateIndicesAttr(indices);target=subset.GetPrim() + UsdShade.MaterialBindingAPI.Apply(target);target.CreateRelationship('material:binding').SetTargets([Sdf.Path(material)]) + if physical:target.CreateRelationship('material:binding:physics').SetTargets([Sdf.Path(physical)]) + records.append(dict(native_mesh=str(p.GetPath()),baked_mesh=str(q.GetPath()),world_geometry_error_m=error,uv_names=uv_names,materials=sorted({v[0] for v in groups}),physical_materials_preserved=sorted({v[1] for v in groups if v[1]}),native_geometry_modified=False)) + return records + + +def author_native(stage, source, output, paths, shared): + from pxr import Sdf, Usd, UsdGeom, UsdPhysics + from .rparena_v16 import material_assets, sha + helpers=Path(__file__).resolve().parents[2]/'scripts/internal/scene_generation/real_assets' + sys.path.insert(0,str(helpers)) + from native_scene_contract import validate + check=validate(source) + if not check['passed']: + raise ValueError('Source native articulation gate is incomplete: '+str(check)) + receipt=json.loads((source/'native_articulation_verification.json').read_text()) + bindings=receipt.get('bindings',[]) + if not bindings: + return dict(source_receipt_sha256=sha(source/'native_articulation_verification.json'), + instances=[],body_paths=[],joint_count=0) + original=Usd.Stage.Open(str(source/receipt['active_runtime'])) + flat=original.Flatten() + layer=Sdf.Layer.CreateNew(str(output/'native.usdc')) + native=Usd.Stage.Open(layer) + world=UsdGeom.Xform.Define(native,'/World').GetPrim();native.SetDefaultPrim(world) + if not Sdf.CopySpec(flat,'/World/Native',layer,'/World/Native'): + raise ValueError('Missing verified /World/Native subtree') + layer.Save() + textures=material_assets(native,output/'native.usdc',output,shared) + records=[];bodies=[];joints=[] + for binding in bindings: + entity=binding['entity_id'];path=binding['instance'] + prim=native.GetPrimAtPath(path) + if not prim:raise ValueError('Missing native instance: '+entity) + movable=[p for p in Usd.PrimRange(prim) if p.IsA(UsdPhysics.Joint) + and not p.IsA(UsdPhysics.FixedJoint) and UsdPhysics.Joint(p).GetJointEnabledAttr().Get()] + if len(movable)!=binding['movable_joint_count']: + raise ValueError('Native joint denominator changed: '+entity) + old=paths[entity] + surfaces=transfer_baked_surface(stage,native,old,path) if (output/'baked-material-delivery.json').exists() else [] + native.OverridePrim(old).SetActive(False) + paths[entity]=path + owned=[str(p.GetPath()) for p in Usd.PrimRange(prim) if p.HasAPI(UsdPhysics.RigidBodyAPI)] + bodies.extend(owned);joints.extend(str(p.GetPath()) for p in movable) + records.append(dict(entity_id=entity,instance=path,disabled_static_prim=old, + movable_joint_count=len(movable),body_paths=owned, + source_sha256=binding['source_sha256'])) + records[-1]['baked_surface_transfer']=surfaces + if len(joints)!=receipt['native_joint_denominator']: + raise ValueError('Native joint total changed') + layer.Save() + stage.GetRootLayer().subLayerPaths.insert(0,'native.usdc') + return dict(source_receipt_sha256=sha(source/'native_articulation_verification.json'), + source_runtime_sha256=sha(source/receipt['active_runtime']),instances=records, + body_paths=bodies,joint_paths=joints,joint_count=len(joints),texture_assets=textures, + validation_scope='source_gate_preserved; delivered_stage_requires_physical_validation') diff --git a/docs/reproduction/public_conversion_code/packages/adapters/rparena_usd_worker.py b/docs/reproduction/public_conversion_code/packages/adapters/rparena_usd_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9dc8caa60582926b6eec3b0f4d2f623cfbb178 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/rparena_usd_worker.py @@ -0,0 +1,114 @@ +"""OpenUSD-only worker used by the RoboHouseGen RPArena exporter.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +_SCENE_ANCHOR = "/World/SceneSmith" + + +def _request(path: Path) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(value, dict): + raise ValueError("RPArena USD worker request must be an object") + if set(value) != {"cleanup_layer", "entity_ids", "scene_usd"}: + raise ValueError("RPArena USD worker request fields are incomplete") + if not isinstance(value["entity_ids"], list) or not value["entity_ids"]: + raise ValueError("RPArena USD worker entity_ids must be a non-empty list") + return value + + +def inspect_scene(request: dict[str, Any]) -> dict[str, Any]: + from pxr import Sdf, Usd, UsdGeom # type: ignore[import-not-found] + + scene_usd_input = Path(str(request["scene_usd"])) + cleanup_layer = Path(str(request["cleanup_layer"])).resolve(strict=False) + if scene_usd_input.is_symlink(): + raise ValueError("RPArena exported scene must be a non-symlink regular file") + scene_usd = scene_usd_input.resolve(strict=True) + if not scene_usd.is_file(): + raise ValueError("RPArena exported scene must be a non-symlink regular file") + if cleanup_layer.exists(): + raise FileExistsError(f"cleanup layer already exists: {cleanup_layer}") + entity_ids = [str(value).strip() for value in request["entity_ids"]] + if any(not value for value in entity_ids) or entity_ids != sorted(set(entity_ids)): + raise ValueError("RPArena USD worker entity_ids must be sorted and unique") + + stage = Usd.Stage.Open(str(scene_usd)) + if stage is None: + raise RuntimeError(f"OpenUSD could not open exported scene: {scene_usd}") + anchor = Sdf.Path(_SCENE_ANCHOR) + anchor_prim = stage.GetPrimAtPath(anchor) + if not anchor_prim or not anchor_prim.IsValid(): + raise ValueError(f"exported scene lacks {_SCENE_ANCHOR}") + + bindings: dict[str, str] = {} + mesh_counts: dict[str, int] = {} + traversed = list(stage.Traverse()) + for entity_id in entity_ids: + token = f"entity__{entity_id}__" + roots: set[str] = set() + for prim in traversed: + if token not in str(prim.GetPath()): + continue + current = prim.GetPath() + while current != Sdf.Path.absoluteRootPath and current.GetParentPath() != anchor: + current = current.GetParentPath() + if current.GetParentPath() == anchor: + roots.add(str(current)) + if len(roots) != 1: + raise ValueError( + f"entity {entity_id!r} must bind to exactly one top-level USD root; " + f"found {sorted(roots)}" + ) + root = next(iter(roots)) + root_prim = stage.GetPrimAtPath(root) + mesh_count = sum( + 1 for descendant in Usd.PrimRange(root_prim) if descendant.IsA(UsdGeom.Mesh) + ) + if mesh_count < 1: + raise ValueError(f"entity {entity_id!r} USD root has no mesh descendants") + bindings[entity_id] = root + mesh_counts[entity_id] = mesh_count + if len(set(bindings.values())) != len(bindings): + raise ValueError("multiple semantic entities bind to the same USD root") + + task_visual_roots = sorted( + str(child.GetPath()) + for child in anchor_prim.GetChildren() + if child.GetName().startswith("task_") + ) + cleanup_layer.parent.mkdir(parents=True, exist_ok=True) + layer = Sdf.Layer.CreateNew(str(cleanup_layer)) + if layer is None: + raise RuntimeError(f"could not create cleanup layer: {cleanup_layer}") + for prim_path in task_visual_roots: + spec = Sdf.CreatePrimInLayer(layer, prim_path) + spec.specifier = Sdf.SpecifierOver + spec.active = False + layer.Save() + + default_prim = stage.GetDefaultPrim() + return { + "schema_version": "robothousegen.rparena-usd-inspection/1.0", + "scene_anchor": _SCENE_ANCHOR, + "source_default_prim": str(default_prim.GetPath()) if default_prim else None, + "entity_prim_paths": bindings, + "entity_mesh_counts": mesh_counts, + "task_visual_roots_disabled": task_visual_roots, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--request", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(inspect_scene(_request(args.request)), sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/reproduction/public_conversion_code/packages/adapters/rparena_v16.py b/docs/reproduction/public_conversion_code/packages/adapters/rparena_v16.py new file mode 100644 index 0000000000000000000000000000000000000000..31cc09094b4f41c49d5ecbf2e66a4da69045a0f6 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/rparena_v16.py @@ -0,0 +1,945 @@ +"""Export v16 scenes without changing the retired asset-first adapter.""" +from __future__ import annotations + +import argparse +from contextlib import contextmanager +import hashlib +import json +import math +import os +from pathlib import Path +import resource +import re +import shutil +import subprocess +import time +import traceback + + +def read(path): + return json.loads(Path(path).read_text(encoding='utf-8')) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + '.tmp') + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8') + temporary.replace(path) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b''): + digest.update(chunk) + return digest.hexdigest() + + +@contextmanager +def timed(records, name, output): + started = time.time() + row = dict(stage=name, started_at=started, status='running', gpu_s=None, + gpu_accounting='未采样;不以 wall time 冒充 GPU·s') + records.append(row) + write(output / 'timing.json', records) + try: + yield row + row['status'] = 'completed' + except Exception as error: + row.update(status='failed', error=str(error), traceback=traceback.format_exc()) + raise + finally: + row.update(wall_s=time.time() - started, + process_peak_rss_bytes=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024, + children_peak_rss_bytes=resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss * 1024, + output_bytes=sum(path.stat().st_size for path in output.rglob('*') if path.is_file())) + write(output / 'timing.json', records) + + +def material_assets(stage, source, package, shared): + from pxr import Sdf, UsdUtils + layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(source)) + if unresolved: + raise ValueError('USD 引用未解析:' + str(unresolved)) + if len(layers) != 1: + raise ValueError('视觉入口含多层 USD;须先明确各层变换和引用,禁止静默 flatten') + copied = [] + for prim in stage.Traverse(): + for attribute in prim.GetAttributes(): + if attribute.GetTypeName() not in (Sdf.ValueTypeNames.Asset, Sdf.ValueTypeNames.AssetArray): + continue + value = attribute.Get() + if value is None: + continue + values = list(value) if attribute.GetTypeName() == Sdf.ValueTypeNames.AssetArray else [value] + replacements = [] + for item in values: + if not item.path: + replacements.append(item) + continue + path = Path(item.resolvedPath or str(source.parent / item.path)).resolve() + if not path.is_file(): + raise FileNotFoundError('材质缺失,需针对缺失材质烘焙:' + str(path)) + identity = sha(path) + relative = 'assets/' + identity + path.suffix.lower() + intern(path, package / relative, shared / (identity + path.suffix.lower())) + replacements.append(Sdf.AssetPath(relative)) + copied.append(dict(source=str(path), path=relative, sha256=identity)) + attribute.Set(replacements if attribute.GetTypeName() == Sdf.ValueTypeNames.AssetArray else replacements[0]) + return copied + + +def intern(source, destination, cached): + cached.parent.mkdir(parents=True, exist_ok=True) + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + if sha(destination) != sha(source): + raise ValueError('目标已存在且内容不同:' + str(destination)) + return + if not cached.exists(): + temporary = cached.with_name(cached.name + '.' + str(os.getpid()) + '.tmp') + shutil.copyfile(source, temporary) + try: + os.link(temporary, cached) + except FileExistsError: + pass + temporary.unlink() + if sha(cached) != sha(source): + raise ValueError('内容缓存身份不一致:' + str(cached)) + try: + os.link(cached, destination) + except OSError: + shutil.copyfile(cached, destination) + + +def deduplicate_geometry(stage, package, shared): + from pxr import Sdf, Usd, UsdGeom + rows = [] + for prim in list(stage.Traverse()): + if not prim.IsA(UsdGeom.Mesh) or prim.IsInstanceProxy(): + continue + geometry = Usd.Stage.CreateInMemory() + mesh = UsdGeom.Mesh.Define(geometry, '/Geometry') + names = [] + for attribute in prim.GetAttributes(): + name = attribute.GetName() + if name.startswith(('xformOp', 'material:', 'physics:', 'physx', 'rhg:', 'userProperties:')) or name in ('visibility', 'purpose'): + continue + if attribute.GetNumTimeSamples(): + raise ValueError('静态 v16 包不允许动画网格:' + str(prim.GetPath())) + if attribute.HasAuthoredValueOpinion(): + target = mesh.GetPrim().CreateAttribute(name, attribute.GetTypeName(), attribute.IsCustom(), attribute.GetVariability()) + target.Set(attribute.Get()) + for key, value in attribute.GetAllMetadata().items(): + if key not in ('typeName', 'custom', 'variability', 'default'): + target.SetMetadata(key, value) + names.append(name) + identity = hashlib.sha256(geometry.GetRootLayer().ExportToString().encode()).hexdigest() + cached = shared / (identity + '.usdc') + if not cached.exists(): + temporary = shared / (identity + '.' + str(os.getpid()) + '.usdc') + geometry.GetRootLayer().Export(str(temporary)) + try: + os.link(temporary, cached) + except FileExistsError: + pass + temporary.unlink() + destination = package / 'assets' / cached.name + if not destination.exists(): + intern(cached, destination, cached) + for name in names: + prim.RemoveProperty(name) + prim.GetReferences().AddReference('assets/' + cached.name, '/Geometry') + rows.append(dict(prim_path=str(prim.GetPath()), geometry_content_sha256=identity, + file_sha256=sha(destination), bytes=destination.stat().st_size)) + return rows + + +def group_roots(stage, roots, name): + from pxr import Usd, UsdGeom + if not roots: + raise ValueError('没有可分组的几何节点:' + name) + parents = {path.GetParentPath() for path in roots} + if len(parents) != 1: + raise ValueError('实体几何跨越不同变换父节点,需显式处理:' + name) + parent = next(iter(parents)) + group = parent.AppendChild(name) + if stage.GetPrimAtPath(group): + raise ValueError('分组节点冲突:' + str(group)) + UsdGeom.Xform.Define(stage, group) + for path in roots: + editor = Usd.NamespaceEditor(stage) + editor.MovePrimAtPath(path, group.AppendChild(path.name)) + if not editor.CanApplyEdits(): + raise ValueError('USD namespace 编辑无法保留依赖:' + str(path)) + editor.ApplyEdits() + return group + + +def entity_paths(stage, manifest): + paths = {} + for entity in manifest['entities']: + identity = entity['entity_id'] + matches = [] + for prim in stage.Traverse(): + values = [prim.GetName()] + values += [str(attribute.Get()) for attribute in prim.GetAttributes() + if attribute.GetName().endswith(('entity_id', 'object_name'))] + if identity in values or any(identity in value for value in values): + matches.append(prim.GetPath()) + roots = [path for path in matches if not any(path != parent and path.HasPrefix(parent) for parent in matches)] + if not roots: + raise ValueError(f'实体没有对应的 USD 几何:{identity}') + paths[identity] = str(roots[0] if len(roots) == 1 else group_roots(stage, roots, 'rparena_entity_' + identity)) + return paths + + +def luna_scene_namespace(stage): + """对齐冻结 Luna 驱动的碰撞路径约定,只改变节点路径。""" + from pxr import UsdGeom + world = stage.GetPrimAtPath('/World') + if stage.GetPrimAtPath('/World/SceneSmith'): + raise ValueError('源已有SceneSmith命名空间;需显式核对,禁止重复包裹') + scene = group_roots(stage, [prim.GetPath() for prim in world.GetChildren()], 'SceneSmith') + floors = [prim.GetPath() for prim in stage.GetPrimAtPath(scene).GetChildren() + if prim.GetName().startswith(('floor__','floor_connection__'))] + if not floors: + raise ValueError('没有v16 floor__地板;不能伪造Luna地板绑定') + shell = group_roots(stage, floors, 'shell_floor') + floor = group_roots(stage, [prim.GetPath() for prim in stage.GetPrimAtPath(shell).GetChildren()], 'Cube') + stage.GetRootLayer().Save() + return dict(scene_root=str(scene), floor_path=str(floor), + geometry_changed=False, driver_contract='frozen_luna_wheel_run_paths') + + +def luna_scene_entry(package, base): + from pxr import Sdf, Usd, UsdGeom + path = package / 'scenesmith/scene.usdc' + path.parent.mkdir(parents=True, exist_ok=True) + layer = Sdf.Layer.CreateNew(str(path)) + layer.subLayerPaths = [base] + layer.defaultPrim = 'World' + layer.Save() + stage = Usd.Stage.Open(layer) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + stage.GetRootLayer().Save() + return 'scenesmith/scene.usdc' + + +def mass_evidence(entity): + candidates = [(entity, 'SceneManifest.entity')] + for key in ('physics', 'physical_properties', 'metadata'): + if isinstance(entity.get(key), dict): + candidates.append((entity[key], 'SceneManifest.entity.' + key)) + for values, source in candidates: + value = values.get('mass_kg') + if isinstance(value, (float, int)) and not isinstance(value, bool) and math.isfinite(value) and value > 0: + return float(value), source + return None, '原始实体和物理元数据未提供质量;禁止臆造' + + +def author_physics(stage, output, manifest, episode, paths): + from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics + layer = Sdf.Layer.CreateNew(str(output / 'physics.usda')) + stage.GetRootLayer().subLayerPaths.insert(0, 'physics.usda') + stage.SetEditTarget(layer) + physics_scene = UsdPhysics.Scene.Define(stage, '/World/PhysicsScene') + physics_scene.CreateGravityDirectionAttr(Gf.Vec3f(0, 0, -1)) + physics_scene.CreateGravityMagnitudeAttr(9.81) + binding = episode.get('bindings', {}).get('pickup_object', {}) + pickup = binding.get('entity_id') + entity = next((row for row in manifest['entities'] if row['entity_id'] == pickup), None) + mass, source = mass_evidence(entity or {}) + if entity is None: + raise ValueError('BenchmarkEpisode 缺少原生 pickup_object 绑定') + root = stage.GetPrimAtPath(paths[pickup]) + if mass is not None: + UsdPhysics.RigidBodyAPI.Apply(root).CreateRigidBodyEnabledAttr(True) + UsdPhysics.MassAPI.Apply(root).CreateMassAttr(mass) + excluded = [] + for prim in stage.Traverse(): + if prim.IsA(UsdGeom.Mesh): + ancestor = prim + hardware = False + source_guide = False + while ancestor and ancestor.GetPath() != Sdf.Path.absoluteRootPath: + kind=ancestor.GetAttribute('rhg:kind') + if kind and kind.Get()=='door_swing_keepout_v9': + source_guide=True + break + if ancestor.GetName().startswith(('door_hinge_pin__','door_hinge_plate__','door_hinge_continuous_bridge__','door_leaf_hinge_strap__','door_leaf_detail__')): + hardware = True + break + ancestor = ancestor.GetParent() + if hardware or source_guide: + UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(False) + excluded.append(str(prim.GetPath())) + continue + if 'pmp20_window_backdrop_' in str(prim.GetPath()): + UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(False) + excluded.append(str(prim.GetPath())) + continue + UsdPhysics.CollisionAPI.Apply(prim).CreateCollisionEnabledAttr(True) + dynamic = prim.GetPath().HasPrefix(root.GetPath()) and mass is not None + UsdPhysics.MeshCollisionAPI.Apply(prim).CreateApproximationAttr('convexHull' if dynamic else 'none') + prim.AddAppliedSchema('PhysxCollisionAPI') + prim.CreateAttribute('physxCollision:contactOffset', Sdf.ValueTypeNames.Float).Set(0.001) + prim.CreateAttribute('physxCollision:restOffset', Sdf.ValueTypeNames.Float).Set(0.0) + layer.Save() + stage.SetEditTarget(stage.GetRootLayer()) + return dict(pickup_entity_id=pickup, mass_kg=mass, mass_source=source, + dynamic_authored=mass is not None, + excluded_attachment_colliders=excluded, + blockers=[] if mass is not None else ['native_mass_metadata_missing']) + + +def author_doors(stage, source, output, *, preserve_source_runtime=False): + from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics + receipt = read(source / 'door_physics_verification.json') + if receipt.get('schema') != 'rhg.house_door_gate.v1' or receipt.get('passed') is not True: + raise ValueError('源门 PhysX 门控没有通过') + expected = receipt.get('evidence_sha256', {}) + required = {'door_physics/input.json.gz','door_physics/mesh_sweep.json', + 'door_physics/runtime/report.json','door_physics/runtime/trace.json', + 'door_physics/runtime/articulated_scene.usdc'} + if not required.issubset(expected): + raise ValueError('源门控缺少完整证据集合') + if sha(source / (source.name + '.blend')) != receipt.get('source_blend_sha256'): + raise ValueError('源 blend 与门控通过时的身份不一致') + for name, digest in expected.items(): + path = (source / name).resolve() + if not path.is_relative_to(source) or sha(path) != digest: + raise ValueError('门控证据缺失或已变化:' + name) + import gzip + payload = json.loads(gzip.decompress((source / 'door_physics/input.json.gz').read_bytes())) + definitions = payload['doors'] + verified_runtime=Usd.Stage.Open(str(source/'door_physics/runtime/articulated_scene.usdc')) if preserve_source_runtime else None + layer = Sdf.Layer.CreateNew(str(output / 'doors.usda')) + stage.GetRootLayer().subLayerPaths.insert(0, 'doors.usda') + stage.SetEditTarget(layer) + results = [] + for definition_index,definition in enumerate(definitions): + name = definition['leaf'] + objects = set(definition['moving_objects']) + matches = [prim for prim in stage.Traverse() if prim.GetName() in objects] + parents = [prim for prim in stage.Traverse() if prim.GetName() == 'door_hinge_joint__' + definition['door_id']] + roots = parents if len(parents) == 1 and all(prim.GetPath().HasPrefix(parents[0].GetPath()) for prim in matches) else [prim for prim in matches if not any(prim != parent and prim.GetPath().HasPrefix(parent.GetPath()) for parent in matches)] + found_names = {prim.GetName() for prim in matches} + if found_names != objects: + raise ValueError('源门的移动部件未完整导出:' + str(objects - found_names)) + body = roots[0] if len(roots) == 1 else stage.GetPrimAtPath(group_roots(stage, [prim.GetPath() for prim in roots], 'rparena_door_' + definition['door_id'])) + mass = definition.get('mass_kg') + if not mass or not definition.get('mass_provenance'): + raise ValueError('源门质量及来源缺失:' + name) + UsdPhysics.RigidBodyAPI.Apply(body).CreateRigidBodyEnabledAttr(True) + UsdPhysics.MassAPI.Apply(body).CreateMassAttr(mass) + copied_physics={} + if verified_runtime: + verified_body=verified_runtime.GetPrimAtPath(f'/World/Doors/Door_{definition_index}') + if not verified_body or verified_body.GetAttribute('physics:mass').Get()!=mass: + raise ValueError('Verified door body identity differs from source definition') + # Plain OpenUSD exporters may not have the PhysX schema plugin + # loaded. GetAppliedSchemas then omits authored PhysX APIs even + # though their attributes remain in the source layer. + schemas=verified_body.GetMetadata('apiSchemas') + for schema in schemas.GetAppliedItems() if schemas else []: + if schema.startswith(('Physics','Physx')):body.AddAppliedSchema(schema) + for attribute in verified_body.GetAuthoredAttributes(): + if attribute.GetName().startswith(('physics:','physxRigidBody:')): + body.CreateAttribute(attribute.GetName(),attribute.GetTypeName(), + custom=attribute.IsCustom(),variability=attribute.GetVariability()).Set(attribute.Get()) + copied_physics[attribute.GetName()]=str(attribute.Get()) + for child in stage.Traverse(): + if child.IsA(UsdGeom.Mesh) and child.GetPath().HasPrefix(body.GetPath()): + UsdPhysics.MeshCollisionAPI.Apply(child).CreateApproximationAttr('convexHull') + joint = UsdPhysics.RevoluteJoint.Define(stage, '/World/RHGDoorJoints/' + definition['door_id']) + joint.CreateAxisAttr('Z') + joint.CreateBody1Rel().SetTargets([body.GetPath()]) + hinge = Gf.Vec3d(*definition['hinge_xyz_m']) + transform = UsdGeom.XformCache().GetLocalToWorldTransform(body) + local = transform.GetInverse().Transform(hinge) + joint.CreateLocalPos0Attr(Gf.Vec3f(*hinge)) + joint.CreateLocalPos1Attr(Gf.Vec3f(*local)) + orientation = transform.ExtractRotationQuat() + joint.CreateLocalRot0Attr(Gf.Quatf(1)) + joint.CreateLocalRot1Attr(Gf.Quatf(orientation.GetInverse())) + sign = definition['opening_sign'] + authored = definition['authored_opening_deg'] + limits = sorted(sign * (angle - authored) for angle in definition['limits_deg']) + joint.CreateLowerLimitAttr(limits[0]) + joint.CreateUpperLimitAttr(limits[1]) + joint.CreateCollisionEnabledAttr(False) + drive = UsdPhysics.DriveAPI.Apply(joint.GetPrim(), 'angular') + drive.CreateTypeAttr('force') + drive.CreateStiffnessAttr(300.0) + drive.CreateDampingAttr(80.0) + drive.CreateMaxForceAttr(150.0) + drive.CreateTargetPositionAttr(0.0) + results.append(dict(door_id=definition['door_id'], body=str(body.GetPath()), + joint=str(joint.GetPath()), source_definition=definition, + preserved_source_body_physics=copied_physics, + acceptance='需要在新组合层重新执行开合,源门控不替代新验收')) + layer.Save() + stage.SetEditTarget(stage.GetRootLayer()) + return results + + +def same_support_destination(package, manifest, source, pickup, paths): + """用实际 USD 顶面筛选同一长支撑面的新目标;不声称物理可达。""" + from pxr import Gf, Usd, UsdGeom + import numpy as np + stage = Usd.Stage.Open(str(package / 'root.usda')) + support = stage.GetPrimAtPath(paths[source['entity_id']]) + triangles = [] + transforms = UsdGeom.XformCache() + for prim in Usd.PrimRange(support): + if not prim.IsA(UsdGeom.Mesh): + continue + mesh = UsdGeom.Mesh(prim) + transform = transforms.GetLocalToWorldTransform(prim) + points = np.asarray([list(transform.Transform(Gf.Vec3d(*point))) + for point in mesh.GetPointsAttr().Get()], dtype=float) + indices = list(mesh.GetFaceVertexIndicesAttr().Get()) + offset = 0 + for count in mesh.GetFaceVertexCountsAttr().Get(): + face = indices[offset:offset+count] + offset += count + for index in range(1, count-1): + triangles.append(points[[face[0], face[index], face[index+1]]]) + if not triangles: + return None + vertices = np.asarray(triangles) + a, b, c = vertices[:, 0], vertices[:, 1], vertices[:, 2] + denominator = (b[:, 1]-c[:, 1])*(a[:, 0]-c[:, 0]) + (c[:, 0]-b[:, 0])*(a[:, 1]-c[:, 1]) + valid = np.abs(denominator) > 1e-10 + a, b, c, denominator = a[valid], b[valid], c[valid], denominator[valid] + z = source['position_xyz_m'][2] + def supported(x, y): + u = ((b[:, 1]-c[:, 1])*(x-c[:, 0]) + (c[:, 0]-b[:, 0])*(y-c[:, 1])) / denominator + v = ((c[:, 1]-a[:, 1])*(x-c[:, 0]) + (a[:, 0]-c[:, 0])*(y-c[:, 1])) / denominator + height = u*a[:, 2] + v*b[:, 2] + (1-u-v)*c[:, 2] + hit = height[(u >= -1e-7) & (v >= -1e-7) & (u+v <= 1+1e-7)] + return bool(len(hit) and abs(float(hit.max())-z) <= .015) + bounds = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render']).ComputeWorldBound(support).ComputeAlignedBox() + lower, upper = bounds.GetMin(), bounds.GetMax() + # 12 cm 的物体包围半宽覆盖原生小物体及标准芥末瓶;不外推给更大物体。 + margin = .12 + candidates = [] + for x in np.arange(lower[0]+margin, upper[0]-margin+.001, .08): + for y in np.arange(lower[1]+margin, upper[1]-margin+.001, .08): + distance = math.dist([x, y], pickup['position_xyz_m'][:2]) + if distance < .5: + continue + if not all(supported(x+dx, y+dy) for dx, dy in ((0,0),(-margin,-margin),(-margin,margin),(margin,-margin),(margin,margin))): + continue + obstructed = False + for entity in manifest['entities']: + if entity['entity_id'] in (source['entity_id'], pickup['entity_id']): + continue + box = entity.get('world_bbox_m') + if box and box[0][2] < z+.30 and box[1][2] > z+.015 and box[0][0]-margin < x < box[1][0]+margin and box[0][1]-margin < y < box[1][1]+margin: + obstructed = True + break + if not obstructed: + candidates.append((distance, float(x), float(y))) + if not candidates: + return None + distance, x, y = max(candidates) + return {**source, 'anchor_id':source['anchor_id']+'::same_support_transfer', + 'position_xyz_m':[x, y, z], 'geometry_source':'USD_mesh_top_five_probe_points_and_entity_bbox_clearance', + 'derivation_evidence':{'transfer_xy_m':distance, 'footprint_half_width_m':margin, + 'maximum_object_height_m':.25, 'physical_reachability_verified':False}} + + +def luna_cases(package, manifest, episode, paths, physics, seeds, allow_same_support=False): + pickup = episode['bindings']['pickup_object'] + entities = {row['entity_id']: row for row in manifest['entities']} + target = entities[pickup['entity_id']] + supports = [row for row in manifest['interaction_anchors'] + if row.get('kind') == 'place_on_top' and row['room_id'] == pickup['room_id']] + if not supports: + raise ValueError('任务房间没有测量支撑面') + source = min(supports, key=lambda row: math.dist(row['position_xyz_m'][:2], pickup['position_xyz_m'][:2])) + destination = episode['bindings'].get('placement_target', {}) + blockers = list(physics['blockers']) + derivation = '保留 BenchmarkEpisode 同房间目标' + if destination.get('room_id') != pickup['room_id'] or destination.get('entity_id') == source['entity_id']: + candidates = [row for row in supports if row['entity_id'] != source['entity_id'] + and 0.35 <= row['position_xyz_m'][2] <= 1.2] + if not candidates: + fallback = same_support_destination(package, manifest, source, pickup, paths) if allow_same_support else None + dimensions = target.get('dimensions_m', target.get('source_dimensions_m')) + if fallback and dimensions and max(dimensions[:2]) <= .24 and dimensions[2] <= .25: + destination = fallback + derivation = '按续跑授权在同一长支撑面转移至少0.5米;USD顶面五点及实体包围盒筛选,物理可达性待完整任务验证' + else: + blockers.append('no_distinct_same_room_support') + derivation = '同房间目标不足;原绑定仅保留为不可执行诊断,不运行跨房间替代任务' + else: + destination = max(candidates, key=lambda row: math.dist(source['position_xyz_m'][:2], row['position_xyz_m'][:2])) + derivation = '首测限定同房间,使用测量锚点派生新的放置任务;原任务保留' + if not destination.get('entity_id'): + raise ValueError('没有原始放置目标;禁止构造虚假任务实体') + room = next(row for row in manifest['rooms'] if row['room_id'] == pickup['room_id']) + x0, y0, x1, y1 = room['bounds_m'] + spawn = [(x0 + x1) / 2, (y0 + y1) / 2, 0.0] + # These are nominal search hints, not collision or reachability certificates. + # The native Luna consumer requires both keys before station search begins. + pick_xy = pickup['position_xyz_m'][:2] + place_xy = destination['position_xyz_m'][:2] + pick_hint = [*spawn[:2], math.atan2(pick_xy[1]-spawn[1], pick_xy[0]-spawn[0])] + place_hint_xy = [max(x0, min(x1, place_xy[0]+spawn[0]-pick_xy[0])), + max(y0, min(y1, place_xy[1]+spawn[1]-pick_xy[1]))] + place_hint = [*place_hint_xy, math.atan2(place_xy[1]-place_hint_xy[1], + place_xy[0]-place_hint_xy[0])] + task_id = package.name + '-native-transfer' + task_entities = [dict(entity_id=key, role='MANIPULATED' if key == pickup['entity_id'] else 'TARGET', + category=entity.get('category', entity.get('role')), required=True, + attributes={**entity, **({'parent_entity_id': source['entity_id']} if key == pickup['entity_id'] else {})}) + for key, entity in entities.items()] + write(package / 'manifests/task.json', dict(schema_version='1.0', task_id=task_id, entities=task_entities, + goal_predicates=[dict(name='supported_by', subject=pickup['entity_id'], object=destination['entity_id'])], + metadata=dict(room_dimensions_m=[x1-x0, y1-y0], pick=pickup, place=destination, + derivation=derivation, original_task_spec=episode['task_spec'], + original_bindings=episode['bindings'], original_success_conditions=episode.get('success_conditions')))) + write(package / 'manifests/scene.json', dict(schema_version='1.0', scene_id=package.name, + task_id=task_id, entity_prim_paths=paths, robot_prim_path='/World/RobotSpawnStub', + runtime_robot_prim_path='/World/Luna/Robot', runtime='luna_wheel_run_mesh', generic_runtime_supported=False)) + write(package / 'manifests/episode.json', episode) + dimensions = target.get('dimensions_m', target.get('source_dimensions_m')) + records = [] + for seed in seeds: + case = dict(case_id=f'{package.name}-native-s{seed}', seed=seed, group='development', split='development', + scene_contract_version='rhg-luna/1.0', scene_id=package.name, scene_path=str(package.resolve()), + source_task_id=task_id, entity_id=pickup['entity_id'], source_id=source['entity_id'], + destination_id=destination['entity_id'], source_surface_z_m=source['position_xyz_m'][2], + source_room_id=source['room_id'], destination_room_id=destination['room_id'], + destination_surface_z_m=destination['position_xyz_m'][2], + target_position_xy=pickup['position_xyz_m'][:2], destination_position_xy=destination['position_xyz_m'][:2], + navigation_bounds=[x0,x1,y0,y1], start_base=spawn, dimensions=dimensions, + pick_base=pick_hint, place_base=place_hint, + station_hints_physical_reachability_verified=False, + mass_kg=physics['mass_kg'], scene_mode='original', shape='original', + object_usd_path=str(package / 'root.usda'), object_prim_path=paths[pickup['entity_id']], + object_position_xyz_m=[*pickup['position_xyz_m'][:2], target.get('base_z_m', 0.0)], + object_kind='original', object_id=target.get('asset_id'), native_target_retained=True, + instruction='在同一房间抓取原生物体,抬升、保持、搬运、放置、释放、撤离并独立读回。', + runnable=not blockers, blockers=blockers, task_derivation=derivation, + destination_derivation_evidence=destination.get('derivation_evidence'), + destination_offset_xy=[0.,0.], object_offset_xy=[0.,0.]) + write(package / ('cases' if case['runnable'] else 'blocked-cases') / (case['case_id'] + '.json'), case) + records.append(case) + write(package / 'luna-case-status.json', dict(status='ready' if not blockers else 'blocked', + reasons=blockers, native_physics=physics, cases=[row['case_id'] for row in records], physical_task_qualified=False)) + return records + + +def standard_control_cases(package, native_cases, template_path, shared): + from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics + template = read(template_path) + if template.get('object_kind') != 'real_mesh' or not template.get('real_mesh'): + raise ValueError('标准物体对照必须来自已验证的 real_mesh case 配方') + source = Path(template['mesh_usd_path']).resolve() + geometry = Path(template['mesh_geometry_path']).resolve() + if sha(source) != template['mesh_usd_sha256'] or sha(geometry) != template['mesh_geometry_sha256']: + raise ValueError('标准物体配方的资产哈希变化') + mass = template['mass_kg'] + if not isinstance(mass,(int,float)) or isinstance(mass,bool) or not math.isfinite(mass) or mass <= 0: + raise ValueError('标准物体配方必须提供有效质量') + original = Usd.Stage.Open(str(source)) + original.Flatten().Export(str(package / 'control-object.usdc')) + asset = Usd.Stage.Open(str(package / 'control-object.usdc')) + material_assets(asset, package / 'control-object.usdc', package, shared) + asset.GetRootLayer().Save() + relative_geometry = 'assets/' + sha(geometry) + '.npz' + intern(geometry, package / relative_geometry, shared / Path(relative_geometry).name) + controls = [] + for native in native_cases: + case = dict(native) + folder = package / 'controls' / str(native['seed']) + folder.mkdir(parents=True) + root = Sdf.Layer.CreateNew(str(folder / 'root.usda')) + root.subLayerPaths = [luna_scene_entry(folder, '../../../root.usda')] + root.Save() + stage = Usd.Stage.Open(str(folder / 'root.usda')) + stage.SetDefaultPrim(stage.GetPrimAtPath('/World')) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + # Luna's SimulationContext creates the GPU physics scene. Importing a + # second scene breaks its single-scene DirectGPU view. + stage.OverridePrim('/World/PhysicsScene').SetActive(False) + stage.OverridePrim(native['object_prim_path']).SetActive(False) + target = UsdGeom.Xform.Define(stage, '/World/G1MeshTarget') + target.GetPrim().GetReferences().AddReference('../../control-object.usdc') + dimensions = template['dimensions'] + position = [*native['target_position_xy'], native['source_surface_z_m'] + dimensions[2]/2 + 0.003] + UsdGeom.Xformable(target).ClearXformOpOrder() + UsdGeom.Xformable(target).AddTranslateOp().Set(Gf.Vec3d(*position)) + UsdPhysics.RigidBodyAPI.Apply(target.GetPrim()).CreateRigidBodyEnabledAttr(True) + UsdPhysics.MassAPI.Apply(target.GetPrim()).CreateMassAttr(float(mass)) + # Preserve the verified object's authored collision decomposition. Enabling + # its visual mesh as an extra hull would change the physical recipe. + collision_parts = [prim for prim in Usd.PrimRange(target.GetPrim()) + if prim.IsA(UsdGeom.Mesh) and prim.HasAPI(UsdPhysics.CollisionAPI) + and UsdPhysics.CollisionAPI(prim).GetCollisionEnabledAttr().Get() is not False] + if not collision_parts: + raise ValueError('标准物体配方没有已声明的碰撞部件') + stage.GetRootLayer().Save() + for name in ('scene.json','task.json','episode.json'): + value = read(package / 'manifests' / name) + if name == 'scene.json': + value['entity_prim_paths'][native['entity_id']] = '/World/G1MeshTarget' + if name == 'task.json': + for entity in value['entities']: + if entity['entity_id'] == native['entity_id']: + entity['attributes'].update(asset_id=template['mesh_source_id'], mass_kg=mass, + dimensions_m=dimensions, control_template=str(template_path)) + write(folder / 'manifests' / name, value) + blockers = [reason for reason in native['blockers'] if reason != 'native_mass_metadata_missing'] + if native.get('destination_derivation_evidence') and (max(dimensions[:2]) > .24 or dimensions[2] > .25): + blockers.append('standard_object_exceeds_same_support_screen_dimensions') + case.update(case_id=native['case_id'].replace('-native-', '-standard-control-'), + scene_path=str(folder), object_kind='real_mesh', real_mesh=True, dimensions=dimensions, + physics_scene_owner='luna_runtime',object_usd_path=str(folder/'root.usda'), + object_prim_path='/World/G1MeshTarget',object_position_xyz_m=position, + mass_kg=mass, mesh_source_id=template['mesh_source_id'], + object_id=template['object_id'], close_position=template['close_position'], + color=template.get('color',[.2,.4,.8]), color_name=template.get('color_name','authored_texture'), + mesh_usd_path=str(package / 'control-object.usdc'), mesh_usd_sha256=sha(package / 'control-object.usdc'), + mesh_geometry_path=str(package / relative_geometry), mesh_geometry_sha256=sha(geometry), + mesh_initial_root_position=position, mesh_initial_yaw_rad=0.0, + native_target_retained=False, parent_room_native_target_retained=False, + condition='standard_object_control', original_native_case_id=native['case_id'], + substitution_reason=native['blockers'], blockers=blockers, runnable=not blockers, + standard_object_provenance=dict(template_path=str(template_path), template_sha256=sha(template_path))) + write(package / ('cases' if case['runnable'] else 'blocked-cases') / (case['case_id'] + '.json'), case) + controls.append(case) + return controls + + +def native_luna_entries(package, cases): + from pxr import Sdf, Usd, UsdGeom + for case in cases: + folder = package/'native'/str(case['seed']) + folder.mkdir(parents=True) + root = Sdf.Layer.CreateNew(str(folder/'root.usda')) + root.subLayerPaths = [luna_scene_entry(folder, '../../../root.usda')] + root.Save() + stage = Usd.Stage.Open(str(folder/'root.usda')) + stage.SetDefaultPrim(stage.GetPrimAtPath('/World')) + UsdGeom.SetStageUpAxis(stage, 'Z') + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + stage.OverridePrim('/World/PhysicsScene').SetActive(False) + stage.GetRootLayer().Save() + for name in ('scene.json','task.json','episode.json'): + write(folder/'manifests'/name, read(package/'manifests'/name)) + case.update(scene_path=str(folder),physics_scene_owner='luna_runtime') + write(package/('cases' if case['runnable'] else 'blocked-cases')/(case['case_id']+'.json'),case) + +def pinned_runtime_files(package): + runtime={} + if (package/'baked-material-delivery.json').exists(): + for name,dependency in read(package/'baked-material-delivery.json')['runtime_dependencies'].items(): + path=Path(dependency['path']).resolve() + if name!='OmniSurface.mdl' or path.name!=name or not path.is_file() or sha(path)!=dependency['sha256']: + raise ValueError('声明的内置 MDL 运行时依赖不匹配') + runtime[path]=dependency['sha256'] + return runtime + + +def register_authored_luna_scene(package, folder): + """登记新整屋的完整源图;不套用旧房间外观恢复或授予外观资格。""" + from pxr import Usd, UsdGeom, UsdUtils + entry = folder / 'root.usda' + stage = Usd.Stage.Open(str(entry)) + meshes = [prim for prim in stage.Traverse() if prim.IsA(UsdGeom.Mesh)] + evidence = dict(world_default_prim=str(stage.GetDefaultPrim().GetPath()) == '/World', + meter_units=UsdGeom.GetStageMetersPerUnit(stage) == 1.0, + z_up=UsdGeom.GetStageUpAxis(stage) == 'Z', + floor_present=bool(stage.GetPrimAtPath('/World/SceneSmith/shell_floor/Cube')), + wall_meshes=sum('wall' in str(prim.GetPath()).lower() for prim in meshes), + ceiling_meshes=sum('ceiling' in str(prim.GetPath()).lower() for prim in meshes), + mesh_count=len(meshes)) + if not all(evidence[key] for key in ('world_default_prim','meter_units','z_up','floor_present','wall_meshes','ceiling_meshes')): + raise ValueError('新整屋登记缺少明确的轴向、单位或完整建筑外壳') + layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(entry)) + if unresolved: + raise ValueError('新整屋登记存在未解析依赖:'+str(unresolved)) + paths = {entry.resolve(), *(Path(layer.realPath).resolve() for layer in layers if layer.realPath), + *(Path(str(asset)).resolve() for asset in assets), + *(path.resolve() for path in (folder/'manifests').glob('*.json')), + (package/'provenance.json').resolve()} + runtime=pinned_runtime_files(package) + if any(not path.is_file() or (not path.is_relative_to(package.resolve()) and path not in runtime) for path in paths): + raise ValueError('新整屋登记依赖缺失或超出包目录') + write(folder/'rhg-authored-scene.json', dict(schema='rparena.rhg-authored-full-scene/1', + entry=str(entry.resolve()),entry_sha256=sha(entry),structural_evidence=evidence, + input_sha256={str(path):sha(path) for path in sorted(paths)}, + runtime_dependency_sha256={str(path):value for path,value in runtime.items()}, + visual_qualification='unqualified_new_house',physical_task_qualified=False)) + +def export_scene(args): + from pxr import Sdf, Usd, UsdGeom, Work + Work.SetConcurrencyLimit(4) + source = args.source.resolve() + output = args.output.resolve() + if not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', args.scene_id) or not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', output.name): + raise ValueError('scene-id 和输出目录名必须符合 RPArena static-scene 标识格式') + if output.exists(): + raise FileExistsError('输出必须为新目录:' + str(output)) + output.mkdir(parents=True) + records = [] + try: + manifest = read(source / 'SceneManifest.v16.json') + episode = read(source / 'BenchmarkEpisode.v16.json') + if manifest.get('schema') != 'robohousegen.SceneManifest.v16' or episode.get('schema') != 'robohousegen.BenchmarkEpisode.v16': + raise ValueError('只接受 v16 的 SceneManifest 与 BenchmarkEpisode') + generation_record = source.parent.parent / 'generation-timing.json' + records.append(dict(stage='generation', status='measured' if generation_record.exists() else 'not_available', + evidence=read(generation_record) if generation_record.exists() else None)) + with timed(records, 'usd_export', output) as row: + delivery_policy=getattr(args,'delivery_policy','source') + if delivery_policy=='source' and args.reuse_package: + raise ValueError('Source delivery requires fresh source conversion; legacy visual packages cannot be reused') + if args.reuse_package: + reuse = args.reuse_package.resolve() + previous = read(reuse/'provenance.json') + expected_sources = previous['source_sha256'] + if any(sha(source/name) != expected for name,expected in expected_sources.items()): + raise ValueError('复用包的源场景身份不同;禁止复用视觉资产') + delivery = read(reuse/'delivery-manifest.json') + for name,expected in delivery['files'].items(): + path = (reuse/name).resolve() + if not path.is_relative_to(reuse) or not path.is_file() or sha(path) != expected: + raise ValueError('复用包交付文件缺失、越界或被修改:'+name) + shared = args.shared_assets.resolve() + for path in sorted((reuse/'assets').iterdir()): + if path.is_file(): + intern(path,output/'assets'/path.name,shared/path.name) + # The visual root is editable below; never hardlink it to the old run. + shutil.copyfile(reuse/'visual.usdc',output/'visual.usdc') + visual = reuse/'visual.usdc' + row.update(visual_reuse='verified_package',reuse_package=str(reuse), + reuse_delivery_sha256=sha(reuse/'delivery-manifest.json')) + else: + visual = source / 'visual_scene_base.usd' + transfer=None + if delivery_policy=='source': + transfer=getattr(args,'baked_transfer',None) + reference=getattr(args,'source_reference',None) + if transfer is None: + if not args.blender:raise ValueError('Default source delivery needs Blender for prepare/render/bake') + repo=Path(__file__).resolve().parents[2] + reference=output/'source-reference' + commands=[ + [args.blender,'-b','-t','2','--python-exit-code','1','--python',str(repo/'scripts/render_delivery_reference.py'),'--','--source',str(source),'--output',str(reference)], + [args.blender,'-b','-t','2','--python-exit-code','1','--python',str(repo/'scripts/bake_delivery_scene.py'),'--','--reference',str(reference),'--output',str(output/'source-transfer')]] + if getattr(args,'window_scenery',None):commands[0]+=['--window-scenery',str(args.window_scenery)] + from .source_device import blender_environment + with blender_environment(output,getattr(args,'gpu',None)) as environment: + for index,command in enumerate(commands): + with (output/f'source-stage-{index}.log').open('x') as log:subprocess.run(command,check=True,stdout=log,stderr=subprocess.STDOUT,env=environment) + transfer=output/'source-transfer' + if reference is None:raise ValueError('Baked delivery requires its saved Blender reference') + receipt=read(transfer/'bake-receipt.json') + if receipt['source_sha256']!=sha(reference/'source.blend') or receipt['geometry_max_error_m']>1e-6: + raise ValueError('Baked source identity or geometry changed') + from .rparena_baked import verify_images + parity=verify_images(transfer,reference,getattr(args,'texture_contract',None));write(output/'baked-source-parity.json',parity) + # Keep the existing mean-error gate. Clarity has its own strict + # verdict; retain it even when downstream diagnosis is needed. + if not parity['mean_error_passed']: + raise ValueError('Baked Blender source differs beyond the original PMP20 5/255 contract; keep failed views') + shutil.copyfile(reference/'source.blend',output/'source.blend') + source_contract=read(reference/'source-delivery.json') + if source_contract['display']!=receipt['source_display']: + raise ValueError('Source display changed after baking') + source_contract['ocio_config']='colormanagement/config.ocio' + write(output/'source-delivery.json',source_contract) + rays=read(reference/'source-ray-visibility.json') + if rays['source_blend_sha256']!=receipt['source_sha256']: + raise ValueError('Source ray visibility belongs to another Blender baseline') + write(output/'source-ray-visibility.json',rays) + shutil.copyfile(reference/'views.json',output/'reference-views.json') + shutil.copytree(reference/'colormanagement',output/'colormanagement') + visual=transfer/'visual.usdc' + reusable = False + if visual.exists(): + candidate = Usd.Stage.Open(str(visual)) + reusable = candidate is not None and all(all(count == 3 for count in UsdGeom.Mesh(prim).GetFaceVertexCountsAttr().Get()) + for prim in candidate.Traverse() if prim.IsA(UsdGeom.Mesh)) + candidate = None + if delivery_policy=='source' and not reusable: + raise ValueError('Baked transfer must contain a triangulated, openable USD') + if not reusable and not args.reuse_package: + if not args.blender: + raise ValueError('缺少 stage4 USD;传 --blender 以复用 RHG stage4') + repo = Path(__file__).resolve().parents[2] + command = [args.blender, '--background', '--python-exit-code', '1', '--python', + str(repo / 'scripts/export_rparena_v16_visual.py'), '--', str(source)] + with (output / 'usd-export.log').open('x') as log: + subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True) + visual = source / 'visual_scene_rparena_triangles.usd' + row['reused_stage4'] = reusable or bool(args.reuse_package) + row['triangulation'] = 'verified_package_triangles' if args.reuse_package else 'stage4_native_triangles' if reusable else 'Blender_stage4_explicit_triangulation_for_frozen_Luna_collision_consumer' + stage = Usd.Stage.Open(str(visual)) + if not stage or not stage.GetPrimAtPath('/World'): + raise ValueError('stage4 USD 必须含 /World') + if UsdGeom.GetStageUpAxis(stage) != 'Z' or abs(UsdGeom.GetStageMetersPerUnit(stage)-1) > 1e-9: + raise ValueError('源场景必须为 Z-up、米制,禁止隐式缩放') + stage.GetRootLayer().Export(str(output / 'visual.usdc')) + stage = Usd.Stage.Open(str(output / 'visual.usdc')) + stage.SetDefaultPrim(stage.GetPrimAtPath('/World')) + if delivery_policy=='source': + for prim in stage.Traverse(): + if 'glass__window__' in str(prim.GetPath()) and prim.IsA(UsdGeom.Mesh): + UsdGeom.Imageable(prim).CreateVisibilityAttr(UsdGeom.Tokens.invisible) + shared = args.shared_assets.resolve() + shared.mkdir(parents=True, exist_ok=True) + textures = material_assets(stage, visual, output, shared) + if transfer is not None: + from .rparena_baked import apply_baked + baked=apply_baked(stage,transfer,output,shared) + write(output/'baked-material-delivery.json',baked) + from .texture_compression import compress_colors + compression_policy=getattr(args,'texture_compression','auto') + if compression_policy=='auto':compression_policy='bc7' if 'texture_budget' in receipt else 'preserve' + compression=compress_colors(stage,output,shared,compression_policy) + variants={} + for item in compression['converted']:variants.setdefault(item['original'],{})[item['path']]=item + textures=[dict(source=item['source'],path=variant['path'],sha256=variant['sha256']) + for item in textures for variant in (variants.get(item['path'],{item['path']:item})).values()] + baked['texture_compression']=compression + write(output/'baked-material-delivery.json',baked) + if args.reuse_package: + old_metadata = read(args.reuse_package/'manifest.json') + namespace = old_metadata['luna_namespace'] + paths = old_metadata['entity_prim_paths'] + if not stage.GetPrimAtPath(namespace['floor_path']) or any(not stage.GetPrimAtPath(path) for path in paths.values()): + raise ValueError('复用视觉的 Luna 命名空间或实体映射不完整') + else: + namespace = luna_scene_namespace(stage) + paths = entity_paths(stage, manifest) + with timed(records, 'geometry_deduplication', output) as row: + geometry = deduplicate_geometry(stage, output, shared) + row.update(mesh_count=len(geometry), shared_asset_count=len({item['geometry_content_sha256'] for item in geometry})) + compact = output / 'visual-compact.usdc' + stage.GetRootLayer().Export(str(compact)) + compact.replace(output / 'visual.usdc') + root = Sdf.Layer.CreateNew(str(output / 'root.usda')) + root.subLayerPaths = [luna_scene_entry(output, '../visual.usdc')] + root.Save() + stage = Usd.Stage.Open(str(output / 'root.usda')) + stage.SetDefaultPrim(stage.GetPrimAtPath('/World')) + UsdGeom.SetStageUpAxis(stage, 'Z') + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + with timed(records, 'physics_layers', output): + physics = author_physics(stage, output, manifest, episode, paths) + doors = author_doors(stage, source, output,preserve_source_runtime=delivery_policy=='source') + native=dict(instances=[],body_paths=[],joint_count=0) + if delivery_policy=='source': + from .rparena_native import author_native + native=author_native(stage,source,output,paths,shared) + write(output/'native-articulation-delivery.json',native) + stage.GetRootLayer().Save() + with timed(records, 'metadata_and_luna_cases', output): + cases = luna_cases(output, manifest, episode, paths, physics, args.seeds, + allow_same_support=args.allow_same_support) + native_luna_entries(output, cases) + controls = [] + if args.control_template: + controls = standard_control_cases(output, cases, args.control_template.resolve(), shared) + case_status = read(output / 'luna-case-status.json') + case_status['standard_control_cases'] = [row['case_id'] for row in controls] + case_status['runnable_case_count'] = sum(row['runnable'] for row in cases + controls) + write(output / 'luna-case-status.json', case_status) + write(output / 'SceneManifest.v16.json', manifest) + write(output / 'BenchmarkEpisode.v16.json', episode) + commit = args.rhg_commit or subprocess.check_output(['git','-C',str(Path(__file__).resolve().parents[2]),'rev-parse','HEAD'], text=True).strip() + provenance = dict(rhg_commit=commit, source_run=str(source), + source_sha256={name:sha(source/name) for name in ('SceneManifest.v16.json','BenchmarkEpisode.v16.json', + 'composition_manifest.runtime.json',source.name+'.blend')}, + adapter_sha256=sha(__file__), physical_task_qualified=False) + write(output / 'provenance.json', provenance) + write(output / 'manifest.json', dict(schema='rhg.rparena.v16/1', provenance=provenance, + rooms=manifest['rooms'], portals=manifest['portals'], + support_surfaces=[row for row in manifest['interaction_anchors'] if row['kind']=='place_on_top'], + entity_prim_paths=paths, luna_namespace=namespace, task=episode, doors=doors, physics=physics, + texture_assets=textures, geometry_assets=geometry, + baked_materials=[dict(object=r['object'],source_material=r['source_material'], + usd_material_name=r['usd_material_name'],channels=list(r['maps'])) for r in receipt['materials']] if transfer is not None else [], + material_delivery=baked if transfer is not None else None,native_articulations=native, + source_texture_acceptance=parity if transfer is not None else None, + baking_status='source_side_baked_after_saved_Blender_reference' if transfer is not None else 'legacy_control_unmodified_visual')) + write(output / 'SCENE-DYNAMIC-ACTORS.json', dict( + source_manifest=str((output/'manifest.json').resolve()), + source_sha256=sha(output/'manifest.json'), + body_paths=[door['body'] for door in doors]+native['body_paths'], + physical_parameters_changed=False)) + write(output / 'plan.json', dict(source=dict(units_scale=1.0))) + write(output / 'portability.json', dict(schema='rhg.portability/1', usd_relative_content_paths=True, + runtime_libraries='explicit installed SDK paths and SHA256; no external scene textures or geometry', + storage='包内 assets 使用内容哈希;同文件系统跨包硬链接共享,跨盘复制', + luna_case_paths='case 中保留当前运行绝对路径;迁移安装后需生成独立 case 副本并更新路径,不修改封存包', physical_acceptance='not_run')) + register_authored_luna_scene(output, output) + for folder in sorted([*(output/'controls').glob('*'),*(output/'native').glob('*')]): + register_authored_luna_scene(output, folder) + with timed(records, 'packaging', output): + from pxr import UsdUtils + layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(output / 'root.usda')) + runtime=pinned_runtime_files(output) + external = [str(path) for path in [*(layer.realPath for layer in layers), *assets] + if not Path(path).resolve().is_relative_to(output) and Path(path).resolve() not in runtime] + if unresolved or external: + raise ValueError('包不可迁移:' + str(dict(unresolved=list(unresolved), external=external))) + metadata = dict(format='rparena-static-scene', schema_version='1.0', id=args.scene_id, + bundle_id=output.name, root_usd='root.usda', runtime_files=[], source=provenance, + acceptance=dict(appearance='not_run',physical_task_qualified=False), + rooms=manifest['rooms'], portals=manifest['portals'], entity_prim_paths=paths, + support_surfaces=[row for row in manifest['interaction_anchors'] if row['kind']=='place_on_top']) + metadata['runtime_files'] = sorted([path.relative_to(output).as_posix() for path in output.rglob('*') if path.is_file() + and path.name not in ('timing.json', 'usd-export.log')]+['rparena.scene.json']) + write(output / 'rparena.scene.json', metadata) + files = {path.relative_to(output).as_posix():sha(path) for path in output.rglob('*') if path.is_file() + and path.name not in ('delivery-manifest.json','checksums.sha256','timing.json','usd-export.log')} + write(output / 'delivery-manifest.json',dict(scene_entry='root.usda', files=files, + acceptance_status='not_run', runtime_dependencies=baked['runtime_dependencies'] if transfer is not None else {})) + (output / 'checksums.sha256').write_text(''.join(f'{digest} {name}\n' for name,digest in sorted(files.items()))) + write(output / 'export-result.json', dict(status='exported_unqualified', package=str(output), + case_count=len(cases)+len(controls), native_case_count=len(cases), + runnable_case_count=sum(row['runnable'] for row in cases+controls), + blockers=sorted({reason for row in cases+controls for reason in row['blockers']}), + physical_task_qualified=False)) + for name in ('rparena_installation', 'isaac_loading_acceptance'): + records.append(dict(stage=name, status='not_run', wall_s=None, gpu_s=None, + peak_rss_bytes=None, output_bytes=None)) + write(output / 'timing.json', records) + except Exception as error: + write(output / 'export-result.json', dict(status='failed', error=str(error),traceback=traceback.format_exc())) + raise + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', type=Path) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--scene-id', required=True) + parser.add_argument('--shared-assets', type=Path, required=True) + parser.add_argument('--blender') + parser.add_argument('--delivery-policy',choices=['source','legacy-control'],default='source') + parser.add_argument('--window-scenery',type=Path) + parser.add_argument('--baked-transfer',type=Path) + parser.add_argument('--source-reference',type=Path) + parser.add_argument('--texture-contract',type=Path,help='Frozen source/baked texture ROI and threshold contract') + parser.add_argument('--texture-compression',choices=('auto','preserve','png','bc7'),default='auto',help='auto uses BC7 for budgeted scenes and preserves legacy controls; png is explicit PNG8 fallback; normals stay PNG') + parser.add_argument('--gpu',help='Idle local GPU index/UUID for source rendering and baking; otherwise reserve an idle GPU') + parser.add_argument('--reuse-package',type=Path,help='源场景四项哈希相同且交付文件全量核验后,复用已封存包的视觉资产;新建全部物理层、入口与元数据') + parser.add_argument('--rhg-commit', help='非 Git 部署目录必须传入已核实的源提交;adapter 文件另外计算哈希') + parser.add_argument('--control-template', type=Path, help='保留原生条件后,按已验证 case 的质量和资产创建标准物体对照') + parser.add_argument('--allow-same-support', action='store_true', help='无第二支撑面时,按续跑授权用实际USD顶面筛选同支撑面至少0.5米转移') + parser.add_argument('--seeds', type=int, nargs='+', default=[2026101801,2026101802,2026101803]) + args = parser.parse_args(argv) + export_scene(args) + return 0 diff --git a/docs/reproduction/public_conversion_code/packages/adapters/sam3d.py b/docs/reproduction/public_conversion_code/packages/adapters/sam3d.py new file mode 100644 index 0000000000000000000000000000000000000000..f93a793e3dbcab750bff350ff1adfb0b12e0776d --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/sam3d.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import json +import os +import shutil +import shlex +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Literal + +from packages.adapters.protocols import NotConfiguredError +from packages.core.files import atomic_write_text +from packages.runtime.gpu_scheduler import GpuInfo, parse_nvidia_smi + +DEFAULT_SAM3_CHECKPOINT = Path("/data/wyc/RoboHouseGenData/assets/high_quality/sam3/sam3.pt") +DEFAULT_SAM3D_PIPELINE = Path( + "/data/wyc/RoboHouseGenData/assets/high_quality/sam-3d-objects/checkpoints/pipeline.yaml" +) +Sam3DMemoryStrategy = Literal["single_gpu", "staged_process", "fsdp"] + + +@dataclass(frozen=True, slots=True) +class Sam3DSettings: + command: tuple[str, ...] + sam3_checkpoint: Path = DEFAULT_SAM3_CHECKPOINT + pipeline_config: Path = DEFAULT_SAM3D_PIPELINE + minimum_vram_gb: float = 32.0 + memory_strategy: Sam3DMemoryStrategy = "single_gpu" + stage_gpu_ids: tuple[int, ...] = () + + @classmethod + def from_env(cls) -> Sam3DSettings: + command = tuple(shlex.split(os.environ.get("SAM3D_COMMAND", ""))) + minimum_vram_gb = float(os.environ.get("SAM3D_MIN_VRAM_GB", "32")) + if minimum_vram_gb <= 0: + raise ValueError("SAM3D_MIN_VRAM_GB must be positive") + memory_strategy = os.environ.get("SAM3D_MEMORY_STRATEGY", "single_gpu") + if memory_strategy not in {"single_gpu", "staged_process", "fsdp"}: + raise ValueError("SAM3D_MEMORY_STRATEGY must be single_gpu, staged_process, or fsdp") + stage_gpu_ids = tuple( + int(item) for item in os.environ.get("SAM3D_STAGE_GPU_IDS", "").split(",") if item + ) + return cls( + command=command, + sam3_checkpoint=Path(os.environ.get("SAM3_CHECKPOINT", str(DEFAULT_SAM3_CHECKPOINT))), + pipeline_config=Path( + os.environ.get("SAM3D_PIPELINE_CONFIG", str(DEFAULT_SAM3D_PIPELINE)) + ), + minimum_vram_gb=minimum_vram_gb, + memory_strategy=memory_strategy, # type: ignore[arg-type] + stage_gpu_ids=stage_gpu_ids, + ) + + +def query_gpus() -> list[GpuInfo]: + if os.environ.get("RHG_CPU_ONLY") == "1" or shutil.which("nvidia-smi") is None: + return [] + result = subprocess.run( + [ + "nvidia-smi", + "--query-gpu=index,name,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader,nounits", + ], + check=False, + capture_output=True, + text=True, + ) + if result.returncode: + return [] + return parse_nvidia_smi(result.stdout) + + +def probe_sam3d(settings: Sam3DSettings | None = None) -> dict[str, object]: + settings = settings or Sam3DSettings.from_env() + gpus = query_gpus() + minimum_vram_mb = int(settings.minimum_vram_gb * 1024) + capable_gpus = [gpu.index for gpu in gpus if gpu.memory_total_mb >= minimum_vram_mb] + strategy_supported = settings.memory_strategy != "fsdp" + if settings.memory_strategy == "staged_process": + # Process isolation removes the simultaneous SAM3 + SAM3D residency. The + # reconstruction peak is still determined by the upstream SAM3D pipeline. + capable_gpus = [gpu.index for gpu in gpus if gpu.memory_total_mb >= 23 * 1024] + checkpoints_ready = settings.sam3_checkpoint.is_file() and settings.pipeline_config.is_file() + return { + "configured": bool(settings.command), + "ready": ( + bool(settings.command) + and checkpoints_ready + and bool(capable_gpus) + and strategy_supported + ), + "command_configured": bool(settings.command), + "sam3_checkpoint": str(settings.sam3_checkpoint), + "sam3_checkpoint_ready": settings.sam3_checkpoint.is_file(), + "pipeline_config": str(settings.pipeline_config), + "pipeline_config_ready": settings.pipeline_config.is_file(), + "minimum_vram_gb": settings.minimum_vram_gb, + "memory_strategy": settings.memory_strategy, + "strategy_supported": strategy_supported, + "strategy_note": ( + "FSDP is not supported by the upstream single-process sparse inference pipeline" + if settings.memory_strategy == "fsdp" + else "SAM3 and SAM3D run in isolated processes" + if settings.memory_strategy == "staged_process" + else "upstream single-GPU execution" + ), + "stage_gpu_ids": list(settings.stage_gpu_ids), + "capable_gpu_ids": capable_gpus, + "detected_gpu_vram_gb": [round(gpu.memory_total_mb / 1024, 2) for gpu in gpus], + } + + +class Sam3DAdapter: + """File-protocol adapter for SAM 3D Objects in an isolated CUDA environment.""" + + def __init__(self, settings: Sam3DSettings | None = None) -> None: + self.settings = settings or Sam3DSettings.from_env() + + def generate( + self, + image: Path, + output_dir: Path, + *, + prompt: str | None = None, + mask: Path | None = None, + seed: int = 42, + ) -> Path: + if not image.is_file(): + raise FileNotFoundError(image) + if mask is not None and not mask.is_file(): + raise FileNotFoundError(mask) + status = probe_sam3d(self.settings) + if not self.settings.command: + raise NotConfiguredError("SAM3D_COMMAND is not configured") + if not self.settings.sam3_checkpoint.is_file(): + raise NotConfiguredError(f"SAM3 checkpoint not found: {self.settings.sam3_checkpoint}") + if not self.settings.pipeline_config.is_file(): + raise NotConfiguredError( + f"SAM 3D Objects pipeline config not found: {self.settings.pipeline_config}" + ) + if not status["capable_gpu_ids"]: + raise RuntimeError( + f"SAM3D requires a GPU with at least {self.settings.minimum_vram_gb:g} GB VRAM; " + f"detected {status['detected_gpu_vram_gb']} GB" + ) + if not status["strategy_supported"]: + raise RuntimeError(str(status["strategy_note"])) + + output_dir.mkdir(parents=True, exist_ok=True) + request_path = output_dir / "sam3d_request.json" + manifest_path = output_dir / "sam3d_manifest.json" + request = { + "schema_version": "1.0", + "image": str(image.resolve()), + "mask": str(mask.resolve()) if mask is not None else None, + "prompt": prompt, + "seed": seed, + "sam3_checkpoint": str(self.settings.sam3_checkpoint.resolve()), + "pipeline_config": str(self.settings.pipeline_config.resolve()), + "memory_strategy": self.settings.memory_strategy, + } + atomic_write_text(request_path, json.dumps(request, indent=2, sort_keys=True) + "\n") + stages = ( + ("mask", "reconstruct") + if self.settings.memory_strategy == "staged_process" + else ("full",) + ) + for index, stage in enumerate(stages): + environment = os.environ.copy() + if self.settings.stage_gpu_ids: + environment["CUDA_VISIBLE_DEVICES"] = str( + self.settings.stage_gpu_ids[min(index, len(self.settings.stage_gpu_ids) - 1)] + ) + environment.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") + command = [ + *self.settings.command, + "--request", + str(request_path), + "--output", + str(output_dir), + ] + if self.settings.memory_strategy == "staged_process": + command.extend(("--stage", stage)) + result = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + env=environment, + ) + if result.returncode: + details = (result.stdout + "\n" + result.stderr)[-2000:] + raise RuntimeError( + f"SAM3D {stage} worker failed ({result.returncode}): {details}" + ) + if not manifest_path.is_file(): + raise RuntimeError("SAM3D worker did not produce sam3d_manifest.json") + json.loads(manifest_path.read_text(encoding="utf-8")) + return manifest_path diff --git a/docs/reproduction/public_conversion_code/packages/adapters/scenesmith.py b/docs/reproduction/public_conversion_code/packages/adapters/scenesmith.py new file mode 100644 index 0000000000000000000000000000000000000000..f0501bf23f51b97dff863c72d2e03f7a9b95218a --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/scenesmith.py @@ -0,0 +1,366 @@ +from __future__ import annotations + +import json +import os +import shlex +import shutil +import signal +import subprocess +import threading +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.adapters.protocols import NotConfiguredError +from packages.core.files import atomic_write_text + +SCENESMITH_COMMIT = "67cc408fd38334b4a926efef45e284302ed5055b" +DEFAULT_ASSET_CATALOG = Path( + "/data/wyc/RoboHouseGenData/assets/high_quality/retrieval_catalog.json" +) + + +def _terminate_process_group(process: subprocess.Popen[str], grace_s: float = 10.0) -> None: + if process.poll() is not None: + return + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + return + try: + process.wait(timeout=grace_s) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + + +def _run_isolated(command: list[str], timeout_s: int) -> subprocess.CompletedProcess[str]: + """Run a backend in its own process group and reap it on interruption.""" + + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + start_new_session=True, + ) + previous_handlers: dict[int, Any] = {} + install_handlers = threading.current_thread() is threading.main_thread() + + def interrupt(signum: int, _frame: object) -> None: + if signum == signal.SIGINT: + raise KeyboardInterrupt + raise SystemExit(128 + signum) + + if install_handlers: + for signum in (signal.SIGINT, signal.SIGTERM): + previous_handlers[signum] = signal.signal(signum, interrupt) + try: + stdout, stderr = process.communicate(timeout=timeout_s) + except BaseException: + _terminate_process_group(process) + raise + finally: + for signum, handler in previous_handlers.items(): + signal.signal(signum, handler) + return subprocess.CompletedProcess(command, process.returncode, stdout, stderr) + +RoboLabPredicateType = Literal[ + "place-on-base", + "left-of", + "right-of", + "front-of", + "back-of", + "random-rot", + "facing-left", + "facing-right", + "facing-front", + "facing-back", + "align-left", + "align-right", + "align-front", + "align-back", + "align-center-lr", + "align-center-fb", + "place-on", + "place-in", + "place-anywhere", +] + + +class RoboLabSceneObject(BaseModel): + model_config = ConfigDict(extra="forbid") + name: str = Field(min_length=1) + + +class RoboLabScenePredicate(BaseModel): + """Wire-compatible predicate accepted by RoboLab robolab-scenegen.""" + + model_config = ConfigDict(extra="forbid") + type: RoboLabPredicateType + object: str | None = None + objects: list[str] | None = None + reference: str | None = None + support: str | None = None + container: str | None = None + x: float | None = None + y: float | None = None + yaw: float | None = None + distance: float | None = Field(default=None, gt=0) + support_ratio: float | None = Field(default=None, gt=0, le=1) + stability: Literal["stable", "unstable", "neutral"] | None = None + position: str | None = None + shelf_level: int | None = Field(default=None, ge=0) + + @model_validator(mode="after") + def validate_shape(self) -> RoboLabScenePredicate: + if self.type == "place-in": + if not self.objects or not self.container: + raise ValueError("place-in requires objects and container") + elif not self.object: + raise ValueError(f"{self.type} requires object") + if ( + self.type + in { + "left-of", + "right-of", + "front-of", + "back-of", + "align-left", + "align-right", + "align-front", + "align-back", + "align-center-lr", + "align-center-fb", + } + and not self.reference + ): + raise ValueError(f"{self.type} requires reference") + if self.type == "place-on" and not self.support: + raise ValueError("place-on requires support") + return self + + def referenced_objects(self) -> set[str]: + values = [self.object, self.reference, self.support, self.container, *(self.objects or [])] + return {value for value in values if value} + + def target_objects(self) -> set[str]: + return set(self.objects or []) if self.type == "place-in" else {self.object or ""} + + +class RoboLabSceneRequest(BaseModel): + """Exact top-level RoboLab scene-gen request: objects plus predicates.""" + + model_config = ConfigDict(extra="forbid") + objects: list[RoboLabSceneObject] = Field(min_length=1) + predicates: list[RoboLabScenePredicate] = Field(min_length=1) + + @model_validator(mode="after") + def validate_references(self) -> RoboLabSceneRequest: + names = [item.name for item in self.objects] + if len(names) != len(set(names)): + raise ValueError("scene object names must be unique") + known = set(names) + referenced = set().union(*(item.referenced_objects() for item in self.predicates)) + if unknown := referenced - known: + raise ValueError(f"predicates reference unknown objects: {sorted(unknown)}") + targeted = set().union(*(item.target_objects() for item in self.predicates)) + if missing := known - targeted: + raise ValueError(f"objects have no placement predicate: {sorted(missing)}") + return self + + @classmethod + def model_validate_robolab(cls, value: dict[str, Any]) -> RoboLabSceneRequest: + return cls.model_validate(value) + + +@dataclass(frozen=True, slots=True) +class SceneSmithSettings: + command: tuple[str, ...] + asset_catalog: Path = DEFAULT_ASSET_CATALOG + asset_index: Path | None = None + timeout_s: int = 14_400 + required: bool = False + + @classmethod + def from_env(cls) -> SceneSmithSettings: + command = tuple(shlex.split(os.environ.get("SCENESMITH_COMMAND", ""))) + timeout_s = int(os.environ.get("SCENESMITH_TIMEOUT_S", "14400")) + if timeout_s <= 0: + raise ValueError("SCENESMITH_TIMEOUT_S must be positive") + return cls( + command=command, + asset_catalog=Path( + os.environ.get("SCENESMITH_ASSET_CATALOG", str(DEFAULT_ASSET_CATALOG)) + ), + asset_index=( + Path(os.environ["RHG_ASSET_INDEX"]) if os.environ.get("RHG_ASSET_INDEX") else None + ), + timeout_s=timeout_s, + required=os.environ.get("SCENESMITH_REQUIRED", "0").casefold() in {"1", "true", "yes"}, + ) + + +def probe_scenesmith(settings: SceneSmithSettings | None = None) -> dict[str, object]: + settings = settings or SceneSmithSettings.from_env() + executable = settings.command[0] if settings.command else "" + executable_ready = bool(executable) and ( + Path(executable).is_file() or shutil.which(executable) is not None + ) + runtime_assets: dict[str, bool] = {} + if "--upstream-root" in settings.command: + index = settings.command.index("--upstream-root") + if index + 1 < len(settings.command): + root = Path(settings.command[index + 1]) + runtime_assets = { + "hssd_models": (root / "data" / "hssd-models" / "objects").is_dir(), + "hssd_support_surfaces": ( + root / "data" / "hssd-models" / "support-surfaces" + ).is_dir(), + "hssd_index": ( + root / "data" / "preprocessed" / "hssd_wnsynsetkey_index.json" + ).is_file(), + "hssd_embeddings": ( + root / "data" / "preprocessed" / "clip_hssd_embeddings.npy" + ).is_file(), + "material_embeddings": ( + root / "data" / "materials" / "embeddings" / "clip_embeddings.npy" + ).is_file(), + "material_index": ( + root / "data" / "materials" / "embeddings" / "embedding_index.yaml" + ).is_file(), + "material_metadata": ( + root / "data" / "materials" / "embeddings" / "metadata_index.yaml" + ).is_file(), + } + runtime_ready = all(runtime_assets.values()) if runtime_assets else True + return { + "configured": bool(settings.command), + "ready": executable_ready + and ( + settings.asset_index is not None + and settings.asset_index.is_file() + or settings.asset_catalog.is_file() + ) + and runtime_ready, + "command": list(settings.command), + "command_ready": executable_ready, + "asset_catalog": str(settings.asset_catalog), + "asset_catalog_ready": settings.asset_catalog.is_file(), + "asset_index": str(settings.asset_index) if settings.asset_index else None, + "asset_index_ready": bool(settings.asset_index and settings.asset_index.is_file()), + "runtime_assets": runtime_assets, + "runtime_assets_ready": runtime_ready, + "required": settings.required, + "timeout_s": settings.timeout_s, + "commit": SCENESMITH_COMMIT, + } + + +class SceneSmithAdapter: + """RoboLab scene-gen compatible input adapter for isolated SceneSmith.""" + + def __init__( + self, + command: list[str] | tuple[str, ...] | None = None, + asset_catalog: Path | None = None, + asset_index: Path | None = None, + timeout_s: int | None = None, + ) -> None: + self.asset_catalog: Path | None + if command is None: + settings = SceneSmithSettings.from_env() + self.command = list(settings.command) + self.asset_catalog = asset_catalog or settings.asset_catalog + self.asset_index = asset_index or settings.asset_index + self.timeout_s = timeout_s or settings.timeout_s + else: + self.command = list(command) + self.asset_catalog = asset_catalog + self.asset_index = asset_index + self.timeout_s = timeout_s or 14_400 + + def version(self) -> str: + return SCENESMITH_COMMIT + + def author( + self, + scene: RoboLabSceneRequest, + output_dir: Path, + *, + context: dict[str, Any] | None = None, + ) -> Path: + if not self.command: + raise NotConfiguredError("SceneSmith command is not configured") + fresh_scene = os.environ.get("RHG_FRESH_SCENE", "0").casefold() in { + "1", + "true", + "yes", + } + reuse_from = None if fresh_scene else os.environ.get("RHG_SCENESMITH_REUSE_FROM") + if reuse_from: + source = Path(reuse_from).resolve() + if not source.is_dir(): + raise NotADirectoryError(source) + # A private copy is required because deterministic post-processing + # rewrites USD/state files. Symlinks or hardlinks would mutate the + # accepted parent checkpoint. copytree preserves sparse metadata + # and is local-I/O only (no API/model work). + shutil.copytree(source, output_dir, dirs_exist_ok=True, symlinks=True) + output_dir.mkdir(parents=True, exist_ok=True) + request = output_dir / "scene_request.json" + atomic_write_text(request, scene.model_dump_json(indent=2, exclude_none=True)) + command = [*self.command, "--request", str(request), "--output", str(output_dir)] + if os.environ.get("RHG_COMPOSED_PREVIEW", "0").casefold() in {"1", "true", "yes"}: + # The outer orchestrator renders root.usda after robot composition. + # Rendering the worker-only scene here would be overwritten and + # doubles the 96-frame preview cost. + command.append("--no-preview") + start_stage = os.environ.get("RHG_SCENESMITH_START_STAGE") + resume_from = os.environ.get("RHG_SCENESMITH_RESUME_FROM") + if start_stage: + command.extend(["--start-stage", start_stage]) + if resume_from: + command.extend(["--resume-from", resume_from]) + if not fresh_scene and ( + reuse_from or os.environ.get("RHG_SCENESMITH_REUSE_UPSTREAM", "0").casefold() in { + "1", + "true", + "yes", + } + ): + command.append("--reuse-upstream") + if context is not None: + context_path = output_dir / "scene_context.json" + atomic_write_text(context_path, json.dumps(context, indent=2, sort_keys=True)) + command.extend(["--context", str(context_path)]) + if self.asset_index is not None: + if not self.asset_index.is_file(): + raise FileNotFoundError(self.asset_index) + command.extend(["--asset-index", str(self.asset_index.resolve())]) + elif self.asset_catalog is not None: + if not self.asset_catalog.is_file(): + raise FileNotFoundError(self.asset_catalog) + command.extend(["--asset-catalog", str(self.asset_catalog.resolve())]) + result = _run_isolated(command, self.timeout_s) + if ( + result.returncode != 0 + and "--no-preview" in command + and "unrecognized arguments: --no-preview" in result.stderr + ): + # ``RHG_COMPOSED_PREVIEW`` is an execution optimization, not part of + # the public worker contract. Older/custom workers must remain valid. + command.remove("--no-preview") + result = _run_isolated(command, self.timeout_s) + manifest = output_dir / "stage_manifest.json" + if result.returncode != 0: + raise RuntimeError(f"SceneSmith failed ({result.returncode}): {result.stderr[-2000:]}") + if not manifest.exists(): + raise RuntimeError("SceneSmith did not produce stage_manifest.json") + json.loads(manifest.read_text(encoding="utf-8")) + return manifest diff --git a/docs/reproduction/public_conversion_code/packages/adapters/source_device.py b/docs/reproduction/public_conversion_code/packages/adapters/source_device.py new file mode 100644 index 0000000000000000000000000000000000000000..65fa622ed84a4c82f9fcf3804689abc597b1ad03 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/source_device.py @@ -0,0 +1,31 @@ +"""Reserve one currently idle local GPU for a source Blender conversion.""" +from contextlib import contextmanager +from pathlib import Path +import fcntl,os,subprocess,tempfile + + +@contextmanager +def blender_environment(output,requested=None): + result=subprocess.run(['nvidia-smi','--query-gpu=index,uuid,memory.used','--format=csv,noheader,nounits'],capture_output=True,text=True,timeout=20) + devices=[] + for line in result.stdout.splitlines(): + fields=[v.strip() for v in line.split(',')] + if len(fields)!=3 or not fields[0].isdigit():continue + index,uuid,used=fields + if requested and requested not in (index,uuid):continue + if float(used)<200:devices.append((index,uuid)) + for index,uuid in devices: + lock=open(Path(tempfile.gettempdir())/('rhg-source-'+uuid+'.lock'),'a+') + try: + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError: + lock.close();continue + try: + used=float(subprocess.check_output(['nvidia-smi','-i',uuid,'--query-gpu=memory.used','--format=csv,noheader,nounits'],text=True,timeout=20)) + if used>=200:continue + cache=Path(output)/'source-blender-cache';cache.mkdir(exist_ok=False) + yield dict(os.environ,CUDA_VISIBLE_DEVICES=uuid,OMP_NUM_THREADS='2',OPENBLAS_NUM_THREADS='1',XDG_CACHE_HOME=str(cache)) + return + finally: + lock.close() + raise RuntimeError('No idle local GPU for source Blender rendering/baking; queue on an available worker') diff --git a/docs/reproduction/public_conversion_code/packages/adapters/texture_compression.py b/docs/reproduction/public_conversion_code/packages/adapters/texture_compression.py new file mode 100644 index 0000000000000000000000000000000000000000..36f4cb92ba6971043bd51a6419ce77a0d742d36c --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/texture_compression.py @@ -0,0 +1,203 @@ +"""RHG-side DDS color conversion, before package sealing or installation.""" +import json +from pathlib import Path + + +def _hdr_dimensions(path): + import re + import struct + if path.suffix.lower() == '.hdr': + with path.open('rb') as stream: + header = stream.read(65536) + match = re.search(rb'([+-][XY])\s+(\d+)\s+([+-][XY])\s+(\d+)', header) + if not match: + raise ValueError('Missing Radiance HDR dimensions: ' + str(path)) + axes = {match[1][-1:]: int(match[2]), match[3][-1:]: int(match[4])} + return axes[b'X'], axes[b'Y'] + with path.open('rb') as stream: + if stream.read(4) != b'\x76\x2f\x31\x01': + raise ValueError('Invalid OpenEXR magic: ' + str(path)) + stream.read(4) + def cstring(): + result = bytearray() + while True: + char = stream.read(1) + if not char: + raise ValueError('Truncated OpenEXR header') + if char == b'\0': + return bytes(result) + result.extend(char) + if len(result) > 4096: + raise ValueError('Invalid OpenEXR attribute name') + while True: + name = cstring() + if not name: + break + kind = cstring() + size = struct.unpack(' 16 * 1024**2: + raise ValueError('Oversized OpenEXR header attribute') + value = stream.read(size) + if name == b'dataWindow' and kind == b'box2i' and size == 16: + xmin, ymin, xmax, ymax = struct.unpack('<4i', value) + return xmax - xmin + 1, ymax - ymin + 1 + raise ValueError('Missing OpenEXR data window: ' + str(path)) + + +def _encode_asset(job): + import hashlib + import os + import sys + import PIL + from PIL import Image + from .rparena_v16 import sha, intern + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts/source_transfer')) + source_name, space, policy, package_name, shared_name = job + source, package, shared = map(Path, (source_name, package_name, shared_name)) + with Image.open(source) as header: + width, height = header.size + requested_color = space == 'sRGB' and policy == 'bc7' + # Isaac 6.0.1 rejects BC textures whose base dimensions are not multiples + # of four, even though a general DDS decoder can read the padded blocks. + color = requested_color and width % 4 == 0 and height % 4 == 0 + cache_policy = 'png-unaligned-bc7-fallback' if requested_color and not color else policy + suffix = '.dds' if color else '.png' + source_digest = sha(source) + encoder = Path(__file__).resolve().parents[2] / 'scripts/source_transfer/dds_textures.py' + cache_key = hashlib.sha256(json.dumps(dict(source_sha256=source_digest, space=space, + policy=cache_policy, encoder_sha256=sha(encoder), pillow=PIL.__version__), sort_keys=True).encode()).hexdigest() + index_dir = shared / 'texture-encoding-v1' + index_dir.mkdir(parents=True, exist_ok=True) + index = index_dir / (cache_key + '.json') + if index.exists(): + cached = json.loads(index.read_text()) + payload = shared / cached['filename'] + if not payload.is_file() or sha(payload) != cached['sha256']: + raise ValueError('Encoded texture cache hash mismatch: ' + str(index)) + relative = 'assets/' + cached['filename'] + intern(payload, package / relative, payload) + return relative + temporary = package / ('resident-' + source_digest + '-' + str(os.getpid()) + suffix) + with Image.open(source) as image: + if color: + from dds_textures import encode + temporary.write_bytes(encode(image, 'BC7', True)) + else: + image.save(temporary, format='PNG') + identity = sha(temporary) + relative = 'assets/' + identity + suffix + intern(temporary, package / relative, shared / (identity + suffix)) + temporary.unlink() + pending = index.with_name(index.name + '.' + str(os.getpid()) + '.tmp') + pending.write_text(json.dumps(dict(filename=identity + suffix, sha256=identity, + source_sha256=source_digest), indent=2)) + pending.replace(index) + return relative + + +def compress_colors(stage, package, shared, policy): + from pxr import Sdf, UsdShade + from PIL import Image + from .rparena_v16 import sha, intern + if policy == 'preserve': + return dict(policy=policy, converted=[], normal_format='PNG') + if policy not in ('bc7', 'png'): + raise ValueError('Unknown texture compression policy') + import sys + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts/source_transfer')) + rows = [] + cache = {} + plans = [] + for prim in stage.Traverse(): + if not prim.IsA(UsdShade.Shader): + continue + shader = UsdShade.Shader(prim) + for attribute in prim.GetAttributes(): + if attribute.GetTypeName() != Sdf.ValueTypeNames.Asset: + continue + value = attribute.Get() + if value is None or not value.path.lower().endswith('.png'): + continue + space = attribute.GetColorSpace() + color_space = shader.GetInput('sourceColorSpace') + space = color_space.Get() if color_space else space + # Never compress scalar/normal maps or infer sRGB from a filename. + source = (package / value.path).resolve() + if not source.is_relative_to(package.resolve()): + raise ValueError('Color asset escapes package') + cache_key = (source, space) + if cache_key not in cache: + cache[cache_key] = None + plans.append((attribute, value.path, cache_key, str(prim.GetPath()))) + import concurrent.futures + import multiprocessing + import os + workers = max(1, min(8, int(os.environ.get('RHG_TEXTURE_COMPRESSION_WORKERS', '4')))) + keys = list(cache) + jobs = [(str(source), space, policy, str(package), str(shared)) for source, space in keys] + # Spawn independent CPU encoders; never fork an initialized USD thread pool. + with concurrent.futures.ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context('spawn')) as pool: + for index, (key, relative) in enumerate(zip(keys, pool.map(_encode_asset, jobs))): + cache[key] = relative + if index % 16 == 0: + print(json.dumps(dict(texture_encoding_completed=index+1, total=len(keys), workers=workers)), flush=True) + for attribute, original, cache_key, shader_path in plans: + relative = cache[cache_key] + space = cache_key[1] + attribute.Set(Sdf.AssetPath(relative)) + rows.append(dict(shader=shader_path, input=attribute.GetName(), + original=original, path=relative, format='DDS BC7 sRGB' if relative.endswith('.dds') else 'PNG8', + fallback_reason='Isaac BC7 base dimensions must be multiples of 4' if space == 'sRGB' and policy == 'bc7' and relative.endswith('.png') else None, + mip_chain=relative.endswith('.dds'), sha256=sha(package / relative))) + # Only remove superseded files in this new, unsealed package. The source + # bake and content-addressed shared cache remain immutable. + live = set() + for prim in stage.Traverse(): + for attribute in prim.GetAttributes(): + if attribute.GetTypeName() == Sdf.ValueTypeNames.Asset: + value = attribute.Get() + if value and value.path.startswith('assets/'): + live.add(value.path) + removed = [] + for source in {key[0] for key in cache}: + relative = source.relative_to(package.resolve()).as_posix() + if relative not in live: + source.unlink() + removed.append(relative) + result = dict(policy=policy, encoder_profile='basic', workers=workers, converted=rows, unique_converted_textures=len(cache), + removed_superseded_package_files=removed, + normal_format='PNG', + normal_fallback_reason='BC5 direct sampling failed the frozen 5/255 native USD/RTX probe; no implicit Z reconstruction') + from texture_budget import mip_bytes + ledger = [] + for relative in sorted(live): + path = package / relative + if path.suffix.lower() not in ('.png', '.dds', '.jpg', '.jpeg', '.exr', '.hdr'): + continue + if path.suffix.lower() in ('.exr', '.hdr'): + size = _hdr_dimensions(path) + fmt = 'HDR unchanged; RGBA32F reserve' + resident = 4 * mip_bytes(*size) + else: + image = Image.open(path) + size = image.size + fmt = 'BC7' if path.suffix.lower() == '.dds' else 'PNG' + resident = mip_bytes(*size, fmt) + if min(size) <= 0: + raise ValueError('Invalid delivered texture dimensions: ' + str(path)) + ledger.append(dict(path=relative, resolution=list(size), format=fmt, + estimated_resident_bytes=resident, + file_bytes=path.stat().st_size, sha256=sha(path))) + budget_path = package / 'texture-budget.json' + if budget_path.exists(): + budget = json.loads(budget_path.read_text()) + budget['source_png_estimated_resident_bytes'] = budget['estimated_resident_bytes'] + budget['estimated_resident_bytes'] = sum(r['estimated_resident_bytes'] for r in ledger) + budget['delivered_textures'] = ledger + budget['compression_policy'] = policy + if budget['estimated_resident_bytes'] > budget['budget_bytes']: + raise ValueError('Delivered texture allocation exceeds the configured scene budget') + budget_path.write_text(json.dumps(budget, indent=2)) + result['delivered_estimated_resident_bytes'] = budget['estimated_resident_bytes'] + (package / 'texture-compression.json').write_text(json.dumps(result, indent=2)) + return result diff --git a/docs/reproduction/public_conversion_code/packages/adapters/texture_metrics.py b/docs/reproduction/public_conversion_code/packages/adapters/texture_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f24ccbc28e702abaeb9eaff1d922f652bc9387 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/adapters/texture_metrics.py @@ -0,0 +1,68 @@ +"""Frozen-region texture checks, without registration or exposure fitting.""" +import json +from pathlib import Path +import numpy as np +from PIL import Image + + +CONTRACT = Path(__file__).resolve().parents[2] / 'scripts/source_transfer/texture-fidelity-contract.json' + + +def compare(reference, candidate, view, contract=None): + contract = contract or json.loads(CONTRACT.read_text(encoding='utf-8')) + a, b = [np.asarray(Image.open(p).convert('RGB'), dtype=float) for p in (reference, candidate)] + if a.shape != b.shape or a.shape[:2] != (720, 960): + raise ValueError('Frozen texture regions require matching 960x720 images') + limits = contract['thresholds'] + rows = [] + for label, (x0, y0, x1, y1) in contract['regions'][view].items(): + gradients = [] + for image in (a, b): + lum = image[y0:y1, x0:x1] @ np.array([.2126, .7152, .0722]) + gradients.append(np.stack(((lum[1:-1,2:]-lum[1:-1,:-2])*.5, + (lum[2:,1:-1]-lum[:-2,1:-1])*.5), axis=-1)) + ga, gb = gradients + ea, eb = [float(np.mean(g*g)) for g in gradients] + ratio = eb/ea if ea > 1e-8 else None + cosine = float(np.mean(ga*gb)/np.sqrt(ea*eb)) if ea*eb > 1e-16 else None + passed = (ratio is not None and cosine is not None and + limits['gradient_energy_ratio_min'] <= ratio <= limits['gradient_energy_ratio_max'] and + cosine >= limits['gradient_cosine_min']) + rows.append(dict(region=label, box=[x0,y0,x1,y1], reference_energy=ea, + candidate_energy=eb, gradient_energy_ratio=ratio, + gradient_cosine=cosine, passed=passed, + enough_texture_evidence=ratio is not None and cosine is not None)) + return dict(view=view, mae=float(abs(a-b).mean()), regions=rows, + clarity_passed=bool(rows) and all(r['passed'] for r in rows)) + + +def compare_directories(reference, candidate, output, contract=None): + contract = contract or json.loads(CONTRACT.read_text(encoding='utf-8')) + rows = [compare(Path(reference)/(v+'.png'), Path(candidate)/(v+'.png'), v, contract) + for v in contract['regions']] + result = dict(contract=contract, views=rows, + clarity_passed=all(r['clarity_passed'] for r in rows), + mean_error_passed=all(r['mae'] <= contract['thresholds']['full_image_rgb_mae_max'] for r in rows)) + Path(output).write_text(json.dumps(result, indent=2), encoding='utf-8') + return result + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser(description='Grade complete frozen render regions without image fitting') + parser.add_argument('--reference', type=Path, required=True) + parser.add_argument('--candidate', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--contract', type=Path, default=CONTRACT) + args = parser.parse_args() + if args.output.exists(): + parser.error('Output already exists; retain previous results and choose a new path') + args.output.parent.mkdir(parents=True, exist_ok=True) + result = compare_directories(args.reference, args.candidate, args.output, + json.loads(args.contract.read_text(encoding='utf-8'))) + passed = result['clarity_passed'] and result['mean_error_passed'] + print(json.dumps(dict(passed=passed, views=len(result['views']), + clarity_passed=result['clarity_passed'], + mean_error_passed=result['mean_error_passed']))) + raise SystemExit(0 if passed else 1) diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/__init__.py b/docs/reproduction/public_conversion_code/packages/asset_registry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3e311bf1a379b792b137a017ba70250fc570bf --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/__init__.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from packages.asset_registry.models import RoboLabCatalogEntry + from packages.asset_registry.repository import AssetRegistry + +__all__ = ["AssetRegistry", "RoboLabCatalogEntry"] + + +def __getattr__(name: str) -> Any: + if name == "AssetRegistry": + from packages.asset_registry.repository import AssetRegistry + + return AssetRegistry + if name == "RoboLabCatalogEntry": + from packages.asset_registry.models import RoboLabCatalogEntry + + return RoboLabCatalogEntry + raise AttributeError(name) diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/admission.py b/docs/reproduction/public_conversion_code/packages/asset_registry/admission.py new file mode 100644 index 0000000000000000000000000000000000000000..d00581946f0765f3baf300a1409d0b3e07413dde --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/admission.py @@ -0,0 +1,304 @@ +from __future__ import annotations + +import hashlib +import re +from collections import defaultdict +from pathlib import Path + +from packages.asset_registry.models import ( + AdmissionStatus, + AssetKind, + AssetRecord, +) + +GENERIC_NAMES = {"link 0 0", "material", "mesh", "node", "object", "root"} +OBJECT_SOURCES = { + "ArtVIP", + "HSSD", + "Lightwheel SimReady", + "ReplicaCAD", + "Google Scanned Objects", + "GoogleResearch on Gazebo Fuel", + "YCB", +} +OBJECT_CATEGORIES = { + "book", + "bookcase", + "bottle", + "bowl", + "cabinet", + "chair", + "computer", + "cup", + "desk", + "faucet", + "floor lamp", + "lamp", + "monitor", + "mug", + "oven", + "plant", + "potted plant", + "refrigerator", + "shelf", + "sink", + "sofa", + "table", + "television", + "trash can", +} + + +def normalize_category(value: str) -> str: + tokens = re.findall(r"[a-z0-9]+", value.casefold().replace("_", "-")) + terms = set(tokens) + if "bottle" in terms or any( + token.startswith("bottle") or token.endswith("bottle") for token in tokens + ): + return "bottle" + if "trash" in terms and terms & {"bin", "can", "dustbin"}: + return "trash can" + if "dustbin" in terms: + return "trash can" + if "countertop" in terms or "worktop" in terms: + return "kitchen counter" if "kitchen" in terms or "countertop" in terms else "worktop" + # Catalogs such as ArtVIP and the H20 qualified overlay often expose a + # useful class only in the filename/tags while their upstream category is + # the generic ``articulated object``. Collapse those records to the same + # compact taxonomy used by task specifications. + if "pottedplant" in terms or ("potted" in terms and "plant" in terms): + return "potted plant" + if "floorlamp" in terms or ("floor" in terms and "lamp" in terms): + return "floor lamp" + if terms & {"television", "television003", "tv"}: + return "television" + if terms & {"refrigerator", "fridge", "freezer"}: + return "refrigerator" + if terms & {"faucet", "spigot"} or "tap" in terms: + return "faucet" + if terms & {"oven", "cooktop", "stovetop", "stove", "cooker"}: + return "oven" + if terms & {"sink", "basin"}: + return "sink" + if terms & {"cabinet", "cabinets", "cupboard", "cupboards"}: + return "cabinet" + if "bookcase" in terms or "bookshelf" in terms: + return "bookcase" + if ( + "computer" in terms + or "workstation" in terms + or any(token.startswith("computer") for token in tokens) + ): + return "computer" + if "monitor" in terms or "display" in terms: + return "monitor" + if "books" in terms or "book" in terms or any(token.startswith("book") for token in tokens): + return "book" + if "shelf" in terms or "shelving" in terms: + return "shelf" + if "mug" in terms: + return "mug" + if "cup" in terms: + return "cup" + if "bowl" in terms: + return "bowl" + if "plant" in terms: + return "plant" + if "lamp" in terms: + return "lamp" + if "desk" in terms or any(token.endswith("desk") for token in tokens): + return "desk" + if "chair" in terms or any(token.endswith("chair") for token in tokens): + return "chair" + if "sofa" in terms or "couch" in terms: + return "sofa" + if "table" in terms: + return "table" + return " ".join(tokens) + + +def canonical_category(record: AssetRecord) -> str: + return normalize_category( + " ".join( + [record.display_name, record.category, *record.tags, *record.synonyms] + ) + ) + + +def infer_asset_kind(record: AssetRecord) -> AssetKind: + category = canonical_category(record) + path = Path(record.usd_path) + path_text = path.as_posix().casefold() + source = record.source.casefold() + h20_namespace = source.split("h20 qualified/", 1)[1] if source.startswith("h20 qualified/") else "" + # ArtVIP Interactive_scene stores individual props under an explicit item + # directory. A path such as childrenroom/item/pottedplant is an object; + # substring matching "room" in childrenroom previously misclassified it as + # a complete ROOM and incorrectly bypassed proxy preparation. + artvip_source = record.source == "ArtVIP" or record.source.casefold().endswith("/artvip") + if artvip_source: + parts = [part.casefold() for part in path.parts] + if "/articulated_objects/" in path_text or "/item/" in path_text or "/itm/" in path_text: + return AssetKind.OBJECT + for marker in ("interactive_scene", "scenes"): + if marker in parts and len(parts) - parts.index(marker) >= 4: + return AssetKind.OBJECT + if (record.source == "Lightwheel SimReady" or h20_namespace == "lightwheel") and ( + "/props/" in path_text or category in OBJECT_CATEGORIES + ): + return AssetKind.OBJECT + if h20_namespace in { + "artvip", + "assets_isaac", + "molmospaces_thor", + "roboparty_20260803", + } and category in OBJECT_CATEGORIES: + return AssetKind.OBJECT + if record.source in OBJECT_SOURCES and category in OBJECT_CATEGORIES: + return AssetKind.OBJECT + if record.source.casefold() in {"poly haven", "ambientcg"} and ( + "material" in category or path.suffix.casefold() in {".jpg", ".jpeg", ".png", ".exr"} + ): + return AssetKind.MATERIAL + if "hdri" in category or path.suffix.casefold() in {".hdr", ".exr"}: + return AssetKind.LIGHTING + category_terms = set(category.split()) + if "interior scene" in category or category_terms & {"room", "stage"}: + return AssetKind.ROOM + return record.asset_kind + + +def _path_exists(record: AssetRecord) -> bool: + return bool(record.usd_path) and Path(record.usd_path).exists() + + +def content_hash(record: AssetRecord) -> str: + existing = next((item.md5 for item in record.files if item.md5), None) + if existing: + return f"md5:{existing.casefold()}" + path = Path(record.usd_path) + if path.is_file(): + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return f"sha256:{digest.hexdigest()}" + return "metadata:" + hashlib.sha256( + f"{record.source}\0{record.asset_id}\0{record.usd_path}".encode() + ).hexdigest() + + +def classify(record: AssetRecord, *, check_paths: bool = True) -> AssetRecord: + kind = infer_asset_kind(record) + reasons: list[str] = [] + display = record.display_name.strip().casefold() + path_text = record.usd_path.casefold() + category = canonical_category(record) + + if record.quality_tier == "REJECTED" or record.qa_status == "REJECTED": + return record.model_copy( + update={ + "schema_version": "1.1", + "asset_kind": kind, + "normalized_category": category, + "admission_status": AdmissionStatus.REJECTED, + "exclusion_reasons": ["upstream_rejected"], + "content_hash": content_hash(record), + } + ) + if record.quality_tier == "C": + reasons.append("quality_tier_c") + if check_paths and not _path_exists(record): + reasons.append("missing_runtime_path") + if display in GENERIC_NAMES: + reasons.append("generic_node_name") + if record.source == "MolmoSpaces" and any( + marker in path_text for marker in ("virtual", "placeholder", "package") + ): + reasons.append("molmospaces_virtual_package") + if record.source == "InteriorAgent" and kind == AssetKind.OBJECT: + reasons.append("interioragent_internal_mesh") + if record.source == "ArtVIP" and "/resource/" in path_text: + reasons.append("artvip_internal_resource") + if record.source == "HSSD" and (kind == AssetKind.ROOM or "/stages/" in path_text): + reasons.append("hssd_stage_not_object") + + if kind == AssetKind.OBJECT: + runtime = record.runtime_compatibility + if ( + runtime is None + or not runtime.canonical_usd_path + or not runtime.proxy_gltf_path + or not runtime.proxy_sdf_path + or not Path(runtime.canonical_usd_path).is_file() + or not Path(runtime.proxy_gltf_path).is_file() + or not Path(runtime.proxy_sdf_path).is_file() + ): + reasons.append("proxy_not_prepared") + if kind == AssetKind.OBJECT and record.source not in OBJECT_SOURCES | {"Poly Haven"}: + if record.source == "MolmoSpaces": + reasons.append("source_not_runtime_instantiable") + + status = AdmissionStatus.COLD if reasons else AdmissionStatus.ACTIVE + return record.model_copy( + update={ + "schema_version": "1.1", + "asset_kind": kind, + "normalized_category": category, + "admission_status": status, + "exclusion_reasons": sorted(set(reasons)), + "content_hash": content_hash(record), + # Canonical aliases are recomputed by the following deduplication + # pass; a formerly cold alias can become the prepared canonical. + "canonical_asset_id": None, + } + ) + + +def _canonical_score(record: AssetRecord) -> tuple[int, int, int, int, int, str]: + qa = {"ISAAC_VALIDATED": 3, "CONVERTED": 2, "DOWNLOADED": 1, "REJECTED": 0} + quality = {"A": 3, "B": 2, "C": 1, "REJECTED": 0} + provenance = sum(bool(item.source_url and item.md5) for item in record.files) + runtime = record.runtime_compatibility + compatibility = int(bool(runtime and runtime.canonical_usd_path)) + # Deduplication must never nominate a cold, uninstantiable record when the + # same content already has a fully prepared ACTIVE representation. The + # previous ordering let provenance/quality beat runtime readiness, leaving + # every alias of some H20 assets cold despite a valid proxy being present. + active = int(record.admission_status == AdmissionStatus.ACTIVE) + return ( + active, + qa[record.qa_status], + quality[record.quality_tier], + provenance, + compatibility, + record.asset_id, + ) + + +def classify_and_deduplicate( + records: list[AssetRecord], *, check_paths: bool = True +) -> list[AssetRecord]: + classified = [classify(record, check_paths=check_paths) for record in records] + groups: dict[str, list[int]] = defaultdict(list) + for index, record in enumerate(classified): + assert record.content_hash is not None + groups[record.content_hash].append(index) + for indices in groups.values(): + if len(indices) < 2: + continue + canonical_index = max(indices, key=lambda index: _canonical_score(classified[index])) + canonical_id = classified[canonical_index].asset_id + for index in indices: + if index == canonical_index: + continue + record = classified[index] + reasons = sorted(set([*record.exclusion_reasons, "duplicate_content"])) + classified[index] = record.model_copy( + update={ + "admission_status": AdmissionStatus.COLD, + "exclusion_reasons": reasons, + "canonical_asset_id": canonical_id, + } + ) + return classified diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/articulation.py b/docs/reproduction/public_conversion_code/packages/asset_registry/articulation.py new file mode 100644 index 0000000000000000000000000000000000000000..756d7acd632f0cdbe2b44b96aa21eb0204279ac9 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/articulation.py @@ -0,0 +1,283 @@ +"""Deterministic native-joint inspection and packaging. No model or category inference.""" +from __future__ import annotations + +import hashlib +import json +import math +import shutil +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(block) + return digest.hexdigest() + + +def inspect_native(path: Path) -> dict[str, Any]: + from pxr import Usd, UsdGeom, UsdPhysics + + path = Path(path).resolve() + stage = Usd.Stage.Open(str(path)) + if stage is None: + raise ValueError(f'Cannot open native USD: {path}') + joints, issues = [], [] + for prim in stage.Traverse(): + if not prim.IsA(UsdPhysics.Joint): + continue + joint = UsdPhysics.Joint(prim) + kind = prim.GetTypeName() + body0 = list(map(str, joint.GetBody0Rel().GetTargets())) + body1 = list(map(str, joint.GetBody1Rel().GetTargets())) + row = {'path': str(prim.GetPath()), 'type': kind, 'body0': body0, 'body1': body1, + 'enabled': bool(joint.GetJointEnabledAttr().Get()), + 'local_pos0': list(joint.GetLocalPos0Attr().Get()), + 'local_pos1': list(joint.GetLocalPos1Attr().Get())} + for side in (0, 1): + q = getattr(joint, f'GetLocalRot{side}Attr')().Get() + row[f'local_rot{side}_wxyz'] = [float(q.GetReal()), *map(float, q.GetImaginary())] + if len(body1) != 1 or len(body0) > 1 or any(not stage.GetPrimAtPath(p) for p in body0 + body1): + issues.append('invalid_joint_bodies:' + row['path']) + movable = kind in ('PhysicsRevoluteJoint', 'PhysicsPrismaticJoint') + row['movable'] = movable + if movable: + typed = UsdPhysics.RevoluteJoint(prim) if kind == 'PhysicsRevoluteJoint' else UsdPhysics.PrismaticJoint(prim) + lower, upper = float(typed.GetLowerLimitAttr().Get()), float(typed.GetUpperLimitAttr().Get()) + axis = str(typed.GetAxisAttr().Get()) + row.update(axis=axis, lower=lower if math.isfinite(lower) else None, + upper=upper if math.isfinite(upper) else None, + unit='degrees' if kind == 'PhysicsRevoluteJoint' else 'stage_units') + if not all(map(math.isfinite, (lower, upper))) or lower >= upper or axis not in ('X', 'Y', 'Z'): + issues.append('invalid_joint_limits_or_axis:' + row['path']) + drive_name = 'angular' if kind == 'PhysicsRevoluteJoint' else 'linear' + drive = UsdPhysics.DriveAPI(prim, drive_name) + row['has_native_drive'] = bool(drive) + elif kind != 'PhysicsFixedJoint': + issues.append('unsupported_joint_type:' + row['path']) + joints.append(row) + movable_count = sum(j['movable'] and j['enabled'] for j in joints) + units, up = UsdGeom.GetStageMetersPerUnit(stage), str(UsdGeom.GetStageUpAxis(stage)) + if movable_count and (abs(units - 1.) > 1e-8 or up != 'Z'): + issues.append('requires_offline_metric_z_up_conversion') + if not stage.GetDefaultPrim(): + issues.append('missing_default_prim') + layers = {str(Path(layer.realPath).resolve()): sha256(Path(layer.realPath)) + for layer in stage.GetUsedLayers() if layer.realPath and Path(layer.realPath).is_file()} + return {'schema': 'rhg.native_articulation.v1', 'source_path': str(path), + 'source_sha256': sha256(path), 'source_layer_sha256': layers, + 'default_prim': str(stage.GetDefaultPrim().GetPath()) if stage.GetDefaultPrim() else None, + 'meters_per_unit': units, 'up_axis': up, 'joints': joints, + 'movable_joint_count': movable_count, 'issues': issues, + 'status': 'native_ready_for_physics' if movable_count and not issues else + 'native_requires_review' if movable_count else 'static_no_native_joints', + 'physics_qualified': False, 'llm_calls': 0, 'joint_generation': 'none_preserve_source'} + + +def prepare_native(path: Path, out: Path) -> dict[str, Any]: + """Seal composed USD and local asset dependencies without rewriting joints.""" + from pxr import Sdf, Usd + + path, out = Path(path).resolve(), Path(out).resolve() + if out.is_relative_to(path.parent): + raise ValueError('Native preparation output must be outside the source directory') + inspection = inspect_native(path) + out.mkdir(parents=True, exist_ok=False) + if inspection['status'] != 'native_ready_for_physics': + (out / 'receipt.json').write_text(json.dumps(inspection, indent=2)) + return inspection + # Articulated asset folders carry MDL-local textures as well as USD layers. + # Keep their relative layout; independently renaming MDL files breaks imports. + shutil.copytree(path.parent, out / 'source') + stage = Usd.Stage.Open(str(out / 'source' / path.name)) + flattened = stage.Flatten() + target = out / 'native.usdc' + flattened.Export(str(target)) + packaged = Usd.Stage.Open(str(target)) + dependencies, unresolved = {}, set() + + def copy_asset(value): + if not isinstance(value, Sdf.AssetPath) or not value.path: + return value + original = Path(value.resolvedPath or value.path) + if not original.is_absolute(): + original = path.parent / original + if not original.is_file(): + unresolved.add(value.path) + return value + digest = sha256(original) + if original.is_relative_to(out): + relative = original.relative_to(out) + dependencies[str(relative)] = digest + return Sdf.AssetPath(relative.as_posix()) + relative = Path('resources') / (digest + original.suffix) + destination = out / relative + destination.parent.mkdir(exist_ok=True) + if not destination.exists(): + shutil.copyfile(original, destination) + dependencies[str(relative)] = digest + return Sdf.AssetPath(relative.as_posix()) + + for prim in packaged.Traverse(): + for attr in prim.GetAttributes(): + value = attr.Get() + if isinstance(value, Sdf.AssetPath): + attr.Set(copy_asset(value)) + elif attr.GetTypeName() == Sdf.ValueTypeNames.AssetArray and value: + attr.Set([copy_asset(item) for item in value]) + packaged.GetRootLayer().Save() + dependencies.update({str(p.relative_to(out)): sha256(p) for p in (out / 'source').rglob('*') if p.is_file()}) + saved = inspect_native(target) + if saved['joints'] != inspection['joints']: + raise ValueError('Packaging changed native joint definitions') + inspection.update(runtime_path='native.usdc', runtime_sha256=sha256(target), + resource_sha256=dependencies, unresolved_visual_assets=sorted(unresolved), + joint_definitions_preserved=True, physical_geometry='native_source_colliders') + (out / 'receipt.json').write_text(json.dumps(inspection, indent=2)) + return inspection + + +def resolve_joint_frame(stage, joint, side, cache=None): + """Resolve one frame using OpenUSD 25.11 parseUtils::_GetLocalPose rules. + + Direct schema access avoids the unstable bulk Python physics-parser callback. + Reference: https://github.com/PixarAnimationStudios/OpenUSD/blob/v25.11/pxr/usd/usdPhysics/parseUtils.cpp + """ + from pxr import Gf, UsdGeom, UsdPhysics + cache = cache or UsdGeom.XformCache() + position = Gf.Vec3f(getattr(joint, f'GetLocalPos{side}Attr')().Get()) + rotation = Gf.Quatf(getattr(joint, f'GetLocalRot{side}Attr')().Get()).GetNormalized() + targets = getattr(joint, f'GetBody{side}Rel')().GetTargets() + if not targets: + return None, position, rotation + if len(targets) != 1: + raise ValueError('Ambiguous native joint relationship') + target = stage.GetPrimAtPath(targets[0]) + if not target: + raise ValueError('Missing native joint target: '+str(targets[0])) + actor, collision = target, None + while actor and actor != stage.GetPseudoRoot(): + if actor.HasAPI(UsdPhysics.RigidBodyAPI): + break + if actor.HasAPI(UsdPhysics.CollisionAPI): + collision = actor + actor = actor.GetParent() + if not actor or actor == stage.GetPseudoRoot(): + actor = collision + target_world = cache.GetLocalToWorldTransform(target) + actor_world = cache.GetLocalToWorldTransform(actor) if actor else Gf.Matrix4d(1.) + if target != actor: + local = Gf.Matrix4d(1.) + local.SetRotate(Gf.Quatd(rotation)) + local.SetTranslateOnly(Gf.Vec3d(position)) + relative = (local*target_world*actor_world.GetInverse()).RemoveScaleShear() + position = Gf.Vec3f(relative.ExtractTranslation()) + rotation = Gf.Quatf(relative.ExtractRotationQuat()).GetNormalized() + scale = Gf.Vec3f(Gf.Transform(actor_world if target != actor else target_world).GetScale()) + position = Gf.Vec3f(*(position[i]*scale[i] for i in range(3))) + return str(actor.GetPath()) if actor else None, position, rotation + + +def bind_native(stage, path: Path, prim_path: str, matrix=None, anchor_frame_mode='authored_matrix') -> dict[str, Any]: + """Reference the complete native graph. Rebase world-fixed anchors after placement.""" + from pxr import Gf, UsdGeom + + source = inspect_native(path) + if source['status'] != 'native_ready_for_physics': + raise ValueError('Asset lacks supported native joints: ' + str(path)) + root = UsdGeom.Xform.Define(stage, prim_path) + root.GetPrim().GetReferences().AddReference(str(Path(path).resolve())) + if matrix is not None: + matrix=Gf.Matrix4d(matrix) + basis=[[float(matrix[i][j]) for j in range(3)] for i in range(3)] + if (abs(matrix.GetDeterminant()-1.)>1e-6 or + any(abs(sum(basis[i][k]*basis[j][k] for k in range(3))-(1. if i==j else 0.))>1e-6 + for i in range(3) for j in range(3))): + raise ValueError('Native joints require rigid placement; pre-scale assets offline') + root.AddTransformOp().Set(matrix) + rebased = rebase_world_fixed_joints(stage, root.GetPrim(), anchor_frame_mode) + return {'instance': prim_path, 'source_sha256': source['source_sha256'], + 'movable_joint_count': source['movable_joint_count'], 'rebased_world_fixed_joints': rebased, + 'joint_generation': 'none_preserve_source', 'anchor_frame_mode':anchor_frame_mode, 'llm_calls': 0} + + +def rebase_world_fixed_joints(stage, root_prim, anchor_frame_mode='authored_matrix') -> list[str]: + """Keep native fixed bases at their placed poses, including nonzero local frames.""" + from pxr import Gf, Usd, UsdGeom, UsdPhysics + cache = UsdGeom.XformCache() + if anchor_frame_mode not in {'authored_matrix','rigid_pose'}: + raise ValueError('Unknown native fixed-anchor frame mode') + root_path = root_prim.GetPath() + rebased = [] + for prim in Usd.PrimRange(root_prim): + if not prim.IsA(UsdPhysics.Joint): + continue + joint = UsdPhysics.Joint(prim) + for relationship in (joint.GetBody0Rel(), joint.GetBody1Rel()): + if any(not target.HasPrefix(root_path) for target in relationship.GetTargets()): + raise ValueError('Native joint escaped its instance: ' + str(prim.GetPath())) + if prim.IsA(UsdPhysics.FixedJoint) and not joint.GetBody0Rel().GetTargets(): + body = stage.GetPrimAtPath(joint.GetBody1Rel().GetTargets()[0]) + local = Gf.Matrix4d(1.) + local.SetRotate(Gf.Quatd(joint.GetLocalRot1Attr().Get())) + local.SetTranslateOnly(Gf.Vec3d(joint.GetLocalPos1Attr().Get())) + anchor = local * cache.GetLocalToWorldTransform(body) + joint.GetLocalPos0Attr().Set(Gf.Vec3f(anchor.ExtractTranslation())) + rotation = anchor.ExtractRotationQuat() + if anchor_frame_mode == 'rigid_pose': + world = cache.GetLocalToWorldTransform(body) + basis = [Gf.Vec3d(*(float(world[i][j]) for j in range(3))) for i in range(3)] + is_rigid = (abs(world.GetDeterminant()-1.)<1e-6 and + all(abs(Gf.Dot(basis[i],basis[j])-(1. if i==j else 0.))<1e-6 + for i in range(3) for j in range(3))) + if not is_rigid: + # Points retain scale, while joint rotations use the rigid + # orientation of the relationship target, as USD physics does. + rigid_world = Gf.Matrix4d(1.) + rigid_world.SetRotate(Gf.Transform(world).GetRotation()) + rotation = (local*rigid_world).ExtractRotationQuat().GetNormalized() + joint.GetLocalRot0Attr().Set(Gf.Quatf(rotation)) + rebased.append(str(prim.GetPath())) + return rebased + + +def bind_from_catalog(stage, catalog_path: Path, asset_id: str, prim_path: str, matrix=None): + """Online reuse of a sealed, motion-verified asset; never generate a joint online.""" + catalog_path=Path(catalog_path).resolve() + catalog=json.loads(catalog_path.read_text()) + if catalog.get('schema')!='rhg.native_articulation_acceptance_catalog.v1' or not catalog.get('complete'): + raise ValueError('Incomplete native-articulation catalog') + rows=[r for r in catalog['records'] if r['asset_id']==asset_id] + if len(rows)!=1 or rows[0].get('joint_motion_qualified') is not True: + raise ValueError('Asset has no verified native-joint motion: '+asset_id) + row=rows[0] + def resolve(relative): + path=(catalog_path.parent/relative).resolve() + if not path.is_relative_to(catalog_path.parent): + raise ValueError('Catalog path escapes its bundle') + return path + bundle=resolve(row['bundle']);receipt_path=bundle/'receipt.json' + report_path=resolve(row['report']) + if sha256(receipt_path)!=row['receipt_sha256'] or sha256(report_path)!=row['report_sha256']: + raise ValueError('Native asset receipt changed') + receipt=json.loads(receipt_path.read_text());report=json.loads(report_path.read_text()) + runtime=resolve(str(Path(row['bundle'])/receipt['runtime_path'])) + if (not report.get('passed') or report.get('negative_control') or report.get('diagnostic_only') or + report.get('joint_denominator')!=row['movable_joint_count'] or + report.get('source_sha256')!=row['source_sha256'] or + report.get('runtime_sha256')!=receipt['runtime_sha256'] or + sha256(runtime)!=receipt['runtime_sha256']): + raise ValueError('Native asset motion acceptance mismatch') + if (row.get('validation_protocol',{}).get('source_floor_contact_required') and + not report.get('floor_contact_included')): + raise ValueError('Native source qualification requires measured floor contact') + for name,digest in receipt['resource_sha256'].items(): + dependency=resolve(str(Path(row['bundle'])/name)) + if sha256(dependency)!=digest:raise ValueError('Native asset dependency changed: '+name) + for name,digest in report['evidence_sha256'].items(): + evidence=resolve(str(Path(row['report']).parent/name)) + if sha256(evidence)!=digest:raise ValueError('Native physics evidence changed: '+name) + return bind_native(stage,runtime,prim_path,matrix, + row.get('validation_protocol',{}).get('anchor_frame_mode','authored_matrix')) diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/basisu.py b/docs/reproduction/public_conversion_code/packages/asset_registry/basisu.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c886901112cfd936a9bb868f5e4f87915f0284 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/basisu.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +import json +import shutil +import struct +import subprocess +import tempfile +from pathlib import Path +from typing import Any + + +_GLB_MAGIC = b"glTF" +_JSON_CHUNK = 0x4E4F534A +_BIN_CHUNK = 0x004E4942 +_PNG_MAGIC = b"\x89PNG\r\n\x1a\n" + + +class BasisuNormalizationError(RuntimeError): + pass + + +def _read_glb(path: Path) -> tuple[dict[str, Any], bytes]: + payload = path.read_bytes() + if len(payload) < 20 or payload[:4] != _GLB_MAGIC: + raise BasisuNormalizationError(f"invalid GLB header: {path}") + version, declared_length = struct.unpack_from(" len(payload): + raise BasisuNormalizationError(f"truncated GLB chunk: {path}") + chunk = payload[offset:end] + offset = end + if chunk_type == _JSON_CHUNK: + loaded = json.loads(chunk.rstrip(b" \t\r\n\0").decode("utf-8")) + if not isinstance(loaded, dict): + raise BasisuNormalizationError(f"GLB JSON root is not an object: {path}") + document = loaded + elif chunk_type == _BIN_CHUNK: + binary = chunk + if document is None: + raise BasisuNormalizationError(f"GLB has no JSON chunk: {path}") + return document, binary + + +def _buffer_view_bytes(document: dict[str, Any], binary: bytes, index: int) -> bytes: + views = document.get("bufferViews") + if not isinstance(views, list) or index < 0 or index >= len(views): + raise BasisuNormalizationError(f"invalid BasisU image bufferView index: {index}") + view = views[index] + if not isinstance(view, dict) or int(view.get("buffer", 0)) != 0: + raise BasisuNormalizationError("BasisU image must use GLB buffer 0") + start = int(view.get("byteOffset", 0)) + length = int(view.get("byteLength", 0)) + end = start + length + if start < 0 or length <= 0 or end > len(binary): + raise BasisuNormalizationError(f"invalid BasisU image buffer range: {start}:{end}") + return binary[start:end] + + +def normalize_basisu_glb(source: Path, output_dir: Path, *, ktx_tool: Path) -> Path: + """Create a Blender-compatible glTF while preserving decoded BasisU textures.""" + + source = source.resolve() + if source.suffix.casefold() != ".glb" or b"KHR_texture_basisu" not in source.read_bytes(): + return source + if not ktx_tool.is_file(): + raise BasisuNormalizationError(f"KTX tool is missing: {ktx_tool}") + document, binary = _read_glb(source) + textures = document.get("textures") + images = document.get("images") + if not isinstance(textures, list) or not isinstance(images, list): + raise BasisuNormalizationError(f"BasisU GLB has no texture/image arrays: {source}") + + basisu_sources: set[int] = set() + for texture in textures: + if not isinstance(texture, dict): + continue + extensions = texture.get("extensions") + basisu = extensions.get("KHR_texture_basisu") if isinstance(extensions, dict) else None + if not isinstance(basisu, dict) or "source" not in basisu: + continue + image_index = int(basisu["source"]) + if image_index < 0 or image_index >= len(images): + raise BasisuNormalizationError(f"invalid BasisU texture source index: {image_index}") + basisu_sources.add(image_index) + texture["source"] = image_index + del extensions["KHR_texture_basisu"] + if not extensions: + texture.pop("extensions", None) + if not basisu_sources: + raise BasisuNormalizationError(f"BasisU extension declared without textures: {source}") + + output_dir = output_dir.resolve() + output_dir.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=f".{output_dir.name}-", dir=output_dir.parent) as raw: + staging = Path(raw) + (staging / "buffer.bin").write_bytes(binary) + for image_index in sorted(basisu_sources): + image = images[image_index] + if not isinstance(image, dict) or "bufferView" not in image: + raise BasisuNormalizationError( + f"BasisU image {image_index} is not embedded in a bufferView" + ) + encoded = staging / f"texture_{image_index:03d}.ktx2" + decoded = staging / f"texture_{image_index:03d}.png" + encoded.write_bytes( + _buffer_view_bytes(document, binary, int(image["bufferView"])) + ) + completed = subprocess.run( + [ + str(ktx_tool.resolve()), + "extract", + "--transcode", + "rgba8", + "--testrun", + str(encoded), + str(decoded), + ], + check=False, + capture_output=True, + text=True, + timeout=120, + ) + if completed.returncode or not decoded.is_file(): + raise BasisuNormalizationError( + f"KTX decode failed for image {image_index}: " + f"{(completed.stdout + completed.stderr)[-1000:]}" + ) + if not decoded.read_bytes().startswith(_PNG_MAGIC): + raise BasisuNormalizationError(f"KTX decoder did not produce PNG: {decoded}") + encoded.unlink() + images[image_index] = { + **({"name": image["name"]} if isinstance(image.get("name"), str) else {}), + "uri": decoded.name, + "mimeType": "image/png", + } + + buffers = document.get("buffers") + if not isinstance(buffers, list) or not buffers or not isinstance(buffers[0], dict): + raise BasisuNormalizationError(f"GLB has no buffer declaration: {source}") + buffers[0]["uri"] = "buffer.bin" + buffers[0]["byteLength"] = len(binary) + for key in ("extensionsRequired", "extensionsUsed"): + values = document.get(key) + if isinstance(values, list): + document[key] = [value for value in values if value != "KHR_texture_basisu"] + if not document[key]: + document.pop(key) + (staging / "asset.gltf").write_text( + json.dumps(document, ensure_ascii=False, separators=(",", ":")), + encoding="utf-8", + ) + if output_dir.exists(): + shutil.rmtree(output_dir) + staging.rename(output_dir) + return output_dir / "asset.gltf" diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/certification.py b/docs/reproduction/public_conversion_code/packages/asset_registry/certification.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf0e0df30e0cc524f0687fa67dc2c4281a61cf1 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/certification.py @@ -0,0 +1,382 @@ +from __future__ import annotations + +import hashlib +import json +from collections import Counter, defaultdict +from collections.abc import Iterable +from pathlib import Path +from typing import Any + +from packages.asset_registry.certification_models import ( + AssetCertification, + CertificationCheck, + CertificationProfile, + FidelityScores, + FrontConfidenceGrade, + QualityTier, +) +from packages.asset_registry.descriptors import AssetDescriptor +from packages.asset_registry.front_certification import ( + definition_for_category, + load_descriptor_index, +) +from packages.asset_registry.ingestion import SourceRegistry +from packages.core.files import atomic_write_text + + +def _clamp(value: float) -> float: + return round(max(0.0, min(100.0, value)), 3) + + +def _dependency_fraction(descriptor: AssetDescriptor) -> float: + total = len(descriptor.texture_dependencies) + len(descriptor.missing_dependencies) + if total == 0: + return 1.0 if descriptor.material_count == 0 else 0.5 + return len(descriptor.texture_dependencies) / total + + +def score_fidelity(descriptor: AssetDescriptor) -> FidelityScores: + pbr = descriptor.pbr_channels + pbr_fraction = sum( + (pbr.base_color, pbr.normal, pbr.roughness, pbr.metallic, pbr.occlusion) + ) / 5.0 + dependency_fraction = _dependency_fraction(descriptor) + measured_scale = ( + descriptor.height_m > 0 + and all(value > 0 for value in descriptor.native_bbox_m) + and descriptor.obb_m is not None + ) + scale_confidence = float( + descriptor.confidence.get( + "dimensions", descriptor.confidence.get("scale", 0.75 if measured_scale else 0.0) + ) + ) + collision = { + "explicit": 92.0, + "visual_conservative": 68.0, + "none": 10.0, + }[descriptor.collision_source] + physics = 15.0 + if descriptor.collision_source != "none" and measured_scale: + physics = 68.0 + if any(token in descriptor.affordances for token in ("mass", "inertia", "friction")): + physics += 18.0 + if "stable" in descriptor.affordances or "static_physics" in descriptor.affordances: + physics += 10.0 + articulation = 50.0 if not descriptor.articulated else 20.0 + if descriptor.articulated: + articulation += min(40.0, 8.0 * len(descriptor.movable_parts)) + articulation += min(25.0, 8.0 * len(descriptor.operational_clearance)) + if any("joint" in item for item in descriptor.affordances): + articulation += 15.0 + semantic = 25.0 if descriptor.category.casefold() in {"", "unknown"} else 72.0 + semantic += 15.0 * float(descriptor.confidence.get("semantic", 0.5)) + semantic += min(13.0, 2.0 * len(descriptor.semantic_tags)) + front_confidence = descriptor.front_confidence or float( + descriptor.confidence.get("front_axis", 0.0) + ) + grade_bonus = { + FrontConfidenceGrade.VERIFIED: 10.0, + FrontConfidenceGrade.HIGH: 5.0, + FrontConfidenceGrade.MEDIUM: 0.0, + FrontConfidenceGrade.LOW: -10.0, + FrontConfidenceGrade.UNKNOWN: -25.0, + FrontConfidenceGrade.AMBIGUOUS: -30.0, + }[descriptor.front_confidence_grade] + front = 100.0 * front_confidence + grade_bonus + definition = definition_for_category(descriptor.category) + if definition.functional_semantics == "none" and descriptor.functional_front_axis == "NONE": + front = max(front, 90.0) + task = 25.0 + min(35.0, 7.0 * len(descriptor.affordances)) + task += min(20.0, 10.0 * len(descriptor.operational_clearance)) + if descriptor.support_type in {"floor", "surface"}: + task += 10.0 + if descriptor.collision_source != "none": + task += 10.0 + return FidelityScores( + geometry_fidelity=_clamp(float(descriptor.quality.geometry)), + material_fidelity=_clamp(0.65 * descriptor.quality.materials + 35.0 * pbr_fraction), + texture_fidelity=_clamp(100.0 * dependency_fraction * (0.55 + 0.45 * pbr_fraction)), + scale_fidelity=_clamp(100.0 * scale_confidence), + render_fidelity=_clamp( + 0.75 * descriptor.quality.realism + + 25.0 * min(1.0, len(descriptor.multiview_images) / 4.0) + ), + collision_fidelity=_clamp(collision), + physics_fidelity=_clamp(physics), + articulation_fidelity=_clamp(articulation), + semantic_fidelity=_clamp(semantic), + front_fidelity=_clamp(front), + task_fidelity=_clamp(task), + ) + + +def derive_quality_tier( + descriptor: AssetDescriptor, fidelity: FidelityScores +) -> QualityTier: + if descriptor.status == "QUARANTINED": + return QualityTier.QUARANTINED + visual = min( + fidelity.geometry_fidelity, + fidelity.material_fidelity, + fidelity.texture_fidelity, + fidelity.render_fidelity, + ) + simulation = min( + fidelity.scale_fidelity, + fidelity.collision_fidelity, + fidelity.physics_fidelity, + fidelity.semantic_fidelity, + ) + definition = definition_for_category(descriptor.category) + front_required = definition.functional_semantics not in {"none", "unknown"} + front_ok = not front_required or fidelity.front_fidelity >= 80.0 + articulation_ok = not descriptor.articulated or fidelity.articulation_fidelity >= 80.0 + if visual >= 80.0 and simulation >= 82.0 and front_ok and articulation_ok: + return QualityTier.HQ_A + if visual >= 65.0 and simulation >= 68.0: + return QualityTier.HQ_B + if simulation >= 72.0 and fidelity.task_fidelity >= 65.0: + return QualityTier.SIM_A + if visual >= 65.0: + return QualityTier.VISUAL_ONLY + return QualityTier.PROXY + + +def derive_capability_profiles( + descriptor: AssetDescriptor, fidelity: FidelityScores +) -> set[CertificationProfile]: + output: set[CertificationProfile] = set() + affordances = {item.casefold() for item in descriptor.affordances} + parts = json.dumps(descriptor.movable_parts, ensure_ascii=False).casefold() + if min( + fidelity.scale_fidelity, + fidelity.collision_fidelity, + fidelity.physics_fidelity, + ) >= 70.0: + output.add(CertificationProfile.STATIC_PHYSICS_V1) + if ( + affordances & {"grasp", "grasp_frame", "grasp_frames", "graspable"} + and min(fidelity.collision_fidelity, fidelity.task_fidelity) >= 65.0 + ): + output.add(CertificationProfile.GRASP_V1) + if descriptor.articulated and ("revolute" in parts or "hinge" in parts): + if min(fidelity.articulation_fidelity, fidelity.front_fidelity) >= 65.0: + output.add(CertificationProfile.HINGE_DOOR_V1) + if descriptor.articulated and ("prismatic" in parts or "drawer" in parts): + if fidelity.articulation_fidelity >= 65.0: + output.add(CertificationProfile.DRAWER_V1) + if affordances & {"bimanual", "two_hand_grasp", "paired_grasp_frames"}: + if fidelity.task_fidelity >= 70.0: + output.add(CertificationProfile.BIMANUAL_V1) + if affordances & {"low_pick", "floor_grasp", "low_reach"}: + if fidelity.task_fidelity >= 65.0: + output.add(CertificationProfile.LOW_PICK_V1) + if descriptor.articulated and affordances & {"pedal", "foot_pedal"}: + if fidelity.articulation_fidelity >= 70.0: + output.add(CertificationProfile.FOOT_PEDAL_V1) + return output + + +def certify_quality( + descriptor: AssetDescriptor, + *, + source_version: str | None = None, +) -> AssetCertification: + selected_source_version = source_version or descriptor.source_version + fidelity = score_fidelity(descriptor) + tier = derive_quality_tier(descriptor, fidelity) + profiles = derive_capability_profiles(descriptor, fidelity) + checks = [ + CertificationCheck( + check_id="identity.sha256", + passed=len(descriptor.sha256) == 64, + method="descriptor_validation", + ), + CertificationCheck( + check_id="license.declared", + passed=bool(descriptor.source_license.strip()), + method="source_manifest", + ), + CertificationCheck( + check_id="source.version_declared", + passed=selected_source_version.casefold() not in {"", "unknown", "latest"}, + method="source_manifest", + details=selected_source_version, + ), + CertificationCheck( + check_id="geometry.loadable", + passed=descriptor.status == "ACTIVE" and descriptor.triangle_count > 0, + method="asset_release_v2", + details=descriptor.status_reason, + ), + CertificationCheck( + check_id="dependencies.resolved", + passed=not descriptor.missing_dependencies, + method="dependency_scan", + details="|".join(descriptor.missing_dependencies), + ), + ] + blocking = [] + if descriptor.status == "QUARANTINED": + blocking.append(descriptor.status_reason) + blocking.extend(check.check_id for check in checks if not check.passed) + production = tier in {QualityTier.HQ_A, QualityTier.HQ_B, QualityTier.SIM_A} and not blocking + return AssetCertification( + asset_id=descriptor.asset_id, + asset_sha256=descriptor.sha256, + source=descriptor.source, + source_version=selected_source_version, + source_license=descriptor.source_license, + quality_tier=tier, + fidelity=fidelity, + capability_profiles=profiles, + checks=checks, + certifier="robothousegen-automated-policy", + policy_version="asset-certification-v1-heuristic", + production_eligible=production, + blocking_reasons=blocking, + ) + + +def role_coverage_report( + descriptors: Iterable[AssetDescriptor], + certifications: dict[str, AssetCertification], +) -> dict[str, Any]: + roles: dict[str, dict[str, Counter[str]]] = defaultdict( + lambda: {"quality_tiers": Counter(), "capability_profiles": Counter(), "sources": Counter()} + ) + for descriptor in descriptors: + certification = certifications[descriptor.asset_id] + if not certification.production_eligible: + continue + role = descriptor.category.casefold().strip() or "unknown" + roles[role]["quality_tiers"][certification.quality_tier.value] += 1 + roles[role]["sources"][descriptor.source] += 1 + for profile in certification.capability_profiles: + roles[role]["capability_profiles"][profile.value] += 1 + return { + "schema_version": "1.0", + "truth_policy": "counts include production_eligible certifications only", + "roles": { + role: {name: dict(sorted(counter.items())) for name, counter in values.items()} + for role, values in sorted(roles.items()) + }, + } + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def batch_certify_quality( + *, + source_index: Path, + output_dir: Path, + source_version: str | None = None, + source_versions: dict[str, str] | None = None, + active_only: bool = False, + limit: int | None = None, +) -> dict[str, Any]: + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite quality certification output: {output_dir}") + descriptors = load_descriptor_index(source_index, active_only=active_only) + if limit is not None: + descriptors = descriptors[:limit] + normalized_versions = { + key.casefold(): value for key, value in (source_versions or {}).items() + } + certifications = { + item.asset_id: certify_quality( + item, + source_version=( + source_version + or normalized_versions.get(item.source.casefold()) + or item.source_version + ), + ) + for item in descriptors + } + output_dir.mkdir(parents=True, exist_ok=False) + certification_jsonl = output_dir / "asset_certifications.jsonl" + descriptor_jsonl = output_dir / "asset_descriptors.certified.jsonl" + coverage_path = output_dir / "asset_role_coverage.json" + atomic_write_text( + certification_jsonl, + "".join(certifications[key].model_dump_json() + "\n" for key in sorted(certifications)), + ) + atomic_write_text( + descriptor_jsonl, + "".join( + AssetDescriptor.model_validate( + { + **descriptor.model_dump(mode="python"), + "schema_version": "2.1", + "source_version": certifications[descriptor.asset_id].source_version, + "certification": certifications[descriptor.asset_id], + } + ).model_dump_json() + + "\n" + for descriptor in descriptors + ), + ) + coverage = role_coverage_report(descriptors, certifications) + atomic_write_text( + coverage_path, json.dumps(coverage, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + ) + report: dict[str, Any] = { + "schema_version": "1.0", + "source_index": str(source_index.resolve()), + "source_index_sha256": _sha256(source_index), + "source_index_preserved": True, + "processed": len(descriptors), + "quality_tiers": dict( + sorted(Counter(item.quality_tier.value for item in certifications.values()).items()) + ), + "capability_profiles": dict( + sorted( + Counter( + profile.value + for item in certifications.values() + for profile in item.capability_profiles + ).items() + ) + ), + "production_eligible": sum(item.production_eligible for item in certifications.values()), + "unknown_source_versions": dict( + sorted( + Counter( + descriptor.source + for descriptor in descriptors + if certifications[descriptor.asset_id].source_version.casefold() + in {"", "unknown", "latest"} + ).items() + ) + ), + "files": {}, + } + for path in (certification_jsonl, descriptor_jsonl, coverage_path): + report["files"][path.name] = {"path": str(path), "sha256": _sha256(path)} + atomic_write_text( + output_dir / "quality_certification_report.json", + json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + return report + + +def source_versions_from_registry(path: Path) -> dict[str, str]: + registry = SourceRegistry.from_yaml(path) + output: dict[str, str] = {} + for source in registry.sources: + aliases = {source.source_id, source.display_name, *source.descriptor_source_aliases} + for alias in aliases: + key = alias.casefold() + previous = output.get(key) + if previous is not None and previous != source.version: + raise ValueError(f"source alias has conflicting versions: {alias}") + output[key] = source.version + return output diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/certification_models.py b/docs/reproduction/public_conversion_code/packages/asset_registry/certification_models.py new file mode 100644 index 0000000000000000000000000000000000000000..17367e7d6a4590712fd558cd822025e901453325 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/certification_models.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from enum import StrEnum +from typing import Annotated, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_serializer, model_validator + +Score100 = Annotated[float, Field(ge=0.0, le=100.0)] +CardinalAxis = Literal["+X", "-X", "+Y", "-Y"] +FrontAxis = Literal["+X", "-X", "+Y", "-Y", "NONE", "AMBIGUOUS"] + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class FrontConfidenceGrade(StrEnum): + VERIFIED = "VERIFIED" + HIGH = "HIGH" + MEDIUM = "MEDIUM" + LOW = "LOW" + UNKNOWN = "UNKNOWN" + AMBIGUOUS = "AMBIGUOUS" + + +class FrontMethod(StrEnum): + HUMAN_REVIEW = "human_review" + MULTIVIEW_CONSENSUS = "multiview_consensus" + AFFORDANCE_CONSENSUS = "affordance_consensus" + DATASET_AND_GEOMETRY = "dataset_and_geometry" + DATASET_CONVENTION = "dataset_convention" + GEOMETRY_HEURISTIC = "geometry_heuristic" + SYMMETRY = "symmetry" + UNKNOWN = "unknown" + + +class SymmetryType(StrEnum): + NONE = "NONE" + ROTATIONAL = "ROTATIONAL" + MIRROR = "MIRROR" + ROTATIONAL_AND_MIRROR = "ROTATIONAL_AND_MIRROR" + UNKNOWN = "UNKNOWN" + + +class FrontReviewStatus(StrEnum): + UNREVIEWED = "UNREVIEWED" + AUTO_REVIEWED = "AUTO_REVIEWED" + NEEDS_REVIEW = "NEEDS_REVIEW" + HUMAN_VERIFIED = "HUMAN_VERIFIED" + REJECTED = "REJECTED" + + +class QualityTier(StrEnum): + HQ_A = "HQ-A" + HQ_B = "HQ-B" + SIM_A = "SIM-A" + VISUAL_ONLY = "VISUAL-ONLY" + PROXY = "PROXY" + QUARANTINED = "QUARANTINED" + + +class CertificationProfile(StrEnum): + STATIC_PHYSICS_V1 = "static_physics_v1" + GRASP_V1 = "grasp_v1" + HINGE_DOOR_V1 = "hinge_door_v1" + DRAWER_V1 = "drawer_v1" + BIMANUAL_V1 = "bimanual_v1" + LOW_PICK_V1 = "low_pick_v1" + FOOT_PEDAL_V1 = "foot_pedal_v1" + + +class FrontEvidence(_StrictModel): + """One immutable observation used to infer visual or functional front.""" + + evidence_id: str = Field(min_length=1) + kind: Literal[ + "source_metadata", + "dataset_convention", + "geometry", + "multiview", + "vlm_vote", + "embedding_vote", + "articulation", + "handle", + "affordance", + "wall_clearance", + "human_review", + "symmetry", + ] + target: Literal["visual_front", "functional_front", "back_axis", "symmetry"] + axis: FrontAxis + confidence: float = Field(ge=0.0, le=1.0) + source_uri: str | None = None + source_hash: str | None = None + reviewed_by: str | None = None + reviewed_at: datetime | None = None + note: str = "" + + @model_validator(mode="after") + def validate_human_provenance(self) -> FrontEvidence: + if self.kind == "human_review" and ( + not self.reviewed_by or self.reviewed_at is None + ): + raise ValueError("human_review evidence requires reviewed_by and reviewed_at") + return self + + +class FidelityScores(_StrictModel): + """Independent quality axes; no single total score is a certification.""" + + geometry_fidelity: Score100 + material_fidelity: Score100 + texture_fidelity: Score100 + scale_fidelity: Score100 + render_fidelity: Score100 + collision_fidelity: Score100 + physics_fidelity: Score100 + articulation_fidelity: Score100 + semantic_fidelity: Score100 + front_fidelity: Score100 + task_fidelity: Score100 + + @property + def mean(self) -> float: + values = [ + self.geometry_fidelity, + self.material_fidelity, + self.texture_fidelity, + self.scale_fidelity, + self.render_fidelity, + self.collision_fidelity, + self.physics_fidelity, + self.articulation_fidelity, + self.semantic_fidelity, + self.front_fidelity, + self.task_fidelity, + ] + return sum(values) / len(values) + + +class CertificationCheck(_StrictModel): + check_id: str = Field(pattern=r"^[a-z][a-z0-9_.-]*$") + passed: bool + method: str + evidence_uri: str | None = None + details: str = "" + + +class AssetCertification(_StrictModel): + """Hash-bound release decision for one immutable asset payload.""" + + schema_version: Literal["1.0"] = "1.0" + asset_id: str = Field(min_length=1) + asset_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + source: str = Field(min_length=1) + source_version: str = Field(min_length=1) + source_license: str = Field(min_length=1) + quality_tier: QualityTier + fidelity: FidelityScores + capability_profiles: set[CertificationProfile] = Field(default_factory=set) + checks: list[CertificationCheck] = Field(default_factory=list) + certified_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) + certifier: str = "robothousegen" + policy_version: str = "asset-certification-v1" + production_eligible: bool = False + blocking_reasons: list[str] = Field(default_factory=list) + + @field_serializer("capability_profiles") + def serialize_profiles(self, value: set[CertificationProfile]) -> list[str]: + return sorted(item.value for item in value) + + @model_validator(mode="after") + def validate_release_decision(self) -> AssetCertification: + failed = [check.check_id for check in self.checks if not check.passed] + if self.quality_tier == QualityTier.QUARANTINED: + if self.production_eligible: + raise ValueError("QUARANTINED assets cannot be production eligible") + if not self.blocking_reasons: + raise ValueError("QUARANTINED certification requires blocking_reasons") + if self.production_eligible and (failed or self.blocking_reasons): + raise ValueError("production eligible certification cannot contain failed checks") + return self diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/context_usd.py b/docs/reproduction/public_conversion_code/packages/asset_registry/context_usd.py new file mode 100644 index 0000000000000000000000000000000000000000..9204eb0d8275ad943be6f48a9a32b062a3f9f585 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/context_usd.py @@ -0,0 +1,378 @@ +from __future__ import annotations + +import json +import math +import sqlite3 +from pathlib import Path +from typing import Any + +from packages.asset_registry.models import AdmissionStatus, AssetRecord + + +def load_indexed_native_asset( + index_path: Path, + asset_id: str, + *, + allow_cold_native_usd: bool = False, +) -> AssetRecord: + uri = f"file:{index_path.resolve()}?mode=ro&immutable=1" + with sqlite3.connect(uri, uri=True) as connection: + row = connection.execute( + "SELECT record_json FROM assets WHERE asset_id = ?", + (asset_id,), + ).fetchone() + if row is None: + raise ValueError(f"context asset is absent from the prepared index: {asset_id}") + record = AssetRecord.model_validate_json(row[0]) + # Exact inputs may legitimately use a stable alias that deduplication + # placed in the cold index. Resolve only an explicit duplicate link, + # and only to an ACTIVE canonical record; all other cold reasons remain + # fail-closed. + if ( + record.admission_status == AdmissionStatus.COLD + and "duplicate_content" in record.exclusion_reasons + and record.canonical_asset_id + ): + canonical_row = connection.execute( + "SELECT record_json FROM assets WHERE asset_id = ?", + (record.canonical_asset_id,), + ).fetchone() + if canonical_row is not None: + canonical_record = AssetRecord.model_validate_json(canonical_row[0]) + if canonical_record.admission_status == AdmissionStatus.ACTIVE: + record = canonical_record + cold_native_only = ( + allow_cold_native_usd + and record.admission_status == AdmissionStatus.COLD + and set(record.exclusion_reasons) == {"proxy_not_prepared"} + ) + if record.admission_status != AdmissionStatus.ACTIVE and not cold_native_only: + raise ValueError( + f"context asset is not admitted for native USD binding: {asset_id} " + f"({record.admission_status}, {record.exclusion_reasons})" + ) + runtime = record.runtime_compatibility + canonical = Path(runtime.canonical_usd_path) if runtime and runtime.canonical_usd_path else None + if canonical is None or not canonical.is_file(): + raise FileNotFoundError(f"context asset has no loadable canonical USD: {asset_id}") + return record + + +def apply_task_asset_overrides( + selections: dict[str, list[dict[str, Any]]], + config: dict[str, Any], + index_path: Path, +) -> tuple[dict[str, list[dict[str, Any]]], dict[str, str]]: + """Replace retrieved first choices without mutating the retrieval provenance.""" + overrides = config.get("task_asset_overrides", {}) + if not isinstance(overrides, dict) or any( + not isinstance(entity_id, str) or not isinstance(asset_id, str) + for entity_id, asset_id in overrides.items() + ): + raise ValueError("task_asset_overrides must map entity IDs to asset IDs") + unknown = set(overrides) - set(selections) + if unknown: + raise ValueError(f"task asset overrides reference unknown entities: {sorted(unknown)}") + effective = json.loads(json.dumps(selections)) + applied: dict[str, str] = {} + for entity_id, asset_id in overrides.items(): + record = load_indexed_native_asset(index_path, asset_id) + replacement = record.model_dump(mode="json") + replacement["retrieval_override"] = True + replacement["requested_asset_id"] = asset_id + replacement["resolved_canonical_asset_id"] = record.asset_id + replacement["retrieval_override_reason"] = "declarative_task_asset_override" + effective[entity_id] = [replacement, *[ + candidate + for candidate in effective[entity_id] + if candidate.get("asset_id") != asset_id + ]] + applied[entity_id] = record.asset_id + return effective, applied + + +def _room_records(value: Any) -> list[tuple[dict[str, Any], dict[str, Any]]]: + rooms: list[tuple[dict[str, Any], dict[str, Any]]] = [] + if isinstance(value, dict): + objects = value.get("objects") + geometry = value.get("room_geometry") + if isinstance(objects, dict) and isinstance(geometry, dict): + rooms.extend( + (record, geometry) + for record in objects.values() + if isinstance(record, dict) + ) + else: + for nested in value.values(): + rooms.extend(_room_records(nested)) + elif isinstance(value, list): + for nested in value: + rooms.extend(_room_records(nested)) + return rooms + + +def _vector3(value: Any, label: str) -> tuple[float, float, float]: + if not isinstance(value, list) or len(value) != 3: + raise ValueError(f"{label} must contain three numbers") + return tuple(float(item) for item in value) + + +def _rotate_vector( + quaternion: tuple[float, float, float, float], + vector: tuple[float, float, float], +) -> tuple[float, float, float]: + w, x, y, z = quaternion + norm = math.sqrt(w * w + x * x + y * y + z * z) + if norm <= 1e-12: + raise ValueError("support entity rotation quaternion has zero length") + w, x, y, z = (item / norm for item in quaternion) + vx, vy, vz = vector + tx = 2 * (y * vz - z * vy) + ty = 2 * (z * vx - x * vz) + tz = 2 * (x * vy - y * vx) + return ( + vx + w * tx + (y * tz - z * ty), + vy + w * ty + (z * tx - x * tz), + vz + w * tz + (x * ty - y * tx), + ) + + +def plan_task_support_translations( + house_state: dict[str, Any], + bindings: dict[str, str], + config: dict[str, Any], +) -> dict[str, tuple[float, float, float]]: + """Place task entities on the corrected top of canonical support assets.""" + + specs = config.get("task_support_placements") or {} + if not isinstance(specs, dict): + raise ValueError("task_support_placements must be an object") + records = { + str(record["object_id"]): record + for record, _geometry in _room_records(house_state) + if isinstance(record.get("object_id"), str) + } + scale_overrides = config.get("canonical_scale_overrides") or {} + planned: dict[str, tuple[float, float, float]] = {} + for entity_id, spec in specs.items(): + if not isinstance(entity_id, str) or not isinstance(spec, dict): + raise ValueError("each task support placement must be an object") + support_entity = str(spec.get("support_entity_id") or "") + if support_entity not in bindings: + raise ValueError( + f"task support placement references an unbound entity: " + f"{entity_id} -> {support_entity}" + ) + support_id = bindings[support_entity] + if support_id.startswith("external:"): + raise ValueError("task support placement cannot use external entity bindings") + support = records.get(support_id) + if support is None: + raise ValueError(f"support object is absent from house state: {support_id}") + bbox_min = _vector3(support.get("bbox_min"), f"{support_id}.bbox_min") + bbox_max = _vector3(support.get("bbox_max"), f"{support_id}.bbox_max") + transform = support.get("transform") or {} + origin = _vector3(transform.get("translation"), f"{support_id}.translation") + rotation_value = transform.get("rotation_wxyz") + if not isinstance(rotation_value, list) or len(rotation_value) != 4: + raise ValueError(f"support object has invalid rotation: {support_id}") + rotation = tuple(float(item) for item in rotation_value) + xy_fraction = spec.get("local_xy_fraction", [0.0, 0.0]) + if not isinstance(xy_fraction, list) or len(xy_fraction) != 2: + raise ValueError("local_xy_fraction must contain two values") + fx, fy = (float(item) for item in xy_fraction) + if abs(fx) > 1 or abs(fy) > 1: + raise ValueError("local_xy_fraction values must be within [-1, 1]") + support_scale = scale_overrides.get(support_entity, [1.0, 1.0, 1.0]) + scale = _vector3(support_scale, f"{support_entity}.canonical scale") + local = ( + ((bbox_min[0] + bbox_max[0]) / 2 + fx * (bbox_max[0] - bbox_min[0]) / 2) + * scale[0], + ((bbox_min[1] + bbox_max[1]) / 2 + fy * (bbox_max[1] - bbox_min[1]) / 2) + * scale[1], + bbox_max[2] * scale[2] + float(spec.get("clearance_m", 0.003)), + ) + rotated = _rotate_vector(rotation, local) + planned[entity_id] = tuple(origin[index] + rotated[index] for index in range(3)) + return planned + + +def plan_context_placements( + house_state: dict[str, Any], + config: dict[str, Any], +) -> list[dict[str, Any]]: + if config.get("schema_version") != "1.0": + raise ValueError("context asset config schema_version must be 1.0") + groups = config.get("groups") + if not isinstance(groups, list): + raise ValueError("context asset config groups must be a list") + if not groups: + return [] + room_records = _room_records(house_state) + by_id = { + str(record["object_id"]): (record, geometry) + for record, geometry in room_records + if isinstance(record.get("object_id"), str) + } + placements: list[dict[str, Any]] = [] + seen_group_ids: set[str] = set() + for group in groups: + if not isinstance(group, dict): + raise ValueError("context asset group must be an object") + group_id = str(group.get("group_id") or "") + asset_id = str(group.get("asset_id") or "") + parents = group.get("parent_object_ids") + if not group_id or group_id in seen_group_ids: + raise ValueError(f"context asset group_id must be non-empty and unique: {group_id!r}") + seen_group_ids.add(group_id) + if not asset_id: + raise ValueError(f"context asset group {group_id} has no asset_id") + if ( + not isinstance(parents, list) + or not parents + or any(not isinstance(item, str) for item in parents) + ): + raise ValueError(f"context asset group {group_id} requires parent_object_ids") + skip_lowest = int(group.get("skip_lowest_surfaces", 0)) + maximum = int(group.get("max_surfaces_per_parent", 1)) + if skip_lowest < 0 or maximum <= 0: + raise ValueError("surface selection counts must be non-negative/positive") + scale_value = group.get("scale", 1.0) + scale = ( + (float(scale_value),) * 3 + if isinstance(scale_value, (int, float)) + else _vector3(scale_value, f"{group_id}.scale") + ) + if any(item <= 0 for item in scale): + raise ValueError(f"context asset group {group_id} scale must be positive") + for parent_id in parents: + if parent_id not in by_id: + raise ValueError(f"context asset parent is absent from house state: {parent_id}") + parent, geometry = by_id[parent_id] + surfaces = parent.get("support_surfaces") or [] + if not isinstance(surfaces, list): + raise ValueError(f"context asset parent has invalid support_surfaces: {parent_id}") + ranked = sorted( + (surface for surface in surfaces if isinstance(surface, dict)), + key=lambda surface: _vector3( + (surface.get("transform") or {}).get("translation"), + f"{parent_id} support translation", + )[2], + ) + selected = ranked[skip_lowest : skip_lowest + maximum] + if len(selected) < maximum: + raise ValueError( + f"context asset parent {parent_id} exposes only " + f"{len(selected)} selected surfaces" + ) + room_offset = ( + float(geometry.get("length", 0.0)) / 2, + float(geometry.get("width", 0.0)) / 2, + 0.0, + ) + for surface in selected: + transform = surface.get("transform") or {} + translation = _vector3(transform.get("translation"), "support translation") + rotation = transform.get("rotation_wxyz") + if not isinstance(rotation, list) or len(rotation) != 4: + raise ValueError( + "support surface has no quaternion: " + f"{surface.get('surface_id')}" + ) + placements.append( + { + "instance_id": f"{group_id}_{parent_id}_{surface['surface_id']}", + "group_id": group_id, + "asset_id": asset_id, + "parent_object_id": parent_id, + "surface_id": str(surface["surface_id"]), + "translation": [ + translation[index] + room_offset[index] for index in range(3) + ], + "rotation_wxyz": [float(item) for item in rotation], + "scale": list(scale), + } + ) + return placements + + +def bind_context_usd_assets( + root_usd: Path, + house_state: dict[str, Any], + config: dict[str, Any], + index_path: Path, +) -> dict[str, dict[str, str]]: + try: + from pxr import Gf, Sdf, Tf, Usd, UsdGeom # type: ignore[import-not-found] + except ImportError as error: + raise RuntimeError("pxr is required to bind context USD assets") from error + stage = Usd.Stage.Open(str(root_usd)) + if stage is None: + raise RuntimeError(f"could not open exported USD: {root_usd}") + placements = plan_context_placements(house_state, config) + allow_cold_native_usd = config.get("allow_cold_native_usd", False) + if not isinstance(allow_cold_native_usd, bool): + raise ValueError("allow_cold_native_usd must be a boolean") + records = { + asset_id: load_indexed_native_asset( + index_path, + asset_id, + allow_cold_native_usd=allow_cold_native_usd, + ) + for asset_id in {item["asset_id"] for item in placements} + } + root = stage.DefinePrim("/World/SceneSmith/NativeContextAssets", "Xform") + root.SetCustomDataByKey("robothousegen:generated_from", "support_surfaces") + bindings: dict[str, dict[str, str]] = {} + for placement in placements: + record = records[placement["asset_id"]] + runtime = record.runtime_compatibility + assert runtime is not None and runtime.canonical_usd_path is not None + canonical = Path(runtime.canonical_usd_path).resolve() + instance_name = Tf.MakeValidIdentifier(placement["instance_id"]) + instance_path = Sdf.Path("/World/SceneSmith/NativeContextAssets").AppendChild(instance_name) + instance = stage.DefinePrim(instance_path, "Xform") + xform = UsdGeom.Xformable(instance) + xform.AddTranslateOp(UsdGeom.XformOp.PrecisionDouble).Set( + Gf.Vec3d(*placement["translation"]) + ) + rotation = placement["rotation_wxyz"] + xform.AddOrientOp(UsdGeom.XformOp.PrecisionDouble).Set( + Gf.Quatd(rotation[0], Gf.Vec3d(*rotation[1:])) + ) + xform.AddScaleOp(UsdGeom.XformOp.PrecisionDouble).Set(Gf.Vec3d(*placement["scale"])) + asset_path = instance_path.AppendChild("CanonicalAsset") + asset_prim = stage.DefinePrim(asset_path, "Xform") + asset_prim.GetReferences().AddReference(str(canonical)) + geometry = record.geometry_metadata + if geometry and geometry.bbox_min_m and geometry.bbox_max_m: + minimum = geometry.bbox_min_m + maximum = geometry.bbox_max_m + local_offset = Gf.Vec3d( + -(minimum[0] + maximum[0]) / 2, + -(minimum[1] + maximum[1]) / 2, + -minimum[2], + ) + UsdGeom.Xformable(asset_prim).AddTranslateOp( + UsdGeom.XformOp.PrecisionDouble + ).Set(local_offset) + for prim in (instance, asset_prim): + prim.SetCustomDataByKey("robothousegen:asset_id", record.asset_id) + prim.SetCustomDataByKey("robothousegen:source", record.source) + key = f"context:{placement['instance_id']}" + bindings[key] = { + "asset_id": record.asset_id, + "canonical_usd": str(canonical), + "prim_path": str(asset_path), + "parent_object_id": placement["parent_object_id"], + "surface_id": placement["surface_id"], + } + stage.GetRootLayer().Save() + return bindings + + +def load_context_config(path: Path) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(value, dict): + raise ValueError(f"context asset config must be a JSON object: {path}") + return value diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/descriptors.py b/docs/reproduction/public_conversion_code/packages/asset_registry/descriptors.py new file mode 100644 index 0000000000000000000000000000000000000000..916ec37b12c39fddc14f66eac15cdb7c762edba3 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/descriptors.py @@ -0,0 +1,267 @@ +from __future__ import annotations + +import math +import re +from datetime import datetime +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from shapely.geometry import Polygon # type: ignore[import-untyped] + +from packages.asset_registry.certification_models import ( + AssetCertification, + FrontAxis, + FrontConfidenceGrade, + FrontEvidence, + FrontMethod, + FrontReviewStatus, + SymmetryType, +) + +Point2 = tuple[float, float] +Point3 = tuple[float, float, float] + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class PbrChannels(_StrictModel): + base_color: bool = False + normal: bool = False + roughness: bool = False + metallic: bool = False + occlusion: bool = False + emissive: bool = False + + +class AssetQuality(_StrictModel): + geometry: int = Field(ge=0, le=100) + materials: int = Field(ge=0, le=100) + realism: int = Field(ge=0, le=100) + overall: int = Field(ge=0, le=100) + + +class OrientedBoundingBox(_StrictModel): + center_m: Point3 + size_m: Point3 + yaw_deg: float + footprint_polygon_m: list[Point2] = Field(min_length=3) + + @model_validator(mode="after") + def validate_geometry(self) -> OrientedBoundingBox: + if any(not math.isfinite(value) for value in self.center_m): + raise ValueError("OBB center must be finite") + if any(not math.isfinite(value) or value <= 0 for value in self.size_m): + raise ValueError("OBB size must be finite and positive") + _validate_polygon(self.footprint_polygon_m, "OBB footprint") + return self + + +class OperationalClearance(_StrictModel): + clearance_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + operation: str = Field(min_length=1) + polygon_m: list[Point2] = Field(min_length=3) + height_range_m: tuple[float, float] + source: Literal["observed", "inferred"] + confidence: float = Field(ge=0, le=1) + + @model_validator(mode="after") + def validate_geometry(self) -> OperationalClearance: + _validate_polygon(self.polygon_m, f"clearance {self.clearance_id}") + if ( + not all(math.isfinite(value) for value in self.height_range_m) + or self.height_range_m[0] < 0 + or self.height_range_m[1] <= self.height_range_m[0] + ): + raise ValueError("clearance height range must be finite and increasing") + return self + + +def _validate_polygon(value: list[Point2], label: str) -> None: + if len(value) < 3: + raise ValueError(f"{label} requires at least three points") + if any( + len(point) != 2 or any(not math.isfinite(float(coordinate)) for coordinate in point) + for point in value + ): + raise ValueError(f"{label} contains invalid coordinates") + polygon = Polygon(value) + if polygon.is_empty or not polygon.is_valid or polygon.area <= 1.0e-10: + raise ValueError(f"{label} must be a valid non-empty polygon") + + +class AssetDescriptor(_StrictModel): + """The machine-readable source of truth for one released local asset. + + All geometry is expressed in the canonical Z-up, metre frame. Semantic + front is recorded separately by ``front_axis`` because real assets do not + consistently use the same authored front direction. The source file is + never modified. ``canonical_transform`` and ``native_to_meter_scale`` + describe the reversible normalization applied by loaders before placement. + """ + + schema_version: Literal["2.0", "2.1"] = "2.1" + asset_id: str = Field(min_length=1) + source: str = Field(min_length=1) + source_version: str = "unknown" + source_license: str = Field(min_length=1) + source_path: str = Field(min_length=1) + canonical_path: str = Field(min_length=1) + sha256: str + category: str = Field(min_length=1) + subcategory: str = "" + display_name: str = Field(min_length=1) + semantic_tags: list[str] = Field(default_factory=list) + synonyms: list[str] = Field(default_factory=list) + style_tags: list[str] = Field(default_factory=list) + color_tags: list[str] = Field(default_factory=list) + material_tags: list[str] = Field(default_factory=list) + pbr_channels: PbrChannels = Field(default_factory=PbrChannels) + units: Literal["meter"] = "meter" + native_units: str = "meter" + native_to_meter_scale: float = Field(default=1.0, gt=0) + up_axis: Literal["Z"] = "Z" + front_axis: Literal["+X", "-X", "+Y", "-Y"] = "+Y" + front_axis_source: Literal[ + "source_metadata", + "dataset_convention", + "geometry_heuristic", + "multiview_verified", + "manual_override", + "unknown", + ] = "unknown" + front_axis_evidence: list[str] = Field(default_factory=list) + # ``front_axis`` above is retained as the v2.0 compatibility field. New + # producers must keep the following visual/functional concepts separate. + visual_front_axis: FrontAxis = "AMBIGUOUS" + functional_front_axis: FrontAxis = "AMBIGUOUS" + back_axis: FrontAxis = "AMBIGUOUS" + head_axis: FrontAxis = "AMBIGUOUS" + foot_axis: FrontAxis = "AMBIGUOUS" + front_yaw_deg: float = 0.0 + front_method: FrontMethod = FrontMethod.UNKNOWN + front_confidence: float = Field(default=0.0, ge=0.0, le=1.0) + front_confidence_grade: FrontConfidenceGrade = FrontConfidenceGrade.UNKNOWN + front_evidence: list[FrontEvidence] = Field(default_factory=list) + symmetry_type: SymmetryType = SymmetryType.UNKNOWN + category_front_definition_version: str = "front-definitions-v1" + review_status: FrontReviewStatus = FrontReviewStatus.UNREVIEWED + reviewed_by: str | None = None + reviewed_at: datetime | None = None + native_up_vector: Point3 = (0.0, 0.0, 1.0) + native_front_vector: Point3 = (0.0, 1.0, 0.0) + canonical_transform: tuple[float, ...] = Field(min_length=16, max_length=16) + native_bbox_m: Point3 + source_bbox_min_m: Point3 + source_bbox_max_m: Point3 + visual_footprint_polygon_m: list[Point2] = Field(default_factory=list) + collision_footprint_polygon_m: list[Point2] = Field(default_factory=list) + support_footprint_polygon_m: list[Point2] = Field(default_factory=list) + layout_reserve_envelope_polygon_m: list[Point2] = Field(default_factory=list) + obb_m: OrientedBoundingBox | None = None + height_m: float = Field(default=0.0, ge=0) + support_type: Literal["floor", "wall", "ceiling", "surface"] = "floor" + wall_affinity: Literal["none", "preferred", "required"] = "none" + articulated: bool = False + movable_parts: list[dict[str, Any]] = Field(default_factory=list) + operational_clearance: list[OperationalClearance] = Field(default_factory=list) + affordances: list[str] = Field(default_factory=list) + uniform_scale_range: tuple[float, float] = (1.0, 1.0) + quality: AssetQuality + thumbnail: str = "" + multiview_images: list[str] = Field(default_factory=list) + geometry_format: str = "" + format_extensions: list[str] = Field(default_factory=list) + loader_compatibility: dict[ + str, Literal["verified", "compatible", "unsupported", "not_tested"] + ] = Field(default_factory=dict) + vertex_count: int = Field(default=0, ge=0) + triangle_count: int = Field(default=0, ge=0) + material_count: int = Field(default=0, ge=0) + collision_source: Literal["explicit", "visual_conservative", "none"] = "none" + texture_dependencies: list[str] = Field(default_factory=list) + missing_dependencies: list[str] = Field(default_factory=list) + canonical_asset_id: str | None = None + near_duplicate_asset_ids: list[str] = Field(default_factory=list) + geometry_signature: str = "" + status: Literal["ACTIVE", "QUARANTINED"] + status_reason: str = "" + observed_fields: list[str] = Field(default_factory=list) + inferred_fields: list[str] = Field(default_factory=list) + confidence: dict[str, float] = Field(default_factory=dict) + certification: AssetCertification | None = None + + @field_validator("sha256") + @classmethod + def validate_sha256(cls, value: str) -> str: + normalized = value.casefold() + if not re.fullmatch(r"[0-9a-f]{64}", normalized): + raise ValueError("sha256 must contain 64 hexadecimal characters") + return normalized + + @model_validator(mode="after") + def validate_descriptor(self) -> AssetDescriptor: + if ( + self.uniform_scale_range[0] <= 0 + or self.uniform_scale_range[1] < self.uniform_scale_range[0] + ): + raise ValueError("uniform scale range must be positive and increasing") + if any(not math.isfinite(value) or value < 0 for value in self.native_bbox_m): + raise ValueError("native bbox dimensions must be finite and non-negative") + for key, value in self.confidence.items(): + if not 0 <= value <= 1: + raise ValueError(f"confidence {key!r} must be in [0, 1]") + overlap = set(self.observed_fields) & set(self.inferred_fields) + if overlap: + raise ValueError(f"fields cannot be both observed and inferred: {sorted(overlap)}") + if not math.isfinite(self.front_yaw_deg): + raise ValueError("front_yaw_deg must be finite") + if self.front_confidence_grade == FrontConfidenceGrade.VERIFIED: + if self.front_confidence < 0.9: + raise ValueError("VERIFIED front requires confidence >= 0.9") + if self.review_status not in { + FrontReviewStatus.HUMAN_VERIFIED, + FrontReviewStatus.AUTO_REVIEWED, + }: + raise ValueError("VERIFIED front requires a completed review status") + if not self.front_evidence: + raise ValueError("VERIFIED front requires structured evidence") + if self.review_status == FrontReviewStatus.HUMAN_VERIFIED: + if not self.reviewed_by or self.reviewed_at is None: + raise ValueError("human review requires reviewed_by and reviewed_at") + if self.certification is not None: + if self.certification.asset_id != self.asset_id: + raise ValueError("asset certification ID does not match descriptor") + if self.certification.asset_sha256 != self.sha256: + raise ValueError("asset certification hash does not match descriptor") + if self.front_axis_source in {"multiview_verified", "manual_override"}: + if self.confidence.get("front_axis", 0.0) < 0.9: + raise ValueError("verified front_axis requires confidence >= 0.9") + if not self.front_axis_evidence: + raise ValueError("verified front_axis requires evidence") + if "front_axis" not in self.observed_fields: + raise ValueError("verified front_axis must be recorded as observed") + if self.status == "ACTIVE": + if self.status_reason: + raise ValueError("ACTIVE descriptors cannot have status_reason") + if self.vertex_count < 3 or self.triangle_count < 1: + raise ValueError("ACTIVE descriptors require non-empty triangle geometry") + if self.height_m <= 0 or any(value <= 0 for value in self.native_bbox_m): + raise ValueError("ACTIVE descriptors require positive measured dimensions") + if self.obb_m is None: + raise ValueError("ACTIVE descriptors require an OBB") + for label, polygon in ( + ("visual footprint", self.visual_footprint_polygon_m), + ("collision footprint", self.collision_footprint_polygon_m), + ("support footprint", self.support_footprint_polygon_m), + ("layout reserve envelope", self.layout_reserve_envelope_polygon_m), + ): + _validate_polygon(polygon, label) + if not self.thumbnail or len(self.multiview_images) < 4: + raise ValueError("ACTIVE descriptors require thumbnail and four multiview images") + if self.missing_dependencies: + raise ValueError("ACTIVE descriptors cannot have missing dependencies") + elif not self.status_reason: + raise ValueError("QUARANTINED descriptors require a concrete status reason") + return self diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/embeddings.py b/docs/reproduction/public_conversion_code/packages/asset_registry/embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..3534d43e5c83002fa18ae5c299d7e8cbfb2b16f4 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/embeddings.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import Protocol + +import numpy as np # type: ignore[import-not-found] + + +class EmbeddingProvider(Protocol): + @property + def dimension(self) -> int: ... + + @property + def model_name(self) -> str: ... + + def encode_passages(self, values: list[str]) -> np.ndarray: ... + + def encode_queries(self, values: list[str]) -> np.ndarray: ... + + +class E5EmbeddingProvider: + def __init__( + self, + model_name: str = "intfloat/multilingual-e5-small", + *, + device: str | None = None, + batch_size: int = 128, + ) -> None: + try: + from sentence_transformers import SentenceTransformer # type: ignore[import-not-found] + except ImportError as error: + raise RuntimeError( + "sentence-transformers is required; install robothousegen[asset-index]" + ) from error + self._model_name = model_name + self._model = SentenceTransformer(model_name, device=device) + self._batch_size = batch_size + dimension_method = getattr( + self._model, + "get_embedding_dimension", + self._model.get_sentence_embedding_dimension, + ) + self._dimension = int(dimension_method()) + + @property + def dimension(self) -> int: + return self._dimension + + @property + def model_name(self) -> str: + return self._model_name + + def _encode(self, values: list[str], prefix: str) -> np.ndarray: + if not values: + return np.empty((0, self.dimension), dtype=np.float32) + vectors = self._model.encode( + [f"{prefix}: {value}" for value in values], + batch_size=self._batch_size, + convert_to_numpy=True, + normalize_embeddings=True, + show_progress_bar=len(values) > self._batch_size, + ) + return np.asarray(vectors, dtype=np.float32) + + def encode_passages(self, values: list[str]) -> np.ndarray: + return self._encode(values, "passage") + + def encode_queries(self, values: list[str]) -> np.ndarray: + return self._encode(values, "query") diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/expansion.py b/docs/reproduction/public_conversion_code/packages/asset_registry/expansion.py new file mode 100644 index 0000000000000000000000000000000000000000..26c301f70692a65fc1c740d3549769a7cbb78830 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/expansion.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +from collections import Counter, defaultdict, deque +from pathlib import Path +from typing import Iterable + +from packages.asset_registry.models import AdmissionStatus, AssetKind, AssetRecord + + +CATEGORY_QUOTAS: dict[str, int] = { + "chair": 32, + "sofa": 16, + "table": 36, + "desk": 18, + "cabinet": 12, + "bookcase": 7, + "shelf": 12, + "floor lamp": 12, + "lamp": 10, + "potted plant": 5, + "plant": 5, + "monitor": 10, + "television": 10, + "computer": 2, + "book": 18, + "bottle": 10, + "bowl": 8, + "cup": 8, + "mug": 6, + "trash can": 3, + "refrigerator": 10, + "sink": 6, + "faucet": 6, + "oven": 5, + "kitchen counter": 10, +} + +# (minimum short horizontal, maximum short horizontal, minimum long horizontal, +# maximum long horizontal, minimum vertical, maximum vertical), in metres. +CATEGORY_DIMENSION_RANGES: dict[str, tuple[float, float, float, float, float, float]] = { + "chair": (0.25, 1.00, 0.30, 1.25, 0.45, 1.55), + "sofa": (0.50, 1.55, 1.05, 3.60, 0.45, 1.45), + "table": (0.30, 1.90, 0.45, 3.60, 0.40, 1.30), + "desk": (0.30, 1.55, 0.55, 3.20, 0.45, 1.30), + "cabinet": (0.18, 1.30, 0.35, 3.20, 0.35, 2.60), + "bookcase": (0.18, 1.30, 0.30, 2.60, 0.45, 2.80), + "shelf": (0.15, 1.40, 0.25, 2.80, 0.30, 2.80), + "floor lamp": (0.12, 1.00, 0.12, 1.20, 0.90, 2.80), + "lamp": (0.04, 0.90, 0.05, 1.00, 0.08, 1.40), + "potted plant": (0.12, 1.40, 0.12, 1.50, 0.20, 2.80), + "plant": (0.08, 1.50, 0.08, 1.60, 0.15, 3.00), + "monitor": (0.02, 0.80, 0.18, 2.20, 0.12, 1.50), + "television": (0.02, 0.90, 0.25, 2.80, 0.15, 1.80), + "computer": (0.05, 0.90, 0.10, 1.20, 0.08, 1.20), + "book": (0.01, 0.45, 0.04, 0.65, 0.01, 0.55), + "bottle": (0.02, 0.35, 0.02, 0.40, 0.06, 0.75), + "bowl": (0.03, 0.70, 0.04, 0.75, 0.02, 0.45), + "cup": (0.02, 0.35, 0.02, 0.40, 0.04, 0.45), + "mug": (0.03, 0.35, 0.03, 0.40, 0.04, 0.45), + "trash can": (0.12, 1.10, 0.12, 1.20, 0.20, 1.60), + "refrigerator": (0.35, 1.50, 0.45, 1.80, 1.20, 2.60), + "sink": (0.10, 1.30, 0.25, 2.20, 0.08, 1.30), + "faucet": (0.02, 0.70, 0.04, 0.80, 0.05, 0.80), + "oven": (0.20, 1.30, 0.25, 1.50, 0.20, 1.40), + "kitchen counter": (0.30, 1.40, 0.50, 4.20, 0.45, 1.40), +} + +SOURCE_PRIORITY = { + "ArtVIP": 0, + "H20 qualified/lightwheel": 1, + "Lightwheel SimReady": 1, + "H20 qualified/molmospaces_thor": 2, + "GoogleResearch on Gazebo Fuel": 3, + "Google Scanned Objects": 3, + "YCB": 3, + "Poly Haven": 3, +} + + +def candidate_rejection_reason(record: AssetRecord) -> str | None: + if record.asset_kind != AssetKind.OBJECT: + return "not_object" + if record.admission_status != AdmissionStatus.COLD: + return "not_cold" + if record.exclusion_reasons != ["proxy_not_prepared"]: + return "additional_exclusion_reason" + if record.quality_tier != "A": + return "quality_below_a" + if float(record.dimension_confidence or 0.0) < 0.9: + return "low_dimension_confidence" + if not Path(record.usd_path).is_file(): + return "missing_runtime_path" + category = str(record.normalized_category or "") + bounds = CATEGORY_DIMENSION_RANGES.get(category) + if bounds is None: + return "category_not_curated" + if record.dimensions_m is None or any(value <= 0 for value in record.dimensions_m): + return "invalid_dimensions" + x, y, z = (float(value) for value in record.dimensions_m) + short, long = sorted((x, y)) + minimum_short, maximum_short, minimum_long, maximum_long, minimum_z, maximum_z = bounds + if not ( + minimum_short <= short <= maximum_short + and minimum_long <= long <= maximum_long + and minimum_z <= z <= maximum_z + ): + return "implausible_category_dimensions" + return None + + +def _source_round_robin(records: Iterable[AssetRecord], limit: int) -> list[AssetRecord]: + buckets: dict[str, deque[AssetRecord]] = defaultdict(deque) + for record in sorted(records, key=lambda item: item.asset_id.casefold()): + buckets[record.source].append(record) + source_names = sorted( + buckets, + key=lambda source: (SOURCE_PRIORITY.get(source, 99), source.casefold()), + ) + selected: list[AssetRecord] = [] + while len(selected) < limit and any(buckets.values()): + for source in source_names: + if buckets[source] and len(selected) < limit: + selected.append(buckets[source].popleft()) + return selected + + +def select_proxy_expansion_candidates( + records: Iterable[AssetRecord], *, maximum_total: int = 240 +) -> tuple[list[AssetRecord], dict[str, int]]: + eligible: dict[str, list[AssetRecord]] = defaultdict(list) + rejection_counts: Counter[str] = Counter() + for record in records: + reason = candidate_rejection_reason(record) + if reason is not None: + rejection_counts[reason] += 1 + continue + eligible[str(record.normalized_category)].append(record) + + selected: list[AssetRecord] = [] + for category, quota in CATEGORY_QUOTAS.items(): + selected.extend(_source_round_robin(eligible.get(category, []), quota)) + selected = selected[:maximum_total] + return selected, dict(sorted(rejection_counts.items())) diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/front_certification.py b/docs/reproduction/public_conversion_code/packages/asset_registry/front_certification.py new file mode 100644 index 0000000000000000000000000000000000000000..361d210d55341472322af3cb24bae7b4cc17d87a --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/front_certification.py @@ -0,0 +1,688 @@ +from __future__ import annotations + +import hashlib +import json +import math +import random +import sqlite3 +from collections import Counter, defaultdict +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any, Literal, cast + +from PIL import Image, ImageDraw, ImageFont +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.asset_registry.certification_models import ( + CardinalAxis, + FrontAxis, + FrontConfidenceGrade, + FrontEvidence, + FrontMethod, + FrontReviewStatus, + SymmetryType, +) +from packages.asset_registry.descriptors import AssetDescriptor +from packages.core.files import atomic_write_text + +AXES: tuple[CardinalAxis, ...] = ("+X", "-X", "+Y", "-Y") +OPPOSITE: dict[CardinalAxis, CardinalAxis] = { + "+X": "-X", + "-X": "+X", + "+Y": "-Y", + "-Y": "+Y", +} +YAW_TO_CANONICAL_FRONT: dict[CardinalAxis, float] = { + "+Y": 0.0, + "+X": 90.0, + "-Y": 180.0, + "-X": -90.0, +} +EVIDENCE_WEIGHTS = { + "human_review": 1.50, + "multiview": 1.25, + "articulation": 1.20, + "handle": 1.20, + "affordance": 1.10, + "vlm_vote": 1.00, + "embedding_vote": 0.90, + "geometry": 0.85, + "wall_clearance": 0.80, + "source_metadata": 0.70, + "dataset_convention": 0.60, + "symmetry": 1.25, +} + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class CategoryFrontDefinition(_StrictModel): + version: Literal["front-definitions-v1"] = "front-definitions-v1" + definition_id: str + categories: set[str] + functional_semantics: Literal[ + "seating_gaze", + "bed_foot", + "operation_side", + "screen_normal", + "none", + "unknown", + ] + visual_matches_functional: bool = True + back_is_opposite_functional: bool = False + default_symmetry: SymmetryType = SymmetryType.UNKNOWN + explanation: str + + +FRONT_DEFINITIONS: tuple[CategoryFrontDefinition, ...] = ( + CategoryFrontDefinition( + definition_id="seating-v1", + categories={"sofa", "chair", "armchair", "office chair", "dining chair"}, + functional_semantics="seating_gaze", + back_is_opposite_functional=True, + explanation=( + "functional_front is the direction a seated person faces; " + "back_axis is the backrest side" + ), + ), + CategoryFrontDefinition( + definition_id="bed-v1", + categories={"bed", "single bed", "double bed", "bunk bed"}, + functional_semantics="bed_foot", + back_is_opposite_functional=True, + explanation=( + "head_axis is the headboard side and foot_axis is the opposite bed-foot direction" + ), + ), + CategoryFrontDefinition( + definition_id="articulated-storage-v1", + categories={ + "cabinet", + "wardrobe", + "refrigerator", + "fridge", + "drawer", + "chest of drawers", + "bookcase", + }, + functional_semantics="operation_side", + back_is_opposite_functional=True, + explanation="functional_front is the door, drawer, or handle operation side", + ), + CategoryFrontDefinition( + definition_id="display-v1", + categories={"television", "tv", "display", "monitor", "computer monitor"}, + functional_semantics="screen_normal", + back_is_opposite_functional=True, + explanation="functional_front is the outward screen normal", + ), + CategoryFrontDefinition( + definition_id="symmetric-none-v1", + categories={ + "round table", + "table", + "round stool", + "stool", + "round trash can", + "trash can", + "plant", + "vase", + }, + functional_semantics="none", + visual_matches_functional=False, + default_symmetry=SymmetryType.ROTATIONAL, + explanation=( + "category permits NONE; direction must not be invented without asymmetric evidence" + ), + ), +) + + +class FrontCertificationResult(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + asset_id: str + asset_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + category: str + category_definition_id: str + category_front_definition_version: Literal["front-definitions-v1"] = "front-definitions-v1" + visual_front_axis: FrontAxis + functional_front_axis: FrontAxis + back_axis: FrontAxis + head_axis: FrontAxis = "AMBIGUOUS" + foot_axis: FrontAxis = "AMBIGUOUS" + symmetry_type: SymmetryType + front_yaw_deg: float + front_method: FrontMethod + front_confidence: float = Field(ge=0.0, le=1.0) + confidence_grade: FrontConfidenceGrade + review_status: FrontReviewStatus + reviewed_by: str | None = None + reviewed_at: datetime | None = None + evidence: list[FrontEvidence] + conflicts: list[str] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_result(self) -> FrontCertificationResult: + if not math.isfinite(self.front_yaw_deg): + raise ValueError("front_yaw_deg must be finite") + if self.confidence_grade == FrontConfidenceGrade.VERIFIED: + if self.front_confidence < 0.9: + raise ValueError("VERIFIED result requires confidence >= 0.9") + kinds = {item.kind for item in self.evidence} + if not kinds & {"human_review", "multiview"}: + raise ValueError("VERIFIED result requires human or multiview evidence") + if self.review_status == FrontReviewStatus.NEEDS_REVIEW and not self.conflicts: + raise ValueError("review queue items require a conflict reason") + if self.review_status == FrontReviewStatus.HUMAN_VERIFIED and ( + not self.reviewed_by or self.reviewed_at is None + ): + raise ValueError("human-verified result requires reviewer provenance") + return self + + +def definition_for_category(category: str) -> CategoryFrontDefinition: + normalized = category.casefold().strip().replace("_", " ") + exact = [item for item in FRONT_DEFINITIONS if normalized in item.categories] + if exact: + return exact[0] + for item in FRONT_DEFINITIONS: + if any(token in normalized for token in item.categories if len(token) >= 4): + return item + return CategoryFrontDefinition( + definition_id="unknown-v1", + categories={normalized or "unknown"}, + functional_semantics="unknown", + visual_matches_functional=False, + explanation="no category-specific front definition is registered", + ) + + +@dataclass(frozen=True) +class _Vote: + axis: FrontAxis + confidence: float + margin: float + kinds: frozenset[str] + conflicts: tuple[str, ...] + + +def _vote(evidence: Sequence[FrontEvidence], target: str) -> _Vote: + selected = [item for item in evidence if item.target == target] + if not selected: + return _Vote("AMBIGUOUS", 0.0, 0.0, frozenset(), ()) + special: defaultdict[str, float] = defaultdict(float) + scores: defaultdict[str, float] = defaultdict(float) + support: defaultdict[str, float] = defaultdict(float) + axes_seen: dict[str, set[str]] = defaultdict(set) + for item in selected: + weight = EVIDENCE_WEIGHTS[item.kind] + weighted = item.confidence * weight + if item.axis in {"NONE", "AMBIGUOUS"}: + special[item.axis] += weighted + else: + scores[item.axis] += weighted + support[item.axis] += weight + if item.confidence >= 0.75: + axes_seen[item.axis].add(item.kind) + conflicts: list[str] = [] + candidates = {**scores, **special} + if not candidates: + return _Vote("AMBIGUOUS", 0.0, 0.0, frozenset(), tuple(conflicts)) + ordered = sorted(candidates, key=lambda axis: (-candidates[axis], axis)) + best = ordered[0] + runner_up = candidates[ordered[1]] if len(ordered) > 1 else 0.0 + strong_axes = sorted(axis for axis, kinds in axes_seen.items() if kinds) + high_trust_kinds = {"human_review", "multiview", "articulation", "handle"} + high_trust_axes = sorted(axis for axis, kinds in axes_seen.items() if kinds & high_trust_kinds) + disagreement_ratio = runner_up / max(candidates[best], 1.0e-9) + if len(high_trust_axes) > 1 or (len(strong_axes) > 1 and disagreement_ratio >= 0.65): + conflicts.append(f"high_confidence_axis_disagreement:{','.join(strong_axes)}") + total = sum(candidates.values()) + confidence = candidates[best] / total if total else 0.0 + margin = (candidates[best] - runner_up) / max(candidates[best], 1.0e-9) + if best not in {"NONE", "AMBIGUOUS"}: + agreement = scores[best] / max(support[best], 1.0e-9) + confidence = min(0.99, 0.55 * confidence + 0.45 * agreement) + if margin < 0.15 and len(ordered) > 1: + conflicts.append(f"low_vote_margin:{margin:.3f}") + if conflicts: + best = "AMBIGUOUS" + confidence = min(confidence, 0.49) + return _Vote( + cast(FrontAxis, best), + round(confidence, 6), + round(margin, 6), + frozenset(item.kind for item in selected), + tuple(conflicts), + ) + + +def _descriptor_evidence(descriptor: AssetDescriptor) -> list[FrontEvidence]: + kind_map = { + "source_metadata": "source_metadata", + "dataset_convention": "dataset_convention", + "geometry_heuristic": "geometry", + "multiview_verified": "multiview", + "manual_override": "source_metadata", + "unknown": "dataset_convention", + } + confidence = float(descriptor.confidence.get("front_axis", 0.0)) + if confidence <= 0.0: + confidence = 0.35 if descriptor.front_axis_source == "unknown" else 0.55 + kind = kind_map[descriptor.front_axis_source] + reviewer: dict[str, Any] = {} + if ( + descriptor.front_axis_source == "manual_override" + and descriptor.reviewed_by + and descriptor.reviewed_at is not None + ): + kind = "human_review" + reviewer = { + "reviewed_by": descriptor.reviewed_by, + "reviewed_at": descriptor.reviewed_at, + } + evidence = [ + FrontEvidence( + evidence_id=f"descriptor:{descriptor.asset_id}:legacy-front", + kind=kind, # type: ignore[arg-type] + target="functional_front", + axis=descriptor.front_axis, + confidence=confidence, + source_hash=descriptor.sha256, + note=( + "compatibility evidence from AssetDescriptor/2.0 front_axis; " + "legacy human provenance is incomplete" + if descriptor.front_axis_source == "manual_override" and not reviewer + else "compatibility evidence from AssetDescriptor/2.0 front_axis" + ), + **reviewer, + ) + ] + if descriptor.front_axis_source in {"multiview_verified", "manual_override"}: + evidence.append( + evidence[0].model_copy( + update={ + "evidence_id": f"descriptor:{descriptor.asset_id}:legacy-visual-front", + "target": "visual_front", + } + ) + ) + return evidence + + +def _grade( + vote: _Vote, evidence: Sequence[FrontEvidence] +) -> tuple[FrontConfidenceGrade, FrontReviewStatus, FrontMethod]: + if vote.conflicts or vote.axis == "AMBIGUOUS": + return ( + FrontConfidenceGrade.AMBIGUOUS, + FrontReviewStatus.NEEDS_REVIEW, + FrontMethod.UNKNOWN, + ) + kinds = {item.kind for item in evidence} + human = "human_review" in kinds + multiview = "multiview" in kinds + if vote.confidence >= 0.9 and (human or multiview): + method = FrontMethod.HUMAN_REVIEW if human else FrontMethod.MULTIVIEW_CONSENSUS + review = FrontReviewStatus.HUMAN_VERIFIED if human else FrontReviewStatus.AUTO_REVIEWED + return FrontConfidenceGrade.VERIFIED, review, method + if vote.confidence >= 0.8 and len(kinds) >= 2: + method = ( + FrontMethod.AFFORDANCE_CONSENSUS + if kinds & {"articulation", "handle", "affordance"} + else FrontMethod.DATASET_AND_GEOMETRY + ) + return FrontConfidenceGrade.HIGH, FrontReviewStatus.AUTO_REVIEWED, method + if vote.confidence >= 0.6 and len(kinds) >= 2: + return ( + FrontConfidenceGrade.MEDIUM, + FrontReviewStatus.AUTO_REVIEWED, + FrontMethod.DATASET_AND_GEOMETRY, + ) + if vote.confidence > 0.0: + method = ( + FrontMethod.GEOMETRY_HEURISTIC + if "geometry" in kinds + else FrontMethod.DATASET_CONVENTION + ) + return FrontConfidenceGrade.LOW, FrontReviewStatus.NEEDS_REVIEW, method + return FrontConfidenceGrade.UNKNOWN, FrontReviewStatus.NEEDS_REVIEW, FrontMethod.UNKNOWN + + +def certify_front( + descriptor: AssetDescriptor, + evidence: Sequence[FrontEvidence] = (), + *, + unresolved_policy: Literal["queue", "reject"] = "queue", +) -> FrontCertificationResult: + definition = definition_for_category(descriptor.category) + combined = [*_descriptor_evidence(descriptor), *evidence] + functional = _vote(combined, "functional_front") + visual = _vote(combined, "visual_front") + back = _vote(combined, "back_axis") + symmetry_evidence = [item for item in combined if item.target == "symmetry"] + symmetry = definition.default_symmetry + if any(item.axis == "NONE" and item.confidence >= 0.7 for item in symmetry_evidence): + symmetry = SymmetryType.ROTATIONAL + + conflicts = [*functional.conflicts, *visual.conflicts, *back.conflicts] + if definition.functional_semantics == "none" and not [ + item + for item in combined + if item.target == "functional_front" and item.kind != "dataset_convention" + ]: + functional = _Vote("NONE", 0.95, 1.0, frozenset({"symmetry"}), ()) + visual = _Vote("NONE", 0.85, 1.0, frozenset({"symmetry"}), ()) + combined.append( + FrontEvidence( + evidence_id=f"category:{definition.definition_id}", + kind="symmetry", + target="symmetry", + axis="NONE", + confidence=0.95, + note=definition.explanation, + ) + ) + elif visual.axis == "AMBIGUOUS" and definition.visual_matches_functional: + visual = functional + + functional_axis = functional.axis + back_axis = back.axis + if ( + back_axis == "AMBIGUOUS" + and definition.back_is_opposite_functional + and functional_axis in AXES + ): + back_axis = OPPOSITE[functional_axis] + head_axis: FrontAxis = "AMBIGUOUS" + foot_axis: FrontAxis = "AMBIGUOUS" + if definition.functional_semantics == "bed_foot" and functional_axis in AXES: + foot_axis = functional_axis + head_axis = OPPOSITE[functional_axis] + back_axis = head_axis + + selected_evidence = [ + item for item in combined if item.target in {"functional_front", "visual_front"} + ] + grade, review, method = _grade(functional, selected_evidence) + if functional_axis == "NONE": + grade = FrontConfidenceGrade.HIGH + review = FrontReviewStatus.AUTO_REVIEWED + method = FrontMethod.SYMMETRY + if review == FrontReviewStatus.NEEDS_REVIEW and not conflicts: + conflicts.append("insufficient_independent_evidence") + if unresolved_policy == "reject" and review == FrontReviewStatus.NEEDS_REVIEW: + review = FrontReviewStatus.REJECTED + yaw = YAW_TO_CANONICAL_FRONT.get(functional_axis, 0.0) # type: ignore[arg-type] + human_evidence = [ + item + for item in combined + if item.kind == "human_review" and item.reviewed_by and item.reviewed_at is not None + ] + human_evidence.sort(key=lambda item: (item.reviewed_at or datetime.min).isoformat()) + latest_human = human_evidence[-1] if human_evidence else None + return FrontCertificationResult( + asset_id=descriptor.asset_id, + asset_sha256=descriptor.sha256, + category=descriptor.category, + category_definition_id=definition.definition_id, + visual_front_axis=visual.axis, + functional_front_axis=functional_axis, + back_axis=back_axis, + head_axis=head_axis, + foot_axis=foot_axis, + symmetry_type=symmetry, + front_yaw_deg=yaw, + front_method=method, + front_confidence=functional.confidence, + confidence_grade=grade, + review_status=review, + reviewed_by=latest_human.reviewed_by if latest_human else None, + reviewed_at=latest_human.reviewed_at if latest_human else None, + evidence=combined, + conflicts=sorted(set(conflicts)), + ) + + +def apply_front_result( + descriptor: AssetDescriptor, result: FrontCertificationResult +) -> AssetDescriptor: + if descriptor.asset_id != result.asset_id or descriptor.sha256 != result.asset_sha256: + raise ValueError("front result is not bound to this descriptor identity") + confidence = dict(descriptor.confidence) + confidence["front_axis"] = result.front_confidence + legacy_source = { + FrontMethod.HUMAN_REVIEW: "manual_override", + FrontMethod.MULTIVIEW_CONSENSUS: "multiview_verified", + FrontMethod.DATASET_CONVENTION: "dataset_convention", + FrontMethod.GEOMETRY_HEURISTIC: "geometry_heuristic", + }.get(result.front_method, "unknown") + observed = list(descriptor.observed_fields) + inferred = list(descriptor.inferred_fields) + front_axis = descriptor.front_axis + front_axis_evidence = list(descriptor.front_axis_evidence) + if result.functional_front_axis in AXES: + front_axis = result.functional_front_axis + front_axis_evidence.extend(item.source_uri or item.evidence_id for item in result.evidence) + if legacy_source in {"multiview_verified", "manual_override"}: + observed = sorted(set(observed) | {"front_axis"}) + inferred = [item for item in inferred if item != "front_axis"] + elif "front_axis" not in observed: + inferred = sorted(set(inferred) | {"front_axis"}) + payload = descriptor.model_dump(mode="python") + payload.update( + { + "schema_version": "2.1", + "front_axis": front_axis, + "front_axis_source": legacy_source, + "front_axis_evidence": sorted(set(front_axis_evidence)), + "visual_front_axis": result.visual_front_axis, + "functional_front_axis": result.functional_front_axis, + "back_axis": result.back_axis, + "head_axis": result.head_axis, + "foot_axis": result.foot_axis, + "front_yaw_deg": result.front_yaw_deg, + "front_method": result.front_method, + "front_confidence": result.front_confidence, + "front_confidence_grade": result.confidence_grade, + "front_evidence": result.evidence, + "symmetry_type": result.symmetry_type, + "category_front_definition_version": result.category_front_definition_version, + "review_status": result.review_status, + "reviewed_by": result.reviewed_by, + "reviewed_at": result.reviewed_at, + "observed_fields": observed, + "inferred_fields": inferred, + "confidence": confidence, + } + ) + return AssetDescriptor.model_validate(payload) + + +def load_descriptor_index(path: Path, *, active_only: bool = True) -> list[AssetDescriptor]: + uri = f"file:{path.resolve()}?mode=ro&immutable=1" + connection = sqlite3.connect(uri, uri=True) + try: + where = " WHERE status='ACTIVE'" if active_only else "" + rows = connection.execute( + f"SELECT descriptor_json FROM asset_descriptors{where} ORDER BY asset_id" + ).fetchall() + finally: + connection.close() + return [AssetDescriptor.model_validate_json(row[0]) for row in rows] + + +def load_evidence_jsonl(path: Path | None) -> dict[str, list[FrontEvidence]]: + output: dict[str, list[FrontEvidence]] = defaultdict(list) + if path is None: + return output + for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + payload = json.loads(line) + asset_id = payload.pop("asset_id", None) + if not isinstance(asset_id, str): + raise ValueError(f"front evidence line {line_number} requires asset_id") + output[asset_id].append(FrontEvidence.model_validate(payload)) + return output + + +def _label_font() -> ImageFont.ImageFont | ImageFont.FreeTypeFont: + return ImageFont.load_default() + + +def build_contact_sheet( + descriptors: Sequence[AssetDescriptor], + results: dict[str, FrontCertificationResult], + output: Path, + *, + sample_size: int = 24, + seed: int = 0, +) -> int: + candidates = [ + descriptor + for descriptor in descriptors + if descriptor.asset_id in results + and any(Path(path).is_file() for path in descriptor.multiview_images) + ] + random.Random(seed).shuffle(candidates) + selected = candidates[:sample_size] + if not selected: + return 0 + thumb_w, thumb_h, label_h = 180, 150, 54 + views_per_asset = 4 + sheet = Image.new( + "RGB", (views_per_asset * thumb_w, len(selected) * (thumb_h + label_h)), "white" + ) + draw = ImageDraw.Draw(sheet) + font = _label_font() + for row, descriptor in enumerate(selected): + result = results[descriptor.asset_id] + y = row * (thumb_h + label_h) + paths = [Path(path) for path in descriptor.multiview_images if Path(path).is_file()][:4] + for column in range(views_per_asset): + x = column * thumb_w + if column < len(paths): + with Image.open(paths[column]) as source: + image = source.convert("RGB") + image.thumbnail((thumb_w - 4, thumb_h - 4)) + paste_x = x + (thumb_w - image.width) // 2 + paste_y = y + (thumb_h - image.height) // 2 + sheet.paste(image, (paste_x, paste_y)) + draw.rectangle((x, y, x + thumb_w - 1, y + thumb_h - 1), outline="#666666") + label = ( + f"{descriptor.asset_id[:64]}\n{descriptor.category} " + f"functional={result.functional_front_axis} " + f"visual={result.visual_front_axis} {result.confidence_grade.value} " + f"{result.front_confidence:.2f}" + ) + draw.multiline_text((4, y + thumb_h + 3), label, fill="black", font=font, spacing=2) + output.parent.mkdir(parents=True, exist_ok=True) + sheet.save(output) + return len(selected) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def batch_certify_fronts( + *, + source_index: Path, + output_dir: Path, + evidence_path: Path | None = None, + categories: set[str] | None = None, + limit: int | None = None, + contact_sheet_sample_size: int = 24, + seed: int = 0, + autonomous: bool = False, +) -> dict[str, Any]: + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite front certification output: {output_dir}") + descriptors = load_descriptor_index(source_index) + if categories: + normalized = {item.casefold() for item in categories} + descriptors = [item for item in descriptors if item.category.casefold() in normalized] + if limit is not None: + descriptors = descriptors[:limit] + evidence = load_evidence_jsonl(evidence_path) + results = { + descriptor.asset_id: certify_front( + descriptor, + evidence.get(descriptor.asset_id, ()), + unresolved_policy="reject" if autonomous else "queue", + ) + for descriptor in descriptors + } + migrated = [apply_front_result(item, results[item.asset_id]) for item in descriptors] + output_dir.mkdir(parents=True, exist_ok=False) + descriptor_jsonl = output_dir / "asset_descriptors.front-certified.jsonl" + result_jsonl = output_dir / "front_certifications.jsonl" + unresolved_jsonl = output_dir / ( + "front_auto_rejections.jsonl" if autonomous else "front_review_queue.jsonl" + ) + atomic_write_text( + descriptor_jsonl, + "".join(item.model_dump_json() + "\n" for item in migrated), + ) + atomic_write_text( + result_jsonl, + "".join(results[key].model_dump_json() + "\n" for key in sorted(results)), + ) + atomic_write_text( + unresolved_jsonl, + "".join( + results[key].model_dump_json() + "\n" + for key in sorted(results) + if results[key].review_status + == (FrontReviewStatus.REJECTED if autonomous else FrontReviewStatus.NEEDS_REVIEW) + ), + ) + contact_sheet = output_dir / "front_contact_sheet.png" + contact_count = build_contact_sheet( + descriptors, + results, + contact_sheet, + sample_size=contact_sheet_sample_size, + seed=seed, + ) + if not contact_count: + contact_sheet = None # type: ignore[assignment] + report: dict[str, Any] = { + "schema_version": "1.0", + "source_index": str(source_index.resolve()), + "source_index_sha256": _sha256(source_index), + "source_index_preserved": True, + "adjudication_mode": "autonomous_reject_unresolved" if autonomous else "review_queue", + "processed": len(results), + "confidence_grades": dict( + sorted(Counter(item.confidence_grade.value for item in results.values()).items()) + ), + "review_statuses": dict( + sorted(Counter(item.review_status.value for item in results.values()).items()) + ), + "review_queue_count": sum( + item.review_status == FrontReviewStatus.NEEDS_REVIEW for item in results.values() + ), + "auto_rejection_count": sum( + item.review_status == FrontReviewStatus.REJECTED for item in results.values() + ), + "contact_sheet_assets": contact_count, + "files": {}, + } + for path in (descriptor_jsonl, result_jsonl, unresolved_jsonl, contact_sheet): + if path is not None and path.is_file(): + report["files"][path.name] = {"path": str(path), "sha256": _sha256(path)} + atomic_write_text( + output_dir / "front_certification_report.json", + json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + return report diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/front_policy.py b/docs/reproduction/public_conversion_code/packages/asset_registry/front_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a66e2b5874c506f34499b8bcdecfa1235000de1c --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/front_policy.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from packages.asset_registry.certification_models import ( + CardinalAxis, + FrontConfidenceGrade, + FrontReviewStatus, +) +from packages.asset_registry.descriptors import AssetDescriptor + +_GRADE_RANK = { + FrontConfidenceGrade.AMBIGUOUS: 0, + FrontConfidenceGrade.UNKNOWN: 0, + FrontConfidenceGrade.LOW: 1, + FrontConfidenceGrade.MEDIUM: 2, + FrontConfidenceGrade.HIGH: 3, + FrontConfidenceGrade.VERIFIED: 4, +} +_CARDINAL = {"+X", "-X", "+Y", "-Y"} + + +def front_meets_requirement( + descriptor: AssetDescriptor, + *, + minimum: FrontConfidenceGrade = FrontConfidenceGrade.HIGH, +) -> bool: + """Return whether a descriptor has a hash-bound, usable functional front.""" + + structured = ( + descriptor.functional_front_axis in _CARDINAL + and _GRADE_RANK[descriptor.front_confidence_grade] >= _GRADE_RANK[minimum] + and bool(descriptor.front_evidence) + and descriptor.review_status + in {FrontReviewStatus.AUTO_REVIEWED, FrontReviewStatus.HUMAN_VERIFIED} + ) + if structured: + return True + # Compatibility bridge for immutable v2.0 indexes. It is deliberately + # equivalent to VERIFIED only; weaker legacy metadata cannot pass a + # direction-sensitive placement gate. + return ( + minimum != FrontConfidenceGrade.VERIFIED + or descriptor.front_axis_source in {"multiview_verified", "manual_override"} + ) and ( + descriptor.front_axis_source in {"multiview_verified", "manual_override"} + and descriptor.confidence.get("front_axis", 0.0) >= 0.9 + and bool(descriptor.front_axis_evidence) + ) + + +def effective_functional_front_axis( + descriptor: AssetDescriptor, + *, + minimum: FrontConfidenceGrade = FrontConfidenceGrade.HIGH, +) -> CardinalAxis | None: + if not front_meets_requirement(descriptor, minimum=minimum): + return None + if descriptor.functional_front_axis in _CARDINAL: + return descriptor.functional_front_axis # type: ignore[return-value] + return descriptor.front_axis + + +def front_grade_rank(value: FrontConfidenceGrade) -> int: + return _GRADE_RANK[value] diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/index.py b/docs/reproduction/public_conversion_code/packages/asset_registry/index.py new file mode 100644 index 0000000000000000000000000000000000000000..b68ff9d3666795a10fcd5baefd2608f348d21ee5 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/index.py @@ -0,0 +1,464 @@ +from __future__ import annotations + +import hashlib +import json +import math +import re +import sqlite3 +import time +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np # type: ignore[import-not-found] + +from packages.asset_registry.admission import normalize_category +from packages.asset_registry.embeddings import EmbeddingProvider +from packages.asset_registry.models import AdmissionStatus, AssetKind, AssetRecord + +FTS_LIMIT = 100 +ANN_LIMIT = 100 +HNSW_M = 32 +HNSW_EF_CONSTRUCTION = 200 +HNSW_EF_SEARCH = 64 + + +def _source_key(value: str) -> str: + normalized = value.casefold() + if "gazebo fuel" in normalized or "google scanned objects" in normalized: + return "google scanned objects" + return normalized + + +def record_text(record: AssetRecord) -> str: + return " ".join( + value + for value in ( + record.display_name, + record.normalized_category or record.category, + record.description, + " ".join(record.tags), + " ".join(record.synonyms), + " ".join(record.affordances), + ) + if value + ) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def build_sqlite_index(records: Sequence[AssetRecord], path: Path) -> list[AssetRecord]: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.unlink(missing_ok=True) + connection = sqlite3.connect(temporary) + try: + connection.executescript( + """ + PRAGMA journal_mode=OFF; + PRAGMA synchronous=OFF; + CREATE TABLE assets ( + row_id INTEGER PRIMARY KEY, + asset_id TEXT NOT NULL UNIQUE, + asset_kind TEXT NOT NULL, + normalized_category TEXT NOT NULL, + source TEXT NOT NULL, + admission_status TEXT NOT NULL, + dimensions_json TEXT, + dimension_confidence REAL, + quality_tier TEXT NOT NULL, + record_json TEXT NOT NULL + ); + CREATE VIRTUAL TABLE active_fts USING fts5( + asset_id, display_name, normalized_category, description, + tags, synonyms, affordances, content='' + ); + CREATE VIRTUAL TABLE cold_fts USING fts5( + asset_id, display_name, normalized_category, description, + tags, synonyms, affordances, exclusion_reasons, content='' + ); + CREATE INDEX assets_kind_status ON assets(asset_kind, admission_status); + CREATE INDEX assets_category ON assets(normalized_category); + """ + ) + active: list[AssetRecord] = [] + for row_id, record in enumerate(records, start=1): + status = record.admission_status or AdmissionStatus.COLD + category = record.normalized_category or normalize_category(record.category) + connection.execute( + "INSERT INTO assets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + row_id, + record.asset_id, + record.asset_kind.value, + category, + record.source, + status.value, + json.dumps(record.dimensions_m) if record.dimensions_m else None, + record.dimension_confidence, + record.quality_tier, + record.model_dump_json(), + ), + ) + fields = ( + row_id, + record.asset_id, + record.display_name, + category, + record.description, + " ".join(record.tags), + " ".join(record.synonyms), + " ".join(record.affordances), + ) + if status == AdmissionStatus.ACTIVE: + connection.execute( + """INSERT INTO active_fts( + rowid, asset_id, display_name, normalized_category, description, + tags, synonyms, affordances + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + fields, + ) + active.append(record) + else: + connection.execute( + """INSERT INTO cold_fts( + rowid, asset_id, display_name, normalized_category, description, + tags, synonyms, affordances, exclusion_reasons + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", + (*fields, " ".join(record.exclusion_reasons)), + ) + connection.commit() + finally: + connection.close() + temporary.replace(path) + return active + + +def build_faiss_index( + records: Sequence[AssetRecord], + path: Path, + embedding_provider: EmbeddingProvider, + *, + sqlite_path: Path, +) -> None: + try: + import faiss # type: ignore[import-not-found] + except ImportError as error: + raise RuntimeError("faiss-cpu is required; install robothousegen[asset-index]") from error + vectors = embedding_provider.encode_passages([record_text(record) for record in records]) + if vectors.shape != (len(records), embedding_provider.dimension): + raise ValueError("embedding provider returned an unexpected vector shape") + base = faiss.IndexHNSWFlat(embedding_provider.dimension, HNSW_M, faiss.METRIC_INNER_PRODUCT) + base.hnsw.efConstruction = HNSW_EF_CONSTRUCTION + base.hnsw.efSearch = HNSW_EF_SEARCH + index = faiss.IndexIDMap2(base) + with sqlite3.connect(sqlite_path) as connection: + row_by_asset_id = dict(connection.execute("SELECT asset_id, row_id FROM assets")) + ids = np.asarray([row_by_asset_id[record.asset_id] for record in records], dtype=np.int64) + index.add_with_ids(np.ascontiguousarray(vectors), ids) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + faiss.write_index(index, str(temporary)) + temporary.replace(path) + + +@dataclass(frozen=True, slots=True) +class AssetQuery: + query: str + asset_id: str | None = None + normalized_category: str | None = None + dimensions_m: tuple[float, float, float] | None = None + asset_kind: AssetKind = AssetKind.OBJECT + source_priority: tuple[str, ...] = () + + +@dataclass(frozen=True, slots=True) +class RetrievalResult: + record: AssetRecord + score: float + lexical_score: float + semantic_score: float + dimension_fit: float + quality_score: float + source_priority_score: float + exact_id: bool + exact_category: bool + + +class HybridAssetIndex: + def __init__( + self, + sqlite_path: Path, + vector_path: Path | None = None, + embedding_provider: EmbeddingProvider | None = None, + ) -> None: + started = time.perf_counter() + uri = f"file:{sqlite_path.resolve()}?mode=ro&immutable=1" + self._connection = sqlite3.connect(uri, uri=True, check_same_thread=False) + self._connection.row_factory = sqlite3.Row + self._embedding_provider = embedding_provider + self._faiss: Any | None = None + if vector_path is not None: + if embedding_provider is None: + raise ValueError("embedding_provider is required with vector_path") + try: + import faiss + except ImportError as error: + raise RuntimeError( + "faiss-cpu is required; install robothousegen[asset-index]" + ) from error + self._faiss = faiss.read_index(str(vector_path)) + base = self._faiss.index if hasattr(self._faiss, "index") else self._faiss + if hasattr(base, "hnsw"): + base.hnsw.efSearch = HNSW_EF_SEARCH + self.load_time_ms = (time.perf_counter() - started) * 1000 + self.query_latencies_ms: list[float] = [] + self._query_vector_cache: dict[str, np.ndarray] = {} + + def close(self) -> None: + self._connection.close() + + def __enter__(self) -> HybridAssetIndex: + return self + + def __exit__(self, *_: object) -> None: + self.close() + + @staticmethod + def _fts_expression(value: str) -> str: + terms = list( + dict.fromkeys( + re.findall( + r"[^\W_]+", + value.casefold().replace("_", " ").replace("-", " "), + flags=re.UNICODE, + ) + ) + ) + return " OR ".join(f'"{term.replace(chr(34), chr(34) * 2)}"' for term in terms) + + def _lexical(self, query: AssetQuery, limit: int) -> dict[int, float]: + expression = self._fts_expression(query.query) + if not expression: + return {} + rows = self._connection.execute( + """ + SELECT rowid, bm25(active_fts) AS rank FROM active_fts + WHERE active_fts MATCH ? ORDER BY rank LIMIT ? + """, + (expression, limit), + ).fetchall() + if not rows: + return {} + raw = [-float(row["rank"]) for row in rows] + low, high = min(raw), max(raw) + scale = high - low + return { + int(row["rowid"]): (score - low) / scale if scale > 1e-9 else 1.0 + for row, score in zip(rows, raw, strict=True) + } + + def _semantic_batch(self, queries: Sequence[AssetQuery], limit: int) -> list[dict[int, float]]: + if self._faiss is None or self._embedding_provider is None: + return [{} for _ in queries] + # Preserve the full entity description for semantic retrieval. The + # normalized category is used independently for exact-category ranking; + # embedding only "desk" discards qualifiers such as "open wooden work" + # and can rank semantically adjacent chairs above the requested table. + keys = [query.query.strip() or query.normalized_category or "object" for query in queries] + missing = list(dict.fromkeys(key for key in keys if key not in self._query_vector_cache)) + if missing: + vectors = self._embedding_provider.encode_queries(missing) + self._query_vector_cache.update(zip(missing, vectors, strict=True)) + matrix = np.ascontiguousarray(np.stack([self._query_vector_cache[key] for key in keys])) + distances, identifiers = self._faiss.search(matrix, limit) + return [ + { + int(identifier): max(0.0, min(1.0, (float(distance) + 1.0) / 2.0)) + for distance, identifier in zip(row_distances, row_ids, strict=True) + if identifier >= 0 + } + for row_distances, row_ids in zip(distances, identifiers, strict=True) + ] + + @staticmethod + def _dimension_fit( + expected: tuple[float, float, float] | None, + actual: tuple[float, float, float] | None, + confidence: float | None, + ) -> float: + if expected is None or actual is None: + return 0.5 + direct = sum( + abs(math.log(a / b)) for a, b in zip(actual, expected, strict=True) + ) / 3 + swapped = ( + abs(math.log(actual[0] / expected[1])) + + abs(math.log(actual[1] / expected[0])) + + abs(math.log(actual[2] / expected[2])) + ) / 3 + fit = math.exp(-min(direct, swapped)) + return fit * (confidence if confidence is not None else 0.2) + + def batch_search( + self, + queries: Sequence[AssetQuery], + *, + limit: int = 5, + candidate_limit: int = FTS_LIMIT, + ) -> list[list[RetrievalResult]]: + semantic = self._semantic_batch(queries, min(candidate_limit, ANN_LIMIT)) + all_results: list[list[RetrievalResult]] = [] + for query, semantic_scores in zip(queries, semantic, strict=True): + started = time.perf_counter() + lexical_scores = self._lexical(query, min(candidate_limit, FTS_LIMIT)) + candidate_ids = set(lexical_scores) | set(semantic_scores) + exact_rows = self._connection.execute( + """ + SELECT row_id FROM assets WHERE admission_status = 'ACTIVE' + AND (asset_id = ? OR normalized_category = ?) LIMIT 200 + """, + (query.asset_id or "", query.normalized_category or ""), + ).fetchall() + candidate_ids.update(int(row[0]) for row in exact_rows) + if not candidate_ids: + all_results.append([]) + self.query_latencies_ms.append((time.perf_counter() - started) * 1000) + continue + placeholders = ",".join("?" for _ in candidate_ids) + rows = self._connection.execute( + f"SELECT * FROM assets WHERE row_id IN ({placeholders}) " + "AND admission_status = 'ACTIVE' AND asset_kind = ?", + (*sorted(candidate_ids), query.asset_kind.value), + ).fetchall() + source_rank = { + _source_key(source): (len(query.source_priority) - index) + / max(1, len(query.source_priority)) + for index, source in enumerate(query.source_priority) + } + results = [] + for row in rows: + record = AssetRecord.model_validate_json(row["record_json"]) + row_id = int(row["row_id"]) + dimensions = ( + tuple(json.loads(row["dimensions_json"])) + if row["dimensions_json"] + else None + ) + dimension_fit = self._dimension_fit( + query.dimensions_m, dimensions, row["dimension_confidence"] + ) + quality = {"A": 1.0, "B": 0.66, "C": 0.33, "REJECTED": 0.0}[ + row["quality_tier"] + ] + source_score = source_rank.get(_source_key(row["source"]), 0.0) + lexical = lexical_scores.get(row_id, 0.0) + semantic_score = semantic_scores.get(row_id, 0.0) + score = ( + 0.35 * lexical + + 0.25 * semantic_score + + 0.20 * dimension_fit + + 0.10 * quality + + 0.10 * source_score + ) + exact_id = bool(query.asset_id and query.asset_id == row["asset_id"]) + exact_category = bool( + query.normalized_category + and query.normalized_category == row["normalized_category"] + ) + results.append( + RetrievalResult( + record=record, + score=score, + lexical_score=lexical, + semantic_score=semantic_score, + dimension_fit=dimension_fit, + quality_score=quality, + source_priority_score=source_score, + exact_id=exact_id, + exact_category=exact_category, + ) + ) + results.sort( + key=lambda item: ( + not item.exact_id, + not item.exact_category, + -item.score, + item.record.asset_id, + ) + ) + all_results.append(results[:limit]) + self.query_latencies_ms.append((time.perf_counter() - started) * 1000) + return all_results + + def timing_report(self) -> dict[str, float | int]: + values = sorted(self.query_latencies_ms) + p95_index = max(0, math.ceil(len(values) * 0.95) - 1) + return { + "cold_load_ms": round(self.load_time_ms, 3), + "hot_query_count": len(values), + "hot_query_p95_ms": round(values[p95_index], 3) if values else 0.0, + "hot_query_max_ms": round(max(values), 3) if values else 0.0, + } + + +def write_index_manifest( + output_dir: Path, + *, + records: Sequence[AssetRecord], + active_records: Sequence[AssetRecord], + embedding_provider: EmbeddingProvider, + build_duration_s: float, +) -> Path: + sqlite_path = output_dir / "asset_index.sqlite3" + vector_path = output_dir / "asset_vectors.faiss" + by_kind = { + kind.value: sum(record.asset_kind == kind for record in active_records) + for kind in AssetKind + } + low_confidence = sum( + record.dimensions_m is not None and (record.dimension_confidence or 0) < 0.5 + for record in records + ) + payload = { + "schema_version": "1.1", + "catalog_records": len(records), + "active_records": len(active_records), + "cold_records": len(records) - len(active_records), + "active_by_kind": by_kind, + "low_confidence_dimension_records": low_confidence, + "embedding_model": embedding_provider.model_name, + "embedding_dimension": embedding_provider.dimension, + "hnsw": { + "M": HNSW_M, + "efConstruction": HNSW_EF_CONSTRUCTION, + "efSearch": HNSW_EF_SEARCH, + "metric": "inner_product_cosine_normalized", + }, + "retrieval": { + "lexical_top_k": FTS_LIMIT, + "ann_top_k": ANN_LIMIT, + "weights": { + "lexical": 0.35, + "semantic": 0.25, + "dimension_fit": 0.20, + "quality": 0.10, + "source_priority": 0.10, + }, + }, + "files": { + sqlite_path.name: _sha256(sqlite_path), + vector_path.name: _sha256(vector_path), + }, + "build_duration_s": round(build_duration_s, 3), + } + path = output_dir / "asset_index_manifest.json" + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return path diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/ingestion.py b/docs/reproduction/public_conversion_code/packages/asset_registry/ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..61370d6644302f7e16e2fe713d4fa47c3cbf3cb0 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/ingestion.py @@ -0,0 +1,453 @@ +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import urllib.error +import urllib.request +import uuid +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime +from enum import StrEnum +from pathlib import Path, PurePosixPath +from typing import Literal + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.core.files import atomic_write_text + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class SourceAccess(StrEnum): + OPEN = "open" + GATED = "gated" + MANUAL_AGREEMENT = "manual_agreement" + LICENSE_REVIEW = "license_review" + + +class DownloadArtifact(_StrictModel): + artifact_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$") + url: str + relative_path: str + expected_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") + expected_md5: str | None = Field(default=None, pattern=r"^[0-9a-f]{32}$") + expected_size_bytes: int | None = Field(default=None, gt=0) + + @model_validator(mode="after") + def validate_relative_path(self) -> DownloadArtifact: + path = PurePosixPath(self.relative_path) + if path.is_absolute() or ".." in path.parts or not path.name: + raise ValueError("artifact relative_path must stay inside its raw version directory") + return self + + +class AssetSourceSpec(_StrictModel): + source_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$") + display_name: str + descriptor_source_aliases: list[str] = Field(default_factory=list) + version: str + purpose: list[str] = Field(default_factory=list) + ingestion_priority: int = Field(default=100, ge=1) + license_id: str + license_url: str + access: SourceAccess + registration_required: bool = False + auto_download_allowed: bool = False + download_method: str + source_url: str + official_size_bytes: int | None = Field(default=None, gt=0) + current_local_path: str | None = None + current_local_size_bytes: int | None = Field(default=None, ge=0) + artifacts: list[DownloadArtifact] = Field(default_factory=list) + notes: list[str] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_access_policy(self) -> AssetSourceSpec: + if self.access != SourceAccess.OPEN and self.auto_download_allowed: + raise ValueError("restricted sources cannot enable unattended download") + if self.auto_download_allowed and not self.artifacts: + raise ValueError("auto-download source requires explicit versioned artifacts") + return self + + +class SourceRegistry(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + generated_for: str = "RoboHouseGen" + sources: list[AssetSourceSpec] + + @model_validator(mode="after") + def validate_source_ids(self) -> SourceRegistry: + ids = [source.source_id for source in self.sources] + if len(ids) != len(set(ids)): + raise ValueError("source registry IDs must be unique") + return self + + @classmethod + def from_yaml(cls, path: Path) -> SourceRegistry: + return cls.model_validate(yaml.safe_load(path.read_text(encoding="utf-8"))) + + def require(self, source_id: str) -> AssetSourceSpec: + for source in self.sources: + if source.source_id == source_id: + return source + raise KeyError(f"asset source is not registered: {source_id}") + + +class AssetStoreLayout(_StrictModel): + root: Path + raw: Path + staged: Path + certified: Path + quarantine: Path + manifests: Path + + @classmethod + def for_root(cls, root: Path) -> AssetStoreLayout: + resolved = root.resolve() + if resolved == Path(resolved.anchor): + raise ValueError("asset store root cannot be a filesystem root") + return cls( + root=resolved, + raw=resolved / "raw", + staged=resolved / "staged", + certified=resolved / "certified", + quarantine=resolved / "quarantine", + manifests=resolved / "manifests", + ) + + def initialize(self) -> None: + for path in (self.raw, self.staged, self.certified, self.quarantine, self.manifests): + path.mkdir(parents=True, exist_ok=True) + + +class LicenseBlockedError(RuntimeError): + pass + + +class ChecksumMismatchError(RuntimeError): + pass + + +class ResumeNotSupportedError(RuntimeError): + pass + + +class IngestArtifactResult(_StrictModel): + artifact_id: str + status: Literal["downloaded", "reused", "blocked", "failed", "staged", "duplicate"] + raw_path: str | None = None + staged_path: str | None = None + bytes: int = Field(default=0, ge=0) + sha256: str | None = None + resumed_from_bytes: int = Field(default=0, ge=0) + message: str = "" + + +class IngestRunManifest(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + run_id: str + source_id: str + source_version: str + source_license: str + license_url: str + authorization_record: str | None = None + authorization_record_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") + started_at: datetime + completed_at: datetime + asset_store_root: str + raw_immutable: Literal[True] = True + results: list[IngestArtifactResult] + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def md5_file(path: Path) -> str: + """Return a source checksum when an upstream catalog publishes only MD5. + + SHA-256 remains the content identity used by RoboHouseGen. MD5 is evaluated + only as an additional exact-byte check against the publisher's manifest. + """ + digest = hashlib.md5(usedforsecurity=False) + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +class AssetIngestor: + def __init__(self, layout: AssetStoreLayout, *, timeout_s: int = 120) -> None: + self.layout = layout + self.timeout_s = timeout_s + + @staticmethod + def _check_authorization(source: AssetSourceSpec, authorization_record: Path | None) -> None: + if source.access == SourceAccess.OPEN and not source.auto_download_allowed: + raise LicenseBlockedError( + f"{source.source_id} is plan-only until its version-pinned artifact manifest " + "is reviewed and auto_download_allowed is enabled" + ) + if source.access == SourceAccess.OPEN: + return + if authorization_record is None or not authorization_record.is_file(): + raise LicenseBlockedError( + f"{source.source_id} requires a local authorization record; " + "RoboHouseGen will not accept terms or supply credentials automatically" + ) + + def _raw_destination(self, source: AssetSourceSpec, artifact: DownloadArtifact) -> Path: + version_root = (self.layout.raw / source.source_id / source.version).resolve() + destination = (version_root / Path(*PurePosixPath(artifact.relative_path).parts)).resolve() + if version_root not in destination.parents: + raise ValueError("raw destination escaped source version root") + return destination + + def download( + self, + source: AssetSourceSpec, + artifact: DownloadArtifact, + *, + authorization_record: Path | None = None, + ) -> IngestArtifactResult: + self._check_authorization(source, authorization_record) + destination = self._raw_destination(source, artifact) + partial = destination.with_suffix(destination.suffix + ".part") + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + digest = sha256_file(destination) + if artifact.expected_sha256 and digest != artifact.expected_sha256: + raise ChecksumMismatchError( + f"existing immutable raw file hash differs: {destination}" + ) + if ( + artifact.expected_size_bytes + and destination.stat().st_size != artifact.expected_size_bytes + ): + raise ChecksumMismatchError( + f"existing immutable raw file size differs: {destination}" + ) + if artifact.expected_md5 and md5_file(destination) != artifact.expected_md5: + raise ChecksumMismatchError( + f"existing immutable raw file publisher checksum differs: {destination}" + ) + return IngestArtifactResult( + artifact_id=artifact.artifact_id, + status="reused", + raw_path=str(destination), + bytes=destination.stat().st_size, + sha256=digest, + ) + resume_from = partial.stat().st_size if partial.is_file() else 0 + request = urllib.request.Request( + artifact.url, + headers={ + "User-Agent": "RoboHouseGen-AssetIngest/1.0", + **({"Range": f"bytes={resume_from}-"} if resume_from else {}), + }, + ) + try: + response = urllib.request.urlopen(request, timeout=self.timeout_s) # noqa: S310 + except urllib.error.URLError as error: + raise RuntimeError(f"asset download failed: {artifact.url}: {error}") from error + status = getattr(response, "status", response.getcode()) + if resume_from and status != 206: + response.close() + raise ResumeNotSupportedError( + f"server did not honor Range for {artifact.artifact_id}; " + f"partial retained at {partial}" + ) + mode = "ab" if resume_from else "xb" + try: + with partial.open(mode) as handle, response: + shutil.copyfileobj(response, handle, length=4 * 1024 * 1024) + handle.flush() + os.fsync(handle.fileno()) + except FileExistsError as error: + raise RuntimeError(f"concurrent partial download detected: {partial}") from error + size = partial.stat().st_size + if artifact.expected_size_bytes is not None and size != artifact.expected_size_bytes: + raise ChecksumMismatchError( + f"download size mismatch for {artifact.artifact_id}: {size} != " + f"{artifact.expected_size_bytes}; partial retained" + ) + digest = sha256_file(partial) + if artifact.expected_md5 is not None and md5_file(partial) != artifact.expected_md5: + raise ChecksumMismatchError( + f"download publisher checksum mismatch for {artifact.artifact_id}; partial retained" + ) + if artifact.expected_sha256 is not None and digest != artifact.expected_sha256: + raise ChecksumMismatchError( + f"download checksum mismatch for {artifact.artifact_id}; partial retained" + ) + partial.replace(destination) + destination.chmod(0o444) + return IngestArtifactResult( + artifact_id=artifact.artifact_id, + status="downloaded", + raw_path=str(destination), + bytes=size, + sha256=digest, + resumed_from_bytes=resume_from, + ) + + def stage( + self, + source: AssetSourceSpec, + artifact: DownloadArtifact, + download: IngestArtifactResult, + ) -> IngestArtifactResult: + if not download.raw_path or not download.sha256: + raise ValueError("only a verified raw artifact can be staged") + raw = Path(download.raw_path).resolve() + expected_raw_root = (self.layout.raw / source.source_id / source.version).resolve() + if expected_raw_root not in raw.parents: + raise ValueError("raw artifact does not belong to this source version") + relative = raw.relative_to(expected_raw_root) + staged = (self.layout.staged / source.source_id / source.version / relative).resolve() + if staged.exists(): + if sha256_file(staged) != download.sha256: + raise FileExistsError(f"refusing to overwrite staged artifact: {staged}") + status: Literal["staged", "duplicate"] = "duplicate" + else: + staged.parent.mkdir(parents=True, exist_ok=True) + # Never hard-link staged data to raw: a converter that writes in + # place would otherwise mutate the supposedly immutable raw inode. + shutil.copy2(raw, staged) + staged.chmod(0o644) + status = "staged" + content_record = ( + self.layout.manifests / "content" / download.sha256[:2] / (download.sha256 + ".json") + ) + if not content_record.exists(): + content_record.parent.mkdir(parents=True, exist_ok=True) + atomic_write_text( + content_record, + json.dumps( + { + "schema_version": "1.0", + "sha256": download.sha256, + "first_raw_path": str(raw), + "source_id": source.source_id, + "source_version": source.version, + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + return IngestArtifactResult( + artifact_id=artifact.artifact_id, + status=status, + raw_path=str(raw), + staged_path=str(staged), + bytes=download.bytes, + sha256=download.sha256, + resumed_from_bytes=download.resumed_from_bytes, + ) + + def run( + self, + source: AssetSourceSpec, + *, + authorization_record: Path | None = None, + stage: bool = True, + workers: int = 1, + ) -> IngestRunManifest: + if not 1 <= workers <= 64: + raise ValueError("ingestion workers must be between 1 and 64") + self.layout.initialize() + started = datetime.now(UTC) + results: list[IngestArtifactResult] = [] + try: + self._check_authorization(source, authorization_record) + except LicenseBlockedError as error: + results.append( + IngestArtifactResult( + artifact_id="source-access", + status="blocked", + message=str(error), + ) + ) + access_blocked = bool(results and results[0].artifact_id == "source-access") + + def download_one(artifact: DownloadArtifact) -> IngestArtifactResult: + try: + return self.download(source, artifact, authorization_record=authorization_record) + except LicenseBlockedError as error: + return IngestArtifactResult( + artifact_id=artifact.artifact_id, + status="blocked", + message=str(error), + ) + except Exception as error: + return IngestArtifactResult( + artifact_id=artifact.artifact_id, + status="failed", + message=f"{type(error).__name__}:{error}", + ) + + if not access_blocked: + if workers == 1: + downloads = [download_one(artifact) for artifact in source.artifacts] + else: + # Download distinct immutable destinations concurrently, then stage + # in manifest order. Serial staging keeps the content-hash ledger + # deterministic even if two URLs resolve to identical bytes. + with ThreadPoolExecutor( + max_workers=workers, + thread_name_prefix=f"ingest-{source.source_id}", + ) as executor: + downloads = list(executor.map(download_one, source.artifacts)) + for artifact, downloaded in zip(source.artifacts, downloads, strict=True): + if stage and downloaded.status in {"downloaded", "reused"}: + try: + results.append(self.stage(source, artifact, downloaded)) + except Exception as error: + results.append( + IngestArtifactResult( + artifact_id=artifact.artifact_id, + status="failed", + raw_path=downloaded.raw_path, + bytes=downloaded.bytes, + sha256=downloaded.sha256, + resumed_from_bytes=downloaded.resumed_from_bytes, + message=f"{type(error).__name__}:{error}", + ) + ) + else: + results.append(downloaded) + completed = datetime.now(UTC) + run_id = completed.strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8] + manifest = IngestRunManifest( + run_id=run_id, + source_id=source.source_id, + source_version=source.version, + source_license=source.license_id, + license_url=source.license_url, + authorization_record=( + str(authorization_record.resolve()) if authorization_record else None + ), + authorization_record_sha256=( + sha256_file(authorization_record) + if authorization_record is not None and authorization_record.is_file() + else None + ), + started_at=started, + completed_at=completed, + asset_store_root=str(self.layout.root), + results=results, + ) + destination = self.layout.manifests / source.source_id / source.version / f"{run_id}.json" + destination.parent.mkdir(parents=True, exist_ok=True) + atomic_write_text(destination, manifest.model_dump_json(indent=2) + "\n") + return manifest diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/models.py b/docs/reproduction/public_conversion_code/packages/asset_registry/models.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1ab9b26d79ee290902875a330fdb83bcf68400 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/models.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import re +from enum import StrEnum +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +class AssetKind(StrEnum): + OBJECT = "OBJECT" + ROOM = "ROOM" + MATERIAL = "MATERIAL" + LIGHTING = "LIGHTING" + + +class DimensionSource(StrEnum): + MEASURED = "MEASURED" + UPSTREAM = "UPSTREAM" + CATEGORY_MEDIAN = "CATEGORY_MEDIAN" + DEFAULT = "DEFAULT" + + +class AdmissionStatus(StrEnum): + ACTIVE = "ACTIVE" + COLD = "COLD" + REJECTED = "REJECTED" + + +class MountType(StrEnum): + FLOOR = "FLOOR" + WALL = "WALL" + CEILING = "CEILING" + SURFACE = "SURFACE" + FREE = "FREE" + + +class AssetFile(BaseModel): + model_config = ConfigDict(extra="forbid") + relative_path: str + source_url: str + md5: str + size_bytes: int = Field(ge=0) + + +class GeometryMetadata(BaseModel): + model_config = ConfigDict(extra="forbid") + bbox_min_m: tuple[float, float, float] | None = None + bbox_max_m: tuple[float, float, float] | None = None + footprint_m: tuple[float, float] | None = None + ground_offset_m: float | None = None + meters_per_unit: float = Field(default=1.0, gt=0) + up_axis: Literal["X", "Y", "Z"] = "Z" + forward_axis: Literal["+X", "-X", "+Y", "-Y", "+Z", "-Z"] = "+Y" + + @model_validator(mode="after") + def validate_bounds(self) -> GeometryMetadata: + if (self.bbox_min_m is None) != (self.bbox_max_m is None): + raise ValueError("bbox_min_m and bbox_max_m must be provided together") + if self.bbox_min_m is not None and self.bbox_max_m is not None: + if any( + low >= high + for low, high in zip(self.bbox_min_m, self.bbox_max_m, strict=True) + ): + raise ValueError("geometry bbox must have positive extent") + if self.footprint_m is not None and any(value <= 0 for value in self.footprint_m): + raise ValueError("footprint_m values must be positive") + return self + + +class PlacementMetadata(BaseModel): + model_config = ConfigDict(extra="forbid") + mount: MountType = MountType.FLOOR + support_surfaces: list[str] = Field(default_factory=list) + receptacle_dimensions_m: tuple[float, float, float] | None = None + approach_clearance_m: tuple[float, float, float] | None = None + + +class JointSummary(BaseModel): + model_config = ConfigDict(extra="forbid") + joint_count: int = Field(default=0, ge=0) + joint_names: list[str] = Field(default_factory=list) + joint_types: list[str] = Field(default_factory=list) + + +IDENTITY_MATRIX_4X4 = ( + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, +) + + +class RuntimeCompatibility(BaseModel): + model_config = ConfigDict(extra="forbid") + canonical_usd_path: str | None = None + proxy_gltf_path: str | None = None + proxy_sdf_path: str | None = None + proxy_to_canonical: tuple[float, ...] = IDENTITY_MATRIX_4X4 + compatible_backends: list[str] = Field(default_factory=list) + articulation: bool = False + joint_summary: JointSummary = Field(default_factory=JointSummary) + has_collision: bool = False + + @model_validator(mode="after") + def validate_transform(self) -> RuntimeCompatibility: + if len(self.proxy_to_canonical) != 16: + raise ValueError("proxy_to_canonical must be a row-major 4x4 matrix") + return self + + +class AssetRecord(BaseModel): + model_config = ConfigDict(extra="forbid") + schema_version: Literal["1.0", "1.1"] = "1.1" + asset_id: str + scene_name: str | None = None + display_name: str + description: str = "" + source: str + source_license: str + category: str + tags: list[str] + files: list[AssetFile] + usd_path: str + dimensions_m: tuple[float, float, float] | None = None + quality_tier: Literal["A", "B", "C", "REJECTED"] = "B" + scoring_allowed: bool = False + qa_status: Literal["DOWNLOADED", "CONVERTED", "ISAAC_VALIDATED", "REJECTED"] = ( + "DOWNLOADED" + ) + + asset_kind: AssetKind = AssetKind.OBJECT + normalized_category: str | None = None + synonyms: list[str] = Field(default_factory=list) + affordances: list[str] = Field(default_factory=list) + geometry_metadata: GeometryMetadata | None = None + dimension_source: DimensionSource | None = None + dimension_confidence: float | None = Field(default=None, ge=0, le=1) + placement_metadata: PlacementMetadata | None = None + runtime_compatibility: RuntimeCompatibility | None = None + admission_status: AdmissionStatus | None = None + exclusion_reasons: list[str] = Field(default_factory=list) + content_hash: str | None = None + canonical_asset_id: str | None = None + + @model_validator(mode="after") + def validate_record(self) -> AssetRecord: + if self.dimensions_m is not None and any(value <= 0 for value in self.dimensions_m): + raise ValueError("asset dimensions must be positive meters") + if self.scene_name is not None and not re.fullmatch( + r"[A-Za-z_][A-Za-z0-9_]*", self.scene_name + ): + raise ValueError("scene_name must be a valid USD identifier") + if self.dimension_source is not None and self.dimensions_m is None: + raise ValueError("dimension_source requires dimensions_m") + if self.dimension_confidence is not None and self.dimensions_m is None: + raise ValueError("dimension_confidence requires dimensions_m") + if self.admission_status == AdmissionStatus.ACTIVE and self.exclusion_reasons: + raise ValueError("ACTIVE assets cannot have exclusion_reasons") + return self + + def to_robolab_catalog_entry(self) -> RoboLabCatalogEntry: + if self.dimensions_m is None: + raise ValueError( + f"asset {self.asset_id!r} has no dimensions_m and cannot be exported to RoboLab" + ) + if self.scene_name is None: + raise ValueError( + f"asset {self.asset_id!r} has no scene_name and cannot be exported to RoboLab" + ) + return RoboLabCatalogEntry.model_validate( + { + "name": self.scene_name, + "usd_path": self.usd_path, + "class": self.category, + "description": self.description or self.display_name, + "dims": self.dimensions_m, + } + ) + + +class RoboLabCatalogEntry(BaseModel): + """Exact object-catalog projection consumed by RoboLab scene-gen.""" + + model_config = ConfigDict(extra="forbid", populate_by_name=True, serialize_by_alias=True) + name: str + usd_path: str + asset_class: str = Field(alias="class") + description: str + dims: tuple[float, float, float] + + @model_validator(mode="after") + def validate_dims(self) -> RoboLabCatalogEntry: + if any(value <= 0 for value in self.dims): + raise ValueError("RoboLab dims must contain positive meters") + return self + + +class AssetCatalog(BaseModel): + model_config = ConfigDict(extra="forbid") + schema_version: Literal["1.0", "1.1"] = "1.1" + source: str + assets: list[AssetRecord] diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/multiview.py b/docs/reproduction/public_conversion_code/packages/asset_registry/multiview.py new file mode 100644 index 0000000000000000000000000000000000000000..207e2894ea3af1c5ebce5f14d3d2f3cff2988f2e --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/multiview.py @@ -0,0 +1,449 @@ +from __future__ import annotations + +import hashlib +import json +import math +import os +import subprocess +import uuid +from collections.abc import Sequence +from pathlib import Path +from typing import Any, Literal, Protocol + +from PIL import Image, ImageDraw, ImageFont +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.asset_registry.certification_models import ( + CardinalAxis, + FrontAxis, + FrontEvidence, + SymmetryType, +) +from packages.core.files import atomic_write_text + +TURN_TABLE_AXES = ( + "+X", + "+X+Y", + "+Y", + "-X+Y", + "-X", + "-X-Y", + "-Y", + "+X-Y", +) +OPPOSITE: dict[CardinalAxis, CardinalAxis] = { + "+X": "-X", + "-X": "+X", + "+Y": "-Y", + "-Y": "+Y", +} + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class TurntableView(_StrictModel): + index: int = Field(ge=0, le=7) + camera_side: str + image_uri: str + image_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + + +class TurntableManifest(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + asset_id: str + asset_uri: str + asset_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + render_uri: str | None = None + render_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") + render_repair: str | None = None + geometry_identity_preserved: Literal[True] | None = None + renderer: str + material_aware: Literal[True] = True + canonical_transform: tuple[float, ...] | None = None + canonical_transform_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") + views: list[TurntableView] = Field(min_length=8, max_length=8) + contact_sheet_uri: str + contact_sheet_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + + @model_validator(mode="after") + def validate_view_order(self) -> TurntableManifest: + if [item.index for item in self.views] != list(range(8)): + raise ValueError("turntable views must be ordered 0..7") + if tuple(item.camera_side for item in self.views) != TURN_TABLE_AXES: + raise ValueError("turntable camera-side labels differ from the canonical order") + if (self.canonical_transform is None) != (self.canonical_transform_sha256 is None): + raise ValueError("canonical transform and its hash must be present together") + if self.canonical_transform is not None: + if len(self.canonical_transform) != 16 or not all( + math.isfinite(value) for value in self.canonical_transform + ): + raise ValueError("canonical transform must contain 16 finite values") + digest = hashlib.sha256( + json.dumps(list(self.canonical_transform), separators=(",", ":")).encode() + ).hexdigest() + if digest != self.canonical_transform_sha256: + raise ValueError("canonical transform hash differs") + runtime_fields = ( + self.render_uri, + self.render_sha256, + self.geometry_identity_preserved, + ) + if any(value is not None for value in runtime_fields) and not all( + value is not None for value in runtime_fields + ): + raise ValueError("render derivative fields must be present together") + return self + + +class AutonomousFrontVote(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + visual_front_axis: FrontAxis + functional_front_axis: FrontAxis + back_axis: FrontAxis + symmetry_type: SymmetryType + confidence: float = Field(ge=0.0, le=1.0) + decisive_view_indices: list[int] = Field(default_factory=list) + visible_cues: list[str] = Field(default_factory=list) + reasoning: str + + @model_validator(mode="after") + def validate_axes(self) -> AutonomousFrontVote: + cardinal = {"+X", "-X", "+Y", "-Y"} + if ( + self.functional_front_axis in cardinal + and self.back_axis + != OPPOSITE[ + self.functional_front_axis # type: ignore[index] + ] + ): + raise ValueError("back_axis must oppose a cardinal functional_front_axis") + if any(index < 0 or index > 7 for index in self.decisive_view_indices): + raise ValueError("decisive view indices must be in 0..7") + return self + + +class ImageAnalysisClient(Protocol): + def analyze_image(self, source: Path, prompt: str) -> str: ... + + +def _contact_sheet(view_paths: Sequence[Path], output: Path, asset_id: str) -> None: + if len(view_paths) != 8: + raise ValueError("eight turntable images are required") + tile = 320 + label_height = 34 + sheet = Image.new("RGB", (4 * tile, 2 * (tile + label_height)), (244, 244, 242)) + draw = ImageDraw.Draw(sheet) + font = ImageFont.load_default() + for index, (path, camera_side) in enumerate(zip(view_paths, TURN_TABLE_AXES, strict=True)): + row, column = divmod(index, 4) + x = column * tile + y = row * (tile + label_height) + with Image.open(path) as source: + image = source.convert("RGB") + image.thumbnail((tile - 8, tile - 8)) + sheet.paste(image, (x + (tile - image.width) // 2, y + (tile - image.height) // 2)) + draw.rectangle((x, y, x + tile - 1, y + tile - 1), outline=(70, 70, 70), width=2) + draw.text( + (x + 6, y + tile + 7), + f"view {index}: camera on {camera_side}", + fill=(20, 20, 20), + font=font, + ) + draw.text((8, 4), asset_id[:100], fill=(10, 10, 10), font=font) + sheet.save(output, format="PNG", optimize=True) + + +def render_material_turntable( + *, + asset_id: str, + asset_path: Path, + asset_sha256: str, + output_dir: Path, + blender: Path, + renderer_script: Path | None = None, + canonical_transform: Sequence[float] | None = None, + render_path: Path | None = None, + render_sha256: str | None = None, + render_repair: str | None = None, +) -> TurntableManifest: + """Render an immutable eight-view, material-aware turntable in Blender.""" + + asset_path = asset_path.resolve() + output_dir = output_dir.resolve() + blender = blender.resolve() + script = ( + renderer_script + or Path(__file__).resolve().parents[2] / "scripts" / "blender_render_asset_turntable.py" + ).resolve() + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite turntable output: {output_dir}") + if not asset_path.is_file() or not blender.is_file() or not script.is_file(): + missing = [str(path) for path in (asset_path, blender, script) if not path.is_file()] + raise FileNotFoundError(f"turntable input is missing: {missing}") + if asset_path.suffix.casefold() in {".glb", ".gltf"} and canonical_transform is None: + raise ValueError("GLB/GLTF turntables require the descriptor canonical transform") + canonical_values = ( + tuple(float(value) for value in canonical_transform) + if canonical_transform is not None + else None + ) + if canonical_values is not None and ( + len(canonical_values) != 16 or not all(math.isfinite(value) for value in canonical_values) + ): + raise ValueError("canonical transform must contain 16 finite values") + actual_asset_sha256 = sha256_file(asset_path) + if actual_asset_sha256 != asset_sha256: + raise ValueError(f"asset hash differs: {actual_asset_sha256} != {asset_sha256}") + runtime_path = render_path.resolve() if render_path is not None else asset_path + if not runtime_path.is_file(): + raise FileNotFoundError(runtime_path) + actual_render_sha256 = sha256_file(runtime_path) + if render_path is not None: + if render_sha256 is None: + raise ValueError("render derivative requires its SHA-256") + if actual_render_sha256 != render_sha256: + raise ValueError("render derivative hash differs") + elif render_sha256 is not None or render_repair is not None: + raise ValueError("render derivative metadata was supplied without a path") + + output_dir.parent.mkdir(parents=True, exist_ok=True) + staging = output_dir.parent / f".{output_dir.name}.tmp-{uuid.uuid4().hex[:12]}" + staging.mkdir(parents=False, exist_ok=False) + command = [ + str(blender), + "--background", + "--factory-startup", + "--python", + str(script), + "--", + "--asset", + str(runtime_path), + "--output", + str(staging), + ] + if canonical_values is not None: + command.extend( + [ + "--canonical-transform-json", + json.dumps(list(canonical_values), separators=(",", ":")), + ] + ) + completed = subprocess.run(command, capture_output=True, text=True, check=False) + atomic_write_text( + staging / "blender.log", + completed.stdout + ("\n[stderr]\n" + completed.stderr if completed.stderr else ""), + ) + if completed.returncode: + raise RuntimeError( + f"Blender turntable failed with code {completed.returncode}; " + f"log={staging / 'blender.log'}" + ) + renderer_report_path = staging / "renderer_report.json" + report = json.loads(renderer_report_path.read_text(encoding="utf-8")) + view_paths = [staging / f"view_{index:02d}.png" for index in range(8)] + if any(not path.is_file() for path in view_paths): + raise RuntimeError("Blender did not produce all eight canonical views") + contact_sheet = staging / "contact_sheet.png" + _contact_sheet(view_paths, contact_sheet, asset_id) + views = [ + TurntableView( + index=index, + camera_side=TURN_TABLE_AXES[index], + image_uri=path.name, + image_sha256=sha256_file(path), + ) + for index, path in enumerate(view_paths) + ] + manifest = TurntableManifest( + asset_id=asset_id, + asset_uri=str(asset_path), + asset_sha256=asset_sha256, + render_uri=(str(runtime_path) if render_path is not None else None), + render_sha256=(actual_render_sha256 if render_path is not None else None), + render_repair=render_repair, + geometry_identity_preserved=(True if render_path is not None else None), + renderer=f"Blender/{report['blender_version']} material-turntable-v1", + canonical_transform=canonical_values, + canonical_transform_sha256=( + hashlib.sha256( + json.dumps(list(canonical_values), separators=(",", ":")).encode() + ).hexdigest() + if canonical_values is not None + else None + ), + views=views, + contact_sheet_uri=contact_sheet.name, + contact_sheet_sha256=sha256_file(contact_sheet), + ) + atomic_write_text( + staging / "turntable_manifest.json", + manifest.model_dump_json(indent=2) + "\n", + ) + if output_dir.exists(): + raise FileExistsError(f"turntable destination appeared during render: {output_dir}") + os.replace(staging, output_dir) + return manifest + + +def _json_object(raw: str) -> dict[str, Any]: + candidate = raw.strip() + if candidate.startswith("```"): + lines = candidate.splitlines() + candidate = "\n".join(lines[1:-1]).strip() + decoder = json.JSONDecoder() + for index, character in enumerate(candidate): + if character != "{": + continue + try: + value, _ = decoder.raw_decode(candidate[index:]) + except json.JSONDecodeError: + continue + if isinstance(value, dict): + return value + raise ValueError("multimodal response contains no JSON object") + + +def parse_front_vote(raw: str) -> AutonomousFrontVote: + return AutonomousFrontVote.model_validate(_json_object(raw)) + + +def front_vote_prompt(*, category: str, definition: str) -> str: + return ( + "You are certifying the usable front of one immutable 3D asset from an " + "eight-view material-aware turntable.\n" + f"Category: {category}\n" + f"Category-specific definition: {definition}\n\n" + "The sheet labels camera positions, not viewing directions: a camera on +Y " + "shows the asset's +Y side. Cardinal answers must be one of +X, -X, +Y, " + "-Y. Use NONE only when the category truly has no directional front; use " + "AMBIGUOUS when evidence is insufficient. For cabinets, refrigerators, " + "drawers, and appliances, functional_front_axis is the side with doors, " + "drawers, handles, controls, or other operation affordances. back_axis must " + "be the exact opposite of a cardinal functional front. Inspect materials " + "and small cues rather than relying on silhouette alone.\n\n" + "Return exactly one JSON object with these keys and no markdown: " + 'schema_version="1.0", visual_front_axis, functional_front_axis, back_axis, ' + "symmetry_type (NONE, ROTATIONAL, MIRROR, ROTATIONAL_AND_MIRROR, or " + "UNKNOWN), confidence (0..1), decisive_view_indices (array of 0..7), " + "visible_cues (array of short strings), reasoning (short string). Do not " + "invent a front when cues conflict." + ) + + +def analyze_turntable_front( + *, + manifest: TurntableManifest, + turntable_root: Path, + category: str, + definition: str, + client: ImageAnalysisClient, + output_dir: Path, +) -> AutonomousFrontVote: + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite autonomous front analysis: {output_dir}") + sheet = (turntable_root / manifest.contact_sheet_uri).resolve() + if sha256_file(sheet) != manifest.contact_sheet_sha256: + raise ValueError("turntable contact sheet hash differs from its manifest") + raw = client.analyze_image(sheet, front_vote_prompt(category=category, definition=definition)) + vote = parse_front_vote(raw) + output_dir.mkdir(parents=True, exist_ok=False) + atomic_write_text(output_dir / "vlm_raw_response.txt", raw.rstrip() + "\n") + atomic_write_text(output_dir / "front_vote.json", vote.model_dump_json(indent=2) + "\n") + atomic_write_text( + output_dir / "analysis_provenance.json", + json.dumps( + { + "schema_version": "1.0", + "asset_id": manifest.asset_id, + "asset_sha256": manifest.asset_sha256, + "turntable_manifest_sha256": sha256_file( + turntable_root / "turntable_manifest.json" + ), + "contact_sheet_sha256": manifest.contact_sheet_sha256, + "human_review_used": False, + "adjudication": "automatic_vlm_material_turntable_v1", + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + return vote + + +def evidence_from_front_vote( + manifest: TurntableManifest, + vote: AutonomousFrontVote, + *, + analysis_uri: str, +) -> list[FrontEvidence]: + note = "; ".join(vote.visible_cues[:6]) or vote.reasoning + evidence = [ + FrontEvidence( + evidence_id=f"turntable:{manifest.asset_sha256}:functional", + kind="multiview", + target="functional_front", + axis=vote.functional_front_axis, + source_uri=analysis_uri, + source_hash=manifest.contact_sheet_sha256, + confidence=vote.confidence, + note=note, + ), + FrontEvidence( + evidence_id=f"vlm:{manifest.asset_sha256}:functional", + kind="vlm_vote", + target="functional_front", + axis=vote.functional_front_axis, + source_uri=analysis_uri, + source_hash=manifest.contact_sheet_sha256, + confidence=vote.confidence, + note=note, + ), + FrontEvidence( + evidence_id=f"turntable:{manifest.asset_sha256}:visual", + kind="multiview", + target="visual_front", + axis=vote.visual_front_axis, + source_uri=analysis_uri, + source_hash=manifest.contact_sheet_sha256, + confidence=vote.confidence, + note=note, + ), + FrontEvidence( + evidence_id=f"turntable:{manifest.asset_sha256}:back", + kind="multiview", + target="back_axis", + axis=vote.back_axis, + source_uri=analysis_uri, + source_hash=manifest.contact_sheet_sha256, + confidence=vote.confidence, + note=note, + ), + ] + if vote.functional_front_axis == "NONE" or vote.symmetry_type in { + SymmetryType.ROTATIONAL, + SymmetryType.ROTATIONAL_AND_MIRROR, + }: + evidence.append( + FrontEvidence( + evidence_id=f"turntable:{manifest.asset_sha256}:symmetry", + kind="symmetry", + target="symmetry", + axis="NONE", + source_uri=analysis_uri, + source_hash=manifest.contact_sheet_sha256, + confidence=vote.confidence, + note=note, + ) + ) + return evidence diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/native_usd.py b/docs/reproduction/public_conversion_code/packages/asset_registry/native_usd.py new file mode 100644 index 0000000000000000000000000000000000000000..27d3d16b4ec158df27f5ea7bc0ab8aab8448f584 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/native_usd.py @@ -0,0 +1,669 @@ +from __future__ import annotations + +import json +import math +import shutil +from pathlib import Path +from typing import Any + + +def _copy_canonical_asset_bundle( + canonical: Path, candidate: dict[str, Any], packaged_dir: Path +) -> Path: + """Copy one canonical USD and its asset-specific external textures. + + Some converted libraries keep every USD in one aggregate ``usd/`` directory + while the source textures remain under the individual downloaded asset. A + recursive copy of the aggregate directory both bloats every entity bundle + and leaves ``./textures`` unresolved. Prefer the source archive's sibling + asset tree when it exposes a texture directory; retain the legacy complete + sibling-directory copy for libraries that are already self-contained. + """ + source_roots: list[Path] = [] + for record in candidate.get("files") or []: + if not isinstance(record, dict): + continue + declared = Path(str(record.get("relative_path") or "")) + if declared.is_file(): + source_roots.append(declared.parent) + texture_roots = [ + root / relative + for root in source_roots + for relative in ( + Path("model/materials/textures"), + Path("materials/textures"), + Path("textures"), + ) + ] + source_textures = next((path for path in texture_roots if path.is_dir()), None) + if source_textures is None: + shutil.copytree(canonical.parent, packaged_dir, dirs_exist_ok=True) + else: + packaged_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(canonical, packaged_dir / canonical.name) + shutil.copytree( + source_textures, packaged_dir / "textures", dirs_exist_ok=True + ) + return packaged_dir / canonical.name + + +def validate_articulation_couplings(value: object) -> dict[str, list[dict[str, Any]]]: + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("articulation_couplings must be an object") + normalized: dict[str, list[dict[str, Any]]] = {} + for entity_id, couplings in value.items(): + if not isinstance(entity_id, str) or not isinstance(couplings, list) or not couplings: + raise ValueError("each articulation coupling entry requires an entity and list") + normalized[entity_id] = [] + for coupling in couplings: + if not isinstance(coupling, dict): + raise ValueError(f"invalid articulation coupling for {entity_id}") + required = {"coupling_id", "input_joint", "output_joint", "gear_ratio"} + optional = {"implementation"} + if not required <= set(coupling) or set(coupling) - required - optional: + raise ValueError( + f"articulation coupling {entity_id} requires {sorted(required)} " + f"and optional {sorted(optional)}" + ) + ratio = float(coupling["gear_ratio"]) + if ratio == 0: + raise ValueError("articulation gear_ratio must be non-zero") + implementation = str(coupling.get("implementation", "GEAR")).upper() + if implementation not in {"GEAR", "MIMIC"}: + raise ValueError("articulation coupling implementation must be GEAR or MIMIC") + normalized[entity_id].append( + { + "coupling_id": str(coupling["coupling_id"]), + "input_joint": str(coupling["input_joint"]).strip("/"), + "output_joint": str(coupling["output_joint"]).strip("/"), + "gear_ratio": ratio, + "implementation": implementation, + } + ) + return normalized + + +def validate_canonical_scale_overrides( + value: object, +) -> dict[str, tuple[float, float, float]]: + """Validate per-entity scale corrections applied to canonical USD references.""" + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("canonical_scale_overrides must be an object") + normalized: dict[str, tuple[float, float, float]] = {} + for entity_id, scale in value.items(): + if not isinstance(entity_id, str) or not entity_id: + raise ValueError("canonical scale override requires a non-empty entity id") + if not isinstance(scale, (list, tuple)) or len(scale) != 3: + raise ValueError( + f"canonical scale override for {entity_id} must contain exactly 3 values" + ) + vector = tuple(float(item) for item in scale) + if any(item <= 0 for item in vector): + raise ValueError( + f"canonical scale override for {entity_id} must be strictly positive" + ) + normalized[entity_id] = vector + return normalized + + +def validate_canonical_yaw_overrides(value: object) -> dict[str, float]: + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("canonical_yaw_overrides must be an object") + result: dict[str, float] = {} + for entity_id, yaw in value.items(): + if not isinstance(entity_id, str) or not entity_id: + raise ValueError("canonical yaw override requires a non-empty entity id") + angle = float(yaw) + if not math.isfinite(angle) or abs(angle) > 360: + raise ValueError( + f"canonical yaw override for {entity_id} must be finite in [-360, 360]" + ) + result[entity_id] = angle + return result + + +def validate_canonical_rotation_overrides( + value: object, +) -> dict[str, tuple[float, float, float]]: + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("canonical_rotation_overrides must be an object") + result: dict[str, tuple[float, float, float]] = {} + for entity_id, rotation in value.items(): + if not isinstance(entity_id, str) or not entity_id: + raise ValueError("canonical rotation override requires a non-empty entity id") + if not isinstance(rotation, (list, tuple)) or len(rotation) != 3: + raise ValueError( + f"canonical rotation override for {entity_id} must contain exactly 3 values" + ) + vector = tuple(float(item) for item in rotation) + if any(not math.isfinite(item) or abs(item) > 360 for item in vector): + raise ValueError( + f"canonical rotation override for {entity_id} must be finite in [-360, 360]" + ) + result[entity_id] = vector + return result + + +def validate_canonical_ground_alignment_overrides(value: object) -> dict[str, float]: + """Validate explicit post-orientation ground lifts for canonical assets.""" + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("canonical_ground_alignment_overrides must be an object") + result: dict[str, float] = {} + for entity_id, offset in value.items(): + if not isinstance(entity_id, str) or not entity_id: + raise ValueError("canonical ground alignment override requires an entity id") + distance = float(offset) + if not math.isfinite(distance) or distance < 0 or distance > 2.0: + raise ValueError( + f"canonical ground alignment override for {entity_id} must be finite in [0, 2]" + ) + result[entity_id] = distance + return result + + +def validate_canonical_visibility_hides(value: object) -> dict[str, list[str]]: + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("canonical_visibility_hides must be an object") + result: dict[str, list[str]] = {} + for entity_id, patterns in value.items(): + if not isinstance(entity_id, str) or not entity_id: + raise ValueError("canonical visibility hides require an entity id") + if not isinstance(patterns, list) or not patterns or any( + not isinstance(pattern, str) or not pattern for pattern in patterns + ): + raise ValueError( + f"canonical visibility hides for {entity_id} must be non-empty strings" + ) + result[entity_id] = list(dict.fromkeys(patterns)) + return result + + +def validate_canonical_material_overrides(value: object) -> dict[str, dict[str, Any]]: + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("canonical_material_overrides must be an object") + result: dict[str, dict[str, Any]] = {} + for entity_id, adjustment in value.items(): + if not isinstance(entity_id, str) or not entity_id or not isinstance(adjustment, dict): + raise ValueError("canonical material overrides require entity objects") + unknown = set(adjustment) - {"base_color_rgb", "roughness", "metallic"} + if unknown: + raise ValueError(f"unknown canonical material channels for {entity_id}: {sorted(unknown)}") + normalized: dict[str, Any] = {} + if "base_color_rgb" in adjustment: + color = adjustment["base_color_rgb"] + if not isinstance(color, (list, tuple)) or len(color) != 3: + raise ValueError(f"canonical material color for {entity_id} needs 3 values") + color_value = tuple(float(item) for item in color) + if any(not math.isfinite(item) or not 0 <= item <= 1 for item in color_value): + raise ValueError(f"canonical material color for {entity_id} must be in [0, 1]") + normalized["base_color_rgb"] = color_value + for channel in ("roughness", "metallic"): + if channel in adjustment: + scalar = float(adjustment[channel]) + if not math.isfinite(scalar) or not 0 <= scalar <= 1: + raise ValueError(f"canonical material {channel} for {entity_id} must be in [0, 1]") + normalized[channel] = scalar + if not normalized: + raise ValueError(f"canonical material override for {entity_id} is empty") + result[entity_id] = normalized + return result + + +def validate_canonical_descendant_material_overrides( + value: object, +) -> dict[str, list[dict[str, Any]]]: + if value is None: + return {} + if not isinstance(value, dict): + raise ValueError("canonical_descendant_material_overrides must be an object") + result: dict[str, list[dict[str, Any]]] = {} + for entity_id, entries in value.items(): + if not isinstance(entity_id, str) or not entity_id: + raise ValueError("canonical descendant material overrides require an entity id") + if not isinstance(entries, list) or not entries: + raise ValueError(f"canonical descendant materials for {entity_id} need entries") + normalized_entries: list[dict[str, Any]] = [] + for entry in entries: + if not isinstance(entry, dict) or not isinstance(entry.get("pattern"), str) or not entry["pattern"]: + raise ValueError(f"canonical descendant material for {entity_id} needs pattern") + adjustment = {key: value for key, value in entry.items() if key != "pattern"} + if not adjustment: + raise ValueError( + f"canonical descendant material for {entity_id} needs material channels" + ) + normalized = validate_canonical_material_overrides({entity_id: adjustment})[entity_id] + normalized_entries.append({"pattern": entry["pattern"], **normalized}) + result[entity_id] = normalized_entries + return result + + +def validate_canonical_static_entities(value: object) -> set[str]: + if value is None: + return set() + if not isinstance(value, list) or any( + not isinstance(entity_id, str) or not entity_id for entity_id in value + ): + raise ValueError("canonical_static_entities must be a list of non-empty entity IDs") + if len(value) != len(set(value)): + raise ValueError("canonical_static_entities must not contain duplicates") + return set(value) + + +def _canonical_ground_alignment_m(candidate: dict[str, Any]) -> float: + """Lift centered canonical geometry so its measured lower bound meets its anchor.""" + geometry = candidate.get("geometry_metadata") or {} + value = geometry.get("ground_offset_m") + if not isinstance(value, (int, float)): + return 0.0 + offset = float(value) + return offset if math.isfinite(offset) and offset > 0.0 else 0.0 + + +def _align_world_fixed_joints(stage: Any, root_prim: Any, gf: Any, usd_geom: Any) -> int: + """Keep fixed-base articulations anchored after their referenced asset is placed.""" + from packages.asset_registry.articulation import rebase_world_fixed_joints + return len(rebase_world_fixed_joints(stage, root_prim)) + + +def bind_canonical_usd_assets( + root_usd: Path, + entity_prim_paths: dict[str, str], + selections: dict[str, list[dict[str, Any]]], + articulation_couplings: object = None, + canonical_scale_overrides: object = None, + canonical_static_entities: object = None, + embedded_entities: set[str] | None = None, + embedded_vertical_offsets: dict[str, float] | None = None, + canonical_yaw_overrides: object = None, + canonical_rotation_overrides: object = None, + canonical_ground_alignment_overrides: object = None, + canonical_visibility_hides: object = None, + canonical_material_overrides: object = None, + canonical_descendant_material_overrides: object = None, +) -> dict[str, dict[str, str]]: + try: + from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics, UsdShade # type: ignore[import-not-found] + except ImportError as error: + raise RuntimeError("pxr is required to bind canonical USD assets") from error + stage = Usd.Stage.Open(str(root_usd)) + if stage is None: + raise RuntimeError(f"could not open exported USD: {root_usd}") + bindings: dict[str, dict[str, str]] = {} + coupling_specs = validate_articulation_couplings(articulation_couplings) + scale_overrides = validate_canonical_scale_overrides(canonical_scale_overrides) + yaw_overrides = validate_canonical_yaw_overrides(canonical_yaw_overrides) + rotation_overrides = validate_canonical_rotation_overrides( + canonical_rotation_overrides + ) + ground_alignment_overrides = validate_canonical_ground_alignment_overrides( + canonical_ground_alignment_overrides + ) + visibility_hides = validate_canonical_visibility_hides(canonical_visibility_hides) + material_overrides = validate_canonical_material_overrides(canonical_material_overrides) + descendant_material_overrides = validate_canonical_descendant_material_overrides( + canonical_descendant_material_overrides + ) + conflicting_rotations = set(yaw_overrides) & set(rotation_overrides) + if conflicting_rotations: + raise ValueError( + "canonical yaw and XYZ rotation overrides are mutually exclusive for " + f"entities: {sorted(conflicting_rotations)}" + ) + static_entities = validate_canonical_static_entities(canonical_static_entities) + embedded_entities = embedded_entities or set() + embedded_vertical_offsets = embedded_vertical_offsets or {} + packaged_root = root_usd.parent / "canonical_assets" + unknown_entities = ( + set(coupling_specs) + | set(scale_overrides) + | set(yaw_overrides) + | set(rotation_overrides) + | set(ground_alignment_overrides) + | set(visibility_hides) + | set(material_overrides) + | set(descendant_material_overrides) + | static_entities + ) - set(entity_prim_paths) + if unknown_entities: + raise ValueError( + "canonical asset configuration references unknown entities: " + f"{sorted(unknown_entities)}" + ) + for entity_id, prim_path in entity_prim_paths.items(): + candidates = selections.get(entity_id, []) + if not candidates: + raise RuntimeError(f"robothousegen has no selected asset for {entity_id}") + candidate = candidates[0] + runtime = candidate.get("runtime_compatibility") or {} + canonical = Path(str(runtime.get("canonical_usd_path") or "")) + if not canonical.is_file(): + raise RuntimeError(f"canonical USD is missing for {entity_id}: {canonical}") + if ( + canonical.suffix.lower() not in {".usd", ".usda", ".usdc", ".usdz"} + and entity_id not in embedded_entities + ): + raise RuntimeError( + f"non-USD canonical asset must be converted or embedded before binding: " + f"{entity_id}: {canonical}" + ) + parent = stage.GetPrimAtPath(prim_path) + if not parent: + raise RuntimeError(f"bound prim is missing for {entity_id}: {prim_path}") + child_path = Sdf.Path(prim_path).AppendChild("RoboHouseGenCanonical") + canonical_prim = stage.DefinePrim(child_path, "Xform") + if entity_id in embedded_entities: + canonical_prim.GetReferences().ClearReferences() + UsdGeom.Xformable(canonical_prim).ClearXformOpOrder() + for child in list(canonical_prim.GetChildren()): + if child.GetName().startswith("Component_"): + stage.RemovePrim(child.GetPath()) + proxy_paths = json.loads( + str(parent.GetCustomDataByKey("robothousegen:proxy_components_json") or "[]") + ) + if not proxy_paths: + raise RuntimeError(f"embedded canonical proxy is missing for {entity_id}") + for index, proxy_path in enumerate(proxy_paths): + adjustment = stage.DefinePrim( + child_path.AppendChild(f"Component_{index:02d}"), "Xform" + ) + adjustment_xform = UsdGeom.Xformable(adjustment) + adjustment_xform.ClearXformOpOrder() + reference_parent = adjustment + vertical_offset = float(embedded_vertical_offsets.get(entity_id, 0.0)) + if vertical_offset: + reference_parent = stage.DefinePrim( + adjustment.GetPath().AppendChild("SupportClearance"), "Xform" + ) + lift = UsdGeom.Xformable(reference_parent) + lift.ClearXformOpOrder() + lift.AddTranslateOp(UsdGeom.XformOp.PrecisionDouble).Set( + Gf.Vec3d(0.0, 0.0, vertical_offset) + ) + embedded = stage.DefinePrim( + reference_parent.GetPath().AppendChild("EmbeddedProxy"), "Xform" + ) + embedded.GetReferences().AddInternalReference(Sdf.Path(str(proxy_path))) + UsdGeom.Imageable(embedded).GetVisibilityAttr().Set(UsdGeom.Tokens.inherited) + object_id = parent.GetCustomDataByKey("robothousegen:scenesmith_object_id") + bindings[entity_id] = { + "asset_id": f"scenesmith:{object_id}", + "source_asset_id": str(candidate["asset_id"]), + "canonical_usd": str(root_usd.resolve()), + "binding_mode": "embedded_generated", + "vertical_offset_m": str(embedded_vertical_offsets.get(entity_id, 0.0)), + "prim_path": str(child_path), + } + continue + # Canonical references are part of the benchmark contract, so they must + # remain resolvable when the version directory is moved or mounted in an + # isolated validator. Materialize an asset-specific portable bundle. + packaged_dir = packaged_root / entity_id + if packaged_root.resolve().is_relative_to(canonical.parent.resolve()): + # Primarily protects synthetic tests where the source asset and + # output scene share one temporary directory. + packaged_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(canonical, packaged_dir / canonical.name) + packaged_canonical = packaged_dir / canonical.name + else: + # Rebinding a resumed attempt must not retain candidates copied by + # an older materialization policy. + if packaged_dir.exists(): + shutil.rmtree(packaged_dir) + packaged_canonical = _copy_canonical_asset_bundle( + canonical, candidate, packaged_dir + ) + reference_path = packaged_canonical.relative_to(root_usd.parent).as_posix() + canonical_prim.GetReferences().ClearReferences() + canonical_prim.GetReferences().AddReference(reference_path) + xform = UsdGeom.Xformable(canonical_prim) + xform.ClearXformOpOrder() + matrix_values = runtime.get("proxy_to_canonical") or [ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1, + ] + matrix = Gf.Matrix4d(*[float(value) for value in matrix_values]) + xform.AddTransformOp().Set(matrix) + ground_alignment_m = ground_alignment_overrides.get( + entity_id, _canonical_ground_alignment_m(candidate) + ) + if ground_alignment_m: + xform.AddTranslateOp(UsdGeom.XformOp.PrecisionDouble).Set( + Gf.Vec3d(0.0, 0.0, ground_alignment_m) + ) + canonical_prim.SetCustomDataByKey( + "robothousegen:canonical_ground_alignment_m", ground_alignment_m + ) + scale = scale_overrides.get(entity_id) + if scale is not None: + xform.AddScaleOp(UsdGeom.XformOp.PrecisionDouble).Set(Gf.Vec3d(*scale)) + canonical_prim.SetCustomDataByKey( + "robothousegen:canonical_scale_override", Gf.Vec3d(*scale) + ) + yaw = yaw_overrides.get(entity_id) + if yaw is not None: + xform.AddRotateZOp(UsdGeom.XformOp.PrecisionDouble).Set(yaw) + canonical_prim.SetCustomDataByKey( + "robothousegen:canonical_yaw_override_deg", yaw + ) + rotation = rotation_overrides.get(entity_id) + if rotation is not None: + xform.AddRotateXYZOp(UsdGeom.XformOp.PrecisionDouble).Set( + Gf.Vec3d(*rotation) + ) + canonical_prim.SetCustomDataByKey( + "robothousegen:canonical_rotation_override_deg", Gf.Vec3d(*rotation) + ) + canonical_prim.SetCustomDataByKey("robothousegen:asset_id", candidate["asset_id"]) + canonical_prim.SetCustomDataByKey("robothousegen:source", candidate["source"]) + hidden_paths: list[str] = [] + for descendant in Usd.PrimRange(canonical_prim): + descendant_path = str(descendant.GetPath()) + if any(pattern in descendant_path for pattern in visibility_hides.get(entity_id, [])): + if descendant.IsA(UsdGeom.Imageable): + UsdGeom.Imageable(descendant).GetVisibilityAttr().Set(UsdGeom.Tokens.invisible) + hidden_paths.append(descendant_path) + material_adjustment = material_overrides.get(entity_id) + material_path = "" + looks = None + if material_adjustment or descendant_material_overrides.get(entity_id): + looks = UsdGeom.Scope.Define(stage, "/World/RoboHouseGenCanonicalLooks") + if material_adjustment: + assert looks is not None + material = UsdShade.Material.Define( + stage, looks.GetPath().AppendChild(entity_id) + ) + shader = UsdShade.Shader.Define( + stage, material.GetPath().AppendChild("PreviewSurface") + ) + shader.CreateIdAttr("UsdPreviewSurface") + shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set( + Gf.Vec3f(*material_adjustment.get("base_color_rgb", (0.5, 0.5, 0.5))) + ) + shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( + material_adjustment.get("roughness", 0.45) + ) + shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set( + material_adjustment.get("metallic", 0.0) + ) + material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") + for descendant in Usd.PrimRange(canonical_prim): + if descendant.IsA(UsdGeom.Gprim) and str(descendant.GetPath()) not in hidden_paths: + UsdShade.MaterialBindingAPI.Apply(descendant).Bind( + material, + bindingStrength=UsdShade.Tokens.strongerThanDescendants, + ) + material_path = str(material.GetPath()) + descendant_material_paths: list[str] = [] + for index, detail in enumerate(descendant_material_overrides.get(entity_id, [])): + assert looks is not None + material = UsdShade.Material.Define( + stage, looks.GetPath().AppendChild(f"{entity_id}_detail_{index:02d}") + ) + shader = UsdShade.Shader.Define( + stage, material.GetPath().AppendChild("PreviewSurface") + ) + shader.CreateIdAttr("UsdPreviewSurface") + shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set( + Gf.Vec3f(*detail.get("base_color_rgb", (0.5, 0.5, 0.5))) + ) + shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( + detail.get("roughness", 0.45) + ) + shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set( + detail.get("metallic", 0.0) + ) + material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") + matched = 0 + for descendant in Usd.PrimRange(canonical_prim): + if descendant.IsA(UsdGeom.Gprim) and detail["pattern"] in str(descendant.GetPath()): + UsdGeom.Imageable(descendant).GetVisibilityAttr().Set(UsdGeom.Tokens.inherited) + UsdShade.MaterialBindingAPI.Apply(descendant).Bind( + material, + bindingStrength=UsdShade.Tokens.strongerThanDescendants, + ) + matched += 1 + if not matched: + raise ValueError( + f"canonical descendant material pattern matched no geometry: " + f"{entity_id}:{detail['pattern']}" + ) + descendant_material_paths.append(str(material.GetPath())) + if entity_id in static_entities: + for descendant in Usd.PrimRange(canonical_prim): + if descendant.GetTypeName().endswith("Joint"): + descendant.SetActive(False) + if descendant.HasAPI(UsdPhysics.RigidBodyAPI): + descendant.RemoveAPI(UsdPhysics.RigidBodyAPI) + if descendant.HasAPI(UsdPhysics.ArticulationRootAPI): + descendant.RemoveAPI(UsdPhysics.ArticulationRootAPI) + canonical_prim.SetCustomDataByKey("robothousegen:physics_mode", "STATIC") + for coupling in coupling_specs.get(entity_id, []): + input_path = child_path.AppendPath(coupling["input_joint"]) + output_path = child_path.AppendPath(coupling["output_joint"]) + input_joint = stage.GetPrimAtPath(input_path) + output_joint = stage.GetPrimAtPath(output_path) + if not input_joint or not output_joint: + raise ValueError( + f"coupling {coupling['coupling_id']} references missing joints: " + f"{input_path}, {output_path}" + ) + if coupling["implementation"] == "MIMIC": + if "PhysicsDriveAPI:angular" in output_joint.GetAppliedSchemas(): + output_joint.RemoveAppliedSchema("PhysicsDriveAPI:angular") + for attribute in output_joint.GetAttributes(): + if attribute.GetName().startswith("drive:angular:"): + attribute.Block() + schema_name = "PhysxMimicJointAPI:rotX" + if schema_name not in output_joint.GetAppliedSchemas(): + output_joint.AddAppliedSchema(schema_name) + prefix = "physxMimicJoint:rotX" + output_joint.CreateRelationship(f"{prefix}:referenceJoint").SetTargets( + [input_path] + ) + output_joint.CreateAttribute( + f"{prefix}:referenceJointAxis", Sdf.ValueTypeNames.Token + ).Set("rotX") + output_joint.CreateAttribute( + f"{prefix}:gearing", Sdf.ValueTypeNames.Float + ).Set(-coupling["gear_ratio"]) + output_joint.CreateAttribute( + f"{prefix}:offset", Sdf.ValueTypeNames.Float + ).Set(0.0) + output_joint.SetCustomDataByKey( + "robothousegen:physical_coupling", coupling["coupling_id"] + ) + else: + input_bodies = input_joint.GetRelationship("physics:body1").GetTargets() + output_bodies = output_joint.GetRelationship("physics:body1").GetTargets() + if len(input_bodies) != 1 or len(output_bodies) != 1: + raise ValueError( + f"coupling {coupling['coupling_id']} requires each hinge to have " + "exactly one physics:body1 target" + ) + coupling_path = child_path.AppendChild("RoboHouseGenCouplings").AppendChild( + coupling["coupling_id"] + ) + gear = stage.DefinePrim(coupling_path, "PhysxPhysicsGearJoint") + gear.CreateRelationship("physics:body0").SetTargets(input_bodies) + gear.CreateRelationship("physics:body1").SetTargets(output_bodies) + gear.CreateRelationship("physics:hinge0").SetTargets([input_path]) + gear.CreateRelationship("physics:hinge1").SetTargets([output_path]) + gear.CreateAttribute("physics:gearRatio", Sdf.ValueTypeNames.Float).Set( + coupling["gear_ratio"] + ) + gear.CreateAttribute( + "physics:excludeFromArticulation", Sdf.ValueTypeNames.Bool + ).Set(True) + gear.SetCustomDataByKey("robothousegen:physical_coupling", True) + # Every native fixed base needs rebasing, including ordinary cupboards + # without an explicitly configured gear/mimic coupling. + if entity_id not in static_entities: + aligned_fixed_joints = _align_world_fixed_joints( + stage, canonical_prim, Gf, UsdGeom + ) + canonical_prim.SetCustomDataByKey( + "robothousegen:aligned_world_fixed_joints", aligned_fixed_joints + ) + bindings[entity_id] = { + "asset_id": str(candidate["asset_id"]), + "canonical_usd": str(packaged_canonical.resolve()), + "source_canonical_usd": str(canonical.resolve()), + "prim_path": str(child_path), + "ground_alignment_m": str(ground_alignment_m), + } + native_joints = [prim for prim in Usd.PrimRange(canonical_prim) + if prim.IsA(UsdPhysics.RevoluteJoint) or prim.IsA(UsdPhysics.PrismaticJoint)] + bindings[entity_id]['native_movable_joint_count'] = str(len(native_joints)) + bindings[entity_id]['native_joint_paths'] = json.dumps([str(p.GetPath()) for p in native_joints]) + if entity_id not in static_entities: + bindings[entity_id]['aligned_world_fixed_joints'] = str(aligned_fixed_joints) + if entity_id in coupling_specs: + bindings[entity_id]["couplings"] = str(len(coupling_specs[entity_id])) + bindings[entity_id]["coupling_implementations"] = ",".join( + coupling["implementation"] for coupling in coupling_specs[entity_id] + ) + bindings[entity_id]["aligned_world_fixed_joints"] = str( + aligned_fixed_joints + ) + if scale is not None: + bindings[entity_id]["canonical_scale"] = ",".join( + f"{item:g}" for item in scale + ) + if yaw is not None: + bindings[entity_id]["canonical_yaw_deg"] = f"{yaw:g}" + if rotation is not None: + bindings[entity_id]["canonical_rotation_deg"] = ",".join( + f"{item:g}" for item in rotation + ) + if entity_id in ground_alignment_overrides: + bindings[entity_id]["canonical_ground_alignment_override_m"] = ( + f"{ground_alignment_m:g}" + ) + if hidden_paths: + bindings[entity_id]["hidden_canonical_prim_paths"] = json.dumps(hidden_paths) + if material_path: + bindings[entity_id]["canonical_material_override"] = material_path + if descendant_material_paths: + bindings[entity_id]["canonical_descendant_material_overrides"] = json.dumps( + descendant_material_paths + ) + if entity_id in static_entities: + bindings[entity_id]["physics_mode"] = "STATIC" + stage.GetRootLayer().Save() + return bindings diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/parametric.py b/docs/reproduction/public_conversion_code/packages/asset_registry/parametric.py new file mode 100644 index 0000000000000000000000000000000000000000..59b7d3c9d49e50ce6eadc0598a71167acbae9203 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/parametric.py @@ -0,0 +1,210 @@ +from __future__ import annotations + +import hashlib +import json +import os +import re +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.asset_registry.models import ( + AssetFile, + AssetRecord, + DimensionSource, + GeometryMetadata, + MountType, + PlacementMetadata, + RuntimeCompatibility, +) +from packages.asset_registry.proxy_sdf import render_proxy_sdf + + +class ParametricMaterial(BaseModel): + model_config = ConfigDict(extra="forbid") + base_color_texture: str | None = None + roughness_texture: str | None = None + normal_texture: str | None = None + base_color: tuple[float, float, float, float] = (0.5, 0.5, 0.5, 1.0) + roughness: float = Field(default=0.45, ge=0.0, le=1.0) + metallic: float = Field(default=0.0, ge=0.0, le=1.0) + texture_scale: tuple[float, float] = (1.0, 1.0) + + +class ParametricAssetRecipe(BaseModel): + model_config = ConfigDict(extra="forbid") + asset_id: str + display_name: str + description: str + category: str + tags: list[str] + synonyms: list[str] = Field(default_factory=list) + dimensions_m: tuple[float, float, float] + geometry_style: str = "slab" + module_count: int = Field(default=1, ge=1, le=16) + mount: MountType + support_surfaces: list[str] = Field(default_factory=list) + bevel_m: float = Field(default=0.004, ge=0.0) + material: ParametricMaterial + source_url: str + source_license: str = "CC0-1.0" + + @model_validator(mode="after") + def validate_geometry(self) -> ParametricAssetRecipe: + if any(value <= 0.0 for value in self.dimensions_m): + raise ValueError("parametric asset dimensions must be positive") + if self.bevel_m * 2.0 >= min(self.dimensions_m): + raise ValueError("bevel_m must be smaller than half the shortest dimension") + return self + + +class ParametricAssetLibrary(BaseModel): + model_config = ConfigDict(extra="forbid") + schema_version: str = "1.0" + output_root: str + assets: list[ParametricAssetRecipe] + + +def _expand_path(value: str, *, base: Path) -> Path: + expanded = os.path.expandvars(value) + unresolved = re.findall(r"\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_]*", expanded) + if unresolved: + raise ValueError(f"unresolved environment variables in path {value!r}: {unresolved}") + path = Path(expanded).expanduser() + return (path if path.is_absolute() else base / path).resolve() + + +def load_parametric_asset_library(path: Path) -> ParametricAssetLibrary: + payload = yaml.safe_load(path.read_text(encoding="utf-8")) + return ParametricAssetLibrary.model_validate(payload) + + +def build_jobs( + library: ParametricAssetLibrary, + *, + recipe_path: Path, +) -> tuple[Path, list[dict[str, Any]]]: + output_root = _expand_path(library.output_root, base=recipe_path.parent) + jobs: list[dict[str, Any]] = [] + for recipe in library.assets: + safe_id = re.sub(r"[^A-Za-z0-9_.-]+", "_", recipe.asset_id) + asset_root = output_root / safe_id + material = recipe.material.model_dump(mode="json") + for key in ("base_color_texture", "roughness_texture", "normal_texture"): + if material.get(key): + material[key] = str(_expand_path(str(material[key]), base=recipe_path.parent)) + jobs.append( + { + "asset_id": recipe.asset_id, + "dimensions_m": list(recipe.dimensions_m), + "geometry_style": recipe.geometry_style, + "module_count": recipe.module_count, + "bevel_m": recipe.bevel_m, + "material": material, + "canonical_usd": str(asset_root / "asset.usdc"), + "proxy_glb": str(asset_root / "asset.glb"), + } + ) + return output_root, jobs + + +def _md5(path: Path) -> str: + digest = hashlib.md5(usedforsecurity=False) + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def records_from_outputs( + library: ParametricAssetLibrary, + *, + recipe_path: Path, + jobs: list[dict[str, Any]], +) -> list[AssetRecord]: + jobs_by_id = {str(job["asset_id"]): job for job in jobs} + records: list[AssetRecord] = [] + for recipe in library.assets: + job = jobs_by_id[recipe.asset_id] + canonical = Path(job["canonical_usd"]) + proxy = Path(job["proxy_glb"]) + for required in (canonical, proxy): + if not required.is_file() or required.stat().st_size == 0: + raise RuntimeError(f"parametric asset output is missing: {required}") + dimensions = recipe.dimensions_m + bbox_min = (-dimensions[0] / 2.0, -dimensions[1] / 2.0, 0.0) + bbox_max = (dimensions[0] / 2.0, dimensions[1] / 2.0, dimensions[2]) + sdf = proxy.with_suffix(".sdf") + sdf.write_text( + render_proxy_sdf( + recipe.asset_id, + proxy.name, + bbox_min, + bbox_max, + articulated=False, + ), + encoding="utf-8", + ) + records.append( + AssetRecord( + asset_id=recipe.asset_id, + scene_name=re.sub(r"[^A-Za-z0-9_]", "_", recipe.asset_id), + display_name=recipe.display_name, + description=recipe.description, + source="RoboHouseGen Parametric", + source_license=recipe.source_license, + category=recipe.category, + tags=recipe.tags, + synonyms=recipe.synonyms, + files=[ + AssetFile( + relative_path=str(canonical.relative_to(canonical.parent.parent)), + source_url=recipe.source_url, + md5=_md5(canonical), + size_bytes=canonical.stat().st_size, + ) + ], + usd_path=str(canonical), + dimensions_m=dimensions, + quality_tier="A", + qa_status="CONVERTED", + normalized_category=recipe.category, + dimension_source=DimensionSource.MEASURED, + dimension_confidence=1.0, + geometry_metadata=GeometryMetadata( + bbox_min_m=bbox_min, + bbox_max_m=bbox_max, + footprint_m=(dimensions[0], dimensions[1]), + ground_offset_m=0.0, + meters_per_unit=1.0, + up_axis="Z", + ), + placement_metadata=PlacementMetadata( + mount=recipe.mount, + support_surfaces=recipe.support_surfaces, + ), + runtime_compatibility=RuntimeCompatibility( + canonical_usd_path=str(canonical), + proxy_gltf_path=str(proxy), + proxy_sdf_path=str(sdf), + compatible_backends=["isaac-sim", "scenesmith"], + articulation=False, + has_collision=False, + ), + ) + ) + return records + + +def merge_records(existing: list[AssetRecord], generated: list[AssetRecord]) -> list[AssetRecord]: + replacements = {record.asset_id: record for record in generated} + merged = [record for record in existing if record.asset_id not in replacements] + merged.extend(generated) + return sorted(merged, key=lambda record: record.asset_id) + + +def write_job_manifest(path: Path, jobs: list[dict[str, Any]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(jobs, indent=2) + "\n", encoding="utf-8") diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/preparation.py b/docs/reproduction/public_conversion_code/packages/asset_registry/preparation.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f22ddc459567869453e7949d0ddaff6c2b03a8 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/preparation.py @@ -0,0 +1,507 @@ +from __future__ import annotations + +import json +import os +import subprocess +import time +from collections import defaultdict +from pathlib import Path +from statistics import median +from typing import Any + +from packages.asset_registry.admission import ( + canonical_category, + classify_and_deduplicate, + content_hash, + infer_asset_kind, + normalize_category, +) +from packages.asset_registry.basisu import normalize_basisu_glb +from packages.asset_registry.embeddings import EmbeddingProvider +from packages.asset_registry.index import ( + build_faiss_index, + build_sqlite_index, + write_index_manifest, +) +from packages.asset_registry.models import ( + AssetCatalog, + AssetKind, + AssetRecord, + DimensionSource, + GeometryMetadata, + JointSummary, + RuntimeCompatibility, +) +from packages.asset_registry.proxy_sdf import repair_proxy_sdf + +DEFAULT_DIMENSIONS_M: dict[str, tuple[float, float, float]] = { + "bottle": (0.08, 0.08, 0.25), + "chair": (0.55, 0.55, 0.9), + "desk": (1.2, 0.7, 0.75), + "door": (0.9, 0.1, 2.05), + "sofa": (2.0, 0.9, 0.85), + "stair": (1.2, 3.0, 1.8), + "table": (1.2, 0.75, 0.75), + "trash can": (0.35, 0.35, 0.65), + "object": (0.5, 0.5, 0.5), +} + + +def _usd_metadata(path: Path) -> dict[str, Any] | None: + if path.suffix.casefold() not in {".usd", ".usda", ".usdc", ".usdz"}: + return None + try: + from pxr import Usd, UsdGeom, UsdPhysics # type: ignore[import-not-found] + except ImportError: + return None + stage = Usd.Stage.Open(str(path)) + if stage is None: + return None + default_prim = stage.GetDefaultPrim() + target = default_prim if default_prim else stage.GetPseudoRoot() + bbox = UsdGeom.BBoxCache(Usd.TimeCode.Default(), [UsdGeom.Tokens.default_]).ComputeWorldBound( + target + ) + aligned = bbox.ComputeAlignedBox() + minimum = tuple(float(value) for value in aligned.GetMin()) + maximum = tuple(float(value) for value in aligned.GetMax()) + meters_per_unit = float(UsdGeom.GetStageMetersPerUnit(stage)) + minimum_m = tuple(value * meters_per_unit for value in minimum) + maximum_m = tuple(value * meters_per_unit for value in maximum) + joints: list[tuple[str, str]] = [] + articulation = False + collision = False + for prim in stage.Traverse(): + if prim.HasAPI(UsdPhysics.ArticulationRootAPI): + articulation = True + if prim.HasAPI(UsdPhysics.CollisionAPI): + collision = True + if prim.IsA(UsdPhysics.Joint): + joints.append((prim.GetName(), prim.GetTypeName())) + return { + "bbox_min_m": minimum_m, + "bbox_max_m": maximum_m, + "dimensions_m": tuple(high - low for low, high in zip(minimum_m, maximum_m, strict=True)), + "meters_per_unit": meters_per_unit, + "up_axis": str(UsdGeom.GetStageUpAxis(stage)).upper(), + "default_prim": default_prim.GetPath().pathString if default_prim else None, + "articulation": articulation, + "collision": collision, + "joints": joints, + } + + +def _mesh_metadata(path: Path) -> dict[str, Any] | None: + if path.suffix.casefold() not in {".glb", ".gltf", ".obj", ".fbx"}: + return None + try: + import numpy as np # type: ignore[import-not-found] + import trimesh # type: ignore[import-not-found] + except ImportError: + return None + loaded = trimesh.load(str(path), force="scene") + bounds = np.asarray(loaded.bounds, dtype=float) + if bounds.shape != (2, 3) or not np.isfinite(bounds).all(): + return None + minimum = tuple(float(value) for value in bounds[0]) + maximum = tuple(float(value) for value in bounds[1]) + if path.suffix.casefold() in {".glb", ".gltf"}: + # glTF is Y-up. AssetRecord geometry uses the Z-up runtime convention. + minimum = (minimum[0], minimum[2], minimum[1]) + maximum = (maximum[0], maximum[2], maximum[1]) + up_axis = "Y" + else: + up_axis = "Z" + return { + "bbox_min_m": minimum, + "bbox_max_m": maximum, + "dimensions_m": tuple( + high - low for low, high in zip(minimum, maximum, strict=True) + ), + "meters_per_unit": 1.0, + "up_axis": up_axis, + "default_prim": None, + "articulation": False, + "collision": False, + "joints": [], + } + + +def _default_dimensions(category: str) -> tuple[float, float, float]: + normalized = normalize_category(category) + for key, dimensions in DEFAULT_DIMENSIONS_M.items(): + if key in normalized: + return dimensions + return DEFAULT_DIMENSIONS_M["object"] + + +def _load_measurement_cache(path: Path | None) -> dict[str, dict[str, Any]]: + if path is None or not path.is_file(): + return {} + payload = json.loads(path.read_text(encoding="utf-8")) + if payload.get("schema_version") != "1.0": + return {} + return { + str(key): value + for key, value in payload.get("measurements", {}).items() + if isinstance(value, dict) + } + + +def _write_measurement_cache(path: Path, records: list[AssetRecord]) -> None: + measurements = {} + for record in records: + if record.content_hash is None or record.dimension_source not in { + DimensionSource.MEASURED, + DimensionSource.UPSTREAM, + }: + continue + measurements[record.content_hash] = { + "dimensions_m": record.dimensions_m, + "dimension_source": record.dimension_source.value, + "dimension_confidence": record.dimension_confidence, + "geometry_metadata": ( + record.geometry_metadata.model_dump(mode="json") + if record.geometry_metadata + else None + ), + "runtime_measurement": ( + { + "canonical_usd_path": record.runtime_compatibility.canonical_usd_path, + "articulation": record.runtime_compatibility.articulation, + "joint_summary": record.runtime_compatibility.joint_summary.model_dump( + mode="json" + ), + "has_collision": record.runtime_compatibility.has_collision, + } + if record.runtime_compatibility + else None + ), + } + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text( + json.dumps( + {"schema_version": "1.0", "measurements": measurements}, + separators=(",", ":"), + ), + encoding="utf-8", + ) + temporary.replace(path) + + +def measure_records( + records: list[AssetRecord], + *, + cache_path: Path | None = None, + asset_ids: frozenset[str] = frozenset(), +) -> list[AssetRecord]: + measured: list[AssetRecord] = [] + cache = _load_measurement_cache(cache_path) + category_values: dict[str, list[tuple[float, float, float]]] = defaultdict(list) + pending: list[int] = [] + for record in records: + path = Path(record.usd_path) + fingerprint = record.content_hash or content_hash(record) + cached = cache.get(fingerprint) + selected = not asset_ids or record.asset_id in asset_ids + metadata = ( + (_usd_metadata(path) or _mesh_metadata(path)) + if selected and cached is None and path.is_file() + else None + ) + normalized = canonical_category(record) + kind = infer_asset_kind(record) + dimensions = record.dimensions_m + source = record.dimension_source + confidence = record.dimension_confidence + geometry = record.geometry_metadata + runtime = record.runtime_compatibility + if cached is not None: + dimensions_value = cached.get("dimensions_m") + dimensions = ( + ( + float(dimensions_value[0]), + float(dimensions_value[1]), + float(dimensions_value[2]), + ) + if dimensions_value is not None + else None + ) + source = DimensionSource(cached["dimension_source"]) + confidence = cached.get("dimension_confidence") + geometry = ( + GeometryMetadata.model_validate(cached["geometry_metadata"]) + if cached.get("geometry_metadata") + else None + ) + runtime_measurement = cached.get("runtime_measurement") + if runtime_measurement: + runtime = (runtime or RuntimeCompatibility()).model_copy( + update={ + "canonical_usd_path": runtime_measurement["canonical_usd_path"], + "articulation": runtime_measurement["articulation"], + "joint_summary": JointSummary.model_validate( + runtime_measurement["joint_summary"] + ), + "has_collision": runtime_measurement["has_collision"], + } + ) + elif metadata is not None and all(value > 1e-6 for value in metadata["dimensions_m"]): + raw_dimensions = metadata["dimensions_m"] + dimensions = (raw_dimensions[0], raw_dimensions[1], raw_dimensions[2]) + source = DimensionSource.MEASURED + confidence = 1.0 + geometry = GeometryMetadata( + bbox_min_m=metadata["bbox_min_m"], + bbox_max_m=metadata["bbox_max_m"], + footprint_m=(dimensions[0], dimensions[1]), + ground_offset_m=-metadata["bbox_min_m"][2], + meters_per_unit=metadata["meters_per_unit"], + up_axis=metadata["up_axis"], + ) + runtime = (runtime or RuntimeCompatibility()).model_copy( + update={ + "canonical_usd_path": str(path.resolve()), + "articulation": metadata["articulation"], + "has_collision": metadata["collision"], + "joint_summary": JointSummary( + joint_count=len(metadata["joints"]), + joint_names=[item[0] for item in metadata["joints"]], + joint_types=[item[1] for item in metadata["joints"]], + ), + } + ) + elif dimensions is not None: + source = source or DimensionSource.UPSTREAM + confidence = confidence if confidence is not None else 0.9 + updated = record.model_copy( + update={ + "schema_version": "1.1", + "asset_kind": kind, + "normalized_category": normalized, + "dimensions_m": dimensions, + "dimension_source": source, + "dimension_confidence": confidence, + "geometry_metadata": geometry, + "runtime_compatibility": runtime, + "content_hash": fingerprint, + } + ) + measured.append(updated) + if dimensions is None: + pending.append(len(measured) - 1) + elif confidence is not None and confidence >= 0.9: + category_values[normalized].append(dimensions) + + medians: dict[str, tuple[float, float, float]] = { + category: ( + median(values[0] for values in category_values[category]), + median(values[1] for values in category_values[category]), + median(values[2] for values in category_values[category]), + ) + for category, values in category_values.items() + } + for index in pending: + record = measured[index] + category = record.normalized_category or "object" + dimensions = medians.get(category) + if dimensions is not None: + source = DimensionSource.CATEGORY_MEDIAN + confidence = 0.4 + else: + dimensions = _default_dimensions(category) + source = DimensionSource.DEFAULT + confidence = 0.2 + measured[index] = record.model_copy( + update={ + "dimensions_m": dimensions, + "dimension_source": source, + "dimension_confidence": confidence, + } + ) + if cache_path is not None: + _write_measurement_cache(cache_path, measured) + return measured + + +def write_catalog(records: list[AssetRecord], path: Path, *, source: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text( + AssetCatalog(source=source, assets=records).model_dump_json(indent=2), + encoding="utf-8", + ) + temporary.replace(path) + + +def _blender_compatible_source(source: Path, proxy_root: Path, digest: str) -> Path: + """Decode BasisU textures before Blender import without discarding materials.""" + if source.suffix.casefold() != ".glb" or b"KHR_texture_basisu" not in source.read_bytes(): + return source + normalized_dir = proxy_root / ".normalized" / digest + normalized = normalized_dir / "asset.gltf" + if normalized.is_file(): + return normalized + ktx_value = os.environ.get("RHG_KTX_TOOL", "").strip() + if not ktx_value: + raise RuntimeError("RHG_KTX_TOOL is required to preserve BasisU proxy textures") + return normalize_basisu_glb(source, normalized_dir, ktx_tool=Path(ktx_value)) + + +def prepare_proxies( + records: list[AssetRecord], + output_dir: Path, + *, + blender: str, + batch_size: int = 64, + query_terms: tuple[str, ...] = (), + asset_ids: frozenset[str] = frozenset(), + limit: int | None = None, +) -> list[AssetRecord]: + proxy_root = output_dir / "proxy" + proxy_root.mkdir(parents=True, exist_ok=True) + jobs: list[dict[str, Any]] = [] + record_jobs: dict[str, tuple[Path, Path]] = {} + for record in records: + if asset_ids and record.asset_id not in asset_ids: + continue + if infer_asset_kind(record) != AssetKind.OBJECT: + continue + path_text = record.usd_path.casefold() + if record.source == "ArtVIP" and "/resource/" in path_text: + continue + if record.source == "InteriorAgent": + continue + searchable = normalize_category( + f"{record.asset_id} {record.display_name} {record.category} {' '.join(record.tags)}" + ) + if query_terms and not any(normalize_category(term) in searchable for term in query_terms): + continue + if limit is not None and len(record_jobs) >= limit: + break + source = Path(record.usd_path) + if not source.is_file() or source.suffix.casefold() not in { + ".usd", + ".usda", + ".usdc", + ".usdz", + ".glb", + ".gltf", + ".obj", + ".fbx", + }: + continue + digest = (record.content_hash or content_hash(record)).split(":", 1)[-1] + safe_id = "".join( + char if char.isalnum() or char in "-_" else "_" for char in record.asset_id + ) + destination = proxy_root / digest[:2] / f"{safe_id}.glb" + sdf = destination.with_suffix(".sdf") + record_jobs[record.asset_id] = (destination, sdf) + compatible_source = _blender_compatible_source(source, proxy_root, digest) + dimensions = record.dimensions_m or (0.5, 0.5, 0.5) + geometry = record.geometry_metadata + bbox_min = ( + geometry.bbox_min_m + if geometry is not None and geometry.bbox_min_m is not None + else (-dimensions[0] / 2, -dimensions[1] / 2, 0.0) + ) + bbox_max = ( + geometry.bbox_max_m + if geometry is not None and geometry.bbox_max_m is not None + else (dimensions[0] / 2, dimensions[1] / 2, dimensions[2]) + ) + if destination.is_file() and sdf.is_file(): + repair_proxy_sdf(sdf, bbox_min, bbox_max) + continue + jobs.append( + { + "asset_id": record.asset_id, + "source": str(compatible_source.resolve()), + "gltf": str(destination.resolve()), + "sdf": str(sdf.resolve()), + "bbox_min_m": bbox_min, + "bbox_max_m": bbox_max, + "articulation": bool( + record.runtime_compatibility and record.runtime_compatibility.articulation + ), + } + ) + worker = Path(__file__).resolve().parents[2] / "scripts" / "blender_prepare_asset_proxies.py" + for offset in range(0, len(jobs), batch_size): + batch = jobs[offset : offset + batch_size] + manifest = proxy_root / f"jobs-{offset // batch_size:05d}.json" + manifest.write_text(json.dumps(batch, indent=2) + "\n", encoding="utf-8") + result = subprocess.run( + [blender, "--background", "--python", str(worker), "--", str(manifest)], + check=False, + capture_output=True, + text=True, + ) + if result.returncode: + details = (result.stdout + result.stderr)[-4000:] + raise RuntimeError(f"Blender proxy batch failed: {details}") + missing_outputs = [ + path + for job in batch + for path in (Path(job["gltf"]), Path(job["sdf"])) + if not path.is_file() + ] + if missing_outputs: + details = (result.stdout + result.stderr)[-4000:] + raise RuntimeError( + f"Blender reported success but proxy outputs are missing: " + f"{missing_outputs}; {details}" + ) + updated = [] + for record in records: + paths = record_jobs.get(record.asset_id) + if paths is None or not all(path.is_file() for path in paths): + updated.append(record) + continue + runtime = record.runtime_compatibility or RuntimeCompatibility() + compatible = sorted(set([*runtime.compatible_backends, "scenesmith", "isaac-sim"])) + updated.append( + record.model_copy( + update={ + "runtime_compatibility": runtime.model_copy( + update={ + "canonical_usd_path": runtime.canonical_usd_path + or ( + str(Path(record.usd_path).resolve()) + if Path(record.usd_path).suffix.casefold() + in {".usd", ".usda", ".usdc", ".usdz"} + else None + ), + "proxy_gltf_path": str(paths[0].resolve()), + "proxy_sdf_path": str(paths[1].resolve()), + "compatible_backends": compatible, + } + ) + } + ) + ) + return updated + + +def build_indexes( + records: list[AssetRecord], output_dir: Path, embedding_provider: EmbeddingProvider +) -> Path: + started = time.perf_counter() + records = classify_and_deduplicate(records) + write_catalog(records, output_dir / "enriched_catalog.json", source="RoboHouseGen indexed") + active = build_sqlite_index(records, output_dir / "asset_index.sqlite3") + build_faiss_index( + active, + output_dir / "asset_vectors.faiss", + embedding_provider, + sqlite_path=output_dir / "asset_index.sqlite3", + ) + return write_index_manifest( + output_dir, + records=records, + active_records=active, + embedding_provider=embedding_provider, + build_duration_s=time.perf_counter() - started, + ) diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/proxy_sdf.py b/docs/reproduction/public_conversion_code/packages/asset_registry/proxy_sdf.py new file mode 100644 index 0000000000000000000000000000000000000000..13c5017524bb243f77fc1ad7a29f6930a8884c62 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/proxy_sdf.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import math +import xml.etree.ElementTree as ET +from pathlib import Path +from xml.sax.saxutils import escape + + +def collision_envelope( + bbox_min: tuple[float, float, float] | list[float], + bbox_max: tuple[float, float, float] | list[float], +) -> tuple[tuple[float, float, float], tuple[float, float, float]]: + # Canonical assets are not guaranteed to be floor-aligned. Manipulands are + # commonly centred around their origin, so clamping a negative Z minimum to + # zero silently removes the lower half of their collision envelope. + lower = tuple(float(value) for value in bbox_min) + upper = (float(bbox_max[0]), float(bbox_max[1]), float(bbox_max[2])) + if any(low >= high for low, high in zip(lower, upper, strict=True)): + raise ValueError(f"invalid collision bbox: min={lower}, max={upper}") + size = (upper[0] - lower[0], upper[1] - lower[1], upper[2] - lower[2]) + center = ( + (lower[0] + upper[0]) / 2, + (lower[1] + upper[1]) / 2, + (lower[2] + upper[2]) / 2, + ) + return center, size + + +def render_proxy_sdf( + name: str, + glb_name: str, + bbox_min: tuple[float, float, float] | list[float], + bbox_max: tuple[float, float, float] | list[float], + *, + articulated: bool, +) -> str: + center, size = collision_envelope(bbox_min, bbox_max) + pose = " ".join(str(value) for value in (*center, 0.0, 0.0, 0.0)) + extent = " ".join(str(value) for value in size) + static = "false" if articulated else "true" + return f''' + + + {static} + + {escape(glb_name)} + + {pose} + {extent} + + + + +''' + + +def repair_proxy_sdf( + path: Path, + bbox_min: tuple[float, float, float] | list[float], + bbox_max: tuple[float, float, float] | list[float], +) -> bool: + center, size = collision_envelope(bbox_min, bbox_max) + tree = ET.parse(path) + collision = tree.find(".//collision[@name='collision_envelope']") + if collision is None: + raise ValueError(f"collision_envelope is missing from {path}") + pose = collision.find("pose") + size_node = collision.find("./geometry/box/size") + if size_node is None: + raise ValueError(f"collision box size is missing from {path}") + expected_pose = (*center, 0.0, 0.0, 0.0) + current_pose = ( + tuple(float(value) for value in pose.text.split()) if pose is not None and pose.text else () + ) + current_size = tuple(float(value) for value in size_node.text.split()) if size_node.text else () + if ( + len(current_pose) == 6 + and len(current_size) == 3 + and all( + math.isclose(actual, expected, abs_tol=1e-9) + for actual, expected in zip( + current_pose + current_size, expected_pose + size, strict=True + ) + ) + ): + return False + if pose is None: + pose = ET.Element("pose") + collision.insert(0, pose) + pose.text = " ".join(str(value) for value in expected_pose) + size_node.text = " ".join(str(value) for value in size) + ET.indent(tree, space=" ") + tree.write(path, encoding="utf-8", xml_declaration=True) + return True diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/release.py b/docs/reproduction/public_conversion_code/packages/asset_registry/release.py new file mode 100644 index 0000000000000000000000000000000000000000..0ba92fd0be6deb455d0d7bfba7e6c7f9f88f8c22 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/release.py @@ -0,0 +1,1871 @@ +from __future__ import annotations + +import ast +import csv +import hashlib +import json +import math +import os +import re +import sqlite3 +import struct +import threading +import time +import traceback +import urllib.parse +import xml.etree.ElementTree as ET +from collections import Counter, defaultdict +from collections.abc import Iterable, Sequence +from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal, cast + +from PIL import Image, ImageDraw +from shapely.geometry import MultiPoint, Polygon, box # type: ignore[import-untyped] +from shapely.ops import unary_union # type: ignore[import-untyped] + +from packages.asset_registry.admission import normalize_category +from packages.asset_registry.descriptors import ( + AssetDescriptor, + AssetQuality, + OperationalClearance, + OrientedBoundingBox, + PbrChannels, + Point2, +) +from packages.asset_registry.models import AdmissionStatus, AssetCatalog, AssetKind, AssetRecord +from packages.core.files import atomic_write_text + +# USD's resolver and stage caches are not safe to drive from several Python +# threads in the same process. GLB/GLTF inspection remains parallel, while +# USD loading is serialized through this narrow gate. +_USD_INSPECTION_LOCK = threading.Lock() + + +SUPPORTED_GEOMETRY_EXTENSIONS = { + ".glb", + ".gltf", + ".obj", + ".fbx", + ".usd", + ".usda", + ".usdc", + ".usdz", + ".sdf", +} +NON_GEOMETRY_KINDS = {AssetKind.MATERIAL, AssetKind.LIGHTING} +STYLE_WORDS = { + "art deco", + "bohemian", + "classic", + "contemporary", + "industrial", + "japanese", + "mid century", + "minimal", + "modern", + "rustic", + "scandinavian", + "traditional", + "vintage", +} +COLOR_WORDS = { + "beige", + "black", + "blue", + "brass", + "bronze", + "brown", + "copper", + "cream", + "gold", + "gray", + "green", + "grey", + "orange", + "pink", + "purple", + "red", + "silver", + "teal", + "white", + "yellow", +} +MATERIAL_WORDS = { + "bamboo", + "ceramic", + "concrete", + "fabric", + "glass", + "leather", + "marble", + "metal", + "plastic", + "rattan", + "steel", + "stone", + "wood", + "wooden", +} + +CATEGORY_SYNONYMS: dict[str, tuple[str, ...]] = { + "armchair": ("accent chair", "easy chair", "reading chair"), + "bookcase": ("bookshelf", "book shelf", "low bookcase"), + "cabinet": ("cupboard", "storage cabinet", "drawer cabinet"), + "chair": ("seat", "work chair", "office chair"), + "chest of drawers": ("drawer cabinet", "dresser", "storage cabinet"), + "desk": ("work desk", "worktable", "writing desk"), + "floor lamp": ("standing lamp", "floor light"), + "lamp": ("light", "lighting fixture"), + "picture": ("wall art", "artwork", "framed art"), + "plant": ("indoor plant", "potted plant", "greenery"), + "potted plant": ("indoor plant", "plant", "greenery"), + "shelf": ("shelving", "storage shelf"), + "side table": ("end table", "occasional table", "small table"), + "sofa": ("couch", "settee"), + "table": ("worktable", "dining table", "desk"), + "vase": ("flower vase", "decorative vessel"), +} + + +@dataclass(slots=True) +class HssdSemantic: + category: str = "" + articulated: bool = False + pickable: bool = False + name: str = "" + + +@dataclass(frozen=True, slots=True) +class FrontAxisOverride: + asset_id: str + asset_sha256: str + front_axis: Literal["+X", "-X", "+Y", "-Y"] + source: Literal["multiview_verified", "manual_override"] + confidence: float + evidence: tuple[str, ...] + note: str = "" + + +@dataclass(slots=True) +class ReleaseMetadata: + hssd_root: Path | None = None + hssd_semantics: dict[str, HssdSemantic] = field(default_factory=dict) + affordances_by_category: dict[str, list[str]] = field(default_factory=dict) + front_axis_overrides: dict[str, FrontAxisOverride] = field(default_factory=dict) + + +_PROCESS_OUTPUT_ROOT: Path | None = None +_PROCESS_METADATA: ReleaseMetadata | None = None +_PROCESS_RENDER_VIEWS = True + + +@dataclass(slots=True) +class GeometryEvidence: + vertices: Any + collision_vertices: Any | None + triangle_count: int + material_count: int + pbr_channels: PbrChannels + material_names: list[str] + texture_dependencies: list[str] + missing_dependencies: list[str] + format_extensions: list[str] + loader_compatibility: dict[str, str] + native_up: tuple[float, float, float] + native_front: tuple[float, float, float] + native_to_meter_scale: float + canonical_transform: tuple[float, ...] + source_bbox_min_m: tuple[float, float, float] + source_bbox_max_m: tuple[float, float, float] + articulated: bool = False + movable_parts: list[dict[str, Any]] = field(default_factory=list) + explicit_collision: bool = False + inferred: list[str] = field(default_factory=list) + + +class _MissingAssetDependencies(Exception): + def __init__(self, paths: Sequence[str]) -> None: + self.paths = list(paths) + super().__init__("|".join(self.paths)) + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _sha256_json(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + +def _words(value: str) -> list[str]: + return re.findall(r"[a-z0-9]+", value.casefold().replace("_", " ").replace("-", " ")) + + +def _clean_category(value: str) -> str: + normalized = normalize_category(value).strip() + aliases = { + "bin": "trash can", + "bookshelf": "bookcase", + "couch": "sofa", + "drawer": "chest of drawers", + "dresser": "chest of drawers", + "filing cabinet": "cabinet", + "fridge": "refrigerator", + "office chair": "chair", + "painting": "picture", + "picture frame": "picture", + "seat": "chair", + "standing lamp": "floor lamp", + "trashcan": "trash can", + "tv": "television", + "wardrobe": "wardrobe", + } + return aliases.get(normalized, normalized or "object") + + +_CATEGORY_HINTS: tuple[tuple[tuple[str, ...], str], ...] = ( + (("floor lamp", "standing lamp"), "floor lamp"), + (("ceiling lamp", "ceiling light", "pendant light"), "ceiling lamp"), + (("desk lamp", "table lamp"), "table lamp"), + (("office chair", "desk chair", "task chair", "work chair"), "chair"), + (("armchair", "accent chair", "easy chair", "reading chair"), "armchair"), + (("side table", "bedside table", "nightstand", "end table"), "side table"), + (("chest of drawers", "drawer chest", "dresser"), "chest of drawers"), + (("bookcase", "bookshelf", "book shelf"), "bookcase"), + (("work desk", "writing desk", "computer desk", "desk"), "desk"), + (("dining table", "coffee table", "work table", "table"), "table"), + (("storage cabinet", "shoe cabinet", "sideboard", "cupboard", "cabinet"), "cabinet"), + (("wardrobe", "armoire"), "wardrobe"), + (("floor plant", "potted plant", "houseplant", "plant"), "potted plant"), + (("wall art", "painting", "picture", "poster", "artwork"), "picture"), + (("trash can", "trashcan", "waste bin", "pedal bin", "bin"), "trash can"), + (("sofa", "couch", "settee"), "sofa"), + (("stool",), "stool"), + (("bench",), "bench"), + (("shelf",), "shelf"), + (("chair",), "chair"), + (("lamp", "lightbox"), "lamp"), + (("bed",), "bed"), + (("basket",), "basket"), + (("carton", "cardboard box", "storage box"), "box"), + (("clock",), "clock"), + (("monitor", "display"), "monitor"), + (("vase",), "vase"), + (("mug", "cup"), "mug"), + (("bottle",), "bottle"), + (("medical", "surgical", "anesthesia", "incubator", "ultrasound"), "medical equipment"), +) + + +def _record_category(record: AssetRecord, semantic: HssdSemantic | None) -> str: + display = " ".join(_words(record.display_name)) + # Prefer explicit object names for well-defined refinements when an + # upstream semantic class is broad (for example HSSD labels some open + # bookcases as cabinets, which would incorrectly invent door clearance). + refinements: tuple[tuple[tuple[str, ...], str], ...] = ( + (("floor lamp", "standing lamp"), "floor lamp"), + (("bookcase", "bookshelf", "book shelf"), "bookcase"), + (("side table", "bedside table", "end table", "nightstand"), "side table"), + (("chest of drawers", "drawer chest", "dresser"), "chest of drawers"), + (("armchair", "accent chair", "easy chair", "reading chair"), "armchair"), + (("potted plant", "indoor plant"), "potted plant"), + (("wall art", "painting", "picture"), "picture"), + (("wardrobe", "armoire"), "wardrobe"), + ) + for phrases, category in refinements: + if any(phrase in display for phrase in phrases): + return category + if semantic and semantic.category: + return _clean_category(semantic.category) + candidate = _clean_category(record.normalized_category or "") + candidate_words = _words(candidate) + # Earlier indexes sometimes stored the complete tokenized search document + # in normalized_category. It is useful for retrieval, but is not a class. + if candidate not in {"", "object"} and len(candidate_words) <= 5: + return candidate + text = " ".join( + _words( + " ".join( + [ + record.display_name, + record.description, + record.category, + Path(record.usd_path).stem, + ] + ) + ) + ) + for phrases, category in _CATEGORY_HINTS: + if any(phrase in text for phrase in phrases): + return category + source_category = _clean_category(record.category.split("/")[-1]) + return source_category if len(_words(source_category)) <= 4 else "object" + + +def _bool_cell(value: str) -> bool: + return value.strip().casefold() in {"1", "true", "yes", "y"} + + +def load_front_axis_overrides(path: Path | None) -> dict[str, FrontAxisOverride]: + if path is None: + return {} + payload = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(payload, dict) or payload.get("schema_version") != "1.0": + raise ValueError("front-axis override file must use schema_version 1.0") + entries = payload.get("overrides") + if not isinstance(entries, list): + raise ValueError("front-axis override file requires an overrides list") + output: dict[str, FrontAxisOverride] = {} + allowed_axes = {"+X", "-X", "+Y", "-Y"} + allowed_sources = {"multiview_verified", "manual_override"} + for index, raw in enumerate(entries): + if not isinstance(raw, dict): + raise ValueError(f"front-axis override {index} must be an object") + asset_id = str(raw.get("asset_id") or "").strip() + asset_sha256 = str(raw.get("asset_sha256") or "").casefold() + front_axis = str(raw.get("front_axis") or "") + source = str(raw.get("source") or "") + confidence = float(raw.get("confidence", 0.0)) + evidence_raw = raw.get("evidence") + evidence = ( + tuple(str(item).strip() for item in evidence_raw if str(item).strip()) + if isinstance(evidence_raw, list) + else () + ) + if not asset_id: + raise ValueError(f"front-axis override {index} has no asset_id") + if asset_id in output: + raise ValueError(f"duplicate front-axis override: {asset_id}") + if not re.fullmatch(r"[0-9a-f]{64}", asset_sha256): + raise ValueError(f"invalid front-axis override sha256: {asset_id}") + if front_axis not in allowed_axes: + raise ValueError(f"invalid front-axis override direction: {asset_id}") + if source not in allowed_sources: + raise ValueError(f"invalid front-axis override source: {asset_id}") + if not 0.9 <= confidence <= 1.0: + raise ValueError(f"verified front-axis confidence must be in [0.9, 1]: {asset_id}") + if not evidence: + raise ValueError(f"verified front-axis override requires evidence: {asset_id}") + output[asset_id] = FrontAxisOverride( + asset_id=asset_id, + asset_sha256=asset_sha256, + front_axis=cast(Literal["+X", "-X", "+Y", "-Y"], front_axis), + source=cast(Literal["multiview_verified", "manual_override"], source), + confidence=confidence, + evidence=evidence, + note=str(raw.get("note") or "").strip(), + ) + return output + + +def load_release_metadata( + hssd_root: Path | None, + front_axis_overrides_path: Path | None = None, +) -> ReleaseMetadata: + metadata = ReleaseMetadata( + hssd_root=hssd_root, + front_axis_overrides=load_front_axis_overrides(front_axis_overrides_path), + ) + if hssd_root is None or not hssd_root.is_dir(): + return metadata + semantics_path = hssd_root / "metadata" / "hssd_obj_semantics_condensed.csv" + if semantics_path.is_file(): + with semantics_path.open("r", encoding="utf-8-sig", newline="") as handle: + rows = csv.reader(handle) + next(rows, None) + for row in rows: + if len(row) < 4 or not row[0].strip(): + continue + metadata.hssd_semantics[row[0].strip()] = HssdSemantic( + category=_clean_category(row[3]), + articulated=_bool_cell(row[1]), + pickable=_bool_cell(row[2]), + ) + objects_path = hssd_root / "metadata" / "objects.json" + if objects_path.is_file(): + payload = json.loads(objects_path.read_text(encoding="utf-8")) + for asset_id, value in payload.items(): + item = metadata.hssd_semantics.setdefault(str(asset_id), HssdSemantic()) + item.name = str(value.get("name") or "") + affordance_path = hssd_root / "metadata" / "affordance_objects.csv" + if affordance_path.is_file(): + with affordance_path.open("r", encoding="utf-8-sig", newline="") as handle: + for row in csv.reader(handle): + if len(row) < 3: + continue + try: + categories = ast.literal_eval(row[-1]) + except (ValueError, SyntaxError): + continue + if not isinstance(categories, list): + continue + action = row[0].strip() + for category in categories: + key = _clean_category(str(category)) + if action and action not in metadata.affordances_by_category.setdefault( + key, [] + ): + metadata.affordances_by_category[key].append(action) + return metadata + + +def _hssd_id(record: AssetRecord, path: Path) -> str | None: + if record.source == "HSSD" or record.asset_id.startswith("hssd:"): + stem = path.stem + for suffix in (".collider", ".filteredSupportSurface", ".supportSurface"): + stem = stem.removesuffix(suffix) + return stem + return None + + +def _gltf_document(path: Path) -> dict[str, Any] | None: + if path.suffix.casefold() == ".gltf": + document = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(document, dict): + raise ValueError("gltf_root_is_not_an_object") + return cast(dict[str, Any], document) + if path.suffix.casefold() != ".glb": + return None + with path.open("rb") as handle: + header = handle.read(12) + if len(header) != 12: + raise ValueError("truncated_glb_header") + magic, version, total_length = struct.unpack("<4sII", header) + if magic != b"glTF" or version != 2 or total_length > path.stat().st_size: + raise ValueError("invalid_glb_header") + while handle.tell() + 8 <= total_length: + length, chunk_type = struct.unpack(" tuple[PbrChannels, int, list[str], list[str], list[str], list[str]]: + dependencies: list[str] = [] + missing: list[str] = [] + for section in ("buffers", "images"): + for item in document.get(section) or []: + uri = str(item.get("uri") or "") + if not uri or uri.startswith("data:"): + continue + candidate = (path.parent / urllib.parse.unquote(uri)).resolve() + dependencies.append(str(candidate)) + if not candidate.is_file(): + missing.append(str(candidate)) + materials = document.get("materials") or [] + names = [str(item.get("name") or "") for item in materials if item.get("name")] + base = normal = roughness = metallic = occlusion = emissive = False + for material in materials: + pbr = material.get("pbrMetallicRoughness") or {} + base = base or bool(pbr.get("baseColorTexture") or pbr.get("baseColorFactor")) + roughness = roughness or bool( + pbr.get("metallicRoughnessTexture") or "roughnessFactor" in pbr + ) + metallic = metallic or bool(pbr.get("metallicRoughnessTexture") or "metallicFactor" in pbr) + normal = normal or bool(material.get("normalTexture")) + occlusion = occlusion or bool(material.get("occlusionTexture")) + emissive = emissive or bool( + material.get("emissiveTexture") or material.get("emissiveFactor") + ) + if materials and not base: + base = True + return ( + PbrChannels( + base_color=base, + normal=normal, + roughness=roughness, + metallic=metallic, + occlusion=occlusion, + emissive=emissive, + ), + len(materials), + names, + dependencies, + missing, + sorted(set(str(value) for value in document.get("extensionsRequired") or [])), + ) + + +def _orientation_from_config( + path: Path, default_up: Sequence[float], default_front: Sequence[float] +) -> tuple[tuple[float, float, float], tuple[float, float, float], bool]: + stem = path.stem.split(".", 1)[0] + config = path.with_name(f"{stem}.object_config.json") + if config.is_file(): + payload = json.loads(config.read_text(encoding="utf-8")) + up = payload.get("up") + front = payload.get("front") + if isinstance(up, list) and len(up) == 3 and isinstance(front, list) and len(front) == 3: + return ( + (float(up[0]), float(up[1]), float(up[2])), + (float(front[0]), float(front[1]), float(front[2])), + True, + ) + return ( + (float(default_up[0]), float(default_up[1]), float(default_up[2])), + (float(default_front[0]), float(default_front[1]), float(default_front[2])), + False, + ) + + +def _canonical_rotation(up: Sequence[float], front: Sequence[float]) -> Any: + import numpy as np + + source_up = np.asarray(up, dtype=float) + source_front = np.asarray(front, dtype=float) + if not np.isfinite(source_up).all() or not np.isfinite(source_front).all(): + raise ValueError("non_finite_orientation") + source_up /= np.linalg.norm(source_up) + source_front -= source_up * float(np.dot(source_front, source_up)) + if np.linalg.norm(source_front) < 1.0e-8: + raise ValueError("parallel_up_and_front") + source_front /= np.linalg.norm(source_front) + source_right = np.cross(source_front, source_up) + source_right /= np.linalg.norm(source_right) + target_right = np.array([1.0, 0.0, 0.0]) + target_up = np.array([0.0, 0.0, 1.0]) + target_front = np.array([0.0, 1.0, 0.0]) + source_basis = np.column_stack([source_right, source_up, source_front]) + target_basis = np.column_stack([target_right, target_up, target_front]) + return target_basis @ np.linalg.inv(source_basis) + + +def _transform_matrix(rotation: Any, scale: float) -> tuple[float, ...]: + import numpy as np + + matrix = np.eye(4, dtype=float) + matrix[:3, :3] = rotation * scale + return tuple(float(value) for value in matrix.reshape(-1)) + + +_CANONICAL_FRONT_VECTORS: dict[str, tuple[float, float, float]] = { + "+X": (1.0, 0.0, 0.0), + "-X": (-1.0, 0.0, 0.0), + "+Y": (0.0, 1.0, 0.0), + "-Y": (0.0, -1.0, 0.0), +} + + +def _native_front_for_canonical_axis( + canonical_transform: Sequence[float], front_axis: str +) -> tuple[float, float, float]: + import numpy as np + + transform = np.asarray(canonical_transform, dtype=float).reshape(4, 4) + canonical = np.asarray(_CANONICAL_FRONT_VECTORS[front_axis], dtype=float) + native = np.linalg.solve(transform[:3, :3], canonical) + length = float(np.linalg.norm(native)) + if not math.isfinite(length) or length <= 1.0e-9: + raise ValueError("front-axis override produced an invalid native direction") + native /= length + return ( + round(float(native[0]), 9), + round(float(native[1]), 9), + round(float(native[2]), 9), + ) + + +def certify_descriptor_front_axis( + descriptor: AssetDescriptor, + override: FrontAxisOverride | None = None, +) -> AssetDescriptor: + """Attach truthful semantic-front provenance without changing asset geometry.""" + + if descriptor.status != "ACTIVE": + return descriptor + if override is None and descriptor.front_axis_source != "unknown": + return descriptor + value = descriptor.model_dump(mode="json") + observed = set(descriptor.observed_fields) + inferred = set(descriptor.inferred_fields) + confidence = dict(descriptor.confidence) + if override is None: + from_source_metadata = "native_front_vector" in observed + value["front_axis_source"] = ( + "source_metadata" if from_source_metadata else "dataset_convention" + ) + value["front_axis_evidence"] = [ + ( + "source orientation metadata; semantic front not yet verified by material views" + if from_source_metadata + else "format default orientation; semantic front not yet verified by material views" + ) + ] + confidence["front_axis"] = 0.75 if from_source_metadata else 0.55 + if from_source_metadata: + observed.add("front_axis") + inferred.discard("front_axis") + else: + inferred.add("front_axis") + observed.discard("front_axis") + else: + if descriptor.asset_id != override.asset_id: + raise ValueError("front-axis override asset_id mismatch") + if descriptor.sha256 != override.asset_sha256: + raise ValueError( + f"front-axis override sha256 mismatch for {descriptor.asset_id}: " + f"expected {override.asset_sha256}, observed {descriptor.sha256}" + ) + evidence = list(override.evidence) + if override.note: + evidence.append(f"note:{override.note}") + value.update( + front_axis=override.front_axis, + front_axis_source=override.source, + front_axis_evidence=evidence, + native_front_vector=_native_front_for_canonical_axis( + descriptor.canonical_transform, override.front_axis + ), + ) + confidence["front_axis"] = override.confidence + confidence["native_front_vector"] = override.confidence + observed.add("front_axis") + inferred.discard("front_axis") + # The semantic native vector is derived by applying the inverse of the + # measured canonical transform to the verified canonical direction. + inferred.add("native_front_vector") + observed.discard("native_front_vector") + value["observed_fields"] = sorted(observed - inferred) + value["inferred_fields"] = sorted(inferred) + value["confidence"] = confidence + return AssetDescriptor.model_validate(value) + + +def _mesh_geometry(path: Path, record: AssetRecord) -> GeometryEvidence: + import numpy as np + import trimesh # type: ignore[import-not-found] + + document = _gltf_document(path) + if document is not None: + pbr, material_count, names, dependencies, missing, format_extensions = ( + _gltf_material_evidence(path, document) + ) + else: + pbr = PbrChannels(base_color=True) + material_count, names, dependencies, missing = 1, [], [], [] + format_extensions = [] + loaded = trimesh.load(str(path), force="scene", process=False) + mesh = loaded.to_geometry() if isinstance(loaded, trimesh.Scene) else loaded + vertices = np.asarray(mesh.vertices, dtype=float) + faces = np.asarray(mesh.faces) + if vertices.ndim != 2 or vertices.shape[1] != 3 or len(vertices) < 3: + raise ValueError("no_geometry_vertices") + if faces.ndim != 2 or len(faces) < 1: + raise ValueError("no_geometry_faces") + if not np.isfinite(vertices).all(): + raise ValueError("non_finite_geometry") + default_up = (0.0, 1.0, 0.0) if path.suffix.casefold() in {".glb", ".gltf"} else (0.0, 0.0, 1.0) + default_front = (0.0, 0.0, -1.0) if default_up[1] else (0.0, 1.0, 0.0) + native_up, native_front, observed_orientation = _orientation_from_config( + path, default_up, default_front + ) + rotation = _canonical_rotation(native_up, native_front) + source_min = vertices.min(axis=0) + source_max = vertices.max(axis=0) + scale = 1.0 + canonical = (rotation @ (vertices * scale).T).T + collision_path = path.with_name(f"{path.stem}.collider{path.suffix}") + collision_vertices = None + explicit_collision = False + if collision_path.is_file(): + collision_loaded = trimesh.load(str(collision_path), force="scene", process=False) + collision_mesh = ( + collision_loaded.to_geometry() + if isinstance(collision_loaded, trimesh.Scene) + else collision_loaded + ) + collision_raw = np.asarray(collision_mesh.vertices, dtype=float) + if collision_raw.ndim == 2 and collision_raw.shape[1] == 3 and len(collision_raw) >= 3: + collision_vertices = (rotation @ (collision_raw * scale).T).T + explicit_collision = bool(np.isfinite(collision_vertices).all()) + inferred = [] if observed_orientation else ["native_orientation"] + return GeometryEvidence( + vertices=canonical, + collision_vertices=collision_vertices, + triangle_count=int(len(faces)), + material_count=material_count, + pbr_channels=pbr, + material_names=names, + texture_dependencies=dependencies, + missing_dependencies=missing, + format_extensions=format_extensions, + loader_compatibility={ + "trimesh": "verified", + "blender_gltf": ( + "unsupported" if "KHR_texture_basisu" in format_extensions else "compatible" + ), + "blender_gltf_basisu_repair": ( + "compatible" if "KHR_texture_basisu" in format_extensions else "not_tested" + ), + }, + native_up=native_up, + native_front=native_front, + native_to_meter_scale=scale, + canonical_transform=_transform_matrix(rotation, scale), + source_bbox_min_m=( + float(source_min[0] * scale), + float(source_min[1] * scale), + float(source_min[2] * scale), + ), + source_bbox_max_m=( + float(source_max[0] * scale), + float(source_max[1] * scale), + float(source_max[2] * scale), + ), + explicit_collision=explicit_collision, + inferred=inferred, + ) + + +def _asset_paths(value: Any) -> Iterable[str]: + try: + from pxr import Sdf # type: ignore[import-not-found] + except ImportError: + return [] + if isinstance(value, Sdf.AssetPath): + # Prefer USD's layer-aware resolved path. Referenced material layers + # (notably ArtVIP's resource/material.usd) author paths relative to + # their own layer, not relative to the root model layer. + return [value.resolvedPath or value.path] + if isinstance(value, (list, tuple)): + output: list[str] = [] + for item in value: + output.extend(_asset_paths(item)) + return output + return [] + + +def _usd_composition_dependencies(path: Path) -> tuple[list[str], list[str]]: + from pxr import UsdUtils + + layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(path)) + dependencies: list[str] = [] + for layer in layers: + layer_path = str(getattr(layer, "realPath", "") or getattr(layer, "identifier", "")) + if layer_path and not layer_path.startswith("anon:"): + dependencies.append(layer_path) + dependencies.extend(str(asset) for asset in assets if str(asset)) + missing = [str(asset) for asset in unresolved if str(asset)] + return sorted(set(dependencies)), sorted(set(missing)) + + +def _usd_geometry(path: Path, _record: AssetRecord) -> GeometryEvidence: + import numpy as np + from pxr import Gf, Usd, UsdGeom, UsdPhysics + + dependencies, missing = _usd_composition_dependencies(path) + if missing: + raise _MissingAssetDependencies(missing) + stage = Usd.Stage.Open(str(path)) + if stage is None: + raise ValueError("usd_stage_open_failed") + meters_per_unit = float(UsdGeom.GetStageMetersPerUnit(stage)) + if not math.isfinite(meters_per_unit) or meters_per_unit <= 0: + raise ValueError("invalid_usd_meters_per_unit") + up_axis = str(UsdGeom.GetStageUpAxis(stage)).upper() + default_up = (0.0, 0.0, 1.0) if up_axis == "Z" else (0.0, 1.0, 0.0) + default_front = (0.0, 1.0, 0.0) if up_axis == "Z" else (0.0, 0.0, -1.0) + native_up, native_front, observed_orientation = _orientation_from_config( + path, default_up, default_front + ) + rotation = _canonical_rotation(native_up, native_front) + xforms = UsdGeom.XformCache(Usd.TimeCode.Default()) + vertices: list[tuple[float, float, float]] = [] + collision_vertices: list[tuple[float, float, float]] = [] + triangle_count = 0 + material_names: list[str] = [] + joints: list[dict[str, Any]] = [] + articulated = False + channels = Counter[str]() + for prim in stage.Traverse(): + if prim.IsA(UsdGeom.Mesh): + points = UsdGeom.Mesh(prim).GetPointsAttr().Get() or [] + matrix = xforms.GetLocalToWorldTransform(prim) + transformed = [matrix.Transform(Gf.Vec3d(*point)) for point in points] + tuples = [(float(point[0]), float(point[1]), float(point[2])) for point in transformed] + vertices.extend(tuples) + if prim.HasAPI(UsdPhysics.CollisionAPI): + collision_vertices.extend(tuples) + counts = UsdGeom.Mesh(prim).GetFaceVertexCountsAttr().Get() or [] + triangle_count += sum(max(int(count) - 2, 0) for count in counts) + if prim.GetTypeName() == "Material": + material_names.append(prim.GetName()) + if prim.HasAPI(UsdPhysics.ArticulationRootAPI): + articulated = True + if prim.IsA(UsdPhysics.Joint): + articulated = True + joints.append({"name": prim.GetName(), "type": prim.GetTypeName()}) + for attribute in prim.GetAttributes(): + name = attribute.GetName().casefold() + if "diffuse" in name or "basecolor" in name: + channels["base_color"] += 1 + if "normal" in name: + channels["normal"] += 1 + if "roughness" in name: + channels["roughness"] += 1 + if "metallic" in name: + channels["metallic"] += 1 + try: + value = attribute.Get() + except Exception: + continue + for asset_path in _asset_paths(value): + if not asset_path or asset_path.startswith(("http://", "https://")): + continue + candidate = (path.parent / asset_path).resolve() + dependencies.append(str(candidate)) + if not candidate.is_file(): + missing.append(str(candidate)) + raw = np.asarray(vertices, dtype=float) + if raw.ndim != 2 or raw.shape[1] != 3 or len(raw) < 3 or triangle_count < 1: + raise ValueError("usd_has_no_triangle_geometry") + if not np.isfinite(raw).all(): + raise ValueError("non_finite_geometry") + source_min = raw.min(axis=0) * meters_per_unit + source_max = raw.max(axis=0) * meters_per_unit + canonical = (rotation @ (raw * meters_per_unit).T).T + collision = None + if collision_vertices: + collision_raw = np.asarray(collision_vertices, dtype=float) + collision = (rotation @ (collision_raw * meters_per_unit).T).T + inferred = [] if observed_orientation else ["native_orientation"] + if collision is None: + inferred.append("collision_footprint_polygon_m") + return GeometryEvidence( + vertices=canonical, + collision_vertices=collision, + triangle_count=triangle_count, + material_count=len(material_names), + pbr_channels=PbrChannels( + base_color=bool(channels["base_color"] or material_names), + normal=bool(channels["normal"]), + roughness=bool(channels["roughness"]), + metallic=bool(channels["metallic"]), + ), + material_names=material_names, + texture_dependencies=sorted(set(dependencies)), + missing_dependencies=sorted(set(missing)), + format_extensions=[], + loader_compatibility={"pxr_usd": "verified"}, + native_up=native_up, + native_front=native_front, + native_to_meter_scale=meters_per_unit, + canonical_transform=_transform_matrix(rotation, meters_per_unit), + source_bbox_min_m=( + float(source_min[0]), + float(source_min[1]), + float(source_min[2]), + ), + source_bbox_max_m=( + float(source_max[0]), + float(source_max[1]), + float(source_max[2]), + ), + articulated=articulated, + movable_parts=joints, + explicit_collision=collision is not None, + inferred=inferred, + ) + + +def _sdf_geometry(path: Path, record: AssetRecord) -> GeometryEvidence: + root = ET.parse(path).getroot() + uri = root.findtext(".//mesh/uri") + if uri: + normalized = uri.removeprefix("file://") + candidate = Path(normalized) + if not candidate.is_absolute(): + candidate = (path.parent / candidate).resolve() + if not candidate.is_file(): + raise ValueError(f"sdf_missing_mesh:{candidate}") + if candidate.suffix.casefold() in {".usd", ".usda", ".usdc", ".usdz"}: + with _USD_INSPECTION_LOCK: + evidence = _usd_geometry(candidate, record) + else: + evidence = _mesh_geometry(candidate, record) + evidence.texture_dependencies = sorted( + set([*evidence.texture_dependencies, str(candidate)]) + ) + return evidence + raise ValueError("sdf_has_no_supported_mesh_geometry") + + +def load_geometry_evidence(path: Path, record: AssetRecord) -> GeometryEvidence: + suffix = path.suffix.casefold() + if suffix in {".glb", ".gltf", ".obj", ".fbx"}: + return _mesh_geometry(path, record) + if suffix in {".usd", ".usda", ".usdc", ".usdz"}: + with _USD_INSPECTION_LOCK: + return _usd_geometry(path, record) + if suffix == ".sdf": + return _sdf_geometry(path, record) + raise ValueError(f"unsupported_geometry_format:{suffix or 'none'}") + + +def _polygon(points: Any, *, minimum_thickness_m: float = 0.005) -> Polygon: + import numpy as np + + values = np.asarray(points, dtype=float) + if values.ndim != 2 or values.shape[1] != 2 or len(values) < 1: + raise ValueError("footprint_has_no_points") + if len(values) > 100_000: + stride = max(1, len(values) // 100_000) + extrema = values[ + np.unique( + np.concatenate( + [ + np.argmin(values, axis=0), + np.argmax(values, axis=0), + np.arange(0, len(values), stride), + ] + ) + ) + ] + values = extrema + geometry = MultiPoint(values).convex_hull + if isinstance(geometry, Polygon) and geometry.area > 1.0e-10: + return geometry + return geometry.buffer(minimum_thickness_m / 2.0, cap_style="square").convex_hull + + +def _points(polygon: Polygon) -> list[Point2]: + return [(round(float(x), 6), round(float(y), 6)) for x, y in polygon.exterior.coords[:-1]] + + +def _clearances(category: str, visual: Polygon, height: float) -> list[OperationalClearance]: + min_x, min_y, max_x, max_y = visual.bounds + width = max_x - min_x + result: list[OperationalClearance] = [] + if category in {"cabinet", "chest of drawers", "refrigerator", "wardrobe"}: + polygon = box(min_x - 0.05, max_y, max_x + 0.05, max_y + min(0.9, max(0.45, width))) + result.append( + OperationalClearance( + clearance_id="front_opening", + operation="open doors or drawers", + polygon_m=_points(polygon), + height_range_m=(0.0, max(height, 0.1)), + source="inferred", + confidence=0.72, + ) + ) + elif category in {"chair", "office chair"}: + polygon = box(min_x - 0.08, min_y - 0.75, max_x + 0.08, min_y) + result.append( + OperationalClearance( + clearance_id="chair_pull_out", + operation="pull chair out and sit", + polygon_m=_points(polygon), + height_range_m=(0.0, max(height, 0.1)), + source="inferred", + confidence=0.78, + ) + ) + elif category == "armchair": + polygon = box(min_x - 0.05, max_y, max_x + 0.05, max_y + 0.45) + result.append( + OperationalClearance( + clearance_id="reading_approach", + operation="approach and sit", + polygon_m=_points(polygon), + height_range_m=(0.0, max(height, 0.1)), + source="inferred", + confidence=0.70, + ) + ) + return result + + +def _support_semantics(category: str) -> tuple[str, str]: + if category in {"picture", "wall art", "mirror", "wall lamp"}: + return "wall", "required" + if category in {"ceiling lamp", "ceiling light"}: + return "ceiling", "none" + if category in { + "book", + "bottle", + "bowl", + "cup", + "mug", + "vase", + "target object", + }: + return "surface", "none" + if category in {"bookcase", "cabinet", "chest of drawers", "desk", "shelf", "television"}: + return "floor", "preferred" + return "floor", "none" + + +def _obb(visual: Polygon, minimum_z: float, maximum_z: float) -> OrientedBoundingBox: + rectangle = visual.minimum_rotated_rectangle + coordinates = list(rectangle.exterior.coords)[:-1] + lengths = [math.dist(coordinates[index], coordinates[(index + 1) % 4]) for index in range(4)] + longest = max(range(4), key=lengths.__getitem__) + first = coordinates[longest] + second = coordinates[(longest + 1) % 4] + yaw = math.degrees(math.atan2(second[1] - first[1], second[0] - first[0])) + width = lengths[longest] + depth = lengths[(longest + 1) % 4] + center = rectangle.centroid + return OrientedBoundingBox( + center_m=(float(center.x), float(center.y), (minimum_z + maximum_z) / 2.0), + size_m=(float(width), float(depth), float(maximum_z - minimum_z)), + yaw_deg=float(((yaw + 180.0) % 360.0) - 180.0), + footprint_polygon_m=_points(rectangle), + ) + + +def _semantic_tags(record: AssetRecord, category: str, semantic: HssdSemantic | None) -> list[str]: + values = set(_words(" ".join([record.display_name, record.category, *record.tags]))) + values.update(_words(category)) + if semantic and semantic.pickable: + values.add("pickable") + if record.admission_status != AdmissionStatus.ACTIVE: + values.add("newly_released") + return sorted(values) + + +def _tag_subset(text: str, candidates: Iterable[str]) -> list[str]: + normalized = " ".join(_words(text)) + return sorted(candidate for candidate in candidates if candidate in normalized) + + +def _quality( + evidence: GeometryEvidence, + *, + collision_explicit: bool, + support_observed: bool, +) -> AssetQuality: + geometry = 55 + min(25, int(math.log10(max(10, evidence.triangle_count)) * 8)) + geometry += 10 if collision_explicit else 0 + geometry += 5 if support_observed else 0 + geometry = min(100, geometry) + material_channels = sum(bool(value) for value in evidence.pbr_channels.model_dump().values()) + materials = min(100, 35 + material_channels * 10 + min(15, evidence.material_count * 3)) + realism = min(100, round(0.55 * geometry + 0.45 * materials)) + overall = round(0.45 * geometry + 0.35 * materials + 0.20 * realism) + return AssetQuality( + geometry=geometry, + materials=materials, + realism=realism, + overall=overall, + ) + + +def _project(vertices: Any, view: str) -> Any: + import numpy as np + + if view == "top": + return vertices[:, [0, 1]] + if view == "front": + return vertices[:, [0, 2]] + if view == "side": + return vertices[:, [1, 2]] + matrix = np.array([[0.86, -0.50, 0.0], [0.24, 0.42, 0.82]], dtype=float) + return vertices @ matrix.T + + +def _render_view(path: Path, vertices: Any, view: str, size: int, label: str) -> None: + import numpy as np + + projected = _project(vertices, view) + polygon = _polygon(projected, minimum_thickness_m=0.001) + coordinates = np.asarray(polygon.exterior.coords[:-1], dtype=float) + minimum = coordinates.min(axis=0) + maximum = coordinates.max(axis=0) + span = np.maximum(maximum - minimum, 1.0e-6) + margin = max(12, size // 12) + usable = size - 2 * margin + scale = min(usable / span[0], usable / span[1]) + pixels = [ + ( + margin + float((point[0] - minimum[0]) * scale), + size - margin - float((point[1] - minimum[1]) * scale), + ) + for point in coordinates + ] + image = Image.new("RGB", (size, size), (247, 244, 236)) + draw = ImageDraw.Draw(image) + draw.rounded_rectangle((4, 4, size - 5, size - 5), radius=9, outline=(185, 177, 160), width=2) + draw.polygon(pixels, fill=(91, 121, 112), outline=(26, 55, 52)) + draw.line([*pixels, pixels[0]], fill=(26, 55, 52), width=max(1, size // 96)) + draw.text((margin, 7), f"{label[:22]} · {view}", fill=(39, 48, 45)) + path.parent.mkdir(parents=True, exist_ok=True) + # Identical assets can be inspected concurrently before deduplication. + # A per-thread temporary name prevents the two renderers from racing on + # the same shared-content view path. + temporary = path.with_suffix(path.suffix + f".{os.getpid()}.{threading.get_ident()}.tmp") + image.save(temporary, format="PNG", optimize=True) + temporary.replace(path) + + +def render_multiviews( + output_root: Path, sha256: str, vertices: Any, label: str +) -> tuple[str, list[str]]: + directory = output_root / "views" / sha256[:2] / sha256 + thumbnail = directory / "thumbnail.png" + view_paths = [directory / f"{view}.png" for view in ("front", "side", "top", "perspective")] + if not thumbnail.is_file(): + _render_view(thumbnail, vertices, "perspective", 128, label) + for view_path, view in zip(view_paths, ("front", "side", "top", "perspective"), strict=True): + if not view_path.is_file(): + _render_view(view_path, vertices, view, 256, label) + return str(thumbnail.resolve()), [str(path.resolve()) for path in view_paths] + + +def _minimal_quarantine(record: AssetRecord, path: Path, reason: str) -> AssetDescriptor: + synthetic_hash = hashlib.sha256( + (record.content_hash or f"{record.asset_id}\0{path}").encode("utf-8") + ).hexdigest() + return AssetDescriptor( + asset_id=record.asset_id, + source=record.source or "unknown", + source_license=record.source_license or "unknown", + source_path=str(path), + canonical_path=str(path), + sha256=synthetic_hash, + category=_clean_category(record.normalized_category or record.category), + display_name=record.display_name or record.asset_id, + canonical_transform=( + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ), + native_bbox_m=(0.0, 0.0, 0.0), + source_bbox_min_m=(0.0, 0.0, 0.0), + source_bbox_max_m=(0.0, 0.0, 0.0), + quality=AssetQuality(geometry=0, materials=0, realism=0, overall=0), + geometry_format=path.suffix.casefold().lstrip("."), + loader_compatibility={}, + status="QUARANTINED", + status_reason=reason[:1000], + inferred_fields=["sha256"] if not path.is_file() else [], + confidence={"status": 1.0}, + ) + + +def inspect_record( + record: AssetRecord, + *, + output_root: Path, + metadata: ReleaseMetadata, + render_views: bool, +) -> AssetDescriptor: + path = Path(record.usd_path) + normalized_path = path.as_posix().casefold() + if record.source.casefold().endswith("artvip") and "/resource/" in normalized_path: + return _minimal_quarantine( + record, + path, + "artvip_internal_resource_component:not_a_primary_scene_asset", + ) + if record.asset_kind in NON_GEOMETRY_KINDS: + return _minimal_quarantine(record, path, "non_3d_asset_kind") + if not path.is_file(): + return _minimal_quarantine(record, path, "missing_runtime_path") + if path.suffix.casefold() not in SUPPORTED_GEOMETRY_EXTENSIONS: + return _minimal_quarantine(record, path, f"unsupported_geometry_format:{path.suffix}") + if not record.source_license.strip() or record.source_license.casefold() in { + "unknown", + "not permitted", + "prohibited", + }: + return _minimal_quarantine(record, path, "source_license_not_permitted") + try: + evidence = load_geometry_evidence(path, record) + except _MissingAssetDependencies as error: + return _minimal_quarantine( + record, + path, + "missing_material_or_texture_dependencies:" + "|".join(error.paths[:8]), + ) + except Exception as error: + reason = f"geometry_load_failed:{type(error).__name__}:{error}" + return _minimal_quarantine(record, path, reason) + import numpy as np + + hssd_id = _hssd_id(record, path) + semantic = metadata.hssd_semantics.get(hssd_id or "") + category = _record_category(record, semantic) + if category == "chair" and any( + token in " ".join(_words(record.display_name)) + for token in ("armchair", "accent chair", "easy chair") + ): + category = "armchair" + if category == "table" and any( + phrase in " ".join(_words(record.display_name)) for phrase in ("side table", "end table") + ): + category = "side table" + vertices = np.asarray(evidence.vertices, dtype=float) + # Thin wall-mounted art is frequently authored flat in HSSD even though + # its semantic mounting direction is vertical. Rotate the longest plane + # dimension into canonical Z while retaining a thin wall-normal footprint. + preliminary_dimensions = vertices.max(axis=0) - vertices.min(axis=0) + if category in {"picture", "painting", "wall art", "mirror"} and ( + preliminary_dimensions[2] < max(preliminary_dimensions[0], preliminary_dimensions[1]) * 0.20 + ): + if preliminary_dimensions[1] >= preliminary_dimensions[0]: + repair = np.array(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0))) + else: + repair = np.array(((0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 0.0))) + vertices = (repair @ vertices.T).T + if evidence.collision_vertices is not None: + evidence.collision_vertices = ( + repair @ np.asarray(evidence.collision_vertices, dtype=float).T + ).T + transform = np.asarray(evidence.canonical_transform, dtype=float).reshape(4, 4) + transform[:3, :3] = repair @ transform[:3, :3] + evidence.canonical_transform = tuple(float(value) for value in transform.reshape(-1)) + evidence.inferred.append("semantic_wall_mount_orientation_repair") + minimum = vertices.min(axis=0) + maximum = vertices.max(axis=0) + dimensions = maximum - minimum + if not np.isfinite(dimensions).all() or any(float(value) <= 1.0e-5 for value in dimensions): + return _minimal_quarantine(record, path, f"invalid_dimensions:{dimensions.tolist()}") + if float(dimensions.max()) > 15.0 or float(dimensions.min()) < 1.0e-5: + return _minimal_quarantine(record, path, f"abnormal_dimensions_m:{dimensions.tolist()}") + if evidence.missing_dependencies: + return _minimal_quarantine( + record, + path, + "missing_material_or_texture_dependencies:" + + "|".join(evidence.missing_dependencies[:8]), + ) + visual = _polygon(vertices[:, :2]) + if evidence.collision_vertices is not None: + collision = _polygon(np.asarray(evidence.collision_vertices)[:, :2]) + collision_source = "explicit" + else: + collision = visual.buffer(0.002, join_style="mitre") + collision_source = "visual_conservative" + evidence.inferred.append("collision_footprint_polygon_m") + ground_band = max(0.004, min(0.03, float(dimensions[2]) * 0.025)) + ground_points = vertices[vertices[:, 2] <= minimum[2] + ground_band, :2] + support_observed = len(ground_points) >= 3 + if support_observed: + support = _polygon(ground_points) + else: + support = collision.buffer(-min(0.005, math.sqrt(collision.area) * 0.02)) + if support.is_empty or not isinstance(support, Polygon): + support = collision + evidence.inferred.append("support_footprint_polygon_m") + clearances = _clearances(category, visual, float(dimensions[2])) + envelope_parts = [visual, collision, *[Polygon(item.polygon_m) for item in clearances]] + envelope = unary_union(envelope_parts).convex_hull + if not isinstance(envelope, Polygon): + envelope = collision + asset_sha = _sha256_file(path) + front_axis_override = metadata.front_axis_overrides.get(record.asset_id) + if front_axis_override and asset_sha != front_axis_override.asset_sha256: + return _minimal_quarantine( + record, + path, + "front_axis_override_sha256_mismatch:" + f"expected={front_axis_override.asset_sha256}:observed={asset_sha}", + ) + if render_views: + thumbnail, multiview = render_multiviews( + output_root, asset_sha, vertices, record.display_name + ) + else: + placeholder_dir = output_root / "views" / asset_sha[:2] / asset_sha + thumbnail = str((placeholder_dir / "thumbnail.png").resolve()) + multiview = [ + str((placeholder_dir / f"{view}.png").resolve()) + for view in ("front", "side", "top", "perspective") + ] + text = " ".join([record.display_name, record.description, record.category, *record.tags]) + material_text = " ".join([text, *evidence.material_names]) + support_type, wall_affinity = _support_semantics(category) + affordances = sorted( + set( + [*record.affordances, *metadata.affordances_by_category.get(category, [])] + + (["pick up and carry"] if semantic and semantic.pickable else []) + ) + ) + synonyms = sorted(set([*record.synonyms, *CATEGORY_SYNONYMS.get(category, ())])) + articulated = bool(evidence.articulated or (semantic and semantic.articulated)) + quality = _quality( + evidence, + collision_explicit=evidence.explicit_collision, + support_observed=support_observed, + ) + geometry_signature = _sha256_json( + { + "category": category, + "dimensions_5cm": [round(float(value) / 0.05) for value in dimensions], + "triangles_log2": round(math.log2(max(1, evidence.triangle_count))), + "materials": min(8, evidence.material_count), + } + )[:24] + observed = { + "sha256", + "native_bbox_m", + "visual_footprint_polygon_m", + "pbr_channels", + "geometry_counts", + "texture_dependencies", + "format_extensions", + } + if evidence.explicit_collision: + observed.add("collision_footprint_polygon_m") + if support_observed: + observed.add("support_footprint_polygon_m") + if "native_orientation" not in evidence.inferred: + observed.update({"native_up_vector", "native_front_vector"}) + inferred = set(evidence.inferred) + inferred.update( + { + "category", + "synonyms", + "style_tags", + "color_tags", + "material_tags", + "support_type", + "wall_affinity", + "operational_clearance", + "layout_reserve_envelope_polygon_m", + "quality", + "loader_compatibility", + } + ) + confidence = { + "geometry": 1.0, + "units": 1.0 if hssd_id or path.suffix.casefold().startswith(".usd") else 0.9, + "orientation": 1.0 if "native_orientation" not in inferred else 0.65, + "category": 0.98 if semantic and semantic.category else 0.78, + "collision": 1.0 if evidence.explicit_collision else 0.72, + "support_footprint": 0.95 if support_observed else 0.65, + "operational_clearance": 0.72 if clearances else 0.60, + "quality": 0.85, + "loader_compatibility": 0.95, + } + descriptor = AssetDescriptor( + asset_id=record.asset_id, + source=record.source, + source_license=record.source_license, + source_path=str(path.resolve()), + canonical_path=str(path.resolve()), + sha256=asset_sha, + category=category, + subcategory=record.category, + display_name=semantic.name if semantic and semantic.name else record.display_name, + semantic_tags=_semantic_tags(record, category, semantic), + synonyms=synonyms, + style_tags=_tag_subset(text, STYLE_WORDS), + color_tags=_tag_subset(text, COLOR_WORDS), + material_tags=_tag_subset(material_text, MATERIAL_WORDS), + pbr_channels=evidence.pbr_channels, + native_units="meter", + native_to_meter_scale=evidence.native_to_meter_scale, + native_up_vector=evidence.native_up, + native_front_vector=evidence.native_front, + canonical_transform=evidence.canonical_transform, + native_bbox_m=( + round(float(dimensions[0]), 6), + round(float(dimensions[1]), 6), + round(float(dimensions[2]), 6), + ), + source_bbox_min_m=evidence.source_bbox_min_m, + source_bbox_max_m=evidence.source_bbox_max_m, + visual_footprint_polygon_m=_points(visual), + collision_footprint_polygon_m=_points(collision), + support_footprint_polygon_m=_points(support), + layout_reserve_envelope_polygon_m=_points(envelope), + obb_m=_obb(visual, float(minimum[2]), float(maximum[2])), + height_m=round(float(dimensions[2]), 6), + support_type=support_type, # type: ignore[arg-type] + wall_affinity=wall_affinity, # type: ignore[arg-type] + articulated=articulated, + movable_parts=evidence.movable_parts, + operational_clearance=clearances, + affordances=affordances, + uniform_scale_range=(1.0, 1.0) if articulated else (0.9, 1.1), + quality=quality, + thumbnail=thumbnail, + multiview_images=multiview, + geometry_format=path.suffix.casefold().lstrip("."), + format_extensions=evidence.format_extensions, + loader_compatibility=evidence.loader_compatibility, # type: ignore[arg-type] + vertex_count=int(len(vertices)), + triangle_count=evidence.triangle_count, + material_count=evidence.material_count, + collision_source=collision_source, # type: ignore[arg-type] + texture_dependencies=evidence.texture_dependencies, + missing_dependencies=[], + geometry_signature=geometry_signature, + status="ACTIVE", + status_reason="", + observed_fields=sorted(observed - inferred), + inferred_fields=sorted(inferred), + confidence=confidence, + ) + return certify_descriptor_front_axis(descriptor, front_axis_override) + + +def _resolve_duplicates(descriptors: list[AssetDescriptor]) -> list[AssetDescriptor]: + by_hash: dict[str, list[int]] = defaultdict(list) + for index, descriptor in enumerate(descriptors): + if descriptor.status == "ACTIVE": + by_hash[descriptor.sha256].append(index) + for indices in by_hash.values(): + if len(indices) < 2: + continue + canonical_index = max( + indices, + key=lambda index: ( + descriptors[index].quality.overall, + bool(descriptors[index].collision_source == "explicit"), + descriptors[index].asset_id, + ), + ) + canonical_id = descriptors[canonical_index].asset_id + for index in indices: + if index == canonical_index: + continue + value = descriptors[index].model_dump(mode="json") + value.update( + status="QUARANTINED", + status_reason=f"duplicate_content:{canonical_id}", + canonical_asset_id=canonical_id, + ) + descriptors[index] = AssetDescriptor.model_validate(value) + by_signature: dict[str, list[int]] = defaultdict(list) + for index, descriptor in enumerate(descriptors): + if descriptor.status == "ACTIVE" and descriptor.geometry_signature: + by_signature[descriptor.geometry_signature].append(index) + for indices in by_signature.values(): + if len(indices) < 2: + continue + ids = [descriptors[index].asset_id for index in indices] + for index in indices: + value = descriptors[index].model_dump(mode="json") + value["near_duplicate_asset_ids"] = [ + asset_id for asset_id in ids if asset_id != descriptors[index].asset_id + ][:64] + descriptors[index] = AssetDescriptor.model_validate(value) + return descriptors + + +def _write_descriptor_index(descriptors: Sequence[AssetDescriptor], path: Path) -> None: + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.unlink(missing_ok=True) + connection = sqlite3.connect(temporary) + try: + connection.executescript( + """ + PRAGMA journal_mode=OFF; + PRAGMA synchronous=OFF; + CREATE TABLE asset_descriptors ( + asset_id TEXT PRIMARY KEY, + asset_sha256 TEXT NOT NULL, + source TEXT NOT NULL, + category TEXT NOT NULL, + support_type TEXT NOT NULL, + quality_overall INTEGER NOT NULL, + status TEXT NOT NULL, + status_reason TEXT NOT NULL, + canonical_path TEXT NOT NULL, + descriptor_json TEXT NOT NULL + ); + CREATE INDEX descriptor_status_category ON asset_descriptors(status, category); + CREATE INDEX descriptor_sha256 ON asset_descriptors(asset_sha256); + CREATE VIRTUAL TABLE active_descriptor_fts USING fts5( + asset_id, display_name, category, semantic_tags, synonyms, + style_tags, color_tags, material_tags, affordances, content='' + ); + """ + ) + for row_id, descriptor in enumerate(descriptors, start=1): + connection.execute( + "INSERT INTO asset_descriptors VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + descriptor.asset_id, + descriptor.sha256, + descriptor.source, + descriptor.category, + descriptor.support_type, + descriptor.quality.overall, + descriptor.status, + descriptor.status_reason, + descriptor.canonical_path, + descriptor.model_dump_json(), + ), + ) + if descriptor.status == "ACTIVE": + connection.execute( + "INSERT INTO active_descriptor_fts(" + "rowid, asset_id, display_name, category, semantic_tags, synonyms, " + "style_tags, color_tags, material_tags, affordances" + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + row_id, + descriptor.asset_id, + descriptor.display_name, + descriptor.category, + " ".join(descriptor.semantic_tags), + " ".join(descriptor.synonyms), + " ".join(descriptor.style_tags), + " ".join(descriptor.color_tags), + " ".join(descriptor.material_tags), + " ".join(descriptor.affordances), + ), + ) + connection.commit() + finally: + connection.close() + temporary.replace(path) + + +def _jsonl(path: Path, descriptors: Iterable[AssetDescriptor]) -> None: + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("w", encoding="utf-8") as handle: + for descriptor in descriptors: + handle.write(descriptor.model_dump_json() + "\n") + temporary.replace(path) + + +def _inventory_roots(roots: Sequence[Path], indexed_paths: set[Path]) -> dict[str, Any]: + output: dict[str, Any] = {} + for root in roots: + resolved = root.resolve() + if not resolved.exists(): + output[str(resolved)] = { + "exists": False, + "geometry_files": 0, + "indexed_primary_files": 0, + } + continue + extensions = Counter[str]() + geometry_files = 0 + indexed = 0 + for path in resolved.rglob("*"): + if not path.is_file() or path.suffix.casefold() not in SUPPORTED_GEOMETRY_EXTENSIONS: + continue + geometry_files += 1 + extensions[path.suffix.casefold()] += 1 + try: + if path.resolve() in indexed_paths: + indexed += 1 + except OSError: + pass + output[str(resolved)] = { + "exists": True, + "geometry_files": geometry_files, + "indexed_primary_files": indexed, + "unindexed_or_auxiliary_geometry_files": geometry_files - indexed, + "by_extension": dict(sorted(extensions.items())), + } + return output + + +def _inspect_record_safely( + record: AssetRecord, + *, + output_root: Path, + metadata: ReleaseMetadata, + render_views: bool, +) -> AssetDescriptor: + try: + return inspect_record( + record, + output_root=output_root, + metadata=metadata, + render_views=render_views, + ) + except Exception as error: # defensive per-asset isolation + details = "".join(traceback.format_exception_only(type(error), error)).strip() + return _minimal_quarantine( + record, + Path(record.usd_path), + f"inspection_internal_error:{details}", + ) + + +def _initialize_inspection_process( + output_root: Path, + metadata: ReleaseMetadata, + render_views: bool, +) -> None: + global _PROCESS_METADATA, _PROCESS_OUTPUT_ROOT, _PROCESS_RENDER_VIEWS + _PROCESS_OUTPUT_ROOT = output_root + _PROCESS_METADATA = metadata + _PROCESS_RENDER_VIEWS = render_views + + +def _inspect_record_in_process(record: AssetRecord) -> AssetDescriptor: + if _PROCESS_OUTPUT_ROOT is None or _PROCESS_METADATA is None: + raise RuntimeError("asset inspection process was not initialized") + return _inspect_record_safely( + record, + output_root=_PROCESS_OUTPUT_ROOT, + metadata=_PROCESS_METADATA, + render_views=_PROCESS_RENDER_VIEWS, + ) + + +def release_catalog( + catalog_path: Path, + output_root: Path, + *, + hssd_root: Path | None = None, + front_axis_overrides_path: Path | None = None, + scan_roots: Sequence[Path] = (), + workers: int = 4, + inspection_backend: str = "process", + render_views: bool = True, + maximum_records: int | None = None, +) -> dict[str, Any]: + started = time.perf_counter() + output_root.mkdir(parents=True, exist_ok=False) + catalog = AssetCatalog.model_validate_json(catalog_path.read_text(encoding="utf-8")) + records = catalog.assets[:maximum_records] if maximum_records is not None else catalog.assets + metadata = load_release_metadata(hssd_root, front_axis_overrides_path) + stage_started = time.perf_counter() + + if inspection_backend not in {"process", "thread"}: + raise ValueError("inspection_backend must be 'process' or 'thread'") + descriptors: list[AssetDescriptor] = [] + worker_count = max(1, workers) + executor_context: ProcessPoolExecutor | ThreadPoolExecutor + if inspection_backend == "process": + executor_context = ProcessPoolExecutor( + max_workers=worker_count, + initializer=_initialize_inspection_process, + initargs=(output_root, metadata, render_views), + ) + descriptor_iterator = executor_context.map( + _inspect_record_in_process, + records, + chunksize=1, + ) + else: + executor_context = ThreadPoolExecutor(max_workers=worker_count) + descriptor_iterator = executor_context.map( + lambda record: _inspect_record_safely( + record, + output_root=output_root, + metadata=metadata, + render_views=render_views, + ), + records, + ) + with executor_context: + for index, descriptor in enumerate(descriptor_iterator, start=1): + descriptors.append(descriptor) + if index == len(records) or index % 250 == 0: + active_so_far = sum(item.status == "ACTIVE" for item in descriptors) + print( + f"asset-release progress={index}/{len(records)} " + f"loadable={active_so_far} quarantined={index - active_so_far}", + flush=True, + ) + inspection_duration = time.perf_counter() - stage_started + dedupe_started = time.perf_counter() + descriptors = _resolve_duplicates(descriptors) + descriptors.sort(key=lambda descriptor: descriptor.asset_id) + dedupe_duration = time.perf_counter() - dedupe_started + active = [descriptor for descriptor in descriptors if descriptor.status == "ACTIVE"] + quarantined = [descriptor for descriptor in descriptors if descriptor.status == "QUARANTINED"] + _jsonl(output_root / "asset_descriptors.jsonl", descriptors) + _jsonl(output_root / "quarantine.jsonl", quarantined) + _write_descriptor_index(descriptors, output_root / "asset_descriptor_index.sqlite3") + before_active = [ + record for record in records if record.admission_status == AdmissionStatus.ACTIVE + ] + before_categories = Counter( + (record.normalized_category or normalize_category(record.category)) + for record in before_active + ) + after_categories = Counter(descriptor.category for descriptor in active) + reasons = Counter(descriptor.status_reason.split(":", 1)[0] for descriptor in quarantined) + indexed_paths = { + Path(record.usd_path).resolve() for record in records if Path(record.usd_path).is_file() + } + inventory_started = time.perf_counter() + inventory = _inventory_roots(scan_roots, indexed_paths) + inventory_duration = time.perf_counter() - inventory_started + report: dict[str, Any] = { + "schema_version": "2.0", + "truth_policy": ( + "ACTIVE only after file, loader, triangle, units, orientation, dimensions, " + "dependency and footprint checks" + ), + "source_catalog": str(catalog_path.resolve()), + "output_root": str(output_root.resolve()), + "inspection_backend": inspection_backend, + "inspection_workers": worker_count, + "front_axis_overrides": { + "path": ( + str(front_axis_overrides_path.resolve()) if front_axis_overrides_path else None + ), + "configured": len(metadata.front_axis_overrides), + "applied_active": sum( + descriptor.front_axis_source in {"multiview_verified", "manual_override"} + for descriptor in active + ), + }, + "before": { + "catalog_records": len(records), + "active_records": len(before_active), + "active_3d_records": sum( + record.asset_kind not in NON_GEOMETRY_KINDS for record in before_active + ), + "active_category_count": len(before_categories), + "active_by_category": dict(before_categories.most_common()), + }, + "after": { + "descriptor_records": len(descriptors), + "active_records": len(active), + "quarantined_records": len(quarantined), + "active_category_count": len(after_categories), + "active_by_category": dict(after_categories.most_common()), + "active_by_source": dict(Counter(item.source for item in active).most_common()), + "quarantine_reasons": dict(reasons.most_common()), + "exact_duplicate_quarantines": sum( + item.status_reason.startswith("duplicate_content:") for item in quarantined + ), + "near_duplicate_members": sum(bool(item.near_duplicate_asset_ids) for item in active), + }, + "source_inventory": inventory, + "durations_s": { + "inspection_and_views": round(inspection_duration, 3), + "deduplication": round(dedupe_duration, 3), + "source_inventory": round(inventory_duration, 3), + "total": round(time.perf_counter() - started, 3), + }, + "files": {}, + } + for path in ( + output_root / "asset_descriptors.jsonl", + output_root / "quarantine.jsonl", + output_root / "asset_descriptor_index.sqlite3", + ): + report["files"][path.name] = {"path": str(path.resolve()), "sha256": _sha256_file(path)} + atomic_write_text( + output_root / "asset_release_report.json", + json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + manifest: dict[str, Any] = { + "schema_version": "2.0", + "descriptor_schema": "packages.asset_registry.descriptors.AssetDescriptor/2.0", + "active_records": len(active), + "quarantined_records": len(quarantined), + "active_by_kind": {"OBJECT_OR_ROOM": len(active)}, + "active_by_category": dict(after_categories.most_common()), + "files": { + **report["files"], + "asset_release_report.json": { + "path": str((output_root / "asset_release_report.json").resolve()), + "sha256": _sha256_file(output_root / "asset_release_report.json"), + }, + }, + "old_indexes_preserved": True, + } + atomic_write_text( + output_root / "asset_index_manifest.json", + json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + return report + + +def load_active_descriptors( + index_path: Path, + asset_ids: Sequence[str] = (), + *, + categories: Sequence[str] = (), +) -> list[AssetDescriptor]: + uri = f"file:{index_path.resolve()}?mode=ro&immutable=1" + connection = sqlite3.connect(uri, uri=True) + try: + clauses = ["status='ACTIVE'"] + parameters: list[str] = [] + if asset_ids: + placeholders = ",".join("?" for _ in asset_ids) + clauses.append(f"asset_id IN ({placeholders})") + parameters.extend(asset_ids) + if categories: + normalized_categories = sorted({_clean_category(item) for item in categories}) + placeholders = ",".join("?" for _ in normalized_categories) + clauses.append(f"category IN ({placeholders})") + parameters.extend(normalized_categories) + rows = connection.execute( + "SELECT descriptor_json FROM asset_descriptors WHERE " + + " AND ".join(clauses) + + " ORDER BY asset_id", + tuple(parameters), + ).fetchall() + finally: + connection.close() + return [AssetDescriptor.model_validate_json(row[0]) for row in rows] + + +def search_active_descriptors( + index_path: Path, + *, + query: str, + category: str | None = None, + limit: int = 20, +) -> list[AssetDescriptor]: + uri = f"file:{index_path.resolve()}?mode=ro&immutable=1" + connection = sqlite3.connect(uri, uri=True) + connection.row_factory = sqlite3.Row + try: + terms = list(dict.fromkeys(_words(query))) + expression = " OR ".join(f'"{term}"' for term in terms) + if expression: + row_ids = [ + int(row[0]) + for row in connection.execute( + "SELECT rowid FROM active_descriptor_fts " + "WHERE active_descriptor_fts MATCH ? LIMIT ?", + (expression, max(limit * 10, 100)), + ) + ] + else: + row_ids = [] + clauses = ["status='ACTIVE'"] + parameters: list[Any] = [] + if category: + clauses.append("category=?") + parameters.append(_clean_category(category)) + if row_ids: + clauses.append(f"rowid IN ({','.join('?' for _ in row_ids)})") + parameters.extend(row_ids) + rows = connection.execute( + "SELECT descriptor_json FROM asset_descriptors WHERE " + + " AND ".join(clauses) + + " ORDER BY quality_overall DESC, asset_id LIMIT ?", + (*parameters, limit), + ).fetchall() + finally: + connection.close() + return [AssetDescriptor.model_validate_json(row[0]) for row in rows] diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/repository.py b/docs/reproduction/public_conversion_code/packages/asset_registry/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..e90247066b8552e2f93fd24a7de3758327cd642c --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/repository.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from packages.asset_registry.models import AssetCatalog, AssetRecord, RoboLabCatalogEntry + + +class AssetRegistry: + def __init__(self, records: list[AssetRecord]) -> None: + self.records = records + + @classmethod + def from_manifest(cls, path: Path) -> AssetRegistry: + catalog = AssetCatalog.model_validate_json(path.read_text(encoding="utf-8")) + return cls(catalog.assets) + + def search(self, query: str, *, scoring_required: bool = False) -> list[AssetRecord]: + terms = query.casefold().split() + matches = [] + for record in self.records: + if scoring_required and not record.scoring_allowed: + continue + text = " ".join( + [record.asset_id, record.display_name, record.category, *record.tags] + ).casefold() + if all(term in text for term in terms): + matches.append(record) + return matches + + def to_json(self) -> str: + return json.dumps( + AssetCatalog(source="merged", assets=self.records).model_dump(mode="json"), + indent=2, + sort_keys=True, + ) + + def to_robolab_catalog(self) -> list[RoboLabCatalogEntry]: + entries = [record.to_robolab_catalog_entry() for record in self.records] + names = [entry.name for entry in entries] + if len(names) != len(set(names)): + raise ValueError("RoboLab scene names must be unique across the exported catalog") + return entries diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/runtime_repair.py b/docs/reproduction/public_conversion_code/packages/asset_registry/runtime_repair.py new file mode 100644 index 0000000000000000000000000000000000000000..53c3caef726397d608e3ccb5aade599558ef3d8e --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/runtime_repair.py @@ -0,0 +1,181 @@ +from __future__ import annotations + +import hashlib +import json +import struct +import subprocess +import tempfile +from pathlib import Path +from typing import Any + +from packages.core.files import atomic_write_bytes + +GLB_JSON_CHUNK = 0x4E4F534A +GLB_BIN_CHUNK = 0x004E4942 + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _read_glb(path: Path) -> tuple[dict[str, Any], bytes]: + payload = path.read_bytes() + if len(payload) < 20: + raise ValueError("truncated_glb") + magic, version, total_length = struct.unpack_from("<4sII", payload, 0) + if magic != b"glTF" or version != 2 or total_length != len(payload): + raise ValueError("invalid_glb_header") + document: dict[str, Any] | None = None + binary: bytes | None = None + offset = 12 + while offset + 8 <= total_length: + length, kind = struct.unpack_from(" bytes: + document["buffers"][0]["byteLength"] = len(binary) + json_chunk = json.dumps( + document, + ensure_ascii=False, + separators=(",", ":"), + ).encode("utf-8") + json_chunk += b" " * ((-len(json_chunk)) % 4) + binary += b"\0" * ((-len(binary)) % 4) + total = 12 + 8 + len(json_chunk) + 8 + len(binary) + return b"".join( + [ + struct.pack("<4sII", b"glTF", 2, total), + struct.pack(" dict[str, Any]: + """Decode embedded KTX2 images to PNG without changing mesh geometry. + + The derivative is explicit runtime material-path repair. It is never used + as a new asset identity: callers retain the original source hash, record + the derivative hash separately, and remeasure the imported geometry. + """ + + source = source.resolve() + destination = destination.resolve() + ktx_cli = ktx_cli.resolve() + if destination.exists(): + raise FileExistsError(f"refusing to overwrite runtime derivative: {destination}") + if not source.is_file() or not ktx_cli.is_file(): + raise FileNotFoundError(source if not source.is_file() else ktx_cli) + document, binary = _read_glb(source) + required = set(str(value) for value in document.get("extensionsRequired") or []) + if "KHR_texture_basisu" not in required: + raise ValueError("source_glb_does_not_require_KHR_texture_basisu") + converted_images: list[dict[str, Any]] = [] + mutable_binary = bytearray(binary) + with tempfile.TemporaryDirectory(prefix="basisu-runtime-repair-") as temp_name: + temp_root = Path(temp_name) + for index, image in enumerate(document.get("images") or []): + if image.get("mimeType") != "image/ktx2": + continue + view_index = int(image["bufferView"]) + view = document["bufferViews"][view_index] + if int(view.get("buffer", 0)) != 0: + raise ValueError("basisu_image_uses_nonzero_buffer") + start = int(view.get("byteOffset", 0)) + end = start + int(view["byteLength"]) + if start < 0 or end > len(binary): + raise ValueError("basisu_image_buffer_view_out_of_range") + ktx_path = temp_root / f"image_{index:04d}.ktx2" + png_path = temp_root / f"image_{index:04d}.png" + ktx_path.write_bytes(binary[start:end]) + result = subprocess.run( + [ + str(ktx_cli), + "extract", + "--transcode", + "rgba8", + str(ktx_path), + str(png_path), + ], + check=False, + capture_output=True, + text=True, + ) + if result.returncode or not png_path.is_file(): + raise RuntimeError( + f"KTX2 decode failed for image {index}: " + + (result.stdout + result.stderr)[-2000:] + ) + png = png_path.read_bytes() + mutable_binary.extend(b"\0" * ((-len(mutable_binary)) % 4)) + new_offset = len(mutable_binary) + mutable_binary.extend(png) + document["bufferViews"].append( + { + "buffer": 0, + "byteOffset": new_offset, + "byteLength": len(png), + } + ) + image["bufferView"] = len(document["bufferViews"]) - 1 + image["mimeType"] = "image/png" + converted_images.append( + { + "image_index": index, + "source_buffer_view": view_index, + "runtime_buffer_view": image["bufferView"], + "png_bytes": len(png), + } + ) + if not converted_images: + raise ValueError("KHR_texture_basisu_declared_but_no_embedded_ktx2_images_found") + for texture in document.get("textures") or []: + extensions = texture.get("extensions") or {} + basisu = extensions.pop("KHR_texture_basisu", None) + if basisu is not None: + texture["source"] = int(basisu["source"]) + if extensions: + texture["extensions"] = extensions + else: + texture.pop("extensions", None) + for key in ("extensionsRequired", "extensionsUsed"): + values = [value for value in document.get(key) or [] if value != "KHR_texture_basisu"] + if values: + document[key] = values + else: + document.pop(key, None) + atomic_write_bytes(destination, _glb_bytes(document, bytes(mutable_binary))) + return { + "repair": "KHR_texture_basisu_embedded_KTX2_to_PNG", + "geometry_changed": False, + "source_path": str(source), + "source_sha256": _sha256(source), + "runtime_path": str(destination), + "runtime_sha256": _sha256(destination), + "converted_images": converted_images, + } diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/source_reporting.py b/docs/reproduction/public_conversion_code/packages/asset_registry/source_reporting.py new file mode 100644 index 0000000000000000000000000000000000000000..387c5befa19469be8455af856ba7cfdede086468 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/source_reporting.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from packages.asset_registry.ingestion import SourceAccess, SourceRegistry +from packages.core.files import atomic_write_text + + +def _gib(value: int | None) -> float | None: + return round(value / (1024**3), 3) if value is not None else None + + +def build_asset_source_report( + registry_path: Path, + inventory_path: Path, +) -> dict[str, Any]: + registry = SourceRegistry.from_yaml(registry_path) + inventory = json.loads(inventory_path.read_text(encoding="utf-8")) + measured = inventory.get("sources") or {} + rows: list[dict[str, Any]] = [] + for source in sorted(registry.sources, key=lambda item: item.ingestion_priority): + current = measured.get(source.source_id) or {} + current_bytes = ( + int(current["bytes"]) + if "bytes" in current + else source.current_local_size_bytes + ) + if source.access != SourceAccess.OPEN: + acquisition_state = "blocked_human_authorization" + elif not source.artifacts: + acquisition_state = "blocked_version_pinned_artifact_manifest" + elif not source.auto_download_allowed: + acquisition_state = "blocked_manifest_review" + else: + acquisition_state = "automatable" + known_delta = ( + max(0, source.official_size_bytes - (current_bytes or 0)) + if source.official_size_bytes is not None + else None + ) + rows.append( + { + "priority": source.ingestion_priority, + "source_id": source.source_id, + "display_name": source.display_name, + "version": source.version, + "license_id": source.license_id, + "license_url": source.license_url, + "access": source.access.value, + "registration_required": source.registration_required, + "download_method": source.download_method, + "source_url": source.source_url, + "current_local_path": current.get("path") or source.current_local_path, + "current_local_bytes": current_bytes, + "current_local_gib": _gib(current_bytes), + "official_size_bytes": source.official_size_bytes, + "official_size_gib": _gib(source.official_size_bytes), + "known_remaining_bytes": known_delta, + "known_remaining_gib": _gib(known_delta), + "acquisition_state": acquisition_state, + "notes": source.notes, + } + ) + disk = inventory["disk"] + known_remaining = sum( + int(item["known_remaining_bytes"] or 0) for item in rows + ) + unknown_sizes = [ + item["source_id"] for item in rows if item["official_size_bytes"] is None + ] + return { + "schema_version": "1.0", + "captured_at": inventory["captured_at"], + "host": inventory["host"], + "filesystem": inventory["filesystem"], + "disk": { + **disk, + "total_gib": _gib(int(disk["total_bytes"])), + "used_gib": _gib(int(disk["used_bytes"])), + "free_gib": _gib(int(disk["free_bytes"])), + }, + "asset_root": inventory["asset_root"], + "sources": rows, + "known_remaining_bytes": known_remaining, + "known_remaining_gib": _gib(known_remaining), + "sources_with_unknown_official_size": unknown_sizes, + "capacity_decision": ( + "known declared deltas fit available space; a complete-corpus capacity claim " + "is blocked because several official sizes are unavailable" + ), + "deletion_performed": False, + "automatic_download_started": False, + } + + +def render_asset_source_markdown(report: dict[str, Any]) -> str: + disk = report["disk"] + lines = [ + "# RoboHouseGen asset source and capacity report", + "", + f"Snapshot: {report['captured_at']} on `{report['host']}` (`{report['filesystem']}`).", + "", + ( + f"Disk: {disk['total_gib']:.1f} GiB total, {disk['used_gib']:.1f} GiB used, " + f"{disk['free_gib']:.1f} GiB free. Asset root: " + f"{_gib(int(report['asset_root']['bytes'])):.1f} GiB." + ), + "", + report["capacity_decision"], + "", + "| Priority | Source | Version | License | Access | Local GiB | Official GiB | State |", + "|---:|---|---|---|---|---:|---:|---|", + ] + for source in report["sources"]: + local = ( + f"{source['current_local_gib']:.3f}" + if source["current_local_gib"] is not None + else "unknown" + ) + official = ( + f"{source['official_size_gib']:.3f}" + if source["official_size_gib"] is not None + else "unknown" + ) + lines.append( + f"| {source['priority']} | {source['display_name']} | {source['version']} | " + f"[{source['license_id']}]({source['license_url']}) | {source['access']} | " + f"{local} | {official} | {source['acquisition_state']} |" + ) + lines.extend( + [ + "", + "Unknown official sizes: " + + ", ".join(f"`{item}`" for item in report["sources_with_unknown_official_size"]) + + ".", + "", + "No assets were deleted. No unattended download was started from an unpinned or " + "restricted source. Restricted sources require a local authorization record; open " + "sources require an explicit, version-pinned artifact and checksum manifest.", + "", + ] + ) + return "\n".join(lines) + + +def write_asset_source_report( + registry_path: Path, + inventory_path: Path, + output_dir: Path, +) -> dict[str, Any]: + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite asset source report: {output_dir}") + output_dir.mkdir(parents=True, exist_ok=False) + report = build_asset_source_report(registry_path, inventory_path) + atomic_write_text( + output_dir / "asset_sources_and_capacity.json", + json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + atomic_write_text( + output_dir / "asset_sources_and_capacity.md", + render_asset_source_markdown(report), + ) + return report diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/style.py b/docs/reproduction/public_conversion_code/packages/asset_registry/style.py new file mode 100644 index 0000000000000000000000000000000000000000..7856b2e992f95349dcc30bd3f0eae6eb366ad45d --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/style.py @@ -0,0 +1,131 @@ +"""Evidence-aware style labels and a read-only retrieval overlay.""" + +from __future__ import annotations + +import json +from pathlib import Path +import re +import sqlite3 + + +def write_style_index(records, path, taxonomy): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".partial") + temporary.unlink(missing_ok=True) + with sqlite3.connect(temporary) as db: + db.executescript("CREATE TABLE metadata(key TEXT PRIMARY KEY,value_json TEXT NOT NULL); CREATE TABLE asset_styles(asset_id TEXT PRIMARY KEY,display_name TEXT,kind TEXT,category TEXT,pools_json TEXT,description TEXT,style_json TEXT NOT NULL); CREATE TABLE style_labels(asset_id TEXT,style TEXT,PRIMARY KEY(asset_id,style)); CREATE INDEX style_lookup ON style_labels(style,asset_id);") + db.execute("INSERT INTO metadata VALUES('taxonomy',?)", (json.dumps(taxonomy, ensure_ascii=False),)) + for record in records: + db.execute("INSERT INTO asset_styles VALUES(?,?,?,?,?,?,?)", (record["asset_id"], record.get("display_name", ""), record.get("kind", "OBJECT"), record.get("category", ""), json.dumps(record.get("pools", [])), record.get("description", ""), json.dumps(record["style"], ensure_ascii=False, separators=(",", ":")))) + db.executemany("INSERT INTO style_labels VALUES(?,?)", [(record["asset_id"], tag) for tag in record["style"]["style_tags"]]) + temporary.replace(path) + + +def normalize_style(value, taxonomy): + token = str(value).casefold().strip() + token = taxonomy.get("aliases", {}).get(token, token) + if token in taxonomy["labels"]: + return token + return next((key for key, label in taxonomy["labels"].items() if token == label.casefold()), None) + + +def classify_style(record, taxonomy, editorial=None): + candidates = [] + conflicts = [] + warnings = [] + provenance = [] + source_hashes = set(record.get("source_sha256", [])) + latest_rank = max((review.get("release_rank", 0) for review in record.get("visual_style_records", [])), default=0) + for review in record.get("visual_style_records", []): + attribute = review["attribute"] + identity = review.get("identity", {}) + hashes = {value for key, value in identity.items() if "sha256" in key and isinstance(value, str) and len(value) == 64} + hashes.update(value for key in ("source", "runtime") if isinstance(value := (identity.get(key, {}).get("value") or {}).get("sha256"), str) and len(value) == 64) + identity_state = "matched" if hashes & source_hashes else "mismatch" if hashes and source_hashes else "unverified" + superseded = review.get("release_rank", 0) < latest_rank + provenance.append({"method": "historical_visual_review", "record_id": review["record_id"], "release": review.get("release"), "superseded": superseded, "status": attribute.get("status"), "identity_status": identity_state, "source_hashes": sorted(hashes), "attribute": attribute, "evidence": review.get("evidence", {})}) + if superseded: + continue + if identity_state == "mismatch": + warnings.append("historical_visual_source_hash_mismatch") + continue + if attribute.get("status") == "conflict": + conflicts.append(review["record_id"]) + if attribute.get("status") not in {"inferred", "confirmed", "measured"}: + continue + value = attribute.get("value") or {} + for item in value.get("labels", []): + label = normalize_style(item.get("name"), taxonomy) + score = item.get("score") + if label and label != "unknown" and isinstance(score, (int, float)) and score >= .65: + candidates.append({"name": label, "score": score, "reason": item.get("reason", ""), "method": "historical_visual_review"}) + if editorial: + provenance.append({"method": "editorial_preview_review", **editorial}) + candidates.extend({"name": label, "score": editorial.get("grade"), "reason": editorial["reason"], "method": "editorial_preview_review"} for label in editorial["labels"] if label in taxonomy["labels"] and label != "unknown") + if not candidates and not conflicts: + for raw in record.get("style_tags", []): + label = normalize_style(raw, taxonomy) + if label and label != "unknown": + candidates.append({"name": label, "score": None, "reason": str(raw), "method": "declared_style_tag"}) + for text_record in record.get("text_evidence", []): + if text_record["field"] not in {"description", "semantic_description", "display_name", "style_tags"}: + continue + text = text_record["text"] + for label, patterns in taxonomy["text_rules"].items(): + for pattern in patterns: + match = re.search(pattern, text, re.I) + if not match: + continue + prefix = text[max(0, match.start() - 35):match.start()].casefold() + if re.search(r"(?:not|no|without|non[- ])\s*(?:a|an|very|particularly)?\s*$", prefix) or prefix.endswith(("非", "不是", "并非")): + continue + candidates.append({"name": label, "score": None, "reason": match.group(), "method": "metadata_style_term"}) + provenance.append({"method": "metadata_style_term", "origin": text_record["origin"], "field": text_record["field"], "term": match.group(), "excerpt": text[max(0, match.start() - 60):match.end() + 100]}) + break + if conflicts: + tags, status = ["unknown"], "conflict" + elif candidates: + tags = sorted({item["name"] for item in candidates}) + methods = {item["method"] for item in candidates} + status = "visual_inferred" if "historical_visual_review" in methods else "editorial_inferred" if "editorial_preview_review" in methods else "metadata_inferred" + else: + tags, status = ["unknown"], "unknown" + return {"schema": "rhg.asset_style.v1", "style_tags": tags, "labels_zh": [taxonomy["labels"][tag] for tag in tags], "status": status, "assessments": candidates, "provenance": provenance, "warnings": sorted(set(warnings)), "conflicts": conflicts, "visual_reviewed_this_run": bool(editorial), "scope": "Visual compatibility only; not calibrated probability, runtime admission or geometry authority."} + + +class AssetStyleIndex: + def __init__(self, path): + self.path = Path(path) + + def get(self, asset_id): + with sqlite3.connect(self.path.resolve().as_uri() + "?mode=ro", uri=True) as db: + row = db.execute("SELECT style_json FROM asset_styles WHERE asset_id=?", (asset_id,)).fetchone() + return json.loads(row[0]) if row else None + + def apply(self, records, requested, mode="strict", allow_neutral=False): + if mode not in {"strict", "prefer"}: + raise ValueError("Unsupported style mode") + output = [] + with sqlite3.connect(self.path.resolve().as_uri() + "?mode=ro", uri=True) as db: + taxonomy = json.loads(db.execute("SELECT value_json FROM metadata WHERE key='taxonomy'").fetchone()[0]) + normalized = normalize_style(requested, taxonomy) + if not normalized or normalized == "unknown": + raise ValueError("Unknown requested style: " + requested) + for position, record in enumerate(records): + row = db.execute("SELECT style_json FROM asset_styles WHERE asset_id=?", (record["asset_id"],)).fetchone() + style = json.loads(row[0]) if row else {"style_tags": ["unknown"], "status": "unknown"} + current_identity = (record.get("annotation_dimension_consumption") or {}).get("source_identity") or record.get("source_identity") or record + current_hashes = {value for key in ("sha256", "asset_sha256", "source_sha256", "runtime_sha256") if isinstance(value := current_identity.get(key), str) and len(value) == 64} + visual_hashes = {value for item in style.get("provenance", []) if item.get("method") == "historical_visual_review" and not item.get("superseded") for value in item.get("source_hashes", [])} + if style["status"] == "visual_inferred" and current_hashes and visual_hashes and not current_hashes & visual_hashes: + style = {**style, "style_tags": ["unknown"], "status": "unknown", "warnings": [*style.get("warnings", []), "query_candidate_source_hash_mismatch"]} + tags = set(style["style_tags"]) + valid = style["status"] not in {"conflict", "unknown"} + exact = valid and normalized in tags + neutral = valid and allow_neutral and "neutral" in tags + if mode == "strict" and not (exact or neutral): + continue + result = dict(record, style=style, style_tags=style["style_tags"], style_match="exact" if exact else "neutral" if neutral else "unknown" if "unknown" in tags else "other") + output.append((0 if exact else 1 if neutral else 2 if "unknown" in tags else 3, position, result)) + return [item[2] for item in sorted(output, key=lambda item: item[:2])] diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/task_aliases.py b/docs/reproduction/public_conversion_code/packages/asset_registry/task_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..f69cbf5d1860eb5c58a9bd2582b5136e3306b324 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/task_aliases.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +import re +from typing import Any + +_GENERIC_TOKENS = { + "asset", + "context", + "item", + "object", + "office", + "source", + "target", +} + + +def _tokens(value: object) -> set[str]: + return { + token + for token in re.findall(r"[a-z0-9]+", str(value).casefold().replace("_", " ")) + if token not in _GENERIC_TOKENS and len(token) > 2 + } + + +def resolve_task_entity_aliases( + descriptions: list[str], + short_names: list[str], + selections: dict[str, list[dict[str, Any]]], + context_config: dict[str, Any] | None = None, +) -> list[str | None]: + """Resolve Agent-renamed objects to unique declarative task entity IDs. + + A result is accepted only when one task entity has a strictly better token overlap. + Ambiguous names such as ``office desk`` therefore remain on the normal retrieval path. + """ + aliases: dict[str, tuple[set[str], set[str]]] = {} + for entity_id, candidates in selections.items(): + if not isinstance(entity_id, str): + continue + record = candidates[0] if candidates and isinstance(candidates[0], dict) else {} + identity_tokens = set().union( + _tokens(entity_id), + _tokens(record.get("normalized_category", "")), + _tokens(record.get("category", "")), + ) + descriptive_tokens = set().union( + identity_tokens, + _tokens(record.get("name", "")), + _tokens(record.get("display_name", "")), + ) + aliases[entity_id] = identity_tokens, descriptive_tokens + + resolved: list[str | None] = [] + for description, short_name in zip(descriptions, short_names, strict=True): + name_query = _tokens(short_name) + description_query = _tokens(description) + ranked = sorted( + ( + ( + 1000 * len(name_query & identity_tokens) + + 100 * len(description_query & identity_tokens) + + 10 * len(name_query & descriptive_tokens) + + len(description_query & descriptive_tokens), + entity_id, + ) + for entity_id, (identity_tokens, descriptive_tokens) in aliases.items() + if (name_query | description_query) & identity_tokens + ), + reverse=True, + ) + if not ranked or (len(ranked) > 1 and ranked[0][0] == ranked[1][0]): + resolved.append(None) + continue + resolved.append(ranked[0][1]) + return resolved + + +def resolve_task_asset_aliases( + descriptions: list[str], + short_names: list[str], + selections: dict[str, list[dict[str, Any]]], + context_config: dict[str, Any], +) -> list[str | None]: + """Resolve task entities only when a declarative asset override exists.""" + + overrides = context_config.get("task_asset_overrides") or {} + if not isinstance(overrides, dict): + return [None] * len(descriptions) + entities = resolve_task_entity_aliases( + descriptions, + short_names, + selections, + context_config, + ) + return [ + str(overrides[entity_id]) + if entity_id is not None and isinstance(overrides.get(entity_id), str) + else None + for entity_id in entities + ] diff --git a/docs/reproduction/public_conversion_code/packages/asset_registry/usd_front_evidence.py b/docs/reproduction/public_conversion_code/packages/asset_registry/usd_front_evidence.py new file mode 100644 index 0000000000000000000000000000000000000000..6b280553f15e4759c2c5cf2e6023503343b1e9dd --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/asset_registry/usd_front_evidence.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from typing import Any + +from packages.asset_registry.certification_models import CardinalAxis, FrontEvidence + +OPPOSITE: dict[CardinalAxis, CardinalAxis] = { + "+X": "-X", + "-X": "+X", + "+Y": "-Y", + "-Y": "+Y", +} + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def infer_exposed_axis( + bounds_min: tuple[float, float, float], + bounds_max: tuple[float, float, float], + points: list[tuple[float, float, float]], +) -> tuple[CardinalAxis, float]: + """Infer which horizontal bounding-box side contains exposed affordance points.""" + + if not points: + raise ValueError("at least one affordance point is required") + extents = [bounds_max[index] - bounds_min[index] for index in range(3)] + if extents[0] <= 0 or extents[1] <= 0: + raise ValueError("asset bounds must have positive horizontal extents") + votes: dict[CardinalAxis, float] = {axis: 0.0 for axis in OPPOSITE} + for point in points: + normalized_distances: dict[CardinalAxis, float] = { + "-X": abs(point[0] - bounds_min[0]) / extents[0], + "+X": abs(bounds_max[0] - point[0]) / extents[0], + "-Y": abs(point[1] - bounds_min[1]) / extents[1], + "+Y": abs(bounds_max[1] - point[1]) / extents[1], + } + best = min(normalized_distances, key=normalized_distances.__getitem__) + votes[best] += max(0.0, 1.0 - normalized_distances[best]) + ordered = sorted(votes, key=lambda axis: (-votes[axis], axis)) + total = sum(votes.values()) + confidence = votes[ordered[0]] / total if total else 0.0 + if confidence < 0.65: + raise ValueError(f"affordance points do not identify one exposed side: {votes}") + return ordered[0], round(min(0.99, 0.75 + 0.25 * confidence), 6) + + +def inspect_usd_operation_front( + *, + asset_id: str, + asset_path: Path, +) -> tuple[list[FrontEvidence], dict[str, Any]]: + """Extract hash-bound handle and joint evidence from a native USD articulation.""" + + from pxr import Usd, UsdGeom, UsdPhysics # type: ignore[import-not-found] + + asset_path = asset_path.resolve() + if not asset_path.is_file(): + raise FileNotFoundError(asset_path) + asset_sha256 = _sha256(asset_path) + stage = Usd.Stage.Open(str(asset_path)) + if stage is None: + raise ValueError(f"USD stage could not be opened: {asset_path}") + cache = UsdGeom.BBoxCache( + Usd.TimeCode.Default(), + [UsdGeom.Tokens.default_, UsdGeom.Tokens.render, UsdGeom.Tokens.proxy], + ) + root = stage.GetDefaultPrim() + if not root: + raise ValueError("USD stage has no default prim") + bounds = cache.ComputeWorldBound(root).ComputeAlignedRange() + minimum = bounds.GetMin() + maximum = bounds.GetMax() + bounds_min = (float(minimum[0]), float(minimum[1]), float(minimum[2])) + bounds_max = (float(maximum[0]), float(maximum[1]), float(maximum[2])) + handles: list[dict[str, Any]] = [] + joints: list[dict[str, Any]] = [] + centers: list[tuple[float, float, float]] = [] + for prim in stage.Traverse(): + lowered = prim.GetName().casefold() + if "handle" in lowered and prim.IsA(UsdGeom.Xformable): + handle_bounds = cache.ComputeWorldBound(prim).ComputeAlignedRange() + midpoint = handle_bounds.GetMidpoint() + center = (float(midpoint[0]), float(midpoint[1]), float(midpoint[2])) + centers.append(center) + handles.append({"prim_path": str(prim.GetPath()), "center_m": center}) + if prim.IsA(UsdPhysics.RevoluteJoint) or prim.IsA(UsdPhysics.PrismaticJoint): + joint = UsdPhysics.Joint(prim) + body0 = [str(item) for item in joint.GetBody0Rel().GetTargets()] + body1 = [str(item) for item in joint.GetBody1Rel().GetTargets()] + lower = prim.GetAttribute("physics:lowerLimit").Get() + upper = prim.GetAttribute("physics:upperLimit").Get() + joints.append( + { + "prim_path": str(prim.GetPath()), + "joint_type": prim.GetTypeName(), + "axis": prim.GetAttribute("physics:axis").Get(), + "lower_limit": float(lower) if lower is not None else None, + "upper_limit": float(upper) if upper is not None else None, + "body0": body0, + "body1": body1, + } + ) + if not handles: + raise ValueError("USD articulation has no handle prims") + if not joints: + raise ValueError("USD articulation has no revolute or prismatic joints") + axis, confidence = infer_exposed_axis(bounds_min, bounds_max, centers) + bindings = { + "schema_version": "1.0", + "asset_id": asset_id, + "asset_uri": str(asset_path), + "asset_sha256": asset_sha256, + "default_prim": str(root.GetPath()), + "bounds_min_m": bounds_min, + "bounds_max_m": bounds_max, + "operation_front_axis": axis, + "handles": handles, + "joints": joints, + } + source_uri = str(asset_path) + note = f"{len(handles)} handle prim(s) lie on {axis}; {len(joints)} movable joint(s) bind doors" + evidence = [ + FrontEvidence( + evidence_id=f"usd-handle:{asset_sha256}", + kind="handle", + target="functional_front", + axis=axis, + confidence=confidence, + source_uri=source_uri, + source_hash=asset_sha256, + note=note, + ), + FrontEvidence( + evidence_id=f"usd-articulation:{asset_sha256}", + kind="articulation", + target="functional_front", + axis=axis, + confidence=max(0.0, confidence - 0.03), + source_uri=source_uri, + source_hash=asset_sha256, + note=note, + ), + FrontEvidence( + evidence_id=f"usd-handle-visual:{asset_sha256}", + kind="geometry", + target="visual_front", + axis=axis, + confidence=max(0.0, confidence - 0.05), + source_uri=source_uri, + source_hash=asset_sha256, + note="visible handles and door panels define the visual front", + ), + FrontEvidence( + evidence_id=f"usd-operation-back:{asset_sha256}", + kind="articulation", + target="back_axis", + axis=OPPOSITE[axis], + confidence=max(0.0, confidence - 0.03), + source_uri=source_uri, + source_hash=asset_sha256, + note="back axis is opposite the handle operation side", + ), + ] + return evidence, json.loads(json.dumps(bindings)) diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/__init__.py b/docs/reproduction/public_conversion_code/packages/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d49cadb69f8d65b05885e877a9efaa21455e05 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/__init__.py @@ -0,0 +1,3 @@ +from packages.benchmark.packager import BenchmarkPackager + +__all__ = ["BenchmarkPackager"] diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/artifact_lifecycle.py b/docs/reproduction/public_conversion_code/packages/benchmark/artifact_lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..2a28741392f4b20a8d073994a9b83ed541a0e979 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/artifact_lifecycle.py @@ -0,0 +1,380 @@ +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import uuid +from datetime import UTC, datetime +from pathlib import Path + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field + +from packages.core.files import atomic_write_text + + +class ArtifactLifecyclePolicy(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: str + enabled: bool = True + compact_after_release: bool = True + preserve_globs: list[str] = Field(default_factory=list) + remove_paths: list[str] = Field(default_factory=list) + + +DEFAULT_POLICY = ( + Path(__file__).resolve().parents[2] / "configs" / "artifact_lifecycle_v1.yaml" +) + + +def load_artifact_lifecycle_policy(path: Path | None = None) -> ArtifactLifecyclePolicy: + selected = path or Path(os.environ.get("RHG_ARTIFACT_POLICY", DEFAULT_POLICY)) + payload = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8")) + return ArtifactLifecyclePolicy.model_validate(payload) + + +def compact_released_attempt( + output: Path, + portable_package: Path, + *, + expected_package_sha256: str | None = None, + policy: ArtifactLifecyclePolicy | None = None, + apply: bool = True, +) -> dict[str, object]: + """Prune reproducible generation workspaces after a portable package is verified.""" + + output = output.resolve() + portable_package = portable_package.resolve() + selected = policy or load_artifact_lifecycle_policy() + if not output.is_dir(): + raise NotADirectoryError(output) + if not portable_package.exists(): + raise FileNotFoundError(portable_package) + package_sha256 = _package_sha256(portable_package) + if expected_package_sha256 and package_sha256 != expected_package_sha256: + raise ValueError("portable package checksum changed before artifact compaction") + + before_bytes = _physical_size(output) + targets = _resolve_targets(output, selected.remove_paths) + plan = [ + { + "path": path.relative_to(output).as_posix(), + "physical_bytes": _physical_size(path), + } + for path in targets + if path.exists() + ] + report: dict[str, object] = { + "schema_version": "1.0", + "created_at": datetime.now(UTC).isoformat(), + "mode": "apply" if apply else "dry_run", + "status": "planned", + "portable_package": str(portable_package), + "portable_sha256": package_sha256, + "before_physical_bytes": before_bytes, + "targets": plan, + "preserved_files": [], + } + if not selected.enabled or not selected.compact_after_release or not apply: + return report + + preserved = _preserve_evidence(output, targets, selected.preserve_globs) + for path in targets: + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(path) + elif path.exists() or path.is_symlink(): + path.unlink() + after_bytes = _physical_size(output) + report.update( + { + "status": "complete", + "completed_at": datetime.now(UTC).isoformat(), + "after_physical_bytes_before_report": after_bytes, + "reclaimed_physical_bytes": max(before_bytes - after_bytes, 0), + "preserved_files": preserved, + } + ) + report_path = output / "supervisor" / "artifact_lifecycle_report.json" + atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") + _write_checksums(output) + return report + + +def build_compact_copy( + source: Path, + destination: Path, + *, + policy: ArtifactLifecyclePolicy | None = None, +) -> dict[str, object]: + """Build a pruned copy without mutating the immutable version directory.""" + + source = source.resolve() + destination = destination.resolve() + selected = policy or load_artifact_lifecycle_policy() + if not source.is_dir(): + raise NotADirectoryError(source) + if destination == source or destination.is_relative_to(source): + raise ValueError("compact copy destination must be outside the source version") + if destination.exists(): + raise FileExistsError(destination) + + excluded = { + Path(relative).as_posix().strip("/") for relative in selected.remove_paths + } + + def ignore(directory: str, names: list[str]) -> set[str]: + relative_dir = Path(directory).resolve().relative_to(source) + ignored: set[str] = set() + for name in names: + if (Path(directory) / name).is_symlink(): + ignored.add(name) + continue + relative = (relative_dir / name).as_posix().strip(".").strip("/") + if any(relative == item or relative.startswith(f"{item}/") for item in excluded): + ignored.add(name) + return ignored + + shutil.copytree(source, destination, symlinks=False, ignore=ignore) + _preserve_evidence_from_source(source, destination, selected) + report: dict[str, object] = { + "schema_version": "1.0", + "created_at": datetime.now(UTC).isoformat(), + "status": "complete", + "source_version": source.name, + "source_physical_bytes": _physical_size(source), + "major_physical_bytes_before_report": _physical_size(destination), + "excluded_paths": sorted(excluded), + } + report_path = destination / "supervisor" / "artifact_lifecycle_report.json" + atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") + _write_checksums(destination) + return report + + +def replace_major_copy( + source: Path, + major: Path, + *, + policy: ArtifactLifecyclePolicy | None = None, +) -> dict[str, object]: + """Atomically replace ``major`` with a compact copy of ``source``.""" + + major = major.resolve() + major.parent.mkdir(parents=True, exist_ok=True) + token = uuid.uuid4().hex + staging = major.parent / f".{major.name}.staging-{token}" + backup = major.parent / f".{major.name}.backup-{token}" + try: + report = build_compact_copy(source, staging, policy=policy) + if major.exists(): + major.rename(backup) + staging.rename(major) + except Exception: + if backup.exists() and not major.exists(): + backup.rename(major) + raise + finally: + if staging.exists(): + shutil.rmtree(staging) + if backup.exists(): + shutil.rmtree(backup) + return report + + +def replace_major_from_portable( + portable: Path, + major: Path, + *, + source_version: Path, +) -> dict[str, object]: + """Atomically materialize ``major`` from an already verified portable bundle.""" + + from packages.benchmark.portable import refresh_checksums, verify_portable_bundle + + portable = portable.resolve() + major = major.resolve() + source_version = source_version.resolve() + if not portable.is_dir(): + raise NotADirectoryError(portable) + if not (portable / "portable_manifest.json").is_file(): + raise FileNotFoundError(portable / "portable_manifest.json") + major.parent.mkdir(parents=True, exist_ok=True) + token = uuid.uuid4().hex + staging = major.parent / f".{major.name}.staging-{token}" + backup = major.parent / f".{major.name}.backup-{token}" + try: + symlinks = [path for path in portable.rglob("*") if path.is_symlink()] + if symlinks: + raise RuntimeError(f"portable source contains symlinks: {symlinks[:3]}") + # Preserve the portable staging hardlinks. This keeps both the live major + # directory and its tar archive compact without coupling path validity. + shutil.copytree(portable, staging, symlinks=False, copy_function=os.link) + snapshot_source = source_version / "snapshot.jpg" + if not (staging / "snapshot.jpg").is_file(): + if not snapshot_source.is_file(): + raise FileNotFoundError(snapshot_source) + shutil.copy2(snapshot_source, staging / "snapshot.jpg") + # ``major`` has a backend-independent, fixed media contract. Older + # portable bundles stored the video only under ``scenesmith/``; expose + # it at the major root without duplicating file data. + preview = staging / "preview.mp4" + if not preview.is_file(): + preview_source = staging / "scenesmith" / "preview.mp4" + if not preview_source.is_file(): + preview_source = source_version / "scenesmith" / "preview.mp4" + if not preview_source.is_file(): + raise FileNotFoundError( + f"major preview is missing for source version: {source_version}" + ) + os.link(preview_source, preview) + history = staging / "iteration_history.mp4" + if not history.is_file(): + history_source = staging / "scenesmith" / "iteration_history.mp4" + if not history_source.is_file(): + history_source = source_version / "iteration_history.mp4" + if not history_source.is_file(): + history_source = source_version / "scenesmith" / "iteration_history.mp4" + if not history_source.is_file(): + raise FileNotFoundError( + f"major iteration history is missing for source version: {source_version}" + ) + os.link(history_source, history) + provenance = { + "schema_version": "1.0", + "materialization_version": "5.0", + "created_at": datetime.now(UTC).isoformat(), + "source_version": source_version.name, + "source_portable_bundle": str(portable), + "self_contained": True, + "media": { + "snapshot": "snapshot.jpg", + "preview": "preview.mp4", + "iteration_history": "iteration_history.mp4", + }, + } + atomic_write_text( + staging / "major_manifest.json", + json.dumps(provenance, ensure_ascii=False, indent=2) + "\n", + ) + refresh_checksums(staging) + verification = verify_portable_bundle(staging, require_pxr=False) + if not verification["passed"]: + raise RuntimeError(f"major portable verification failed: {verification['failures']}") + if major.exists(): + major.rename(backup) + staging.rename(major) + except Exception: + if backup.exists() and not major.exists(): + backup.rename(major) + raise + finally: + if staging.exists(): + shutil.rmtree(staging) + if backup.exists(): + shutil.rmtree(backup) + return { + "schema_version": "1.0", + "status": "complete", + "source_version": source_version.name, + "source_portable_bundle": str(portable), + "verification": verification, + } + + +def _resolve_targets(output: Path, relative_paths: list[str]) -> list[Path]: + targets: list[Path] = [] + for relative in relative_paths: + candidate = (output / relative).resolve() + if not candidate.is_relative_to(output): + raise ValueError(f"artifact cleanup path escapes the run: {relative}") + if candidate == output: + raise ValueError("artifact cleanup cannot target the run root") + targets.append(candidate) + return targets + + +def _preserve_evidence(output: Path, targets: list[Path], globs: list[str]) -> list[str]: + destination_root = output / "supervisor" / "generation_evidence" + preserved: list[str] = [] + for target in targets: + if not target.is_dir(): + continue + for pattern in globs: + for source in sorted(target.glob(pattern)): + if not source.is_file(): + continue + relative = source.relative_to(output) + destination = destination_root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + preserved.append(destination.relative_to(output).as_posix()) + return sorted(set(preserved)) + + +def _preserve_evidence_from_source( + source_root: Path, + destination_root: Path, + policy: ArtifactLifecyclePolicy, +) -> list[str]: + evidence_root = destination_root / "supervisor" / "generation_evidence" + preserved: list[str] = [] + for target in _resolve_targets(source_root, policy.remove_paths): + if not target.is_dir(): + continue + for pattern in policy.preserve_globs: + for source in sorted(target.glob(pattern)): + if not source.is_file(): + continue + relative = source.relative_to(source_root) + destination = evidence_root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + preserved.append(destination.relative_to(destination_root).as_posix()) + return sorted(set(preserved)) + + +def _physical_size(path: Path) -> int: + if not path.exists(): + return 0 + files = [path] if path.is_file() else path.rglob("*") + seen: set[tuple[int, int]] = set() + total = 0 + for item in files: + if not item.is_file(): + continue + stat = item.stat() + key = (stat.st_dev, stat.st_ino) + if key in seen: + continue + seen.add(key) + total += stat.st_blocks * 512 + return total + + +def _package_sha256(path: Path) -> str: + if path.is_dir(): + digest = hashlib.sha256() + for item in sorted(path.rglob("*")): + if item.is_file(): + digest.update(item.relative_to(path).as_posix().encode()) + digest.update(_sha256_file(item).encode()) + return digest.hexdigest() + return _sha256_file(path) + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _write_checksums(output: Path) -> None: + checksums = [] + for path in sorted(output.rglob("*")): + if path.is_file() and path.name != "checksums.sha256": + checksums.append(f"{_sha256_file(path)} {path.relative_to(output)}") + atomic_write_text(output / "checksums.sha256", "\n".join(checksums) + "\n") diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/domain_randomization.py b/docs/reproduction/public_conversion_code/packages/benchmark/domain_randomization.py new file mode 100644 index 0000000000000000000000000000000000000000..737e9f2294fde35fdf28285ff222cfaa1d00cde0 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/domain_randomization.py @@ -0,0 +1,399 @@ +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import tempfile +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] + +from packages.core.files import atomic_write_text + +PROJECT_ROOT = Path(__file__).resolve().parents[2] +DEFAULT_POLICY = PROJECT_ROOT / "configs/scene_generation/domain_randomization_v1.yaml" +_AXIS = {"x": 0, "y": 1, "z": 2} + + +@dataclass(frozen=True) +class CompiledOverrides: + applied: list[dict[str, Any]] + deferred: list[dict[str, Any]] + + +class DomainRandomizationCompiler: + """Compile declarative episode factors into a stronger USD override layer.""" + + def __init__(self, policy_path: Path | None = None) -> None: + selected = policy_path or Path( + os.environ.get("RHG_DOMAIN_RANDOMIZATION_POLICY", DEFAULT_POLICY) + ) + payload = yaml.safe_load(selected.read_text(encoding="utf-8")) + if payload.get("schema_version") != "1.0" or not isinstance( + payload.get("operations"), dict + ): + raise ValueError(f"invalid domain-randomization policy: {selected}") + self.policy_path = selected + self.operations: dict[str, dict[str, Any]] = payload["operations"] + + def validate(self, operations: list[object], entity_ids: set[str]) -> None: + for raw in operations: + if not isinstance(raw, dict): + raise ValueError("scene override operation must be an object") + operation = str(raw.get("operation", "")) + if operation not in self.operations: + raise ValueError(f"domain-randomization policy has no operation {operation!r}") + entity_id = str(raw.get("entity_id", "")) + if entity_id != "robot" and entity_id not in entity_ids: + raise ValueError(f"scene override references unknown entity {entity_id!r}") + policy = self.operations[operation] + missing_fields = [ + field for field in policy.get("required_fields", []) if not raw.get(field) + ] + if missing_fields: + raise ValueError(f"scene override {operation!r} requires fields {missing_fields}") + if policy.get("value_type", "float") == "float": + value = raw.get("value") + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"scene override {operation!r} requires a numeric value") + + def compile( + self, + *, + episode_root: Path, + override_layer: Path, + operations: list[object], + entity_prim_paths: dict[str, str], + robot_prim_path: str, + ) -> CompiledOverrides: + normalized = [ + self._normalize(item, entity_prim_paths, robot_prim_path) for item in operations + ] + if not override_layer.is_file(): + atomic_write_text(override_layer, _empty_layer()) + if not normalized: + return CompiledOverrides(applied=[], deferred=[]) + try: + result = self._compile_with_pxr(episode_root, override_layer, normalized) + except ImportError: + worker_python = os.environ.get("RHG_USD_PYTHON") or os.environ.get("SCENESMITH_PYTHON") + if worker_python and Path(worker_python).resolve() != Path(sys.executable).resolve(): + result = self._compile_external( + Path(worker_python), episode_root, override_layer, normalized + ) + else: + result = self._compile_portable_fallback(override_layer, normalized) + return result + + def _compile_external( + self, + python: Path, + episode_root: Path, + override_layer: Path, + operations: list[dict[str, Any]], + ) -> CompiledOverrides: + with tempfile.TemporaryDirectory(prefix="rhg-usd-worker-") as temporary: + payload = Path(temporary) / "request.json" + result_path = Path(temporary) / "result.json" + payload.write_text( + json.dumps( + { + "episode_root": str(episode_root.resolve()), + "override_layer": str(override_layer.resolve()), + "operations": operations, + "result": str(result_path), + } + ), + encoding="utf-8", + ) + environment = os.environ.copy() + existing_python_path = environment.get("PYTHONPATH", "") + environment["PYTHONPATH"] = str(PROJECT_ROOT) + ( + os.pathsep + existing_python_path if existing_python_path else "" + ) + completed = subprocess.run( + [ + str(python), + "-m", + "packages.benchmark.domain_randomization", + payload.as_posix(), + ], + cwd=PROJECT_ROOT, + env=environment, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + if completed.returncode != 0 or not result_path.is_file(): + detail = (completed.stderr or completed.stdout).strip() + raise RuntimeError(f"USD domain-randomization worker failed: {detail}") + result = json.loads(result_path.read_text(encoding="utf-8")) + return CompiledOverrides( + applied=list(result["applied"]), deferred=list(result["deferred"]) + ) + + def _normalize( + self, + raw: object, + entity_prim_paths: dict[str, str], + robot_prim_path: str, + ) -> dict[str, Any]: + if not isinstance(raw, dict): + raise ValueError("scene override operation must be an object") + operation = str(raw.get("operation", "")) + if operation not in self.operations: + raise ValueError(f"domain-randomization policy has no operation {operation!r}") + entity_id = str(raw.get("entity_id", "")) + if entity_id == "robot": + prim_path = robot_prim_path + else: + try: + prim_path = entity_prim_paths[entity_id] + except KeyError as error: + raise ValueError( + f"scene override references unknown entity {entity_id!r}" + ) from error + return { + **raw, + "entity_id": entity_id, + "prim_path": prim_path, + "policy": self.operations[operation], + } + + def _compile_with_pxr( + self, episode_root: Path, override_layer: Path, operations: list[dict[str, Any]] + ) -> CompiledOverrides: + from pxr import Gf, Sdf, Usd, UsdGeom # type: ignore[import-not-found] + + stage = Usd.Stage.Open(str(episode_root)) + if stage is None: + raise ValueError(f"cannot open episode stage: {episode_root}") + layer = Sdf.Layer.FindOrOpen(str(override_layer)) or Sdf.Layer.CreateNew( + str(override_layer) + ) + stage.SetEditTarget(layer) + applied: list[dict[str, Any]] = [] + deferred: list[dict[str, Any]] = [] + for item in operations: + policy = item["policy"] + primitive = str(policy["primitive"]) + prim = stage.GetPrimAtPath(item["prim_path"]) + if not prim.IsValid(): + deferred.append(_public(item, "target_prim_missing")) + continue + targets = [prim] + if primitive.startswith("descendant_"): + selector = policy.get("selector", {}) + pattern = re.compile(str(selector.get("name_pattern", ".*"))) + type_names = set(selector.get("type_names", [])) + targets = [ + candidate + for candidate in Usd.PrimRange(prim) + if pattern.fullmatch(candidate.GetName()) + and (not type_names or candidate.GetTypeName() in type_names) + ] + primitive = primitive.removeprefix("descendant_") + if not targets: + deferred.append(_public(item, "selector_matched_no_prims")) + continue + for target in targets: + value = item.get("value") + if primitive == "translate": + xform = UsdGeom.Xformable(target) + axis = _AXIS[str(policy["axis"])] + vector = [0.0, 0.0, 0.0] + vector[axis] = float(value) + if policy.get("mode") == "absolute": + existing = _local_translation(xform, Gf) + vector[axis] = float(value) - existing[axis] + suffix = "rhg_absolute" + else: + suffix = f"rhg_{item['operation']}" + xform.AddTranslateOp(opSuffix=suffix).Set(Gf.Vec3d(*vector)) + elif primitive == "rotate": + if policy.get("axis") != "z" or policy.get("unit") != "degrees": + raise ValueError("rotate currently requires axis=z and unit=degrees") + UsdGeom.Xformable(target).AddRotateZOp(opSuffix=f"rhg_{item['operation']}").Set( + float(value) + ) + elif primitive == "uniform_scale": + scale = float(value) + UsdGeom.Xformable(target).AddScaleOp(opSuffix=f"rhg_{item['operation']}").Set( + Gf.Vec3f(scale, scale, scale) + ) + elif primitive == "scale_to_extent": + axis = _AXIS[str(policy["axis"])] + bounds = UsdGeom.BBoxCache( + Usd.TimeCode.Default(), [UsdGeom.Tokens.default_] + ).ComputeLocalBound(target) + extent = list(bounds.GetRange().GetSize()) + scale = [1.0, 1.0, 1.0] + if extent[axis] <= 0: + deferred.append(_public(item, "target_extent_is_zero")) + continue + scale[axis] = float(value) / float(extent[axis]) + UsdGeom.Xformable(target).AddScaleOp(opSuffix=f"rhg_{item['operation']}").Set( + Gf.Vec3f(*scale) + ) + elif primitive in {"property_set", "property_scale", "metadata"}: + attribute = target.GetAttribute(str(policy["property"])) + if not attribute: + attribute = target.CreateAttribute( + str(policy["property"]), + _sdf_type(policy.get("value_type", "float"), Sdf), + custom=True, + ) + output = value + if primitive == "property_scale": + current = attribute.Get() + if not isinstance(current, (int, float)): + current = policy.get("default_base") + if not isinstance(current, (int, float)): + deferred.append(_public(item, "property_has_no_numeric_base_value")) + continue + output = float(current) * float(value) + attribute.Set(_typed_value(output, policy.get("value_type", "float"))) + elif primitive == "reference_set": + references = target.GetReferences() + references.ClearReferences() + if not references.AddReference(str(value)): + deferred.append(_public(item, "asset_reference_rejected")) + continue + elif primitive == "variant_select": + field = str(policy.get("variant_set_field", "variant_set")) + set_name = str(item.get(field, "")) + variant_set = target.GetVariantSets().GetVariantSet(set_name) + if not set_name or not variant_set.IsValid(): + deferred.append(_public(item, "variant_set_missing")) + continue + if not variant_set.SetVariantSelection(str(value)): + deferred.append(_public(item, "variant_selection_rejected")) + continue + else: + raise ValueError(f"unsupported domain-randomization primitive {primitive!r}") + applied.append( + {**_public(item, "applied"), "target_prim_path": str(target.GetPath())} + ) + layer.Save() + return CompiledOverrides(applied=applied, deferred=deferred) + + def _compile_portable_fallback( + self, override_layer: Path, operations: list[dict[str, Any]] + ) -> CompiledOverrides: + # The fallback authors concrete translation/property values for deterministic stages. + # Operations requiring composed bounds or base property values remain explicit runtime work. + entries: dict[str, dict[str, list[str]]] = {} + applied: list[dict[str, Any]] = [] + deferred: list[dict[str, Any]] = [] + for item in operations: + policy = item["policy"] + primitive = str(policy["primitive"]) + entry = entries.setdefault( + str(item["prim_path"]), {"properties": [], "xform_order": []} + ) + if primitive == "translate": + vector = [0.0, 0.0, 0.0] + vector[_AXIS[str(policy["axis"])]] = float(item["value"]) + operation_name = f"xformOp:translate:rhg_{item['operation']}" + entry["properties"].append( + f"double3 {operation_name} = ({vector[0]}, {vector[1]}, {vector[2]})" + ) + entry["xform_order"].append(operation_name) + elif primitive == "rotate": + operation_name = f"xformOp:rotateZ:rhg_{item['operation']}" + entry["properties"].append(f"float {operation_name} = {float(item['value'])}") + entry["xform_order"].append(operation_name) + elif primitive == "uniform_scale": + operation_name = f"xformOp:scale:rhg_{item['operation']}" + scale = float(item["value"]) + entry["properties"].append(f"float3 {operation_name} = ({scale}, {scale}, {scale})") + entry["xform_order"].append(operation_name) + elif primitive in {"property_set", "metadata"}: + value_type = str(policy.get("value_type", "float")) + value = _usda_value(item["value"], value_type) + entry["properties"].append(f"custom {value_type} {policy['property']} = {value}") + else: + deferred.append(_public(item, "requires_pxr_composed_stage")) + continue + applied.append(_public(item, "applied_fallback")) + atomic_write_text(override_layer, _layer_with_entries(entries)) + return CompiledOverrides(applied=applied, deferred=deferred) + + +def _local_translation(xform: Any, gf: Any) -> list[float]: + result = xform.GetLocalTransformation() + matrix = result[0] if isinstance(result, tuple) else result + value = matrix.ExtractTranslation() if matrix is not None else gf.Vec3d(0.0) + return [float(value[0]), float(value[1]), float(value[2])] + + +def _sdf_type(name: str, sdf: Any) -> Any: + return {"float": sdf.ValueTypeNames.Float, "string": sdf.ValueTypeNames.String}.get( + name, sdf.ValueTypeNames.String + ) + + +def _typed_value(value: Any, value_type: str) -> Any: + return float(value) if value_type == "float" else str(value) + + +def _public(item: dict[str, Any], status: str) -> dict[str, Any]: + return {key: value for key, value in item.items() if key != "policy"} | {"status": status} + + +def _empty_layer() -> str: + return '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + + +def _layer_with_entries(entries: dict[str, dict[str, list[str]]]) -> str: + tree: dict[str, Any] = {"properties": [], "children": {}} + for path, entry in entries.items(): + node = tree + for part in (part for part in path.split("/") if part): + node = node["children"].setdefault(part, {"properties": [], "children": {}}) + node["properties"].extend(entry["properties"]) + if entry["xform_order"]: + order = ", ".join(json.dumps(name) for name in entry["xform_order"]) + node["properties"].append(f"uniform token[] xformOpOrder = [{order}]") + + def render(node: dict[str, Any], depth: int) -> list[str]: + lines = [] + indent = " " * depth + lines.extend(f"{indent}{value}" for value in node["properties"]) + for name, child in node["children"].items(): + lines.append(f'{indent}over "{name}" {{') + lines.extend(render(child, depth + 1)) + lines.append(f"{indent}}}") + return lines + + bodies = render(tree, 0) + return _empty_layer() + "\n".join(bodies) + ("\n" if bodies else "") + + +def _usda_value(value: Any, value_type: str) -> str: + return json.dumps(str(value)) if value_type == "string" else str(float(value)) + + +def _worker(payload_path: Path) -> None: + payload = json.loads(payload_path.read_text(encoding="utf-8")) + compiler = DomainRandomizationCompiler() + result = compiler._compile_with_pxr( # noqa: SLF001 + Path(payload["episode_root"]), + Path(payload["override_layer"]), + list(payload["operations"]), + ) + Path(payload["result"]).write_text( + json.dumps({"applied": result.applied, "deferred": result.deferred}), + encoding="utf-8", + ) + + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise SystemExit("usage: python -m packages.benchmark.domain_randomization REQUEST.json") + _worker(Path(sys.argv[1])) diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/packager.py b/docs/reproduction/public_conversion_code/packages/benchmark/packager.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd70c8421f3af3955fecbbaf96ab448d4b791c1 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/packager.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from packages.core.files import atomic_write_text +from packages.schemas.models import BenchmarkEpisode, SceneManifest, TaskSpec + + +class BenchmarkPackager: + def package( + self, + task: TaskSpec, + scene: SceneManifest, + robot_id: str, + output_dir: Path, + *, + benchmark_version: str = "0.1.0", + episode_id: str | None = None, + max_duration_s: float = 120.0, + split: str = "train", + factor_values: dict[str, object] | None = None, + evaluator_policy: dict[str, object] | None = None, + ) -> BenchmarkEpisode: + self._validate_contract(task, scene, output_dir) + episode = BenchmarkEpisode( + benchmark_version=benchmark_version, + episode_id=episode_id or f"episode-{task.task_id.removeprefix('task-')}-{robot_id}", + task_id=task.task_id, + scene_id=scene.scene_id, + root_usd_uri=scene.layer_plan.root_layer, + robot_profile=robot_id, + seed=task.random_seed, + evaluator_uri="manifests/evaluator.json", + max_duration_s=max_duration_s, + split=split, # type: ignore[arg-type] + factor_values=factor_values + or {"difficulty": task.plan.difficulty.model_dump(mode="json")}, + ) + manifests = output_dir / "manifests" + manifests.mkdir(parents=True, exist_ok=True) + atomic_write_text(manifests / "task.json", task.model_dump_json(indent=2)) + atomic_write_text(manifests / "episode.json", episode.model_dump_json(indent=2)) + evaluator = { + "schema_version": "1.1", + "task_id": task.task_id, + "scene_id": scene.scene_id, + "entity_prim_paths": scene.entity_prim_paths, + "robot_prim_path": scene.robot_prim_path, + "goals": [item.model_dump(mode="json") for item in task.goal_predicates], + "safety": [item.model_dump(mode="json") for item in task.safety_predicates], + "stages": [item.model_dump(mode="json") for item in task.stages], + "validation_contract": (evaluator_policy or {}).get("isaac_validation", {}), + "observation_contract": { + "trajectory_aware": any( + item.params.get("temporal") in {"ever", "always"} + for item in task.goal_predicates + task.safety_predicates + ), + "required_streams": sorted( + { + stream + for item in task.goal_predicates + task.safety_predicates + for stream in ( + (["contact_report"] if item.name == "contact" else []) + + (["joint_position"] if item.name in {"pressed", "open"} else []) + ) + } + ), + "synchronization_groups": self._synchronization_groups(task), + "joint_position_unit": "degrees", + "contact_evidence_fields": ["subject_body", "object_link"], + }, + } + atomic_write_text( + manifests / "evaluator.json", json.dumps(evaluator, indent=2, sort_keys=True) + ) + checksums = [] + for path in sorted(output_dir.rglob("*")): + if path.is_file() and path.name != "checksums.sha256": + checksum = hashlib.sha256(path.read_bytes()).hexdigest() + checksums.append(f"{checksum} {path.relative_to(output_dir)}") + atomic_write_text(output_dir / "checksums.sha256", "\n".join(checksums) + "\n") + return episode + + @staticmethod + def _synchronization_groups(task: TaskSpec) -> dict[str, dict[str, object]]: + groups: dict[str, dict[str, object]] = {} + for index, predicate in enumerate(task.goal_predicates): + group = predicate.params.get("synchronization_group") + if not group: + continue + entry = groups.setdefault( + str(group), + { + "window_s": float(predicate.params.get("synchronization_window_s", 0.0)), + "goal_indices": [], + }, + ) + current_window = entry["window_s"] + assert isinstance(current_window, (int, float)) + entry["window_s"] = min( + float(current_window), + float(predicate.params.get("synchronization_window_s", 0.0)), + ) + goal_indices = entry["goal_indices"] + assert isinstance(goal_indices, list) + goal_indices.append(index) + return groups + + @staticmethod + def _validate_contract(task: TaskSpec, scene: SceneManifest, output_dir: Path) -> None: + if scene.task_id != task.task_id: + raise ValueError( + f"scene task_id {scene.task_id!r} does not match task {task.task_id!r}" + ) + if scene.random_seed != task.random_seed: + raise ValueError( + f"scene seed {scene.random_seed} does not match task seed {task.random_seed}" + ) + expected_entities = {entity.entity_id for entity in task.entities if entity.required} + missing = expected_entities - scene.entity_prim_paths.keys() + if missing: + raise ValueError(f"scene is missing required task entities: {sorted(missing)}") + root_layer = Path(scene.layer_plan.root_layer) + if root_layer.is_absolute() or ".." in root_layer.parts: + raise ValueError("scene root layer must be a relative path inside the benchmark") + if not (output_dir / root_layer).is_file(): + raise ValueError(f"scene root layer does not exist: {root_layer}") diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/performance_compare.py b/docs/reproduction/public_conversion_code/packages/benchmark/performance_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a35d5afb7c09e2c0949e300e8e254a8fb502c1 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/performance_compare.py @@ -0,0 +1,415 @@ +from __future__ import annotations + +import hashlib +import json +import math +import statistics +from collections import defaultdict +from pathlib import Path +from typing import Any + +from PIL import Image, ImageDraw, ImageFont + +from packages.core.files import atomic_write_text + +CertificationKey = tuple[str, str] + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _summary(values: list[float]) -> dict[str, float] | None: + if not values: + return None + ordered = sorted(values) + p95_index = max(0, math.ceil(0.95 * len(ordered)) - 1) + return { + "count": float(len(ordered)), + "median_s": round(statistics.median(ordered), 6), + "p95_s": round(ordered[p95_index], 6), + "max_s": round(ordered[-1], 6), + } + + +def _load_batch(root: Path) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: + manifest_path = root / "batch_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + trials: dict[str, dict[str, Any]] = {} + for result in manifest.get("results") or []: + scene_id = str(result["scene_id"]) + trial_path = Path(result["output"]) / "trial_run_report.json" + if not trial_path.is_file(): + trial_path = root / Path(result["output"]).name / "trial_run_report.json" + if not trial_path.is_file(): + raise FileNotFoundError(f"trial report missing for {scene_id}: {trial_path}") + trials[scene_id] = json.loads(trial_path.read_text(encoding="utf-8")) + return manifest, trials + + +def _load_certifications( + path: Path | None, +) -> tuple[dict[CertificationKey, dict[str, Any]], dict[str, Any] | None]: + if path is None: + return {}, None + resolved = path.resolve() + if not resolved.is_file(): + raise FileNotFoundError(resolved) + records: dict[CertificationKey, dict[str, Any]] = {} + with resolved.open("r", encoding="utf-8") as handle: + for line_number, line in enumerate(handle, start=1): + if not line.strip(): + continue + record = json.loads(line) + asset_id = str(record.get("asset_id", "")) + asset_sha256 = str(record.get("asset_sha256", "")) + if not asset_id or len(asset_sha256) != 64: + raise ValueError( + f"invalid certification identity at {resolved}:{line_number}" + ) + key = (asset_id, asset_sha256) + if key in records and records[key] != record: + raise ValueError(f"conflicting duplicate certification: {key}") + records[key] = record + return records, { + "path": str(resolved), + "sha256": _sha256(resolved), + "record_count": len(records), + } + + +def _scenario_bundle_identity( + manifest: dict[str, Any], batch_root: Path +) -> dict[str, str | None]: + declared = Path(str(manifest["scenario_bundle"])) + repository_copy = Path(__file__).resolve().parents[2] / "examples" / declared.name + candidates = (declared, batch_root / declared.name, repository_copy) + path = next((item for item in candidates if item.is_file()), None) + recorded_hash = manifest.get("scenario_bundle_sha256") + digest = _sha256(path) if path is not None else recorded_hash + return { + "declared_path": str(declared), + "resolved_path": str(path.resolve()) if path is not None else None, + "sha256": str(digest) if digest else None, + } + + +def _aggregate( + manifest: dict[str, Any], + trials: dict[str, dict[str, Any]], + root: Path, + certifications: dict[CertificationKey, dict[str, Any]] | None = None, +) -> dict[str, Any]: + results = list(manifest.get("results") or []) + wall = [float(item["duration_s"]) for item in results] + total = [float(item["stage_timings_s"]["total"]) for item in trials.values()] + stages: dict[str, list[float]] = defaultdict(list) + retry_counts: list[int] = [] + hash_hits = 0 + hash_misses = 0 + cache_reports = 0 + hard_passed = 0 + task_passed = 0 + certified = 0 + external_certifications_matched = 0 + hq_a = 0 + production_eligible = 0 + quality_tiers: dict[str, int] = defaultdict(int) + fidelity_values: dict[str, list[float]] = defaultdict(list) + selected = 0 + for scene_id, trial in trials.items(): + for stage, duration in (trial.get("stage_timings_s") or {}).items(): + stages[str(stage)].append(float(duration)) + retry_counts.append( + int(trial.get("asset_reselection_count", 0)) + + int(trial.get("automatic_render_retry_count", 0)) + ) + sha_stats = ((trial.get("cache_stats") or {}).get("file_sha256") or {}) + if "hits" in sha_stats and "misses" in sha_stats: + hash_hits += int(sha_stats["hits"]) + hash_misses += int(sha_stats["misses"]) + cache_reports += 1 + result = next(item for item in results if str(item["scene_id"]) == scene_id) + scene_root = Path(result["output"]) + if not scene_root.is_dir(): + scene_root = root / Path(result["output"]).name + hard_path = scene_root / "all_hard_checks.json" + task_path = scene_root / "pick_move_place_task.json" + if hard_path.is_file(): + hard_passed += int( + json.loads(hard_path.read_text(encoding="utf-8")).get("passed") is True + ) + if task_path.is_file(): + task_passed += int( + json.loads(task_path.read_text(encoding="utf-8")).get("passed") is True + ) + for descriptor_path in scene_root.glob("asset_descriptors/*/asset_descriptor.json"): + selected += 1 + descriptor = json.loads(descriptor_path.read_text(encoding="utf-8")) + certification = descriptor.get("certification") + if not isinstance(certification, dict) and certifications: + certification = certifications.get( + (str(descriptor.get("asset_id", "")), str(descriptor.get("sha256", ""))) + ) + external_certifications_matched += int(isinstance(certification, dict)) + if isinstance(certification, dict): + certified += 1 + tier = str(certification.get("quality_tier", "UNKNOWN")) + quality_tiers[tier] += 1 + hq_a += int(tier == "HQ-A") + production_eligible += int(certification.get("production_eligible") is True) + fidelity = certification.get("fidelity") + if isinstance(fidelity, dict): + for dimension, score in fidelity.items(): + if isinstance(score, int | float): + fidelity_values[str(dimension)].append(float(score)) + if selected == 0: + selected = sum(int(item.get("selected_asset_count", 0)) for item in results) + return { + "scene_count": len(results), + "driver_wall_time": _summary(wall), + "pipeline_total": _summary(total), + "stages": {key: _summary(value) for key, value in sorted(stages.items())}, + "retries": { + "total": sum(retry_counts), + "per_scene": retry_counts, + }, + "cache": { + "file_sha256_reports": cache_reports, + "file_sha256_hits": hash_hits if cache_reports else None, + "file_sha256_misses": hash_misses if cache_reports else None, + "file_sha256_hit_rate": ( + round(hash_hits / (hash_hits + hash_misses), 6) + if hash_hits + hash_misses + else None + ), + }, + "quality": { + "selected_asset_count": selected, + "certified_asset_count": certified, + "certification_coverage_ratio": ( + round(certified / selected, 6) if selected else None + ), + "external_certifications_matched": external_certifications_matched, + "quality_tier_counts": dict(sorted(quality_tiers.items())), + "hq_a_asset_count": hq_a if certified else None, + "hq_a_ratio": round(hq_a / certified, 6) if certified else None, + "hq_a_ratio_selected": round(hq_a / selected, 6) if selected and certified else None, + "production_eligible_asset_count": production_eligible if certified else None, + "production_eligible_ratio_selected": ( + round(production_eligible / selected, 6) if selected and certified else None + ), + "fidelity_median_by_dimension": { + dimension: round(statistics.median(values), 6) + for dimension, values in sorted(fidelity_values.items()) + }, + "not_measured_reason": ( + None + if certified + else "selected descriptors were not joined to AssetCertification/1.0 evidence" + ), + }, + "hard_checks": { + "layout_scene_pass_count": hard_passed, + "layout_scene_pass_rate": round(hard_passed / len(results), 6) if results else None, + "task_pass_count": task_passed, + "task_pass_rate": round(task_passed / len(results), 6) if results else None, + }, + } + + +def _delta(baseline: dict[str, Any], candidate: dict[str, Any]) -> dict[str, Any]: + output: dict[str, Any] = {} + for metric in ("median_s", "p95_s", "max_s"): + before = baseline["pipeline_total"][metric] + after = candidate["pipeline_total"][metric] + output[metric] = { + "baseline": before, + "candidate": after, + "delta_s": round(after - before, 6), + "speedup_fraction": round((before - after) / before, 6) if before else None, + } + return output + + +def compare_batches( + baseline_root: Path, + candidate_root: Path, + *, + baseline_certifications: Path | None = None, + candidate_certifications: Path | None = None, +) -> dict[str, Any]: + baseline_manifest, baseline_trials = _load_batch(baseline_root) + candidate_manifest, candidate_trials = _load_batch(candidate_root) + baseline_ids = [str(item["scene_id"]) for item in baseline_manifest["results"]] + candidate_ids = [str(item["scene_id"]) for item in candidate_manifest["results"]] + if baseline_ids != candidate_ids: + raise ValueError("benchmark scene IDs or ordering differ") + baseline_bundle = _scenario_bundle_identity(baseline_manifest, baseline_root) + candidate_bundle = _scenario_bundle_identity(candidate_manifest, candidate_root) + if baseline_bundle["sha256"] and candidate_bundle["sha256"]: + if baseline_bundle["sha256"] != candidate_bundle["sha256"]: + raise ValueError("benchmark scenario bundles differ; comparison is invalid") + bundle_evidence = "sha256" + elif baseline_bundle["declared_path"] == candidate_bundle["declared_path"]: + bundle_evidence = "identical_declared_path_only" + else: + raise ValueError("scenario bundle identity cannot be proven") + baseline_records, baseline_certification_evidence = _load_certifications( + baseline_certifications + ) + candidate_records, candidate_certification_evidence = _load_certifications( + candidate_certifications + ) + baseline = _aggregate( + baseline_manifest, + baseline_trials, + baseline_root, + baseline_records, + ) + candidate = _aggregate( + candidate_manifest, + candidate_trials, + candidate_root, + candidate_records, + ) + return { + "schema_version": "1.0", + "comparison_valid": True, + "same_scene_ids_and_order": True, + "scenario_bundle_identity": { + "evidence": bundle_evidence, + "sha256": baseline_bundle["sha256"], + "baseline": baseline_bundle, + "candidate": candidate_bundle, + }, + "baseline_root": str(baseline_root.resolve()), + "candidate_root": str(candidate_root.resolve()), + "certification_evidence": { + "baseline": baseline_certification_evidence, + "candidate": candidate_certification_evidence, + }, + "baseline": baseline, + "candidate": candidate, + "pipeline_total_delta": _delta(baseline, candidate), + "claim_policy": ( + "Only measured fields are compared. Missing cache or HQ-A evidence remains null; " + "no acceleration or quality claim is inferred from missing data." + ), + } + + +def summarize_batch(root: Path) -> dict[str, Any]: + manifest, trials = _load_batch(root) + return { + "schema_version": "1.0", + "root": str(root.resolve()), + "scenario_bundle_identity": _scenario_bundle_identity(manifest, root), + "metrics": _aggregate(manifest, trials, root), + "claim_policy": ( + "Missing cache or AssetCertification evidence is null and is not inferred." + ), + } + + +def write_batch_summary(root: Path, output_dir: Path) -> dict[str, Any]: + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite benchmark summary: {output_dir}") + output_dir.mkdir(parents=True, exist_ok=False) + report = summarize_batch(root) + atomic_write_text( + output_dir / "benchmark_summary.json", + json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + return report + + +def build_quality_contact_sheet( + baseline_root: Path, + candidate_root: Path, + output: Path, + *, + maximum_scenes: int = 10, +) -> int: + baseline_manifest, _ = _load_batch(baseline_root) + candidate_manifest, _ = _load_batch(candidate_root) + baseline_results = {str(item["scene_id"]): item for item in baseline_manifest["results"]} + candidate_results = {str(item["scene_id"]): item for item in candidate_manifest["results"]} + scene_ids = [ + scene_id for scene_id in baseline_results if scene_id in candidate_results + ][:maximum_scenes] + rows: list[tuple[str, Path, Path]] = [] + for scene_id in scene_ids: + left_declared = Path(str(baseline_results[scene_id].get("final_image", ""))) + right_declared = Path(str(candidate_results[scene_id].get("final_image", ""))) + left = ( + left_declared + if left_declared.is_file() + else baseline_root + / Path(baseline_results[scene_id]["output"]).name + / left_declared.name + ) + right = ( + right_declared + if right_declared.is_file() + else candidate_root + / Path(candidate_results[scene_id]["output"]).name + / right_declared.name + ) + if left.is_file() and right.is_file(): + rows.append((scene_id, left, right)) + if not rows: + return 0 + cell_w, cell_h, label_h = 480, 320, 34 + sheet = Image.new("RGB", (cell_w * 2, (cell_h + label_h) * len(rows)), "white") + draw = ImageDraw.Draw(sheet) + font = ImageFont.load_default() + for row, (scene_id, left, right) in enumerate(rows): + y = row * (cell_h + label_h) + for column, (label, path) in enumerate((("baseline", left), ("candidate", right))): + with Image.open(path) as source: + image = source.convert("RGB") + image.thumbnail((cell_w, cell_h)) + x = column * cell_w + (cell_w - image.width) // 2 + sheet.paste(image, (x, y + (cell_h - image.height) // 2)) + draw.text( + (column * cell_w + 5, y + cell_h + 4), + f"{scene_id} · {label}", + fill="black", + font=font, + ) + output.parent.mkdir(parents=True, exist_ok=True) + sheet.save(output) + return len(rows) + + +def write_comparison( + baseline_root: Path, + candidate_root: Path, + output_dir: Path, + *, + baseline_certifications: Path | None = None, + candidate_certifications: Path | None = None, +) -> dict[str, Any]: + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite benchmark comparison: {output_dir}") + output_dir.mkdir(parents=True, exist_ok=False) + report = compare_batches( + baseline_root, + candidate_root, + baseline_certifications=baseline_certifications, + candidate_certifications=candidate_certifications, + ) + sheet = output_dir / "render_quality_comparison.png" + count = build_quality_contact_sheet(baseline_root, candidate_root, sheet) + report["render_quality_contact_sheet"] = str(sheet.resolve()) if count else None + report["render_quality_scene_count"] = count + atomic_write_text( + output_dir / "benchmark_comparison.json", + json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + return report diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/portable.py b/docs/reproduction/public_conversion_code/packages/benchmark/portable.py new file mode 100644 index 0000000000000000000000000000000000000000..dafb5c824fce164f5c8eb559fc7b8c942f4366ff --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/portable.py @@ -0,0 +1,665 @@ +from __future__ import annotations + +import hashlib +import json +import os +import re +import subprocess +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from packages.core.files import atomic_write_text + +REFERENCE_PATTERN = re.compile(r"@([^@]+)@") +ISAAC_RUNTIME_ASSETS = {"OmniPBR.mdl"} +RUNTIME_SCENE_FILES = ( + "scene.usdc", + "preview.mp4", + "iteration_history.mp4", + "iterations_manifest.json", + "stage_manifest.json", + "scene_request.json", + "scene_context.json", + "selected_assets.json", + "effective_selected_assets.json", + "compiled_prompt.txt", + "timing.json", + "cleanup_report.json", + "cleanup_config.json", + "context_assets_config.json", + "agent_skill_policy.json", + "scene_dependency_graph.json", + "dependency_execution_plan.json", + "agent_orchestration_effective.json", + "planning_agent_output.json", + "agent_execution_plan.json", + "agent_execution_ledger.json", + "global_critic.json", + "agent_merge_result.json", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def refresh_checksums(root: Path) -> int: + lines = [] + for path in sorted(root.rglob("*")): + if path.is_file() and not path.is_symlink() and path.name != "checksums.sha256": + lines.append(f"{sha256(path)} {path.relative_to(root).as_posix()}") + atomic_write_text(root / "checksums.sha256", "\n".join(lines) + "\n") + return len(lines) + + +def _hardlink(source: Path, destination: Path) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + os.link(source, destination) + + +def _runtime_files(source: Path) -> list[tuple[Path, Path]]: + files: list[tuple[Path, Path]] = [] + for relative_root in (Path("layers"), Path("manifests")): + for path in sorted((source / relative_root).rglob("*")): + if ( + path.is_file() + and not path.is_symlink() + and path.relative_to(source) != Path("manifests/portable_validation.json") + ): + files.append((path, path.relative_to(source))) + files.append((source / "root.usda", Path("root.usda"))) + snapshot = source / "snapshot.jpg" + if snapshot.is_file(): + files.append((snapshot, Path("snapshot.jpg"))) + # Stable public media entry. Keep the SceneSmith-native location as + # provenance/backward compatibility, while portable consumers can always + # open ``preview.mp4`` without knowing which scene backend produced it. + root_preview = source / "preview.mp4" + scenesmith_preview = source / "scenesmith" / "preview.mp4" + preview = root_preview if root_preview.is_file() else scenesmith_preview + if preview.is_file(): + files.append((preview, Path("preview.mp4"))) + root_history = source / "iteration_history.mp4" + scenesmith_history = source / "scenesmith" / "iteration_history.mp4" + history = root_history if root_history.is_file() else scenesmith_history + if history.is_file(): + files.append((history, Path("iteration_history.mp4"))) + for name in RUNTIME_SCENE_FILES: + path = source / "scenesmith" / name + if path.is_file(): + files.append((path, Path("scenesmith") / name)) + texture_root = source / "scenesmith" / "textures" + if texture_root.is_dir(): + for path in sorted(texture_root.rglob("*")): + if path.is_file() and not path.is_symlink(): + files.append((path, path.relative_to(source))) + robot_assets_root = source / "assets" / "robots" + if robot_assets_root.is_dir(): + for path in sorted(robot_assets_root.rglob("*")): + if path.is_file() and not path.is_symlink(): + files.append((path, path.relative_to(source))) + postprocess_root = source / "scenesmith" / "postprocess_iterations" + if postprocess_root.is_dir(): + for path in sorted(postprocess_root.rglob("*")): + if path.is_file() and not path.is_symlink(): + files.append((path, path.relative_to(source))) + subtree_root = source / "scenesmith" / "subtrees" + if subtree_root.is_dir(): + for path in sorted(subtree_root.rglob("*")): + if path.is_file() and not path.is_symlink(): + files.append((path, path.relative_to(source))) + house_state = source / "scenesmith/upstream/scene_000/combined_house/house_state.json" + stage_manifest = source / "scenesmith/stage_manifest.json" + if stage_manifest.is_file(): + manifest = json.loads(stage_manifest.read_text(encoding="utf-8")) + relative_state = manifest.get("house_state") + if isinstance(relative_state, str) and relative_state: + candidate = source / "scenesmith" / relative_state + if candidate.is_file(): + house_state = candidate + if house_state.is_file(): + files.append((house_state, Path("provenance/house_state.json"))) + return files + + +def portable_source_fingerprint(source: Path) -> str: + """Hash every source artifact that is materialized into a portable bundle.""" + + digest = hashlib.sha256() + for path, relative in _runtime_files(source.resolve()): + digest.update(relative.as_posix().encode("utf-8")) + digest.update(b"\0") + digest.update(sha256(path).encode("ascii")) + digest.update(b"\n") + return digest.hexdigest() + + +def _native_asset_bindings(source: Path) -> dict[str, Any]: + manifest_path = source / "scenesmith/stage_manifest.json" + if not manifest_path.is_file(): + return {} + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + bindings = manifest.get("native_asset_bindings") or {} + if not isinstance(bindings, dict): + raise ValueError(f"native_asset_bindings must be an object: {manifest_path}") + return bindings + + +def _dependency_destination(root: Path, source: Path, kind: str) -> Path: + path_digest = hashlib.sha256(str(source).encode("utf-8")).hexdigest()[:16] + return root / "scenesmith" / "assets" / kind / f"{path_digest}-{source.name}" + + +def _is_isaac_runtime_asset(value: object) -> bool: + """Recognize only named modules guaranteed by the declared Isaac runtime.""" + + normalized = str(value).replace("\\", "/").rsplit("/", 1)[-1] + return normalized in ISAAC_RUNTIME_ASSETS + + +def _stage_usd_dependencies( + source_scene: Path, + destination_scene: Path, + destination_root: Path, +) -> dict[str, Any]: + try: + from pxr import Sdf, Usd, UsdUtils # type: ignore[import-not-found] + except ImportError as error: + raise RuntimeError( + "pxr is required to stage native USD dependencies for a portable bundle" + ) from error + + layers, asset_paths, unresolved = UsdUtils.ComputeAllDependencies(str(source_scene)) + external_runtime_assets = sorted( + {str(path).replace("\\", "/").rsplit("/", 1)[-1] for path in unresolved} + & ISAAC_RUNTIME_ASSETS + ) + unresolved_files = sorted( + str(path) for path in unresolved if not _is_isaac_runtime_asset(path) + ) + if unresolved_files: + raise RuntimeError( + "USD dependencies could not be resolved: " + ", ".join(unresolved_files) + ) + + source_scene = source_scene.resolve() + layer_sources = { + Path(layer.realPath).resolve(): layer + for layer in layers + if layer.realPath and Path(layer.realPath).is_file() + } + if source_scene not in layer_sources: + raise RuntimeError(f"USD dependency traversal omitted root layer: {source_scene}") + + destination_by_source: dict[Path, Path] = {source_scene: destination_scene} + for source in sorted(layer_sources, key=str): + if source != source_scene: + destination_by_source[source] = _dependency_destination(destination_root, source, "usd") + non_layer_sources = { + Path(path).resolve() + for path in asset_paths + if Path(path).is_file() and Path(path).resolve() not in layer_sources + } + missing_assets = sorted( + str(path) + for path in asset_paths + if not Path(path).is_file() and not _is_isaac_runtime_asset(path) + ) + if missing_assets: + raise RuntimeError("USD asset files are missing: " + ", ".join(missing_assets)) + for source in sorted(non_layer_sources, key=str): + destination_by_source[source] = _dependency_destination(destination_root, source, "files") + + hardlinked_assets = 0 + for source in sorted(non_layer_sources, key=str): + target = destination_by_source[source] + _hardlink(source, target) + hardlinked_assets += 1 + + rewritten_layers = 0 + for source, source_layer in sorted(layer_sources.items(), key=lambda item: str(item[0])): + target = destination_by_source[source] + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_name(f".{target.name}.rewrite{target.suffix}") + if not source_layer.Export(str(temporary)): + raise RuntimeError(f"could not export USD dependency: {source}") + output_layer = Sdf.Layer.FindOrOpen(str(temporary)) + if output_layer is None: + raise RuntimeError(f"could not reopen staged USD layer: {temporary}") + unstaged: list[str] = [] + + def rebase( + asset_path: str, + *, + source_layer: Any = source_layer, + source: Path = source, + target: Path = target, + unstaged: list[str] = unstaged, + ) -> str: + if not asset_path: + return asset_path + resolved_text = Sdf.ComputeAssetPathRelativeToLayer(source_layer, asset_path) + resolved = Path(resolved_text).resolve() + dependency_target = destination_by_source.get(resolved) + if dependency_target is None: + if resolved.is_file(): + unstaged.append(f"{source}: {asset_path} -> {resolved}") + return asset_path + return os.path.relpath(dependency_target, target.parent).replace(os.sep, "/") + + UsdUtils.ModifyAssetPaths(output_layer, rebase) + if unstaged: + raise RuntimeError("USD dependencies were not staged: " + ", ".join(unstaged)) + output_layer.Save() + temporary.replace(target) + rewritten_layers += 1 + + stage = Usd.Stage.Open(str(destination_scene)) + if stage is None: + raise RuntimeError(f"staged USD scene does not open: {destination_scene}") + return { + "rewritten_layers": rewritten_layers, + "hardlinked_assets": hardlinked_assets, + "dependency_count": len(destination_by_source) - 1, + "external_runtime_assets": external_runtime_assets, + } + + +def create_portable_bundle( + source: Path, + destination: Path, + *, + policy_path: Path | None = None, +) -> dict[str, Any]: + source = source.resolve() + destination = destination.resolve() + if destination.exists(): + raise FileExistsError(destination) + if not (source / "root.usda").is_file(): + raise FileNotFoundError(source / "root.usda") + if source.stat().st_dev != destination.parent.stat().st_dev: + raise RuntimeError("hard-link staging requires source and destination on one filesystem") + destination.mkdir() + linked = 0 + for path, relative in _runtime_files(source): + if not path.is_file(): + raise FileNotFoundError(path) + _hardlink(path, destination / relative) + linked += 1 + if policy_path is not None: + policy_path = policy_path.resolve() + _hardlink(policy_path, destination / "runtime/policies" / policy_path.name) + linked += 1 + + usd_dependencies = { + "rewritten_layers": 0, + "hardlinked_assets": 0, + "dependency_count": 0, + "external_runtime_assets": [], + } + if _native_asset_bindings(source): + usd_dependencies = _stage_usd_dependencies( + source / "scenesmith/scene.usdc", + destination / "scenesmith/scene.usdc", + destination, + ) + linked += usd_dependencies["hardlinked_assets"] + + furniture = destination / "layers/furniture.usda" + text = furniture.read_text(encoding="utf-8") + corrected = text.replace("@scenesmith/scene.usdc@", "@../scenesmith/scene.usdc@") + if corrected != text: + # Break the hard link before writing metadata that is specific to the portable layout. + temporary = furniture.with_suffix(".tmp") + temporary.write_text(corrected, encoding="utf-8") + temporary.replace(furniture) + + manifest = { + "schema_version": "1.0", + "format": "robothousegen-portable-benchmark", + "created_at": datetime.now(UTC).isoformat(), + "source_run_name": source.name, + "source_fingerprint": portable_source_fingerprint(source), + "entrypoint": "root.usda", + "episode": "manifests/episode.json", + "evaluator": "manifests/evaluator.json", + "hardlink_staging": True, + "hardlinked_files": linked, + "usd_dependencies": usd_dependencies, + "runtime_requirements": { + "simulator": "Isaac Sim 6.0.1", + "benchmark_runtime": "Isaac Lab-Arena release/0.2.1", + "robot_profile": "unitree_g1_43dof", + }, + } + atomic_write_text( + destination / "portable_manifest.json", + json.dumps(manifest, indent=2, sort_keys=True) + "\n", + ) + manifest["checksummed_files"] = refresh_checksums(destination) + return manifest + + +def _verify_checksums(root: Path) -> list[str]: + failures = [] + checksum_path = root / "checksums.sha256" + if not checksum_path.is_file(): + return ["checksums.sha256 is missing"] + for line in checksum_path.read_text(encoding="utf-8").splitlines(): + expected, separator, relative = line.partition(" ") + path = root / relative + if not separator or not path.is_file() or sha256(path) != expected: + failures.append(relative or line) + return failures + + +def _verify_text_references(root: Path, *, allowed_root: Path | None = None) -> list[str]: + allowed_root = (allowed_root or root).resolve() + failures = [] + for layer in [root / "root.usda", *(root / "layers").glob("*.usda")]: + for reference in REFERENCE_PATTERN.findall(layer.read_text(encoding="utf-8")): + if reference.startswith(("http://", "https://", "omniverse://")): + failures.append(f"external URI in {layer.relative_to(root)}: {reference}") + continue + target = (layer.parent / reference).resolve() + if not target.is_relative_to(allowed_root) or not target.is_file(): + failures.append(f"broken reference in {layer.relative_to(root)}: {reference}") + return failures + + +def _verify_usd( + root: Path, *, allowed_root: Path | None = None +) -> tuple[dict[str, Any], list[str]]: + allowed_root = (allowed_root or root).resolve() + try: + from pxr import Sdf, Usd, UsdPhysics + except ImportError: + return {"pxr_available": False}, [] + stage = Usd.Stage.Open(str(root / "root.usda")) + if stage is None: + return {"pxr_available": True, "stage_open": False}, ["USD stage did not open"] + failures: list[str] = [] + external_paths: list[str] = [] + for layer in stage.GetLayerStack(): + if not layer.realPath: + continue + for reference in layer.GetExternalReferences(): + target = Path(layer.ComputeAbsolutePath(reference)).resolve() + external_paths.append(str(target)) + if not target.is_relative_to(allowed_root) or not target.is_file(): + failures.append(f"USD dependency escapes bundle: {target}") + asset_paths = 0 + for prim in stage.Traverse(): + for attribute in prim.GetAttributes(): + value = attribute.Get() + values = value if isinstance(value, (list, tuple)) else [value] + for item in values: + if isinstance(item, Sdf.AssetPath) and item.path: + asset_paths += 1 + if item.path in ISAAC_RUNTIME_ASSETS: + continue + asset_target = Path(item.resolvedPath).resolve() if item.resolvedPath else None + if ( + asset_target is None + or not asset_target.is_relative_to(allowed_root) + or not asset_target.is_file() + ): + failures.append(f"USD asset dependency is missing or external: {item.path}") + evaluator = json.loads((root / "manifests/evaluator.json").read_text(encoding="utf-8")) + missing_prims = [ + path + for path in [ + *evaluator.get("entity_prim_paths", {}).values(), + evaluator.get("robot_prim_path"), + ] + if path and not stage.GetPrimAtPath(path) + ] + failures.extend(f"evaluator prim is missing: {path}" for path in missing_prims) + task = json.loads((root / "manifests/task.json").read_text(encoding="utf-8")) + entity_paths = evaluator.get("entity_prim_paths", {}) + manipulation_physics: dict[str, Any] = {} + for entity in task.get("entities", []): + if not isinstance(entity, dict) or entity.get("role") != "MANIPULATED": + continue + entity_id = str(entity.get("entity_id", "")) + prim_path = entity_paths.get(entity_id) + prim = stage.GetPrimAtPath(prim_path) if isinstance(prim_path, str) else None + rigid = bool(prim and prim.HasAPI(UsdPhysics.RigidBodyAPI)) + collisions = ( + [ + str(descendant.GetPath()) + for descendant in Usd.PrimRange(prim) + if descendant.HasAPI(UsdPhysics.CollisionAPI) + ] + if prim + else [] + ) + manipulation_physics[entity_id] = { + "prim_path": prim_path, + "rigid_body_api": rigid, + "collision_prim_paths": collisions, + } + if not rigid: + failures.append(f"manipulated entity lacks RigidBodyAPI: {entity_id}") + if not collisions: + failures.append(f"manipulated entity lacks CollisionAPI geometry: {entity_id}") + return { + "pxr_available": True, + "stage_open": True, + "traversed_prims": sum(1 for _ in stage.Traverse()), + "external_layers": len(external_paths), + "asset_paths": asset_paths, + "missing_evaluator_prims": missing_prims, + "manipulation_physics": manipulation_physics, + }, failures + + +def verify_portable_bundle(root: Path, *, require_pxr: bool = False) -> dict[str, Any]: + root = root.resolve() + failures: list[str] = [] + required = [ + "root.usda", + "portable_manifest.json", + "manifests/task.json", + "manifests/scene.json", + "manifests/evaluator.json", + "manifests/episode.json", + ] + if (root / "scenesmith/stage_manifest.json").is_file() or ( + root / "scenesmith/scene.usdc" + ).is_file(): + required.append("scenesmith/scene.usdc") + failures.extend(relative for relative in required if not (root / relative).is_file()) + symlinks = [str(path.relative_to(root)) for path in root.rglob("*") if path.is_symlink()] + failures.extend(f"symlink is not portable: {path}" for path in symlinks) + failures.extend(f"checksum mismatch: {path}" for path in _verify_checksums(root)) + failures.extend(_verify_text_references(root)) + usd_report, usd_failures = _verify_usd(root) + failures.extend(usd_failures) + if require_pxr and not usd_report.get("pxr_available"): + failures.append("pxr is required for full USD validation") + return { + "schema_version": "1.0", + "root": str(root), + "passed": not failures, + "failures": failures, + "file_count": sum(1 for path in root.rglob("*") if path.is_file()), + "size_bytes": sum(path.stat().st_size for path in root.rglob("*") if path.is_file()), + "symlink_count": len(symlinks), + "usd": usd_report, + } + + +def _link_tree(source: Path, destination: Path) -> int: + linked = 0 + for path in sorted(source.rglob("*")): + if path.is_symlink(): + raise RuntimeError(f"portable source contains a symlink: {path}") + if path.is_file(): + _hardlink(path, destination / path.relative_to(source)) + linked += 1 + return linked + + +def create_portable_suite_bundle(source: Path, destination: Path) -> dict[str, Any]: + """Stage a shared-scene benchmark suite with every dependency inside one directory.""" + + source = source.resolve() + destination = destination.resolve() + if destination.exists(): + raise FileExistsError(destination) + suite_manifest_path = source / "manifests/suite.json" + if not suite_manifest_path.is_file(): + raise FileNotFoundError(suite_manifest_path) + if source.stat().st_dev != destination.parent.stat().st_dev: + raise RuntimeError("hard-link staging requires source and destination on one filesystem") + suite_manifest = json.loads(suite_manifest_path.read_text(encoding="utf-8")) + episodes = suite_manifest.get("episodes") + if not isinstance(episodes, list) or not episodes: + raise ValueError("suite manifest must contain episodes") + + destination.mkdir() + linked = 0 + for relative in (Path("inputs"), Path("manifests")): + root = source / relative + if root.is_dir(): + linked += _link_tree(root, destination / relative) + for episode in episodes: + if not isinstance(episode, dict) or not isinstance(episode.get("episode_id"), str): + raise ValueError("suite episode entries require episode_id") + episode_id = episode["episode_id"] + episode_root = source / "episodes" / episode_id + if not episode_root.is_dir(): + raise FileNotFoundError(episode_root) + linked += _link_tree(episode_root, destination / "episodes" / episode_id) + + shared_source = source / "shared_scene" + shared_destination = destination / "shared_scene" + for path, relative in _runtime_files(shared_source): + if not path.is_file(): + raise FileNotFoundError(path) + _hardlink(path, shared_destination / relative) + linked += 1 + + usd_dependencies = { + "rewritten_layers": 0, + "hardlinked_assets": 0, + "dependency_count": 0, + } + if _native_asset_bindings(shared_source): + usd_dependencies = _stage_usd_dependencies( + shared_source / "scenesmith/scene.usdc", + shared_destination / "scenesmith/scene.usdc", + shared_destination, + ) + linked += usd_dependencies["hardlinked_assets"] + + manifest = { + "schema_version": "1.0", + "format": "robothousegen-portable-suite", + "created_at": datetime.now(UTC).isoformat(), + "source_run_name": source.name, + "suite": "manifests/suite.json", + "shared_scene_entrypoint": "shared_scene/root.usda", + "shared_scene_usd": ( + "shared_scene/scenesmith/scene.usdc" + if (shared_destination / "scenesmith/scene.usdc").is_file() + else None + ), + "episode_count": len(episodes), + "hardlink_staging": True, + "hardlinked_files": linked, + "usd_dependencies": usd_dependencies, + "runtime_requirements": { + "simulator": "Isaac Sim 6.0.1", + "benchmark_runtime": "Isaac Lab-Arena release/0.2.1", + }, + } + atomic_write_text( + destination / "portable_manifest.json", + json.dumps(manifest, indent=2, sort_keys=True) + "\n", + ) + manifest["checksummed_files"] = refresh_checksums(destination) + return manifest + + +def verify_portable_suite_bundle(root: Path, *, require_pxr: bool = False) -> dict[str, Any]: + root = root.resolve() + failures: list[str] = [] + required = [ + "portable_manifest.json", + "manifests/suite.json", + "manifests/build_timing.json", + "shared_scene/root.usda", + "shared_scene/manifests/scene.json", + ] + portable_path = root / "portable_manifest.json" + if portable_path.is_file(): + portable = json.loads(portable_path.read_text(encoding="utf-8")) + shared_scene_usd = portable.get("shared_scene_usd") + if isinstance(shared_scene_usd, str): + required.append(shared_scene_usd) + failures.extend(relative for relative in required if not (root / relative).is_file()) + symlinks = [str(path.relative_to(root)) for path in root.rglob("*") if path.is_symlink()] + failures.extend(f"symlink is not portable: {path}" for path in symlinks) + failures.extend(f"checksum mismatch: {path}" for path in _verify_checksums(root)) + + suite_path = root / "manifests/suite.json" + episodes: list[dict[str, Any]] = [] + if suite_path.is_file(): + payload = json.loads(suite_path.read_text(encoding="utf-8")) + raw_episodes = payload.get("episodes", []) + if isinstance(raw_episodes, list): + episodes = [item for item in raw_episodes if isinstance(item, dict)] + else: + failures.append("suite manifest episodes must be a list") + usd_reports: dict[str, Any] = {} + for episode in episodes: + episode_id = episode.get("episode_id") + if not isinstance(episode_id, str): + failures.append("suite episode is missing episode_id") + continue + episode_root = root / "episodes" / episode_id + for relative in ( + "root.usda", + "manifests/task.json", + "manifests/episode.json", + "manifests/evaluator.json", + "manifests/scene_overrides.json", + ): + if not (episode_root / relative).is_file(): + failures.append(f"episodes/{episode_id}/{relative} is missing") + if not (episode_root / "root.usda").is_file(): + continue + failures.extend(_verify_text_references(episode_root, allowed_root=root)) + if (episode_root / "manifests/evaluator.json").is_file(): + usd_report, usd_failures = _verify_usd(episode_root, allowed_root=root) + usd_reports[episode_id] = usd_report + failures.extend(f"{episode_id}: {failure}" for failure in usd_failures) + if require_pxr and not usd_report.get("pxr_available"): + failures.append(f"{episode_id}: pxr is required for full USD validation") + + return { + "schema_version": "1.0", + "root": str(root), + "passed": not failures, + "failures": failures, + "episode_count": len(episodes), + "file_count": sum(1 for path in root.rglob("*") if path.is_file()), + "size_bytes": sum(path.stat().st_size for path in root.rglob("*") if path.is_file()), + "symlink_count": len(symlinks), + "usd": usd_reports, + } + + +def create_zstd_archive(bundle: Path, archive: Path) -> None: + archive.parent.mkdir(parents=True, exist_ok=True) + subprocess.run( + ["tar", "--zstd", "-cf", str(archive), "-C", str(bundle.parent), bundle.name], + check=True, + ) diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/request.py b/docs/reproduction/public_conversion_code/packages/benchmark/request.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf6498f9b8f64075b2a9de6aac8d53d84587873 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/request.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, Literal + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.schemas.models import PredicateSpec, RobotSpawnSpec, TaskEntity, TaskStageSpec +from packages.supervisor.models import IterationPolicyRequest + + +class TaskSkillRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + skill_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + parameters: dict[str, str | int | float | bool] = Field(default_factory=dict) + + +class TaskGraphRequest(BaseModel): + """Optional H20-compatible declarative task graph.""" + + model_config = ConfigDict(extra="forbid") + + task_type: str = Field(default="object_transfer", pattern=r"^[a-z][a-z0-9_]*$") + required_rooms: list[str] = Field(default_factory=lambda: ["workshop"], min_length=1) + initial_predicates: list[PredicateSpec] = Field(default_factory=list) + forbidden_initial_predicates: list[PredicateSpec] = Field(default_factory=list) + goal_predicates: list[PredicateSpec] = Field(default_factory=list) + safety_predicates: list[PredicateSpec] = Field(default_factory=list) + skills: list[TaskSkillRequest] = Field(default_factory=list) + stages: list[TaskStageSpec] = Field(default_factory=list) + + +class SceneProfileRequest(BaseModel): + """H20 topology envelope retained as additive benchmark input metadata.""" + + model_config = ConfigDict(extra="allow") + + topology: Literal["enclosed", "open_surface"] = "enclosed" + enclosure_mode: Literal["generated", "reusable_asset", "review_gate"] = "generated" + floor: bool = True + physical_walls: bool = True + ceiling: bool = True + furniture: bool = True + wall_mounted: bool = True + ceiling_mounted: bool = True + manipuland: Literal["always", "request_driven", "disabled"] = "always" + boundary: Literal["physical_enclosure", "logical_footprint"] = "physical_enclosure" + footprint_margin_m: float = Field(default=0.25, ge=0.0) + hidden_collision_barrier: bool = False + + +class BenchmarkBuildRequest(BaseModel): + """Declarative input for one generated benchmark; no scenario code is required.""" + + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["1.0", "1.1"] = "1.0" + case_id: str | None = Field(default=None, pattern=r"^[a-z0-9][a-z0-9-]*$") + prompt: str = Field(min_length=1) + robot: str = "unitree_g1_43dof" + robot_spawn: RobotSpawnSpec | None = None + scene_entities: list[TaskEntity] = Field(default_factory=list) + task_graph: TaskGraphRequest | None = None + scene_config: dict[str, Any] = Field(default_factory=dict) + scene: SceneProfileRequest | None = None + seed: int = 42 + task_seed: int | None = Field(default=None, ge=0, le=(1 << 32) - 1) + generation_seed: int | None = Field(default=None, ge=0, le=(1 << 32) - 1) + backend: Literal["auto", "metric_v2", "deterministic", "scenesmith"] = "metric_v2" + iteration: IterationPolicyRequest = Field(default_factory=IterationPolicyRequest) + + @property + def effective_seed(self) -> int: + return self.generation_seed if self.generation_seed is not None else ( + self.task_seed if self.task_seed is not None else self.seed + ) + + @model_validator(mode="after") + def validate_task_graph_entities(self) -> BenchmarkBuildRequest: + if self.task_graph is not None and not self.scene_entities: + raise ValueError("task_graph requires scene_entities") + return self + + @classmethod + def from_yaml(cls, path: Path) -> BenchmarkBuildRequest: + payload = yaml.safe_load(path.read_text(encoding="utf-8")) + return cls.model_validate(payload) + + +class SuiteFactorRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + name: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + values: list[str | int | float | bool] = Field(min_length=1) + labels: list[str] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_values_and_labels(self) -> SuiteFactorRequest: + if self.labels and len(self.labels) != len(self.values): + raise ValueError("factor labels and values must have equal length") + if len(self.labels) != len(set(self.labels)): + raise ValueError("factor labels must be unique") + return self + + +class SuiteVariantSetRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + label: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") + conditions: list[str] = Field(default_factory=list) + factors: list[SuiteFactorRequest] = Field(default_factory=list) + constants: dict[str, str | int | float | bool] = Field(default_factory=dict) + + @model_validator(mode="after") + def validate_expansion_source(self) -> SuiteVariantSetRequest: + if not self.conditions and not self.factors: + raise ValueError("variant set needs at least one condition or factor") + if len(self.conditions) != len(set(self.conditions)): + raise ValueError("variant-set conditions must be unique") + factor_names = [factor.name for factor in self.factors] + if len(factor_names) != len(set(factor_names)): + raise ValueError("variant-set factor names must be unique") + return self + + +class SuiteEpisodeGroupRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + group_id: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") + template: str + variant_sets: list[SuiteVariantSetRequest] = Field(min_length=1) + + +class SuiteSceneRequest(BaseModel): + """Scene-generation inputs; additions belong in config, not scenario branches.""" + + model_config = ConfigDict(extra="forbid") + + backend: Literal["auto", "metric_v2", "deterministic", "scenesmith"] = "metric_v2" + task_type: str = "composed_scene" + prompt: str = Field(min_length=1) + asset_lock: str = Field(min_length=1) + asset_conversions: str | None = None + domain_randomization_policy: str | None = None + room_size_m: tuple[float, float, float] | None = None + base_placements: list[dict[str, Any]] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_room_size(self) -> SuiteSceneRequest: + if self.room_size_m is not None and any(value <= 0 for value in self.room_size_m): + raise ValueError("scene room_size_m values must be positive") + return self + + +class SuiteEvaluationRequest(BaseModel): + """Evaluator policy envelope with open predicate-specific thresholds.""" + + model_config = ConfigDict(extra="allow") + + evaluator: str = "predicate_graph_v1" + metrics: list[str] = Field(default_factory=list) + + +class SuiteRuntimeRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + max_duration_s: float = Field(default=120.0, gt=0) + simulator: dict[str, Any] = Field(default_factory=dict) + arena_version: str | None = None + gpu_policy: str | None = None + episode_isolation: str | None = None + oracle: dict[str, Any] = Field(default_factory=dict) + + +class SuiteOutputRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + split: str = "test" + portable: dict[str, Any] = Field(default_factory=dict) + per_episode: list[str] = Field(default_factory=list) + suite_media: list[str] = Field(default_factory=list) + + +class BenchmarkSuiteBuildRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["1.0"] = "1.0" + suite_id: str + robot: str = "unitree_g1_43dof" + seed: int = 42 + benchmark_version: str = "1.0.0" + task_library: str + scene: SuiteSceneRequest + evaluation: SuiteEvaluationRequest = Field(default_factory=SuiteEvaluationRequest) + runtime: SuiteRuntimeRequest = Field(default_factory=SuiteRuntimeRequest) + output: SuiteOutputRequest = Field(default_factory=SuiteOutputRequest) + episode_groups: list[SuiteEpisodeGroupRequest] = Field(min_length=1) + + @model_validator(mode="after") + def validate_group_ids(self) -> BenchmarkSuiteBuildRequest: + group_ids = [group.group_id for group in self.episode_groups] + if len(group_ids) != len(set(group_ids)): + raise ValueError("suite episode group IDs must be unique") + return self + + @classmethod + def from_yaml(cls, path: Path) -> BenchmarkSuiteBuildRequest: + payload = yaml.safe_load(path.read_text(encoding="utf-8")) + return cls.model_validate(payload) diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/suite_builder.py b/docs/reproduction/public_conversion_code/packages/benchmark/suite_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1543187f1ec1e05e673a2541f5d532b39945db --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/suite_builder.py @@ -0,0 +1,401 @@ +from __future__ import annotations + +import json +import os +import shutil +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from packages.benchmark.domain_randomization import DEFAULT_POLICY, DomainRandomizationCompiler +from packages.benchmark.packager import BenchmarkPackager +from packages.benchmark.portable import refresh_checksums +from packages.benchmark.request import BenchmarkSuiteBuildRequest +from packages.benchmark.suite_matrix import expand_episode_matrix +from packages.benchmark.task_library import load_suite_task_library +from packages.core.files import atomic_write_text +from packages.scene_generation.dependency_graph import ( + DEFAULT_DEPENDENCY_POLICY, + load_dependency_policy, +) +from packages.scene_generation.orchestrator import GenerationBackend, SceneGenerationOrchestrator +from packages.schemas.models import ( + BenchmarkSuiteManifest, + PredicateSpec, + SceneLayerPlan, + SceneManifest, + TaskEntity, + TaskSpec, +) + + +@dataclass(frozen=True) +class ValidatedSuiteInputs: + request: BenchmarkSuiteBuildRequest + library_source: Path + asset_source: Path + policy_source: Path + variants: list[Any] + tasks: list[TaskSpec] + asset_lock: dict[str, Any] + randomization_compiler: DomainRandomizationCompiler + scene_task: TaskSpec + report: dict[str, Any] + + +class BenchmarkSuiteBuilder: + """Build a portable shared-scene suite entirely from declarative inputs.""" + + def __init__(self, scene_builder: SceneGenerationOrchestrator | None = None) -> None: + self.scene_builder = scene_builder or SceneGenerationOrchestrator.from_env() + + def build( + self, + suite_path: Path, + output_dir: Path, + *, + backend_override: GenerationBackend | None = None, + ) -> BenchmarkSuiteManifest: + started = time.perf_counter() + validated = validate_suite_inputs(suite_path) + request = validated.request + variants = validated.variants + tasks = validated.tasks + + output_dir.mkdir(parents=True, exist_ok=True) + inputs = output_dir / "inputs" + inputs.mkdir(parents=True, exist_ok=True) + shutil.copy2(suite_path, inputs / "suite.yaml") + library_source = validated.library_source + shutil.copy2(library_source, inputs / library_source.name) + asset_source = validated.asset_source + asset_target = inputs / asset_source.name + shutil.copy2(asset_source, asset_target) + if conversion_declared := request.scene.asset_conversions: + conversion_source = _resolve_input(suite_path, str(conversion_declared)) + shutil.copy2(conversion_source, inputs / conversion_source.name) + policy_source = validated.policy_source + frozen_policy = inputs / "domain_randomization_policy.yaml" + shutil.copy2(policy_source, frozen_policy) + dependency_policy_source = Path( + os.environ.get("RHG_SCENE_DEPENDENCY_POLICY", DEFAULT_DEPENDENCY_POLICY) + ).expanduser().resolve() + load_dependency_policy(dependency_policy_source) + shutil.copy2(dependency_policy_source, inputs / "scene_dependency_policy.yaml") + randomization_compiler = validated.randomization_compiler + scene_task = validated.scene_task + backend = backend_override or GenerationBackend(request.scene.backend) + self.scene_builder.backend = backend + shared_dir = output_dir / "shared_scene" + shared_scene = self.scene_builder.build(scene_task, shared_dir, request.robot) + + packager = BenchmarkPackager() + max_duration_s = request.runtime.max_duration_s + split = request.output.split + for variant, task in zip(variants, tasks, strict=True): + episode_dir = output_dir / "episodes" / variant.episode_id + _write_episode_composition( + episode_dir, + variant.factor_values, + list(task.metadata.get("scene_overrides", [])), + [item.model_dump(mode="json") for item in task.initial_predicates], + shared_scene.entity_prim_paths, + shared_scene.robot_prim_path, + randomization_compiler, + ) + episode_scene = SceneManifest( + scene_id=shared_scene.scene_id, + task_id=task.task_id, + random_seed=task.random_seed, + layer_plan=SceneLayerPlan(root_layer="root.usda", layers={}), + entity_prim_paths={ + entity.entity_id: shared_scene.entity_prim_paths[entity.entity_id] + for entity in task.entities + }, + robot_prim_path=shared_scene.robot_prim_path, + source_checkpoints={ + **shared_scene.source_checkpoints, + "shared_scene": "../../shared_scene/root.usda", + }, + content_hash=shared_scene.content_hash, + ) + packager.package( + task, + episode_scene, + request.robot, + episode_dir, + benchmark_version=request.benchmark_version, + episode_id=variant.episode_id, + max_duration_s=max_duration_s, + split=split, + factor_values={ + "level": variant.level, + "condition": variant.condition, + **variant.factor_values, + }, + evaluator_policy=request.evaluation.model_dump(exclude_none=True), + ) + + manifest = BenchmarkSuiteManifest( + suite_id=request.suite_id, + benchmark_version=request.benchmark_version, + robot_profile=request.robot, + shared_scene_uri="shared_scene/root.usda", + asset_lock_uri=f"inputs/{asset_target.name}", + episodes=variants, + metrics=request.evaluation.metrics, + ) + manifests = output_dir / "manifests" + manifests.mkdir(parents=True, exist_ok=True) + atomic_write_text(manifests / "suite.json", manifest.model_dump_json(indent=2)) + atomic_write_text( + manifests / "build_timing.json", + json.dumps( + { + "schema_version": "1.0", + "episode_count": len(variants), + "frozen_inputs": sorted( + path.name for path in inputs.iterdir() if path.is_file() + ), + "total_duration_s": round(time.perf_counter() - started, 3), + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + refresh_checksums(output_dir) + return manifest + + +def validate_suite_inputs(suite_path: Path) -> ValidatedSuiteInputs: + """Validate every data-owned suite extension before starting an expensive backend.""" + + request = BenchmarkSuiteBuildRequest.from_yaml(suite_path) + library = load_suite_task_library(suite_path, request) + library_source = _resolve_input(suite_path, request.task_library) + asset_source = _resolve_input(suite_path, request.scene.asset_lock) + policy_source = ( + _resolve_input(suite_path, request.scene.domain_randomization_policy) + if request.scene.domain_randomization_policy + else DEFAULT_POLICY.resolve() + ) + variants = expand_episode_matrix(request) + tasks = [library.instantiate(request, variant) for variant in variants] + + referenced_templates = {group.template for group in request.episode_groups} + missing_templates = referenced_templates - set(library.templates) + if missing_templates: + raise ValueError(f"suite references missing task templates: {sorted(missing_templates)}") + metadata_only_factors: list[str] = [] + for group in request.episode_groups: + entry = library.templates[group.template] + for variant_set in group.variant_sets: + for factor in variant_set.factors: + bound = ( + factor.name in entry.factor_bindings + or factor.name in entry.scene_factor_bindings + or _contains_template_token(entry.model_dump(mode="json"), factor.name) + ) + if not bound: + metadata_only_factors.append( + f"{group.group_id}.{variant_set.label}.{factor.name}" + ) + + entity_signatures: dict[str, tuple[str, str, bool]] = {} + for task in tasks: + for entity in task.entities: + signature = (entity.role, entity.category, entity.required) + previous = entity_signatures.setdefault(entity.entity_id, signature) + if previous != signature: + raise ValueError( + f"shared entity {entity.entity_id!r} changes role/category/required " + "between episode variants" + ) + entity_ids = set(entity_signatures) + for raw in request.scene.base_placements: + predicate = PredicateSpec.model_validate(raw) + referenced = {predicate.subject} + if predicate.object is not None: + referenced.add(predicate.object) + unknown = referenced - entity_ids - {"robot"} + if unknown: + raise ValueError(f"scene base placement references unknown entities: {sorted(unknown)}") + + raw_asset_lock = json.loads(asset_source.read_text(encoding="utf-8")) + if not isinstance(raw_asset_lock, dict): + raise ValueError("suite asset lock must contain a JSON object") + asset_lock: dict[str, Any] = raw_asset_lock + for section in ("task_asset_overrides", "procedural_assets"): + records = asset_lock.get(section, {}) + if not isinstance(records, dict): + raise ValueError(f"asset lock {section} must be an object") + unknown = set(records) - entity_ids + if unknown: + raise ValueError(f"asset lock {section} references unknown entities: {sorted(unknown)}") + overrides = asset_lock.get("task_asset_overrides", {}) + invalid_assets = [ + key for key, value in overrides.items() if not isinstance(value, str) or not value + ] + if invalid_assets: + raise ValueError(f"asset lock has invalid asset IDs for: {sorted(invalid_assets)}") + + randomization_compiler = DomainRandomizationCompiler(policy_source) + operation_count = 0 + for task in tasks: + operations = list(task.metadata.get("scene_overrides", [])) + randomization_compiler.validate(operations, entity_ids) + operation_count += len(operations) + scene_task = _merge_scene_task(request, tasks, asset_lock=asset_lock) + report = { + "schema_version": "1.0", + "status": "valid", + "suite_id": request.suite_id, + "backend": request.scene.backend, + "episode_count": len(variants), + "task_template_count": len(referenced_templates), + "entity_count": len(entity_ids), + "domain_operation_count": operation_count, + "asset_override_count": len(overrides), + "procedural_asset_count": len(asset_lock.get("procedural_assets", {})), + "metadata_only_factors": metadata_only_factors, + "data_only_extension_points": [ + "scene", + "task_library", + "episode_groups", + "asset_lock", + "domain_randomization_policy", + "robot_profile", + "evaluation", + ], + } + return ValidatedSuiteInputs( + request=request, + library_source=library_source, + asset_source=asset_source, + policy_source=policy_source, + variants=variants, + tasks=tasks, + asset_lock=asset_lock, + randomization_compiler=randomization_compiler, + scene_task=scene_task, + report=report, + ) + + +def _contains_template_token(value: object, name: str) -> bool: + token = "${" + name + "}" + if isinstance(value, dict): + return any(_contains_template_token(item, name) for item in value.values()) + if isinstance(value, list): + return any(_contains_template_token(item, name) for item in value) + return isinstance(value, str) and token in value + + +def _resolve_input(suite_path: Path, declared: str) -> Path: + path = Path(declared) + candidates = [path] if path.is_absolute() else [suite_path.parent / path, Path.cwd() / path] + for candidate in candidates: + if candidate.is_file(): + return candidate.resolve() + raise FileNotFoundError(f"suite input does not exist: {declared}") + + +def _merge_scene_task( + request: BenchmarkSuiteBuildRequest, + tasks: list[TaskSpec], + *, + asset_lock: dict[str, object], +) -> TaskSpec: + if not tasks: + raise ValueError("suite must contain at least one task") + entities: dict[str, TaskEntity] = {} + for task in tasks: + for entity in task.entities: + previous = entities.get(entity.entity_id) + if previous is not None and previous.role != entity.role: + raise ValueError(f"shared entity {entity.entity_id!r} has conflicting roles") + entities.setdefault(entity.entity_id, entity) + procedural = asset_lock.get("procedural_assets", {}) + if not isinstance(procedural, dict): + raise ValueError("asset lock procedural_assets must be an object") + unknown_procedural = set(procedural) - set(entities) + if unknown_procedural: + raise ValueError( + f"procedural assets reference unknown entities: {sorted(unknown_procedural)}" + ) + for entity_id, geometry in procedural.items(): + entity = entities[entity_id] + entities[entity_id] = entity.model_copy( + update={"attributes": {**entity.attributes, "procedural_geometry": geometry}} + ) + base = tasks[0] + base_placements = [PredicateSpec.model_validate(item) for item in request.scene.base_placements] + scene_description = request.scene.prompt + if room_size := request.scene.room_size_m: + scene_description += f" Exact room dimensions in meters: {room_size}." + return base.model_copy( + update={ + "task_id": f"scene-{request.suite_id}", + "natural_language": scene_description, + "task_type": request.scene.task_type, + "entities": list(entities.values()), + "initial_predicates": base_placements, + "random_seed": request.seed, + "parameters": {}, + "metadata": { + "scene": request.scene.model_dump(mode="json", exclude_none=True), + "suite_id": request.suite_id, + "asset_lock": asset_lock, + }, + } + ) + + +def _write_episode_composition( + episode_dir: Path, + factor_values: dict[str, str | int | float | bool], + scene_overrides: list[object], + initial_predicates: list[object], + entity_prim_paths: dict[str, str], + robot_prim_path: str, + compiler: DomainRandomizationCompiler, +) -> None: + layers = episode_dir / "layers" + layers.mkdir(parents=True, exist_ok=True) + override_layer = layers / "episode_overrides.usda" + atomic_write_text(override_layer, '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n') + atomic_write_text( + episode_dir / "root.usda", + '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' + " subLayers = [@layers/episode_overrides.usda@, @../../shared_scene/root.usda@]\n" + ' upAxis = "Z"\n)\n', + ) + compiled = compiler.compile( + episode_root=episode_dir / "root.usda", + override_layer=override_layer, + operations=scene_overrides, + entity_prim_paths=entity_prim_paths, + robot_prim_path=robot_prim_path, + ) + manifests = episode_dir / "manifests" + manifests.mkdir(parents=True, exist_ok=True) + atomic_write_text( + manifests / "scene_overrides.json", + json.dumps( + { + "schema_version": "1.1", + "factor_values": factor_values, + "operations": scene_overrides, + "applied_operations": compiled.applied, + "deferred_operations": compiled.deferred, + "policy_uri": "../../inputs/domain_randomization_policy.yaml", + "initial_predicates": initial_predicates, + "application_phase": "before_episode_timer_start", + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/suite_matrix.py b/docs/reproduction/public_conversion_code/packages/benchmark/suite_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..7f903cd76f68e4dc4709f3a839ecdfd6fe65d1a3 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/suite_matrix.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import hashlib + +from packages.benchmark.request import BenchmarkSuiteBuildRequest +from packages.schemas.models import EpisodeVariantSpec + + +def expand_episode_matrix(request: BenchmarkSuiteBuildRequest) -> list[EpisodeVariantSpec]: + episodes: list[EpisodeVariantSpec] = [] + for group in request.episode_groups: + for variant_set in group.variant_sets: + for condition in variant_set.conditions: + episodes.append( + _episode( + request, + group.group_id, + group.template, + variant_set.label, + condition, + dict(variant_set.constants), + ) + ) + for factor in variant_set.factors: + labels = factor.labels or _value_labels(len(factor.values)) + if len(labels) != len(factor.values): + raise ValueError( + f"factor {factor.name} labels and values must have equal length" + ) + for endpoint, value in zip(labels, factor.values, strict=True): + episodes.append( + _episode( + request, + group.group_id, + group.template, + variant_set.label, + f"{factor.name}_{endpoint}", + {**variant_set.constants, factor.name: value}, + ) + ) + ids = [episode.episode_id for episode in episodes] + if len(ids) != len(set(ids)): + raise ValueError("expanded suite contains duplicate episode IDs") + return episodes + + +def _episode( + request: BenchmarkSuiteBuildRequest, + task_family: str, + template_name: str, + level: str, + condition: str, + factor_values: dict[str, str | int | float | bool], +) -> EpisodeVariantSpec: + slug = condition.casefold().replace(" ", "_").replace("-", "_") + episode_id = f"{task_family.casefold()}-{level.casefold()}-{slug}" + digest = hashlib.sha256(f"{request.seed}:{episode_id}".encode()).digest() + seed = int.from_bytes(digest[:4], "big") + root = f"episodes/{episode_id}" + return EpisodeVariantSpec( + episode_id=episode_id, + task_family=task_family, + template_name=template_name, + level=level, + condition=condition, + seed=seed, + factor_values=factor_values, + task_uri=f"{root}/manifests/task.json", + root_usd_uri=f"{root}/root.usda", + evaluator_uri=f"{root}/manifests/evaluator.json", + ) + + +def _value_labels(count: int) -> list[str]: + if count == 2: + return ["low", "high"] + return [f"case_{index:02d}" for index in range(1, count + 1)] diff --git a/docs/reproduction/public_conversion_code/packages/benchmark/task_library.py b/docs/reproduction/public_conversion_code/packages/benchmark/task_library.py new file mode 100644 index 0000000000000000000000000000000000000000..c6171b7a2e7d1fba5d03ec3cb75e8016173b01dc --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/benchmark/task_library.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import copy +import re +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field + +from packages.benchmark.request import BenchmarkSuiteBuildRequest +from packages.schemas.models import EpisodeVariantSpec, TaskSpec + +_TOKEN = re.compile(r"^\$\{([a-zA-Z0-9_.-]+)\}$") + + +class TaskTemplateEntry(BaseModel): + model_config = ConfigDict(extra="forbid") + + task: dict[str, Any] + factor_bindings: dict[str, list[str]] = Field(default_factory=dict) + scene_factor_bindings: dict[str, list[dict[str, str]]] = Field(default_factory=dict) + condition_overlays: dict[str, dict[str, Any]] = Field(default_factory=dict) + + +class TaskTemplateLibrary(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: str = "1.0" + templates: dict[str, TaskTemplateEntry] + + @classmethod + def from_file(cls, path: Path) -> TaskTemplateLibrary: + payload = yaml.safe_load(path.read_text(encoding="utf-8")) + return cls.model_validate(payload) + + def instantiate( + self, + request: BenchmarkSuiteBuildRequest, + variant: EpisodeVariantSpec, + ) -> TaskSpec: + template_name = variant.template_name + try: + entry = self.templates[template_name] + except KeyError as error: + raise ValueError(f"task library has no template {template_name!r}") from error + + payload = copy.deepcopy(entry.task) + context: dict[str, Any] = { + "episode_id": variant.episode_id, + "family_id": variant.task_family, + "level": variant.level, + "condition": variant.condition, + "seed": variant.seed, + "robot": request.robot, + **variant.factor_values, + } + payload = _render(payload, context) + overlay = entry.condition_overlays.get(variant.condition) + if overlay: + payload = _deep_merge(payload, _render(copy.deepcopy(overlay), context)) + for factor_name, value in variant.factor_values.items(): + for pointer in entry.factor_bindings.get(factor_name, []): + _set_json_pointer(payload, pointer, value) + + payload["task_id"] = f"task-{variant.episode_id}" + payload["random_seed"] = variant.seed + payload["parameters"] = dict(variant.factor_values) + scene_overrides = [] + for factor_name, value in variant.factor_values.items(): + for binding in entry.scene_factor_bindings.get(factor_name, []): + scene_overrides.append({**binding, "factor": factor_name, "value": value}) + payload.setdefault("metadata", {})["scene_overrides"] = scene_overrides + plan = payload.setdefault("plan", {}) + plan["plan_id"] = f"plan-{variant.episode_id}" + return TaskSpec.model_validate(payload) + + +def load_suite_task_library( + suite_path: Path, request: BenchmarkSuiteBuildRequest +) -> TaskTemplateLibrary: + declared = Path(request.task_library) + path = declared if declared.is_absolute() else suite_path.parent / declared + return TaskTemplateLibrary.from_file(path.resolve()) + + +def _render(value: Any, context: dict[str, Any]) -> Any: + if isinstance(value, dict): + return {key: _render(item, context) for key, item in value.items()} + if isinstance(value, list): + return [_render(item, context) for item in value] + if not isinstance(value, str): + return value + exact = _TOKEN.fullmatch(value) + if exact: + return _lookup(context, exact.group(1)) + for token in re.findall(r"\$\{([a-zA-Z0-9_.-]+)\}", value): + value = value.replace(f"${{{token}}}", str(_lookup(context, token))) + return value + + +def _lookup(context: dict[str, Any], name: str) -> Any: + if name not in context: + raise ValueError(f"task template references missing value {name!r}") + return context[name] + + +def _deep_merge(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]: + for key, value in overlay.items(): + if isinstance(value, dict) and isinstance(base.get(key), dict): + base[key] = _deep_merge(base[key], value) + else: + base[key] = value + return base + + +def _set_json_pointer(payload: dict[str, Any], pointer: str, value: Any) -> None: + if not pointer.startswith("/"): + raise ValueError(f"JSON pointer must start with '/': {pointer}") + parts = [part.replace("~1", "/").replace("~0", "~") for part in pointer[1:].split("/")] + target: Any = payload + for part in parts[:-1]: + target = target[int(part)] if isinstance(target, list) else target[part] + leaf = parts[-1] + if isinstance(target, list): + target[int(leaf)] = value + else: + target[leaf] = value diff --git a/docs/reproduction/public_conversion_code/packages/config/__init__.py b/docs/reproduction/public_conversion_code/packages/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..117b030c19b048f990514afe282fc6bdd13402f9 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/config/__init__.py @@ -0,0 +1,3 @@ +from packages.config.generation import GenerationPolicy, load_generation_policy + +__all__ = ["GenerationPolicy", "load_generation_policy"] diff --git a/docs/reproduction/public_conversion_code/packages/config/generation.py b/docs/reproduction/public_conversion_code/packages/config/generation.py new file mode 100644 index 0000000000000000000000000000000000000000..f106e6c30f3a52c8667a7e49d92f0ea08e4983fc --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/config/generation.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import os +from functools import lru_cache +from pathlib import Path + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field + + +class StrictPolicyModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class TaskAgentPolicy(StrictPolicyModel): + canonical_rooms: list[str] = Field(min_length=1) + architectural_markers: set[str] = Field(default_factory=set) + prompt_rules: list[str] = Field(default_factory=list) + allow_region_entities: bool = False + + +class CategoryDimensionRule(StrictPolicyModel): + maximum_short_axis_m: float | None = Field(default=None, gt=0) + maximum_long_axis_m: float | None = Field(default=None, gt=0) + maximum_volume_m3: float | None = Field(default=None, gt=0) + + +class CategoryIdentityRule(StrictPolicyModel): + required_any: set[str] = Field(min_length=1) + + +GENERIC_CATEGORY_TERMS = { + "asset", + "fixture", + "kitchen", + "object", + "room", + # Location/mount qualifiers must not beat the semantic noun in a + # category selector (for example, display vs. wall tile). + "wall", + "mounted", +} + + +def _selector_score(category_terms: set[str], selector: str) -> tuple[int, int, float]: + selector_terms = set(selector.casefold().replace("-", " ").replace("_", " ").split()) + matches = category_terms & selector_terms + if not matches: + return (0, 0, 0.0) + specific = len(matches - GENERIC_CATEGORY_TERMS) + # A location or mount qualifier alone must not select a semantic rule. + # For example, "wall-mounted display" must not inherit the backsplash + # envelope merely because both categories contain "wall". + if specific == 0: + return (0, 0, 0.0) + return (specific, len(matches), len(matches) / len(selector_terms)) + + +class AssetRetrievalPolicy(StrictPolicyModel): + default_source_priority: list[str] = Field(default_factory=list) + category_source_priority: dict[str, list[str]] = Field(default_factory=dict) + quality_scores: dict[str, int] = Field(default_factory=dict) + preferred_source_bonus: int = 200 + default_source_bonus: int = 10 + max_candidates: int = Field(default=5, gt=0) + prompt_candidates: int = Field(default=3, gt=0) + exact_category_min_candidates: int = Field(default=3, gt=0) + minimum_dimension_fit: float = Field(default=0.55, ge=0.0, le=1.0) + minimum_dimension_fit_candidates: int = Field(default=3, gt=0) + category_dimension_rules: dict[str, CategoryDimensionRule] = Field(default_factory=dict) + category_identity_rules: dict[str, CategoryIdentityRule] = Field(default_factory=dict) + + def priorities_for(self, category: str) -> list[str]: + category_terms = set(category.casefold().replace("-", " ").replace("_", " ").split()) + best_score = (0, 0, 0.0) + best_sources: list[str] = [] + for selector, sources in self.category_source_priority.items(): + score = _selector_score(category_terms, selector) + if score > best_score: + best_score = score + best_sources = sources + return list(best_sources or self.default_source_priority) + + def dimension_rule_for(self, category: str) -> CategoryDimensionRule | None: + category_terms = set(category.casefold().replace("-", " ").replace("_", " ").split()) + best_score = (0, 0, 0.0) + best_rule: CategoryDimensionRule | None = None + for selector, rule in self.category_dimension_rules.items(): + score = _selector_score(category_terms, selector) + if score > best_score: + best_score = score + best_rule = rule + return best_rule + + def identity_rule_for(self, category: str) -> CategoryIdentityRule | None: + category_terms = set(category.casefold().replace("-", " ").replace("_", " ").split()) + best_score = (0, 0, 0.0) + best_rule: CategoryIdentityRule | None = None + for selector, rule in self.category_identity_rules.items(): + score = _selector_score(category_terms, selector) + if score > best_score: + best_score = score + best_rule = rule + return best_rule + + +class ScenePromptPolicy(StrictPolicyModel): + headline: str + minimum_corridor_width_m: float = Field(default=1.2, gt=0) + constraints: list[str] = Field(default_factory=list) + + +class GenerationPolicy(StrictPolicyModel): + schema_version: str + task_agent: TaskAgentPolicy + asset_retrieval: AssetRetrievalPolicy + scene_prompt: ScenePromptPolicy + + +DEFAULT_POLICY_PATH = Path(__file__).resolve().parents[2] / "configs" / "generation_policy.yaml" + + +@lru_cache(maxsize=8) +def _load_cached(path: str) -> GenerationPolicy: + policy_path = Path(path) + if not policy_path.is_file(): + raise FileNotFoundError(policy_path) + payload = yaml.safe_load(policy_path.read_text(encoding="utf-8")) + return GenerationPolicy.model_validate(payload) + + +def load_generation_policy(path: Path | None = None) -> GenerationPolicy: + selected = path or Path(os.environ.get("RHG_GENERATION_POLICY", DEFAULT_POLICY_PATH)) + return _load_cached(str(selected.expanduser().resolve())) diff --git a/docs/reproduction/public_conversion_code/packages/core/__init__.py b/docs/reproduction/public_conversion_code/packages/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9b487ae5d8d3f0e97090cb3930bca213fadd5c2e --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/__init__.py @@ -0,0 +1 @@ +"""Core state and utility behavior.""" diff --git a/docs/reproduction/public_conversion_code/packages/core/contracts/__init__.py b/docs/reproduction/public_conversion_code/packages/core/contracts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..99314456ee5abcbb25914bbfb1cf82d976a85eb3 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/contracts/__init__.py @@ -0,0 +1,69 @@ +"""Public contracts for the task-conditioned scene compiler.""" + +from packages.core.contracts.asset import ( + AssetCertification, + AssetDescriptor, + CertificationProfile, + FidelityScores, + FrontAxis, + FrontConfidenceGrade, + FrontEvidence, + FrontMethod, + FrontReviewStatus, + QualityTier, + SymmetryType, +) +from packages.core.contracts.providers import ( + ProviderLock, + ProviderRole, + SceneRequirements, + canonical_sha256, +) +from packages.core.contracts.scene import ( + AssetLockEntry, + EntityPrimBinding, + EvaluatorSpec, + JointPrimBinding, + RobotStart, + SceneBundle, + SceneRuntimeBindings, +) +from packages.scene_generation.metric_layout import MetricLayoutSpec +from packages.scene_generation.multi_room import ( + MetricPortal, + MetricRoom, + MultiRoomMetricLayoutSpec, + MultiRoomMetricZone, +) +from packages.schemas.models import TaskSpec + +__all__ = [ + "AssetCertification", + "AssetDescriptor", + "AssetLockEntry", + "EntityPrimBinding", + "CertificationProfile", + "EvaluatorSpec", + "FidelityScores", + "FrontAxis", + "FrontConfidenceGrade", + "FrontEvidence", + "FrontMethod", + "FrontReviewStatus", + "JointPrimBinding", + "MetricLayoutSpec", + "MetricPortal", + "MetricRoom", + "MultiRoomMetricLayoutSpec", + "MultiRoomMetricZone", + "ProviderLock", + "ProviderRole", + "QualityTier", + "RobotStart", + "SceneBundle", + "SceneRuntimeBindings", + "SceneRequirements", + "SymmetryType", + "TaskSpec", + "canonical_sha256", +] diff --git a/docs/reproduction/public_conversion_code/packages/core/contracts/asset.py b/docs/reproduction/public_conversion_code/packages/core/contracts/asset.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf0ac1fac6403baa3fadff61703fe21091bddff --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/contracts/asset.py @@ -0,0 +1,38 @@ +"""Stable asset contracts. + +The implementation models remain in ``asset_registry`` so existing imports and +descriptor indexes keep working. This module is the public compiler-facing +contract surface. +""" + +from packages.asset_registry.certification_models import ( + AssetCertification, + CardinalAxis, + CertificationCheck, + CertificationProfile, + FidelityScores, + FrontAxis, + FrontConfidenceGrade, + FrontEvidence, + FrontMethod, + FrontReviewStatus, + QualityTier, + SymmetryType, +) +from packages.asset_registry.descriptors import AssetDescriptor + +__all__ = [ + "AssetCertification", + "AssetDescriptor", + "CardinalAxis", + "CertificationCheck", + "CertificationProfile", + "FidelityScores", + "FrontAxis", + "FrontConfidenceGrade", + "FrontEvidence", + "FrontMethod", + "FrontReviewStatus", + "QualityTier", + "SymmetryType", +] diff --git a/docs/reproduction/public_conversion_code/packages/core/contracts/providers.py b/docs/reproduction/public_conversion_code/packages/core/contracts/providers.py new file mode 100644 index 0000000000000000000000000000000000000000..94372614d7f5852a6994f36e763da5195443ce29 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/contracts/providers.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import hashlib +import json +import math +from datetime import date, datetime +from enum import StrEnum +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.asset_registry.certification_models import FrontConfidenceGrade + + +def _canonical_value(value: Any) -> Any: + if isinstance(value, BaseModel): + # Preserve sets and enums until the recursive normalizer sees them. + # ``mode="json"`` turns sets into iteration-ordered lists, making a + # sealed model hash change after a JSON round trip. + return _canonical_value(value.model_dump(mode="python")) + if isinstance(value, dict): + return {str(key): _canonical_value(item) for key, item in value.items()} + if isinstance(value, (set, frozenset)): + normalized = [_canonical_value(item) for item in value] + return sorted( + normalized, + key=lambda item: json.dumps( + item, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ), + ) + if isinstance(value, (list, tuple)): + return [_canonical_value(item) for item in value] + if isinstance(value, StrEnum): + return value.value + if isinstance(value, Path): + return value.as_posix() + if isinstance(value, (datetime, date)): + return value.isoformat() + if isinstance(value, float) and not math.isfinite(value): + raise ValueError("canonical hashes do not permit NaN or infinity") + return value + + +def canonical_sha256(value: Any) -> str: + encoded = json.dumps( + _canonical_value(value), + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class ProviderRole(StrEnum): + GEOMETRY = "geometry" + VISUAL = "visual" + ASSET = "asset" + RUNTIME = "runtime" + + +class ProviderLock(_StrictModel): + """Immutable provider selection written into every production manifest.""" + + schema_version: Literal["1.0"] = "1.0" + provider_id: str = Field(pattern=r"^[a-z][a-z0-9_.-]*$") + role: ProviderRole + version: str = Field(min_length=1) + implementation_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + config: dict[str, Any] = Field(default_factory=dict) + config_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + allowed_layers: set[str] = Field(default_factory=set) + locked_geometry_sha256: str | None = Field( + default=None, pattern=r"^[0-9a-f]{64}$" + ) + fallback_allowed: Literal[False] = False + + @classmethod + def create( + cls, + *, + provider_id: str, + role: ProviderRole, + version: str, + implementation_sha256: str, + config: dict[str, Any] | None = None, + allowed_layers: set[str] | None = None, + locked_geometry_sha256: str | None = None, + ) -> ProviderLock: + selected = config or {} + return cls( + provider_id=provider_id, + role=role, + version=version, + implementation_sha256=implementation_sha256, + config=selected, + config_sha256=canonical_sha256(selected), + allowed_layers=allowed_layers or set(), + locked_geometry_sha256=locked_geometry_sha256, + ) + + @model_validator(mode="after") + def verify_config_hash(self) -> ProviderLock: + if canonical_sha256(self.config) != self.config_sha256: + raise ValueError("provider config_sha256 does not match canonical config") + if self.provider_id == "auto": + raise ValueError("production manifests cannot lock the auto provider") + if self.role == ProviderRole.VISUAL and self.locked_geometry_sha256 is None: + raise ValueError("visual providers must bind to the locked geometry hash") + return self + + +class SceneRequirements(_StrictModel): + """Task-derived requirements consumed by scene providers and validators.""" + + schema_version: Literal["1.0"] = "1.0" + task_id: str + required_rooms: list[str] = Field(min_length=1) + entity_roles: dict[str, str] = Field(default_factory=dict) + required_asset_certifications: set[str] = Field(default_factory=set) + required_robot_capabilities: set[str] = Field(default_factory=set) + minimum_corridor_width_m: float = Field(default=1.0, gt=0.0) + hard_constraints: list[str] = Field(default_factory=list) + soft_preferences: list[str] = Field(default_factory=list) + approach_zones: list[str] = Field(default_factory=list) + stance_zones: list[str] = Field(default_factory=list) + minimum_front_confidence_by_role: dict[str, FrontConfidenceGrade] = Field( + default_factory=dict + ) diff --git a/docs/reproduction/public_conversion_code/packages/core/contracts/scene.py b/docs/reproduction/public_conversion_code/packages/core/contracts/scene.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e340a4c02b1d89855cdde9008c81ff5ac92726 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/contracts/scene.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.core.contracts.providers import ( + ProviderLock, + ProviderRole, + SceneRequirements, + canonical_sha256, +) +from packages.scene_generation.metric_layout import MetricLayoutSpec +from packages.scene_generation.multi_room import MultiRoomMetricLayoutSpec +from packages.schemas.models import PredicateSpec, TaskSpec + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class EvaluatorSpec(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + evaluator_id: str = Field(pattern=r"^[a-z][a-z0-9_.-]*$") + task_id: str + evaluator_template: str = "predicate_graph_v1" + initial_state: list[PredicateSpec] = Field(default_factory=list) + goal_predicates: list[PredicateSpec] = Field(min_length=1) + safety_predicates: list[PredicateSpec] = Field(default_factory=list) + goal_must_be_false_initially: bool = True + witness_builder: str = Field(min_length=1) + negative_control_tests: list[str] = Field(min_length=1) + required_observation_streams: set[str] = Field(default_factory=set) + parameters: dict[str, Any] = Field(default_factory=dict) + + +class AssetLockEntry(_StrictModel): + asset_id: str + asset_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + source: str + source_version: str + source_license: str + asset_uri: str | None = None + descriptor_uri: str + certification_uri: str | None = None + role: str + entity_ids: list[str] = Field(default_factory=list) + capability_certifications: set[str] = Field(default_factory=set) + + +class RobotStart(_StrictModel): + translation_m: tuple[float, float, float] + yaw_deg: float + stance_zone: str | None = None + + +class EntityPrimBinding(_StrictModel): + entity_id: str + scene_prim_path: str = Field(pattern=r"^/[^/].*") + asset_id: str + asset_prim_path: str | None = None + physics_body_prim_path: str | None = Field(default=None, pattern=r"^/[^/].*") + + +class JointPrimBinding(_StrictModel): + joint_id: str + scene_prim_path: str = Field(pattern=r"^/[^/].*") + joint_type: Literal["revolute", "prismatic"] + lower_limit: float + upper_limit: float + handle_entity_id: str | None = None + + @model_validator(mode="after") + def validate_limits(self) -> JointPrimBinding: + if self.upper_limit <= self.lower_limit: + raise ValueError("joint upper_limit must exceed lower_limit") + return self + + +class SceneRuntimeBindings(_StrictModel): + """Task IDs bound to exact composed USD prim paths for Isaac/evaluator use.""" + + schema_version: Literal["1.0"] = "1.0" + task_id: str + entity_bindings: list[EntityPrimBinding] = Field(min_length=1) + joint_bindings: list[JointPrimBinding] = Field(default_factory=list) + world_anchor_entity_ids: list[str] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_unique_ids(self) -> SceneRuntimeBindings: + entity_ids = [item.entity_id for item in self.entity_bindings] + if len(entity_ids) != len(set(entity_ids)): + raise ValueError("runtime entity binding IDs must be unique") + joint_ids = [item.joint_id for item in self.joint_bindings] + if len(joint_ids) != len(set(joint_ids)): + raise ValueError("runtime joint binding IDs must be unique") + unknown_handles = { + item.handle_entity_id + for item in self.joint_bindings + if item.handle_entity_id and item.handle_entity_id not in set(entity_ids) + } + if unknown_handles: + raise ValueError( + f"runtime joints reference unknown handle entities: {sorted(unknown_handles)}" + ) + if len(self.world_anchor_entity_ids) != len(set(self.world_anchor_entity_ids)): + raise ValueError("world anchor entity IDs must be unique") + unknown_anchors = set(self.world_anchor_entity_ids) - set(entity_ids) + if unknown_anchors: + raise ValueError(f"world anchors reference unknown entities: {sorted(unknown_anchors)}") + bindings = {item.entity_id: item for item in self.entity_bindings} + missing_bodies = [ + entity_id + for entity_id in self.world_anchor_entity_ids + if bindings[entity_id].physics_body_prim_path is None + ] + if missing_bodies: + raise ValueError( + f"world anchor entities require physics body prim paths: {sorted(missing_bodies)}" + ) + return self + + +class SceneBundle(_StrictModel): + """The sealed output contract passed to the Isaac runtime.""" + + schema_version: Literal["1.0"] = "1.0" + bundle_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$") + scene_id: str + task_spec: TaskSpec + scene_requirements: SceneRequirements + metric_layout_spec: MetricLayoutSpec | MultiRoomMetricLayoutSpec + evaluator_spec: EvaluatorSpec + provider_locks: list[ProviderLock] = Field(min_length=1) + layer_uris: dict[str, str] + asset_lock: list[AssetLockEntry] + robot_start: RobotStart + runtime_bindings_uri: str | None = None + layered_scene_plan_uri: str | None = None + validation_report_uris: list[str] = Field(default_factory=list) + provenance: dict[str, Any] = Field(default_factory=dict) + created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) + content_hash: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") + + @model_validator(mode="after") + def validate_and_seal(self) -> SceneBundle: + if self.task_spec.task_id != self.scene_requirements.task_id: + raise ValueError("SceneRequirements task_id does not match TaskSpec") + if self.task_spec.task_id != self.evaluator_spec.task_id: + raise ValueError("EvaluatorSpec task_id does not match TaskSpec") + geometry = [lock for lock in self.provider_locks if lock.role == ProviderRole.GEOMETRY] + if len(geometry) != 1 or geometry[0].provider_id != "metric_v2": + raise ValueError("SceneBundle requires exactly one metric_v2 geometry provider") + allowed_visual_layers = {"materials", "wallpaper", "lighting", "decor", "exterior"} + for lock in self.provider_locks: + if lock.provider_id == "scenesmith_visual": + if lock.role != ProviderRole.VISUAL: + raise ValueError("SceneSmith may only be locked as a visual provider") + forbidden = lock.allowed_layers - allowed_visual_layers + if forbidden: + raise ValueError( + f"SceneSmith visual provider touches locked layers: {sorted(forbidden)}" + ) + if lock.locked_geometry_sha256 != geometry[0].config.get("metric_layout_sha256"): + raise ValueError("SceneSmith visual lock is not bound to Metric V2 geometry") + if "root" not in self.layer_uris: + raise ValueError("SceneBundle layer_uris requires a root layer") + if self.runtime_bindings_uri is not None and ( + self.runtime_bindings_uri.startswith("/") + or ".." in self.runtime_bindings_uri.replace("\\", "/").split("/") + ): + raise ValueError("SceneBundle runtime_bindings_uri must stay relative to the bundle") + if self.layered_scene_plan_uri is not None and ( + self.layered_scene_plan_uri.startswith("/") + or ".." in self.layered_scene_plan_uri.replace("\\", "/").split("/") + ): + raise ValueError("SceneBundle layered_scene_plan_uri must stay relative to the bundle") + if "robot" in self.layer_uris or any( + "robot" in uri.casefold() for uri in self.layer_uris.values() + ): + raise ValueError("base SceneBundle must not embed a robot layer or robot asset") + calculated = canonical_sha256(self.model_dump(mode="python", exclude={"content_hash"})) + if self.content_hash is not None and self.content_hash != calculated: + raise ValueError("SceneBundle content_hash does not match bundle contents") + object.__setattr__(self, "content_hash", calculated) + return self diff --git a/docs/reproduction/public_conversion_code/packages/core/file_lock.py b/docs/reproduction/public_conversion_code/packages/core/file_lock.py new file mode 100644 index 0000000000000000000000000000000000000000..793d3cdc0b56cacc63a3b73cfd80bc606202fe48 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/file_lock.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import os +from typing import TextIO + +if os.name == "nt": + import msvcrt +else: + import fcntl + + +def _prepare_windows_byte(handle: TextIO) -> None: + handle.seek(0) + if not handle.read(1): + handle.seek(0) + handle.write("\0") + handle.flush() + handle.seek(0) + + +def lock_file(handle: TextIO, *, blocking: bool = True) -> bool: + """Lock the first byte of a file; return false for a busy non-blocking lock.""" + if os.name == "nt": + try: + _prepare_windows_byte(handle) + except OSError: + if not blocking: + return False + raise + mode = msvcrt.LK_LOCK if blocking else msvcrt.LK_NBLCK + try: + msvcrt.locking(handle.fileno(), mode, 1) + except OSError: + if not blocking: + return False + raise + return True + flags = fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB) # type: ignore[attr-defined] + try: + fcntl.flock(handle.fileno(), flags) # type: ignore[attr-defined] + except BlockingIOError: + return False + return True + + +def unlock_file(handle: TextIO) -> None: + if os.name == "nt": + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) + return + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) # type: ignore[attr-defined] diff --git a/docs/reproduction/public_conversion_code/packages/core/files.py b/docs/reproduction/public_conversion_code/packages/core/files.py new file mode 100644 index 0000000000000000000000000000000000000000..e397ce8b6adf4dcd65223fe9083ae972cc92feb2 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/files.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import os +import tempfile +from pathlib import Path + + +def atomic_write_text(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp_name, path) + except BaseException: + Path(temp_name).unlink(missing_ok=True) + raise + + +def atomic_write_bytes(path: Path, content: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp_name, path) + except BaseException: + Path(temp_name).unlink(missing_ok=True) + raise diff --git a/docs/reproduction/public_conversion_code/packages/core/state_machine.py b/docs/reproduction/public_conversion_code/packages/core/state_machine.py new file mode 100644 index 0000000000000000000000000000000000000000..b3a5cb7ded51c325ff2a824beb0b1519b012c13f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/core/state_machine.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import StrEnum + + +class JobState(StrEnum): + CREATED = "CREATED" + TASK_RETRIEVED = "TASK_RETRIEVED" + TASK_DESIGNED = "TASK_DESIGNED" + CAPABILITY_MATCHED = "CAPABILITY_MATCHED" + SCENE_AUTHORED = "SCENE_AUTHORED" + USD_COMPOSED = "USD_COMPOSED" + ISAAC_VALIDATED = "ISAAC_VALIDATED" + EVALUATOR_COMPILED = "EVALUATOR_COMPILED" + BENCHMARK_PACKAGED = "BENCHMARK_PACKAGED" + REQUIRES_REVIEW = "REQUIRES_REVIEW" + FAILED = "FAILED" + + +TRANSITIONS: dict[JobState, set[JobState]] = { + JobState.CREATED: {JobState.TASK_RETRIEVED, JobState.FAILED}, + JobState.TASK_RETRIEVED: {JobState.TASK_DESIGNED, JobState.REQUIRES_REVIEW, JobState.FAILED}, + JobState.TASK_DESIGNED: { + JobState.CAPABILITY_MATCHED, + JobState.REQUIRES_REVIEW, + JobState.FAILED, + }, + JobState.CAPABILITY_MATCHED: {JobState.SCENE_AUTHORED, JobState.FAILED}, + JobState.SCENE_AUTHORED: {JobState.USD_COMPOSED, JobState.FAILED}, + JobState.USD_COMPOSED: {JobState.ISAAC_VALIDATED, JobState.FAILED}, + JobState.ISAAC_VALIDATED: {JobState.EVALUATOR_COMPILED, JobState.FAILED}, + JobState.EVALUATOR_COMPILED: {JobState.BENCHMARK_PACKAGED, JobState.FAILED}, + JobState.REQUIRES_REVIEW: {JobState.TASK_DESIGNED, JobState.FAILED}, + JobState.FAILED: set(), + JobState.BENCHMARK_PACKAGED: set(), +} + + +class InvalidTransitionError(ValueError): + pass + + +@dataclass +class JobStateMachine: + state: JobState = JobState.CREATED + history: list[JobState] = field(default_factory=lambda: [JobState.CREATED]) + + def transition(self, target: JobState) -> None: + if target not in TRANSITIONS[self.state]: + raise InvalidTransitionError(f"invalid transition: {self.state} -> {target}") + self.state = target + self.history.append(target) diff --git a/docs/reproduction/public_conversion_code/packages/evaluator/__init__.py b/docs/reproduction/public_conversion_code/packages/evaluator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7a155115d1faa678c97a0575ee7a705114a64ed --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/evaluator/__init__.py @@ -0,0 +1,13 @@ +from packages.evaluator.engine import ( + DeterministicEvaluator, + FactProvider, + ObservationFrame, + TraceFactProvider, +) + +__all__ = [ + "DeterministicEvaluator", + "FactProvider", + "ObservationFrame", + "TraceFactProvider", +] diff --git a/docs/reproduction/public_conversion_code/packages/evaluator/engine.py b/docs/reproduction/public_conversion_code/packages/evaluator/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..15a97dcc34f040161b5ca830603b3e84a6875398 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/evaluator/engine.py @@ -0,0 +1,391 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from math import degrees, radians +from typing import Any, Protocol + +from packages.schemas.models import ( + EvaluationResult, + PredicateResult, + PredicateSpec, + StageEvaluationResult, + TaskSpec, + TaskStageSpec, +) + + +class FactProvider(Protocol): + def evaluate(self, predicate: PredicateSpec) -> tuple[bool, dict[str, Any]]: ... + + +@dataclass(frozen=True, slots=True) +class ObservationFrame: + time_s: float + facts: dict[tuple[str, str, str | None], bool] + values: dict[str, float] + evidence: dict[tuple[str, str, str | None], dict[str, Any] | list[dict[str, Any]]] = field( + default_factory=dict + ) + value_units: dict[str, str] = field(default_factory=dict) + + +@dataclass +class TraceFactProvider: + """Evaluate terminal and temporal predicates from simulator observations.""" + + frames: list[ObservationFrame] + + @staticmethod + def _joint_value(predicate: PredicateSpec, frame: ObservationFrame, joint: str) -> float: + value = frame.values[joint] + source_unit = frame.value_units.get(joint) + target_unit = predicate.params.get("unit") + if source_unit == "radians" and target_unit == "degrees": + return degrees(value) + if source_unit == "degrees" and target_unit == "radians": + return radians(value) + return value + + @staticmethod + def _contact_evidence_matches(predicate: PredicateSpec, frame: ObservationFrame) -> bool: + expected_body = predicate.params.get("subject_body") + expected_link = predicate.params.get("object_link") + if expected_body is None and expected_link is None: + return True + key = (predicate.name, predicate.subject, predicate.object) + raw_records = frame.evidence.get(key) + if raw_records is None: + return False + records = raw_records if isinstance(raw_records, list) else [raw_records] + allowed_bodies = ( + {"left_foot", "right_foot"} + if expected_body == "left_or_right_foot" + else {str(expected_body)} + ) + return any( + (expected_body is None or record.get("subject_body") in allowed_bodies) + and (expected_link is None or record.get("object_link") == expected_link) + for record in records + ) + + @staticmethod + def _passes_at(predicate: PredicateSpec, frame: ObservationFrame) -> bool: + if predicate.name in {"pressed", "open"}: + joint = str(predicate.params.get("joint", "")) + if joint in frame.values: + threshold = float(predicate.params.get("threshold", 0.0)) + value = TraceFactProvider._joint_value(predicate, frame, joint) + return ( + value <= threshold + if predicate.params.get("direction") == "lte" + else value >= threshold + ) + key = (predicate.name, predicate.subject, predicate.object) + passed = bool(frame.facts.get(key, False)) + if passed and predicate.name == "contact": + passed = TraceFactProvider._contact_evidence_matches(predicate, frame) + return passed + + def _matching_frames(self, predicate: PredicateSpec) -> list[ObservationFrame]: + return [frame for frame in self.frames if self._passes_at(predicate, frame)] + + def evaluate(self, predicate: PredicateSpec) -> tuple[bool, dict[str, Any]]: + if not self.frames: + return False, {"source": "simulator_trace", "reason": "empty_trace"} + key = (predicate.name, predicate.subject, predicate.object) + temporal = str(predicate.params.get("temporal", "current")) + candidates = self.frames if temporal in {"ever", "always"} else self.frames[-1:] + matched = [frame for frame in candidates if self._passes_at(predicate, frame)] + observed: dict[str, Any] = { + "fact_key": key, + "source": "simulator_trace", + "temporal": temporal, + } + if matched: + observed["first_match_time_s"] = matched[0].time_s + if predicate.hold_seconds > 0: + held, hold_observed = self._evaluate_hold(predicate, temporal) + observed.update(hold_observed) + return held, observed + if temporal == "always": + observed["matched_frame_count"] = len(matched) + observed["total_frame_count"] = len(candidates) + return len(matched) == len(candidates), observed + if predicate.name in {"pressed", "open"}: + joint = str(predicate.params.get("joint", "")) + threshold = float(predicate.params.get("threshold", 0.0)) + direction = str(predicate.params.get("direction", "gte")) + values = [ + self._joint_value(predicate, frame, joint) + for frame in candidates + if joint in frame.values + ] + if values: + observed.update( + joint=joint, + observed_min=min(values), + observed_max=max(values), + ) + joint_passed = ( + any(value <= threshold for value in values) + if direction == "lte" + else any(value >= threshold for value in values) + ) + return joint_passed, observed + return bool(matched), observed + + def _evaluate_hold( + self, predicate: PredicateSpec, temporal: str + ) -> tuple[bool, dict[str, Any]]: + runs: list[tuple[float, float]] = [] + run_start: float | None = None + run_end: float | None = None + for frame in self.frames: + if self._passes_at(predicate, frame): + run_start = frame.time_s if run_start is None else run_start + run_end = frame.time_s + elif run_start is not None and run_end is not None: + runs.append((run_start, run_end)) + run_start = run_end = None + if run_start is not None and run_end is not None: + runs.append((run_start, run_end)) + required = predicate.hold_seconds + eligible = [run for run in runs if run[1] - run[0] >= required] + if temporal == "current": + eligible = [run for run in eligible if run[1] == self.frames[-1].time_s] + best_duration = max((end - start for start, end in runs), default=0.0) + return bool(eligible), { + "hold_seconds_required": required, + "longest_hold_seconds": best_duration, + "hold_interval_s": list(eligible[0]) if eligible else None, + } + + def evaluate_synchronized( + self, predicates: list[PredicateSpec], window_s: float + ) -> tuple[bool, dict[str, Any]]: + matches = [self._matching_frames(predicate) for predicate in predicates] + if any(not frames for frames in matches): + return False, { + "source": "simulator_trace", + "reason": "synchronized_predicate_missing", + "window_s": window_s, + } + event_times = sorted({frame.time_s for frames in matches for frame in frames}) + for start in event_times: + end = start + window_s + selected = [ + next((frame.time_s for frame in frames if start <= frame.time_s <= end), None) + for frames in matches + ] + if all(value is not None for value in selected): + matched_times = [value for value in selected if value is not None] + return True, { + "source": "simulator_trace", + "window_s": window_s, + "matched_times_s": matched_times, + "synchronized_interval_s": [start, max(matched_times)], + } + return False, { + "source": "simulator_trace", + "reason": "events_outside_synchronization_window", + "window_s": window_s, + "candidate_times_s": [[frame.time_s for frame in frames] for frames in matches], + } + + +@dataclass +class MappingFactProvider: + facts: dict[tuple[str, str, str | None], bool] + + def evaluate(self, predicate: PredicateSpec) -> tuple[bool, dict[str, Any]]: + key = (predicate.name, predicate.subject, predicate.object) + value = self.facts.get(key, False) + if predicate.name == "not": + value = not value + return value, {"fact_key": key, "source": "simulator_truth"} + + +class DeterministicEvaluator: + def evaluate_task(self, task: TaskSpec, provider: FactProvider) -> EvaluationResult: + result = self.evaluate(task.goal_predicates, task.safety_predicates, provider) + stage_results: list[StageEvaluationResult] = [] + completion_indices: dict[str, int] = {} + for stage in task.stages: + missing = [ + dependency + for dependency in stage.depends_on + if dependency not in completion_indices + ] + if missing: + stage_results.append( + StageEvaluationResult( + stage_id=stage.stage_id, + passed=False, + score=0.0, + predicate_results=[], + failure_reason=f"dependency_failed:{','.join(missing)}", + ) + ) + continue + start_index = ( + max(completion_indices[dependency] for dependency in stage.depends_on) + 1 + if stage.depends_on + else 0 + ) + stage_result, completion_index = self._evaluate_stage( + stage, provider, start_index=start_index + ) + stage_results.append(stage_result) + if completion_index is not None: + completion_indices[stage.stage_id] = completion_index + total_weight = sum(stage.weight for stage in task.stages) + achieved_weight = sum( + stage.weight * stage_result.score + for stage, stage_result in zip(task.stages, stage_results, strict=True) + ) + progress = achieved_weight / total_weight if total_weight else result.final_score + return result.model_copy( + update={"stage_results": stage_results, "stage_progress": progress} + ) + + def evaluate( + self, + goals: list[PredicateSpec], + safety: list[PredicateSpec], + provider: FactProvider, + ) -> EvaluationResult: + goal_results = [self._evaluate(item, provider) for item in goals] + goal_results = self._enforce_synchronization(goals, goal_results, provider) + safety_results = [self._evaluate(item, provider) for item in safety] + passed_goals = sum(item.passed for item in goal_results) + score = passed_goals / len(goal_results) if goal_results else 0.0 + safety_events = [ + f"failed:{item.predicate.name}:{item.predicate.subject}" + for item in safety_results + if not item.passed + ] + success = bool(goal_results) and score == 1.0 and not safety_events + first_success_time_s = None + if success and isinstance(provider, TraceFactProvider) and provider.frames: + first_success_time_s = self._first_trace_success_time(goals, safety, provider) + return EvaluationResult( + success=success, + final_score=score, + predicate_results=[*goal_results, *safety_results], + safety_events=safety_events, + first_success_time_s=first_success_time_s, + terminal_reason="success" if success else "predicate_failed", + ) + + @classmethod + def _evaluate_stage( + cls, + stage: TaskStageSpec, + provider: FactProvider, + *, + start_index: int = 0, + ) -> tuple[StageEvaluationResult, int | None]: + evaluation_provider = provider + completion_index: int | None = None + first_success_time_s: float | None = None + if isinstance(provider, TraceFactProvider): + for endpoint in range(start_index, len(provider.frames)): + window = TraceFactProvider(provider.frames[start_index : endpoint + 1]) + completion = [cls._evaluate(item, window) for item in stage.completion_predicates] + completion = cls._enforce_synchronization( + stage.completion_predicates, completion, window + ) + invariants = [cls._evaluate(item, window) for item in stage.invariants] + if all(item.passed for item in [*completion, *invariants]): + evaluation_provider = window + completion_index = endpoint + first_success_time_s = provider.frames[endpoint].time_s + break + else: + evaluation_provider = TraceFactProvider(provider.frames[start_index:]) + + completion = [ + cls._evaluate(item, evaluation_provider) for item in stage.completion_predicates + ] + completion = cls._enforce_synchronization( + stage.completion_predicates, completion, evaluation_provider + ) + invariants = [cls._evaluate(item, evaluation_provider) for item in stage.invariants] + results = [*completion, *invariants] + score = sum(item.passed for item in results) / len(results) if results else 0.0 + passed = bool(results) and all(item.passed for item in results) + if passed and completion_index is None: + completion_index = start_index + return ( + StageEvaluationResult( + stage_id=stage.stage_id, + passed=passed, + score=score, + predicate_results=results, + first_success_time_s=first_success_time_s, + failure_reason=None if passed else "stage_predicate_failed", + ), + completion_index if passed else None, + ) + + @classmethod + def _first_trace_success_time( + cls, + goals: list[PredicateSpec], + safety: list[PredicateSpec], + provider: TraceFactProvider, + ) -> float | None: + for endpoint in range(len(provider.frames)): + prefix = TraceFactProvider(provider.frames[: endpoint + 1]) + goal_results = [cls._evaluate(item, prefix) for item in goals] + goal_results = cls._enforce_synchronization(goals, goal_results, prefix) + safety_results = [cls._evaluate(item, prefix) for item in safety] + if ( + goal_results + and all(item.passed for item in goal_results) + and all(item.passed for item in safety_results) + ): + return provider.frames[endpoint].time_s + return None + + @staticmethod + def _enforce_synchronization( + predicates: list[PredicateSpec], + results: list[PredicateResult], + provider: FactProvider, + ) -> list[PredicateResult]: + groups: dict[str, list[int]] = {} + for index, predicate in enumerate(predicates): + group = predicate.params.get("synchronization_group") + if group: + groups.setdefault(str(group), []).append(index) + for group, indices in groups.items(): + windows = { + float(predicates[index].params.get("synchronization_window_s", 0.0)) + for index in indices + } + window_s = min(windows) + evaluator = getattr(provider, "evaluate_synchronized", None) + if evaluator is None: + passed, observed = ( + False, + { + "reason": "provider_has_no_synchronized_trace", + "window_s": window_s, + }, + ) + else: + passed, observed = evaluator([predicates[index] for index in indices], window_s) + for index in indices: + details = dict(results[index].observed) + details["synchronization_group"] = group + details["synchronization"] = observed + results[index] = results[index].model_copy( + update={"passed": results[index].passed and passed, "observed": details} + ) + return results + + @staticmethod + def _evaluate(predicate: PredicateSpec, provider: FactProvider) -> PredicateResult: + passed, observed = provider.evaluate(predicate) + return PredicateResult(predicate=predicate, passed=passed, observed=observed) diff --git a/docs/reproduction/public_conversion_code/packages/evaluator/suite.py b/docs/reproduction/public_conversion_code/packages/evaluator/suite.py new file mode 100644 index 0000000000000000000000000000000000000000..22d67e0469bea8ae9ed1f8d06c8f4e73a4e786c5 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/evaluator/suite.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from collections import defaultdict +from pathlib import Path + +from packages.schemas.models import ( + BenchmarkSuiteManifest, + EvaluationResult, + SuiteEvaluationSummary, +) + + +def summarize_suite(root: Path, *, require_complete: bool = True) -> SuiteEvaluationSummary: + manifest = BenchmarkSuiteManifest.model_validate_json( + (root / "manifests" / "suite.json").read_text(encoding="utf-8") + ) + results: dict[str, EvaluationResult] = {} + missing = [] + for episode in manifest.episodes: + result_path = root / "episodes" / episode.episode_id / "results" / "evaluation.json" + if not result_path.is_file(): + missing.append(episode.episode_id) + continue + results[episode.episode_id] = EvaluationResult.model_validate_json( + result_path.read_text(encoding="utf-8") + ) + if require_complete and missing: + raise FileNotFoundError(f"suite is missing {len(missing)} evaluation results") + + family_success: dict[str, list[bool]] = defaultdict(list) + atomic_families: set[str] = set() + extension_ids: list[str] = [] + for episode in manifest.episodes: + result = results.get(episode.episode_id) + if result is None: + continue + family_success[episode.task_family].append(result.success) + if episode.level == "EXTENSION": + extension_ids.append(episode.episode_id) + else: + atomic_families.add(episode.task_family) + rates = {family: sum(values) / len(values) for family, values in sorted(family_success.items())} + atomic_rates = [rates[family] for family in sorted(atomic_families)] + extension_results = [results[episode_id] for episode_id in extension_ids] + evaluated = list(results.values()) + successes = sum(result.success for result in evaluated) + return SuiteEvaluationSummary( + suite_id=manifest.suite_id, + episode_count=len(manifest.episodes), + successful_episodes=successes, + success_rate=successes / len(evaluated) if evaluated else 0.0, + atomic_macro_success_rate=(sum(atomic_rates) / len(atomic_rates) if atomic_rates else 0.0), + extension_success_rate=( + sum(result.success for result in extension_results) / len(extension_results) + if extension_results + else 0.0 + ), + mean_stage_progress=( + sum(result.stage_progress for result in evaluated) / len(evaluated) + if evaluated + else 0.0 + ), + safety_failure_count=sum(bool(result.safety_events) for result in evaluated), + task_family_success_rates=rates, + missing_episode_ids=missing, + ) diff --git a/docs/reproduction/public_conversion_code/packages/generative/__init__.py b/docs/reproduction/public_conversion_code/packages/generative/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c264b0fa69a548fbf5d0350c54438e81ec2bbe6 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/generative/__init__.py @@ -0,0 +1,3 @@ +from packages.generative.client import GenerativeClient, RelaySettings + +__all__ = ["GenerativeClient", "RelaySettings"] diff --git a/docs/reproduction/public_conversion_code/packages/generative/client.py b/docs/reproduction/public_conversion_code/packages/generative/client.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf77c23a25207309ff9d0b0980408b557fa2b93 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/generative/client.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +import base64 +import mimetypes +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal, cast + +from openai import OpenAI + + +@dataclass(frozen=True) +class RelaySettings: + base_url: str + api_key: str + image_model: str = "gpt-image-2" + multimodal_model: str = "gpt-6-astra" + multimodal_api: Literal["auto", "responses", "chat"] = "auto" + text_base_url: str | None = None + text_api_key: str | None = None + reasoning_effort: Literal["low", "medium", "high", "xhigh"] | None = None + disable_response_storage: bool = True + + @property + def resolved_text_base_url(self) -> str: + return (self.text_base_url or self.base_url).rstrip("/") + + @property + def resolved_text_api_key(self) -> str: + return self.text_api_key or self.api_key + + @classmethod + def from_env(cls) -> RelaySettings: + api_key, _ = cls._credential_from_env() + if not api_key: + raise RuntimeError( + "IMAGE2_API_KEY is not set and no readable IMAGE2_API_KEY_FILE was found" + ) + raw_api_mode = os.environ.get("MULTIMODAL_API", "auto").strip().casefold() + if raw_api_mode not in {"auto", "responses", "chat"}: + raise ValueError("MULTIMODAL_API must be auto, responses, or chat") + api_mode = cast(Literal["auto", "responses", "chat"], raw_api_mode) + image_base_url = os.environ.get( + "IMAGE2_BASE_URL", "https://54-169-24-77.sslip.io/v1" + ).rstrip("/") + text_api_key, _ = cls._text_credential_from_env() + raw_reasoning_effort = os.environ.get( + "MULTIMODAL_REASONING_EFFORT", + os.environ.get("RHG_PLANNER_REASONING_EFFORT", ""), + ).strip().casefold() + if raw_reasoning_effort and raw_reasoning_effort not in { + "low", + "medium", + "high", + "xhigh", + }: + raise ValueError("MULTIMODAL_REASONING_EFFORT must be low, medium, high, or xhigh") + disable_storage = os.environ.get( + "OPENAI_DISABLE_RESPONSE_STORAGE", + os.environ.get("RHG_PLANNER_DISABLE_RESPONSE_STORAGE", "1"), + ).casefold() in {"1", "true", "yes"} + return cls( + base_url=image_base_url, + api_key=api_key, + image_model=os.environ.get("IMAGE2_MODEL", "gpt-image-2"), + multimodal_model=os.environ.get("MULTIMODAL_MODEL", "gpt-6-astra"), + multimodal_api=api_mode, + text_base_url=os.environ.get("OPENAI_BASE_URL", image_base_url).rstrip("/"), + text_api_key=text_api_key or api_key, + reasoning_effort=( + cast(Literal["low", "medium", "high", "xhigh"], raw_reasoning_effort) + if raw_reasoning_effort + else None + ), + disable_response_storage=disable_storage, + ) + + @classmethod + def status_from_env(cls) -> dict[str, object]: + api_key, credential_source = cls._credential_from_env() + text_api_key, text_credential_source = cls._text_credential_from_env() + return { + "configured": bool(api_key), + "credential_source": credential_source, + "base_url": os.environ.get( + "IMAGE2_BASE_URL", "https://54-169-24-77.sslip.io/v1" + ).rstrip("/"), + "image_model": os.environ.get("IMAGE2_MODEL", "gpt-image-2"), + "multimodal_model": os.environ.get("MULTIMODAL_MODEL", "gpt-6-astra"), + "multimodal_api": os.environ.get("MULTIMODAL_API", "auto"), + "text_base_url": os.environ.get( + "OPENAI_BASE_URL", + os.environ.get("IMAGE2_BASE_URL", "https://54-169-24-77.sslip.io/v1"), + ).rstrip("/"), + "text_configured": bool(text_api_key or api_key), + "text_credential_source": text_credential_source or credential_source, + "reasoning_effort": os.environ.get( + "MULTIMODAL_REASONING_EFFORT", + os.environ.get("RHG_PLANNER_REASONING_EFFORT"), + ), + "response_storage_disabled": os.environ.get( + "OPENAI_DISABLE_RESPONSE_STORAGE", + os.environ.get("RHG_PLANNER_DISABLE_RESPONSE_STORAGE", "1"), + ).casefold() + in {"1", "true", "yes"}, + } + + @staticmethod + def _credential_from_env() -> tuple[str, str | None]: + api_key = os.environ.get("IMAGE2_API_KEY", "").strip() + if api_key: + return api_key, "environment" + key_path = Path( + os.environ.get("IMAGE2_API_KEY_FILE", str(Path.home() / ".config/codeximage2/api_key")) + ).expanduser() + if not key_path.is_file(): + return "", None + if key_path.stat().st_mode & 0o077: + raise RuntimeError(f"IMAGE2_API_KEY_FILE must have mode 600: {key_path}") + return key_path.read_text(encoding="utf-8").strip(), "file" + + @staticmethod + def _text_credential_from_env() -> tuple[str, str | None]: + api_key = os.environ.get("OPENAI_API_KEY", "").strip() + if api_key: + return api_key, "environment" + key_value = os.environ.get("OPENAI_API_KEY_FILE", "").strip() + if not key_value: + return "", None + key_path = Path(key_value).expanduser() + if not key_path.is_file(): + return "", None + if key_path.stat().st_mode & 0o077: + raise RuntimeError(f"OPENAI_API_KEY_FILE must have mode 600: {key_path}") + return key_path.read_text(encoding="utf-8").strip(), "file" + + +class GenerativeClient: + """Small relay client that never returns or logs credentials or encoded inputs.""" + + def __init__( + self, + settings: RelaySettings, + client: OpenAI | None = None, + text_client: OpenAI | None = None, + ) -> None: + self.settings = settings + # Relay-specific model names are intentionally broader than the SDK's literals. + self.client: Any = client or OpenAI(api_key=settings.api_key, base_url=settings.base_url) + if text_client is not None: + self.text_client: Any = text_client + elif client is not None: + self.text_client = client + else: + text_base_url = getattr( + settings, "resolved_text_base_url", settings.base_url.rstrip("/") + ) + text_api_key = getattr(settings, "resolved_text_api_key", settings.api_key) + if text_base_url == settings.base_url.rstrip("/") and text_api_key == settings.api_key: + self.text_client = self.client + else: + self.text_client = OpenAI( + api_key=text_api_key, + base_url=text_base_url, + ) + + def list_models(self) -> list[str]: + return sorted(model.id for model in self.text_client.models.list().data) + + def _response_options(self) -> dict[str, Any]: + options: dict[str, Any] = {"store": not self.settings.disable_response_storage} + if self.settings.reasoning_effort: + options["reasoning"] = {"effort": self.settings.reasoning_effort} + return options + + def generate_image( + self, + prompt: str, + output: Path, + *, + size: str = "1024x1024", + quality: str = "high", + ) -> Path: + self._ensure_new_output(output) + result = self.client.images.generate( + model=self.settings.image_model, + prompt=prompt, + size=size, + quality=quality, + ) + encoded = result.data[0].b64_json if result.data else None + if not encoded: + raise RuntimeError("image relay returned no base64 image") + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(base64.b64decode(encoded, validate=True)) + return output + + def edit_image( + self, + source: Path, + prompt: str, + output: Path, + *, + size: str = "1024x1024", + quality: str = "medium", + ) -> Path: + if not source.is_file(): + raise FileNotFoundError(source) + self._ensure_new_output(output) + with source.open("rb") as image: + result = self.client.images.edit( + model=self.settings.image_model, + image=image, + prompt=prompt, + size=size, + quality=quality, + ) + encoded = result.data[0].b64_json if result.data else None + if not encoded: + raise RuntimeError("image relay returned no base64 image") + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(base64.b64decode(encoded, validate=True)) + return output + + def analyze_image(self, source: Path, prompt: str) -> str: + image_url = self._data_url(source) + if self.settings.multimodal_api in {"auto", "responses"}: + try: + response = self.text_client.responses.create( + model=self.settings.multimodal_model, + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + {"type": "input_image", "image_url": image_url}, + ], + } + ], + **self._response_options(), + ) + return str(response.output_text) + except Exception: + if self.settings.multimodal_api == "responses": + raise + response = self.text_client.chat.completions.create( + model=self.settings.multimodal_model, + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": prompt}, + {"type": "image_url", "image_url": {"url": image_url}}, + ], + } + ], + ) + content = response.choices[0].message.content + if not isinstance(content, str): + raise RuntimeError("multimodal relay returned no text") + return content + + def generate_text(self, prompt: str) -> str: + if not prompt.strip(): + raise ValueError("text prompt cannot be empty") + if self.settings.multimodal_api in {"auto", "responses"}: + try: + response = self.text_client.responses.create( + model=self.settings.multimodal_model, + input=prompt, + **self._response_options(), + ) + output = str(response.output_text) + if not output.strip(): + raise RuntimeError("text relay returned no output") + return output + except Exception: + if self.settings.multimodal_api == "responses": + raise + response = self.text_client.chat.completions.create( + model=self.settings.multimodal_model, + messages=[{"role": "user", "content": prompt}], + ) + content = response.choices[0].message.content + if not isinstance(content, str) or not content.strip(): + raise RuntimeError("text relay returned no text") + return content + + @staticmethod + def _ensure_new_output(output: Path) -> None: + if output.exists(): + raise FileExistsError(f"refusing to overwrite: {output}") + + @staticmethod + def _data_url(source: Path) -> str: + if not source.is_file(): + raise FileNotFoundError(source) + mime_type = mimetypes.guess_type(source.name)[0] or "application/octet-stream" + encoded = base64.b64encode(source.read_bytes()).decode("ascii") + return f"data:{mime_type};base64,{encoded}" diff --git a/docs/reproduction/public_conversion_code/packages/plugins/__init__.py b/docs/reproduction/public_conversion_code/packages/plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d0e6f42606f591bed00546d87f285ab056c9fc6 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/plugins/__init__.py @@ -0,0 +1 @@ +"""Plugin host namespace.""" diff --git a/docs/reproduction/public_conversion_code/packages/plugins/tasks/__init__.py b/docs/reproduction/public_conversion_code/packages/plugins/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c045f3a4beef84f9ace30ed846d58d389de602ab --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/plugins/tasks/__init__.py @@ -0,0 +1,37 @@ +from packages.plugins.tasks.base import ( + EntityRoleRequirement, + InterfaceOnlyTaskPlugin, + TaskPlugin, + TaskPluginCompilation, + TaskPluginRegistry, + TaskPluginSpec, +) +from packages.plugins.tasks.builtins import ( + builtin_task_plugins, + default_task_plugin_registry, +) +from packages.plugins.tasks.cabinet_open_close import ( + CabinetOpenClosePlugin, + CabinetRetrieveParameters, + build_witness, +) +from packages.plugins.tasks.pick_move_place import ( + PickMovePlaceParameters, + PickMovePlacePlugin, +) + +__all__ = [ + "CabinetOpenClosePlugin", + "CabinetRetrieveParameters", + "EntityRoleRequirement", + "InterfaceOnlyTaskPlugin", + "PickMovePlaceParameters", + "PickMovePlacePlugin", + "TaskPlugin", + "TaskPluginCompilation", + "TaskPluginRegistry", + "TaskPluginSpec", + "build_witness", + "builtin_task_plugins", + "default_task_plugin_registry", +] diff --git a/docs/reproduction/public_conversion_code/packages/plugins/tasks/base.py b/docs/reproduction/public_conversion_code/packages/plugins/tasks/base.py new file mode 100644 index 0000000000000000000000000000000000000000..85426399f6d02c3566ff1526b2104b2c482abc49 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/plugins/tasks/base.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +from collections.abc import Iterable +from importlib.metadata import entry_points +from typing import Any, Literal, Protocol + +from pydantic import BaseModel, ConfigDict, Field, field_serializer, model_validator + +from packages.asset_registry.certification_models import CertificationProfile +from packages.core.contracts import EvaluatorSpec, SceneRequirements +from packages.schemas.models import PredicateSpec, TaskSpec + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class EntityRoleRequirement(_StrictModel): + role_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + task_role: Literal["BACKGROUND", "CONTEXT", "MANIPULATED", "TARGET", "REGION"] + category: str + required_certifications: set[CertificationProfile] = Field(default_factory=set) + required_affordances: set[str] = Field(default_factory=set) + + +class TaskPluginSpec(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + plugin_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + version: str + task_type: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + implementation_status: Literal["operational", "interface_only"] + required_robot_capabilities: set[str] = Field(default_factory=set) + required_asset_certifications: set[CertificationProfile] = Field(default_factory=set) + entity_roles: list[EntityRoleRequirement] = Field(min_length=1) + initial_state: list[PredicateSpec] = Field(default_factory=list) + goal_predicates: list[PredicateSpec] = Field(min_length=1) + safety_predicates: list[PredicateSpec] = Field(default_factory=list) + approach_zones: list[str] = Field(default_factory=list) + stance_zones: list[str] = Field(default_factory=list) + skill_graph: list[str] = Field(min_length=1) + witness_builder: str = Field(min_length=1) + evaluator: str = Field(min_length=1) + negative_control_tests: list[str] = Field(min_length=1) + + @field_serializer("required_robot_capabilities") + def serialize_robot_capabilities(self, value: set[str]) -> list[str]: + return sorted(value) + + @field_serializer("required_asset_certifications") + def serialize_asset_profiles( + self, value: set[CertificationProfile] + ) -> list[str]: + return sorted(item.value for item in value) + + @model_validator(mode="after") + def validate_roles_and_zones(self) -> TaskPluginSpec: + roles = [item.role_id for item in self.entity_roles] + if len(roles) != len(set(roles)): + raise ValueError("task plugin entity role IDs must be unique") + unknown_zones = (set(self.approach_zones) | set(self.stance_zones)) - set(roles) + if unknown_zones: + raise ValueError(f"task plugin references unknown zones: {sorted(unknown_zones)}") + declared = { + profile + for role in self.entity_roles + for profile in role.required_certifications + } + if not declared.issubset(self.required_asset_certifications): + raise ValueError("entity role certification is missing from plugin requirements") + return self + + +class TaskPluginCompilation(_StrictModel): + plugin_id: str + plugin_version: str + task_spec: TaskSpec + scene_requirements: SceneRequirements + evaluator_spec: EvaluatorSpec + witness: dict[str, Any] + + +class TaskPlugin(Protocol): + spec: TaskPluginSpec + + def compile(self, parameters: dict[str, Any], *, seed: int) -> TaskPluginCompilation: ... + + +class InterfaceOnlyTaskPlugin: + def __init__(self, spec: TaskPluginSpec) -> None: + if spec.implementation_status != "interface_only": + raise ValueError("InterfaceOnlyTaskPlugin requires interface_only status") + self.spec = spec + + def compile(self, parameters: dict[str, Any], *, seed: int) -> TaskPluginCompilation: + del parameters, seed + raise NotImplementedError( + f"task plugin {self.spec.plugin_id} declares interfaces only; no policy is promised" + ) + + +class TaskPluginRegistry: + ENTRY_POINT_GROUP = "robothousegen.task_plugins" + + def __init__(self, plugins: Iterable[TaskPlugin] = ()) -> None: + self._plugins: dict[str, TaskPlugin] = {} + for plugin in plugins: + self.register(plugin) + + def register(self, plugin: TaskPlugin) -> None: + plugin_id = plugin.spec.plugin_id + if plugin_id in self._plugins: + raise ValueError(f"duplicate task plugin: {plugin_id}") + self._plugins[plugin_id] = plugin + + def discover(self) -> None: + for candidate in entry_points().select(group=self.ENTRY_POINT_GROUP): + loaded = candidate.load() + plugin = loaded() if isinstance(loaded, type) else loaded + self.register(plugin) + + def require(self, plugin_id: str) -> TaskPlugin: + try: + return self._plugins[plugin_id] + except KeyError as error: + raise KeyError(f"task plugin is not registered: {plugin_id}") from error + + @property + def specs(self) -> tuple[TaskPluginSpec, ...]: + return tuple(self._plugins[key].spec for key in sorted(self._plugins)) diff --git a/docs/reproduction/public_conversion_code/packages/plugins/tasks/builtins.py b/docs/reproduction/public_conversion_code/packages/plugins/tasks/builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..cc7d944b11d74d9f54459449e9c47aca7747656c --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/plugins/tasks/builtins.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +from packages.asset_registry.certification_models import CertificationProfile +from packages.plugins.tasks.base import ( + EntityRoleRequirement, + InterfaceOnlyTaskPlugin, + TaskPlugin, + TaskPluginRegistry, + TaskPluginSpec, +) +from packages.plugins.tasks.cabinet_open_close import CabinetOpenClosePlugin +from packages.plugins.tasks.pick_move_place import PickMovePlacePlugin +from packages.schemas.models import PredicateSpec + + +def _interface_plugin( + plugin_id: str, + *, + task_type: str, + capabilities: set[str], + certifications: set[CertificationProfile], + skills: list[str], + negative_controls: list[str], +) -> InterfaceOnlyTaskPlugin: + return InterfaceOnlyTaskPlugin( + TaskPluginSpec( + plugin_id=plugin_id, + version="1.0", + task_type=task_type, + implementation_status="interface_only", + required_robot_capabilities=capabilities, + required_asset_certifications=certifications, + entity_roles=[ + EntityRoleRequirement( + role_id="task_asset", + task_role="MANIPULATED", + category="plugin_specific_asset", + required_certifications=certifications, + ), + EntityRoleRequirement( + role_id="approach_zone", task_role="REGION", category="approach_zone" + ), + EntityRoleRequirement( + role_id="stance_zone", task_role="REGION", category="stance_zone" + ), + ], + initial_state=[], + goal_predicates=[PredicateSpec(name="plugin_goal", subject="task_asset")], + safety_predicates=[PredicateSpec(name="no_safety_event", subject="robot")], + approach_zones=["approach_zone"], + stance_zones=["stance_zone"], + skill_graph=skills, + witness_builder=f"{plugin_id}.witness_v1", + evaluator="predicate_graph_v1", + negative_control_tests=negative_controls, + ) + ) + + +def builtin_task_plugins() -> list[TaskPlugin]: + return [ + CabinetOpenClosePlugin(), + PickMovePlacePlugin(), + _interface_plugin( + "door_open_close", + task_type="door_open_close", + capabilities={"locomotion", "articulated_interaction"}, + certifications={CertificationProfile.HINGE_DOOR_V1}, + skills=["navigate", "open_door", "close_door"], + negative_controls=["no_op", "skip_open", "skip_close"], + ), + _interface_plugin( + "low_pick", + task_type="low_pick", + capabilities={"locomotion", "single_hand_grasp", "low_reach", "stand_recovery"}, + certifications={CertificationProfile.LOW_PICK_V1, CertificationProfile.GRASP_V1}, + skills=["navigate", "squat", "grasp", "recover_stand"], + negative_controls=["no_op", "standing_only"], + ), + _interface_plugin( + "kneeling_pick", + task_type="kneeling_pick", + capabilities={"kneel", "single_hand_grasp", "stand_recovery"}, + certifications={CertificationProfile.LOW_PICK_V1, CertificationProfile.GRASP_V1}, + skills=["navigate", "kneel", "grasp", "recover_stand"], + negative_controls=["no_op", "no_knee_contact", "unsafe_recovery"], + ), + _interface_plugin( + "bimanual_carry", + task_type="bimanual_carry", + capabilities={"bimanual_grasp", "load_carry", "locomotion"}, + certifications={CertificationProfile.BIMANUAL_V1}, + skills=["navigate", "bimanual_grasp", "carry", "bimanual_place"], + negative_controls=["no_op", "single_hand_bypass", "random_policy"], + ), + _interface_plugin( + "pedal_bin", + task_type="pedal_bin", + capabilities={"foot_pedal_interaction", "single_hand_grasp", "balance"}, + certifications={CertificationProfile.FOOT_PEDAL_V1, CertificationProfile.GRASP_V1}, + skills=["navigate", "press_pedal", "grasp", "place"], + negative_controls=["no_op", "hand_press_bypass", "unstable_press"], + ), + ] + + +def default_task_plugin_registry() -> TaskPluginRegistry: + return TaskPluginRegistry(builtin_task_plugins()) diff --git a/docs/reproduction/public_conversion_code/packages/plugins/tasks/cabinet_open_close.py b/docs/reproduction/public_conversion_code/packages/plugins/tasks/cabinet_open_close.py new file mode 100644 index 0000000000000000000000000000000000000000..ecbbbddd4b4f0f4f854a9094c092d34391e63ffe --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/plugins/tasks/cabinet_open_close.py @@ -0,0 +1,393 @@ +from __future__ import annotations + +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +from packages.asset_registry.certification_models import ( + CertificationProfile, + FrontConfidenceGrade, +) +from packages.core.contracts import EvaluatorSpec, SceneRequirements +from packages.plugins.tasks.base import ( + EntityRoleRequirement, + TaskPluginCompilation, + TaskPluginSpec, +) +from packages.schemas.models import ( + DifficultyVector, + PredicateSpec, + SkillInvocation, + TaskEntity, + TaskPlan, + TaskSpec, + TaskStageSpec, +) + + +class CabinetRetrieveParameters(BaseModel): + model_config = ConfigDict(extra="forbid") + + task_id: str = Field(default="cabinet_retrieve_sample", pattern=r"^[a-z][a-z0-9_]*$") + room: str = "kitchen" + object_category: str = "mug" + target_category: str = "table" + cabinet_category: str = "articulated_cabinet" + door_joint: str = "cabinet_door_joint" + seed_description: str = "" + + +def _predicates(door_joint: str) -> dict[str, PredicateSpec]: + return { + "door_closed": PredicateSpec( + name="closed", + subject="cabinet_door", + params={"joint": door_joint, "threshold": 0.1, "direction": "lte"}, + ), + "door_open_ever": PredicateSpec( + name="open", + subject="cabinet_door", + params={ + "joint": door_joint, + "threshold": 0.8, + "direction": "gte", + "temporal": "ever", + }, + ), + "object_inside": PredicateSpec( + name="inside", subject="contained_object", object="cabinet" + ), + "object_on_target": PredicateSpec( + name="on", subject="contained_object", object="target_surface" + ), + "released": PredicateSpec(name="released", subject="contained_object"), + "stable": PredicateSpec( + name="stable", subject="contained_object", hold_seconds=1.0 + ), + } + + +class CabinetOpenClosePlugin: + """Vertical sample: open cabinet, retrieve object, place it, close cabinet.""" + + spec = TaskPluginSpec( + plugin_id="cabinet_open_close", + version="1.0", + task_type="cabinet_retrieve_and_close", + implementation_status="operational", + required_robot_capabilities={ + "locomotion", + "single_hand_grasp", + "articulated_interaction", + }, + required_asset_certifications={ + CertificationProfile.STATIC_PHYSICS_V1, + CertificationProfile.GRASP_V1, + CertificationProfile.HINGE_DOOR_V1, + }, + entity_roles=[ + EntityRoleRequirement( + role_id="cabinet", + task_role="BACKGROUND", + category="articulated_cabinet", + required_certifications={ + CertificationProfile.STATIC_PHYSICS_V1, + CertificationProfile.HINGE_DOOR_V1, + }, + required_affordances={"door_sweep", "operation_clearance"}, + ), + EntityRoleRequirement( + role_id="cabinet_door", + task_role="CONTEXT", + category="cabinet_door", + required_certifications={CertificationProfile.HINGE_DOOR_V1}, + required_affordances={"revolute_joint", "joint_limits"}, + ), + EntityRoleRequirement( + role_id="handle", + task_role="CONTEXT", + category="handle", + required_certifications={CertificationProfile.HINGE_DOOR_V1}, + required_affordances={"grasp_frame"}, + ), + EntityRoleRequirement( + role_id="contained_object", + task_role="MANIPULATED", + category="task_object", + required_certifications={CertificationProfile.GRASP_V1}, + required_affordances={"grasp_frames"}, + ), + EntityRoleRequirement( + role_id="target_surface", + task_role="TARGET", + category="support_surface", + required_certifications={CertificationProfile.STATIC_PHYSICS_V1}, + required_affordances={"support_surface"}, + ), + EntityRoleRequirement( + role_id="cabinet_approach", + task_role="REGION", + category="approach_zone", + ), + EntityRoleRequirement( + role_id="cabinet_stance", + task_role="REGION", + category="stance_zone", + ), + ], + initial_state=[ + PredicateSpec(name="closed", subject="cabinet_door"), + PredicateSpec(name="inside", subject="contained_object", object="cabinet"), + ], + goal_predicates=[ + PredicateSpec(name="open", subject="cabinet_door"), + PredicateSpec(name="on", subject="contained_object", object="target_surface"), + PredicateSpec(name="closed", subject="cabinet_door"), + ], + safety_predicates=[ + PredicateSpec(name="no_safety_event", subject="robot"), + PredicateSpec(name="robot_stable", subject="robot"), + ], + approach_zones=["cabinet_approach"], + stance_zones=["cabinet_stance"], + skill_graph=["navigate", "open_door", "grasp", "place", "close_door"], + witness_builder="cabinet_open_close.witness_v1", + evaluator="predicate_graph_v1", + negative_control_tests=["no_op", "random_policy", "skip_open", "skip_close"], + ) + + def compile(self, parameters: dict[str, Any], *, seed: int) -> TaskPluginCompilation: + declared = CabinetRetrieveParameters.model_validate(parameters) + predicates = _predicates(declared.door_joint) + description = ( + f"在{declared.room}中打开柜门,从柜内取出{declared.object_category}," + f"放到{declared.target_category}上,然后关闭柜门。" + ) + entities = [ + TaskEntity( + entity_id="cabinet", + role="BACKGROUND", + category=declared.cabinet_category, + attributes={ + "required_certifications": ["static_physics_v1", "hinge_door_v1"], + "functional_front_required": True, + }, + ), + TaskEntity( + entity_id="cabinet_door", + role="CONTEXT", + category="cabinet_door", + attributes={"parent": "cabinet", "joint": declared.door_joint}, + ), + TaskEntity( + entity_id="handle", + role="CONTEXT", + category="handle", + attributes={"parent": "cabinet_door", "requires_grasp_frame": True}, + ), + TaskEntity( + entity_id="contained_object", + role="MANIPULATED", + category=declared.object_category, + attributes={"required_certifications": ["grasp_v1"]}, + ), + TaskEntity( + entity_id="target_surface", + role="TARGET", + category=declared.target_category, + attributes={"required_certifications": ["static_physics_v1"]}, + ), + TaskEntity(entity_id="cabinet_approach", role="REGION", category="approach_zone"), + TaskEntity(entity_id="cabinet_stance", role="REGION", category="stance_zone"), + ] + invocations = [ + SkillInvocation( + invocation_id="approach_cabinet", + skill_id="navigate", + parameters={"region": "cabinet_approach"}, + ), + SkillInvocation( + invocation_id="open_cabinet", + skill_id="open_door", + parameters={"object": "cabinet_door", "target": "handle"}, + depends_on=["approach_cabinet"], + ), + SkillInvocation( + invocation_id="retrieve_object", + skill_id="grasp", + parameters={"object": "contained_object"}, + depends_on=["open_cabinet"], + ), + SkillInvocation( + invocation_id="place_object", + skill_id="place", + parameters={"object": "contained_object", "target": "target_surface"}, + depends_on=["retrieve_object"], + ), + SkillInvocation( + invocation_id="close_cabinet", + skill_id="close_door", + parameters={"object": "cabinet_door", "target": "handle"}, + depends_on=["place_object"], + ), + ] + plan = TaskPlan( + plan_id=f"plan-{declared.task_id}", + natural_language=description, + skills=invocations, + required_capabilities=set(self.spec.required_robot_capabilities), + difficulty=DifficultyVector( + body=0.45, + manipulation=0.75, + cognition=0.45, + body_reason="navigate and maintain a cabinet-side stance", + manipulation_reason="hinged interaction followed by grasp and placement", + cognition_reason="ordered open-retrieve-place-close state machine", + ), + ) + goals = [ + predicates["door_open_ever"], + predicates["object_on_target"], + predicates["released"], + predicates["stable"], + predicates["door_closed"], + ] + safety = [ + PredicateSpec(name="no_safety_event", subject="robot"), + PredicateSpec(name="robot_stable", subject="robot", hold_seconds=1.0), + PredicateSpec(name="door_sweep_clear", subject="cabinet_door"), + PredicateSpec(name="torque_within_limits", subject="robot"), + ] + task = TaskSpec( + task_id=f"task-{declared.task_id}", + natural_language=description, + task_type=self.spec.task_type, + required_rooms=[declared.room], + entities=entities, + initial_predicates=[predicates["door_closed"], predicates["object_inside"]], + forbidden_initial_predicates=[ + predicates["door_open_ever"], + predicates["object_on_target"], + ], + goal_predicates=goals, + safety_predicates=safety, + stages=[ + TaskStageSpec( + stage_id="open_cabinet", + name="Open cabinet", + completion_predicates=[predicates["door_open_ever"]], + invariants=[PredicateSpec(name="robot_stable", subject="robot")], + ), + TaskStageSpec( + stage_id="retrieve_object", + name="Retrieve object", + completion_predicates=[ + PredicateSpec(name="held_by", subject="contained_object", object="robot") + ], + depends_on=["open_cabinet"], + ), + TaskStageSpec( + stage_id="place_object", + name="Place object", + completion_predicates=[ + predicates["object_on_target"], + predicates["released"], + ], + depends_on=["retrieve_object"], + ), + TaskStageSpec( + stage_id="close_cabinet", + name="Close cabinet", + completion_predicates=[predicates["door_closed"]], + depends_on=["place_object"], + ), + ], + plan=plan, + random_seed=seed, + parameters={ + "task_plugin": self.spec.plugin_id, + "task_plugin_version": self.spec.version, + "door_joint": declared.door_joint, + }, + metadata={ + "task_plugin": self.spec.model_dump(mode="json"), + "description_source": "TaskSpec structured parameters", + }, + ) + requirements = SceneRequirements( + task_id=task.task_id, + required_rooms=task.required_rooms, + entity_roles={item.entity_id: item.role for item in task.entities}, + required_asset_certifications={ + item.value for item in self.spec.required_asset_certifications + }, + required_robot_capabilities=set(self.spec.required_robot_capabilities), + minimum_corridor_width_m=1.0, + hard_constraints=[ + "door_sweep_clear", + "operation_clearance", + "cabinet_stance_reachable", + "object_grasp_reachable", + "collision_free_navigation", + ], + soft_preferences=["cabinet_near_target_surface", "coherent_kitchen_motif"], + approach_zones=self.spec.approach_zones, + stance_zones=self.spec.stance_zones, + minimum_front_confidence_by_role={ + "cabinet": FrontConfidenceGrade.VERIFIED, + "cabinet_door": FrontConfidenceGrade.VERIFIED, + "handle": FrontConfidenceGrade.HIGH, + }, + ) + evaluator = EvaluatorSpec( + evaluator_id=f"evaluator.{declared.task_id}", + task_id=task.task_id, + initial_state=task.initial_predicates, + goal_predicates=task.goal_predicates, + safety_predicates=task.safety_predicates, + witness_builder=self.spec.witness_builder, + negative_control_tests=self.spec.negative_control_tests, + required_observation_streams={ + "joint_position", + "contact_report", + "object_pose", + "robot_stability", + }, + parameters={"door_joint": declared.door_joint}, + ) + witness = build_witness(task, declared.door_joint) + return TaskPluginCompilation( + plugin_id=self.spec.plugin_id, + plugin_version=self.spec.version, + task_spec=task, + scene_requirements=requirements, + evaluator_spec=evaluator, + witness=witness, + ) + + +def build_witness(task: TaskSpec, door_joint: str) -> dict[str, Any]: + """Deterministic oracle outline; controllers bind these symbolic steps in Isaac.""" + + return { + "schema_version": "1.0", + "task_id": task.task_id, + "kind": "scripted_symbolic_witness", + "controller_required": True, + "steps": [ + {"skill": "navigate", "target": "cabinet_approach"}, + {"skill": "open_door", "joint": door_joint, "target_fraction": 0.8}, + {"skill": "grasp", "object": "contained_object"}, + {"skill": "place", "object": "contained_object", "target": "target_surface"}, + {"skill": "close_door", "joint": door_joint, "target_fraction": 0.1}, + ], + "required_validations": [ + "navigation", + "stance", + "ik_collision", + "articulation", + "physics_stability", + "goal_initially_false", + "negative_controls", + ], + } diff --git a/docs/reproduction/public_conversion_code/packages/plugins/tasks/pick_move_place.py b/docs/reproduction/public_conversion_code/packages/plugins/tasks/pick_move_place.py new file mode 100644 index 0000000000000000000000000000000000000000..4d9a584c1b437b4968bb64e04800cc0460229927 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/plugins/tasks/pick_move_place.py @@ -0,0 +1,342 @@ +from __future__ import annotations + +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +from packages.asset_registry.certification_models import CertificationProfile +from packages.core.contracts import EvaluatorSpec, SceneRequirements +from packages.plugins.tasks.base import ( + EntityRoleRequirement, + TaskPluginCompilation, + TaskPluginSpec, +) +from packages.schemas.models import ( + DifficultyVector, + PredicateSpec, + SkillInvocation, + TaskEntity, + TaskPlan, + TaskSpec, + TaskStageSpec, +) + + +class PickMovePlaceParameters(BaseModel): + model_config = ConfigDict(extra="forbid") + + task_id: str = Field(default="cross_room_pick_move_place", pattern=r"^[a-z][a-z0-9_]*$") + source_room: str = "living_room" + target_room: str = "study" + object_category: str = "mug" + source_category: str = "side_table" + target_category: str = "desk" + + +class PickMovePlacePlugin: + """Operational structured task supporting same-room and cross-room transfer.""" + + spec = TaskPluginSpec( + plugin_id="pick_move_place", + version="2.0", + task_type="pick_move_place", + implementation_status="operational", + required_robot_capabilities={"locomotion", "single_hand_grasp"}, + required_asset_certifications={ + CertificationProfile.STATIC_PHYSICS_V1, + CertificationProfile.GRASP_V1, + }, + entity_roles=[ + EntityRoleRequirement( + role_id="source_surface", + task_role="BACKGROUND", + category="support_surface", + required_certifications={CertificationProfile.STATIC_PHYSICS_V1}, + required_affordances={"support_surface"}, + ), + EntityRoleRequirement( + role_id="task_object", + task_role="MANIPULATED", + category="task_object", + required_certifications={CertificationProfile.GRASP_V1}, + required_affordances={"grasp_frames"}, + ), + EntityRoleRequirement( + role_id="target_surface", + task_role="TARGET", + category="support_surface", + required_certifications={CertificationProfile.STATIC_PHYSICS_V1}, + required_affordances={"support_surface"}, + ), + EntityRoleRequirement( + role_id="source_approach", + task_role="REGION", + category="approach_zone", + ), + EntityRoleRequirement( + role_id="target_approach", + task_role="REGION", + category="approach_zone", + ), + ], + initial_state=[ + PredicateSpec(name="on", subject="task_object", object="source_surface"), + PredicateSpec(name="stable", subject="task_object"), + ], + goal_predicates=[ + PredicateSpec(name="on", subject="task_object", object="target_surface"), + PredicateSpec(name="released", subject="task_object"), + PredicateSpec(name="stable", subject="task_object", hold_seconds=1.0), + ], + safety_predicates=[ + PredicateSpec(name="no_safety_event", subject="robot"), + PredicateSpec(name="robot_stable", subject="robot"), + ], + approach_zones=["source_approach", "target_approach"], + stance_zones=["source_approach", "target_approach"], + skill_graph=["navigate", "grasp", "navigate", "place"], + witness_builder="pick_move_place.witness_v2", + evaluator="predicate_graph_v1", + negative_control_tests=["no_op", "random_policy", "skip_grasp", "wrong_room"], + ) + + def compile(self, parameters: dict[str, Any], *, seed: int) -> TaskPluginCompilation: + declared = PickMovePlaceParameters.model_validate(parameters) + object_on_source = PredicateSpec( + name="on", + subject="task_object", + object="source_surface", + ) + object_on_target = PredicateSpec( + name="on", + subject="task_object", + object="target_surface", + ) + released = PredicateSpec(name="released", subject="task_object") + stable = PredicateSpec( + name="stable", + subject="task_object", + hold_seconds=1.0, + ) + safety = [ + PredicateSpec(name="no_safety_event", subject="robot"), + PredicateSpec(name="robot_stable", subject="robot", hold_seconds=1.0), + ] + required_rooms = list(dict.fromkeys((declared.source_room, declared.target_room))) + description = ( + f"在{declared.source_room}从{declared.source_category}拿起" + f"{declared.object_category},穿过连通房间移动到{declared.target_room}," + f"并将其稳定放到{declared.target_category}上。" + ) + entities = [ + TaskEntity( + entity_id="source_surface", + role="BACKGROUND", + category=declared.source_category, + attributes={ + "room": declared.source_room, + "required_certifications": ["static_physics_v1"], + }, + ), + TaskEntity( + entity_id="task_object", + role="MANIPULATED", + category=declared.object_category, + attributes={ + "room": declared.source_room, + "required_certifications": ["grasp_v1"], + }, + ), + TaskEntity( + entity_id="target_surface", + role="TARGET", + category=declared.target_category, + attributes={ + "room": declared.target_room, + "required_certifications": ["static_physics_v1"], + }, + ), + TaskEntity( + entity_id="source_approach", + role="REGION", + category="approach_zone", + attributes={"room": declared.source_room}, + ), + TaskEntity( + entity_id="target_approach", + role="REGION", + category="approach_zone", + attributes={"room": declared.target_room}, + ), + ] + invocations = [ + SkillInvocation( + invocation_id="navigate_to_source", + skill_id="navigate", + parameters={"region": "source_approach"}, + ), + SkillInvocation( + invocation_id="grasp_object", + skill_id="grasp", + parameters={"object": "task_object"}, + depends_on=["navigate_to_source"], + ), + SkillInvocation( + invocation_id="navigate_to_target", + skill_id="navigate", + parameters={"region": "target_approach", "cross_room": True}, + depends_on=["grasp_object"], + ), + SkillInvocation( + invocation_id="place_object", + skill_id="place", + parameters={"object": "task_object", "target": "target_surface"}, + depends_on=["navigate_to_target"], + ), + ] + plan = TaskPlan( + plan_id=f"plan-{declared.task_id}", + natural_language=description, + skills=invocations, + required_capabilities=set(self.spec.required_robot_capabilities), + difficulty=DifficultyVector( + body=0.55 if len(required_rooms) > 1 else 0.35, + manipulation=0.55, + cognition=0.50, + body_reason="cross-room locomotion while carrying an object", + manipulation_reason="single-hand grasp, transport, release, and stable placement", + cognition_reason="ordered source-to-target room and predicate sequence", + ), + ) + goals = [object_on_target, released, stable] + task = TaskSpec( + task_id=f"task-{declared.task_id}", + natural_language=description, + task_type=self.spec.task_type, + required_rooms=required_rooms, + entities=entities, + initial_predicates=[ + object_on_source, + PredicateSpec(name="stable", subject="task_object"), + ], + forbidden_initial_predicates=[object_on_target], + goal_predicates=goals, + safety_predicates=safety, + stages=[ + TaskStageSpec( + stage_id="grasp_source", + name="Grasp object in source room", + completion_predicates=[ + PredicateSpec( + name="held_by", + subject="task_object", + object="robot", + ) + ], + ), + TaskStageSpec( + stage_id="place_target", + name="Place object in target room", + completion_predicates=goals, + depends_on=["grasp_source"], + ), + ], + plan=plan, + evaluator_template="predicate_graph_v1", + random_seed=seed, + parameters={ + "source_room": declared.source_room, + "target_room": declared.target_room, + "cross_room": len(required_rooms) > 1, + }, + metadata={ + "task_plugin": self.spec.model_dump(mode="json"), + "description_source": "TaskSpec structured parameters", + }, + ) + requirements = SceneRequirements( + task_id=task.task_id, + required_rooms=required_rooms, + entity_roles={entity.entity_id: entity.role for entity in entities}, + required_asset_certifications={ + profile.value for profile in self.spec.required_asset_certifications + }, + required_robot_capabilities=set(self.spec.required_robot_capabilities), + minimum_corridor_width_m=0.85, + hard_constraints=[ + "connected_room_graph", + "portal_clearance", + "cross_room_route_clear", + "door_sweep_clear", + "source_and_target_reachable", + "collision_free_carry", + ], + soft_preferences=["short_cross_room_route", "coherent_room_functions"], + approach_zones=["source_approach", "target_approach"], + stance_zones=["source_approach", "target_approach"], + ) + evaluator = EvaluatorSpec( + evaluator_id=f"eval.{declared.task_id}", + task_id=task.task_id, + evaluator_template="predicate_graph_v1", + initial_state=task.initial_predicates, + goal_predicates=goals, + safety_predicates=safety, + witness_builder=self.spec.witness_builder, + negative_control_tests=self.spec.negative_control_tests, + required_observation_streams={ + "object_pose", + "contact_report", + "robot_pose", + "room_occupancy", + }, + parameters={ + "source_room": declared.source_room, + "target_room": declared.target_room, + "require_portal_crossing": len(required_rooms) > 1, + }, + ) + witness = { + "schema_version": "2.0", + "task_id": task.task_id, + "kind": "scripted_symbolic_witness", + "controller_required": True, + "steps": [ + {"skill": "navigate", "target": "source_approach"}, + {"skill": "grasp", "object": "task_object"}, + { + "skill": "navigate", + "target": "target_approach", + "required_room_sequence": required_rooms, + }, + { + "skill": "place", + "object": "task_object", + "target": "target_surface", + }, + ], + "required_validations": [ + "room_graph", + "portal_sequence", + "navigation", + "carry_clearance", + "ik_collision", + "physics_stability", + "goal_initially_false", + "negative_controls", + ], + } + return TaskPluginCompilation( + plugin_id=self.spec.plugin_id, + plugin_version=self.spec.version, + task_spec=task, + scene_requirements=requirements, + evaluator_spec=evaluator, + witness=witness, + ) + + +__all__ = [ + "PickMovePlaceParameters", + "PickMovePlacePlugin", +] diff --git a/docs/reproduction/public_conversion_code/packages/providers/__init__.py b/docs/reproduction/public_conversion_code/packages/providers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52bd457400b7da3cf07dcf2fa70e9f767d72dce3 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/providers/__init__.py @@ -0,0 +1,6 @@ +"""Versioned scene and asset provider hosts.""" + +from packages.providers.assets import registry_from_source_manifest +from packages.providers.scenes import default_scene_provider_registry + +__all__ = ["default_scene_provider_registry", "registry_from_source_manifest"] diff --git a/docs/reproduction/public_conversion_code/packages/providers/assets/__init__.py b/docs/reproduction/public_conversion_code/packages/providers/assets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dca8b6a2053208b7a3e6ea63e798732494b42c0e --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/providers/assets/__init__.py @@ -0,0 +1,23 @@ +from pathlib import Path + +from packages.asset_registry.ingestion import SourceRegistry +from packages.providers.assets.base import ( + AssetIngestionPlan, + AssetProvider, + AssetProviderRegistry, + SourceAssetProvider, +) + + +def registry_from_source_manifest(path: Path) -> AssetProviderRegistry: + sources = SourceRegistry.from_yaml(path) + return AssetProviderRegistry(SourceAssetProvider(item) for item in sources.sources) + + +__all__ = [ + "AssetIngestionPlan", + "AssetProvider", + "AssetProviderRegistry", + "SourceAssetProvider", + "registry_from_source_manifest", +] diff --git a/docs/reproduction/public_conversion_code/packages/providers/assets/base.py b/docs/reproduction/public_conversion_code/packages/providers/assets/base.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb09e47b083eb9e6f05e59f99bfd0eaac98a578 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/providers/assets/base.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +import hashlib +from collections.abc import Iterable +from pathlib import Path +from typing import Protocol + +from pydantic import BaseModel, ConfigDict + +from packages.asset_registry.ingestion import AssetSourceSpec, AssetStoreLayout, SourceAccess +from packages.core.contracts.providers import ProviderLock, ProviderRole + + +class AssetIngestionPlan(BaseModel): + model_config = ConfigDict(extra="forbid") + + source_id: str + source_version: str + source_license: str + raw_root: str + staged_root: str + certified_root: str + quarantine_root: str + manifest_root: str + artifact_count: int + executable_without_human: bool + blocking_reason: str | None = None + + +class AssetProvider(Protocol): + provider_id: str + + def lock(self) -> ProviderLock: ... + + def ingestion_plan(self, layout: AssetStoreLayout) -> AssetIngestionPlan: ... + + +class SourceAssetProvider: + """Adapter from a reviewed source manifest into the asset provider host.""" + + def __init__(self, source: AssetSourceSpec) -> None: + self.source = source + self.provider_id = source.source_id + + @staticmethod + def _implementation_sha256() -> str: + path = Path(__file__).resolve().parents[2] / "asset_registry" / "ingestion.py" + return hashlib.sha256(path.read_bytes()).hexdigest() + + def lock(self) -> ProviderLock: + return ProviderLock.create( + provider_id=self.provider_id, + role=ProviderRole.ASSET, + version=self.source.version, + implementation_sha256=self._implementation_sha256(), + config={ + "source_url": self.source.source_url, + "license_id": self.source.license_id, + "license_url": self.source.license_url, + "access": self.source.access.value, + "artifact_ids": [item.artifact_id for item in self.source.artifacts], + }, + ) + + def ingestion_plan(self, layout: AssetStoreLayout) -> AssetIngestionPlan: + version_parts = (self.source.source_id, self.source.version) + human_required = self.source.access != SourceAccess.OPEN + executable = ( + bool(self.source.artifacts) + and (self.source.auto_download_allowed or human_required) + ) + reason = None + if not self.source.artifacts: + reason = "no version-pinned artifact manifest" + elif human_required: + reason = "local authorization record required at execution time" + elif not self.source.auto_download_allowed: + reason = "source manifest has not enabled automated acquisition" + return AssetIngestionPlan( + source_id=self.source.source_id, + source_version=self.source.version, + source_license=self.source.license_id, + raw_root=str(layout.raw.joinpath(*version_parts)), + staged_root=str(layout.staged.joinpath(*version_parts)), + certified_root=str(layout.certified.joinpath(*version_parts)), + quarantine_root=str(layout.quarantine.joinpath(*version_parts)), + manifest_root=str(layout.manifests.joinpath(*version_parts)), + artifact_count=len(self.source.artifacts), + executable_without_human=executable and not human_required, + blocking_reason=reason, + ) + + +class AssetProviderRegistry: + def __init__(self, providers: Iterable[AssetProvider] = ()) -> None: + self._providers: dict[str, AssetProvider] = {} + for provider in providers: + self.register(provider) + + def register(self, provider: AssetProvider) -> None: + if provider.provider_id in self._providers: + raise ValueError(f"duplicate asset provider: {provider.provider_id}") + self._providers[provider.provider_id] = provider + + def require(self, provider_id: str) -> AssetProvider: + try: + return self._providers[provider_id] + except KeyError as error: + raise KeyError(f"asset provider is not registered: {provider_id}") from error + + @property + def provider_ids(self) -> tuple[str, ...]: + return tuple(sorted(self._providers)) diff --git a/docs/reproduction/public_conversion_code/packages/providers/scenes/__init__.py b/docs/reproduction/public_conversion_code/packages/providers/scenes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e79338ef5c49df93b7a39320aa3ff91ee80b94d8 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/providers/scenes/__init__.py @@ -0,0 +1,22 @@ +from packages.providers.scenes.base import SceneProvider, SceneProviderRegistry +from packages.providers.scenes.metric_v2 import MetricV2Provider +from packages.providers.scenes.scenesmith_visual import ( + SCENESMITH_VISUAL_LAYERS, + SceneSmithVisualProvider, + VisualLayerDelta, +) + + +def default_scene_provider_registry() -> SceneProviderRegistry: + return SceneProviderRegistry([MetricV2Provider()]) + + +__all__ = [ + "MetricV2Provider", + "SCENESMITH_VISUAL_LAYERS", + "SceneProvider", + "SceneProviderRegistry", + "SceneSmithVisualProvider", + "VisualLayerDelta", + "default_scene_provider_registry", +] diff --git a/docs/reproduction/public_conversion_code/packages/providers/scenes/base.py b/docs/reproduction/public_conversion_code/packages/providers/scenes/base.py new file mode 100644 index 0000000000000000000000000000000000000000..03a190f744b85a927de9c84a35f7e664aa63b7bb --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/providers/scenes/base.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from collections.abc import Iterable +from typing import Protocol + +from packages.core.contracts import ProviderLock +from packages.scene_generation.metric_layout import MetricLayoutSpec + + +class SceneProvider(Protocol): + provider_id: str + version: str + + def lock(self, layout: MetricLayoutSpec, config: dict[str, object]) -> ProviderLock: ... + + +class SceneProviderRegistry: + """Explicit provider registry; it never retries with another provider.""" + + def __init__(self, providers: Iterable[SceneProvider] = ()) -> None: + self._providers: dict[str, SceneProvider] = {} + for provider in providers: + self.register(provider) + + def register(self, provider: SceneProvider) -> None: + if provider.provider_id == "auto": + raise ValueError("auto is a selection mode, not a provider") + if provider.provider_id in self._providers: + raise ValueError(f"duplicate scene provider: {provider.provider_id}") + self._providers[provider.provider_id] = provider + + def require(self, provider_id: str = "metric_v2") -> SceneProvider: + if provider_id == "auto": + raise ValueError("provider must be explicitly resolved before production generation") + try: + return self._providers[provider_id] + except KeyError as error: + raise KeyError(f"scene provider is not registered: {provider_id}") from error + + @property + def provider_ids(self) -> tuple[str, ...]: + return tuple(sorted(self._providers)) diff --git a/docs/reproduction/public_conversion_code/packages/providers/scenes/metric_v2.py b/docs/reproduction/public_conversion_code/packages/providers/scenes/metric_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..07b22cb2cc029ad0bacc0ffe6303e49dcebf83f1 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/providers/scenes/metric_v2.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import hashlib +from pathlib import Path + +from packages.core.contracts import ProviderLock, ProviderRole, canonical_sha256 +from packages.scene_generation.metric_layout import MetricLayoutSpec +from packages.scene_generation.multi_room import MultiRoomMetricLayoutSpec + + +class MetricV2Provider: + """Formal wrapper around the existing MetricLayoutSpec compiler truth.""" + + provider_id = "metric_v2" + version = "3.0" + + @staticmethod + def _implementation_sha256() -> str: + root = Path(__file__).resolve().parents[2] / "scene_generation" + digest = hashlib.sha256() + for source in (root / "metric_layout.py", root / "multi_room.py"): + digest.update(source.name.encode("utf-8")) + digest.update(source.read_bytes()) + return digest.hexdigest() + + def lock( + self, + layout: MetricLayoutSpec | MultiRoomMetricLayoutSpec, + config: dict[str, object], + ) -> ProviderLock: + layout_hash = canonical_sha256(layout.model_dump(mode="json")) + selected = { + **config, + "metric_layout_sha256": layout_hash, + "metric_layout_schema_version": layout.schema_version, + "topology_kind": ( + "multi_room" if isinstance(layout, MultiRoomMetricLayoutSpec) else "single_room" + ), + } + return ProviderLock.create( + provider_id=self.provider_id, + role=ProviderRole.GEOMETRY, + version=self.version, + implementation_sha256=self._implementation_sha256(), + config=selected, + allowed_layers={ + "architecture", + "furniture", + "task", + "semantics", + "physics_overrides", + }, + ) diff --git a/docs/reproduction/public_conversion_code/packages/providers/scenes/scenesmith_visual.py b/docs/reproduction/public_conversion_code/packages/providers/scenes/scenesmith_visual.py new file mode 100644 index 0000000000000000000000000000000000000000..116d9577cabd7cb6fe7d191e6fc3cf046381f3ea --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/providers/scenes/scenesmith_visual.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import hashlib +from pathlib import Path + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.core.contracts import ProviderLock, ProviderRole, canonical_sha256 + +SCENESMITH_VISUAL_LAYERS = {"materials", "wallpaper", "lighting", "decor", "exterior"} + + +class VisualLayerDelta(BaseModel): + """Hash evidence proving that a visual pass did not mutate geometry truth.""" + + model_config = ConfigDict(extra="forbid") + + touched_layers: set[str] = Field(default_factory=set) + metric_layout_sha256_before: str = Field(pattern=r"^[0-9a-f]{64}$") + metric_layout_sha256_after: str = Field(pattern=r"^[0-9a-f]{64}$") + task_spec_sha256_before: str = Field(pattern=r"^[0-9a-f]{64}$") + task_spec_sha256_after: str = Field(pattern=r"^[0-9a-f]{64}$") + operation_envelopes_sha256_before: str = Field(pattern=r"^[0-9a-f]{64}$") + operation_envelopes_sha256_after: str = Field(pattern=r"^[0-9a-f]{64}$") + robot_start_sha256_before: str = Field(pattern=r"^[0-9a-f]{64}$") + robot_start_sha256_after: str = Field(pattern=r"^[0-9a-f]{64}$") + + @model_validator(mode="after") + def preserve_locked_truth(self) -> VisualLayerDelta: + forbidden = self.touched_layers - SCENESMITH_VISUAL_LAYERS + if forbidden: + raise ValueError(f"visual delta touches locked layers: {sorted(forbidden)}") + pairs = ( + (self.metric_layout_sha256_before, self.metric_layout_sha256_after, "layout"), + (self.task_spec_sha256_before, self.task_spec_sha256_after, "task"), + ( + self.operation_envelopes_sha256_before, + self.operation_envelopes_sha256_after, + "operation envelopes", + ), + (self.robot_start_sha256_before, self.robot_start_sha256_after, "robot start"), + ) + changed = [label for before, after, label in pairs if before != after] + if changed: + raise ValueError(f"visual provider changed locked truth: {changed}") + return self + + +class SceneSmithVisualProvider: + provider_id = "scenesmith_visual" + version = "1.0" + + @staticmethod + def _implementation_sha256() -> str: + source = Path(__file__).resolve().parents[2] / "adapters" / "scenesmith.py" + return hashlib.sha256(source.read_bytes()).hexdigest() + + def lock( + self, + geometry_lock: ProviderLock, + config: dict[str, object], + *, + allowed_layers: set[str] | None = None, + ) -> ProviderLock: + if geometry_lock.provider_id != "metric_v2" or geometry_lock.role != ProviderRole.GEOMETRY: + raise ValueError("SceneSmith visual provider requires a Metric V2 geometry lock") + selected_layers = allowed_layers or set(SCENESMITH_VISUAL_LAYERS) + forbidden = selected_layers - SCENESMITH_VISUAL_LAYERS + if forbidden: + raise ValueError(f"SceneSmith visual layers are forbidden: {sorted(forbidden)}") + layout_hash = geometry_lock.config.get("metric_layout_sha256") + if not isinstance(layout_hash, str): + raise ValueError("Metric V2 lock is missing metric_layout_sha256") + selected = {**config, "geometry_provider_lock_sha256": canonical_sha256( + geometry_lock.model_dump(mode="json") + )} + return ProviderLock.create( + provider_id=self.provider_id, + role=ProviderRole.VISUAL, + version=self.version, + implementation_sha256=self._implementation_sha256(), + config=selected, + allowed_layers=selected_layers, + locked_geometry_sha256=layout_hash, + ) diff --git a/docs/reproduction/public_conversion_code/packages/robots/__init__.py b/docs/reproduction/public_conversion_code/packages/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b55495a86b869de37e58fe0989dcf2f0552e3cf3 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/robots/__init__.py @@ -0,0 +1,3 @@ +from packages.robots.profiles import ROBOT_PROFILES, CapabilityMatcher, get_robot_profile + +__all__ = ["ROBOT_PROFILES", "CapabilityMatcher", "get_robot_profile"] diff --git a/docs/reproduction/public_conversion_code/packages/robots/profiles.py b/docs/reproduction/public_conversion_code/packages/robots/profiles.py new file mode 100644 index 0000000000000000000000000000000000000000..b0971d867aebfd15d0364f7aa738f68f4452bbd4 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/robots/profiles.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import os +from pathlib import Path + +import yaml # type: ignore[import-untyped] + +from packages.schemas.models import CapabilityMatch, RobotCapabilityProfile, TaskPlan + + +def load_robot_profiles(path: Path | None = None) -> dict[str, RobotCapabilityProfile]: + declared = path or Path(os.environ.get("RHG_ROBOT_PROFILES", "configs/robots/profiles_v1.yaml")) + if not declared.is_absolute() and not declared.is_file(): + declared = Path(__file__).resolve().parents[2] / declared + payload = yaml.safe_load(declared.read_text(encoding="utf-8")) + profiles = [RobotCapabilityProfile.model_validate(item) for item in payload["robots"]] + from packages.robots.task_constraints import get_task_constraints + for item in profiles: + if item.robot_id in ("unitree_g1_43dof", "rp1_3", "luna"): + item.task_constraints = get_task_constraints(item.robot_id) + registry = {item.robot_id: item for item in profiles} + if len(registry) != len(profiles): + raise ValueError(f"robot profile catalog contains duplicate IDs: {declared}") + return registry + + +ROBOT_PROFILES = load_robot_profiles() + + +def get_robot_profile(robot_id: str) -> RobotCapabilityProfile: + robot_id = {"g1": "unitree_g1_43dof", "rp1": "rp1_3"}.get(robot_id, robot_id) + try: + return ROBOT_PROFILES[robot_id] + except KeyError as error: + raise KeyError(f"unknown robot profile: {robot_id}") from error + + +class CapabilityMatcher: + def match(self, plan: TaskPlan, robot: RobotCapabilityProfile) -> CapabilityMatch: + missing = plan.required_capabilities - robot.capabilities + return CapabilityMatch( + compatible=not missing, + robot_id=robot.robot_id, + required=plan.required_capabilities, + missing=missing, + ) diff --git a/docs/reproduction/public_conversion_code/packages/robots/task_constraints.py b/docs/reproduction/public_conversion_code/packages/robots/task_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..5804a2a2b2295050ca0e42da4055dbc9618e4d3c --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/robots/task_constraints.py @@ -0,0 +1,109 @@ +"""Frozen scalar dimensions only. Never opens robot assets or collision geometry.""" + +from __future__ import annotations + +import math +from copy import deepcopy +from pathlib import Path +from typing import Any + +import yaml + +ALIASES = {"unitree_g1_43dof": "g1", "unitree_g1": "g1", "rp1_3": "rp1"} +CATALOG = yaml.safe_load( + (Path(__file__).resolve().parents[2] / "configs/robots/task_constraints_v1.yaml").read_text( + encoding="utf-8" + ) +)["robots"] + + +def get_task_constraints(robot_id: str | None = None) -> dict[str, Any]: + key = ALIASES.get(robot_id or "default_all", robot_id or "default_all") + if key != "default_all": + if key not in CATALOG: + raise ValueError(f"unknown task constraint robot: {robot_id}") + return {"profile_id": key, **deepcopy(CATALOG[key])} + profiles = list(CATALOG.values()) + result = {"profile_id": key, "members": list(CATALOG)} + for field in ( + "body_width_m", + "body_depth_m", + "carry_corridor_width_m", + "carry_turn_diameter_m", + ): + result[field] = max(p[field] for p in profiles) + result["max_grip_dimension_m"] = min(p["max_grip_dimension_m"] for p in profiles) + result["support_height_range_m"] = [ + max(p["support_height_range_m"][0] for p in profiles), + min(p["support_height_range_m"][1] for p in profiles), + ] + result["depth_table"] = [ + { + "height_m": row["height_m"], + **{ + field: min(p["depth_table"][index][field] for p in profiles) + for field in ("comfort_m", "reachable_m", "edge_m") + }, + } + for index, row in enumerate(profiles[0]["depth_table"]) + ] + result["depth_models"] = [deepcopy(p["depth_model"]) for p in profiles] + return result + + +def depth_bands(profile: dict[str, Any], height: float) -> tuple[float, float, float]: + """DEPTH-RULES comfort/reachable/edge depths at the actual support height. + + The table is a reference snapshot only. Universal profiles intersect the + individual continuous functions, never their parameters or sampled rows. + """ + if not math.isfinite(height): + raise ValueError("support height must be finite") + models = profile.get("depth_models") or [profile["depth_model"]] + values = [] + for model in models: + center = height + model["reference_object_half_height_m"] + low, high = model["shoulder_height_posture_envelope_m"] + shoulder = min(max(center, low), high) + vertical = center - shoulder + deductions = ( + model["front_to_shoulder_m"] + + model["body_edge_clearance_m"] + + model["per_side_hand_reserve_m"] + ) + values.append( + tuple( + max( + 0.0, + math.sqrt( + max( + 0.0, + ( + model["k"][tier] * model["arm_total_to_tool_m"] + + model["contact_offset_m"] + ) + ** 2 + - vertical**2, + ) + ) + - deductions, + ) + for tier in ("comfort", "reachable", "edge") + ) + ) + return tuple(min(row[i] for row in values) for i in range(3)) + + +def depth_limits(profile: dict[str, Any], height: float) -> tuple[float, float]: + """Keep the existing two-band API; edge is available through depth_bands.""" + return depth_bands(profile, height)[:2] + + +def pending_constraints(robot_id: str | None, enabled: bool = True) -> dict[str, Any]: + return { + "enabled": enabled, + "status": "pending_geometry" if enabled else "disabled", + "profile": get_task_constraints(robot_id), + "checks": [], + "resampling_count": 0, + } diff --git a/docs/reproduction/public_conversion_code/packages/runtime/__init__.py b/docs/reproduction/public_conversion_code/packages/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62815462288b396a69e973e1924af5ecb605fb59 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/__init__.py @@ -0,0 +1,17 @@ +from packages.runtime.gpu_scheduler import ( + DynamicGpuPool, + GpuInfo, + GpuLease, + parse_nvidia_smi, + probe_gpus, + select_gpus, +) + +__all__ = [ + "DynamicGpuPool", + "GpuInfo", + "GpuLease", + "parse_nvidia_smi", + "probe_gpus", + "select_gpus", +] diff --git a/docs/reproduction/public_conversion_code/packages/runtime/blender_resident.py b/docs/reproduction/public_conversion_code/packages/runtime/blender_resident.py new file mode 100644 index 0000000000000000000000000000000000000000..1a98848971bc8ba4299fecfd2bad7a746fe8cf90 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/blender_resident.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +import json +import socket +import uuid +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field + + +class BlenderWorkerResponse(BaseModel): + model_config = ConfigDict(extra="forbid") + + protocol_version: Literal["1.0"] = "1.0" + job_id: str + status: Literal["passed", "failed", "shutting_down"] + jobs_completed: int = Field(ge=0) + elapsed_s: float = Field(ge=0.0) + report: str | None = None + error: str | None = None + + +def _endpoint(value: str) -> tuple[str, int]: + host, separator, raw_port = value.rpartition(":") + if not separator or not host: + raise ValueError("Blender resident endpoint must be host:port") + port = int(raw_port) + if not 1 <= port <= 65535: + raise ValueError("Blender resident endpoint port is invalid") + return host, port + + +def _request(endpoint: str, payload: dict[str, Any], *, timeout_s: float) -> dict[str, Any]: + host, port = _endpoint(endpoint) + encoded = (json.dumps(payload, separators=(",", ":")) + "\n").encode() + with socket.create_connection((host, port), timeout=timeout_s) as connection: + connection.settimeout(timeout_s) + connection.sendall(encoded) + chunks: list[bytes] = [] + total = 0 + while True: + chunk = connection.recv(65536) + if not chunk: + break + chunks.append(chunk) + total += len(chunk) + if total > 4 * 1024 * 1024: + raise RuntimeError("Blender resident response exceeded 4 MiB") + if b"\n" in chunk: + break + raw = b"".join(chunks).split(b"\n", 1)[0] + if not raw: + raise RuntimeError("Blender resident worker returned an empty response") + value = json.loads(raw) + if not isinstance(value, dict): + raise RuntimeError("Blender resident worker returned a non-object response") + return value + + +def submit_blender_job( + endpoint: str, + *, + manifest: Path, + output: Path, + mode: Literal["compose", "render-only"] = "compose", + timeout_s: float = 3600.0, +) -> BlenderWorkerResponse: + job_id = uuid.uuid4().hex + response = BlenderWorkerResponse.model_validate( + _request( + endpoint, + { + "protocol_version": "1.0", + "op": "compose", + "job_id": job_id, + "manifest": str(manifest.resolve()), + "output": str(output.resolve()), + "mode": mode, + }, + timeout_s=timeout_s, + ) + ) + if response.job_id != job_id: + raise RuntimeError("Blender resident response job ID differs") + if response.status != "passed": + raise RuntimeError(f"Blender resident job failed: {response.error}") + return response + + +def shutdown_blender_worker( + endpoint: str, *, timeout_s: float = 30.0 +) -> BlenderWorkerResponse: + job_id = uuid.uuid4().hex + response = BlenderWorkerResponse.model_validate( + _request( + endpoint, + { + "protocol_version": "1.0", + "op": "shutdown", + "job_id": job_id, + }, + timeout_s=timeout_s, + ) + ) + if response.job_id != job_id or response.status != "shutting_down": + raise RuntimeError("Blender resident worker did not acknowledge shutdown") + return response diff --git a/docs/reproduction/public_conversion_code/packages/runtime/gpu_scheduler.py b/docs/reproduction/public_conversion_code/packages/runtime/gpu_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..a6005f0b11d3b5c0bfcaebb7dd5eab6395bdb2e9 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/gpu_scheduler.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import os +import subprocess +import time +from dataclasses import dataclass +from pathlib import Path +from typing import TextIO + +from packages.core.file_lock import lock_file + +NVIDIA_SMI_QUERY = "index,name,memory.total,memory.used,memory.free,utilization.gpu" + + +@dataclass(frozen=True, slots=True) +class GpuInfo: + index: int + name: str + memory_total_mb: int + memory_used_mb: int + memory_free_mb: int + utilization_percent: int + + +def parse_nvidia_smi(output: str) -> list[GpuInfo]: + gpus: list[GpuInfo] = [] + for line_number, raw_line in enumerate(output.splitlines(), start=1): + line = raw_line.strip() + if not line: + continue + parts = [part.strip() for part in line.split(",")] + if len(parts) != 6: + raise ValueError(f"invalid nvidia-smi row {line_number}: {raw_line!r}") + try: + gpus.append( + GpuInfo( + index=int(parts[0]), + name=parts[1], + memory_total_mb=int(parts[2]), + memory_used_mb=int(parts[3]), + memory_free_mb=int(parts[4]), + utilization_percent=int(parts[5]), + ) + ) + except ValueError as exc: + raise ValueError(f"invalid nvidia-smi row {line_number}: {raw_line!r}") from exc + return gpus + + +def select_gpus( + gpus: list[GpuInfo], + *, + allowed_ids: set[int] | None, + max_gpus: int, + min_free_vram_mb: int, + max_used_vram_mb: int, + max_utilization_percent: int, +) -> list[GpuInfo]: + if max_gpus < 0: + raise ValueError("max_gpus must be non-negative (0 means all eligible GPUs)") + candidates = [ + gpu + for gpu in gpus + if (allowed_ids is None or gpu.index in allowed_ids) + and gpu.memory_free_mb >= min_free_vram_mb + and gpu.memory_used_mb <= max_used_vram_mb + and gpu.utilization_percent <= max_utilization_percent + ] + candidates.sort(key=lambda gpu: (gpu.utilization_percent, -gpu.memory_free_mb, gpu.index)) + return candidates if max_gpus == 0 else candidates[:max_gpus] + + +def probe_gpus() -> list[GpuInfo]: + completed = subprocess.run( + [ + "nvidia-smi", + f"--query-gpu={NVIDIA_SMI_QUERY}", + "--format=csv,noheader,nounits", + ], + check=True, + capture_output=True, + text=True, + ) + return parse_nvidia_smi(completed.stdout) + + +@dataclass(slots=True) +class GpuLease: + gpu: GpuInfo + handle: TextIO + + def close(self) -> None: + if not self.handle.closed: + self.handle.close() + + def __enter__(self) -> GpuLease: + return self + + def __exit__(self, *_: object) -> None: + self.close() + + +class DynamicGpuPool: + """Cross-process GPU leasing with a fresh memory check before every lease.""" + + def __init__( + self, + lock_root: Path, + *, + allowed_ids: set[int] | None = None, + min_free_vram_mb: int = 8192, + max_used_vram_mb: int = 1 << 30, + max_utilization_percent: int = 100, + ) -> None: + self.lock_root = lock_root + self.allowed_ids = allowed_ids + self.min_free_vram_mb = min_free_vram_mb + self.max_used_vram_mb = max_used_vram_mb + self.max_utilization_percent = max_utilization_percent + self.lock_root.mkdir(parents=True, exist_ok=True) + + def try_acquire(self, *, excluded_ids: set[int] | None = None) -> GpuLease | None: + excluded_ids = excluded_ids or set() + candidates = select_gpus( + probe_gpus(), + allowed_ids=( + None + if self.allowed_ids is None + else self.allowed_ids - excluded_ids + ), + max_gpus=0, + min_free_vram_mb=self.min_free_vram_mb, + max_used_vram_mb=self.max_used_vram_mb, + max_utilization_percent=self.max_utilization_percent, + ) + if self.allowed_ids is None: + candidates = [gpu for gpu in candidates if gpu.index not in excluded_ids] + for gpu in candidates: + path = self.lock_root / f"gpu-{gpu.index}.lock" + handle = path.open("a+", encoding="utf-8") + if not lock_file(handle, blocking=False): + handle.close() + continue + handle.seek(0) + handle.truncate() + handle.write( + f"pid={os.getpid()} gpu={gpu.index} acquired_unix={time.time():.3f}\n" + ) + handle.flush() + return GpuLease(gpu=gpu, handle=handle) + return None + + def acquire( + self, + *, + timeout_s: float, + poll_interval_s: float = 5.0, + excluded_ids: set[int] | None = None, + ) -> GpuLease: + deadline = time.monotonic() + timeout_s + while True: + lease = self.try_acquire(excluded_ids=excluded_ids) + if lease is not None: + return lease + if time.monotonic() >= deadline: + raise TimeoutError("no GPU satisfied the lease requirements before timeout") + time.sleep(min(poll_interval_s, max(0.0, deadline - time.monotonic()))) diff --git a/docs/reproduction/public_conversion_code/packages/runtime/isaac/__init__.py b/docs/reproduction/public_conversion_code/packages/runtime/isaac/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92419281443ff522d32fbe6d0986c2809f35eab8 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/isaac/__init__.py @@ -0,0 +1,24 @@ +from packages.runtime.isaac.contracts import ( + IsaacRunManifest, + IsaacValidationPlan, + RobotInjectionSpec, +) +from packages.runtime.isaac.evaluator import ( + CabinetTraceEvaluation, + CabinetTraceSample, + cabinet_negative_control_traces, + evaluate_cabinet_trace, +) +from packages.runtime.isaac.injection import IsaacRobotInjector, load_and_verify_bundle + +__all__ = [ + "IsaacRobotInjector", + "IsaacRunManifest", + "IsaacValidationPlan", + "CabinetTraceEvaluation", + "CabinetTraceSample", + "RobotInjectionSpec", + "load_and_verify_bundle", + "cabinet_negative_control_traces", + "evaluate_cabinet_trace", +] diff --git a/docs/reproduction/public_conversion_code/packages/runtime/isaac/contracts.py b/docs/reproduction/public_conversion_code/packages/runtime/isaac/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..9914f57728cac2f5756475ed968cc0ade2530854 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/isaac/contracts.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.core.contracts.scene import RobotStart, SceneBundle + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class RobotInjectionSpec(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + scene_bundle_id: str + scene_bundle_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + robot_id: str + robot_asset_uri: str + robot_asset_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + robot_profile_version: str + spawn: RobotStart + injection_layer_uri: str + + @classmethod + def for_bundle( + cls, + bundle: SceneBundle, + **values: Any, + ) -> RobotInjectionSpec: + if bundle.content_hash is None: + raise ValueError("SceneBundle must be sealed before robot injection") + return cls( + scene_bundle_id=bundle.bundle_id, + scene_bundle_sha256=bundle.content_hash, + spawn=bundle.robot_start, + **values, + ) + + +class IsaacValidationPlan(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + validators: list[ + Literal[ + "asset", + "layout", + "navigation", + "reachability", + "physics", + "task", + "safety", + ] + ] = Field(min_length=7) + require_oracle_replay: Literal[True] = True + require_no_op_control: Literal[True] = True + require_random_control: Literal[True] = True + require_goal_false_initially: Literal[True] = True + warm_process_required: bool = True + gpu_lease_required: bool = True + + @model_validator(mode="after") + def require_full_gate(self) -> IsaacValidationPlan: + required = { + "asset", + "layout", + "navigation", + "reachability", + "physics", + "task", + "safety", + } + if set(self.validators) != required: + raise ValueError("Isaac validation plan must include every production hard gate") + return self + + +class IsaacRunManifest(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + run_id: str + scene_bundle_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + robot_injection_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + isaac_sim_version: str + isaac_lab_arena_version: str + seed: int + started_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) + completed_at: datetime | None = None + validator_reports: dict[str, str] = Field(default_factory=dict) + oracle_replay_uri: str | None = None + negative_control_report_uri: str | None = None + passed: bool = False + failure_reasons: list[str] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_release(self) -> IsaacRunManifest: + if self.passed: + required = { + "asset", + "layout", + "navigation", + "reachability", + "physics", + "task", + "safety", + } + if set(self.validator_reports) != required: + raise ValueError("passed Isaac run requires every validator report") + if not self.oracle_replay_uri or not self.negative_control_report_uri: + raise ValueError("passed Isaac run requires replay and negative-control evidence") + if self.completed_at is None or self.failure_reasons: + raise ValueError("passed Isaac run must be complete and failure-free") + return self diff --git a/docs/reproduction/public_conversion_code/packages/runtime/isaac/evaluator.py b/docs/reproduction/public_conversion_code/packages/runtime/isaac/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..3d8bbd917bbfa3942b96a4b8abac910b87abce3b --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/isaac/evaluator.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict, Field + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class CabinetTraceSample(_StrictModel): + step: str + door_fraction: float = Field(ge=0.0, le=1.0) + object_state: str + released: bool + stable: bool + robot_stable: bool + safety_event: bool = False + + +class CabinetTraceEvaluation(_StrictModel): + passed: bool + checks: dict[str, bool] + + +def evaluate_cabinet_trace(samples: list[CabinetTraceSample]) -> CabinetTraceEvaluation: + if not samples: + raise ValueError("cabinet evaluator requires at least one trace sample") + initial = samples[0] + final = samples[-1] + checks = { + "goal_false_initially": not ( + initial.door_fraction >= 0.8 + and initial.object_state == "target_surface" + and initial.door_fraction <= 0.1 + ), + "door_open_ever": any(item.door_fraction >= 0.8 for item in samples), + "object_on_target": final.object_state == "target_surface", + "object_released": final.released, + "object_stable": final.stable, + "door_closed_finally": final.door_fraction <= 0.1, + "robot_stable": all(item.robot_stable for item in samples), + "no_safety_event": not any(item.safety_event for item in samples), + } + return CabinetTraceEvaluation(passed=all(checks.values()), checks=checks) + + +def cabinet_negative_control_traces() -> dict[str, list[CabinetTraceSample]]: + closed = CabinetTraceSample( + step="initial", + door_fraction=0.0, + object_state="cabinet", + released=True, + stable=True, + robot_stable=True, + ) + return { + "no_op": [closed, closed.model_copy(update={"step": "final"})], + "random_policy": [ + closed, + closed.model_copy( + update={ + "step": "random", + "door_fraction": 0.37, + "object_state": "cabinet", + } + ), + ], + "skip_open": [ + closed, + closed.model_copy( + update={ + "step": "final", + "object_state": "target_surface", + } + ), + ], + "skip_close": [ + closed, + closed.model_copy(update={"step": "open", "door_fraction": 0.9}), + closed.model_copy( + update={ + "step": "final", + "door_fraction": 0.9, + "object_state": "target_surface", + } + ), + ], + } diff --git a/docs/reproduction/public_conversion_code/packages/runtime/isaac/injection.py b/docs/reproduction/public_conversion_code/packages/runtime/isaac/injection.py new file mode 100644 index 0000000000000000000000000000000000000000..21960dab6d1e9b3e7eb4ddde9f92da2ee6e59160 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/isaac/injection.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import uuid +from pathlib import Path + +from packages.core.contracts import SceneBundle, canonical_sha256 +from packages.core.files import atomic_write_text +from packages.robots.profiles import get_robot_profile +from packages.runtime.isaac.contracts import RobotInjectionSpec + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _usd_identifier(value: str) -> str: + sanitized = "".join( + character if character.isalnum() or character == "_" else "_" + for character in value + ) + if not sanitized: + raise ValueError("USD identifier cannot be empty") + return sanitized if not sanitized[0].isdigit() else f"_{sanitized}" + + +def _usd_path(path: str | Path) -> str: + return str(path).replace("\\", "/").replace("@", "%40") + + +def load_and_verify_bundle(bundle_root: Path) -> SceneBundle: + bundle_root = bundle_root.resolve() + manifest = bundle_root / "manifests" / "scene_bundle.json" + if not manifest.is_file(): + raise FileNotFoundError(f"SceneBundle manifest is missing: {manifest}") + bundle = SceneBundle.model_validate_json(manifest.read_text(encoding="utf-8")) + hashes = bundle.provenance.get("artifact_sha256") + if not isinstance(hashes, dict) or not hashes: + raise ValueError("SceneBundle provenance has no artifact SHA-256 ledger") + for relative, expected in hashes.items(): + if not isinstance(relative, str) or not isinstance(expected, str): + raise ValueError("SceneBundle artifact ledger must map paths to hashes") + path = (bundle_root / relative).resolve() + if not path.is_relative_to(bundle_root): + raise ValueError(f"SceneBundle artifact path escapes bundle root: {relative}") + if not path.is_file(): + raise FileNotFoundError(f"SceneBundle artifact is missing: {relative}") + actual = _sha256(path) + if actual != expected: + raise ValueError( + f"SceneBundle artifact hash differs for {relative}: {actual} != {expected}" + ) + root = (bundle_root / bundle.layer_uris["root"]).resolve() + if not root.is_relative_to(bundle_root) or not root.is_file(): + raise ValueError("SceneBundle root layer is missing or escapes bundle root") + return bundle + + +def _robot_layer( + *, + robot_id: str, + robot_reference: str, + translation_m: tuple[float, float, float], + yaw_deg: float, +) -> str: + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n\n' + 'over Xform "World" {\n' + f' def Xform "Robot" (\n prepend references = @{_usd_path(robot_reference)}@\n' + " ) {\n" + f' custom string robothousegen_robot_id = "{robot_id}"\n' + f" double3 xformOp:translate = ({translation_m[0]:.9g}, " + f"{translation_m[1]:.9g}, {translation_m[2]:.9g})\n" + f" float xformOp:rotateZ = {yaw_deg:.9g}\n" + ' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]\n' + " }\n}\n" + ) + + +def _composed_root(robot_layer: str, base_root: str) -> str: + return ( + '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' + f" subLayers = [\n @{_usd_path(robot_layer)}@,\n" + f" @{_usd_path(base_root)}@\n ]\n" + ' upAxis = "Z"\n)\n\nover Xform "World" {}\n' + ) + + +class IsaacRobotInjector: + version = "1.0" + + def inject( + self, + *, + bundle_root: Path, + output_dir: Path, + robot_id: str, + robot_asset: Path, + robot_asset_sha256: str, + stage_robot_asset: bool = True, + ) -> RobotInjectionSpec: + bundle_root = bundle_root.resolve() + output_dir = output_dir.resolve() + robot_asset = robot_asset.resolve() + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite Isaac injection output: {output_dir}") + bundle = load_and_verify_bundle(bundle_root) + profile = get_robot_profile(robot_id) + missing_capabilities = ( + bundle.scene_requirements.required_robot_capabilities - profile.capabilities + ) + if missing_capabilities: + raise ValueError( + f"robot {robot_id} lacks required capabilities: {sorted(missing_capabilities)}" + ) + if not robot_asset.is_file(): + raise FileNotFoundError(f"robot asset is missing: {robot_asset}") + actual_robot_hash = _sha256(robot_asset) + if actual_robot_hash != robot_asset_sha256: + raise ValueError( + f"robot asset hash differs: {actual_robot_hash} != {robot_asset_sha256}" + ) + declared_hash = profile.metadata.get("scene_asset_sha256") + if isinstance(declared_hash, str) and declared_hash != robot_asset_sha256: + raise ValueError( + f"robot profile hash differs for {robot_id}: {declared_hash} != " + f"{robot_asset_sha256}" + ) + + output_dir.parent.mkdir(parents=True, exist_ok=True) + staging = output_dir.parent / f".{output_dir.name}.tmp-{uuid.uuid4().hex[:12]}" + layers = staging / "layers" + manifests = staging / "manifests" + layers.mkdir(parents=True) + manifests.mkdir() + if stage_robot_asset: + asset_root = staging / "assets" / "robots" / _usd_identifier(robot_id) + shutil.copytree(robot_asset.parent, asset_root) + packaged_robot = asset_root / robot_asset.name + if _sha256(packaged_robot) != robot_asset_sha256: + raise ValueError("packaged robot asset hash differs after staging") + robot_reference = os.path.relpath(packaged_robot, start=layers).replace("\\", "/") + else: + packaged_robot = robot_asset + robot_reference = robot_asset.as_posix() + injection_layer = layers / "robot.usda" + atomic_write_text( + injection_layer, + _robot_layer( + robot_id=robot_id, + robot_reference=robot_reference, + translation_m=bundle.robot_start.translation_m, + yaw_deg=bundle.robot_start.yaw_deg, + ), + ) + base_root = (bundle_root / bundle.layer_uris["root"]).resolve() + relative_base = os.path.relpath(base_root, start=staging).replace("\\", "/") + atomic_write_text(staging / "root.usda", _composed_root("layers/robot.usda", relative_base)) + spec = RobotInjectionSpec.for_bundle( + bundle, + robot_id=robot_id, + robot_asset_uri=str(packaged_robot), + robot_asset_sha256=robot_asset_sha256, + robot_profile_version=profile.model_version, + injection_layer_uri="layers/robot.usda", + ) + atomic_write_text( + manifests / "robot_injection.json", + spec.model_dump_json(indent=2) + "\n", + ) + atomic_write_text( + manifests / "injection_provenance.json", + json.dumps( + { + "schema_version": "1.0", + "injector": f"IsaacRobotInjector/{self.version}", + "scene_bundle_manifest": str( + bundle_root / "manifests" / "scene_bundle.json" + ), + "scene_bundle_sha256": bundle.content_hash, + "robot_injection_sha256": canonical_sha256(spec), + "robot_asset_source": str(robot_asset), + "robot_asset_staged": stage_robot_asset, + "base_bundle_modified": False, + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + if output_dir.exists(): + raise FileExistsError( + f"Isaac injection destination appeared during build: {output_dir}" + ) + os.replace(staging, output_dir) + return spec diff --git a/docs/reproduction/public_conversion_code/packages/runtime/paths.py b/docs/reproduction/public_conversion_code/packages/runtime/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..0f3229bea32b6a5c9402309c7525766eea4d931a --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/paths.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import os +from pathlib import Path + +PROJECT_ROOT = Path(__file__).resolve().parents[2] + + +def data_root() -> Path: + """Return the external artifact root; never default inside the code checkout.""" + + configured = os.environ.get("RHG_DATA_ROOT") + root = Path(configured).expanduser() if configured else PROJECT_ROOT.parent / "RoboHouseGenData" + return root.resolve() + + +def runs_root() -> Path: + configured = os.environ.get("RHG_RUNS_ROOT") + root = Path(configured).expanduser() if configured else data_root() / "runs" + return root.resolve() + + +def api_runs_root() -> Path: + configured = os.environ.get("RHG_RUN_ROOT") + root = Path(configured).expanduser() if configured else runs_root() / "api" + return root.resolve() + + +def media_root() -> Path: + configured = os.environ.get("RHG_MEDIA_ROOT") + root = Path(configured).expanduser() if configured else data_root() / "media" + return root.resolve() + + +def resolve_run_path(path: Path) -> Path: + """Map conventional ``runs/...`` paths to the external runs root.""" + + if path.is_absolute() or not path.parts or path.parts[0] != "runs": + return path + return runs_root().joinpath(*path.parts[1:]) diff --git a/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_parallel.py b/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..bb3a7f367fba459d91f65eac397a50b136f66ea6 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_parallel.py @@ -0,0 +1,1970 @@ +from __future__ import annotations + +import asyncio +import json +import multiprocessing +import os +import re +import signal +import threading +import time +import traceback +import types +import xml.etree.ElementTree as ET +from concurrent.futures import ThreadPoolExecutor, as_completed +from copy import deepcopy +from dataclasses import asdict, is_dataclass +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] + +from packages.runtime.gpu_scheduler import DynamicGpuPool +from packages.runtime.scenesmith_skill_policy import ( + ManipulandSkillPolicy, + load_scenesmith_skill_policy, +) +from packages.scene_generation.dependency_graph import manipulation_assignments + +_PROCESS_START_LOCK = threading.Lock() + +_COLLISION_LINE = re.compile( + r"^- (?P.+?) collides with (?P.+?) " + r"\((?P[^)]*)\)$" +) + + +def task_support_ids( + context: dict[str, Any], dependency_graph: dict[str, Any] | None = None +) -> set[str]: + if dependency_graph: + planned = manipulation_assignments(dependency_graph) + if planned: + return set(planned) + task = context.get("task", {}) + return { + str(predicate["object"]) + for predicate in task.get("initial_predicates", []) + if predicate.get("name") in {"on", "supported_by", "inside"} + and predicate.get("object") + } + + +def serialize_selection(selection: Any) -> dict[str, Any]: + if is_dataclass(selection): + return asdict(selection) + if hasattr(selection, "model_dump"): + return selection.model_dump(mode="json") + if hasattr(selection, "__dict__"): + return deepcopy(vars(selection)) + return {"furniture_id": str(selection.furniture_id)} + + +def maximum_interval_concurrency(timings: list[dict[str, Any]]) -> int: + """Return measured overlap; queued work without a lease is deliberately excluded.""" + + events: list[tuple[float, int]] = [] + for timing in timings: + started = timing.get("lease_acquired_unix", timing.get("started_unix")) + completed = timing.get("completed_unix") + if not isinstance(started, (int, float)) or not isinstance(completed, (int, float)): + continue + if completed < started: + continue + events.extend(((float(started), 1), (float(completed), -1))) + active = 0 + maximum = 0 + # End events sort before starts at the same timestamp so touching intervals + # are not reported as concurrent. + for _, delta in sorted(events, key=lambda item: (item[0], item[1])): + active += delta + maximum = max(maximum, active) + return maximum + + +def evaluate_branch_completion( + additions: dict[str, list[str]], expected_by_furniture: dict[str, list[str]] +) -> tuple[dict[str, dict[str, Any]], list[str]]: + """Require critical shards to materialize every stable planned entity ID.""" + + completion = {} + for furniture_id, expected in sorted(expected_by_furniture.items()): + added = additions.get(furniture_id, []) + missing = [ + entity_id + for entity_id in expected + if not any( + object_id == entity_id or object_id.startswith(f"{entity_id}_") + for object_id in added + ) + ] + completion[furniture_id] = { + "expected_entity_ids": expected, + "added_object_ids": added, + "missing_entity_ids": missing, + "passed": not missing, + } + failed = sorted( + furniture_id for furniture_id, report in completion.items() if not report["passed"] + ) + return completion, failed + + +def project_declared_support_chain( + scene: Any, + dependency_graph: dict[str, Any], + *, + contact_gap_m: float = 0.001, +) -> list[dict[str, Any]]: + """Seat generated children on generated parents before local critique. + + SceneSmith extracts support surfaces once when a shard starts, so a deeper + child cannot otherwise see an intermediate parent generated in that shard. + This deterministic pass realizes those DAG edges while preserving x/y/yaw. + """ + + if contact_gap_m < 0.0: + raise ValueError("contact_gap_m must be non-negative") + objects = getattr(scene, "objects", {}) + if not isinstance(objects, dict): + return [] + + def matching_object(entity_id: str) -> Any | None: + exact = [ + value + for object_id, value in objects.items() + if str(object_id) == entity_id or str(object_id).startswith(f"{entity_id}_") + ] + if len(exact) == 1: + return exact[0] + described = [ + value + for value in objects.values() + if entity_id.casefold() + in " ".join( + str(getattr(value, field, "")) + for field in ("object_id", "name", "description") + ).casefold() + ] + return described[0] if len(described) == 1 else None + + edges: list[tuple[str, str]] = [] + for node in dependency_graph.get("nodes", []): + if not isinstance(node, dict) or node.get("stage") != "manipulation": + continue + entity_id = str(node.get("entity_id") or node.get("node_id") or "") + attributes = (node.get("metadata") or {}).get("attributes") or {} + parent_id = str(attributes.get("supported_by") or "") + if entity_id and parent_id: + edges.append((entity_id, parent_id)) + + changes: list[dict[str, Any]] = [] + # A bounded fixed point handles serialized node orders that are not topological. + for _ in range(max(1, len(edges))): + changed = False + for child_id, parent_id in edges: + child = matching_object(child_id) + parent = matching_object(parent_id) + if child is None or parent is None: + continue + if any( + getattr(item, "bbox_min", None) is None + or getattr(item, "bbox_max", None) is None + for item in (child, parent) + ): + continue + child_translation = child.transform.translation().copy() + parent_translation = parent.transform.translation() + # RoomScene serializes bbox coordinates after uniform asset scaling. + # Applying scale_factor again would double-scale HSSD/Objaverse assets. + parent_top = float(parent_translation[2] + float(parent.bbox_max[2])) + child_bottom_offset = float(child.bbox_min[2]) + target_z = parent_top + contact_gap_m - child_bottom_offset + previous_z = float(child_translation[2]) + if abs(previous_z - target_z) <= 1.0e-6: + continue + child_translation[2] = target_z + child.transform.set_translation(child_translation) + changes.append( + { + "entity_id": child_id, + "parent_entity_id": parent_id, + "object_id": str(getattr(child, "object_id", child_id)), + "previous_z_m": previous_z, + "corrected_z_m": target_z, + "contact_gap_m": contact_gap_m, + } + ) + changed = True + if not changed: + break + return changes + + +def _world_aabb(scene_object: Any) -> tuple[list[float], list[float]] | None: + """Return an object's conservative world AABB from its local bbox and pose.""" + + bbox_min = getattr(scene_object, "bbox_min", None) + bbox_max = getattr(scene_object, "bbox_max", None) + transform = getattr(scene_object, "transform", None) + if bbox_min is None or bbox_max is None or transform is None: + return None + try: + rotation = transform.rotation().matrix() + translation = transform.translation() + corners = [] + for x in (float(bbox_min[0]), float(bbox_max[0])): + for y in (float(bbox_min[1]), float(bbox_max[1])): + for z in (float(bbox_min[2]), float(bbox_max[2])): + local = (x, y, z) + corners.append( + [ + float(translation[axis]) + + sum( + float(rotation[axis][component]) * local[component] + for component in range(3) + ) + for axis in range(3) + ] + ) + except (IndexError, TypeError, ValueError, AttributeError): + return None + return ( + [min(corner[axis] for corner in corners) for axis in range(3)], + [max(corner[axis] for corner in corners) for axis in range(3)], + ) + + +def filter_disjoint_collision_report( + report: str, + scene: Any, + *, + tolerance_m: float = 0.003, +) -> tuple[str, list[dict[str, Any]]]: + """Remove narrow-phase collisions contradicted by world-space broad phase.""" + + if tolerance_m < 0.0: + raise ValueError("tolerance_m must be non-negative") + objects = getattr(scene, "objects", {}) + if not isinstance(objects, dict) or "Collisions (" not in report: + return report, [] + + removed: list[dict[str, Any]] = [] + kept_lines: list[str] = [] + collision_header_index: int | None = None + kept_collision_count = 0 + in_collision_section = False + for line in report.splitlines(): + if line.startswith("Collisions ("): + collision_header_index = len(kept_lines) + kept_lines.append(line) + in_collision_section = True + continue + if in_collision_section and line and not line.startswith("- "): + in_collision_section = False + match = _COLLISION_LINE.match(line) if in_collision_section else None + if match is None: + kept_lines.append(line) + continue + first_id = match.group("first") + second_id = match.group("second") + first_bounds = _world_aabb(objects.get(first_id)) + second_bounds = _world_aabb(objects.get(second_id)) + if first_bounds is None or second_bounds is None: + kept_collision_count += 1 + kept_lines.append(line) + continue + separated_axes = [ + axis + for axis in range(3) + if first_bounds[1][axis] < second_bounds[0][axis] - tolerance_m + or second_bounds[1][axis] < first_bounds[0][axis] - tolerance_m + ] + if not separated_axes: + kept_collision_count += 1 + kept_lines.append(line) + continue + removed.append( + { + "first_object_id": first_id, + "second_object_id": second_id, + "reported_detail": match.group("detail"), + "first_world_aabb": first_bounds, + "second_world_aabb": second_bounds, + "separated_axes": separated_axes, + } + ) + + if not removed: + return report, [] + if collision_header_index is not None: + if kept_collision_count: + kept_lines[collision_header_index] = f"Collisions ({kept_collision_count}):" + else: + del kept_lines[collision_header_index] + remaining_violations = sum(1 for line in kept_lines if line.startswith("- ")) + if remaining_violations == 0: + return "No physics violations detected. All objects are properly placed.", removed + for index, line in enumerate(kept_lines): + if line.startswith("Physics violations detected ("): + kept_lines[index] = ( + f"Physics violations detected ({remaining_violations} issue(s)):" + ) + break + return "\n".join(kept_lines), removed + + +def protected_manipulation_entities( + dependency_graph: dict[str, Any], + baseline: dict[str, Any], + furniture_id: str, +) -> set[str]: + """Return stable manipulation IDs owned by one furniture support branch.""" + + record = (baseline.get("objects") or {}).get(furniture_id, {}) + support_candidates = { + furniture_id, + str(record.get("object_id") or ""), + str(record.get("name") or ""), + } + support_candidates.discard("") + branch_nodes: set[str] = set() + for branch in dependency_graph.get("branches", []): + if not isinstance(branch, dict): + continue + root = str(branch.get("root_node_id") or "") + if any( + candidate == root or candidate.startswith(f"{root}_") + for candidate in support_candidates + ): + branch_nodes.update(str(item) for item in branch.get("node_ids", [])) + return { + str(node.get("entity_id") or node.get("node_id")) + for node in dependency_graph.get("nodes", []) + if isinstance(node, dict) + and node.get("stage") == "manipulation" + and str(node.get("node_id")) in branch_nodes + } + + +def prioritize_manipuland_selections( + selections: list[Any], + object_descriptions: dict[str, str], + critical_support_ids: set[str], + *, + max_contextual_supports: int, + max_items_per_critical_support: int, + max_items_per_contextual_support: int, +) -> tuple[list[Any], dict[str, Any]]: + """Keep task supports plus a bounded amount of contextual clutter.""" + + matched_supports: dict[str, str] = {} + critical = [] + contextual = [] + for selection in selections: + furniture_id = str(selection.furniture_id) + description = object_descriptions.get(furniture_id, "").casefold() + matched = next( + ( + support_id + for support_id in sorted(critical_support_ids) + if support_id.casefold() in description + or support_id.casefold().replace("_", " ") in description + ), + None, + ) + if matched is None: + contextual.append(selection) + else: + matched_supports[matched] = furniture_id + critical.append(selection) + + unresolved = sorted(critical_support_ids - set(matched_supports)) + fallback = bool(critical_support_ids and unresolved) + chosen = list(selections) if fallback else [*critical, *contextual[:max_contextual_supports]] + critical_furniture = set(matched_supports.values()) + capped = [] + for selection in chosen: + copied = deepcopy(selection) + limit = ( + max_items_per_critical_support + if str(copied.furniture_id) in critical_furniture + else max_items_per_contextual_support + ) + suggested = getattr(copied, "suggested_items", []) + if isinstance(suggested, list): + copied.suggested_items = suggested[:limit] + capped.append(copied) + return capped, { + "input_support_count": len(selections), + "selected_support_count": len(capped), + "critical_support_bindings": matched_supports, + "unresolved_critical_supports": unresolved, + "filter_fallback": fallback, + } + + +def task_graph_manipuland_selections( + context: dict[str, Any], + object_descriptions: dict[str, str], + context_config: dict[str, Any], + selection_class: type, + dependency_graph: dict[str, Any] | None = None, +) -> list[Any] | None: + """Build exact task-support assignments when the task graph is complete.""" + + task = context.get("task", {}) + entities = { + str(entity.get("entity_id")): entity + for entity in task.get("entities", []) + if entity.get("entity_id") + } + assignments = manipulation_assignments(dependency_graph or {}) + if not assignments: + assignments = {} + for predicate in task.get("initial_predicates", []): + if predicate.get("name") not in {"on", "supported_by", "inside"}: + continue + subject = predicate.get("subject") + support = predicate.get("object") + if subject and support: + assignments.setdefault(str(support), []).append(str(subject)) + if not assignments: + return None + + support_bindings: dict[str, str] = {} + for support_id in assignments: + matches = [ + furniture_id + for furniture_id, description in object_descriptions.items() + if support_id.casefold() in description.casefold() + or support_id.casefold().replace("_", " ") in description.casefold() + ] + if len(matches) != 1: + return None + support_bindings[support_id] = matches[0] + + asset_overrides = context_config.get("task_asset_overrides", {}) + graph_nodes = { + str(node["node_id"]): node + for node in (dependency_graph or {}).get("nodes", []) + if isinstance(node, dict) and node.get("node_id") + } + selections = [] + for support_id, subjects in assignments.items(): + item_lines = [] + for subject_id in subjects: + entity = entities.get(subject_id) + if entity is None: + return None + attributes = entity.get("attributes", {}) + marker = ( + f" [RHG_ASSET_ID={asset_overrides[subject_id]}]" + if subject_id in asset_overrides + else "" + ) + item_lines.append( + "REQUIRED: exactly one " + f"{entity.get('category', subject_id)} named {subject_id}; " + f"attributes={json.dumps(attributes, sort_keys=True)}; " + f"depends_on={graph_nodes.get(subject_id, {}).get('depends_on', [support_id])}." + f"{marker} " + "Generate this exact asset once; do not create piles, stacks, " + "duplicates, optional variants, or substitute objects." + ) + selections.append( + selection_class( + furniture_id=support_bindings[support_id], + suggested_items="\n".join(item_lines), + prompt_constraints=( + f"Build the declared manipulation subtree rooted at {support_id} in " + "parent-before-child order. Place only the required task objects; " + "preserve grasp access and the humanoid approach corridor. " + "For a single required object, call one-asset generation and one-object " + "placement tools only; never call pile or stack tools. After canonical " + "generation succeeds, its identity and dimensions are frozen: only move " + "the existing object, and never regenerate, rescale, or delete it." + ), + style_notes="Sparse task-critical placement; no optional clutter.", + context_furniture_ids=[], + ) + ) + return selections + + +def should_try_task_graph(policy: ManipulandSkillPolicy, context: dict[str, Any]) -> bool: + """Use a complete task graph before optional contextual surface analysis.""" + + return policy.support_selection_mode == "task_graph_first" and bool(context) + + +def prepare_native_gltf_supports( + baseline: dict[str, Any], scene_dir: Path, blender_server: Any +) -> dict[str, Any]: + """Make pre-existing native GLB furniture visible to Drake shard renders.""" + + converted = [] + reused = [] + for object_id, record in sorted(baseline.get("objects", {}).items()): + if not isinstance(record, dict): + continue + metadata = record.get("metadata") or {} + geometry_value = record.get("geometry_path") + if metadata.get("asset_source") != "robothousegen" or not geometry_value: + continue + geometry_path = Path(str(geometry_value)) + if geometry_path.suffix.lower() != ".glb": + continue + source = geometry_path if geometry_path.is_absolute() else scene_dir / geometry_path + output = source.with_suffix(".gltf") + if output.is_file(): + reused.append(str(object_id)) + else: + blender_server.convert_glb_to_gltf( + input_path=source, + output_path=output, + export_yup=True, + ) + converted.append(str(object_id)) + + sdf_value = record.get("sdf_path") + if not sdf_value: + raise ValueError(f"native support {object_id} has no SDF path") + sdf_path = Path(str(sdf_value)) + if not sdf_path.is_absolute(): + sdf_path = scene_dir / sdf_path + tree = ET.parse(sdf_path) + rewritten = 0 + already_gltf = 0 + for uri in tree.findall(".//mesh/uri"): + if not uri.text: + continue + uri_name = Path(uri.text).name + if uri_name == source.name: + uri.text = output.name + rewritten += 1 + elif uri_name == output.name: + already_gltf += 1 + if rewritten == 0 and already_gltf == 0: + raise ValueError( + f"native support SDF for {object_id} does not reference {source.name}" + ) + if rewritten: + tree.write(sdf_path, encoding="utf-8", xml_declaration=True) + record["geometry_path"] = ( + str(output) + if geometry_path.is_absolute() + else str(output.relative_to(scene_dir)) + ) + return { + "converted_object_ids": converted, + "reused_object_ids": reused, + "prepared_count": len(converted) + len(reused), + } + + +def parse_gpu_ids(value: str | None) -> set[int] | None: + if value is None or not value.strip(): + return None + ids = {int(item.strip()) for item in value.split(",") if item.strip()} + if not ids: + raise ValueError("GPU ID list must contain at least one integer") + return ids + + +def service_connection_kwargs(coordinator: Any) -> dict[str, Any]: + """Resolve the service endpoints leased by the parent SceneSmith run.""" + + def endpoint(name: str, default_port: int) -> tuple[str, int]: + prefix = f"RHG_{name.upper()}_SERVER" + host = os.environ.get( + f"{prefix}_HOST", + str(getattr(coordinator, f"{name}_server_host", "127.0.0.1")), + ) + inherited_port = getattr(coordinator, f"{name}_server_port", default_port) + port = int(os.environ.get(f"{prefix}_PORT", str(inherited_port))) + return host, port + + geometry_host, geometry_port = endpoint("geometry", 7000) + hssd_host, hssd_port = endpoint("hssd", 7001) + articulated_host, articulated_port = endpoint("articulated", 7002) + materials_host, materials_port = endpoint("materials", 7008) + return { + "geometry_server_host": geometry_host, + "geometry_server_port": geometry_port, + "hssd_server_host": hssd_host, + "hssd_server_port": hssd_port, + "articulated_server_host": articulated_host, + "articulated_server_port": articulated_port, + "materials_server_host": materials_host, + "materials_server_port": materials_port, + } + + +def merge_scene_states( + baseline: dict[str, Any], + shards: list[tuple[str, dict[str, Any]]], + *, + reject_foreign_mutations: bool = True, + allow_unowned_shards: bool = False, +) -> tuple[dict[str, Any], dict[str, list[str]]]: + """Merge isolated furniture deltas and reject cross-shard mutation.""" + + merged = deepcopy(baseline) + base_objects = baseline["objects"] + merged_objects = merged["objects"] + structural_supports = _structural_support_ids(baseline) + additions: dict[str, list[str]] = {} + for furniture_id, state in sorted(shards, key=lambda item: item[0]): + objects = state["objects"] + owner_is_object = furniture_id in base_objects + if ( + not allow_unowned_shards + and not owner_is_object + and furniture_id not in structural_supports + ): + raise ValueError(f"shard owner is absent from baseline: {furniture_id}") + changed_foreign = [ + object_id + for object_id, base_value in base_objects.items() + if object_id != furniture_id + and object_id in objects + and objects[object_id] != base_value + ] + removed = sorted(set(base_objects) - set(objects)) + if (changed_foreign or removed) and reject_foreign_mutations: + raise ValueError( + f"shard {furniture_id} modified foreign objects: " + f"changed={sorted(changed_foreign)} removed={removed}" + ) + if owner_is_object: + if furniture_id not in objects: + raise ValueError(f"shard removed its owner object: {furniture_id}") + merged_objects[furniture_id] = deepcopy(objects[furniture_id]) + new_ids = sorted(set(objects) - set(base_objects)) + for object_id in new_ids: + merged_id = object_id + if merged_id in merged_objects: + merged_id = f"{furniture_id}__{object_id}" + suffix = 1 + while merged_id in merged_objects: + merged_id = f"{furniture_id}__{object_id}_{suffix}" + suffix += 1 + record = deepcopy(objects[object_id]) + if isinstance(record, dict) and record.get("object_id") == object_id: + record["object_id"] = merged_id + merged_objects[merged_id] = record + additions.setdefault(furniture_id, []).append(merged_id) + additions.setdefault(furniture_id, []) + return merged, additions + + +def consolidate_branch_assets(branch_dirs: list[Path], destination: Path) -> dict[str, int]: + """Hard-link isolated branch assets into the merged room-local asset tree.""" + + destination = destination.resolve() + destination.mkdir(parents=True, exist_ok=True) + linked = 0 + reused = 0 + merged_registry_entries = 0 + normalized_registry_entries = 0 + for branch_dir in sorted(path.resolve() for path in branch_dirs): + source_root = branch_dir / "generated_assets" + if not source_root.is_dir(): + continue + for source in sorted(source_root.rglob("*")): + if not source.is_file() or source.is_symlink(): + continue + relative = source.relative_to(source_root) + target = destination / relative + target.parent.mkdir(parents=True, exist_ok=True) + if source.name == "asset_registry.json": + existing = ( + json.loads(target.read_text(encoding="utf-8")) + if target.is_file() + else {} + ) + incoming = json.loads(source.read_text(encoding="utf-8")) + if not isinstance(existing, dict) or not isinstance(incoming, dict): + raise ValueError(f"asset registry must contain an object: {relative}") + + def rebase(value: Any, source_prefix: str = str(source_root)) -> Any: + if isinstance(value, str): + return value.replace(source_prefix, str(destination)) + if isinstance(value, list): + return [rebase(item) for item in value] + if isinstance(value, dict): + return {key: rebase(item) for key, item in value.items()} + return value + + rebased = rebase(incoming) + for asset_id, record in rebased.items(): + if asset_id in existing and existing[asset_id] != record: + old = existing[asset_id] + old_metadata = old.get("metadata", {}) if isinstance(old, dict) else {} + new_metadata = ( + record.get("metadata", {}) if isinstance(record, dict) else {} + ) + same_identity = ( + isinstance(old, dict) + and isinstance(record, dict) + and old.get("object_id") == record.get("object_id") + and old_metadata.get("robothousegen_asset_id") + == new_metadata.get("robothousegen_asset_id") + ) + if not same_identity: + raise ValueError( + f"asset registry collision differs: {relative}:{asset_id}" + ) + # Normalize an older projection whose absolute paths still + # point into the immutable isolated subtree. Asset identity + # and all underlying files remain unchanged. + existing[asset_id] = record + normalized_registry_entries += 1 + if asset_id not in existing: + existing[asset_id] = record + merged_registry_entries += 1 + target.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8") + continue + if target.exists(): + if target.stat().st_size != source.stat().st_size: + raise ValueError(f"branch asset collision differs: {relative}") + reused += 1 + continue + os.link(source, target) + linked += 1 + return { + "linked_files": linked, + "reused_files": reused, + "merged_registry_entries": merged_registry_entries, + "normalized_registry_entries": normalized_registry_entries, + } + + +def _structural_support_ids(state: dict[str, Any]) -> set[str]: + """Return room-geometry supports that intentionally live outside objects.""" + + room_geometry = state.get("room_geometry", {}) + if not isinstance(room_geometry, dict): + return set() + supports: set[str] = set() + floor = room_geometry.get("floor") + if isinstance(floor, dict) and floor.get("object_id"): + supports.add(str(floor["object_id"])) + ceiling = room_geometry.get("ceiling") + if isinstance(ceiling, dict) and ceiling.get("object_id"): + supports.add(str(ceiling["object_id"])) + return supports + + +def find_foreign_mutations( + baseline: dict[str, Any], shards: list[tuple[str, dict[str, Any]]] +) -> dict[str, dict[str, list[str]]]: + base_objects = baseline["objects"] + report = {} + for furniture_id, state in shards: + objects = state["objects"] + changed = sorted( + object_id + for object_id, base_value in base_objects.items() + if object_id != furniture_id + and object_id in objects + and objects[object_id] != base_value + ) + removed = sorted(set(base_objects) - set(objects)) + if changed or removed: + report[furniture_id] = {"changed": changed, "removed": removed} + return report + + +def _is_oom(error: BaseException) -> bool: + message = str(error).casefold() + return any( + marker in message + for marker in ( + "out of memory", + "cuda_error_out_of_memory", + "failed to allocate", + "gpu memory", + ) + ) + + +def _shard_process_main(result_path: Path, kwargs: dict[str, Any]) -> None: + """Execute one shard in its own process group and persist a bounded result.""" + + os.setsid() + envelope: dict[str, Any] + try: + furniture_id, state, timing = _run_one_shard(**kwargs) + envelope = { + "status": "complete", + "furniture_id": furniture_id, + "state": state, + "timing": timing, + } + except BaseException as error: + envelope = { + "status": "failed", + "error": repr(error), + "traceback": traceback.format_exc(), + } + temporary = result_path.with_suffix(".tmp") + temporary.write_text(json.dumps(envelope), encoding="utf-8") + temporary.replace(result_path) + + +def _terminate_process_group(process: multiprocessing.Process) -> None: + if process.pid is None or not process.is_alive(): + return + try: + if os.getpgid(process.pid) == process.pid: + os.killpg(process.pid, signal.SIGTERM) + else: + process.terminate() + except ProcessLookupError: + return + process.join(timeout=10) + if process.is_alive(): + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.join(timeout=10) + + +def _run_one_shard_isolated( + *, + baseline: dict[str, Any], + selection: Any, + output_root: Path, + shard_timeout_s: float, + fallback_on_timeout: bool, + _process_target: Any = _shard_process_main, + **kwargs: Any, +) -> tuple[str, dict[str, Any], dict[str, Any]]: + """Enforce a real wall-clock deadline around blocking model and render calls.""" + + furniture_id = str(selection.furniture_id) + shard_root = output_root / furniture_id + shard_root.mkdir(parents=True, exist_ok=True) + result_path = shard_root / "shard_process_result.json" + result_path.unlink(missing_ok=True) + process_kwargs = { + **kwargs, + "baseline": baseline, + "selection": selection, + "output_root": output_root, + "shard_timeout_s": shard_timeout_s, + "fallback_on_timeout": fallback_on_timeout, + } + # Never fork a process that has imported bpy. Blender starts native worker + # threads during import, and forking that state can leave the child blocked + # before the shard target is entered. ``spawn`` costs one clean import per + # shard, but is safe when coordinator threads launch workers. + context = multiprocessing.get_context("spawn") + process = context.Process( + target=_process_target, + args=(result_path, process_kwargs), + name=f"rhg-manipuland-{furniture_id}", + ) + started = time.time() + # SceneSmith is launched as a script whose main module imports Blender-only + # _bpy. multiprocessing otherwise re-runs that script in every child. Point + # the bootstrap at this side-effect-free module only while preparation data + # is captured, then immediately restore the real Hydra entry point. + import __main__ + + with _PROCESS_START_LOCK: + original_main_file = getattr(__main__, "__file__", None) + __main__.__file__ = str( + Path(__file__).with_name("scenesmith_process_bootstrap.py").resolve() + ) + try: + process.start() + finally: + if original_main_file is None: + delattr(__main__, "__file__") + else: + __main__.__file__ = original_main_file + process.join(timeout=shard_timeout_s) + if process.is_alive(): + _terminate_process_group(process) + timing = { + "furniture_id": furniture_id, + "status": "timeout_fallback" if fallback_on_timeout else "timeout", + "started_unix": started, + "duration_s": round(time.time() - started, 3), + "timeout_s": shard_timeout_s, + "selection": serialize_selection(selection), + "attempts": [], + } + if fallback_on_timeout: + (shard_root / "shard_scene_state.json").write_text( + json.dumps(baseline, indent=2), encoding="utf-8" + ) + return furniture_id, deepcopy(baseline), timing + raise TimeoutError( + f"task-critical Manipuland shard {furniture_id} exceeded {shard_timeout_s}s" + ) + if not result_path.is_file(): + raise RuntimeError( + f"Manipuland shard {furniture_id} exited with code {process.exitcode} " + "without a result" + ) + envelope = json.loads(result_path.read_text(encoding="utf-8")) + if envelope.get("status") != "complete": + raise RuntimeError( + f"Manipuland shard {furniture_id} failed: {envelope.get('error')}\n" + f"{envelope.get('traceback', '')}" + ) + return envelope["furniture_id"], envelope["state"], envelope["timing"] + + +def apply_request_manipuland_policy( + policy: ManipulandSkillPolicy, config: dict[str, Any] +) -> ManipulandSkillPolicy: + """Apply the small, validated per-benchmark budget surface.""" + + overrides = config.get("manipuland_policy", {}) + if not overrides: + return policy + allowed = { + "critical_shard_timeout_s", + "contextual_shard_timeout_s", + "max_contextual_supports", + "max_items_per_critical_support", + "max_items_per_contextual_support", + } + unknown = sorted(set(overrides) - allowed) + if unknown: + raise ValueError(f"unsupported manipuland_policy fields: {unknown}") + payload = policy.model_dump() + payload.update(overrides) + return ManipulandSkillPolicy.model_validate(payload) + + +def _furniture_subtree_specs() -> list[dict[str, Any]]: + graph_path = Path(os.environ.get("RHG_SCENE_DEPENDENCY_GRAPH_FILE", "")) + context_path = Path(os.environ.get("RHG_SCENE_CONTEXT_FILE", "")) + if not graph_path.is_file() or not context_path.is_file(): + return [] + graph = json.loads(graph_path.read_text(encoding="utf-8")) + context = json.loads(context_path.read_text(encoding="utf-8")) + nodes = {str(node["node_id"]): node for node in graph.get("nodes", [])} + entities = { + str(entity["entity_id"]): entity + for entity in (context.get("task") or {}).get("entities", []) + if entity.get("entity_id") + } + planning_path = Path(os.environ.get("RHG_PLANNING_AGENT_OUTPUT_FILE", "")) + if planning_path.is_file(): + planning = json.loads(planning_path.read_text(encoding="utf-8")) + partitions = [ + { + "branch_id": subtree["subtree_id"], + "root_node_id": subtree["root_node_id"], + "node_ids": subtree["node_ids"], + "critical": subtree.get("critical", True), + } + for subtree in planning.get("subtrees", []) + ] + else: + partitions = graph.get("branches", []) + specs = [] + for branch in partitions: + furniture_nodes = [ + nodes[node_id] + for node_id in branch.get("node_ids", []) + if node_id in nodes + and nodes[node_id].get("stage") == "furniture" + and nodes[node_id].get("entity_id") + ] + if not furniture_nodes: + continue + entity_ids = [str(node["entity_id"]) for node in furniture_nodes] + descriptions = [ + { + "entity_id": entity_id, + "category": entities.get(entity_id, {}).get("category"), + "attributes": entities.get(entity_id, {}).get("attributes", {}), + } + for entity_id in entity_ids + ] + specs.append( + { + "subtree_id": str(branch["branch_id"]), + "root_node_id": str(branch["root_node_id"]), + "entity_ids": entity_ids, + "entities": descriptions, + "critical": bool(branch.get("critical", True)), + } + ) + return specs + + +def _subtree_has_locked_furniture_pose(spec: dict[str, Any]) -> bool: + """Return true when every owned item has a complete benchmark-locked pose. + + SceneSmith's natural placement noise is useful for open-ended generation, but + it must not perturb an explicitly declared comparison layout. Besides making + exact and DAG profiles incomparable, the drift can reintroduce opening and + corridor violations after an Agent has already selected the intended pose. + """ + + entities = spec.get("entities") + if not isinstance(entities, list) or not entities: + return False + for entity in entities: + attributes = entity.get("attributes", {}) if isinstance(entity, dict) else {} + center = attributes.get("placement_center_m") + if ( + not attributes.get("asset_id") + or not isinstance(center, list) + or len(center) != 2 + or "yaw_deg" not in attributes + ): + return False + return True + + +def _force_locked_furniture_placement(worker: Any, perfect_mode: Any) -> None: + """Force the agent's lazily-created furniture tools to remain noise-free.""" + + original_create = worker._create_designer_tools + original_set = worker._set_placement_noise_profile + + def create_designer_tools(self: Any) -> list[Any]: + tools = original_create() + self.furniture_tools.set_noise_profile(perfect_mode) + return tools + + def set_placement_noise_profile(_self: Any, _requested_mode: Any) -> None: + # The planner may request ``natural`` after inspecting the prose. For a + # benchmark-locked pose this would violate the declared input contract. + original_set(perfect_mode) + + worker._create_designer_tools = types.MethodType(create_designer_tools, worker) + worker._set_placement_noise_profile = types.MethodType( + set_placement_noise_profile, worker + ) + + +def _repair_furniture_entity_ids() -> set[str] | None: + """Return the exact failed furniture entities requested by Supervisor.""" + + raw = os.environ.get("RHG_REPAIR_PLAN", "").strip() + if not raw: + return None + try: + plan = json.loads(raw) + except json.JSONDecodeError: + return None + entity_ids: set[str] = set() + scoped_step = False + for step in plan.get("steps", []): + if step.get("action") != "rerun_branch" or step.get("stage") != "furniture": + continue + scoped_step = True + entity_ids.update(str(item) for item in step.get("entity_ids", []) if item) + return entity_ids if scoped_step and entity_ids else None + + +def _score_floor(scores_path: Path) -> float | None: + try: + payload = yaml.safe_load(scores_path.read_text(encoding="utf-8")) or {} + except (OSError, yaml.YAMLError): + return None + grades = [ + float(value["grade"]) + for value in payload.values() + if isinstance(value, dict) and isinstance(value.get("grade"), (int, float)) + ] + return min(grades) if grades else None + + +def _cached_furniture_subtree( + resume_root: Path, + subtree_id: str, + *, + critic_min_score: float, +) -> tuple[dict[str, Any], Path, float] | None: + """Load an accepted immutable subtree result from the parent checkpoint.""" + + safe_id = subtree_id.replace(":", "__").replace("/", "_") + pattern = ( + "scene_*/room_*/parallel_base_branches/furniture/" + f"parallel_furniture_subtrees/{safe_id}" + ) + matches = sorted(resume_root.glob(pattern)) + if len(matches) != 1: + return None + branch_dir = matches[0] + snapshot = branch_dir / "subtree_result.json" + metadata = branch_dir / "subtree_result_meta.json" + if snapshot.is_file() and metadata.is_file(): + try: + state = json.loads(snapshot.read_text(encoding="utf-8")) + meta = json.loads(metadata.read_text(encoding="utf-8")) + score = float(meta["critic_min_score"]) + except (OSError, ValueError, KeyError, TypeError): + pass + else: + if score >= critic_min_score and isinstance(state.get("objects"), dict): + return state, branch_dir, score + render_roots = sorted( + branch_dir.glob("scene_renders/furniture/renders_*"), reverse=True + ) + for render_root in render_roots: + scores = render_root / "scores.yaml" + state_path = render_root / "scene_state.json" + score = _score_floor(scores) + if score is None or score < critic_min_score or not state_path.is_file(): + continue + try: + state = json.loads(state_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if isinstance(state.get("objects"), dict): + return state, branch_dir, score + return None + + +def run_parallel_furniture_subtrees(coordinator: Any, scene: Any) -> Any: + """Run one real Stateful Furniture Agent per independent support/motif subtree.""" + + specs = _furniture_subtree_specs() + enabled = os.environ.get("RHG_AGENT_ORCHESTRATION_MODE", "legacy") == "dag_agents" + if not enabled or len(specs) <= 1: + asyncio.run(coordinator.add_furniture(scene=scene)) + return scene + + baseline = scene.to_state_dict() + baseline_hash = scene.content_hash() + output_root = scene.scene_dir / "parallel_furniture_subtrees" + output_root.mkdir(parents=True, exist_ok=True) + worker_limit = int(os.environ.get("RHG_FURNITURE_SUBTREE_WORKERS", "8")) + repair_entity_ids = _repair_furniture_entity_ids() + active_specs = list(specs) + cached_results: list[tuple[str, dict[str, Any]]] = [] + cached_timings: list[dict[str, Any]] = [] + cached_asset_dirs: list[Path] = [] + if repair_entity_ids: + resume_value = os.environ.get("RHG_SCENESMITH_RESUME_FROM", "") + resume_root = Path(resume_value) if resume_value else None + if resume_root is not None and resume_root.is_dir(): + active_specs = [] + critic_min_score = load_scenesmith_skill_policy().furniture.early_finish_min_score + for spec in specs: + owned = {str(item) for item in spec["entity_ids"]} + if owned & repair_entity_ids: + active_specs.append(spec) + continue + cached = _cached_furniture_subtree( + resume_root, + str(spec["subtree_id"]), + critic_min_score=critic_min_score, + ) + if cached is None: + active_specs.append(spec) + continue + state, branch_dir, score = cached + cached_results.append((str(spec["subtree_id"]), state)) + cached_asset_dirs.append(branch_dir) + cached_timings.append( + { + "task_id": f"generation:{spec['subtree_id']}", + "role": "generation", + "status": "reused", + "subtree_id": str(spec["subtree_id"]), + "owned_entity_ids": spec["entity_ids"], + "critic_min_score": score, + "source_checkpoint": str(branch_dir), + "duration_s": 0.0, + } + ) + worker_count = max(1, min(worker_limit, len(active_specs) or 1)) + allowed = parse_gpu_ids( + os.environ.get("RHG_FURNITURE_GPU_IDS") + or os.environ.get("SCENESMITH_GPU_IDS") + or os.environ.get("CUDA_VISIBLE_DEVICES") + ) + gpu_pool = DynamicGpuPool( + Path(os.environ.get("RHG_GPU_LOCK_ROOT", str(output_root / "gpu_locks"))), + allowed_ids=allowed, + min_free_vram_mb=int(os.environ.get("RHG_FURNITURE_MIN_FREE_VRAM_MB", "8192")), + max_used_vram_mb=int(os.environ.get("RHG_FURNITURE_MAX_USED_VRAM_MB", str(1 << 30))), + max_utilization_percent=int( + os.environ.get("RHG_FURNITURE_MAX_GPU_UTILIZATION", "100") + ), + ) + connections = service_connection_kwargs(coordinator) + agent_class = type(coordinator) + cfg = coordinator.cfg + logger_class = type(coordinator.logger) + scene_class = type(scene) + coordinator.cleanup() + + def run_one(spec: dict[str, Any]) -> tuple[str, dict[str, Any], dict[str, Any]]: + scheduled = time.time() + lease = gpu_pool.acquire( + timeout_s=float(os.environ.get("RHG_GPU_WAIT_TIMEOUT_S", "2700")) + ) + started = time.time() + worker = None + subtree_id = str(spec["subtree_id"]) + safe_id = subtree_id.replace(":", "__").replace("/", "_") + try: + shard_root = output_root / safe_id + shard_root.mkdir(parents=True, exist_ok=True) + logger = logger_class(output_dir=shard_root) + shard_scene = scene_class(room_geometry=None, scene_dir=shard_root) + shard_scene.restore_from_state_dict(deepcopy(baseline)) + shard_scene.text_description = ( + f"{scene.text_description}\n\n" + "RoboHouseGen subtree ownership contract: generate and place exactly the " + f"following owned furniture entities and no other furniture: " + f"{json.dumps(spec['entities'], ensure_ascii=False, sort_keys=True)}. " + "Do not modify architecture or any foreign subtree. Preserve the stable entity " + "IDs in names, descriptions, and audit output. During this isolated subtree " + "critique, other furniture subtrees are intentionally absent. Do not reduce any " + "Realism, Functionality, Layout, Holistic Completeness, Prompt Following, or " + "Reachability grade because foreign furniture, the full room arrangement, or the " + "merged task scene is absent. Evaluate only the owned entities, their asset " + "quality, scale, floor contact, architecture clearance, and declared local " + "relations. Cross-subtree completeness is exclusively a Global Critic concern." + ) + worker = agent_class( + cfg=deepcopy(cfg), + logger=logger, + num_workers=worker_count, + render_gpu_id=lease.gpu.index, + **connections, + ) + if _subtree_has_locked_furniture_pose(spec): + # Import from the per-run SceneSmith overlay, never from or into + # the shared read-only checkout. + from scenesmith.agent_utils.placement_noise import PlacementNoiseMode + + _force_locked_furniture_placement(worker, PlacementNoiseMode.PERFECT) + asyncio.run(worker.add_furniture(scene=shard_scene)) + state = shard_scene.to_state_dict() + score_candidates = [ + score + for path in shard_root.glob("**/scores.yaml") + if (score := _score_floor(path)) is not None + ] + minimum_score = max(score_candidates) if score_candidates else 0.0 + (shard_root / "subtree_result.json").write_text( + json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8" + ) + (shard_root / "subtree_result_meta.json").write_text( + json.dumps( + { + "schema_version": "1.0", + "baseline_hash": baseline_hash, + "critic_min_score": minimum_score, + "owned_entity_ids": spec["entity_ids"], + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + additions = sorted(set(state.get("objects", {})) - set(baseline.get("objects", {}))) + if not additions: + raise RuntimeError(f"furniture subtree {subtree_id} generated no objects") + completed = time.time() + return subtree_id, state, { + "task_id": f"generation:{subtree_id}", + "role": "generation", + "status": "complete", + "subtree_id": subtree_id, + "owned_entity_ids": spec["entity_ids"], + "added_object_ids": additions, + "gpu_id": lease.gpu.index, + "model": str(getattr(cfg.openai, "model", "unknown")), + "reasoning_effort": "medium", + "scheduled_unix": scheduled, + "lease_acquired_unix": started, + "started_unix": started, + "completed_unix": completed, + "queue_duration_s": round(started - scheduled, 3), + "duration_s": round(completed - started, 3), + "total_duration_s": round(completed - scheduled, 3), + } + finally: + if worker is not None: + worker.cleanup() + lease.close() + + results: list[tuple[str, dict[str, Any]]] = list(cached_results) + timings: list[dict[str, Any]] = list(cached_timings) + parallel_started = time.time() + if active_specs: + with ThreadPoolExecutor( + max_workers=worker_count, thread_name_prefix="rhg-furniture-subtree" + ) as pool: + futures = [pool.submit(run_one, spec) for spec in active_specs] + for future in as_completed(futures): + subtree_id, state, timing = future.result() + results.append((subtree_id, state)) + timings.append(timing) + merged, additions = merge_scene_states( + baseline, + results, + reject_foreign_mutations=True, + allow_unowned_shards=True, + ) + # Subtree RoomScene records are restored into the parent room and therefore + # resolve generated asset paths relative to the parent ``scene_dir``. Keep + # the immutable subtree copies for audit, but materialize hard links in the + # canonical room-local asset tree before manipulation workers consume them. + subtree_dirs = [ + output_root + / str(spec["subtree_id"]).replace(":", "__").replace("/", "_") + for spec in active_specs + ] + cached_asset_dirs + asset_merge = consolidate_branch_assets( + subtree_dirs, + scene.scene_dir / "generated_assets", + ) + scene.restore_from_state_dict(merged) + timing = { + "schema_version": "1.0", + "mode": "parallel_agent_subtrees", + "baseline_hash": baseline_hash, + "worker_count": worker_count, + "max_observed_concurrency": maximum_interval_concurrency(timings), + "repair_entity_ids": sorted(repair_entity_ids or []), + "reused_subtrees": sorted(item[0] for item in cached_results), + "subtrees": sorted(timings, key=lambda item: item["subtree_id"]), + "additions": additions, + "asset_merge": asset_merge, + "parallel_stage_duration_s": round(time.time() - parallel_started, 3), + } + (output_root / "timing.json").write_text( + json.dumps(timing, indent=2), encoding="utf-8" + ) + return scene + + +def _run_one_shard( + *, + agent_class: type, + cfg: Any, + logger_class: type, + scene_class: type, + baseline: dict[str, Any], + scene_dir: Path, + selection: Any, + worker_count: int, + gpu_pool: DynamicGpuPool, + output_root: Path, + oom_retries: int, + service_connections: dict[str, Any], + item_limit: int, + shard_timeout_s: float, + fallback_on_timeout: bool, +) -> tuple[str, dict[str, Any], dict[str, Any]]: + furniture_id = str(selection.furniture_id) + attempted_gpus: set[int] = set() + started = time.time() + attempts: list[dict[str, Any]] = [] + for attempt in range(oom_retries + 1): + lease = gpu_pool.acquire( + timeout_s=float(os.environ.get("RHG_GPU_WAIT_TIMEOUT_S", "2700")), + excluded_ids=attempted_gpus, + ) + gpu_id = lease.gpu.index + attempted_gpus.add(gpu_id) + attempt_started = time.time() + worker = None + stateful_module = None + original_surface_extractor = None + try: + shard_root = output_root / furniture_id + shard_root.mkdir(parents=True, exist_ok=True) + logger = logger_class(output_dir=shard_root) + shard_scene = scene_class(room_geometry=None, scene_dir=scene_dir) + shard_scene.restore_from_state_dict(deepcopy(baseline)) + shard_cfg = deepcopy(cfg) + from omegaconf import OmegaConf + + OmegaConf.update( + shard_cfg, "rhg_item_limit", item_limit, force_add=True + ) + worker = agent_class( + cfg=shard_cfg, + logger=logger, + num_workers=worker_count, + render_gpu_id=gpu_id, + **service_connections, + ) + + async def fixed_analysis(_self: Any, _scene: Any) -> list[Any]: + return [deepcopy(selection)] + + worker._analyze_furniture_for_placement = types.MethodType( # noqa: SLF001 + fixed_analysis, worker + ) + graph_path = Path(os.environ.get("RHG_SCENE_DEPENDENCY_GRAPH_FILE", "")) + runtime_dependency_graph = ( + json.loads(graph_path.read_text(encoding="utf-8")) + if graph_path.is_file() + else {} + ) + protected_ids = protected_manipulation_entities( + runtime_dependency_graph, baseline, furniture_id + ) + tool_guard_events: list[dict[str, Any]] = [] + generated_once: set[str] = set() + tool_guard_path = shard_root / "critical_entity_tool_guard.json" + + def protected_id( + object_id: str, _protected_ids: set[str] = protected_ids + ) -> str | None: + return next( + ( + entity_id + for entity_id in sorted(_protected_ids) + if object_id == entity_id + or object_id.startswith(f"{entity_id}_") + ), + None, + ) + + def record_guard( + action: str, + entity_ids: list[str], + reason: str, + _events: list[dict[str, Any]] = tool_guard_events, + _path: Path = tool_guard_path, + _protected_ids: set[str] = protected_ids, + ) -> str: + event = { + "timestamp_unix": time.time(), + "action": action, + "entity_ids": entity_ids, + "status": "rejected", + "reason": reason, + } + _events.append(event) + _path.write_text( + json.dumps( + { + "schema_version": "1.0", + "protected_entity_ids": sorted(_protected_ids), + "events": _events, + }, + indent=2, + ), + encoding="utf-8", + ) + return json.dumps( + { + "success": False, + "error_type": "critical_entity_frozen", + "message": reason, + "entity_ids": entity_ids, + } + ) + + original_remove = worker._remove_manipuland_impl # noqa: SLF001 + original_rescale = worker._rescale_manipuland_impl # noqa: SLF001 + original_generate = worker._generate_assets_impl # noqa: SLF001 + + def guarded_remove( + _self: Any, + object_id: str, + _protected_id: Any = protected_id, + _record_guard: Any = record_guard, + _original_remove: Any = original_remove, + **kwargs: Any, + ) -> str: + entity_id = _protected_id(str(object_id)) + if entity_id is not None: + return _record_guard( + "remove_manipuland", + [entity_id], + f"Critical entity {entity_id} is frozen; move it instead of " + "deleting or replacing it inside the local Agent.", + ) + return _original_remove(object_id=object_id, **kwargs) + + def guarded_rescale( + _self: Any, + object_id: str, + scale_factor: float, + _protected_id: Any = protected_id, + _record_guard: Any = record_guard, + _original_rescale: Any = original_rescale, + **kwargs: Any, + ) -> str: + entity_id = _protected_id(str(object_id)) + if entity_id is not None: + return _record_guard( + "rescale_manipuland", + [entity_id], + f"Critical entity {entity_id} has canonical dimensions and " + "cannot be scaled; correct its transform or report infeasible.", + ) + return _original_rescale( + object_id=object_id, scale_factor=scale_factor, **kwargs + ) + + def guarded_generate( + _self: Any, + request: Any, + _protected_id: Any = protected_id, + _generated_once: set[str] = generated_once, + _record_guard: Any = record_guard, + _original_generate: Any = original_generate, + ) -> str: + requested = [ + str(item) + for item in (getattr(request, "short_names", None) or []) + ] + repeated = sorted( + entity_id + for name in requested + if (entity_id := _protected_id(name)) in _generated_once + ) + if repeated: + return _record_guard( + "generate_manipuland_assets", + repeated, + "Canonical generation already succeeded for " + f"{', '.join(repeated)}; reuse the listed asset and only " + "adjust its transform.", + ) + result = _original_generate(request) + try: + payload = json.loads(result) + except (TypeError, json.JSONDecodeError): + payload = {} + if payload.get("success"): + _generated_once.update( + entity_id + for name in requested + if (entity_id := _protected_id(name)) is not None + ) + return result + + worker._remove_manipuland_impl = types.MethodType( # noqa: SLF001 + guarded_remove, worker + ) + worker._rescale_manipuland_impl = types.MethodType( # noqa: SLF001 + guarded_rescale, worker + ) + worker._generate_assets_impl = types.MethodType( # noqa: SLF001 + guarded_generate, worker + ) + original_request_critique = worker._request_critique_impl # noqa: SLF001 + support_projection_ledger: list[dict[str, Any]] = [] + + async def critique_with_declared_support_projection( + _self: Any, + *args: Any, + _graph: dict[str, Any] = runtime_dependency_graph, + _ledger: list[dict[str, Any]] = support_projection_ledger, + _shard_root: Path = shard_root, + _request_critique: Any = original_request_critique, + **kwargs: Any, + ) -> Any: + corrections = project_declared_support_chain( + _self.scene, _graph + ) + if corrections: + _ledger.extend(corrections) + _self.rendering_manager.clear_cache() + (_shard_root / "support_projection_ledger.json").write_text( + json.dumps( + { + "schema_version": "1.0", + "status": "applied", + "corrections": _ledger, + }, + indent=2, + ), + encoding="utf-8", + ) + return await _request_critique(*args, **kwargs) + + worker._request_critique_impl = types.MethodType( # noqa: SLF001 + critique_with_declared_support_projection, worker + ) + support_kind = furniture_id.casefold() + if any( + token in support_kind + for token in ("counter", "table", "desk", "workbench", "stove") + ): + import scenesmith.manipuland_agents.stateful_manipuland_agent as stateful_module + + original_surface_extractor = ( + stateful_module.extract_and_propagate_support_surfaces + ) + surface_limit = max( + 1, int(os.environ.get("RHG_TASK_SUPPORT_SURFACE_LIMIT", "6")) + ) + + def bounded_surface_extractor( + *args: Any, + _extractor: Any = original_surface_extractor, + _limit: int = surface_limit, + **kwargs: Any, + ) -> list[Any]: + surfaces = list(_extractor(*args, **kwargs)) + if len(surfaces) <= _limit: + return surfaces + + def rank(surface: Any) -> tuple[float, float]: + translation = surface.transform.translation() + world_top = float(translation[2] + surface.bounding_box_max[2]) + return world_top, float(surface.area) + + highest = max(rank(surface)[0] for surface in surfaces) + top_band = [ + surface + for surface in surfaces + if rank(surface)[0] >= highest - 0.05 + ] + selected = sorted(top_band, key=rank, reverse=True)[:_limit] + furniture = kwargs.get("furniture_object") + if furniture is not None: + furniture.support_surfaces = selected + return selected + + stateful_module.extract_and_propagate_support_surfaces = ( + bounded_surface_extractor + ) + try: + asyncio.run( + asyncio.wait_for( + worker.add_manipulands(scene=shard_scene), + timeout=shard_timeout_s, + ) + ) + except TimeoutError: + if not fallback_on_timeout: + raise + state = deepcopy(baseline) + state_path = shard_root / "shard_scene_state.json" + state_path.write_text(json.dumps(state, indent=2), encoding="utf-8") + attempts.append( + { + "attempt": attempt + 1, + "gpu_id": gpu_id, + "status": "timeout_fallback", + "duration_s": round(time.time() - attempt_started, 3), + "timeout_s": shard_timeout_s, + } + ) + return furniture_id, state, { + "furniture_id": furniture_id, + "status": "timeout_fallback", + "started_unix": started, + "duration_s": round(time.time() - started, 3), + "selection": serialize_selection(selection), + "attempts": attempts, + } + state = shard_scene.to_state_dict() + state_path = shard_root / "shard_scene_state.json" + state_path.write_text(json.dumps(state, indent=2), encoding="utf-8") + attempts.append( + { + "attempt": attempt + 1, + "gpu_id": gpu_id, + "status": "complete", + "duration_s": round(time.time() - attempt_started, 3), + } + ) + return furniture_id, state, { + "furniture_id": furniture_id, + "status": "complete", + "started_unix": started, + "duration_s": round(time.time() - started, 3), + "selection": serialize_selection(selection), + "attempts": attempts, + } + except BaseException as error: + attempts.append( + { + "attempt": attempt + 1, + "gpu_id": gpu_id, + "status": "oom" if _is_oom(error) else "failed", + "duration_s": round(time.time() - attempt_started, 3), + "error": repr(error), + } + ) + if not _is_oom(error) or attempt >= oom_retries: + raise + finally: + if stateful_module is not None and original_surface_extractor is not None: + stateful_module.extract_and_propagate_support_surfaces = ( + original_surface_extractor + ) + if worker is not None: + worker.cleanup() + lease.close() + raise AssertionError("unreachable shard retry state") + + +def run_parallel_manipulands(coordinator: Any, scene: Any) -> Any: + """Run independent furniture workflows concurrently and merge their deltas.""" + + from scenesmith.agent_utils.room import RoomScene + from scenesmith.utils.logging import ConsoleLogger + + worker_limit = int(os.environ.get("RHG_MANIPULAND_PARALLEL_WORKERS", "0")) + if worker_limit < 0: + raise ValueError("RHG_MANIPULAND_PARALLEL_WORKERS must be non-negative") + baseline = scene.to_state_dict() + native_proxy_preparation = prepare_native_gltf_supports( + baseline, + scene.scene_dir, + coordinator.blender_server, + ) + skill_policy = load_scenesmith_skill_policy().manipuland + request_config_path = Path(os.environ.get("RHG_CONTEXT_ASSET_CONFIG", "")) + request_config = ( + json.loads(request_config_path.read_text(encoding="utf-8")) + if request_config_path.is_file() + else {} + ) + skill_policy = apply_request_manipuland_policy(skill_policy, request_config) + context_path = Path(os.environ.get("RHG_SCENE_CONTEXT_FILE", "")) + context = ( + json.loads(context_path.read_text(encoding="utf-8")) + if context_path.is_file() + else {} + ) + dependency_graph_path = Path(os.environ.get("RHG_SCENE_DEPENDENCY_GRAPH_FILE", "")) + dependency_graph = ( + json.loads(dependency_graph_path.read_text(encoding="utf-8")) + if dependency_graph_path.is_file() + else {} + ) + graph_worker_limit = int( + (dependency_graph.get("scheduler") or {}).get("max_parallel_branches", 0) + ) + if graph_worker_limit > 0: + worker_limit = ( + min(worker_limit, graph_worker_limit) if worker_limit > 0 else graph_worker_limit + ) + descriptions = { + str(object_id): " ".join( + str(record.get(key, "")) for key in ("object_id", "name", "description") + ) + for object_id, record in baseline.get("objects", {}).items() + if isinstance(record, dict) + } + analysis_started = time.time() + selections = None + analysis_mode = "vlm" + if should_try_task_graph(skill_policy, context): + from scenesmith.agent_utils.scene_analyzer import FurnitureSelection + + selections = task_graph_manipuland_selections( + context, + descriptions, + request_config, + FurnitureSelection, + dependency_graph, + ) + if selections is not None: + analysis_mode = "task_graph" + if selections is None: + selections = asyncio.run( # noqa: SLF001 + coordinator._analyze_furniture_for_placement(scene) + ) + analysis_duration = time.time() - analysis_started + if not selections: + return scene + if context: + selections, selection_report = prioritize_manipuland_selections( + selections, + descriptions, + task_support_ids(context, dependency_graph), + max_contextual_supports=skill_policy.max_contextual_supports, + max_items_per_critical_support=skill_policy.max_items_per_critical_support, + max_items_per_contextual_support=skill_policy.max_items_per_contextual_support, + ) + else: + selection_report = { + "input_support_count": len(selections), + "selected_support_count": len(selections), + "filter_fallback": True, + "reason": "scene context unavailable; preserving all supports", + } + baseline_hash = scene.content_hash() + worker_count = len(selections) if worker_limit == 0 else min(worker_limit, len(selections)) + output_root = scene.scene_dir / "parallel_manipulands" + output_root.mkdir(parents=True, exist_ok=True) + allowed = parse_gpu_ids( + os.environ.get("RHG_MANIPULAND_GPU_IDS") + or os.environ.get("SCENESMITH_GPU_IDS") + or os.environ.get("CUDA_VISIBLE_DEVICES") + ) + gpu_pool = DynamicGpuPool( + Path(os.environ.get("RHG_GPU_LOCK_ROOT", str(output_root / "gpu_locks"))), + allowed_ids=allowed, + min_free_vram_mb=int(os.environ.get("RHG_MANIPULAND_MIN_FREE_VRAM_MB", "8192")), + max_used_vram_mb=int(os.environ.get("RHG_MANIPULAND_MAX_USED_VRAM_MB", str(1 << 30))), + max_utilization_percent=int( + os.environ.get("RHG_MANIPULAND_MAX_GPU_UTILIZATION", "100") + ), + ) + service_connections = service_connection_kwargs(coordinator) + coordinator.cleanup() + critical_furniture_ids = set( + selection_report.get("critical_support_bindings", {}).values() + ) + conservative_limits = bool(selection_report.get("filter_fallback")) + item_limits = { + str(selection.furniture_id): ( + skill_policy.max_items_per_critical_support + if conservative_limits + or str(selection.furniture_id) in critical_furniture_ids + else skill_policy.max_items_per_contextual_support + ) + for selection in selections + } + shard_deadlines = { + str(selection.furniture_id): ( + skill_policy.critical_shard_timeout_s + if conservative_limits + or str(selection.furniture_id) in critical_furniture_ids + else skill_policy.contextual_shard_timeout_s + ) + for selection in selections + } + started = time.time() + results: list[tuple[str, dict[str, Any]]] = [] + timings: list[dict[str, Any]] = [] + import scenesmith.agent_utils.base_stateful_agent as base_stateful_module + import scenesmith.manipuland_agents.tools.vision_tools as vision_tools_module + + original_base_physics_check = base_stateful_module.check_physics_violations + original_vision_physics_check = vision_tools_module.check_physics_violations + physics_filter_events: list[dict[str, Any]] = [] + physics_filter_lock = threading.Lock() + + def geometry_sanity_checked_physics(*args: Any, **kwargs: Any) -> str: + report = original_base_physics_check(*args, **kwargs) + runtime_scene = kwargs.get("scene") or (args[0] if args else None) + filtered, removed = filter_disjoint_collision_report(report, runtime_scene) + if removed: + with physics_filter_lock: + physics_filter_events.append( + { + "timestamp_unix": time.time(), + "current_furniture_id": str( + kwargs.get("current_furniture_id") or "" + ), + "removed_false_positive_collisions": removed, + } + ) + return filtered + + # Both modules import the function directly, so patch their adapter-local + # bindings for the duration of the isolated manipulation shards. + base_stateful_module.check_physics_violations = geometry_sanity_checked_physics + vision_tools_module.check_physics_violations = geometry_sanity_checked_physics + try: + with ThreadPoolExecutor( + max_workers=worker_count, thread_name_prefix="rhg-furniture" + ) as pool: + futures = [ + pool.submit( + _run_one_shard_isolated, + agent_class=type(coordinator), + cfg=coordinator.cfg, + logger_class=ConsoleLogger, + scene_class=RoomScene, + baseline=baseline, + scene_dir=scene.scene_dir, + selection=selection, + worker_count=worker_count, + gpu_pool=gpu_pool, + output_root=output_root, + oom_retries=int( + os.environ.get("RHG_MANIPULAND_OOM_RETRIES", "2") + ), + service_connections=service_connections, + item_limit=item_limits[str(selection.furniture_id)], + shard_timeout_s=shard_deadlines[str(selection.furniture_id)], + fallback_on_timeout=( + not conservative_limits + and str(selection.furniture_id) + not in critical_furniture_ids + ), + ) + for selection in selections + ] + for future in as_completed(futures): + furniture_id, state, timing = future.result() + results.append((furniture_id, state)) + timings.append(timing) + finally: + base_stateful_module.check_physics_violations = original_base_physics_check + vision_tools_module.check_physics_violations = original_vision_physics_check + (output_root / "physics_collision_sanity.json").write_text( + json.dumps( + { + "schema_version": "1.0", + "policy": "reject_narrow_phase_collision_when_world_aabbs_disjoint", + "events": physics_filter_events, + }, + indent=2, + ), + encoding="utf-8", + ) + merge_started = time.time() + ignored_foreign_mutations = find_foreign_mutations(baseline, results) + merged, additions = merge_scene_states( + baseline, results, reject_foreign_mutations=False + ) + scene.restore_from_state_dict(merged) + planned_assignments = manipulation_assignments(dependency_graph) + expected_by_furniture = { + str(furniture_id): planned_assignments[support_id] + for support_id, furniture_id in selection_report.get( + "critical_support_bindings", {} + ).items() + if support_id in planned_assignments + } + branch_completion, failed_critical_branches = evaluate_branch_completion( + additions, expected_by_furniture + ) + timing = { + "schema_version": "1.0", + "mode": "parallel_furniture_shards", + "baseline_hash": baseline_hash, + "worker_count": worker_count, + "analysis_duration_s": round(analysis_duration, 3), + "analysis_mode": analysis_mode, + "effective_policy": skill_policy.model_dump(mode="json"), + "selection_policy": selection_report, + "native_proxy_preparation": native_proxy_preparation, + "service_connections": service_connections, + "item_limits": item_limits, + "shard_deadlines_s": shard_deadlines, + "shards": sorted(timings, key=lambda item: item["furniture_id"]), + "additions": additions, + "branch_completion": branch_completion, + "failed_critical_branches": failed_critical_branches, + "ignored_foreign_mutations": ignored_foreign_mutations, + "merge_duration_s": round(time.time() - merge_started, 3), + "parallel_stage_duration_s": round(time.time() - started, 3), + } + (output_root / "timing.json").write_text( + json.dumps(timing, indent=2), encoding="utf-8" + ) + if failed_critical_branches: + raise RuntimeError( + "critical manipulation branches did not produce their planned entities: " + f"{failed_critical_branches}" + ) + return scene diff --git a/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_process_bootstrap.py b/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_process_bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..16a6050094535c1f1dfb680bcb7b86a7b5d0bb1f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_process_bootstrap.py @@ -0,0 +1,23 @@ +"""Multiprocessing bootstrap that preserves SceneSmith's bpy-first import order.""" + +import sys + +# A spawned process inherits the parent's current sys.path. Once bpy has been +# imported, that path contains Blender's internal ``scripts/modules`` directory; +# resolving ``bpy`` from there bypasses the wheel bootstrap which loads the +# native ``_bpy`` extension. Remove only those generated internal entries so a +# clean spawned interpreter resolves the installed bpy wheel normally. +sys.path[:] = [ + entry + for entry in sys.path + if not ( + "/site-packages/bpy/" in entry.replace("\\", "/") + and "/scripts/" in entry.replace("\\", "/") + ) +] + +try: + import bpy # type: ignore[import-not-found] # noqa: F401 +except ModuleNotFoundError as error: + if error.name != "bpy": + raise diff --git a/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_skill_policy.py b/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_skill_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..98bb941a9f9f551535e50cb1e6bdb3de57bec3a3 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/scenesmith_skill_policy.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import json +import math +import os +from pathlib import Path +from typing import Annotated, Literal, TypeAlias + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field + +ApiTimeout: TypeAlias = Literal["auto"] | Annotated[float, Field(gt=0)] # noqa: UP040 + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class AgentTurnBudget(_StrictModel): + designer: int = Field(gt=0) + planner: int = Field(gt=0) + critic: int = Field(gt=0) + + +class AgentSkillStage(_StrictModel): + skill_id: str = Field(min_length=1) + scope: Literal["global", "task_critical", "contextual", "local", "merge"] + execution: Literal["agent", "analytic", "batch", "cached"] + parallelizable: bool = False + max_calls: int = Field(ge=0) + quality_gate: str | None = None + + +class FurnitureSkillPolicy(_StrictModel): + max_critique_rounds: int = Field(ge=0) + early_finish_min_score: float = Field(ge=0.0, le=10.0) + max_turns: AgentTurnBudget + session_summarization: bool = False + api_timeout_read_s: ApiTimeout = "auto" + api_timeout_pool_s: ApiTimeout = "auto" + max_contextual_instances: int = Field(ge=0) + skills: list[AgentSkillStage] = Field(min_length=1) + prompt_rules: list[str] = Field(default_factory=list) + + +class ManipulandSkillPolicy(_StrictModel): + support_selection_mode: Literal["task_graph_first", "vlm"] = "task_graph_first" + max_critique_rounds: int = Field(ge=0) + early_finish_min_score: float = Field(ge=0.0, le=10.0) + max_turns: AgentTurnBudget + session_summarization: bool = False + api_timeout_read_s: ApiTimeout = "auto" + api_timeout_pool_s: ApiTimeout = "auto" + critical_shard_timeout_s: float = Field(gt=0) + contextual_shard_timeout_s: float = Field(gt=0) + max_contextual_supports: int = Field(ge=0) + max_items_per_critical_support: int = Field(gt=0) + max_items_per_contextual_support: int = Field(ge=0) + skills: list[AgentSkillStage] = Field(min_length=1) + prompt_rules: list[str] = Field(default_factory=list) + + +class SceneSmithSkillPolicy(_StrictModel): + schema_version: str + furniture: FurnitureSkillPolicy + manipuland: ManipulandSkillPolicy + + @property + def prompt_rules(self) -> list[str]: + furniture_plan = " -> ".join(stage.skill_id for stage in self.furniture.skills) + manipuland_plan = " -> ".join(stage.skill_id for stage in self.manipuland.skills) + return [ + f"Furniture execution skills: {furniture_plan}.", + *self.furniture.prompt_rules, + f"Manipuland execution skills: {manipuland_plan}.", + *self.manipuland.prompt_rules, + ] + + +DEFAULT_SKILL_POLICY = ( + Path(__file__).resolve().parents[2] + / "configs" + / "scene_generation" + / "agent_skills_v1.yaml" +) + + +def load_scenesmith_skill_policy(path: Path | None = None) -> SceneSmithSkillPolicy: + selected = path or Path(os.environ.get("RHG_SCENESMITH_SKILL_POLICY", DEFAULT_SKILL_POLICY)) + payload = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8")) + apply_attempt_budget_multiplier(payload) + apply_repair_budget_overrides(payload) + return SceneSmithSkillPolicy.model_validate(payload) + + +def apply_attempt_budget_multiplier(payload: dict[str, object]) -> None: + """Give v1 more bounded Agent work without extending transport or wall timeouts.""" + multiplier = float(os.environ.get("RHG_ATTEMPT_BUDGET_MULTIPLIER", "1.0")) + if not 1.0 <= multiplier <= 1.6: + raise ValueError("attempt budget multiplier must be between 1.0 and 1.6") + if multiplier == 1.0: + return + for stage_name in ("furniture", "manipuland"): + stage = payload.get(stage_name) + if not isinstance(stage, dict): + raise ValueError(f"skill policy is missing {stage_name} configuration") + turns = stage.get("max_turns") + if not isinstance(turns, dict): + raise ValueError(f"skill policy is missing {stage_name}.max_turns") + for role in ("designer", "planner", "critic"): + turns[role] = max(1, math.ceil(int(turns[role]) * multiplier)) + + +def apply_repair_budget_overrides(payload: dict[str, object]) -> None: + """Apply allowlisted Supervisor budget adjustments to the loaded policy.""" + raw_plan = os.environ.get("RHG_REPAIR_PLAN", "").strip() + if not raw_plan: + return + try: + plan = json.loads(raw_plan) + except json.JSONDecodeError as error: + raise ValueError("RHG_REPAIR_PLAN must be valid JSON") from error + for step in plan.get("steps", []): + if ( + step.get("action") != "adjust_stage_budget" + or step.get("stage") != "manipuland" + ): + continue + multiplier = float(step.get("parameters", {}).get("timeout_multiplier", 1.0)) + if not 1.0 <= multiplier <= 4.0: + raise ValueError("manipuland timeout_multiplier must be between 1 and 4") + manipuland = payload.get("manipuland") + if not isinstance(manipuland, dict): + raise ValueError("skill policy is missing manipuland configuration") + for key in ("critical_shard_timeout_s", "contextual_shard_timeout_s"): + manipuland[key] = float(manipuland[key]) * multiplier diff --git a/docs/reproduction/public_conversion_code/packages/runtime/stack_batch.py b/docs/reproduction/public_conversion_code/packages/runtime/stack_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..86569b84ec287c2c84b45b769b30dc81b630154d --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/runtime/stack_batch.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +import time +from collections.abc import Callable +from dataclasses import dataclass + + +@dataclass(frozen=True, slots=True) +class StackJob: + stack_id: str + surface_id: str + bbox_min_xy: tuple[float, float] + bbox_max_xy: tuple[float, float] + + +@dataclass(frozen=True, slots=True) +class StackBatchResult[T]: + values: dict[str, T] + batches: list[dict[str, object]] + + +def group_stack_jobs(jobs: list[StackJob], margin_m: float = 0.05) -> list[list[StackJob]]: + """Group stacks that share a support and may interact in one physics world.""" + + remaining = {job.stack_id: job for job in jobs} + groups: list[list[StackJob]] = [] + while remaining: + _, first = remaining.popitem() + group = [first] + frontier = [first] + while frontier: + current = frontier.pop() + touching = [ + candidate + for candidate in remaining.values() + if _overlaps(current, candidate, margin_m) + ] + for candidate in touching: + remaining.pop(candidate.stack_id) + group.append(candidate) + frontier.append(candidate) + groups.append(sorted(group, key=lambda item: item.stack_id)) + return sorted(groups, key=lambda group: group[0].stack_id) + + +def run_stack_batches[T]( + groups: list[list[StackJob]], + run_batch: Callable[[list[StackJob]], dict[str, T]], +) -> StackBatchResult[T]: + """Execute stack worlds with deterministic bisection down to single-stack fallback.""" + + values: dict[str, T] = {} + records: list[dict[str, object]] = [] + + def run(group: list[StackJob]) -> None: + started = time.perf_counter() + try: + batch_values = run_batch(group) + expected = {item.stack_id for item in group} + if set(batch_values) != expected: + raise ValueError("stack simulator returned an incomplete batch") + values.update(batch_values) + records.append( + { + "stack_ids": sorted(expected), + "status": "complete", + "duration_s": round(time.perf_counter() - started, 6), + } + ) + except Exception as error: + records.append( + { + "stack_ids": [item.stack_id for item in group], + "status": "fallback" if len(group) > 1 else "failed", + "duration_s": round(time.perf_counter() - started, 6), + "error": repr(error), + } + ) + if len(group) == 1: + raise + middle = len(group) // 2 + run(group[:middle]) + run(group[middle:]) + + for group in groups: + run(group) + return StackBatchResult(values=values, batches=records) + + +def _overlaps(left: StackJob, right: StackJob, margin_m: float) -> bool: + if left.surface_id != right.surface_id: + return False + return not ( + left.bbox_max_xy[0] + margin_m < right.bbox_min_xy[0] + or right.bbox_max_xy[0] + margin_m < left.bbox_min_xy[0] + or left.bbox_max_xy[1] + margin_m < right.bbox_min_xy[1] + or right.bbox_max_xy[1] + margin_m < left.bbox_min_xy[1] + ) diff --git a/docs/reproduction/public_conversion_code/packages/scenarios/__init__.py b/docs/reproduction/public_conversion_code/packages/scenarios/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c190bd0b50e947510d7afa9e9a76370df3797cde --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scenarios/__init__.py @@ -0,0 +1,4 @@ +from packages.scenarios.router import build_scene_for_task +from packages.scenarios.stair_room import StairRoomConfig, StairRoomScenario + +__all__ = ["StairRoomConfig", "StairRoomScenario", "build_scene_for_task"] diff --git a/docs/reproduction/public_conversion_code/packages/scenarios/router.py b/docs/reproduction/public_conversion_code/packages/scenarios/router.py new file mode 100644 index 0000000000000000000000000000000000000000..07e273d8b751e6ed1a8f41bf7d31771c50c45c09 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scenarios/router.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from pathlib import Path + +from packages.scenarios.stair_room import StairRoomConfig, StairRoomScenario +from packages.schemas.models import RobotSpawnSpec, SceneManifest, TaskSpec +from packages.usd_composer.composer import USDComposer + + +def build_scene_for_task( + task: TaskSpec, + output_dir: Path, + robot_id: str, + *, + stair_config: StairRoomConfig | None = None, + robot_spawn: RobotSpawnSpec | None = None, +) -> SceneManifest: + """Route a compiled task to its deterministic scene generator.""" + if task.task_type == "humanoid_stair_ascent": + return StairRoomScenario(stair_config).build(task, output_dir, robot_id) + if stair_config is not None: + raise ValueError("stair_config is only valid for humanoid_stair_ascent tasks") + return USDComposer().compose(task, output_dir, robot_id, robot_spawn) diff --git a/docs/reproduction/public_conversion_code/packages/scenarios/stair_room.py b/docs/reproduction/public_conversion_code/packages/scenarios/stair_room.py new file mode 100644 index 0000000000000000000000000000000000000000..ae3318abcd05b3b2d264e7c0eef4ed35a87d730d --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scenarios/stair_room.py @@ -0,0 +1,462 @@ +from __future__ import annotations + +import hashlib +import json +import math +from dataclasses import dataclass +from pathlib import Path + +from packages.core.files import atomic_write_text +from packages.schemas.models import SceneLayerPlan, SceneManifest, TaskSpec +from packages.usd_composer.composer import LAYER_NAMES + + +@dataclass(frozen=True) +class StairRoomConfig: + step_count: int = 18 + riser_height_m: float = 1.0 / 6.0 + tread_depth_m: float = 0.27 + stair_width_m: float = 1.4 + landing_depth_m: float = 1.2 + room_length_m: float = 8.5 + room_width_m: float = 4.8 + wall_height_m: float = 4.5 + visual_theme: str = "modern_warm" + + def validate(self) -> None: + if not 4 <= self.step_count <= 24: + raise ValueError("step_count must be between 4 and 24") + if not 0.1 <= self.riser_height_m <= 0.2: + raise ValueError("riser_height_m must be between 0.10 and 0.20") + if not 0.24 <= self.tread_depth_m <= 0.45: + raise ValueError("tread_depth_m must be between 0.24 and 0.45") + if self.stair_width_m < 1.2: + raise ValueError("stair_width_m must be at least 1.2") + if self.landing_depth_m < 1.2: + raise ValueError("landing_depth_m must be at least 1.2") + if self.visual_theme != "modern_warm": + raise ValueError("visual_theme must be modern_warm") + + +class StairRoomScenario: + def __init__(self, config: StairRoomConfig | None = None) -> None: + self.config = config or StairRoomConfig() + self.config.validate() + + def build(self, task: TaskSpec, output_dir: Path, robot_id: str) -> SceneManifest: + if task.task_type != "humanoid_stair_ascent": + raise ValueError("stair room requires a humanoid_stair_ascent TaskSpec") + layers_dir = output_dir / "layers" + manifests_dir = output_dir / "manifests" + layers_dir.mkdir(parents=True, exist_ok=True) + manifests_dir.mkdir(parents=True, exist_ok=True) + layers = {name: f"layers/{name}.usda" for name in LAYER_NAMES} + for name, relative_path in layers.items(): + if name == "room": + body = self._room_layer(task.task_id) + elif name == "task": + body = self._task_layer(task.task_id) + elif name == "robot": + body = self._robot_layer(task.task_id, robot_id) + elif name == "lighting": + body = self._lighting_layer(task.task_id) + else: + body = self._empty_layer(name, task.task_id, robot_id) + atomic_write_text(output_dir / relative_path, body) + + sublayers = ",\n ".join(f"@{uri}@" for uri in layers.values()) + root = ( + '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' + f' subLayers = [\n {sublayers}\n ]\n upAxis = "Z"\n)\n\n' + 'def Xform "World" (\n customData = {\n' + ' string robothousegen_scenario = "humanoid_stair_room_v1"\n' + f' string robothousegen_task_id = "{task.task_id}"\n' + " }\n) {}\n" + ) + atomic_write_text(output_dir / "root.usda", root) + digest = hashlib.sha256(task.model_dump_json().encode()) + digest.update(root.encode()) + for name in LAYER_NAMES: + digest.update((output_dir / layers[name]).read_bytes()) + manifest = SceneManifest( + scene_id=f"stair-room-{task.task_id.removeprefix('task-')}", + task_id=task.task_id, + random_seed=task.random_seed, + layer_plan=SceneLayerPlan(layers=layers), + entity_prim_paths={ + "staircase": "/World/Staircase", + "start_region": "/World/TaskRegions/StartRegion", + "goal_region": "/World/TaskRegions/GoalRegion", + }, + robot_prim_path="/World/RobotSpawnStub", + source_checkpoints={ + "generator": "StairRoomScenario/1.1", + "robot_profile": robot_id, + }, + content_hash=digest.hexdigest(), + ) + atomic_write_text( + manifests_dir / "scene.json", + json.dumps(manifest.model_dump(mode="json"), indent=2, sort_keys=True), + ) + atomic_write_text( + manifests_dir / "stair_config.json", + json.dumps(self.config.__dict__, indent=2, sort_keys=True), + ) + return manifest + + def _room_layer(self, task_id: str) -> str: + config = self.config + lines = [ + "#usda 1.0", + '(\n metersPerUnit = 1\n upAxis = "Z"\n)', + 'over Xform "World" {', + ' def PhysicsScene "PhysicsScene" {', + " vector3f physics:gravityDirection = (0, 0, -1)", + " float physics:gravityMagnitude = 9.81", + " }", + self._cube( + "Floor", + (0.0, 0.0, -0.05), + (config.room_length_m, config.room_width_m, 0.1), + collision=True, + color=(0.12, 0.14, 0.15), + ), + self._material_library(), + self._cube( + "WallLeft", + (0.0, config.room_width_m / 2, config.wall_height_m / 2), + (config.room_length_m, 0.1, config.wall_height_m), + collision=True, + color=(0.72, 0.7, 0.66), + ), + self._cube( + "WallRight", + (0.0, -config.room_width_m / 2, config.wall_height_m / 2), + (config.room_length_m, 0.1, config.wall_height_m), + collision=True, + color=(0.72, 0.7, 0.66), + ), + self._cube( + "WallBack", + (config.room_length_m / 2, 0.0, config.wall_height_m / 2), + (0.1, config.room_width_m, config.wall_height_m), + collision=True, + color=(0.72, 0.7, 0.66), + ), + self._cube( + "BaseboardLeft", + (0.0, config.room_width_m / 2 - 0.07, 0.09), + (config.room_length_m, 0.06, 0.18), + collision=False, + color=(0.08, 0.09, 0.1), + ), + self._cube( + "BaseboardRight", + (0.0, -config.room_width_m / 2 + 0.07, 0.09), + (config.room_length_m, 0.06, 0.18), + collision=False, + color=(0.08, 0.09, 0.1), + ), + self._physics_probe(), + ' def Xform "Staircase" (', + f' customData = {{ string robothousegen_task_id = "{task_id}" }}', + " ) {", + ] + run = config.step_count * config.tread_depth_m + start_x = -run / 2 + for index in range(1, config.step_count + 1): + height = index * config.riser_height_m + x = start_x + (index - 0.5) * config.tread_depth_m + lines.append( + self._cube( + f"Step_{index:02d}", + (x, 0.0, height / 2), + (config.tread_depth_m, config.stair_width_m, height), + collision=True, + color=(0.42, 0.34, 0.25), + indent=" ", + ) + ) + lines.append( + self._cube( + f"TreadCap_{index:02d}", + (x, 0.0, height + 0.012), + (config.tread_depth_m + 0.015, config.stair_width_m, 0.024), + collision=False, + color=(0.52, 0.27, 0.11), + indent=" ", + ) + ) + top_height = config.step_count * config.riser_height_m + landing_x = run / 2 + config.landing_depth_m / 2 + lines.extend( + [ + self._cube( + "Landing", + (landing_x, 0.0, top_height / 2), + (config.landing_depth_m, config.stair_width_m, top_height), + collision=True, + color=(0.42, 0.34, 0.25), + indent=" ", + ), + self._cube( + "LandingCap", + (landing_x, 0.0, top_height + 0.012), + (config.landing_depth_m, config.stair_width_m, 0.024), + collision=False, + color=(0.52, 0.27, 0.11), + indent=" ", + ), + *self._rail_geometry(start_x, run, top_height), + " }", + "}", + ] + ) + return "\n".join(lines) + "\n" + + def _rail_geometry(self, start_x: float, run: float, top_height: float) -> list[str]: + config = self.config + lines: list[str] = [] + for side, y in ( + ("Left", config.stair_width_m / 2 + 0.04), + ("Right", -config.stair_width_m / 2 - 0.04), + ): + for index in range(config.step_count + 1): + x = start_x + index * config.tread_depth_m + z = min((index + 1) * config.riser_height_m, top_height) + lines.append( + self._cube( + f"RailPost{side}_{index:02d}", + (x, y, z + 0.48), + (0.045, 0.045, 0.96), + collision=False, + color=(0.07, 0.08, 0.09), + indent=" ", + ) + ) + slope_length = (run * run + top_height * top_height) ** 0.5 + angle = -math.degrees(math.atan2(top_height, run)) + lines.append( + self._cube( + f"Handrail{side}", + (start_x + run / 2, y, top_height / 2 + 1.0), + (slope_length + 0.15, 0.07, 0.07), + collision=False, + color=(0.04, 0.05, 0.055), + indent=" ", + rotate_y=angle, + ) + ) + return lines + + def _task_layer(self, task_id: str) -> str: + config = self.config + run = config.step_count * config.tread_depth_m + top_height = config.step_count * config.riser_height_m + start_x = -run / 2 - 0.8 + goal_x = run / 2 + config.landing_depth_m / 2 + return ( + "\n".join( + [ + "#usda 1.0", + '(\n metersPerUnit = 1\n upAxis = "Z"\n)', + 'over Xform "World" {', + ' def Xform "TaskRegions" {', + self._cube( + "StartRegion", + (start_x, 0.0, 0.01), + (1.2, 1.2, 0.02), + collision=False, + color=(0.15, 0.35, 0.8), + opacity=0.45, + indent=" ", + ), + self._cube( + "GoalRegion", + (goal_x, 0.0, top_height + 0.01), + (1.0, 1.2, 0.02), + collision=False, + color=(0.1, 0.75, 0.3), + opacity=0.55, + indent=" ", + ), + " }", + "}", + ] + ) + + "\n" + ) + + def _robot_layer(self, task_id: str, robot_id: str) -> str: + run = self.config.step_count * self.config.tread_depth_m + x = -run / 2 - 0.8 + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + 'over Xform "World" {\n' + ' def Xform "RobotSpawnStub" (\n' + " customData = {\n" + f' string robothousegen_robot_id = "{robot_id}"\n' + f' string robothousegen_task_id = "{task_id}"\n' + " }\n" + " ) {\n" + f" double3 xformOp:translate = ({x:.6f}, 0, 0)\n" + ' uniform token[] xformOpOrder = ["xformOp:translate"]\n' + f"{self._robot_cube('RobotTorso', (0, 0, 1.15), (0.34, 0.22, 0.48))}\n" + f"{self._robot_cube('RobotPelvis', (0, 0, 0.84), (0.3, 0.2, 0.18))}\n" + f"{self._robot_cube('RobotHead', (0, 0, 1.52), (0.22, 0.2, 0.22))}\n" + f"{self._robot_cube('RobotArmLeft', (0, 0.26, 1.08), (0.13, 0.13, 0.55))}\n" + f"{self._robot_cube('RobotArmRight', (0, -0.26, 1.08), (0.13, 0.13, 0.55))}\n" + f"{self._robot_cube('RobotLegLeft', (0, 0.12, 0.43), (0.15, 0.15, 0.68))}\n" + f"{self._robot_cube('RobotLegRight', (0, -0.12, 0.43), (0.15, 0.15, 0.68))}\n" + f"{self._robot_cube('RobotFootLeft', (0.08, 0.12, 0.08), (0.32, 0.16, 0.12))}\n" + f"{self._robot_cube('RobotFootRight', (0.08, -0.12, 0.08), (0.32, 0.16, 0.12))}\n" + " }\n" + "}\n" + ) + + @staticmethod + def _robot_cube( + name: str, + translate: tuple[float, float, float], + dimensions: tuple[float, float, float], + ) -> str: + tx, ty, tz = translate + sx, sy, sz = (value / 2 for value in dimensions) + return ( + f' def Cube "{name}" {{\n' + " color3f[] primvars:displayColor = [(0.68, 0.035, 0.025)]\n" + " rel material:binding = \n" + f" double3 xformOp:scale = ({sx:.6f}, {sy:.6f}, {sz:.6f})\n" + f" double3 xformOp:translate = ({tx:.6f}, {ty:.6f}, {tz:.6f})\n" + ' uniform token[] xformOpOrder = ["xformOp:translate", ' + '"xformOp:scale"]\n' + " }" + ) + + @staticmethod + def _lighting_layer(task_id: str) -> str: + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + 'over Xform "World" {\n' + ' def DomeLight "RoomLight" {\n' + " float inputs:intensity = 700\n" + " color3f inputs:color = (0.92, 0.95, 1.0)\n" + " }\n" + "}\n" + ) + + @staticmethod + def _empty_layer(name: str, task_id: str, robot_id: str) -> str: + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n' + " customLayerData = {\n" + f' string robothousegen_layer_role = "{name}"\n' + f' string robothousegen_robot_id = "{robot_id}"\n' + f' string robothousegen_task_id = "{task_id}"\n' + " }\n)\n" + ) + + @staticmethod + def _cube( + name: str, + translate: tuple[float, float, float], + dimensions: tuple[float, float, float], + *, + collision: bool, + color: tuple[float, float, float], + opacity: float = 1.0, + indent: str = " ", + rotate_y: float | None = None, + ) -> str: + schemas = ' (prepend apiSchemas = ["PhysicsCollisionAPI"])' if collision else "" + tx, ty, tz = translate + sx, sy, sz = (value / 2 for value in dimensions) + rotate = ( + f"{indent} double xformOp:rotateY = {rotate_y:.6f}\n" if rotate_y is not None else "" + ) + order = ( + '["xformOp:translate", "xformOp:rotateY", "xformOp:scale"]' + if rotate_y is not None + else '["xformOp:translate", "xformOp:scale"]' + ) + material = StairRoomScenario._material_for_prim(name) + return ( + f'{indent}def Cube "{name}"{schemas} {{\n' + f"{indent} color3f[] primvars:displayColor = [{color}]\n" + f"{indent} float[] primvars:displayOpacity = [{opacity}]\n" + f"{indent} rel material:binding = \n" + f"{indent} double3 xformOp:scale = ({sx:.6f}, {sy:.6f}, {sz:.6f})\n" + f"{indent} double3 xformOp:translate = ({tx:.6f}, {ty:.6f}, {tz:.6f})\n" + f"{rotate}" + f"{indent} uniform token[] xformOpOrder = {order}\n" + f"{indent}}}" + ) + + @staticmethod + def _material_for_prim(name: str) -> str: + if name == "Floor": + return "Floor" + if name.startswith("Wall"): + return "Wall" + if name.startswith(("TreadCap", "LandingCap")): + return "WoodTread" + if name.startswith(("Step_", "Landing")): + return "StairBody" + if name.startswith(("RailPost", "Handrail", "Baseboard")): + return "Metal" + if name == "StartRegion": + return "StartRegion" + if name == "GoalRegion": + return "GoalRegion" + return "Neutral" + + @staticmethod + def _material_library() -> str: + definitions = ( + ("Floor", (0.055, 0.065, 0.07), 0.72, 0.0, 1.0), + ("Wall", (0.52, 0.46, 0.38), 0.82, 0.0, 1.0), + ("StairBody", (0.10, 0.115, 0.13), 0.68, 0.0, 1.0), + ("WoodTread", (0.43, 0.16, 0.045), 0.34, 0.0, 1.0), + ("Metal", (0.025, 0.03, 0.035), 0.22, 0.82, 1.0), + ("StartRegion", (0.025, 0.18, 0.8), 0.36, 0.0, 0.42), + ("GoalRegion", (0.02, 0.8, 0.18), 0.30, 0.0, 0.50), + ("RobotRed", (0.70, 0.025, 0.02), 0.28, 0.30, 1.0), + ("Neutral", (0.22, 0.24, 0.26), 0.55, 0.0, 1.0), + ) + lines = [' def Scope "Looks" {'] + for name, color, roughness, metallic, opacity in definitions: + lines.extend( + [ + f' def Material "{name}" {{', + " token outputs:surface.connect = " + f"", + ' def Shader "PreviewSurface" {', + ' uniform token info:id = "UsdPreviewSurface"', + f" color3f inputs:diffuseColor = {color}", + f" float inputs:roughness = {roughness}", + f" float inputs:metallic = {metallic}", + f" float inputs:opacity = {opacity}", + " token outputs:surface", + " }", + " }", + ] + ) + lines.append(" }") + return "\n".join(lines) + + @staticmethod + def _physics_probe() -> str: + return ( + ' def Cube "ValidationProbe" (\n' + ' prepend apiSchemas = ["PhysicsCollisionAPI", "PhysicsRigidBodyAPI", ' + '"PhysicsMassAPI"]\n' + " ) {\n" + " float physics:mass = 1\n" + " color3f[] primvars:displayColor = [(0.95, 0.75, 0.1)]\n" + " rel material:binding = \n" + " double3 xformOp:scale = (0.1, 0.1, 0.1)\n" + " double3 xformOp:translate = (-3, 1.5, 1)\n" + ' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]\n' + " }" + ) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/__init__.py b/docs/reproduction/public_conversion_code/packages/scene_generation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a18a335c3fa22ad03216f720e21da0c2f988f6d3 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/__init__.py @@ -0,0 +1,43 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from packages.scene_generation.bundle_compiler import SceneBundleCompiler + from packages.scene_generation.compiler import SceneRequestCompiler + from packages.scene_generation.orchestrator import ( + GenerationBackend, + SceneGenerationOrchestrator, + ) + +__all__ = [ + "GenerationBackend", + "SceneBundleCompiler", + "SceneGenerationOrchestrator", + "SceneRequestCompiler", +] + + +def __getattr__(name: str) -> object: + """Keep public imports stable without loading GPU/runtime adapters eagerly.""" + + if name == "SceneBundleCompiler": + from packages.scene_generation.bundle_compiler import SceneBundleCompiler + + value = SceneBundleCompiler + elif name == "SceneRequestCompiler": + from packages.scene_generation.compiler import SceneRequestCompiler + + value = SceneRequestCompiler + elif name in {"GenerationBackend", "SceneGenerationOrchestrator"}: + from packages.scene_generation.orchestrator import ( + GenerationBackend, + SceneGenerationOrchestrator, + ) + + value = { + "GenerationBackend": GenerationBackend, + "SceneGenerationOrchestrator": SceneGenerationOrchestrator, + }[name] + else: + raise AttributeError(name) + globals()[name] = value + return value diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/agent_executor.py b/docs/reproduction/public_conversion_code/packages/scene_generation/agent_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..3135d089e361d882783b71e124011c2e05a0489b --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/agent_executor.py @@ -0,0 +1,545 @@ +from __future__ import annotations + +import asyncio +import hashlib +import inspect +import json +import random +import time +import traceback +from collections.abc import Awaitable, Callable +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field + +from packages.core.files import atomic_write_text +from packages.scene_generation.agent_orchestration import ( + AgentExecutionPlan, + AgentExecutionTask, + AgentOrchestrationPolicy, + AgentRole, +) + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class AgentTaskResult(_StrictModel): + accepted: bool = True + summary: str + artifacts: dict[str, str] = Field(default_factory=dict) + metrics: dict[str, float | int | bool | str | None] = Field(default_factory=dict) + critic_score: float | None = Field(default=None, ge=0, le=10) + hard_gates_passed: bool = True + failure_signature: str | None = None + resource_lease: dict[str, str | int | float | bool | None] = Field(default_factory=dict) + trace_id: str | None = None + + +class AgentTaskRecord(_StrictModel): + task_id: str + agent_id: str + role: AgentRole + subtree_id: str | None = None + status: Literal["pending", "running", "complete", "failed", "blocked", "reused"] = "pending" + model: str | None = None + reasoning_effort: str | None = None + depends_on: list[str] = Field(default_factory=list) + owned_node_ids: list[str] = Field(default_factory=list) + resource_class: str + resource_lease: dict[str, str | int | float | bool | None] = Field(default_factory=dict) + started_unix: float | None = None + completed_unix: float | None = None + duration_s: float | None = None + attempt_count: int = 0 + input_sha256: str + output_sha256: str | None = None + result: AgentTaskResult | None = None + error: str | None = None + + +class AgentExecutionLedger(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + graph_id: str + plan_sha256: str + status: Literal["running", "complete", "failed"] = "running" + started_unix: float + completed_unix: float | None = None + max_concurrent_agent_runs: int + max_observed_concurrency: int = 0 + records: dict[str, AgentTaskRecord] + + +class AgentRuntimeContext(_StrictModel): + output_root: Path + task_payload: dict[str, Any] = Field(default_factory=dict) + scene_payload: dict[str, Any] = Field(default_factory=dict) + + +AgentHandler = Callable[ + [AgentExecutionTask, AgentRuntimeContext], + AgentTaskResult | Awaitable[AgentTaskResult], +] + + +class RepeatedFailureSignature(RuntimeError): + """A deterministic local failure repeated enough times to require orchestration.""" + + +class AgentDecisionRejected(RuntimeError): + """A completed Agent decision rejected immutable evidence. + + Retrying the same semantic decision without changing its input cannot repair the + scene. It only spends another API call and can make the ledger nondeterministic + when a later sample disagrees with the first one. Transient transport failures + remain covered by the API retry loop; semantic rejection returns to the DAG + orchestrator immediately. + """ + + +def _json_sha256(value: Any) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str).encode() + return hashlib.sha256(payload).hexdigest() + + +def _plan_sha256(plan: AgentExecutionPlan) -> str: + return _json_sha256(plan.model_dump(mode="json")) + + +def _task_input_sha256( + task: AgentExecutionTask, + plan: AgentExecutionPlan, + context: AgentRuntimeContext, +) -> str: + scene_payload = dict(context.scene_payload) + if task.role is AgentRole.GLOBAL_CRITIC: + # Eevee can produce byte-different PNGs for an unchanged USD. Keep the + # image hashes in the runtime payload for audit, but key checkpoint reuse + # to stable scene evidence so an interrupted global repair does not spend + # another model call merely because the same views were re-rendered. + views = scene_payload.get("final_critic_views") + if isinstance(views, list): + scene_payload["final_critic_views"] = [ + {"path": view.get("path")} if isinstance(view, dict) and view.get("path") else view + for view in views + ] + else: + # Merged-scene images are not inputs to upstream subtree work. Excluding + # them prevents render noise from invalidating every recovery checkpoint. + scene_payload.pop("final_critic_views", None) + return _json_sha256( + { + "task": task.model_dump(mode="json"), + "planning_sha256": plan.planning_sha256, + "task_payload": context.task_payload, + "scene_payload": scene_payload, + } + ) + + +def _checkpoint_path(root: Path, task_id: str) -> Path: + safe = task_id.replace(":", "__").replace("/", "_") + return root / "agent_checkpoints" / f"{safe}.json" + + +def _artifact_hashes_valid(root: Path, result: AgentTaskResult) -> bool: + for relative, expected_hash in result.artifacts.items(): + path = root / relative + if not path.is_file(): + return False + digest = hashlib.sha256(path.read_bytes()).hexdigest() + if digest != expected_hash: + return False + return True + + +def _persist_ledger(path: Path, ledger: AgentExecutionLedger) -> None: + atomic_write_text(path, ledger.model_dump_json(indent=2) + "\n") + + +def _persist_checkpoint( + path: Path, + record: AgentTaskRecord, +) -> None: + atomic_write_text(path, record.model_dump_json(indent=2) + "\n") + + +def _load_reusable_record( + task: AgentExecutionTask, + *, + input_sha256: str, + output_root: Path, +) -> AgentTaskRecord | None: + path = _checkpoint_path(output_root, task.task_id) + if not path.is_file(): + return None + try: + record = AgentTaskRecord.model_validate_json(path.read_text(encoding="utf-8")) + except Exception: + return None + reusable_rejected_global = False + if ( + record.result is not None + and task.role is AgentRole.GLOBAL_CRITIC + and not record.result.accepted + and record.result.failure_signature + ): + for relative in record.result.artifacts: + if not relative.startswith("agent_outputs/") or not relative.endswith(".json"): + continue + try: + payload = json.loads((output_root / relative).read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + if isinstance(payload, dict) and isinstance( + payload.get("proposed_local_transform"), dict + ): + reusable_rejected_global = True + break + if ( + record.task_id != task.task_id + or record.input_sha256 != input_sha256 + or record.status not in {"complete", "reused"} + or record.result is None + or ( + (not record.result.accepted or not record.result.hard_gates_passed) + and not reusable_rejected_global + ) + or not _artifact_hashes_valid(output_root, record.result) + ): + return None + return record.model_copy(update={"status": "reused", "error": None}) + + +async def execute_agent_plan( + plan: AgentExecutionPlan, + handlers: dict[AgentRole, AgentHandler], + *, + context: AgentRuntimeContext, + policy: AgentOrchestrationPolicy, + ledger_path: Path | None = None, + resume: bool = True, +) -> AgentExecutionLedger: + """Execute the Agent DAG with real task state, bounded concurrency and checkpoints.""" + + ledger_path = ledger_path or context.output_root / "agent_execution_ledger.json" + context.output_root.mkdir(parents=True, exist_ok=True) + records: dict[str, AgentTaskRecord] = {} + for task in plan.tasks: + input_hash = _task_input_sha256(task, plan, context) + reused = ( + _load_reusable_record(task, input_sha256=input_hash, output_root=context.output_root) + if resume + else None + ) + records[task.task_id] = reused or AgentTaskRecord( + task_id=task.task_id, + agent_id=f"{task.role.value}:{task.subtree_id or task.task_id}", + role=task.role, + subtree_id=task.subtree_id, + model=task.model, + reasoning_effort=task.reasoning_effort, + depends_on=task.depends_on, + owned_node_ids=task.owned_node_ids, + resource_class=task.resource_class, + input_sha256=input_hash, + ) + ledger = AgentExecutionLedger( + graph_id=plan.graph_id, + plan_sha256=_plan_sha256(plan), + started_unix=time.time(), + max_concurrent_agent_runs=plan.max_concurrent_agent_runs, + records=records, + ) + _persist_ledger(ledger_path, ledger) + semaphore = asyncio.Semaphore(plan.max_concurrent_agent_runs) + resource_semaphores = { + name: asyncio.Semaphore(resource.slots) + for name, resource in policy.resource_classes.items() + } + record_lock = asyncio.Lock() + active = 0 + + async def run_one(task: AgentExecutionTask) -> None: + nonlocal active + record = records[task.task_id] + if record.status == "reused": + return + handler = handlers.get(task.role) + if handler is None: + raise KeyError(f"no Agent handler registered for role {task.role}") + retry = policy.api + resource_semaphore = resource_semaphores.get(task.resource_class) + if resource_semaphore is None: + resource_semaphore = asyncio.Semaphore(plan.max_concurrent_agent_runs) + async with semaphore, resource_semaphore: + async with record_lock: + active += 1 + ledger.max_observed_concurrency = max(ledger.max_observed_concurrency, active) + record.status = "running" + record.started_unix = time.time() + resource_policy = policy.resource_classes.get(task.resource_class) + record.resource_lease = { + "resource_class": task.resource_class, + "kind": resource_policy.kind if resource_policy else "unclassified", + "slot_limit": ( + resource_policy.slots if resource_policy else plan.max_concurrent_agent_runs + ), + } + _persist_ledger(ledger_path, ledger) + try: + last_error: BaseException | None = None + for attempt in range(retry.max_retries + 1): + record.attempt_count = attempt + 1 + try: + value = handler(task, context) + if inspect.isawaitable(value): + timeout_s = ( + policy.agents[task.role].timeout_s + if task.role in policy.agents + else 900.0 + ) + result = await asyncio.wait_for(value, timeout=timeout_s) + else: + result = value + record.result = result + global_quality_rejection = ( + task.role is AgentRole.GLOBAL_CRITIC and result.critic_score is not None + ) + if ( + not result.accepted or not result.hard_gates_passed + ) and not global_quality_rejection: + signature = result.failure_signature or "agent_output_rejected" + record.result = result + raise AgentDecisionRejected( + f"task {task.task_id} rejected with signature {signature}" + ) + critic_threshold = policy.local_optimizer.critic_min_score + if task.role is AgentRole.GLOBAL_CRITIC: + configured_threshold = context.scene_payload.get( + "global_critic_threshold" + ) + if isinstance(configured_threshold, (int, float)) and not isinstance( + configured_threshold, bool + ): + critic_threshold = float(configured_threshold) + if task.role in {AgentRole.LOCAL_CRITIC, AgentRole.GLOBAL_CRITIC} and ( + result.critic_score is None + or result.critic_score < critic_threshold + ): + signature = ( + "critic_score_missing" + if result.critic_score is None + else f"critic_below_threshold:{result.critic_score}" + ) + record.result = result.model_copy( + update={ + "accepted": False, + "hard_gates_passed": False, + "failure_signature": signature, + } + ) + result = record.result + if task.role is not AgentRole.GLOBAL_CRITIC: + raise AgentDecisionRejected( + f"task {task.task_id} critic score " + f"{result.critic_score} is missing or below " + f"{critic_threshold}" + ) + if result.resource_lease: + record.resource_lease.update(result.resource_lease) + record.output_sha256 = _json_sha256(result.model_dump(mode="json")) + record.status = "complete" + actual_started = result.metrics.get("actual_agent_started_unix") + actual_completed = result.metrics.get("actual_agent_completed_unix") + if isinstance(actual_started, (int, float)) and isinstance( + actual_completed, (int, float) + ): + record.started_unix = float(actual_started) + record.completed_unix = float(actual_completed) + else: + record.completed_unix = time.time() + record.duration_s = round( + record.completed_unix - (record.started_unix or 0.0), 6 + ) + _persist_checkpoint( + _checkpoint_path(context.output_root, task.task_id), record + ) + return + except BaseException as error: # noqa: BLE001 - persisted below + last_error = error + if ( + isinstance(error, (AgentDecisionRejected, RepeatedFailureSignature)) + or attempt >= retry.max_retries + ): + raise + delay = min( + retry.max_backoff_s, + retry.initial_backoff_s * (2**attempt), + ) + random.uniform(0, retry.jitter_s) + await asyncio.sleep(delay) + raise AssertionError(last_error) + except BaseException as error: # noqa: BLE001 - ledger is the audit authority + record.status = "failed" + record.completed_unix = time.time() + record.duration_s = round(record.completed_unix - (record.started_unix or 0.0), 6) + record.error = "".join(traceback.format_exception_only(type(error), error)).strip() + raise + finally: + async with record_lock: + active -= 1 + _persist_ledger(ledger_path, ledger) + + by_id = {task.task_id: task for task in plan.tasks} + pending = { + task.task_id + for task in plan.tasks + if records[task.task_id].status not in {"complete", "reused"} + } + running: dict[str, asyncio.Task[None]] = {} + failed = False + while pending or running: + ready = sorted( + task_id + for task_id in pending + if all( + records[dependency].status in {"complete", "reused"} + for dependency in by_id[task_id].depends_on + ) + ) + for task_id in ready: + pending.remove(task_id) + running[task_id] = asyncio.create_task( + run_one(by_id[task_id]), name=f"rhg-agent-{task_id}" + ) + if not running: + for task_id in pending: + records[task_id].status = "blocked" + records[task_id].error = "dependency failed or no ready task" + failed = bool(pending) + break + done, _ = await asyncio.wait(running.values(), return_when=asyncio.FIRST_COMPLETED) + for future in done: + task_id = next(key for key, value in running.items() if value is future) + del running[task_id] + try: + await future + except BaseException: # noqa: BLE001 - sibling subtrees may finish cleanly + failed = True + if failed: + failed_dependencies = { + task_id for task_id, record in records.items() if record.status == "failed" + } + for task_id in list(pending): + if any( + dependency in failed_dependencies or records[dependency].status == "blocked" + for dependency in by_id[task_id].depends_on + ): + records[task_id].status = "blocked" + records[task_id].error = "upstream Agent task failed" + pending.remove(task_id) + if running: + await asyncio.gather(*running.values(), return_exceptions=True) + ledger.completed_unix = time.time() + unique_intervals: dict[str, tuple[float, float]] = {} + for record in records.values(): + if record.started_unix is None or record.completed_unix is None: + continue + actual_ids = ( + str(record.result.metrics.get("actual_agent_run_ids", "")) + if record.result is not None + else "" + ) + keys = [value for value in actual_ids.split(",") if value] or [record.task_id] + for key in keys: + unique_intervals[key] = ( + float(record.started_unix), + float(record.completed_unix), + ) + events = sorted( + [(started, 1) for started, _ in unique_intervals.values()] + + [(completed, -1) for _, completed in unique_intervals.values()], + key=lambda item: (item[0], item[1]), + ) + interval_active = 0 + for _, delta in events: + interval_active += delta + ledger.max_observed_concurrency = max(ledger.max_observed_concurrency, interval_active) + ledger.status = ( + "failed" + if any(record.status in {"failed", "blocked"} for record in records.values()) + else "complete" + ) + _persist_ledger(ledger_path, ledger) + if ledger.status == "failed": + failures = { + task_id: record.error + for task_id, record in records.items() + if record.status in {"failed", "blocked"} + } + raise RuntimeError(f"Agent execution DAG failed: {failures}") + return ledger + + +def project_ledger_to_dependency_plan( + dependency_plan: dict[str, Any], + ledger: AgentExecutionLedger, +) -> dict[str, Any]: + """Project actual Agent evidence without manufacturing completion statuses.""" + + projected = dict(dependency_plan) + projected["agent_execution_ledger"] = "agent_execution_ledger.json" + projected["agent_execution_status"] = ledger.status + for task in projected.get("tasks", []): + task_id = str(task.get("task_id", "")) + node_id = str(task.get("node_id") or "") + if task_id == "compose:world": + candidates = [ledger.records["merge:world"]] if "merge:world" in ledger.records else [] + elif task_id.startswith("fit-local:"): + candidates = [ + record + for record in ledger.records.values() + if record.task_id.startswith(f"fit-local:{node_id}:to:") + ] + elif task_id.startswith("freeze:"): + candidates = [ + record + for record in ledger.records.values() + if record.task_id.startswith("freeze:") and node_id in record.owned_node_ids + ] + else: + candidates = [record for record in ledger.records.values() if record.task_id == task_id] + if not candidates: + task["status"] = "unmapped" + continue + statuses = {record.status for record in candidates} + task["status"] = ( + "failed" + if "failed" in statuses + else "blocked" + if "blocked" in statuses + else "complete" + if statuses <= {"complete", "reused"} + else "running" + if "running" in statuses + else "pending" + ) + task["agent_task_ids"] = [record.task_id for record in candidates] + task["evidence_sha256"] = [record.output_sha256 for record in candidates] + for branch in projected.get("branches", []): + node_ids = set(branch.get("node_ids") or []) + candidates = [ + record for record in ledger.records.values() if node_ids & set(record.owned_node_ids) + ] + branch["status"] = ( + "complete" + if candidates and all(record.status in {"complete", "reused"} for record in candidates) + else "failed" + if any(record.status in {"failed", "blocked"} for record in candidates) + else "pending" + ) + projected["status"] = ledger.status + projected["completed_unix"] = ledger.completed_unix + return projected diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/agent_orchestration.py b/docs/reproduction/public_conversion_code/packages/scene_generation/agent_orchestration.py new file mode 100644 index 0000000000000000000000000000000000000000..f442b26ddc1cedaf87ec52908cc005d2485a2e18 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/agent_orchestration.py @@ -0,0 +1,643 @@ +from __future__ import annotations + +import hashlib +import json +import os +from collections import defaultdict +from enum import StrEnum +from pathlib import Path +from typing import Any, Literal + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.scene_generation.dependency_graph import SceneDependencyGraph +from packages.robots.task_constraints import get_task_constraints + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class OrchestrationMode(StrEnum): + DAG_AGENTS = "dag_agents" + LEGACY = "legacy" + + +class AgentRole(StrEnum): + PLANNING = "planning" + DAG_ORCHESTRATOR = "dag_orchestrator" + GENERATION = "generation" + LOCAL_RELATION = "local_relation" + LOCAL_CRITIC = "local_critic" + GLOBAL_CRITIC = "global_critic" + ANALYTIC = "analytic" + + +class AgentModelPolicy(_StrictModel): + model: str = "gpt-6-astra" + reasoning_effort: Literal["low", "medium", "high", "xhigh"] = "medium" + max_turns: int = Field(default=10, ge=1) + timeout_s: float = Field(default=900.0, gt=0) + + +class ApiRetryPolicy(_StrictModel): + max_retries: int = Field(default=3, ge=0) + initial_backoff_s: float = Field(default=1.0, ge=0) + max_backoff_s: float = Field(default=20.0, ge=0) + jitter_s: float = Field(default=0.5, ge=0) + + +class CuroboPolicy(_StrictModel): + mode: Literal["auto", "disabled", "required"] = "auto" + fallback: Literal["analytic_drake", "fail"] = "analytic_drake" + min_free_vram_mb: int = Field(default=16384, ge=0) + max_gpu_utilization_percent: int = Field(default=70, ge=0, le=100) + lease_timeout_s: float = Field(default=30.0, ge=0) + + +class DeterministicPlacementPolicy(_StrictModel): + enabled: bool = True + room_containment_tolerance_m: float = Field(default=0.003, ge=0) + floor_gap_m: float = Field(default=0.005, ge=0) + penetration_tolerance_m: float = Field(default=0.003, ge=0) + free_wall_clearance_m: float = Field(default=0.03, ge=0) + against_wall_gap_m: float = Field(default=0.01, ge=0) + candidate_grid_m: float = Field(default=0.05, gt=0) + narrow_phase_finalists: int = Field(default=32, ge=1) + maximum_task_support_height_m: float = Field( + default_factory=lambda: get_task_constraints()["support_height_range_m"][1], gt=0) + task_asset_policy: Literal["reselect"] = "reselect" + optional_asset_policy: Literal["drop"] = "drop" + allow_solver_scaling: Literal[False] = False + + +class LocalOptimizerPolicy(_StrictModel): + broad_phase: Literal["cluster_aabb"] = "cluster_aabb" + narrow_phase: Literal["drake_signed_distance", "mesh_distance"] = ( + "drake_signed_distance" + ) + support_max_gap_m: float = Field(default=0.005, ge=0) + support_max_penetration_m: float = Field(default=0.003, ge=0) + support_minimum_coverage: float = Field(default=0.8, ge=0, le=1) + center_of_mass_margin_m: float = Field(default=0.01, ge=0) + critic_min_score: float = Field(default=6.5, ge=0, le=10) + required_views: list[Literal["top", "task_side", "oblique"]] = Field( + default_factory=lambda: ["top", "task_side", "oblique"] + ) + required_pbr_channels: list[str] = Field( + default_factory=lambda: ["albedo", "roughness", "metallic", "normal"] + ) + optional_pbr_channels: list[str] = Field(default_factory=lambda: ["height", "ao"]) + curobo: CuroboPolicy = Field(default_factory=CuroboPolicy) + deterministic_placement: DeterministicPlacementPolicy = Field( + default_factory=DeterministicPlacementPolicy + ) + + +class ResourceClassPolicy(_StrictModel): + kind: Literal["cpu", "gpu", "llm", "mixed"] + slots: int = Field(default=1, ge=1) + + +class AgentOrchestrationPolicy(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + mode: OrchestrationMode = OrchestrationMode.DAG_AGENTS + partition: Literal["hybrid_subtree"] = "hybrid_subtree" + max_concurrent_agent_runs: int | Literal["auto"] = 8 + local_repair_rounds: int = Field(default=1, ge=0) + same_failure_signature_limit: int = Field(default=2, ge=1) + planning_failure_fallback: Literal["fail", "legacy"] = "fail" + api: ApiRetryPolicy = Field(default_factory=ApiRetryPolicy) + agents: dict[AgentRole, AgentModelPolicy] + local_optimizer: LocalOptimizerPolicy = Field(default_factory=LocalOptimizerPolicy) + resource_classes: dict[str, ResourceClassPolicy] = Field(default_factory=dict) + + @model_validator(mode="after") + def validate_agent_roles(self) -> AgentOrchestrationPolicy: + required = { + AgentRole.PLANNING, + AgentRole.DAG_ORCHESTRATOR, + AgentRole.GENERATION, + AgentRole.LOCAL_RELATION, + AgentRole.LOCAL_CRITIC, + AgentRole.GLOBAL_CRITIC, + } + missing = required - set(self.agents) + if missing: + raise ValueError(f"agent policies missing roles: {sorted(missing)}") + return self + + def concurrency(self) -> int: + if self.max_concurrent_agent_runs != "auto": + return self.max_concurrent_agent_runs + return max(1, min(8, max(1, (os.cpu_count() or 1) // 8))) + + +DEFAULT_AGENT_ORCHESTRATION_POLICY = ( + Path(__file__).resolve().parents[2] + / "configs" + / "scene_generation" + / "agent_orchestration_v1.yaml" +) + + +def load_agent_orchestration_policy( + path: Path | None = None, + *, + overrides: dict[str, Any] | None = None, +) -> AgentOrchestrationPolicy: + selected = path or Path( + os.environ.get( + "RHG_AGENT_ORCHESTRATION_POLICY", DEFAULT_AGENT_ORCHESTRATION_POLICY + ) + ) + payload = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8")) + overrides = overrides or {} + allowed = { + "mode", + "max_concurrent_agent_runs", + "local_detail_profile", + "deterministic_placement_enabled", + } + unknown = set(overrides) - allowed + if unknown: + raise ValueError(f"unsupported agent_orchestration overrides: {sorted(unknown)}") + payload.update( + { + key: value + for key, value in overrides.items() + if key not in {"local_detail_profile", "deterministic_placement_enabled"} + } + ) + if "deterministic_placement_enabled" in overrides: + payload["local_optimizer"]["deterministic_placement"]["enabled"] = bool( + overrides["deterministic_placement_enabled"] + ) + if overrides.get("local_detail_profile", "full") != "full": + raise ValueError("only local_detail_profile=full is supported in schema 1.0") + return AgentOrchestrationPolicy.model_validate(payload) + + +class PlanningSubtree(_StrictModel): + subtree_id: str = Field(pattern=r"^[a-z0-9][a-z0-9_.-]*$") + root_node_id: str + node_ids: list[str] = Field(min_length=1) + motif: str + critical: bool = True + hard_constraints: list[str] = Field(default_factory=list) + + +class PlanningAgentOutput(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + graph_id: str + entity_ids: list[str] + subtrees: list[PlanningSubtree] + cross_subtree_constraints: list[str] = Field(default_factory=list) + planner_model: str + reasoning_effort: Literal["high"] = "high" + source: Literal["agent", "deterministic_fallback"] = "agent" + trace_id: str | None = None + + @model_validator(mode="after") + def validate_partition(self) -> PlanningAgentOutput: + flattened = [node for subtree in self.subtrees for node in subtree.node_ids] + duplicates = {node for node in flattened if flattened.count(node) > 1} + if duplicates: + raise ValueError(f"nodes assigned to multiple subtrees: {sorted(duplicates)}") + return self + + +class AgentExecutionTask(_StrictModel): + task_id: str + role: AgentRole + subtree_id: str | None = None + node_id: str | None = None + parent_id: str | None = None + depends_on: list[str] = Field(default_factory=list) + resource_class: str + owned_node_ids: list[str] = Field(default_factory=list) + preserves_local_subtree: bool = False + model: str | None = None + reasoning_effort: Literal["low", "medium", "high", "xhigh"] | None = None + max_turns: int | None = None + + +class AgentExecutionPlan(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + graph_id: str + planning_sha256: str + mode: Literal["dag_agents"] = "dag_agents" + tasks: list[AgentExecutionTask] + max_concurrent_agent_runs: int = Field(ge=1) + + @model_validator(mode="after") + def validate_dependencies(self) -> AgentExecutionPlan: + task_ids = [task.task_id for task in self.tasks] + if len(task_ids) != len(set(task_ids)): + raise ValueError("agent execution task IDs must be unique") + known = set(task_ids) + missing = { + dependency + for task in self.tasks + for dependency in task.depends_on + if dependency not in known + } + if missing: + raise ValueError(f"agent execution plan references missing tasks: {sorted(missing)}") + completed: set[str] = set() + remaining = {task.task_id: set(task.depends_on) for task in self.tasks} + while remaining: + ready = {task_id for task_id, deps in remaining.items() if deps <= completed} + if not ready: + raise ValueError(f"agent execution plan contains a cycle: {sorted(remaining)}") + completed.update(ready) + for task_id in ready: + del remaining[task_id] + return self + + +def _safe_id(value: str) -> str: + return "".join(char if char.isalnum() or char in "_.-" else "-" for char in value) + + +def _matching_set_nodes(graph: SceneDependencyGraph) -> dict[str, set[str]]: + """Return declarative repeated-instance motifs from immutable graph metadata.""" + + groups: dict[str, set[str]] = defaultdict(set) + for node in graph.nodes: + attributes = node.metadata.get("attributes") if isinstance(node.metadata, dict) else None + if not isinstance(attributes, dict): + continue + group = str(attributes.get("matching_set") or "").strip() + if group and node.entity_id: + groups[group].add(node.node_id) + return {group: nodes for group, nodes in groups.items() if len(nodes) >= 2} + + +def _semantic_motif_nodes(graph: SceneDependencyGraph) -> dict[str, set[str]]: + groups: dict[str, set[str]] = defaultdict(set) + for node in graph.nodes: + attributes = node.metadata.get("attributes") if isinstance(node.metadata, dict) else None + if not isinstance(attributes, dict): + continue + motif = str(attributes.get("semantic_motif") or "").strip() + if motif and node.entity_id: + groups[motif].add(node.node_id) + return {motif: nodes for motif, nodes in groups.items() if len(nodes) >= 2} + + +def deterministic_planning_output( + graph: SceneDependencyGraph, + policy: AgentOrchestrationPolicy, +) -> PlanningAgentOutput: + """Create the validated fallback/seed partition that constrains the Planning Agent.""" + + architecture = {node.node_id for node in graph.nodes if node.kind == "architecture"} + subtrees = [ + PlanningSubtree( + subtree_id="architecture", + root_node_id="room_shell" if "room_shell" in architecture else sorted(architecture)[0], + node_ids=sorted(architecture), + motif="room_architecture", + critical=True, + hard_constraints=["preserve metric room-local frame"], + ) + ] + matching_sets = _matching_set_nodes(graph) + semantic_motifs = _semantic_motif_nodes(graph) + matched_nodes: set[str] = set() + node_by_id = {node.node_id: node for node in graph.nodes} + branch_by_node = { + node_id: branch + for branch in graph.branches + for node_id in branch.node_ids + if node_id not in architecture + } + def add_motif_subtree( + motif_label: str, + group: str, + member_nodes: set[str], + motif_constraint: str, + ) -> None: + if member_nodes & matched_nodes: + overlap = sorted(member_nodes & matched_nodes) + raise ValueError( + f"entities cannot belong to overlapping planning motifs: {overlap}" + ) + # Include descendants owned by each repeated support so one motif Agent + # can preserve their local coordinates and reuse the shared canonical + # asset preparation. A node may only belong to one immutable branch. + owned = sorted( + { + node_id + for member in member_nodes + for node_id in branch_by_node[member].node_ids + if node_id not in architecture + } + ) + matched_nodes.update(owned) + subtrees.append( + PlanningSubtree( + subtree_id=f"motif-{_safe_id(group)}", + root_node_id=sorted(member_nodes)[0], + node_ids=owned, + motif=motif_label, + critical=any(branch_by_node[member].critical for member in member_nodes), + hard_constraints=[ + "owned_delta_only", + "preserve_child_local_transforms", + motif_constraint, + ], + ) + ) + + # Repeated canonical instances have the stronger ownership requirement, so + # freeze those complete dependency branches before considering broader + # semantic motifs. Building both lists eagerly made matched_nodes appear + # empty to the semantic filter and assigned dining sets twice. + for group, member_nodes in sorted(matching_sets.items()): + add_motif_subtree( + f"matching_set:{group}", + group, + member_nodes, + "reuse_one_canonical_asset_for_matching_set", + ) + for motif, member_nodes in sorted(semantic_motifs.items()): + if member_nodes & matched_nodes: + continue + add_motif_subtree( + f"semantic_motif:{motif}", + motif, + member_nodes, + "compose_coherent_functional_cluster", + ) + for branch in graph.branches: + nodes = sorted(node_id for node_id in branch.node_ids if node_id not in architecture) + if not nodes or set(nodes) <= matched_nodes: + continue + root = node_by_id[branch.root_node_id] + motif = "support_subtree" if any( + node_by_id[node].stage == "manipulation" for node in nodes + ) else f"{root.stage}_motif" + subtrees.append( + PlanningSubtree( + subtree_id=_safe_id(branch.branch_id), + root_node_id=branch.root_node_id, + node_ids=nodes, + motif=motif, + critical=branch.critical, + hard_constraints=["owned_delta_only", "preserve_child_local_transforms"], + ) + ) + return PlanningAgentOutput( + graph_id=graph.graph_id, + entity_ids=sorted( + node.entity_id for node in graph.nodes if node.entity_id is not None + ), + subtrees=subtrees, + planner_model=policy.agents[AgentRole.PLANNING].model, + reasoning_effort="high", + source="deterministic_fallback", + ) + + +def validate_planning_output( + graph: SceneDependencyGraph, + output: PlanningAgentOutput, +) -> PlanningAgentOutput: + known = {node.node_id for node in graph.nodes} + expected_entities = sorted( + node.entity_id for node in graph.nodes if node.entity_id is not None + ) + if output.graph_id != graph.graph_id: + raise ValueError("Planning Agent changed graph_id") + if sorted(output.entity_ids) != expected_entities: + raise ValueError("Planning Agent changed the immutable task entity set") + assigned = {node for subtree in output.subtrees for node in subtree.node_ids} + if assigned != known: + raise ValueError( + "Planning Agent partition must cover the graph exactly; " + f"missing={sorted(known - assigned)} foreign={sorted(assigned - known)}" + ) + for subtree in output.subtrees: + if subtree.root_node_id not in subtree.node_ids: + raise ValueError(f"subtree {subtree.subtree_id} root is not owned by the subtree") + owner = { + node_id: subtree.subtree_id + for subtree in output.subtrees + for node_id in subtree.node_ids + } + architecture = {node.node_id for node in graph.nodes if node.kind == "architecture"} + architecture_owners = {owner[node_id] for node_id in architecture} + if len(architecture_owners) != 1: + raise ValueError("architecture nodes must remain in one initial barrier subtree") + architecture_owner = next(iter(architecture_owners)) + if any( + node_id not in architecture and owner[node_id] == architecture_owner + for node_id in known + ): + raise ValueError("the architecture barrier cannot own generated entity nodes") + for node in graph.nodes: + for parent_id in node.depends_on: + if parent_id in architecture: + continue + if owner[node.node_id] != owner[parent_id]: + raise ValueError( + "support dependency cannot cross ownership subtrees: " + f"{node.node_id} -> {parent_id}" + ) + for group, members in _matching_set_nodes(graph).items(): + matching_owners = {owner[node_id] for node_id in members} + if len(matching_owners) != 1: + raise ValueError( + f"matching_set {group} must remain in one motif ownership subtree" + ) + for motif, members in _semantic_motif_nodes(graph).items(): + motif_owners = {owner[node_id] for node_id in members} + if len(motif_owners) != 1: + raise ValueError( + f"semantic_motif {motif} must remain in one functional ownership subtree" + ) + return output + + +def _planning_hash(output: PlanningAgentOutput) -> str: + payload = json.dumps(output.model_dump(mode="json"), sort_keys=True).encode() + return hashlib.sha256(payload).hexdigest() + + +def build_agent_execution_plan( + graph: SceneDependencyGraph, + planning: PlanningAgentOutput, + policy: AgentOrchestrationPolicy, +) -> AgentExecutionPlan: + validate_planning_output(graph, planning) + nodes = {node.node_id: node for node in graph.nodes} + subtree_by_node = { + node_id: subtree + for subtree in planning.subtrees + for node_id in subtree.node_ids + } + architecture_subtree_id = next( + subtree.subtree_id + for subtree in planning.subtrees + if any(nodes[node_id].kind == "architecture" for node_id in subtree.node_ids) + ) + tasks: list[AgentExecutionTask] = [] + for node in graph.nodes: + subtree = subtree_by_node[node.node_id] + if node.kind == "architecture" or node.execution in {"analytic", "native_usd", "external"}: + role = AgentRole.ANALYTIC + model_policy = None + else: + role = AgentRole.GENERATION + model_policy = policy.agents[role] + generation_dependencies = ( + [f"freeze:{architecture_subtree_id}"] + if node.kind != "architecture" + else [ + f"generate:{parent}" + for parent in node.depends_on + if nodes[parent].kind == "architecture" + ] + ) + tasks.append( + AgentExecutionTask( + task_id=f"generate:{node.node_id}", + role=role, + subtree_id=subtree.subtree_id, + node_id=node.node_id, + depends_on=generation_dependencies, + resource_class=graph.scheduler.resource_class_by_stage[node.stage], + owned_node_ids=[node.node_id], + model=model_policy.model if model_policy else None, + reasoning_effort=model_policy.reasoning_effort if model_policy else None, + max_turns=model_policy.max_turns if model_policy else None, + ) + ) + relation_ids_by_subtree: dict[str, list[str]] = defaultdict(list) + for node in graph.nodes: + subtree = subtree_by_node[node.node_id] + for parent in node.depends_on: + task_id = f"fit-local:{node.node_id}:to:{parent}" + relation_ids_by_subtree[subtree.subtree_id].append(task_id) + relation_role = ( + AgentRole.ANALYTIC + if node.kind == "architecture" or node.execution == "native_usd" + else AgentRole.LOCAL_RELATION + ) + model_policy = ( + policy.agents[AgentRole.LOCAL_RELATION] + if relation_role is AgentRole.LOCAL_RELATION + else None + ) + tasks.append( + AgentExecutionTask( + task_id=task_id, + role=relation_role, + subtree_id=subtree.subtree_id, + node_id=node.node_id, + parent_id=parent, + depends_on=[f"generate:{parent}", f"generate:{node.node_id}"], + resource_class="local_relation", + owned_node_ids=[node.node_id], + preserves_local_subtree=True, + model=model_policy.model if model_policy else None, + reasoning_effort=model_policy.reasoning_effort if model_policy else None, + max_turns=model_policy.max_turns if model_policy else None, + ) + ) + freeze_ids: list[str] = [] + for subtree in planning.subtrees: + prerequisites = relation_ids_by_subtree[subtree.subtree_id] or [ + f"generate:{node_id}" for node_id in subtree.node_ids + ] + freeze_id = f"freeze:{subtree.subtree_id}" + if subtree.subtree_id == "architecture": + # The room shell is the initial deterministic barrier. Its topology, + # dimensions and connectivity are checked by the floor-plan tools; an + # extra LLM critic here would add cost without owning a visual subtree. + tasks.append( + AgentExecutionTask( + task_id=freeze_id, + role=AgentRole.ANALYTIC, + subtree_id=subtree.subtree_id, + depends_on=sorted(prerequisites), + resource_class="cpu_postprocess", + owned_node_ids=subtree.node_ids, + preserves_local_subtree=True, + ) + ) + else: + critic_policy = policy.agents[AgentRole.LOCAL_CRITIC] + critic_id = f"local-critic:{subtree.subtree_id}" + tasks.extend([ + AgentExecutionTask( + task_id=critic_id, + role=AgentRole.LOCAL_CRITIC, + subtree_id=subtree.subtree_id, + depends_on=sorted(prerequisites), + resource_class="local_critic", + owned_node_ids=subtree.node_ids, + model=critic_policy.model, + reasoning_effort=critic_policy.reasoning_effort, + max_turns=critic_policy.max_turns, + ), + AgentExecutionTask( + task_id=freeze_id, + role=AgentRole.ANALYTIC, + subtree_id=subtree.subtree_id, + depends_on=[critic_id], + resource_class="cpu_postprocess", + owned_node_ids=subtree.node_ids, + preserves_local_subtree=True, + ), + ]) + freeze_ids.append(freeze_id) + tasks.append( + AgentExecutionTask( + task_id="merge:world", + role=AgentRole.DAG_ORCHESTRATOR, + depends_on=sorted(freeze_ids), + resource_class="cpu_postprocess", + owned_node_ids=sorted(nodes), + model=policy.agents[AgentRole.DAG_ORCHESTRATOR].model, + reasoning_effort=policy.agents[AgentRole.DAG_ORCHESTRATOR].reasoning_effort, + max_turns=policy.agents[AgentRole.DAG_ORCHESTRATOR].max_turns, + ) + ) + global_policy = policy.agents[AgentRole.GLOBAL_CRITIC] + tasks.append( + AgentExecutionTask( + task_id="global-critic:scene", + role=AgentRole.GLOBAL_CRITIC, + depends_on=["merge:world"], + resource_class="local_critic", + owned_node_ids=sorted(nodes), + model=global_policy.model, + reasoning_effort=global_policy.reasoning_effort, + max_turns=global_policy.max_turns, + ) + ) + return AgentExecutionPlan( + graph_id=graph.graph_id, + planning_sha256=_planning_hash(planning), + tasks=tasks, + max_concurrent_agent_runs=policy.concurrency(), + ) + + +def resolve_orchestration_mode( + context_config: dict[str, Any], + *, + resuming_legacy_checkpoint: bool, +) -> tuple[AgentOrchestrationPolicy, dict[str, Any]]: + overrides = context_config.get("agent_orchestration") or {} + if not isinstance(overrides, dict): + raise ValueError("scene_config.agent_orchestration must be an object") + explicit = "mode" in overrides + if resuming_legacy_checkpoint and not explicit: + overrides = {**overrides, "mode": "legacy"} + policy = load_agent_orchestration_policy(overrides=overrides) + return policy, overrides diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/agent_runtime.py b/docs/reproduction/public_conversion_code/packages/scene_generation/agent_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..1d872a2f8d8259348df9bf21d33b3ae69cc203e8 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/agent_runtime.py @@ -0,0 +1,528 @@ +from __future__ import annotations + +import base64 +import inspect +import json +import os +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +from packages.core.files import atomic_write_text +from packages.scene_generation.agent_executor import ( + AgentRuntimeContext, + AgentTaskResult, +) +from packages.scene_generation.agent_orchestration import ( + AgentExecutionTask, + AgentOrchestrationPolicy, + AgentRole, + PlanningAgentOutput, + deterministic_planning_output, + validate_planning_output, +) +from packages.scene_generation.dependency_graph import SceneDependencyGraph + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class StructuredAgentOutput(_StrictModel): + accepted: bool + summary: str + hard_gates_passed: bool = True + critic_score: float | None = Field(default=None, ge=0, le=10) + failure_signature: str | None = None + constraints: list[str] = Field(default_factory=list) + proposed_local_transform: dict[str, Any] | None = None + violations: list[str] = Field(default_factory=list) + repair_directive: dict[str, Any] | None = None + + +ROLE_INSTRUCTIONS: dict[AgentRole, str] = { + AgentRole.GENERATION: ( + "Select or generate only the owned canonical assets. Preserve immutable entity IDs, " + "metric scale, PBR materials, collision suitability, and write no foreign subtree state." + ), + AgentRole.LOCAL_RELATION: ( + "Audit only the declared child-to-parent relation against the supplied deterministic " + "placement certificate and metric scene payload. The deterministic solver has already " + "authored the transform: do not invent or propose a different transform, and do not " + "claim an unapplied movement occurred. Accept a passed certificate unless a supplied, " + "in-scope structured semantic constraint is measurably violated. Do not audit cross-subtree " + "constraints omitted from this local payload, and do not replace an exact certificate " + "measurement with an approximate axis-aligned bbox estimate. Preserve frozen descendants." + ), + AgentRole.LOCAL_CRITIC: ( + "Independently judge the owned subtree using the supplied analytic certificate and local " + "views. Reject floating, penetration, unstable contact, wrong identity, scale, PBR, or " + "unreachable task geometry. A deterministic placement certificate plus a collision-backed " + "inferred or authored support surface is sufficient static-support evidence; require a " + "simulation physics certificate only for manipulated rigid bodies. Do not request an " + "unapplied transform. Other parallel furniture subtrees are intentionally absent from " + "local views: never penalize the owned subtree for missing foreign entities, global room " + "completeness, or relationships owned by another subtree. Return a numeric critic_score " + "for the owned subtree. A score below the configured threshold is a rejection." + ), + AgentRole.DAG_ORCHESTRATOR: ( + "Audit only the supplied deterministic merge evidence: content hashes, ownership, frozen " + "dependency checkpoints, and the world-geometry certificate. Do not require global-critic, " + "robot-route, preview, portable-package, or major artifacts because those are downstream of " + "this merge task. Do not propose geometry, scaling, semantic, or layout changes here. Reject " + "only a measurable merge-provenance or ownership violation in the supplied evidence." + ), + AgentRole.GLOBAL_CRITIC: ( + "Judge the merged scene for cross-subtree collision, task semantics, robot circulation, " + "asset identity, visual coherence, domain completeness, asset detail, PBR material realism, " + "and available physics evidence. Score geometry/contact, task clarity/circulation, " + "room-domain completeness, asset shape/detail fidelity, material/texture realism, and " + "lighting/composition independently; critic_score must equal the lowest dimension, not an " + "average. Upstream branch scores are provenance only and must not override defects visible " + "in the final views. Reject an empty or showroom-like room containing only isolated task " + "anchors when the prompt requests a functional kitchen, workshop, bar, or similar domain. " + "Reject blank placeholder panels, repeated low-detail boxes, stretched or missing textures, " + "flat indistinguishable materials, weak contact shadows, missing required domain fixtures, " + "or final views that do not make task-critical entities recognizable. Put stable affected " + "entity IDs in repair_directive.entities when known so checkpoint repair stays local. Audit " + "only artifacts declared available in the supplied deterministic evidence. The configured " + "release threshold is scene_payload.global_critic_threshold; set accepted and " + "hard_gates_passed true whenever the lowest score meets that threshold and no severe " + "failure exists. Do not silently apply an older 7.5 threshold. Do not require " + "preview, major, portable-package, or final robot-runtime certificates that are produced " + "after this task." + ), +} + + +def _agents_sdk() -> tuple[Any, Any, Any]: + try: + from agents import ( + Agent, + ModelSettings, + RunConfig, + Runner, + set_default_openai_api, + trace, + ) + except ImportError as error: # pragma: no cover - core dev env intentionally excludes SDK + raise RuntimeError( + "dag_agents mode requires the SceneSmith runtime with openai-agents installed" + ) from error + agents_api = os.environ.get("RHG_OPENAI_AGENTS_API", "responses").strip().lower() + if agents_api == "chat_completions": + set_default_openai_api("chat_completions") + elif agents_api != "responses": + raise ValueError( + "RHG_OPENAI_AGENTS_API must be 'responses' or 'chat_completions'" + ) + return Agent, ModelSettings, (RunConfig, Runner, trace) + + +def _compatible_output_schema(output_type: type[BaseModel]) -> Any: + """Allow mapping-valued fields with Agents SDK strict structured outputs. + + ``StructuredAgentOutput`` intentionally carries extensible transform and repair + mappings. Those cannot be represented by the SDK's strict JSON-schema subset, + so make the relaxation explicit instead of failing every DAG role at startup. + Pydantic still validates the returned value before it is persisted. + """ + + try: + from agents import AgentOutputSchema + except ImportError as error: # pragma: no cover - guarded by _agents_sdk in runtime + raise RuntimeError( + "dag_agents mode requires AgentOutputSchema from openai-agents" + ) from error + return AgentOutputSchema(output_type, strict_json_schema=False) + + +async def run_planning_agent( + graph: SceneDependencyGraph, + policy: AgentOrchestrationPolicy, + *, + output_path: Path, + design_prompt: str | None = None, + blueprint_path: Path | None = None, + blueprint_analysis: dict[str, Any] | None = None, +) -> PlanningAgentOutput: + """Run the high-reasoning planner with a deterministic, immutable partition seed.""" + + Agent, ModelSettings, runtime = _agents_sdk() + RunConfig, Runner, trace = runtime + seed = deterministic_planning_output(graph, policy) + model_policy = policy.agents[AgentRole.PLANNING] + agent = Agent( + name="RoboHouseGen Planning Agent", + model=model_policy.model, + model_settings=ModelSettings( + reasoning={"effort": model_policy.reasoning_effort}, + parallel_tool_calls=True, + ), + output_type=PlanningAgentOutput, + instructions=( + "Partition the immutable scene dependency graph into hybrid support/motif subtrees. " + "You may improve motif labels and hard constraints, but must preserve graph_id, every " + "entity ID, every graph node exactly once, dependency semantics, and subtree " + "ownership. Entities sharing attributes.matching_set are one repeated-instance motif " + "and must remain together in the seeded motif subtree; do not split them into one " + "Agent session per instance. Entities sharing attributes.semantic_motif are one " + "functional cluster and must also remain in one seeded subtree. " + "Return only the structured output." + ), + ) + planning_text = ( + "Immutable graph:\n" + + graph.model_dump_json(indent=2) + + "\nValidated partition seed:\n" + + seed.model_dump_json(indent=2) + ) + if design_prompt is not None or blueprint_analysis is not None: + planning_text += ( + "\nFrozen top-level design context. Use it to refine constraints and motif labels; " + "it does not authorize any graph topology change.\n" + + json.dumps( + { + "original_prompt": design_prompt, + "blueprint_analysis": blueprint_analysis, + }, + ensure_ascii=False, + sort_keys=True, + ) + ) + planning_input: str | list[dict[str, Any]] = planning_text + if blueprint_path is not None: + suffix = blueprint_path.suffix.casefold() + mime_type = "image/png" if suffix == ".png" else "image/jpeg" + image_url = ( + f"data:{mime_type};base64," + + base64.b64encode(blueprint_path.read_bytes()).decode("ascii") + ) + planning_input = [ + { + "role": "user", + "content": [ + {"type": "input_text", "text": planning_text}, + { + "type": "input_image", + "image_url": image_url, + "detail": "high", + }, + ], + } + ] + with trace( + "RoboHouseGen Planning Agent", + metadata={"graph_id": graph.graph_id, "role": "planning"}, + ) as workflow_trace: + result = await Runner.run( + agent, + input=planning_input, + max_turns=model_policy.max_turns, + run_config=RunConfig( + workflow_name="RoboHouseGen Planning Agent", + trace_include_sensitive_data=False, + trace_metadata={"graph_id": graph.graph_id, "role": "planning"}, + ), + ) + output = result.final_output + if not isinstance(output, PlanningAgentOutput): + output = PlanningAgentOutput.model_validate(output) + output = output.model_copy( + update={ + "planner_model": model_policy.model, + "reasoning_effort": "high", + "source": "agent", + "trace_id": workflow_trace.trace_id, + } + ) + validate_planning_output(graph, output) + atomic_write_text(output_path, output.model_dump_json(indent=2) + "\n") + return output + + +class OpenAIAgentRoleHandler: + """Independent Runner handler for one DAG task; no session is shared across tasks.""" + + def __init__(self, policy: AgentOrchestrationPolicy) -> None: + self.policy = policy + + @staticmethod + def _runner_input( + task: AgentExecutionTask, + context: AgentRuntimeContext, + ) -> str | list[dict[str, Any]]: + payload = json.dumps( + { + "task": task.model_dump(mode="json"), + "task_payload": context.task_payload, + "scene_payload": context.scene_payload, + }, + ensure_ascii=False, + sort_keys=True, + ) + if task.role not in {AgentRole.LOCAL_CRITIC, AgentRole.GLOBAL_CRITIC}: + return payload + if task.role is AgentRole.GLOBAL_CRITIC: + views = context.scene_payload.get("final_critic_views") or [] + else: + views = [] + evidence = context.scene_payload.get("deterministic_task_evidence") or {} + artifact_payloads = evidence.get("artifact_payloads") or {} + seen: set[Path] = set() + for artifact in artifact_payloads.values(): + if not isinstance(artifact, dict): + continue + for record in artifact.get("score_evidence") or []: + if not isinstance(record, dict) or not isinstance(record.get("path"), str): + continue + score_path = context.output_root / "upstream" / record["path"] + image_paths = sorted( + score_path.parent.glob("*.png"), + key=lambda path: ( + "top" not in path.name.casefold(), + "side" not in path.name.casefold(), + path.name, + ), + ) + for image_path in image_paths: + resolved = image_path.resolve() + if resolved in seen: + continue + seen.add(resolved) + views.append( + { + "path": resolved.relative_to(context.output_root.resolve()).as_posix() + } + ) + if len(views) >= 3: + break + if len(views) >= 3: + break + if len(views) >= 3: + break + content: list[dict[str, Any]] = [{"type": "input_text", "text": payload}] + output_root = context.output_root.resolve() + for record in views: + if not isinstance(record, dict) or not isinstance(record.get("path"), str): + continue + path = (context.output_root / record["path"]).resolve() + try: + path.relative_to(output_root) + except ValueError as error: + raise ValueError(f"critic view escapes output root: {path}") from error + if not path.is_file() or path.suffix.casefold() not in {".png", ".jpg", ".jpeg"}: + raise FileNotFoundError(f"missing final critic view: {path}") + media_type = "image/png" if path.suffix.casefold() == ".png" else "image/jpeg" + encoded = base64.b64encode(path.read_bytes()).decode("ascii") + content.append( + { + "type": "input_image", + "image_url": f"data:{media_type};base64,{encoded}", + "detail": "high", + } + ) + if len(content) == 1: + raise RuntimeError(f"{task.role.value} requires critic views") + return [{"role": "user", "content": content}] + + async def __call__( + self, + task: AgentExecutionTask, + context: AgentRuntimeContext, + ) -> AgentTaskResult: + if task.role == AgentRole.ANALYTIC: + raise ValueError("analytic tasks require deterministic tool handlers") + Agent, ModelSettings, runtime = _agents_sdk() + RunConfig, Runner, trace = runtime + model_policy = self.policy.agents[task.role] + agent = Agent( + name=f"RoboHouseGen {task.role.value} {task.task_id}", + model=model_policy.model, + model_settings=ModelSettings( + reasoning={"effort": model_policy.reasoning_effort}, + parallel_tool_calls=True, + ), + output_type=_compatible_output_schema(StructuredAgentOutput), + instructions=ROLE_INSTRUCTIONS[task.role], + ) + with trace( + f"RoboHouseGen {task.role.value}", + metadata={ + "task_id": task.task_id, + "subtree_id": task.subtree_id or "global", + }, + ) as workflow_trace: + result = await Runner.run( + agent, + input=self._runner_input(task, context), + max_turns=model_policy.max_turns, + run_config=RunConfig( + workflow_name=f"RoboHouseGen {task.role.value}", + trace_include_sensitive_data=False, + trace_metadata={ + "task_id": task.task_id, + "subtree_id": task.subtree_id or "global", + }, + ), + ) + output = result.final_output + if not isinstance(output, StructuredAgentOutput): + output = StructuredAgentOutput.model_validate(output) + artifact_dir = context.output_root / "agent_outputs" + artifact_dir.mkdir(parents=True, exist_ok=True) + artifact = artifact_dir / f"{task.task_id.replace(':', '__')}.json" + atomic_write_text(artifact, output.model_dump_json(indent=2) + "\n") + import hashlib + + relative = artifact.relative_to(context.output_root).as_posix() + usage = getattr(getattr(result, "context_wrapper", None), "usage", None) + return AgentTaskResult( + accepted=output.accepted, + summary=output.summary, + artifacts={relative: hashlib.sha256(artifact.read_bytes()).hexdigest()}, + critic_score=output.critic_score, + hard_gates_passed=output.hard_gates_passed, + failure_signature=output.failure_signature, + metrics={ + "violation_count": len(output.violations), + "llm_requests": int(getattr(usage, "requests", 0) or 0), + "input_tokens": int(getattr(usage, "input_tokens", 0) or 0), + "output_tokens": int(getattr(usage, "output_tokens", 0) or 0), + }, + trace_id=workflow_trace.trace_id, + ) + + +class EvidenceBoundAgentHandler: + """Require both an independent Agent decision and deterministic scene evidence.""" + + def __init__( + self, + policy: AgentOrchestrationPolicy, + evidence_handler: Callable[[AgentExecutionTask, AgentRuntimeContext], AgentTaskResult], + *, + agent_handler: Callable[ + [AgentExecutionTask, AgentRuntimeContext], AgentTaskResult | Any + ] + | None = None, + ) -> None: + self.agent = agent_handler or OpenAIAgentRoleHandler(policy) + self.evidence_handler = evidence_handler + + async def __call__( + self, + task: AgentExecutionTask, + context: AgentRuntimeContext, + ) -> AgentTaskResult: + evidence_result = self.evidence_handler(task, context) + if not evidence_result.accepted or not evidence_result.hard_gates_passed: + return evidence_result.model_copy( + update={ + "metrics": { + **evidence_result.metrics, + "deterministic_short_circuit": True, + "llm_requests": 0, + } + } + ) + + evidence_payloads: dict[str, Any] = {} + for relative in evidence_result.artifacts: + artifact = context.output_root / relative + if artifact.suffix != ".json" or not artifact.is_file(): + continue + try: + evidence_payloads[relative] = json.loads(artifact.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + audit_context = context.model_copy(deep=True) + if task.role in {AgentRole.LOCAL_RELATION, AgentRole.LOCAL_CRITIC}: + relevant_ids = { + value + for value in [task.node_id, task.parent_id, *task.owned_node_ids] + if value + } + constraints = audit_context.scene_payload.get("semantic_constraints") or [] + audit_context.scene_payload["semantic_constraints"] = [ + constraint + for constraint in constraints + if isinstance(constraint, dict) + and { + str(constraint.get("subject") or ""), + str(constraint.get("object") or ""), + } + <= relevant_ids + ] + world_certificate = audit_context.scene_payload.get( + "world_geometry_certificate" + ) + if isinstance(world_certificate, dict): + world_certificate["semantic_constraints"] = [ + constraint + for constraint in world_certificate.get("semantic_constraints") or [] + if isinstance(constraint, dict) + and { + str(constraint.get("subject") or ""), + str(constraint.get("object") or ""), + } + <= relevant_ids + ] + audit_context.scene_payload["deterministic_task_evidence"] = { + "result": evidence_result.model_dump(mode="json"), + "artifact_payloads": evidence_payloads, + "contract": ( + "This evidence was generated before the Agent audit and is authoritative for the " + "current DAG task. Do not require artifacts produced by downstream tasks. " + "Entities listed in downstream_physics_entity_ids intentionally receive rigid-body, " + "mass and convex-hull collision authoring in BenchmarkPackager after this DAG; " + "their missing upstream physics certificate is not a current-task failure." + ), + } + agent_value = self.agent(task, audit_context) + agent_result = await agent_value if inspect.isawaitable(agent_value) else agent_value + accepted = agent_result.accepted and evidence_result.accepted + hard_gates = agent_result.hard_gates_passed and evidence_result.hard_gates_passed + # The structured Agent can correctly describe acceptance at a per-case + # threshold yet an SDK coercion from an older prompt/schema may retain a + # stale rejection boolean. Reconcile only this narrow, auditable case. + configured_threshold = context.scene_payload.get("global_critic_threshold") + threshold_acceptance = bool( + task.role is AgentRole.GLOBAL_CRITIC + and isinstance(configured_threshold, (int, float)) + and agent_result.critic_score is not None + and agent_result.critic_score >= float(configured_threshold) + and evidence_result.accepted + and evidence_result.hard_gates_passed + and not agent_result.failure_signature + and agent_result.summary.lstrip().casefold().startswith("accepted") + ) + if threshold_acceptance: + accepted = True + hard_gates = True + artifacts = {**agent_result.artifacts, **evidence_result.artifacts} + scores = [ + value + for value in (evidence_result.critic_score, agent_result.critic_score) + if value is not None + ] + score = min(scores) if scores else None + signature = None if threshold_acceptance else ( + evidence_result.failure_signature or agent_result.failure_signature + ) + return AgentTaskResult( + accepted=accepted, + hard_gates_passed=hard_gates, + summary=f"Agent: {agent_result.summary}; deterministic gate: {evidence_result.summary}", + artifacts=artifacts, + metrics={ + **agent_result.metrics, + **evidence_result.metrics, + }, + critic_score=score, + failure_signature=signature, + resource_lease=agent_result.resource_lease, + trace_id=agent_result.trace_id, + ) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/asset_first.py b/docs/reproduction/public_conversion_code/packages/scene_generation/asset_first.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba1188a4ad9d4ac27249b5b9466db1fef83abbb --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/asset_first.py @@ -0,0 +1,1399 @@ +from __future__ import annotations + +import hashlib +import json +import math +from functools import lru_cache +from pathlib import Path +from typing import Any, Literal + +from PIL import Image, ImageDraw +from pydantic import BaseModel, ConfigDict, Field, model_validator +from shapely import affinity # type: ignore[import-untyped] +from shapely.geometry import LineString, Point, Polygon, box # type: ignore[import-untyped] +from shapely.ops import unary_union # type: ignore[import-untyped] + +from packages.asset_registry.certification_models import FrontConfidenceGrade +from packages.asset_registry.descriptors import AssetDescriptor, Point2 +from packages.asset_registry.front_certification import definition_for_category +from packages.asset_registry.front_policy import effective_functional_front_axis +from packages.asset_registry.release import load_active_descriptors +from packages.core.files import atomic_write_text +from packages.scene_generation.metric_layout import ( + MetricEntityLayout, + MetricKeepOutRegion, + MetricLayoutSpec, + MetricZone, + NaturalPerturbationPolicy, +) + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +@lru_cache(maxsize=4096) +def _sha256_file_cached(path_text: str, size: int, modified_ns: int) -> str: + del size, modified_ns + digest = hashlib.sha256() + with Path(path_text).open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _sha256_file(path: Path) -> str: + resolved = path.resolve() + stat = resolved.stat() + return _sha256_file_cached(str(resolved), stat.st_size, stat.st_mtime_ns) + + +def file_hash_cache_stats() -> dict[str, int]: + info = _sha256_file_cached.cache_info() + return { + "hits": info.hits, + "misses": info.misses, + "maxsize": int(info.maxsize or 0), + "currsize": info.currsize, + } + + +def clear_file_hash_cache() -> None: + _sha256_file_cached.cache_clear() + + +def _canonical_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + +class FurnitureAssetChoice(_StrictModel): + """The complete authority of the Furniture Agent in the v2 flow. + + Deliberately no XY, yaw, dimensions, scale, or footprint fields exist. The + strict model rejects attempts by an Agent to smuggle pose authority into the + frozen selection artifact. + """ + + entity_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + asset_id: str = Field(min_length=1) + zone_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + parent_entity_id: str | None = None + semantic_role: str = Field(min_length=1) + placement_preference: Literal[ + "zone_center", + "north_wall", + "south_wall", + "east_wall", + "west_wall", + "zone_east", + "zone_west", + "near_anchor", + ] = "zone_center" + near_entity_id: str | None = None + face_entity_id: str | None = None + near_distance_m: tuple[float, float] | None = None + relative_to_anchor: Literal[ + "north", + "south", + "east", + "west", + "north_east", + "north_west", + "south_east", + "south_west", + ] | None = None + functional_front_semantics: Literal[ + "seating_gaze", "bed_foot", "operation_side", "screen_normal" + ] | None = None + functional_front_axis: Literal["+X", "-X", "+Y", "-Y"] | None = None + functional_front_source: Literal[ + "geometry_backrest_verified", + "geometry_headboard_verified", + "multiview_geometry_consensus", + "multiview_affordance_consensus", + ] | None = None + functional_front_confidence: float | None = Field(default=None, ge=0.0, le=1.0) + functional_front_evidence: list[str] = Field(default_factory=list) + minimum_front_confidence_grade: FrontConfidenceGrade = FrontConfidenceGrade.HIGH + + @model_validator(mode="after") + def validate_relation(self) -> FurnitureAssetChoice: + if self.placement_preference == "near_anchor" and not self.near_entity_id: + raise ValueError("near_anchor requires near_entity_id") + if (self.near_distance_m or self.relative_to_anchor) and not self.near_entity_id: + raise ValueError("distance/relative constraints require near_entity_id") + if self.near_distance_m and ( + self.near_distance_m[0] < 0 + or self.near_distance_m[1] <= 0 + or self.near_distance_m[1] < self.near_distance_m[0] + ): + raise ValueError("near_distance_m must be an increasing non-negative range") + functional_values = ( + self.functional_front_semantics, + self.functional_front_axis, + self.functional_front_source, + self.functional_front_confidence, + ) + if any(value is not None for value in functional_values): + if not all(value is not None for value in functional_values): + raise ValueError("functional-front certificate fields must be complete") + if (self.functional_front_confidence or 0.0) < 0.85: + raise ValueError("functional-front confidence must be at least 0.85") + if not self.functional_front_evidence: + raise ValueError("functional-front certificate requires evidence") + if self.entity_id in { + self.near_entity_id, + self.parent_entity_id, + self.face_entity_id, + }: + raise ValueError("entity cannot depend on itself") + return self + + +class AssetSelectionSpec(_StrictModel): + schema_version: Literal["2.0"] = "2.0" + generated_by: Literal["Furniture Agent"] = "Furniture Agent" + pose_authority: Literal["none"] = "none" + descriptor_index: str + descriptor_index_sha256: str + choices: list[FurnitureAssetChoice] = Field(min_length=1) + + @model_validator(mode="after") + def validate_choices(self) -> AssetSelectionSpec: + entity_ids = [choice.entity_id for choice in self.choices] + if len(entity_ids) != len(set(entity_ids)): + raise ValueError("Furniture Agent emitted duplicate entity IDs") + known = set(entity_ids) + for choice in self.choices: + for reference in ( + choice.parent_entity_id, + choice.near_entity_id, + choice.face_entity_id, + ): + if reference and reference not in known: + raise ValueError(f"{choice.entity_id} references unknown entity {reference}") + return self + + +class AssetFirstZone(_StrictModel): + zone_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + polygon_xy_m: list[Point2] = Field(min_length=3) + + +class AssetFirstOpening(_StrictModel): + opening_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + kind: Literal["door", "window"] + wall: Literal["north", "south", "east", "west"] + center_m: float + width_m: float = Field(gt=0) + height_m: float = Field(gt=0) + sill_height_m: float = Field(default=0.0, ge=0) + door_hinge: Literal["left", "right"] = "left" + door_open_angle_deg: float = Field(default=32.0, ge=15.0, le=90.0) + keep_out_polygon_xy_m: list[Point2] = Field(min_length=3) + planning_only: bool = False + + +class AssetFirstRoomRequest(_StrictModel): + robot_id: str | None = None + robot_constraints_enabled: bool = True + task_object_entity_id: str | None = None + room_dimensions_m: tuple[float, float, float] + zones: list[AssetFirstZone] = Field(min_length=1) + openings: list[AssetFirstOpening] = Field(default_factory=list) + route_centerline_xy_m: list[Point2] = Field(min_length=2) + route_width_m: float = Field(default=1.2, ge=1.2) + robot_start_xy_m: Point2 + solver_grid_m: float = Field(default=0.1, gt=0, le=0.5) + + @model_validator(mode="after") + def validate_room(self) -> AssetFirstRoomRequest: + if any(not math.isfinite(value) or value <= 0 for value in self.room_dimensions_m): + raise ValueError("room dimensions must be finite and positive") + room = box( + -self.room_dimensions_m[0] / 2, + -self.room_dimensions_m[1] / 2, + self.room_dimensions_m[0] / 2, + self.room_dimensions_m[1] / 2, + ) + for zone in self.zones: + polygon = Polygon(zone.polygon_xy_m) + if not polygon.is_valid or not room.buffer(1.0e-6).covers(polygon): + raise ValueError(f"zone {zone.zone_id} is invalid or outside the room") + route = LineString(self.route_centerline_xy_m).buffer( + self.route_width_m / 2.0, cap_style="flat", join_style="round" + ) + if route.is_empty or not room.buffer(1.0e-6).covers(route): + raise ValueError("robot route is empty or outside the room") + if not route.buffer(1.0e-6).covers(Point(self.robot_start_xy_m)): + raise ValueError("robot start is not on the route") + return self + + +class AssetFirstHardCheck(_StrictModel): + check_id: str + passed: bool + details: str + entity_ids: list[str] = Field(default_factory=list) + + +class AssetFirstValidationReport(_StrictModel): + schema_version: Literal["2.0"] = "2.0" + passed: bool + checks: list[AssetFirstHardCheck] + failures: list[str] = Field(default_factory=list) + + +def freeze_asset_selection( + descriptor_index: Path, + choices: list[FurnitureAssetChoice], + output_path: Path, +) -> AssetSelectionSpec: + descriptor_index = descriptor_index.resolve() + if not descriptor_index.is_file(): + raise FileNotFoundError(descriptor_index) + spec = AssetSelectionSpec( + descriptor_index=str(descriptor_index), + descriptor_index_sha256=_sha256_file(descriptor_index), + choices=choices, + ) + atomic_write_text(output_path, spec.model_dump_json(indent=2) + "\n") + return spec + + +def _centered_polygon(points: list[Point2], center: Point2, scale: float) -> Polygon: + polygon = Polygon(points) + visual_center = polygon.centroid + polygon = affinity.translate(polygon, xoff=-visual_center.x, yoff=-visual_center.y) + polygon = affinity.scale(polygon, xfact=scale, yfact=scale, origin=(0.0, 0.0)) + return affinity.translate(polygon, xoff=center[0], yoff=center[1]) + + +def _local_polygons(descriptor: AssetDescriptor, scale: float) -> dict[str, Polygon]: + visual = Polygon(descriptor.visual_footprint_polygon_m) + center = visual.centroid + + def normalized(points: list[Point2]) -> Polygon: + polygon = Polygon(points) + polygon = affinity.translate(polygon, xoff=-center.x, yoff=-center.y) + return affinity.scale(polygon, xfact=scale, yfact=scale, origin=(0.0, 0.0)) + + clearances = [normalized(item.polygon_m) for item in descriptor.operational_clearance] + operational = unary_union(clearances).convex_hull if clearances else Polygon() + return { + "visual": normalized(descriptor.visual_footprint_polygon_m), + "collision": normalized(descriptor.collision_footprint_polygon_m), + "support": normalized(descriptor.support_footprint_polygon_m), + "reserve": normalized(descriptor.layout_reserve_envelope_polygon_m), + "operational": operational, + } + + +def _world(local: Polygon, center: Point2, yaw_deg: float) -> Polygon: + rotated = affinity.rotate(local, yaw_deg, origin=(0.0, 0.0)) + return affinity.translate(rotated, xoff=center[0], yoff=center[1]) + + +def _polygon_points(polygon: Polygon) -> list[Point2]: + if polygon.is_empty: + return [] + return [(round(float(x), 6), round(float(y), 6)) for x, y in polygon.exterior.coords[:-1]] + + +_FRONT_AXIS_VECTORS: dict[str, Point2] = { + "+X": (1.0, 0.0), + "-X": (-1.0, 0.0), + "+Y": (0.0, 1.0), + "-Y": (0.0, -1.0), +} + + +def _is_direction_sensitive(descriptor: AssetDescriptor) -> bool: + return definition_for_category(descriptor.category).functional_semantics in { + "seating_gaze", + "bed_foot", + "operation_side", + "screen_normal", + } + + +def _certified_placement_front_axis( + choice: FurnitureAssetChoice, + descriptor: AssetDescriptor, +) -> str | None: + """Return a functional front only when a placement certificate exists. + + ``descriptor.front_axis`` is retained for compatibility and geometry + rotation, but it is not evidence that an object has a usable front. In + particular, it must never cause a chair, cabinet, display, or bed to be + described as correctly facing an entity or a room opening. + """ + + descriptor_axis = effective_functional_front_axis( + descriptor, + minimum=choice.minimum_front_confidence_grade, + ) + if descriptor_axis is not None: + return descriptor_axis + if ( + choice.functional_front_axis is not None + and choice.functional_front_source is not None + and (choice.functional_front_confidence or 0.0) >= 0.85 + and bool(choice.functional_front_evidence) + ): + return choice.functional_front_axis + return None + + +def _normalize_yaw(value: float) -> float: + return float(((value + 180.0) % 360.0) - 180.0) + + +def _world_front_vector(front_axis: str, yaw_deg: float) -> Point2: + local_x, local_y = _FRONT_AXIS_VECTORS[front_axis] + yaw = math.radians(yaw_deg) + return ( + math.cos(yaw) * local_x - math.sin(yaw) * local_y, + math.sin(yaw) * local_x + math.cos(yaw) * local_y, + ) + + +def _yaw_toward_vector(front_axis: str, target: Point2) -> float: + if math.hypot(*target) <= 1.0e-9: + raise ValueError("facing target cannot coincide with the entity center") + desired_angle = math.degrees(math.atan2(target[1], target[0])) + local_x, local_y = _FRONT_AXIS_VECTORS[front_axis] + local_angle = math.degrees(math.atan2(local_y, local_x)) + return _normalize_yaw(desired_angle - local_angle) + + +def _candidate_yaws( + choice: FurnitureAssetChoice, + descriptor: AssetDescriptor, + center: Point2, + placed_centers: dict[str, Point2], +) -> list[float]: + certified_front = _certified_placement_front_axis(choice, descriptor) + if choice.face_entity_id: + if certified_front is None: + raise ValueError( + "facing placement requires a verified semantic front: " + f"entity={choice.entity_id} asset={descriptor.asset_id}" + ) + target = placed_centers.get(choice.face_entity_id) + if target is None: + raise ValueError( + f"facing target is not placed for {choice.entity_id}: {choice.face_entity_id}" + ) + direction = (target[0] - center[0], target[1] - center[1]) + if math.hypot(*direction) <= 1.0e-9: + return [] + return [ + _yaw_toward_vector( + certified_front, + direction, + ) + ] + preference = choice.placement_preference + if preference in {"zone_west", "zone_east"}: + return [0.0, 180.0] + inward = { + "north_wall": (0.0, -1.0), + "south_wall": (0.0, 1.0), + "east_wall": (-1.0, 0.0), + "west_wall": (1.0, 0.0), + }.get(preference) + if inward is not None: + # Direction-sensitive categories have already been rejected above + # without a certificate. Direction-neutral assets may use their + # authored geometry axis for a purely geometric wall alignment. + return [_yaw_toward_vector(certified_front or descriptor.front_axis, inward)] + if descriptor.wall_affinity == "required": + return [0.0, 90.0, 180.0, -90.0] + return [0.0, 180.0, 90.0, -90.0] + + +def _candidate_score( + center: Point2, + choice: FurnitureAssetChoice, + zone: Polygon, + room: Polygon, + placed_centers: dict[str, Point2], +) -> tuple[float, float, float]: + point = Point(center) + zone_center = zone.centroid + wall_distance = { + "north_wall": abs(room.bounds[3] - center[1]), + "south_wall": abs(center[1] - room.bounds[1]), + "east_wall": abs(room.bounds[2] - center[0]), + "west_wall": abs(center[0] - room.bounds[0]), + "zone_east": abs(zone.bounds[2] - center[0]), + "zone_west": abs(center[0] - zone.bounds[0]), + }.get(choice.placement_preference, point.distance(zone_center)) + anchor_distance = 0.0 + relation_slot_cost = 0.0 + if choice.near_entity_id and choice.near_entity_id in placed_centers: + anchor = placed_centers[choice.near_entity_id] + anchor_distance = math.dist(center, anchor) + if choice.relative_to_anchor: + direction = { + "north": (0.0, 1.0), + "south": (0.0, -1.0), + "east": (1.0, 0.0), + "west": (-1.0, 0.0), + # Table-side diagonal slots are primarily north/south with a + # smaller lateral component. A 45-degree target pushed paired + # chairs toward room corners instead of beside one another. + "north_east": (0.42, math.sqrt(1.0 - 0.42**2)), + "north_west": (-0.42, math.sqrt(1.0 - 0.42**2)), + "south_east": (0.42, -math.sqrt(1.0 - 0.42**2)), + "south_west": (-0.42, -math.sqrt(1.0 - 0.42**2)), + }[choice.relative_to_anchor] + preferred_distance = ( + sum(choice.near_distance_m) / 2.0 + if choice.near_distance_m + else max(anchor_distance, 0.9) + ) + semantic_slot = ( + anchor[0] + direction[0] * preferred_distance, + anchor[1] + direction[1] * preferred_distance, + ) + relation_slot_cost = math.dist(center, semantic_slot) + stable = int(hashlib.sha256(f"{choice.entity_id}:{center}".encode()).hexdigest()[:8], 16) + if choice.near_distance_m: + preferred_distance = sum(choice.near_distance_m) / 2.0 + anchor_distance_cost = abs(anchor_distance - preferred_distance) + else: + anchor_distance_cost = anchor_distance + return ( + wall_distance + anchor_distance_cost * 1.5 + relation_slot_cost * 3.0, + point.distance(zone_center), + stable / 2**32, + ) + + +def _relation_satisfied( + center: Point2, + choice: FurnitureAssetChoice, + placed_centers: dict[str, Point2], +) -> bool: + if not choice.near_entity_id: + return True + anchor = placed_centers.get(choice.near_entity_id) + if anchor is None: + return False + delta_x = center[0] - anchor[0] + delta_y = center[1] - anchor[1] + distance = math.hypot(delta_x, delta_y) + if choice.near_distance_m and not ( + choice.near_distance_m[0] - 1.0e-9 + <= distance + <= choice.near_distance_m[1] + 1.0e-9 + ): + return False + relative = choice.relative_to_anchor + if relative is None or distance <= 1.0e-9: + return relative is None + tolerance = math.cos(math.radians(42.5 if "_" in relative else 45.0)) + target = { + "north": (0.0, 1.0), + "south": (0.0, -1.0), + "east": (1.0, 0.0), + "west": (-1.0, 0.0), + "north_east": (0.42, math.sqrt(1.0 - 0.42**2)), + "north_west": (-0.42, math.sqrt(1.0 - 0.42**2)), + "south_east": (0.42, -math.sqrt(1.0 - 0.42**2)), + "south_west": (-0.42, -math.sqrt(1.0 - 0.42**2)), + }[relative] + alignment = (delta_x * target[0] + delta_y * target[1]) / distance + return alignment >= tolerance + + +def _grid_candidates(zone: Polygon, step: float) -> list[Point2]: + min_x, min_y, max_x, max_y = zone.bounds + output: list[Point2] = [] + x = math.ceil(min_x / step) * step + while x <= max_x + 1.0e-8: + y = math.ceil(min_y / step) * step + while y <= max_y + 1.0e-8: + if zone.buffer(1.0e-8).covers(Point(x, y)): + output.append((round(x, 6), round(y, 6))) + y += step + x += step + return output + + +def _choices_share_functional_group( + left: FurnitureAssetChoice, + right: FurnitureAssetChoice, +) -> bool: + """Return true for explicitly related furniture whose use envelopes may overlap. + + A pulled-out desk chair and its desk, or two chairs at the same table, need + overlapping *operational* space to be usable. Their physical collision + footprints must remain disjoint; unrelated furniture still reserves its full + safety/operation envelope. + """ + + if left.entity_id in {right.near_entity_id, right.face_entity_id}: + return True + if right.entity_id in {left.near_entity_id, left.face_entity_id}: + return True + return bool( + left.near_entity_id + and left.near_entity_id == right.near_entity_id + and left.relative_to_anchor + and right.relative_to_anchor + ) + + +def _make_entity( + choice: FurnitureAssetChoice, + descriptor: AssetDescriptor, + zone: MetricZone, + local: dict[str, Polygon], + center: Point2, + yaw: float, + descriptor_ref: str, +) -> MetricEntityLayout: + worlds = {name: _world(polygon, center, yaw) for name, polygon in local.items()} + rectangle = worlds["visual"].minimum_rotated_rectangle + coordinates = list(rectangle.exterior.coords)[:-1] + lengths = [math.dist(coordinates[index], coordinates[(index + 1) % 4]) for index in range(4)] + longest = max(range(4), key=lengths.__getitem__) + first, second = coordinates[longest], coordinates[(longest + 1) % 4] + obb_yaw = math.degrees(math.atan2(second[1] - first[1], second[0] - first[0])) + reserve_bounds = worlds["reserve"].bounds + footprint_m = ( + float(reserve_bounds[2] - reserve_bounds[0]), + float(reserve_bounds[3] - reserve_bounds[1]), + ) + mount = { + "floor": "FLOOR", + "wall": "WALL", + "ceiling": "CEILING", + "surface": "SURFACE", + }[descriptor.support_type] + certified_front = _certified_placement_front_axis(choice, descriptor) + world_front = ( + _world_front_vector(certified_front, yaw) if certified_front is not None else None + ) + return MetricEntityLayout( + entity_id=choice.entity_id, + center_xy_m=center, + yaw_deg=yaw, + footprint_m=footprint_m, + zone_id=zone.zone_id, + zone_polygon_xy_m=zone.polygon_xy_m, + parent_entity_id=choice.parent_entity_id, + mount=mount, + allow_natural_perturbation=False, + asset_id=descriptor.asset_id, + asset_sha256=descriptor.sha256, + asset_descriptor_ref=descriptor_ref, + asset_locked=True, + canonical_uniform_scale=1.0, + dimensions_m=descriptor.native_bbox_m, + category=descriptor.category, + display_name=descriptor.display_name, + support_type=descriptor.support_type, + quality_overall=descriptor.quality.overall, + asset_status="ACTIVE", + visual_footprint_local_m=_polygon_points(local["visual"]), + collision_footprint_local_m=_polygon_points(local["collision"]), + support_footprint_local_m=_polygon_points(local["support"]), + visual_footprint_xy_m=_polygon_points(worlds["visual"]), + collision_footprint_xy_m=_polygon_points(worlds["collision"]), + support_footprint_xy_m=_polygon_points(worlds["support"]), + layout_reserve_envelope_xy_m=_polygon_points(worlds["reserve"]), + operational_clearance_polygon_xy_m=_polygon_points(worlds["operational"]), + canonical_front_axis=certified_front, + world_front_vector_xy=( + round(world_front[0], 9), + round(world_front[1], 9), + ) if world_front is not None else None, + facing_target_entity_id=choice.face_entity_id, + near_entity_id=choice.near_entity_id, + near_distance_m=choice.near_distance_m, + relative_to_anchor=choice.relative_to_anchor, + functional_front_semantics=choice.functional_front_semantics, + functional_front_source=choice.functional_front_source, + functional_front_confidence=choice.functional_front_confidence, + functional_front_evidence=choice.functional_front_evidence, + rotated_obb_m={ + "center_m": [ + round(float(rectangle.centroid.x), 6), + round(float(rectangle.centroid.y), 6), + round(descriptor.height_m / 2.0, 6), + ], + "size_m": [ + round(float(lengths[longest]), 6), + round(float(lengths[(longest + 1) % 4]), 6), + round(descriptor.height_m, 6), + ], + "yaw_deg": round(float(((obb_yaw + 180.0) % 360.0) - 180.0), 6), + "footprint_polygon_xy_m": _polygon_points(rectangle), + }, + ) + + +def compile_asset_first_layout( + selection_path: Path, + room_request: AssetFirstRoomRequest, + *, + descriptor_refs: dict[str, str] | None = None, +) -> MetricLayoutSpec: + selection_path = selection_path.resolve() + selection = AssetSelectionSpec.model_validate_json(selection_path.read_text(encoding="utf-8")) + index_path = Path(selection.descriptor_index).resolve() + if _sha256_file(index_path) != selection.descriptor_index_sha256: + raise ValueError("asset descriptor index changed after Furniture Agent selection") + descriptors = load_active_descriptors( + index_path, [choice.asset_id for choice in selection.choices] + ) + descriptor_by_id = {descriptor.asset_id: descriptor for descriptor in descriptors} + missing = {choice.asset_id for choice in selection.choices} - set(descriptor_by_id) + if missing: + raise ValueError(f"Furniture Agent selected unavailable assets: {sorted(missing)}") + for choice in selection.choices: + descriptor = descriptor_by_id[choice.asset_id] + category_semantics = definition_for_category(descriptor.category).functional_semantics + direction_sensitive = _is_direction_sensitive(descriptor) + if ( + not choice.face_entity_id + and not choice.functional_front_semantics + and not direction_sensitive + ): + continue + confidence = descriptor.front_confidence or descriptor.confidence.get( + "front_axis", 0.0 + ) + descriptor_axis = effective_functional_front_axis( + descriptor, + minimum=choice.minimum_front_confidence_grade, + ) + descriptor_certified = descriptor_axis is not None + functional_certified = ( + choice.functional_front_axis is not None + and choice.functional_front_source is not None + and (choice.functional_front_confidence or 0.0) >= 0.85 + and bool(choice.functional_front_evidence) + ) + if not descriptor_certified and not functional_certified: + raise ValueError( + "direction-sensitive asset requires a verified semantic front: " + f"entity={choice.entity_id} asset={descriptor.asset_id} " + f"category_semantics={category_semantics} " + f"method={descriptor.front_method.value} " + f"grade={descriptor.front_confidence_grade.value} confidence={confidence:.3f}" + ) + if choice.functional_front_source in { + "multiview_geometry_consensus", + "multiview_affordance_consensus", + } and ( + not descriptor_certified or choice.functional_front_axis != descriptor_axis + ): + raise ValueError( + "functional-front consensus does not match the descriptor certificate: " + f"entity={choice.entity_id}" + ) + for descriptor in descriptors: + source = Path(descriptor.canonical_path) + if not source.is_file() or _sha256_file(source) != descriptor.sha256: + raise ValueError(f"asset changed after certification: {descriptor.asset_id}") + width, depth, height = room_request.room_dimensions_m + room = box(-width / 2.0, -depth / 2.0, width / 2.0, depth / 2.0) + zones = [ + MetricZone(zone_id=zone.zone_id, polygon_xy_m=zone.polygon_xy_m) + for zone in room_request.zones + ] + zone_by_id = {zone.zone_id: zone for zone in zones} + unknown_zones = {choice.zone_id for choice in selection.choices} - set(zone_by_id) + if unknown_zones: + raise ValueError(f"Furniture Agent selected unknown zones: {sorted(unknown_zones)}") + route = LineString(room_request.route_centerline_xy_m).buffer( + room_request.route_width_m / 2.0, cap_style="flat", join_style="round" + ) + if not isinstance(route, Polygon): + raise ValueError("asset-first route is not one polygon") + keep_outs = [ + MetricKeepOutRegion( + region_id=opening.opening_id, + kind=opening.kind, + polygon_xy_m=opening.keep_out_polygon_xy_m, + ) + for opening in room_request.openings + ] + fixed_obstacles = [route, *[Polygon(region.polygon_xy_m) for region in keep_outs]] + choice_by_id = {choice.entity_id: choice for choice in selection.choices} + unresolved = set(choice_by_id) + placed: dict[str, MetricEntityLayout] = {} + placed_reserves: dict[str, Polygon] = {} + placed_centers: dict[str, Point2] = {} + while unresolved: + ready = [ + choice_by_id[entity_id] + for entity_id in unresolved + if ( + not choice_by_id[entity_id].parent_entity_id + or choice_by_id[entity_id].parent_entity_id in placed + ) + and ( + not choice_by_id[entity_id].near_entity_id + or choice_by_id[entity_id].near_entity_id in placed + ) + and ( + not choice_by_id[entity_id].face_entity_id + or choice_by_id[entity_id].face_entity_id in placed + ) + ] + if not ready: + raise ValueError( + f"cyclic or unresolved asset placement dependencies: {sorted(unresolved)}" + ) + ready.sort( + key=lambda choice: ( + choice.parent_entity_id is not None, + -Polygon(descriptor_by_id[choice.asset_id].layout_reserve_envelope_polygon_m).area, + choice.entity_id, + ) + ) + for choice in ready: + descriptor = descriptor_by_id[choice.asset_id] + local = _local_polygons(descriptor, 1.0) + zone_record = zone_by_id[choice.zone_id] + zone = Polygon(zone_record.polygon_xy_m) + selected_pose: tuple[Point2, float] | None = None + if choice.parent_entity_id: + parent = placed[choice.parent_entity_id] + parent_surface = Polygon(parent.visual_footprint_xy_m).buffer(-0.03) + if parent_surface.is_empty: + parent_surface = Polygon(parent.visual_footprint_xy_m) + candidate_centers = [ + (float(parent_surface.centroid.x), float(parent_surface.centroid.y)), + *_grid_candidates(parent_surface, max(0.05, room_request.solver_grid_m / 2.0)), + ] + if (room_request.robot_constraints_enabled + and choice.entity_id == room_request.task_object_entity_id): + from packages.robots.task_constraints import depth_limits, get_task_constraints + from packages.scene_generation.robot_constraints import service_frame + profile = get_task_constraints(room_request.robot_id) + parent_descriptor = descriptor_by_id[parent.asset_id] + support_height = parent.base_elevation_m + parent_descriptor.height_m + low, high = profile["support_height_range_m"] + if not low <= support_height <= high: + raise ValueError(f"robot_constraints:support_height:{support_height}:{parent.entity_id}") + if min(descriptor.native_bbox_m) > profile["max_grip_dimension_m"]: + raise ValueError(f"robot_constraints:grip_dimension:{choice.entity_id}") + edge, normal, _ = service_frame(parent, parent_descriptor, room) + comfort, reachable = depth_limits(profile, support_height) + def placement_depth(center): + return (edge.x-center[0])*normal[0]+(edge.y-center[1])*normal[1] + candidate_centers = [center for center in candidate_centers[1:] + if 0 <= placement_depth(center) <= reachable] + candidate_centers.sort(key=lambda center: (placement_depth(center) > comfort, placement_depth(center))) + for center in candidate_centers: + for yaw in _candidate_yaws(choice, descriptor, center, placed_centers): + visual = _world(local["visual"], center, yaw) + if parent_surface.buffer(1.0e-6).covers(visual): + selected_pose = (center, yaw) + break + if selected_pose: + break + else: + candidates = _grid_candidates(zone, room_request.solver_grid_m) + candidates.sort( + key=lambda center: _candidate_score(center, choice, zone, room, placed_centers) + ) + for center in candidates: + if not _relation_satisfied(center, choice, placed_centers): + continue + for yaw in _candidate_yaws(choice, descriptor, center, placed_centers): + reserve = _world(local["reserve"], center, yaw) + collision = _world(local["collision"], center, yaw) + if not room.buffer(1.0e-6).covers(reserve): + continue + if not zone.buffer(1.0e-6).covers(reserve): + continue + if any(reserve.intersects(obstacle) for obstacle in fixed_obstacles): + continue + placement_conflict = False + for other_id, other_reserve in placed_reserves.items(): + other_choice = choice_by_id[other_id] + if _choices_share_functional_group(choice, other_choice): + other_collision = Polygon( + placed[other_id].collision_footprint_xy_m + ) + if ( + collision.intersection(other_collision).area + > 1.0e-7 + ): + placement_conflict = True + break + elif reserve.intersection(other_reserve).area > 1.0e-7: + placement_conflict = True + break + if placement_conflict: + continue + selected_pose = (center, yaw) + break + if selected_pose: + break + if selected_pose is None: + occupied = { + entity_id: { + "center_xy_m": placed[entity_id].center_xy_m, + "reserve_bounds_xy_m": [round(value, 3) for value in polygon.bounds], + } + for entity_id, polygon in sorted(placed_reserves.items()) + } + raise ValueError( + "deterministic asset-first solver found no feasible pose for " + f"{choice.entity_id} " + f"({descriptor.asset_id}) in zone {choice.zone_id}; " + f"already_placed={json.dumps(occupied, sort_keys=True)}" + ) + center, yaw = selected_pose + descriptor_ref = ( + descriptor_refs[choice.entity_id] + if descriptor_refs and choice.entity_id in descriptor_refs + else f"{index_path}#asset_id={descriptor.asset_id}" + ) + entity = _make_entity( + choice, descriptor, zone_record, local, center, yaw, descriptor_ref + ) + placed[choice.entity_id] = entity + placed_centers[choice.entity_id] = center + if not choice.parent_entity_id: + placed_reserves[choice.entity_id] = Polygon(entity.layout_reserve_envelope_xy_m) + unresolved.remove(choice.entity_id) + ordered_entities = [placed[choice.entity_id] for choice in selection.choices] + spec = MetricLayoutSpec( + schema_version="2.0", + source_blueprint="rich_blueprint.png", + source_blueprint_sha256="0" * 64, + source_hints_sha256=_canonical_sha256(selection.model_dump(mode="json")), + room_dimensions_m=(width, depth, height), + room_polygon_mode="dimensions_box", + room_polygon_xy_m=[ + (-width / 2, -depth / 2), + (width / 2, -depth / 2), + (width / 2, depth / 2), + (-width / 2, depth / 2), + ], + zones=zones, + entities=ordered_entities, + keep_out_regions=keep_outs, + route_width_m=room_request.route_width_m, + route_polygon_xy_m=_polygon_points(route), + robot_start_xy_m=room_request.robot_start_xy_m, + footprint_tolerance_m=0.02, + footprint_validation_mode="target", + natural_perturbation=NaturalPerturbationPolicy(enabled=False), + asset_descriptor_index=str(index_path), + asset_selection_path=str(selection_path), + asset_selection_sha256=_sha256_file(selection_path), + layout_truth_sha256=None, + room_shell_source="metric_layout_spec", + furniture_agent_pose_authority="none", + coordinate_solver="deterministic_asset_certificate_grid_v3_front_aware", + asset_reselection_count=0, + ) + validation = validate_asset_first_layout( + spec, selection=selection, descriptors=descriptor_by_id + ) + if not validation.passed: + failed_details = { + item.check_id: item.details for item in validation.checks if not item.passed + } + raise ValueError( + "asset-first hard checks failed: " + json.dumps(failed_details, sort_keys=True) + ) + payload = spec.model_dump(mode="json") + payload["layout_truth_sha256"] = _canonical_sha256({**payload, "layout_truth_sha256": None}) + return MetricLayoutSpec.model_validate(payload) + + +def validate_asset_first_layout( + spec: MetricLayoutSpec, + *, + selection: AssetSelectionSpec | None = None, + descriptors: dict[str, AssetDescriptor] | None = None, +) -> AssetFirstValidationReport: + checks: list[AssetFirstHardCheck] = [] + + def check( + check_id: str, passed: bool, details: str, entity_ids: list[str] | None = None + ) -> None: + checks.append( + AssetFirstHardCheck( + check_id=check_id, + passed=passed, + details=details, + entity_ids=entity_ids or [], + ) + ) + + check("schema_v2", spec.schema_version == "2.0", f"schema={spec.schema_version}") + check( + "furniture_agent_has_no_pose_authority", + spec.furniture_agent_pose_authority == "none" + and (selection is None or selection.pose_authority == "none"), + f"layout={spec.furniture_agent_pose_authority}; " + f"selection={getattr(selection, 'pose_authority', None)}", + ) + room = Polygon(spec.room_polygon_xy_m) + route = Polygon(spec.route_polygon_xy_m) + zones = {zone.zone_id: Polygon(zone.polygon_xy_m) for zone in spec.zones} + entity_by_id = spec.entity_by_id + front_aware = bool(spec.coordinate_solver and "front_aware" in spec.coordinate_solver) + for entity in spec.entities: + visual = Polygon(entity.visual_footprint_xy_m) + collision = Polygon(entity.collision_footprint_xy_m) + support = Polygon(entity.support_footprint_xy_m) + operational = ( + Polygon(entity.operational_clearance_polygon_xy_m) + if entity.operational_clearance_polygon_xy_m + else Polygon() + ) + reserve = Polygon(entity.layout_reserve_envelope_xy_m) + for label, polygon in ( + ("visual", visual), + ("collision", collision), + ("support", support), + ("reserve", reserve), + ): + check( + f"{entity.entity_id}_{label}_inside_room", + room.buffer(1.0e-6).covers(polygon), + f"{label} area={polygon.area:.6f}", + [entity.entity_id], + ) + check( + f"{entity.entity_id}_inside_zone", + zones[entity.zone_id].buffer(1.0e-6).covers(reserve), + f"zone={entity.zone_id}", + [entity.entity_id], + ) + intersections = { + label: route.intersection(polygon).area + for label, polygon in ( + ("visual", visual), + ("collision", collision), + ("operational", operational), + ) + if not polygon.is_empty + } + check( + f"{entity.entity_id}_route_1p2m_clear", + all(area <= 1.0e-8 for area in intersections.values()), + json.dumps(intersections, sort_keys=True), + [entity.entity_id], + ) + local_visual = Polygon(entity.visual_footprint_local_m) + rebuilt = _world(local_visual, entity.center_xy_m, entity.yaw_deg) + check( + f"{entity.entity_id}_pose_projection_consistent", + rebuilt.hausdorff_distance(visual) <= 0.002, + f"hausdorff_m={rebuilt.hausdorff_distance(visual):.6f}", + [entity.entity_id], + ) + obb = Polygon(entity.rotated_obb_m["footprint_polygon_xy_m"]) + expected_obb = visual.minimum_rotated_rectangle + obb_coordinates = list(obb.exterior.coords)[:-1] + expected_coordinates = list(expected_obb.exterior.coords)[:-1] + obb_sizes = sorted( + math.dist(obb_coordinates[index], obb_coordinates[(index + 1) % 4]) + for index in range(2) + ) + expected_sizes = sorted( + math.dist(expected_coordinates[index], expected_coordinates[(index + 1) % 4]) + for index in range(2) + ) + obb_polygon_error = obb.hausdorff_distance(expected_obb) + obb_center_error = obb.centroid.distance(expected_obb.centroid) + obb_size_errors = [abs(obb_sizes[index] - expected_sizes[index]) for index in range(2)] + check( + f"{entity.entity_id}_rotated_obb_consistent", + obb_polygon_error <= 0.002 + or ( + obb_center_error <= max(0.002, spec.footprint_tolerance_m) + and all(error <= 0.002 for error in obb_size_errors) + ), + ( + f"hausdorff_m={obb_polygon_error:.6f}; " + f"center_error_m={obb_center_error:.6f}; " + f"sorted_size_errors_m={obb_size_errors}" + ), + [entity.entity_id], + ) + descriptor = descriptors.get(entity.asset_id or "") if descriptors else None + # A front certificate is mandatory only for an object whose category + # has a functional side, an object explicitly facing another entity, + # or an Agent-supplied functional certificate. Neutral assets retain + # a valid geometric yaw without pretending that it is semantic front. + front_required = bool( + entity.facing_target_entity_id + or entity.functional_front_source + or (descriptor is not None and _is_direction_sensitive(descriptor)) + ) + if front_aware and front_required: + front_fields_present = ( + entity.canonical_front_axis in _FRONT_AXIS_VECTORS + and entity.world_front_vector_xy is not None + ) + check( + f"{entity.entity_id}_certified_front_present", + front_fields_present, + ( + f"axis={entity.canonical_front_axis}; " + f"world_vector={entity.world_front_vector_xy}" + ), + [entity.entity_id], + ) + if front_fields_present: + expected_front = _world_front_vector( + entity.canonical_front_axis or "+Y", entity.yaw_deg + ) + front_error = math.dist(expected_front, entity.world_front_vector_xy or (0.0, 0.0)) + check( + f"{entity.entity_id}_front_vector_matches_yaw", + front_error <= 1.0e-6, + f"vector_error={front_error:.9f}", + [entity.entity_id], + ) + if entity.facing_target_entity_id: + target = entity_by_id[entity.facing_target_entity_id] + vector = entity.world_front_vector_xy or (0.0, 0.0) + delta = ( + target.center_xy_m[0] - entity.center_xy_m[0], + target.center_xy_m[1] - entity.center_xy_m[1], + ) + distance = math.hypot(*delta) + alignment = ( + (vector[0] * delta[0] + vector[1] * delta[1]) / distance + if distance > 1.0e-9 + else -1.0 + ) + check( + f"{entity.entity_id}_faces_{entity.facing_target_entity_id}", + alignment >= math.cos(math.radians(1.0)), + f"cosine_alignment={alignment:.9f}", + [entity.entity_id, entity.facing_target_entity_id], + ) + if entity.near_entity_id: + anchor = entity_by_id[entity.near_entity_id] + delta_x = entity.center_xy_m[0] - anchor.center_xy_m[0] + delta_y = entity.center_xy_m[1] - anchor.center_xy_m[1] + distance = math.hypot(delta_x, delta_y) + if entity.near_distance_m: + check( + f"{entity.entity_id}_distance_to_{entity.near_entity_id}", + ( + entity.near_distance_m[0] - 1.0e-6 + <= distance + <= entity.near_distance_m[1] + 1.0e-6 + ), + f"distance_m={distance:.6f}; range={entity.near_distance_m}", + [entity.entity_id, entity.near_entity_id], + ) + if entity.relative_to_anchor: + check( + f"{entity.entity_id}_{entity.relative_to_anchor}_of_" + f"{entity.near_entity_id}", + _relation_satisfied( + entity.center_xy_m, + FurnitureAssetChoice( + entity_id=entity.entity_id, + asset_id=entity.asset_id or "asset", + zone_id=entity.zone_id, + semantic_role=entity.display_name or entity.entity_id, + near_entity_id=entity.near_entity_id, + near_distance_m=entity.near_distance_m, + relative_to_anchor=entity.relative_to_anchor, + ), + {entity.near_entity_id: anchor.center_xy_m}, + ), + ( + f"delta=({delta_x:.6f},{delta_y:.6f}); " + f"relation={entity.relative_to_anchor}" + ), + [entity.entity_id, entity.near_entity_id], + ) + if descriptor is not None: + source = Path(descriptor.canonical_path) + identity_ok = ( + descriptor.status == "ACTIVE" + and descriptor.sha256 == entity.asset_sha256 + and source.is_file() + and _sha256_file(source) == entity.asset_sha256 + ) + check( + f"{entity.entity_id}_asset_identity_locked", + identity_ok, + f"asset_id={entity.asset_id}; sha256={entity.asset_sha256}", + [entity.entity_id], + ) + scale_ok = ( + descriptor.uniform_scale_range[0] + <= entity.canonical_uniform_scale + <= descriptor.uniform_scale_range[1] + ) + check( + f"{entity.entity_id}_uniform_scale_only", + scale_ok, + f"scale={entity.canonical_uniform_scale}; allowed={descriptor.uniform_scale_range}", + [entity.entity_id], + ) + if front_aware and front_required: + if entity.functional_front_source: + check( + f"{entity.entity_id}_functional_front_certificate_complete", + ( + entity.functional_front_semantics is not None + and (entity.functional_front_confidence or 0.0) >= 0.85 + and bool(entity.functional_front_evidence) + ), + ( + f"semantics={entity.functional_front_semantics}; " + f"source={entity.functional_front_source}; " + f"confidence={entity.functional_front_confidence}" + ), + [entity.entity_id], + ) + else: + descriptor_front_axis = effective_functional_front_axis(descriptor) + check( + f"{entity.entity_id}_front_axis_matches_descriptor", + entity.canonical_front_axis == descriptor_front_axis, + ( + f"layout={entity.canonical_front_axis}; " + f"descriptor={descriptor_front_axis}" + ), + [entity.entity_id], + ) + top_level = [entity for entity in spec.entities if not entity.parent_entity_id] + for index, left in enumerate(top_level): + left_shape = Polygon(left.layout_reserve_envelope_xy_m) + for right in top_level[index + 1 :]: + right_shape = Polygon(right.layout_reserve_envelope_xy_m) + left_choice = FurnitureAssetChoice( + entity_id=left.entity_id, + asset_id=left.asset_id or "asset", + zone_id=left.zone_id, + semantic_role=left.display_name or left.entity_id, + near_entity_id=left.near_entity_id, + relative_to_anchor=left.relative_to_anchor, + face_entity_id=left.facing_target_entity_id, + ) + right_choice = FurnitureAssetChoice( + entity_id=right.entity_id, + asset_id=right.asset_id or "asset", + zone_id=right.zone_id, + semantic_role=right.display_name or right.entity_id, + near_entity_id=right.near_entity_id, + relative_to_anchor=right.relative_to_anchor, + face_entity_id=right.facing_target_entity_id, + ) + if _choices_share_functional_group(left_choice, right_choice): + overlap = Polygon(left.collision_footprint_xy_m).intersection( + Polygon(right.collision_footprint_xy_m) + ).area + check_id = f"functional_group_collision_free_{left.entity_id}_{right.entity_id}" + details = f"physical_overlap_m2={overlap:.8f}; reserve_overlap_allowed=true" + else: + overlap = left_shape.intersection(right_shape).area + check_id = f"no_reserve_overlap_{left.entity_id}_{right.entity_id}" + details = f"overlap_m2={overlap:.8f}" + check( + check_id, + overlap <= 1.0e-8, + details, + [left.entity_id, right.entity_id], + ) + for entity in spec.entities: + if not entity.parent_entity_id: + continue + parent = entity_by_id[entity.parent_entity_id] + supported = ( + Polygon(parent.visual_footprint_xy_m) + .buffer(1.0e-6) + .covers(Polygon(entity.visual_footprint_xy_m)) + ) + check( + f"{entity.entity_id}_supported_by_{parent.entity_id}", + supported, + "child visual footprint must lie on parent support envelope", + [entity.entity_id, parent.entity_id], + ) + failures = [check.check_id for check in checks if not check.passed] + return AssetFirstValidationReport(passed=not failures, checks=checks, failures=failures) + + +def render_rich_blueprint( + spec: MetricLayoutSpec, + descriptors: dict[str, AssetDescriptor], + output_path: Path, + *, + title: str, + task: dict[str, Any] | None = None, +) -> Path: + width_px, height_px = 2200, 1400 + plan_left, plan_top, plan_right, plan_bottom = 80, 145, 1360, 1320 + legend_left = 1420 + image = Image.new("RGB", (width_px, height_px), (248, 246, 239)) + draw = ImageDraw.Draw(image, "RGBA") + draw.text((80, 45), title, fill=(25, 38, 35, 255), stroke_width=1) + draw.text( + (80, 88), + "Metric truth: metric_layout_spec.json · 1.2 m route · visual / collision / operation", + fill=(66, 79, 75, 255), + ) + room = Polygon(spec.room_polygon_xy_m) + min_x, min_y, max_x, max_y = room.bounds + scale = min( + (plan_right - plan_left) / (max_x - min_x), (plan_bottom - plan_top) / (max_y - min_y) + ) + + def pixel(point: Point2) -> tuple[float, float]: + return ( + plan_left + (point[0] - min_x) * scale, + plan_bottom - (point[1] - min_y) * scale, + ) + + palette = [(222, 232, 224, 125), (232, 221, 207, 125), (216, 226, 235, 125)] + for index, zone in enumerate(spec.zones): + draw.polygon( + [pixel(point) for point in zone.polygon_xy_m], fill=palette[index % len(palette)] + ) + center = Polygon(zone.polygon_xy_m).centroid + draw.text(pixel((center.x, center.y)), zone.zone_id, fill=(79, 92, 87, 210)) + draw.polygon( + [pixel(point) for point in spec.route_polygon_xy_m], + fill=(91, 164, 180, 95), + outline=(39, 118, 137, 230), + width=4, + ) + draw.text(pixel(spec.robot_start_xy_m), "ROBOT START", fill=(13, 84, 102, 255)) + if task: + task_route = [tuple(point) for point in task.get("route_waypoints_xy_m", [])] + if len(task_route) >= 2: + draw.line( + [pixel(point) for point in task_route], + fill=(20, 131, 211, 235), + width=8, + joint="curve", + ) + pick_xy = tuple(task["pick"]["position_xyz_m"][:2]) + place_xy = tuple(task["place"]["position_xyz_m"][:2]) + for point, label, color in ( + (pick_xy, "PICK", (40, 168, 92, 255)), + (place_xy, "PLACE", (235, 132, 31, 255)), + ): + center = pixel(point) + draw.ellipse( + (center[0] - 12, center[1] - 12, center[0] + 12, center[1] + 12), + outline=color, + width=7, + ) + draw.text((center[0] + 15, center[1] - 10), label, fill=color) + for region in spec.keep_out_regions: + draw.polygon( + [pixel(point) for point in region.polygon_xy_m], + fill=(216, 92, 76, 65), + outline=(177, 55, 42, 230), + width=3, + ) + draw.text( + pixel(region.polygon_xy_m[0]), + f"{region.kind.upper()} {region.region_id}", + fill=(139, 43, 32, 255), + ) + colors = [(52, 91, 83), (126, 91, 52), (74, 82, 126), (120, 65, 91)] + for index, entity in enumerate(spec.entities): + entity_color = colors[index % len(colors)] + draw.polygon( + [pixel(point) for point in entity.visual_footprint_xy_m], + fill=(*entity_color, 165), + outline=(*entity_color, 255), + width=3, + ) + draw.line( + [pixel(point) for point in entity.collision_footprint_xy_m] + + [pixel(entity.collision_footprint_xy_m[0])], + fill=(190, 67, 49, 230), + width=2, + ) + if entity.operational_clearance_polygon_xy_m: + draw.line( + [pixel(point) for point in entity.operational_clearance_polygon_xy_m] + + [pixel(entity.operational_clearance_polygon_xy_m[0])], + fill=(223, 142, 42, 220), + width=4, + ) + center_px = pixel(entity.center_xy_m) + draw.ellipse( + (center_px[0] - 5, center_px[1] - 5, center_px[0] + 5, center_px[1] + 5), + fill=(20, 25, 24, 255), + ) + draw.text((center_px[0] + 7, center_px[1] - 12), entity.entity_id, fill=(22, 28, 26, 255)) + draw.line( + [pixel(point) for point in spec.room_polygon_xy_m] + [pixel(spec.room_polygon_xy_m[0])], + fill=(25, 34, 31, 255), + width=9, + ) + legend_title = "ASSET-LOCKED ENTITIES" + if task: + legend_title += f" · {task['task_id']}" + draw.text((legend_left, 82), legend_title, fill=(26, 39, 36, 255), stroke_width=1) + row_height = 108 + for index, entity in enumerate(spec.entities): + descriptor = descriptors[entity.asset_id or ""] + y = 130 + index * row_height + if y + row_height > height_px: + break + thumbnail = Image.open(descriptor.thumbnail).convert("RGB") + thumbnail.thumbnail((86, 86)) + image.paste(thumbnail, (legend_left, y + 6)) + x = legend_left + 102 + dimensions = entity.dimensions_m or (0.0, 0.0, 0.0) + lines = [ + f"{entity.entity_id} | {descriptor.category} · {descriptor.display_name[:42]}", + f"asset_id: {descriptor.asset_id[:68]}", + ( + f"{dimensions[0]:.2f} × {dimensions[1]:.2f} × {dimensions[2]:.2f} m " + f"yaw {entity.yaw_deg:.0f}°" + ), + ( + f"support {descriptor.support_type} " + f"quality {descriptor.quality.overall}/100 ACTIVE" + ), + ] + for line_index, text in enumerate(lines): + draw.text((x, y + 5 + line_index * 22), text, fill=(36, 46, 43, 255)) + draw.line( + (legend_left, y + 101, width_px - 60, y + 101), fill=(188, 183, 169, 180), width=1 + ) + draw.rectangle((1520, 1290, 1570, 1310), fill=(52, 91, 83, 165)) + draw.text((1580, 1286), "visual", fill=(45, 55, 52, 255)) + draw.line((1680, 1300, 1730, 1300), fill=(190, 67, 49, 255), width=3) + draw.text((1740, 1286), "collision", fill=(45, 55, 52, 255)) + draw.line((1880, 1300, 1930, 1300), fill=(223, 142, 42, 255), width=4) + draw.text((1940, 1286), "operation", fill=(45, 55, 52, 255)) + output_path.parent.mkdir(parents=True, exist_ok=True) + temporary = output_path.with_suffix(output_path.suffix + ".tmp") + image.save(temporary, format="PNG", optimize=True) + temporary.replace(output_path) + return output_path + + +def finalize_layout_blueprint_identity( + spec: MetricLayoutSpec, blueprint_path: Path +) -> MetricLayoutSpec: + payload = spec.model_dump(mode="json") + payload["source_blueprint"] = blueprint_path.name + payload["source_blueprint_sha256"] = _sha256_file(blueprint_path) + payload["layout_truth_sha256"] = _canonical_sha256({**payload, "layout_truth_sha256": None}) + return MetricLayoutSpec.model_validate(payload) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/bundle_compiler.py b/docs/reproduction/public_conversion_code/packages/scene_generation/bundle_compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..16d6a19fc25ea5a1d23ebd78819938263605b292 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/bundle_compiler.py @@ -0,0 +1,675 @@ +from __future__ import annotations + +import hashlib +import json +import math +import os +import uuid +from datetime import UTC, datetime +from pathlib import Path + +from shapely.geometry import Polygon # type: ignore[import-untyped] + +from packages.core.contracts import ( + AssetLockEntry, + RobotStart, + SceneBundle, + SceneRuntimeBindings, + canonical_sha256, +) +from packages.core.files import atomic_write_text +from packages.plugins.tasks.base import TaskPluginCompilation, TaskPluginSpec +from packages.providers.scenes import MetricV2Provider, SceneSmithVisualProvider +from packages.scene_generation.metric_layout import MetricEntityLayout, MetricLayoutSpec +from packages.scene_generation.motifs import LayeredScenePlan +from packages.scene_generation.multi_room import ( + MultiRoomMetricLayoutSpec, + build_multi_room_validation_report, + door_leaf_polygon, + multi_room_wall_runs, +) +from packages.validators import validate_task_plugin_compilation + +BASE_LAYER_ORDER = ( + "physics_overrides", + "task", + "regions", + "semantics", + "furniture", + "architecture", + "materials", + "wallpaper", + "lighting", + "decor", + "exterior", +) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _usd_identifier(value: str) -> str: + sanitized = "".join( + character if character.isalnum() or character == "_" else "_" for character in value + ) + if not sanitized: + raise ValueError("USD identifier cannot be empty") + return sanitized if not sanitized[0].isdigit() else f"_{sanitized}" + + +def _usd_string(value: str) -> str: + return value.replace("\\", "\\\\").replace('"', '\\"') + + +def _polygon_mesh( + name: str, + points: list[tuple[float, float]], + z: float, + *, + collision: bool = False, +) -> str: + vertices = ", ".join(f"({x:.9g}, {y:.9g}, {z:.9g})" for x, y in points) + indices = ", ".join(str(index) for index in range(len(points))) + schemas = ' (\n prepend apiSchemas = ["PhysicsCollisionAPI"]\n )' if collision else "" + collision_attribute = "\n bool physics:collisionEnabled = true" if collision else "" + return ( + f' def Mesh "{_usd_identifier(name)}"{schemas} {{\n' + f" point3f[] points = [{vertices}]\n" + f" int[] faceVertexCounts = [{len(points)}]\n" + f" int[] faceVertexIndices = [{indices}]\n" + ' uniform token subdivisionScheme = "none"\n' + f" bool doubleSided = true{collision_attribute}\n" + " }" + ) + + +def _wall_cube( + name: str, + start: tuple[float, float], + end: tuple[float, float], + *, + thickness_m: float, + height_m: float, + base_elevation_m: float, +) -> str: + dx = end[0] - start[0] + dy = end[1] - start[1] + length = math.hypot(dx, dy) + center_x = (start[0] + end[0]) / 2.0 + center_y = (start[1] + end[1]) / 2.0 + yaw = math.degrees(math.atan2(dy, dx)) + return ( + f' def Cube "{_usd_identifier(name)}" (\n' + ' prepend apiSchemas = ["PhysicsCollisionAPI"]\n' + " ) {\n" + " double size = 1\n" + " bool physics:collisionEnabled = true\n" + " double3 xformOp:translate = " + f"({center_x:.9g}, {center_y:.9g}, " + f"{base_elevation_m + height_m / 2.0:.9g})\n" + f" float xformOp:rotateZ = {yaw:.9g}\n" + f" float3 xformOp:scale = ({length:.9g}, {thickness_m:.9g}, " + f"{height_m:.9g})\n" + " uniform token[] xformOpOrder = " + '["xformOp:translate", "xformOp:rotateZ", "xformOp:scale"]\n' + " }" + ) + + +def _single_room_architecture_layer(layout: MetricLayoutSpec) -> str: + height = float(layout.room_dimensions_m[2]) + wall_thickness = 0.08 + walls: list[str] = [] + points = layout.room_polygon_xy_m + for index, (start, end) in enumerate(zip(points, [*points[1:], points[0]], strict=True)): + walls.append( + _wall_cube( + f"Wall_{index:03d}", + start, + end, + thickness_m=wall_thickness, + height_m=height, + base_elevation_m=0.0, + ) + ) + floor = _polygon_mesh("Floor", points, 0.0, collision=True) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n\n' + 'over Xform "World" {\n' + ' def Xform "Architecture" {\n' + f"{floor}\n" + "\n".join(walls) + "\n }\n}\n" + ) + + +def _multi_room_architecture_layer(layout: MultiRoomMetricLayoutSpec) -> str: + rooms = [ + _polygon_mesh( + f"Room_{room.room_id}_Floor", + room.floor_polygon_xy_m, + room.floor_elevation_m, + collision=True, + ) + for room in layout.rooms + ] + walls = [ + _wall_cube( + f"Wall_{index:03d}", + run.start_xy_m, + run.end_xy_m, + thickness_m=layout.wall_thickness_m, + height_m=run.height_m, + base_elevation_m=run.floor_elevation_m, + ) + for index, run in enumerate(multi_room_wall_runs(layout)) + ] + room_by_id = layout.room_by_id + portals: list[str] = [] + for portal in layout.portals: + owners = (room_by_id[portal.room_a_id], room_by_id[portal.room_b_id]) + wall_height = min(room.height_m for room in owners) + floor_elevation = max(room.floor_elevation_m for room in owners) + lintel_height = wall_height - portal.clear_height_m + if lintel_height > 0.01: + portals.append( + _wall_cube( + f"Portal_{portal.portal_id}_Lintel", + portal.opening_segment_xy_m[0], + portal.opening_segment_xy_m[1], + thickness_m=layout.wall_thickness_m, + height_m=lintel_height, + base_elevation_m=floor_elevation + portal.clear_height_m, + ) + ) + if portal.kind != "door": + continue + swing_room = Polygon(room_by_id[portal.swing_room_id or ""].floor_polygon_xy_m) + leaf = door_leaf_polygon(portal, swing_room).minimum_rotated_rectangle + coordinates = list(leaf.exterior.coords)[:-1] + edges = [ + ( + coordinates[index], + coordinates[(index + 1) % len(coordinates)], + ) + for index in range(len(coordinates)) + ] + start, end = max( + edges, + key=lambda edge: math.dist(edge[0], edge[1]), + ) + center = leaf.centroid + yaw = math.degrees(math.atan2(end[1] - start[1], end[0] - start[0])) + leaf_height = min(portal.clear_height_m - 0.04, 2.05) + portals.append( + f' def Xform "Portal_{_usd_identifier(portal.portal_id)}" {{\n' + f' custom string robothousegen_portal_id = "{_usd_string(portal.portal_id)}"\n' + f' custom string robothousegen_room_a_id = "{_usd_string(portal.room_a_id)}"\n' + f' custom string robothousegen_room_b_id = "{_usd_string(portal.room_b_id)}"\n' + ' def Cube "DoorLeaf" (\n' + ' prepend apiSchemas = ["PhysicsCollisionAPI"]\n' + " ) {\n" + " double size = 1\n" + " bool physics:collisionEnabled = true\n" + " double3 xformOp:translate = " + f"({center.x:.9g}, {center.y:.9g}, " + f"{floor_elevation + leaf_height / 2.0:.9g})\n" + f" float xformOp:rotateZ = {yaw:.9g}\n" + f" float3 xformOp:scale = ({portal.clear_width_m:.9g}, " + f"{portal.wall_thickness_m * 0.44:.9g}, {leaf_height:.9g})\n" + " uniform token[] xformOpOrder = " + '["xformOp:translate", "xformOp:rotateZ", "xformOp:scale"]\n' + " }\n" + " }" + ) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n\n' + 'over Xform "World" {\n' + ' def Xform "Architecture" {\n' + ' def Scope "Rooms" {\n' + "\n".join(rooms) + "\n }\n" + ' def Scope "Walls" {\n' + "\n".join(walls) + "\n }\n" + ' def Scope "Portals" {\n' + "\n".join(portals) + "\n }\n" + " }\n}\n" + ) + + +def _architecture_layer( + layout: MetricLayoutSpec | MultiRoomMetricLayoutSpec, +) -> str: + if isinstance(layout, MultiRoomMetricLayoutSpec): + return _multi_room_architecture_layer(layout) + return _single_room_architecture_layer(layout) + + +def _asset_by_entity(asset_lock: list[AssetLockEntry]) -> dict[str, AssetLockEntry]: + bound: dict[str, AssetLockEntry] = {} + for item in asset_lock: + entity_ids = item.entity_ids or [item.role] + for entity_id in entity_ids: + if entity_id in bound: + raise ValueError(f"multiple asset locks bind entity {entity_id}") + bound[entity_id] = item + return bound + + +def _entity_xform(entity: MetricEntityLayout, lock: AssetLockEntry | None) -> str: + name = _usd_identifier(entity.entity_id) + translation_z = entity.base_elevation_m + reference = "" + owns_reference = bool( + lock is not None + and lock.asset_uri + and (not lock.entity_ids or entity.entity_id == lock.role) + ) + if owns_reference and lock is not None: + asset_uri = lock.asset_uri + if asset_uri is None: + raise AssertionError("asset URI was narrowed above") + reference = f" (\n prepend references = @{_usd_string(asset_uri)}@\n )" + dimensions = entity.dimensions_m or (entity.footprint_m[0], entity.footprint_m[1], 0.1) + proxy = "" + if not reference: + translation_z = entity.base_elevation_m + dimensions[2] / 2.0 + proxy = ( + '\n def Cube "LayoutProxy" {\n' + ' uniform token purpose = "guide"\n' + " double size = 1\n" + " float3 xformOp:scale = " + f"({dimensions[0]:.9g}, {dimensions[1]:.9g}, {dimensions[2]:.9g})\n" + ' uniform token[] xformOpOrder = ["xformOp:scale"]\n' + " }" + ) + asset_id = lock.asset_id if lock is not None else entity.asset_id or "unbound" + asset_hash = lock.asset_sha256 if lock is not None else entity.asset_sha256 or "" + room_metadata = ( + f' custom string robothousegen_room_id = "{_usd_string(entity.room_id)}"\n' + if entity.room_id + else "" + ) + return ( + f' def Xform "{name}"{reference} {{\n' + f' custom string robothousegen_entity_id = "{_usd_string(entity.entity_id)}"\n' + f"{room_metadata}" + f' custom string robothousegen_asset_id = "{_usd_string(asset_id)}"\n' + f' custom string robothousegen_asset_sha256 = "{_usd_string(asset_hash)}"\n' + " double3 xformOp:translate = " + f"({entity.center_xy_m[0]:.9g}, {entity.center_xy_m[1]:.9g}, " + f"{translation_z:.9g})\n" + f" float xformOp:rotateZ = {entity.yaw_deg:.9g}\n" + ' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]' + f"{proxy}\n" + " }" + ) + + +def _furniture_layer( + layout: MetricLayoutSpec | MultiRoomMetricLayoutSpec, + asset_lock: list[AssetLockEntry], +) -> str: + bound = _asset_by_entity(asset_lock) + bodies = [_entity_xform(entity, bound.get(entity.entity_id)) for entity in layout.entities] + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n\n' + 'over Xform "World" {\n def Xform "Entities" {\n' + "\n".join(bodies) + "\n }\n}\n" + ) + + +def _validate_asset_payloads(asset_lock: list[AssetLockEntry]) -> None: + checked: set[tuple[str, str]] = set() + for item in asset_lock: + identity = (item.asset_id, item.asset_sha256) + if identity in checked: + continue + checked.add(identity) + if not item.asset_uri: + raise ValueError(f"asset lock has no immutable payload URI: {item.asset_id}") + if "://" in item.asset_uri: + continue + payload = Path(item.asset_uri).expanduser() + if not payload.is_absolute(): + payload = payload.resolve() + if not payload.is_file(): + raise FileNotFoundError(f"locked asset payload is missing: {payload}") + digest = _sha256(payload) + if digest != item.asset_sha256: + raise ValueError( + f"locked asset payload hash differs for {item.asset_id}: " + f"{digest} != {item.asset_sha256}" + ) + + +def _regions_layer( + layout: MetricLayoutSpec | MultiRoomMetricLayoutSpec, +) -> str: + bodies = [ + _polygon_mesh(f"Zone_{zone.zone_id}", zone.polygon_xy_m, 0.002) for zone in layout.zones + ] + if isinstance(layout, MultiRoomMetricLayoutSpec): + bodies.extend( + _polygon_mesh( + f"RoomRegion_{room.room_id}", + room.floor_polygon_xy_m, + room.floor_elevation_m + 0.001, + ) + for room in layout.rooms + ) + bodies.extend( + _polygon_mesh( + f"DoorSweep_{portal.portal_id}", + portal.swing_polygon_xy_m, + layout.room_by_id[portal.swing_room_id or ""].floor_elevation_m + 0.006, + ) + for portal in layout.portals + if portal.kind == "door" + ) + bodies.append(_polygon_mesh("NavigationRoute", layout.route_polygon_xy_m, 0.004)) + bodies.extend( + _polygon_mesh(f"KeepOut_{region.region_id}", region.polygon_xy_m, 0.006) + for region in layout.keep_out_regions + ) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n\n' + 'over Xform "World" {\n def Scope "Regions" {\n' + "\n".join(bodies) + "\n }\n}\n" + ) + + +def _metadata_layer(role: str, task_id: str) -> str: + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n' + " customLayerData = {\n" + f' string robothousegen_task_id = "{_usd_string(task_id)}"\n' + f' string robothousegen_layer_role = "{_usd_string(role)}"\n' + " }\n)\n" + ) + + +def _root_layer(layer_uris: dict[str, str]) -> str: + ordered = [layer_uris[name] for name in BASE_LAYER_ORDER if name in layer_uris] + sublayers = ",\n ".join(f"@{_usd_string(uri)}@" for uri in ordered) + return ( + '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' + f" subLayers = [\n {sublayers}\n ]\n" + ' upAxis = "Z"\n)\n\ndef Xform "World" {}\n' + ) + + +class SceneBundleCompiler: + """Compile immutable Metric V2/V3 truth into a robot-free SceneBundle directory.""" + + version = "3.0" + + def compile( + self, + *, + plugin_spec: TaskPluginSpec, + compilation: TaskPluginCompilation, + metric_layout: MetricLayoutSpec | MultiRoomMetricLayoutSpec, + output_dir: Path, + asset_lock: list[AssetLockEntry], + robot_start: RobotStart | None = None, + visual_provider_config: dict[str, object] | None = None, + require_asset_locks: bool = True, + verify_asset_payloads: bool = True, + runtime_bindings: SceneRuntimeBindings | None = None, + layered_scene_plan: LayeredScenePlan | None = None, + ) -> SceneBundle: + output_dir = output_dir.resolve() + if output_dir.exists(): + raise FileExistsError(f"refusing to overwrite SceneBundle output: {output_dir}") + output_dir.parent.mkdir(parents=True, exist_ok=True) + + task_entities = { + entity.entity_id + for entity in compilation.task_spec.entities + if entity.required and entity.role not in {"REGION", "ROBOT"} + } + layout_entities = {entity.entity_id for entity in metric_layout.entities} + if task_entities != layout_entities: + raise ValueError( + "MetricLayoutSpec entity set differs from required TaskSpec entities: " + f"task_only={sorted(task_entities - layout_entities)} " + f"layout_only={sorted(layout_entities - task_entities)}" + ) + if isinstance(metric_layout, MultiRoomMetricLayoutSpec): + available_rooms = { + value for room in metric_layout.rooms for value in (room.room_id, room.room_type) + } + missing_rooms = set(compilation.task_spec.required_rooms) - available_rooms + if missing_rooms: + raise ValueError( + "TaskSpec requires rooms absent from multi-room layout: " + f"{sorted(missing_rooms)}" + ) + layout_entity_by_id = metric_layout.entity_by_id + room_by_id = metric_layout.room_by_id + for task_entity in compilation.task_spec.entities: + declared_room = task_entity.attributes.get("room") + if ( + not isinstance(declared_room, str) + or task_entity.entity_id not in layout_entity_by_id + ): + continue + layout_entity = layout_entity_by_id[task_entity.entity_id] + room_id = layout_entity.room_id or "" + room = room_by_id.get(room_id) + if room is None or declared_room not in {room.room_id, room.room_type}: + raise ValueError( + f"TaskSpec entity {task_entity.entity_id} room differs from layout" + ) + bound = _asset_by_entity(asset_lock) + missing = layout_entities - set(bound) + if require_asset_locks and missing: + raise ValueError(f"required scene entities have no asset lock: {sorted(missing)}") + if verify_asset_payloads: + _validate_asset_payloads(asset_lock) + for entity in metric_layout.entities: + lock = bound.get(entity.entity_id) + if entity.asset_locked and ( + lock is None + or lock.asset_id != entity.asset_id + or lock.asset_sha256 != entity.asset_sha256 + ): + raise ValueError(f"asset lock does not match MetricLayoutSpec: {entity.entity_id}") + + validation = validate_task_plugin_compilation(plugin_spec, compilation) + if not validation.passed: + raise ValueError("task plugin static validation failed") + if runtime_bindings is not None: + if runtime_bindings.task_id != compilation.task_spec.task_id: + raise ValueError("runtime bindings task_id differs from TaskSpec") + bound_entities = {item.entity_id for item in runtime_bindings.entity_bindings} + if bound_entities != layout_entities: + raise ValueError( + "runtime binding entity set differs from MetricLayoutSpec: " + f"missing={sorted(layout_entities - bound_entities)} " + f"extra={sorted(bound_entities - layout_entities)}" + ) + elif "joint_position" in compilation.evaluator_spec.required_observation_streams: + raise ValueError("joint-position evaluator requires explicit runtime USD bindings") + if layered_scene_plan is not None: + if layered_scene_plan.task_id != compilation.task_spec.task_id: + raise ValueError("layered scene plan task_id differs from TaskSpec") + expected_layout_hash = canonical_sha256(metric_layout.model_dump(mode="json")) + if layered_scene_plan.metric_layout_sha256 != expected_layout_hash: + raise ValueError("layered scene plan is not bound to MetricLayoutSpec") + staging = output_dir.parent / f".{output_dir.name}.tmp-{uuid.uuid4().hex[:12]}" + staging.mkdir(parents=False, exist_ok=False) + manifests = staging / "manifests" + layers = staging / "layers" + manifests.mkdir() + layers.mkdir() + layer_uris = { + "root": "root.usda", + **{name: f"layers/{name}.usda" for name in BASE_LAYER_ORDER}, + } + atomic_write_text(layers / "architecture.usda", _architecture_layer(metric_layout)) + atomic_write_text(layers / "furniture.usda", _furniture_layer(metric_layout, asset_lock)) + atomic_write_text(layers / "regions.usda", _regions_layer(metric_layout)) + for name in set(BASE_LAYER_ORDER) - {"architecture", "furniture", "regions"}: + atomic_write_text( + layers / f"{name}.usda", + _metadata_layer(name, compilation.task_spec.task_id), + ) + atomic_write_text(staging / "root.usda", _root_layer(layer_uris)) + atomic_write_text( + manifests / "metric_layout_spec.json", + metric_layout.model_dump_json(indent=2) + "\n", + ) + atomic_write_text( + manifests / "task_spec.json", + compilation.task_spec.model_dump_json(indent=2) + "\n", + ) + atomic_write_text( + manifests / "scene_requirements.json", + compilation.scene_requirements.model_dump_json(indent=2) + "\n", + ) + atomic_write_text( + manifests / "evaluator_spec.json", + compilation.evaluator_spec.model_dump_json(indent=2) + "\n", + ) + atomic_write_text( + manifests / "oracle_witness.json", + json.dumps(compilation.witness, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + atomic_write_text( + manifests / "asset_lock.json", + json.dumps( + [item.model_dump(mode="json") for item in asset_lock], + ensure_ascii=False, + indent=2, + sort_keys=True, + ) + + "\n", + ) + atomic_write_text( + manifests / "task_plugin_static_validation.json", + validation.model_dump_json(indent=2) + "\n", + ) + multi_room_validation: dict[str, object] | None = None + if isinstance(metric_layout, MultiRoomMetricLayoutSpec): + multi_room_validation = build_multi_room_validation_report(metric_layout) + if not multi_room_validation["passed"]: + raise ValueError("multi-room hard validation failed") + atomic_write_text( + manifests / "multi_room_validation.json", + json.dumps( + multi_room_validation, + ensure_ascii=False, + indent=2, + sort_keys=True, + ) + + "\n", + ) + if runtime_bindings is not None: + atomic_write_text( + manifests / "runtime_bindings.json", + runtime_bindings.model_dump_json(indent=2) + "\n", + ) + if layered_scene_plan is not None: + atomic_write_text( + manifests / "layered_scene_plan.json", + layered_scene_plan.model_dump_json(indent=2) + "\n", + ) + + geometry_lock = MetricV2Provider().lock( + metric_layout, + { + "task_plugin": compilation.plugin_id, + "task_plugin_version": compilation.plugin_version, + "compiler_version": self.version, + "topology_kind": ( + "multi_room" + if isinstance(metric_layout, MultiRoomMetricLayoutSpec) + else "single_room" + ), + }, + ) + provider_locks = [geometry_lock] + if visual_provider_config is not None: + provider_locks.append( + SceneSmithVisualProvider().lock(geometry_lock, visual_provider_config) + ) + artifact_hashes = { + path.relative_to(staging).as_posix(): _sha256(path) + for path in sorted(staging.rglob("*")) + if path.is_file() + } + stance_zone = ( + compilation.scene_requirements.stance_zones[0] + if compilation.scene_requirements.stance_zones + else None + ) + start = robot_start or RobotStart( + translation_m=( + float(metric_layout.robot_start_xy_m[0]), + float(metric_layout.robot_start_xy_m[1]), + 0.0, + ), + yaw_deg=0.0, + stance_zone=stance_zone, + ) + bundle = SceneBundle( + bundle_id=f"bundle.{compilation.task_spec.task_id.removeprefix('task-')}", + scene_id=f"scene-{compilation.task_spec.task_id.removeprefix('task-')}", + task_spec=compilation.task_spec, + scene_requirements=compilation.scene_requirements, + metric_layout_spec=metric_layout, + evaluator_spec=compilation.evaluator_spec, + provider_locks=provider_locks, + layer_uris=layer_uris, + asset_lock=asset_lock, + robot_start=start, + runtime_bindings_uri=( + "manifests/runtime_bindings.json" if runtime_bindings is not None else None + ), + layered_scene_plan_uri=( + "manifests/layered_scene_plan.json" if layered_scene_plan is not None else None + ), + validation_report_uris=[ + "manifests/task_plugin_static_validation.json", + *( + ["manifests/multi_room_validation.json"] + if multi_room_validation is not None + else [] + ), + ], + provenance={ + "compiler": f"SceneBundleCompiler/{self.version}", + "compiled_at": datetime.now(UTC).isoformat(), + "metric_layout_sha256": canonical_sha256(metric_layout), + "task_spec_sha256": canonical_sha256(compilation.task_spec), + "runtime_bindings_sha256": ( + canonical_sha256(runtime_bindings) if runtime_bindings is not None else None + ), + "layered_scene_plan_sha256": ( + canonical_sha256(layered_scene_plan) if layered_scene_plan is not None else None + ), + "artifact_sha256": artifact_hashes, + "output_policy": "new-directory-atomic-rename", + "robot_included": False, + "topology": ( + { + "kind": "multi_room", + "room_count": len(metric_layout.rooms), + "portal_count": len(metric_layout.portals), + "route_room_ids": metric_layout.route_room_ids, + "route_portal_ids": metric_layout.route_portal_ids, + } + if isinstance(metric_layout, MultiRoomMetricLayoutSpec) + else {"kind": "single_room", "room_count": 1} + ), + }, + ) + atomic_write_text( + manifests / "scene_bundle.json", + bundle.model_dump_json(indent=2) + "\n", + ) + if output_dir.exists(): + raise FileExistsError( + f"SceneBundle destination appeared during compilation: {output_dir}" + ) + os.replace(staging, output_dir) + return bundle diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/compiler.py b/docs/reproduction/public_conversion_code/packages/scene_generation/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac89eb8b7537b4af306fa967c0bb29b2a977201 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/compiler.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import os +from pathlib import Path + +import yaml # type: ignore[import-untyped] + +from packages.adapters.scenesmith import ( + RoboLabSceneObject, + RoboLabScenePredicate, + RoboLabSceneRequest, +) +from packages.schemas.models import PredicateSpec, TaskEntity, TaskSpec + + +class SceneRequestCompiler: + """Compile simulator-independent task entities into the RoboLab scene-gen wire format.""" + + def __init__(self, policy_path: Path | None = None) -> None: + declared = policy_path or Path( + os.environ.get("RHG_SCENE_COMPILER_POLICY", "configs/scene_generation/compiler_v1.yaml") + ) + if not declared.is_absolute() and not declared.is_file(): + declared = Path(__file__).resolve().parents[2] / declared + payload = yaml.safe_load(declared.read_text(encoding="utf-8")) + placement = payload["placement"] + self.floor_mounted_categories = set(placement["floor_mounted_categories"]) + self.floor_mounted_category_markers = tuple(placement["floor_mounted_category_markers"]) + + def compile(self, task: TaskSpec) -> RoboLabSceneRequest: + physical_entities = [ + entity + for entity in task.entities + if entity.role not in {"REGION", "ROBOT"} + and "procedural_geometry" not in entity.attributes + ] + if not physical_entities: + raise ValueError("SceneSmith requires at least one physical task entity") + objects = [RoboLabSceneObject(name=entity.entity_id) for entity in physical_entities] + known = {entity.entity_id for entity in physical_entities} + predicates: list[RoboLabScenePredicate] = [] + seen_predicates: set[str] = set() + placed: set[str] = set() + for predicate in task.initial_predicates: + compiled = self._compile_predicate(predicate, known) + if compiled is not None: + key = compiled.model_dump_json(exclude_none=True) + if key not in seen_predicates: + predicates.append(compiled) + seen_predicates.add(key) + placed.update(compiled.target_objects()) + for entity in physical_entities: + if entity.entity_id not in placed: + predicates.append(self._default_placement(entity)) + return RoboLabSceneRequest(objects=objects, predicates=predicates) + + @staticmethod + def _compile_predicate( + predicate: PredicateSpec, known: set[str] + ) -> RoboLabScenePredicate | None: + if predicate.subject not in known: + return None + support_relation = str(predicate.params.get("support_relation", "")).casefold() + if support_relation in {"false", "none", "not_supported", "unsupported"}: + return None + if predicate.name in {"on", "supported_by"} and predicate.object in known: + return RoboLabScenePredicate( + type="place-on", object=predicate.subject, support=predicate.object + ) + if predicate.name == "inside" and predicate.object in known: + return RoboLabScenePredicate( + type="place-in", objects=[predicate.subject], container=predicate.object + ) + if predicate.name == "near" and predicate.object in known: + return RoboLabScenePredicate( + type="front-of", object=predicate.subject, reference=predicate.object + ) + return None + + def _default_placement(self, entity: TaskEntity) -> RoboLabScenePredicate: + mount = str(entity.attributes.get("mount", "")).upper() + floor_mounted = entity.attributes.get("floor_mounted") is True + category = entity.category.casefold().replace("-", "_").replace(" ", "_") + if ( + entity.role == "BACKGROUND" + or mount == "FLOOR" + or floor_mounted + or category in self.floor_mounted_categories + or any(marker in category for marker in self.floor_mounted_category_markers) + ): + return RoboLabScenePredicate(type="place-on-base", object=entity.entity_id) + return RoboLabScenePredicate(type="place-anywhere", object=entity.entity_id) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/conflict_resampling.py b/docs/reproduction/public_conversion_code/packages/scene_generation/conflict_resampling.py new file mode 100644 index 0000000000000000000000000000000000000000..36c8b890e91160176c8342fffb7d6e04a64f9438 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/conflict_resampling.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import re +from collections import deque +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field + + +class ConflictDiagnosis(BaseModel): + """Bounded diagnosis used to preserve unaffected scene entities.""" + + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["1.0"] = "1.0" + reason: str + directly_conflicting_entity_ids: list[str] = Field(default_factory=list) + resample_entity_ids: list[str] = Field(default_factory=list) + preserved_entity_ids: list[str] = Field(default_factory=list) + fallback_full_resample: bool = False + + +def diagnose_conflict( + reason: str, + *, + entity_ids: list[str], + dependency_graph: dict[str, set[str]] | None = None, +) -> ConflictDiagnosis: + """Find exact entity tokens and include only their downstream dependents. + + ``dependency_graph`` maps an entity to entities whose placement or diversity + constraint depends on it. If an error names no entity, the caller receives + an explicit full-resample fallback instead of silently guessing a culprit. + """ + + known = list(dict.fromkeys(entity_ids)) + boundaries = { + entity_id: re.compile( + rf"(? str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _font(size: int) -> ImageFont.ImageFont: + for candidate in ( + Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"), + Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"), + ): + if candidate.is_file(): + return ImageFont.truetype(str(candidate), size=size) + return ImageFont.load_default() + + +def _quality_grade(score: float) -> str: + if score >= 90: + return "A" + if score >= 80: + return "B" + if score >= 70: + return "C" + return "D" + + +def _descriptor_rows(index: Path) -> list[dict[str, Any]]: + connection = sqlite3.connect(f"file:{index.resolve()}?mode=ro", uri=True) + try: + return [ + json.loads(row[0]) + for row in connection.execute( + "select descriptor_json from asset_descriptors" + ) + ] + finally: + connection.close() + + +def _inventory(index: Path, output: Path) -> dict[str, Any]: + descriptors = [item for item in _descriptor_rows(index) if item.get("status") == "ACTIVE"] + used = [ + json.loads(path.read_text(encoding="utf-8")) + for path in sorted((output / "asset_descriptors").glob("*/asset_descriptor.json")) + ] + used_entity_by_asset = { + json.loads(path.read_text(encoding="utf-8"))["asset_id"]: path.parent.name + for path in sorted((output / "asset_descriptors").glob("*/asset_descriptor.json")) + } + + source_stats: dict[str, dict[str, Any]] = defaultdict( + lambda: { + "active_assets": 0, + "categories": Counter(), + "formats": Counter(), + "licenses": Counter(), + "grades": Counter(), + "quality_sums": Counter(), + "isaac_ready": 0, + "high_fidelity_tagged": 0, + } + ) + category_stats: dict[str, dict[str, Any]] = defaultdict( + lambda: { + "active_assets": 0, + "sources": Counter(), + "grades": Counter(), + "quality_total": 0.0, + } + ) + for item in descriptors: + source = str(item.get("source") or "Unknown") + category = str(item.get("category") or "unknown") + quality = dict(item.get("quality") or {}) + overall = float(quality.get("overall") or 0.0) + source_item = source_stats[source] + source_item["active_assets"] += 1 + source_item["categories"][category] += 1 + source_item["formats"][str(item.get("geometry_format") or "unknown")] += 1 + source_item["licenses"][str(item.get("source_license") or "unknown")] += 1 + source_item["grades"][_quality_grade(overall)] += 1 + for key in ("overall", "geometry", "materials", "realism"): + source_item["quality_sums"][key] += float(quality.get(key) or 0.0) + compatibility = dict(item.get("loader_compatibility") or {}) + if compatibility.get("isaac_sim") in {"compatible", "verified"}: + source_item["isaac_ready"] += 1 + if "high_fidelity" in (item.get("semantic_tags") or []): + source_item["high_fidelity_tagged"] += 1 + + category_item = category_stats[category] + category_item["active_assets"] += 1 + category_item["sources"][source] += 1 + category_item["grades"][_quality_grade(overall)] += 1 + category_item["quality_total"] += overall + + used_source_counts = Counter(str(item.get("source") or "Unknown") for item in used) + source_rows = [] + for source, item in sorted(source_stats.items()): + count = int(item["active_assets"]) + source_rows.append( + { + "source": source, + "used_in_scene": used_source_counts[source], + "active_assets": count, + "category_count": len(item["categories"]), + "top_categories": item["categories"].most_common(8), + "formats": dict(item["formats"].most_common()), + "licenses": dict(item["licenses"].most_common()), + "quality_grade_counts": dict(item["grades"]), + "quality_average": { + key: round(float(item["quality_sums"][key]) / max(count, 1), 2) + for key in ("overall", "geometry", "materials", "realism") + }, + "isaac_ready": int(item["isaac_ready"]), + "isaac_ready_percent": round(100.0 * item["isaac_ready"] / max(count, 1), 2), + "high_fidelity_tagged": int(item["high_fidelity_tagged"]), + } + ) + category_rows = [ + { + "category": category, + "active_assets": int(item["active_assets"]), + "source_count": len(item["sources"]), + "sources": dict(item["sources"].most_common()), + "quality_average": round( + float(item["quality_total"]) / max(int(item["active_assets"]), 1), 2 + ), + "quality_grade_counts": dict(item["grades"]), + } + for category, item in sorted( + category_stats.items(), key=lambda value: (-value[1]["active_assets"], value[0]) + ) + ] + used_rows = [] + for item in used: + quality = dict(item.get("quality") or {}) + overall = float(quality.get("overall") or 0.0) + used_rows.append( + { + "entity_id": used_entity_by_asset.get(item["asset_id"], "unknown"), + "asset_id": item["asset_id"], + "display_name": item.get("display_name"), + "source": item.get("source"), + "category": item.get("category"), + "subcategory": item.get("subcategory"), + "format": item.get("geometry_format"), + "dimensions_m": item.get("native_bbox_m"), + "material_tags": item.get("material_tags") or [], + "quality": quality, + "quality_grade": _quality_grade(overall), + "isaac_compatibility": (item.get("loader_compatibility") or {}).get( + "isaac_sim", "not_tested" + ), + } + ) + return { + "schema_version": "1.0", + "generated_at": datetime.now(UTC).isoformat(), + "descriptor_index": str(index.resolve()), + "descriptor_index_sha256": _sha256(index), + "active_asset_count": len(descriptors), + "source_library_count": len(source_rows), + "category_count": len(category_rows), + "used_asset_count": len(used_rows), + "used_source_counts": dict(sorted(used_source_counts.items())), + "used_assets": used_rows, + "source_libraries": source_rows, + "categories": category_rows, + } + + +def _render_layout(layout_path: Path, target: Path) -> None: + layout = json.loads(layout_path.read_text(encoding="utf-8")) + rooms = list(layout.get("rooms") or []) + if not rooms: + polygon = layout.get("room_polygon_xy_m") or [] + rooms = [{"room_id": "room", "room_type": "room", "floor_polygon_xy_m": polygon}] + all_points = [tuple(point) for room in rooms for point in room["floor_polygon_xy_m"]] + min_x = min(point[0] for point in all_points) + max_x = max(point[0] for point in all_points) + min_y = min(point[1] for point in all_points) + max_y = max(point[1] for point in all_points) + width_px, height_px, margin = 1600, 1000, 90 + scale = min( + (width_px - 2 * margin) / max(max_x - min_x, 1.0e-6), + (height_px - 2 * margin) / max(max_y - min_y, 1.0e-6), + ) + + def pixel(point: tuple[float, float]) -> tuple[int, int]: + return ( + int(round(margin + (point[0] - min_x) * scale)), + int(round(height_px - margin - (point[1] - min_y) * scale)), + ) + + image = Image.new("RGB", (width_px, height_px), (247, 248, 249)) + draw = ImageDraw.Draw(image, "RGBA") + colors = ((220, 236, 243, 255), (240, 230, 204, 255), (222, 238, 218, 255)) + title_font, room_font, label_font = _font(32), _font(23), _font(17) + for index, room in enumerate(rooms): + points = [pixel(tuple(point)) for point in room["floor_polygon_xy_m"]] + draw.polygon(points, fill=colors[index % len(colors)]) + label_x = min(point[0] for point in points) + 22 + label_y = min(point[1] for point in points) + 18 + room_type = str(room.get("room_type") or "") + room_label = str(room["room_id"]) + if room_type and room_type != room_label: + room_label += f"\n{room_type}" + draw.text( + (label_x, label_y), + room_label, + fill=(31, 42, 51, 255), + font=room_font, + anchor="la", + align="left", + ) + route = layout.get("route_polygon_xy_m") or [] + if route: + draw.polygon( + [pixel(tuple(point)) for point in route], + fill=(67, 160, 103, 70), + outline=(28, 121, 65, 230), + width=4, + ) + room_boundaries = unary_union( + [Polygon(room["floor_polygon_xy_m"]).boundary for room in rooms] + ) + portal_cuts = unary_union( + [ + LineString(portal["opening_segment_xy_m"]).buffer(1.0e-4, cap_style=2) + for portal in layout.get("portals") or [] + ] + ) + visible_walls = room_boundaries.difference(portal_cuts) + wall_lines = ( + list(visible_walls.geoms) + if isinstance(visible_walls, MultiLineString) + else [visible_walls] + ) + for line in wall_lines: + if not isinstance(line, LineString): + continue + coordinates = list(line.coords) + for start, end in zip(coordinates, coordinates[1:], strict=False): + draw.line( + [pixel(tuple(start)), pixel(tuple(end))], + fill=(35, 44, 52, 255), + width=8, + ) + for portal in layout.get("portals") or []: + segment = [pixel(tuple(point)) for point in portal["opening_segment_xy_m"]] + for endpoint in segment: + draw.ellipse( + (endpoint[0] - 7, endpoint[1] - 7, endpoint[0] + 7, endpoint[1] + 7), + fill=(20, 116, 176, 255), + ) + center = ( + (segment[0][0] + segment[1][0]) // 2, + (segment[0][1] + segment[1][1]) // 2, + ) + draw.text(center, portal["portal_id"], fill=(11, 64, 100, 255), font=label_font, anchor="ms") + task_path = layout_path.parent / "pick_move_place_task.json" + task = json.loads(task_path.read_text(encoding="utf-8")) if task_path.is_file() else {} + task_route = [pixel(tuple(point)) for point in task.get("route_waypoints_xy_m") or []] + if len(task_route) >= 2: + draw.line(task_route, fill=(13, 137, 169, 255), width=7, joint="curve") + for point in task.get("portal_waypoints_xy_m") or []: + center = pixel(tuple(point)) + draw.ellipse( + (center[0] - 9, center[1] - 9, center[0] + 9, center[1] + 9), + fill=(255, 255, 255, 255), + outline=(13, 137, 169, 255), + width=4, + ) + entity_records = [] + center_groups: dict[tuple[float, float], list[str]] = defaultdict(list) + for entity in layout.get("entities") or []: + center_key = tuple(round(float(value), 5) for value in entity["center_xy_m"]) + center_groups[center_key].append(entity["entity_id"]) + entity_records.append((entity, center_key)) + for entity, center_key in entity_records: + footprint = entity.get("visual_footprint_xy_m") or [] + if footprint: + points = [pixel(tuple(point)) for point in footprint] + else: + center = entity["center_xy_m"] + size = entity["footprint_m"] + points = [ + pixel((center[0] - size[0] / 2, center[1] - size[1] / 2)), + pixel((center[0] + size[0] / 2, center[1] - size[1] / 2)), + pixel((center[0] + size[0] / 2, center[1] + size[1] / 2)), + pixel((center[0] - size[0] / 2, center[1] + size[1] / 2)), + ] + draw.polygon(points, fill=(64, 72, 82, 210), outline=(20, 26, 31, 255)) + center = pixel(tuple(entity["center_xy_m"])) + siblings = center_groups[center_key] + sibling_index = siblings.index(entity["entity_id"]) + label_x = max(point[0] for point in points) + 12 + label_y = center[1] + int((sibling_index - (len(siblings) - 1) / 2.0) * 28) + label = entity["entity_id"] + bounds = draw.textbbox((label_x, label_y), label, font=label_font, anchor="lm") + draw.rounded_rectangle( + (bounds[0] - 5, bounds[1] - 3, bounds[2] + 5, bounds[3] + 3), + radius=3, + fill=(255, 255, 255, 225), + outline=(95, 106, 115, 180), + ) + draw.line((center, (label_x - 5, label_y)), fill=(73, 83, 92, 220), width=2) + draw.text((label_x, label_y), label, fill=(30, 39, 47, 255), font=label_font, anchor="lm") + draw.text( + (margin, 32), + "RoboHouseGen Metric Layout", + fill=(25, 35, 44, 255), + font=title_font, + ) + draw.text( + (margin, height_px - 28), + "Blue endpoints: portal Cyan: actual task path Green: route corridor", + fill=(55, 65, 73, 255), + font=label_font, + anchor="ls", + ) + target.parent.mkdir(parents=True, exist_ok=True) + image.save(target, format="PNG", optimize=True) + + +def _dashboard_html(inventory: dict[str, Any]) -> str: + data = json.dumps(inventory, ensure_ascii=False).replace("" + f"{html.escape(str(item['entity_id']))}{html.escape(str(item['asset_id']))}" + f"{html.escape(str(item['display_name']))}" + f"{html.escape(str(item['source']))}" + f"{html.escape(str(item['category']))}" + f"{' × '.join(f'{float(value):.3f}' for value in item['dimensions_m'])}" + f"{item['quality_grade']} {float(item['quality'].get('overall', 0)):.1f}" + f"{html.escape(str(item['isaac_compatibility']))}" + "" + for item in inventory["used_assets"] + ) + source_rows = "".join( + "" + f"{html.escape(item['source'])}" + f"{item['used_in_scene']}{item['active_assets']:,}" + f"{item['category_count']}" + f"{item['quality_average']['overall']:.2f}" + f"{item['quality_average']['geometry']:.2f}" + f"{item['quality_average']['materials']:.2f}" + f"{item['isaac_ready_percent']:.2f}%" + "" + for item in inventory["source_libraries"] + ) + return f""" + +RoboHouseGen 资产与布局看板

RoboHouseGen 资产与布局看板

场景用量、ACTIVE 库存、类别分布与保真度审计

+
{inventory['used_asset_count']}本场景使用资产
{inventory['active_asset_count']:,}ACTIVE 资产总量
{inventory['source_library_count']}资产来源库
{inventory['category_count']}资产类别
+

布局证据

Metric V3 2D layout
Metric V3 二维图纸:房间、portal、路线与绑定实体
Rendered top view
Blender 实际场景正交顶视图
+

本场景实际资产

{used_rows}
实体 / Asset ID名称来源库类别尺寸 m质量Isaac
+

来源库库存与平均保真度

{source_rows}
来源库场景使用ACTIVE类别数综合质量几何材质Isaac Ready
+

类别库存

类别ACTIVE 数量来源库数综合质量均值A/B/C/D来源分布
+
索引:{html.escape(inventory['descriptor_index'])}
SHA-256:{inventory['descriptor_index_sha256']}
生成时间:{inventory['generated_at']}
+
""" + + +def build_asset_first_delivery_reports(output: Path, descriptor_index: Path) -> dict[str, Any]: + output = output.resolve() + reports = output / "reports" + layout_dir = reports / "layout" + layout_dir.mkdir(parents=True, exist_ok=True) + layout_path = ( + output / "metric_layout_spec_v3.json" + if (output / "metric_layout_spec_v3.json").is_file() + else output / "metric_layout_spec.json" + ) + _render_layout(layout_path, layout_dir / "metric-v3-layout.png") + top_view = output / "validation_views" / "005_metric_top.png" + if top_view.is_file(): + shutil.copy2(top_view, layout_dir / "rendered-top-view.png") + placement_blueprint = output / "rich_metric_blueprint.png" + if placement_blueprint.is_file(): + shutil.copy2(placement_blueprint, layout_dir / "asset-placement-blueprint.png") + inventory = _inventory(descriptor_index.resolve(), output) + atomic_write_text( + reports / "asset_inventory.json", + json.dumps(inventory, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + atomic_write_text(reports / "asset_dashboard.html", _dashboard_html(inventory)) + artifacts = [ + path + for path in ( + layout_dir / "metric-v3-layout.png", + layout_dir / "rendered-top-view.png", + layout_dir / "asset-placement-blueprint.png", + reports / "asset_inventory.json", + reports / "asset_dashboard.html", + ) + if path.is_file() + ] + manifest = { + "schema_version": "1.0", + "reports_dir": str(reports), + "layout_source": str(layout_path), + "artifacts": [ + { + "path": str(path.relative_to(output)), + "sha256": _sha256(path), + "size_bytes": path.stat().st_size, + } + for path in artifacts + ], + } + atomic_write_text( + reports / "report_manifest.json", + json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + ) + return manifest diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/dependency_graph.py b/docs/reproduction/public_conversion_code/packages/scene_generation/dependency_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..d83cebe9b26e29a557515ba48511cf96e78afafa --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/dependency_graph.py @@ -0,0 +1,435 @@ +from __future__ import annotations + +import os +from collections import defaultdict +from pathlib import Path +from typing import Any, Literal, cast + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator + +SceneStage = Literal[ + "architecture", + "furniture", + "wall_mounted", + "ceiling_mounted", + "manipulation", + "postprocess", +] +ExecutionMode = Literal["agent", "analytic", "native_usd", "external"] + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class ArchitectureNodePolicy(_StrictModel): + node_id: str = Field(min_length=1) + stage: Literal["architecture"] = "architecture" + execution: ExecutionMode = "agent" + depends_on: list[str] = Field(default_factory=list) + + +class DependencyInferencePolicy(_StrictModel): + dependency_predicates: set[str] + role_stages: dict[str, SceneStage] + mount_stages: dict[str, SceneStage] + stage_default_dependencies: dict[SceneStage, list[str]] + stage_execution: dict[SceneStage, ExecutionMode] + + +class DependencySchedulerPolicy(_StrictModel): + max_parallel_branches: int = Field(default=0, ge=0) + branch_failure_policy: Literal["fail_fast", "fail_critical_skip_context"] + merge_policy: Literal["owned_delta_only"] = "owned_delta_only" + wave_barrier: bool = True + final_global_validation: bool = True + resource_class_by_stage: dict[SceneStage, str] + + +class DependencySchedulerOverride(_StrictModel): + max_parallel_branches: int | None = Field(default=None, ge=0) + branch_failure_policy: Literal["fail_fast", "fail_critical_skip_context"] | None = None + wave_barrier: bool | None = None + final_global_validation: bool | None = None + + +class SceneDependencyPolicy(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + architecture: list[ArchitectureNodePolicy] = Field(min_length=1) + inference: DependencyInferencePolicy + scheduler: DependencySchedulerPolicy + + +class DependencyNodeOverride(_StrictModel): + node_id: str = Field(min_length=1) + depends_on: list[str] | None = None + add_dependencies: list[str] = Field(default_factory=list) + stage: SceneStage | None = None + execution: ExecutionMode | None = None + critical: bool | None = None + + +class DependencyGraphOverrides(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + nodes: list[DependencyNodeOverride] = Field(default_factory=list) + scheduler: DependencySchedulerOverride | None = None + + @model_validator(mode="after") + def validate_unique_nodes(self) -> DependencyGraphOverrides: + ids = [node.node_id for node in self.nodes] + if len(ids) != len(set(ids)): + raise ValueError("dependency_graph override node IDs must be unique") + return self + + +class SceneDependencyNode(_StrictModel): + node_id: str = Field(min_length=1) + kind: Literal["architecture", "entity", "context_asset"] + stage: SceneStage + execution: ExecutionMode + depends_on: list[str] = Field(default_factory=list) + critical: bool = True + entity_id: str | None = None + category: str | None = None + asset_id: str | None = None + metadata: dict[str, Any] = Field(default_factory=dict) + + +class SceneDependencyBranch(_StrictModel): + branch_id: str + root_node_id: str + node_ids: list[str] + critical: bool + stages: list[SceneStage] + + +class SceneDependencyWave(_StrictModel): + wave_index: int = Field(ge=0) + node_ids: list[str] + branch_ids: list[str] + resource_classes: list[str] + + +class SceneDependencyGraph(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + graph_id: str + nodes: list[SceneDependencyNode] + branches: list[SceneDependencyBranch] + waves: list[SceneDependencyWave] + scheduler: DependencySchedulerPolicy + + @model_validator(mode="after") + def validate_graph(self) -> SceneDependencyGraph: + ids = [node.node_id for node in self.nodes] + if len(ids) != len(set(ids)): + raise ValueError("scene dependency node IDs must be unique") + known = set(ids) + missing = { + dependency + for node in self.nodes + for dependency in node.depends_on + if dependency not in known + } + if missing: + raise ValueError(f"scene dependency graph references unknown nodes: {sorted(missing)}") + _topological_levels({node.node_id: set(node.depends_on) for node in self.nodes}) + return self + + +DEFAULT_DEPENDENCY_POLICY = ( + Path(__file__).resolve().parents[2] + / "configs" + / "scene_generation" + / "dependency_graph_v1.yaml" +) + + +def load_dependency_policy(path: Path | None = None) -> SceneDependencyPolicy: + selected = path or Path( + os.environ.get("RHG_SCENE_DEPENDENCY_POLICY", DEFAULT_DEPENDENCY_POLICY) + ) + payload = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8")) + return SceneDependencyPolicy.model_validate(payload) + + +def _topological_levels(dependencies: dict[str, set[str]]) -> list[list[str]]: + remaining = {node_id: set(values) for node_id, values in dependencies.items()} + levels: list[list[str]] = [] + completed: set[str] = set() + while remaining: + ready = sorted( + node_id for node_id, values in remaining.items() if values <= completed + ) + if not ready: + cycle_nodes = sorted(remaining) + raise ValueError(f"scene dependency graph contains a cycle: {cycle_nodes}") + levels.append(ready) + completed.update(ready) + for node_id in ready: + del remaining[node_id] + return levels + + +def _entity_stage(entity: dict[str, Any], policy: SceneDependencyPolicy) -> SceneStage: + attributes = entity.get("attributes") or {} + declared = attributes.get("scene_stage") + if declared is not None: + return cast(SceneStage, str(declared)) + mount = str(attributes.get("mount", "")).upper() + if mount in policy.inference.mount_stages: + return policy.inference.mount_stages[mount] + return policy.inference.role_stages.get(str(entity.get("role", "CONTEXT")), "furniture") + + +def _dedupe(values: list[str]) -> list[str]: + return list(dict.fromkeys(values)) + + +def _branch_roots( + nodes: dict[str, SceneDependencyNode], architecture_ids: set[str] +) -> dict[str, str]: + roots: dict[str, str] = {} + + def resolve(node_id: str, trail: set[str]) -> str: + if node_id in roots: + return roots[node_id] + if node_id in trail: + raise ValueError(f"scene dependency graph contains a cycle at {node_id}") + node = nodes[node_id] + parents = [parent for parent in node.depends_on if parent not in architecture_ids] + if not parents: + roots[node_id] = node_id + return node_id + parent_roots = {resolve(parent, trail | {node_id}) for parent in parents} + # A node joining multiple branches becomes its own merge branch. + roots[node_id] = next(iter(parent_roots)) if len(parent_roots) == 1 else node_id + return roots[node_id] + + for candidate in nodes: + if candidate not in architecture_ids: + resolve(candidate, set()) + return roots + + +def compile_scene_dependency_graph( + task: dict[str, Any], + context_config: dict[str, Any] | None = None, + *, + policy: SceneDependencyPolicy | None = None, +) -> SceneDependencyGraph: + """Compile task predicates and declarative overrides into an auditable scene DAG.""" + + policy = policy or load_dependency_policy() + context_config = context_config or {} + nodes: dict[str, SceneDependencyNode] = {} + architecture_ids = {item.node_id for item in policy.architecture} + for item in policy.architecture: + nodes[item.node_id] = SceneDependencyNode( + node_id=item.node_id, + kind="architecture", + stage=item.stage, + execution=item.execution, + depends_on=item.depends_on, + critical=True, + ) + + entities = { + str(entity["entity_id"]): entity + for entity in task.get("entities", []) + if entity.get("entity_id") + and str(entity.get("entity_id")) not in architecture_ids + and entity.get("role") not in {"ROBOT", "REGION"} + and "procedural_geometry" not in (entity.get("attributes") or {}) + and entity.get("attributes", {}).get("scene_generation") != "external" + } + relation_dependencies: dict[str, list[str]] = defaultdict(list) + for predicate in task.get("initial_predicates", []): + if predicate.get("name") not in policy.inference.dependency_predicates: + continue + subject = predicate.get("subject") + parent = predicate.get("object") + if subject in entities and parent in entities: + relation_dependencies[str(subject)].append(str(parent)) + + for entity_id, entity in entities.items(): + stage = _entity_stage(entity, policy) + declared_dependencies = (entity.get("attributes") or {}).get("depends_on", []) + if not isinstance(declared_dependencies, list) or any( + not isinstance(item, str) or not item for item in declared_dependencies + ): + raise ValueError(f"entity {entity_id} attributes.depends_on must be a string list") + dependencies = ( + relation_dependencies.get(entity_id) + or declared_dependencies + or policy.inference.stage_default_dependencies.get(stage, ["room_shell"]) + ) + nodes[entity_id] = SceneDependencyNode( + node_id=entity_id, + entity_id=entity_id, + kind="entity", + stage=stage, + execution=policy.inference.stage_execution.get(stage, "agent"), + depends_on=_dedupe(list(dependencies)), + critical=bool(entity.get("required", True)), + category=str(entity.get("category") or entity_id), + metadata={"role": entity.get("role"), "attributes": entity.get("attributes") or {}}, + ) + + for group in context_config.get("groups", []): + if not isinstance(group, dict): + raise ValueError("context asset group must be an object") + group_id = str(group.get("group_id") or "") + asset_id = str(group.get("asset_id") or "") + for parent in group.get("parent_object_ids") or []: + parent = str(parent) + if parent not in nodes: + nodes[parent] = SceneDependencyNode( + node_id=parent, + kind="entity", + stage="furniture", + execution="agent", + depends_on=policy.inference.stage_default_dependencies["furniture"], + critical=bool(group.get("required", False)), + entity_id=parent, + category=parent.replace("_", " "), + metadata={"source": "context_asset_parent"}, + ) + node_id = f"context:{group_id}:{parent}" + nodes[node_id] = SceneDependencyNode( + node_id=node_id, + kind="context_asset", + stage="postprocess", + execution="native_usd", + depends_on=[parent], + critical=bool(group.get("required", False)), + asset_id=asset_id, + metadata={"group_id": group_id, "parent_object_id": parent}, + ) + + overrides = DependencyGraphOverrides.model_validate( + context_config.get("dependency_graph") or {"schema_version": "1.0"} + ) + effective_scheduler = policy.scheduler + if overrides.scheduler is not None: + effective_scheduler = policy.scheduler.model_copy( + update=overrides.scheduler.model_dump(exclude_none=True) + ) + for override in overrides.nodes: + if override.node_id not in nodes: + raise ValueError( + f"dependency_graph override references unknown node: {override.node_id}" + ) + node = nodes[override.node_id] + update: dict[str, Any] = {} + if override.depends_on is not None: + update["depends_on"] = _dedupe(override.depends_on + override.add_dependencies) + elif override.add_dependencies: + update["depends_on"] = _dedupe(node.depends_on + override.add_dependencies) + for field in ("stage", "execution", "critical"): + value = getattr(override, field) + if value is not None: + update[field] = value + nodes[override.node_id] = node.model_copy(update=update) + + graph_dependencies = {node_id: set(node.depends_on) for node_id, node in nodes.items()} + levels = _topological_levels(graph_dependencies) + roots = _branch_roots(nodes, architecture_ids) + grouped: dict[str, list[str]] = defaultdict(list) + for node_id, root_id in roots.items(): + grouped[root_id].append(node_id) + branches = [ + SceneDependencyBranch( + branch_id=f"branch:{root_id}", + root_node_id=root_id, + node_ids=sorted(node_ids), + critical=any(nodes[node_id].critical for node_id in node_ids), + stages=list(dict.fromkeys(nodes[node_id].stage for node_id in sorted(node_ids))), + ) + for root_id, node_ids in sorted(grouped.items()) + ] + branch_by_node = { + node_id: branch.branch_id for branch in branches for node_id in branch.node_ids + } + waves = [ + SceneDependencyWave( + wave_index=index, + node_ids=node_ids, + branch_ids=sorted( + {branch_by_node[node_id] for node_id in node_ids if node_id in branch_by_node} + ), + resource_classes=sorted({ + effective_scheduler.resource_class_by_stage[nodes[node_id].stage] + for node_id in node_ids + }), + ) + for index, node_ids in enumerate(levels) + ] + task_id = str(task.get("task_id") or "scene") + return SceneDependencyGraph( + graph_id=f"scene-dependencies:{task_id}", + nodes=list(nodes.values()), + branches=branches, + waves=waves, + scheduler=effective_scheduler, + ) + + +def dependency_prompt_rules(graph: SceneDependencyGraph) -> list[str]: + by_id = {node.node_id: node for node in graph.nodes} + children: dict[str, list[str]] = defaultdict(list) + for node in graph.nodes: + for parent in node.depends_on: + children[parent].append(node.node_id) + tree_edges = [ + f"{parent} -> {{{', '.join(sorted(node_ids))}}}" + for parent, node_ids in sorted(children.items()) + ] + return [ + "Follow the frozen scene dependency graph; never generate a child before its " + "declared parents pass their quality gate.", + "Independent branches may run concurrently, but each branch may mutate only " + "its owned nodes.", + "Dependency tree edges (items in braces are siblings, not a chain): " + + " | ".join(tree_edges), + "Required nodes: " + + ", ".join(sorted(node.node_id for node in by_id.values() if node.critical)), + ] + + +def manipulation_assignments(graph: dict[str, Any]) -> dict[str, list[str]]: + nodes = { + str(node["node_id"]): node + for node in graph.get("nodes", []) + if isinstance(node, dict) and node.get("node_id") + } + assignments: dict[str, list[tuple[int, str]]] = defaultdict(list) + + def root_support(node_id: str, trail: set[str]) -> tuple[str, int] | None: + if node_id in trail: + return None + node = nodes[node_id] + parents = [parent for parent in node.get("depends_on", []) if parent in nodes] + non_architecture = [ + parent for parent in parents if nodes[parent].get("kind") != "architecture" + ] + if len(non_architecture) != 1: + return None + parent = non_architecture[0] + if nodes[parent].get("stage") != "manipulation": + return parent, 1 + ancestor = root_support(parent, trail | {node_id}) + if ancestor is None: + return None + return ancestor[0], ancestor[1] + 1 + + for node_id, node in nodes.items(): + if node.get("stage") != "manipulation" or node.get("kind") != "entity": + continue + resolved = root_support(node_id, set()) + if resolved is not None: + assignments[resolved[0]].append((resolved[1], node_id)) + return { + support: [node_id for _depth, node_id in sorted(items)] + for support, items in sorted(assignments.items()) + } diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/design_contract.py b/docs/reproduction/public_conversion_code/packages/scene_generation/design_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c9f82a0428caf52278afc9876645c463fc1602 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/design_contract.py @@ -0,0 +1,413 @@ +from __future__ import annotations + +import hashlib +import json +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Literal, Protocol + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from packages.core.files import atomic_write_text +from packages.generative import GenerativeClient, RelaySettings +from packages.scene_generation.dependency_graph import ( + SceneDependencyGraph, + compile_scene_dependency_graph, +) +from packages.scene_generation.metric_layout import ( + MetricLayoutSpec, + prepare_metric_layout_spec, +) + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class BlueprintZone(_StrictModel): + zone_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + purpose: str = Field(min_length=1) + relative_location: str = Field(min_length=1) + required_objects: list[str] = Field(default_factory=list) + + +class BlueprintRelation(_StrictModel): + subject: str = Field(min_length=1) + relation: str = Field(min_length=1) + object: str = Field(min_length=1) + rationale: str = Field(min_length=1) + + +class BlueprintAnalysis(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + summary: str = Field(min_length=1) + room_count: int = Field(ge=1) + enclosure: Literal["enclosed", "open_surface", "mixed"] + zones: list[BlueprintZone] = Field(min_length=1) + circulation: list[str] = Field(default_factory=list) + spatial_relations: list[BlueprintRelation] = Field(default_factory=list) + ambiguities: list[str] = Field(default_factory=list) + + @field_validator("circulation", mode="before") + @classmethod + def normalize_circulation(cls, value: Any) -> Any: + """Accept the common labeled-object form emitted by multimodal models.""" + + if value is None: + return [] + if isinstance(value, str): + return [value] + if not isinstance(value, dict): + return value + normalized: list[str] = [] + for raw_label, raw_entries in value.items(): + label = str(raw_label).replace("_", " ").strip() + entries = raw_entries if isinstance(raw_entries, list) else [raw_entries] + for entry in entries: + if entry is None: + continue + text = ( + entry + if isinstance(entry, str) + else json.dumps(entry, ensure_ascii=False, sort_keys=True) + ) + normalized.append(f"{label}: {text}" if label else text) + return normalized + + +class CaseDesignContract(_StrictModel): + schema_version: Literal["1.0", "1.1"] = "1.1" + status: Literal["frozen"] = "frozen" + created_at: str + prompt_sha256: str + task_sha256: str + blueprint_path: str + blueprint_sha256: str + blueprint_analysis_path: str + blueprint_analysis_sha256: str + dependency_graph_path: str + dependency_graph_sha256: str + metric_layout_spec_path: str | None = None + metric_layout_spec_sha256: str | None = None + graph_id: str + node_ids: list[str] + + +class BlueprintClient(Protocol): + def generate_image( + self, + prompt: str, + output: Path, + *, + size: str = "1024x1024", + quality: str = "high", + ) -> Path: ... + + def analyze_image(self, source: Path, prompt: str) -> str: ... + + +def _sha256_bytes(value: bytes) -> str: + return hashlib.sha256(value).hexdigest() + + +def _sha256_file(path: Path) -> str: + return _sha256_bytes(path.read_bytes()) + + +def _canonical_sha256(value: dict[str, Any]) -> str: + return _sha256_bytes( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode( + "utf-8" + ) + ) + + +def _parse_object(text: str) -> dict[str, Any]: + start = text.find("{") + end = text.rfind("}") + if start < 0 or end < start: + raise ValueError("Blueprint Agent returned no JSON object") + value = json.loads(text[start : end + 1]) + if not isinstance(value, dict): + raise ValueError("Blueprint Agent output must be a JSON object") + return value + + +def prepare_case_blueprint( + case_root: Path, + prompt: str, + *, + client: BlueprintClient | None = None, +) -> tuple[Path, BlueprintAnalysis]: + """Generate the case-level drawing once, then read it with a multimodal Agent.""" + + design_root = case_root.resolve() / "case_design" + image_path = design_root / "blueprint.png" + analysis_path = design_root / "blueprint_analysis.json" + prompt_hash = _sha256_bytes(prompt.encode("utf-8")) + identity_path = design_root / "blueprint_identity.json" + if image_path.is_file() and analysis_path.is_file() and identity_path.is_file(): + identity = json.loads(identity_path.read_text(encoding="utf-8")) + if identity.get("prompt_sha256") != prompt_hash: + raise ValueError("frozen blueprint prompt differs from case prompt") + if identity.get("blueprint_sha256") != _sha256_file(image_path): + raise ValueError("frozen blueprint image hash mismatch") + return image_path, BlueprintAnalysis.model_validate_json( + analysis_path.read_text(encoding="utf-8") + ) + selected_client = client or GenerativeClient(RelaySettings.from_env()) + design_root.mkdir(parents=True, exist_ok=True) + drawing_prompt = f"""Create one precise top-down architectural blueprint for this scene request. +Use a white drafting background, dark dimensionless wall lines, labeled functional zones, +simple furniture footprints, door/window symbols, support-object labels, source-to-target +arrows, and a clearly marked robot circulation route. Do not use perspective rendering, +decorative illustration, people, logos, or invented numeric dimensions. The drawing is an +Agent design artifact that will constrain downstream scene Agents. + +Original design request: +{prompt} +""" + if not image_path.exists(): + selected_client.generate_image( + drawing_prompt, image_path, size="1536x1024", quality="high" + ) + elif not image_path.is_file(): + raise RuntimeError("case blueprint path exists but is not a file") + if identity_path.exists() and not analysis_path.exists(): + raise RuntimeError("case blueprint identity exists without its analysis") + analysis_prompt = f"""You are the second-level Blueprint Analysis Agent. Read both the +original design text below and the attached Agent-generated drawing. Return exactly one JSON +object with keys schema_version, summary, room_count, enclosure, zones, circulation, +spatial_relations, ambiguities. schema_version is "1.0". enclosure is enclosed, open_surface, +or mixed. zones is a non-empty array of objects with zone_id, purpose, relative_location, +required_objects. circulation is an array of strings, never an object. spatial_relations +contains subject, relation, object, rationale. Preserve +semantic object names from the text. Do not treat decorative marks as required objects and do +not invent metric dimensions absent from the original text. + +Original design text: +{prompt} +""" + analysis = BlueprintAnalysis.model_validate( + _parse_object(selected_client.analyze_image(image_path, analysis_prompt)) + ) + atomic_write_text(analysis_path, analysis.model_dump_json(indent=2) + "\n") + atomic_write_text( + identity_path, + json.dumps( + { + "schema_version": "1.0", + "prompt_sha256": prompt_hash, + "blueprint_sha256": _sha256_file(image_path), + "generation_order": [ + "text_prompt", + "blueprint_image_agent", + "text_plus_blueprint_multimodal_agent", + ], + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + return image_path, analysis + + +def freeze_case_design_contract( + case_root: Path, + prompt: str, + task: dict[str, Any], + context_config: dict[str, Any], + *, + client: BlueprintClient | None = None, +) -> CaseDesignContract: + """Freeze blueprint and scene DAG above every Supervisor version.""" + + design_root = case_root.resolve() / "case_design" + contract_path = design_root / "contract.json" + task_hash = _canonical_sha256(task) + if contract_path.is_file(): + contract = CaseDesignContract.model_validate_json( + contract_path.read_text(encoding="utf-8") + ) + verify_case_design_contract(contract_path, prompt=prompt, task=task) + layout_config = context_config.get("metric_layout") or {} + if isinstance(layout_config, dict) and bool(layout_config.get("enabled")): + if not contract.metric_layout_spec_path: + raise ValueError( + "existing frozen design contract has no metric layout; use a new case_id" + ) + return contract + + layout_config = context_config.get("metric_layout") or {} + if not isinstance(layout_config, dict): + raise ValueError("scene_config.metric_layout must be an object") + selected_client = client + if bool(layout_config.get("enabled")) and selected_client is None: + selected_client = GenerativeClient(RelaySettings.from_env()) + blueprint_path, _analysis = prepare_case_blueprint( + case_root, prompt, client=selected_client + ) + graph = compile_scene_dependency_graph(task, context_config) + graph_path = design_root / "scene_dependency_graph.json" + atomic_write_text(graph_path, graph.model_dump_json(indent=2) + "\n") + metric_layout = prepare_metric_layout_spec( + design_root, + blueprint_path, + prompt, + task, + context_config, + client=selected_client, # type: ignore[arg-type] + ) + analysis_path = design_root / "blueprint_analysis.json" + contract = CaseDesignContract( + created_at=datetime.now(UTC).isoformat(), + prompt_sha256=_sha256_bytes(prompt.encode("utf-8")), + task_sha256=task_hash, + blueprint_path=blueprint_path.relative_to(design_root).as_posix(), + blueprint_sha256=_sha256_file(blueprint_path), + blueprint_analysis_path=analysis_path.relative_to(design_root).as_posix(), + blueprint_analysis_sha256=_sha256_file(analysis_path), + dependency_graph_path=graph_path.relative_to(design_root).as_posix(), + dependency_graph_sha256=_sha256_file(graph_path), + metric_layout_spec_path=( + metric_layout[0].relative_to(design_root).as_posix() + if metric_layout is not None + else None + ), + metric_layout_spec_sha256=( + _sha256_file(metric_layout[0]) if metric_layout is not None else None + ), + graph_id=graph.graph_id, + node_ids=sorted(node.node_id for node in graph.nodes), + ) + atomic_write_text(contract_path, contract.model_dump_json(indent=2) + "\n") + return contract + + +def verify_case_design_contract( + contract_path: Path, + *, + prompt: str | None = None, + task: dict[str, Any] | None = None, +) -> tuple[CaseDesignContract, SceneDependencyGraph, BlueprintAnalysis]: + contract_path = contract_path.resolve() + contract = CaseDesignContract.model_validate_json( + contract_path.read_text(encoding="utf-8") + ) + root = contract_path.parent + files = { + contract.blueprint_path: contract.blueprint_sha256, + contract.blueprint_analysis_path: contract.blueprint_analysis_sha256, + contract.dependency_graph_path: contract.dependency_graph_sha256, + } + if bool(contract.metric_layout_spec_path) != bool(contract.metric_layout_spec_sha256): + raise ValueError("frozen metric layout path/hash must be present together") + if contract.metric_layout_spec_path and contract.metric_layout_spec_sha256: + files[contract.metric_layout_spec_path] = contract.metric_layout_spec_sha256 + for relative, expected in files.items(): + path = (root / relative).resolve() + if not path.is_relative_to(root) or not path.is_file(): + raise FileNotFoundError(f"case design artifact is missing or escapes root: {relative}") + if _sha256_file(path) != expected: + raise ValueError(f"frozen case design artifact hash mismatch: {relative}") + if prompt is not None and _sha256_bytes(prompt.encode("utf-8")) != contract.prompt_sha256: + raise ValueError("case prompt differs from frozen design contract") + if task is not None and _canonical_sha256(task) != contract.task_sha256: + raise ValueError("case task differs from frozen design contract") + graph = SceneDependencyGraph.model_validate_json( + (root / contract.dependency_graph_path).read_text(encoding="utf-8") + ) + if graph.graph_id != contract.graph_id or sorted( + node.node_id for node in graph.nodes + ) != contract.node_ids: + raise ValueError("frozen DAG identity differs from design contract") + analysis = BlueprintAnalysis.model_validate_json( + (root / contract.blueprint_analysis_path).read_text(encoding="utf-8") + ) + if contract.metric_layout_spec_path: + metric_layout = MetricLayoutSpec.model_validate_json( + (root / contract.metric_layout_spec_path).read_text(encoding="utf-8") + ) + if metric_layout.source_blueprint_sha256 != contract.blueprint_sha256: + raise ValueError("frozen metric layout references a different blueprint hash") + return contract, graph, analysis + + +def validate_repair_plan_against_contract( + contract_path: Path, + repair_plan: Any, +) -> None: + """Reject version-local repairs that attempt to rewrite frozen DAG topology.""" + + contract, graph, _analysis = verify_case_design_contract(contract_path) + payload = ( + repair_plan.model_dump(mode="json") + if hasattr(repair_plan, "model_dump") + else repair_plan + ) + if not isinstance(payload, dict) or not isinstance(payload.get("steps"), list): + raise ValueError("repair plan must contain a steps array") + known_entities = {node.entity_id for node in graph.nodes if node.entity_id} + topology_keys = { + "add_node", + "remove_node", + "node_id", + "nodes", + "depends_on", + "dependencies", + "dependency_graph", + "graph_id", + "recompile_dag", + } + metric_pose_keys = { + "metric_layout_spec", + "center_xy_m", + "yaw_deg", + "footprint_m", + "zone_polygon_xy_m", + "route_polygon_xy_m", + "robot_start_xy_m", + "keep_out_regions", + "translation", + "rotation_wxyz", + } + + def nested_keys(value: Any) -> set[str]: + if isinstance(value, dict): + mapping_keys = {str(key) for key in value} + for child in value.values(): + mapping_keys.update(nested_keys(child)) + return mapping_keys + if isinstance(value, list): + list_keys: set[str] = set() + for child in value: + list_keys.update(nested_keys(child)) + return list_keys + return set() + for index, step in enumerate(payload["steps"]): + if not isinstance(step, dict): + raise ValueError(f"repair step {index} must be an object") + unknown = set(step.get("entity_ids") or []) - known_entities + if unknown: + raise ValueError( + f"repair step {index} references entities outside frozen DAG: " + + ", ".join(sorted(unknown)) + ) + parameters = step.get("parameters") or {} + if not isinstance(parameters, dict): + raise ValueError(f"repair step {index} parameters must be an object") + forbidden_keys = topology_keys | ( + metric_pose_keys if contract.metric_layout_spec_path else set() + ) + forbidden = forbidden_keys & nested_keys(parameters) + if forbidden: + target = ( + "frozen DAG topology" + if forbidden <= topology_keys + else "frozen design geometry/topology" + ) + raise ValueError( + f"repair step {index} attempts to mutate {target}: " + + ", ".join(sorted(forbidden)) + ) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/deterministic_placement.py b/docs/reproduction/public_conversion_code/packages/scene_generation/deterministic_placement.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f2d0af6d00031d4e5000fbdd6581f21ce5b592 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/deterministic_placement.py @@ -0,0 +1,1402 @@ +from __future__ import annotations + +import hashlib +import json +import math +import threading +import time +from collections import defaultdict +from collections.abc import Iterable +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field +from shapely import affinity # type: ignore[import-untyped] +from shapely.geometry import Polygon, box # type: ignore[import-untyped] +from shapely.strtree import STRtree # type: ignore[import-untyped] + +from packages.core.files import atomic_write_text +from packages.scene_generation.agent_orchestration import DeterministicPlacementPolicy +from packages.scene_generation.dependency_graph import SceneDependencyGraph +from packages.scene_generation.metric_layout import ( + MetricLayoutSpec, + MetricLayoutValidation, + validate_metric_layout_footprints, +) + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class PlacementMeasurement(_StrictModel): + entity_id: str + parent_id: str | None = None + local_bbox_min_m: tuple[float, float, float] + local_bbox_max_m: tuple[float, float, float] + original_translation_m: tuple[float, float, float] + corrected_translation_m: tuple[float, float, float] + yaw_deg: float = 0.0 + target_center_xy_m: tuple[float, float] | None = None + footprint_polygon_xy_m: list[tuple[float, float]] = Field(default_factory=list) + world_bbox_min_m: tuple[float, float, float] + world_bbox_max_m: tuple[float, float, float] + room_boundary_margin_m: float + floor_gap_m: float | None = None + penetration_m: float = Field(default=0.0, ge=0) + support_coverage: float | None = None + com_margin_m: float | None = None + task_support_surface_height_m: float | None = None + collision_free: bool = True + asset_sha256: str | None = None + transform_sha256: str + candidate_kind: str + narrow_phase_backend: str + hard_gates_passed: bool + failures: list[str] = Field(default_factory=list) + + +class PlacementCertificate(_StrictModel): + schema_version: str = "1.0" + subtree_id: str + solver: str = "deterministic_shapely_strtree" + api_token_count: int = 0 + elapsed_s: float = Field(ge=0) + hard_gates_passed: bool + failures: list[str] = Field(default_factory=list) + entities: list[PlacementMeasurement] = Field(default_factory=list) + + +class SemanticConstraintMeasurement(_StrictModel): + constraint_id: str + relation: str + subject: str + object: str + anchor: str | None = None + minimum_distance_m: float | None = Field(default=None, ge=0) + maximum_distance_m: float | None = Field(default=None, ge=0) + measured_distance_m: float | None = Field(default=None, ge=0) + maximum_angle_degrees: float | None = Field(default=None, ge=0, le=180) + measured_angle_degrees: float | None = Field(default=None, ge=0, le=180) + forward_axis_local: str | None = None + maximum_cosine: float | None = Field(default=None, ge=-1, le=1) + measured_cosine: float | None = Field(default=None, ge=-1, le=1) + hard_gates_passed: bool + + +class WorldGeometryCertificate(_StrictModel): + schema_version: str = "1.0" + solver: str = "deterministic_shapely_strtree" + api_token_count: int = 0 + elapsed_s: float = Field(ge=0) + hard_gates_passed: bool + room_polygon_xy_m: list[tuple[float, float]] + transform_sha256: str + state_transform_sha256: str | None = None + usd_transform_sha256: str | None = None + usd_validation_passed: bool | None = None + failures: list[str] = Field(default_factory=list) + entities: list[PlacementMeasurement] = Field(default_factory=list) + semantic_constraints: list[SemanticConstraintMeasurement] = Field(default_factory=list) + parallel_intervals: list[dict[str, float | str]] = Field(default_factory=list) + dropped_optional_entities: dict[str, str] = Field(default_factory=dict) + metric_layout_spec_sha256: str | None = None + metric_layout_validation: MetricLayoutValidation | None = None + + +@dataclass(frozen=True) +class _Geometry: + entity_id: str + minimum: tuple[float, float, float] + maximum: tuple[float, float, float] + original: tuple[float, float, float] + yaw_degrees: float + + @property + def footprint(self) -> Polygon: + shape = box(self.minimum[0], self.minimum[1], self.maximum[0], self.maximum[1]) + if self.yaw_degrees: + shape = affinity.rotate(shape, self.yaw_degrees, origin=(0.0, 0.0)) + return shape + + +@dataclass(frozen=True) +class PlacementSolution: + translations: dict[str, tuple[float, float, float]] + measurements: dict[str, PlacementMeasurement] + world_certificate: WorldGeometryCertificate + yaw_degrees: dict[str, float] = field(default_factory=dict) + metric_layout_spec: MetricLayoutSpec | None = None + parent_by_entity: dict[str, str | None] = field(default_factory=dict) + + +def _finite_vector(value: Any, *, name: str) -> tuple[float, float, float]: + if not isinstance(value, (list, tuple)) or len(value) != 3: + raise ValueError(f"{name}:expected_xyz") + result = tuple(float(item) for item in value) + if not all(math.isfinite(item) and abs(item) < 1.0e20 for item in result): + raise ValueError(f"{name}:non_finite") + return result # type: ignore[return-value] + + +def _yaw_degrees(rotation: Any) -> float: + if not isinstance(rotation, (list, tuple)) or len(rotation) != 4: + return 0.0 + w, x, y, z = (float(item) for item in rotation) + return math.degrees(math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))) + + +def _sha(payload: Any) -> str: + return hashlib.sha256( + json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def _room_polygon(evidence: dict[str, Any]) -> tuple[Polygon, float]: + rooms = evidence.get("rooms") or {} + if not isinstance(rooms, dict) or not rooms: + raise ValueError("room_geometry:missing") + room = next(iter(rooms.values())) + if not isinstance(room, dict): + raise ValueError("room_geometry:invalid") + polygon_xy = room.get("floor_polygon_xy_m") + if isinstance(polygon_xy, list) and len(polygon_xy) >= 3: + polygon = Polygon( + [ + (float(point[0]), float(point[1])) + for point in polygon_xy + if isinstance(point, (list, tuple)) and len(point) >= 2 + ] + ) + if not polygon.is_valid or polygon.is_empty or polygon.area <= 0: + raise ValueError("room_geometry:invalid_floor_polygon") + floor_z = float(room.get("floor_z_m") or 0.0) + return polygon, floor_z + minimum = room.get("floor_bbox_min") + maximum = room.get("floor_bbox_max") + if minimum is not None and maximum is not None: + low = _finite_vector(minimum, name="floor_bbox_min") + high = _finite_vector(maximum, name="floor_bbox_max") + if high[0] <= low[0] or high[1] <= low[1]: + raise ValueError("room_geometry:empty_floor") + return box(low[0], low[1], high[0], high[1]), high[2] + length = float(room.get("length") or 0.0) + width = float(room.get("width") or 0.0) + if not math.isfinite(length) or not math.isfinite(width) or min(length, width) <= 0: + raise ValueError("room_geometry:missing_floor_bounds") + return box(-length / 2.0, -width / 2.0, length / 2.0, width / 2.0), 0.0 + + +def _geometry(entity_id: str, record: dict[str, Any]) -> _Geometry: + minimum = _finite_vector(record.get("bbox_min_local_m"), name=f"{entity_id}:bbox_min") + maximum = _finite_vector(record.get("bbox_max_local_m"), name=f"{entity_id}:bbox_max") + if any(maximum[index] <= minimum[index] for index in range(3)): + raise ValueError(f"{entity_id}:empty_bbox") + transform = record.get("transform") or {} + original = _finite_vector(transform.get("translation", [0, 0, 0]), name=f"{entity_id}:pose") + return _Geometry( + entity_id=entity_id, + minimum=minimum, + maximum=maximum, + original=original, + yaw_degrees=_yaw_degrees(transform.get("rotation_wxyz")), + ) + + +def _parent_map(graph: SceneDependencyGraph) -> dict[str, str | None]: + architecture = {node.node_id for node in graph.nodes if node.kind == "architecture"} + result: dict[str, str | None] = {} + for node in graph.nodes: + if node.kind == "architecture" or node.execution == "external": + continue + semantic = [item for item in node.depends_on if item not in architecture] + result[node.node_id] = semantic[0] if semantic else None + return result + + +def _depth(entity_id: str, parents: dict[str, str | None]) -> int: + seen: set[str] = set() + current = entity_id + result = 0 + while parents.get(current) is not None: + if current in seen: + raise ValueError(f"dependency_cycle:{entity_id}") + seen.add(current) + current = str(parents[current]) + result += 1 + return result + + +def _translated(shape: Polygon, pose: tuple[float, float, float]) -> Polygon: + return affinity.translate(shape, xoff=pose[0], yoff=pose[1]) + + +def _opposition_cosine(subject: Polygon, other: Polygon, anchor: Polygon) -> float: + anchor_center = anchor.centroid + subject_center = subject.centroid + other_center = other.centroid + left = (subject_center.x - anchor_center.x, subject_center.y - anchor_center.y) + right = (other_center.x - anchor_center.x, other_center.y - anchor_center.y) + denominator = math.hypot(*left) * math.hypot(*right) + if denominator <= 1.0e-9: + return 1.0 + return float((left[0] * right[0] + left[1] * right[1]) / denominator) + + +def _analytic_box_signed_distance( + left: _Geometry, + left_pose: tuple[float, float, float], + right: _Geometry, + right_pose: tuple[float, float, float], +) -> float: + left_shape = _translated(left.footprint, left_pose) + right_shape = _translated(right.footprint, right_pose) + left_z = (left_pose[2] + left.minimum[2], left_pose[2] + left.maximum[2]) + right_z = (right_pose[2] + right.minimum[2], right_pose[2] + right.maximum[2]) + xy_distance = left_shape.distance(right_shape) + z_distance = max(right_z[0] - left_z[1], left_z[0] - right_z[1], 0.0) + if xy_distance > 0 or z_distance > 0: + return math.hypot(xy_distance, z_distance) + xy_penetration = math.sqrt(max(left_shape.intersection(right_shape).area, 0.0)) + z_penetration = min(left_z[1], right_z[1]) - max(left_z[0], right_z[0]) + return -min(xy_penetration, z_penetration) + + +def _drake_box_signed_distance( + left: _Geometry, + left_pose: tuple[float, float, float], + right: _Geometry, + right_pose: tuple[float, float, float], +) -> tuple[float, str]: + try: + from pydrake.geometry import ( # type: ignore[import-not-found] + Box, + FramePoseVector, + GeometryFrame, + GeometryInstance, + ProximityProperties, + SceneGraph, + ) + from pydrake.math import ( # type: ignore[import-not-found] + RigidTransform, + RotationMatrix, + ) + except ImportError: + return _analytic_box_signed_distance(left, left_pose, right, right_pose), "analytic_box" + + scene_graph = SceneGraph() + source = scene_graph.RegisterSource("robothousegen-placement") + frames = [ + scene_graph.RegisterFrame(source, GeometryFrame("candidate")), + scene_graph.RegisterFrame(source, GeometryFrame("obstacle")), + ] + geometry_ids = [] + poses = FramePoseVector() + for index, (item, pose) in enumerate(((left, left_pose), (right, right_pose))): + dimensions = tuple(item.maximum[axis] - item.minimum[axis] for axis in range(3)) + center_local = tuple((item.minimum[axis] + item.maximum[axis]) / 2.0 for axis in range(3)) + yaw = math.radians(item.yaw_degrees) + center_world = ( + pose[0] + math.cos(yaw) * center_local[0] - math.sin(yaw) * center_local[1], + pose[1] + math.sin(yaw) * center_local[0] + math.cos(yaw) * center_local[1], + pose[2] + center_local[2], + ) + geometry_id = scene_graph.RegisterGeometry( + source, + frames[index], + GeometryInstance(RigidTransform(), Box(*dimensions), f"box-{index}"), + ) + scene_graph.AssignRole(source, geometry_id, ProximityProperties()) + geometry_ids.append(geometry_id) + poses.set_value( + frames[index], + RigidTransform(RotationMatrix.MakeZRotation(yaw), center_world), + ) + context = scene_graph.CreateDefaultContext() + scene_graph.get_source_pose_port(source).FixValue(context, poses) + query = scene_graph.get_query_output_port().Eval(context) + distance = query.ComputeSignedDistancePairClosestPoints(*geometry_ids).distance + return float(distance), "drake_signed_distance" + + +def _candidate_xy( + original: tuple[float, float, float], + footprint: Polygon, + feasible: Polygon, + grid_m: float, +) -> Iterable[tuple[str, float, float]]: + yield "agent_original", original[0], original[1] + translated = _translated(footprint, original) + if not feasible.covers(translated): + dx = min(0.0, feasible.bounds[2] - translated.bounds[2]) + max( + 0.0, feasible.bounds[0] - translated.bounds[0] + ) + dy = min(0.0, feasible.bounds[3] - translated.bounds[3]) + max( + 0.0, feasible.bounds[1] - translated.bounds[1] + ) + yield "nearest_feasible_projection", original[0] + dx, original[1] + dy + min_x, min_y, max_x, max_y = feasible.bounds + center = footprint.centroid + anchors = [ + (min_x - footprint.bounds[0], original[1]), + (max_x - footprint.bounds[2], original[1]), + (original[0], min_y - footprint.bounds[1]), + (original[0], max_y - footprint.bounds[3]), + ] + for x, y in anchors: + yield "wall_anchor", x, y + nx = max(1, int((max_x - min_x) / grid_m) + 1) + ny = max(1, int((max_y - min_y) / grid_m) + 1) + for ix in range(nx): + for iy in range(ny): + yield "fixed_grid", min_x + ix * grid_m - center.x, min_y + iy * grid_m - center.y + + +def solve_deterministic_placements( + *, + geometry_evidence: dict[str, Any], + graph: SceneDependencyGraph, + policy: DeterministicPlacementPolicy, + subtree_by_node: dict[str, str] | None = None, + asset_hashes: dict[str, str] | None = None, + fixed_obstacles: ( + dict[str, tuple[tuple[float, float, float], tuple[float, float, float]]] | None + ) = None, + semantic_constraints: list[dict[str, Any]] | None = None, + optional_entity_ids: set[str] | None = None, + metric_layout_spec: MetricLayoutSpec | None = None, + metric_layout_perturbation_attempt: int | None = None, + robot_id: str | None = None, + robot_constraints_enabled: bool = True, +) -> PlacementSolution: + """Solve task-entity transforms without an LLM or nondeterministic search.""" + + from packages.robots.task_constraints import get_task_constraints + support_range = (get_task_constraints(robot_id)["support_height_range_m"] + if robot_constraints_enabled else (0., policy.maximum_task_support_height_m)) + started = time.monotonic() + room, floor_z = _room_polygon(geometry_evidence) + evidence_room = room + first_room = next(iter((geometry_evidence.get("rooms") or {}).values())) + wall_height = float(first_room.get("wall_height") or 0.0) + ceiling_z = floor_z + wall_height if wall_height > 0 else None + entities = geometry_evidence.get("entities") or {} + parents = _parent_map(graph) + optional_entity_ids = set(optional_entity_ids or set()) + metric_by_id = metric_layout_spec.entity_by_id if metric_layout_spec else {} + if metric_layout_spec is not None: + # A metric layout is a hard contract. Optional asset dropping would make + # the authored scene differ from the blueprint, so every DAG entity is required. + optional_entity_ids.clear() + room = Polygon(metric_layout_spec.room_polygon_xy_m) + unsafe_optional = { + optional_id + for optional_id in optional_entity_ids + if any( + parent_id == optional_id and child_id not in optional_entity_ids + for child_id, parent_id in parents.items() + ) + } + if unsafe_optional: + raise ValueError( + f"optional placement nodes cannot own critical children: {sorted(unsafe_optional)}" + ) + node_by_id = {node.node_id: node for node in graph.nodes} + task_support_ids = { + parent_id + for child_id, parent_id in parents.items() + if parent_id is not None and node_by_id[child_id].stage == "manipulation" + } + semantic_anchor_ids = { + str(constraint.get("anchor")) + for constraint in semantic_constraints or [] + if isinstance(constraint, dict) + and constraint.get("relation") == "opposite_sides" + and constraint.get("anchor") + } + required = sorted( + parents, + key=lambda item: ( + _depth(item, parents), + 0 if item in semantic_anchor_ids else 1, + item, + ), + ) + geometries: dict[str, _Geometry] = {} + failures: list[str] = [] + dropped_optional_entities: dict[str, str] = {} + for entity_id in required: + try: + geometries[entity_id] = _geometry(entity_id, entities[entity_id]) + except KeyError: + if entity_id in optional_entity_ids: + dropped_optional_entities[entity_id] = "missing_geometry" + else: + failures.append(f"{entity_id}:missing_geometry") + except ValueError as error: + if entity_id in optional_entity_ids: + dropped_optional_entities[entity_id] = str(error) + else: + failures.append(str(error)) + required = [item for item in required if item not in dropped_optional_entities] + if metric_layout_spec is not None: + solver_ids = set(required) + metric_ids = set(metric_by_id) + for entity_id in sorted(solver_ids - metric_ids): + failures.append(f"{entity_id}:metric_layout_missing_entity") + for entity_id in sorted(metric_ids - solver_ids): + failures.append(f"{entity_id}:metric_layout_entity_not_in_dag") + room_tolerance = max(0.02, policy.room_containment_tolerance_m) + if not ( + evidence_room.buffer(room_tolerance).covers(room) + and room.buffer(room_tolerance).covers(evidence_room) + ): + failures.append("world:metric_layout_room_mismatch") + for entity_id in sorted(solver_ids & metric_ids): + declared = metric_by_id[entity_id] + if parents.get(entity_id) != declared.parent_entity_id: + failures.append(f"{entity_id}:metric_layout_parent_mismatch") + item = geometries.get(entity_id) + if item is None: + continue + actual_span = ( + item.maximum[0] - item.minimum[0], + item.maximum[1] - item.minimum[1], + ) + if metric_layout_spec.footprint_validation_mode == "maximum_envelope": + footprint_mismatch = any( + actual_span[index] - declared.footprint_m[index] + > metric_layout_spec.footprint_tolerance_m + for index in range(2) + ) + footprint_failure = "metric_layout_asset_footprint_exceeds_envelope" + else: + footprint_mismatch = any( + abs(actual_span[index] - declared.footprint_m[index]) + > metric_layout_spec.footprint_tolerance_m + for index in range(2) + ) + footprint_failure = "metric_layout_asset_footprint_mismatch" + if footprint_mismatch: + failures.append( + f"{entity_id}:{footprint_failure}:" + f"actual={actual_span}:declared={declared.footprint_m}" + ) + rotated = replace(item, yaw_degrees=declared.yaw_deg) + local_center = rotated.footprint.centroid + metric_pose = ( + declared.center_xy_m[0] - float(local_center.x), + declared.center_xy_m[1] - float(local_center.y), + item.original[2], + ) + geometries[entity_id] = replace(rotated, original=metric_pose) + for obstacle_id, (minimum, maximum) in (fixed_obstacles or {}).items(): + try: + low = _finite_vector(minimum, name=f"{obstacle_id}:bbox_min") + high = _finite_vector(maximum, name=f"{obstacle_id}:bbox_max") + obstacle_footprint = box(low[0], low[1], high[0], high[1]) + if any(high[index] <= low[index] for index in range(3)): + failures.append(f"{obstacle_id}:empty_bbox") + elif not room.buffer(policy.room_containment_tolerance_m).covers(obstacle_footprint): + failures.append(f"{obstacle_id}:outside_room") + except ValueError as error: + failures.append(str(error)) + if failures: + certificate = WorldGeometryCertificate( + elapsed_s=time.monotonic() - started, + hard_gates_passed=False, + room_polygon_xy_m=list(room.exterior.coords), + transform_sha256=_sha({}), + failures=sorted(failures), + dropped_optional_entities=dropped_optional_entities, + metric_layout_spec_sha256=( + _sha(metric_layout_spec.model_dump(mode="json")) + if metric_layout_spec is not None + else None + ), + ) + return PlacementSolution( + {}, + {}, + certificate, + metric_layout_spec=metric_layout_spec, + parent_by_entity=parents, + ) + + clearance_room = room.buffer(-policy.free_wall_clearance_m) + containment_room = room.buffer(policy.room_containment_tolerance_m) + placed_shapes: dict[str, Polygon] = {} + translations: dict[str, tuple[float, float, float]] = {} + measurements: dict[str, PlacementMeasurement] = {} + obstacle_shapes = [ + box(low[0], low[1], high[0], high[1]) for low, high in (fixed_obstacles or {}).values() + ] + obstacle_geometries = [ + _Geometry(name, low, high, (0.0, 0.0, 0.0), 0.0) + for name, (low, high) in (fixed_obstacles or {}).items() + ] + metric_forbidden_shapes = ( + [Polygon(metric_layout_spec.route_polygon_xy_m)] + + [Polygon(region.polygon_xy_m) for region in metric_layout_spec.keep_out_regions] + if metric_layout_spec is not None + else [] + ) + relation_constraints: dict[str, list[dict[str, Any]]] = defaultdict(list) + for constraint in semantic_constraints or []: + if not isinstance(constraint, dict) or constraint.get("relation") not in { + "clearance", + "center_distance", + "opposite_sides", + }: + continue + if constraint.get("relation") == "opposite_sides" and not bool( + constraint.get("enforce") + ): + continue + subject = str(constraint.get("subject") or "") + object_id = str(constraint.get("object") or "") + if subject and object_id: + relation_constraints[subject].append({**constraint, "other": object_id}) + relation_constraints[object_id].append({**constraint, "other": subject}) + + root_ids = [entity_id for entity_id in required if parents.get(entity_id) is None] + worker_count = max(1, min(8, len(root_ids))) + start_gate = threading.Event() + start_lock = threading.Lock() + started_workers = 0 + + def prepare_root_candidates(entity_id: str) -> dict[str, Any]: + nonlocal started_workers + item = geometries[entity_id] + node = node_by_id[entity_id] + attributes = node.metadata.get("attributes") or {} + against_wall = bool(attributes.get("against_wall")) or node.stage == "wall_mounted" + if node.stage == "ceiling_mounted" and ceiling_z is not None: + z = ceiling_z - item.maximum[2] + elif node.stage == "wall_mounted": + z = item.original[2] + else: + z = floor_z - item.minimum[2] + if metric_layout_spec is not None: + feasible = Polygon(metric_by_id[entity_id].zone_polygon_xy_m).intersection( + containment_room + ) + else: + feasible = ( + containment_room + if against_wall + else (clearance_room if not clearance_room.is_empty else containment_room) + ) + started_unix = time.time() + with start_lock: + started_workers += 1 + if started_workers >= worker_count: + start_gate.set() + start_gate.wait() + candidates = ( + [("metric_layout_spec", item.original[0], item.original[1])] + if metric_layout_spec is not None + else list( + _candidate_xy(item.original, item.footprint, feasible, policy.candidate_grid_m) + ) + ) + candidates.sort( + key=lambda value: ( + (value[1] - item.original[0]) ** 2 + (value[2] - item.original[1]) ** 2, + value[0], + value[1], + value[2], + ) + ) + completed_unix = time.time() + return { + "z": z, + "feasible": feasible, + "against_wall": against_wall, + "candidates": candidates, + "interval": { + "task_id": f"root-candidates:{entity_id}", + "started_unix": started_unix, + "completed_unix": completed_unix, + "duration_s": completed_unix - started_unix, + }, + } + + with ThreadPoolExecutor(max_workers=worker_count) as executor: + root_candidate_data = dict( + zip(root_ids, executor.map(prepare_root_candidates, root_ids), strict=True) + ) + parallel_intervals = [root_candidate_data[item]["interval"] for item in root_ids] + + for entity_id in required: + item = geometries[entity_id] + parent_id = parents[entity_id] + if parent_id in dropped_optional_entities: + if entity_id in optional_entity_ids: + dropped_optional_entities[entity_id] = f"parent_dropped:{parent_id}" + continue + failures.append(f"{entity_id}:critical_child_of_dropped_parent:{parent_id}") + continue + own_failures: list[str] = [] + support_coverage: float | None = None + com_margin: float | None = None + candidate_kind = "agent_original" + narrow_phase_backend = "not_required" + if parent_id and parent_id in geometries and parent_id in translations: + parent = geometries[parent_id] + parent_shape = placed_shapes[parent_id] + safe_support = parent_shape.buffer(-max(0.0, policy.room_containment_tolerance_m)) + z = translations[parent_id][2] + parent.maximum[2] - item.minimum[2] + parent_delta = tuple( + translations[parent_id][index] - parent.original[index] for index in range(3) + ) + rigid_seed = ( + item.original[0] + parent_delta[0], + item.original[1] + parent_delta[1], + item.original[2] + parent_delta[2], + ) + candidates = ( + [("metric_layout_spec", item.original[0], item.original[1])] + if metric_layout_spec is not None + else _candidate_xy( + rigid_seed, item.footprint, safe_support, policy.candidate_grid_m + ) + ) + chosen = None + sibling_ids = [ + other_id + for other_id in placed_shapes + if parents.get(other_id) == parent_id and other_id != parent_id + ] + for kind, x, y in candidates: + shape = _translated(item.footprint, (x, y, z)) + if not safe_support.covers(shape): + continue + collides = False + for sibling_id in sibling_ids: + if not shape.intersects(placed_shapes[sibling_id]): + continue + distance, narrow_phase_backend = _drake_box_signed_distance( + item, + (x, y, z), + geometries[sibling_id], + translations[sibling_id], + ) + if ( + metric_layout_spec is not None + and shape.intersection(placed_shapes[sibling_id]).area > 1.0e-8 + ) or distance < -policy.penetration_tolerance_m: + collides = True + break + if not collides: + chosen = (kind, (x, y, z), shape) + break + if chosen is None: + own_failures.append("support_infeasible") + pose = (item.original[0], item.original[1], z) + shape = _translated(item.footprint, pose) + else: + candidate_kind, pose, shape = chosen + intersection = shape.intersection(parent_shape).area + support_coverage = intersection / max(shape.area, 1.0e-12) + com_margin = ( + safe_support.boundary.distance(shape.centroid) + if safe_support.covers(shape.centroid) + else -1.0 + ) + if support_coverage + 1.0e-9 < 0.8: + own_failures.append("support_coverage") + if not safe_support.covers(shape.centroid): + own_failures.append("center_of_mass") + else: + prepared = root_candidate_data[entity_id] + z = float(prepared["z"]) + feasible = prepared["feasible"] + against_wall = bool(prepared["against_wall"]) + candidates = prepared["candidates"] + chosen = None + existing_ids = [other_id for other_id in placed_shapes if parents.get(other_id) is None] + existing = [placed_shapes[other_id] for other_id in existing_ids] + obstacle_shapes + tree = STRtree(existing) if existing else None + for kind, x, y in candidates: + shape = _translated(item.footprint, (x, y, z)) + if not feasible.covers(shape): + continue + if any(shape.intersects(forbidden) for forbidden in metric_forbidden_shapes): + continue + wall_gap = room.boundary.distance(shape) + if against_wall and wall_gap > policy.against_wall_gap_m: + continue + semantic_valid = True + for constraint in relation_constraints.get(entity_id, []): + other_id = str(constraint["other"]) + if other_id not in placed_shapes: + continue + relation = str(constraint.get("relation") or "") + if relation == "opposite_sides": + anchor_id = str(constraint.get("anchor") or "") + if anchor_id not in placed_shapes: + continue + maximum_cosine = float(constraint.get("maximum_cosine") or -0.8) + if ( + _opposition_cosine( + shape, + placed_shapes[other_id], + placed_shapes[anchor_id], + ) + > maximum_cosine + ): + semantic_valid = False + break + continue + if relation == "center_distance": + clearance_distance = shape.centroid.distance( + placed_shapes[other_id].centroid + ) + else: + clearance_distance = shape.distance(placed_shapes[other_id]) + minimum_distance = float(constraint.get("minimum_distance_m") or 0.0) + maximum_distance = float(constraint.get("maximum_distance_m") or math.inf) + if not minimum_distance <= clearance_distance <= maximum_distance: + semantic_valid = False + break + if not semantic_valid: + continue + collision = False + if tree is not None: + for index in tree.query(shape): + obstacle_index = int(index) + if not shape.intersects(existing[obstacle_index]): + continue + if obstacle_index < len(existing_ids): + other_id = existing_ids[obstacle_index] + other_geometry = geometries[other_id] + other_pose = translations[other_id] + else: + fixed_index = obstacle_index - len(existing_ids) + other_geometry = obstacle_geometries[fixed_index] + other_pose = (0.0, 0.0, 0.0) + distance, narrow_phase_backend = _drake_box_signed_distance( + item, (x, y, z), other_geometry, other_pose + ) + if ( + metric_layout_spec is not None + and shape.intersection(existing[obstacle_index]).area > 1.0e-8 + ) or distance < -policy.penetration_tolerance_m: + collision = True + break + if collision: + continue + chosen = (kind, (x, y, z), shape) + break + if chosen is None: + own_failures.append("collision_or_containment_infeasible") + pose = (item.original[0], item.original[1], z) + shape = _translated(item.footprint, pose) + else: + candidate_kind, pose, shape = chosen + + placed_shapes[entity_id] = shape + translations[entity_id] = pose + min_x, min_y, max_x, max_y = shape.bounds + world_min = (min_x, min_y, pose[2] + item.minimum[2]) + world_max = (max_x, max_y, pose[2] + item.maximum[2]) + task_support_height = world_max[2] if entity_id in task_support_ids else None + if not containment_room.covers(shape): + own_failures.append("outside_room") + room_margin = room.boundary.distance(shape) if room.covers(shape) else -room.distance(shape) + floor_gap = None if parent_id else world_min[2] - floor_z + penetration = max(0.0, floor_z - world_min[2]) if not parent_id else 0.0 + stage = node_by_id[entity_id].stage + if stage in {"wall_mounted", "ceiling_mounted"}: + floor_gap = None + penetration = 0.0 + if world_min[2] < floor_z - policy.penetration_tolerance_m: + own_failures.append("below_room") + if ceiling_z is not None and world_max[2] > ceiling_z + policy.penetration_tolerance_m: + own_failures.append("above_room") + if ( + stage == "wall_mounted" + and room.boundary.distance(shape) > policy.against_wall_gap_m + ): + own_failures.append("against_wall_gap") + if floor_gap is not None and floor_gap > policy.floor_gap_m: + own_failures.append("floor_gap") + if penetration > policy.penetration_tolerance_m: + own_failures.append("penetration") + if ( + task_support_height is not None + and task_support_height > support_range[1] + ): + own_failures.append("task_support_above_robot_workspace") + if task_support_height is not None and task_support_height < support_range[0]: + own_failures.append("task_support_below_robot_workspace") + if own_failures and entity_id in optional_entity_ids: + dropped_optional_entities[entity_id] = ",".join(sorted(set(own_failures))) + placed_shapes.pop(entity_id, None) + translations.pop(entity_id, None) + continue + digest_payload = { + "entity_id": entity_id, + "translation_m": pose, + "yaw_deg": item.yaw_degrees, + } + measurements[entity_id] = PlacementMeasurement( + entity_id=entity_id, + parent_id=parent_id, + local_bbox_min_m=item.minimum, + local_bbox_max_m=item.maximum, + original_translation_m=item.original, + corrected_translation_m=pose, + yaw_deg=item.yaw_degrees, + target_center_xy_m=( + metric_by_id[entity_id].center_xy_m + if entity_id in metric_by_id + else None + ), + footprint_polygon_xy_m=[ + (float(x), float(y)) for x, y in list(shape.exterior.coords)[:-1] + ], + world_bbox_min_m=world_min, + world_bbox_max_m=world_max, + room_boundary_margin_m=room_margin, + floor_gap_m=floor_gap, + penetration_m=penetration, + support_coverage=support_coverage, + com_margin_m=com_margin, + task_support_surface_height_m=task_support_height, + collision_free="collision_or_containment_infeasible" not in own_failures, + asset_sha256=(asset_hashes or {}).get(entity_id), + transform_sha256=_sha(digest_payload), + candidate_kind=candidate_kind, + narrow_phase_backend=narrow_phase_backend, + hard_gates_passed=not own_failures, + failures=sorted(set(own_failures)), + ) + failures.extend(f"{entity_id}:{failure}" for failure in own_failures) + + semantic_measurements: list[SemanticConstraintMeasurement] = [] + for constraint in semantic_constraints or []: + if not isinstance(constraint, dict) or constraint.get("relation") not in { + "clearance", + "center_distance", + }: + continue + subject = str(constraint.get("subject") or "") + object_id = str(constraint.get("object") or "") + constraint_id = str( + constraint.get("constraint_id") or f"{constraint.get('relation')}:{subject}:{object_id}" + ) + minimum_distance = float(constraint.get("minimum_distance_m") or 0.0) + maximum_distance = float(constraint.get("maximum_distance_m") or math.inf) + if subject not in placed_shapes or object_id not in placed_shapes: + failures.append(f"semantic_constraint:{constraint_id}:missing_entity") + continue + relation = str(constraint.get("relation")) + measured_distance = float( + placed_shapes[subject].centroid.distance(placed_shapes[object_id].centroid) + if relation == "center_distance" + else placed_shapes[subject].distance(placed_shapes[object_id]) + ) + passed = minimum_distance <= measured_distance <= maximum_distance + semantic_measurements.append( + SemanticConstraintMeasurement( + constraint_id=constraint_id, + relation=relation, + subject=subject, + object=object_id, + minimum_distance_m=minimum_distance, + maximum_distance_m=maximum_distance, + measured_distance_m=measured_distance, + hard_gates_passed=passed, + ) + ) + if not passed: + failures.append( + f"semantic_constraint:{constraint_id}:clearance={measured_distance:.6f}" + ) + + for constraint in semantic_constraints or []: + if not isinstance(constraint, dict) or not bool(constraint.get("enforce")): + continue + relation = str(constraint.get("relation") or "") + if relation not in {"facing", "opposite_sides"}: + continue + subject = str(constraint.get("subject") or "") + object_id = str(constraint.get("object") or "") + constraint_id = str(constraint.get("constraint_id") or f"{relation}:{subject}:{object_id}") + if subject not in placed_shapes or object_id not in placed_shapes: + failures.append(f"semantic_constraint:{constraint_id}:missing_entity") + continue + if relation == "facing": + subject_center = placed_shapes[subject].centroid + object_center = placed_shapes[object_id].centroid + target_vector = ( + object_center.x - subject_center.x, + object_center.y - subject_center.y, + ) + target_norm = math.hypot(*target_vector) + yaw = math.radians(geometries[subject].yaw_degrees) + forward_axis = str(constraint.get("forward_axis_local") or "+x").casefold() + if forward_axis == "+y": + forward = (-math.sin(yaw), math.cos(yaw)) + elif forward_axis == "-x": + forward = (-math.cos(yaw), -math.sin(yaw)) + elif forward_axis == "-y": + forward = (math.sin(yaw), -math.cos(yaw)) + else: + forward_axis = "+x" + forward = (math.cos(yaw), math.sin(yaw)) + cosine = ( + (forward[0] * target_vector[0] + forward[1] * target_vector[1]) / target_norm + if target_norm > 1.0e-9 + else -1.0 + ) + measured_angle = math.degrees(math.acos(max(-1.0, min(1.0, cosine)))) + maximum_angle = float(constraint.get("maximum_angle_degrees") or 35.0) + passed = measured_angle <= maximum_angle + semantic_measurements.append( + SemanticConstraintMeasurement( + constraint_id=constraint_id, + relation=relation, + subject=subject, + object=object_id, + maximum_angle_degrees=maximum_angle, + measured_angle_degrees=measured_angle, + forward_axis_local=forward_axis, + hard_gates_passed=passed, + ) + ) + if not passed: + failures.append( + f"semantic_constraint:{constraint_id}:facing_angle={measured_angle:.6f}" + ) + continue + + anchor = str(constraint.get("anchor") or "") + if anchor not in placed_shapes: + failures.append(f"semantic_constraint:{constraint_id}:missing_anchor") + continue + measured_cosine = _opposition_cosine( + placed_shapes[subject], + placed_shapes[object_id], + placed_shapes[anchor], + ) + maximum_cosine = float(constraint.get("maximum_cosine") or -0.8) + passed = measured_cosine <= maximum_cosine + semantic_measurements.append( + SemanticConstraintMeasurement( + constraint_id=constraint_id, + relation=relation, + subject=subject, + object=object_id, + anchor=anchor, + maximum_cosine=maximum_cosine, + measured_cosine=measured_cosine, + hard_gates_passed=passed, + ) + ) + if not passed: + failures.append( + f"semantic_constraint:{constraint_id}:opposition_cosine={measured_cosine:.6f}" + ) + + metric_validation: MetricLayoutValidation | None = None + if metric_layout_spec is not None: + metric_validation = validate_metric_layout_footprints( + metric_layout_spec, + placed_shapes, + center_tolerance_m=max(0.003, policy.room_containment_tolerance_m), + perturbation_applied=metric_layout_perturbation_attempt is not None, + perturbation_attempt=metric_layout_perturbation_attempt, + ) + failures.extend(metric_validation.failures) + yaw_degrees = { + entity_id: geometries[entity_id].yaw_degrees + for entity_id in translations + } + transform_hash = _sha( + { + key: { + "translation_m": translations[key], + "yaw_deg": yaw_degrees[key], + } + for key in sorted(translations) + } + ) + elapsed = time.monotonic() - started + world_certificate = WorldGeometryCertificate( + elapsed_s=elapsed, + hard_gates_passed=not failures, + room_polygon_xy_m=list(room.exterior.coords), + transform_sha256=transform_hash, + failures=sorted(set(failures)), + entities=[measurements[key] for key in sorted(measurements)], + semantic_constraints=semantic_measurements, + parallel_intervals=parallel_intervals, + dropped_optional_entities=dropped_optional_entities, + metric_layout_spec_sha256=( + _sha(metric_layout_spec.model_dump(mode="json")) + if metric_layout_spec is not None + else None + ), + metric_layout_validation=metric_validation, + ) + return PlacementSolution( + translations, + measurements, + world_certificate, + yaw_degrees=yaw_degrees, + metric_layout_spec=metric_layout_spec, + parent_by_entity=parents, + ) + + +def write_placement_artifacts( + output_root: Path, + solution: PlacementSolution, + *, + subtree_by_node: dict[str, str], +) -> dict[str, PlacementCertificate]: + output_root.mkdir(parents=True, exist_ok=True) + plan = { + "schema_version": "1.0", + "solver": "deterministic_shapely_strtree", + "api_token_count": 0, + "entities": [ + { + "entity_id": entity_id, + "parent_id": item.parent_id, + "original_translation_m": item.original_translation_m, + "corrected_translation_m": item.corrected_translation_m, + "yaw_deg": item.yaw_deg, + "target_center_xy_m": item.target_center_xy_m, + "footprint_polygon_xy_m": item.footprint_polygon_xy_m, + "candidate_kind": item.candidate_kind, + } + for entity_id, item in sorted(solution.measurements.items()) + ], + } + atomic_write_text( + output_root / "constraint_placement_plan.json", + json.dumps(plan, indent=2, sort_keys=True) + "\n", + ) + grouped: dict[str, list[PlacementMeasurement]] = defaultdict(list) + for entity_id, item in solution.measurements.items(): + grouped[subtree_by_node.get(entity_id, "unowned")].append(item) + certificates: dict[str, PlacementCertificate] = {} + for subtree_id, items in grouped.items(): + failures = sorted(failure for item in items for failure in item.failures) + certificate = PlacementCertificate( + subtree_id=subtree_id, + elapsed_s=solution.world_certificate.elapsed_s, + hard_gates_passed=not failures, + failures=failures, + entities=sorted(items, key=lambda item: item.entity_id), + ) + subtree = output_root / "subtrees" / subtree_id + subtree.mkdir(parents=True, exist_ok=True) + atomic_write_text( + subtree / "placement_certificate.json", + certificate.model_dump_json(indent=2) + "\n", + ) + delta = { + "schema_version": "1.0", + "subtree_id": subtree_id, + "local_coordinates_frozen": True, + "transforms": { + item.entity_id: { + "translation_m": item.corrected_translation_m, + "yaw_deg": item.yaw_deg, + "transform_sha256": item.transform_sha256, + } + for item in items + }, + } + atomic_write_text( + subtree / "owned_transform_delta.json", + json.dumps(delta, indent=2, sort_keys=True) + "\n", + ) + certificates[subtree_id] = certificate + atomic_write_text( + output_root / "world_geometry_certificate.json", + solution.world_certificate.model_dump_json(indent=2) + "\n", + ) + return certificates + + +def validate_final_usd_geometry( + root_usd: Path, + entity_prim_paths: dict[str, str], + solution: PlacementSolution, + certificate_path: Path, + *, + tolerance_m: float = 0.003, +) -> WorldGeometryCertificate: + """Re-measure the composed stage; metadata-only certificates cannot publish.""" + + try: + from pxr import Gf, Usd, UsdGeom # type: ignore[import-not-found] + except ImportError as error: # pragma: no cover - owned by the Isaac/SceneSmith env + raise RuntimeError("pxr is required for final USD geometry certification") from error + stage = Usd.Stage.Open(str(root_usd)) + if stage is None: + raise RuntimeError(f"could not open final USD for certification: {root_usd}") + cache = UsdGeom.BBoxCache( + Usd.TimeCode.Default(), + [UsdGeom.Tokens.default_, UsdGeom.Tokens.render, UsdGeom.Tokens.proxy], + useExtentsHint=False, + ) + xform_cache = UsdGeom.XformCache(Usd.TimeCode.Default()) + failures = list(solution.world_certificate.failures) + usd_transforms: dict[str, tuple[float, float, float]] = {} + usd_footprints: dict[str, Polygon] = {} + metric_local_footprints: dict[str, Polygon] = {} + usd_forward_vectors: dict[str, tuple[float, float]] = {} + expected_world_transforms: dict[str, tuple[float, float, float]] = {} + for entity_id, expected in solution.measurements.items(): + authored_path = entity_prim_paths.get(entity_id) + if not authored_path: + failures.append(f"{entity_id}:missing_usd_prim_binding") + continue + stage_path = authored_path.replace( + "/World/SceneSmithGenerated/SceneSmith", "/World/SceneSmith", 1 + ) + prim = stage.GetPrimAtPath(stage_path) + if not prim: + failures.append(f"{entity_id}:missing_usd_prim") + continue + if UsdGeom.Imageable(prim).ComputeVisibility() == UsdGeom.Tokens.invisible: + failures.append(f"{entity_id}:usd_prim_invisible") + continue + aligned = cache.ComputeWorldBound(prim).ComputeAlignedBox() + minimum = tuple(float(aligned.GetMin()[index]) for index in range(3)) + maximum = tuple(float(aligned.GetMax()[index]) for index in range(3)) + if not all(math.isfinite(value) and abs(value) < 1.0e20 for value in minimum + maximum): + failures.append(f"{entity_id}:non_finite_usd_bbox") + continue + if any(maximum[index] <= minimum[index] for index in range(3)): + failures.append(f"{entity_id}:empty_usd_bbox") + continue + matrix = xform_cache.GetLocalToWorldTransform(prim) + translation = tuple(float(matrix.ExtractTranslation()[index]) for index in range(3)) + usd_transforms[entity_id] = translation # type: ignore[assignment] + expected_payload = prim.GetCustomDataByKey("robothousegen:solver_world_translation_json") + try: + expected_translation = _finite_vector( + json.loads(str(expected_payload)), name=f"{entity_id}:authored_solver_pose" + ) + except (ValueError, TypeError, json.JSONDecodeError): + expected_translation = expected.corrected_translation_m + expected_world_transforms[entity_id] = expected_translation + frame_offset = tuple( + expected_translation[index] - expected.corrected_translation_m[index] + for index in range(3) + ) + expected_world_min = tuple( + expected.world_bbox_min_m[index] + frame_offset[index] + for index in range(3) + ) + expected_world_max = tuple( + expected.world_bbox_max_m[index] + frame_offset[index] + for index in range(3) + ) + if any( + abs(minimum[index] - expected_world_min[index]) > tolerance_m + or abs(maximum[index] - expected_world_max[index]) > tolerance_m + for index in range(3) + ): + failures.append(f"{entity_id}:proxy_canonical_world_bbox_mismatch") + local_minimum = expected.local_bbox_min_m + local_maximum = expected.local_bbox_max_m + footprint_corners = [ + matrix.Transform(Gf.Vec3d(x, y, local_minimum[2])) + for x, y in ( + (local_minimum[0], local_minimum[1]), + (local_maximum[0], local_minimum[1]), + (local_maximum[0], local_maximum[1]), + (local_minimum[0], local_maximum[1]), + ) + ] + usd_footprint = Polygon( + [(float(point[0]), float(point[1])) for point in footprint_corners] + ).convex_hull + if usd_footprint.is_empty or usd_footprint.area <= 0: + failures.append(f"{entity_id}:empty_usd_footprint") + continue + usd_footprints[entity_id] = usd_footprint + metric_local_footprints[entity_id] = affinity.translate( + usd_footprint, + xoff=-frame_offset[0], + yoff=-frame_offset[1], + ) + if expected.footprint_polygon_xy_m: + expected_footprint = affinity.translate( + Polygon(expected.footprint_polygon_xy_m), + xoff=frame_offset[0], + yoff=frame_offset[1], + ) + if usd_footprint.hausdorff_distance(expected_footprint) > tolerance_m: + failures.append(f"{entity_id}:usd_oriented_footprint_mismatch") + # Cache both canonical horizontal axes. The semantic measurement records + # which native forward axis was certified for this asset. + for axis_name, local_axis in ( + ("+x", (1.0, 0.0)), + ("+y", (0.0, 1.0)), + ("-x", (-1.0, 0.0)), + ("-y", (0.0, -1.0)), + ): + forward = matrix.TransformDir(Gf.Vec3d(local_axis[0], local_axis[1], 0.0)) + forward_norm = math.hypot(float(forward[0]), float(forward[1])) + if forward_norm > 1.0e-9: + usd_forward_vectors[f"{entity_id}:{axis_name}"] = ( + float(forward[0]) / forward_norm, + float(forward[1]) / forward_norm, + ) + room_polygon = affinity.translate( + Polygon(solution.world_certificate.room_polygon_xy_m), + xoff=frame_offset[0], + yoff=frame_offset[1], + ) + usd_aligned_footprint = box(minimum[0], minimum[1], maximum[0], maximum[1]) + if not room_polygon.buffer(tolerance_m).covers(usd_aligned_footprint): + failures.append(f"{entity_id}:usd_bbox_outside_room") + if any( + abs(translation[index] - expected_translation[index]) > tolerance_m + for index in range(3) + ): + failures.append(f"{entity_id}:usd_transform_mismatch") + metric_usd_validation: MetricLayoutValidation | None = None + if solution.metric_layout_spec is not None: + prior_metric = solution.world_certificate.metric_layout_validation + metric_usd_validation = validate_metric_layout_footprints( + solution.metric_layout_spec, + metric_local_footprints, + center_tolerance_m=tolerance_m, + perturbation_applied=bool( + prior_metric and prior_metric.perturbation_applied + ), + perturbation_attempt=( + prior_metric.perturbation_attempt if prior_metric else None + ), + ) + failures.extend(metric_usd_validation.failures) + state_hash = _sha( + {key: expected_world_transforms[key] for key in sorted(expected_world_transforms)} + ) + usd_hash = _sha({key: usd_transforms[key] for key in sorted(usd_transforms)}) + if set(usd_transforms) != set(solution.translations): + failures.append("world:usd_entity_set_mismatch") + # Hashes encode independently measured values. Exact hash equality is required + # after normalizing float precision to the transform gate tolerance. + normalized_state = { + key: tuple(round(value, 6) for value in expected_world_transforms[key]) + for key in sorted(expected_world_transforms) + } + normalized_usd = { + key: tuple(round(value, 6) for value in usd_transforms[key]) + for key in sorted(usd_transforms) + } + if normalized_state != normalized_usd: + failures.append("world:state_usd_transform_hash_mismatch") + usd_semantic_measurements: list[SemanticConstraintMeasurement] = [] + for expected_semantic in solution.world_certificate.semantic_constraints: + if ( + expected_semantic.subject not in usd_footprints + or expected_semantic.object not in usd_footprints + ): + failures.append( + f"semantic_constraint:{expected_semantic.constraint_id}:missing_usd_entity" + ) + continue + if expected_semantic.relation in {"clearance", "center_distance"}: + measured = float( + usd_footprints[expected_semantic.subject].centroid.distance( + usd_footprints[expected_semantic.object].centroid + ) + if expected_semantic.relation == "center_distance" + else usd_footprints[expected_semantic.subject].distance( + usd_footprints[expected_semantic.object] + ) + ) + semantic_minimum = float(expected_semantic.minimum_distance_m or 0.0) + semantic_maximum = float(expected_semantic.maximum_distance_m or math.inf) + passed = ( + semantic_minimum - tolerance_m + <= measured + <= semantic_maximum + tolerance_m + ) + semantic_measurement = expected_semantic.model_copy( + update={"measured_distance_m": measured, "hard_gates_passed": passed} + ) + failure_value = measured + elif expected_semantic.relation == "facing": + subject_center = usd_footprints[expected_semantic.subject].centroid + object_center = usd_footprints[expected_semantic.object].centroid + target = ( + object_center.x - subject_center.x, + object_center.y - subject_center.y, + ) + target_norm = math.hypot(*target) + axis = expected_semantic.forward_axis_local or "+x" + forward = usd_forward_vectors.get( + f"{expected_semantic.subject}:{axis}", (0.0, 0.0) + ) + cosine = ( + (forward[0] * target[0] + forward[1] * target[1]) / target_norm + if target_norm > 1.0e-9 + else -1.0 + ) + measured = math.degrees(math.acos(max(-1.0, min(1.0, cosine)))) + semantic_maximum = float(expected_semantic.maximum_angle_degrees or 35.0) + passed = measured <= semantic_maximum + 0.1 + semantic_measurement = expected_semantic.model_copy( + update={"measured_angle_degrees": measured, "hard_gates_passed": passed} + ) + failure_value = measured + else: + anchor = expected_semantic.anchor or "" + if anchor not in usd_footprints: + failures.append( + f"semantic_constraint:{expected_semantic.constraint_id}:missing_usd_anchor" + ) + continue + anchor_center = usd_footprints[anchor].centroid + subject_center = usd_footprints[expected_semantic.subject].centroid + object_center = usd_footprints[expected_semantic.object].centroid + left = (subject_center.x - anchor_center.x, subject_center.y - anchor_center.y) + right = (object_center.x - anchor_center.x, object_center.y - anchor_center.y) + denominator = math.hypot(*left) * math.hypot(*right) + measured = ( + (left[0] * right[0] + left[1] * right[1]) / denominator + if denominator > 1.0e-9 + else 1.0 + ) + semantic_maximum = float(expected_semantic.maximum_cosine or -0.8) + passed = measured <= semantic_maximum + 1.0e-3 + semantic_measurement = expected_semantic.model_copy( + update={"measured_cosine": measured, "hard_gates_passed": passed} + ) + failure_value = measured + usd_semantic_measurements.append(semantic_measurement) + if not passed: + failures.append( + f"semantic_constraint:{expected_semantic.constraint_id}:" + f"usd_{expected_semantic.relation}=" + f"{failure_value:.6f}" + ) + certificate = solution.world_certificate.model_copy( + update={ + "state_transform_sha256": state_hash, + "usd_transform_sha256": usd_hash, + "usd_validation_passed": not failures, + "hard_gates_passed": not failures, + "failures": sorted(set(failures)), + "semantic_constraints": usd_semantic_measurements, + "metric_layout_validation": metric_usd_validation, + } + ) + atomic_write_text(certificate_path, certificate.model_dump_json(indent=2) + "\n") + return certificate diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/functional_front.py b/docs/reproduction/public_conversion_code/packages/scene_generation/functional_front.py new file mode 100644 index 0000000000000000000000000000000000000000..91a3e9d27e987d0a8d3bbb95c76237d14087bb4e --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/functional_front.py @@ -0,0 +1,256 @@ +from __future__ import annotations + +import math +from functools import lru_cache +from pathlib import Path +from typing import Any, Literal, cast + +import numpy as np +import trimesh +from pydantic import BaseModel, ConfigDict, Field + +from packages.asset_registry.descriptors import AssetDescriptor +from packages.asset_registry.front_certification import definition_for_category +from packages.asset_registry.front_policy import effective_functional_front_axis + +FunctionalSemantics = Literal[ + "seating_gaze", "bed_foot", "operation_side", "screen_normal" +] +GeometryFunctionalSemantics = Literal["seating_gaze", "bed_foot"] +FunctionalAxis = Literal["+X", "-X", "+Y", "-Y"] + +_AXIS_VECTORS: dict[FunctionalAxis, np.ndarray] = { + "+X": np.asarray((1.0, 0.0)), + "-X": np.asarray((-1.0, 0.0)), + "+Y": np.asarray((0.0, 1.0)), + "-Y": np.asarray((0.0, -1.0)), +} +_OPPOSITE: dict[FunctionalAxis, FunctionalAxis] = { + "+X": "-X", + "-X": "+X", + "+Y": "-Y", + "-Y": "+Y", +} +_CERTIFIED_DESCRIPTOR_SOURCES = {"multiview_verified", "manual_override"} + + +class FunctionalFrontCertificate(BaseModel): + """Hash-bound evidence for the side a person or robot functionally faces. + + Authored forward vectors are not sufficient for asymmetric furniture. A + Geometry certificates treat a seating backrest or bed headboard as the + back. Storage/display certificates instead consume the descriptor's + autonomous, hash-bound multiview affordance result. + """ + + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["1.0"] = "1.0" + asset_id: str + asset_sha256: str + semantics: FunctionalSemantics + functional_front_axis: FunctionalAxis + detected_back_axis: FunctionalAxis + source: Literal[ + "geometry_backrest_verified", + "geometry_headboard_verified", + "multiview_geometry_consensus", + "multiview_affordance_consensus", + ] + confidence: float = Field(ge=0.0, le=1.0) + score_by_axis: dict[str, float] + score_margin: float = Field(ge=0.0) + opposite_side_margin: float + evidence: list[str] + + +def opposite_axis(axis: FunctionalAxis) -> FunctionalAxis: + return _OPPOSITE[axis] + + +def _canonical_vertices(descriptor: AssetDescriptor) -> np.ndarray: + source = Path(descriptor.canonical_path) + loaded = trimesh.load(str(source), force="scene", process=False) + meshes: list[Any] = ( + list(loaded.geometry.values()) if isinstance(loaded, trimesh.Scene) else [loaded] + ) + transform = np.asarray(descriptor.canonical_transform, dtype=np.float64).reshape(4, 4) + transformed: list[np.ndarray] = [] + for mesh in meshes: + vertices = np.asarray(mesh.vertices, dtype=np.float64) + if not len(vertices): + continue + homogeneous = np.column_stack((vertices, np.ones(len(vertices)))) + transformed.append((homogeneous @ transform.T)[:, :3]) + if not transformed: + raise ValueError(f"functional-front mesh is empty: {descriptor.asset_id}") + return np.concatenate(transformed, axis=0) + + +def _back_support_scores(vertices: np.ndarray) -> dict[FunctionalAxis, float]: + low = vertices.min(axis=0) + high = vertices.max(axis=0) + span = np.maximum(high - low, 1.0e-9) + normalized_z = (vertices[:, 2] - low[2]) / span[2] + output: dict[FunctionalAxis, float] = {} + for axis, direction in _AXIS_VECTORS.items(): + projection = vertices[:, :2] @ direction + threshold = projection.max() - 0.22 * (projection.max() - projection.min()) + edge_z = normalized_z[projection >= threshold] + if len(edge_z) < 12: + output[axis] = 0.0 + continue + high_fraction = float(np.mean(edge_z >= 0.58)) + upper = edge_z[edge_z >= 0.42] + upper_mean = float(np.mean(upper)) if len(upper) else 0.0 + p90 = float(np.quantile(edge_z, 0.90)) + output[axis] = 0.55 * high_fraction + 0.30 * upper_mean + 0.15 * p90 + return output + + +def certificate_from_vertices( + *, + descriptor: AssetDescriptor, + semantics: GeometryFunctionalSemantics, + vertices: np.ndarray, +) -> FunctionalFrontCertificate: + scores = _back_support_scores(vertices) + ordered = sorted(scores, key=lambda axis: (-scores[axis], axis)) + back = ordered[0] + functional = opposite_axis(back) + score_margin = scores[back] - scores[ordered[1]] + opposite_margin = scores[back] - scores[functional] + if score_margin < 0.10 or opposite_margin < 0.18: + raise ValueError( + "functional front is geometrically ambiguous: " + f"asset={descriptor.asset_id} semantics={semantics} " + f"scores={{{', '.join(f'{axis}:{scores[axis]:.3f}' for axis in ordered)}}}" + ) + descriptor_is_certified = ( + descriptor.front_axis_source in _CERTIFIED_DESCRIPTOR_SOURCES + and descriptor.confidence.get("front_axis", 0.0) >= 0.9 + ) + if descriptor_is_certified and descriptor.front_axis != functional: + raise ValueError( + "multiview and geometry functional fronts disagree: " + f"asset={descriptor.asset_id} multiview={descriptor.front_axis} " + f"geometry={functional}" + ) + confidence = min( + 0.99, + 0.82 + 0.45 * score_margin + 0.18 * max(0.0, opposite_margin - 0.18), + ) + if descriptor_is_certified: + source = "multiview_geometry_consensus" + confidence = max(confidence, float(descriptor.confidence["front_axis"])) + elif semantics == "bed_foot": + source = "geometry_headboard_verified" + else: + source = "geometry_backrest_verified" + noun = "headboard" if semantics == "bed_foot" else "backrest" + return FunctionalFrontCertificate( + asset_id=descriptor.asset_id, + asset_sha256=descriptor.sha256, + semantics=semantics, + functional_front_axis=functional, + detected_back_axis=back, + source=source, # type: ignore[arg-type] + confidence=round(confidence, 6), + score_by_axis={axis: round(score, 6) for axis, score in scores.items()}, + score_margin=round(score_margin, 6), + opposite_side_margin=round(opposite_margin, 6), + evidence=[ + f"canonical mesh {noun} side={back}", + f"functional direction is opposite {noun}: {functional}", + f"dominance margin={score_margin:.6f}", + f"opposite-side margin={opposite_margin:.6f}", + "certificate is bound to the immutable asset SHA-256", + ], + ) + + +@lru_cache(maxsize=512) +def _cached_certificate( + descriptor_json: str, + semantics: GeometryFunctionalSemantics, +) -> FunctionalFrontCertificate: + descriptor = AssetDescriptor.model_validate_json(descriptor_json) + return certificate_from_vertices( + descriptor=descriptor, + semantics=semantics, + vertices=_canonical_vertices(descriptor), + ) + + +def certify_functional_front( + descriptor: AssetDescriptor, + semantics: FunctionalSemantics, +) -> FunctionalFrontCertificate: + if semantics in {"operation_side", "screen_normal"}: + axis = effective_functional_front_axis(descriptor) + if axis is None: + raise ValueError( + "direction-sensitive asset lacks an autonomous HIGH/VERIFIED front: " + f"asset={descriptor.asset_id} semantics={semantics} " + f"grade={descriptor.front_confidence_grade.value} " + f"review={descriptor.review_status.value}" + ) + evidence = [ + ( + f"{item.kind}:{item.target}:{item.axis}:" + f"{item.source_hash or descriptor.sha256}" + ) + for item in descriptor.front_evidence + if item.target in {"functional_front", "visual_front"} + ] + if not evidence: + raise ValueError("descriptor front certificate has no structured evidence") + certificate = FunctionalFrontCertificate( + asset_id=descriptor.asset_id, + asset_sha256=descriptor.sha256, + semantics=semantics, + functional_front_axis=axis, + detected_back_axis=opposite_axis(axis), + source="multiview_affordance_consensus", + confidence=descriptor.front_confidence, + score_by_axis={axis: descriptor.front_confidence}, + score_margin=descriptor.front_confidence, + opposite_side_margin=descriptor.front_confidence, + evidence=[ + *evidence, + "certificate is bound to the immutable asset SHA-256", + ], + ) + else: + certificate = _cached_certificate(descriptor.model_dump_json(), semantics) + source = Path(descriptor.canonical_path) + if not source.is_file(): + raise FileNotFoundError(source) + # AssetDescriptor identity is checked again in the compilation stage. This + # check prevents a caller from applying a cached certificate to another ID. + if certificate.asset_id != descriptor.asset_id or certificate.asset_sha256 != descriptor.sha256: + raise ValueError("functional-front certificate identity mismatch") + if not math.isfinite(certificate.confidence) or certificate.confidence < 0.85: + raise ValueError("functional-front certificate confidence below 0.85") + return certificate + + +def functional_front_cache_stats() -> dict[str, int]: + info = _cached_certificate.cache_info() + return { + "hits": info.hits, + "misses": info.misses, + "maxsize": int(info.maxsize or 0), + "currsize": info.currsize, + } + + +def semantics_for_category(category: str) -> FunctionalSemantics | None: + semantics = definition_for_category(category).functional_semantics + if semantics in {"seating_gaze", "bed_foot", "operation_side", "screen_normal"}: + return cast(FunctionalSemantics, semantics) + return None + + +def certificate_payload(certificate: FunctionalFrontCertificate) -> dict[str, Any]: + return certificate.model_dump(mode="json") diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/generation_profile.py b/docs/reproduction/public_conversion_code/packages/scene_generation/generation_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..38341196c66b86e4a985d88b95aa0804fd0dbb5d --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/generation_profile.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import re +from enum import StrEnum +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + + +class GenerationProfile(StrEnum): + DAG_AGENTS = "dag_agents" + EXACT_LAYOUT_FAST = "exact_layout_fast" + AGENT_OUTLINE_FAST = "agent_outline_fast" + + +class ExactLayoutEligibility(BaseModel): + model_config = ConfigDict(extra="forbid") + + profile: GenerationProfile + eligible: bool + room_dimensions_m: tuple[float, float, float] | None = None + floor_entity_ids: list[str] = Field(default_factory=list) + supported_entity_ids: list[str] = Field(default_factory=list) + skipped_agent_roles: list[str] = Field(default_factory=list) + failures: list[str] = Field(default_factory=list) + + +def resolve_generation_profile(scene_config: dict[str, Any]) -> GenerationProfile: + raw = str(scene_config.get("generation_profile") or GenerationProfile.DAG_AGENTS.value) + try: + return GenerationProfile(raw) + except ValueError as error: + raise ValueError( + "scene_config.generation_profile must be one of: " + + ", ".join(item.value for item in GenerationProfile) + ) from error + + +def _dimensions_from_config_or_prompt( + scene_config: dict[str, Any], natural_language: str +) -> tuple[float, float, float] | None: + configured = scene_config.get("room_dimensions_m") + if isinstance(configured, (list, tuple)) and len(configured) == 3: + try: + values = tuple(float(value) for value in configured) + except (TypeError, ValueError): + return None + if all(value > 0 for value in values): + return values # type: ignore[return-value] + match = re.search( + r"(\d+(?:\.\d+)?)\s*(?:m(?:etre)?s?)?\s*(?:by|x|×)\s*" + r"(\d+(?:\.\d+)?)\s*(?:m(?:etre)?s?)?\s*(?:by|x|×)\s*" + r"(\d+(?:\.\d+)?)\s*(?:m(?:etre)?s?)?", + natural_language, + flags=re.IGNORECASE, + ) + if match is None: + return None + return tuple(float(match.group(index)) for index in (1, 2, 3)) # type: ignore[return-value] + + +def evaluate_exact_layout( + task: dict[str, Any], scene_config: dict[str, Any] +) -> ExactLayoutEligibility: + """Validate the explicit, fail-closed contract for the zero-Agent upstream path.""" + + profile = resolve_generation_profile(scene_config) + if profile is GenerationProfile.DAG_AGENTS: + return ExactLayoutEligibility(profile=profile, eligible=False) + + failures: list[str] = [] + rooms = task.get("required_rooms") or [] + if not isinstance(rooms, list) or len(rooms) != 1: + failures.append("exact_layout_fast_requires_exactly_one_room") + # A declared room envelope is useful to every fast profile: exact-layout + # consumes it as a hard authoring contract, while agent-outline forwards it + # to the floor-plan agent and final visual preflight. Older outline requests + # remain valid when they omit it. + dimensions = _dimensions_from_config_or_prompt( + scene_config, str(task.get("natural_language") or "") + ) + if profile is GenerationProfile.EXACT_LAYOUT_FAST and dimensions is None: + failures.append("exact_layout_fast_requires_room_dimensions_m") + + entities = task.get("entities") or [] + if not isinstance(entities, list): + failures.append("task_entities_must_be_a_list") + entities = [] + support_placements = scene_config.get("task_support_placements") or {} + if not isinstance(support_placements, dict): + failures.append("task_support_placements_must_be_an_object") + support_placements = {} + + floor_ids: list[str] = [] + supported_ids: list[str] = [] + for entity in entities: + if not isinstance(entity, dict) or not entity.get("entity_id"): + failures.append("every_entity_requires_entity_id") + continue + entity_id = str(entity["entity_id"]) + role = str(entity.get("role") or "") + attributes = entity.get("attributes") or {} + if not isinstance(attributes, dict): + failures.append(f"{entity_id}:attributes_must_be_an_object") + continue + mount = str(attributes.get("mount") or "").upper() + if mount not in {"FLOOR", "SURFACE"}: + continue + asset_id = attributes.get("asset_id") + dimensions_m = attributes.get("dimensions_m") or attributes.get( + "target_dimensions_m" + ) + if not isinstance(asset_id, str) or not asset_id.strip(): + failures.append(f"{entity_id}:asset_id_required") + if not isinstance(dimensions_m, list) or len(dimensions_m) != 3: + failures.append(f"{entity_id}:dimensions_m_required") + if mount == "FLOOR": + floor_ids.append(entity_id) + pose = attributes.get("placement_center_m") + if not isinstance(pose, list) or len(pose) != 2: + failures.append(f"{entity_id}:placement_center_m_required") + if "yaw_deg" not in attributes: + failures.append(f"{entity_id}:yaw_deg_required") + else: + supported_ids.append(entity_id) + placement = support_placements.get(entity_id) + if not isinstance(placement, dict) or not placement.get("support_entity_id"): + failures.append(f"{entity_id}:task_support_placement_required") + if role == "MANIPULATED" and bool(attributes.get("kinematic_on_support")): + failures.append(f"{entity_id}:manipulated_entity_cannot_be_kinematic") + if not floor_ids: + failures.append("exact_layout_fast_requires_floor_entities") + + return ExactLayoutEligibility( + profile=profile, + eligible=not failures, + room_dimensions_m=dimensions, + floor_entity_ids=sorted(floor_ids), + supported_entity_ids=sorted(supported_ids), + skipped_agent_roles=( + [ + "planning", + "floor_plan", + "furniture", + "wall_mounted", + "ceiling_mounted", + ] + if profile is GenerationProfile.EXACT_LAYOUT_FAST + else ["planning", "furniture", "wall_mounted", "ceiling_mounted"] + ), + failures=failures, + ) + + +def require_exact_layout( + task: dict[str, Any], scene_config: dict[str, Any] +) -> ExactLayoutEligibility: + result = evaluate_exact_layout(task, scene_config) + if result.profile is not GenerationProfile.DAG_AGENTS and not result.eligible: + raise ValueError(f"{result.profile.value}_ineligible:" + ";".join(result.failures)) + return result + + +def is_fast_layout_profile(profile: GenerationProfile) -> bool: + return profile in { + GenerationProfile.EXACT_LAYOUT_FAST, + GenerationProfile.AGENT_OUTLINE_FAST, + } diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/geometry_task.py b/docs/reproduction/public_conversion_code/packages/scene_generation/geometry_task.py new file mode 100644 index 0000000000000000000000000000000000000000..5bfefc9231706b489759c5372b8a90818fb1e859 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/geometry_task.py @@ -0,0 +1,141 @@ +"""The production asset-selection/layout/task path, stopping before rendering/export. + +This entry point never invokes Blender, a collision loader, IK, or a simulator. +""" + +from __future__ import annotations + +import json +import threading +from pathlib import Path + +from packages.asset_registry.release import load_active_descriptors +from packages.scene_generation.asset_first import ( + FurnitureAssetChoice, + compile_asset_first_layout, + freeze_asset_selection, +) +from packages.scene_generation.pick_move_place import build_pick_move_place_task +from packages.scene_generation.robot_constraints import RobotConstraintError + +_LOCK = threading.Lock() # Existing scenario configurator uses module-level role settings. + + +def generate_geometry_task( + scenario: dict, + descriptor_index: Path, + output: Path, + robot_id: str | None = None, + enabled: bool = True, + max_attempts: int = 24, +) -> dict: + from scripts import run_asset_first_scenario as runner + from scripts import run_asset_first_studio as pipeline + + output.mkdir(parents=True, exist_ok=False) + (output / "scenario.json").write_text( + json.dumps(scenario, ensure_ascii=False, indent=2), encoding="utf-8" + ) + attempts = [] + crowded_fallback = None + + def save(spec, task): + payload = { + "output_dir": str(output.resolve()), + "task": task.model_dump(mode="json"), + "layout": spec.model_dump(mode="json"), + "robot_constraints": task.robot_constraints, + "attempts": attempts, + } + (output / "task.json").write_text(task.model_dump_json(indent=2), encoding="utf-8") + (output / "metric_layout.json").write_text(spec.model_dump_json(indent=2), encoding="utf-8") + (output / "result.json").write_text( + json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8" + ) + (output / "attempts.json").write_text( + json.dumps(attempts, ensure_ascii=False, indent=2), encoding="utf-8" + ) + return payload + + with _LOCK: + runner._configure( + scenario, + { + key: set() + for key in ("asset_ids", "asset_hashes", "geometry_signatures", "display_names") + }, + ) + descriptors = load_active_descriptors(descriptor_index.resolve()) + buckets = { + role: pipeline._role_candidates(descriptors, role) for role in pipeline.ROLE_CONFIG + } + from packages.scene_generation.robot_constraints import constrain_candidate_buckets + + buckets = constrain_candidate_buckets( + buckets, + {**pipeline.TASK_CONFIG, "robot_id": robot_id, "robot_constraints_enabled": enabled}, + ) + for attempt in range(max_attempts): + try: + selected = pipeline._select_assets( + descriptors, + attempt + pipeline.SELECTION_VARIANT_OFFSET, + candidate_buckets=buckets, + dimension_only=True, + ) + refs = pipeline._write_selected_descriptors( + selected, output / f"descriptors_{attempt:02d}" + ) + selection_path = output / f"selection_{attempt:02d}.json" + # Consume frozen descriptor fronts; do not run mesh-based front certification. + choices = [ + FurnitureAssetChoice( + **{ + key: value + for key, value in item.items() + if key in FurnitureAssetChoice.model_fields + }, + asset_id=selected[item["entity_id"]].asset_id, + ) + for item in scenario["placements"] + ] + freeze_asset_selection(descriptor_index.resolve(), choices, selection_path) + room = pipeline._room_request().model_copy( + update={ + "robot_id": robot_id, + "robot_constraints_enabled": enabled, + "task_object_entity_id": pipeline.TASK_CONFIG["movable_object_entity_id"], + } + ) + spec = compile_asset_first_layout(selection_path, room, descriptor_refs=refs) + task = build_pick_move_place_task( + spec, + {d.asset_id: d for d in selected.values()}, + { + **pipeline.TASK_CONFIG, + "robot_id": robot_id, + "robot_constraints_enabled": enabled, + "resampling_count": attempt, + }, + ) + attempts.append({"attempt": attempt, "passed": True}) + if "small_crowded_target" in task.robot_constraints.get("hard_reasons", []): + crowded_fallback = (spec, task) + attempts[-1]["deferred_crowded_target"] = True + continue + return save(spec, task) + except ValueError as error: + attempts.append({"attempt": attempt, "passed": False, "reason": str(error)}) + (output / "attempts.json").write_text( + json.dumps(attempts, ensure_ascii=False, indent=2), encoding="utf-8" + ) + if crowded_fallback is not None: + spec, task = crowded_fallback + task.robot_constraints["resampling_count"] += len(attempts) - 1 + return save(spec, task) + raise RobotConstraintError( + "candidate_budget_exhausted", + robot_id=robot_id or "default_all", + resampling_count=max_attempts, + attempts=attempts, + ) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/global_pose_repair.py b/docs/reproduction/public_conversion_code/packages/scene_generation/global_pose_repair.py new file mode 100644 index 0000000000000000000000000000000000000000..77161580959aca24f2f2d89376ae8f6ce20caafa --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/global_pose_repair.py @@ -0,0 +1,274 @@ +from __future__ import annotations + +import math +from typing import Any + +from pydantic import BaseModel, ConfigDict + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class PoseRepairUpdate(_StrictModel): + entity_id: str + original_translation_m: tuple[float, float, float] + translation_m: tuple[float, float, float] + original_rotation_wxyz: tuple[float, float, float, float] + rotation_wxyz: tuple[float, float, float, float] + inherited_from: str | None = None + + +def _finite_vector(value: Any, *, size: int, label: str) -> tuple[float, ...]: + if not isinstance(value, (list, tuple)) or len(value) != size: + raise ValueError(f"{label}:expected_{size}_vector") + result = tuple(float(item) for item in value) + if not all(math.isfinite(item) and abs(item) < 1.0e6 for item in result): + raise ValueError(f"{label}:non_finite") + return result + + +def _canonical_front_rotation(value: Any) -> tuple[float, float, float, float] | None: + """Convert an explicit canonical +X front cardinal directive to world yaw.""" + + text = str(value or "").casefold() + if "canonical" not in text or "front" not in text: + return None + directions = { + "east": 0.0, + "north": math.pi / 2.0, + "west": math.pi, + "south": -math.pi / 2.0, + } + matches = [direction for direction in directions if f"facing {direction}" in text] + if len(matches) != 1: + return None + yaw = directions[matches[0]] + return (math.cos(yaw / 2.0), 0.0, 0.0, math.sin(yaw / 2.0)) + + +def apply_global_pose_repair( + house_state: dict[str, Any], + bindings: dict[str, str], + proposal: dict[str, Any], + *, + parent_by_entity: dict[str, str | None], + max_translation_delta_m: float = 3.0, +) -> dict[str, PoseRepairUpdate]: + """Apply a critic's bounded pose-only patch to exact bound state records. + + Asset identity, scale, entity ownership, and robot spawn are intentionally + outside this interface. Descendants inherit a parent translation so a frozen + support subtree remains rigid during a global layout repair. + """ + + if not isinstance(proposal, dict): + raise ValueError("global_pose_repair:missing_operations") + operations = proposal.get("operations") + if not isinstance(operations, list) and isinstance(proposal.get("transforms"), list): + operations = proposal["transforms"] + if isinstance(operations, list): + normalized_operations = [] + for value in operations: + if not isinstance(value, dict): + normalized_operations.append(value) + continue + operation = dict(value) + if not operation.get("operation") and ( + operation.get("translation_m") is not None + or operation.get("translation") is not None + ): + operation["operation"] = "set_pose" + if operation.get("translation_m") is None: + operation["translation_m"] = operation.get("translation") + normalized_operations.append(operation) + operations = normalized_operations + else: + operations = [] + keyed_transforms = proposal.get("transforms") + target_transforms = proposal.get("target_transforms_world_m") + keyed_entities = proposal.get("entities") + candidates = ( + keyed_transforms + if isinstance(keyed_transforms, dict) + else target_transforms + if isinstance(target_transforms, dict) + else keyed_entities + if isinstance(keyed_entities, dict) + else proposal + ) + for entity_id, value in candidates.items(): + if entity_id in {"coordinate_frame", "frame", "validation_note"}: + continue + if not isinstance(value, dict): + continue + translation = ( + value.get("translation") + or value.get("translation_m") + or value.get("translation_approx") + ) + rotation = value.get("rotation_wxyz") or value.get( + "rotation_wxyz_if_native_forward_is_positive_x" + ) + orientation_directive = value.get("orientation_directive") or value.get("orientation") + if rotation is None: + rotation = _canonical_front_rotation(orientation_directive) + if translation is not None and (rotation is not None or orientation_directive): + operation = { + "entity_id": entity_id, + "operation": "set_pose", + "translation_m": translation, + } + if rotation is not None: + operation["rotation_wxyz"] = rotation + operations.append(operation) + if not operations: + raise ValueError("global_pose_repair:missing_operations") + frame_value = proposal.get("frame") or proposal.get("coordinate_frame") + if frame_value is None and operations: + frame_value = "SceneSmith world meters" + frame = str(frame_value or "").casefold() + if "scenesmith" not in frame or "meter" not in frame: + raise ValueError("global_pose_repair:unsupported_frame") + + records: dict[str, dict[str, Any]] = {} + object_to_entity = { + object_id: entity_id + for entity_id, object_id in bindings.items() + if isinstance(object_id, str) + and not object_id.startswith("external:") + and not object_id.startswith("native-local:") + } + rooms = house_state.get("rooms") or {} + room_values = rooms.values() if isinstance(rooms, dict) else [] + for room in room_values: + if not isinstance(room, dict): + continue + objects = room.get("objects") or {} + values = objects.values() if isinstance(objects, dict) else objects + for record in values if isinstance(values, (list, tuple, type({}.values()))) else []: + if not isinstance(record, dict): + continue + entity_id = object_to_entity.get(str(record.get("object_id") or "")) + if entity_id: + records[entity_id] = record + + explicit: dict[str, PoseRepairUpdate] = {} + for operation in operations: + if not isinstance(operation, dict): + raise ValueError("global_pose_repair:invalid_operation") + entity_id = str(operation.get("entity_id") or "") + if entity_id not in records or entity_id in explicit: + raise ValueError(f"global_pose_repair:invalid_entity:{entity_id}") + kind = str(operation.get("operation") or "") + if kind not in {"translate", "set_pose"}: + raise ValueError(f"global_pose_repair:unsupported_operation:{kind}") + transform = records[entity_id].get("transform") or {} + original_translation = _finite_vector( + transform.get("translation"), size=3, label=f"{entity_id}:translation" + ) + original_rotation = _finite_vector( + transform.get("rotation_wxyz", [1, 0, 0, 0]), + size=4, + label=f"{entity_id}:rotation", + ) + if kind == "translate": + delta = _finite_vector( + operation.get("delta_translation_m"), + size=3, + label=f"{entity_id}:delta", + ) + translation = tuple(original_translation[i] + delta[i] for i in range(3)) + if operation.get("resulting_translation_m") is not None: + claimed = _finite_vector( + operation["resulting_translation_m"], + size=3, + label=f"{entity_id}:result", + ) + if any(abs(claimed[i] - translation[i]) > 1.0e-4 for i in range(3)): + raise ValueError(f"global_pose_repair:inconsistent_result:{entity_id}") + rotation = original_rotation + else: + translation = _finite_vector( + operation.get("translation_m"), + size=3, + label=f"{entity_id}:translation", + ) + rotation = ( + _finite_vector( + operation.get("rotation_wxyz"), + size=4, + label=f"{entity_id}:rotation", + ) + if operation.get("rotation_wxyz") is not None + else original_rotation + ) + displacement = math.dist(original_translation, translation) + if displacement > max_translation_delta_m: + raise ValueError(f"global_pose_repair:translation_limit:{entity_id}:{displacement:.6f}") + norm = math.sqrt(sum(value * value for value in rotation)) + if abs(norm - 1.0) > 1.0e-3: + raise ValueError(f"global_pose_repair:non_unit_rotation:{entity_id}") + explicit[entity_id] = PoseRepairUpdate( + entity_id=entity_id, + original_translation_m=original_translation, # type: ignore[arg-type] + translation_m=translation, # type: ignore[arg-type] + original_rotation_wxyz=original_rotation, # type: ignore[arg-type] + rotation_wxyz=rotation, # type: ignore[arg-type] + ) + + updates = dict(explicit) + for parent_id, parent_update in list(explicit.items()): + delta = tuple( + parent_update.translation_m[index] - parent_update.original_translation_m[index] + for index in range(3) + ) + descendants = { + entity_id + for entity_id in records + if entity_id not in explicit and _has_ancestor(entity_id, parent_id, parent_by_entity) + } + for entity_id in sorted(descendants): + transform = records[entity_id].get("transform") or {} + original_translation = _finite_vector( + transform.get("translation"), size=3, label=f"{entity_id}:translation" + ) + original_rotation = _finite_vector( + transform.get("rotation_wxyz", [1, 0, 0, 0]), + size=4, + label=f"{entity_id}:rotation", + ) + updates[entity_id] = PoseRepairUpdate( + entity_id=entity_id, + original_translation_m=original_translation, # type: ignore[arg-type] + translation_m=tuple( + original_translation[index] + delta[index] for index in range(3) + ), + original_rotation_wxyz=original_rotation, # type: ignore[arg-type] + rotation_wxyz=original_rotation, # type: ignore[arg-type] + inherited_from=parent_id, + ) + + for entity_id, update in updates.items(): + transform = records[entity_id].setdefault("transform", {}) + transform["translation"] = list(update.translation_m) + transform["rotation_wxyz"] = list(update.rotation_wxyz) + metadata = records[entity_id].setdefault("metadata", {}) + if isinstance(metadata, dict): + metadata["robothousegen_transform_source"] = "global_critic_bounded_pose_repair" + return updates + + +def _has_ancestor( + entity_id: str, + ancestor_id: str, + parent_by_entity: dict[str, str | None], +) -> bool: + seen: set[str] = set() + current = parent_by_entity.get(entity_id) + while current is not None and current not in seen: + if current == ancestor_id: + return True + seen.add(current) + current = parent_by_entity.get(current) + return False diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/hierarchical_execution.py b/docs/reproduction/public_conversion_code/packages/scene_generation/hierarchical_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..57ff1ea7f26b2e81cecbc193084d30cf9cb4ee42 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/hierarchical_execution.py @@ -0,0 +1,336 @@ +from __future__ import annotations + +import math +import os +import threading +import time +from collections import defaultdict +from collections.abc import Callable +from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.scene_generation.dependency_graph import SceneDependencyGraph + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class RigidTransform(_StrictModel): + """Child pose expressed in its parent's stable local coordinate frame.""" + + translation_m: tuple[float, float, float] = (0.0, 0.0, 0.0) + rotation_xyzw: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0) + + @model_validator(mode="after") + def normalize_rotation(self) -> RigidTransform: + norm = math.sqrt(sum(value * value for value in self.rotation_xyzw)) + if norm <= 1.0e-12: + raise ValueError("rotation quaternion must be non-zero") + self.rotation_xyzw = tuple(value / norm for value in self.rotation_xyzw) + return self + + +class HierarchicalExecutionTask(_StrictModel): + task_id: str + kind: Literal["generate_node", "fit_local_relation", "freeze_subtree", "compose_world"] + node_id: str | None = None + parent_id: str | None = None + depends_on: list[str] = Field(default_factory=list) + resource_class: str + preserves_local_subtree: bool = False + + +class HierarchicalExecutionPlan(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + graph_id: str + coordinate_semantics: Literal["parent_local_recursive"] = "parent_local_recursive" + tasks: list[HierarchicalExecutionTask] + placement_parents: dict[str, str | None] + constraint_parents: dict[str, list[str]] + max_parallel_tasks: int = Field(default=0, ge=0) + + @model_validator(mode="after") + def validate_dependencies(self) -> HierarchicalExecutionPlan: + ids = [task.task_id for task in self.tasks] + if len(ids) != len(set(ids)): + raise ValueError("hierarchical execution task IDs must be unique") + missing = { + dependency + for task in self.tasks + for dependency in task.depends_on + if dependency not in set(ids) + } + if missing: + raise ValueError(f"hierarchical execution plan has missing tasks: {sorted(missing)}") + return self + + +class HierarchicalTaskRecord(_StrictModel): + task_id: str + status: Literal["pending", "running", "complete", "failed"] = "pending" + resource_class: str + started_unix: float | None = None + completed_unix: float | None = None + duration_s: float | None = None + worker: str | None = None + result: dict[str, Any] = Field(default_factory=dict) + error: str | None = None + + +class HierarchicalExecutionLedger(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + graph_id: str + started_unix: float + completed_unix: float | None = None + status: Literal["running", "complete", "failed"] = "running" + records: dict[str, HierarchicalTaskRecord] + + +TaskHandler = Callable[[HierarchicalExecutionTask], dict[str, Any] | None] + + +def execute_hierarchical_plan( + plan: HierarchicalExecutionPlan, + handlers: dict[str, TaskHandler], + *, + ledger_path: Path, + max_workers: int | None = None, +) -> HierarchicalExecutionLedger: + """Execute ready local-frame tasks concurrently and persist an audit ledger.""" + + worker_count = max_workers or plan.max_parallel_tasks or max(1, os.cpu_count() or 1) + records = { + task.task_id: HierarchicalTaskRecord( + task_id=task.task_id, + resource_class=task.resource_class, + ) + for task in plan.tasks + } + ledger = HierarchicalExecutionLedger( + graph_id=plan.graph_id, + started_unix=time.time(), + records=records, + ) + ledger_path.parent.mkdir(parents=True, exist_ok=True) + persist_lock = threading.Lock() + + def persist() -> None: + with persist_lock: + temporary = ledger_path.with_suffix(ledger_path.suffix + ".tmp") + temporary.write_text(ledger.model_dump_json(indent=2) + "\n", encoding="utf-8") + temporary.replace(ledger_path) + + def run(task: HierarchicalExecutionTask) -> dict[str, Any]: + record = records[task.task_id] + record.status = "running" + record.started_unix = time.time() + record.worker = threading.current_thread().name + persist() + handler = handlers.get(task.kind) + if handler is None: + raise KeyError(f"no handler registered for hierarchical task kind {task.kind}") + return handler(task) or {} + + by_id = {task.task_id: task for task in plan.tasks} + pending = set(by_id) + running: dict[Future[dict[str, Any]], str] = {} + failed = False + persist() + with ThreadPoolExecutor(max_workers=worker_count, thread_name_prefix="rhg-subtree") as pool: + while pending or running: + ready = sorted( + task_id + for task_id in pending + if all(records[item].status == "complete" for item in by_id[task_id].depends_on) + ) + for task_id in ready[: max(0, worker_count - len(running))]: + pending.remove(task_id) + running[pool.submit(run, by_id[task_id])] = task_id + if not running: + failed = True + break + done, _ = wait(running, return_when=FIRST_COMPLETED) + for future in done: + task_id = running.pop(future) + record = records[task_id] + record.completed_unix = time.time() + record.duration_s = round(record.completed_unix - (record.started_unix or 0.0), 6) + try: + record.result = future.result() + record.status = "complete" + except Exception as error: # noqa: BLE001 - persisted before propagation + record.status = "failed" + record.error = repr(error) + failed = True + persist() + if failed: + for future in running: + future.cancel() + break + ledger.completed_unix = time.time() + ledger.status = "failed" if failed else "complete" + persist() + if failed: + failures = {key: value.error for key, value in records.items() if value.status == "failed"} + raise RuntimeError(f"hierarchical execution failed: {failures}") + return ledger + + +def _placement_parent(node_id: str, dependencies: list[str], architecture: set[str]) -> str | None: + non_architecture = [item for item in dependencies if item not in architecture] + if non_architecture: + return non_architecture[0] + # Floor is the stable local frame for floor-mounted objects. Wall and ceiling + # dependencies remain simultaneous geometric constraints, not transform parents. + for preferred in ("floor", "walls", "ceiling", "room_shell"): + if preferred in dependencies: + return preferred + return dependencies[0] if dependencies else None + + +def build_hierarchical_execution_plan( + graph: SceneDependencyGraph, +) -> HierarchicalExecutionPlan: + """Compile a DAG into parallel node generation and parent-local fitting tasks. + + An edge fit depends only on canonical parent/child generation. It intentionally + does not depend on the parent's own placement, allowing ``bottle -> table`` and + ``table subtree -> room`` fitting to run concurrently. World poses are composed + only after every local subtree has been frozen. + """ + + architecture = {node.node_id for node in graph.nodes if node.kind == "architecture"} + placement_parents = { + node.node_id: _placement_parent(node.node_id, node.depends_on, architecture) + for node in graph.nodes + } + constraint_parents = { + node.node_id: [ + dependency + for dependency in node.depends_on + if dependency != placement_parents[node.node_id] + ] + for node in graph.nodes + } + children: dict[str, list[str]] = defaultdict(list) + for node_id, parent_id in placement_parents.items(): + if parent_id is not None: + children[parent_id].append(node_id) + + tasks: list[HierarchicalExecutionTask] = [] + for node in graph.nodes: + resource = graph.scheduler.resource_class_by_stage[node.stage] + tasks.append( + HierarchicalExecutionTask( + task_id=f"generate:{node.node_id}", + kind="generate_node", + node_id=node.node_id, + resource_class=resource, + ) + ) + for node in graph.nodes: + parent_id = placement_parents[node.node_id] + if parent_id is None: + continue + tasks.append( + HierarchicalExecutionTask( + task_id=f"fit-local:{node.node_id}", + kind="fit_local_relation", + node_id=node.node_id, + parent_id=parent_id, + depends_on=[f"generate:{parent_id}", f"generate:{node.node_id}"], + resource_class=graph.scheduler.resource_class_by_stage[node.stage], + preserves_local_subtree=True, + ) + ) + # Freezing is bottom-up. Once frozen, a parent-world adjustment transforms the + # whole owned subtree and cannot mutate any accepted child-local transform. + for node in reversed(graph.nodes): + dependencies = [] + if placement_parents[node.node_id] is not None: + dependencies.append(f"fit-local:{node.node_id}") + dependencies.extend(f"freeze:{child}" for child in children[node.node_id]) + tasks.append( + HierarchicalExecutionTask( + task_id=f"freeze:{node.node_id}", + kind="freeze_subtree", + node_id=node.node_id, + parent_id=placement_parents[node.node_id], + depends_on=dependencies or [f"generate:{node.node_id}"], + resource_class="cpu_postprocess", + preserves_local_subtree=True, + ) + ) + roots = [node_id for node_id, parent_id in placement_parents.items() if parent_id is None] + tasks.append( + HierarchicalExecutionTask( + task_id="compose:world", + kind="compose_world", + depends_on=[f"freeze:{node_id}" for node_id in roots], + resource_class="cpu_postprocess", + preserves_local_subtree=True, + ) + ) + return HierarchicalExecutionPlan( + graph_id=graph.graph_id, + tasks=tasks, + placement_parents=placement_parents, + constraint_parents=constraint_parents, + max_parallel_tasks=graph.scheduler.max_parallel_branches, + ) + + +def compose_transform(parent: RigidTransform, child_local: RigidTransform) -> RigidTransform: + px, py, pz, pw = parent.rotation_xyzw + cx, cy, cz, cw = child_local.rotation_xyzw + vx, vy, vz = child_local.translation_m + # Rotate the child-local translation by the parent quaternion. + tx = 2.0 * (py * vz - pz * vy) + ty = 2.0 * (pz * vx - px * vz) + tz = 2.0 * (px * vy - py * vx) + rx = vx + pw * tx + (py * tz - pz * ty) + ry = vy + pw * ty + (pz * tx - px * tz) + rz = vz + pw * tz + (px * ty - py * tx) + qx = pw * cx + px * cw + py * cz - pz * cy + qy = pw * cy - px * cz + py * cw + pz * cx + qz = pw * cz + px * cy - py * cx + pz * cw + qw = pw * cw - px * cx - py * cy - pz * cz + return RigidTransform( + translation_m=( + parent.translation_m[0] + rx, + parent.translation_m[1] + ry, + parent.translation_m[2] + rz, + ), + rotation_xyzw=(qx, qy, qz, qw), + ) + + +def compose_world_transforms( + placement_parents: dict[str, str | None], + local_transforms: dict[str, RigidTransform], +) -> dict[str, RigidTransform]: + """Resolve world transforms without changing any stored child-local transform.""" + + world: dict[str, RigidTransform] = {} + + def resolve(node_id: str, trail: set[str]) -> RigidTransform: + if node_id in world: + return world[node_id] + if node_id in trail: + raise ValueError(f"placement hierarchy contains a cycle at {node_id}") + local = local_transforms[node_id] + parent_id = placement_parents[node_id] + world[node_id] = ( + local + if parent_id is None + else compose_transform(resolve(parent_id, trail | {node_id}), local) + ) + return world[node_id] + + for node_id in placement_parents: + resolve(node_id, set()) + return world diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/local_optimization.py b/docs/reproduction/public_conversion_code/packages/scene_generation/local_optimization.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6bd86bf2ce99ad2a873df1f861043835ba989f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/local_optimization.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +import importlib.util +import json +import math +import os +import shlex +import shutil +import subprocess +from pathlib import Path +from typing import Any, Literal, Protocol + +from pydantic import BaseModel, ConfigDict, Field + +from packages.core.files import atomic_write_text +from packages.scene_generation.agent_orchestration import LocalOptimizerPolicy + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class AxisAlignedBounds(_StrictModel): + minimum_m: tuple[float, float, float] + maximum_m: tuple[float, float, float] + + def overlaps(self, other: AxisAlignedBounds, *, margin_m: float = 0.0) -> bool: + return all( + self.minimum_m[axis] - margin_m + <= other.maximum_m[axis] + margin_m + and other.minimum_m[axis] - margin_m + <= self.maximum_m[axis] + margin_m + for axis in range(3) + ) + + +class SupportMeasurement(_StrictModel): + child_id: str + support_id: str + gap_m: float + penetration_m: float = Field(ge=0) + contact_coverage: float = Field(ge=0, le=1) + center_of_mass_margin_m: float + stable_under_gravity: bool + + +class MaterialMeasurement(_StrictModel): + entity_id: str + channels: set[str] = Field(default_factory=set) + uv_scale_valid: bool = True + color_space_valid: bool = True + blank_material: bool = False + + +class ReachabilityCertificate(_StrictModel): + backend: Literal["curobo_v2", "analytic_drake"] + passed: bool + degraded: bool = False + collision_aware: bool + reachable_pose_count: int = Field(default=0, ge=0) + details: dict[str, Any] = Field(default_factory=dict) + + +class LocalDetailCertificate(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + subtree_id: str + broad_phase_candidates: list[tuple[str, str]] = Field(default_factory=list) + support_measurements: list[SupportMeasurement] = Field(default_factory=list) + material_measurements: list[MaterialMeasurement] = Field(default_factory=list) + reachability: ReachabilityCertificate | None = None + hard_gates_passed: bool + failures: list[str] = Field(default_factory=list) + metrics: dict[str, float | int | bool | str] = Field(default_factory=dict) + + +class CuroboReachabilityService(Protocol): + def available(self) -> bool: ... + + def evaluate( + self, + *, + robot_id: str, + target_poses: list[dict[str, Any]], + world: dict[str, Any], + ) -> ReachabilityCertificate: ... + + +class OptionalCuroboReachability: + """Optional cuRobo V2 boundary; it never reports a GPU pass when unavailable.""" + + def available(self) -> bool: + command = os.environ.get("RHG_CUROBO_SERVICE_COMMAND", "").strip() + if not command: + return False + executable = shlex.split(command)[0] + return bool( + importlib.util.find_spec("curobo") is not None + or Path(executable).is_file() + or shutil.which(executable) + ) + + def evaluate( + self, + *, + robot_id: str, + target_poses: list[dict[str, Any]], + world: dict[str, Any], + ) -> ReachabilityCertificate: + if not self.available(): + raise RuntimeError("configured cuRobo V2 service is unavailable") + command = shlex.split(os.environ["RHG_CUROBO_SERVICE_COMMAND"]) + completed = subprocess.run( + command, + input=json.dumps( + { + "schema_version": "1.0", + "robot_id": robot_id, + "target_poses": target_poses, + "world": world, + } + ), + text=True, + capture_output=True, + timeout=float(os.environ.get("RHG_CUROBO_SERVICE_TIMEOUT_S", "120")), + check=False, + ) + if completed.returncode: + raise RuntimeError( + f"cuRobo service failed ({completed.returncode}): " + f"{completed.stderr[-1000:]}" + ) + payload = json.loads(completed.stdout) + certificate = ReachabilityCertificate.model_validate(payload) + if certificate.backend != "curobo_v2" or certificate.degraded: + raise ValueError("cuRobo service returned a non-GPU or degraded certificate") + return certificate + + +def analytic_reachability( + *, + target_poses: list[dict[str, Any]], + maximum_reach_m: float = 1.1, +) -> ReachabilityCertificate: + reachable = 0 + for pose in target_poses: + position = pose.get("translation_m") or pose.get("position") + if not isinstance(position, (list, tuple)) or len(position) != 3: + continue + distance = math.sqrt(sum(float(value) ** 2 for value in position)) + if distance <= maximum_reach_m: + reachable += 1 + return ReachabilityCertificate( + backend="analytic_drake", + passed=reachable > 0, + degraded=True, + collision_aware=False, + reachable_pose_count=reachable, + details={"maximum_reach_m": maximum_reach_m}, + ) + + +def evaluate_local_details( + *, + subtree_id: str, + bounds: dict[str, AxisAlignedBounds], + support_measurements: list[SupportMeasurement], + material_measurements: list[MaterialMeasurement], + policy: LocalOptimizerPolicy, + robot_id: str | None = None, + target_poses: list[dict[str, Any]] | None = None, + world: dict[str, Any] | None = None, + curobo: CuroboReachabilityService | None = None, +) -> LocalDetailCertificate: + failures: list[str] = [] + broad_phase = [ + (left, right) + for index, left in enumerate(sorted(bounds)) + for right in sorted(bounds)[index + 1 :] + if bounds[left].overlaps(bounds[right]) + ] + for item in support_measurements: + if item.gap_m > policy.support_max_gap_m: + failures.append(f"{item.child_id}:support_gap") + if item.penetration_m > policy.support_max_penetration_m: + failures.append(f"{item.child_id}:penetration") + if item.contact_coverage < policy.support_minimum_coverage: + failures.append(f"{item.child_id}:contact_coverage") + if item.center_of_mass_margin_m < policy.center_of_mass_margin_m: + failures.append(f"{item.child_id}:center_of_mass") + if not item.stable_under_gravity: + failures.append(f"{item.child_id}:unstable") + required_channels = {value.casefold() for value in policy.required_pbr_channels} + for item in material_measurements: + channels = {value.casefold() for value in item.channels} + missing = required_channels - channels + if missing: + failures.append(f"{item.entity_id}:missing_pbr:{','.join(sorted(missing))}") + if not item.uv_scale_valid: + failures.append(f"{item.entity_id}:uv_scale") + if not item.color_space_valid: + failures.append(f"{item.entity_id}:color_space") + if item.blank_material: + failures.append(f"{item.entity_id}:blank_material") + reachability = None + if target_poses is not None: + service = curobo or OptionalCuroboReachability() + if policy.curobo.mode != "disabled" and service.available(): + reachability = service.evaluate( + robot_id=robot_id or "unknown", + target_poses=target_poses, + world=world or {}, + ) + elif policy.curobo.mode == "required" or policy.curobo.fallback == "fail": + failures.append("reachability:curobo_unavailable") + else: + reachability = analytic_reachability(target_poses=target_poses) + if reachability is not None and not reachability.passed: + failures.append("reachability:no_valid_pose") + failures = sorted(set(failures)) + return LocalDetailCertificate( + subtree_id=subtree_id, + broad_phase_candidates=broad_phase, + support_measurements=support_measurements, + material_measurements=material_measurements, + reachability=reachability, + hard_gates_passed=not failures, + failures=failures, + metrics={ + "broad_phase_candidate_count": len(broad_phase), + "support_count": len(support_measurements), + "material_count": len(material_measurements), + "curobo_degraded": bool(reachability and reachability.degraded), + }, + ) + + +def write_local_detail_certificate( + path: Path, + certificate: LocalDetailCertificate, +) -> None: + atomic_write_text(path, certificate.model_dump_json(indent=2) + "\n") + + +def load_measurements(path: Path) -> dict[str, Any]: + payload = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(payload, dict): + raise ValueError(f"local measurement payload must be an object: {path}") + return payload diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/manipulation_physics.py b/docs/reproduction/public_conversion_code/packages/scene_generation/manipulation_physics.py new file mode 100644 index 0000000000000000000000000000000000000000..607225e773659cfdd40a67bf98f3c6902cc10e8f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/manipulation_physics.py @@ -0,0 +1,274 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from packages.core.files import atomic_write_text + + +def author_manipulation_physics( + root_usd: Path, + task_manifest: Path, + scene_manifest: Path, + report_path: Path, +) -> dict[str, Any]: + """Author rigid-body and collision APIs for every manipulated task entity.""" + + try: + from pxr import ( # type: ignore[import-not-found] + Gf, + Sdf, + Usd, + UsdGeom, + UsdPhysics, + UsdShade, + ) + except ImportError as error: + raise RuntimeError("pxr is required to author manipulation physics") from error + + root_usd = root_usd.resolve() + task = json.loads(task_manifest.read_text(encoding="utf-8")) + scene = json.loads(scene_manifest.read_text(encoding="utf-8")) + manipulated = [ + entity + for entity in task.get("entities", []) + if isinstance(entity, dict) and entity.get("role") == "MANIPULATED" + ] + if not manipulated: + report = {"schema_version": "1.0", "passed": True, "entities": {}} + atomic_write_text(report_path, json.dumps(report, indent=2, sort_keys=True) + "\n") + return report + + stage = Usd.Stage.Open(str(root_usd)) + if stage is None: + raise RuntimeError(f"could not open composed stage: {root_usd}") + physics_layer = root_usd.parent / "layers" / "physics_overrides.usda" + layer = next( + ( + item + for item in stage.GetLayerStack() + if item.realPath and Path(item.realPath).resolve() == physics_layer.resolve() + ), + None, + ) + if layer is None: + raise RuntimeError(f"physics override layer is not in the stage stack: {physics_layer}") + stage.SetEditTarget(layer) + bindings = scene.get("entity_prim_paths") or {} + materials: dict[str, Any] = {} + + def appearance_material(entity: dict[str, Any]) -> Any | None: + entity_id = str(entity["entity_id"]) + appearance = (entity.get("attributes") or {}).get("appearance") or {} + if not appearance: + return None + if entity_id in materials: + return materials[entity_id] + color = appearance.get("base_color_rgb", [0.5, 0.5, 0.5]) + if not isinstance(color, list) or len(color) != 3: + raise ValueError(f"invalid base_color_rgb for {entity_id}: {color}") + looks = UsdGeom.Scope.Define(stage, "/World/RoboHouseGenLooks") + material = UsdShade.Material.Define(stage, looks.GetPath().AppendChild(entity_id)) + shader = UsdShade.Shader.Define( + stage, material.GetPath().AppendChild("PreviewSurface") + ) + shader.CreateIdAttr("UsdPreviewSurface") + shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set( + Gf.Vec3f(*(float(value) for value in color)) + ) + shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set( + float(appearance.get("roughness", 0.25)) + ) + shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set( + float(appearance.get("metallic", 0.0)) + ) + shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set( + float(appearance.get("opacity", 1.0)) + ) + material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") + materials[entity_id] = material + return material + + results: dict[str, Any] = {} + manipulated_ids = {str(entity["entity_id"]) for entity in manipulated} + support_pairs = { + (str(predicate.get("subject")), str(predicate.get("object"))) + for section in ("initial_predicates", "goal_predicates") + for predicate in task.get(section, []) + if isinstance(predicate, dict) + and predicate.get("name") == "supported_by" + and str(predicate.get("subject")) in manipulated_ids + and isinstance(predicate.get("object"), str) + and predicate.get("object") in bindings + } + support_ids = { + str(dependency) + for entity in manipulated + for dependency in (entity.get("attributes") or {}).get("depends_on", []) + if isinstance(dependency, str) and dependency in bindings + } | {support_id for _, support_id in support_pairs} + support_collisions: dict[str, list[str]] = {} + for support_id in sorted(support_ids): + support_path = bindings[support_id] + support_prim = stage.GetPrimAtPath(support_path) + if not support_prim: + raise RuntimeError( + f"manipulation support prim is missing: {support_id} -> {support_path}" + ) + collision_paths: list[str] = [] + for descendant in Usd.PrimRange(support_prim): + if descendant.IsInstanceProxy() or not descendant.IsA(UsdGeom.Gprim): + continue + collision = UsdPhysics.CollisionAPI.Apply(descendant) + collision.CreateCollisionEnabledAttr(True) + if descendant.IsA(UsdGeom.Mesh): + mesh_collision = UsdPhysics.MeshCollisionAPI.Apply(descendant) + # Static support meshes may be concave (for example a curved bar). + # Isaac/PhysX supports triangle-mesh collision for static bodies and + # it preserves the visible support surface much better than wrapping + # the whole piece in a convex hull. + mesh_collision.CreateApproximationAttr("none") + collision_paths.append(str(descendant.GetPath())) + if not collision_paths: + raise RuntimeError(f"manipulation support has no collision geometry: {support_id}") + support_collisions[support_id] = collision_paths + + # A generated support can have a visually correct top whose coarse source mesh is + # locally lower than its world AABB (curved counters are a common example). Add a + # small invisible static contact patch exactly below each initial manipulated object. + # This preserves the visible placement while giving PhysX a deterministic local + # support surface; target supports still receive their full static collision mesh. + bbox_cache = UsdGeom.BBoxCache( + Usd.TimeCode.Default(), + [UsdGeom.Tokens.default_, UsdGeom.Tokens.render, UsdGeom.Tokens.proxy], + ) + support_contacts: dict[str, str] = {} + initial_pairs = { + (str(predicate.get("subject")), str(predicate.get("object"))) + for predicate in task.get("initial_predicates", []) + if isinstance(predicate, dict) + and predicate.get("name") == "supported_by" + and str(predicate.get("subject")) in manipulated_ids + and isinstance(predicate.get("object"), str) + and predicate.get("object") in bindings + } + contacts_scope = UsdGeom.Scope.Define(stage, "/World/RoboHouseGenPhysics/SupportContacts") + for object_id, support_id in sorted(initial_pairs): + object_prim = stage.GetPrimAtPath(bindings[object_id]) + support_prim = stage.GetPrimAtPath(bindings[support_id]) + object_box = bbox_cache.ComputeWorldBound(object_prim).ComputeAlignedBox() + support_box = bbox_cache.ComputeWorldBound(support_prim).ComputeAlignedBox() + object_min, object_max = object_box.GetMin(), object_box.GetMax() + support_max = support_box.GetMax() + size_x = min(0.30, max(0.12, float(object_max[0] - object_min[0]) + 0.08)) + size_y = min(0.30, max(0.12, float(object_max[1] - object_min[1]) + 0.08)) + thickness = 0.02 + contact_name = f"{object_id}_on_{support_id}" + cube = UsdGeom.Cube.Define(stage, contacts_scope.GetPath().AppendChild(contact_name)) + cube.CreateSizeAttr(1.0) + UsdGeom.XformCommonAPI(cube).SetTranslate( + Gf.Vec3d( + float((object_min[0] + object_max[0]) / 2), + float((object_min[1] + object_max[1]) / 2), + float(support_max[2]) - thickness / 2, + ) + ) + UsdGeom.XformCommonAPI(cube).SetScale(Gf.Vec3f(size_x, size_y, thickness)) + cube.CreateVisibilityAttr(UsdGeom.Tokens.invisible) + UsdPhysics.CollisionAPI.Apply(cube.GetPrim()).CreateCollisionEnabledAttr(True) + support_contacts[object_id] = str(cube.GetPath()) + for entity in manipulated: + entity_id = str(entity["entity_id"]) + prim_path = bindings.get(entity_id) + if not isinstance(prim_path, str): + raise RuntimeError(f"manipulated entity has no prim binding: {entity_id}") + prim = stage.GetPrimAtPath(prim_path) + if not prim: + raise RuntimeError(f"manipulated entity prim is missing: {entity_id} -> {prim_path}") + attributes = entity.get("attributes") or {} + if bool(attributes.get("kinematic_on_support")): + raise ValueError( + f"manipulated entity cannot be kinematic_on_support: {entity_id}" + ) + rigid = UsdPhysics.RigidBodyAPI.Apply(prim) + rigid.CreateRigidBodyEnabledAttr(True) + rigid.CreateKinematicEnabledAttr(False) + mass_kg = float((entity.get("attributes") or {}).get("mass_kg", 0.5)) + UsdPhysics.MassAPI.Apply(prim).CreateMassAttr(mass_kg) + material = appearance_material(entity) + collision_paths: list[str] = [] + for descendant in Usd.PrimRange(prim): + if descendant == prim or descendant.IsInstanceProxy(): + continue + if not descendant.IsA(UsdGeom.Gprim): + continue + collision = UsdPhysics.CollisionAPI.Apply(descendant) + collision.CreateCollisionEnabledAttr(True) + if descendant.IsA(UsdGeom.Mesh): + mesh_collision = UsdPhysics.MeshCollisionAPI.Apply(descendant) + mesh_collision.CreateApproximationAttr("convexHull") + if material is not None: + UsdShade.MaterialBindingAPI.Apply(descendant).Bind( + material, + bindingStrength=UsdShade.Tokens.strongerThanDescendants, + ) + collision_paths.append(str(descendant.GetPath())) + if not collision_paths: + raise RuntimeError(f"manipulated entity has no collision geometry: {entity_id}") + results[entity_id] = { + "prim_path": prim_path, + "mass_kg": mass_kg, + "rigid_body_api": True, + "kinematic": False, + "collision_prim_paths": collision_paths, + "appearance_material": str(material.GetPath()) if material is not None else None, + } + + # Context and target finishes are also task configuration. Binding them here keeps + # the generated Python reusable while YAML controls domain randomization and style. + for entity in task.get("entities", []): + if not isinstance(entity, dict) or entity.get("entity_id") not in bindings: + continue + attributes = entity.get("attributes") or {} + configured_scale = attributes.get("scale_xyz") + if configured_scale is not None: + if not isinstance(configured_scale, list) or len(configured_scale) != 3: + raise ValueError( + f"invalid scale_xyz for {entity['entity_id']}: {configured_scale}" + ) + prim = stage.GetPrimAtPath(bindings[str(entity["entity_id"])]) + xformable = UsdGeom.Xformable(prim) + scale_op = next( + ( + op + for op in xformable.GetOrderedXformOps() + if op.GetOpName() == "xformOp:scale:rhgConfig" + ), + None, + ) + if scale_op is None: + scale_op = xformable.AddScaleOp(opSuffix="rhgConfig") + scale_op.Set(Gf.Vec3f(*(float(value) for value in configured_scale))) + material = appearance_material(entity) + if material is None: + continue + prim = stage.GetPrimAtPath(bindings[str(entity["entity_id"])]) + for descendant in Usd.PrimRange(prim): + if descendant.IsInstanceProxy() or not descendant.IsA(UsdGeom.Gprim): + continue + UsdShade.MaterialBindingAPI.Apply(descendant).Bind( + material, + bindingStrength=UsdShade.Tokens.strongerThanDescendants, + ) + layer.Save() + report = { + "schema_version": "1.0", + "passed": True, + "physics_layer": physics_layer.relative_to(root_usd.parent).as_posix(), + "entities": results, + "support_collisions": support_collisions, + "support_contacts": support_contacts, + } + atomic_write_text(report_path, json.dumps(report, indent=2, sort_keys=True) + "\n") + return report diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/metric_layout.py b/docs/reproduction/public_conversion_code/packages/scene_generation/metric_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..ad1e1e8bed28602d3d3cfc320247ebaba8211292 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/metric_layout.py @@ -0,0 +1,1655 @@ +from __future__ import annotations + +import hashlib +import heapq +import json +import math +import random +from pathlib import Path +from typing import Any, Literal, Protocol, cast + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from shapely import affinity # type: ignore[import-untyped] +from shapely.geometry import LineString, Point, Polygon, box # type: ignore[import-untyped] +from shapely.ops import unary_union # type: ignore[import-untyped] + +from packages.asset_registry.front_certification import definition_for_category +from packages.core.files import atomic_write_text + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +Point2 = tuple[float, float] + + +def _validate_unit_point(value: Point2, *, label: str) -> Point2: + if len(value) != 2 or not all(math.isfinite(float(item)) for item in value): + raise ValueError(f"{label} must contain two finite coordinates") + if not all(0.0 <= float(item) <= 1.0 for item in value): + raise ValueError(f"{label} must be normalized to [0, 1]") + return float(value[0]), float(value[1]) + + +def _polygon(value: list[Point2], *, label: str) -> Polygon: + if len(value) < 3: + raise ValueError(f"{label} requires at least three points") + polygon = Polygon(value) + if polygon.is_empty or not polygon.is_valid or polygon.area <= 1.0e-9: + raise ValueError(f"{label} is not a valid non-empty polygon") + return polygon + + +class BlueprintMetricZoneHint(_StrictModel): + zone_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + polygon_uv: list[Point2] = Field(min_length=3) + + @field_validator("polygon_uv") + @classmethod + def validate_polygon(cls, value: list[Point2]) -> list[Point2]: + points = [_validate_unit_point(point, label="zone polygon point") for point in value] + _polygon(points, label="zone polygon") + return points + + +class BlueprintMetricEntityHint(_StrictModel): + entity_id: str = Field(min_length=1) + center_uv: Point2 + yaw_deg: float + zone_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + + @field_validator("center_uv") + @classmethod + def validate_center(cls, value: Point2) -> Point2: + return _validate_unit_point(value, label="entity center_uv") + + @field_validator("yaw_deg") + @classmethod + def normalize_yaw(cls, value: float) -> float: + if not math.isfinite(value): + raise ValueError("yaw_deg must be finite") + return ((float(value) + 180.0) % 360.0) - 180.0 + + +class BlueprintOpeningHint(_StrictModel): + opening_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + kind: Literal["door", "window"] + keep_out_polygon_uv: list[Point2] = Field(min_length=3) + + @model_validator(mode="before") + @classmethod + def normalize_inward_keep_out_alias(cls, value: Any) -> Any: + if not isinstance(value, dict): + return value + if "keep_out_polygon_uv" not in value and "inward_keep_out_polygon_uv" in value: + normalized = dict(value) + normalized["keep_out_polygon_uv"] = normalized.pop("inward_keep_out_polygon_uv") + return normalized + return value + + @field_validator("keep_out_polygon_uv") + @classmethod + def validate_polygon(cls, value: list[Point2]) -> list[Point2]: + points = [_validate_unit_point(point, label="opening keep-out point") for point in value] + _polygon(points, label="opening keep-out polygon") + return points + + +class BlueprintMetricHints(_StrictModel): + """Scale-free geometry read from the frozen top-down blueprint.""" + + schema_version: Literal["1.0"] = "1.0" + room_outline_uv: list[Point2] = Field( + default_factory=lambda: [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)], + min_length=3, + ) + zones: list[BlueprintMetricZoneHint] = Field(min_length=1) + entities: list[BlueprintMetricEntityHint] = Field(min_length=1) + openings: list[BlueprintOpeningHint] = Field(default_factory=list) + route_centerline_uv: list[Point2] = Field(min_length=2) + robot_start_uv: Point2 + + @field_validator("room_outline_uv", "route_centerline_uv") + @classmethod + def validate_normalized_points(cls, value: list[Point2]) -> list[Point2]: + return [_validate_unit_point(point, label="blueprint point") for point in value] + + @field_validator("robot_start_uv") + @classmethod + def validate_robot_start(cls, value: Point2) -> Point2: + return _validate_unit_point(value, label="robot_start_uv") + + @model_validator(mode="after") + def validate_references(self) -> BlueprintMetricHints: + _polygon(self.room_outline_uv, label="room outline") + zone_ids = [zone.zone_id for zone in self.zones] + if len(zone_ids) != len(set(zone_ids)): + raise ValueError("blueprint metric zone IDs must be unique") + entity_ids = [entity.entity_id for entity in self.entities] + if len(entity_ids) != len(set(entity_ids)): + raise ValueError("blueprint metric entity IDs must be unique") + unknown_zones = {entity.zone_id for entity in self.entities} - set(zone_ids) + if unknown_zones: + raise ValueError(f"metric entities reference unknown zones: {sorted(unknown_zones)}") + opening_ids = [opening.opening_id for opening in self.openings] + if len(opening_ids) != len(set(opening_ids)): + raise ValueError("blueprint opening IDs must be unique") + return self + + +class MetricZone(_StrictModel): + zone_id: str + # Multi-room Metric V3 requires this field. It stays optional so V1/V2 + # single-room manifests remain byte-compatible and continue to validate. + room_id: str | None = None + polygon_xy_m: list[Point2] = Field(min_length=3) + + @model_validator(mode="after") + def validate_polygon(self) -> MetricZone: + _polygon(self.polygon_xy_m, label=f"metric zone {self.zone_id}") + return self + + +class MetricEntityLayout(_StrictModel): + entity_id: str + # Explicit room ownership is mandatory in MultiRoomMetricLayoutSpec and + # optional for historical single-room MetricLayoutSpec records. + room_id: str | None = None + center_xy_m: Point2 + yaw_deg: float + footprint_m: Point2 + zone_id: str + zone_polygon_xy_m: list[Point2] = Field(min_length=3) + parent_entity_id: str | None = None + mount: str = "FLOOR" + # Bottom-surface elevation is part of Metric V2 geometry truth. Historical + # floor assets remain at zero, while objects inside/on furniture can no + # longer be silently flattened onto the room floor during USD composition. + base_elevation_m: float = Field(default=0.0, ge=0.0) + allow_natural_perturbation: bool = True + # Asset-first v2 fields. They remain optional only so historical 1.0 + # contracts can still be read; MetricLayoutSpec enforces every field for a + # 2.0 layout before it can enter scene composition. + asset_id: str | None = None + asset_sha256: str | None = None + asset_descriptor_ref: str | None = None + asset_locked: bool = False + canonical_uniform_scale: float = Field(default=1.0, gt=0) + dimensions_m: tuple[float, float, float] | None = None + category: str | None = None + display_name: str | None = None + support_type: Literal["floor", "wall", "ceiling", "surface"] | None = None + quality_overall: int | None = Field(default=None, ge=0, le=100) + asset_status: Literal["ACTIVE"] | None = None + visual_footprint_local_m: list[Point2] = Field(default_factory=list) + collision_footprint_local_m: list[Point2] = Field(default_factory=list) + support_footprint_local_m: list[Point2] = Field(default_factory=list) + visual_footprint_xy_m: list[Point2] = Field(default_factory=list) + collision_footprint_xy_m: list[Point2] = Field(default_factory=list) + support_footprint_xy_m: list[Point2] = Field(default_factory=list) + layout_reserve_envelope_xy_m: list[Point2] = Field(default_factory=list) + operational_clearance_polygon_xy_m: list[Point2] = Field(default_factory=list) + rotated_obb_m: dict[str, Any] = Field(default_factory=dict) + canonical_front_axis: Literal["+X", "-X", "+Y", "-Y"] | None = None + world_front_vector_xy: Point2 | None = None + facing_target_entity_id: str | None = None + near_entity_id: str | None = None + near_distance_m: tuple[float, float] | None = None + relative_to_anchor: ( + Literal[ + "north", + "south", + "east", + "west", + "north_east", + "north_west", + "south_east", + "south_west", + ] + | None + ) = None + functional_front_semantics: ( + Literal["seating_gaze", "bed_foot", "operation_side", "screen_normal"] | None + ) = None + functional_front_source: ( + Literal[ + "geometry_backrest_verified", + "geometry_headboard_verified", + "multiview_geometry_consensus", + "multiview_affordance_consensus", + ] + | None + ) = None + functional_front_confidence: float | None = Field(default=None, ge=0.0, le=1.0) + functional_front_evidence: list[str] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_geometry(self) -> MetricEntityLayout: + if not all(math.isfinite(value) for value in self.center_xy_m): + raise ValueError("metric entity center must be finite") + if not math.isfinite(self.yaw_deg): + raise ValueError("metric entity yaw must be finite") + if not math.isfinite(self.base_elevation_m): + raise ValueError("metric entity base elevation must be finite") + if not all(math.isfinite(value) and value > 0 for value in self.footprint_m): + raise ValueError("metric entity footprint must be finite and positive") + _polygon(self.zone_polygon_xy_m, label=f"metric entity zone {self.entity_id}") + if self.dimensions_m is not None and any( + not math.isfinite(value) or value <= 0 for value in self.dimensions_m + ): + raise ValueError("metric entity dimensions must be finite and positive") + if self.world_front_vector_xy is not None: + if not all(math.isfinite(value) for value in self.world_front_vector_xy): + raise ValueError("world front vector must be finite") + length = math.hypot(*self.world_front_vector_xy) + if abs(length - 1.0) > 1.0e-6: + raise ValueError("world front vector must be unit length") + if (self.near_distance_m or self.relative_to_anchor) and not self.near_entity_id: + raise ValueError("metric relation constraints require near_entity_id") + if self.near_distance_m and ( + self.near_distance_m[0] < 0 + or self.near_distance_m[1] <= 0 + or self.near_distance_m[1] < self.near_distance_m[0] + ): + raise ValueError("metric near-distance range is invalid") + functional_values = ( + self.functional_front_semantics, + self.functional_front_source, + self.functional_front_confidence, + ) + if any(value is not None for value in functional_values): + if not all(value is not None for value in functional_values): + raise ValueError("functional-front certificate fields must be complete") + if self.canonical_front_axis is None or self.world_front_vector_xy is None: + raise ValueError("functional-front certificate requires a canonical axis") + if (self.functional_front_confidence or 0.0) < 0.85: + raise ValueError("functional-front confidence must be at least 0.85") + if not self.functional_front_evidence: + raise ValueError("functional-front certificate requires evidence") + for label, polygon in ( + ("visual local footprint", self.visual_footprint_local_m), + ("collision local footprint", self.collision_footprint_local_m), + ("support local footprint", self.support_footprint_local_m), + ("visual world footprint", self.visual_footprint_xy_m), + ("collision world footprint", self.collision_footprint_xy_m), + ("support world footprint", self.support_footprint_xy_m), + ("layout reserve envelope", self.layout_reserve_envelope_xy_m), + ("operational clearance", self.operational_clearance_polygon_xy_m), + ): + if polygon: + _polygon(polygon, label=f"{self.entity_id} {label}") + return self + + +class MetricKeepOutRegion(_StrictModel): + region_id: str + kind: Literal["door", "window"] + polygon_xy_m: list[Point2] = Field(min_length=3) + + @model_validator(mode="after") + def validate_polygon(self) -> MetricKeepOutRegion: + _polygon(self.polygon_xy_m, label=f"metric keep-out {self.region_id}") + return self + + +class AlongWallSequenceConstraint(_StrictModel): + constraint_id: str + entity_ids: list[str] = Field(min_length=2) + wall: Literal["north", "south", "east", "west"] + order: Literal["increasing", "decreasing"] = "increasing" + maximum_gap_m: float = Field(default=0.45, ge=0) + maximum_wall_offset_m: float = Field(default=0.20, ge=0) + + +class RadialSeatingConstraint(_StrictModel): + constraint_id: str + table_id: str + chair_ids: list[str] = Field(min_length=1) + minimum_radius_m: float = Field(gt=0) + maximum_radius_m: float = Field(gt=0) + maximum_facing_error_deg: float = Field(default=25.0, ge=0, le=180) + pull_out_clearance_m: float = Field(default=0.65, ge=0) + forward_axis_local: Literal["+x", "+y", "-x", "-y"] = "+y" + + @model_validator(mode="after") + def validate_radius(self) -> RadialSeatingConstraint: + if self.maximum_radius_m < self.minimum_radius_m: + raise ValueError("maximum seating radius must be >= minimum seating radius") + return self + + +class NaturalPerturbationPolicy(_StrictModel): + enabled: bool = False + seed: int = 0 + translation_std_m: float = Field(default=0.025, ge=0) + translation_max_m: float = Field(default=0.06, ge=0) + yaw_std_deg: float = Field(default=1.5, ge=0) + yaw_max_deg: float = Field(default=4.0, ge=0) + maximum_attempts: int = Field(default=24, ge=1, le=512) + + +class MetricLayoutSpec(_StrictModel): + schema_version: Literal["1.0", "2.0"] = "1.0" + coordinate_system: Literal["room_center_xy_metres_x_east_y_north"] = ( + "room_center_xy_metres_x_east_y_north" + ) + source_blueprint: str + source_blueprint_sha256: str + source_hints_sha256: str + room_dimensions_m: tuple[float, float, float] + room_polygon_mode: Literal["blueprint_outline", "dimensions_box"] = "blueprint_outline" + room_polygon_xy_m: list[Point2] = Field(min_length=3) + zones: list[MetricZone] = Field(min_length=1) + entities: list[MetricEntityLayout] = Field(min_length=1) + keep_out_regions: list[MetricKeepOutRegion] = Field(default_factory=list) + route_width_m: float = Field(default=1.2, ge=1.2) + route_polygon_xy_m: list[Point2] = Field(min_length=3) + robot_start_xy_m: Point2 + along_wall_sequences: list[AlongWallSequenceConstraint] = Field(default_factory=list) + radial_seating: list[RadialSeatingConstraint] = Field(default_factory=list) + footprint_tolerance_m: float = Field(default=0.12, ge=0, le=0.5) + footprint_validation_mode: Literal["target", "maximum_envelope"] = "target" + require_oriented_footprint_checks: Literal[True] = True + require_no_furniture_overlap: Literal[True] = True + require_route_clearance: Literal[True] = True + natural_perturbation: NaturalPerturbationPolicy = Field( + default_factory=NaturalPerturbationPolicy + ) + asset_descriptor_index: str | None = None + asset_selection_path: str | None = None + asset_selection_sha256: str | None = None + layout_truth_sha256: str | None = None + room_shell_source: Literal["metric_layout_spec"] | None = None + furniture_agent_pose_authority: Literal["none"] | None = None + coordinate_solver: str | None = None + asset_reselection_count: int = Field(default=0, ge=0) + + @model_validator(mode="after") + def validate_references(self) -> MetricLayoutSpec: + if any(value <= 0 or not math.isfinite(value) for value in self.room_dimensions_m): + raise ValueError("room_dimensions_m must be finite and positive") + room = _polygon(self.room_polygon_xy_m, label="metric room polygon") + route = _polygon(self.route_polygon_xy_m, label="metric route polygon") + if not room.buffer(1.0e-6).covers(route): + raise ValueError("metric route polygon must remain inside the room") + if not route.buffer(1.0e-6).covers(Point(self.robot_start_xy_m)): + raise ValueError("metric robot start must lie on the route polygon") + zone_ids = [zone.zone_id for zone in self.zones] + if len(zone_ids) != len(set(zone_ids)): + raise ValueError("metric zone IDs must be unique") + zone_by_id = {zone.zone_id: zone for zone in self.zones} + entity_ids = [entity.entity_id for entity in self.entities] + if len(entity_ids) != len(set(entity_ids)): + raise ValueError("metric entity IDs must be unique") + known = set(entity_ids) + if unknown := {entity.zone_id for entity in self.entities} - set(zone_by_id): + raise ValueError(f"metric entities reference unknown zones: {sorted(unknown)}") + for entity in self.entities: + declared_zone = Polygon(zone_by_id[entity.zone_id].polygon_xy_m) + entity_zone = Polygon(entity.zone_polygon_xy_m) + if not declared_zone.equals_exact(entity_zone, tolerance=1.0e-8): + raise ValueError(f"{entity.entity_id}: entity zone polygon differs from zone") + if unknown := { + entity.parent_entity_id + for entity in self.entities + if entity.parent_entity_id and entity.parent_entity_id not in known + }: + raise ValueError(f"metric entity parents are unknown: {sorted(unknown)}") + if unknown := { + entity.facing_target_entity_id + for entity in self.entities + if entity.facing_target_entity_id and entity.facing_target_entity_id not in known + }: + raise ValueError(f"metric entity facing targets are unknown: {sorted(unknown)}") + if unknown := { + entity.near_entity_id + for entity in self.entities + if entity.near_entity_id and entity.near_entity_id not in known + }: + raise ValueError(f"metric entity near targets are unknown: {sorted(unknown)}") + if unknown := { + entity_id + for constraint in self.along_wall_sequences + for entity_id in constraint.entity_ids + if entity_id not in known + }: + raise ValueError( + f"along-wall constraints reference unknown entities: {sorted(unknown)}" + ) + if unknown := { + entity_id + for constraint in self.radial_seating + for entity_id in [constraint.table_id, *constraint.chair_ids] + if entity_id not in known + }: + raise ValueError( + f"radial seating constraints reference unknown entities: {sorted(unknown)}" + ) + if self.schema_version == "2.0": + if not self.asset_descriptor_index: + raise ValueError("asset-first metric layout requires asset_descriptor_index") + if not self.asset_selection_path or not self.asset_selection_sha256: + raise ValueError( + "asset-first metric layout requires frozen asset selection identity" + ) + if self.room_shell_source != "metric_layout_spec": + raise ValueError("asset-first room shell must be sourced from metric_layout_spec") + if self.furniture_agent_pose_authority != "none": + raise ValueError( + "Furniture Agent cannot own coordinates or yaw in asset-first layouts" + ) + if not self.coordinate_solver: + raise ValueError( + "asset-first metric layout requires a deterministic coordinate solver" + ) + front_aware = "front_aware" in self.coordinate_solver + for entity in self.entities: + missing_fields = [ + name + for name, value in ( + ("asset_id", entity.asset_id), + ("asset_sha256", entity.asset_sha256), + ("asset_descriptor_ref", entity.asset_descriptor_ref), + ("dimensions_m", entity.dimensions_m), + ("category", entity.category), + ("display_name", entity.display_name), + ("support_type", entity.support_type), + ("quality_overall", entity.quality_overall), + ("asset_status", entity.asset_status), + ("visual_footprint_local_m", entity.visual_footprint_local_m), + ("collision_footprint_local_m", entity.collision_footprint_local_m), + ("support_footprint_local_m", entity.support_footprint_local_m), + ("visual_footprint_xy_m", entity.visual_footprint_xy_m), + ("collision_footprint_xy_m", entity.collision_footprint_xy_m), + ("support_footprint_xy_m", entity.support_footprint_xy_m), + ("layout_reserve_envelope_xy_m", entity.layout_reserve_envelope_xy_m), + ("rotated_obb_m", entity.rotated_obb_m), + ) + if value is None or value == [] or value == {} + ] + if missing_fields: + raise ValueError( + f"{entity.entity_id}: asset-first binding is incomplete: {missing_fields}" + ) + if not entity.asset_locked: + raise ValueError(f"{entity.entity_id}: asset binding is not locked") + if entity.asset_status != "ACTIVE": + raise ValueError(f"{entity.entity_id}: selected asset is not ACTIVE") + direction_sensitive = definition_for_category( + entity.category or "unknown" + ).functional_semantics not in {"none", "unknown"} + front_required = bool( + entity.facing_target_entity_id + or entity.functional_front_semantics + or direction_sensitive + ) + if front_aware and front_required and ( + entity.canonical_front_axis is None or entity.world_front_vector_xy is None + ): + raise ValueError( + f"{entity.entity_id}: directional placement requires certified front fields" + ) + return self + + @property + def entity_by_id(self) -> dict[str, MetricEntityLayout]: + return {entity.entity_id: entity for entity in self.entities} + + +class MetricLayoutValidation(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + passed: bool + failures: list[str] = Field(default_factory=list) + entity_footprints_xy_m: dict[str, list[Point2]] = Field(default_factory=dict) + pull_out_polygons_xy_m: dict[str, list[Point2]] = Field(default_factory=dict) + perturbation_applied: bool = False + perturbation_attempt: int | None = None + + +class MetricBlueprintClient(Protocol): + def analyze_image(self, source: Path, prompt: str) -> str: ... + + +def _sha256_bytes(value: bytes) -> str: + return hashlib.sha256(value).hexdigest() + + +def _sha256_file(path: Path) -> str: + return _sha256_bytes(path.read_bytes()) + + +def _canonical_sha256(value: Any) -> str: + return _sha256_bytes( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") + ) + + +def _parse_object(text: str) -> dict[str, Any]: + start = text.find("{") + end = text.rfind("}") + if start < 0 or end < start: + raise ValueError("Metric Layout Agent returned no JSON object") + value = json.loads(text[start : end + 1]) + if not isinstance(value, dict): + raise ValueError("Metric Layout Agent output must be a JSON object") + return value + + +def _room_dimensions(context_config: dict[str, Any]) -> tuple[float, float, float]: + value = context_config.get("room_dimensions_m") + if not isinstance(value, (list, tuple)) or len(value) != 3: + raise ValueError("metric_layout requires scene_config.room_dimensions_m=[x,y,z]") + result = (float(value[0]), float(value[1]), float(value[2])) + if any(not math.isfinite(item) or item <= 0 for item in result): + raise ValueError("metric layout room dimensions must be finite and positive") + return result + + +def _entity_footprint(entity: dict[str, Any]) -> Point2: + attributes = entity.get("attributes") or {} + for key in ("footprint_m", "dimensions_m", "target_dimensions_m", "expected_dimensions_m"): + value = attributes.get(key) + if isinstance(value, (list, tuple)) and len(value) >= 2: + result = float(value[0]), float(value[1]) + if all(math.isfinite(item) and item > 0 for item in result): + return result + raise ValueError(f"{entity.get('entity_id')}:metric_layout_requires_footprint_m") + + +def _parent_id(entity: dict[str, Any], known: set[str]) -> str | None: + attributes = entity.get("attributes") or {} + dependencies = attributes.get("depends_on") or [] + for dependency in dependencies if isinstance(dependencies, list) else []: + candidate = str(dependency) + if candidate in known: + return candidate + return None + + +BlueprintBounds = tuple[float, float, float, float] + + +def _uv_to_xy( + point: Point2, + dimensions: tuple[float, float, float], + source_bounds: BlueprintBounds = (0.0, 0.0, 1.0, 1.0), +) -> Point2: + min_u, min_v, max_u, max_v = source_bounds + span_u = max_u - min_u + span_v = max_v - min_v + if span_u <= 1.0e-9 or span_v <= 1.0e-9: + raise ValueError("blueprint room outline must have non-zero width and height") + normalized_u = (float(point[0]) - min_u) / span_u + normalized_v = (float(point[1]) - min_v) / span_v + return ( + (normalized_u - 0.5) * dimensions[0], + (0.5 - normalized_v) * dimensions[1], + ) + + +def _metric_polygon( + points: list[Point2], + dimensions: tuple[float, float, float], + source_bounds: BlueprintBounds = (0.0, 0.0, 1.0, 1.0), +) -> list[Point2]: + return [_uv_to_xy(point, dimensions, source_bounds) for point in points] + + +def oriented_footprint( + center_xy_m: Point2, + footprint_m: Point2, + yaw_deg: float, +) -> Polygon: + half_x, half_y = float(footprint_m[0]) / 2.0, float(footprint_m[1]) / 2.0 + shape = box(-half_x, -half_y, half_x, half_y) + shape = affinity.rotate(shape, float(yaw_deg), origin=(0.0, 0.0)) + return affinity.translate(shape, xoff=float(center_xy_m[0]), yoff=float(center_xy_m[1])) + + +def _closest_wall(center: Point2, room: Polygon) -> Literal["north", "south", "east", "west"]: + min_x, min_y, max_x, max_y = room.bounds + distances: dict[Literal["north", "south", "east", "west"], float] = { + "north": abs(max_y - center[1]), + "south": abs(center[1] - min_y), + "east": abs(max_x - center[0]), + "west": abs(center[0] - min_x), + } + return min(distances, key=distances.get) # type: ignore[arg-type] + + +def _infer_along_wall_constraints( + entities: list[MetricEntityLayout], room: Polygon +) -> list[AlongWallSequenceConstraint]: + role_markers = { + "counter": ("counter", "bar"), + "refrigerator": ("refrigerator", "fridge"), + "beverage_cabinet": ("beverage_cabinet", "drink_cabinet", "beverage_cooler"), + } + selected: dict[str, MetricEntityLayout] = {} + for role, markers in role_markers.items(): + matches = [ + entity + for entity in entities + if any(marker in entity.entity_id.casefold() for marker in markers) + ] + if matches: + selected[role] = matches[0] + if len(selected) != 3: + return [] + values = list(selected.values()) + walls = [_closest_wall(entity.center_xy_m, room) for entity in values] + if len(set(walls)) != 1: + return [] + wall = walls[0] + tangent_axis = 0 if wall in {"north", "south"} else 1 + ordered = sorted(values, key=lambda entity: entity.center_xy_m[tangent_axis]) + return [ + AlongWallSequenceConstraint( + constraint_id="blueprint-counter-fridge-beverage-cabinet-order", + entity_ids=[entity.entity_id for entity in ordered], + wall=wall, + ) + ] + + +def _infer_radial_seating_constraints( + entities: list[MetricEntityLayout], +) -> list[RadialSeatingConstraint]: + tables = [ + entity + for entity in entities + if any(marker in entity.entity_id.casefold() for marker in ("table", "desk")) + and entity.parent_entity_id is None + ] + chairs = [ + entity + for entity in entities + if any(marker in entity.entity_id.casefold() for marker in ("chair", "stool", "seat")) + and entity.parent_entity_id is None + ] + grouped: dict[str, list[MetricEntityLayout]] = {table.entity_id: [] for table in tables} + for chair in chairs: + candidates = [table for table in tables if table.zone_id == chair.zone_id] or tables + if not candidates: + continue + table = min( + candidates, + key=lambda item: math.dist(chair.center_xy_m, item.center_xy_m), + ) + grouped[table.entity_id].append(chair) + result: list[RadialSeatingConstraint] = [] + by_id = {entity.entity_id: entity for entity in entities} + for table_id, assigned in grouped.items(): + if not assigned: + continue + table = by_id[table_id] + radii = [math.dist(chair.center_xy_m, table.center_xy_m) for chair in assigned] + result.append( + RadialSeatingConstraint( + constraint_id=f"blueprint-seating-around-{table_id}", + table_id=table_id, + chair_ids=[chair.entity_id for chair in assigned], + minimum_radius_m=max(0.25, min(radii) - 0.12), + maximum_radius_m=max(radii) + 0.12, + ) + ) + return result + + +def _translation_offsets(step_m: float, maximum_m: float) -> list[Point2]: + if step_m <= 0 or maximum_m < 0: + raise ValueError("metric solver translation step/radius must be positive") + cells = int(math.ceil(maximum_m / step_m)) + offsets = { + (round(ix * step_m, 9), round(iy * step_m, 9)) + for ix in range(-cells, cells + 1) + for iy in range(-cells, cells + 1) + if math.hypot(ix * step_m, iy * step_m) <= maximum_m + 1.0e-9 + } + return sorted( + offsets, + key=lambda item: ( + item[0] * item[0] + item[1] * item[1], + abs(item[1]), + abs(item[0]), + item[1], + item[0], + ), + ) + + +def _yaw_facing_target( + center: Point2, + target: Point2, + forward_axis: Literal["+x", "+y", "-x", "-y"], +) -> float: + target_angle = math.degrees(math.atan2(target[1] - center[1], target[0] - center[0])) + local_angle = {"+x": 0.0, "+y": 90.0, "-x": 180.0, "-y": -90.0}[forward_axis] + return ((target_angle - local_angle + 180.0) % 360.0) - 180.0 + + +def _solve_metric_entities( + entities: list[MetricEntityLayout], + room: Polygon, + keep_outs: list[MetricKeepOutRegion], + seating: list[RadialSeatingConstraint], + *, + translation_step_m: float, + maximum_displacement_m: float, +) -> list[MetricEntityLayout]: + """Project blueprint poses minimally into the collision-free metric feasible set.""" + + by_id = {entity.entity_id: entity for entity in entities} + seating_by_chair = { + chair_id: constraint for constraint in seating for chair_id in constraint.chair_ids + } + keep_out_shapes = [Polygon(region.polygon_xy_m) for region in keep_outs] + offsets = _translation_offsets(translation_step_m, maximum_displacement_m) + solved: dict[str, MetricEntityLayout] = {} + solved_shapes: dict[str, Polygon] = {} + reserved_pull_outs: dict[str, Polygon] = {} + + roots = [ + entity for entity in entities if entity.parent_entity_id is None and entity.mount == "FLOOR" + ] + table_ids = {constraint.table_id for constraint in seating} + + def placement_priority(entity: MetricEntityLayout) -> int: + raw_shape = oriented_footprint(entity.center_xy_m, entity.footprint_m, entity.yaw_deg) + raw_outside_feasible_area = not room.buffer(1.0e-6).covers(raw_shape) or any( + raw_shape.intersects(region) for region in keep_out_shapes + ) + if raw_outside_feasible_area and entity.entity_id not in seating_by_chair: + return 0 + if entity.entity_id in table_ids: + return 1 + if entity.entity_id in seating_by_chair: + return 2 + return 3 + + roots.sort(key=placement_priority) + for entity in roots: + seating_constraint = seating_by_chair.get(entity.entity_id) + yaw = entity.yaw_deg + if seating_constraint is not None: + table = solved.get(seating_constraint.table_id) or by_id.get( + seating_constraint.table_id + ) + if table is None: + raise ValueError( + f"{entity.entity_id}:metric_solver_missing_table:{seating_constraint.table_id}" + ) + yaw = _yaw_facing_target( + entity.center_xy_m, + table.center_xy_m, + seating_constraint.forward_axis_local, + ) + + selected: MetricEntityLayout | None = None + selected_shape: Polygon | None = None + selected_pull_out: Polygon | None = None + for offset_x, offset_y in offsets: + center = ( + entity.center_xy_m[0] + offset_x, + entity.center_xy_m[1] + offset_y, + ) + candidate_yaw = yaw + if seating_constraint is not None: + table = ( + solved.get(seating_constraint.table_id) or by_id[seating_constraint.table_id] + ) + candidate_yaw = _yaw_facing_target( + center, + table.center_xy_m, + seating_constraint.forward_axis_local, + ) + shape = oriented_footprint(center, entity.footprint_m, candidate_yaw) + if not room.buffer(1.0e-6).covers(shape): + continue + if any(shape.intersects(region) for region in keep_out_shapes): + continue + if any(shape.intersection(other).area > 1.0e-8 for other in solved_shapes.values()): + continue + if any( + shape.intersection(pull_out).area > 1.0e-8 + for pull_out in reserved_pull_outs.values() + ): + continue + candidate_pull_out: Polygon | None = None + if seating_constraint is not None: + yaw_radians = math.radians(candidate_yaw) + forward = { + "+x": (math.cos(yaw_radians), math.sin(yaw_radians)), + "+y": (-math.sin(yaw_radians), math.cos(yaw_radians)), + "-x": (-math.cos(yaw_radians), -math.sin(yaw_radians)), + "-y": (math.sin(yaw_radians), -math.cos(yaw_radians)), + }[seating_constraint.forward_axis_local] + pull_size = ( + ( + seating_constraint.pull_out_clearance_m, + entity.footprint_m[1], + ) + if seating_constraint.forward_axis_local in {"+x", "-x"} + else ( + entity.footprint_m[0], + seating_constraint.pull_out_clearance_m, + ) + ) + pull_center = ( + center[0] - forward[0] * seating_constraint.pull_out_clearance_m / 2.0, + center[1] - forward[1] * seating_constraint.pull_out_clearance_m / 2.0, + ) + candidate_pull_out = oriented_footprint( + pull_center, + pull_size, + candidate_yaw, + ) + if not room.buffer(1.0e-6).covers(candidate_pull_out): + continue + if any( + candidate_pull_out.intersection(other).area > 1.0e-8 + for other_id, other in solved_shapes.items() + if other_id != seating_constraint.table_id + ): + continue + selected = entity.model_copy(update={"center_xy_m": center, "yaw_deg": candidate_yaw}) + selected_shape = shape + selected_pull_out = candidate_pull_out + break + if selected is None or selected_shape is None: + raise ValueError( + f"{entity.entity_id}:metric_solver_no_feasible_pose_within_" + f"{maximum_displacement_m:g}m" + ) + solved[entity.entity_id] = selected + solved_shapes[entity.entity_id] = selected_shape + if selected_pull_out is not None: + reserved_pull_outs[entity.entity_id] = selected_pull_out + + pending = [entity for entity in entities if entity.entity_id not in solved] + while pending: + progress = False + next_pending: list[MetricEntityLayout] = [] + for entity in pending: + parent_id = entity.parent_entity_id + if parent_id is None: + solved[entity.entity_id] = entity + progress = True + continue + solved_parent = solved.get(parent_id) + raw_parent = by_id.get(parent_id) + if solved_parent is None or raw_parent is None: + next_pending.append(entity) + continue + yaw_delta = math.radians(solved_parent.yaw_deg - raw_parent.yaw_deg) + relative_x = entity.center_xy_m[0] - raw_parent.center_xy_m[0] + relative_y = entity.center_xy_m[1] - raw_parent.center_xy_m[1] + rotated_x = relative_x * math.cos(yaw_delta) - relative_y * math.sin(yaw_delta) + rotated_y = relative_x * math.sin(yaw_delta) + relative_y * math.cos(yaw_delta) + solved[entity.entity_id] = entity.model_copy( + update={ + "center_xy_m": ( + solved_parent.center_xy_m[0] + rotated_x, + solved_parent.center_xy_m[1] + rotated_y, + ), + "yaw_deg": entity.yaw_deg + math.degrees(yaw_delta), + } + ) + progress = True + if not progress: + unresolved = sorted(entity.entity_id for entity in next_pending) + raise ValueError(f"metric solver unresolved parent chain: {unresolved}") + pending = next_pending + + return [solved[entity.entity_id] for entity in entities] + + +def _expand_metric_zones_to_footprints( + zones: list[MetricZone], + entities: list[MetricEntityLayout], + room: Polygon, +) -> tuple[list[MetricZone], list[MetricEntityLayout]]: + shapes_by_zone: dict[str, list[Polygon]] = {} + for entity in entities: + shapes_by_zone.setdefault(entity.zone_id, []).append( + oriented_footprint(entity.center_xy_m, entity.footprint_m, entity.yaw_deg) + ) + expanded: list[MetricZone] = [] + for zone in zones: + geometry = unary_union( + [Polygon(zone.polygon_xy_m), *shapes_by_zone.get(zone.zone_id, [])] + ).convex_hull + geometry = geometry.buffer(0.01, join_style="mitre").intersection(room) + if geometry.is_empty: + raise ValueError(f"metric zone became empty after room clipping: {zone.zone_id}") + if not isinstance(geometry, Polygon): + geometry = geometry.convex_hull + expanded.append( + zone.model_copy( + update={ + "polygon_xy_m": [ + (float(x), float(y)) for x, y in list(geometry.exterior.coords)[:-1] + ] + } + ) + ) + expanded_by_id = {zone.zone_id: zone for zone in expanded} + return expanded, [ + entity.model_copy(update={"zone_polygon_xy_m": expanded_by_id[entity.zone_id].polygon_xy_m}) + for entity in entities + ] + + +def _solve_metric_route( + raw_points: list[Point2], + raw_robot_start: Point2, + room: Polygon, + furniture: list[Polygon], + route_width_m: float, + *, + grid_step_m: float, +) -> tuple[Polygon, Point2]: + if grid_step_m <= 0: + raise ValueError("metric route grid step must be positive") + half_width = route_width_m / 2.0 + clearance = 0.01 + safe_room = room.buffer(-(half_width + clearance), join_style="mitre") + if safe_room.is_empty: + raise ValueError("room is too small for the required metric route width") + furniture_union = unary_union(furniture) + blocked = unary_union( + [shape.buffer(half_width + clearance, join_style="mitre") for shape in furniture] + ) + raw_line = LineString(raw_points) + min_x, min_y, max_x, max_y = room.bounds + count_x = int(math.floor((max_x - min_x) / grid_step_m)) + 1 + count_y = int(math.floor((max_y - min_y) / grid_step_m)) + 1 + nodes: dict[tuple[int, int], Point2] = {} + for ix in range(count_x + 1): + x = min_x + ix * grid_step_m + for iy in range(count_y + 1): + y = min_y + iy * grid_step_m + point = Point(x, y) + if safe_room.covers(point) and not blocked.covers(point): + nodes[(ix, iy)] = (float(x), float(y)) + if not nodes: + raise ValueError("metric route solver found no traversable grid nodes") + + def nearest_node(point: Point2) -> tuple[int, int]: + return min( + nodes, + key=lambda key: ( + (nodes[key][0] - point[0]) ** 2 + (nodes[key][1] - point[1]) ** 2, + key, + ), + ) + + def segment_is_clear(start: Point2, end: Point2) -> bool: + corridor = LineString([start, end]).buffer( + half_width, + cap_style="flat", + join_style="round", + ) + return room.buffer(1.0e-6).covers(corridor) and not corridor.intersects(furniture_union) + + neighbor_steps = [ + (-1, -1), + (-1, 0), + (-1, 1), + (0, -1), + (0, 1), + (1, -1), + (1, 0), + (1, 1), + ] + + def find_path(start: tuple[int, int], goal: tuple[int, int]) -> list[Point2]: + queue: list[tuple[float, float, tuple[int, int]]] = [(0.0, 0.0, start)] + came_from: dict[tuple[int, int], tuple[int, int]] = {} + cost = {start: 0.0} + while queue: + _priority, current_cost, current = heapq.heappop(queue) + if current_cost > cost.get(current, math.inf) + 1.0e-12: + continue + if current == goal: + break + for dx, dy in neighbor_steps: + neighbor = (current[0] + dx, current[1] + dy) + if neighbor not in nodes: + continue + start_xy = nodes[current] + end_xy = nodes[neighbor] + if not segment_is_clear(start_xy, end_xy): + continue + length = math.dist(start_xy, end_xy) + deviation = Point(end_xy).distance(raw_line) + next_cost = current_cost + length * (1.0 + 0.35 * deviation) + if next_cost + 1.0e-12 >= cost.get(neighbor, math.inf): + continue + cost[neighbor] = next_cost + came_from[neighbor] = current + heuristic = math.dist(end_xy, nodes[goal]) + heapq.heappush( + queue, + (next_cost + heuristic, next_cost, neighbor), + ) + if goal not in cost: + raise ValueError("metric route solver could not connect blueprint waypoints") + keys = [goal] + while keys[-1] != start: + keys.append(came_from[keys[-1]]) + keys.reverse() + return [nodes[key] for key in keys] + + robot_node = nearest_node(raw_robot_start) + reachable = {robot_node} + frontier = [robot_node] + while frontier: + current = frontier.pop() + for dx, dy in neighbor_steps: + neighbor = (current[0] + dx, current[1] + dy) + if neighbor in reachable or neighbor not in nodes: + continue + if not segment_is_clear(nodes[current], nodes[neighbor]): + continue + reachable.add(neighbor) + frontier.append(neighbor) + + def nearest_reachable_node(point: Point2) -> tuple[int, int]: + return min( + reachable, + key=lambda key: ( + (nodes[key][0] - point[0]) ** 2 + (nodes[key][1] - point[1]) ** 2, + key, + ), + ) + + waypoint_nodes = [ + nearest_reachable_node(raw_points[0]), + robot_node, + nearest_reachable_node(raw_points[-1]), + ] + + def simplify_path(path: list[Point2]) -> list[Point2]: + simplified: list[Point2] = [] + cursor = 0 + while cursor < len(path): + simplified.append(path[cursor]) + if cursor == len(path) - 1: + break + next_cursor = cursor + 1 + for candidate in range(len(path) - 1, cursor, -1): + if segment_is_clear(path[cursor], path[candidate]): + next_cursor = candidate + break + cursor = next_cursor + return simplified + + route_points: list[Point2] = [] + for start, goal in zip(waypoint_nodes, waypoint_nodes[1:], strict=False): + segment = simplify_path(find_path(start, goal)) + route_points.extend(segment if not route_points else segment[1:]) + + route = LineString(route_points).buffer( + half_width, + cap_style="flat", + join_style="round", + ) + if route.is_empty or not isinstance(route, Polygon): + raise ValueError("metric route solver did not produce one valid polygon") + if not room.buffer(1.0e-6).covers(route): + raise ValueError("metric route solver produced an out-of-room corridor") + if any(route.intersects(shape) for shape in furniture): + raise ValueError("metric route solver produced a furniture intersection") + return route, nodes[waypoint_nodes[1]] + + +def compile_metric_layout_spec( + *, + blueprint_path: Path, + hints: BlueprintMetricHints, + task: dict[str, Any], + context_config: dict[str, Any], +) -> MetricLayoutSpec: + layout_config = context_config.get("metric_layout") or {} + if not isinstance(layout_config, dict): + raise ValueError("scene_config.metric_layout must be an object") + dimensions = _room_dimensions(context_config) + room_outline_uv = _polygon(hints.room_outline_uv, label="blueprint room outline") + source_bounds: BlueprintBounds = room_outline_uv.bounds + room_polygon_mode_value = str(layout_config.get("room_polygon_mode", "blueprint_outline")) + if room_polygon_mode_value not in {"blueprint_outline", "dimensions_box"}: + raise ValueError( + "metric_layout.room_polygon_mode must be blueprint_outline or dimensions_box" + ) + room_polygon_mode = cast( + Literal["blueprint_outline", "dimensions_box"], room_polygon_mode_value + ) + if room_polygon_mode == "dimensions_box": + room_polygon = box( + -dimensions[0] / 2.0, + -dimensions[1] / 2.0, + dimensions[0] / 2.0, + dimensions[1] / 2.0, + ) + elif room_polygon_mode == "blueprint_outline": + room_polygon = _polygon( + _metric_polygon(hints.room_outline_uv, dimensions, source_bounds), + label="metric room outline", + ) + zones = [ + MetricZone( + zone_id=zone.zone_id, + polygon_xy_m=_metric_polygon(zone.polygon_uv, dimensions, source_bounds), + ) + for zone in hints.zones + ] + zone_by_id = {zone.zone_id: zone for zone in zones} + task_entities = [ + entity + for entity in task.get("entities") or [] + if isinstance(entity, dict) + and entity.get("entity_id") + and str(entity.get("role") or "").upper() not in {"REGION", "ROBOT"} + ] + known = {str(entity["entity_id"]) for entity in task_entities} + hint_by_id = {hint.entity_id: hint for hint in hints.entities} + missing = known - set(hint_by_id) + unknown = set(hint_by_id) - known + if missing: + raise ValueError(f"Metric Layout Agent omitted task entities: {sorted(missing)}") + if unknown: + raise ValueError(f"Metric Layout Agent invented task entities: {sorted(unknown)}") + entities: list[MetricEntityLayout] = [] + for task_entity in task_entities: + entity_id = str(task_entity["entity_id"]) + hint = hint_by_id[entity_id] + zone = zone_by_id[hint.zone_id] + attributes = task_entity.get("attributes") or {} + mount = str(attributes.get("mount") or "FLOOR").upper() + parent = _parent_id(task_entity, known) + entities.append( + MetricEntityLayout( + entity_id=entity_id, + center_xy_m=_uv_to_xy(hint.center_uv, dimensions, source_bounds), + yaw_deg=hint.yaw_deg, + footprint_m=_entity_footprint(task_entity), + zone_id=hint.zone_id, + zone_polygon_xy_m=zone.polygon_xy_m, + parent_entity_id=parent, + mount=mount, + allow_natural_perturbation=(mount == "FLOOR" and parent is None), + ) + ) + keep_outs = [ + MetricKeepOutRegion( + region_id=opening.opening_id, + kind=opening.kind, + polygon_xy_m=_metric_polygon(opening.keep_out_polygon_uv, dimensions, source_bounds), + ) + for opening in hints.openings + ] + for kind in ("door", "window"): + minimum = int(layout_config.get(f"minimum_{kind}_keepouts", 0)) + observed = sum(region.kind == kind for region in keep_outs) + if observed < minimum: + raise ValueError( + f"blueprint metric layout requires at least {minimum} {kind} keep-outs; " + f"observed {observed}" + ) + along_wall_values = layout_config.get("along_wall_sequences") or [] + radial_values = layout_config.get("radial_seating") or [] + along_wall = [AlongWallSequenceConstraint.model_validate(value) for value in along_wall_values] + radial = [RadialSeatingConstraint.model_validate(value) for value in radial_values] + infer_relations = bool(layout_config.get("infer_metric_relations", True)) + solver_seating = radial or ( + _infer_radial_seating_constraints(entities) if infer_relations else [] + ) + entities = _solve_metric_entities( + entities, + room_polygon, + keep_outs, + solver_seating, + translation_step_m=float(layout_config.get("solver_grid_step_m", 0.025)), + maximum_displacement_m=float(layout_config.get("solver_max_displacement_m", 0.75)), + ) + zones, entities = _expand_metric_zones_to_footprints(zones, entities, room_polygon) + if infer_relations: + along_wall = along_wall or _infer_along_wall_constraints(entities, room_polygon) + radial = radial or _infer_radial_seating_constraints(entities) + + route_width = max(1.2, float(layout_config.get("route_width_m", 1.2))) + raw_route_points = [ + _uv_to_xy(point, dimensions, source_bounds) for point in hints.route_centerline_uv + ] + route_polygon, robot_start = _solve_metric_route( + raw_route_points, + _uv_to_xy(hints.robot_start_uv, dimensions, source_bounds), + room_polygon, + [ + oriented_footprint(entity.center_xy_m, entity.footprint_m, entity.yaw_deg) + for entity in entities + if entity.parent_entity_id is None and entity.mount == "FLOOR" + ], + route_width, + grid_step_m=float(layout_config.get("route_solver_grid_step_m", 0.10)), + ) + perturbation_value = layout_config.get("natural_perturbation") or {} + if not isinstance(perturbation_value, dict): + raise ValueError("metric_layout.natural_perturbation must be an object") + perturbation = NaturalPerturbationPolicy.model_validate( + { + "seed": int(context_config.get("random_layout_seed") or 0), + **perturbation_value, + } + ) + footprint_validation_mode_value = str(layout_config.get("footprint_validation_mode", "target")) + if footprint_validation_mode_value not in {"target", "maximum_envelope"}: + raise ValueError( + "metric_layout.footprint_validation_mode must be target or maximum_envelope" + ) + footprint_validation_mode = cast( + Literal["target", "maximum_envelope"], footprint_validation_mode_value + ) + spec = MetricLayoutSpec( + source_blueprint=blueprint_path.name, + source_blueprint_sha256=_sha256_file(blueprint_path), + source_hints_sha256=_canonical_sha256(hints.model_dump(mode="json")), + room_dimensions_m=dimensions, + room_polygon_mode=room_polygon_mode, + room_polygon_xy_m=list(room_polygon.exterior.coords)[:-1], + zones=zones, + entities=entities, + keep_out_regions=keep_outs, + route_width_m=route_width, + route_polygon_xy_m=list(route_polygon.exterior.coords)[:-1], + robot_start_xy_m=robot_start, + along_wall_sequences=along_wall, + radial_seating=radial, + footprint_tolerance_m=float(layout_config.get("footprint_tolerance_m", 0.12)), + footprint_validation_mode=footprint_validation_mode, + natural_perturbation=perturbation, + ) + validation = validate_metric_layout_footprints( + spec, + { + entity.entity_id: oriented_footprint( + entity.center_xy_m, entity.footprint_m, entity.yaw_deg + ) + for entity in entities + }, + ) + if not validation.passed: + raise ValueError( + "blueprint metric layout failed hard checks: " + ";".join(validation.failures) + ) + return spec + + +def prepare_metric_layout_spec( + design_root: Path, + blueprint_path: Path, + prompt: str, + task: dict[str, Any], + context_config: dict[str, Any], + *, + client: MetricBlueprintClient, +) -> tuple[Path, MetricLayoutSpec] | None: + layout_config = context_config.get("metric_layout") or {} + if not isinstance(layout_config, dict): + raise ValueError("scene_config.metric_layout must be an object") + if not bool(layout_config.get("enabled")): + return None + target = design_root / "metric_layout_spec.json" + hints_path = design_root / "metric_layout_hints.json" + if target.is_file() and hints_path.is_file(): + existing = MetricLayoutSpec.model_validate_json(target.read_text(encoding="utf-8")) + expected_entities = { + str(entity["entity_id"]) + for entity in task.get("entities") or [] + if isinstance(entity, dict) + and entity.get("entity_id") + and str(entity.get("role") or "").upper() not in {"REGION", "ROBOT"} + } + if existing.source_blueprint_sha256 != _sha256_file(blueprint_path): + raise ValueError("existing metric layout references a different blueprint") + if existing.room_dimensions_m != _room_dimensions(context_config): + raise ValueError("existing metric layout uses different room dimensions") + if set(existing.entity_by_id) != expected_entities: + raise ValueError("existing metric layout entity set differs from the frozen task") + return target, existing + room_dimensions = _room_dimensions(context_config) + entities = [] + for entity in task.get("entities") or []: + if not isinstance(entity, dict) or not entity.get("entity_id"): + continue + if str(entity.get("role") or "").upper() in {"REGION", "ROBOT"}: + continue + attributes = entity.get("attributes") or {} + entities.append( + { + "entity_id": str(entity["entity_id"]), + "category": str(entity.get("category") or ""), + "mount": str(attributes.get("mount") or "FLOOR"), + "footprint_m": _entity_footprint(entity), + "depends_on": attributes.get("depends_on") or [], + } + ) + analysis_prompt = f"""You are the Metric Layout Agent. Read the frozen top-down blueprint and +return exactly one JSON object with schema_version, room_outline_uv, zones, entities, openings, +route_centerline_uv, and robot_start_uv. All image coordinates are normalized [u,v] where u grows +left-to-right and v grows top-to-bottom. Keep the blueprint's positions and orientation strictly; +do not redesign it. Use every exact entity_id below exactly once and invent none. Each zone has +zone_id and polygon_uv. Each entity has entity_id, center_uv, yaw_deg, and zone_id. Each visible + door/window has opening_id, kind, and keep_out_polygon_uv large enough for inward operation and +approach. route_centerline_uv must describe the clear robot aisle shown by the drawing; place the +centerline beside source/destination approach faces rather than through furniture. robot_start_uv +must be on that aisle. Do not output metres: RoboHouseGen will scale the drawing deterministically +to the declared {room_dimensions[0]:g} m by {room_dimensions[1]:g} m room and buffer the route to +exactly {max(1.2, float(layout_config.get("route_width_m", 1.2))):g} m. + +Exact task entities and declared footprints: +{json.dumps(entities, ensure_ascii=False, indent=2)} + +Original design request: +{prompt} +""" + explicit_hints = layout_config.get("blueprint_hints") + if explicit_hints is not None: + hints = BlueprintMetricHints.model_validate(explicit_hints) + elif hints_path.is_file(): + hints = BlueprintMetricHints.model_validate_json(hints_path.read_text(encoding="utf-8")) + else: + hints = BlueprintMetricHints.model_validate( + _parse_object(client.analyze_image(blueprint_path, analysis_prompt)) + ) + atomic_write_text(hints_path, hints.model_dump_json(indent=2) + "\n") + spec = compile_metric_layout_spec( + blueprint_path=blueprint_path, + hints=hints, + task=task, + context_config=context_config, + ) + atomic_write_text(target, spec.model_dump_json(indent=2) + "\n") + return target, spec + + +def validate_metric_layout_footprints( + spec: MetricLayoutSpec, + footprints: dict[str, Polygon], + *, + center_tolerance_m: float = 0.03, + perturbation_applied: bool = False, + perturbation_attempt: int | None = None, +) -> MetricLayoutValidation: + failures: list[str] = [] + room = Polygon(spec.room_polygon_xy_m) + route = Polygon(spec.route_polygon_xy_m) + if not route.buffer(1.0e-6).covers(Point(spec.robot_start_xy_m)): + failures.append("robot_start:metric_layout_outside_route") + entity_by_id = spec.entity_by_id + keep_outs = {region.region_id: Polygon(region.polygon_xy_m) for region in spec.keep_out_regions} + output_footprints: dict[str, list[Point2]] = {} + for entity_id, declared in entity_by_id.items(): + shape = footprints.get(entity_id) + if shape is None: + failures.append(f"{entity_id}:metric_layout_missing_footprint") + continue + output_footprints[entity_id] = [ + (float(x), float(y)) for x, y in list(shape.exterior.coords)[:-1] + ] + if not room.buffer(1.0e-6).covers(shape): + failures.append(f"{entity_id}:metric_layout_outside_room") + zone = Polygon(declared.zone_polygon_xy_m) + if not zone.buffer(1.0e-6).covers(shape): + failures.append(f"{entity_id}:metric_layout_outside_zone:{declared.zone_id}") + if ( + shape.centroid.distance( + oriented_footprint(declared.center_xy_m, (0.002, 0.002), 0.0).centroid + ) + > center_tolerance_m + ): + failures.append(f"{entity_id}:metric_layout_center_mismatch") + if spec.require_route_clearance and shape.intersects(route): + failures.append(f"{entity_id}:metric_layout_route_intersection") + for region_id, keep_out in keep_outs.items(): + if shape.intersects(keep_out): + failures.append(f"{entity_id}:metric_layout_keep_out_intersection:{region_id}") + + root_ids = [ + entity_id + for entity_id, entity in entity_by_id.items() + if entity.parent_entity_id is None and entity.mount == "FLOOR" and entity_id in footprints + ] + if spec.require_no_furniture_overlap: + for index, left_id in enumerate(root_ids): + for right_id in root_ids[index + 1 :]: + overlap = footprints[left_id].intersection(footprints[right_id]).area + if overlap > 1.0e-8: + failures.append(f"{left_id}:metric_layout_obb_overlap:{right_id}:{overlap:.6f}") + + min_x, min_y, max_x, max_y = room.bounds + for wall_constraint in spec.along_wall_sequences: + if any(entity_id not in footprints for entity_id in wall_constraint.entity_ids): + failures.append(f"semantic_constraint:{wall_constraint.constraint_id}:missing_entity") + continue + tangent_axis = 0 if wall_constraint.wall in {"north", "south"} else 1 + ordered = sorted( + wall_constraint.entity_ids, + key=lambda entity_id: footprints[entity_id].centroid.coords[0][tangent_axis], + reverse=wall_constraint.order == "decreasing", + ) + if ordered != wall_constraint.entity_ids: + failures.append(f"semantic_constraint:{wall_constraint.constraint_id}:wall_order") + wall_coordinate = { + "north": max_y, + "south": min_y, + "east": max_x, + "west": min_x, + }[wall_constraint.wall] + for entity_id in wall_constraint.entity_ids: + shape = footprints[entity_id] + near_edge = { + "north": shape.bounds[3], + "south": shape.bounds[1], + "east": shape.bounds[2], + "west": shape.bounds[0], + }[wall_constraint.wall] + if abs(wall_coordinate - near_edge) > wall_constraint.maximum_wall_offset_m + 1.0e-6: + failures.append( + f"{entity_id}:semantic_constraint:{wall_constraint.constraint_id}:wall_offset" + ) + for left_id, right_id in zip( + wall_constraint.entity_ids, + wall_constraint.entity_ids[1:], + strict=False, + ): + left_bounds = footprints[left_id].bounds + right_bounds = footprints[right_id].bounds + if wall_constraint.order == "increasing": + gap = right_bounds[tangent_axis] - left_bounds[tangent_axis + 2] + else: + gap = left_bounds[tangent_axis] - right_bounds[tangent_axis + 2] + if gap < -1.0e-8: + failures.append( + f"semantic_constraint:{wall_constraint.constraint_id}:" + f"sequence_overlap={gap:.6f}" + ) + elif gap > wall_constraint.maximum_gap_m + 1.0e-6: + failures.append( + f"semantic_constraint:{wall_constraint.constraint_id}:maximum_gap={gap:.6f}" + ) + + pull_outs: dict[str, list[Point2]] = {} + for seating_constraint in spec.radial_seating: + table = footprints.get(seating_constraint.table_id) + if table is None: + failures.append(f"semantic_constraint:{seating_constraint.constraint_id}:missing_table") + continue + table_center = table.centroid + for chair_id in seating_constraint.chair_ids: + chair = footprints.get(chair_id) + if chair is None: + failures.append( + f"semantic_constraint:{seating_constraint.constraint_id}:missing_chair" + ) + continue + chair_center = chair.centroid + radius = chair_center.distance(table_center) + if not ( + seating_constraint.minimum_radius_m <= radius <= seating_constraint.maximum_radius_m + ): + failures.append( + f"{chair_id}:semantic_constraint:{seating_constraint.constraint_id}:" + f"radius={radius:.6f}" + ) + declared = entity_by_id[chair_id] + yaw = math.radians(declared.yaw_deg) + axis = seating_constraint.forward_axis_local + forward = { + "+x": (math.cos(yaw), math.sin(yaw)), + "+y": (-math.sin(yaw), math.cos(yaw)), + "-x": (-math.cos(yaw), -math.sin(yaw)), + "-y": (math.sin(yaw), -math.cos(yaw)), + }[axis] + target = (table_center.x - chair_center.x, table_center.y - chair_center.y) + norm = math.hypot(*target) + cosine = ( + (forward[0] * target[0] + forward[1] * target[1]) / norm if norm > 1.0e-9 else -1.0 + ) + angle = math.degrees(math.acos(max(-1.0, min(1.0, cosine)))) + if angle > seating_constraint.maximum_facing_error_deg + 1.0e-6: + failures.append( + f"{chair_id}:semantic_constraint:{seating_constraint.constraint_id}:" + f"facing={angle:.6f}" + ) + pull_size = ( + (seating_constraint.pull_out_clearance_m, declared.footprint_m[1]) + if axis in {"+x", "-x"} + else ( + declared.footprint_m[0], + seating_constraint.pull_out_clearance_m, + ) + ) + pull_center = ( + chair_center.x - forward[0] * seating_constraint.pull_out_clearance_m / 2.0, + chair_center.y - forward[1] * seating_constraint.pull_out_clearance_m / 2.0, + ) + pull = oriented_footprint( + pull_center, + pull_size, + declared.yaw_deg, + ) + pull_outs[chair_id] = [(float(x), float(y)) for x, y in list(pull.exterior.coords)[:-1]] + if not room.covers(pull): + failures.append( + f"{chair_id}:semantic_constraint:{seating_constraint.constraint_id}:" + "pull_out_outside_room" + ) + for other_id in root_ids: + if other_id in {chair_id, seating_constraint.table_id}: + continue + if pull.intersection(footprints[other_id]).area > 1.0e-8: + failures.append( + f"{chair_id}:semantic_constraint:{seating_constraint.constraint_id}:" + f"pull_out_blocked_by:{other_id}" + ) + + return MetricLayoutValidation( + passed=not failures, + failures=sorted(set(failures)), + entity_footprints_xy_m=output_footprints, + pull_out_polygons_xy_m=pull_outs, + perturbation_applied=perturbation_applied, + perturbation_attempt=perturbation_attempt, + ) + + +def perturbed_metric_layouts(spec: MetricLayoutSpec) -> list[tuple[int, MetricLayoutSpec]]: + policy = spec.natural_perturbation + if not policy.enabled: + return [] + generator = random.Random(policy.seed) + result: list[tuple[int, MetricLayoutSpec]] = [] + entity_by_id = spec.entity_by_id + for attempt in range(1, policy.maximum_attempts + 1): + root_delta: dict[str, tuple[float, float, float]] = {} + updates: dict[str, MetricEntityLayout] = {} + for entity in spec.entities: + if entity.allow_natural_perturbation: + dx = max( + -policy.translation_max_m, + min(policy.translation_max_m, generator.gauss(0.0, policy.translation_std_m)), + ) + dy = max( + -policy.translation_max_m, + min(policy.translation_max_m, generator.gauss(0.0, policy.translation_std_m)), + ) + dyaw = max( + -policy.yaw_max_deg, + min(policy.yaw_max_deg, generator.gauss(0.0, policy.yaw_std_deg)), + ) + root_delta[entity.entity_id] = (dx, dy, dyaw) + updates[entity.entity_id] = entity.model_copy( + update={ + "center_xy_m": ( + entity.center_xy_m[0] + dx, + entity.center_xy_m[1] + dy, + ), + "yaw_deg": entity.yaw_deg + dyaw, + } + ) + for entity in spec.entities: + if entity.entity_id in updates: + continue + root_id = entity.parent_entity_id + while root_id is not None and root_id not in root_delta: + root_id = entity_by_id[root_id].parent_entity_id + delta = root_delta.get(root_id or "") + if delta is None: + updates[entity.entity_id] = entity + else: + root = entity_by_id[str(root_id)] + yaw_delta = math.radians(delta[2]) + relative_x = entity.center_xy_m[0] - root.center_xy_m[0] + relative_y = entity.center_xy_m[1] - root.center_xy_m[1] + updates[entity.entity_id] = entity.model_copy( + update={ + "center_xy_m": ( + root.center_xy_m[0] + + delta[0] + + math.cos(yaw_delta) * relative_x + - math.sin(yaw_delta) * relative_y, + root.center_xy_m[1] + + delta[1] + + math.sin(yaw_delta) * relative_x + + math.cos(yaw_delta) * relative_y, + ), + "yaw_deg": entity.yaw_deg + delta[2], + } + ) + result.append( + ( + attempt, + spec.model_copy( + update={"entities": [updates[entity.entity_id] for entity in spec.entities]} + ), + ) + ) + return result + + +def load_metric_layout_spec_from_contract( + contract_path: Path, contract: Any +) -> MetricLayoutSpec | None: + relative = getattr(contract, "metric_layout_spec_path", None) + expected = getattr(contract, "metric_layout_spec_sha256", None) + if not relative: + return None + path = (contract_path.resolve().parent / str(relative)).resolve() + if not path.is_relative_to(contract_path.resolve().parent) or not path.is_file(): + raise FileNotFoundError("frozen metric layout spec is missing or escapes case_design") + if expected and _sha256_file(path) != expected: + raise ValueError("frozen metric layout spec hash mismatch") + return MetricLayoutSpec.model_validate_json(path.read_text(encoding="utf-8")) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/motifs.py b/docs/reproduction/public_conversion_code/packages/scene_generation/motifs.py new file mode 100644 index 0000000000000000000000000000000000000000..034ba1f7ebbb62c96ff8d47037fca6f5446a6893 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/motifs.py @@ -0,0 +1,367 @@ +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any, Literal + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator +from shapely.geometry import Polygon # type: ignore[import-untyped] + +from packages.core.contracts.providers import canonical_sha256 +from packages.core.files import atomic_write_text +from packages.scene_generation.metric_layout import MetricLayoutSpec +from packages.scene_generation.multi_room import MultiRoomMetricLayoutSpec +from packages.schemas.models import TaskSpec + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class MotifRelation(_StrictModel): + subject_role: str + relation: Literal[ + "near", + "faces", + "beside", + "centered_on", + "against_wall", + "paired_with", + ] + object_role: str | None = None + preferred_distance_m: tuple[float, float] | None = None + preferred_angle_deg: tuple[float, float] | None = None + weight: float = Field(default=1.0, gt=0.0) + + @model_validator(mode="after") + def validate_ranges(self) -> MotifRelation: + for value, label in ( + (self.preferred_distance_m, "distance"), + (self.preferred_angle_deg, "angle"), + ): + if value is not None and ( + value[1] < value[0] or not all(math.isfinite(x) for x in value) + ): + raise ValueError(f"motif {label} range is invalid") + if self.relation != "against_wall" and not self.object_role: + raise ValueError(f"motif relation {self.relation} requires object_role") + return self + + +class SceneMotif(_StrictModel): + motif_id: str = Field(pattern=r"^[a-z][a-z0-9_.-]*$") + version: str + room_types: set[str] + activity: str + required_roles: list[str] = Field(min_length=2) + optional_roles: list[str] = Field(default_factory=list) + relations: list[MotifRelation] = Field(min_length=1) + source_datasets: set[str] = Field(default_factory=set) + provenance: list[str] = Field(default_factory=list) + + +class MotifLibrary(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + motifs: list[SceneMotif] + + @model_validator(mode="after") + def unique_ids(self) -> MotifLibrary: + ids = [item.motif_id for item in self.motifs] + if len(ids) != len(set(ids)): + raise ValueError("motif IDs must be unique") + return self + + @classmethod + def from_yaml(cls, path: Path) -> MotifLibrary: + return cls.model_validate(yaml.safe_load(path.read_text(encoding="utf-8"))) + + def retrieve( + self, + *, + room_type: str, + entity_categories: set[str], + limit: int = 5, + ) -> list[SceneMotif]: + normalized_room = room_type.casefold() + normalized_entities = {item.casefold().replace("_", " ") for item in entity_categories} + + def evidence(motif: SceneMotif) -> tuple[float, int, bool]: + room_match = normalized_room in {item.casefold() for item in motif.room_types} + roles = {item.casefold().replace("_", " ") for item in motif.required_roles} + matched_roles = len(roles & normalized_entities) + coverage = matched_roles / max(1, len(roles)) + return coverage, matched_roles, room_match + + def score(motif: SceneMotif) -> tuple[float, str]: + coverage, _matched_roles, room_match = evidence(motif) + return (2.0 if room_match else 0.0) + coverage, motif.motif_id + + def eligible(motif: SceneMotif) -> bool: + coverage, matched_roles, room_match = evidence(motif) + # A room-name match alone is too weak: a kitchen task mentioning only a + # table must not import an unrelated dining motif. Require two semantic + # role matches (or complete coverage for a two-role motif) and use the + # room type only for ranking those evidence-backed candidates. + return matched_roles >= 2 and (coverage >= 0.5 or room_match) + + ranked = sorted(self.motifs, key=lambda item: (-score(item)[0], score(item)[1])) + return [item for item in ranked if eligible(item)][:limit] + + +class ReferenceScene(_StrictModel): + reference_id: str + source: str + source_version: str + source_license: str + source_hash: str = Field(pattern=r"^[0-9a-f]{64}$") + room_type: str + style_tags: set[str] = Field(default_factory=set) + task_types: set[str] = Field(default_factory=set) + room_dimensions_m: tuple[float, float, float] + motif_ids: list[str] = Field(default_factory=list) + relative_statistics: dict[str, float] = Field(default_factory=dict) + quality: float = Field(default=0.5, ge=0.0, le=1.0) + + +class ReferenceSceneMemory: + """Metadata-only retrieval memory; it carries no authoritative coordinates.""" + + def __init__(self, references: list[ReferenceScene]) -> None: + self.references = references + + @classmethod + def from_jsonl(cls, path: Path) -> ReferenceSceneMemory: + return cls( + [ + ReferenceScene.model_validate_json(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + ) + + def retrieve( + self, + *, + room_type: str, + style_tags: set[str], + task_type: str, + room_dimensions_m: tuple[float, float, float], + limit: int = 5, + ) -> list[ReferenceScene]: + target_volume = math.prod(room_dimensions_m) + normalized_room = room_type.casefold() + normalized_styles = {tag.casefold() for tag in style_tags} + + def score(item: ReferenceScene) -> tuple[float, str]: + room_score = 2.0 if item.room_type.casefold() == normalized_room else 0.0 + style_score = len( + {tag.casefold() for tag in item.style_tags} & normalized_styles + ) / max(1, len(normalized_styles)) + task_score = 1.0 if task_type in item.task_types else 0.0 + volume_ratio = min(target_volume, math.prod(item.room_dimensions_m)) / max( + target_volume, math.prod(item.room_dimensions_m) + ) + total = room_score + style_score + task_score + volume_ratio + item.quality + return total, item.reference_id + + def eligible(item: ReferenceScene) -> bool: + return bool( + item.room_type.casefold() == normalized_room + or task_type in item.task_types + or ( + normalized_styles + and {tag.casefold() for tag in item.style_tags} & normalized_styles + ) + ) + + ranked = sorted(self.references, key=lambda item: (-score(item)[0], score(item)[1])) + return [item for item in ranked if eligible(item)][:limit] + + +class SoftLayoutPrior(_StrictModel): + prior_id: str + source: Literal["motif", "reference"] + relation: str + subject_role: str + object_role: str | None = None + preferred_distance_m: tuple[float, float] | None = None + preferred_angle_deg: tuple[float, float] | None = None + weight: float = Field(gt=0.0) + provenance: list[str] = Field(default_factory=list) + + +class LayeredScenePlan(_StrictModel): + """Semantic plan around an immutable MetricLayoutSpec geometry truth.""" + + schema_version: Literal["1.0"] = "1.0" + task_id: str + metric_layout_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + topology_layer: dict[str, Any] + activity_zones: list[str] + anchor_entities: list[str] + motif_ids: list[str] + secondary_entities: list[str] + visual_layers: list[str] + task_entities: list[str] + robot_start_xy_m: tuple[float, float] + hard_constraints: list[str] + soft_priors: list[SoftLayoutPrior] + reference_ids: list[str] + geometry_mutations: Literal[0] = 0 + + +def compile_layered_scene_plan( + *, + task: TaskSpec, + metric_layout: MetricLayoutSpec | MultiRoomMetricLayoutSpec, + motif_library: MotifLibrary, + reference_memory: ReferenceSceneMemory | None = None, + room_type: str | None = None, + style_tags: set[str] | None = None, + motif_limit: int = 5, + reference_limit: int = 5, +) -> LayeredScenePlan: + layout_before = canonical_sha256(metric_layout.model_dump(mode="json")) + selected_room = room_type or task.required_rooms[0] + selected_dimensions = metric_layout.room_dimensions_m + if isinstance(metric_layout, MultiRoomMetricLayoutSpec): + matches = [ + room for room in metric_layout.rooms if selected_room in {room.room_id, room.room_type} + ] + if not matches: + raise ValueError(f"layered plan room is absent from layout: {selected_room}") + selected_polygon = Polygon(matches[0].floor_polygon_xy_m) + minimum_x, minimum_y, maximum_x, maximum_y = selected_polygon.bounds + selected_dimensions = ( + maximum_x - minimum_x, + maximum_y - minimum_y, + matches[0].height_m, + ) + categories = {entity.category for entity in task.entities} + motifs = motif_library.retrieve( + room_type=selected_room, + entity_categories=categories, + limit=motif_limit, + ) + references = ( + reference_memory.retrieve( + room_type=selected_room, + style_tags=style_tags or set(), + task_type=task.task_type, + room_dimensions_m=selected_dimensions, + limit=reference_limit, + ) + if reference_memory is not None + else [] + ) + priors = [ + SoftLayoutPrior( + prior_id=f"motif.{motif.motif_id}.{index}", + source="motif", + relation=relation.relation, + subject_role=relation.subject_role, + object_role=relation.object_role, + preferred_distance_m=relation.preferred_distance_m, + preferred_angle_deg=relation.preferred_angle_deg, + weight=relation.weight, + provenance=motif.provenance, + ) + for motif in motifs + for index, relation in enumerate(motif.relations) + ] + for reference in references: + for relation, value in sorted(reference.relative_statistics.items()): + priors.append( + SoftLayoutPrior( + prior_id=f"reference.{reference.reference_id}.{relation}", + source="reference", + relation=relation, + subject_role="retrieved_scene_role", + weight=max(0.01, reference.quality), + provenance=[ + f"{reference.source}@{reference.source_version}", + reference.source_license, + reference.source_hash, + f"statistic={value}", + ], + ) + ) + layout_after = canonical_sha256(metric_layout.model_dump(mode="json")) + if layout_before != layout_after: + raise RuntimeError("motif/reference planning mutated MetricLayoutSpec") + anchors = [ + entity.entity_id for entity in task.entities if entity.role in {"BACKGROUND", "TARGET"} + ] + secondary = [entity.entity_id for entity in task.entities if entity.role == "CONTEXT"] + task_entities = [ + entity.entity_id + for entity in task.entities + if entity.role in {"MANIPULATED", "TARGET", "REGION"} + ] + topology_layer: dict[str, Any] + if isinstance(metric_layout, MultiRoomMetricLayoutSpec): + topology_layer = { + "kind": "multi_room", + "rooms": [ + { + "room_id": room.room_id, + "room_type": room.room_type, + "floor_polygon_xy_m": room.floor_polygon_xy_m, + "height_m": room.height_m, + } + for room in metric_layout.rooms + ], + "portals": [ + { + "portal_id": portal.portal_id, + "kind": portal.kind, + "room_a_id": portal.room_a_id, + "room_b_id": portal.room_b_id, + "clear_width_m": portal.clear_width_m, + } + for portal in metric_layout.portals + ], + "route_room_ids": metric_layout.route_room_ids, + "route_portal_ids": metric_layout.route_portal_ids, + } + else: + topology_layer = { + "kind": "single_room", + "room_dimensions_m": metric_layout.room_dimensions_m, + "room_polygon_mode": metric_layout.room_polygon_mode, + "opening_keep_out_ids": [item.region_id for item in metric_layout.keep_out_regions], + } + return LayeredScenePlan( + task_id=task.task_id, + metric_layout_sha256=layout_before, + topology_layer=topology_layer, + activity_zones=[zone.zone_id for zone in metric_layout.zones], + anchor_entities=anchors, + motif_ids=[motif.motif_id for motif in motifs], + secondary_entities=secondary, + visual_layers=["materials", "wallpaper", "lighting", "decor", "exterior"], + task_entities=task_entities, + robot_start_xy_m=metric_layout.robot_start_xy_m, + hard_constraints=[ + "collision_free", + "route_clearance", + "door_sweep_clear", + "support_valid", + "robot_stance_reachable", + "task_reachability", + ], + soft_priors=priors, + reference_ids=[item.reference_id for item in references], + ) + + +def write_layered_scene_plan(path: Path, plan: LayeredScenePlan) -> None: + if path.exists(): + raise FileExistsError(f"refusing to overwrite layered scene plan: {path}") + atomic_write_text( + path, + json.dumps(plan.model_dump(mode="json"), ensure_ascii=False, indent=2, sort_keys=True) + + "\n", + ) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/multi_room.py b/docs/reproduction/public_conversion_code/packages/scene_generation/multi_room.py new file mode 100644 index 0000000000000000000000000000000000000000..62cf9f3b24b8eb0e93f4e0a2e6c3bb2085507cd6 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/multi_room.py @@ -0,0 +1,1184 @@ +from __future__ import annotations + +import hashlib +import json +import math +from dataclasses import dataclass +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator +from shapely import affinity # type: ignore[import-untyped] +from shapely.geometry import ( # type: ignore[import-untyped] + GeometryCollection, + LineString, + MultiLineString, + MultiPolygon, + Point, + Polygon, + box, +) +from shapely.ops import unary_union # type: ignore[import-untyped] + +from packages.scene_generation.metric_layout import ( + MetricEntityLayout, + MetricKeepOutRegion, + NaturalPerturbationPolicy, + Point2, +) + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +def _polygon(points: list[Point2], *, label: str) -> Polygon: + polygon = Polygon(points) + if not polygon.is_valid or polygon.is_empty or polygon.area <= 1.0e-8: + raise ValueError(f"{label} must be a valid non-empty polygon") + return polygon + + +def _segment(points: tuple[Point2, Point2], *, label: str) -> LineString: + line = LineString(points) + if not line.is_valid or line.length <= 1.0e-8: + raise ValueError(f"{label} must be a valid non-zero segment") + return line + + +def _line_parts(value: Any) -> list[LineString]: + if isinstance(value, LineString): + return [value] + if isinstance(value, (MultiLineString, GeometryCollection)): + return [part for child in value.geoms for part in _line_parts(child)] + return [] + + +def _polygon_parts(value: Any) -> list[Polygon]: + if isinstance(value, Polygon): + return [value] + if isinstance(value, (MultiPolygon, GeometryCollection)): + return [part for child in value.geoms for part in _polygon_parts(child)] + return [] + + +def _canonical_sha256(value: Any) -> str: + payload = json.dumps( + value, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def _oriented_footprint(entity: MetricEntityLayout) -> Polygon: + if entity.layout_reserve_envelope_xy_m: + return _polygon( + entity.layout_reserve_envelope_xy_m, + label=f"{entity.entity_id} layout reserve envelope", + ) + local = box( + -entity.footprint_m[0] / 2.0, + -entity.footprint_m[1] / 2.0, + entity.footprint_m[0] / 2.0, + entity.footprint_m[1] / 2.0, + ) + rotated = affinity.rotate(local, entity.yaw_deg, origin=(0.0, 0.0)) + return affinity.translate( + rotated, + xoff=entity.center_xy_m[0], + yoff=entity.center_xy_m[1], + ) + + +class MetricRoom(_StrictModel): + room_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + room_type: str = Field(min_length=1) + floor_polygon_xy_m: list[Point2] = Field(min_length=3) + height_m: float = Field(default=2.8, gt=0.0) + floor_elevation_m: float = 0.0 + + @model_validator(mode="after") + def validate_geometry(self) -> MetricRoom: + _polygon(self.floor_polygon_xy_m, label=f"room {self.room_id}") + if not math.isfinite(self.height_m) or not math.isfinite(self.floor_elevation_m): + raise ValueError(f"room {self.room_id} height/elevation must be finite") + return self + + +class MultiRoomMetricZone(_StrictModel): + zone_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + room_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + polygon_xy_m: list[Point2] = Field(min_length=3) + + @model_validator(mode="after") + def validate_polygon(self) -> MultiRoomMetricZone: + _polygon(self.polygon_xy_m, label=f"zone {self.zone_id}") + return self + + +class MetricPortal(_StrictModel): + portal_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + kind: Literal["door", "open_passage"] = "door" + room_a_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + room_b_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + opening_segment_xy_m: tuple[Point2, Point2] + clear_width_m: float = Field(gt=0.0) + clear_height_m: float = Field(default=2.1, gt=0.0) + wall_thickness_m: float = Field(default=0.10, gt=0.0) + traversable: Literal[True] = True + hinge_side: Literal["left", "right"] | None = None + swing_room_id: str | None = None + swing_polygon_xy_m: list[Point2] = Field(default_factory=list) + door_open_angle_deg: float = Field(default=90.0, ge=30.0, le=120.0) + initial_open_fraction: float = Field(default=1.0, ge=0.0, le=1.0) + + @model_validator(mode="after") + def validate_portal(self) -> MetricPortal: + if self.room_a_id == self.room_b_id: + raise ValueError(f"portal {self.portal_id} must connect two different rooms") + line = _segment(self.opening_segment_xy_m, label=f"portal {self.portal_id}") + if abs(line.length - self.clear_width_m) > 1.0e-5: + raise ValueError( + f"portal {self.portal_id} clear width differs from its opening segment" + ) + if self.kind == "door": + if self.hinge_side is None or self.swing_room_id is None: + raise ValueError(f"door portal {self.portal_id} requires hinge and swing room") + if self.swing_room_id not in {self.room_a_id, self.room_b_id}: + raise ValueError(f"door portal {self.portal_id} swing room is not connected") + if not self.swing_polygon_xy_m: + raise ValueError(f"door portal {self.portal_id} requires a sweep polygon") + _polygon( + self.swing_polygon_xy_m, + label=f"door portal {self.portal_id} sweep", + ) + elif ( + any(value is not None for value in (self.hinge_side, self.swing_room_id)) + or self.swing_polygon_xy_m + ): + raise ValueError("open passages cannot declare door hinge/sweep fields") + return self + + +def portal_midpoint(portal: MetricPortal) -> Point: + return _segment( + portal.opening_segment_xy_m, + label=f"portal {portal.portal_id}", + ).interpolate(0.5, normalized=True) + + +def _rotate(vector: Point2, angle_deg: float) -> Point2: + angle = math.radians(angle_deg) + cosine = math.cos(angle) + sine = math.sin(angle) + return ( + vector[0] * cosine - vector[1] * sine, + vector[0] * sine + vector[1] * cosine, + ) + + +def _door_hinge_and_vector(portal: MetricPortal) -> tuple[Point2, Point2]: + start, end = portal.opening_segment_xy_m + if portal.hinge_side == "left": + return start, (end[0] - start[0], end[1] - start[1]) + return end, (start[0] - end[0], start[1] - end[1]) + + +def _door_rotation_sign(portal: MetricPortal, swing_room: Polygon) -> float: + hinge, closed = _door_hinge_and_vector(portal) + candidates: list[tuple[bool, float, float]] = [] + for sign in (-1.0, 1.0): + opened = _rotate(closed, sign * portal.door_open_angle_deg) + center = Point(hinge[0] + opened[0] / 2.0, hinge[1] + opened[1] / 2.0) + candidates.append( + ( + swing_room.buffer(1.0e-6).covers(center), + center.distance(swing_room.centroid), + sign, + ) + ) + inside = [candidate for candidate in candidates if candidate[0]] + if not inside: + raise ValueError(f"door {portal.portal_id} cannot swing into {portal.swing_room_id}") + return min(inside, key=lambda item: item[1])[2] + + +def door_swing_polygon( + *, + opening_segment_xy_m: tuple[Point2, Point2], + hinge_side: Literal["left", "right"], + open_angle_deg: float, + swing_room: Polygon, + portal_id: str, +) -> list[Point2]: + temporary = MetricPortal.model_construct( + portal_id=portal_id, + kind="door", + room_a_id="room_a", + room_b_id="room_b", + opening_segment_xy_m=opening_segment_xy_m, + clear_width_m=LineString(opening_segment_xy_m).length, + clear_height_m=2.1, + wall_thickness_m=0.1, + traversable=True, + hinge_side=hinge_side, + swing_room_id="room_a", + swing_polygon_xy_m=[(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], + door_open_angle_deg=open_angle_deg, + initial_open_fraction=1.0, + ) + hinge, closed = _door_hinge_and_vector(temporary) + sign = _door_rotation_sign(temporary, swing_room) + steps = max(8, int(math.ceil(open_angle_deg / 7.5))) + points: list[Point2] = [hinge] + for index in range(steps + 1): + vector = _rotate(closed, sign * open_angle_deg * index / steps) + points.append((hinge[0] + vector[0], hinge[1] + vector[1])) + sweep = Polygon(points).buffer(0.015, join_style="mitre") + if not swing_room.buffer(0.025).covers(sweep): + raise ValueError(f"door {portal_id} sweep leaves its declared swing room") + return [(float(x), float(y)) for x, y in list(sweep.exterior.coords)[:-1]] + + +def door_leaf_polygon(portal: MetricPortal, swing_room: Polygon) -> Polygon: + if portal.kind != "door": + raise ValueError("door leaf geometry requires a door portal") + hinge, closed = _door_hinge_and_vector(portal) + sign = _door_rotation_sign(portal, swing_room) + opened = _rotate( + closed, + sign * portal.door_open_angle_deg * portal.initial_open_fraction, + ) + end = (hinge[0] + opened[0], hinge[1] + opened[1]) + return LineString([hinge, end]).buffer( + portal.wall_thickness_m * 0.22, + cap_style=2, + ) + + +@dataclass(frozen=True, slots=True) +class WallRun: + start_xy_m: Point2 + end_xy_m: Point2 + floor_elevation_m: float + height_m: float + + +class MultiRoomMetricLayoutSpec(_StrictModel): + """Metric V3 building truth with explicit rooms, portals, and route topology.""" + + schema_version: Literal["3.0"] = "3.0" + coordinate_system: Literal["building_world_xy_metres_x_east_y_north"] = ( + "building_world_xy_metres_x_east_y_north" + ) + source_blueprint: str + source_blueprint_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + source_hints_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + rooms: list[MetricRoom] = Field(min_length=2) + portals: list[MetricPortal] = Field(min_length=1) + zones: list[MultiRoomMetricZone] = Field(min_length=2) + entities: list[MetricEntityLayout] = Field(min_length=1) + keep_out_regions: list[MetricKeepOutRegion] = Field(default_factory=list) + route_width_m: float = Field(default=0.85, ge=0.75) + robot_id: str | None = None + robot_constraints_enabled: bool = True + route_polygon_xy_m: list[Point2] = Field(min_length=3) + route_room_ids: list[str] = Field(min_length=2) + route_portal_ids: list[str] = Field(min_length=1) + robot_start_xy_m: Point2 + robot_start_room_id: str + wall_thickness_m: float = Field(default=0.10, gt=0.0, le=0.30) + footprint_tolerance_m: float = Field(default=0.08, ge=0.0, le=0.5) + require_explicit_room_ownership: Literal[True] = True + require_connected_room_graph: Literal[True] = True + require_portal_bound_route: Literal[True] = True + require_door_sweep_clearance: Literal[True] = True + require_no_furniture_overlap: Literal[True] = True + require_route_clearance: Literal[True] = True + natural_perturbation: NaturalPerturbationPolicy = Field( + default_factory=NaturalPerturbationPolicy + ) + asset_binding_mode: Literal["proxy", "asset_first"] = "proxy" + asset_descriptor_index: str | None = None + asset_selection_path: str | None = None + asset_selection_sha256: str | None = None + layout_truth_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$") + room_shell_source: Literal["multi_room_metric_layout_spec"] = "multi_room_metric_layout_spec" + furniture_agent_pose_authority: Literal["none"] = "none" + coordinate_solver: str = "metric_v3_multi_room_front_aware" + + @model_validator(mode="after") + def validate_building(self) -> MultiRoomMetricLayoutSpec: + tolerance = 1.0e-6 + if self.robot_constraints_enabled: + from packages.robots.task_constraints import get_task_constraints + minimum_width = max(.75, get_task_constraints(self.robot_id)["carry_corridor_width_m"]) + if self.route_width_m < minimum_width: + raise ValueError(f"robot_constraints:route_width:{self.route_width_m}<{minimum_width}") + room_ids = [room.room_id for room in self.rooms] + if len(room_ids) != len(set(room_ids)): + raise ValueError("multi-room room IDs must be unique") + room_by_id = {room.room_id: room for room in self.rooms} + room_polygons = { + room.room_id: _polygon( + room.floor_polygon_xy_m, + label=f"room {room.room_id}", + ) + for room in self.rooms + } + for index, room_a in enumerate(self.rooms): + for room_b in self.rooms[index + 1 :]: + overlap = ( + room_polygons[room_a.room_id].intersection(room_polygons[room_b.room_id]).area + ) + if overlap > tolerance: + raise ValueError(f"rooms overlap: {room_a.room_id}, {room_b.room_id}") + + portal_ids = [portal.portal_id for portal in self.portals] + if len(portal_ids) != len(set(portal_ids)): + raise ValueError("multi-room portal IDs must be unique") + portal_by_id = {portal.portal_id: portal for portal in self.portals} + adjacency: dict[str, set[str]] = {room_id: set() for room_id in room_ids} + for portal in self.portals: + if unknown := {portal.room_a_id, portal.room_b_id} - set(room_ids): + raise ValueError( + f"portal {portal.portal_id} references unknown rooms: {sorted(unknown)}" + ) + room_a = room_polygons[portal.room_a_id] + room_b = room_polygons[portal.room_b_id] + shared = room_a.boundary.intersection(room_b.boundary) + opening = _segment( + portal.opening_segment_xy_m, + label=f"portal {portal.portal_id}", + ) + if shared.length + tolerance < portal.clear_width_m or not shared.buffer( + tolerance, + cap_style=2, + ).covers(opening): + raise ValueError( + f"portal {portal.portal_id} is not contained by a shared room boundary" + ) + if ( + abs( + room_by_id[portal.room_a_id].floor_elevation_m + - room_by_id[portal.room_b_id].floor_elevation_m + ) + > 0.02 + ): + raise ValueError( + f"portal {portal.portal_id} connects incompatible floor elevations" + ) + if portal.clear_width_m + tolerance < self.route_width_m: + raise ValueError(f"portal {portal.portal_id} is narrower than the required route") + if portal.clear_height_m > min( + room_by_id[portal.room_a_id].height_m, + room_by_id[portal.room_b_id].height_m, + ): + raise ValueError(f"portal {portal.portal_id} is taller than its rooms") + if portal.kind == "door": + swing_room = room_polygons[portal.swing_room_id or ""] + sweep = _polygon( + portal.swing_polygon_xy_m, + label=f"door portal {portal.portal_id} sweep", + ) + if not swing_room.buffer(0.025).covers(sweep): + raise ValueError(f"door {portal.portal_id} sweep leaves {portal.swing_room_id}") + adjacency[portal.room_a_id].add(portal.room_b_id) + adjacency[portal.room_b_id].add(portal.room_a_id) + + visited: set[str] = set() + pending = [room_ids[0]] + while pending: + room_id = pending.pop() + if room_id in visited: + continue + visited.add(room_id) + pending.extend(adjacency[room_id] - visited) + if visited != set(room_ids): + raise ValueError( + f"multi-room topology is disconnected: {sorted(set(room_ids) - visited)}" + ) + + building = unary_union(list(room_polygons.values())) + if not isinstance(building, Polygon): + raise ValueError("multi-room floor union must form one connected building polygon") + + zone_ids = [zone.zone_id for zone in self.zones] + if len(zone_ids) != len(set(zone_ids)): + raise ValueError("multi-room zone IDs must be unique") + zone_by_id = {zone.zone_id: zone for zone in self.zones} + for zone in self.zones: + if zone.room_id not in room_by_id: + raise ValueError(f"zone {zone.zone_id} references an unknown room") + value = _polygon(zone.polygon_xy_m, label=f"zone {zone.zone_id}") + if not room_polygons[zone.room_id].buffer(tolerance).covers(value): + raise ValueError(f"zone {zone.zone_id} leaves room {zone.room_id}") + + entity_ids = [entity.entity_id for entity in self.entities] + if len(entity_ids) != len(set(entity_ids)): + raise ValueError("multi-room entity IDs must be unique") + known_entities = set(entity_ids) + root_footprints: dict[str, Polygon] = {} + for entity in self.entities: + if entity.zone_id not in zone_by_id: + raise ValueError(f"entity {entity.entity_id} references an unknown zone") + zone = zone_by_id[entity.zone_id] + if entity.room_id != zone.room_id: + raise ValueError(f"entity {entity.entity_id} room ownership differs from its zone") + declared_zone = _polygon( + entity.zone_polygon_xy_m, + label=f"entity {entity.entity_id} zone", + ) + actual_zone = _polygon(zone.polygon_xy_m, label=f"zone {zone.zone_id}") + if not actual_zone.equals_exact(declared_zone, tolerance=1.0e-8): + raise ValueError(f"entity {entity.entity_id} zone polygon differs from zone") + footprint = _oriented_footprint(entity) + if not room_polygons[zone.room_id].buffer(tolerance).covers(footprint): + raise ValueError(f"entity {entity.entity_id} leaves room {zone.room_id}") + if entity.parent_entity_id is None: + root_footprints[entity.entity_id] = footprint + if unknown := { + entity.parent_entity_id + for entity in self.entities + if entity.parent_entity_id and entity.parent_entity_id not in known_entities + }: + raise ValueError(f"multi-room entity parents are unknown: {sorted(unknown)}") + if unknown := { + entity.facing_target_entity_id + for entity in self.entities + if entity.facing_target_entity_id + and entity.facing_target_entity_id not in known_entities + }: + raise ValueError(f"multi-room facing targets are unknown: {sorted(unknown)}") + if unknown := { + entity.near_entity_id + for entity in self.entities + if entity.near_entity_id and entity.near_entity_id not in known_entities + }: + raise ValueError(f"multi-room near targets are unknown: {sorted(unknown)}") + + root_items = sorted(root_footprints.items()) + for index, (entity_a, footprint_a) in enumerate(root_items): + for entity_b, footprint_b in root_items[index + 1 :]: + if footprint_a.intersection(footprint_b).area > tolerance: + raise ValueError(f"root furniture overlaps: {entity_a}, {entity_b}") + + route = _polygon(self.route_polygon_xy_m, label="multi-room route") + if not building.buffer(tolerance).covers(route): + raise ValueError("multi-room route leaves the building floor union") + if self.robot_start_room_id not in room_by_id: + raise ValueError("robot start room is unknown") + start = Point(self.robot_start_xy_m) + if not route.buffer(tolerance).covers(start): + raise ValueError("multi-room robot start must lie on the route") + if not room_polygons[self.robot_start_room_id].buffer(tolerance).covers(start): + raise ValueError("robot start does not lie in robot_start_room_id") + if self.route_room_ids[0] != self.robot_start_room_id: + raise ValueError("route_room_ids must begin at robot_start_room_id") + if len(self.route_portal_ids) != len(self.route_room_ids) - 1: + raise ValueError("route portal sequence must connect every route room transition") + if unknown := set(self.route_room_ids) - set(room_ids): + raise ValueError(f"route references unknown rooms: {sorted(unknown)}") + if unknown := set(self.route_portal_ids) - set(portal_ids): + raise ValueError(f"route references unknown portals: {sorted(unknown)}") + for index, portal_id in enumerate(self.route_portal_ids): + expected_rooms = { + self.route_room_ids[index], + self.route_room_ids[index + 1], + } + portal = portal_by_id[portal_id] + if {portal.room_a_id, portal.room_b_id} != expected_rooms: + raise ValueError(f"route portal {portal_id} does not connect its consecutive rooms") + if not route.buffer(tolerance).covers(portal_midpoint(portal)): + raise ValueError(f"route does not pass through portal {portal_id}") + shared = room_polygons[portal.room_a_id].boundary.intersection( + room_polygons[portal.room_b_id].boundary + ) + crossing = route.intersection(shared) + opening = LineString(portal.opening_segment_xy_m) + if crossing.is_empty or not opening.buffer( + tolerance, + cap_style=2, + ).covers(crossing): + raise ValueError( + f"route crosses a solid shared wall outside portal {portal_id}" + ) + for room_id in self.route_room_ids: + if route.intersection(room_polygons[room_id]).area <= tolerance: + raise ValueError(f"route does not enter room {room_id}") + for entity_id, footprint in root_footprints.items(): + if route.intersection(footprint).area > tolerance: + raise ValueError(f"route intersects root furniture: {entity_id}") + for portal in self.portals: + if portal.kind != "door": + continue + swing_room = room_polygons[portal.swing_room_id or ""] + leaf = door_leaf_polygon(portal, swing_room) + if route.intersection(leaf).area > tolerance: + raise ValueError(f"open door leaf blocks route: {portal.portal_id}") + sweep = _polygon( + portal.swing_polygon_xy_m, + label=f"door portal {portal.portal_id} sweep", + ) + for entity_id, footprint in root_footprints.items(): + if sweep.intersection(footprint).area > tolerance: + raise ValueError( + f"door {portal.portal_id} sweep intersects root furniture: {entity_id}" + ) + + if self.asset_binding_mode == "asset_first": + if not self.asset_descriptor_index: + raise ValueError("asset-first multi-room layout requires descriptor index") + if not self.asset_selection_path or not self.asset_selection_sha256: + raise ValueError("asset-first multi-room layout requires frozen selection") + for entity in self.entities: + required_values = { + "asset_id": entity.asset_id, + "asset_sha256": entity.asset_sha256, + "asset_descriptor_ref": entity.asset_descriptor_ref, + "dimensions_m": entity.dimensions_m, + "category": entity.category, + "display_name": entity.display_name, + "asset_status": entity.asset_status, + "layout_reserve_envelope_xy_m": entity.layout_reserve_envelope_xy_m, + } + missing = [key for key, value in required_values.items() if not value] + if missing or not entity.asset_locked: + raise ValueError( + f"{entity.entity_id}: incomplete multi-room asset binding: {missing}" + ) + return self + + @property + def room_by_id(self) -> dict[str, MetricRoom]: + return {room.room_id: room for room in self.rooms} + + @property + def zone_by_id(self) -> dict[str, MultiRoomMetricZone]: + return {zone.zone_id: zone for zone in self.zones} + + @property + def entity_by_id(self) -> dict[str, MetricEntityLayout]: + return {entity.entity_id: entity for entity in self.entities} + + @property + def building_polygon(self) -> Polygon: + value = unary_union([Polygon(room.floor_polygon_xy_m) for room in self.rooms]) + if not isinstance(value, Polygon): + raise ValueError("multi-room building polygon is not connected") + return value + + @property + def room_dimensions_m(self) -> tuple[float, float, float]: + minimum_x, minimum_y, maximum_x, maximum_y = self.building_polygon.bounds + return ( + maximum_x - minimum_x, + maximum_y - minimum_y, + max(room.floor_elevation_m + room.height_m for room in self.rooms), + ) + + @property + def room_polygon_mode(self) -> Literal["multi_room_union"]: + return "multi_room_union" + + @property + def room_polygon_xy_m(self) -> list[Point2]: + return [(float(x), float(y)) for x, y in list(self.building_polygon.exterior.coords)[:-1]] + + +def multi_room_wall_runs(layout: MultiRoomMetricLayoutSpec) -> list[WallRun]: + boundaries = unary_union([Polygon(room.floor_polygon_xy_m).boundary for room in layout.rooms]) + cuts = unary_union( + [ + LineString(portal.opening_segment_xy_m).buffer( + max(1.0e-5, layout.wall_thickness_m * 1.0e-3), + cap_style=2, + ) + for portal in layout.portals + ] + ) + remaining = boundaries.difference(cuts) + room_polygons = {room.room_id: Polygon(room.floor_polygon_xy_m) for room in layout.rooms} + runs: list[WallRun] = [] + for line in _line_parts(remaining): + coordinates = list(line.coords) + for start, end in zip(coordinates, coordinates[1:], strict=False): + segment = LineString([start, end]) + if segment.length <= 0.015: + continue + midpoint = segment.interpolate(0.5, normalized=True) + owners = [ + room + for room in layout.rooms + if room_polygons[room.room_id].boundary.distance(midpoint) <= 1.0e-5 + ] + if not owners: + raise ValueError("wall run has no owning room") + runs.append( + WallRun( + start_xy_m=(float(start[0]), float(start[1])), + end_xy_m=(float(end[0]), float(end[1])), + floor_elevation_m=max(room.floor_elevation_m for room in owners), + height_m=min(room.height_m for room in owners), + ) + ) + return sorted( + runs, + key=lambda item: ( + round(item.start_xy_m[0], 8), + round(item.start_xy_m[1], 8), + round(item.end_xy_m[0], 8), + round(item.end_xy_m[1], 8), + ), + ) + + +def build_multi_room_validation_report( + layout: MultiRoomMetricLayoutSpec, +) -> dict[str, Any]: + adjacency: dict[str, set[str]] = {room.room_id: set() for room in layout.rooms} + portal_checks: dict[str, bool] = {} + room_polygons = {room.room_id: Polygon(room.floor_polygon_xy_m) for room in layout.rooms} + for portal in layout.portals: + adjacency[portal.room_a_id].add(portal.room_b_id) + adjacency[portal.room_b_id].add(portal.room_a_id) + shared = room_polygons[portal.room_a_id].boundary.intersection( + room_polygons[portal.room_b_id].boundary + ) + portal_checks[portal.portal_id] = shared.buffer(1.0e-6).covers( + LineString(portal.opening_segment_xy_m) + ) + visited: set[str] = set() + pending = [layout.rooms[0].room_id] + while pending: + room_id = pending.pop() + if room_id in visited: + continue + visited.add(room_id) + pending.extend(adjacency[room_id] - visited) + + root_footprints = { + entity.entity_id: _oriented_footprint(entity) + for entity in layout.entities + if entity.parent_entity_id is None + } + root_items = sorted(root_footprints.items()) + furniture_non_overlap = all( + first.intersection(second).area <= 1.0e-6 + for index, (_first_id, first) in enumerate(root_items) + for _second_id, second in root_items[index + 1 :] + ) + route = Polygon(layout.route_polygon_xy_m) + building = unary_union(list(room_polygons.values())) + wall_runs = multi_room_wall_runs(layout) + opening_checks = { + portal.portal_id: all( + LineString((run.start_xy_m, run.end_xy_m)).distance(portal_midpoint(portal)) + >= portal.clear_width_m / 2.0 - 1.0e-4 + for run in wall_runs + ) + for portal in layout.portals + } + route_opening_checks = {} + for portal in layout.portals: + shared = room_polygons[portal.room_a_id].boundary.intersection( + room_polygons[portal.room_b_id].boundary + ) + crossing = route.intersection(shared) + opening = LineString(portal.opening_segment_xy_m) + route_opening_checks[portal.portal_id] = not crossing.is_empty and opening.buffer( + 1.0e-6, + cap_style=2, + ).covers(crossing) + door_sweep_checks: dict[str, bool] = {} + door_leaf_checks: dict[str, bool] = {} + for portal in layout.portals: + if portal.kind != "door": + continue + sweep = Polygon(portal.swing_polygon_xy_m) + door_sweep_checks[portal.portal_id] = all( + sweep.intersection(footprint).area <= 1.0e-6 for footprint in root_footprints.values() + ) + swing_room = room_polygons[portal.swing_room_id or ""] + leaf = door_leaf_polygon(portal, swing_room) + door_leaf_checks[portal.portal_id] = route.intersection(leaf).area <= 1.0e-6 + + route_chain_valid = len(layout.route_portal_ids) == len(layout.route_room_ids) - 1 + if route_chain_valid: + portal_by_id = {portal.portal_id: portal for portal in layout.portals} + route_chain_valid = all( + portal_id in portal_by_id + and { + portal_by_id[portal_id].room_a_id, + portal_by_id[portal_id].room_b_id, + } + == {layout.route_room_ids[index], layout.route_room_ids[index + 1]} + for index, portal_id in enumerate(layout.route_portal_ids) + ) + checks = { + "room_count_at_least_two": len(layout.rooms) >= 2, + "room_graph_connected": visited == set(adjacency), + "room_interiors_do_not_overlap": all( + first.intersection(second).area <= 1.0e-6 + for index, first in enumerate(room_polygons.values()) + for second in list(room_polygons.values())[index + 1 :] + ), + "all_portals_on_shared_boundaries": all(portal_checks.values()), + "all_portals_clear_route_width": all( + portal.clear_width_m + 1.0e-6 >= layout.route_width_m for portal in layout.portals + ), + "route_is_single_connected_polygon": ( + isinstance(route, Polygon) and route.is_valid and not route.is_empty + ), + "route_stays_inside_building": building.buffer(1.0e-6).covers(route), + "route_covers_robot_start": route.covers(Point(layout.robot_start_xy_m)), + "route_portal_chain_complete": route_chain_valid, + "route_crosses_shared_walls_only_at_portals": all(route_opening_checks.values()), + "route_clears_root_furniture": all( + route.intersection(footprint).area <= 1.0e-6 for footprint in root_footprints.values() + ), + "root_furniture_non_overlapping": furniture_non_overlap, + "door_sweeps_clear_root_furniture": all(door_sweep_checks.values()), + "open_door_leaves_clear_route": all(door_leaf_checks.values()), + "internal_wall_openings_emitted": bool(wall_runs) and all(opening_checks.values()), + } + return { + "schema_version": "1.0", + "validator": "multi_room_metric_v3_hard_checks", + "passed": all(checks.values()), + "checks": checks, + "room_count": len(layout.rooms), + "portal_count": len(layout.portals), + "route_room_ids": layout.route_room_ids, + "route_portal_ids": layout.route_portal_ids, + "adjacency": {key: sorted(value) for key, value in sorted(adjacency.items())}, + "portal_checks": portal_checks, + "opening_checks": opening_checks, + "route_opening_checks": route_opening_checks, + "door_sweep_checks": door_sweep_checks, + "door_leaf_checks": door_leaf_checks, + "wall_run_count": len(wall_runs), + } + + +class RoomProgram(_StrictModel): + room_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + room_type: str = Field(min_length=1) + dimensions_m: tuple[float, float, float] + + @model_validator(mode="after") + def validate_dimensions(self) -> RoomProgram: + if any(not math.isfinite(value) or value <= 0 for value in self.dimensions_m): + raise ValueError(f"room program {self.room_id} dimensions must be positive") + return self + + +RoomSide = Literal["east", "north", "west", "south"] + + +class RoomConnectionProgram(_StrictModel): + portal_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + room_a_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + room_b_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + kind: Literal["door", "open_passage"] = "door" + clear_width_m: float = Field(default=1.10, ge=0.80) + clear_height_m: float = Field(default=2.10, gt=0.0) + preferred_side_of_room_a: RoomSide | None = None + hinge_side: Literal["left", "right"] = "left" + swing_room_id: str | None = None + initial_open_fraction: float = Field(default=1.0, ge=0.0, le=1.0) + + @model_validator(mode="after") + def validate_rooms(self) -> RoomConnectionProgram: + if self.room_a_id == self.room_b_id: + raise ValueError("room connection requires two different rooms") + if self.swing_room_id and self.swing_room_id not in { + self.room_a_id, + self.room_b_id, + }: + raise ValueError("room connection swing_room_id must be an endpoint") + return self + + +class MultiRoomEntityRequest(_StrictModel): + entity_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + room_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + center_uv: Point2 + footprint_m: Point2 + yaw_deg: float = 0.0 + parent_entity_id: str | None = None + mount: str = "FLOOR" + base_elevation_m: float = Field(default=0.0, ge=0.0) + dimensions_m: tuple[float, float, float] | None = None + category: str | None = None + display_name: str | None = None + + @model_validator(mode="after") + def validate_placement(self) -> MultiRoomEntityRequest: + if any(value < 0.0 or value > 1.0 for value in self.center_uv): + raise ValueError(f"entity {self.entity_id} center_uv must stay in [0, 1]") + if any(not math.isfinite(value) or value <= 0 for value in self.footprint_m): + raise ValueError(f"entity {self.entity_id} footprint must be positive") + return self + + +class MultiRoomGenerationRequest(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + request_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + rooms: list[RoomProgram] = Field(min_length=2) + connections: list[RoomConnectionProgram] = Field(min_length=1) + route_room_ids: list[str] = Field(min_length=2) + entities: list[MultiRoomEntityRequest] = Field(min_length=1) + robot_start_uv: Point2 = (0.5, 0.5) + route_width_m: float = Field(default=0.85, ge=0.75) + robot_id: str | None = None + robot_constraints_enabled: bool = True + wall_thickness_m: float = Field(default=0.10, gt=0.0, le=0.30) + seed: int = 0 + + @model_validator(mode="after") + def validate_program(self) -> MultiRoomGenerationRequest: + from packages.robots.task_constraints import get_task_constraints + if self.robot_constraints_enabled: + object.__setattr__(self, "route_width_m", max( + self.route_width_m, get_task_constraints(self.robot_id)["carry_corridor_width_m"])) + room_ids = [room.room_id for room in self.rooms] + if len(room_ids) != len(set(room_ids)): + raise ValueError("room program IDs must be unique") + known = set(room_ids) + if len(self.connections) != len(self.rooms) - 1: + raise ValueError("automatic multi-room packing requires a tree topology") + portal_ids = [item.portal_id for item in self.connections] + if len(portal_ids) != len(set(portal_ids)): + raise ValueError("room connection portal IDs must be unique") + edge_pairs = [ + frozenset((connection.room_a_id, connection.room_b_id)) + for connection in self.connections + ] + if len(edge_pairs) != len(set(edge_pairs)): + raise ValueError("room connection endpoint pairs must be unique") + adjacency: dict[str, set[str]] = {room_id: set() for room_id in room_ids} + for connection in self.connections: + if unknown := {connection.room_a_id, connection.room_b_id} - known: + raise ValueError(f"room connection references unknown rooms: {sorted(unknown)}") + if connection.clear_width_m + 1.0e-6 < self.route_width_m: + raise ValueError(f"portal {connection.portal_id} is narrower than route_width_m") + adjacency[connection.room_a_id].add(connection.room_b_id) + adjacency[connection.room_b_id].add(connection.room_a_id) + visited: set[str] = set() + pending = [room_ids[0]] + while pending: + room_id = pending.pop() + if room_id in visited: + continue + visited.add(room_id) + pending.extend(adjacency[room_id] - visited) + if visited != known: + raise ValueError(f"room connection graph is disconnected: {sorted(known - visited)}") + if unknown := set(self.route_room_ids) - known: + raise ValueError(f"route program references unknown rooms: {sorted(unknown)}") + if len(self.route_room_ids) != len(set(self.route_room_ids)): + raise ValueError("automatic route_room_ids must form a simple room path") + for room_a, room_b in zip( + self.route_room_ids, + self.route_room_ids[1:], + strict=False, + ): + if frozenset((room_a, room_b)) not in edge_pairs: + raise ValueError(f"route rooms are not adjacent: {room_a}, {room_b}") + entity_ids = [entity.entity_id for entity in self.entities] + if len(entity_ids) != len(set(entity_ids)): + raise ValueError("multi-room entity request IDs must be unique") + if unknown := {entity.room_id for entity in self.entities} - known: + raise ValueError(f"entity requests reference unknown rooms: {sorted(unknown)}") + if any(value < 0.0 or value > 1.0 for value in self.robot_start_uv): + raise ValueError("robot_start_uv must stay in [0, 1]") + return self + + +_SIDES: tuple[RoomSide, ...] = ("east", "north", "west", "south") +_OPPOSITE: dict[RoomSide, RoomSide] = { + "east": "west", + "west": "east", + "north": "south", + "south": "north", +} + + +def _attached_box( + anchor: Polygon, + dimensions: tuple[float, float, float], + side: RoomSide, +) -> Polygon: + minimum_x, minimum_y, maximum_x, maximum_y = anchor.bounds + width, depth, _height = dimensions + center_x = (minimum_x + maximum_x) / 2.0 + center_y = (minimum_y + maximum_y) / 2.0 + if side == "east": + return box(maximum_x, center_y - depth / 2.0, maximum_x + width, center_y + depth / 2.0) + if side == "west": + return box(minimum_x - width, center_y - depth / 2.0, minimum_x, center_y + depth / 2.0) + if side == "north": + return box(center_x - width / 2.0, maximum_y, center_x + width / 2.0, maximum_y + depth) + if side == "south": + return box(center_x - width / 2.0, minimum_y - depth, center_x + width / 2.0, minimum_y) + raise ValueError(f"unknown attachment side: {side}") + + +def _longest_shared_boundary(first: Polygon, second: Polygon) -> LineString: + parts = _line_parts(first.boundary.intersection(second.boundary)) + if not parts: + raise ValueError("attached rooms have no shared boundary") + return max(parts, key=lambda item: item.length) + + +def _centered_subsegment(line: LineString, width_m: float) -> tuple[Point2, Point2]: + if line.length < width_m + 0.10: + raise ValueError("shared room boundary is too short for portal clearance") + midpoint = line.length / 2.0 + start = line.interpolate(midpoint - width_m / 2.0) + end = line.interpolate(midpoint + width_m / 2.0) + return ((float(start.x), float(start.y)), (float(end.x), float(end.y))) + + +def generate_multi_room_layout( + request: MultiRoomGenerationRequest, +) -> MultiRoomMetricLayoutSpec: + programs = {room.room_id: room for room in request.rooms} + start_room_id = request.route_room_ids[0] + start_program = programs[start_room_id] + width, depth, _height = start_program.dimensions_m + placed: dict[str, Polygon] = { + start_room_id: box(-width / 2.0, -depth / 2.0, width / 2.0, depth / 2.0) + } + pending = list(request.connections) + while pending: + progressed = False + for connection in list(pending): + a_placed = connection.room_a_id in placed + b_placed = connection.room_b_id in placed + if a_placed == b_placed: + continue + anchor_id = connection.room_a_id if a_placed else connection.room_b_id + new_id = connection.room_b_id if a_placed else connection.room_a_id + preferred = connection.preferred_side_of_room_a + if preferred and not a_placed: + preferred = _OPPOSITE[preferred] + rotation = (request.seed + len(placed) * 3) % len(_SIDES) + fallback = [*_SIDES[rotation:], *_SIDES[:rotation]] + sides = ([preferred] if preferred else []) + [ + side for side in fallback if side != preferred + ] + selected: Polygon | None = None + for side in sides: + candidate = _attached_box( + placed[anchor_id], + programs[new_id].dimensions_m, + side, + ) + if any(candidate.intersection(other).area > 1.0e-6 for other in placed.values()): + continue + unintended_touch = any( + other_id != anchor_id and candidate.boundary.intersection(other).length > 1.0e-6 + for other_id, other in placed.items() + ) + if unintended_touch: + continue + shared = _longest_shared_boundary(placed[anchor_id], candidate) + if shared.length < connection.clear_width_m + 0.10: + continue + selected = candidate + break + if selected is None: + raise ValueError( + f"could not place room {new_id} without overlap around {anchor_id}" + ) + placed[new_id] = selected + pending.remove(connection) + progressed = True + if not progressed: + raise ValueError("room connection order cannot reach every room from route start") + + rooms = [ + MetricRoom( + room_id=program.room_id, + room_type=program.room_type, + floor_polygon_xy_m=[ + (float(x), float(y)) for x, y in list(placed[program.room_id].exterior.coords)[:-1] + ], + height_m=program.dimensions_m[2], + ) + for program in request.rooms + ] + portals: list[MetricPortal] = [] + for connection in request.connections: + shared = _longest_shared_boundary( + placed[connection.room_a_id], + placed[connection.room_b_id], + ) + opening = _centered_subsegment(shared, connection.clear_width_m) + if connection.kind == "door": + swing_room_id = connection.swing_room_id or connection.room_a_id + sweep = door_swing_polygon( + opening_segment_xy_m=opening, + hinge_side=connection.hinge_side, + open_angle_deg=90.0, + swing_room=placed[swing_room_id], + portal_id=connection.portal_id, + ) + portals.append( + MetricPortal( + portal_id=connection.portal_id, + kind="door", + room_a_id=connection.room_a_id, + room_b_id=connection.room_b_id, + opening_segment_xy_m=opening, + clear_width_m=connection.clear_width_m, + clear_height_m=connection.clear_height_m, + wall_thickness_m=request.wall_thickness_m, + hinge_side=connection.hinge_side, + swing_room_id=swing_room_id, + swing_polygon_xy_m=sweep, + initial_open_fraction=connection.initial_open_fraction, + ) + ) + else: + portals.append( + MetricPortal( + portal_id=connection.portal_id, + kind="open_passage", + room_a_id=connection.room_a_id, + room_b_id=connection.room_b_id, + opening_segment_xy_m=opening, + clear_width_m=connection.clear_width_m, + clear_height_m=connection.clear_height_m, + wall_thickness_m=request.wall_thickness_m, + hinge_side=None, + swing_room_id=None, + swing_polygon_xy_m=[], + ) + ) + + zones: list[MultiRoomMetricZone] = [] + for room in rooms: + inset = placed[room.room_id].buffer( + -(request.wall_thickness_m + 0.05), + join_style="mitre", + ) + if not isinstance(inset, Polygon) or inset.is_empty: + raise ValueError(f"room {room.room_id} is too small for an interior zone") + zones.append( + MultiRoomMetricZone( + zone_id=f"{room.room_id}_main", + room_id=room.room_id, + polygon_xy_m=[(float(x), float(y)) for x, y in list(inset.exterior.coords)[:-1]], + ) + ) + zone_by_room = {zone.room_id: zone for zone in zones} + entities: list[MetricEntityLayout] = [] + for entity in request.entities: + zone = zone_by_room[entity.room_id] + zone_polygon = Polygon(zone.polygon_xy_m) + minimum_x, minimum_y, maximum_x, maximum_y = zone_polygon.bounds + center = ( + minimum_x + entity.center_uv[0] * (maximum_x - minimum_x), + minimum_y + entity.center_uv[1] * (maximum_y - minimum_y), + ) + entities.append( + MetricEntityLayout( + entity_id=entity.entity_id, + room_id=entity.room_id, + center_xy_m=center, + yaw_deg=entity.yaw_deg, + footprint_m=entity.footprint_m, + zone_id=zone.zone_id, + zone_polygon_xy_m=zone.polygon_xy_m, + parent_entity_id=entity.parent_entity_id, + mount=entity.mount, + base_elevation_m=entity.base_elevation_m, + dimensions_m=entity.dimensions_m, + category=entity.category, + display_name=entity.display_name, + ) + ) + + portal_by_rooms = { + frozenset((portal.room_a_id, portal.room_b_id)): portal for portal in portals + } + route_portals = [ + portal_by_rooms[frozenset((room_a, room_b))] + for room_a, room_b in zip( + request.route_room_ids, + request.route_room_ids[1:], + strict=False, + ) + ] + waypoints: list[Point2] = [] + for index, room_id in enumerate(request.route_room_ids): + centroid = placed[room_id].centroid + waypoints.append((float(centroid.x), float(centroid.y))) + if index < len(route_portals): + middle = portal_midpoint(route_portals[index]) + waypoints.append((float(middle.x), float(middle.y))) + route_geometry = ( + LineString(waypoints) + .buffer( + request.route_width_m / 2.0, + cap_style=2, + join_style=2, + ) + .intersection(unary_union(list(placed.values())).buffer(1.0e-8)) + ) + route_parts = _polygon_parts(route_geometry) + if len(route_parts) != 1: + raise ValueError("generated cross-room route is not one connected polygon") + route_polygon = route_parts[0] + start_polygon = placed[start_room_id] + min_x, min_y, max_x, max_y = start_polygon.bounds + robot_start = ( + min_x + request.robot_start_uv[0] * (max_x - min_x), + min_y + request.robot_start_uv[1] * (max_y - min_y), + ) + request_hash = _canonical_sha256(request.model_dump(mode="json")) + layout = MultiRoomMetricLayoutSpec( + source_blueprint=f"metric-v3:generated:{request.request_id}", + source_blueprint_sha256=request_hash, + source_hints_sha256=request_hash, + rooms=rooms, + portals=portals, + zones=zones, + entities=entities, + route_width_m=request.route_width_m, + robot_id=request.robot_id, + robot_constraints_enabled=request.robot_constraints_enabled, + route_polygon_xy_m=[ + (float(x), float(y)) for x, y in list(route_polygon.exterior.coords)[:-1] + ], + route_room_ids=request.route_room_ids, + route_portal_ids=[portal.portal_id for portal in route_portals], + robot_start_xy_m=robot_start, + robot_start_room_id=start_room_id, + wall_thickness_m=request.wall_thickness_m, + ) + truth = _canonical_sha256(layout.model_dump(mode="json", exclude={"layout_truth_sha256"})) + return layout.model_copy(update={"layout_truth_sha256": truth}) + + +__all__ = [ + "MetricPortal", + "MetricRoom", + "MultiRoomEntityRequest", + "MultiRoomGenerationRequest", + "MultiRoomMetricLayoutSpec", + "MultiRoomMetricZone", + "RoomConnectionProgram", + "RoomProgram", + "WallRun", + "build_multi_room_validation_report", + "door_leaf_polygon", + "door_swing_polygon", + "generate_multi_room_layout", + "multi_room_wall_runs", + "portal_midpoint", +] diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/orchestrator.py b/docs/reproduction/public_conversion_code/packages/scene_generation/orchestrator.py new file mode 100644 index 0000000000000000000000000000000000000000..6fd7d4c4236ac7ef291c73ca9df9053769c453b1 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/orchestrator.py @@ -0,0 +1,1137 @@ +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import shlex +import shutil +import subprocess +import sys +import time +from enum import StrEnum +from pathlib import Path + +from packages.adapters.embodiedgen import EmbodiedGenAdapter, EmbodiedGenSettings +from packages.adapters.scenesmith import SceneSmithAdapter, SceneSmithSettings +from packages.core.files import atomic_write_text +from packages.scenarios.router import build_scene_for_task +from packages.scene_generation.compiler import SceneRequestCompiler +from packages.scene_generation.design_contract import verify_case_design_contract +from packages.scene_generation.metric_layout import load_metric_layout_spec_from_contract +from packages.schemas.models import RobotSpawnSpec, SceneLayerPlan, SceneManifest, TaskSpec +from packages.usd_composer.composer import LAYER_NAMES + + +def _resolve_blender_executable() -> str: + for variable in ("BLENDER_BIN", "BLENDER"): + if configured := os.environ.get(variable): + return configured + if command := os.environ.get("SCENESMITH_COMMAND"): + tokens = shlex.split(command) + if "--blender" in tokens: + index = tokens.index("--blender") + 1 + if index < len(tokens): + return tokens[index] + if data_root := os.environ.get("RHG_DATA_ROOT"): + bundled = Path(data_root) / "tools" / "blender-4.3.2-linux-x64" / "blender" + if bundled.is_file(): + return str(bundled) + return shutil.which("blender") or "blender" + + +class GenerationBackend(StrEnum): + AUTO = "auto" + METRIC_V2 = "metric_v2" + DETERMINISTIC = "deterministic" + SCENESMITH = "scenesmith" + + @property + def resolved(self) -> GenerationBackend: + # ``auto`` is accepted only for backward-compatible inputs. Resolution + # happens once, before work starts, and never depends on a provider + # failure. Metric V2 is the production default. + return GenerationBackend.METRIC_V2 if self is GenerationBackend.AUTO else self + + @property + def is_metric(self) -> bool: + return self.resolved in { + GenerationBackend.METRIC_V2, + GenerationBackend.DETERMINISTIC, + } + + +class SceneGenerationOrchestrator: + def __init__( + self, + backend: GenerationBackend = GenerationBackend.METRIC_V2, + *, + scenesmith: SceneSmithAdapter | None = None, + embodiedgen: EmbodiedGenAdapter | None = None, + ) -> None: + self.backend = backend + self.scenesmith = scenesmith + self.embodiedgen = embodiedgen + + @classmethod + def from_env(cls) -> SceneGenerationOrchestrator: + backend = GenerationBackend(os.environ.get("RHG_SCENE_BACKEND", "metric_v2")) + settings = SceneSmithSettings.from_env() + adapter = SceneSmithAdapter() if settings.command else None + embodiedgen_settings = EmbodiedGenSettings.from_env() + embodiedgen = EmbodiedGenAdapter() if embodiedgen_settings.command else None + return cls(backend, scenesmith=adapter, embodiedgen=embodiedgen) + + def build( + self, + task: TaskSpec, + output_dir: Path, + robot_id: str, + robot_spawn: RobotSpawnSpec | None = None, + ) -> SceneManifest: + selected = self.backend.resolved + if selected in {GenerationBackend.METRIC_V2, GenerationBackend.DETERMINISTIC}: + return build_scene_for_task(task, output_dir, robot_id, robot_spawn=robot_spawn) + raise RuntimeError( + "SceneSmith geometry generation is disabled: generate locked geometry with " + "metric_v2, then invoke the scenesmith_visual provider on visual layers only" + ) + + def _build_scenesmith( + self, + task: TaskSpec, + output_dir: Path, + robot_id: str, + robot_spawn: RobotSpawnSpec | None, + ) -> SceneManifest: + if self.scenesmith is None: + raise RuntimeError("SceneSmith adapter is not configured") + contract_value = os.environ.get("RHG_CASE_DESIGN_CONTRACT") + if contract_value: + contract_path = Path(contract_value).resolve() + contract, _graph, _analysis = verify_case_design_contract( + contract_path, + prompt=task.natural_language, + task=task.model_dump(mode="json"), + ) + metric_layout = load_metric_layout_spec_from_contract(contract_path, contract) + if metric_layout is not None: + from packages.usd_composer.composer import _resolve_robot_spawn + + resolved_spawn = _resolve_robot_spawn(robot_id, robot_spawn) + robot_spawn = resolved_spawn.model_copy( + update={ + "translation_m": ( + float(metric_layout.robot_start_xy_m[0]), + float(metric_layout.robot_start_xy_m[1]), + float(resolved_spawn.translation_m[2]), + ) + } + ) + base = build_scene_for_task(task, output_dir, robot_id, robot_spawn=robot_spawn) + request = SceneRequestCompiler().compile(task) + embodiedgen_context: dict[str, object] | None = None + if self.embodiedgen is not None: + embodiedgen_manifest_path = self.embodiedgen.compile(task, output_dir / "embodiedgen") + embodiedgen_context = json.loads(embodiedgen_manifest_path.read_text(encoding="utf-8")) + repair_plan: dict[str, object] | None = None + if raw_repair_plan := os.environ.get("RHG_REPAIR_PLAN"): + parsed_repair_plan = json.loads(raw_repair_plan) + if not isinstance(parsed_repair_plan, dict): + raise ValueError("RHG_REPAIR_PLAN must contain a JSON object") + repair_plan = parsed_repair_plan + stage_dir = output_dir / "scenesmith" + external_bindings = { + entity.entity_id: base.entity_prim_paths[entity.entity_id] + for entity in task.entities + if ( + "procedural_geometry" in entity.attributes + or entity.attributes.get("scene_generation") == "external" + or ( + entity.role not in {"REGION", "ROBOT"} + and not base.entity_prim_paths[entity.entity_id].startswith("/World/Entities/") + ) + ) + } + stage_manifest_path = self.scenesmith.author( + request, + stage_dir, + context={ + "task": task.model_dump(mode="json"), + "robot_id": robot_id, + "robot_spawn": ( + robot_spawn.model_dump(mode="json") if robot_spawn is not None else None + ), + "embodiedgen": embodiedgen_context, + "external_entity_bindings": external_bindings, + "repair_plan": repair_plan, + }, + ) + stage_manifest = json.loads(stage_manifest_path.read_text(encoding="utf-8")) + if stage_manifest.get("status") != "complete": + raise RuntimeError("SceneSmith stage did not report complete status") + generated_usd = Path(str(stage_manifest.get("root_usd", ""))) + if not generated_usd.is_absolute(): + generated_usd = stage_dir / generated_usd + if not generated_usd.is_file(): + raise RuntimeError(f"SceneSmith root USD is missing: {generated_usd}") + object_bindings = stage_manifest.get("object_bindings") + dropped_optional = set(stage_manifest.get("dropped_optional_entities") or {}) + expected = {item.name for item in request.objects} - dropped_optional + if not isinstance(object_bindings, dict) or expected - set(object_bindings): + raise RuntimeError("SceneSmith did not bind every requested task entity") + + self._place_robot_in_scenesmith_room( + task=task, + output_dir=output_dir, + stage_dir=stage_dir, + stage_manifest=stage_manifest, + robot_id=robot_id, + declared_spawn=robot_spawn, + ) + + furniture_layer = output_dir / base.layer_plan.layers["furniture"] + generated_uri = os.path.relpath(generated_usd, start=furniture_layer.parent) + atomic_write_text( + furniture_layer, + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + 'over Xform "World" {\n' + ' def Xform "SceneSmithGenerated" (\n' + f" prepend references = @{generated_uri}@\n" + " ) {}\n}\n", + ) + semantics = output_dir / base.layer_plan.layers["semantics"] + atomic_write_text(semantics, self._semantics_layer(task, object_bindings)) + composed_robot_report = self._validate_composed_robot_placement(output_dir) + digest = hashlib.sha256() + digest.update(task.model_dump_json().encode()) + digest.update(stage_manifest_path.read_bytes()) + digest.update(generated_usd.read_bytes()) + generated_paths = stage_manifest.get("entity_prim_paths") + if generated_paths is None: + generated_paths = {} + elif not isinstance(generated_paths, dict) or expected - set(generated_paths): + raise RuntimeError("SceneSmith did not bind task entities to exported USD prims") + entity_prim_paths = {**base.entity_prim_paths, **generated_paths} + manifest = SceneManifest( + scene_id=f"scenesmith-{task.task_id.removeprefix('task-')}", + task_id=task.task_id, + random_seed=task.random_seed, + layer_plan=SceneLayerPlan(layers={name: f"layers/{name}.usda" for name in LAYER_NAMES}), + entity_prim_paths=entity_prim_paths, + robot_prim_path=base.robot_prim_path, + source_checkpoints={ + "generator": "SceneSmithAdapter/1.0", + "base_generator": base.source_checkpoints.get("generator", "USDComposer"), + "scenesmith_commit": str(stage_manifest.get("scenesmith_commit", "unknown")), + "stage_manifest": stage_manifest_path.relative_to(output_dir).as_posix(), + "robot_profile": robot_id, + **( + { + "robot_composed_validation": composed_robot_report.relative_to( + output_dir + ).as_posix() + } + if composed_robot_report is not None + else {} + ), + }, + content_hash=digest.hexdigest(), + ) + manifests_dir = output_dir / "manifests" + scene_manifest_path = manifests_dir / "scene.json" + task_manifest_path = manifests_dir / "task.json" + atomic_write_text(task_manifest_path, task.model_dump_json(indent=2) + "\n") + atomic_write_text( + scene_manifest_path, + json.dumps(manifest.model_dump(mode="json"), indent=2, sort_keys=True) + "\n", + ) + material_report = self._author_and_validate_pbr( + output_dir=output_dir, + task_manifest_path=task_manifest_path, + scene_manifest_path=scene_manifest_path, + ) + if material_report is not None: + digest.update(material_report.read_bytes()) + digest.update((output_dir / "layers" / "materials.usda").read_bytes()) + checkpoints = dict(manifest.source_checkpoints) + checkpoints["material_validation"] = material_report.relative_to(output_dir).as_posix() + manifest = manifest.model_copy( + update={ + "content_hash": digest.hexdigest(), + "source_checkpoints": checkpoints, + } + ) + atomic_write_text( + scene_manifest_path, + json.dumps(manifest.model_dump(mode="json"), indent=2, sort_keys=True) + "\n", + ) + # SceneSmith's internal global critic intentionally runs before the outer + # benchmark layers exist. Render a second release-grade evidence set from + # the fully composed root so the robot, task semantics, and PBR opinions + # are all visible to the Supervisor release critic. + stage_manifest = self._render_composed_critic_views( + output_dir, stage_dir, stage_manifest_path, stage_manifest + ) + return manifest + + @staticmethod + def _validate_composed_robot_placement(output_dir: Path) -> Path | None: + usd_python = os.environ.get("RHG_USD_PYTHON") + required = os.environ.get( + "RHG_REQUIRE_COMPOSED_ROBOT_VALIDATION", "1" if usd_python else "0" + ).casefold() in {"1", "true", "yes"} + if not usd_python: + if required: + raise RuntimeError( + "composed robot placement validation requires RHG_USD_PYTHON" + ) + return None + placement_audit = output_dir / "manifests" / "robot_placement_validation.json" + if not placement_audit.is_file(): + if required: + raise RuntimeError(f"robot placement audit is missing: {placement_audit}") + return None + report = output_dir / "manifests" / "robot_composed_placement_validation.json" + command = [ + usd_python, + str( + Path(__file__).resolve().parents[2] + / "scripts" + / "validate_composed_robot_placement.py" + ), + str(output_dir / "root.usda"), + str(placement_audit), + str(report), + ] + started = time.perf_counter() + result = subprocess.run( + command, + cwd=Path(__file__).resolve().parents[2], + capture_output=True, + text=True, + timeout=int(os.environ.get("RHG_COMPOSED_ROBOT_VALIDATION_TIMEOUT_S", "180")), + check=False, + ) + log_path = output_dir / "manifests" / "robot_composed_placement_validation.log.json" + atomic_write_text( + log_path, + json.dumps( + { + "schema_version": "1.0", + "command": command, + "duration_s": round(time.perf_counter() - started, 3), + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "report": report.relative_to(output_dir).as_posix(), + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + if result.returncode != 0 or not report.is_file(): + raise RuntimeError( + "composed robot placement validation failed " + f"(returncode={result.returncode}, log={log_path})" + ) + payload = json.loads(report.read_text(encoding="utf-8")) + if payload.get("passed") is not True: + raise RuntimeError(f"composed robot placement validation failed: {report}") + return report + + @staticmethod + def _render_composed_critic_views( + output_dir: Path, + stage_dir: Path, + stage_manifest_path: Path, + stage_manifest: dict[str, object], + ) -> dict[str, object]: + configured = os.environ.get("RHG_COMPOSED_CRITIC_VIEWS") + enabled = ( + configured.casefold() in {"1", "true", "yes"} + if configured is not None + else os.environ.get("RHG_COMPOSED_PREVIEW", "0").casefold() + in {"1", "true", "yes"} + ) + if not enabled: + return stage_manifest + + started = time.perf_counter() + views_dir = stage_dir / "final_composed_critic_views" + views_dir.mkdir(parents=True, exist_ok=True) + manifest_path = views_dir / "manifest.json" + renderer = ( + Path(__file__).resolve().parents[2] + / "scripts" + / "blender_render_global_critic_views.py" + ) + command = [ + _resolve_blender_executable(), + "--background", + "--threads", + os.environ.get("RHG_CRITIC_RENDER_THREADS", "8"), + "--python", + str(renderer), + "--", + str(output_dir / "root.usda"), + str(views_dir), + str(manifest_path), + ] + run_env = os.environ.copy() + # Blender 4.3 can segfault while resolving material bindings across the + # composed root's SceneSmith and robot layers. The evidence renderer + # imports those two immutable assets separately and applies the packaged + # robot transform, preserving native scene materials and formal USD. + run_env["RHG_CRITIC_SPLIT_COMPOSED_IMPORT"] = "1" + if data_root := os.environ.get("RHG_DATA_ROOT"): + runtime_libs = Path(data_root) / "tools" / "runtime-libs" + if runtime_libs.is_dir(): + current = run_env.get("LD_LIBRARY_PATH", "") + run_env["LD_LIBRARY_PATH"] = str(runtime_libs) + (f":{current}" if current else "") + maximum_sigsegv_retries = int( + os.environ.get("RHG_COMPOSED_CRITIC_SIGSEGV_RETRIES", "1") + ) + attempts: list[dict[str, object]] = [] + while True: + result = subprocess.run( + command, + cwd=Path(__file__).resolve().parents[2], + env=run_env, + capture_output=True, + text=True, + timeout=int(os.environ.get("RHG_COMPOSED_CRITIC_TIMEOUT_S", "1800")), + check=False, + ) + attempts.append( + { + "attempt": len(attempts) + 1, + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "manifest_exists": manifest_path.is_file(), + } + ) + retryable_sigsegv = ( + result.returncode == -11 + and not manifest_path.is_file() + and len(attempts) <= maximum_sigsegv_retries + ) + if not retryable_sigsegv: + break + failed_views_dir = stage_dir / ( + f"final_composed_critic_views.failed-sigsegv-{len(attempts)}" + ) + suffix = 1 + while failed_views_dir.exists(): + suffix += 1 + failed_views_dir = stage_dir / ( + "final_composed_critic_views.failed-sigsegv-" + f"{len(attempts)}-{suffix}" + ) + views_dir.rename(failed_views_dir) + views_dir.mkdir(parents=True, exist_ok=False) + log_path = stage_dir / "composed_critic_views.log" + atomic_write_text( + log_path, + json.dumps( + { + "schema_version": "1.0", + "command": command, + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "manifest_exists": manifest_path.is_file(), + "attempts": attempts, + "sigsegv_retries": len(attempts) - 1, + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + if result.returncode or not manifest_path.is_file(): + raise RuntimeError( + "composed critic view render failed " + f"(returncode={result.returncode}, log={log_path})" + ) + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + audit = payload.get("robot_visual_audit") or {} + views = payload.get("views") or {} + if ( + not isinstance(audit, dict) + or audit.get("passed") is not True + or not isinstance(views, dict) + or "robot_access" not in views + ): + raise RuntimeError(f"composed critic robot visibility failed: {manifest_path}") + duration = round(time.perf_counter() - started, 3) + updated = { + **stage_manifest, + "composed_critic_views_manifest": manifest_path.relative_to(stage_dir).as_posix(), + "composed_critic_views_source_usd": "../root.usda", + "composed_critic_views_duration_s": duration, + "composed_critic_views_log": log_path.name, + } + atomic_write_text(stage_manifest_path, json.dumps(updated, indent=2, sort_keys=True) + "\n") + timing_path = stage_dir / "timing.json" + if timing_path.is_file(): + timing = json.loads(timing_path.read_text(encoding="utf-8")) + timing["composed_critic_views"] = { + "duration_s": duration, + "source_usd": "../root.usda", + "manifest": manifest_path.relative_to(stage_dir).as_posix(), + } + atomic_write_text(timing_path, json.dumps(timing, indent=2, sort_keys=True) + "\n") + return updated + + @staticmethod + def _author_and_validate_pbr( + *, + output_dir: Path, + task_manifest_path: Path, + scene_manifest_path: Path, + ) -> Path | None: + policy = os.environ.get("RHG_PBR_POLICY") + enabled = bool(policy) or os.environ.get("RHG_ENABLE_PBR", "0").casefold() in { + "1", + "true", + "yes", + } + if not enabled: + return None + + project_root = Path(__file__).resolve().parents[2] + report_path = output_dir / "manifests" / "material_validation.json" + log_path = output_dir / "manifests" / "material_authoring.log.json" + usd_python = ( + os.environ.get("RHG_PBR_PYTHON") + or os.environ.get("RHG_USD_PYTHON") + or sys.executable + ) + command = [ + usd_python, + str(project_root / "scripts" / "author_pbr.py"), + "--root-usd", + str(output_dir / "root.usda"), + "--task-manifest", + str(task_manifest_path), + "--scene-manifest", + str(scene_manifest_path), + "--report", + str(report_path), + ] + if policy: + command.extend(["--policy", policy]) + started = time.perf_counter() + result = subprocess.run( + command, + cwd=project_root, + capture_output=True, + text=True, + timeout=int(os.environ.get("RHG_PBR_TIMEOUT_S", "900")), + check=False, + ) + atomic_write_text( + log_path, + json.dumps( + { + "schema_version": "1.0", + "command": command, + "duration_s": round(time.perf_counter() - started, 3), + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "report": report_path.relative_to(output_dir).as_posix(), + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + if result.returncode != 0 or not report_path.is_file(): + raise RuntimeError( + "PBR authoring failed " + f"(returncode={result.returncode}, log={log_path})" + ) + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("passed") is not True: + raise RuntimeError(f"PBR validation failed: {report_path}") + return report_path + + @staticmethod + def _place_robot_in_scenesmith_room( + *, + task: TaskSpec, + output_dir: Path, + stage_dir: Path, + stage_manifest: dict[str, object], + robot_id: str, + declared_spawn: RobotSpawnSpec | None, + ) -> None: + """Resolve the public room-centred spawn against exported room geometry. + + Current SceneSmith stages use a room-centred frame, while some legacy workers + described rooms from their southwest corner. The scene-state floor bounds are + authoritative when present; assuming either convention from dimensions alone + can produce a placement audit that passes even though the robot crosses a wall. + """ + + lock = task.metadata.get("asset_lock") or {} + if not isinstance(lock, dict): + lock = {} + frame = str(lock.get("robot_spawn_frame") or "room_center_local") + if frame not in {"room_center_local", "world"}: + raise ValueError(f"unsupported robot_spawn_frame: {frame}") + + room: dict[str, object] | None = None + geometry_bounds: tuple[float, float, float, float] | None = None + floor_z: float | None = None + scene_objects: list[dict[str, object]] = [] + house_state_ref = stage_manifest.get("house_state") + if isinstance(house_state_ref, str): + house_state_path = Path(house_state_ref) + if not house_state_path.is_absolute(): + house_state_path = stage_dir / house_state_path + if house_state_path.is_file(): + house_state = json.loads(house_state_path.read_text(encoding="utf-8")) + # Current SceneSmith snapshots wrap each room state under + # ``rooms[room_id]``; older checkpoints expose room_geometry and + # objects at the top level. Normalize the single-room form so + # robot clearance/source-facing checks see the authored support. + nested_rooms = house_state.get("rooms") + if ( + not house_state.get("objects") + and isinstance(nested_rooms, dict) + and len(nested_rooms) == 1 + ): + nested_room = next(iter(nested_rooms.values())) + if isinstance(nested_room, dict): + house_state = nested_room + raw_objects = house_state.get("objects") or [] + if isinstance(raw_objects, dict): + scene_objects = [ + value for value in raw_objects.values() if isinstance(value, dict) + ] + elif isinstance(raw_objects, list): + scene_objects = [value for value in raw_objects if isinstance(value, dict)] + room_geometry = house_state.get("room_geometry") + if isinstance(room_geometry, dict): + floor = room_geometry.get("floor") + if isinstance(floor, dict): + bbox_min = floor.get("bbox_min") + bbox_max = floor.get("bbox_max") + transform = floor.get("transform") or {} + translation = ( + transform.get("translation") + if isinstance(transform, dict) + else None + ) + if ( + isinstance(bbox_min, (list, tuple)) + and isinstance(bbox_max, (list, tuple)) + and len(bbox_min) >= 2 + and len(bbox_max) >= 2 + ): + tx = ( + float(translation[0]) + if isinstance(translation, (list, tuple)) + and len(translation) >= 2 + else 0.0 + ) + ty = ( + float(translation[1]) + if isinstance(translation, (list, tuple)) + and len(translation) >= 2 + else 0.0 + ) + geometry_bounds = ( + float(bbox_min[0]) + tx, + float(bbox_min[1]) + ty, + float(bbox_max[0]) + tx, + float(bbox_max[1]) + ty, + ) + tz = ( + float(translation[2]) + if isinstance(translation, (list, tuple)) + and len(translation) >= 3 + else 0.0 + ) + floor_z = ( + float(bbox_max[2]) + tz + if len(bbox_max) >= 3 + else tz + ) + rooms = house_state.get("rooms") or [] + if isinstance(rooms, list) and len(rooms) == 1 and isinstance(rooms[0], dict): + room = rooms[0] + + dimensions = lock.get("room_dimensions_m") + bounds_source: str + if geometry_bounds is not None: + bounds = geometry_bounds + length = bounds[2] - bounds[0] + width = bounds[3] - bounds[1] + origin_x, origin_y = bounds[0], bounds[1] + bounds_source = "scene_state.room_geometry.floor" + elif room is not None: + length = float(room.get("length", 0.0)) + width = float(room.get("width", 0.0)) + raw_position = room.get("position") or [0.0, 0.0] + origin_x, origin_y = float(raw_position[0]), float(raw_position[1]) + bounds = (origin_x, origin_y, origin_x + length, origin_y + width) + bounds_source = "scene_state.rooms" + elif isinstance(dimensions, (list, tuple)) and len(dimensions) >= 2: + length, width = float(dimensions[0]), float(dimensions[1]) + origin_x, origin_y = -length / 2.0, -width / 2.0 + bounds = (origin_x, origin_y, length / 2.0, width / 2.0) + bounds_source = "declared_dimensions_centered_fallback" + else: + # Legacy/fake SceneSmith workers may not expose a room frame. Preserve + # their existing contract, but do not claim an indoor-placement audit. + return + if length <= 0 or width <= 0: + raise ValueError(f"invalid SceneSmith room dimensions: {length} x {width}") + if floor_z is None: + floor_z = 0.0 + room_height = ( + float(dimensions[2]) + if isinstance(dimensions, (list, tuple)) and len(dimensions) >= 3 + else 3.0 + ) + + spawn = declared_spawn + if spawn is None: + from packages.usd_composer.composer import _resolve_robot_spawn + + spawn = _resolve_robot_spawn(robot_id, None) + local = tuple(float(value) for value in spawn.translation_m) + offset = (origin_x + length / 2.0, origin_y + width / 2.0, 0.0) + world = ( + tuple(local[index] + offset[index] for index in range(3)) + if frame == "room_center_local" + else local + ) + + from packages.robots.profiles import get_robot_profile + + radius = float(get_robot_profile(robot_id).footprint_radius_m) + footprint_inside = ( + bounds[0] + radius <= world[0] <= bounds[2] - radius + and bounds[1] + radius <= world[1] <= bounds[3] - radius + ) + wall_clearances = { + "west": world[0] - bounds[0] - radius, + "east": bounds[2] - world[0] - radius, + "south": world[1] - bounds[1] - radius, + "north": bounds[3] - world[1] - radius, + } + required_wall_clearance = float(lock.get("robot_wall_clearance_m", 0.25)) + minimum_wall_clearance = min(wall_clearances.values()) + wall_clearance_passed = bool( + footprint_inside and minimum_wall_clearance >= required_wall_clearance + ) + + def planar_bounds(record: dict[str, object]) -> tuple[float, float, float, float] | None: + minimum = record.get("bbox_min") + maximum = record.get("bbox_max") + transform = record.get("transform") or {} + if not ( + isinstance(minimum, (list, tuple)) + and isinstance(maximum, (list, tuple)) + and len(minimum) >= 2 + and len(maximum) >= 2 + and isinstance(transform, dict) + ): + return None + translation = transform.get("translation") or [0.0, 0.0, 0.0] + rotation = transform.get("rotation_wxyz") or [1.0, 0.0, 0.0, 0.0] + if not ( + isinstance(translation, (list, tuple)) + and len(translation) >= 2 + and isinstance(rotation, (list, tuple)) + and len(rotation) >= 4 + ): + return None + w, x, y, z = (float(value) for value in rotation[:4]) + yaw = math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)) + cosine, sine = math.cos(yaw), math.sin(yaw) + tx, ty = float(translation[0]), float(translation[1]) + corners = [] + for local_x in (float(minimum[0]), float(maximum[0])): + for local_y in (float(minimum[1]), float(maximum[1])): + corners.append( + ( + tx + cosine * local_x - sine * local_y, + ty + sine * local_x + cosine * local_y, + ) + ) + return ( + min(point[0] for point in corners), + min(point[1] for point in corners), + max(point[0] for point in corners), + max(point[1] for point in corners), + ) + + obstacle_clearances: list[dict[str, object]] = [] + source_entity_ids = { + str(predicate.object) + for predicate in task.initial_predicates + if predicate.name in {"on", "supported_by"} and predicate.object + } + source_center_distances: list[float] = [] + source_centers: list[tuple[float, float]] = [] + for record in scene_objects: + if str(record.get("object_type") or "").casefold() in { + "wall", + "floor", + "ceiling", + # Planar robot clearance is only meaningful for obstacles whose + # vertical extent intersects the robot. Ceiling-mounted lights + # were previously projected onto the floor and could reject an + # otherwise safe spawn directly beneath a 3 m fixture. + "ceiling_mounted", + }: + continue + record_bounds = planar_bounds(record) + if record_bounds is None: + continue + dx = max(record_bounds[0] - world[0], 0.0, world[0] - record_bounds[2]) + dy = max(record_bounds[1] - world[1], 0.0, world[1] - record_bounds[3]) + clearance = math.hypot(dx, dy) - radius + record_name = str(record.get("name") or record.get("object_id") or "unknown") + obstacle_clearances.append( + { + "object": record_name, + "clearance_m": round(clearance, 6), + "bounds_xy_m": [round(value, 6) for value in record_bounds], + } + ) + if record_name in source_entity_ids: + source_center = ( + (record_bounds[0] + record_bounds[2]) / 2.0, + (record_bounds[1] + record_bounds[3]) / 2.0, + ) + source_centers.append(source_center) + source_center_distances.append( + math.hypot(world[0] - source_center[0], world[1] - source_center[1]) + ) + obstacle_clearances.sort(key=lambda item: float(item["clearance_m"])) + nearest_obstacle = obstacle_clearances[0] if obstacle_clearances else None + required_obstacle_clearance = float(lock.get("robot_obstacle_clearance_m", 0.1)) + obstacle_clearance_passed = bool( + nearest_obstacle is None + or float(nearest_obstacle["clearance_m"]) >= required_obstacle_clearance + ) + source_approach_distance = ( + min(source_center_distances) if source_center_distances else None + ) + maximum_source_approach = lock.get("robot_max_source_approach_distance_m") + source_approach_passed = bool( + maximum_source_approach is None + or source_approach_distance is None + or source_approach_distance <= float(maximum_source_approach) + ) + source_facing_required = bool(lock.get("robot_source_facing_required", False)) + source_facing_tolerance = float(lock.get("robot_source_facing_tolerance_deg", 30.0)) + forward_axis = str(lock.get("robot_forward_axis_local", "+X")).upper() + local_forward_angles = {"+X": 0.0, "+Y": 90.0, "-X": 180.0, "-Y": -90.0} + if forward_axis not in local_forward_angles: + raise ValueError(f"unsupported robot_forward_axis_local: {forward_axis}") + nearest_source_center = ( + min( + source_centers, + key=lambda point: math.hypot(world[0] - point[0], world[1] - point[1]), + ) + if source_centers + else None + ) + source_facing_error: float | None = None + if nearest_source_center is not None: + desired_angle = math.degrees( + math.atan2(nearest_source_center[1] - world[1], nearest_source_center[0] - world[0]) + ) + robot_yaw = float(spawn.rotation_rpy_deg[2]) + actual_angle = robot_yaw + local_forward_angles[forward_axis] + source_facing_error = abs((actual_angle - desired_angle + 180.0) % 360.0 - 180.0) + source_facing_passed = bool( + not source_facing_required + or ( + source_facing_error is not None + and source_facing_error <= source_facing_tolerance + ) + ) + inside = bool( + footprint_inside + and wall_clearance_passed + and obstacle_clearance_passed + and source_approach_passed + and source_facing_passed + ) + audit = { + "schema_version": "1.1", + "passed": inside, + "coordinate_frame": frame, + "declared_translation_m": list(local), + "room_to_world_offset_m": list(offset), + "world_translation_m": list(world), + "room_bounds_xy_m": list(bounds), + "room_bounds_source": bounds_source, + "room_floor_z_m": floor_z, + "room_ceiling_z_m": floor_z + room_height, + "robot_footprint_radius_m": radius, + "footprint_inside_room": footprint_inside, + "wall_clearance_m": { + key: round(value, 6) for key, value in wall_clearances.items() + }, + "minimum_wall_clearance_m": round(minimum_wall_clearance, 6), + "required_wall_clearance_m": required_wall_clearance, + "wall_clearance_passed": wall_clearance_passed, + "nearest_obstacle": nearest_obstacle, + "required_obstacle_clearance_m": required_obstacle_clearance, + "obstacle_clearance_passed": obstacle_clearance_passed, + "source_approach_distance_m": ( + round(source_approach_distance, 6) + if source_approach_distance is not None + else None + ), + "maximum_source_approach_distance_m": maximum_source_approach, + "source_approach_passed": source_approach_passed, + "source_facing_required": source_facing_required, + "robot_forward_axis_local": forward_axis, + "nearest_source_center_m": ( + list(nearest_source_center) if nearest_source_center is not None else None + ), + "source_facing_error_deg": ( + round(source_facing_error, 6) if source_facing_error is not None else None + ), + "source_facing_tolerance_deg": source_facing_tolerance, + "source_facing_passed": source_facing_passed, + } + audit_path = output_dir / "manifests" / "robot_placement_validation.json" + atomic_write_text(audit_path, json.dumps(audit, indent=2, sort_keys=True) + "\n") + if not inside: + raise ValueError( + f"robot spawn is outside the generated room or unsafe after {frame} " + f"conversion: world_xy={world[:2]}, bounds={bounds}, radius={radius}, " + f"wall_clearance={minimum_wall_clearance:.3f}, " + f"nearest_obstacle={nearest_obstacle}, source_distance={source_approach_distance}, " + f"source_facing_error={source_facing_error}" + ) + + robot_layer = output_dir / "layers" / "robot.usda" + layer_text = robot_layer.read_text(encoding="utf-8") + replacement = "double3 xformOp:translate = (" + ", ".join(str(v) for v in world) + ")" + layer_text, count = re.subn( + r"double3 xformOp:translate\s*=\s*\([^)]*\)", replacement, layer_text, count=1 + ) + if count != 1: + raise RuntimeError("robot layer has no unique xformOp:translate") + atomic_write_text(robot_layer, layer_text) + + robot_manifest_path = output_dir / "manifests" / "robot.json" + robot_manifest = json.loads(robot_manifest_path.read_text(encoding="utf-8")) + robot_manifest["declared_translation_m"] = list(local) + robot_manifest["translation_m"] = list(world) + robot_manifest["coordinate_frame"] = "world" + robot_manifest["declared_coordinate_frame"] = frame + robot_manifest["room_to_world_offset_m"] = list(offset) + robot_manifest["placement_validation"] = audit_path.relative_to(output_dir).as_posix() + atomic_write_text( + robot_manifest_path, json.dumps(robot_manifest, indent=2, sort_keys=True) + "\n" + ) + + @staticmethod + def _render_composed_preview( + output_dir: Path, + stage_dir: Path, + stage_manifest_path: Path, + stage_manifest: dict[str, object], + ) -> dict[str, object]: + enabled = os.environ.get("RHG_COMPOSED_PREVIEW", "0").casefold() in { + "1", + "true", + "yes", + } + if not enabled: + return stage_manifest + started = time.perf_counter() + preview = stage_dir / "preview.mp4" + camera_manifest = stage_dir / "preview_camera_manifest.json" + command = [ + sys.executable, + str(Path(__file__).resolve().parents[2] / "scripts" / "render_scene_preview.py"), + str(output_dir / "root.usda"), + str(preview), + "--blender", + _resolve_blender_executable(), + "--frames", + os.environ.get("RHG_PREVIEW_FRAMES", "96"), + "--fps", + os.environ.get("RHG_PREVIEW_FPS", "24"), + "--width", + os.environ.get("RHG_PREVIEW_WIDTH", "960"), + "--height", + os.environ.get("RHG_PREVIEW_HEIGHT", "540"), + "--camera-manifest", + str(camera_manifest), + ] + if hdri := os.environ.get("RHG_PREVIEW_HDRI"): + command.extend(["--hdri", hdri]) + command.extend( + [ + "--hdri-strength", + os.environ.get("RHG_PREVIEW_HDRI_STRENGTH", "0.12"), + ] + ) + if material_root := os.environ.get("RHG_PREVIEW_MATERIAL_ROOT"): + command.extend(["--material-root", material_root]) + run_env = os.environ.copy() + run_env["RHG_PREVIEW_SPLIT_COMPOSED_IMPORT"] = "1" + result = subprocess.run( + command, + cwd=Path(__file__).resolve().parents[2], + env=run_env, + capture_output=True, + text=True, + timeout=int(os.environ.get("RHG_COMPOSED_PREVIEW_TIMEOUT_S", "3600")), + check=False, + ) + preview_log = stage_dir / "composed_preview.log" + atomic_write_text( + preview_log, + json.dumps( + { + "schema_version": "1.0", + "command": command, + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "output_exists": preview.is_file(), + "output_size_bytes": preview.stat().st_size if preview.is_file() else 0, + "camera_manifest_exists": camera_manifest.is_file(), + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + if result.returncode or not preview.is_file(): + raise RuntimeError( + "composed benchmark preview failed " + f"(returncode={result.returncode}, log={preview_log})" + ) + if not camera_manifest.is_file(): + raise RuntimeError( + f"composed benchmark preview has no camera framing audit: {camera_manifest}" + ) + camera_audit = json.loads(camera_manifest.read_text(encoding="utf-8")) + if camera_audit.get("passed") is not True: + raise RuntimeError(f"composed benchmark camera framing failed: {camera_manifest}") + duration = round(time.perf_counter() - started, 3) + updated = { + **stage_manifest, + "preview_mp4": preview.name, + "preview_scope": "composed_benchmark_root", + "preview_source_usd": "../root.usda", + "composed_preview_duration_s": duration, + "composed_preview_log": preview_log.name, + "preview_camera_manifest": camera_manifest.name, + } + atomic_write_text(stage_manifest_path, json.dumps(updated, indent=2, sort_keys=True) + "\n") + timing_path = stage_dir / "timing.json" + if timing_path.is_file(): + timing = json.loads(timing_path.read_text(encoding="utf-8")) + timing["composed_preview"] = { + "duration_s": duration, + "source_usd": "../root.usda", + "output": preview.name, + } + atomic_write_text(timing_path, json.dumps(timing, indent=2, sort_keys=True) + "\n") + return updated + + @staticmethod + def _semantics_layer(task: TaskSpec, bindings: dict[str, str]) -> str: + entities = [] + for entity in task.entities: + binding = bindings.get(entity.entity_id, "") + entities.append( + f' def Xform "{entity.entity_id}" {{\n' + f' custom string robothousegen_scenesmith_object_id = "{binding}"\n' + " }" + ) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + 'over Xform "World" {\n def Xform "Entities" {\n' + + "\n".join(entities) + + "\n }\n}\n" + ) + + +def render_accepted_final_preview( + output_dir: Path, + *, + accepted: bool, + hard_gates_passed: bool, + critic_passed: bool, +) -> Path | None: + """Render the release video only after the Supervisor's final decision.""" + + gate = { + "schema_version": "1.0", + "accepted": bool(accepted), + "hard_gates_passed": bool(hard_gates_passed), + "critic_passed": bool(critic_passed), + } + gate["passed"] = all(gate[key] for key in ( + "accepted", + "hard_gates_passed", + "critic_passed", + )) + gate_path = output_dir / "manifests" / "final_video_publish_gate.json" + if not gate["passed"]: + gate["status"] = "withheld" + atomic_write_text(gate_path, json.dumps(gate, indent=2, sort_keys=True) + "\n") + raise RuntimeError("final video withheld because the final quality gate failed") + + stage_dir = output_dir / "scenesmith" + stage_manifest_path = stage_dir / "stage_manifest.json" + if not stage_manifest_path.is_file(): + gate["status"] = "withheld" + gate["failure"] = "stage_manifest_missing" + atomic_write_text(gate_path, json.dumps(gate, indent=2, sort_keys=True) + "\n") + raise FileNotFoundError(stage_manifest_path) + stage_manifest = json.loads(stage_manifest_path.read_text(encoding="utf-8")) + inner_gate_path = stage_dir / "global_critic_publish_gate.json" + inner_gate = ( + json.loads(inner_gate_path.read_text(encoding="utf-8")) + if inner_gate_path.is_file() + else {} + ) + if stage_manifest.get("status") != "complete" or inner_gate.get("passed") is not True: + gate["status"] = "withheld" + gate["failure"] = "scenesmith_or_inner_global_critic_not_complete" + atomic_write_text(gate_path, json.dumps(gate, indent=2, sort_keys=True) + "\n") + raise RuntimeError(str(gate["failure"])) + + updated = SceneGenerationOrchestrator._render_composed_preview( + output_dir, + stage_dir, + stage_manifest_path, + stage_manifest, + ) + preview_value = updated.get("preview_mp4") + preview_candidate = stage_dir / str(preview_value) if preview_value else None + preview = ( + preview_candidate + if preview_candidate is not None and preview_candidate.is_file() + else None + ) + gate["status"] = "published" if preview is not None else "disabled" + gate["preview_mp4"] = ( + preview.relative_to(output_dir).as_posix() if preview is not None else None + ) + atomic_write_text(gate_path, json.dumps(gate, indent=2, sort_keys=True) + "\n") + return preview diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/pbr.py b/docs/reproduction/public_conversion_code/packages/scene_generation/pbr.py new file mode 100644 index 0000000000000000000000000000000000000000..77a35d29d481f2e76734de5ed39caf33430832ae --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/pbr.py @@ -0,0 +1,587 @@ +from __future__ import annotations + +import json +import hashlib +import math +import os +import shutil +from pathlib import Path +from typing import Any, Literal + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from packages.core.files import atomic_write_text + +PBRChannelName = Literal["albedo", "roughness", "metallic", "normal", "height", "ao"] + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class PBRChannel(_StrictModel): + texture: str | None = None + scalar: float | tuple[float, float, float] | None = None + color_space: Literal["sRGB", "raw"] + + @model_validator(mode="after") + def validate_source(self) -> PBRChannel: + if self.texture is None and self.scalar is None: + raise ValueError("PBR channel needs a texture or scalar") + if isinstance(self.scalar, float) and not 0.0 <= self.scalar <= 1.0: + raise ValueError("scalar PBR channels must be within [0, 1]") + if isinstance(self.scalar, tuple) and any(not 0.0 <= item <= 1.0 for item in self.scalar): + raise ValueError("PBR color channels must be within [0, 1]") + return self + + +class PBRMaterialSpec(_StrictModel): + entity_id: str + material_class: str + profile: Literal["imported", "uniform", "detailed"] + channels: dict[PBRChannelName, PBRChannel] = Field(default_factory=dict) + uv_primvar: str = "st" + uv_scale_m: float = Field(default=1.0, gt=0) + normal_convention: Literal["OpenGL", "DirectX"] = "OpenGL" + opacity: float = Field(default=1.0, ge=0, le=1) + required: bool = True + + +class PBRManifest(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + workflow: Literal["metallic_roughness"] = "metallic_roughness" + materials: list[PBRMaterialSpec] + + +DEFAULT_PBR_POLICY = ( + Path(__file__).resolve().parents[2] / "configs" / "scene_generation" / "pbr_profiles_v1.yaml" +) + + +def load_pbr_policy(path: Path | None = None) -> dict[str, Any]: + selected = path or Path(os.environ.get("RHG_PBR_POLICY", DEFAULT_PBR_POLICY)) + value = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8")) + if not isinstance(value, dict) or value.get("schema_version") != "1.0": + raise ValueError("PBR policy must use schema_version 1.0") + return value + + +def compile_pbr_manifest(task: dict[str, Any], policy: dict[str, Any]) -> PBRManifest: + detailed = {str(item).casefold() for item in policy["detailed_material_classes"]} + color_spaces = policy["color_spaces"] + materials: list[PBRMaterialSpec] = [] + for entity in task.get("entities", []): + if not isinstance(entity, dict) or entity.get("role") in {"ROBOT", "REGION"}: + continue + entity_id = str(entity.get("entity_id") or "") + if not entity_id: + continue + attributes = entity.get("attributes") or {} + appearance = attributes.get("appearance") or {} + if not appearance and isinstance(attributes.get("procedural_geometry"), dict): + components = attributes["procedural_geometry"].get("components") or [] + first = components[0] if components and isinstance(components[0], dict) else {} + appearance = { + "base_color_rgb": first.get("display_color", [0.5, 0.5, 0.5]), + "roughness": 0.5, + "metallic": 0.0, + "material_class": "uniform", + } + if not appearance: + materials.append( + PBRMaterialSpec( + entity_id=entity_id, + material_class="imported", + profile="imported", + required=bool(entity.get("required", True)), + ) + ) + continue + material_class = str( + appearance.get("material_class") or attributes.get("material_class") or "uniform" + ).casefold() + profile: Literal["uniform", "detailed"] = ( + "detailed" if material_class in detailed else "uniform" + ) + textures = appearance.get("textures") or {} + if not isinstance(textures, dict): + raise ValueError(f"appearance.textures must be an object for {entity_id}") + channels: dict[PBRChannelName, PBRChannel] = {} + scalar_values: dict[str, Any] = { + "albedo": appearance.get("base_color_rgb"), + "roughness": appearance.get("roughness"), + "metallic": appearance.get("metallic"), + } + for channel in ("albedo", "roughness", "metallic", "normal", "height", "ao"): + texture = textures.get(channel) + scalar = scalar_values.get(channel) + if texture is None and scalar is None: + continue + if channel == "albedo" and scalar is not None: + if not isinstance(scalar, (list, tuple)) or len(scalar) != 3: + raise ValueError(f"base_color_rgb must contain 3 values for {entity_id}") + scalar = tuple(float(item) for item in scalar) + elif scalar is not None: + scalar = float(scalar) + channels[channel] = PBRChannel( + texture=str(texture) if texture is not None else None, + scalar=scalar, + color_space=color_spaces[channel], + ) + materials.append( + PBRMaterialSpec( + entity_id=entity_id, + material_class=material_class, + profile=profile, + channels=channels, + uv_primvar=str(appearance.get("uv_primvar", "st")), + uv_scale_m=float(appearance.get("uv_scale_m", 1.0)), + normal_convention=str(appearance.get("normal_convention", "OpenGL")), + opacity=float(appearance.get("opacity", 1.0)), + required=bool(entity.get("required", True)), + ) + ) + return PBRManifest(materials=materials) + + +def validate_pbr_manifest( + manifest: PBRManifest, + policy: dict[str, Any], + *, + imported_bindings: dict[str, bool] | None = None, +) -> dict[str, Any]: + bindings_supplied = imported_bindings is not None + imported_bindings = imported_bindings or {} + profiles = policy["profiles"] + uv_limits = policy["uv_scale_m"] + results: list[dict[str, Any]] = [] + for material in manifest.materials: + profile = profiles[material.profile] + required_channels = set(profile["required_channels"]) + allow_scalar = set(profile["allow_scalar"]) + missing = sorted(required_channels - set(material.channels)) + invalid_scalar = sorted( + channel + for channel, spec in material.channels.items() + if spec.texture is None and channel not in allow_scalar + ) + wrong_color_space = sorted( + channel + for channel, spec in material.channels.items() + if spec.color_space != policy["color_spaces"][channel] + ) + missing_binding = not imported_bindings.get(material.entity_id, False) + uv_valid = uv_limits["minimum"] <= material.uv_scale_m <= uv_limits["maximum"] + passed = ( + not missing + and not invalid_scalar + and not wrong_color_space + and uv_valid + and (not bindings_supplied or not missing_binding) + ) + if material.profile == "imported": + # Imported appearance is owned by the catalog asset. A missing + # UsdShade binding may still be an MDL/displayColor/native renderer + # material and cannot invalidate an otherwise physical asset. + passed = True + results.append( + { + "entity_id": material.entity_id, + "material_class": material.material_class, + "profile": material.profile, + "passed": passed, + "required": material.required, + "missing_channels": missing, + "invalid_scalar_channels": invalid_scalar, + "wrong_color_space": wrong_color_space, + "uv_scale_m": material.uv_scale_m, + "uv_scale_valid": uv_valid, + "imported_material_bound": imported_bindings.get(material.entity_id), + } + ) + failed = [item["entity_id"] for item in results if item["required"] and not item["passed"]] + material_warnings = { + item["entity_id"]: ["source_material_binding_not_detected"] + for item in results + if bindings_supplied + and item["profile"] == "imported" + and item["imported_material_bound"] is False + } + return { + "schema_version": "1.0", + "passed": not failed, + "failed_entities": failed, + "material_warnings": material_warnings, + "materials": results, + } + + +def _normalize_imported_material_adjustment( + entity_id: str, adjustment: dict[str, Any] +) -> dict[str, Any]: + allowed = {"base_color_rgb", "roughness", "metallic"} + unknown = set(adjustment) - allowed + if unknown: + raise ValueError( + f"unsupported imported material adjustment for {entity_id}: {sorted(unknown)}" + ) + if not adjustment: + raise ValueError(f"imported material adjustment for {entity_id} is empty") + + normalized: dict[str, Any] = {} + for name in ("roughness", "metallic"): + if name not in adjustment: + continue + value = adjustment[name] + if isinstance(value, bool): + raise ValueError(f"imported {name} adjustment for {entity_id} must be numeric") + try: + scalar = float(value) + except (TypeError, ValueError) as error: + raise ValueError( + f"imported {name} adjustment for {entity_id} must be numeric" + ) from error + if not math.isfinite(scalar) or not 0.0 <= scalar <= 1.0: + raise ValueError( + f"imported {name} adjustment for {entity_id} must be finite and in [0, 1]" + ) + normalized[name] = scalar + + if "base_color_rgb" in adjustment: + color = adjustment["base_color_rgb"] + if not isinstance(color, (list, tuple)) or len(color) != 3: + raise ValueError( + f"imported base_color_rgb adjustment for {entity_id} must contain 3 values" + ) + values: list[float] = [] + for item in color: + if isinstance(item, bool): + raise ValueError( + f"imported base_color_rgb adjustment for {entity_id} must be numeric" + ) + try: + value = float(item) + except (TypeError, ValueError) as error: + raise ValueError( + f"imported base_color_rgb adjustment for {entity_id} must be numeric" + ) from error + if not math.isfinite(value) or not 0.0 <= value <= 1.0: + raise ValueError( + f"imported base_color_rgb adjustment for {entity_id} must be finite and in [0, 1]" + ) + values.append(value) + normalized["base_color_rgb"] = tuple(values) + return normalized + + +def _summarize_imported_material_adjustment( + normalized: dict[str, Any], + shader_paths: set[str], + authored_channels: dict[str, set[str]], +) -> dict[str, Any]: + """Describe a best-effort override without rejecting the source material.""" + + unapplied = sorted(name for name, paths in authored_channels.items() if not paths) + return { + **normalized, + "shader_paths": sorted(shader_paths), + "authored_channels": { + name: sorted(paths) for name, paths in authored_channels.items() + }, + "fully_applied": not unapplied, + "unapplied_channels": unapplied, + "preserved_source_material": bool(unapplied), + } + + +def author_and_validate_pbr( + root_usd: Path, + task_manifest: Path, + scene_manifest: Path, + report_path: Path, + *, + policy_path: Path | None = None, +) -> dict[str, Any]: + """Author task-owned PBR opinions after conversion and validate the result.""" + + try: + from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade # type: ignore[import-not-found] + except ImportError as error: + raise RuntimeError("pxr is required for PBR authoring and validation") from error + root_usd = root_usd.resolve() + task = json.loads(task_manifest.read_text(encoding="utf-8")) + scene = json.loads(scene_manifest.read_text(encoding="utf-8")) + policy = load_pbr_policy(policy_path) + manifest = compile_pbr_manifest(task, policy) + manifest_path = report_path.with_name("material_manifest.json") + atomic_write_text(manifest_path, manifest.model_dump_json(indent=2) + "\n") + stage = Usd.Stage.Open(str(root_usd)) + if stage is None: + raise RuntimeError(f"could not open composed stage: {root_usd}") + # Author appearance independently from physics so either concern can be + # reviewed, replaced, or hashed without mutating the other layer. + material_layer_path = root_usd.parent / "layers" / "materials.usda" + layer = next( + ( + item + for item in stage.GetLayerStack() + if item.realPath and Path(item.realPath).resolve() == material_layer_path.resolve() + ), + None, + ) + if layer is None: + raise RuntimeError( + f"material override layer is not in the stage stack: {material_layer_path}" + ) + stage.SetEditTarget(layer) + bindings = scene.get("entity_prim_paths") or {} + looks = UsdGeom.Scope.Define(stage, "/World/RoboHouseGenPBRLooks") + authored: dict[str, str] = {} + imported_bound: dict[str, bool] = {} + missing_texture_files: dict[str, list[str]] = {} + imported_adjustments: dict[str, dict[str, Any]] = {} + + def renderable_gprims(entity_prim: Any) -> list[Any]: + """Return appearance geometry, never guide/proxy collision geometry.""" + + result: list[Any] = [] + for item in Usd.PrimRange(entity_prim): + if item.IsInstanceProxy() or not item.IsA(UsdGeom.Gprim): + continue + purpose = UsdGeom.Imageable(item).ComputePurpose() + if purpose in {UsdGeom.Tokens.default_, UsdGeom.Tokens.render}: + result.append(item) + continue + # Remove stale task-layer bindings produced by older versions. A + # purpose=guide/proxy collider must never acquire an appearance. + binding_api = UsdShade.MaterialBindingAPI(item) + binding_api.UnbindDirectBinding() + return result + + def preview_material(name: str, color: tuple[float, float, float], roughness: float, metallic: float) -> Any: + material = UsdShade.Material.Define(stage, looks.GetPath().AppendChild(name)) + shader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("PreviewSurface")) + shader.CreateIdAttr("UsdPreviewSurface") + shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*color)) + shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(roughness) + shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(metallic) + material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") + return material + + # The official G1 asset used by the validated runtime has correct geometry + # and articulation, but its source USD ships with a single flat-white + # preview material. Add a task-owned appearance layer so RTX evidence reads + # as a robot, without mutating the official robot payload or physics. + robot_prim = stage.GetPrimAtPath(str(scene.get("robot_prim_path") or "/World/Robot")) + if robot_prim.IsValid(): + robot_materials = { + "shell": preview_material("g1_shell", (0.58, 0.62, 0.66), 0.3, 0.35), + "joint": preview_material("g1_joint", (0.035, 0.045, 0.055), 0.38, 0.18), + "head": preview_material("g1_head", (0.01, 0.015, 0.02), 0.24, 0.25), + } + joint_terms = ( + "hip", "knee", "ankle", "waist", "shoulder", "elbow", "wrist", "hand" + ) + for gprim in renderable_gprims(robot_prim): + path = str(gprim.GetPath()).casefold() + role = "head" if "head_link" in path else "joint" if any(term in path for term in joint_terms) else "shell" + UsdShade.MaterialBindingAPI.Apply(gprim).Bind( + robot_materials[role], bindingStrength=UsdShade.Tokens.strongerThanDescendants + ) + authored["__robot_g1_appearance__"] = ",".join( + str(material.GetPath()) for material in robot_materials.values() + ) + + for entity in task.get("entities", []): + if not isinstance(entity, dict): + continue + entity_id = str(entity.get("entity_id") or "") + adjustment = (entity.get("attributes") or {}).get("imported_material_adjustment") + if not isinstance(adjustment, dict): + continue + normalized = _normalize_imported_material_adjustment(entity_id, adjustment) + entity_prim = stage.GetPrimAtPath(str(bindings.get(entity_id) or "")) + shader_paths: set[str] = set() + authored_channels: dict[str, set[str]] = { + name: set() for name in normalized + } + if entity_prim: + for gprim in renderable_gprims(entity_prim): + material = UsdShade.MaterialBindingAPI(gprim).ComputeBoundMaterial()[0] + if not material: + continue + for shader_prim in Usd.PrimRange(material.GetPrim()): + if shader_prim.GetTypeName() != "Shader": + continue + shader = UsdShade.Shader(shader_prim) + shader_id = str(shader.GetIdAttr().Get() or "") + override = UsdShade.Shader(stage.OverridePrim(shader_prim.GetPath())) + for name, value in normalized.items(): + input_name = "diffuseColor" if name == "base_color_rgb" else name + if shader_id != "UsdPreviewSurface" and not shader.GetInput(input_name): + continue + value_type = ( + Sdf.ValueTypeNames.Color3f + if name == "base_color_rgb" + else Sdf.ValueTypeNames.Float + ) + authored_input = override.CreateInput(input_name, value_type) + authored_input.DisconnectSource() + authored_input.Set( + Gf.Vec3f(*value) if name == "base_color_rgb" else value + ) + shader_path = str(shader_prim.GetPath()) + shader_paths.add(shader_path) + authored_channels[name].add(shader_path) + imported_adjustments[entity_id] = _summarize_imported_material_adjustment( + normalized, shader_paths, authored_channels + ) + + for spec in manifest.materials: + prim = stage.GetPrimAtPath(str(bindings.get(spec.entity_id) or "")) + if not prim.IsValid(): + imported_bound[spec.entity_id] = False + continue + gprims = renderable_gprims(prim) + imported_bound[spec.entity_id] = any( + UsdShade.MaterialBindingAPI(item).ComputeBoundMaterial()[0] for item in gprims + ) + if spec.profile == "imported": + continue + material = UsdShade.Material.Define(stage, looks.GetPath().AppendChild(spec.entity_id)) + shader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("PreviewSurface")) + shader.CreateIdAttr("UsdPreviewSurface") + primvar = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("PrimvarReader")) + primvar.CreateIdAttr("UsdPrimvarReader_float2") + primvar.CreateInput("varname", Sdf.ValueTypeNames.Token).Set(spec.uv_primvar) + primvar.CreateOutput("result", Sdf.ValueTypeNames.Float2) + uv_transform = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("UVScale")) + uv_transform.CreateIdAttr("UsdTransform2d") + uv_transform.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource( + primvar.ConnectableAPI(), "result" + ) + repeat = 1.0 / spec.uv_scale_m + uv_transform.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(repeat, repeat)) + uv_transform.CreateOutput("result", Sdf.ValueTypeNames.Float2) + scalar_inputs = { + "albedo": ("diffuseColor", Sdf.ValueTypeNames.Color3f), + "roughness": ("roughness", Sdf.ValueTypeNames.Float), + "metallic": ("metallic", Sdf.ValueTypeNames.Float), + } + shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(spec.opacity) + staged_channels: dict[str, str] = {} + missing_textures: list[str] = [] + for channel, channel_spec in spec.channels.items(): + if channel_spec.scalar is not None and channel in scalar_inputs: + name, value_type = scalar_inputs[channel] + value: Any = channel_spec.scalar + if channel == "albedo": + value = Gf.Vec3f(*value) + shader.CreateInput(name, value_type).Set(value) + if channel_spec.texture is not None: + expanded = Path(os.path.expandvars(channel_spec.texture)).expanduser() + candidates = ( + [expanded] + if expanded.is_absolute() + else [task_manifest.parent / expanded, root_usd.parent / expanded, expanded] + ) + approved_roots = [task_manifest.parent.resolve(), root_usd.parent.resolve()] + if material_root := os.environ.get("RHG_MATERIAL_ROOT"): + approved_roots.append(Path(material_root).expanduser().resolve()) + source = None + for candidate in candidates: + if candidate.is_symlink() or not candidate.is_file(): + continue + resolved = candidate.resolve() + if any(resolved.is_relative_to(allowed) for allowed in approved_roots): + source = resolved + break + if source is None: + missing_textures.append(f"{channel}:{channel_spec.texture}") + continue + source_digest = hashlib.sha256(source.read_bytes()).hexdigest()[:16] + destination = ( + root_usd.parent / "textures" / "pbr" / spec.entity_id + / f"{source.stem}-{source_digest}{source.suffix}" + ) + destination.parent.mkdir(parents=True, exist_ok=True) + if not destination.is_file(): + try: + os.link(source, destination) + except OSError: + shutil.copy2(source, destination) + if hashlib.sha256(destination.read_bytes()).hexdigest() != hashlib.sha256(source.read_bytes()).hexdigest(): + raise RuntimeError(f"PBR texture copy hash mismatch: {source}") + staged_channels[channel] = destination.relative_to(root_usd.parent).as_posix() + texture = UsdShade.Shader.Define( + stage, material.GetPath().AppendChild(f"{channel}_texture") + ) + texture.CreateIdAttr("UsdUVTexture") + texture.CreateInput("file", Sdf.ValueTypeNames.Asset).Set( + Sdf.AssetPath(f"../{staged_channels[channel]}") + ) + texture.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set( + channel_spec.color_space + ) + texture.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource( + uv_transform.ConnectableAPI(), "result" + ) + if channel in {"albedo", "normal"}: + texture.CreateOutput("rgb", Sdf.ValueTypeNames.Float3) + else: + texture.CreateOutput("r", Sdf.ValueTypeNames.Float) + if channel == "albedo": + shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource( + texture.ConnectableAPI(), "rgb" + ) + elif channel in {"roughness", "metallic"}: + shader.CreateInput(channel, Sdf.ValueTypeNames.Float).ConnectToSource( + texture.ConnectableAPI(), "r" + ) + elif channel == "normal": + shader.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource( + texture.ConnectableAPI(), "rgb" + ) + elif channel in {"height", "ao"}: + shader.GetPrim().SetCustomDataByKey( + "robothousegen:unsupported_pbr_channel", channel + ) + shader.GetPrim().SetCustomDataByKey("robothousegen:pbr_channels", staged_channels) + shader.GetPrim().SetCustomDataByKey("robothousegen:material_class", spec.material_class) + shader.GetPrim().SetCustomDataByKey("robothousegen:uv_scale_m", spec.uv_scale_m) + shader.GetPrim().SetCustomDataByKey( + "robothousegen:normal_convention", spec.normal_convention + ) + material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") + for gprim in gprims: + UsdShade.MaterialBindingAPI.Apply(gprim).Bind( + material, bindingStrength=UsdShade.Tokens.strongerThanDescendants + ) + imported_bound[spec.entity_id] = bool(gprims) + authored[spec.entity_id] = str(material.GetPath()) + if missing_textures: + missing_texture_files[spec.entity_id] = missing_textures + layer.Save() + report = validate_pbr_manifest(manifest, policy, imported_bindings=imported_bound) + report["imported_material_adjustments"] = imported_adjustments + report["material_adjustment_warnings"] = { + entity_id: item["unapplied_channels"] + for entity_id, item in imported_adjustments.items() + if item["unapplied_channels"] + } + if missing_texture_files: + report["passed"] = False + report["failed_entities"] = sorted( + set(report["failed_entities"]) | set(missing_texture_files) + ) + report.update( + { + "material_layer": material_layer_path.relative_to(root_usd.parent).as_posix(), + "material_manifest": manifest_path.relative_to(root_usd.parent).as_posix(), + "authored_materials": authored, + "missing_texture_files": missing_texture_files, + } + ) + atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") + return report diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/pick_move_place.py b/docs/reproduction/public_conversion_code/packages/scene_generation/pick_move_place.py new file mode 100644 index 0000000000000000000000000000000000000000..f0fa9b00192fff5da39b1544a119c9516efb0df8 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/pick_move_place.py @@ -0,0 +1,576 @@ +from __future__ import annotations + +import heapq +import math +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator +from shapely import affinity +from shapely.geometry import LineString, Point, Polygon +from shapely.ops import unary_union +from shapely.prepared import prep + +from packages.asset_registry.descriptors import AssetDescriptor +from packages.scene_generation.metric_layout import MetricEntityLayout, MetricLayoutSpec + + +Point2 = tuple[float, float] +Point3 = tuple[float, float, float] + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class RobotPose(_StrictModel): + x_m: float + y_m: float + yaw_deg: float + + +class ManipulationEndpoint(_StrictModel): + entity_id: str + support_entity_id: str + position_xyz_m: Point3 + approach_pose: RobotPose + navigation_pose: RobotPose | None = None + + +class PickMovePlaceTask(_StrictModel): + schema_version: Literal["1.0"] = "1.0" + task_id: str + task_type: Literal["pick_move_place"] = "pick_move_place" + description_zh: str + description_en: str + movable_object_entity_id: str + source_support_entity_id: str + target_support_entity_id: str + robot_start_pose: RobotPose + pick: ManipulationEndpoint + place: ManipulationEndpoint + route_waypoints_xy_m: list[Point2] = Field(min_length=3) + route_length_m: float = Field(gt=0) + service_connectors_xy_m: dict[str, list[Point2]] = Field(default_factory=dict) + robot_radius_m: float = Field(gt=0) + planning_grid_m: float = Field(gt=0) + required_portal_ids: list[str] = Field(default_factory=list) + portal_waypoints_xy_m: list[Point2] = Field(default_factory=list) + validation_checks: list[dict[str, Any]] + passed: bool + robot_constraints: dict[str, Any] = Field(default_factory=dict) + + @model_validator(mode="after") + def validate_task(self) -> PickMovePlaceTask: + if self.pick.entity_id != self.movable_object_entity_id: + raise ValueError("pick endpoint does not identify the movable object") + if self.pick.support_entity_id != self.source_support_entity_id: + raise ValueError("pick endpoint source support mismatch") + if self.place.support_entity_id != self.target_support_entity_id: + raise ValueError("place endpoint target support mismatch") + if self.passed != all(bool(item.get("passed")) for item in self.validation_checks): + raise ValueError("task pass flag disagrees with validation checks") + return self + + +def _angle_toward(source: Point2, target: Point2) -> float: + return ((math.degrees(math.atan2(target[1] - source[1], target[0] - source[0])) + 180) % 360) - 180 + + +def _base_heights( + spec: MetricLayoutSpec, + descriptors: dict[str, AssetDescriptor], +) -> dict[str, float]: + by_id = spec.entity_by_id + output: dict[str, float] = {} + unresolved = set(by_id) + while unresolved: + progressed = False + for entity_id in sorted(unresolved): + entity = by_id[entity_id] + if entity.parent_entity_id and entity.parent_entity_id not in output: + continue + descriptor = descriptors[entity.asset_id or ""] + if entity.parent_entity_id: + parent = by_id[entity.parent_entity_id] + parent_descriptor = descriptors[parent.asset_id or ""] + output[entity_id] = output[parent.entity_id] + parent_descriptor.height_m + elif entity.support_type == "wall": + output[entity_id] = max( + 0.85, (spec.room_dimensions_m[2] - descriptor.height_m) / 2.0 + ) + elif entity.support_type == "ceiling": + output[entity_id] = max(0.0, spec.room_dimensions_m[2] - descriptor.height_m) + else: + output[entity_id] = 0.0 + unresolved.remove(entity_id) + progressed = True + if not progressed: + raise ValueError(f"cannot resolve task support heights: {sorted(unresolved)}") + return output + + +def _grid_key(point: Point2, step: float) -> tuple[int, int]: + return round(point[0] / step), round(point[1] / step) + + +def _grid_point(key: tuple[int, int], step: float) -> Point2: + return key[0] * step, key[1] * step + + +def _nearest_free_key( + point: Point2, + *, + step: float, + is_free: Any, +) -> tuple[int, int]: + origin = _grid_key(point, step) + for radius in range(0, 8): + candidates = [ + (origin[0] + dx, origin[1] + dy) + for dx in range(-radius, radius + 1) + for dy in range(-radius, radius + 1) + if max(abs(dx), abs(dy)) == radius + ] + candidates.sort(key=lambda key: math.dist(point, _grid_point(key, step))) + for key in candidates: + if is_free(_grid_point(key, step)): + return key + raise ValueError(f"no free planning grid cell near {point}") + + +def _astar( + start: Point2, + goal: Point2, + *, + step: float, + is_free: Any, +) -> list[Point2] | None: + start_key = _nearest_free_key(start, step=step, is_free=is_free) + goal_key = _nearest_free_key(goal, step=step, is_free=is_free) + queue: list[tuple[float, float, tuple[int, int]]] = [(0.0, 0.0, start_key)] + parents: dict[tuple[int, int], tuple[int, int]] = {} + costs = {start_key: 0.0} + moves = [ + (-1, 0, 1.0), + (1, 0, 1.0), + (0, -1, 1.0), + (0, 1, 1.0), + (-1, -1, math.sqrt(2.0)), + (-1, 1, math.sqrt(2.0)), + (1, -1, math.sqrt(2.0)), + (1, 1, math.sqrt(2.0)), + ] + visited: set[tuple[int, int]] = set() + while queue: + _, cost, current = heapq.heappop(queue) + if current in visited: + continue + visited.add(current) + if current == goal_key: + chain = [current] + while chain[-1] != start_key: + chain.append(parents[chain[-1]]) + chain.reverse() + points = [_grid_point(key, step) for key in chain] + points[0] = start + points[-1] = goal + return points + for dx, dy, weight in moves: + neighbor = current[0] + dx, current[1] + dy + point = _grid_point(neighbor, step) + if not is_free(point): + continue + if dx and dy: + if not is_free(_grid_point((current[0] + dx, current[1]), step)): + continue + if not is_free(_grid_point((current[0], current[1] + dy), step)): + continue + new_cost = cost + weight * step + if new_cost >= costs.get(neighbor, float("inf")): + continue + costs[neighbor] = new_cost + parents[neighbor] = current + heuristic = math.dist(point, _grid_point(goal_key, step)) + heapq.heappush(queue, (new_cost + heuristic, new_cost, neighbor)) + return None + + +def _simplify(points: list[Point2]) -> list[Point2]: + if len(points) <= 2: + return points + output = [points[0]] + previous_direction: tuple[int, int] | None = None + for index in range(1, len(points)): + delta = ( + round((points[index][0] - points[index - 1][0]) * 1000), + round((points[index][1] - points[index - 1][1]) * 1000), + ) + gcd = math.gcd(abs(delta[0]), abs(delta[1])) or 1 + direction = delta[0] // gcd, delta[1] // gcd + if previous_direction is not None and direction != previous_direction: + output.append(points[index - 1]) + previous_direction = direction + output.append(points[-1]) + return output + + +def _approach_candidates( + entity: MetricEntityLayout, + *, + robot_radius: float, + is_free: Any, +) -> list[Point2]: + shape = Polygon(entity.collision_footprint_xy_m) + boundary = shape.buffer(robot_radius + 0.24, join_style="round").exterior + candidates = [ + (float(boundary.interpolate(index / 48.0, normalized=True).x), + float(boundary.interpolate(index / 48.0, normalized=True).y)) + for index in range(48) + ] + candidates = [point for point in candidates if is_free(point)] + candidates.sort( + key=lambda point: ( + math.dist(point, entity.center_xy_m), + round(math.atan2(point[1] - entity.center_xy_m[1], point[0] - entity.center_xy_m[0]), 6), + ) + ) + return candidates + + +def build_pick_move_place_task( + spec: MetricLayoutSpec, + descriptors: dict[str, AssetDescriptor], + config: dict[str, Any], +) -> PickMovePlaceTask: + by_id = spec.entity_by_id + object_id = str(config["movable_object_entity_id"]) + source_id = str(config["source_support_entity_id"]) + target_id = str(config["target_support_entity_id"]) + missing = {object_id, source_id, target_id} - set(by_id) + if missing: + raise ValueError(f"pick-move-place task references unknown entities: {sorted(missing)}") + movable = by_id[object_id] + source = by_id[source_id] + target = by_id[target_id] + if movable.parent_entity_id != source_id: + raise ValueError( + f"task object {object_id} is not initially supported by {source_id}: " + f"parent={movable.parent_entity_id}" + ) + if source_id == target_id: + raise ValueError("pick and place supports must differ") + from packages.robots.task_constraints import get_task_constraints + from packages.scene_generation.robot_constraints import ( + RobotConstraintError, endpoint_candidates, move_entity, target_surroundings, + ) + enabled = config.get("robot_constraints_enabled", True) + profile = get_task_constraints(config.get("robot_id")) + robot_radius = (profile["carry_corridor_width_m"] / 2 if enabled + else float(config.get("robot_radius_m", .28))) + raw_room = Polygon(spec.room_polygon_xy_m) + raw_shapes = [Polygon(e.collision_footprint_xy_m) for e in spec.entities + if e.parent_entity_id is None and e.support_type == "floor"] + raw_shapes.extend(Polygon(points) for points in config.get("navigation_keepout_polygons_xy_m", [])) + # Descriptor clearance polygons are reserved sweep areas, not robot stand areas. + for e in spec.entities: + descriptor = descriptors[e.asset_id or ""] + for clearance in descriptor.operational_clearance: + if any(word in clearance.operation.lower() for word in ("door", "drawer", "open", "swing")): + shape = affinity.rotate(Polygon(clearance.polygon_m), e.yaw_deg, origin=(0, 0)) + raw_shapes.append(affinity.translate(shape, xoff=e.center_xy_m[0], yoff=e.center_xy_m[1])) + raw_obstacles = unary_union(raw_shapes) + base = _base_heights(spec, descriptors) + object_descriptor = descriptors[movable.asset_id or ""] + grip_dimensions = movable.dimensions_m or object_descriptor.native_bbox_m + grip_axis = min(range(3), key=lambda i: grip_dimensions[i]) + if enabled and grip_dimensions[grip_axis] > profile["max_grip_dimension_m"]: + raise RobotConstraintError("grip_dimension", measured_m=grip_dimensions[grip_axis], + maximum_m=profile["max_grip_dimension_m"]) + endpoint_data = {} + grid = float(config.get("planning_grid_m", 0.10)) + room = Polygon(spec.room_polygon_xy_m).buffer(-robot_radius) + obstacle_shapes = [ + Polygon(entity.collision_footprint_xy_m).buffer(robot_radius + 0.02) + for entity in spec.entities + if entity.parent_entity_id is None and entity.support_type == "floor" + ] + obstacle_shapes.extend( + Polygon(points).buffer(robot_radius + 0.02, join_style="mitre") + for points in config.get("navigation_keepout_polygons_xy_m", []) + ) + obstacles = (raw_obstacles.buffer(robot_radius + .02) if enabled + else unary_union(obstacle_shapes)) + + prepared_room = prep(room.buffer(1.0e-8)) + prepared_obstacles = prep(obstacles.buffer(1.0e-8)) + + def is_free(point: Point2) -> bool: + value = Point(point) + return prepared_room.covers(value) and not prepared_obstacles.covers(value) + + start = tuple(float(value) for value in spec.robot_start_xy_m) + pick_candidates = _approach_candidates(source, robot_radius=robot_radius, is_free=is_free) + place_candidates = _approach_candidates(target, robot_radius=robot_radius, is_free=is_free) + if not enabled and (not pick_candidates or not place_candidates): + raise ValueError("task support has no collision-free robot approach pose") + if enabled: + for support in (source, target): + height = base[support.entity_id] + descriptors[support.asset_id or ""].height_m + endpoint_data[support.entity_id] = endpoint_candidates( + spec, descriptors, support, movable, height, profile, + raw_room, raw_obstacles, robot_radius) + pick_candidates = [c["navigation_station"] for c in endpoint_data[source_id] if is_free(c["navigation_station"])] + place_candidates = [c["navigation_station"] for c in endpoint_data[target_id] if is_free(c["navigation_station"])] + # Retain sampling order: comfortable and shallow placements first. + else: + pick_candidates.sort(key=lambda point: math.dist(start, point)) + required_portals = list(config.get("required_portals") or []) + portal_waypoints = [ + ( + (float(item["opening_segment_xy_m"][0][0]) + float(item["opening_segment_xy_m"][1][0])) / 2.0, + (float(item["opening_segment_xy_m"][0][1]) + float(item["opening_segment_xy_m"][1][1])) / 2.0, + ) + for item in required_portals + ] + selected: tuple[Point2, Point2, list[Point2], list[Point2]] | None = None + best_length = float("inf") + resampling_count = int(config.get("resampling_count", 0)) + selected_turn_diameter = 0.0 + selected_turn_point = None + for pick_approach in list(dict.fromkeys(pick_candidates))[:32]: + first = _astar(start, pick_approach, step=grid, is_free=is_free) + if first is None: + continue + ordered_places = list(dict.fromkeys(place_candidates)) if enabled else sorted( + place_candidates, key=lambda point: math.dist(pick_approach, point)) + for place_approach in ordered_places[:20]: + segment_start = pick_approach + second_segments: list[list[Point2]] = [] + for segment_goal in [*portal_waypoints, place_approach]: + segment = _astar(segment_start, segment_goal, step=grid, is_free=is_free) + if segment is None: + second_segments = [] + break + second_segments.append(segment) + segment_start = segment_goal + if not second_segments: + continue + second = [] + for segment in second_segments: + simplified = _simplify(segment) + second.extend(simplified if not second else simplified[1:]) + length = sum(math.dist(a, b) for a, b in zip(first, first[1:])) + sum( + math.dist(a, b) for a, b in zip(second, second[1:]) + ) + turn_diameter = 0.0 + turn_point = None + if enabled: + # Check full continuous segments, including off-grid endpoint connectors. + lines = [LineString(first), *[LineString(segment) for segment in second_segments]] + if any(not raw_room.buffer(-robot_radius-.019).covers(line) + or line.distance(raw_obstacles) < robot_radius+.019 for line in lines): + resampling_count += 1 + continue + carry_line = LineString(second) + for index in range(max(1, math.ceil(carry_line.length/grid))+1): + point = carry_line.interpolate(min(index*grid, carry_line.length)) + diameter = 2*min(point.distance(raw_room.boundary), point.distance(raw_obstacles)) + if diameter > turn_diameter: + turn_diameter, turn_point = diameter, (point.x, point.y) + if turn_diameter + 1e-8 < profile["carry_turn_diameter_m"]: + resampling_count += 1 + continue + if length < best_length: + best_length = length + selected = pick_approach, place_approach, first, second + selected_turn_diameter, selected_turn_point = turn_diameter, turn_point + if selected is not None: + break + if selected is None: + if enabled: + raise RobotConstraintError("connected_carry_route_or_turn", profile_id=profile["profile_id"], + resampling_count=resampling_count) + raise ValueError("no connected robot path from start through pick to place") + pick_approach, place_approach, first_path, second_path = selected + route = _simplify(first_path) + second_path[1:] + robot_summary = {"enabled": enabled, "profile": profile, "status": "disabled", "checks": [], + "resampling_count": resampling_count} + if enabled: + pick_data = next(c for c in endpoint_data[source_id] if c["navigation_station"] == pick_approach) + place_data = next(c for c in endpoint_data[target_id] if c["navigation_station"] == place_approach) + move_entity(movable, pick_data["xy"]) + config = {**config, "place_offset_xy_m": ( + place_data["xy"][0]-target.center_xy_m[0], place_data["xy"][1]-target.center_xy_m[1])} + surroundings = target_surroundings(spec, descriptors, target, place_data["support_height_m"], + place_data["xy"], movable, profile["max_grip_dimension_m"]/2) + if surroundings["hand_object_clearance_m"] < .01: + raise RobotConstraintError("target_hand_clearance", **surroundings) + hard_reasons = [] + if any(c["effective_depth_m"] > c["comfort_m"] for c in (pick_data, place_data)): + hard_reasons.append("outside_comfort_depth") + if surroundings["hard"]: + hard_reasons.append("small_crowded_target") + if profile["profile_id"] in ("luna", "default_all") and .08 <= grip_dimensions[grip_axis] <= .099: + hard_reasons.append("luna_gripper_withdrawal_margin") + raised = profile["profile_id"] in ("g1", "default_all") and place_data["support_height_m"] > .52 + robot_summary.update(status="hard" if hard_reasons else "passed", difficulty="hard" if hard_reasons else "standard", + hard_reasons=hard_reasons, + service_front_source={"source": pick_data["service_front_source"], "target": place_data["service_front_source"]}, + checks=[ + {"check_id": "support_height", "passed": True, + "measured_m": [pick_data["support_height_m"], place_data["support_height_m"]]}, + {"check_id": "placement_depth", "passed": True, "source": pick_data, "target": place_data}, + {"check_id": "service_and_spawn_connected", "passed": True, + "body_width_m": profile["body_width_m"], "body_depth_m": profile["body_depth_m"], + "source_docking_sweep_xy_m": pick_data["docking_sweep_xy_m"], + "target_docking_sweep_xy_m": place_data["docking_sweep_xy_m"]}, + {"check_id": "carry_corridor", "passed": True, + "required_m": profile["carry_corridor_width_m"], + "docking_width_m": profile["carry_corridor_width_m"] + .04, + "scope": "circular transit plus full-width rectangular docking sweeps", + "measured_m": 2*min(LineString(second_path).distance(raw_obstacles), + LineString(second_path).distance(raw_room.boundary))}, + {"check_id": "carry_turn", "passed": True, "measured_m": selected_turn_diameter, + "center_xy_m": selected_turn_point, "required_m": profile["carry_turn_diameter_m"]}, + {"check_id": "grip_dimension", "passed": True, "axis": grip_axis, + "measured_m": grip_dimensions[grip_axis], "required_max_m": profile["max_grip_dimension_m"]}, + {"check_id": "target_surroundings", "passed": True, **surroundings}, + {"check_id": "g1_raise_before_approach", "passed": True, "required": raised}, + ]) + base = _base_heights(spec, descriptors) + movable_descriptor = descriptors[movable.asset_id or ""] + target_descriptor = descriptors[target.asset_id or ""] + pick_position = ( + float(movable.center_xy_m[0]), + float(movable.center_xy_m[1]), + round(base[object_id] + movable_descriptor.height_m / 2.0, 6), + ) + place_offset = tuple(float(value) for value in config.get("place_offset_xy_m", (0.0, 0.0))) + place_position = ( + round(float(target.center_xy_m[0]) + place_offset[0], 6), + round(float(target.center_xy_m[1]) + place_offset[1], 6), + round(base[target_id] + target_descriptor.height_m + movable_descriptor.height_m / 2.0, 6), + ) + place_shape = affinity.rotate( + Polygon(movable.visual_footprint_local_m), + movable.yaw_deg, + origin=(0.0, 0.0), + ) + place_shape = affinity.translate( + place_shape, + xoff=place_position[0], + yoff=place_position[1], + ) + target_surface = Polygon(target.support_footprint_xy_m).buffer(-0.015) + if target_surface.is_empty: + target_surface = Polygon(target.visual_footprint_xy_m).buffer(-0.015) + place_supported = target_surface.buffer(1.0e-6).covers(place_shape) + child_blockers = [ + child.entity_id + for child in spec.entities + if child.parent_entity_id == target_id + and child.entity_id != object_id + and place_shape.intersection(Polygon(child.visual_footprint_xy_m)).area > 1.0e-7 + ] + maximum_height = profile["support_height_range_m"][1] if enabled else float(config.get("maximum_manipulation_height_m", 1.55)) + start_yaw = _angle_toward(start, route[1]) if len(route) > 1 else 0.0 + route_line = LineString(route) + portal_checks = [ + { + "check_id": f"route_crosses_portal_{item['portal_id']}", + "passed": route_line.intersects(LineString(item["opening_segment_xy_m"])), + "details": ( + f"portal={item['portal_id']} opening={item['opening_segment_xy_m']}" + ), + } + for item in required_portals + ] + checks = [ + {"check_id": "task_object_on_declared_source", "passed": True, + "details": f"{object_id}.parent={source_id}"}, + {"check_id": "robot_start_collision_free", "passed": is_free(start), + "details": f"start={start}"}, + {"check_id": "pick_approach_collision_free", "passed": is_free(pick_approach), + "details": f"pick_approach={pick_approach}"}, + {"check_id": "place_approach_collision_free", "passed": is_free(place_approach), + "details": f"place_approach={place_approach}"}, + {"check_id": "start_pick_place_path_connected", "passed": len(route) >= 3, + "details": f"waypoints={len(route)} length_m={best_length:.3f}"}, + {"check_id": "target_support_differs_from_source", "passed": source_id != target_id, + "details": f"source={source_id} target={target_id}"}, + {"check_id": "place_footprint_supported", "passed": place_supported, + "details": f"target={target_id} place_xy={place_position[:2]}"}, + {"check_id": "place_pose_clear_of_existing_children", "passed": not child_blockers, + "details": f"blocking_children={child_blockers}"}, + {"check_id": "pick_and_place_height_reachable", + "passed": (all(profile["support_height_range_m"][0] <= h <= maximum_height for h in (base[object_id], base[target_id]+target_descriptor.height_m)) if enabled else pick_position[2] <= maximum_height and place_position[2] <= maximum_height), + "details": ( + f"pick_z={pick_position[2]:.3f} place_z={place_position[2]:.3f} " + f"maximum_z={maximum_height:.3f}" + )}, + *portal_checks, + ] + passed = all(bool(item["passed"]) for item in checks) + if not passed: + failures = [ + f"{item['check_id']}:{item['details']}" for item in checks if not item["passed"] + ] + raise ValueError("pick-move-place task hard checks failed: " + "; ".join(failures)) + if enabled: + from packages.scene_generation.asset_first import _canonical_sha256 + spec.layout_truth_sha256 = _canonical_sha256({ + **spec.model_dump(mode="json"), "layout_truth_sha256": None}) + pick_service = pick_data["station"] if enabled else pick_approach + place_service = place_data["station"] if enabled else place_approach + service_connectors = {"pick": [pick_approach, pick_service], + "place": [place_approach, place_service]} if enabled else {} + if enabled: + best_length += 2*math.dist(pick_approach, pick_service) + math.dist(place_approach, place_service) + return PickMovePlaceTask( + task_id=str(config["task_id"]), + description_zh=str(config["description_zh"]), + description_en=str(config["description_en"]), + movable_object_entity_id=object_id, + source_support_entity_id=source_id, + target_support_entity_id=target_id, + robot_start_pose=RobotPose(x_m=start[0], y_m=start[1], yaw_deg=round(start_yaw, 6)), + pick=ManipulationEndpoint( + entity_id=object_id, + support_entity_id=source_id, + position_xyz_m=pick_position, + approach_pose=RobotPose( + x_m=round(pick_service[0], 6), y_m=round(pick_service[1], 6), + yaw_deg=round(_angle_toward(pick_service, pick_position[:2] if enabled else source.center_xy_m), 6), + ), + navigation_pose=RobotPose(x_m=pick_approach[0], y_m=pick_approach[1], + yaw_deg=round(_angle_toward(pick_approach, pick_position[:2]), 6)) if enabled else None, + ), + place=ManipulationEndpoint( + entity_id=object_id, + support_entity_id=target_id, + position_xyz_m=place_position, + approach_pose=RobotPose( + x_m=round(place_service[0], 6), y_m=round(place_service[1], 6), + yaw_deg=round(_angle_toward(place_service, place_position[:2] if enabled else target.center_xy_m), 6), + ), + navigation_pose=RobotPose(x_m=place_approach[0], y_m=place_approach[1], + yaw_deg=round(_angle_toward(place_approach, place_position[:2]), 6)) if enabled else None, + ), + route_waypoints_xy_m=[(round(x, 6), round(y, 6)) for x, y in route], + route_length_m=round(best_length, 6), + service_connectors_xy_m=service_connectors, + robot_radius_m=robot_radius, + planning_grid_m=grid, + required_portal_ids=[str(item["portal_id"]) for item in required_portals], + portal_waypoints_xy_m=[ + (round(point[0], 6), round(point[1], 6)) for point in portal_waypoints + ], + validation_checks=checks, + passed=passed, + robot_constraints=robot_summary, + ) + + +def load_task(path: Path) -> PickMovePlaceTask: + return PickMovePlaceTask.model_validate_json(path.read_text(encoding="utf-8")) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/production_agent_handlers.py b/docs/reproduction/public_conversion_code/packages/scene_generation/production_agent_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f33efc7c3a20cd64e6abea44d3b6684133f54f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/production_agent_handlers.py @@ -0,0 +1,831 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] + +from packages.core.files import atomic_write_text +from packages.scene_generation.agent_executor import AgentRuntimeContext, AgentTaskResult +from packages.scene_generation.agent_orchestration import AgentExecutionTask, AgentRole +from packages.scene_generation.deterministic_placement import PlacementCertificate + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _write_artifact(root: Path, relative: str, payload: dict[str, Any]) -> dict[str, str]: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + atomic_write_text(path, json.dumps(payload, indent=2, sort_keys=True) + "\n") + return {relative: _sha256(path)} + + +def _score(path: Path) -> tuple[float | None, dict[str, float]]: + try: + payload = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + except Exception: + return None, {} + grades = { + str(key): float(value["grade"]) + for key, value in payload.items() + if isinstance(value, dict) and isinstance(value.get("grade"), (int, float)) + } + return (min(grades.values()) if grades else None), grades + + +def _scope_polluted_score( + path: Path, + *, + owned_ids: set[str], + foreign_ids: set[str], + threshold: float, +) -> bool: + """Detect a branch critic that graded intentionally absent sibling subtrees.""" + + score, _grades = _score(path) + if score is None or score >= threshold or not foreign_ids: + return False + try: + text = path.read_text(encoding="utf-8", errors="ignore").casefold() + except OSError: + return False + foreign_mentioned = any( + entity_id.casefold() in text + or entity_id.replace("_", " ").casefold() in text + for entity_id in foreign_ids - owned_ids + ) + ownership_acknowledged = "ownership contract" in text or "owned subtree" in text + foreign_absence_penalty = any( + phrase in text + for phrase in ( + "missing foreign", + "foreign sibling", + "other required furniture", + "branches are merged", + "branches have not merged", + "otherwise empty room", + "isolated chair", + ) + ) + return foreign_mentioned and ownership_acknowledged and foreign_absence_penalty + + +class SceneSmithEvidenceHandlers: + """Turn concrete SceneSmith runs into content-addressed DAG checkpoints. + + SceneSmith's planner/designer/critic Agents do the expensive work. These handlers + are deliberately deterministic: they only accept a DAG node when an owned binding, + a completed branch run and (for critics) a real scores.yaml are present. + """ + + def __init__( + self, + output_root: Path, + upstream_root: Path, + *, + critic_min_score: float, + analytic_node_ids: set[str] | None = None, + manipulation_node_ids: set[str] | None = None, + required_support_node_ids: set[str] | None = None, + support_surface_node_ids: set[str] | None = None, + node_stages: dict[str, str] | None = None, + placement_certificates_required: bool = True, + downstream_physics_node_ids: set[str] | None = None, + world_geometry_certificate_required: bool = True, + ) -> None: + self.output_root = output_root + self.upstream_root = upstream_root + self.critic_min_score = critic_min_score + self.score_files = sorted(upstream_root.rglob("scores.yaml")) + self.binding_ids: set[str] = set() + self.entity_prim_paths: dict[str, str] = {} + self.analytic_node_ids = analytic_node_ids or set() + self.manipulation_node_ids = manipulation_node_ids or set() + self.required_support_node_ids = required_support_node_ids or set() + self.support_surface_node_ids = support_surface_node_ids or set() + self.node_stages = node_stages or {} + self.placement_certificates_required = placement_certificates_required + self.downstream_physics_node_ids = downstream_physics_node_ids or set() + self.world_geometry_certificate_required = world_geometry_certificate_required + self.run_intervals = self._load_run_intervals() + self.placement_certificates: dict[str, PlacementCertificate] = {} + self.dropped_optional_ids: set[str] = set() + + def update_scene_evidence( + self, + *, + binding_ids: set[str], + entity_prim_paths: dict[str, str], + placement_certificates: dict[str, PlacementCertificate] | None = None, + dropped_optional_ids: set[str] | None = None, + ) -> None: + self.binding_ids = set(binding_ids) + self.entity_prim_paths = dict(entity_prim_paths) + self.placement_certificates = dict(placement_certificates or {}) + self.dropped_optional_ids = set(dropped_optional_ids or set()) + + def _load_run_intervals(self) -> list[dict[str, Any]]: + intervals: list[dict[str, Any]] = [] + for path in self.upstream_root.rglob("parallel_base_branches/execution_ledger.json"): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except Exception: + continue + for item in payload.get("tasks", []): + if not isinstance(item, dict): + continue + intervals.append( + { + "run_id": f"{path.relative_to(self.upstream_root)}:{item.get('task_id')}", + "kind": str(item.get("task_id", "")).removeprefix("base-branch:"), + "node_ids": [], + **item, + } + ) + for path in self.upstream_root.rglob("parallel_furniture_subtrees/timing.json"): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except Exception: + continue + for item in payload.get("subtrees", []): + if isinstance(item, dict): + intervals.append( + { + "run_id": ( + f"{path.relative_to(self.upstream_root)}:{item.get('subtree_id')}" + ), + "kind": "furniture", + "node_ids": item.get("owned_entity_ids", []), + **item, + } + ) + for path in self.upstream_root.rglob("parallel_manipulands/timing.json"): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except Exception: + continue + for item in payload.get("shards", []): + if not isinstance(item, dict): + continue + searchable = json.dumps(item, sort_keys=True) + started = item.get("started_unix") + duration = item.get("duration_s") + intervals.append( + { + "run_id": ( + f"{path.relative_to(self.upstream_root)}:{item.get('furniture_id')}" + ), + "kind": "manipulation", + "node_ids": [ + node_id + for node_id in self.manipulation_node_ids + if node_id in searchable + ], + "started_unix": started, + "completed_unix": ( + float(started) + float(duration) + if isinstance(started, (int, float)) + and isinstance(duration, (int, float)) + else None + ), + "duration_s": duration, + "gpu_id": (item.get("attempts") or [{}])[-1].get("gpu_id"), + } + ) + return intervals + + def _actual_run_metrics(self, node_ids: list[str]) -> dict[str, Any]: + exact_candidates = [] + stage_candidates = [] + for interval in self.run_intervals: + interval_nodes = set(interval.get("node_ids") or []) + kind = str(interval.get("kind") or "") + matches_node = bool(interval_nodes & set(node_ids)) + matches_stage = any(self.node_stages.get(node_id) == kind for node_id in node_ids) + if matches_node: + exact_candidates.append(interval) + elif not interval_nodes and matches_stage: + stage_candidates.append(interval) + candidates = exact_candidates or stage_candidates + starts = [ + float(item["started_unix"]) + for item in candidates + if isinstance(item.get("started_unix"), (int, float)) + ] + ends = [ + float(item["completed_unix"]) + for item in candidates + if isinstance(item.get("completed_unix"), (int, float)) + ] + metrics: dict[str, Any] = {} + if starts and ends: + metrics.update( + { + "actual_agent_started_unix": min(starts), + "actual_agent_completed_unix": max(ends), + "actual_agent_duration_s": max(ends) - min(starts), + } + ) + metrics["actual_agent_run_ids"] = ",".join( + sorted({str(item["run_id"]) for item in candidates if item.get("run_id")}) + ) + gpu_ids = sorted( + {int(item["gpu_id"]) for item in candidates if isinstance(item.get("gpu_id"), int)} + ) + if gpu_ids: + metrics["actual_gpu_ids"] = ",".join(map(str, gpu_ids)) + return metrics + + def handlers(self) -> dict[AgentRole, Any]: + return {role: self for role in AgentRole if role is not AgentRole.PLANNING} + + def agent_scene_evidence(self) -> dict[str, Any]: + scores = [] + for path in self.score_files: + score, grades = _score(path) + if score is not None: + scores.append( + { + "path": path.relative_to(self.upstream_root).as_posix(), + "minimum_grade": score, + "grades": grades, + } + ) + physics = [] + for path in self.upstream_root.rglob("*physics_certificate.json"): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except Exception: + continue + physics.append( + { + "path": path.relative_to(self.upstream_root).as_posix(), + "status": payload.get("status"), + "included_object_ids": payload.get("included_object_ids", []), + } + ) + return {"critic_scores": scores, "physics_certificates": physics} + + def __call__(self, task: AgentExecutionTask, context: AgentRuntimeContext) -> AgentTaskResult: + if task.task_id.startswith("fit-local:"): + return self._relation(task) + if task.role in {AgentRole.ANALYTIC, AgentRole.GENERATION}: + return self._generation_or_freeze(task) + if task.role is AgentRole.LOCAL_RELATION: + return self._relation(task) + if task.role is AgentRole.LOCAL_CRITIC: + return self._critic(task, global_scope=False) + if task.role is AgentRole.DAG_ORCHESTRATOR: + return self._merge(task, context) + if task.role is AgentRole.GLOBAL_CRITIC: + return self._critic(task, global_scope=True) + raise ValueError(f"unsupported production Agent role: {task.role}") + + def _generation_or_freeze(self, task: AgentExecutionTask) -> AgentTaskResult: + if task.task_id.startswith("freeze:"): + return self._freeze(task) + node_id = task.node_id or "" + is_architecture = node_id in self.analytic_node_ids + present = ( + is_architecture + or node_id.startswith("context:") + or node_id in self.binding_ids + or node_id in self.entity_prim_paths + or node_id in self.dropped_optional_ids + ) + evidence = sorted( + path.relative_to(self.upstream_root).as_posix() + for path in self.upstream_root.rglob("*.json") + if node_id and node_id in path.as_posix() + )[:20] + payload = { + "schema_version": "1.0", + "task_id": task.task_id, + "node_id": node_id, + "accepted": present, + "source": ("analytic_floor_plan" if is_architecture else "scenesmith_owned_agent_run"), + "binding": self.entity_prim_paths.get(node_id), + "evidence": evidence, + } + relative = f"subtrees/{task.subtree_id}/generation_result.{node_id}.json" + artifacts = _write_artifact(self.output_root, relative, payload) + return AgentTaskResult( + accepted=present, + hard_gates_passed=present, + summary=f"canonical node {node_id} {'verified' if present else 'missing'}", + artifacts=artifacts, + failure_signature=None if present else f"missing_owned_node:{node_id}", + metrics=self._actual_run_metrics([node_id]), + ) + + def _relation(self, task: AgentExecutionTask) -> AgentTaskResult: + child = task.node_id or "" + parent = task.parent_id or "" + child_present = ( + child in self.analytic_node_ids + or child.startswith("context:") + or child in self.binding_ids + or child in self.entity_prim_paths + or child in self.dropped_optional_ids + ) + parent_present = ( + parent in self.binding_ids + or parent in self.entity_prim_paths + or parent in self.analytic_node_ids + or parent in self.dropped_optional_ids + ) + certificate = self.placement_certificates.get(str(task.subtree_id)) + measurement = ( + next( + (item for item in certificate.entities if item.entity_id == child), + None, + ) + if certificate is not None + else None + ) + architecture_relation = child in self.analytic_node_ids + parent_is_architecture = parent in self.analytic_node_ids + explicitly_dropped = child in self.dropped_optional_ids + geometry_passed = ( + architecture_relation + or explicitly_dropped + or ( + not self.placement_certificates_required + and certificate is None + and child_present + and parent_present + ) + or bool( + certificate + and certificate.hard_gates_passed + and measurement + and measurement.hard_gates_passed + and ( + measurement.parent_id == parent + or (measurement.parent_id is None and parent_is_architecture) + ) + ) + ) + accepted = child_present and parent_present and geometry_passed + relative = f"subtrees/{task.subtree_id}/local_relation.{child}.to.{parent}.json" + artifacts = _write_artifact( + self.output_root, + relative, + { + "schema_version": "1.0", + "task_id": task.task_id, + "child": child, + "parent": parent, + "child_prim": self.entity_prim_paths.get(child), + "parent_prim": self.entity_prim_paths.get(parent), + "preserve_child_local_transform": True, + "placement_certificate": ( + f"subtrees/{task.subtree_id}/placement_certificate.json" + if certificate is not None + else None + ), + "placement_transform_sha256": ( + measurement.transform_sha256 if measurement is not None else None + ), + "geometry_hard_gates_passed": geometry_passed, + "geometry_evidence_mode": ( + "placement_certificate" + if certificate is not None + else ( + "bound_upstream_agent_result" + if not self.placement_certificates_required + else "missing_required_placement_certificate" + ) + ), + "optional_entity_dropped": explicitly_dropped, + "accepted": accepted, + }, + ) + return AgentTaskResult( + accepted=accepted, + hard_gates_passed=accepted, + summary=f"parent-local relation {child} -> {parent} verified", + artifacts=artifacts, + failure_signature=( + None + if accepted + else ( + f"placement_certificate_failed:{child}:{parent}" + if child_present and parent_present + else f"missing_relation_binding:{child}:{parent}" + ) + ), + ) + + def _matching_scores( + self, task: AgentExecutionTask + ) -> list[tuple[Path, float, dict[str, float]]]: + terms = [value.lower() for value in task.owned_node_ids if value] + path_matches: list[tuple[Path, float, dict[str, float]]] = [] + content_matches: list[tuple[Path, float, dict[str, float]]] = [] + fallback: list[tuple[Path, float, dict[str, float]]] = [] + for path in self.score_files: + score, grades = _score(path) + if score is None: + continue + item = (path, score, grades) + fallback.append(item) + path_text = path.as_posix().lower() + if any(term in path_text for term in terms): + path_matches.append(item) + continue + try: + content = path.read_text(encoding="utf-8", errors="ignore")[:12000].lower() + except OSError: + content = "" + if any(term in content for term in terms): + content_matches.append(item) + + # The critic prose for one furniture branch can mention a sibling ID while + # checking cross-branch spacing. Path ownership is therefore authoritative; + # prose matching is only a compatibility fallback for older layouts. + selected = path_matches or content_matches or fallback + # ``scene_renders`` contains every rejected revision. When SceneSmith has + # persisted an accepted/final ``scene_states`` score for this subtree, use + # that checkpoint evidence and do not let an obsolete render permanently + # poison all later DAG iterations. + final_scores = [item for item in selected if "/scene_states/" in item[0].as_posix()] + return final_scores or selected + + def _critic(self, task: AgentExecutionTask, *, global_scope: bool) -> AgentTaskResult: + if ( + not global_scope + and task.owned_node_ids + and set(task.owned_node_ids) <= self.dropped_optional_ids + ): + relative = f"subtrees/{task.subtree_id}/local_critic.json" + artifacts = _write_artifact( + self.output_root, + relative, + { + "schema_version": "1.0", + "task_id": task.task_id, + "scope": "local_subtree", + "accepted": True, + "skipped_reason": "all_owned_entities_explicitly_dropped_optional", + "dropped_entity_ids": sorted(task.owned_node_ids), + }, + ) + return AgentTaskResult( + accepted=True, + hard_gates_passed=True, + summary="optional dropped subtree has no visual critic target", + artifacts=artifacts, + ) + candidates = self._matching_scores(task) + scope_invalid: list[tuple[Path, float, dict[str, float]]] = [] + if not global_scope: + owned_ids = set(task.owned_node_ids) + foreign_ids = set(self.entity_prim_paths) - owned_ids + scope_invalid = [ + item + for item in candidates + if _scope_polluted_score( + item[0], + owned_ids=owned_ids, + foreign_ids=foreign_ids, + threshold=self.critic_min_score, + ) + ] + candidates = [item for item in candidates if item not in scope_invalid] + score = min((item[1] for item in candidates), default=None) + physics_evidence: list[dict[str, Any]] = [] + owned_manipulation_ids = set(task.owned_node_ids) & self.manipulation_node_ids + deferred_physics_ids = owned_manipulation_ids & self.downstream_physics_node_ids + requires_local_physics = bool( + (owned_manipulation_ids - deferred_physics_ids) and not global_scope + ) + for path in self.upstream_root.rglob("*physics_certificate.json"): + try: + certificate = json.loads(path.read_text(encoding="utf-8")) + except Exception: + continue + searchable = json.dumps(certificate, sort_keys=True).lower() + if global_scope or any(node.lower() in searchable for node in task.owned_node_ids): + physics_evidence.append( + { + "path": path.relative_to(self.upstream_root).as_posix(), + "status": certificate.get("status"), + "sha256": _sha256(path), + } + ) + physics_passed = all(item["status"] == "passed" for item in physics_evidence) and ( + bool(physics_evidence) or not requires_local_physics + ) + missing_support_surfaces = sorted( + set(task.owned_node_ids) + & self.required_support_node_ids - self.support_surface_node_ids + ) + support_surfaces_passed = not missing_support_surfaces + # A global release decision must never turn missing local score files + # into ``critic_below_threshold:None``. Exact-layout runs intentionally + # skip stochastic local decoration Critics, so absence of upstream + # scores requires the independent visual global Critic instead. + visual_agent_required = bool( + (scope_invalid and not candidates) or (global_scope and not candidates) + ) + accepted = ( + (visual_agent_required or (score is not None and score >= self.critic_min_score)) + and physics_passed + and support_surfaces_passed + ) + payload = { + "schema_version": "1.0", + "task_id": task.task_id, + "scope": "global" if global_scope else "local_subtree", + "score": score, + "visual_agent_required": visual_agent_required, + "scope_invalid_score_evidence": [ + { + "path": path.relative_to(self.upstream_root).as_posix(), + "minimum_grade": item_score, + "grades": grades, + } + for path, item_score, grades in scope_invalid + ], + "threshold": self.critic_min_score, + "accepted": accepted, + "physics_required": requires_local_physics, + "downstream_physics_entity_ids": sorted(deferred_physics_ids), + "physics_passed": physics_passed, + "physics_evidence": physics_evidence, + "required_support_surfaces_passed": support_surfaces_passed, + "missing_support_surface_entity_ids": missing_support_surfaces, + "score_evidence": [ + { + "path": path.relative_to(self.upstream_root).as_posix(), + "minimum_grade": item_score, + "grades": grades, + } + for path, item_score, grades in candidates + ], + } + relative = ( + "global_critic.json" + if global_scope + else f"subtrees/{task.subtree_id}/local_critic.json" + ) + artifacts = _write_artifact(self.output_root, relative, payload) + return AgentTaskResult( + accepted=accepted, + hard_gates_passed=accepted and physics_passed, + summary=( + ( + "global critic requires independent visual Agent because no valid " + "upstream score evidence exists" + if global_scope + else "local critic requires independent visual Agent due scope-invalid " + "upstream score" + ) + if visual_agent_required + else f"{'global' if global_scope else 'local'} critic minimum grade={score}" + ), + artifacts=artifacts, + critic_score=score, + failure_signature=( + None + if accepted + else ( + "missing_support_surface:" + ",".join(missing_support_surfaces) + if missing_support_surfaces + else "missing_required_physics_certificate" + if requires_local_physics and not physics_passed + else f"critic_below_threshold:{score}" + ) + ), + ) + + def _freeze(self, task: AgentExecutionTask) -> AgentTaskResult: + subtree_dir = self.output_root / "subtrees" / str(task.subtree_id) + subtree_dir.mkdir(parents=True, exist_ok=True) + delta = subtree_dir / "owned_delta.usda" + owned = { + node_id: self.entity_prim_paths[node_id] + for node_id in task.owned_node_ids + if node_id in self.entity_prim_paths + } + lines = [ + "#usda 1.0", + "(", + ' customLayerData = { string rhg:ownership = "frozen" }', + ")", + "", + ] + for index, (node_id, prim_path) in enumerate(sorted(owned.items())): + lines.extend( + [ + f'def Scope "owned_{index}" (', + " customData = { " + f'string entity_id = "{node_id}"; ' + f'string source_prim = "{prim_path}" }}', + ")", + "{", + "}", + "", + ] + ) + atomic_write_text(delta, "\n".join(lines)) + generation_files = sorted(subtree_dir.glob("generation_result.*.json")) + relation_files = sorted(subtree_dir.glob("local_relation.*.json")) + aggregate_artifacts: dict[str, str] = {} + for name, files in ( + ("generation_result.json", generation_files), + ("local_relation.json", relation_files), + ): + relative = f"subtrees/{task.subtree_id}/{name}" + aggregate_artifacts.update( + _write_artifact( + self.output_root, + relative, + { + "schema_version": "1.0", + "subtree_id": task.subtree_id, + "items": [json.loads(path.read_text(encoding="utf-8")) for path in files], + }, + ) + ) + checkpoint_relative = f"subtrees/{task.subtree_id}/checkpoint.json" + checkpoint_artifacts = _write_artifact( + self.output_root, + checkpoint_relative, + { + "schema_version": "1.0", + "subtree_id": task.subtree_id, + "owned_node_ids": task.owned_node_ids, + "owned_prim_paths": owned, + "owned_delta_sha256": _sha256(delta), + "local_coordinates_frozen": True, + }, + ) + delta_relative = delta.relative_to(self.output_root).as_posix() + checkpoint_artifacts[delta_relative] = _sha256(delta) + checkpoint_artifacts.update(aggregate_artifacts) + return AgentTaskResult( + summary=f"froze subtree {task.subtree_id} in parent-local coordinates", + artifacts=checkpoint_artifacts, + metrics={"owned_prim_count": len(owned)}, + ) + + def _merge( + self, + task: AgentExecutionTask, + context: AgentRuntimeContext, + ) -> AgentTaskResult: + deltas = sorted((self.output_root / "subtrees").glob("*/owned_delta.usda")) + world_certificate_path = self.output_root / "world_geometry_certificate.json" + root_usd = self.output_root / str(context.scene_payload.get("root_usd") or "") + geometry_evidence_path = self.output_root / "agent_geometry_evidence.json" + if ( + not self.world_geometry_certificate_required + and not world_certificate_path.is_file() + and root_usd.is_file() + ): + # Disabling the optional placement solver does not disable provenance. + # Bind the immutable upstream root (and analytic geometry evidence when + # available) into a deterministic certificate so a downstream Agent + # never has to infer whether a null certificate is acceptable. + _write_artifact( + self.output_root, + world_certificate_path.name, + { + "schema_version": "1.0", + "hard_gates_passed": True, + "validation_mode": "upstream_root_binding", + "deterministic_placement_solver_enabled": False, + "root_usd": root_usd.relative_to(self.output_root).as_posix(), + "root_usd_sha256": _sha256(root_usd), + "agent_geometry_evidence": ( + geometry_evidence_path.relative_to(self.output_root).as_posix() + if geometry_evidence_path.is_file() + else None + ), + "agent_geometry_evidence_sha256": ( + _sha256(geometry_evidence_path) + if geometry_evidence_path.is_file() + else None + ), + }, + ) + try: + world_certificate = json.loads(world_certificate_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + world_certificate = {} + world_geometry_passed = ( + world_certificate.get("hard_gates_passed") is True + or ( + not self.world_geometry_certificate_required + and not world_certificate_path.is_file() + ) + ) + merge_failures: list[str] = [] + owned_by_node: dict[str, str] = {} + delta_records: list[dict[str, Any]] = [] + allowed_node_ids = set(task.owned_node_ids) + for delta in deltas: + checkpoint_path = delta.with_name("checkpoint.json") + try: + checkpoint = json.loads(checkpoint_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + checkpoint = {} + delta_sha256 = _sha256(delta) + subtree_id = str(checkpoint.get("subtree_id") or delta.parent.name) + owned_node_ids = [str(value) for value in checkpoint.get("owned_node_ids") or []] + owned_prim_paths = { + str(key): str(value) + for key, value in (checkpoint.get("owned_prim_paths") or {}).items() + } + if not checkpoint: + merge_failures.append(f"missing_checkpoint:{subtree_id}") + if checkpoint.get("owned_delta_sha256") != delta_sha256: + merge_failures.append(f"delta_hash_mismatch:{subtree_id}") + foreign_nodes = sorted(set(owned_node_ids) - allowed_node_ids) + if foreign_nodes: + merge_failures.append( + f"foreign_owned_nodes:{subtree_id}:" + ",".join(foreign_nodes) + ) + for node_id in owned_node_ids: + previous_owner = owned_by_node.get(node_id) + if previous_owner is not None and previous_owner != subtree_id: + merge_failures.append( + f"duplicate_node_ownership:{node_id}:{previous_owner}:{subtree_id}" + ) + owned_by_node[node_id] = subtree_id + for node_id, prim_path in owned_prim_paths.items(): + expected_path = self.entity_prim_paths.get(node_id) + if expected_path is not None and prim_path != expected_path: + merge_failures.append(f"prim_path_mismatch:{node_id}") + delta_records.append( + { + "subtree_id": subtree_id, + "path": delta.relative_to(self.output_root).as_posix(), + "sha256": delta_sha256, + "checkpoint_path": checkpoint_path.relative_to(self.output_root).as_posix(), + "checkpoint_sha256": _sha256(checkpoint_path) + if checkpoint_path.is_file() + else None, + "owned_node_ids": owned_node_ids, + "owned_prim_paths": owned_prim_paths, + "local_coordinates_frozen": checkpoint.get("local_coordinates_frozen") is True, + } + ) + if not root_usd.is_file(): + merge_failures.append("missing_composed_root_usd") + if not world_geometry_passed: + merge_failures.append("world_geometry_certificate_failed") + if not deltas: + merge_failures.append("no_owned_deltas") + root_usd_sha256 = _sha256(root_usd) if root_usd.is_file() else None + accepted = not merge_failures + relative = "agent_merge_result.json" + artifacts = _write_artifact( + self.output_root, + relative, + { + "schema_version": "1.0", + "task_id": task.task_id, + "merge_policy": "owned_delta_only", + "accepted": accepted, + "world_geometry_certificate": ( + world_certificate_path.name if world_certificate_path.is_file() else None + ), + "world_geometry_hard_gates_passed": world_geometry_passed, + "world_geometry_evidence_mode": ( + "deterministic_upstream_binding" + if world_certificate_path.is_file() + else "bound_upstream_agent_result" + ), + "world_geometry_certificate_sha256": _sha256(world_certificate_path) + if world_certificate_path.is_file() + else None, + "base_root_usd_sha256": root_usd_sha256, + "composed_result_sha256": root_usd_sha256, + "authoring_task_id": task.task_id, + "allowed_owned_node_ids": sorted(allowed_node_ids), + "dependency_freeze_hashes": { + record["subtree_id"]: record["checkpoint_sha256"] + for record in delta_records + }, + "deltas": delta_records, + "failures": merge_failures, + }, + ) + return AgentTaskResult( + accepted=accepted, + hard_gates_passed=accepted, + summary=f"merged {len(deltas)} immutable owned deltas", + artifacts=artifacts, + failure_signature=( + None + if accepted + else "merge_provenance_failed:" + ";".join(merge_failures) + ), + ) diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/prompt_multi_room.py b/docs/reproduction/public_conversion_code/packages/scene_generation/prompt_multi_room.py new file mode 100644 index 0000000000000000000000000000000000000000..8d38dbf356120bbf0229f48562a5d2f599a5baae --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/prompt_multi_room.py @@ -0,0 +1,212 @@ +from __future__ import annotations + +import hashlib +import json +import math +from typing import Literal + +from shapely.geometry import LineString, Polygon + +from packages.scene_generation.metric_layout import MetricLayoutSpec +from packages.scene_generation.multi_room import ( + MetricPortal, + MetricRoom, + MultiRoomMetricLayoutSpec, + MultiRoomMetricZone, + build_multi_room_validation_report, + door_leaf_polygon, + door_swing_polygon, + multi_room_wall_runs, +) + + +def _canonical_sha256(value: object) -> str: + return hashlib.sha256( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + +def derive_two_room_metric_v3( + placement: MetricLayoutSpec, + *, + source_entity_id: str, + target_entity_id: str, + movable_entity_id: str, + room_ids: tuple[str, str], + room_types: tuple[str, str], + split_axis: Literal["x", "y"], + portal_id: str, + seed: int, +) -> MultiRoomMetricLayoutSpec: + """Promote a validated two-zone placement to authoritative Metric V3 topology.""" + + width, depth, height = placement.room_dimensions_m + room_a_id, room_b_id = room_ids + if split_axis == "x": + room_a_polygon = [ + (-width / 2.0, -depth / 2.0), + (0.0, -depth / 2.0), + (0.0, depth / 2.0), + (-width / 2.0, depth / 2.0), + ] + room_b_polygon = [ + (0.0, -depth / 2.0), + (width / 2.0, -depth / 2.0), + (width / 2.0, depth / 2.0), + (0.0, depth / 2.0), + ] + portal_width = min(max(placement.route_width_m + 0.20, 1.35), depth - 0.30) + opening = ((0.0, -portal_width / 2.0), (0.0, portal_width / 2.0)) + else: + room_a_polygon = [ + (-width / 2.0, -depth / 2.0), + (width / 2.0, -depth / 2.0), + (width / 2.0, 0.0), + (-width / 2.0, 0.0), + ] + room_b_polygon = [ + (-width / 2.0, 0.0), + (width / 2.0, 0.0), + (width / 2.0, depth / 2.0), + (-width / 2.0, depth / 2.0), + ] + portal_width = min(max(placement.route_width_m + 0.20, 1.35), width - 0.30) + opening = ((-portal_width / 2.0, 0.0), (portal_width / 2.0, 0.0)) + + rooms = [ + MetricRoom( + room_id=room_a_id, + room_type=room_types[0], + floor_polygon_xy_m=room_a_polygon, + height_m=height, + ), + MetricRoom( + room_id=room_b_id, + room_type=room_types[1], + floor_polygon_xy_m=room_b_polygon, + height_m=height, + ), + ] + swing_polygon = door_swing_polygon( + opening_segment_xy_m=opening, + hinge_side="left" if seed % 2 == 0 else "right", + open_angle_deg=90.0, + swing_room=Polygon(room_a_polygon), + portal_id=portal_id, + ) + portal = MetricPortal( + portal_id=portal_id, + kind="door", + room_a_id=room_a_id, + room_b_id=room_b_id, + opening_segment_xy_m=opening, + clear_width_m=portal_width, + clear_height_m=min(2.20, height - 0.20), + wall_thickness_m=0.10, + hinge_side="left" if seed % 2 == 0 else "right", + swing_room_id=room_a_id, + swing_polygon_xy_m=swing_polygon, + initial_open_fraction=1.0, + ) + zone_room = {"room_a_zone": room_a_id, "room_b_zone": room_b_id} + zones = [ + MultiRoomMetricZone( + zone_id=zone.zone_id, + room_id=zone_room[zone.zone_id], + polygon_xy_m=zone.polygon_xy_m, + ) + for zone in placement.zones + if zone.zone_id in zone_room + ] + entity_room = { + source_entity_id: room_a_id, + movable_entity_id: room_a_id, + target_entity_id: room_b_id, + } + entities = [] + for entity in placement.entities: + room_id = entity_room.get(entity.entity_id, zone_room.get(entity.zone_id)) + if room_id is None: + raise ValueError(f"cannot assign room ownership to {entity.entity_id}") + entities.append(entity.model_copy(update={"room_id": room_id})) + + draft = MultiRoomMetricLayoutSpec( + source_blueprint=placement.source_blueprint, + source_blueprint_sha256=placement.source_blueprint_sha256, + source_hints_sha256=placement.source_hints_sha256, + rooms=rooms, + portals=[portal], + zones=zones, + entities=entities, + keep_out_regions=[], + route_width_m=placement.route_width_m, + route_polygon_xy_m=placement.route_polygon_xy_m, + route_room_ids=[room_a_id, room_b_id], + route_portal_ids=[portal_id], + robot_start_xy_m=placement.robot_start_xy_m, + robot_start_room_id=room_a_id, + wall_thickness_m=0.10, + asset_binding_mode="asset_first", + asset_descriptor_index=placement.asset_descriptor_index, + asset_selection_path=placement.asset_selection_path, + asset_selection_sha256=placement.asset_selection_sha256, + coordinate_solver="metric_v3_two_room_from_seeded_asset_placement", + ) + truth = _canonical_sha256(draft.model_dump(mode="json", exclude={"layout_truth_sha256"})) + layout = draft.model_copy(update={"layout_truth_sha256": truth}) + report = build_multi_room_validation_report(layout) + if not report["passed"]: + failures = [key for key, passed in report["checks"].items() if not passed] + raise ValueError(f"Metric V3 promotion failed: {failures}") + return layout + + +def multi_room_render_payload(layout: MultiRoomMetricLayoutSpec) -> dict[str, object]: + building_boundary = layout.building_polygon.boundary + internal_runs = [] + for run in multi_room_wall_runs(layout): + line = LineString((run.start_xy_m, run.end_xy_m)) + midpoint = line.interpolate(0.5, normalized=True) + if building_boundary.distance(midpoint) <= 1.0e-5: + continue + internal_runs.append( + { + "start_xy_m": list(run.start_xy_m), + "end_xy_m": list(run.end_xy_m), + "floor_elevation_m": run.floor_elevation_m, + "height_m": run.height_m, + } + ) + portals = [] + for portal in layout.portals: + item = portal.model_dump(mode="json") + if portal.kind == "door": + swing_room = Polygon( + layout.room_by_id[portal.swing_room_id or ""].floor_polygon_xy_m + ) + leaf = door_leaf_polygon(portal, swing_room).minimum_rotated_rectangle + points = list(leaf.exterior.coords)[:-1] + edges = [ + (math.dist(points[index], points[(index + 1) % 4]), index) + for index in range(4) + ] + _length, edge_index = max(edges) + start = points[edge_index] + end = points[(edge_index + 1) % 4] + item["door_leaf_center_xy_m"] = [ + float(leaf.centroid.x), + float(leaf.centroid.y), + ] + item["door_leaf_yaw_deg"] = math.degrees( + math.atan2(end[1] - start[1], end[0] - start[0]) + ) + portals.append(item) + return { + "schema_version": "3.0", + "rooms": [room.model_dump(mode="json") for room in layout.rooms], + "portals": portals, + "interior_wall_segments": internal_runs, + "route_room_ids": layout.route_room_ids, + "route_portal_ids": layout.route_portal_ids, + "validation": build_multi_room_validation_report(layout), + } diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/robot_constraints.py b/docs/reproduction/public_conversion_code/packages/scene_generation/robot_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..69f445d41499883388a130e0db0a23578d58bdc2 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/robot_constraints.py @@ -0,0 +1,355 @@ +"""Generation-time support/placement/service constraints using descriptor polygons only.""" + +from __future__ import annotations + +import math +from typing import Any + +from shapely import affinity +from shapely.geometry import LineString, Point, Polygon + +from packages.robots.task_constraints import depth_limits + + +def constrain_candidate_buckets(buckets: dict, config: dict) -> dict: + """Prune impossible assets before selection, keeping original ranking intact.""" + from packages.robots.task_constraints import get_task_constraints + + if not config or not config.get("robot_constraints_enabled", True): + return buckets + profile = get_task_constraints(config.get("robot_id")) + result = {role: list(items) for role, items in buckets.items()} + object_id = config["movable_object_entity_id"] + result[object_id] = [ + d for d in result[object_id] if min(d.native_bbox_m) <= profile["max_grip_dimension_m"] + ] + low, high = profile["support_height_range_m"] + for role in (config["source_support_entity_id"], config["target_support_entity_id"]): + result[role] = [d for d in result[role] if low <= d.height_m <= high] + return result + + +class RobotConstraintError(ValueError): + def __init__(self, check_id: str, **details: Any): + self.robot_constraints = {"status": "failed", "check_id": check_id, **details} + import json + + super().__init__(json.dumps({"robot_constraints": self.robot_constraints})) + + +def service_frame( + entity: Any, + descriptor: Any, + floor: Polygon | None = None, + inferred_normal: tuple[float, float] | None = None, +) -> tuple[Point, tuple[float, float], str]: + """Use authored descriptor direction before inferring an inward layout face. + + A descriptor's authored axis need not be a photometrically verified semantic + certificate for these rough constraints. Unknown/default-only axes do not + override a real against-wall layout inference. + """ + surface = Polygon(entity.support_footprint_xy_m or entity.visual_footprint_xy_m) + axes = {"+X": (1, 0), "-X": (-1, 0), "+Y": (0, 1), "-Y": (0, -1)} + local = axes.get(descriptor.functional_front_axis) + if local is None and descriptor.front_axis_source != "unknown": + local = axes.get(descriptor.front_axis) + if local is None: + for clearance in descriptor.operational_clearance: + c = Polygon(clearance.polygon_m).centroid + if math.hypot(c.x, c.y) > 1e-6: + local = (c.x / math.hypot(c.x, c.y), c.y / math.hypot(c.x, c.y)) + break + if local is not None: + angle = math.radians(entity.yaw_deg) + front = ( + local[0] * math.cos(angle) - local[1] * math.sin(angle), + local[0] * math.sin(angle) + local[1] * math.cos(angle), + ) + source = "descriptor" + elif entity.world_front_vector_xy is not None: + front = entity.world_front_vector_xy + source = "descriptor" + elif inferred_normal is not None: + front, source = inferred_normal, "inferred" + elif floor is not None: + footprint = Polygon(entity.collision_footprint_xy_m or entity.visual_footprint_xy_m) + # The closest room wall is the back wall for an against-wall placement. + # Its inward normal is the operational front; no authored default +Y is used. + walls = list(floor.exterior.coords) + candidates = [] + for start, end in zip(walls, walls[1:], strict=False): + dx, dy = end[0] - start[0], end[1] - start[1] + length = math.hypot(dx, dy) + if length <= 1e-8: + continue + normal = (-dy / length, dx / length) + midpoint = ((start[0] + end[0]) / 2, (start[1] + end[1]) / 2) + if not floor.covers( + Point(midpoint[0] + normal[0] * 0.001, midpoint[1] + normal[1] * 0.001) + ): + normal = (-normal[0], -normal[1]) + candidates.append((footprint.distance(LineString([start, end])), normal)) + candidates.sort(key=lambda item: item[0]) + if candidates and candidates[0][0] <= 0.35: + front = candidates[0][1] + else: + center = floor.representative_point() + dx, dy = center.x - surface.centroid.x, center.y - surface.centroid.y + if abs(dx) + abs(dy) <= 1e-8: + front = (0.0, 1.0) # Candidate only: service width/connectivity must still pass. + else: + front = ( + (math.copysign(1.0, dx), 0.0) + if abs(dx) > abs(dy) + else (0.0, math.copysign(1.0, dy)) + ) + source = "inferred" + else: + raise RobotConstraintError("service_front_undetermined", entity_id=entity.entity_id) + extent = max( + (x - surface.centroid.x) * front[0] + (y - surface.centroid.y) * front[1] + for x, y in surface.exterior.coords + ) + return ( + Point(surface.centroid.x + extent * front[0], surface.centroid.y + extent * front[1]), + front, + source, + ) + + +def footprint_at(entity: Any, xy: tuple[float, float]) -> Polygon: + return affinity.translate( + affinity.rotate(Polygon(entity.visual_footprint_local_m), entity.yaw_deg, origin=(0, 0)), + xoff=xy[0], + yoff=xy[1], + ) + + +def endpoint_candidates( + spec: Any, + descriptors: Any, + support: Any, + movable: Any, + height: float, + profile: dict, + floor: Any, + obstacles: Any, + radius: float, + inferred_normal: tuple[float, float] | None = None, +) -> list[dict]: + low, high = profile["support_height_range_m"] + if not low <= height <= high: + raise RobotConstraintError( + "support_height", entity_id=support.entity_id, measured_m=height, allowed_m=[low, high] + ) + comfort, reachable = depth_limits(profile, height) + edge, normal, front_source = service_frame( + support, descriptors[support.asset_id], floor, inferred_normal + ) + tangent = (-normal[1], normal[0]) + surface = Polygon(support.support_footprint_xy_m or support.visual_footprint_xy_m) + width = profile["body_width_m"] + depth = profile["body_depth_m"] + 0.04 + obstacle_front = max( + (x - edge.x) * normal[0] + (y - edge.y) * normal[1] + for x, y in support.collision_footprint_xy_m + ) + # The navigation circle represents lateral carrying clearance, NOT body length. + # Dock with the actual rectangular footprint; keep a separate circular predock. + offset = depth / 2 + 0.01 + max(0.0, obstacle_front) + navigation_offset = max(offset, radius + 0.03 + max(0.0, obstacle_front)) + standoff_extra = max(0.0, offset - profile["body_depth_m"] / 2 - 0.01) + output = [] + # Sample from the service edge inward, never seed at the tabletop centroid. + for i in range(1, math.ceil(reachable / 0.025) + 1): + d = min(i * 0.025, reachable) + if d + standoff_extra > reachable: + continue + for j in range(0, 31): + lateral = 0 if j == 0 else ((j + 1) // 2) * 0.05 * (1 if j % 2 else -1) + xy = ( + edge.x - normal[0] * d + tangent[0] * lateral, + edge.y - normal[1] * d + tangent[1] * lateral, + ) + shape = footprint_at(movable, xy) + if not surface.buffer(-0.015).covers(shape): + continue + if any( + e.parent_entity_id == support.entity_id + and e.entity_id != movable.entity_id + and shape.buffer(0.01).intersects(Polygon(e.visual_footprint_xy_m)) + for e in spec.entities + ): + continue + # Reserve a rectangle of the full footprint, outside drawer/door sweeps. + station = ( + edge.x + normal[0] * offset + tangent[0] * lateral, + edge.y + normal[1] * offset + tangent[1] * lateral, + ) + navigation_station = ( + edge.x + normal[0] * navigation_offset + tangent[0] * lateral, + edge.y + normal[1] * navigation_offset + tangent[1] * lateral, + ) + strip = Polygon( + [ + ( + station[0] + normal[0] * a + tangent[0] * b, + station[1] + normal[1] * a + tangent[1] * b, + ) + for a, b in ( + (-depth / 2, -width / 2), + (-depth / 2, width / 2), + (depth / 2, width / 2), + (depth / 2, -width / 2), + ) + ] + ) + # Sweep the entire carrying width through the straight docking motion. + carry_width = profile["carry_corridor_width_m"] + 0.04 + + def rect(center, carry_width=carry_width): + return Polygon( + [ + ( + center[0] + normal[0] * a + tangent[0] * b, + center[1] + normal[1] * a + tangent[1] * b, + ) + for a, b in ( + (-depth / 2, -carry_width / 2), + (-depth / 2, carry_width / 2), + (depth / 2, carry_width / 2), + (depth / 2, -carry_width / 2), + ) + ] + ) + + docking_sweep = rect(station).union(rect(navigation_station)).convex_hull + if ( + not floor.covers(strip) + or strip.intersects(obstacles) + or not floor.covers(docking_sweep) + or docking_sweep.intersects(obstacles) + ): + continue + output.append( + dict( + xy=xy, + station=station, + navigation_station=navigation_station, + service_front_source=front_source, + service_front_normal_xy=normal, + docking_sweep_xy_m=list(docking_sweep.exterior.coords), + depth_m=d, + comfort_m=comfort, + effective_depth_m=d + standoff_extra, + standoff_extra_m=standoff_extra, + reachable_m=reachable, + service_strip_xy_m=list(strip.exterior.coords), + inferred_front=front_source == "inferred", + support_height_m=height, + ) + ) + output.sort( + key=lambda c: ( + c["effective_depth_m"] > comfort, + abs(c["depth_m"] - 0.15), + math.dist(c["xy"], (edge.x, edge.y)), + ) + ) + if front_source == "inferred" and inferred_normal is None: + for alternative in ((1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)): + if math.dist(alternative, normal) < 1e-6: + continue + try: + output.extend( + endpoint_candidates( + spec, + descriptors, + support, + movable, + height, + profile, + floor, + obstacles, + radius, + inferred_normal=alternative, + ) + ) + except RobotConstraintError: + pass + if not output: + raise RobotConstraintError( + "service_or_depth", + entity_id=support.entity_id, + reachable_m=reachable, + body_width_m=width, + ) + return output + + +def move_entity(entity: Any, xy: tuple[float, float]) -> None: + dx, dy = xy[0] - entity.center_xy_m[0], xy[1] - entity.center_xy_m[1] + for field in ( + "visual_footprint_xy_m", + "collision_footprint_xy_m", + "support_footprint_xy_m", + "layout_reserve_envelope_xy_m", + "operational_clearance_polygon_xy_m", + ): + points = getattr(entity, field) + if points: + setattr(entity, field, [(x + dx, y + dy) for x, y in points]) + if entity.rotated_obb_m: + obb = dict(entity.rotated_obb_m) + if obb.get("center_m"): + x, y, z = obb["center_m"] + obb["center_m"] = [x + dx, y + dy, z] + if obb.get("footprint_polygon_xy_m"): + obb["footprint_polygon_xy_m"] = [ + (x + dx, y + dy) for x, y in obb["footprint_polygon_xy_m"] + ] + entity.rotated_obb_m = obb + entity.center_xy_m = xy + + +def target_surroundings( + spec: Any, + descriptors: Any, + target: Any, + height: float, + xy: tuple[float, float], + movable: Any, + hand_reserve_m: float = 0.0, +) -> dict: + surface = Polygon(target.support_footprint_xy_m or target.visual_footprint_xy_m) + bounds = surface.minimum_rotated_rectangle.exterior.coords + sides = [LineString([bounds[i], bounds[i + 1]]) for i in range(4)] + blockers = [ + e + for e in spec.entities + if e.entity_id not in (target.entity_id, movable.entity_id) + and e.parent_entity_id is None + and e.support_type == "floor" + and e.base_elevation_m + descriptors[e.asset_id].height_m > height + ] + crowded = sum( + any(side.distance(Polygon(e.visual_footprint_xy_m)) < 0.5 for e in blockers) + for side in sides + ) + # Conservative scalar hand reserve: same grip axis at source and destination. + clearance = min( + ( + footprint_at(movable, xy) + .buffer(hand_reserve_m) + .distance(Polygon(e.visual_footprint_xy_m)) + for e in blockers + ), + default=100.0, + ) + return { + "small_surface": min(s.length for s in sides) < 0.5, + "crowded_sides": crowded, + "hand_object_clearance_m": clearance, + "hard": min(s.length for s in sides) < 0.5 and crowded >= 2, + } diff --git a/docs/reproduction/public_conversion_code/packages/scene_generation/semantic_constraints.py b/docs/reproduction/public_conversion_code/packages/scene_generation/semantic_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..b6677e4d9d3745465b1248b0d1d95417f02d0c11 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/scene_generation/semantic_constraints.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +import math +import re +from typing import Any + +_APART_RANGE = re.compile( + r"(?P\d+(?:\.\d+)?)\s*(?:to|[-~])\s*" + r"(?P\d+(?:\.\d+)?)\s*(?:meters?|metres?|m)\s+apart\b", + re.IGNORECASE, +) + + +def compile_task_semantic_constraints( + task: dict[str, Any], + configured: list[dict[str, Any]] | None = None, +) -> list[dict[str, Any]]: + """Compile scene-layout requirements without another model call. + + Explicit YAML/JSON constraints remain authoritative. Task-Agent structured + constraints and conservative attribute/predicate fallbacks fill gaps for a + newly generated case. The fallback intentionally recognizes only relations + that name stable task entities and numeric ``A to B meters apart`` ranges. + """ + + result: list[dict[str, Any]] = [] + seen: set[str] = set() + seen_relations: set[tuple[str, str, str, str]] = set() + + def add(value: Any) -> None: + if not isinstance(value, dict): + return + relation = str(value.get("relation") or "") + subject = str(value.get("subject") or "") + object_id = str(value.get("object") or "") + if not relation or not subject or not object_id: + return + normalized = dict(value) + if relation == "opposite_sides": + normalized.setdefault("enforce", True) + normalized.setdefault("constraint_id", f"{relation}:{subject}:{object_id}") + key = str(normalized["constraint_id"]) + signature = (relation, subject, object_id, str(normalized.get("anchor") or "")) + if key not in seen and signature not in seen_relations: + result.append(normalized) + seen.add(key) + seen_relations.add(signature) + + for constraint in configured or []: + add(constraint) + metadata = task.get("metadata") or {} + if isinstance(metadata, dict): + for constraint in metadata.get("semantic_constraints") or []: + add(constraint) + + entities = { + str(item.get("entity_id")): item + for item in task.get("entities") or [] + if isinstance(item, dict) and item.get("entity_id") + } + for entity_id, entity in entities.items(): + attributes = entity.get("attributes") or {} + target = str(attributes.get("oriented_toward") or "") + if target in entities: + add( + { + "constraint_id": f"facing:{entity_id}:{target}", + "relation": "facing", + "subject": entity_id, + "object": target, + } + ) + + opposite_groups: dict[str, list[str]] = {} + for entity_id, entity in entities.items(): + attributes = entity.get("attributes") or {} + placement = str(attributes.get("placement") or "").casefold() + target = str(attributes.get("oriented_toward") or "") + if "opposite" in placement and target in entities: + opposite_groups.setdefault(target, []).append(entity_id) + for anchor, members in sorted(opposite_groups.items()): + for left, right in zip(sorted(members)[::2], sorted(members)[1::2], strict=False): + add( + { + "constraint_id": f"opposite_sides:{left}:{right}:{anchor}", + "relation": "opposite_sides", + "subject": left, + "object": right, + "anchor": anchor, + } + ) + + # For simple A-to-B transfers, the source and target supports are already + # unambiguous in the initial and goal predicate graphs. + initial_supports = { + str(item.get("subject")): str(item.get("object")) + for item in task.get("initial_predicates") or [] + if isinstance(item, dict) + and item.get("name") in {"on", "supported_by"} + and item.get("subject") + and item.get("object") + } + goal_supports = { + str(item.get("subject")): str(item.get("object")) + for item in task.get("goal_predicates") or [] + if isinstance(item, dict) + and item.get("name") in {"on", "supported_by"} + and item.get("subject") + and item.get("object") + } + transfer_pairs = sorted( + { + (initial_supports[item], goal_supports[item]) + for item in set(initial_supports) & set(goal_supports) + if initial_supports[item] != goal_supports[item] + and initial_supports[item] in entities + and goal_supports[item] in entities + } + ) + range_match = _APART_RANGE.search(str(task.get("natural_language") or "")) + if len(transfer_pairs) == 1 and range_match: + source, target = transfer_pairs[0] + add( + { + "constraint_id": f"transfer_support_distance:{source}:{target}", + "relation": "center_distance", + "subject": source, + "object": target, + "minimum_distance_m": float(range_match.group("minimum")), + "maximum_distance_m": float(range_match.group("maximum")), + } + ) + return result + + +def calibrate_facing_axes( + constraints: list[dict[str, Any]], + geometry_evidence: dict[str, Any], +) -> list[dict[str, Any]]: + """Bind an explicit cardinal local front axis after a critic pose proposal. + + Retrieved libraries do not share one furniture-front convention. The proposed + rotation and target direction provide a deterministic calibration signal; the + subsequent global visual critic remains the authority on whether that axis + corresponds to the visible front of the asset. + """ + + entities = geometry_evidence.get("entities") or {} + result: list[dict[str, Any]] = [] + for constraint in constraints: + updated = dict(constraint) + if constraint.get("relation") != "facing": + result.append(updated) + continue + subject = entities.get(str(constraint.get("subject") or "")) + object_record = entities.get(str(constraint.get("object") or "")) + if not isinstance(subject, dict) or not isinstance(object_record, dict): + result.append(updated) + continue + subject_transform = subject.get("transform") or {} + object_transform = object_record.get("transform") or {} + subject_position = subject_transform.get("translation") + object_position = object_transform.get("translation") + rotation = subject_transform.get("rotation_wxyz") + if not ( + isinstance(subject_position, (list, tuple)) + and isinstance(object_position, (list, tuple)) + and len(subject_position) >= 2 + and len(object_position) >= 2 + and isinstance(rotation, (list, tuple)) + and len(rotation) == 4 + ): + result.append(updated) + continue + w, x, y, z = (float(value) for value in rotation) + yaw = math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)) + target = ( + float(object_position[0]) - float(subject_position[0]), + float(object_position[1]) - float(subject_position[1]), + ) + target_norm = math.hypot(*target) + if target_norm <= 1.0e-9: + result.append(updated) + continue + axes = { + "+x": (math.cos(yaw), math.sin(yaw)), + "+y": (-math.sin(yaw), math.cos(yaw)), + "-x": (-math.cos(yaw), -math.sin(yaw)), + "-y": (math.sin(yaw), -math.cos(yaw)), + } + updated["forward_axis_local"] = max( + axes, + key=lambda name: ( + axes[name][0] * target[0] + axes[name][1] * target[1], + name, + ), + ) + result.append(updated) + return result diff --git a/docs/reproduction/public_conversion_code/packages/schemas/__init__.py b/docs/reproduction/public_conversion_code/packages/schemas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..742b87c55dabe86f0c7e09b99beb9f3eaee07ec2 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/schemas/__init__.py @@ -0,0 +1,43 @@ +from packages.schemas.models import ( + BenchmarkEpisode, + BenchmarkSuiteManifest, + BenchmarkSuiteSpec, + DifficultyVector, + EpisodeVariantSpec, + EvaluationResult, + FeasibilityReport, + PredicateSpec, + RobotCapabilityProfile, + SceneManifest, + SkillInvocation, + SkillSpec, + StageEvaluationResult, + SuiteEvaluationSummary, + TaskEntity, + TaskPlan, + TaskRecord, + TaskSpec, + TaskStageSpec, +) + +__all__ = [ + "BenchmarkEpisode", + "BenchmarkSuiteSpec", + "DifficultyVector", + "EvaluationResult", + "BenchmarkSuiteManifest", + "EpisodeVariantSpec", + "StageEvaluationResult", + "SuiteEvaluationSummary", + "TaskStageSpec", + "FeasibilityReport", + "PredicateSpec", + "RobotCapabilityProfile", + "SceneManifest", + "SkillInvocation", + "SkillSpec", + "TaskEntity", + "TaskPlan", + "TaskRecord", + "TaskSpec", +] diff --git a/docs/reproduction/public_conversion_code/packages/schemas/models.py b/docs/reproduction/public_conversion_code/packages/schemas/models.py new file mode 100644 index 0000000000000000000000000000000000000000..556999abf3e4a47f9e7bb8806dc87d8ca0d6c1d6 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/schemas/models.py @@ -0,0 +1,384 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from enum import StrEnum +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_serializer, model_validator + +Score = Annotated[float, Field(ge=0.0, le=1.0)] + + +class StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class ReviewStatus(StrEnum): + CANDIDATE = "candidate" + REVIEWED = "reviewed" + PUBLISHED = "published" + REJECTED = "rejected" + + +class DifficultyVector(StrictModel): + """Normalized body, interaction, and horizon/cognitive difficulty.""" + + body: Score + manipulation: Score + cognition: Score + body_reason: str = "" + manipulation_reason: str = "" + cognition_reason: str = "" + + @property + def mean(self) -> float: + return (self.body + self.manipulation + self.cognition) / 3.0 + + +class TaskRecord(StrictModel): + schema_version: Literal["1.0"] = "1.0" + record_id: str + name: str + description: str + benchmark: str + category: str + difficulty: DifficultyVector + tier: Literal["L0", "L1", "L2", "L3"] + source_uri: str | None = None + media_uri: str | None = None + source_license: str | None = None + review_status: ReviewStatus = ReviewStatus.CANDIDATE + provenance: dict[str, Any] = Field(default_factory=dict) + tags: list[str] = Field(default_factory=list) + + +class TaskEntity(StrictModel): + entity_id: str + role: Literal["BACKGROUND", "CONTEXT", "MANIPULATED", "TARGET", "DISTRACTOR", "ROBOT", "REGION"] + category: str + attributes: dict[str, Any] = Field(default_factory=dict) + required: bool = True + + +class PredicateSpec(StrictModel): + name: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + subject: str + object: str | None = None + params: dict[str, float | int | str | bool] = Field(default_factory=dict) + hold_seconds: float = Field(default=0.0, ge=0.0) + + @model_validator(mode="after") + def validate_temporal_parameters(self) -> PredicateSpec: + temporal = self.params.get("temporal") + if temporal is not None and temporal not in {"current", "ever", "always"}: + raise ValueError("predicate params.temporal must be current, ever, or always") + sync_group = self.params.get("synchronization_group") + sync_window = self.params.get("synchronization_window_s") + if sync_group is not None and (not isinstance(sync_group, str) or not sync_group.strip()): + raise ValueError("predicate params.synchronization_group must be a non-empty string") + if sync_window is not None and ( + isinstance(sync_window, bool) + or not isinstance(sync_window, (int, float)) + or sync_window < 0 + ): + raise ValueError("predicate params.synchronization_window_s must be non-negative") + if sync_window is not None and sync_group is None: + raise ValueError( + "predicate params.synchronization_window_s requires synchronization_group" + ) + unit = self.params.get("unit") + if unit is not None and unit not in {"degrees", "radians"}: + raise ValueError("predicate params.unit must be degrees or radians") + if self.name == "pressed" and "joint" not in self.params: + raise ValueError("pressed predicate requires params.joint") + if self.name == "pressed": + threshold = self.params.get("threshold") + if isinstance(threshold, bool) or not isinstance(threshold, (int, float)): + raise ValueError("pressed predicate requires a numeric params.threshold") + if self.params.get("direction") not in {"gte", "lte"}: + raise ValueError("pressed predicate requires params.direction gte or lte") + if self.name == "open" and "joint" in self.params: + threshold = self.params.get("threshold") + if isinstance(threshold, bool) or not isinstance(threshold, (int, float)): + raise ValueError("joint-based open predicate requires a numeric threshold") + if self.params.get("direction") not in {"gte", "lte"}: + raise ValueError("joint-based open predicate requires direction gte or lte") + return self + + +class SkillSpec(StrictModel): + schema_version: Literal["1.0"] = "1.0" + skill_id: str + description: str + required_capabilities: set[str] = Field(default_factory=set) + allowed_parameters: set[str] = Field(default_factory=set) + produced_predicates: set[str] = Field(default_factory=set) + + +class SkillInvocation(StrictModel): + invocation_id: str + skill_id: str + parameters: dict[str, str | int | float | bool] = Field(default_factory=dict) + depends_on: list[str] = Field(default_factory=list) + + +class TaskPlan(StrictModel): + schema_version: Literal["1.0"] = "1.0" + plan_id: str + natural_language: str + skills: list[SkillInvocation] + required_capabilities: set[str] = Field(default_factory=set) + difficulty: DifficultyVector + + @field_serializer("required_capabilities") + def serialize_required_capabilities(self, value: set[str]) -> list[str]: + return sorted(value) + + @model_validator(mode="after") + def validate_graph(self) -> TaskPlan: + ids = [item.invocation_id for item in self.skills] + if len(ids) != len(set(ids)): + raise ValueError("skill invocation ids must be unique") + known: set[str] = set() + for invocation in self.skills: + missing = set(invocation.depends_on) - known + if missing: + raise ValueError(f"dependencies must precede invocation: {sorted(missing)}") + known.add(invocation.invocation_id) + return self + + +class TaskStageSpec(StrictModel): + """One independently scored phase in a task execution.""" + + stage_id: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + name: str + completion_predicates: list[PredicateSpec] = Field(min_length=1) + invariants: list[PredicateSpec] = Field(default_factory=list) + depends_on: list[str] = Field(default_factory=list) + weight: float = Field(default=1.0, gt=0.0) + + +class TaskSpec(StrictModel): + schema_version: Literal["1.0"] = "1.0" + task_id: str + natural_language: str + task_type: str + required_rooms: list[str] + entities: list[TaskEntity] + initial_predicates: list[PredicateSpec] = Field(default_factory=list) + forbidden_initial_predicates: list[PredicateSpec] = Field(default_factory=list) + goal_predicates: list[PredicateSpec] + safety_predicates: list[PredicateSpec] = Field(default_factory=list) + stages: list[TaskStageSpec] = Field(default_factory=list) + plan: TaskPlan + evaluator_template: str = "predicate_graph_v1" + random_seed: int = 0 + parameters: dict[str, str | int | float | bool] = Field(default_factory=dict) + metadata: dict[str, Any] = Field(default_factory=dict) + + @model_validator(mode="after") + def validate_entity_references(self) -> TaskSpec: + entity_ids = {entity.entity_id for entity in self.entities} + for predicate in ( + self.initial_predicates + + self.forbidden_initial_predicates + + self.goal_predicates + + self.safety_predicates + + [item for stage in self.stages for item in stage.completion_predicates] + + [item for stage in self.stages for item in stage.invariants] + ): + for reference in (predicate.subject, predicate.object): + if reference and reference != "robot" and reference not in entity_ids: + raise ValueError(f"predicate references unknown entity: {reference}") + stage_ids = [stage.stage_id for stage in self.stages] + if len(stage_ids) != len(set(stage_ids)): + raise ValueError("task stage IDs must be unique") + known: set[str] = set() + for stage in self.stages: + missing = set(stage.depends_on) - known + if missing: + raise ValueError(f"task stage dependencies must precede stage: {sorted(missing)}") + known.add(stage.stage_id) + return self + + +class RobotCapabilityProfile(StrictModel): + task_constraints: dict[str, Any] = Field(default_factory=dict) + schema_version: Literal["1.0"] = "1.0" + robot_id: str + display_name: str + model_version: str + embodiment_plugin: str + capabilities: set[str] + control_modes: set[str] + observation_keys: set[str] + height_m: float = Field(gt=0) + shoulder_width_m: float = Field(gt=0) + footprint_radius_m: float = Field(gt=0) + payload_kg: float = Field(ge=0) + metadata: dict[str, Any] = Field(default_factory=dict) + + +class RobotSpawnSpec(StrictModel): + """Scene-level robot placement and optional visual-asset override.""" + + translation_m: tuple[float, float, float] = (0.0, 0.0, 0.0) + rotation_rpy_deg: tuple[float, float, float] = (0.0, 0.0, 0.0) + asset_uri: str | None = None + + +class CapabilityMatch(StrictModel): + compatible: bool + robot_id: str + required: set[str] + missing: set[str] + + +class PredicateResult(StrictModel): + predicate: PredicateSpec + passed: bool + observed: dict[str, Any] = Field(default_factory=dict) + + +class StageEvaluationResult(StrictModel): + stage_id: str + passed: bool + score: Score + predicate_results: list[PredicateResult] + first_success_time_s: float | None = Field(default=None, ge=0.0) + failure_reason: str | None = None + + +class EvaluationResult(StrictModel): + success: bool + final_score: float = Field(ge=0.0, le=1.0) + predicate_results: list[PredicateResult] + safety_events: list[str] = Field(default_factory=list) + first_success_time_s: float | None = Field(default=None, ge=0.0) + terminal_reason: str + stage_results: list[StageEvaluationResult] = Field(default_factory=list) + stage_progress: Score = 0.0 + + +class BenchmarkEpisode(StrictModel): + schema_version: Literal["1.0"] = "1.0" + benchmark_version: str + episode_id: str + task_id: str + scene_id: str + root_usd_uri: str + robot_profile: str + seed: int + evaluator_uri: str + max_duration_s: float = Field(gt=0) + split: Literal["train", "val", "test", "hidden_test"] + factor_values: dict[str, Any] = Field(default_factory=dict) + + +class BenchmarkSuiteSpec(StrictModel): + schema_version: Literal["1.0"] = "1.0" + suite_id: str + requested_episodes: int = Field(gt=0) + robot_profiles: list[str] + category_weights: dict[str, float] = Field(default_factory=dict) + target_difficulty: DifficultyVector + seed: int + created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) + + +class EpisodeVariantSpec(StrictModel): + episode_id: str + task_family: str + template_name: str + level: str + condition: str + seed: int + factor_values: dict[str, str | int | float | bool] = Field(default_factory=dict) + task_uri: str + root_usd_uri: str + evaluator_uri: str + + +class BenchmarkSuiteManifest(StrictModel): + schema_version: Literal["1.0"] = "1.0" + suite_id: str + benchmark_version: str + robot_profile: str + shared_scene_uri: str + asset_lock_uri: str + episodes: list[EpisodeVariantSpec] = Field(min_length=1) + metrics: list[str] = Field(default_factory=list) + created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) + + @model_validator(mode="after") + def validate_episode_ids(self) -> BenchmarkSuiteManifest: + ids = [episode.episode_id for episode in self.episodes] + if len(ids) != len(set(ids)): + raise ValueError("suite episode IDs must be unique") + return self + + +class SuiteEvaluationSummary(StrictModel): + schema_version: Literal["1.0"] = "1.0" + suite_id: str + episode_count: int = Field(ge=0) + successful_episodes: int = Field(ge=0) + success_rate: Score + atomic_macro_success_rate: Score + extension_success_rate: Score + mean_stage_progress: Score + safety_failure_count: int = Field(ge=0) + task_family_success_rates: dict[str, Score] = Field(default_factory=dict) + missing_episode_ids: list[str] = Field(default_factory=list) + + +class SceneLayerPlan(StrictModel): + root_layer: str = "root.usda" + layers: dict[str, str] + + +class SceneManifest(StrictModel): + schema_version: Literal["1.0"] = "1.0" + scene_id: str + task_id: str + random_seed: int + layer_plan: SceneLayerPlan + entity_prim_paths: dict[str, str] + robot_prim_path: str + source_checkpoints: dict[str, str] = Field(default_factory=dict) + content_hash: str + + @model_validator(mode="after") + def validate_prim_paths(self) -> SceneManifest: + paths = [*self.entity_prim_paths.values(), self.robot_prim_path] + if any(not path.startswith("/World/") for path in paths): + raise ValueError("scene prim paths must be absolute children of /World") + if len(paths) != len(set(paths)): + raise ValueError("scene entity and robot prim paths must be unique") + return self + + +class ValidationCheck(StrictModel): + name: str + passed: bool + message: str = "" + evidence_uri: str | None = None + + +class ValidationReport(StrictModel): + schema_version: Literal["1.0"] = "1.0" + scene_id: str + robot_id: str + passed: bool + checks: list[ValidationCheck] + simulator_version: str + seed: int + + +class FeasibilityReport(StrictModel): + schema_version: Literal["1.0"] = "1.0" + task_id: str + robot_id: str + capability_match: CapabilityMatch + validation: ValidationReport | None = None diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/__init__.py b/docs/reproduction/public_conversion_code/packages/supervisor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbde14a9e7817b6e5d99d59884c362f97d88a7ef --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/__init__.py @@ -0,0 +1,25 @@ +"""Case-level autonomous benchmark iteration.""" + +from packages.supervisor.case import CaseManager, derive_case_id +from packages.supervisor.models import ( + AttemptManifest, + GateResult, + IterationPolicy, + QualityReport, + RepairAction, + RepairPlan, +) +from packages.supervisor.runner import IterationResult, SupervisorRunner + +__all__ = [ + "AttemptManifest", + "CaseManager", + "GateResult", + "IterationPolicy", + "IterationResult", + "QualityReport", + "RepairAction", + "RepairPlan", + "SupervisorRunner", + "derive_case_id", +] diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/case.py b/docs/reproduction/public_conversion_code/packages/supervisor/case.py new file mode 100644 index 0000000000000000000000000000000000000000..63eaba052bdf5ccd144c066754b4ca2ed2b93240 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/case.py @@ -0,0 +1,500 @@ +from __future__ import annotations + +import hashlib +import json +import re +import shutil +from collections.abc import Iterator +from contextlib import contextmanager +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from packages.benchmark.artifact_lifecycle import ( + replace_major_copy, + replace_major_from_portable, +) +from packages.benchmark.portable import create_zstd_archive, portable_source_fingerprint +from packages.core.file_lock import lock_file, unlock_file +from packages.core.files import atomic_write_text +from packages.supervisor.models import AttemptManifest, QualityReport + +VERSION_PATTERN = re.compile(r"^v(?P[1-9][0-9]*)-(?P[0-9]{8})$") +LEGACY_PATTERN = re.compile( + r"^(?:scenesmith-)?(?P.+?)-v(?P[1-9][0-9]*)-(?P[0-9]{8})(?:-portable)?$" +) + + +def derive_case_id(prompt: str) -> str: + words = re.findall(r"[a-z0-9]+", prompt.casefold()) + ignored = {"a", "an", "the", "to", "from", "and", "with", "in", "on", "of"} + slug = "-".join(word for word in words if word not in ignored)[:64].strip("-") + if slug: + return slug + return f"case-{hashlib.sha256(prompt.encode('utf-8')).hexdigest()[:12]}" + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _world_certificate_allows_downstream_validation(certificate: dict[str, Any]) -> bool: + """Accept either a completed USD check or an explicitly deferred upstream binding. + + ``upstream_root_binding`` is emitted when deterministic placement is disabled. It + proves the immutable SceneSmith root and its geometry evidence were bound, while + the required portable and Isaac validators below provide the actual stage-open, + prim, bounds, collision, and stability checks. Other certificate modes must + continue to carry their own successful USD validation result. + """ + + return certificate.get("hard_gates_passed") is True and ( + certificate.get("usd_validation_passed") is True + or certificate.get("validation_mode") == "upstream_root_binding" + ) + + +def _requires_scenesmith_world_certificate(scenesmith_root: Path) -> bool: + """Media fallback alone must not make a deterministic run look SceneSmith-owned.""" + + return (scenesmith_root / "stage_manifest.json").is_file() or ( + scenesmith_root / "scene.usdc" + ).is_file() + + +class CaseManager: + def __init__(self, root: Path, *, allow_non_isaac_portable: bool = False) -> None: + self.root = root.resolve() + self.allow_non_isaac_portable = allow_non_isaac_portable + + @contextmanager + def locked(self) -> Iterator[None]: + self.root.mkdir(parents=True, exist_ok=True) + lock_path = self.root / ".case.lock" + with lock_path.open("a+", encoding="utf-8") as handle: + lock_file(handle) + try: + yield + finally: + unlock_file(handle) + + @contextmanager + def campaign_locked(self) -> Iterator[None]: + """Serialize Supervisors for one case while still allowing parallel inner stages.""" + self.root.mkdir(parents=True, exist_ok=True) + lock_path = self.root / ".campaign.lock" + with lock_path.open("a+", encoding="utf-8") as handle: + lock_file(handle) + try: + yield + finally: + unlock_file(handle) + + def initialize(self, *, case_id: str, prompt: str, robot: str, seed: int) -> None: + payload = { + "schema_version": "1.0", + "case_id": case_id, + "prompt": prompt, + "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), + "robot": robot, + "seed": seed, + "created_at": datetime.now(UTC).isoformat(), + } + with self.locked(): + path = self.root / "case.json" + if path.is_file(): + existing = json.loads(path.read_text(encoding="utf-8")) + identity = ("case_id", "prompt_sha256", "robot", "seed") + if any(existing.get(key) != payload[key] for key in identity): + raise ValueError(f"case identity differs from existing {path}") + return + atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + + def allocate_attempt(self, *, parent_version: str | None) -> tuple[Path, AttemptManifest]: + with self.locked(): + numbers = [ + int(match.group("number")) + for child in self.root.iterdir() + if child.is_dir() and (match := VERSION_PATTERN.fullmatch(child.name)) + ] + version = f"v{max(numbers, default=0) + 1}-{datetime.now().strftime('%Y%m%d')}" + output = self.root / version + output.mkdir() + started = datetime.now(UTC).isoformat() + design_contract: str | None = None + fixed_dag_sha256: str | None = None + fixed_graph_id: str | None = None + contract_path = self.root / "case_design" / "contract.json" + if contract_path.is_file(): + contract = json.loads(contract_path.read_text(encoding="utf-8")) + design_contract = "../../case_design/contract.json" + fixed_dag_sha256 = str(contract.get("dependency_graph_sha256") or "") or None + fixed_graph_id = str(contract.get("graph_id") or "") or None + manifest = AttemptManifest( + version=version, + status="running", + parent_version=parent_version, + design_contract=design_contract, + fixed_dag_sha256=fixed_dag_sha256, + fixed_graph_id=fixed_graph_id, + started_at=started, + ) + self.write_attempt(output, manifest) + return output, manifest + + def write_attempt(self, output: Path, manifest: AttemptManifest) -> None: + path = output / "supervisor" / "attempt_manifest.json" + atomic_write_text(path, manifest.model_dump_json(indent=2) + "\n") + + def read_attempt(self, output: Path) -> AttemptManifest: + path = output / "supervisor" / "attempt_manifest.json" + return AttemptManifest.model_validate_json(path.read_text(encoding="utf-8")) + + def append_attempt(self, manifest: AttemptManifest) -> None: + with self.locked(): + path = self.root / "attempts.jsonl" + with path.open("a", encoding="utf-8") as handle: + handle.write(manifest.model_dump_json() + "\n") + handle.flush() + + def update_campaign(self) -> None: + attempts = [] + for child in sorted(self.root.iterdir()): + if not child.is_dir() or VERSION_PATTERN.fullmatch(child.name) is None: + continue + path = child / "supervisor" / "attempt_manifest.json" + if path.is_file(): + attempts.append(json.loads(path.read_text(encoding="utf-8"))) + payload = { + "schema_version": "1.0", + "updated_at": datetime.now(UTC).isoformat(), + "attempt_count": len(attempts), + "attempts": attempts, + } + atomic_write_text( + self.root / "campaign_manifest.json", + json.dumps(payload, ensure_ascii=False, indent=2) + "\n", + ) + + def release(self, output: Path, report: QualityReport) -> Path: + if not report.accepted or not report.hard_gates_passed or not report.critic_passed: + raise ValueError("refusing to release an attempt that did not pass all gates") + major_manifest_path = self.root / "major" / "major_manifest.json" + major_manifest = ( + json.loads(major_manifest_path.read_text(encoding="utf-8")) + if major_manifest_path.is_file() + else {} + ) + if ( + major_manifest.get("source_version") != output.name + or not self._portable_matches_source(self.root / "major", output) + ): + self.consider_for_major(output, report) + major_manifest = ( + json.loads(major_manifest_path.read_text(encoding="utf-8")) + if major_manifest_path.is_file() + else {} + ) + if ( + major_manifest.get("source_version") != output.name + or not self._portable_matches_source(self.root / "major", output) + ): + raise ValueError("refusing release because portable major was not materialized") + portable_path = self._portable_release_path(output) + portable_file = self.root / portable_path if portable_path else None + if portable_file is None or not portable_file.exists(): + raise ValueError("refusing release because portable package is missing") + portable_sha256 = ( + _sha256_file(portable_file) + if portable_file is not None and portable_file.is_file() + else None + ) + payload = { + "schema_version": "1.0", + "released_at": datetime.now(UTC).isoformat(), + "version": output.name, + "run_dir": output.name, + "quality_report": f"{output.name}/supervisor/quality_report.json", + "portable_package": portable_path, + "portable_sha256": portable_sha256, + "major_dir": "major", + "certification_level": ( + "portable_contract" + if self.allow_non_isaac_portable + else "isaac_validated_portable" + ), + } + path = self.root / "release.json" + atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + (self.root / "blocked.json").unlink(missing_ok=True) + return path + + def consider_for_major(self, output: Path, report: QualityReport) -> bool: + """Promote only a version accepted by every final publication gate.""" + + if not ( + report.accepted + and report.hard_gates_passed + and report.critic_passed + ): + return False + + output = output.resolve() + minimum_major_files = ( + output / "root.usda", + output / "snapshot.jpg", + output / "preview.mp4", + output / "iteration_history.mp4", + ) + minimum_major_ready = all(path.is_file() for path in minimum_major_files) + portable = self.root / "packages" / output.name + validation_path = output / "manifests" / "portable_validation.json" + validation: dict[str, Any] | None = None + portable_ready = False + if portable.is_dir() and validation_path.is_file(): + try: + validation = json.loads(validation_path.read_text(encoding="utf-8")) + task_path = output / "manifests/task.json" + if not task_path.is_file(): + task_path = portable / "manifests/task.json" + task = json.loads(task_path.read_text(encoding="utf-8")) + manipulated_ids = { + str(entity.get("entity_id")) + for entity in task.get("entities", []) + if isinstance(entity, dict) and entity.get("role") == "MANIPULATED" + } + physics = (validation.get("usd") or {}).get("manipulation_physics") or {} + portable_ready = bool( + validation.get("passed") + and self._portable_matches_source(portable, output) + and not any( + not isinstance(physics.get(entity_id), dict) + or not physics[entity_id].get("rigid_body_api") + or not physics[entity_id].get("collision_prim_paths") + for entity_id in manipulated_ids + ) + ) + except (OSError, ValueError, json.JSONDecodeError): + portable_ready = False + + scenesmith_root = output / "scenesmith" + if portable_ready and _requires_scenesmith_world_certificate(scenesmith_root): + world_certificate_path = scenesmith_root / "world_geometry_certificate.json" + try: + world_certificate = json.loads( + world_certificate_path.read_text(encoding="utf-8") + ) + except (OSError, json.JSONDecodeError): + portable_ready = False + else: + portable_ready = _world_certificate_allows_downstream_validation( + world_certificate + ) + if not portable_ready and not minimum_major_ready: + return False + + candidate_rank = self._quality_rank(report) + manifest_path = self.root / "major.json" + with self.locked(): + current: dict[str, Any] | None = None + if manifest_path.is_file(): + current = json.loads(manifest_path.read_text(encoding="utf-8")) + current_rank = tuple(current.get("quality_rank", [])) if current else () + rank_migrated = False + if current and len(current_rank) != len(candidate_rank): + source_version = current.get("source_version") + source_quality = ( + self.root / str(source_version) / "supervisor" / "quality_report.json" + ) + if source_quality.is_file(): + try: + incumbent_report = QualityReport.model_validate_json( + source_quality.read_text(encoding="utf-8") + ) + except (OSError, ValueError): + pass + else: + current_rank = self._quality_rank(incumbent_report) + current["quality_rank"] = list(current_rank) + rank_migrated = True + major_manifest_path = self.root / "major/major_manifest.json" + major_manifest = ( + json.loads(major_manifest_path.read_text(encoding="utf-8")) + if major_manifest_path.is_file() + else {} + ) + already_portable_major = major_manifest.get("materialization_version") == "5.0" + same_source_needs_upgrade = bool( + portable_ready + and current + and current.get("source_version") == output.name + and ( + not already_portable_major + or not self._portable_matches_source(self.root / "major", output) + ) + ) + major_missing = not (self.root / "major").is_dir() + if ( + current_rank + and candidate_rank <= current_rank + and not same_source_needs_upgrade + and not major_missing + ): + if rank_migrated and current is not None: + atomic_write_text( + manifest_path, + json.dumps(current, ensure_ascii=False, indent=2) + "\n", + ) + return False + if portable_ready: + lifecycle = replace_major_from_portable( + portable, self.root / "major", source_version=output + ) + certification_level = ( + "portable_contract" + if self.allow_non_isaac_portable + else "isaac_validated_portable" + ) + else: + lifecycle = replace_major_copy(output, self.root / "major") + certification_level = "best_effort_attempt" + archive = self.root / "packages" / "major.tar.zst" + archive.parent.mkdir(parents=True, exist_ok=True) + temporary_archive = archive.with_name(f".{archive.name}.tmp") + temporary_archive.unlink(missing_ok=True) + create_zstd_archive(self.root / "major", temporary_archive) + temporary_archive.replace(archive) + payload = { + "schema_version": "1.0", + "updated_at": datetime.now(UTC).isoformat(), + "source_version": output.name, + "quality_rank": list(candidate_rank), + "accepted": report.accepted, + "hard_gates_passed": report.hard_gates_passed, + "critic_passed": report.critic_passed, + "critic_score": report.critic_score, + "major_dir": "major", + "snapshot": "major/snapshot.jpg", + "preview": "major/preview.mp4", + "iteration_history": "major/iteration_history.mp4", + "portable_archive": "packages/major.tar.zst", + "portable_archive_sha256": _sha256_file(archive), + "portable_verification": validation if portable_ready else None, + "artifact_lifecycle": lifecycle, + "certification_level": certification_level, + } + atomic_write_text( + manifest_path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n" + ) + return True + + def _portable_matches_source(self, portable: Path, source: Path) -> bool: + manifest_path = portable / "portable_manifest.json" + isaac_path = portable / "manifests" / "isaac_validation.json" + if not manifest_path.is_file() or ( + not self.allow_non_isaac_portable and not isaac_path.is_file() + ): + return False + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + isaac = ( + json.loads(isaac_path.read_text(encoding="utf-8")) + if isaac_path.is_file() + else {} + ) + expected_fingerprint = portable_source_fingerprint(source) + except (OSError, ValueError, json.JSONDecodeError): + return False + runtime = manifest.get("runtime_requirements") or {} + return bool( + manifest.get("source_fingerprint") == expected_fingerprint + and ( + self.allow_non_isaac_portable + or ( + isaac.get("passed") is True + and runtime.get("simulator") == "Isaac Sim 6.0.1" + ) + ) + ) + + @staticmethod + def _quality_rank( + report: QualityReport, + ) -> tuple[int, int, int, int, float, int, int]: + severe = [gate for gate in report.gates if gate.severity == "severe"] + severe_passed = sum(gate.passed for gate in severe) + observed_critic_scores = [ + float(match) + for gate in report.gates + for match in re.findall( + r"critic_below_threshold:([0-9]+(?:\.[0-9]+)?)", gate.message + ) + ] + completion_stage = ( + 2 + if report.critic_score is not None + else 1 + if observed_critic_scores + else 0 + ) + effective_critic_score = ( + report.critic_score + if report.critic_score is not None + else min(observed_critic_scores) + if observed_critic_scores + else -1.0 + ) + return ( + int(report.accepted), + int(report.hard_gates_passed), + int(report.critic_passed), + completion_stage, + effective_critic_score, + severe_passed, + -len(severe), + ) + + def _portable_release_path(self, output: Path) -> str | None: + archive = self.root / "packages" / f"{output.name}.tar.zst" + if archive.is_file(): + return archive.relative_to(self.root).as_posix() + directory = self.root / "packages" / output.name + return directory.relative_to(self.root).as_posix() if directory.is_dir() else None + + def block(self, *, reason: str, elapsed_s: float, last_version: str | None) -> Path: + payload = { + "schema_version": "1.0", + "blocked_at": datetime.now(UTC).isoformat(), + "reason": reason, + "elapsed_s": round(elapsed_s, 3), + "last_version": last_version, + "resumable": True, + } + path = self.root / "blocked.json" + atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + return path + + +def plan_legacy_migration(source_root: Path) -> list[dict[str, Any]]: + plan: list[dict[str, Any]] = [] + for child in sorted(source_root.iterdir()): + if not child.is_dir() or not (match := LEGACY_PATTERN.fullmatch(child.name)): + continue + case_id = re.sub(r"[^a-z0-9]+", "-", match.group("case").casefold()).strip("-") + version = f"v{match.group('number')}-{match.group('date')}" + plan.append({"source": str(child), "destination": str(source_root / case_id / version)}) + return plan + + +def apply_legacy_migration(plan: list[dict[str, Any]]) -> None: + for item in plan: + source = Path(str(item["source"])) + destination = Path(str(item["destination"])) + if destination.exists(): + raise FileExistsError(destination) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(source), str(destination)) diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/models.py b/docs/reproduction/public_conversion_code/packages/supervisor/models.py new file mode 100644 index 0000000000000000000000000000000000000000..6750e516699392e762eda68783cb02e0d64d50fc --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/models.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +from enum import StrEnum +from pathlib import Path +from typing import Any, Literal + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +class RepairAction(StrEnum): + REPROJECT_ENTITY_ON_CANONICAL_SUPPORT = "reproject_entity_on_canonical_support" + REPLACE_OR_REBIND_ASSET_EXACT_ID = "replace_or_rebind_asset_exact_id" + HIDE_DUPLICATE_PROXY = "hide_duplicate_proxy" + RERUN_BRANCH = "rerun_branch" + RERUN_STAGE_FROM_CHECKPOINT = "rerun_stage_from_checkpoint" + ADJUST_STAGE_BUDGET = "adjust_stage_budget" + RERENDER_PREVIEW = "rerender_preview" + REEXPORT_CANONICAL_USD = "reexport_canonical_usd" + + +class RepairStep(BaseModel): + model_config = ConfigDict(extra="forbid") + + action: RepairAction + entity_ids: list[str] = Field(default_factory=list) + stage: str | None = None + branch: str | None = None + asset_id: str | None = None + checkpoint: str | None = None + parameters: dict[str, str | int | float | bool] = Field(default_factory=dict) + reason: str = Field(min_length=1) + + +class RepairPlan(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["1.0"] = "1.0" + parent_version: str + failure_signature: str + strategy: str + steps: list[RepairStep] = Field(min_length=1) + expected_improvement: str + + +class GateResult(BaseModel): + model_config = ConfigDict(extra="forbid") + + gate_id: str + passed: bool + severity: Literal["info", "warning", "severe"] = "severe" + message: str + affected_entities: list[str] = Field(default_factory=list) + metric: float | None = None + threshold: float | None = None + evidence: dict[str, Any] = Field(default_factory=dict) + + +class QualityReport(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["1.0"] = "1.0" + accepted: bool + hard_gates_passed: bool + critic_passed: bool + critic_score: float | None = None + gates: list[GateResult] + failure_signature: str | None = None + + +class IterationPolicy(BaseModel): + model_config = ConfigDict(extra="forbid") + + enabled: bool = True + wall_clock_budget_s: float = Field(default=7200.0, gt=0) + max_parallel_attempts: int | Literal["auto"] = "auto" + stagnation_repeat_limit: int = Field(default=2, ge=1) + critic_min_score: float = Field(default=6.5, ge=0, le=10) + # Internal/test callers opt in explicitly. User-facing CLI/API request + # defaults are strict and pass True when constructing this runtime policy. + critic_required: bool = False + # None means there is no outer-attempt count limit. Wall-clock, + # repeated-failure, stagnation, and repair-strategy guards still apply. + max_total_attempts: int | None = Field(default=None, ge=1) + first_attempt_budget_multiplier: float = Field(default=1.5, ge=1.25, le=1.6) + same_failure_signature_limit: int = Field(default=2, ge=2, le=10) + checkpoint_repairs_only_after_first: bool = True + repair_policy: Path | None = None + quality_policy: Path | None = None + + @classmethod + def from_yaml(cls, path: Path) -> IterationPolicy: + payload = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + if "iteration" in payload: + payload = payload["iteration"] + return cls.model_validate(payload) + + +class AttemptManifest(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["1.0"] = "1.0" + version: str + status: Literal["running", "failed", "passed", "superseded"] + parent_version: str | None = None + design_contract: str | None = None + fixed_dag_sha256: str | None = None + fixed_graph_id: str | None = None + started_at: str + completed_at: str | None = None + duration_s: float | None = None + repair_plan: str | None = None + quality_report: str | None = None + failure_signature: str | None = None + error: str | None = None + + +class IterationPolicyRequest(BaseModel): + """YAML-facing policy; paths remain portable and are resolved by the CLI.""" + + model_config = ConfigDict(extra="forbid") + + enabled: bool = True + wall_clock_budget_s: float = Field(default=7200.0, gt=0) + max_parallel_attempts: int | Literal["auto"] = "auto" + stagnation_repeat_limit: int = Field(default=2, ge=1) + critic_min_score: float = Field(default=6.5, ge=0, le=10) + critic_required: bool = True + max_total_attempts: int | None = Field(default=None, ge=1) + first_attempt_budget_multiplier: float = Field(default=1.5, ge=1.25, le=1.6) + same_failure_signature_limit: int = Field(default=2, ge=2, le=10) + checkpoint_repairs_only_after_first: bool = True + repair_policy: str = "configs/supervisor/repair_policy_v1.yaml" + quality_policy: str = "configs/supervisor/quality_gates_strict_v1.yaml" + + @model_validator(mode="after") + def reject_absolute_policy_paths(self) -> IterationPolicyRequest: + for value in (self.repair_policy, self.quality_policy): + if Path(value).is_absolute() or ".." in Path(value).parts: + raise ValueError("supervisor policy paths must be repository-relative") + return self diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/planner.py b/docs/reproduction/public_conversion_code/packages/supervisor/planner.py new file mode 100644 index 0000000000000000000000000000000000000000..c01cfe45bb87f0c91b93ea3c1216ebc53b108b1f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/planner.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] + +from packages.generative import GenerativeClient, RelaySettings +from packages.supervisor.models import QualityReport, RepairPlan + + +class RepairPlanner: + """Produces schema-validated plans from a configuration-owned action catalog.""" + + def __init__(self, policy_path: Path | None, stagnation_repeat_limit: int) -> None: + self.repeat_limit = stagnation_repeat_limit + self.config: dict[str, Any] = {} + if policy_path and policy_path.is_file(): + self.config = yaml.safe_load(policy_path.read_text(encoding="utf-8")) or {} + + def plan( + self, + report: QualityReport, + *, + parent_version: str, + signature_occurrences: int, + ) -> RepairPlan | None: + failed = [gate for gate in report.gates if not gate.passed and gate.severity == "severe"] + gate_ids = sorted(gate.gate_id for gate in failed) + strategies = self._matching_strategies(gate_ids) + strategy_index = (max(signature_occurrences, 1) - 1) // self.repeat_limit + if strategy_index >= len(strategies): + return None + selected = strategies[strategy_index] + steps = json.loads( + json.dumps(selected["steps"]).replace("PLACEHOLDER_PARENT", parent_version) + ) + affected_entities = sorted( + { + entity_id + for gate in failed + for entity_id in gate.affected_entities + } + ) + if affected_entities: + for step in steps: + if ( + step.get("action") == "rerun_branch" + and step.get("stage") == "furniture" + and not step.get("entity_ids") + ): + step["entity_ids"] = affected_entities + template = { + "schema_version": "1.0", + "parent_version": parent_version, + "failure_signature": report.failure_signature or "unknown", + "strategy": str(selected["strategy"]), + "steps": steps, + "expected_improvement": str( + selected.get("expected_improvement", "resolve failed gates") + ), + } + if ( + self.config.get("agent_planning", {}).get("enabled", False) + and RelaySettings.status_from_env()["configured"] + ): + template = self._agent_select( + template, + strategies[strategy_index:], + gate_ids, + parent_version, + ) + return RepairPlan.model_validate(template) + + def _matching_strategies(self, gate_ids: list[str]) -> list[dict[str, Any]]: + matched = [] + for item in self.config.get("strategies", []): + gates = set(item.get("when_gates", [])) + if "*" in gates or gates.intersection(gate_ids): + matched.append(item) + return matched + + @staticmethod + def _agent_select( + template: dict[str, Any], + strategies: list[dict[str, Any]], + gate_ids: list[str], + parent_version: str, + ) -> dict[str, Any]: + prompt = ( + "Choose exactly one repair strategy for the failed RoboHouseGen gates. " + "Do not invent actions or fields. Return the selected strategy JSON verbatim.\n" + f"Failed gates: {json.dumps(gate_ids)}\n" + f"Allowed strategies: {json.dumps(strategies)}" + ) + raw = GenerativeClient(RelaySettings.from_env()).generate_text(prompt) + try: + chosen = json.loads(raw[raw.index("{") : raw.rindex("}") + 1]) + except (ValueError, json.JSONDecodeError): + return template + allowed = next( + (item for item in strategies if item.get("strategy") == chosen.get("strategy")), None + ) + if allowed is None: + return template + return { + **template, + "strategy": allowed["strategy"], + "steps": json.loads( + json.dumps(allowed["steps"]).replace("PLACEHOLDER_PARENT", parent_version) + ), + "expected_improvement": allowed.get("expected_improvement", "resolve failed gates"), + } diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/quality.py b/docs/reproduction/public_conversion_code/packages/supervisor/quality.py new file mode 100644 index 0000000000000000000000000000000000000000..db8a92629e0cc26497d44909671340f7e23dbfff --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/quality.py @@ -0,0 +1,1135 @@ +from __future__ import annotations + +import hashlib +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +import uuid +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] +from PIL import Image, ImageDraw + +from packages.benchmark.portable import ( + create_portable_bundle, + create_zstd_archive, + portable_source_fingerprint, + refresh_checksums, + verify_portable_bundle, +) +from packages.core.files import atomic_write_text +from packages.generative import GenerativeClient, RelaySettings +from packages.supervisor.models import GateResult, IterationPolicy, QualityReport +from packages.supervisor.visual_preflight import evaluate_visual_preflight + + +def _json(path: Path) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(value, dict): + raise ValueError(f"expected JSON object: {path}") + return value + + +def _asset_ids(value: object) -> set[str]: + found: set[str] = set() + if isinstance(value, dict): + asset_id = value.get("asset_id") + if isinstance(asset_id, str): + found.add(asset_id) + for child in value.values(): + found.update(_asset_ids(child)) + elif isinstance(value, list): + for child in value: + found.update(_asset_ids(child)) + return found + + +def _global_critic_affected_entities(output: Path, valid_entity_ids: set[str]) -> list[str]: + path = output / "scenesmith" / "agent_outputs" / "global-critic__scene.json" + if not path.is_file(): + return [] + try: + payload = _json(path) + except (OSError, ValueError, json.JSONDecodeError): + return [] + directive = payload.get("repair_directive") or {} + candidates = directive.get("entities") if isinstance(directive, dict) else [] + return sorted( + {str(entity_id) for entity_id in candidates or [] if str(entity_id) in valid_entity_ids} + ) + + +def _robot_release_gates(output: Path) -> list[GateResult]: + """Require geometric and visual proof whenever a benchmark contains a robot.""" + robot_path = output / "manifests" / "robot.json" + if not robot_path.is_file(): + return [] + + placement_path = output / "manifests" / "robot_placement_validation.json" + placement = _json(placement_path) if placement_path.is_file() else {} + placement_facts = { + key: placement.get(key) + for key in ( + "passed", + "footprint_inside_room", + "wall_clearance_passed", + "obstacle_clearance_passed", + "source_approach_passed", + "source_facing_passed", + ) + } + placement_passed = placement_path.is_file() and all( + value is True for value in placement_facts.values() + ) + + preview_path = output / "scenesmith" / "preview_camera_manifest.json" + preview = _json(preview_path) if preview_path.is_file() else {} + shots = preview.get("shots") if isinstance(preview, dict) else [] + required_shots = [ + shot + for shot in (shots if isinstance(shots, list) else []) + if isinstance(shot, dict) and shot.get("required_robot_full_body") is True + ] + preview_passed = ( + preview_path.is_file() + and preview.get("passed") is True + and preview.get("robot_detected") is True + and bool(required_shots) + and all( + shot.get("passed") is True and shot.get("robot_full_body_visible") is True + for shot in required_shots + ) + ) + + critic_path = output / "scenesmith" / "final_composed_critic_views" / "manifest.json" + critic = _json(critic_path) if critic_path.is_file() else {} + audit = critic.get("robot_visual_audit") if isinstance(critic, dict) else {} + audit = audit if isinstance(audit, dict) else {} + views = critic.get("views") if isinstance(critic, dict) else {} + views = views if isinstance(views, dict) else {} + robot_view = views.get("robot_access") + resolved_robot_view = None + if isinstance(robot_view, str) and robot_view: + candidate = Path(robot_view) + resolved_robot_view = candidate if candidate.is_absolute() else output / "scenesmith" / candidate + critic_passed = ( + critic_path.is_file() + and audit.get("passed") is True + and int(audit.get("detected_mesh_count") or 0) > 0 + and audit.get("view_created") is True + and resolved_robot_view is not None + and resolved_robot_view.is_file() + ) + + return [ + GateResult( + gate_id="robot_room_placement", + passed=placement_passed, + message=f"report_present={placement_path.is_file()} facts={placement_facts}", + affected_entities=[] if placement_passed else ["robot"], + evidence={"report": str(placement_path.relative_to(output))}, + ), + GateResult( + gate_id="robot_preview_visibility", + passed=preview_passed, + message=( + f"report_present={preview_path.is_file()} detected={preview.get('robot_detected')} " + f"required_full_body_shots={len(required_shots)}" + ), + affected_entities=[] if preview_passed else ["robot"], + evidence={"report": str(preview_path.relative_to(output))}, + ), + GateResult( + gate_id="robot_global_critic_visibility", + passed=critic_passed, + message=( + f"report_present={critic_path.is_file()} audit={audit} " + f"robot_access_present={bool(resolved_robot_view and resolved_robot_view.is_file())}" + ), + affected_entities=[] if critic_passed else ["robot"], + evidence={"report": str(critic_path.relative_to(output))}, + ), + ] + + +def _usd_python_from_environment() -> str: + configured = os.environ.get("RHG_USD_PYTHON", "").strip() + if configured: + return configured + scenesmith_command = os.environ.get("SCENESMITH_COMMAND", "").strip() + if scenesmith_command: + return shlex.split(scenesmith_command)[0] + data_root = os.environ.get("RHG_DATA_ROOT", "").strip() + if data_root: + candidate = Path(data_root) / "conda-envs/scenesmith-sam3d/bin/python" + if candidate.is_file(): + return str(candidate) + return "" + + +class QualityEvaluator: + def __init__(self, policy: IterationPolicy) -> None: + self.policy = policy + self.config: dict[str, Any] = {} + if policy.quality_policy and policy.quality_policy.is_file(): + self.config = yaml.safe_load(policy.quality_policy.read_text(encoding="utf-8")) or {} + + def evaluate(self, output: Path) -> QualityReport: + # Author the inexpensive manipulation schema first. Visual rejection is + # evaluated before launching Isaac or portable extraction so an obviously + # low-fidelity version cannot spend minutes in external validators. + self._materialize_manipulation_physics(output) + gates: list[GateResult] = [] + agent_global_score: float | None = None + required = [ + "root.usda", + "manifests/task.json", + "manifests/scene.json", + "manifests/episode.json", + ] + missing = [name for name in required if not (output / name).is_file()] + gates.append( + GateResult( + gate_id="benchmark_contract", passed=not missing, message=f"missing={missing}" + ) + ) + if missing: + return self._report(gates, critic_passed=not self.policy.critic_required) + + task = _json(output / "manifests/task.json") + scene = _json(output / "manifests/scene.json") + expected = { + str(item["entity_id"]) + for item in task.get("entities", []) + if isinstance(item, dict) and item.get("role") != "ROBOT" + } + bindings = scene.get("entity_prim_paths", {}) + missing_entities = sorted(expected - set(bindings if isinstance(bindings, dict) else {})) + duplicate_paths = [] + if isinstance(bindings, dict): + paths = [str(bindings[item]) for item in expected if item in bindings] + duplicate_paths = sorted({path for path in paths if paths.count(path) > 1}) + gates.append( + GateResult( + gate_id="entity_identity", + passed=not missing_entities and not duplicate_paths, + message=f"missing={missing_entities} duplicate_paths={duplicate_paths}", + affected_entities=missing_entities, + ) + ) + gates.extend(_robot_release_gates(output)) + + stage_path = output / "scenesmith" / "stage_manifest.json" + if stage_path.is_file(): + stage = _json(stage_path) + gates.append( + GateResult( + gate_id="scenesmith_complete", + passed=stage.get("status") == "complete", + message=f"status={stage.get('status')}", + ) + ) + graph_files = [ + stage.get("scene_dependency_graph"), + stage.get("dependency_execution_plan"), + ] + missing_graph = [ + str(name) + for name in graph_files + if not isinstance(name, str) or not (stage_path.parent / name).is_file() + ] + gates.append( + GateResult( + gate_id="dependency_plan_saved", + passed=not missing_graph, + message=f"missing={missing_graph}", + ) + ) + if stage.get("orchestration_mode") == "dag_agents": + ledger_name = stage.get("agent_execution_ledger") + ledger_path = stage_path.parent / str(ledger_name or "") + ledger = _json(ledger_path) if ledger_name and ledger_path.is_file() else {} + records = ledger.get("records") if isinstance(ledger, dict) else {} + records = records if isinstance(records, dict) else {} + incomplete = sorted( + task_id + for task_id, record in records.items() + if not isinstance(record, dict) + or record.get("status") not in {"complete", "reused"} + ) + global_record = records.get("global-critic:scene", {}) + global_result = ( + global_record.get("result", {}) if isinstance(global_record, dict) else {} + ) + global_score = ( + global_result.get("critic_score") if isinstance(global_result, dict) else None + ) + if isinstance(global_score, (int, float)): + agent_global_score = float(global_score) + publish_gate_path = stage_path.parent / str( + stage.get("global_critic_publish_gate") or "" + ) + publish_gate = ( + _json(publish_gate_path) + if stage.get("global_critic_publish_gate") + and publish_gate_path.is_file() + else {} + ) + # The in-worker global critic is preliminary because the robot + # and outer benchmark layers do not exist yet. Release scoring + # happens below from the shared final composed contact sheet. + dag_passed = ( + ledger.get("status") == "complete" + and bool(records) + and not incomplete + and global_result.get("accepted") is True + and global_result.get("hard_gates_passed") is True + and publish_gate.get("passed") is True + ) + gates.append( + GateResult( + gate_id="agent_dag_execution", + passed=dag_passed, + message=( + f"ledger_status={ledger.get('status')} incomplete={incomplete} " + f"global_score={global_score} publish_gate={publish_gate.get('passed')}" + ), + metric=( + float(global_score) if isinstance(global_score, (int, float)) else None + ), + threshold=self.policy.critic_min_score, + affected_entities=( + [] if dag_passed else _global_critic_affected_entities(output, expected) + ), + evidence={ + "global_failure_signature": ( + global_result.get("failure_signature") + if isinstance(global_result, dict) + else None + ) + }, + ) + ) + native = stage.get("native_asset_bindings", {}) + effective_path = output / "scenesmith" / "effective_selected_assets.json" + selected_path = output / "scenesmith" / "selected_assets.json" + selected_payload = ( + _json(effective_path if effective_path.is_file() else selected_path) + if (effective_path.is_file() or selected_path.is_file()) + else {} + ) + selected_ids = _asset_ids(selected_payload) if selected_payload else set() + native_ids = ( + { + str(binding["asset_id"]) + for binding in native.values() + if isinstance(binding, dict) + and binding.get("binding_mode") != "embedded_generated" + and isinstance(binding.get("asset_id"), str) + } + if isinstance(native, dict) + else set() + ) + mismatched = sorted(native_ids - selected_ids) if selected_ids else sorted(native_ids) + locked_assets = stage.get("task_asset_overrides", {}) + wrong_locked_assets = ( + sorted( + entity + for entity, expected_asset in locked_assets.items() + if isinstance(native, dict) + and ( + not isinstance(native.get(entity), dict) + or native[entity].get("binding_mode") == "embedded_generated" + or native[entity].get("asset_id") != expected_asset + ) + ) + if isinstance(locked_assets, dict) + else [] + ) + missing_usd = ( + sorted( + entity + for entity, binding in native.items() + if isinstance(binding, dict) + and ( + not isinstance(binding.get("canonical_usd"), str) + or not Path(str(binding["canonical_usd"])).is_file() + ) + ) + if isinstance(native, dict) + else [] + ) + gates.append( + GateResult( + gate_id="canonical_asset_identity", + passed=not mismatched and not missing_usd and not wrong_locked_assets, + message=( + f"unselected_ids={mismatched} missing_usd={missing_usd} " + f"wrong_locked_assets={wrong_locked_assets}" + ), + affected_entities=sorted(set(missing_usd + wrong_locked_assets)), + ) + ) + indexed_task_entities = { + str(entity_id) + for entity_id, candidates in selected_payload.items() + if str(entity_id) in expected + and isinstance(candidates, list) + and any( + isinstance(candidate, dict) and candidate.get("asset_id") + for candidate in candidates + ) + } + embedded_indexed_entities = sorted( + entity_id + for entity_id in indexed_task_entities + if not isinstance(native, dict) + or not isinstance(native.get(entity_id), dict) + or native[entity_id].get("binding_mode") == "embedded_generated" + ) + gates.append( + GateResult( + gate_id="indexed_task_asset_binding", + passed=not embedded_indexed_entities, + message=( + "indexed_entities_without_explicit_native_binding=" + f"{embedded_indexed_entities}" + ), + affected_entities=embedded_indexed_entities, + ) + ) + + preflight_gate = self._visual_preflight(output) + gates.append(preflight_gate) + if not preflight_gate.passed: + return self._report(gates, critic_passed=False, critic_score=None) + + critic_passed, supervisor_critic_score = self._critic(output, task) + critic_score = supervisor_critic_score + supervisor_report_path = output / "supervisor/critic_report.json" + supervisor_severe = [] + if supervisor_report_path.is_file(): + supervisor_result = _json(supervisor_report_path).get("result") or {} + if isinstance(supervisor_result, dict): + raw_severe = supervisor_result.get("severe_failures") or [] + if isinstance(raw_severe, list): + supervisor_severe = raw_severe + if critic_score is None and agent_global_score is not None: + # Preserve preliminary evidence only when final visual review is + # disabled; it can never override a final composed-frame rejection. + critic_score = agent_global_score + if self.policy.critic_required or supervisor_critic_score is not None: + shared_evidence = { + "report": "scenesmith/final_global_critic_report.json", + "shared_final_frames": True, + } + gates.append( + GateResult( + gate_id="final_global_visual_critic", + passed=critic_passed, + message=( + f"score={supervisor_critic_score} threshold={self.policy.critic_min_score} " + f"severe_failures={len(supervisor_severe)}" + ), + metric=supervisor_critic_score, + threshold=self.policy.critic_min_score, + evidence=shared_evidence, + ) + ) + gates.append( + GateResult( + gate_id="supervisor_visual_critic", + passed=critic_passed, + message=( + f"score={supervisor_critic_score} " + f"required={self.policy.critic_required} " + "reference_calibrated=" + f"{(output / 'supervisor/critic_reference_manifest.json').is_file()} " + "shared_final_frames=True " + f"severe_failures={len(supervisor_severe)}" + ), + metric=supervisor_critic_score, + threshold=self.policy.critic_min_score, + evidence=shared_evidence, + ) + ) + if not critic_passed: + return self._report(gates, critic_passed=False, critic_score=critic_score) + + external_reports = self.config.get("external_reports", []) + portable_reports = [ + report_config + for report_config in external_reports + if str(report_config.get("gate_id")) == "portable_bundle_verification" + or Path(str(report_config.get("path", ""))).name == "portable_validation.json" + ] + nonportable_reports = [ + report_config + for report_config in external_reports + if report_config not in portable_reports + ] + self._materialize_validation_reports(output, include_portable=False) + + def append_report_gates(report_configs: list[dict[str, Any]]) -> None: + for report_config in report_configs: + path = output / str(report_config["path"]) + required_report = bool(report_config.get("required", True)) + payload = _json(path) if path.is_file() else {} + passed = ( + bool(payload.get(str(report_config.get("pass_field", "passed")))) + if payload + else not required_report + ) + gates.append( + GateResult( + gate_id=str(report_config["gate_id"]), + passed=passed, + message=f"report={path.relative_to(output)} present={path.is_file()}", + ) + ) + + append_report_gates(nonportable_reports) + prepublish = self._report( + gates, + critic_passed=critic_passed, + critic_score=critic_score, + ) + if not prepublish.accepted: + return prepublish + + # The exact frames consumed by the final Critic are now accepted and all + # scene/physics hard gates have passed. Only now may a release video exist. + from packages.scene_generation.orchestrator import render_accepted_final_preview + from packages.supervisor.snapshot import ensure_version_media + + if ( + (output / "scenesmith/stage_manifest.json").is_file() + and (output / "scenesmith/global_critic_publish_gate.json").is_file() + ): + render_accepted_final_preview( + output, + accepted=True, + hard_gates_passed=True, + critic_passed=True, + ) + ensure_version_media(output, force_snapshot=True) + + self._materialize_validation_reports( + output, + include_isaac=False, + include_portable=True, + ) + append_report_gates(portable_reports) + return self._report(gates, critic_passed=critic_passed, critic_score=critic_score) + + def _visual_preflight(self, output: Path) -> GateResult: + config = self.config.get("visual_preflight") or {} + config = config if isinstance(config, dict) else {} + manifest_path = output / "scenesmith/final_composed_critic_views/manifest.json" + manifest = _json(manifest_path) if manifest_path.is_file() else {} + report = evaluate_visual_preflight(manifest, config) + report_path = output / "supervisor/visual_preflight_report.json" + atomic_write_text( + report_path, + json.dumps(report, ensure_ascii=False, indent=2) + "\n", + ) + return GateResult( + gate_id="visual_preflight", + passed=report["passed"], + message=( + f"required={report['required']} manifest_present={manifest_path.is_file()} " + f"failures={report['failures']}" + ), + evidence={"report": str(report_path.relative_to(output))}, + ) + + def _materialize_validation_reports( + self, + output: Path, + *, + include_isaac: bool = True, + include_portable: bool = True, + ) -> None: + self._materialize_manipulation_physics(output) + configured = { + str(item.get("gate_id")): item for item in self.config.get("external_reports", []) + } + isaac = configured.get("isaac_physics_and_support") + isaac_report = output / "manifests" / "isaac_validation.json" + portable = configured.get("portable_bundle_verification") + portable_report = output / "manifests" / "portable_validation.json" + if ( + include_isaac + and isaac + and bool(isaac.get("required", True)) + and not isaac_report.is_file() + ): + self._run_isaac_validation(output, isaac_report) + if include_portable and portable and bool(portable.get("required", True)): + # A prior report does not prove that the bundle still matches the + # source version. The validator performs a cheap source-fingerprint + # comparison and atomically rebuilds only when evidence changed. + self._run_portable_validation(output, portable_report) + + @staticmethod + def _materialize_manipulation_physics(output: Path) -> None: + task_path = output / "manifests/task.json" + scene_path = output / "manifests/scene.json" + root_path = output / "root.usda" + report_path = output / "manifests/manipulation_physics.json" + if report_path.is_file() or not all( + path.is_file() for path in (task_path, scene_path, root_path) + ): + return + task = _json(task_path) + if not any( + isinstance(entity, dict) and entity.get("role") == "MANIPULATED" + for entity in task.get("entities", []) + ): + return + executable = sys.executable + try: + import pxr # type: ignore[import-not-found] # noqa: F401 + except ImportError: + executable = os.environ.get("RHG_USD_PYTHON", "").strip() + if not executable: + scenesmith_command = os.environ.get("SCENESMITH_COMMAND", "").strip() + executable = shlex.split(scenesmith_command)[0] if scenesmith_command else "" + try: + if not executable: + raise RuntimeError("no USD-capable Python configured") + script = Path(__file__).resolve().parents[2] / "scripts/author_manipulation_physics.py" + command = [ + *shlex.split(executable), + str(script), + "--root", + str(root_path), + "--task", + str(task_path), + "--scene", + str(scene_path), + "--report", + str(report_path), + ] + result = subprocess.run(command, capture_output=True, text=True, check=False) + if result.returncode: + raise RuntimeError((result.stdout + result.stderr)[-4000:]) + except Exception as error: + atomic_write_text( + report_path, + json.dumps( + { + "schema_version": "1.0", + "passed": False, + "error": f"{type(error).__name__}: {error}", + }, + indent=2, + ) + + "\n", + ) + refresh_checksums(output) + + def _run_portable_validation(self, output: Path, report_path: Path) -> None: + destination = output.parent / "packages" / output.name + try: + destination.parent.mkdir(parents=True, exist_ok=True) + expected_fingerprint = portable_source_fingerprint(output) + portable_manifest = destination / "portable_manifest.json" + existing_fingerprint = ( + str(_json(portable_manifest).get("source_fingerprint") or "") + if portable_manifest.is_file() + else "" + ) + portable_is_current = ( + destination.is_dir() and existing_fingerprint == expected_fingerprint + ) + require_pxr = bool(self.config.get("portable_require_pxr", True)) + usd_python = _usd_python_from_environment() + try: + import pxr # type: ignore[import-not-found] # noqa: F401 + + pxr_available = True + except ImportError: + pxr_available = False + if require_pxr and not pxr_available and usd_python: + archive = destination.with_suffix(".tar.zst") + packager = ( + Path(__file__).resolve().parents[2] / "scripts/package_portable_benchmark.py" + ) + command = [*shlex.split(usd_python), str(packager)] + if destination.exists(): + command.extend(["verify", "--bundle", str(destination), "--require-pxr"]) + else: + command.extend( + [ + "create", + "--source", + str(output), + "--output", + str(destination), + ] + ) + if self.config.get("create_archive", True): + command.extend(["--archive", str(archive)]) + result = subprocess.run(command, capture_output=True, text=True, check=False) + if result.returncode: + raise RuntimeError((result.stdout + result.stderr)[-4000:]) + payload = json.loads(result.stdout) + report = payload.get("verification", payload) + if archive.is_file(): + report["archive"] = str(archive) + else: + rebuilt = False + if not portable_is_current: + token = uuid.uuid4().hex + staging = destination.parent / f".{destination.name}.staging-{token}" + backup = destination.parent / f".{destination.name}.backup-{token}" + try: + create_portable_bundle(output, staging) + staging_report = verify_portable_bundle( + staging, require_pxr=require_pxr + ) + if not staging_report.get("passed"): + raise RuntimeError( + "staged portable verification failed: " + f"{staging_report.get('failures', [])}" + ) + if destination.exists(): + destination.rename(backup) + staging.rename(destination) + except Exception: + if backup.exists() and not destination.exists(): + backup.rename(destination) + raise + finally: + if staging.exists(): + shutil.rmtree(staging) + if backup.exists(): + shutil.rmtree(backup) + rebuilt = True + report = verify_portable_bundle(destination, require_pxr=require_pxr) + if report.get("passed") and self.config.get("create_archive", True): + archive = destination.with_suffix(".tar.zst") + if rebuilt or not archive.exists(): + temporary_archive = archive.with_name(f".{archive.name}.tmp") + temporary_archive.unlink(missing_ok=True) + create_zstd_archive(destination, temporary_archive) + temporary_archive.replace(archive) + report["archive"] = str(archive) + except Exception as error: + report = { + "schema_version": "1.0", + "passed": False, + "error": f"{type(error).__name__}: {error}", + } + atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") + + @staticmethod + def _run_isaac_validation(output: Path, report: Path) -> None: + repository = Path(__file__).resolve().parents[2] + validator = repository / "scripts" / "isaac_validate_benchmark.py" + direct = os.environ.get("RHG_ISAAC_PYTHON", "").strip() + if not direct: + data_root = os.environ.get("RHG_DATA_ROOT", "").strip() + local_candidates = [] + if data_root: + local_candidates.append( + Path(data_root) / "conda-envs" / "isaacsim-6.0.1" / "bin" / "python3.12" + ) + direct = next( + (str(candidate) for candidate in local_candidates if candidate.is_file()), "" + ) + settle_frames = os.environ.get("RHG_ISAAC_SETTLE_FRAMES", "180").strip() + if not settle_frames.isdigit() or int(settle_frames) <= 0: + raise ValueError("RHG_ISAAC_SETTLE_FRAMES must be a positive integer") + if direct: + command = [ + *shlex.split(direct), + str(validator), + str(output / "root.usda"), + "--report", + str(report), + "--settle-frames", + settle_frames, + ] + report_root = None + elif shutil.which("docker"): + report_root = output / "supervisor" / "isaac_reports" + cache_root = Path( + os.environ.get( + "RHG_ISAAC_CACHE_ROOT", + str(output.parent.parent / ".cache" / "isaac-sim"), + ) + ) + command = [ + sys.executable, + str(repository / "scripts" / "isaac_parallel_validate.py"), + str(output / "root.usda"), + "--scene-root", + str(output), + "--report-root", + str(report_root), + "--cache-root", + str(cache_root), + "--validator", + str(validator), + "--max-gpus", + "1", + "--settle-frames", + settle_frames, + "--image", + os.environ.get("RHG_ISAAC_IMAGE", "wholebody-scene-mvp-v0-arena:latest"), + ] + else: + atomic_write_text( + report, + json.dumps( + { + "schema_version": "1.0", + "passed": False, + "error": "neither RHG_ISAAC_PYTHON nor docker is available", + }, + indent=2, + ) + + "\n", + ) + return + run_environment = os.environ.copy() + run_environment.setdefault("OMNI_KIT_ACCEPT_EULA", "YES") + if direct: + isaac_executable = Path(shlex.split(direct)[0]).expanduser().resolve() + isaac_library = isaac_executable.parent.parent / "lib" + inherited_libraries = run_environment.get("LD_LIBRARY_PATH", "") + run_environment["LD_LIBRARY_PATH"] = ( + f"{isaac_library}:{inherited_libraries}" + if inherited_libraries + else str(isaac_library) + ) + configured_gpu = os.environ.get("RHG_ISAAC_GPU_ID", "").strip() + if not configured_gpu: + configured_gpu = os.environ.get("SCENESMITH_GPU_IDS", "").split(",", 1)[0].strip() + if configured_gpu: + run_environment["RHG_ISAAC_GPU_ID"] = configured_gpu + # Kit's Vulkan device enumeration is independent of CUDA remapping; + # mixing the two can make the configured physical index invalid. + run_environment.pop("CUDA_VISIBLE_DEVICES", None) + vulkan_icd = os.environ.get( + "RHG_ISAAC_VULKAN_ICD", "/etc/vulkan/icd.d/nvidia_icd.json" + ).strip() + if vulkan_icd: + run_environment["VK_ICD_FILENAMES"] = vulkan_icd + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + timeout=int(os.environ.get("RHG_ISAAC_VALIDATION_TIMEOUT_S", "1800")), + check=False, + env=run_environment, + ) + except (OSError, subprocess.TimeoutExpired) as error: + atomic_write_text( + report, + json.dumps( + { + "schema_version": "1.0", + "passed": False, + "error": f"{type(error).__name__}: {error}", + }, + indent=2, + ) + + "\n", + ) + return + if report_root is not None and not report.is_file(): + candidates = sorted( + path + for path in report_root.glob("*.json") + if path.name != "parallel_validation_summary.json" + ) + if len(candidates) == 1: + atomic_write_text(report, candidates[0].read_text(encoding="utf-8")) + if result.returncode and not report.is_file(): + atomic_write_text( + report, + json.dumps( + { + "schema_version": "1.0", + "passed": False, + "error": (result.stdout + result.stderr)[-4000:], + }, + indent=2, + ) + + "\n", + ) + + def _critic(self, output: Path, task: dict[str, Any]) -> tuple[bool, float | None]: + if not self.policy.critic_required: + return True, None + frame = self._critic_frame(output) + if frame is None or not RelaySettings.status_from_env()["configured"]: + return False, None + rubric = self.config.get( + "critic_prompt", + "Inspect the final composed benchmark. Score geometry, physical plausibility, " + "asset identity, task clarity, and visual quality from 0 to 10. Severe issues " + "include floating objects, penetration, duplicated proxies, or wrong asset identity.", + ) + machine_evidence: dict[str, Any] = {} + for name in ("manipulation_physics", "isaac_validation", "portable_validation"): + report_path = output / "manifests" / f"{name}.json" + if not report_path.is_file(): + continue + report = _json(report_path) + evidence: dict[str, Any] = {"passed": report.get("passed")} + if name == "manipulation_physics": + evidence["entities"] = report.get("entities", {}) + elif name == "isaac_validation": + evidence["failed_checks"] = [ + item.get("name") + for item in report.get("checks", []) + if isinstance(item, dict) and not item.get("passed") + ] + elif name == "portable_validation": + evidence["manipulation_physics"] = (report.get("usd") or {}).get( + "manipulation_physics", {} + ) + machine_evidence[name] = evidence + stage_manifest_path = output / "scenesmith/stage_manifest.json" + if stage_manifest_path.is_file(): + stage_manifest = _json(stage_manifest_path) + native_bindings = stage_manifest.get("native_asset_bindings") or {} + if isinstance(native_bindings, dict): + machine_evidence["locked_native_asset_bindings"] = { + entity_id: { + "asset_id": binding.get("asset_id"), + "binding_mode": binding.get("binding_mode"), + } + for entity_id, binding in native_bindings.items() + if isinstance(entity_id, str) and isinstance(binding, dict) + } + context_assets_path = output / "scenesmith/context_assets_config.json" + if context_assets_path.is_file(): + context_assets = _json(context_assets_path) + support_placements = context_assets.get("task_support_placements") or {} + if isinstance(support_placements, dict): + machine_evidence["authored_support_placements"] = support_placements + preflight_path = output / "supervisor/visual_preflight_report.json" + if preflight_path.is_file(): + preflight = _json(preflight_path) + machine_evidence["final_visual_preflight"] = { + "passed": preflight.get("passed"), + "checks": { + str(item.get("check_id")): { + "passed": item.get("passed"), + "evidence": item.get("evidence", {}), + } + for item in preflight.get("checks", []) + if isinstance(item, dict) and item.get("check_id") + }, + } + prompt = ( + f"{rubric}\nTask: {task.get('natural_language', '')}\n" + "The following physics, schema, and portability facts were independently " + "machine-validated. Treat passing facts as established and review every labeled " + "GENERATED view in the contact sheet. Generated panels are different camera views " + "of the same single scene, not separate scenes or simultaneous duplicates: " + "an object recurring in multiple quadrants is the same object instance. Never " + "report duplicated proxies merely because the same asset is visible in more " + "than one quadrant; duplication must be visible within one quadrant or proven " + "by machine identity evidence. Do not penalize one view merely for not showing " + "hidden schemas or the full action. When an exact native asset binding is " + "machine-validated, score shape/detail fidelity against that requested asset " + "identity; do not demand replacement by an unrelated higher-poly model. A " + "neutral powered-off television screen is intentional and must not be treated " + "as a missing texture. Authored support placements identify the actual support " + "for each loose prop; do not relabel an integral flush desk insert as a loose " + "object when the named object is machine-authored on a different support. " + + ( + "Panels labeled REFERENCE are user-supplied visual calibration frames, not " + "views of the generated scene. Do not evaluate their task semantics or count " + "their objects. Score only GENERATED panels, using the REFERENCE panels to " + "calibrate rendering realism, material response, and lighting: 7.5 means the " + "generated visual quality is at least comparable to that supplied baseline " + "while all generated-scene engineering and task requirements remain satisfied. " + if (output / "supervisor/critic_reference_manifest.json").is_file() + else "" + ) + + f"sequence: {json.dumps(machine_evidence, ensure_ascii=False)}\n" + 'Return JSON only: {"score": number, "severe_failures": [string], ' + '"summary": string}' + ) + raw = GenerativeClient(RelaySettings.from_env()).analyze_image(frame, prompt) + match = re.search(r"\{.*\}", raw, re.DOTALL) + payload = json.loads(match.group(0) if match else raw) + view_manifest = output / "scenesmith/final_composed_critic_views/manifest.json" + view_payload = _json(view_manifest) if view_manifest.is_file() else {} + view_hashes = { + role: hashlib.sha256( + (Path(path) if Path(path).is_absolute() else output / "scenesmith" / path).read_bytes() + ).hexdigest() + for role, path in (view_payload.get("views") or {}).items() + if isinstance(role, str) + and isinstance(path, str) + and (Path(path) if Path(path).is_absolute() else output / "scenesmith" / path).is_file() + } + shared_report = { + "schema_version": "2.0", + "consumers": ["final_global_critic", "supervisor"], + "source_view_manifest": str(view_manifest.relative_to(output)), + "source_view_manifest_sha256": ( + hashlib.sha256(view_manifest.read_bytes()).hexdigest() + if view_manifest.is_file() + else None + ), + "view_sha256": view_hashes, + "frame": str(frame.relative_to(output)), + "frame_sha256": hashlib.sha256(frame.read_bytes()).hexdigest(), + "threshold": self.policy.critic_min_score, + "raw": raw, + "result": payload, + } + serialized = json.dumps(shared_report, ensure_ascii=False, indent=2) + "\n" + atomic_write_text(output / "supervisor" / "critic_report.json", serialized) + atomic_write_text(output / "scenesmith" / "final_global_critic_report.json", serialized) + score = float(payload.get("score", 0)) + severe = payload.get("severe_failures") or [] + return score >= self.policy.critic_min_score and not severe, score + + @staticmethod + def _critic_frame(output: Path) -> Path | None: + target = output / "supervisor" / "critic_frame.jpg" + # This contact sheet is derived evidence, not an immutable source artifact. + # Always rebuild it from the current critic-view manifest so a rerender or + # renderer-profile change cannot be evaluated through a stale JPEG. + if target.is_file(): + target.unlink() + reference_manifest = target.parent / "critic_reference_manifest.json" + if reference_manifest.is_file(): + reference_manifest.unlink() + # Prefer the topology-aware, full-resolution evidence rendered from the + # final canonical USD. Video extraction downsamples each view to 480p + # before tiling and can make native meshes/materials look like proxies. + # Prefer the release-grade composed views: unlike the SceneSmith-internal + # DAG views, these include the robot and all outer benchmark layers. + view_manifests = [ + output / "scenesmith/final_composed_critic_views/manifest.json", + output / "scenesmith/final_critic_views/manifest.json", + ] + view_manifest = next((path for path in view_manifests if path.is_file()), None) + if view_manifest is not None: + try: + raw_views = (_json(view_manifest).get("views") or {}) + view_items = [ + (str(role), Path(str(path))) + for role, path in raw_views.items() + if isinstance(role, str) and isinstance(path, str) + ] + resolved_items = [ + (role, path if path.is_absolute() else output / "scenesmith" / path) + for role, path in view_items + ] + if len(resolved_items) >= 4 and all(path.is_file() for _, path in resolved_items): + reference_items: list[tuple[str, Path]] = [] + reference_root_text = os.environ.get("RHG_CRITIC_REFERENCE_DIR", "").strip() + if reference_root_text: + reference_root = Path(reference_root_text).resolve() + if reference_root.is_dir(): + reference_items = [ + (f"REFERENCE:{path.stem}", path) + for path in sorted(reference_root.iterdir()) + if path.suffix.casefold() in {".jpg", ".jpeg", ".png"} + ][:4] + labeled_items = [ + (f"GENERATED:{role}", path) for role, path in resolved_items + ] + reference_items + target.parent.mkdir(parents=True, exist_ok=True) + width, height, label_height = 640, 360, 24 + columns = 3 if len(labeled_items) >= 6 else 2 + rows = (len(labeled_items) + columns - 1) // columns + sheet = Image.new("RGB", (columns * width, rows * (height + label_height)), "white") + draw = ImageDraw.Draw(sheet) + for index, (role, path) in enumerate(labeled_items): + image = Image.open(path).convert("RGB") + image.thumbnail((width, height)) + x = (index % columns) * width + y = (index // columns) * (height + label_height) + sheet.paste(image, (x + (width - image.width) // 2, y + label_height)) + draw.text((x + 8, y + 5), role, fill="black") + sheet.save(target, format="JPEG", quality=94, optimize=True) + if reference_items: + atomic_write_text( + reference_manifest, + json.dumps( + { + "schema_version": "1.0", + "calibration_rule": ( + "7.5 means generated visual quality is at least " + "comparable to the user-supplied reference" + ), + "generated_views": [role for role, _ in resolved_items], + "reference_frames": [ + { + "label": role, + "path": str(path), + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + } + for role, path in reference_items + ], + }, + indent=2, + ) + + "\n", + ) + elif reference_manifest.exists(): + reference_manifest.unlink() + return target + except (OSError, ValueError, TypeError): + pass + preview = output / "scenesmith" / "preview.mp4" + if preview.is_file() and shutil.which("ffmpeg"): + target.parent.mkdir(parents=True, exist_ok=True) + result = subprocess.run( + [ + "ffmpeg", + "-y", + "-i", + str(preview), + "-vf", + "fps=1,scale=480:270:force_original_aspect_ratio=decrease," + "pad=480:270:(ow-iw)/2:(oh-ih)/2,tile=2x2", + "-frames:v", + "1", + str(target), + ], + capture_output=True, + timeout=60, + check=False, + ) + if result.returncode == 0 and target.is_file(): + return target + candidates = sorted((output / "scenesmith").glob("iteration_frames/*.png")) + return candidates[-1] if candidates else None + + @staticmethod + def _report( + gates: list[GateResult], *, critic_passed: bool, critic_score: float | None = None + ) -> QualityReport: + failed = sorted( + gate.gate_id for gate in gates if not gate.passed and gate.severity == "severe" + ) + signature = hashlib.sha256("|".join(failed).encode()).hexdigest()[:16] if failed else None + hard_passed = not failed + return QualityReport( + accepted=hard_passed and critic_passed, + hard_gates_passed=hard_passed, + critic_passed=critic_passed, + critic_score=critic_score, + gates=gates, + failure_signature=signature, + ) diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/runner.py b/docs/reproduction/public_conversion_code/packages/supervisor/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..0f733d41cea2c5b40d9ab4f7a68eff718c9060c4 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/runner.py @@ -0,0 +1,1027 @@ +from __future__ import annotations + +import json +import os +import re +import shutil +import time +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] +from pydantic import BaseModel, ConfigDict + +from packages.core.files import atomic_write_text +from packages.scene_generation.design_contract import ( + validate_repair_plan_against_contract, +) +from packages.supervisor.case import VERSION_PATTERN, CaseManager +from packages.supervisor.models import ( + GateResult, + IterationPolicy, + QualityReport, + RepairAction, + RepairPlan, + RepairStep, +) +from packages.supervisor.planner import RepairPlanner +from packages.supervisor.quality import QualityEvaluator +from packages.supervisor.snapshot import ensure_version_media + +BuildAttempt = Callable[[Path, RepairPlan | None], dict[str, Any]] + + +def is_packaging_only_recheck(plan: RepairPlan | None) -> bool: + """Return whether a repair only revalidates an already accepted scene payload.""" + + return bool(plan is not None and plan.strategy == "portable_packaging_recheck") + + +def materialize_packaging_recheck( + case_root: Path, + output: Path, + plan: RepairPlan, +) -> dict[str, Any]: + """Clone an immutable parent payload without re-entering SceneSmith. + + Portable-package defects are downstream of generation. Re-running SceneSmith can + change geometry and, more importantly, turns a packaging repair into another model + generation. The clone deliberately excludes prior Supervisor decisions, checksums, + and portable validation so the new version receives fresh evidence. + """ + + if not is_packaging_only_recheck(plan): + raise ValueError("repair plan is not a portable packaging recheck") + root = case_root.resolve() + source = (root / plan.parent_version).resolve() + destination = output.resolve() + if not source.is_relative_to(root) or not destination.is_relative_to(root): + raise ValueError("packaging recheck paths must remain inside the case directory") + if source == destination or not source.is_dir(): + raise ValueError(f"invalid packaging recheck parent: {source}") + required = ("root.usda", "manifests/task.json", "manifests/scene.json") + missing = [name for name in required if not (source / name).is_file()] + if missing: + raise ValueError(f"packaging recheck parent is incomplete: missing={missing}") + + def ignore(directory: str, names: list[str]) -> set[str]: + current = Path(directory).resolve() + ignored: set[str] = set() + if current == source: + ignored.update({"supervisor", "checksums.sha256"} & set(names)) + if current == source / "manifests": + ignored.update({"portable_validation.json"} & set(names)) + return ignored + + shutil.copytree(source, destination, dirs_exist_ok=True, symlinks=True, ignore=ignore) + provenance = { + "schema_version": "1.0", + "mode": "packaging_only_recheck", + "source_version": source.name, + "scene_generation_invoked": False, + "excluded_evidence": [ + "supervisor/", + "checksums.sha256", + "manifests/portable_validation.json", + ], + } + atomic_write_text( + destination / "supervisor" / "packaging_recheck_provenance.json", + json.dumps(provenance, ensure_ascii=False, indent=2) + "\n", + ) + return provenance + + +def generation_failure_entities(exc: BaseException) -> list[str]: + """Extract stable entity IDs from evidence-bound subtree failures.""" + + message = str(exc) + deterministic_match = re.search( + r"deterministic_placement_failed:affected_entities=([^:;\s]+)", message + ) + if deterministic_match: + return sorted( + {entity_id for entity_id in deterministic_match.group(1).split(",") if entity_id} + ) + scored_failures = { + match.group(1) + for match in re.finditer( + r"['\"]local-critic:branch-([A-Za-z0-9_.-]+)['\"]\s*:\s*" + r"['\"][^'\"]*critic_below_threshold[^'\"]*['\"]", + message, + ) + } + if scored_failures: + return sorted(scored_failures) + incomplete_branches = re.search( + r"critical manipulation branches did not produce their planned entities:\s*\[([^]]+)\]", + message, + flags=re.IGNORECASE, + ) + if incomplete_branches: + branch_ids = re.findall(r"['\"]([A-Za-z0-9_.-]+)['\"]", incomplete_branches.group(1)) + # A furniture repair may expand one stable support into implementation + # modules. Report the stable owner so checkpoint repair can replace the + # invalid expansion without leaking generated instance IDs into the task. + return sorted({re.sub(r"_module_[0-9]+$", "", item) for item in branch_ids}) + return sorted( + {match.group(1) for match in re.finditer(r"local-critic:branch-([A-Za-z0-9_.-]+)", message)} + ) + + +def generation_failure_signature(exc: BaseException) -> str: + """Classify infrastructure failures so unrelated defects do not stagnate.""" + + message = str(exc).casefold() + if ( + "deterministic_placement_failed:" in message + or "infeasible_asset:semantic_constraint:" in message + ): + # Asset generation has completed. The failed hard gate belongs to the + # deterministic placement/composition stage and must never trigger a + # furniture or manipulation regeneration by default. + return "deterministic_placement_failure" + if "final_usd_geometry_failed:" in message: + # The expensive generative stages succeeded. This is a deterministic + # composition/export defect and must only re-run post-processing. + return "final_usd_geometry_failure" + if ( + "agent execution dag failed" in message + and ("merge:world" in message or "global-critic:scene" in message) + and "local-critic:branch-" not in message + ): + # Generation, local placement, and local critics have already completed. + # Merge/global audit failures are downstream post-processing defects; a + # manipulation resume would throw away accepted subtree work. + return "agent_postprocess_failure" + if ( + "agent execution dag failed" in message + and "local-critic:branch-" in message + ): + # Preserve the semantic failure across the SceneSmith subprocess boundary. + # This is an owned furniture-subtree rejection, not the final composed + # visual gate. Route it to furniture checkpoint repair so the rejected + # subtree is regenerated while accepted siblings remain frozen. + return "agent_local_critic_failure" + if ( + "critical manipulation branches did not produce their planned entities" in message + and re.search(r"_module_[0-9]+", message) + ): + # Manipulation is only the first consumer to notice the defect. A stable + # furniture entity was replaced by ad-hoc modules, so replaying the same + # manipulation checkpoint cannot repair it. + return "upstream_entity_identity_failure" + if "no object binding for" in message: + # Non-fatal tracing timeouts can precede the terminal traceback. The + # deterministic binding error is the actionable cause and takes priority. + return "entity_binding_failure" + if isinstance(exc, TimeoutError) or "timed out" in message or "timeout" in message: + return "generation_timeout" + if "manipuland shard" in message: + return "manipuland_worker_failure" + if "scenesmith failed" in message: + return "scenesmith_generation_failure" + return "generation_failure" + + +def generation_failure_fingerprint(exc: BaseException) -> str: + """Scope semantic failures to the owned subtree for stagnation accounting.""" + + signature = generation_failure_signature(exc) + entities = generation_failure_entities(exc) + if ( + signature + in { + "supervisor_visual_critic", + "agent_local_critic_failure", + "deterministic_placement_failure", + "upstream_entity_identity_failure", + } + and entities + ): + return f"{signature}:{','.join(entities)}" + return signature + + +def refine_historical_failure(report: QualityReport, output: Path | None = None) -> QualityReport: + """Recover a semantic gate from an older generic subprocess failure report.""" + + original_signature = (report.failure_signature or "").split(":", 1)[0] + if original_signature not in { + "scenesmith_generation_failure", + "supervisor_visual_critic", + }: + return report + message = "\n".join(gate.message for gate in report.gates if gate.message) + classified = generation_failure_signature(RuntimeError(message)) + if ( + original_signature == "supervisor_visual_critic" + and classified != "agent_local_critic_failure" + ): + return report + refined = ( + report.failure_signature + if classified in {"generation_failure", "scenesmith_generation_failure"} + else classified + ) + if refined == report.failure_signature and output is not None: + minimum_visual_score: float | None = None + for score_path in output.glob("scenesmith/upstream/**/scores.yaml"): + try: + payload = yaml.safe_load(score_path.read_text(encoding="utf-8")) or {} + except (OSError, yaml.YAMLError): + continue + grades = [ + float(value["grade"]) + for value in payload.values() + if isinstance(value, dict) and isinstance(value.get("grade"), (int, float)) + ] + if grades: + score = min(grades) + minimum_visual_score = ( + score if minimum_visual_score is None else min(minimum_visual_score, score) + ) + if minimum_visual_score is not None and minimum_visual_score < 7.0: + refined = "supervisor_visual_critic" + if refined == report.failure_signature: + return report + gates = [ + gate.model_copy( + update={ + "gate_id": refined, + "affected_entities": gate.affected_entities + or generation_failure_entities(RuntimeError(gate.message)), + } + ) + if gate.gate_id + in {"scenesmith_generation_failure", "supervisor_visual_critic"} + else gate + for gate in report.gates + ] + return report.model_copy(update={"failure_signature": refined, "gates": gates}) + + +class IterationResult(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + + case_dir: Path + output_dir: Path | None + released_version: str | None + release: Path | None + blocked: Path | None + attempts: list[str] + payload: dict[str, Any] | None = None + + +class SupervisorRunner: + def __init__( + self, + manager: CaseManager, + policy: IterationPolicy, + build_attempt: BuildAttempt, + *, + evaluator: QualityEvaluator | None = None, + resume_blocked: bool = False, + ) -> None: + self.manager = manager + self.policy = policy + self.build_attempt = build_attempt + self.evaluator = evaluator or QualityEvaluator(policy) + self.planner = RepairPlanner(policy.repair_policy, policy.stagnation_repeat_limit) + self.resume_blocked = resume_blocked + + def run(self) -> IterationResult: + with self.manager.campaign_locked(): + return self._run_locked() + + def _run_locked(self) -> IterationResult: + started = time.monotonic() + atomic_write_text( + self.manager.root / "supervisor_policy.json", + self.policy.model_dump_json(indent=2) + "\n", + ) + self._reconcile_interrupted_attempts() + existing_release = self.manager.root / "release.json" + if existing_release.is_file(): + release_data = json.loads(existing_release.read_text(encoding="utf-8")) + output = self.manager.root / str(release_data["run_dir"]) + return IterationResult( + case_dir=self.manager.root, + output_dir=output, + released_version=output.name, + release=existing_release, + blocked=None, + attempts=[], + ) + history = self._attempt_history() + attempts: list[str] = [] + parent: str | None = history[-1][1].version if history else None + repair_plan: RepairPlan | None = None + last_signature, consecutive_failures = self._consecutive_failure_state(history) + blocked_path = self.manager.root / "blocked.json" + resumed_campaign = False + if self.resume_blocked: + if not blocked_path.is_file(): + raise RuntimeError("--resume-blocked requires an existing blocked.json") + blocked_payload = json.loads(blocked_path.read_text(encoding="utf-8")) + if not blocked_payload.get("resumable"): + raise RuntimeError("the blocked campaign is not resumable") + audit_path = self.manager.root / "resume_audit.jsonl" + with audit_path.open("a", encoding="utf-8") as handle: + handle.write( + json.dumps( + { + "schema_version": "1.0", + "resumed_at": datetime.now(UTC).isoformat(), + "prior_block": blocked_payload, + "history_attempt_count": len(history), + }, + ensure_ascii=False, + ) + + "\n" + ) + blocked_path.unlink() + resumed_campaign = True + # A requested resume starts a fresh repeated-failure audit while + # preserving all attempts and their original quality reports. + consecutive_failures = 0 + last_payload: dict[str, Any] | None = None + if consecutive_failures >= self.policy.same_failure_signature_limit: + repeat_phrase = ( + "twice" + if self.policy.same_failure_signature_limit == 2 + else f"{self.policy.same_failure_signature_limit} times" + ) + return self._blocked_result( + f"failure signature {last_signature!r} repeated consecutively {repeat_phrase}", + started, + parent, + attempts, + ) + if history: + last_report = self._quality_report(history[-1][0]) + if last_report is None: + return self._blocked_result( + "latest attempt has no valid quality report", + started, + parent, + attempts, + ) + if last_report.accepted: + release = self.manager.release(history[-1][0], last_report) + return IterationResult( + case_dir=self.manager.root, + output_dir=history[-1][0], + released_version=history[-1][1].version, + release=release, + blocked=None, + attempts=attempts, + ) + last_report = refine_historical_failure(last_report, history[-1][0]) + if ( + self.policy.max_total_attempts is not None + and len(history) >= self.policy.max_total_attempts + ): + return self._blocked_result( + f"maximum of {self.policy.max_total_attempts} outer attempts already reached", + started, + parent, + attempts, + ) + repair_plan = self.planner.plan( + last_report, + parent_version=parent or history[-1][1].version, + signature_occurrences=max(consecutive_failures, 1), + ) + repair_plan = self._checkpoint_repair_plan(repair_plan) + if repair_plan is None and not self._can_retry_failed_stage_without_checkpoint( + last_report, + parent or history[-1][1].version, + ) and not resumed_campaign: + return self._blocked_result( + "no validated checkpoint-local repair is available", + started, + parent, + attempts, + ) + while time.monotonic() - started < self.policy.wall_clock_budget_s: + if ( + self.policy.max_total_attempts is not None + and len(history) + len(attempts) >= self.policy.max_total_attempts + ): + break + output, manifest = self.manager.allocate_attempt(parent_version=parent) + attempts.append(output.name) + attempt_started = time.monotonic() + attempt_number = len(history) + len(attempts) + budget_multiplier = ( + self.policy.first_attempt_budget_multiplier if attempt_number == 1 else 1.0 + ) + effective = { + "schema_version": "1.0", + "attempt_number": attempt_number, + "attempt_budget_multiplier": budget_multiplier, + "max_total_attempts": self.policy.max_total_attempts, + "critic_min_score": self.policy.critic_min_score, + "checkpoint_repairs_only_after_first": ( + self.policy.checkpoint_repairs_only_after_first + ), + } + if repair_plan is not None: + repair_path = output / "supervisor" / "repair_plan.json" + atomic_write_text(repair_path, repair_plan.model_dump_json(indent=2) + "\n") + effective.update( + { + "parent_version": repair_plan.parent_version, + "strategy": repair_plan.strategy, + "steps": [step.model_dump(mode="json") for step in repair_plan.steps], + } + ) + manifest.repair_plan = "supervisor/repair_plan.json" + self.manager.write_attempt(output, manifest) + atomic_write_text( + output / "supervisor" / "effective_overrides.json", + json.dumps(effective, ensure_ascii=False, indent=2) + "\n", + ) + report: QualityReport + error: str | None = None + try: + if is_packaging_only_recheck(repair_plan): + assert repair_plan is not None + last_payload = materialize_packaging_recheck( + self.manager.root, output, repair_plan + ) + else: + with repair_environment( + repair_plan, + self.manager.root, + attempt_budget_multiplier=budget_multiplier, + ): + last_payload = self.build_attempt(output, repair_plan) + ensure_version_media( + output, + force_snapshot=True, + allow_final_preview_fallback=False, + ) + report = self.evaluator.evaluate(output) + if report.accepted: + ensure_version_media(output, force_snapshot=True) + else: + ensure_version_media( + output, + force_snapshot=True, + allow_final_preview_fallback=False, + ) + except Exception as exc: + error = f"{type(exc).__name__}: {exc}" + gate_id = generation_failure_signature(exc) + failure_signature = generation_failure_fingerprint(exc) + try: + # Persist the failure first so a pre-render diagnostic frame + # contains the actual failed stage instead of a generic card. + manifest.error = error + self.manager.write_attempt(output, manifest) + ensure_version_media( + output, + force_snapshot=True, + allow_final_preview_fallback=False, + ) + except Exception as media_exc: + error += f"; media_contract={type(media_exc).__name__}: {media_exc}" + report = QualityReport( + accepted=False, + hard_gates_passed=False, + critic_passed=not self.policy.critic_required, + gates=[ + GateResult( + gate_id=gate_id, + passed=False, + message=error, + affected_entities=generation_failure_entities(exc), + ) + ], + failure_signature=failure_signature, + ) + quality_path = output / "supervisor" / "quality_report.json" + atomic_write_text(quality_path, report.model_dump_json(indent=2) + "\n") + manifest.status = "passed" if report.accepted else "failed" + manifest.completed_at = datetime.now(UTC).isoformat() + manifest.duration_s = round(time.monotonic() - attempt_started, 3) + manifest.quality_report = "supervisor/quality_report.json" + manifest.failure_signature = report.failure_signature + manifest.error = error + self.manager.write_attempt(output, manifest) + self.manager.append_attempt(manifest) + self.manager.update_campaign() + if report.accepted and (output / "snapshot.jpg").is_file(): + self.manager.consider_for_major(output, report) + if report.accepted: + release = self.manager.release(output, report) + return IterationResult( + case_dir=self.manager.root, + output_dir=output, + released_version=output.name, + release=release, + blocked=None, + attempts=attempts, + payload=last_payload, + ) + signature = report.failure_signature or "unknown" + if signature == last_signature: + consecutive_failures += 1 + else: + last_signature = signature + consecutive_failures = 1 + if consecutive_failures >= self.policy.same_failure_signature_limit: + repeat_phrase = ( + "twice" + if self.policy.same_failure_signature_limit == 2 + else f"{self.policy.same_failure_signature_limit} times" + ) + return self._blocked_result( + f"failure signature {signature!r} repeated consecutively {repeat_phrase}", + started, + output.name, + attempts, + output=output, + payload=last_payload, + ) + repair_plan = self.planner.plan( + report, + parent_version=output.name, + signature_occurrences=consecutive_failures, + ) + repair_plan = self._checkpoint_repair_plan(repair_plan) + parent = output.name + if repair_plan is None and not self._can_retry_failed_stage_without_checkpoint( + report, + parent, + ): + return self._blocked_result( + "allowlisted checkpoint-local repair strategies exhausted", + started, + parent, + attempts, + output=output, + payload=last_payload, + ) + attempt_limit_reached = ( + self.policy.max_total_attempts is not None + and len(history) + len(attempts) >= self.policy.max_total_attempts + ) + blocked = self.manager.block( + reason=( + f"maximum of {self.policy.max_total_attempts} outer attempts reached" + if attempt_limit_reached + else "wall-clock budget exhausted" + ), + elapsed_s=time.monotonic() - started, + last_version=parent, + ) + return IterationResult( + case_dir=self.manager.root, + output_dir=self.manager.root / parent if parent else None, + released_version=None, + release=None, + blocked=blocked, + attempts=attempts, + payload=last_payload, + ) + + def _attempt_history(self) -> list[tuple[Path, Any]]: + history = [] + for output in self.manager.root.iterdir(): + if not output.is_dir() or VERSION_PATTERN.fullmatch(output.name) is None: + continue + manifest_path = output / "supervisor" / "attempt_manifest.json" + if manifest_path.is_file(): + history.append((output, self.manager.read_attempt(output))) + return sorted( + history, + key=lambda item: int(VERSION_PATTERN.fullmatch(item[0].name).group("number")), + ) + + @staticmethod + def _consecutive_failure_state(history: list[tuple[Path, Any]]) -> tuple[str | None, int]: + signature: str | None = None + count = 0 + for _, manifest in reversed(history): + if manifest.status != "failed": + break + current = manifest.failure_signature or "unknown" + if signature is None: + signature = current + if current != signature: + break + count += 1 + return signature, count + + @staticmethod + def _quality_report(output: Path) -> QualityReport | None: + path = output / "supervisor" / "quality_report.json" + if not path.is_file(): + return None + try: + return QualityReport.model_validate_json(path.read_text(encoding="utf-8")) + except ValueError: + return None + + def _checkpoint_repair_plan(self, plan: RepairPlan | None) -> RepairPlan | None: + if plan is None or not self.policy.checkpoint_repairs_only_after_first: + return plan + checkpoint = self._nearest_ancestor_checkpoint(plan.parent_version) + if checkpoint is None: + return None + steps = list(plan.steps) + resume_index = next( + ( + index + for index, step in enumerate(steps) + if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT + ), + None, + ) + failure_kind = (plan.failure_signature or "").split(":", 1)[0] + requested_resume_stage = steps[resume_index].stage if resume_index is not None else None + # A process can be interrupted while carrying out a postprocess-only + # repair after its reusable upstream checkpoint has already been copied. + # The generic interrupted-attempt strategy asks for ``manipuland``, but + # that would unnecessarily reopen accepted Agent geometry. Preserve the + # interrupted parent's explicitly persisted postprocess scope instead. + if failure_kind == "interrupted_attempt": + parent_plan_path = ( + self.manager.root + / plan.parent_version + / "supervisor" + / "repair_plan.json" + ) + if parent_plan_path.is_file(): + try: + parent_plan = RepairPlan.model_validate_json( + parent_plan_path.read_text(encoding="utf-8") + ) + except (OSError, ValueError): + parent_plan = None + parent_resume = ( + next( + ( + step + for step in parent_plan.steps + if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT + ), + None, + ) + if parent_plan is not None + else None + ) + if parent_resume is not None and parent_resume.stage == "postprocess": + requested_resume_stage = "postprocess" + resume_stage = ( + "postprocess" + if requested_resume_stage == "postprocess" + or failure_kind + in { + "final_usd_geometry_failure", + "agent_postprocess_failure", + "deterministic_placement_failure", + } + else self._checkpoint_resume_stage(checkpoint) + ) + if resume_stage is None: + return None + # The checkpoint detector identifies how far a prior attempt completed; + # it must not silently narrow an explicit repair plan past the stage that + # actually failed. For example, a completed manipulation checkpoint can + # still contain furniture rejected by the final visual critic, in which + # case the planner's requested furniture repair must be honored. + if resume_index is not None and plan.strategy in { + "global_dag_furniture_repair", + "visual_support_and_layout_repair", + "upstream_entity_identity_repair", + }: + requested_stage = steps[resume_index].stage + stage_order = ("floor_plan", "furniture", "wall", "ceiling", "manipuland") + if ( + requested_stage in stage_order + and resume_stage in stage_order + and stage_order.index(requested_stage) < stage_order.index(resume_stage) + ): + resume_stage = requested_stage + resume = RepairStep( + action=RepairAction.RERUN_STAGE_FROM_CHECKPOINT, + stage=resume_stage, + checkpoint=checkpoint.as_posix(), + reason="Resume the failed branch from the parent SceneSmith checkpoint.", + ) + if resume_index is None: + steps.insert(0, resume) + else: + original = steps[resume_index] + steps[resume_index] = original.model_copy( + update={"stage": resume_stage, "checkpoint": checkpoint.as_posix()} + ) + return plan.model_copy(update={"steps": steps}) + + def _can_retry_failed_stage_without_checkpoint( + self, + report: QualityReport, + parent_version: str, + ) -> bool: + """Permit one deterministic stage retry when no checkpoint can exist yet. + + A worker/runtime failure before the first materialized checkpoint cannot + be expressed honestly as a checkpoint-local scene repair. The outer + repeated-signature guard still stops the campaign if the retry produces + the same failure again. Once any usable checkpoint exists, the normal + checkpoint-only repair policy remains authoritative. + """ + + if report.failure_signature not in { + "generation_failure", + "generation_timeout", + "interrupted_attempt", + "scenesmith_generation_failure", + }: + return False + return self._nearest_ancestor_checkpoint(parent_version) is None + + def _checkpoint_resume_stage(self, checkpoint: Path) -> str | None: + """Select the earliest unfinished SceneSmith stage in a checkpoint.""" + + root = self.manager.root / checkpoint + for timing_path in root.glob("scene_*/room_*/parallel_manipulands/timing.json"): + try: + timing = json.loads(timing_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + completions = timing.get("branch_completion") or {} + failed = timing.get("failed_critical_branches") or [] + if ( + isinstance(completions, dict) + and completions + and not failed + and all( + isinstance(value, dict) and value.get("passed") is True + for value in completions.values() + ) + ): + # Re-enter manipulation to reproduce the final merged blend; + # the accepted furniture/architecture checkpoint remains frozen. + return "manipuland" + for ledger_path in root.glob("scene_*/room_*/parallel_base_branches/execution_ledger.json"): + try: + ledger = json.loads(ledger_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if ledger.get("status") == "complete": + return "manipuland" + floor_render_patterns = ( + "scene_*/floor_plans/floor_plan_renders/renders_*", + "scene_*/floor_plans/*/floor_plan_renders/renders_*", + ) + if any(any(root.glob(pattern)) for pattern in floor_render_patterns): + return "furniture" + return None + + def _nearest_ancestor_checkpoint(self, version: str) -> Path | None: + """Return the newest usable checkpoint in an attempt's ancestry. + + Infrastructure failures may create a version directory before SceneSmith + writes any checkpoint. Follow parent_version links so a later invocation + can resume from the last materialized attempt instead of treating the + resource-only failure as a request for full regeneration. + """ + + candidate = version + visited: set[str] = set() + while candidate and candidate not in visited: + visited.add(candidate) + checkpoint = Path(candidate) / "scenesmith" / "upstream" + resolved = self.manager.root / checkpoint + # Logs, Hydra configs and half-written scene directories are not a + # resumable checkpoint. SceneSmith writes this marker only after + # the reusable base state has been materialized. + if ( + (resolved / "checkpoint.json").is_file() + or self._legacy_upstream_complete(resolved) + or self._checkpoint_resume_stage(checkpoint) is not None + ): + return checkpoint + manifest_path = resolved.parents[1] / "supervisor" / "attempt_manifest.json" + if not manifest_path.is_file(): + return None + try: + manifest = self.manager.read_attempt(resolved.parents[1]) + except ValueError: + return None + candidate = manifest.parent_version or "" + return None + + @staticmethod + def _legacy_upstream_complete(upstream: Path) -> bool: + """Recognize runs completed before the checkpoint marker was introduced.""" + + log_path = upstream.parent / "upstream.log" + if not log_path.is_file(): + return False + try: + if "Experiment execution completed in" not in log_path.read_text( + encoding="utf-8", errors="replace" + ): + return False + except OSError: + return False + return any(upstream.glob("scene_*/room_*/scene_states/final_scene/scene.blend")) or any( + upstream.glob("**/house.blend") + ) + + def _blocked_result( + self, + reason: str, + started: float, + parent: str | None, + attempts: list[str], + *, + output: Path | None = None, + payload: dict[str, Any] | None = None, + ) -> IterationResult: + blocked = self.manager.block( + reason=reason, + elapsed_s=time.monotonic() - started, + last_version=parent, + ) + return IterationResult( + case_dir=self.manager.root, + output_dir=output or (self.manager.root / parent if parent else None), + released_version=None, + release=None, + blocked=blocked, + attempts=attempts, + payload=payload, + ) + + def _reconcile_interrupted_attempts(self) -> None: + """Finalize attempts left running by a prior process interruption. + + A process cannot execute cleanup after SIGKILL or host loss. The next + Supervisor invocation therefore repairs the visual contract before it + allocates another version, without requiring an external backfill job. + """ + + reconciled = False + for output in sorted(self.manager.root.iterdir()): + if not output.is_dir() or VERSION_PATTERN.fullmatch(output.name) is None: + continue + manifest_path = output / "supervisor" / "attempt_manifest.json" + if not manifest_path.is_file(): + continue + manifest = self.manager.read_attempt(output) + if manifest.status != "running": + continue + error = "Supervisor process ended before attempt finalization; auto-reconciled" + failure_signature = "interrupted_attempt" + # If a bad retry was interrupted before it produced a checkpoint, + # retain a deterministic parent failure that can be repaired from + # the parent's completed upstream scene. Otherwise the generic + # interruption would unnecessarily rerun an expensive Agent stage. + current_upstream = output / "scenesmith" / "upstream" + if manifest.parent_version and not (current_upstream / "checkpoint.json").is_file(): + parent_output = self.manager.root / manifest.parent_version + parent_report = self._quality_report(parent_output) + if parent_report is not None: + parent_report = refine_historical_failure(parent_report, parent_output) + parent_failure_kind = (parent_report.failure_signature or "").split(":", 1)[0] + if parent_failure_kind in { + "final_usd_geometry_failure", + "agent_postprocess_failure", + "deterministic_placement_failure", + }: + failure_signature = parent_report.failure_signature + error += "; retained deterministic failure from parent checkpoint" + manifest.error = error + try: + ensure_version_media( + output, + force_snapshot=True, + allow_final_preview_fallback=False, + ) + except Exception as media_exc: + manifest.error += f"; media_contract={type(media_exc).__name__}: {media_exc}" + report = QualityReport( + accepted=False, + hard_gates_passed=False, + critic_passed=not self.policy.critic_required, + gates=[ + GateResult( + gate_id=failure_signature, + passed=False, + message=manifest.error, + ) + ], + failure_signature=failure_signature, + ) + quality_path = output / "supervisor" / "quality_report.json" + atomic_write_text(quality_path, report.model_dump_json(indent=2) + "\n") + manifest.status = "failed" + manifest.completed_at = datetime.now(UTC).isoformat() + manifest.quality_report = "supervisor/quality_report.json" + manifest.failure_signature = failure_signature + self.manager.write_attempt(output, manifest) + self.manager.append_attempt(manifest) + reconciled = True + if reconciled: + self.manager.update_campaign() + + +@contextmanager +def repair_environment( + plan: RepairPlan | None, + case_root: Path, + *, + attempt_budget_multiplier: float = 1.0, +) -> Iterator[None]: + updates = { + "RHG_CASE_ROOT": str(case_root), + "RHG_ATTEMPT_BUDGET_MULTIPLIER": str(attempt_budget_multiplier), + } + design_contract = case_root / "case_design" / "contract.json" + if design_contract.is_file(): + if plan is not None: + validate_repair_plan_against_contract(design_contract, plan) + updates["RHG_CASE_DESIGN_CONTRACT"] = str(design_contract.resolve()) + fresh_scene = os.environ.get("RHG_FRESH_SCENE", "0").casefold() in { + "1", + "true", + "yes", + } + external_reuse = ( + "" if fresh_scene else os.environ.get("RHG_SCENESMITH_REUSE_FROM", "").strip() + ) + if external_reuse: + resolved_external_reuse = Path(external_reuse).resolve() + if not resolved_external_reuse.is_dir(): + raise NotADirectoryError(resolved_external_reuse) + # A product suite may reuse a separately accepted immutable room. The + # adapter still makes a private copy before deterministic postprocessing. + updates["RHG_SCENESMITH_REUSE_FROM"] = str(resolved_external_reuse) + if plan is not None: + updates["RHG_REPAIR_PLAN"] = json.dumps(plan.model_dump(mode="json")) + resume = ( + next( + ( + step + for step in plan.steps + if step.action == RepairAction.RERUN_STAGE_FROM_CHECKPOINT + ), + None, + ) + if plan is not None + else None + ) + if resume is not None and not fresh_scene: + if resume.stage == "postprocess": + if not resume.checkpoint: + raise ValueError("postprocess repair requires a SceneSmith checkpoint") + checkpoint = Path(resume.checkpoint) + if not checkpoint.is_absolute(): + checkpoint = case_root / checkpoint + resolved = checkpoint.resolve() + if not resolved.is_relative_to(case_root.resolve()): + raise ValueError("repair checkpoint must remain within the case directory") + # The checkpoint points at ``scenesmith/upstream``. The adapter + # stages that completed SceneSmith directory into the new version + # and asks the worker to re-run deterministic export/validation only. + updates["RHG_SCENESMITH_REUSE_FROM"] = str(resolved.parent) + else: + if resume.stage: + updates["RHG_SCENESMITH_START_STAGE"] = resume.stage + if resume.checkpoint: + checkpoint = Path(resume.checkpoint) + if not checkpoint.is_absolute(): + checkpoint = case_root / checkpoint + resolved = checkpoint.resolve() + if not resolved.is_relative_to(case_root.resolve()): + raise ValueError("repair checkpoint must remain within the case directory") + updates["RHG_SCENESMITH_RESUME_FROM"] = str(resolved) + managed_keys = { + *updates, + "RHG_REPAIR_PLAN", + "RHG_SCENESMITH_START_STAGE", + "RHG_SCENESMITH_RESUME_FROM", + "RHG_SCENESMITH_REUSE_FROM", + } + previous = {key: os.environ.get(key) for key in managed_keys} + for key in managed_keys - updates.keys(): + os.environ.pop(key, None) + os.environ.update(updates) + try: + yield + finally: + for key, value in previous.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/snapshot.py b/docs/reproduction/public_conversion_code/packages/supervisor/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..bd9a5b9d96960681f1311a9ff7ea766a33bba0fd --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/snapshot.py @@ -0,0 +1,314 @@ +from __future__ import annotations + +import json +import os +import shutil +import subprocess +from datetime import UTC, datetime +from pathlib import Path + +from PIL import Image + +from packages.core.files import atomic_write_text + + +def _ffmpeg_executable() -> str | None: + configured = os.environ.get("RHG_FFMPEG", "").strip() + if configured: + candidate = Path(configured).expanduser() + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + discovered = shutil.which("ffmpeg") + if discovered: + return discovered + data_root = os.environ.get("RHG_DATA_ROOT", "").strip() + if data_root: + for relative in ("tools/bin/ffmpeg", "tmp/rhg-tools/ffmpeg"): + candidate = Path(data_root) / relative + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + try: + import imageio_ffmpeg # type: ignore[import-not-found] + + bundled = Path(imageio_ffmpeg.get_ffmpeg_exe()) + if bundled.is_file() and os.access(bundled, os.X_OK): + return str(bundled) + except (ImportError, OSError, RuntimeError): + pass + return None + + +def ensure_version_media( + output: Path, + *, + force_snapshot: bool = False, + allow_final_preview_fallback: bool = True, +) -> dict[str, object]: + """Materialize the mandatory per-attempt visual contract. + + This runs in the Supervisor lifecycle, not only at the end of a successful + SceneSmith export, so failed and interrupted attempts keep their own visual + history instead of inheriting a floor-plan still from another attempt. + """ + + output = output.resolve() + scenesmith = output / "scenesmith" + scenesmith.mkdir(parents=True, exist_ok=True) + upstream = scenesmith / "upstream" + history = scenesmith / "iteration_history.mp4" + history_error: str | None = None + if upstream.is_dir(): + try: + from scripts.index_scenesmith_iterations import build_iteration_history + + build_iteration_history(upstream, scenesmith) + except Exception as error: + history_error = f"{type(error).__name__}: {error}" + if not history.is_file() or history.stat().st_size == 0: + diagnostic = _ensure_diagnostic_frame(output, history_error) + _encode_still_video(diagnostic, history) + _stamp_iteration_manifest(output) + + native_preview = scenesmith / "preview.mp4" + root_preview = output / "preview.mp4" + preview_method: str | None = "generated_scene_preview" + if allow_final_preview_fallback: + if not native_preview.is_file() or native_preview.stat().st_size == 0: + _replace_hardlink(history, native_preview) + preview_method = "iteration_history_fallback" + _replace_hardlink(native_preview, root_preview) + else: + native_preview.unlink(missing_ok=True) + root_preview.unlink(missing_ok=True) + preview_method = None + root_history = output / "iteration_history.mp4" + _replace_hardlink(history, root_history) + + snapshot = ensure_version_snapshot(output, force=force_snapshot) + payload: dict[str, object] = { + "schema_version": "1.0", + "created_at": datetime.now(UTC).isoformat(), + "status": "complete" if allow_final_preview_fallback else "diagnostic_complete", + "snapshot": snapshot.relative_to(output).as_posix(), + "preview": ( + root_preview.relative_to(output).as_posix() + if allow_final_preview_fallback + else None + ), + "backend_preview": ( + native_preview.relative_to(output).as_posix() + if allow_final_preview_fallback + else None + ), + "preview_method": preview_method, + "final_video_withheld": not allow_final_preview_fallback, + "iteration_history": root_history.relative_to(output).as_posix(), + "backend_iteration_history": history.relative_to(output).as_posix(), + "history_error": history_error, + } + atomic_write_text( + output / "supervisor" / "media_manifest.json", + json.dumps(payload, ensure_ascii=False, indent=2) + "\n", + ) + return payload + + +def ensure_version_snapshot(output: Path, *, force: bool = False) -> Path: + """Persist one stable, human-readable still image for a generated version.""" + + output = output.resolve() + target = output / "snapshot.jpg" + if not force and target.is_file() and target.stat().st_size > 0: + return target + + image_source = _find_image_source(output) + video_source = _find_video_source(output) + source: Path | None = None + method: str + target.parent.mkdir(parents=True, exist_ok=True) + ffmpeg = _ffmpeg_executable() + if video_source is not None and ffmpeg: + result = subprocess.run( + [ + ffmpeg, + "-y", + "-ss", + "00:00:00.500", + "-i", + str(video_source), + "-frames:v", + "1", + "-q:v", + "2", + str(target), + ], + capture_output=True, + timeout=60, + check=False, + ) + if result.returncode != 0 or not target.is_file() or target.stat().st_size == 0: + target.unlink(missing_ok=True) + if image_source is None: + raise RuntimeError(f"failed to extract version snapshot from {video_source}") + with Image.open(image_source) as image: + image.convert("RGB").save(target, format="JPEG", quality=92) + source = image_source + method = "image_after_video_fallback" + else: + source = video_source + method = "video_frame_0_5s" + elif image_source is not None: + with Image.open(image_source) as image: + image.convert("RGB").save(target, format="JPEG", quality=92) + source = image_source + method = "image" + else: + raise RuntimeError(f"no render image or readable preview video found under {output}") + + payload = { + "schema_version": "1.0", + "created_at": datetime.now(UTC).isoformat(), + "snapshot": target.relative_to(output).as_posix(), + "source": source.relative_to(output).as_posix(), + "method": method, + } + atomic_write_text( + output / "supervisor" / "snapshot_manifest.json", + json.dumps(payload, ensure_ascii=False, indent=2) + "\n", + ) + return target + + +def _find_image_source(output: Path) -> Path | None: + preferred = [ + output / "supervisor" / "critic_frame.jpg", + output / "scenesmith" / "preview.jpg", + output / "scenesmith" / "preview.png", + ] + for path in preferred: + if path.is_file() and path.stat().st_size > 0: + return path + # Iteration contact sheets encode both stage and version, and therefore are + # a better attempt snapshot than a reused floor plan. + iteration_candidates = [ + path + for pattern in ( + "scenesmith/iteration_frames/*.png", + "scenesmith/iteration_frames/*.jpg", + ) + for path in output.glob(pattern) + if path.is_file() + ] + if iteration_candidates: + return max(iteration_candidates, key=lambda path: path.stat().st_mtime) + patterns = ( + "scenesmith/**/*preview*.png", + "scenesmith/**/*preview*.jpg", + "scenesmith/**/floor_plan.png", + ) + candidates = [path for pattern in patterns for path in output.glob(pattern) if path.is_file()] + return max(candidates, key=lambda path: path.stat().st_mtime) if candidates else None + + +def _ensure_diagnostic_frame(output: Path, history_error: str | None) -> Path: + frame = output / "scenesmith" / "iteration_frames" / "frame_0000.png" + frame.parent.mkdir(parents=True, exist_ok=True) + image = Image.new("RGB", (1280, 720), (24, 27, 30)) + from PIL import ImageDraw + + draw = ImageDraw.Draw(image) + manifest = output / "supervisor" / "attempt_manifest.json" + attempt = json.loads(manifest.read_text(encoding="utf-8")) if manifest.is_file() else {} + lines = [ + f"RoboHouseGen attempt: {output.name}", + f"status: {attempt.get('status', 'running')}", + "No SceneSmith render state was completed before this checkpoint.", + ] + error = attempt.get("error") or history_error + if error: + lines.extend(("", "diagnostic:", str(error)[:700])) + y = 56 + for line in lines: + draw.text((56, y), line, fill=(242, 242, 238)) + y += 42 + image.save(frame, optimize=True) + manifest_payload = { + "schema_version": "1.1", + "attempt_version": output.name, + "iteration_count": 1, + "visual_iteration_count": 1, + "critic_iteration_count": 0, + "critic_total_duration_s": 0.0, + "iterations": [ + { + "index": 0, + "scene": "diagnostic", + "room": "diagnostic", + "stage": "attempt_lifecycle", + "iteration": output.name, + "contact_sheet": frame.relative_to(output).as_posix(), + } + ], + } + atomic_write_text( + output / "scenesmith" / "iterations_manifest.json", + json.dumps(manifest_payload, ensure_ascii=False, indent=2) + "\n", + ) + return frame + + +def _encode_still_video(frame: Path, target: Path) -> None: + ffmpeg = _ffmpeg_executable() + if not ffmpeg: + raise RuntimeError("ffmpeg is required for the per-version media contract") + target.parent.mkdir(parents=True, exist_ok=True) + # Keep fallback diagnostics bounded even on heavily shared machines. The + # bundled ffmpeg otherwise probes all logical CPUs and can stall for minutes + # while encoding a single repeated frame under contention. + result = subprocess.run( + [ + ffmpeg, "-y", "-loop", "1", "-framerate", "1", "-i", str(frame), + "-frames:v", "1", "-c:v", "libx264", "-preset", "ultrafast", + "-tune", "stillimage", "-threads", "1", "-pix_fmt", "yuv420p", + "-movflags", "+faststart", str(target), + ], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + if result.returncode or not target.is_file(): + raise RuntimeError(f"diagnostic video encoding failed: {result.stderr[-2000:]}") + + +def _stamp_iteration_manifest(output: Path) -> None: + """Attach attempt identity even when history was reused from a checkpoint.""" + + path = output / "scenesmith" / "iterations_manifest.json" + if not path.is_file(): + return + payload = json.loads(path.read_text(encoding="utf-8")) + if payload.get("attempt_version") == output.name: + return + payload["attempt_version"] = output.name + atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + + +def _replace_hardlink(source: Path, destination: Path) -> None: + if destination.is_file(): + try: + if os.path.samefile(source, destination): + return + except OSError: + pass + destination.unlink() + destination.parent.mkdir(parents=True, exist_ok=True) + os.link(source, destination) + + +def _find_video_source(output: Path) -> Path | None: + preferred = output / "scenesmith" / "preview.mp4" + if preferred.is_file() and preferred.stat().st_size > 0: + return preferred + candidates = [path for path in output.glob("**/preview.mp4") if path.is_file()] + return max(candidates, key=lambda path: path.stat().st_mtime) if candidates else None diff --git a/docs/reproduction/public_conversion_code/packages/supervisor/visual_preflight.py b/docs/reproduction/public_conversion_code/packages/supervisor/visual_preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a4afff81ec6c0b4ac3590612a51aaa384abcc --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/supervisor/visual_preflight.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import Any + + +AUDIT_CONTRACT = { + "room_size_and_occupancy": "room_geometry_audit", + "aisle_visibility": "aisle_visual_audit", + "emissive_and_real_lighting": "lighting_material_audit", + "no_white_placeholder_panels": "placeholder_panel_audit", + "required_pbr_bindings": "material_fidelity_audit", +} + + +def evaluate_visual_preflight( + render_manifest: dict[str, Any], config: dict[str, Any] | None = None +) -> dict[str, Any]: + """Evaluate machine-authored final-frame facts before any vision-model call.""" + + settings = config or {} + required = bool(settings.get("required", False)) + checks: list[dict[str, Any]] = [] + for check_id, audit_key in AUDIT_CONTRACT.items(): + audit = render_manifest.get(audit_key) + present = isinstance(audit, dict) + passed = present and audit.get("passed") is True + checks.append( + { + "check_id": check_id, + "audit_key": audit_key, + "present": present, + "passed": passed if required else (passed or not present), + "evidence": audit if present else {}, + } + ) + failures = [item["check_id"] for item in checks if not item["passed"]] + return { + "schema_version": "1.0", + "required": required, + "source": "scenesmith/final_composed_critic_views/manifest.json", + "checks": checks, + "failures": failures, + "passed": not failures, + } diff --git a/docs/reproduction/public_conversion_code/packages/task_agent/__init__.py b/docs/reproduction/public_conversion_code/packages/task_agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f0a9f56634a40b34d66575cad29b5b2aec90567 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_agent/__init__.py @@ -0,0 +1,10 @@ +from packages.task_agent.generator import ConstrainedTaskAgent, TaskDesignError +from packages.task_agent.service import generate_task_spec +from packages.task_agent.spec_agent import GenerativeTaskSpecAgent + +__all__ = [ + "ConstrainedTaskAgent", + "GenerativeTaskSpecAgent", + "TaskDesignError", + "generate_task_spec", +] diff --git a/docs/reproduction/public_conversion_code/packages/task_agent/compiler.py b/docs/reproduction/public_conversion_code/packages/task_agent/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..fbba7930c53849bb6bb555efe6edb570d60ecbc8 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_agent/compiler.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import copy +import os +import re +from pathlib import Path +from typing import Any + +import yaml # type: ignore[import-untyped] + +from packages.schemas.models import PredicateSpec, TaskEntity, TaskPlan, TaskSpec + +DEFAULT_POLICY = Path(__file__).resolve().parents[2] / "configs/task_agent/compiler_v1.yaml" + + +class TaskCompiler: + """Compile a verified skill graph into simulator-independent task predicates.""" + + def __init__(self, policy_path: Path | None = None) -> None: + selected = policy_path or Path(os.environ.get("RHG_TASK_COMPILER_POLICY", DEFAULT_POLICY)) + self.policy: dict[str, Any] = yaml.safe_load(selected.read_text(encoding="utf-8")) + if self.policy.get("schema_version") != "1.0": + raise ValueError(f"unsupported task compiler policy: {selected}") + + def compile(self, plan: TaskPlan, seed: int = 0) -> TaskSpec: + text = plan.natural_language.casefold() + skill_ids = {item.skill_id for item in plan.skills} + object_category = self._first_category(text) + profile = copy.deepcopy(self.policy["default_task"]) + for candidate in self.policy.get("task_profiles", []): + if skill_ids & set(candidate.get("match_any_skills", [])): + profile = _deep_merge(profile, copy.deepcopy(candidate)) + break + profile.pop("match_any_skills", None) + place_prefix = profile.pop("place_goal_prefix", []) + if skill_ids & {"place", "bimanual_place"}: + profile["goal_predicates"] = place_prefix + profile["goal_predicates"] + profile = _render(profile, {"object_category": object_category}) + required_rooms = profile.pop("required_rooms", [self._room(text)]) + return TaskSpec( + task_id=plan.plan_id.replace("plan-", "task-"), + natural_language=plan.natural_language, + task_type=profile.pop("task_type"), + required_rooms=required_rooms, + entities=[TaskEntity.model_validate(item) for item in profile.pop("entities")], + initial_predicates=[ + PredicateSpec.model_validate(item) for item in profile.pop("initial_predicates", []) + ], + forbidden_initial_predicates=[ + PredicateSpec.model_validate(item) + for item in profile.pop("forbidden_initial_predicates", []) + ], + goal_predicates=[ + PredicateSpec.model_validate(item) for item in profile.pop("goal_predicates") + ], + safety_predicates=[ + PredicateSpec.model_validate(item) for item in profile.pop("safety_predicates", []) + ], + plan=plan, + random_seed=seed, + ) + + def _first_category(self, text: str) -> str: + for item in self.policy.get("object_aliases", []): + pattern, category = item["pattern"], item["category"] + if re.search(pattern, text): + return category + return str(self.policy["default_object_category"]) + + def _room(self, text: str) -> str: + for item in self.policy.get("room_aliases", []): + pattern, room = item["pattern"], item["room"] + if re.search(pattern, text): + return room + return str(self.policy["default_room"]) + + +def _deep_merge(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]: + for key, value in overlay.items(): + if isinstance(value, dict) and isinstance(base.get(key), dict): + base[key] = _deep_merge(base[key], value) + else: + base[key] = value + return base + + +def _render(value: Any, context: dict[str, str]) -> Any: + if isinstance(value, dict): + return {key: _render(item, context) for key, item in value.items()} + if isinstance(value, list): + return [_render(item, context) for item in value] + if isinstance(value, str): + for key, replacement in context.items(): + value = value.replace(f"${{{key}}}", replacement) + return value diff --git a/docs/reproduction/public_conversion_code/packages/task_agent/declared_transfer.py b/docs/reproduction/public_conversion_code/packages/task_agent/declared_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c8f6f8a20c48d53814ad1eb72aff3ea13b7d58 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_agent/declared_transfer.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import hashlib +import re + +from packages.schemas.models import ( + DifficultyVector, + PredicateSpec, + SkillInvocation, + TaskEntity, + TaskPlan, + TaskSpec, +) +from packages.task_agent.skills import default_skill_registry + + +def compile_declared_object_transfer( + prompt: str, + entities: list[TaskEntity], + seed: int, +) -> TaskSpec | None: + """Compile a fully declared, unarticulated one-object A-to-B task offline.""" + + manipulated = [item for item in entities if item.role == "MANIPULATED" and item.required] + targets = [item for item in entities if item.role == "TARGET" and item.required] + if len(manipulated) != 1 or len(targets) != 1: + return None + item = manipulated[0] + target = targets[0] + entity_by_id = {entity.entity_id: entity for entity in entities} + dependencies = item.attributes.get("depends_on") or [] + if not isinstance(dependencies, list): + return None + source_candidates = [ + entity_by_id[str(entity_id)] + for entity_id in dependencies + if str(entity_id) in entity_by_id + and entity_by_id[str(entity_id)].role in {"CONTEXT", "TARGET"} + ] + if len(source_candidates) != 1 or source_candidates[0].entity_id == target.entity_id: + return None + source = source_candidates[0] + if not all( + "support_surface" + in {str(value).casefold() for value in entity.attributes.get("required_affordances", [])} + for entity in (source, target) + ): + return None + + dimensions = item.attributes.get("target_dimensions_m") or [] + bimanual = ( + "bowl" in item.category.casefold() + or (isinstance(dimensions, list) and dimensions and max(float(x) for x in dimensions) >= 0.18) + ) + grasp_skill = "bimanual_grasp" if bimanual else "grasp" + place_skill = "bimanual_place" if bimanual else "place" + skill_specs = [ + ("navigate", {"target": source.entity_id}), + (grasp_skill, {"object": item.entity_id}), + ("carry", {"object": item.entity_id, "target": target.entity_id}), + ("navigate", {"target": target.entity_id}), + (place_skill, {"object": item.entity_id, "target": target.entity_id}), + ] + registry = default_skill_registry() + invocations: list[SkillInvocation] = [] + capabilities: set[str] = set() + previous: str | None = None + for index, (skill_id, parameters) in enumerate(skill_specs, start=1): + invocation_id = f"s{index:02d}-{skill_id}" + invocations.append( + SkillInvocation( + invocation_id=invocation_id, + skill_id=skill_id, + parameters=parameters, + depends_on=[previous] if previous else [], + ) + ) + capabilities.update(registry[skill_id].required_capabilities) + previous = invocation_id + + token = hashlib.sha256(f"{seed}\0{prompt}".encode()).hexdigest()[:12] + plan = TaskPlan( + plan_id=f"plan-{token}", + natural_language=prompt, + skills=invocations, + required_capabilities=capabilities, + difficulty=DifficultyVector( + body=0.75, + manipulation=0.4, + cognition=1.0, + body_reason="three mobility stages", + manipulation_reason="grasp and place", + cognition_reason="ordered five-stage transfer", + ), + ) + contact_params = { + "max_support_gap_m": 0.005, + "max_penetration_m": 0.003, + "stable_com_projection": True, + } + upright = any( + term in item.category.casefold() for term in ("bowl", "cup", "mug", "bottle", "can") + ) + initial = [ + PredicateSpec( + name="supported_by", + subject=item.entity_id, + object=source.entity_id, + params=contact_params, + ), + PredicateSpec(name="stable", subject=item.entity_id), + ] + goals = [ + PredicateSpec( + name="supported_by", + subject=item.entity_id, + object=target.entity_id, + params={**contact_params, "placement": "near_center"}, + hold_seconds=1.0, + ), + PredicateSpec(name="stable", subject=item.entity_id, hold_seconds=1.0), + PredicateSpec(name="released", subject=item.entity_id, hold_seconds=1.0), + ] + if upright: + initial.append(PredicateSpec(name="upright", subject=item.entity_id)) + goals.insert(1, PredicateSpec(name="upright", subject=item.entity_id, hold_seconds=1.0)) + + room_terms = [ + (r"\bkitchen\b", "kitchen"), + (r"\bdining\b", "dining_room"), + (r"\bworkshop\b", "workshop"), + (r"\boffice\b", "office"), + (r"\bliving\b|\blounge\b", "living_room"), + ] + required_rooms = [room for pattern, room in room_terms if re.search(pattern, prompt.casefold())] + return TaskSpec( + task_id=f"task-{token}", + natural_language=prompt, + task_type="declared_object_transfer", + required_rooms=list(dict.fromkeys(required_rooms)) or ["indoor_room"], + entities=entities, + initial_predicates=initial, + forbidden_initial_predicates=[ + PredicateSpec( + name="supported_by", subject=item.entity_id, object=target.entity_id + ) + ], + goal_predicates=goals, + safety_predicates=[ + PredicateSpec( + name="robot_stable", + subject="robot", + params={"temporal": "always"}, + hold_seconds=1.0, + ), + PredicateSpec( + name="no_safety_event", + subject="robot", + params={"temporal": "always"}, + ), + ], + plan=plan, + random_seed=seed, + metadata={"task_compiler": "declared_object_transfer_v1", "llm_requests": 0}, + ) diff --git a/docs/reproduction/public_conversion_code/packages/task_agent/generator.py b/docs/reproduction/public_conversion_code/packages/task_agent/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..5e719bff22880c75cd9405f2721931738bd12c98 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_agent/generator.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import os +import random +import re +from pathlib import Path +from uuid import uuid4 + +import yaml # type: ignore[import-untyped] + +from packages.schemas.models import DifficultyVector, SkillInvocation, TaskPlan +from packages.task_agent.compiler import DEFAULT_POLICY +from packages.task_agent.skills import default_skill_registry +from packages.task_catalog.repository import TaskCatalog + + +class TaskDesignError(ValueError): + pass + + +class ConstrainedTaskAgent: + """Retrieval-guided task composer that can only emit registered skills.""" + + def __init__(self, catalog: TaskCatalog) -> None: + self.catalog = catalog + self.skills = default_skill_registry() + policy_path = Path(os.environ.get("RHG_TASK_COMPILER_POLICY", DEFAULT_POLICY)) + self.policy = yaml.safe_load(policy_path.read_text(encoding="utf-8")) + + def generate(self, prompt: str, seed: int = 0) -> TaskPlan: + normalized = prompt.casefold().strip() + if not normalized: + raise TaskDesignError("task prompt cannot be empty") + selected = self._select_skills(normalized) + if not selected: + retrieved = self.catalog.search(prompt, limit=1) + if not retrieved: + raise TaskDesignError("prompt cannot be mapped to registered skills") + selected = self._skills_from_category(retrieved[0].category.casefold()) + if not selected: + raise TaskDesignError("retrieved task requires unregistered skills") + + rng = random.Random(seed) + plan_token = uuid4().hex[:12] if seed == 0 else f"{rng.getrandbits(48):012x}" + invocations: list[SkillInvocation] = [] + previous: str | None = None + required: set[str] = set() + for index, skill_id in enumerate(selected, start=1): + invocation_id = f"s{index:02d}-{skill_id}" + invocations.append( + SkillInvocation( + invocation_id=invocation_id, + skill_id=skill_id, + depends_on=[previous] if previous else [], + ) + ) + previous = invocation_id + required.update(self.skills[skill_id].required_capabilities) + + body = min(1.0, 0.25 * sum(skill in {"navigate", "carry", "step_up"} for skill in selected)) + manipulation = min( + 1.0, + 0.2 + * sum( + skill + in { + "grasp", + "bimanual_grasp", + "place", + "bimanual_place", + "push", + "open_door", + "close_door", + } + for skill in selected + ), + ) + cognition = min(1.0, max(0.0, (len(selected) - 1) / 4.0)) + mobility_stages = sum(skill in {"navigate", "carry", "step_up"} for skill in selected) + return TaskPlan( + plan_id=f"plan-{plan_token}", + natural_language=prompt, + skills=invocations, + required_capabilities=required, + difficulty=DifficultyVector( + body=body, + manipulation=manipulation, + cognition=cognition, + body_reason=f"{mobility_stages} mobility stages", + manipulation_reason=f"{len(selected)} verified skill stages", + cognition_reason=f"ordered plan with {len(selected)} stages", + ), + ) + + def validate(self, plan: TaskPlan) -> None: + for invocation in plan.skills: + skill = self.skills.get(invocation.skill_id) + if skill is None: + raise TaskDesignError(f"unregistered skill: {invocation.skill_id}") + unknown = set(invocation.parameters) - skill.allowed_parameters + if unknown: + raise TaskDesignError( + f"unsupported parameters for {skill.skill_id}: {sorted(unknown)}" + ) + + def _select_skills(self, prompt: str) -> list[str]: + return [ + skill + for item in self.policy.get("skill_patterns", []) + if re.search(item["pattern"], prompt) + for skill in item["skills"] + ] + + def _skills_from_category(self, category: str) -> list[str]: + for item in self.policy.get("category_skill_patterns", []): + if re.search(item["pattern"], category): + return list(item["skills"]) + return [] diff --git a/docs/reproduction/public_conversion_code/packages/task_agent/service.py b/docs/reproduction/public_conversion_code/packages/task_agent/service.py new file mode 100644 index 0000000000000000000000000000000000000000..0adda1e74dd77ca27351b391659d156f0d68e793 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_agent/service.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +import os + +from packages.schemas.models import TaskSpec +from packages.task_agent.compiler import TaskCompiler +from packages.task_agent.generator import ConstrainedTaskAgent +from packages.task_agent.spec_agent import GenerativeTaskSpecAgent +from packages.task_catalog.repository import TaskCatalog + + +def generate_task_spec( + prompt: str, + seed: int, + *, + catalog: TaskCatalog | None = None, + mode: str | None = None, +) -> TaskSpec: + """Generate one TaskSpec through the shared CLI/API policy-selected entry point.""" + selected_mode = (mode or os.environ.get("RHG_TASK_AGENT", "rules")).strip().casefold() + if selected_mode == "generative": + return GenerativeTaskSpecAgent.from_env().generate(prompt, seed) + if selected_mode != "rules": + raise ValueError("RHG_TASK_AGENT must be rules or generative") + selected_catalog = catalog or TaskCatalog.from_default_survey() + plan = ConstrainedTaskAgent(selected_catalog).generate(prompt, seed) + return TaskCompiler().compile(plan, seed) diff --git a/docs/reproduction/public_conversion_code/packages/task_agent/skills.py b/docs/reproduction/public_conversion_code/packages/task_agent/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..27170452146df0b9277003165722c80e5ec15ff4 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_agent/skills.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import os +from pathlib import Path + +import yaml # type: ignore[import-untyped] + +from packages.schemas.models import SkillSpec + + +def default_skill_registry(path: Path | None = None) -> dict[str, SkillSpec]: + declared = path or Path( + os.environ.get("RHG_SKILL_CATALOG", "configs/task_agent/skills_v1.yaml") + ) + if not declared.is_absolute() and not declared.is_file(): + declared = Path(__file__).resolve().parents[2] / declared + payload = yaml.safe_load(declared.read_text(encoding="utf-8")) + skills = [SkillSpec.model_validate(item) for item in payload["skills"]] + registry = {item.skill_id: item for item in skills} + if len(registry) != len(skills): + raise ValueError(f"skill catalog contains duplicate IDs: {declared}") + return registry diff --git a/docs/reproduction/public_conversion_code/packages/task_agent/spec_agent.py b/docs/reproduction/public_conversion_code/packages/task_agent/spec_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..e05f4ed00c5bcc574e07446414398ee982238d51 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_agent/spec_agent.py @@ -0,0 +1,625 @@ +from __future__ import annotations + +import json +import math +import random +import re +from typing import Protocol, get_args + +from pydantic import BaseModel, ConfigDict, Field + +from packages.config import GenerationPolicy, load_generation_policy +from packages.generative import GenerativeClient, RelaySettings +from packages.schemas.models import ( + DifficultyVector, + PredicateSpec, + SkillInvocation, + TaskEntity, + TaskPlan, + TaskSpec, +) +from packages.task_agent.generator import TaskDesignError +from packages.task_agent.skills import default_skill_registry + + +class TextGenerator(Protocol): + def generate_text(self, prompt: str) -> str: ... + + +class TaskSkillDraft(BaseModel): + model_config = ConfigDict(extra="forbid") + + skill_id: str + parameters: dict[str, str | int | float | bool] = Field(default_factory=dict) + + +class TaskSemanticConstraintDraft(BaseModel): + model_config = ConfigDict(extra="forbid") + + constraint_id: str + relation: str + subject: str + object: str + anchor: str | None = None + minimum_distance_m: float | None = Field(default=None, ge=0) + maximum_distance_m: float | None = Field(default=None, ge=0) + + +class TaskDraft(BaseModel): + model_config = ConfigDict(extra="forbid") + + task_type: str = Field(pattern=r"^[a-z][a-z0-9_]*$") + required_rooms: list[str] = Field(min_length=1) + entities: list[TaskEntity] = Field(min_length=1) + skills: list[str | TaskSkillDraft] = Field(min_length=1) + initial_predicates: list[PredicateSpec] = Field(default_factory=list) + forbidden_initial_predicates: list[PredicateSpec] = Field(default_factory=list) + goal_predicates: list[PredicateSpec] = Field(min_length=1) + safety_predicates: list[PredicateSpec] = Field(default_factory=list) + semantic_constraints: list[TaskSemanticConstraintDraft] = Field(default_factory=list) + + +class GenerativeTaskSpecAgent: + """Generate a schema-validated benchmark task graph without scenario code.""" + + def __init__( + self, + client: TextGenerator, + max_attempts: int = 3, + policy: GenerationPolicy | None = None, + ) -> None: + if max_attempts <= 0: + raise ValueError("max_attempts must be positive") + self.client = client + self.max_attempts = max_attempts + self.skills = default_skill_registry() + self.policy = policy or load_generation_policy() + + @classmethod + def from_env(cls) -> GenerativeTaskSpecAgent: + return cls(GenerativeClient(RelaySettings.from_env())) + + def generate(self, prompt: str, seed: int = 0) -> TaskSpec: + if not prompt.strip(): + raise TaskDesignError("task prompt cannot be empty") + request = self._request_prompt(prompt) + error_context = "" + last_error: Exception | None = None + for _ in range(self.max_attempts): + output = self.client.generate_text(request + error_context) + try: + draft = TaskDraft.model_validate(self._parse_object(output)) + return self._compile(draft, prompt, seed) + except (ValueError, TypeError, json.JSONDecodeError) as error: + last_error = error + error_context = ( + "\nThe previous JSON failed validation. Return a corrected JSON object only. " + f"Validation error: {error}\n" + ) + raise TaskDesignError(f"task agent could not produce a valid task graph: {last_error}") + + def _compile(self, draft: TaskDraft, prompt: str, seed: int) -> TaskSpec: + normalized_entities: list[TaskEntity] = [] + matching_aliases = ( + "matching_set", + "matching_group", + "matching_set_id", + "matching_group_id", + ) + for entity in draft.entities: + attributes = dict(entity.attributes) + matching_values = { + str(attributes[key]).strip() + for key in matching_aliases + if attributes.get(key) is not None and str(attributes[key]).strip() + } + if len(matching_values) > 1: + raise ValueError( + f"entity {entity.entity_id} has conflicting matching-set identifiers: " + f"{sorted(matching_values)}" + ) + for key in matching_aliases: + attributes.pop(key, None) + if matching_values: + attributes["matching_set"] = next(iter(matching_values)) + normalized_entities.append(entity.model_copy(update={"attributes": attributes})) + + prompt_distance_range = self._distance_range_from_prompt(prompt) + normalized_constraints: list[TaskSemanticConstraintDraft] = [] + for constraint in draft.semantic_constraints: + minimum = constraint.minimum_distance_m + maximum = constraint.maximum_distance_m + finite_bounds = ( + minimum is not None + and maximum is not None + and math.isfinite(minimum) + and math.isfinite(maximum) + ) + if finite_bounds and maximum < minimum: + minimum, maximum = maximum, minimum + elif ( + constraint.relation == "center_distance" + and not finite_bounds + and prompt_distance_range is not None + ): + minimum, maximum = prompt_distance_range + normalized_constraints.append( + constraint.model_copy( + update={ + "minimum_distance_m": minimum, + "maximum_distance_m": maximum, + } + ) + ) + draft = draft.model_copy( + update={ + "entities": normalized_entities, + "semantic_constraints": normalized_constraints, + } + ) + self._validate_draft(draft) + skill_ids = [item if isinstance(item, str) else item.skill_id for item in draft.skills] + unknown = set(skill_ids) - self.skills.keys() + if unknown: + raise ValueError(f"unregistered skills: {sorted(unknown)}") + required_capabilities: set[str] = set() + invocations: list[SkillInvocation] = [] + previous: str | None = None + for index, item in enumerate(draft.skills, start=1): + skill_id = item if isinstance(item, str) else item.skill_id + parameters = {} if isinstance(item, str) else item.parameters + required_capabilities.update(self.skills[skill_id].required_capabilities) + invocation_id = f"s{index:02d}-{skill_id}" + invocations.append( + SkillInvocation( + invocation_id=invocation_id, + skill_id=skill_id, + parameters=parameters, + depends_on=[previous] if previous else [], + ) + ) + previous = invocation_id + + rng = random.Random(seed) + token = f"{rng.getrandbits(48):012x}" + mobility = sum(skill in {"navigate", "carry", "step_up"} for skill in skill_ids) + manipulation = sum( + skill + in { + "grasp", + "bimanual_grasp", + "place", + "bimanual_place", + "push", + "open_door", + "close_door", + "press_pedal", + } + for skill in skill_ids + ) + plan = TaskPlan( + plan_id=f"plan-{token}", + natural_language=prompt, + skills=invocations, + required_capabilities=required_capabilities, + difficulty=DifficultyVector( + body=min(1.0, mobility * 0.25), + manipulation=min(1.0, manipulation * 0.2), + cognition=min(1.0, max(0.0, (len(skill_ids) - 1) / 4.0)), + body_reason=f"{mobility} mobility stages", + manipulation_reason=f"{manipulation} manipulation stages", + cognition_reason=f"ordered plan with {len(skill_ids)} stages", + ), + ) + raw_goals, raw_safety = self._normalize_predicate_roles( + draft.goal_predicates, draft.safety_predicates + ) + goals = self._add_temporal_constraints(raw_goals, skill_ids) + safety = self._add_safety_constraints(raw_safety) + return TaskSpec( + task_id=f"task-{token}", + natural_language=prompt, + task_type=draft.task_type, + required_rooms=draft.required_rooms, + entities=draft.entities, + initial_predicates=draft.initial_predicates, + forbidden_initial_predicates=draft.forbidden_initial_predicates, + goal_predicates=goals, + safety_predicates=safety, + plan=plan, + random_seed=seed, + metadata={ + "semantic_constraints": [ + item.model_dump(exclude_none=True) for item in draft.semantic_constraints + ] + }, + ) + + @staticmethod + def _distance_range_from_prompt(prompt: str) -> tuple[float, float] | None: + match = re.search( + r"(?P\d+(?:\.\d+)?)\s*(?:to|[-\u2013\u2014])\s*" + r"(?P\d+(?:\.\d+)?)\s*(?:m|meters?)\s+apart\b", + prompt, + flags=re.IGNORECASE, + ) + if match is None: + return None + values = (float(match.group("minimum")), float(match.group("maximum"))) + return tuple(sorted(values)) # type: ignore[return-value] + + @staticmethod + def _add_temporal_constraints( + goals: list[PredicateSpec], skills: list[str] + ) -> list[PredicateSpec]: + """Make physical pedal activation require contact at the threshold crossing.""" + if "press_pedal" not in skills: + return goals + constrained: list[PredicateSpec] = [] + for predicate in goals: + params = dict(predicate.params) + if predicate.name in {"contact", "pressed"}: + params.setdefault("temporal", "ever") + params.setdefault("synchronization_group", "pedal_activation") + params.setdefault("synchronization_window_s", 0.15) + if predicate.name == "pressed": + params.setdefault("unit", "degrees") + elif predicate.name == "open": + # A spring-return pedal bin is expected to close after the robot steps away. + params.setdefault("temporal", "ever") + if "joint" in params: + params.setdefault("unit", "degrees") + constrained.append(predicate.model_copy(update={"params": params})) + return constrained + + @staticmethod + def _normalize_predicate_roles( + goals: list[PredicateSpec], safety: list[PredicateSpec] + ) -> tuple[list[PredicateSpec], list[PredicateSpec]]: + safety_names = {"allowed_body_contact", "no_safety_event"} + normalized_goals = [item for item in goals if item.name not in safety_names] + candidates = [*safety, *(item for item in goals if item.name in safety_names)] + normalized_safety: list[PredicateSpec] = [] + seen: set[str] = set() + for predicate in candidates: + key = predicate.model_dump_json(exclude={"params"}) + json.dumps( + predicate.params, sort_keys=True + ) + if key not in seen: + normalized_safety.append(predicate) + seen.add(key) + return normalized_goals, normalized_safety + + @staticmethod + def _add_safety_constraints(safety: list[PredicateSpec]) -> list[PredicateSpec]: + constrained: list[PredicateSpec] = [] + for predicate in safety: + params = dict(predicate.params) + params.setdefault("temporal", "always") + constrained.append(predicate.model_copy(update={"params": params})) + return constrained + + def _validate_draft(self, draft: TaskDraft) -> None: + allowed_rooms = set(self.policy.task_agent.canonical_rooms) + unknown_rooms = set(draft.required_rooms) - allowed_rooms + if unknown_rooms: + raise ValueError(f"non-canonical required_rooms: {sorted(unknown_rooms)}") + predicates = ( + draft.initial_predicates + + draft.forbidden_initial_predicates + + draft.goal_predicates + + draft.safety_predicates + ) + entity_ids = {entity.entity_id for entity in draft.entities} + for constraint in draft.semantic_constraints: + references = {constraint.subject, constraint.object} + if constraint.anchor: + references.add(constraint.anchor) + unknown = references - entity_ids + if unknown: + raise ValueError( + f"semantic constraint references unknown entities: {sorted(unknown)}" + ) + if constraint.relation == "center_distance": + if ( + constraint.minimum_distance_m is None + or constraint.maximum_distance_m is None + or not math.isfinite(constraint.minimum_distance_m) + or not math.isfinite(constraint.maximum_distance_m) + or constraint.maximum_distance_m < constraint.minimum_distance_m + ): + raise ValueError( + "distance constraint requires an ordered minimum/maximum range" + ) + elif constraint.relation == "clearance": + if ( + constraint.minimum_distance_m is None + or not math.isfinite(constraint.minimum_distance_m) + or ( + constraint.maximum_distance_m is not None + and ( + not math.isfinite(constraint.maximum_distance_m) + or constraint.maximum_distance_m < constraint.minimum_distance_m + ) + ) + ): + raise ValueError( + "clearance constraint requires a finite minimum and optional " + "ordered maximum" + ) + for item in draft.skills: + if isinstance(item, str): + continue + skill = self.skills.get(item.skill_id) + if skill is None: + continue + unknown_parameters = set(item.parameters) - skill.allowed_parameters + if unknown_parameters: + raise ValueError( + f"unsupported parameters for {item.skill_id}: {sorted(unknown_parameters)}" + ) + for key in {"object", "target", "region"} & item.parameters.keys(): + value = item.parameters[key] + if not isinstance(value, str) or value not in entity_ids: + raise ValueError( + f"skill {item.skill_id} parameter {key} must name a task entity" + ) + self._validate_pedal_disposal_order(draft) + referenced_entities = { + reference + for predicate in predicates + for reference in (predicate.subject, predicate.object) + if reference and reference != "robot" + } + support_entities = { + predicate.object + for predicate in predicates + if predicate.name in {"on", "supported_by"} and predicate.object + } + changed_goal_entities = { + predicate.subject + for predicate in draft.goal_predicates + if predicate.name in {"on", "inside", "inside_region", "released", "open", "closed"} + } + architectural_markers = self.policy.task_agent.architectural_markers + for entity in draft.entities: + if entity.role == "ROBOT" or entity.entity_id == "robot": + raise ValueError("robot is implicit and must not be emitted as a task entity") + if entity.role == "REGION" and not self.policy.task_agent.allow_region_entities: + raise ValueError( + "REGION entities are not emitted until the scene backend can author " + "their geometry" + ) + priority = entity.attributes.get("asset_priority") + if priority is not None and ( + not isinstance(priority, list) + or not priority + or any(not isinstance(source, str) or not source for source in priority) + ): + raise ValueError( + "entity attributes.asset_priority must be a non-empty string array" + ) + mount = entity.attributes.get("mount") + if mount is not None and mount not in { + "FLOOR", + "SURFACE", + "WALL", + "CEILING", + "FREE", + }: + raise ValueError( + "entity attributes.mount must be FLOOR, SURFACE, WALL, CEILING, or FREE" + ) + floor_mounted = entity.attributes.get("floor_mounted") + if floor_mounted is not None and not isinstance(floor_mounted, bool): + raise ValueError("entity attributes.floor_mounted must be boolean") + if ( + entity.entity_id not in referenced_entities + and entity.attributes.get("task_relevant") is not True + ): + raise ValueError( + f"unreferenced entity {entity.entity_id} must be omitted or marked " + "task_relevant=true" + ) + if ( + entity.role == "MANIPULATED" + and entity.entity_id in support_entities + and entity.entity_id not in changed_goal_entities + ): + raise ValueError( + f"support-only entity {entity.entity_id} cannot have role MANIPULATED" + ) + entity_terms = set(entity.entity_id.casefold().replace("-", "_").split("_")) | set( + entity.category.casefold().replace("-", "_").split("_") + ) + if ( + entity_terms & architectural_markers + and entity.entity_id not in changed_goal_entities + ): + raise ValueError( + f"architectural scene element {entity.entity_id} must not be a task entity" + ) + + unary = { + "released", + "stable", + "open", + "closed", + "robot_stable", + "allowed_body_contact", + "no_safety_event", + "pressed", + } + binary = { + "on", + "inside", + "near", + "held_by", + "supported_by", + "inside_region", + "contact", + "feet_in_region", + } + for predicate in predicates: + if predicate.name in unary and predicate.object is not None: + raise ValueError(f"unary predicate {predicate.name} must have object=null") + if predicate.name in binary and predicate.object is None: + raise ValueError(f"binary predicate {predicate.name} requires object") + if predicate.name == "allowed_body_contact" and predicate.subject != "robot": + raise ValueError("allowed_body_contact must use subject robot") + for predicate in draft.initial_predicates: + support_relation = str(predicate.params.get("support_relation", "")).casefold() + if support_relation in {"false", "none", "not_supported", "unsupported"}: + raise ValueError( + "negative support relations belong in forbidden_initial_predicates" + ) + + @staticmethod + def _validate_pedal_disposal_order(draft: TaskDraft) -> None: + skill_ids = [item if isinstance(item, str) else item.skill_id for item in draft.skills] + pedal_targets = { + predicate.subject for predicate in draft.goal_predicates if predicate.name == "pressed" + } + disposal_objects = { + predicate.subject + for predicate in draft.goal_predicates + if predicate.name == "inside" and predicate.object in pedal_targets + } + if not disposal_objects: + return + press_indices = [ + index for index, skill_id in enumerate(skill_ids) if skill_id == "press_pedal" + ] + grasp_indices = [ + index + for index, skill_id in enumerate(skill_ids) + if skill_id in {"grasp", "bimanual_grasp"} + ] + carry_indices = [index for index, skill_id in enumerate(skill_ids) if skill_id == "carry"] + place_indices = [ + index + for index, skill_id in enumerate(skill_ids) + if skill_id in {"place", "bimanual_place"} + ] + feasible = any( + grasp < carry < press < place + for grasp in grasp_indices + for carry in carry_indices + for press in press_indices + for place in place_indices + ) + if not feasible: + raise ValueError( + "pedal-bin disposal must order grasp, carry, press_pedal, then place; " + "opening a spring-return bin before fetching the object is infeasible" + ) + + def _request_prompt(self, user_prompt: str) -> str: + skills = ", ".join(self.skills) + predicates = ", ".join(get_args(PredicateSpec.model_fields["name"].annotation)) + rooms = ", ".join(self.policy.task_agent.canonical_rooms) + policy_rules = "\n".join(f"- {rule}" for rule in self.policy.task_agent.prompt_rules) + return f"""You are the task-design Agent in a humanoid benchmark generator. +Convert the user's complete request into one simulator-independent task graph. +Return exactly one JSON object, with no markdown and no commentary. + +Required JSON keys: +task_type, required_rooms, entities, skills, initial_predicates, +forbidden_initial_predicates, goal_predicates, safety_predicates, semantic_constraints. + +Entity fields: entity_id, role, category, attributes, required. +Allowed emitted roles: BACKGROUND, CONTEXT, MANIPULATED, TARGET, DISTRACTOR, REGION. +Canonical required_rooms values: {rooms}. +Allowed skill_id values: {skills}. +skills must be an execution-ordered JSON array of objects. Each object has skill_id and +parameters. Allowed parameter keys are object, target, region, hand, and effector. Values +for object, target, and region must be exact entity IDs. Repeat a skill when the action is +performed more than once; for example, emit separate navigate steps for separate destinations. +Allowed predicate names: {predicates}. +Predicate fields: name, subject, object, params, hold_seconds. +semantic_constraints is an array of measurable initial scene-layout relations. Each item has +constraint_id, relation, subject, object, optional anchor, and optional numeric +minimum_distance_m/maximum_distance_m. Use stable entity IDs. Supported relations are +center_distance, clearance, facing, and opposite_sides. Emit [] when none are requested. + +Rules: +- Create a separate physical entity for every required object and every requested count. +- Use semantic snake_case IDs such as source_table, target_table, sofa, transfer_box. +- All predicate references except robot must name an entity. +- Encode the actual initial state and measurable terminal goals, not visual wishes. +- Encode every requested numeric distance and every task-relevant facing/opposite-side layout + in semantic_constraints; do not leave these requirements only in prose or attributes. +- Put absent or negated relations in forbidden_initial_predicates. Never encode negation + inside params, such as support_relation="not_supported", on a positive initial predicate. +- Emit physical entities needed for task support, manipulation, target evaluation, navigation + obstacles, and every explicitly requested functional furniture/fixture that makes the named + room domain usable and visually recognizable. A requested refrigerator, sink cabinet, + cooktop/oven, workbench, tool cabinet, bar back, shelving unit, or similar functional fixture + is a CONTEXT or BACKGROUND entity even when it is not manipulated. Do not omit it by hiding it + inside another entity's prose description. +- Functional fixtures requested as one coherent set must share a stable non-empty + attributes.semantic_motif value such as "kitchen_run" or "workshop_storage". This lets one + subtree Agent create the cluster without one expensive session per fixture. Keep purely + decorative accessories, architecture, materials, and lighting in the natural-language scene + request; do not turn decorations into task entities. +- An unreferenced obstacle or essential BACKGROUND entity must set attributes.task_relevant=true. +- Put source/target support objects in the graph so scene generation can bind them. +- A support-only table, shelf, floor, or container is BACKGROUND, CONTEXT, or TARGET, + never MANIPULATED unless the task also changes that support object's state or pose. +- Preserve source priorities such as ArtVIP or Poly Haven in entity attributes.asset_priority. +- attributes.asset_priority must be a JSON string array, for example ["ArtVIP", "Poly Haven"]. +- For assets that must form one matching set, give every member the same non-empty + attributes.matching_set value. Do not invent aliases such as matching_group or + matching_set_id. +- Set attributes.mount="FLOOR" on every freestanding floor object such as a desk, sofa, + display stand, cabinet, or trash bin. Set mount="SURFACE" only for objects that require + a support predicate. Never leave a floor-mounted TARGET or CONTEXT object unmarked. +- Do not create an entity for the room itself; required_rooms already carries room membership. +- The robot is implicit. Never emit a ROBOT entity or an entity with entity_id robot. +- Do not emit REGION entities; the current scene backend does not author region geometry. +- Floors, walls, ceilings, thresholds, doorways, windows, lighting, materials, and trim + belong to the scene request, not the task graph, unless that exact element is an + explicitly manipulated or evaluated goal object. +- released, stable, open, closed, pressed, robot_stable, allowed_body_contact and no_safety_event + are unary predicates and must use object: null. +- For a foot-pedal task use press_pedal and emit all three measurable facts: contact + between robot and the pedal with params.subject_body plus temporal=ever, pressed on + the pedal joint with temporal=ever, and open on the lid joint with temporal=ever. A + spring-return lid does not need to remain open in the terminal state. +- Put the contact and pressed facts in synchronization_group="pedal_activation" with + synchronization_window_s=0.15. They must overlap in the simulator trace; the task + compiler also enforces this constraint if it is omitted. +- For pedal-bin disposal, order the physical stages as grasp object, carry object to bin, + press_pedal while retaining it, then place/release it. Never open a spring-return bin + before walking away to fetch the object; this ordering fails semantic validation. +- For the ArtVIP 20 L pedal bin use pressed threshold 35.0 degrees with direction gte, + and open threshold -60.0 degrees with direction lte. Set params.unit="degrees" on both; + thresholds must be JSON numbers. +- allowed_body_contact always uses subject robot; identify the allowed target entity, + link, and robot body in params. +- A contact goal must identify params.subject_body="left_or_right_foot" and the exact + pedal link in params.object_link. Entity-level contact without matching body/link + evidence is insufficient. +- Do not add a scenario-specific implementation name; task_type is a descriptive snake_case label. +- Use only registered skills and predicates. Every physical action stage must have its own + skill entry and entity-bound parameters; repeated skill IDs are valid. +- Include robot_stable and no_safety_event when appropriate. no_safety_event uses + params.temporal="always" because a transient safety violation cannot be erased by a + clean terminal frame. Safety predicates belong only in safety_predicates, never in + goal_predicates; the compiler moves and deduplicates them defensively. +Policy rules: +{policy_rules} + +User request: +{user_prompt} +""" + + @staticmethod + def _parse_object(text: str) -> dict[str, object]: + start = text.find("{") + if start < 0: + raise json.JSONDecodeError("no JSON object found", text, 0) + value, _ = json.JSONDecoder().raw_decode(text[start:]) + if not isinstance(value, dict): + raise TypeError("task agent output must be a JSON object") + return value diff --git a/docs/reproduction/public_conversion_code/packages/task_catalog/__init__.py b/docs/reproduction/public_conversion_code/packages/task_catalog/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ebfb9286720fe390f65f5d29a935b127e0e10732 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_catalog/__init__.py @@ -0,0 +1,3 @@ +from packages.task_catalog.repository import TaskCatalog + +__all__ = ["TaskCatalog"] diff --git a/docs/reproduction/public_conversion_code/packages/task_catalog/html_import.py b/docs/reproduction/public_conversion_code/packages/task_catalog/html_import.py new file mode 100644 index 0000000000000000000000000000000000000000..a997f9f67defe1361e566d21593d3ed8013a14b9 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_catalog/html_import.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any, Literal, cast + +from packages.schemas.models import DifficultyVector, ReviewStatus, TaskRecord + +TASK_DATA = re.compile(r"const TASKS = (\[.*?\]);\s*const state", re.DOTALL) + + +class CatalogImportError(ValueError): + pass + + +def load_survey_html(path: Path) -> list[TaskRecord]: + source = path.read_text(encoding="utf-8") + match = TASK_DATA.search(source) + if not match: + raise CatalogImportError(f"TASKS JSON not found in {path}") + raw: list[dict[str, Any]] = json.loads(match.group(1)) + return [_convert(item, path) for item in raw] + + +def _convert(item: dict[str, Any], path: Path) -> TaskRecord: + tier_value = str(item["tier"]).split()[0] + if tier_value not in {"L0", "L1", "L2", "L3"}: + raise CatalogImportError(f"invalid tier for record {item.get('id')}: {tier_value}") + tier = cast(Literal["L0", "L1", "L2", "L3"], tier_value) + links = item.get("links", []) + source_uri = links[0] if links else item.get("video") or None + media_uri = item.get("image") or item.get("video") or None + return TaskRecord( + record_id=f"survey-{int(item['id']):03d}", + name=str(item["name"]), + description=str(item["description"]), + benchmark=str(item["benchmark"]), + category=str(item["category"]), + difficulty=DifficultyVector( + body=float(item["b"]) / 4.0, + manipulation=float(item["i"]) / 4.0, + cognition=float(item["h"]) / 4.0, + body_reason=str(item["bReason"]), + manipulation_reason=str(item["iReason"]), + cognition_reason=str(item["hReason"]), + ), + tier=tier, + source_uri=source_uri, + media_uri=media_uri, + review_status=ReviewStatus.REVIEWED, + provenance={ + "source_file": path.name, + "source_id": item["id"], + "original_scores": {"B": item["b"], "I": item["i"], "H": item["h"]}, + }, + tags=[str(item["benchmark"]), str(item["category"])], + ) diff --git a/docs/reproduction/public_conversion_code/packages/task_catalog/repository.py b/docs/reproduction/public_conversion_code/packages/task_catalog/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..6e37b43ed28bdfa8bc043308146459d9b6dcaf35 --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/task_catalog/repository.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +from collections import Counter +from pathlib import Path + +from packages.schemas.models import TaskRecord +from packages.task_catalog.html_import import load_survey_html + +DEFAULT_SURVEY = ( + Path(__file__).resolve().parents[2] / "docs" / "人形任务三维度任务预览网页_20260731.html" +) + + +class TaskCatalog: + def __init__(self, records: list[TaskRecord]) -> None: + self._records = records + + @classmethod + def from_default_survey(cls) -> TaskCatalog: + return cls(load_survey_html(DEFAULT_SURVEY)) + + @property + def records(self) -> list[TaskRecord]: + return list(self._records) + + def search( + self, + query: str = "", + benchmark: str | None = None, + category: str | None = None, + tier: str | None = None, + limit: int = 50, + ) -> list[TaskRecord]: + terms = [term.casefold() for term in query.split() if term] + + def score(record: TaskRecord) -> int | None: + if benchmark and record.benchmark != benchmark: + return None + if category and record.category != category: + return None + if tier and record.tier != tier: + return None + haystack = " ".join( + [record.name, record.description, record.benchmark, record.category, *record.tags] + ).casefold() + if not all(term in haystack for term in terms): + return None + return sum(4 if term in record.name.casefold() else 1 for term in terms) + + ranked = [ + (value, record) for record in self._records if (value := score(record)) is not None + ] + ranked.sort(key=lambda pair: (-pair[0], pair[1].record_id)) + return [record for _, record in ranked[:limit]] + + def stats(self) -> dict[str, object]: + count = len(self._records) + means = { + "body": sum(item.difficulty.body for item in self._records) / count, + "manipulation": sum(item.difficulty.manipulation for item in self._records) / count, + "cognition": sum(item.difficulty.cognition for item in self._records) / count, + } + return { + "total": count, + "benchmarks": dict(Counter(item.benchmark for item in self._records)), + "categories": dict(Counter(item.category for item in self._records)), + "tiers": dict(Counter(item.tier for item in self._records)), + "means": means, + } diff --git a/docs/reproduction/public_conversion_code/packages/usd_composer/__init__.py b/docs/reproduction/public_conversion_code/packages/usd_composer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6955cd7388722c49db0d4693fa7356f798cb3c4b --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/usd_composer/__init__.py @@ -0,0 +1,3 @@ +from packages.usd_composer.composer import USDComposer + +__all__ = ["USDComposer"] diff --git a/docs/reproduction/public_conversion_code/packages/usd_composer/composer.py b/docs/reproduction/public_conversion_code/packages/usd_composer/composer.py new file mode 100644 index 0000000000000000000000000000000000000000..b676e60392d664e1c4ed0d164a8c86d70b673a0f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/usd_composer/composer.py @@ -0,0 +1,280 @@ +from __future__ import annotations + +import hashlib +import json +import os +import re +import shutil +from pathlib import Path + +from packages.core.files import atomic_write_text +from packages.robots.profiles import get_robot_profile +from packages.schemas.models import ( + RobotSpawnSpec, + SceneLayerPlan, + SceneManifest, + TaskEntity, + TaskSpec, +) + +LAYER_NAMES = ( + # USD sublayers are strongest-first. Keep physical invariants stronger + # than appearance, and keep both task-owned override layers stronger than + # imported/generated geometry. + "physics_overrides", + "materials", + "room", + "furniture", + "clutter", + "task", + "regions", + "semantics", + "lighting", + "robot", +) + + +class USDComposer: + """Create a compositional USD skeleton without requiring Isaac or pxr.""" + + def compose( + self, + task: TaskSpec, + output_dir: Path, + robot_id: str, + robot_spawn: RobotSpawnSpec | None = None, + ) -> SceneManifest: + layers_dir = output_dir / "layers" + manifests_dir = output_dir / "manifests" + layers_dir.mkdir(parents=True, exist_ok=True) + manifests_dir.mkdir(parents=True, exist_ok=True) + spawn = _resolve_robot_spawn(robot_id, robot_spawn) + packaged_asset_uri, source_asset = _stage_robot_asset( + output_dir, robot_id, spawn.asset_uri + ) + layers: dict[str, str] = {} + for name in LAYER_NAMES: + relative = f"layers/{name}.usda" + layers[name] = relative + body = self._layer_body(name, task, robot_id, spawn, packaged_asset_uri) + atomic_write_text(output_dir / relative, body) + + sublayers = ",\n ".join(f"@{uri}@" for uri in layers.values()) + root = ( + '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' + f' subLayers = [\n {sublayers}\n ]\n upAxis = "Z"\n)\n\n' + 'def Xform "World" {}\n' + ) + atomic_write_text(output_dir / "root.usda", root) + digest = hashlib.sha256() + digest.update(task.model_dump_json().encode()) + for name in LAYER_NAMES: + digest.update((output_dir / layers[name]).read_bytes()) + manifest = SceneManifest( + scene_id=f"scene-{task.task_id.removeprefix('task-')}", + task_id=task.task_id, + random_seed=task.random_seed, + layer_plan=SceneLayerPlan(layers=layers), + entity_prim_paths={ + entity.entity_id: f"/World/Entities/{_usd_identifier(entity.entity_id)}" + for entity in task.entities + }, + robot_prim_path="/World/Robot", + source_checkpoints={ + "robot_profile": robot_id, + "robot_asset": source_asset or "unavailable", + }, + content_hash=digest.hexdigest(), + ) + atomic_write_text( + manifests_dir / "scene.json", + json.dumps(manifest.model_dump(mode="json"), indent=2, sort_keys=True), + ) + atomic_write_text( + manifests_dir / "robot.json", + json.dumps( + { + "schema_version": "1.0", + "robot_id": robot_id, + "prim_path": manifest.robot_prim_path, + "translation_m": list(spawn.translation_m), + "rotation_rpy_deg": list(spawn.rotation_rpy_deg), + "source_asset_uri": source_asset, + "packaged_asset_uri": packaged_asset_uri, + "embodiment_plugin": _robot_embodiment_plugin(robot_id), + }, + indent=2, + sort_keys=True, + ) + + "\n", + ) + return manifest + + @staticmethod + def _layer_body( + name: str, + task: TaskSpec, + robot_id: str, + robot_spawn: RobotSpawnSpec, + robot_asset_uri: str | None, + ) -> str: + if name in {"task", "regions"}: + role = "REGION" if name == "regions" else None + procedural_entities = [ + entity + for entity in task.entities + if (entity.role == role if role else entity.role != "REGION") + and "procedural_geometry" in entity.attributes + ] + return _procedural_layer(procedural_entities) + if name == "semantics": + semantic_entities = "\n".join( + f' def Xform "{entity.entity_id}" {{}}' for entity in task.entities + ) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + 'over Xform "World" {\n def Xform "Entities" {\n' + f"{semantic_entities}\n" + " }\n}\n" + ) + if name == "robot": + reference = ( + f" (\n prepend references = @{robot_asset_uri}@\n )" + if robot_asset_uri + else "" + ) + translation = ", ".join(str(value) for value in robot_spawn.translation_m) + rotation = ", ".join(str(value) for value in robot_spawn.rotation_rpy_deg) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + f'over Xform "World" {{\n def Xform "Robot"{reference} {{\n' + f' custom string robothousegen_robot_id = "{robot_id}"\n' + f" double3 xformOp:translate = ({translation})\n" + f" float3 xformOp:rotateXYZ = ({rotation})\n" + ' uniform token[] xformOpOrder = ' + '["xformOp:translate", "xformOp:rotateXYZ"]\n' + " }\n}\n" + ) + if name == "physics_overrides": + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + 'over Xform "World" {\n' + ' def PhysicsScene "PhysicsScene" {\n' + " vector3f physics:gravityDirection = (0, 0, -1)\n" + " float physics:gravityMagnitude = 9.81\n" + " bool physxScene:enableGPUDynamics = false\n" + ' uniform token physxScene:broadphaseType = "MBP"\n' + " }\n}\n" + ) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n' + " customLayerData = {\n" + f' string robothousegen_task_id = "{task.task_id}"\n' + f' string robothousegen_layer_role = "{name}"\n' + f' string robothousegen_robot_id = "{robot_id}"\n' + " }\n)\n" + ) + + +def _robot_metadata(robot_id: str) -> dict[str, object]: + """Unknown replaceable robots remain valid when no packaged asset is declared.""" + + try: + return dict(get_robot_profile(robot_id).metadata) + except KeyError: + return {} + + +def _robot_embodiment_plugin(robot_id: str) -> str | None: + try: + return get_robot_profile(robot_id).embodiment_plugin + except KeyError: + return None + + +def _resolve_robot_spawn(robot_id: str, declared: RobotSpawnSpec | None) -> RobotSpawnSpec: + if declared is not None: + return declared + metadata = _robot_metadata(robot_id) + return RobotSpawnSpec( + translation_m=metadata.get("default_spawn_translation_m", (0.0, 0.0, 0.0)), + rotation_rpy_deg=metadata.get("default_spawn_rotation_rpy_deg", (0.0, 0.0, 0.0)), + asset_uri=metadata.get("scene_asset_uri"), + ) + + +def _stage_robot_asset( + output_dir: Path, robot_id: str, declared_uri: str | None +) -> tuple[str | None, str | None]: + asset_uri = declared_uri or _robot_metadata(robot_id).get("scene_asset_uri") + if not isinstance(asset_uri, str) or not asset_uri: + return None, None + source = Path(os.path.expandvars(asset_uri)).expanduser() + if not source.is_absolute(): + data_root = Path(os.environ.get("RHG_DATA_ROOT", output_dir.parent)) + source = data_root / source + source = source.resolve() + if not source.is_file(): + if os.environ.get("RHG_REQUIRE_ROBOT_ASSET", "0").casefold() in {"1", "true", "yes"}: + raise FileNotFoundError(f"robot scene asset is missing: {source}") + return None, str(source) + destination_root = output_dir / "assets" / "robots" / _usd_identifier(robot_id) + shutil.copytree(source.parent, destination_root, dirs_exist_ok=True) + packaged = destination_root / source.name + return f"../{packaged.relative_to(output_dir).as_posix()}", str(source) + + +def _usd_identifier(value: str) -> str: + identifier = re.sub(r"[^A-Za-z0-9_]", "_", value) + return identifier if not identifier[:1].isdigit() else f"_{identifier}" + + +def _procedural_layer(entities: list[TaskEntity]) -> str: + bodies = [] + for raw_entity in entities: + geometry = raw_entity.attributes["procedural_geometry"] + if not isinstance(geometry, dict): + raise ValueError(f"procedural geometry for {raw_entity.entity_id} must be an object") + collision = bool(geometry.get("collision", False)) + components = geometry.get("components", []) + if not isinstance(components, list) or not components: + raise ValueError(f"procedural geometry for {raw_entity.entity_id} needs components") + children = [] + for index, component in enumerate(components): + if not isinstance(component, dict) or component.get("shape") != "cube": + raise ValueError("procedural components currently require shape=cube") + size = _vector3(component.get("size_m"), "size_m", positive=True) + translation = _vector3(component.get("translation_m"), "translation_m") + color = _vector3(component.get("display_color", [0.5, 0.5, 0.5]), "display_color") + component_name = _usd_identifier(str(component.get("name", f"component_{index}"))) + schema = ' (prepend apiSchemas = ["PhysicsCollisionAPI"])' if collision else "" + children.append( + f' def Cube "{component_name}"{schema} {{\n' + " double size = 1\n" + f" float3 xformOp:scale = ({size[0]}, {size[1]}, {size[2]})\n" + " double3 xformOp:translate = " + f"({translation[0]}, {translation[1]}, {translation[2]})\n" + " uniform token[] xformOpOrder = " + '["xformOp:translate", "xformOp:scale"]\n' + " color3f[] primvars:displayColor = " + f"[({color[0]}, {color[1]}, {color[2]})]\n" + " }" + ) + bodies.append( + f' def Xform "{_usd_identifier(raw_entity.entity_id)}" {{\n' + + "\n".join(children) + + "\n }" + ) + return ( + '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n' + 'over Xform "World" {\n over Xform "Entities" {\n' + "\n".join(bodies) + "\n }\n}\n" + ) + + +def _vector3(value: object, label: str, *, positive: bool = False) -> tuple[float, float, float]: + if not isinstance(value, list) or len(value) != 3: + raise ValueError(f"procedural component {label} must have three values") + result = (float(value[0]), float(value[1]), float(value[2])) + if positive and any(item <= 0 for item in result): + raise ValueError(f"procedural component {label} must be positive") + return result diff --git a/docs/reproduction/public_conversion_code/packages/validators/__init__.py b/docs/reproduction/public_conversion_code/packages/validators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a215af2c966d53b1bfe433ae1e12a703a9fa75d --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/validators/__init__.py @@ -0,0 +1,15 @@ +from packages.validators.base import ( + ValidationDisposition, + ValidationFinding, + ValidatorRegistry, + ValidatorReport, +) +from packages.validators.task_plugin import validate_task_plugin_compilation + +__all__ = [ + "ValidationDisposition", + "ValidationFinding", + "ValidatorRegistry", + "ValidatorReport", + "validate_task_plugin_compilation", +] diff --git a/docs/reproduction/public_conversion_code/packages/validators/base.py b/docs/reproduction/public_conversion_code/packages/validators/base.py new file mode 100644 index 0000000000000000000000000000000000000000..487fd43f78a4bf2a5a915ad7bc4afbb138aadd0a --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/validators/base.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from collections.abc import Iterable +from enum import StrEnum + +from pydantic import BaseModel, ConfigDict, Field + + +class ValidationDisposition(StrEnum): + PASSED = "passed" + FAILED = "failed" + RUNTIME_REQUIRED = "runtime_required" + + +class ValidationFinding(BaseModel): + model_config = ConfigDict(extra="forbid") + + check_id: str + disposition: ValidationDisposition + details: str = "" + evidence: list[str] = Field(default_factory=list) + + +class ValidatorReport(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: str = "1.0" + validator_id: str + subject_id: str + passed: bool + findings: list[ValidationFinding] + runtime_required_checks: list[str] = Field(default_factory=list) + + @classmethod + def build( + cls, + *, + validator_id: str, + subject_id: str, + findings: Iterable[ValidationFinding], + ) -> ValidatorReport: + materialized = list(findings) + return cls( + validator_id=validator_id, + subject_id=subject_id, + passed=all( + item.disposition != ValidationDisposition.FAILED + for item in materialized + ), + findings=materialized, + runtime_required_checks=[ + item.check_id + for item in materialized + if item.disposition == ValidationDisposition.RUNTIME_REQUIRED + ], + ) + + +class ValidatorRegistry: + def __init__(self) -> None: + self._validators: dict[str, object] = {} + + def register(self, validator_id: str, validator: object) -> None: + if validator_id in self._validators: + raise ValueError(f"duplicate validator: {validator_id}") + self._validators[validator_id] = validator + + def require(self, validator_id: str) -> object: + try: + return self._validators[validator_id] + except KeyError as error: + raise KeyError(f"validator is not registered: {validator_id}") from error diff --git a/docs/reproduction/public_conversion_code/packages/validators/task_plugin.py b/docs/reproduction/public_conversion_code/packages/validators/task_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..bd4a3517d83af8e392d943967eda30aec34a801e --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/validators/task_plugin.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import json +from typing import Any + +from packages.plugins.tasks.base import TaskPluginCompilation, TaskPluginSpec +from packages.schemas.models import PredicateSpec +from packages.validators.base import ( + ValidationDisposition, + ValidationFinding, + ValidatorReport, +) + + +def _predicate_key(predicate: PredicateSpec) -> str: + return json.dumps( + predicate.model_dump(mode="json"), + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) + + +def _finding(check_id: str, passed: bool, details: str) -> ValidationFinding: + return ValidationFinding( + check_id=check_id, + disposition=( + ValidationDisposition.PASSED if passed else ValidationDisposition.FAILED + ), + details=details, + ) + + +def validate_task_plugin_compilation( + spec: TaskPluginSpec, + compilation: TaskPluginCompilation, +) -> ValidatorReport: + task = compilation.task_spec + requirements = compilation.scene_requirements + evaluator = compilation.evaluator_spec + findings: list[ValidationFinding] = [] + findings.append( + _finding( + "plugin.identity_bound", + compilation.plugin_id == spec.plugin_id + and compilation.plugin_version == spec.version, + f"compiled={compilation.plugin_id}@{compilation.plugin_version}; " + f"declared={spec.plugin_id}@{spec.version}", + ) + ) + findings.append( + _finding( + "task.truth_is_structured", + task.metadata.get("description_source") == "TaskSpec structured parameters" + and task.metadata.get("task_plugin", {}).get("plugin_id") == spec.plugin_id, + "natural language must be emitted from the structured plugin compilation", + ) + ) + findings.append( + _finding( + "requirements.task_id", + requirements.task_id == task.task_id == evaluator.task_id, + "TaskSpec, SceneRequirements and EvaluatorSpec must bind to one task_id", + ) + ) + findings.append( + _finding( + "requirements.robot_capabilities", + requirements.required_robot_capabilities + == spec.required_robot_capabilities, + "compiled robot capabilities must exactly match the plugin declaration", + ) + ) + declared_profiles = {item.value for item in spec.required_asset_certifications} + findings.append( + _finding( + "requirements.asset_certifications", + requirements.required_asset_certifications == declared_profiles, + "compiled asset profiles must exactly match the plugin declaration", + ) + ) + initial = {_predicate_key(item) for item in task.initial_predicates} + goals = {_predicate_key(item) for item in task.goal_predicates} + forbidden = {_predicate_key(item) for item in task.forbidden_initial_predicates} + findings.append( + _finding( + "goal.conjunction_false_initially", + bool(goals - initial) and bool(goals & forbidden), + "at least one goal must be absent initially and explicitly forbidden initially", + ) + ) + findings.append( + _finding( + "evaluator.goal_identity", + [_predicate_key(item) for item in evaluator.goal_predicates] + == [_predicate_key(item) for item in task.goal_predicates], + "evaluator goals must be byte-canonically equivalent to TaskSpec goals", + ) + ) + witness_steps = compilation.witness.get("steps") + witness_skills = ( + [str(item.get("skill")) for item in witness_steps if isinstance(item, dict)] + if isinstance(witness_steps, list) + else [] + ) + findings.append( + _finding( + "witness.skill_graph", + witness_skills == spec.skill_graph, + f"witness={witness_skills}; declared={spec.skill_graph}", + ) + ) + controls = set(evaluator.negative_control_tests) + findings.append( + _finding( + "negative_controls.declared", + controls == set(spec.negative_control_tests) + and {"no_op", "random_policy"}.issubset(controls), + f"controls={sorted(controls)}", + ) + ) + findings.append( + _finding( + "negative_controls.no_op_static", + bool(goals - initial), + "no-op cannot satisfy the full goal conjunction from the declared initial state", + ) + ) + runtime_checks: dict[str, str] = { + "runtime.navigation": "navigation and stance zones require a runtime occupancy map", + "runtime.ik_collision": ( + "IK and collision feasibility require the selected assets and robot" + ), + "runtime.physics_stability": "mass, contact and articulation must run in Isaac", + "runtime.oracle_replay": "the symbolic witness must be bound to a controller and replayed", + "negative_controls.random_policy": "random-policy accidental success is empirical", + "runtime.safety_limits": "contact force and torque limits require simulator observations", + } + for check_id, details in runtime_checks.items(): + findings.append( + ValidationFinding( + check_id=check_id, + disposition=ValidationDisposition.RUNTIME_REQUIRED, + details=details, + ) + ) + return ValidatorReport.build( + validator_id="task_plugin_static_v1", + subject_id=task.task_id, + findings=findings, + ) + + +def report_to_json(report: ValidatorReport) -> dict[str, Any]: + return report.model_dump(mode="json") diff --git a/docs/reproduction/public_conversion_code/packages/version.py b/docs/reproduction/public_conversion_code/packages/version.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc265d36f2b8ad7aaa91dcc8a8010f9f6ba0e2f --- /dev/null +++ b/docs/reproduction/public_conversion_code/packages/version.py @@ -0,0 +1,4 @@ +"""Stable product-release metadata exposed without changing public schemas.""" + +PRODUCT_VERSION = "fast" +API_COMPAT_VERSION = "0.1.0" diff --git a/docs/reproduction/public_conversion_code/scripts/author_isaac_asset_metadata.py b/docs/reproduction/public_conversion_code/scripts/author_isaac_asset_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..afc07ea1d168f3784c89ce9f98f91eb348e0ac40 --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/author_isaac_asset_metadata.py @@ -0,0 +1,112 @@ +"""Author collision and canonical-stage metadata on copied USD assets.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +from pxr import Sdf, Usd, UsdGeom, UsdPhysics, UsdShade + + +def _first_geometry(stage: Usd.Stage) -> Usd.Prim | None: + for prim in stage.Traverse(): + if prim.IsA(UsdGeom.Mesh): + return prim + return None + + +def _author(job: dict[str, str]) -> dict[str, object]: + path = Path(job["path"]).resolve() + stage = Usd.Stage.Open(str(path)) + if stage is None: + raise RuntimeError(f"could not open USD: {path}") + root = stage.GetDefaultPrim() + if not root or not root.IsValid(): + root = _first_geometry(stage) + if root is None: + raise RuntimeError(f"USD has no mesh: {path}") + stage.SetDefaultPrim(root) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + root.SetCustomDataByKey("robothousegen:isaac_compatible", True) + root.SetCustomDataByKey("robothousegen:canonical_frame", "Z-up meters") + repaired_dependencies: list[str] = [] + for prim in stage.Traverse(): + if not prim.IsA(UsdShade.Shader): + continue + file_input = UsdShade.Shader(prim).GetInput("file") + if not file_input: + continue + value = file_input.Get() + if not isinstance(value, Sdf.AssetPath) or not value.path: + continue + declared = Path(value.path.replace("\\", "/")) + referenced = declared if declared.is_absolute() else path.parent / declared + if referenced.is_file(): + continue + # Some upstream PolyHaven USD packages retain the publisher's staging + # absolute texture path. The managed package has the same texture under + # its sibling textures directory, so resolve by immutable basename + # before trying an extension-equivalent local file. + local_texture_root = path.parent / "textures" + alternatives = [] + if local_texture_root.is_dir(): + alternatives.extend(local_texture_root.glob(declared.name)) + alternatives.extend(local_texture_root.glob(declared.stem + ".*")) + alternatives.extend(referenced.parent.glob(referenced.stem + ".*")) + alternatives = sorted(set(alternatives)) + replacement = next((candidate for candidate in alternatives if candidate.is_file()), None) + if replacement is None: + continue + relative = replacement.relative_to(path.parent).as_posix() + file_input.Set(Sdf.AssetPath("./" + relative)) + repaired_dependencies.append(f"{value.path}->{relative}") + mesh_count = 0 + collision_count = 0 + for prim in stage.Traverse(): + if not prim.IsA(UsdGeom.Mesh): + continue + mesh_count += 1 + api = UsdPhysics.CollisionAPI.Apply(prim) + api.CreateCollisionEnabledAttr().Set(True) + collision_count += 1 + stage.GetRootLayer().Save() + return { + "asset_id": job["asset_id"], + "status": "authored", + "path": str(path), + "mesh_count": mesh_count, + "collision_mesh_count": collision_count, + "repaired_texture_dependencies": repaired_dependencies, + } + + +def main() -> None: + values = sys.argv[sys.argv.index("--") + 1 :] + if len(values) != 2: + raise ValueError("expected jobs JSON and result JSON") + jobs_path, result_path = (Path(value).resolve() for value in values) + jobs = json.loads(jobs_path.read_text(encoding="utf-8")) + if not isinstance(jobs, list): + raise ValueError("jobs JSON must contain a list") + results = [] + for job in jobs: + try: + results.append(_author(job)) + except Exception as error: + results.append( + { + "asset_id": str(job.get("asset_id", "unknown")), + "status": "failed", + "error": f"{type(error).__name__}: {error}", + } + ) + result_path.parent.mkdir(parents=True, exist_ok=True) + result_path.write_text(json.dumps(results, indent=2, sort_keys=True) + "\n", encoding="utf-8") + if any(item["status"] == "failed" for item in results): + raise RuntimeError("one or more USD authoring jobs failed") + + +if __name__ == "__main__": + main() diff --git a/docs/reproduction/public_conversion_code/scripts/blender_convert_asset.py b/docs/reproduction/public_conversion_code/scripts/blender_convert_asset.py new file mode 100644 index 0000000000000000000000000000000000000000..83f706ad5d594de3ccd563941c3d3d2b42ddca8c --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/blender_convert_asset.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import sys +from pathlib import Path + +import bpy + + +def args_after_separator() -> list[str]: + return sys.argv[sys.argv.index("--") + 1 :] + + +source_text, output_text = args_after_separator() +source = Path(source_text) +output = Path(output_text) +bpy.ops.wm.read_factory_settings(use_empty=True) + +extension = source.suffix.casefold() +if extension == ".blend": + bpy.ops.wm.open_mainfile(filepath=str(source)) +elif extension in {".glb", ".gltf"}: + bpy.ops.import_scene.gltf(filepath=str(source)) +elif extension == ".fbx": + bpy.ops.import_scene.fbx(filepath=str(source)) +elif extension == ".obj": + if hasattr(bpy.ops.wm, "obj_import"): + bpy.ops.wm.obj_import(filepath=str(source)) + else: + bpy.ops.import_scene.obj(filepath=str(source)) +else: + raise ValueError(f"unsupported Blender input: {extension}") + +bpy.ops.wm.usd_export(filepath=str(output), export_materials=True, relative_paths=True) diff --git a/docs/reproduction/public_conversion_code/scripts/blender_convert_high_fidelity_batch.py b/docs/reproduction/public_conversion_code/scripts/blender_convert_high_fidelity_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..1a6a7a6ff5ff9f9c008199424a8ade5516c66858 --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/blender_convert_high_fidelity_batch.py @@ -0,0 +1,72 @@ +"""Convert a batch of extracted OBJ assets into canonical USD packages.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import bpy + + +def _reset() -> None: + bpy.ops.wm.read_factory_settings(use_empty=True) + + +def _convert(job: dict[str, str]) -> dict[str, str]: + source = Path(job["source"]).resolve() + output = Path(job["output"]).resolve() + if not source.is_file(): + raise FileNotFoundError(source) + output.parent.mkdir(parents=True, exist_ok=True) + _reset() + suffix = source.suffix.casefold() + if suffix == ".obj": + bpy.ops.wm.obj_import(filepath=str(source)) + elif suffix in {".glb", ".gltf"}: + bpy.ops.import_scene.gltf(filepath=str(source)) + elif suffix == ".fbx": + bpy.ops.import_scene.fbx(filepath=str(source)) + else: + raise ValueError(f"unsupported mesh source: {suffix}") + if not bpy.context.scene.objects: + raise RuntimeError(f"OBJ import produced no objects: {source}") + bpy.ops.wm.usd_export( + filepath=str(output), + export_materials=True, + relative_paths=True, + root_prim_path="/Asset", + ) + if not output.is_file() or output.stat().st_size == 0: + raise RuntimeError(f"USD export did not create {output}") + return {"asset_id": job["asset_id"], "status": "converted", "output": str(output)} + + +def main() -> None: + values = sys.argv[sys.argv.index("--") + 1 :] + if len(values) != 2: + raise ValueError("expected jobs JSON and result JSON") + jobs_path, result_path = (Path(value).resolve() for value in values) + jobs = json.loads(jobs_path.read_text(encoding="utf-8")) + if not isinstance(jobs, list): + raise ValueError("jobs JSON must contain a list") + results = [] + for job in jobs: + try: + results.append(_convert(job)) + except Exception as error: + results.append( + { + "asset_id": str(job.get("asset_id", "unknown")), + "status": "failed", + "error": f"{type(error).__name__}: {error}", + } + ) + result_path.parent.mkdir(parents=True, exist_ok=True) + result_path.write_text(json.dumps(results, indent=2, sort_keys=True) + "\n", encoding="utf-8") + if any(item["status"] == "failed" for item in results): + raise RuntimeError("one or more batch conversions failed") + + +if __name__ == "__main__": + main() diff --git a/docs/reproduction/public_conversion_code/scripts/convert_asset.py b/docs/reproduction/public_conversion_code/scripts/convert_asset.py new file mode 100644 index 0000000000000000000000000000000000000000..05b43aeea430f071f14f9604da66096f59e27112 --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/convert_asset.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +from pathlib import Path + +from packages.core.files import atomic_write_text + +MESH_EXTENSIONS = {".blend", ".fbx", ".glb", ".gltf", ".obj"} + + +def run(command: list[str]) -> None: + result = subprocess.run(command, check=False, text=True, capture_output=True) + if result.returncode: + raise RuntimeError(f"converter failed ({result.returncode}): {result.stderr[-4000:]}") + + +def copy_usd_package(source: Path, output: Path) -> int: + shutil.copy2(source, output) + source_textures = source.parent / "textures" + output_textures = output.parent / "textures" + if not source_textures.is_dir() or source_textures.resolve() == output_textures.resolve(): + return 0 + shutil.copytree(source_textures, output_textures, dirs_exist_ok=True) + return sum(path.is_file() for path in source_textures.rglob("*")) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Convert a visual asset to an Isaac-compatible USD" + ) + parser.add_argument("source", type=Path) + parser.add_argument("output", type=Path) + parser.add_argument("--blender", default=os.environ.get("BLENDER_BIN", "blender")) + parser.add_argument("--isaac-converter-command", nargs="+") + args = parser.parse_args() + source = args.source.resolve() + output = args.output.resolve() + if not source.is_file(): + raise FileNotFoundError(source) + output.parent.mkdir(parents=True, exist_ok=True) + + extension = source.suffix.casefold() + dependencies_copied = 0 + if extension in {".usd", ".usda", ".usdc", ".usdz"}: + dependencies_copied = copy_usd_package(source, output) + converter = "copy-usd" + elif extension in MESH_EXTENSIONS: + helper = Path(__file__).with_name("blender_convert_asset.py") + run([args.blender, "--background", "--python", str(helper), "--", str(source), str(output)]) + converter = "blender" + elif extension in {".urdf", ".xml", ".mjcf"}: + if not args.isaac_converter_command: + raise RuntimeError("URDF/MJCF conversion requires --isaac-converter-command") + run([*args.isaac_converter_command, "--source", str(source), "--output", str(output)]) + converter = "isaac" + else: + raise ValueError(f"unsupported input extension: {extension}") + + manifest = { + "schema_version": "1.0", + "source": str(source), + "output": str(output), + "converter": converter, + "dependencies_copied": dependencies_copied, + "scoring_allowed": False, + "qa_status": "CONVERTED_VISUAL_ONLY", + } + atomic_write_text( + output.with_suffix(output.suffix + ".manifest.json"), json.dumps(manifest, indent=2) + ) + print(json.dumps(manifest, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/docs/reproduction/public_conversion_code/scripts/prepare_asset_pool.py b/docs/reproduction/public_conversion_code/scripts/prepare_asset_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..83bdea7718b39cd30bf18efa52e2e449f99902da --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/prepare_asset_pool.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""Prepare every metadata-ready candidate in a frozen household-role catalog.""" +import argparse,atexit,copy,hashlib,json,os,socket,sqlite3,subprocess,sys,time,traceback,tempfile,shutil +from pathlib import Path + +ROOT=Path(__file__).resolve().parents[1] +CODE=ROOT/'scripts/internal/scene_generation/real_assets' +sys.path.insert(0,str(CODE)) +from stage_checkpoint import atomic_json,HashMemo,fingerprint +_RUNTIME_RELEASE_HASHES=HashMemo() + +def read(path):return json.loads(Path(path).read_text()) + +def freeze_runtime_release(rows,path,allow_substitutes=False): + """Freeze optional derived runtimes while retaining original source identity.""" + memo=HashMemo();path=Path(path).resolve();identity=memo.digest(path);indexed={} + for line in path.read_text().splitlines(): + if not line.strip():continue + record=json.loads(line);indexed.setdefault(record['asset_id'],[]).append(record) + for row in rows: + matches=indexed.get(row['asset_id'],[]) + if len(matches)!=1: + row['runtime_release_rejection']='no_unique_runtime_release_match';continue + record=matches[0];source=Path(row['canonical_path']);runtime=Path(record['library_locator']) + try: + source_sha=memo.digest(source) + if not record.get('file_and_dependency_integrity_verified'): + raise ValueError('runtime_release_integrity_unqualified') + original_locator=record.get('original_library_locator') or record.get('source_locator') + if not original_locator or memo.digest(original_locator)!=source_sha: + raise ValueError('runtime_release_original_source_mismatch') + if record.get('uses_substitute') and not allow_substitutes: + raise ValueError('runtime_release_material_substitution_disallowed') + runtime_sha=memo.digest(runtime) + if runtime_sha==memo.digest(row.get('runtime_path') or source):continue + provenance=Path(record['repair_provenance_manifest']) + row['runtime_release_selection']={'release_path':str(path),'release_sha256':identity, + 'original_candidate_key':row['pool_candidate_key'],'source_sha256':source_sha, + 'original_runtime_path':str(row.get('runtime_path') or source), + 'original_runtime_sha256':memo.digest(row.get('runtime_path') or source), + 'runtime_path':str(runtime),'runtime_sha256':runtime_sha, + 'repair_provenance_manifest':str(provenance),'repair_provenance_sha256':memo.digest(provenance), + 'repair_status':record.get('repair_status'),'uses_substitute':bool(record.get('uses_substitute')), + 'source_catalog_runtime_eligibility':record.get('source_runtime_eligibility'), + 'appearance_qualification':'requires_new_evidence_for_this_runtime'} + row['pool_candidate_key']=fingerprint({'original':row['pool_candidate_key'],'runtime_sha256':runtime_sha,'release_sha256':identity}) + except (OSError,KeyError,ValueError) as error:row['runtime_release_rejection']=str(error) + return {'path':str(path),'sha256':identity,'allow_material_substitutes':allow_substitutes, + 'changed_runtime_count':sum('runtime_release_selection' in r for r in rows), + 'rejected_count':sum('runtime_release_rejection' in r for r in rows)} + + +def activate_runtime_release(row,pair_root=None,config=None): + if row.get('runtime_release_rejection'):raise ValueError(row['runtime_release_rejection']) + selected=row.get('runtime_release_selection') + if not selected:return row + memo=_RUNTIME_RELEASE_HASHES + for path,expected in ((selected['release_path'],selected['release_sha256']), + (row['canonical_path'],selected['source_sha256']),(selected['runtime_path'],selected['runtime_sha256']), + (selected['repair_provenance_manifest'],selected['repair_provenance_sha256'])): + if memo.digest(path)!=expected:raise ValueError('frozen_runtime_release_identity_changed') + row['runtime_path']=selected['runtime_path'];row['runtime_sha256']=selected['runtime_sha256'] + row['runtime_provenance']=copy.deepcopy(selected) + row['runtime_material_fidelity_unverified']=True + if not pair_root:raise ValueError('runtime_release_material_pair_qualification_required') + folder=Path(pair_root)/'cases'/row['pool_candidate_key'];proof_path=folder/'pair_result.json' + proof=read(proof_path);process=read(folder/'process.json');case=read(folder/'case.json') + if (process.get('exit_code')!=0 or not proof.get('passed') or proof.get('schema')!='rhg.runtime_material_pair.v1' + or proof.get('case_sha256')!=memo.digest(folder/'case.json') + or proof.get('source_sha256')!=selected['source_sha256'] + or proof.get('runtime_sha256')!=selected['runtime_sha256'] + or proof.get('canonical_transform')!=row['canonical_transform'] + or proof.get('original',{}).get('mesh_signatures')!=proof.get('repaired',{}).get('mesh_signatures') + or not proof.get('original',{}).get('mesh_signatures')): + raise ValueError('runtime_release_material_pair_not_qualified') + expected_original=selected.get('original_runtime_sha256') or case['original_runtime_sha256'] + if memo.digest(case['original_runtime'])!=expected_original:raise ValueError('runtime_release_reference_runtime_changed') + for path,expected in proof.get('dependencies',{}).items(): + if memo.digest(path)!=expected:raise ValueError('runtime_release_pair_dependency_changed') + from official_mdl_adapter import runtime_identity + pipeline=hashlib.sha256(json.dumps(runtime_identity(config),sort_keys=True).encode()).hexdigest() + for side in ('original','repaired'): + declared=proof[side].get('material_pipeline_sha256') + if declared and declared!=pipeline:raise ValueError('runtime_release_pair_material_pipeline_changed') + row['runtime_material_fidelity_unverified']=False + row['runtime_material_pair_qualification']={'path':str(proof_path),'sha256':memo.digest(proof_path), + 'scope':'exact_imported_geometry_UV_normals_material_assignment_and_pixel_bound_node_graph', + 'MDL_lossless_equivalence':False} + if row.get('annotation_overlay'): + row['annotation_overlay']['runtime_evidence_reused']=False + row['annotation_overlay']['runtime_variant_requires_new_evidence']=True + for key in ('texture_derivative_plan','source_support_geometry','source_geometry_probe_key', + 'source_material_pipeline_sha256','probe_implementation_sha256','prepared_source_frame_contract','prepared_material_artifact'): + row.pop(key,None) + receipt=row.get('annotation_dimension_consumption') + if receipt: + receipt.setdefault('previous_runtime_dimension_decision',copy.deepcopy(receipt)) + receipt.update(action='hint',reason='new_runtime_variant_requires_current_measurement',comparable=False) + return row + + +def initialize(args): + args.pool.mkdir(parents=True,exist_ok=False) + config=read(args.config) + with sqlite3.connect(args.catalog.resolve().as_uri()+'?mode=ro',uri=True) as db: + catalog_report=json.loads(db.execute("SELECT value FROM metadata WHERE key='report'").fetchone()[0]) + rows=[json.loads(r[0]) for r in db.execute('SELECT metadata_json FROM candidates ORDER BY candidate_key')] + roles=set(args.role or catalog_report['required_roles']);pending=[];ready=[] + for row in rows: + matching=set(row['catalog_roles']) & roles + if not matching:continue + if row['catalog_state']!='placement_candidate_unprepared': + pending.append({'asset_id':row['asset_id'],'roles':sorted(matching),'state':row['catalog_state'], + 'blockers':row.get('annotation_replacement_blockers',[])});continue + variants=[row] + if row.get('source_component_provenance'): + reflected=copy.deepcopy(row);reflected['canonical_transform'][0]*=-1 + reflected['pool_counter_reflection']=True;variants.append(reflected) + for variant in variants: + variant['pool_candidate_key']=fingerprint([variant['asset_id'],variant['canonical_path'], + variant.get('canonical_transform'),variant.get('canonical_front_axis'),variant.get('runtime_path')]) + ready.append(variant) + unique={r['pool_candidate_key']:r for r in ready};ready=list(unique.values()) + runtime_release=freeze_runtime_release(ready,args.runtime_release_manifest,args.allow_material_substitutes) if args.runtime_release_manifest else None + (args.pool/'tasks').mkdir();(args.pool/'results').mkdir() + for index,start in enumerate(range(0,len(ready),8)): + atomic_json(args.pool/'tasks'/f'{index:05d}.json',ready[start:start+8]) + atomic_json(args.pool/'pending_metadata.json',pending) + atomic_json(args.pool/'configuration.json',config) + atomic_json(args.pool/'manifest.json',{'schema':'rhg.prepared_pool_build.v1','created_at':time.time(), + 'catalog_path':str(args.catalog),'catalog_sha256':HashMemo().digest(args.catalog), + 'source_metadata_identity':catalog_report['source_metadata_identity'],'roles':sorted(roles), + 'candidate_count':len(ready),'task_count':len(list((args.pool/'tasks').glob('*.json'))), + 'metadata_pending_rows':len(pending),'fixed_denominator':True,'runtime_release':runtime_release, + 'qualification':'source_import_material_geometry_support; final_scene_acceptance_still_required'}) + print(json.dumps(read(args.pool/'manifest.json')),flush=True) + +def worker(args): + from stable_pipeline import child_environment + from annotation_overlay import apply_overlay + from bind_fixed_layout import (apply_orientation_overrides,preparation_entity,apply_geometry_probe, + prepared_candidate,semantic_match) + from unified_asset_catalog import refresh_verified_roles + from texture_derivatives import plan_candidates + from source_probe_contract import configure_preparation_context,implementation_signature + from support_contact_cache import apply_records,implementation_signature as support_signature + from source_support import support_geometry_prepared + config=read(args.pool/'configuration.json');meta=read(args.pool/'manifest.json') + if args.blender:config['blender']=args.blender + if getattr(args,'gpu',None) is not None:config['gpu']=args.gpu + config['python']=sys.executable + env=child_environment(config,args.pool/'worker_runtime'/str(os.getpid())) + env['RHG_MATERIAL_PHASE']='offline_prepare' + env['RHG_PREPARED_MATERIAL_ROOT']=str(args.pool/'material_libraries') + if args.material_artifact_index:env['RHG_PREPARED_MATERIAL_INDEX']=str(args.material_artifact_index) + material_index=read(args.material_artifact_index) if args.material_artifact_index else {} + version=subprocess.check_output([config['blender'],'--version'],text=True,timeout=30).splitlines()[0].removeprefix('Blender ') + env['RHG_PREPARATION_BLENDER_VERSION']=version + os.environ.update(env) + local_lookup=None + if not meta.get('source_attribute_release'): + local_lookup=Path(tempfile.mkdtemp(prefix='rhg_pool_lookup_'))/'annotation.sqlite3' + atexit.register(shutil.rmtree,local_lookup.parent,ignore_errors=True) + # The main lookup is read-only; only the small per-worker dimension cache is mutable. + local_lookup.symlink_to(args.lookup.resolve()) + shutil.copy2(str(args.lookup)+'.json',str(local_lookup)+'.json') + configure_preparation_context(config['mdl_search_paths'],version) + signature=implementation_signature(CODE,CODE.parent) + for task in sorted((args.pool/'tasks').glob('*.json')): + work=args.pool/'results'/task.stem + try:work.mkdir() + except FileExistsError:continue + atomic_json(work/'worker.json',{'pid':os.getpid(),'host':socket.gethostname(),'status':'running','started':time.time()}) + records=[] + try: + if meta.get('source_attribute_release'): + from source_release_preparation import verify_candidates + rows=verify_candidates(read(task),meta['source_attribute_release']) + else: + rows,overlay=apply_overlay(read(task),local_lookup) + rows=refresh_verified_roles(rows,meta['roles'],semantic_match) + rows=apply_orientation_overrides(rows,read(CODE/'source_orientation_overrides.json')) + rows,_=plan_candidates(rows,args.pool/'texture_derivatives',config['texture_decoder']) + entities=[] + for row in rows: + try: + row=activate_runtime_release(row,args.runtime_material_pairs,config) + if material_index.get('rejections'): + from prepared_materials import identity as material_identity,fingerprint as material_fingerprint + rejected=material_index['rejections'].get(material_fingerprint(material_identity(row))) + if rejected: + raise ValueError('Independent offline material asset rejection: '+json.dumps(rejected)) + if row.get('pool_counter_reflection'): + row['source_geometry_variant']={ + 'kind':'counter_long_axis_reflection', + 'source_wrapper_sha256':row['source_component_provenance']['wrapper_sha256'], + 'matrix':list(row['canonical_transform']),'front_preserved':'+Y', + 'reason':'offline qualification of the certified reflected counter contract'} + role='kitchen_sink' if 'kitchen_sink' in row['catalog_roles'] else next(iter(sorted(set(row['catalog_roles']) & set(meta['roles'])))) + slot={'entity_id':'pool_'+row['pool_candidate_key'],'role':role,'binding_semantic_key':role, + 'layout_slot_id':role,'dimensions_m':row['dimensions_m'],'center_xy_m':[0,0], + 'base_z_m':0,'yaw_deg':0,'contract_yaw_deg':0} + entity=preparation_entity(slot,row,1.,row['dimensions_m']);entities.append(entity) + except Exception as error: + records.append({'candidate_key':row['pool_candidate_key'],'asset_id':row['asset_id'], + 'status':'source_entry_preparation_failed','error':repr(error)}) + manifest=work/'source_manifest.json';atomic_json(manifest,{'entities':entities}) + geometry=work/'source_geometry_probe.json';support=work/'source_support_probe.json' + if entities: + with (work/'geometry.log').open('w') as log: + result=subprocess.run([sys.executable,str(CODE/'prepare_sources_resilient.py'), + '--manifest',str(manifest),'--out',str(geometry),'--helpers-dir',str(CODE.parent), + '--blender',config['blender']],env=env,stdout=log,stderr=subprocess.STDOUT,timeout=1200) + if result.returncode not in (0,1):raise RuntimeError('geometry worker exit '+str(result.returncode)) + candidates=apply_geometry_probe(entities,read(geometry),signature) + valid=[e for e in candidates if prepared_candidate(e)] + atomic_json(work/'support_manifest.json',{'entities':valid}) + if valid: + with (work/'support.log').open('w') as log: + subprocess.run([config['blender'],'--background','--threads','4','--python-exit-code','1', + '--python',str(CODE/'probe_support_contacts.py'),'--','--manifest',str(work/'support_manifest.json'), + '--out',str(support),'--geometry-probe',str(geometry),'--helpers-dir',str(CODE.parent)], + env=env,stdout=log,stderr=subprocess.STDOUT,timeout=600) + candidates=apply_records(candidates,read(support) if support.exists() else {'records':[]}, + blender_version=version,mdl_search_paths=config['mdl_search_paths'],importer_signature=signature, + support_signature=support_signature(CODE,signature)) + qualified=[] + for row in candidates: + passed=prepared_candidate(row) and support_geometry_prepared(row) + records.append({'candidate_key':row['pool_candidate_key'],'asset_id':row['asset_id'], + 'status':'prepared' if passed else 'source_or_support_preparation_failed', + 'error':row.get('probe_rejected') or row.get('source_support_geometry_rejection')}) + if passed: + row.pop('texture_derivative_plan',None) + row['catalog_state']='placement_candidate_unprepared' # compatible role query; pool receipt carries qualification + qualified.append(row) + atomic_json(work/'qualified_candidates.json',qualified) + except Exception as error: + (work/'exception.txt').write_text(traceback.format_exc()) + known={r['candidate_key'] for r in records} + records.extend({'candidate_key':r['pool_candidate_key'],'asset_id':r['asset_id'], + 'status':'worker_failure','error':repr(error)} for r in read(task) if r['pool_candidate_key'] not in known) + atomic_json(work/'receipt.json',{'host':socket.gethostname(),'records':records,'task_sha256':HashMemo().digest(task), + 'blender_version':version,'importer_signature':signature,'completed_at':time.time()}) + print(json.dumps({'task':task.stem,'prepared':sum(r['status']=='prepared' for r in records),'total':len(records)}),flush=True) + +def finalize(args): + from collections import Counter + from support_contact_cache import item_key,implementation_signature as support_signature + from prepared_asset_pool import SCHEMA + meta=read(args.pool/'manifest.json');tasks=sorted((args.pool/'tasks').glob('*.json')) + assert all((args.pool/'results'/task.stem/'receipt.json').is_file() for task in tasks),'Preparation still running' + target=args.pool/'prepared_assets.sqlite3' + assert not target.exists(),'Never overwrite a sealed pool' + statuses=Counter();qualified=0;signature=None;version=None;rows=[];annotation_identities=set() + acceptance_index=read(args.material_artifact_index) if args.material_artifact_index else {'artifacts':{}} + accepted_materials={ref['sha256']:ref for ref in acceptance_index['artifacts'].values()} + accepted_materials.update({record['artifact']['sha256']:record['artifact'] + for record in acceptance_index.get('case_artifacts',{}).values()}) + def verify_acceptance(ref): + memo=HashMemo() + try: + certificate=ref['acceptance'] + if memo.digest(certificate['path'])!=certificate['sha256']: + raise ValueError('Material acceptance certificate changed') + evidence=read(certificate['path']) + if evidence.get('passed') is not True or evidence['manifest_sha256']!=ref['sha256']: + raise ValueError('Material acceptance identity mismatch') + if any(memo.digest(e['path'])!=e['sha256'] for e in evidence['evidence']): + raise ValueError('Material acceptance evidence changed') + return ref['sha256'],None + except (KeyError,ValueError,OSError) as error: + return ref['sha256'],str(error) + from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(max_workers=8) as verifier: + acceptance_errors=dict(verifier.map(verify_acceptance,accepted_materials.values())) + quarantine_path=ROOT/'configs/prepared_asset_quarantine.json' + quarantine=read(quarantine_path) if quarantine_path.exists() else {'schema':'rhg.native_assembly_quarantine.v1','entries':[]} + assert quarantine['schema']=='rhg.native_assembly_quarantine.v1' + quarantined=0 + with sqlite3.connect(target.with_suffix('.tmp')) as db: + db.execute('CREATE TABLE candidates(candidate_key TEXT PRIMARY KEY, asset_id TEXT, candidate_json TEXT, geometry_json TEXT, support_json TEXT)') + db.execute('CREATE TABLE quarantined_candidates(candidate_key TEXT PRIMARY KEY, asset_id TEXT, candidate_json TEXT, geometry_json TEXT, support_json TEXT, reason_json TEXT)') + for task in tasks: + work=args.pool/'results'/task.stem;receipt=read(work/'receipt.json') + assert HashMemo().digest(task)==receipt['task_sha256'] + assert {r['pool_candidate_key'] for r in read(task)}=={r['candidate_key'] for r in receipt['records']},'Missing candidate receipts' + statuses.update(r['status'] for r in receipt['records']);rows.extend(receipt['records']) + if signature is None:signature=receipt['importer_signature'];version=receipt['blender_version'] + assert signature==receipt['importer_signature'] and version==receipt['blender_version'] + if not (work/'qualified_candidates.json').exists():continue + prepared_rows=read(work/'qualified_candidates.json') + if not prepared_rows:continue + geometry=read(work/'source_geometry_probe.json')['lookup'];support={r['key']:r for r in read(work/'source_support_probe.json')['records']} + for original in prepared_rows: + row=copy.deepcopy(original);geo=copy.deepcopy(geometry[row['source_geometry_probe_key']]);sup=support[item_key(row)] + consumption=row['annotation_dimension_consumption'] + annotation_identities.add((consumption['snapshot_sha256'],consumption['lookup_sha256'])) + if geo.get('prepared_material_artifact') or geo.get('source_material_compatibility',{}).get('translated_materials') or row.get('runtime_release_selection'): + prepared=geo.get('prepared_material_artifact',{}) + if not prepared and row.get('runtime_release_selection'): + from prepared_materials import fingerprint as material_fingerprint + material_key=material_fingerprint({'source_sha256':row['asset_sha256'], + 'runtime_sha256':row['runtime_sha256'],'canonical_transform':[float(v) for v in row['canonical_transform']]}) + prepared=acceptance_index['artifacts'].get(material_key,{}) + accepted=accepted_materials.get(prepared.get('sha256')) + try: + if not accepted or accepted['path']!=prepared['path']: + raise ValueError('Independent offline material acceptance missing or failed') + if acceptance_errors[prepared['sha256']]: + raise ValueError(acceptance_errors[prepared['sha256']]) + except (KeyError,ValueError,OSError) as error: + statuses['prepared']-=1;statuses['material_acceptance_failed_or_pending']+=1 + result=next(r for r in receipt['records'] if r['candidate_key']==row['pool_candidate_key']) + result.update(status='material_acceptance_failed_or_pending',source_preparation_status='prepared',error=str(error)) + continue + row['prepared_material_artifact']=copy.deepcopy(accepted) + geo['prepared_material_artifact']=copy.deepcopy(accepted) + geo['source_material_compatibility']['prepared_material_artifact']=copy.deepcopy(accepted) + for key in ('mesh_material_records','material_images','upward_planes_m','previews'):geo.pop(key,None) + if 'measurement' in geo:geo['measurement']={k:v for k,v in geo['measurement'].items() if k in ('visual_footprint_polygon_xy_m','canonical_dimensions_m')} + for key in ('annotation_overlay','annotation_field_values','source_record_metadata','annotation_hints', + 'texture_derivative_plan','source_support_geometry'):row.pop(key,None) + values=(row['pool_candidate_key'],row['asset_id'],json.dumps(row),json.dumps(geo),json.dumps(sup)) + reason=next((e for e in quarantine['entries'] if e['runtime_sha256']==row['runtime_sha256'] and e['blender_version']==version),None) + if reason: + db.execute('INSERT INTO quarantined_candidates VALUES(?,?,?,?,?,?)',(*values,json.dumps(reason))) + statuses['prepared']-=1;statuses['assembly_unstable']+=1;quarantined+=1 + result=next(r for r in receipt['records'] if r['candidate_key']==row['pool_candidate_key']) + result.update(status='assembly_unstable',source_preparation_status='prepared',quarantine=reason) + continue + db.execute('INSERT INTO candidates VALUES(?,?,?,?,?)',values) + qualified+=1 + db.execute('CREATE INDEX asset_lookup ON candidates(asset_id)') + assert len(annotation_identities)==1,'Mixed annotation inputs in one pool' + snapshot_sha,lookup_sha=next(iter(annotation_identities));config=read(args.pool/'configuration.json') + assert snapshot_sha==config['annotation_sha256'] + target.with_suffix('.tmp').replace(target) + receipt={**meta,'schema':SCHEMA,'sha256':HashMemo().digest(target),'qualified_count':qualified, + 'candidate_status_counts':dict(statuses),'importer_signature':signature,'blender_version':version, + 'support_signature':support_signature(CODE,signature),'finalized_at':time.time(), + 'source_qualified_count_before_quarantine':qualified+quarantined,'assembly_quarantined_count':quarantined, + 'material_acceptance_index_sha256':HashMemo().digest(args.material_artifact_index) if args.material_artifact_index else None, + 'material_acceptance_gate':'independent_offline_asset_acceptance_required_for_translated_materials', + 'quarantine_registry_sha256':HashMemo().digest(quarantine_path) if quarantine_path.exists() else None, + 'annotation_identity':{'snapshot_sha256':snapshot_sha,'lookup_sha256':lookup_sha, + 'delivery_receipt_sha256':config.get('annotation_delivery_receipt_sha256')}} + atomic_json(target.with_suffix('.receipt.json'),receipt);atomic_json(args.pool/'all_candidate_results.json',rows) + print(json.dumps(receipt),flush=True) + + +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('mode',choices=['init','worker','finalize']) + p.add_argument('--pool',type=Path,required=True);p.add_argument('--config',type=Path) + p.add_argument('--catalog',type=Path);p.add_argument('--lookup',type=Path);p.add_argument('--blender') + p.add_argument('--gpu',help='Explicit worker GPU; overrides the frozen preparation configuration device only') + p.add_argument('--runtime-release-manifest',type=Path,help='Explicit available_models.jsonl; derived runtimes are remeasured in a new pool') + p.add_argument('--allow-material-substitutes',action='store_true',help='Explicitly admit labelled substitutions; never claims original material recovery') + p.add_argument('--runtime-material-pairs',type=Path,help='Independent source/repaired material-pair results required for changed runtime bytes') + p.add_argument('--material-artifact-index',type=Path,help='Reuse immutable offline material libraries and their asset acceptance') + p.add_argument('--role',action='append',help='Repeat to freeze the union of roles required by multiple household cases') + args=p.parse_args();{'init':initialize,'worker':worker,'finalize':finalize}[args.mode](args) +if __name__=='__main__':main() diff --git a/docs/reproduction/public_conversion_code/scripts/preprocess_high_fidelity_assets.py b/docs/reproduction/public_conversion_code/scripts/preprocess_high_fidelity_assets.py new file mode 100755 index 0000000000000000000000000000000000000000..8c4f2e77d488c5d7670ba99405db87f69437f014 --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/preprocess_high_fidelity_assets.py @@ -0,0 +1,777 @@ +#!/usr/bin/env python3 +"""Prepare full GSO/PolyHaven packages for Isaac Sim and rich ACTIVE retrieval. + +The command never mutates raw or staged source packages. It writes a resumable, +versioned canonical USD library, then releases only assets that pass geometry, +dependency, collision, dimensions, orientation and rich-tag checks. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import re +import shutil +import subprocess +import sys +import time +import zipfile +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Iterable + +from pydantic import BaseModel, ConfigDict, Field + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from packages.asset_registry.descriptors import AssetDescriptor +from packages.asset_registry.basisu import normalize_basisu_glb +from packages.asset_registry.front_certification import definition_for_category +from packages.asset_registry.front_policy import front_meets_requirement +from packages.asset_registry.models import AssetCatalog, AssetFile, AssetKind, AssetRecord +from packages.asset_registry.release import _resolve_duplicates, _write_descriptor_index +from packages.core.files import atomic_write_text + + +class _StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class PlanItem(_StrictModel): + asset_id: str + source: str + source_license: str + display_name: str + category: str + source_path: str + canonical_path: str + source_kind: str + status: str = "pending" + error: str = "" + + +class PreprocessPlan(_StrictModel): + schema_version: str = "1.0" + created_at: str + sources: dict[str, str] + items: list[PlanItem] + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _md5(path: Path) -> str: + digest = hashlib.md5(usedforsecurity=False) + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _words(value: str) -> list[str]: + return re.findall(r"[a-z0-9]+", value.casefold().replace("_", " ").replace("-", " ")) + + +def _slug(value: str) -> str: + return "-".join(_words(value)) or "asset" + + +def _title(value: str) -> str: + return " ".join(token.capitalize() for token in _words(value)) + + +def _category(value: str) -> str: + text = " ".join(_words(value)) + rules = ( + (("bookcase", "bookshelf", "book shelf"), "bookcase"), + (("desk", "worktable", "writing table"), "desk"), + (("side table", "end table", "coffee table", "dining table", "table"), "table"), + (("office chair", "armchair", "chair"), "chair"), + (("sofa", "couch"), "sofa"), + (("cabinet", "cupboard", "dresser", "drawer"), "cabinet"), + (("shelf", "rack"), "shelf"), + (("mug",), "mug"), + (("cup",), "cup"), + (("bottle",), "bottle"), + (("bowl",), "bowl"), + (("carton", "box", "crate"), "box"), + (("lamp", "light"), "lamp"), + (("plant", "flower", "tree"), "plant"), + (("laptop",), "computer"), + (("monitor", "display"), "monitor"), + (("television", " tv"), "television"), + (("door",), "door"), + ) + return next((category for needles, category in rules if any(needle in text for needle in needles)), "object") + + +def _safe_extract(archive: Path, destination: Path) -> None: + root = destination.resolve() + with zipfile.ZipFile(archive) as bundle: + for member in bundle.infolist(): + target = (destination / member.filename).resolve() + if not target.is_relative_to(root): + raise ValueError(f"archive member escapes destination: {member.filename}") + bundle.extractall(destination) + + +def _plan_paths(output: Path) -> tuple[Path, Path, Path]: + return output / "preprocess_plan.json", output / "prepared_catalog.json", output / "preprocess_report.json" + + +def _discover(asset_root: Path, output: Path, *, base_index: Path, include_base_active: bool) -> PreprocessPlan: + gso_root = asset_root / "raw/gso_fuel_collection_full/collection-2022-06-13-snapshot-20260828/archives" + poly_root = asset_root / "raw/polyhaven_models_full_2k/api-models-20260828-2k/models" + canonical = output / "canonical" + if not gso_root.is_dir() or not poly_root.is_dir(): + raise FileNotFoundError("full GSO and PolyHaven managed source packages are required") + items: list[PlanItem] = [] + for source in sorted(poly_root.glob("*/*_2k.usdc")): + name = source.parent.name + items.append( + PlanItem( + asset_id=f"polyhaven:{name}", + source="Poly Haven", + source_license="CC0-1.0", + display_name=_title(name), + category=_category(name), + source_path=str(source), + canonical_path=str(canonical / "polyhaven" / name / source.name), + source_kind="polyhaven_usd", + ) + ) + for archive in sorted(gso_root.glob("*.zip")): + name = archive.stem + items.append( + PlanItem( + asset_id=f"gso:{name}", + source="Google Scanned Objects", + source_license="CC-BY-4.0", + display_name=_title(name), + category=_category(name), + source_path=str(archive), + canonical_path=str(canonical / "gso" / name / "asset.usdc"), + source_kind="gso_zip_obj", + ) + ) + if include_base_active: + discovered_ids = {item.asset_id for item in items} + for descriptor in _read_descriptors(base_index): + if descriptor.status != "ACTIVE": + continue + if descriptor.asset_id in discovered_ids: + continue + source = Path(descriptor.canonical_path) + suffix = source.suffix.casefold() + kind = "base_usd" if suffix in {".usd", ".usda", ".usdc", ".usdz"} else "base_mesh" + safe_id = re.sub(r"[^a-zA-Z0-9_.-]+", "_", descriptor.asset_id) + items.append( + PlanItem( + asset_id=descriptor.asset_id, + source=descriptor.source, + source_license=descriptor.source_license, + display_name=descriptor.display_name, + category=descriptor.category, + source_path=str(source), + canonical_path=str( + output + / "canonical" + / "base" + / descriptor.sha256[:2] + / f"{safe_id}{source.suffix.casefold() if kind == 'base_usd' else '.usdc'}" + ), + source_kind=kind, + ) + ) + ids = [item.asset_id for item in items] + if len(ids) != len(set(ids)): + raise ValueError("asset discovery produced duplicate IDs") + return PreprocessPlan( + created_at=datetime.now(UTC).isoformat(), + sources={"gso_raw": str(gso_root), "polyhaven_raw": str(poly_root)}, + items=items, + ) + + +def _write_plan(plan: PreprocessPlan, path: Path) -> None: + atomic_write_text(path, plan.model_dump_json(indent=2) + "\n") + + +def _selected(plan: PreprocessPlan, sources: set[str], limit: int | None) -> list[PlanItem]: + selected = [item for item in plan.items if item.source_kind.split("_", 1)[0] in sources] + return selected[:limit] if limit is not None else selected + + +def _copy_polyhaven(item: PlanItem) -> None: + source = Path(item.source_path) + destination = Path(item.canonical_path) + if destination.is_file(): + return + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + # Managed raw packages are immutable (0444). Canonical copies are the + # separate writable layer where Isaac collision metadata is authored. + destination.chmod(0o644) + textures = source.parent / "textures" + if textures.is_dir(): + shutil.copytree(textures, destination.parent / "textures", dirs_exist_ok=True) + + +def _copy_base_usd(item: PlanItem) -> None: + source = Path(item.source_path) + destination = Path(item.canonical_path) + if destination.is_file(): + return + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + destination.chmod(0o644) + for name in ("textures", "materials"): + sibling = source.parent / name + if sibling.is_dir(): + shutil.copytree(sibling, destination.parent / name, dirs_exist_ok=True) + + +def _blender_source(item: PlanItem, output: Path) -> Path: + source = Path(item.source_path) + if source.suffix.casefold() != ".glb" or b"KHR_texture_basisu" not in source.read_bytes(): + return source + ktx = os.environ.get("RHG_KTX_TOOL", "").strip() + if not ktx: + raise RuntimeError("RHG_KTX_TOOL is required for KHR_texture_basisu conversion") + normalized = output / ".normalized" / _sha256(source) / "asset.gltf" + if normalized.is_file(): + return normalized + return normalize_basisu_glb(source, normalized.parent, ktx_tool=Path(ktx)) + + +def _extract_gso(item: PlanItem) -> Path: + archive = Path(item.source_path) + destination = Path(item.canonical_path).parent + obj = destination / "meshes/model.obj" + if obj.is_file(): + return obj + destination.mkdir(parents=True, exist_ok=True) + _safe_extract(archive, destination) + if not obj.is_file(): + candidates = sorted(destination.rglob("*.obj")) + if not candidates: + raise FileNotFoundError(f"no OBJ in {archive}") + return candidates[0] + return obj + + +def _run(command: list[str]) -> None: + result = subprocess.run(command, check=False, capture_output=True, text=True) + if result.returncode: + raise RuntimeError((result.stdout + result.stderr)[-4000:]) + + +def _convert( + plan: PreprocessPlan, + output: Path, + args: argparse.Namespace, + *, + checkpoint_path: Path | None = None, +) -> PreprocessPlan: + selected = _selected(plan, set(args.sources.split(",")), args.limit) + jobs: list[dict[str, str]] = [] + for item in selected: + try: + if item.source_kind == "polyhaven_usd": + _copy_polyhaven(item) + item.status = "converted" + elif item.source_kind == "base_usd": + _copy_base_usd(item) + item.status = "converted" + else: + source = _extract_gso(item) if item.source_kind == "gso_zip_obj" else _blender_source(item, output) + if not Path(item.canonical_path).is_file(): + jobs.append({"asset_id": item.asset_id, "source": str(source), "output": item.canonical_path}) + else: + item.status = "converted" + except Exception as error: + item.status = "failed" + item.error = f"{type(error).__name__}: {error}" + if checkpoint_path is not None: + _write_plan(plan, checkpoint_path) + worker = PROJECT_ROOT / "scripts/blender_convert_high_fidelity_batch.py" + for offset in range(0, len(jobs), args.blender_batch_size): + batch = jobs[offset : offset + args.blender_batch_size] + jobs_path = output / "jobs" / f"gso_convert_{offset // args.blender_batch_size:05d}.json" + result_path = jobs_path.with_suffix(".result.json") + atomic_write_text(jobs_path, json.dumps(batch, indent=2) + "\n") + try: + _run([args.blender, "--background", "--python", str(worker), "--", str(jobs_path), str(result_path)]) + except Exception: + pass + results = json.loads(result_path.read_text(encoding="utf-8")) if result_path.is_file() else [] + by_id = {str(item.get("asset_id")): item for item in results} + for job in batch: + result = by_id.get(job["asset_id"], {"status": "failed", "error": "missing worker result"}) + target = next(item for item in plan.items if item.asset_id == job["asset_id"]) + target.status = "converted" if result.get("status") == "converted" else "failed" + target.error = str(result.get("error") or "") + if checkpoint_path is not None: + _write_plan(plan, checkpoint_path) + author_jobs = [ + {"asset_id": item.asset_id, "path": item.canonical_path} + for item in selected + if item.status == "converted" and Path(item.canonical_path).is_file() + ] + for job in author_jobs: + Path(job["path"]).chmod(0o644) + author = PROJECT_ROOT / "scripts/author_isaac_asset_metadata.py" + for offset in range(0, len(author_jobs), args.usd_batch_size): + batch = author_jobs[offset : offset + args.usd_batch_size] + jobs_path = output / "jobs" / f"isaac_author_{offset // args.usd_batch_size:05d}.json" + result_path = jobs_path.with_suffix(".result.json") + atomic_write_text(jobs_path, json.dumps(batch, indent=2) + "\n") + try: + _run([args.usd_python, str(author), "--", str(jobs_path), str(result_path)]) + except Exception: + pass + results = json.loads(result_path.read_text(encoding="utf-8")) if result_path.is_file() else [] + by_id = {str(item.get("asset_id")): item for item in results} + for job in batch: + result = by_id.get(job["asset_id"], {"status": "failed", "error": "missing USD author result"}) + target = next(item for item in plan.items if item.asset_id == job["asset_id"]) + target.status = "ready" if result.get("status") == "authored" else "failed" + target.error = str(result.get("error") or "") + if checkpoint_path is not None: + _write_plan(plan, checkpoint_path) + return plan + + +def _records(plan: PreprocessPlan, *, selected_only: Iterable[PlanItem] | None = None) -> list[AssetRecord]: + values = list(selected_only) if selected_only is not None else plan.items + records = [] + for item in values: + canonical = Path(item.canonical_path) + if item.status != "ready" or not canonical.is_file(): + continue + source = Path(item.source_path) + records.append( + AssetRecord( + asset_id=item.asset_id, + display_name=item.display_name, + description=( + f"High-fidelity {item.source} asset prepared as a canonical " + "Z-up metre USD with explicit collision meshes for Isaac Sim." + ), + source=item.source, + source_license=item.source_license, + category=item.category, + tags=sorted(set([*(_words(item.display_name)), item.category, "high fidelity", "isaac sim", "pbr"])), + files=[ + AssetFile( + relative_path=str(source), + source_url="managed-immutable-source", + md5=_md5(source), + size_bytes=source.stat().st_size, + ) + ], + usd_path=str(canonical), + quality_tier="A", + scoring_allowed=True, + qa_status="CONVERTED", + asset_kind=AssetKind.OBJECT, + ) + ) + return records + + +def _size_class(dimensions: tuple[float, float, float]) -> str: + footprint = dimensions[0] * dimensions[1] + if max(dimensions) <= 0.35: + return "small" + if footprint >= 2.0 or max(dimensions) >= 2.0: + return "large" + return "medium" + + +_CARDINAL_AXES = {"+X", "-X", "+Y", "-Y"} +_OPPOSITE_AXIS = {"+X": "-X", "-X": "+X", "+Y": "-Y", "-Y": "+Y"} +_RIGHT_OF_FRONT = {"+X": "-Y", "-X": "+Y", "+Y": "+X", "-Y": "-X"} + + +def _axis_tag(axis: str) -> str: + return axis.replace("+", "positive_").replace("-", "negative_").casefold() + + +def _orientation_contract(descriptor: AssetDescriptor) -> dict[str, Any]: + """Expose the complete canonical frame and the placement authority. + + ``front_axis`` alone is not enough for an Agent to decide whether an asset + may face another entity. The contract keeps visual metadata separate from + a certified functional direction and makes the safety policy searchable. + """ + + definition = definition_for_category(descriptor.category) + semantic = definition.functional_semantics + directional = semantic not in {"none", "unknown"} + certified = front_meets_requirement(descriptor) + structured_certificate = bool( + descriptor.functional_front_axis in _CARDINAL_AXES + and descriptor.front_evidence + and descriptor.review_status.value in {"AUTO_REVIEWED", "HUMAN_VERIFIED"} + ) + functional_front = ( + descriptor.functional_front_axis + if descriptor.functional_front_axis in _CARDINAL_AXES and certified + else None + ) + # Old v2 descriptors can be certified through their hash-bound legacy + # certificate, even though their structured functional field is absent. + if functional_front is None and certified: + functional_front = descriptor.front_axis + visual_front = ( + descriptor.visual_front_axis + if descriptor.visual_front_axis in _CARDINAL_AXES + else None + ) + front = functional_front or visual_front + right = _RIGHT_OF_FRONT.get(front) if front else None + policy = ( + "directional_placement_allowed" + if directional and functional_front + else "directional_placement_blocked" + if directional + else "rotationally_symmetric_no_front_required" + if descriptor.symmetry_type.value.casefold() in { + "rotational", + "rotational_and_mirror", + } + else "visual_orientation_optional" + ) + return { + "schema_version": "orientation-contract-v1", + "canonical_frame": {"up": "+Z", "down": "-Z", "units": "meter"}, + "category_definition": definition.definition_id, + "functional_semantics": semantic, + "direction_sensitive": directional, + "directional_placement_policy": policy, + "functional_front": functional_front, + "visual_front": visual_front, + "back": _OPPOSITE_AXIS.get(front) if front else None, + "right": right, + "left": _OPPOSITE_AXIS.get(right) if right else None, + "functional_front_certified": certified, + "confidence": ( + descriptor.front_confidence + if structured_certificate + else descriptor.confidence.get("front_axis", 0.0) + ), + "confidence_grade": ( + descriptor.front_confidence_grade.value + if structured_certificate + else "VERIFIED" if certified else descriptor.front_confidence_grade.value + ), + "method": ( + descriptor.front_method.value + if structured_certificate + else descriptor.front_axis_source + ), + "review_status": ( + descriptor.review_status.value + if structured_certificate + else "LEGACY_HASH_BOUND_CERTIFICATE" if certified else descriptor.review_status.value + ), + "symmetry": descriptor.symmetry_type.value, + "anti_inversion": { + "canonical_up": "+Z", + "placement_requires_z_up": True, + "roll_pitch_allowed": False, + }, + } + + +def _rich_tags(descriptor: AssetDescriptor) -> AssetDescriptor: + width, depth, height = descriptor.native_bbox_m + aspect = max(width, depth) / max(min(width, depth), 1.0e-6) + tokens = set(descriptor.semantic_tags) + orientation = _orientation_contract(descriptor) + tokens.update( + { + "high_fidelity", + "canonical_z_up", + "units_meter", + f"size_{_size_class((width, depth, height))}", + f"width_m_{width:.2f}".replace(".", "p"), + f"depth_m_{depth:.2f}".replace(".", "p"), + f"height_m_{height:.2f}".replace(".", "p"), + f"footprint_m2_{width * depth:.2f}".replace(".", "p"), + f"aspect_ratio_{aspect:.1f}".replace(".", "p"), + f"support_{descriptor.support_type}", + # This legacy axis remains useful for geometry inspection, but it + # is explicitly not a functional placement certificate. + f"authored_geometry_front_{_axis_tag(descriptor.front_axis)}", + f"front_confidence_{descriptor.front_confidence_grade.value.casefold()}", + f"quality_overall_{descriptor.quality.overall}", + f"quality_geometry_{descriptor.quality.geometry}", + f"quality_materials_{descriptor.quality.materials}", + "collision_explicit" if descriptor.collision_source == "explicit" else "collision_conservative", + "articulated" if descriptor.articulated else "static_rigid", + } + ) + tokens.update({"up_positive_z", "down_negative_z", "no_roll_pitch"}) + functional_front = orientation["functional_front"] + if orientation["visual_front"]: + tokens.add(f"visual_front_{_axis_tag(orientation['visual_front'])}") + if functional_front: + right = orientation["right"] + left = orientation["left"] + tokens.update( + { + f"functional_front_{_axis_tag(functional_front)}", + f"back_{_axis_tag(orientation['back'])}", + f"right_{_axis_tag(right)}", + f"left_{_axis_tag(left)}", + "orientation_directional_allowed", + "front_certified", + } + ) + elif orientation["direction_sensitive"]: + tokens.update({"orientation_directional_blocked", "front_uncertified"}) + elif orientation["directional_placement_policy"] == "rotationally_symmetric_no_front_required": + tokens.add("orientation_rotationally_symmetric") + else: + tokens.add("orientation_visual_optional") + for channel, enabled in descriptor.pbr_channels.model_dump().items(): + if enabled: + tokens.add(f"pbr_{channel}") + if height > max(width, depth) * 1.5: + tokens.add("spatial_tall") + if aspect > 2.0: + tokens.add("spatial_elongated") + values = descriptor.model_dump(mode="json") + values["semantic_tags"] = sorted(tokens) + values["synonyms"] = sorted(set([*descriptor.synonyms, descriptor.category, descriptor.subcategory])) + is_isaac_ready = ( + Path(descriptor.canonical_path).suffix.casefold() in {".usd", ".usda", ".usdc", ".usdz"} + and descriptor.collision_source == "explicit" + ) + if is_isaac_ready: + tokens.add("isaac_sim_compatible") + values["loader_compatibility"] = { + **descriptor.loader_compatibility, + "isaac_sim": "verified", + "pxr_usd": "verified", + } + else: + tokens.add("isaac_conversion_pending") + values["loader_compatibility"] = { + **descriptor.loader_compatibility, + "isaac_sim": "not_tested", + } + values["semantic_tags"] = sorted(tokens) + values["confidence"] = { + **descriptor.confidence, + "isaac_compatibility": 1.0 if is_isaac_ready else 0.0, + "rich_tags": 1.0, + } + return AssetDescriptor.model_validate(values) + + +def _read_descriptors(index: Path) -> list[AssetDescriptor]: + import sqlite3 + + connection = sqlite3.connect(f"file:{index.resolve()}?mode=ro", uri=True) + try: + return [AssetDescriptor.model_validate_json(row[0]) for row in connection.execute("select descriptor_json from asset_descriptors")] + finally: + connection.close() + + +def _release(plan: PreprocessPlan, output: Path, args: argparse.Namespace) -> dict[str, Any]: + failures = [item for item in plan.items if item.status != "ready"] + if failures and not args.allow_partial_release: + raise RuntimeError(f"release blocked: {len(failures)} assets are not ready") + records = _records(plan) + if not records: + raise RuntimeError("no ready assets to release") + catalog = output / "prepared_catalog.json" + atomic_write_text(catalog, AssetCatalog(source="full high-fidelity managed assets", assets=records).model_dump_json(indent=2) + "\n") + release_root = output / "descriptor_release" + if not release_root.exists(): + command = [ + args.release_python, + str(PROJECT_ROOT / "scripts/release_local_assets.py"), + str(catalog), + str(release_root), + "--scan-root", + str(output / "canonical"), + "--workers", + str(args.release_workers), + "--inspection-backend", + "process", + ] + if args.front_axis_overrides.is_file(): + command.extend(["--front-axis-overrides", str(args.front_axis_overrides)]) + _run(command) + new = _read_descriptors(release_root / "asset_descriptor_index.sqlite3") + current = _read_descriptors(args.base_index) + merged = {item.asset_id: item for item in current} + for item in new: + if item.status == "ACTIVE": + merged[item.asset_id] = item + descriptors = [_rich_tags(item) for item in merged.values()] + descriptors = _resolve_duplicates(descriptors) + descriptors.sort(key=lambda item: item.asset_id) + active = [item for item in descriptors if item.status == "ACTIVE"] + index_root = output / "active_index" + index_root.mkdir(parents=True, exist_ok=True) + _write_descriptor_index(descriptors, index_root / "asset_descriptor_index.sqlite3") + atomic_write_text( + index_root / "asset_descriptors.jsonl", + "".join(item.model_dump_json() + "\n" for item in descriptors), + ) + retrieval = [] + for item in active: + retrieval.append( + { + "asset_id": item.asset_id, + "display_name": item.display_name, + "category": item.category, + "subcategory": item.subcategory, + "dimensions_m": item.native_bbox_m, + "front_axis": item.front_axis, + "front_confidence": item.front_confidence, + "orientation": _orientation_contract(item), + "quality": item.quality.model_dump(mode="json"), + "tags": item.semantic_tags, + "synonyms": item.synonyms, + "isaac_usd": item.canonical_path, + } + ) + atomic_write_text(index_root / "rich_retrieval_documents.json", json.dumps(retrieval, ensure_ascii=False, indent=2) + "\n") + activation = output / "activate_runtime.env" + if not failures: + atomic_write_text( + activation, + "# Generated only after a complete high-fidelity release.\n" + f"export RHG_ASSET_INDEX={index_root / 'asset_descriptor_index.sqlite3'}\n" + f"export RHG_RICH_RETRIEVAL_DOCUMENTS={index_root / 'rich_retrieval_documents.json'}\n", + ) + return { + "descriptor_release": str(release_root), + "active_index": str(index_root / "asset_descriptor_index.sqlite3"), + "rich_retrieval_documents": str(index_root / "rich_retrieval_documents.json"), + "new_assets_ready": len(records), + "new_assets_failed": len(failures), + "merged_active_records": len(active), + "merged_descriptor_records": len(descriptors), + "activation_env": str(activation) if not failures else None, + } + + +def _arguments() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--asset-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--base-index", type=Path, required=True) + parser.add_argument("--stage", choices=("discover", "convert", "release", "all"), default="all") + parser.add_argument( + "--include-base-active", + action="store_true", + help="also convert every ACTIVE descriptor from --base-index into canonical USD", + ) + parser.add_argument("--sources", default="gso,polyhaven") + parser.add_argument("--limit", type=int) + parser.add_argument("--blender", required=True) + parser.add_argument("--usd-python", required=True) + parser.add_argument( + "--release-python", + help="Python with pxr, trimesh, Pillow and project dependencies; defaults to --usd-python", + ) + parser.add_argument("--blender-batch-size", type=int, default=24) + parser.add_argument("--usd-batch-size", type=int, default=128) + parser.add_argument("--extract-workers", type=int, default=8) + parser.add_argument("--release-workers", type=int, default=8) + parser.add_argument("--front-axis-overrides", type=Path, default=PROJECT_ROOT / "configs/assets/front_axis_overrides_v1.json") + parser.add_argument("--allow-partial-release", action="store_true") + return parser.parse_args() + + +def _migrate_plan(plan: PreprocessPlan) -> PreprocessPlan: + """Repair earlier canonical-path planning without touching completed source data.""" + for item in plan.items: + source = Path(item.source_path) + target = Path(item.canonical_path) + if item.source_kind == "base_usd" and target.suffix.casefold() != source.suffix.casefold(): + item.canonical_path = str(target.with_suffix(source.suffix.casefold())) + if item.status == "failed": + item.status, item.error = "pending", "" + elif item.status == "failed": + item.status, item.error = "pending", "" + return plan + + +def main() -> None: + args = _arguments() + selected_sources = set(args.sources.split(",")) + if not selected_sources <= {"gso", "polyhaven", "base"}: + raise ValueError("--sources accepts gso, polyhaven and/or base") + if args.include_base_active: + selected_sources.add("base") + args.sources = ",".join(sorted(selected_sources)) + if args.limit is not None and args.limit < 1: + raise ValueError("--limit must be positive") + if not args.blender_batch_size or not args.usd_batch_size or not args.release_workers: + raise ValueError("batch and worker counts must be positive") + if not args.blender or not Path(args.blender).is_file(): + raise FileNotFoundError(args.blender) + if not Path(args.usd_python).is_file(): + raise FileNotFoundError(args.usd_python) + args.release_python = args.release_python or args.usd_python + if not Path(args.release_python).is_file(): + raise FileNotFoundError(args.release_python) + if not args.base_index.is_file(): + raise FileNotFoundError(args.base_index) + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + plan_path, _catalog_path, report_path = _plan_paths(output) + started = time.perf_counter() + plan = ( + PreprocessPlan.model_validate_json(plan_path.read_text(encoding="utf-8")) + if plan_path.is_file() + else _discover( + args.asset_root.resolve(), + output, + base_index=args.base_index.resolve(), + include_base_active=args.include_base_active, + ) + ) + plan = _migrate_plan(plan) + if args.stage in {"discover", "all"}: + _write_plan(plan, plan_path) + if args.stage in {"convert", "all"}: + plan = _convert(plan, output, args, checkpoint_path=plan_path) + _write_plan(plan, plan_path) + release = _release(plan, output, args) if args.stage in {"release", "all"} else None + summary = { + "schema_version": "1.0", + "created_at": datetime.now(UTC).isoformat(), + "stage": args.stage, + "plan": str(plan_path), + "counts": dict(Counter(item.status for item in plan.items)), + "duration_s": round(time.perf_counter() - started, 3), + "release": release, + } + atomic_write_text(report_path, json.dumps(summary, ensure_ascii=False, indent=2) + "\n") + print(json.dumps(summary, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/docs/reproduction/public_conversion_code/scripts/seal_material_acceptance.py b/docs/reproduction/public_conversion_code/scripts/seal_material_acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..350e64ce203ffc4b55cd70390b606ffbfd22084d --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/seal_material_acceptance.py @@ -0,0 +1,119 @@ +"""Seal independent asset render/review evidence into an immutable material index.""" +import argparse +from concurrent.futures import ThreadPoolExecutor +from collections import Counter +import hashlib +import json +from pathlib import Path +import sys + +CODE = Path(__file__).resolve().parent / 'internal/scene_generation/real_assets' +sys.path.insert(0, str(CODE)) +from prepared_materials import fingerprint +from official_mdl_adapter import digest + + +def read(path): + return json.loads(Path(path).read_text()) + + +def seal(bench, out, allow_visual_adjudications=False): + out.mkdir(parents=True, exist_ok=False) + index = {'schema': 'rhg.accepted_material_index.v1', 'artifacts': {}, 'case_artifacts': {}, 'rejections': {}, + 'cases': [], 'acceptance_boundary': 'SDK-mapped graph/pixel preservation and independent image readability; not lossless MDL'} + def inspect_case(case): + directory = bench / 'results' / case['case_id'] + disposition = {'case_id': case['case_id'], 'scope': case.get('scope'), 'passed': False} + key = None + ref = None + try: + frozen = read(case['path']) + if digest(case['path']) != case['sha256']: + raise ValueError('Frozen asset case changed') + candidate = frozen['candidate'] + key = fingerprint({'source_sha256': candidate['asset_sha256'], + 'runtime_sha256': candidate.get('runtime_sha256') or candidate['asset_sha256'], + 'canonical_transform': [float(v) for v in candidate['canonical_transform']]}) + process = read(directory / 'process.json') + result = read(directory / 'render.json') + if result.get('case_sha256') != case['sha256'] or result.get('case_id') != case['case_id']: + raise ValueError('Rendered asset does not match the frozen case') + review_path = directory / 'appearance_review.json' + review = read(review_path) + if process['exit_code'] != 0 or result.get('passed') is not True: + raise ValueError('Asset execution failed') + if not result.get('gates', {}).get('library_graph_and_pixel_readback'): + raise ValueError('Library graph/pixel readback was not verified') + if len(result.get('images', [])) != 4: + raise ValueError('Four independent asset views required') + if review.get('render_sha256') != digest(directory / 'render.json'): + raise ValueError('Independent appearance review is pending or stale') + additional_evidence=[] + if review.get('passed') is not True: + if not allow_visual_adjudications: + raise ValueError('Independent appearance review failed') + adjudication=read(directory/'visual_adjudication.json') + if (adjudication.get('schema')!='rhg.independent_visual_adjudication.v1' + or adjudication.get('readability_passed') is not True + or adjudication.get('visible_missing_material_not_detected') is not True + or not adjudication.get('reviewer') or not adjudication.get('reason') + or adjudication.get('original_model_review_sha256')!=digest(review_path) + or adjudication.get('render_sha256')!=digest(directory/'render.json') + or adjudication.get('sheet_sha256')!=digest(directory/'appearance_sheet.jpg')): + raise ValueError('Visual adjudication is incomplete or stale') + additional_evidence=['visual_adjudication.json','appearance_sheet.jpg'] + disposition['accepted_after_visual_adjudication']=True + ref = dict(result['prepared_material_artifact']) + if digest(ref['path']) != ref['sha256']: + raise ValueError('Material library manifest changed') + manifest = read(ref['path']) + if fingerprint(manifest['identity']) != key: + raise ValueError('Material library belongs to another source/runtime/frame') + if digest(manifest['library_path']) != manifest['library_sha256']: + raise ValueError('Material library changed') + evidence = [{'path': str(directory / name), 'sha256': digest(directory / name)} + for name in ['process.json', 'render.json', 'appearance_review.json']+additional_evidence] + evidence.extend({'path': image['path'], 'sha256': image['sha256']} for image in result['images']) + if any(digest(entry['path']) != entry['sha256'] for entry in evidence): + raise ValueError('Asset evidence changed') + certificate = {'schema': 'rhg.material_asset_acceptance.v1', 'passed': True, + 'case_id': case['case_id'], 'manifest_sha256': ref['sha256'], + 'evidence': evidence, 'acceptance_boundary': index['acceptance_boundary'], + 'sealer_sha256': digest(__file__)} + path = out / (case['case_id'] + '.json') + path.write_text(json.dumps(certificate, indent=2)) + ref['acceptance'] = {'path': str(path), 'sha256': digest(path)} + disposition['passed'] = True + except (KeyError, ValueError, OSError) as error: + disposition['reason'] = str(error) + return disposition,key,ref + with ThreadPoolExecutor(max_workers=8) as pool: + # map preserves the frozen case order, including duplicate identities. + for disposition,key,ref in pool.map(inspect_case,read(bench/'manifest.json')['cases']): + if disposition['passed']: + index['case_artifacts'][disposition['case_id']]={'identity_key':key,'artifact':ref} + if key in index['artifacts'] and index['artifacts'][key]['sha256']!=ref['sha256']: + disposition['duplicate_source_identity']=True + else: + index['artifacts'][key]=ref + elif key: + index['rejections'].setdefault(key,[]).append(disposition.copy()) + index['cases'].append(disposition) + # A failed duplicate is never silently replaced by a passing attempt. + for key in index['rejections']: + index['artifacts'].pop(key, None) + index['case_artifacts']={case:record for case,record in index['case_artifacts'].items() + if record['identity_key'] not in index['rejections']} + index['counts'] = dict(Counter('accepted' if case['passed'] else 'failed_or_pending' for case in index['cases'])) + index['counts']['accepted_after_visual_adjudication']=sum(case.get('passed') and case.get('accepted_after_visual_adjudication',False) for case in index['cases']) + (out / 'index.json').write_text(json.dumps(index, indent=2)) + print(json.dumps(index['counts'])) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bench', type=Path, required=True) + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--allow-visual-adjudications',action='store_true',help='Accept separately documented, hash-bound visual adjudications while preserving model rejections') + args = parser.parse_args() + seal(args.bench, args.out, args.allow_visual_adjudications) diff --git a/docs/reproduction/public_conversion_code/scripts/setup_mdl_sdk.py b/docs/reproduction/public_conversion_code/scripts/setup_mdl_sdk.py new file mode 100644 index 0000000000000000000000000000000000000000..d7b97d0b8f70b094e0f9736d71ecb418514a6354 --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/setup_mdl_sdk.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Install the pinned official MDL SDK on a remote Linux x86-64 worker.""" +import argparse +import hashlib +import json +from pathlib import Path +import platform +import subprocess +import tarfile +import tempfile +import urllib.request + +VERSION='2026.0.2' +NAME='MDL-SDK-2026.0.2-391700.2276-linux-x86-64' +SHA256='5aa37997647c757d27a0c16d467d5f3f26244a2303e697d4eabf0e3719b8dc19' +URL=f'https://github.com/NVIDIA/MDL-SDK/releases/download/{VERSION}/{NAME}.tgz' + + +def sha(path): + h=hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda:stream.read(8<<20),b''):h.update(block) + return h.hexdigest() + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--install-root',type=Path,required=True) + p.add_argument('--worker-python',type=Path,required=True,help='Existing CPython 3.10 executable matching the SDK binding ABI') + p.add_argument('--archive',type=Path,help='Reuse a remotely stored official archive') + args=p.parse_args() + if platform.system()!='Linux' or platform.machine() not in {'x86_64','AMD64'}: + raise SystemExit('This pinned SDK package targets Linux x86-64. Run setup on the rendering server.') + version=subprocess.check_output([str(args.worker_python),'-c','import sys; print("%s.%s"%sys.version_info[:2])'],text=True).strip() + if version!='3.10':raise SystemExit('The official Python binding requires CPython 3.10.') + target=args.install_root.resolve() + if target.exists():raise SystemExit('Installation target already exists; choose a new versioned directory.') + target.parent.mkdir(parents=True,exist_ok=True) + archive=args.archive or target.parent/(NAME+'.tgz') + if not archive.exists(): + partial=archive.with_suffix(archive.suffix+'.partial') + if partial.exists():raise SystemExit('A partial download is retained at '+str(partial)+'. Use a new archive path or resume it explicitly.') + with urllib.request.urlopen(URL,timeout=120) as response,partial.open('xb') as stream: + while block:=response.read(8<<20):stream.write(block) + partial.rename(archive) + if sha(archive)!=SHA256:raise SystemExit('Official SDK archive checksum mismatch; file retained for diagnosis.') + staging=Path(tempfile.mkdtemp(prefix='mdl-sdk-install-',dir=target.parent)) + with tarfile.open(archive) as bundle: + for member in bundle.getmembers(): + destination=(staging/member.name).resolve() + if not destination.is_relative_to(staging):raise ValueError('Unsafe SDK archive path') + if member.issym() or member.islnk(): + link=(destination.parent/member.linkname).resolve() if member.issym() else (staging/member.linkname).resolve() + if not link.is_relative_to(staging):raise ValueError('SDK archive link leaves installation directory') + bundle.extractall(staging) + (staging/NAME).rename(target) + receipt={'sdk_version':VERSION,'source_url':URL,'archive_sha256':SHA256, + 'sdk_root':str(target),'worker_python':str(args.worker_python.absolute()),'worker_python_version':version, + 'binary_sha256':{str(p.relative_to(target)):sha(p) for p in (target/'lib').glob('*.so')}} + (target/'rhg_sdk_installation.json').write_text(json.dumps(receipt,indent=2)+'\n') + print(json.dumps({'mdl_backend':'official_sdk','mdl_sdk_root':str(target), + 'mdl_sdk_python':str(args.worker_python.absolute()),'mdl_bake_resolution':1024},indent=2)) + + +if __name__=='__main__':main() diff --git a/docs/reproduction/public_conversion_code/scripts/validate_material_assets.py b/docs/reproduction/public_conversion_code/scripts/validate_material_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..1e13aa56e245858abd5888bf8e9d175c584a2ced --- /dev/null +++ b/docs/reproduction/public_conversion_code/scripts/validate_material_assets.py @@ -0,0 +1,135 @@ +"""Render prepared MDL assets independently before sealing a source pool.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import random +import signal +import socket +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT / 'internal/scene_generation/real_assets')) +from stable_pipeline import child_environment + + +def read(path): + return json.loads(Path(path).read_text()) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def initialize(args): + args.out.mkdir(parents=True, exist_ok=False) + for name in ('cases', 'results'): + (args.out / name).mkdir() + config = read(args.pool / 'configuration.json') + cases, dispositions = [], [] + for task in sorted((args.pool / 'tasks').glob('*.json')): + work = args.pool / 'results' / task.stem + receipt = read(work / 'receipt.json') + assert receipt['task_sha256'] == digest(task) + prepared = {row['pool_candidate_key']: row for row in read(work / 'qualified_candidates.json')} if (work / 'qualified_candidates.json').exists() else {} + geometry = read(work / 'source_geometry_probe.json')['lookup'] if prepared else {} + for record in receipt['records']: + status = dict(record) + candidate = prepared.get(record['candidate_key']) + if candidate is None: + status['material_validation'] = 'source_preparation_failed' + elif args.runtime_changes_only and not candidate.get('runtime_release_selection'): + status['material_validation'] = 'unchanged_runtime_requires_existing_asset_acceptance' + else: + geo = geometry[candidate['source_geometry_probe_key']] + if not geo.get('source_material_compatibility', {}).get('translated_materials') and not candidate.get('runtime_release_selection'): + status['material_validation'] = 'native_importer_graph_preserved' + else: + if geo.get('prepared_material_artifact'): + candidate['prepared_material_artifact'] = geo['prepared_material_artifact'] + candidate.update(uniform_scale=1, yaw_deg=0, center_xy_m=[0, 0], base_z_m=0, + source_dimensions_m=candidate['dimensions_m']) + case_id = record['candidate_key'] + case = {'case_id': case_id, 'asset_id': candidate['asset_id'], 'candidate': candidate, + 'condition': config['mdl_backend'] + '_prepared_library', 'identity_issues': []} + path = args.out / 'cases' / (case_id + '.json') + path.write_text(json.dumps(case, indent=2)) + cases.append({'case_id': case_id, 'asset_id': candidate['asset_id'], + 'path': str(path), 'sha256': digest(path), 'scope': 'prepared_translated_materials'}) + status['material_validation'] = 'scheduled_independent_asset_views' + dispositions.append(status) + (args.out / 'manifest.json').write_text(json.dumps({'schema': 'rhg.offline_material_validation.v1', + 'pool': str(args.pool), 'pool_manifest_sha256': digest(args.pool / 'manifest.json'), + 'configuration': config, 'cases': cases, 'fixed_case_count': len(cases), + 'original_pool_candidate_count': len(dispositions), 'dispositions': dispositions, + 'runtime_changes_only': args.runtime_changes_only, + 'render_settings': {'samples': 12, 'width': 384, 'height': 384, 'views': 4}}, indent=2)) + print(json.dumps({'original_candidates': len(dispositions), 'material_validation_cases': len(cases)})) + + +def worker(args): + manifest = read(args.out / 'manifest.json') + config = manifest['configuration'] + config['gpu'] = args.gpu + env = child_environment(config, args.out / 'worker_runtime' / (socket.gethostname() + '_' + str(os.getpid()))) + env.update(RHG_MATERIAL_PHASE='offline_prepare', RHG_BENCH_DEVICE=args.device, + RHG_PREPARED_MATERIAL_ROOT=str(args.out / 'material_libraries')) + if args.device == 'CPU': + env['CUDA_VISIBLE_DEVICES'] = '' + cases = list(manifest['cases']) + random.Random(socket.gethostname() + str(os.getpid())).shuffle(cases) + for case in cases: + if args.device == 'GPU': + for _ in range(6): + used = int(subprocess.check_output(['nvidia-smi', '-i', args.gpu, '--query-gpu=memory.used', + '--format=csv,noheader,nounits'], text=True, timeout=10).strip()) + if used < 256: + break + time.sleep(2) + if used >= 256: + print(json.dumps({'status': 'resource_deferred', 'gpu': args.gpu, 'used_MiB': used}), flush=True) + break + out = args.out / 'results' / case['case_id'] + out.mkdir(exist_ok=True) + try: + with (out / 'claim.json').open('x') as stream: + json.dump({'pid': os.getpid(), 'host': socket.gethostname(), 'gpu': args.gpu}, stream) + except FileExistsError: + continue + start = time.time() + command = [config['blender'], '--factory-startup', '--background', '--threads', '4', + '--python-exit-code', '1', '--python', str(ROOT / 'validate_material_asset.py'), '--', case['path']] + reason = None + with (out / 'render.log').open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=env, start_new_session=True) + try: + process.wait(timeout=1200) + except subprocess.TimeoutExpired: + reason = 'asset_execution_timeout' + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + receipt = {'case_id': case['case_id'], 'host': socket.gethostname(), 'gpu': args.gpu, + 'device': args.device, 'exit_code': process.returncode, 'reason': reason, + 'elapsed_s': time.time() - start, 'command': command} + (out / 'process.json').write_text(json.dumps(receipt, indent=2)) + print(json.dumps(receipt), flush=True) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('mode', choices=['init', 'worker']) + parser.add_argument('--pool', type=Path) + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--gpu', default='0') + parser.add_argument('--device', choices=['CPU', 'GPU'], default='GPU') + parser.add_argument('--runtime-changes-only', action='store_true', + help='Validate changed runtimes; unchanged material libraries still require their existing acceptance index at finalization') + args = parser.parse_args() + {'init': initialize, 'worker': worker}[args.mode](args) diff --git a/docs/reproduction/public_download_control/conversion-source-manifest.json b/docs/reproduction/public_download_control/conversion-source-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..d689231fe3faa8f8af0c3015ed0dc97cba697ba3 --- /dev/null +++ b/docs/reproduction/public_download_control/conversion-source-manifest.json @@ -0,0 +1,1613 @@ +{ + "schema": "rphome.public_asset_download.v1", + "host": "H20-96-4", + "root": "/data/RPHomeGen/public_assets_20261115", + "jobs": [ + { + "name": "polyhaven_models", + "kind": "direct", + "destination": "assets/polyhaven", + "conversion": "Original USD and texture dependencies; validate runtime import and proxy/baking separately.", + "files": [ + { + "relative_path": "wooden_table_02/wooden_table_02_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/wooden_table_02/wooden_table_02_2k.usdc", + "md5": "907a9d8fa292c8217afedb88641fe44d", + "size": 16081 + }, + { + "relative_path": "wooden_table_02/textures/wooden_table_02_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_table_02/wooden_table_02_metal_2k.exr", + "md5": "b03fd78d6179d5408bc5f6b6fbd6136c", + "size": 13296 + }, + { + "relative_path": "wooden_table_02/textures/wooden_table_02_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/wooden_table_02/wooden_table_02_diff_2k.jpg", + "md5": "2a346503ce15e4df59c0fd4ed1891047", + "size": 711929 + }, + { + "relative_path": "wooden_table_02/textures/wooden_table_02_rough_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/wooden_table_02/wooden_table_02_rough_2k.jpg", + "md5": "50647bce6cdbba9eed1d7f7fab403d01", + "size": 785964 + }, + { + "relative_path": "wooden_table_02/textures/wooden_table_02_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_table_02/wooden_table_02_nor_gl_2k.exr", + "md5": "88b2bc4f3d04100599722aaa3b1dad4b", + "size": 5041006 + }, + { + "relative_path": "wooden_table_02/textures/wooden_table_02_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_table_02/wooden_table_02_rough_2k.exr", + "md5": "b7f4da4d166c8ef198024cd16f14c885", + "size": 4459865 + }, + { + "relative_path": "round_wooden_table_01/round_wooden_table_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/round_wooden_table_01/round_wooden_table_01_2k.usdc", + "md5": "a66fb562cc40822e889d01ba954986c7", + "size": 440189 + }, + { + "relative_path": "round_wooden_table_01/textures/round_wooden_table_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/round_wooden_table_01/round_wooden_table_01_nor_gl_2k.exr", + "md5": "caeed11cd98f080e8190997ccf8b6033", + "size": 2094023 + }, + { + "relative_path": "round_wooden_table_01/textures/round_wooden_table_01_rough_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/round_wooden_table_01/round_wooden_table_01_rough_2k.jpg", + "md5": "831116c55269c7ca2a3f782403b39749", + "size": 362172 + }, + { + "relative_path": "round_wooden_table_01/textures/round_wooden_table_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/round_wooden_table_01/round_wooden_table_01_diff_2k.jpg", + "md5": "5a3ff753c828e773cc02fb48d1857365", + "size": 435742 + }, + { + "relative_path": "round_wooden_table_01/textures/round_wooden_table_01_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/round_wooden_table_01/round_wooden_table_01_metal_2k.exr", + "md5": "cf7ee3231a3538e3f96095fc9530d656", + "size": 45179 + }, + { + "relative_path": "round_wooden_table_01/textures/round_wooden_table_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/round_wooden_table_01/round_wooden_table_01_rough_2k.exr", + "md5": "c67eba533cb12f327b7790dae1cce9f8", + "size": 3490992 + }, + { + "relative_path": "modern_arm_chair_01/modern_arm_chair_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/modern_arm_chair_01/modern_arm_chair_01_2k.usdc", + "md5": "fb8cf8e078d94d7f3e05a6da6a32d7d9", + "size": 434468 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_legs_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_legs_rough_2k.png", + "md5": "18c94c599e209be684a572581efaa534", + "size": 3497673 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_pillow_metal_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_pillow_metal_2k.png", + "md5": "d1b4236811cde253fe1d58c79386c101", + "size": 8264 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_pillow_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_pillow_nor_gl_2k.png", + "md5": "158e18aeb04dae4dc3f9cbb1fa149512", + "size": 7433277 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_legs_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_legs_diff_2k.png", + "md5": "9e31c85b0d6f0ead7d6db4e99e41f3a3", + "size": 10153780 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_legs_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_legs_nor_gl_2k.png", + "md5": "eccc4bcdcf0e8dacd87369b29ec4db17", + "size": 10611050 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_pillow_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_pillow_rough_2k.png", + "md5": "c254dfbdead5e52eb744b6600bc05922", + "size": 2512880 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_pillow_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_pillow_diff_2k.png", + "md5": "934bd83b139fb59a799f077c7f89509f", + "size": 6961371 + }, + { + "relative_path": "modern_arm_chair_01/textures/modern_arm_chair_01_legs_metal_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/modern_arm_chair_01/modern_arm_chair_01_legs_metal_2k.png", + "md5": "d1b4236811cde253fe1d58c79386c101", + "size": 8264 + }, + { + "relative_path": "sofa_02/sofa_02_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/sofa_02/sofa_02_2k.usdc", + "md5": "ec2abe543e6a665ddf1f12f9b6024cbc", + "size": 189532 + }, + { + "relative_path": "sofa_02/textures/sofa_02_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/sofa_02/sofa_02_nor_gl_2k.exr", + "md5": "c803f44b48c70780d53dc84ad7eb9a48", + "size": 4916874 + }, + { + "relative_path": "sofa_02/textures/sofa_02_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/sofa_02/sofa_02_diff_2k.jpg", + "md5": "37808357cc7d00fd62bda197cf89e6ae", + "size": 323319 + }, + { + "relative_path": "sofa_02/textures/sofa_02_roughness_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/sofa_02/sofa_02_roughness_2k.jpg", + "md5": "1f8b1f14c6309a419e3a9ad6a50f4b58", + "size": 405582 + }, + { + "relative_path": "sofa_02/textures/sofa_02_metallic_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/sofa_02/sofa_02_metallic_2k.exr", + "md5": "6ba70e5f38cbc934581ca7583721446b", + "size": 13296 + }, + { + "relative_path": "sofa_02/textures/sofa_02_roughness_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/sofa_02/sofa_02_roughness_2k.exr", + "md5": "f0e338aa452021f55550389e19f8239e", + "size": 2952734 + }, + { + "relative_path": "steel_frame_shelves_01/steel_frame_shelves_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/steel_frame_shelves_01/steel_frame_shelves_01_2k.usdc", + "md5": "aad68c5ab05fd96a31a5cbde99b9a3fc", + "size": 220975 + }, + { + "relative_path": "steel_frame_shelves_01/textures/steel_frame_shelves_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/steel_frame_shelves_01/steel_frame_shelves_01_nor_gl_2k.exr", + "md5": "374244add253805ce6184847312cf1e9", + "size": 3043577 + }, + { + "relative_path": "steel_frame_shelves_01/textures/steel_frame_shelves_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/steel_frame_shelves_01/steel_frame_shelves_01_diff_2k.jpg", + "md5": "fe1269a8e9cdbe3bd7359269c5f56510", + "size": 1679686 + }, + { + "relative_path": "steel_frame_shelves_01/textures/steel_frame_shelves_01_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/steel_frame_shelves_01/steel_frame_shelves_01_metal_2k.exr", + "md5": "7f8f31df9ad25f8994ae990b18dedece", + "size": 452320 + }, + { + "relative_path": "steel_frame_shelves_01/textures/steel_frame_shelves_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/steel_frame_shelves_01/steel_frame_shelves_01_rough_2k.exr", + "md5": "f0414e0170bfb708789ed68ad497691d", + "size": 2892710 + }, + { + "relative_path": "modern_wooden_cabinet/modern_wooden_cabinet_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/modern_wooden_cabinet/modern_wooden_cabinet_2k.usdc", + "md5": "a570735a1b503e56f4f2ccd3b77401be", + "size": 1239196 + }, + { + "relative_path": "modern_wooden_cabinet/textures/modern_wooden_cabinet_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/modern_wooden_cabinet/modern_wooden_cabinet_rough_2k.exr", + "md5": "e3b373e8be83d79695995b4d170d80fa", + "size": 3942111 + }, + { + "relative_path": "modern_wooden_cabinet/textures/modern_wooden_cabinet_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/modern_wooden_cabinet/modern_wooden_cabinet_diff_2k.jpg", + "md5": "56ff732ed0f359711f87b27bffbb1146", + "size": 2750362 + }, + { + "relative_path": "modern_wooden_cabinet/textures/modern_wooden_cabinet_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/modern_wooden_cabinet/modern_wooden_cabinet_nor_gl_2k.exr", + "md5": "e5e5383ef159ce0d59d253526f49be06", + "size": 4778298 + }, + { + "relative_path": "CoffeeCart_01/CoffeeCart_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/CoffeeCart_01/CoffeeCart_01_2k.usdc", + "md5": "e1980572947b4bca4b4d81b898d1fb7d", + "size": 1879642 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_props_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_props_diff_2k.png", + "md5": "25d04f5a376723437ecf18d8fdc0b32e", + "size": 3640662 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_props_roughness_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_props_roughness_2k.png", + "md5": "c3aa60660cb2af558cc95a7f81a1db0a", + "size": 1777048 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_cart_metallic_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_cart_metallic_2k.png", + "md5": "9ad907f77165f1db6debcddde95d1f58", + "size": 23863 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_cart_roughness_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_cart_roughness_2k.png", + "md5": "bed7ccc98016162a18bed77aef0d4284", + "size": 1589520 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_props_metallic_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_props_metallic_2k.png", + "md5": "be88156c114554720a8e5112a77ca985", + "size": 167563 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_cart_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_cart_diff_2k.png", + "md5": "c6f1d4fca5bf38a90d78bd46884a2ed8", + "size": 3509441 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_props_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_props_nor_gl_2k.png", + "md5": "3bc0847b4c4e7cd41ac4ebe59294ae7b", + "size": 1799442 + }, + { + "relative_path": "CoffeeCart_01/textures/CoffeeCart_01_cart_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/CoffeeCart_01/CoffeeCart_01_cart_nor_gl_2k.png", + "md5": "ff07fa070c17115c0859fe822bae6b28", + "size": 1267498 + }, + { + "relative_path": "cardboard_box_01/cardboard_box_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/cardboard_box_01/cardboard_box_01_2k.usdc", + "md5": "61df40585f64ad87a4af0d3db11b909f", + "size": 843513 + }, + { + "relative_path": "cardboard_box_01/textures/cardboard_box_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/cardboard_box_01/cardboard_box_01_diff_2k.jpg", + "md5": "40a2ca17b3a7fb225798fe4d88868417", + "size": 1987615 + }, + { + "relative_path": "cardboard_box_01/textures/cardboard_box_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/cardboard_box_01/cardboard_box_01_rough_2k.exr", + "md5": "94d5af70ad42dbdf382d052583f98479", + "size": 2076621 + }, + { + "relative_path": "cardboard_box_01/textures/cardboard_box_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/cardboard_box_01/cardboard_box_01_nor_gl_2k.exr", + "md5": "cc8628c74ef7eeca1c284fb14ecf379c", + "size": 6552207 + }, + { + "relative_path": "wicker_basket_01/wicker_basket_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/wicker_basket_01/wicker_basket_01_2k.usdc", + "md5": "83e6cd54cf13cbd034c930f31cf5438b", + "size": 1047702 + }, + { + "relative_path": "wicker_basket_01/textures/wicker_basket_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wicker_basket_01/wicker_basket_01_rough_2k.exr", + "md5": "3c323691c00420985c5b843ca663b46d", + "size": 3582232 + }, + { + "relative_path": "wicker_basket_01/textures/wicker_basket_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/wicker_basket_01/wicker_basket_01_diff_2k.jpg", + "md5": "b5fa48725aabd3ae05b4be3091e3ac40", + "size": 2606521 + }, + { + "relative_path": "wicker_basket_01/textures/wicker_basket_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wicker_basket_01/wicker_basket_01_nor_gl_2k.exr", + "md5": "ffb58a23400572d01c1c07f2584431f4", + "size": 5092175 + }, + { + "relative_path": "wine_bottles_01/wine_bottles_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/wine_bottles_01/wine_bottles_01_2k.usdc", + "md5": "af4bde287c5c71e622eb41b00ba0515f", + "size": 1452675 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_clearwater_crystals_01_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_clearwater_crystals_01_rough_2k.png", + "md5": "8cfb33305f23bcdc4449945190a7fe59", + "size": 265209 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_clearwater_crystals_01_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_clearwater_crystals_01_diff_2k.png", + "md5": "f44750382e61276b6b8e046d9385db6b", + "size": 260056 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_02_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_02_rough_2k.png", + "md5": "47e619bd62726c22fc9ac34a6218a787", + "size": 1002243 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_paper_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_paper_nor_gl_2k.png", + "md5": "6a91647360c91f7159a397a6f81297cf", + "size": 23343724 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wine_bottles_01/wine_bottles_01_nor_gl_2k.exr", + "md5": "9d20630955e88d408d8dea073d064daf", + "size": 1364652 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wine_bottles_01/wine_bottles_01_rough_2k.exr", + "md5": "edc870014313828d9ce9ac91a04f6582", + "size": 3546757 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_02_alpha_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_02_alpha_2k.png", + "md5": "61adc70ae255ce7a64999111de26ad82", + "size": 16503 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_clearwater_crystals_01_alpha_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_clearwater_crystals_01_alpha_2k.png", + "md5": "f18359ab927e6a6f82b26774be0c0e39", + "size": 48442 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_clearwater_crystals_01_metal_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_clearwater_crystals_01_metal_2k.png", + "md5": "3abc56ae6dcd0cdacad68c41609126f8", + "size": 214152 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_01_alpha_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_01_alpha_2k.png", + "md5": "a1027d9fe8f5ab329838d059b7fcbae7", + "size": 31069 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_alpha_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_alpha_2k.png", + "md5": "d8aa2d76ec75b1335aeb7447f15b06c6", + "size": 14417 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/wine_bottles_01/wine_bottles_01_diff_2k.jpg", + "md5": "ab062aa3837a897cd1ccbdaadf8c9b37", + "size": 351644 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_intertwine_01_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_intertwine_01_rough_2k.png", + "md5": "3ba04cfafea9b9a9f3134f01a9888734", + "size": 191248 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_02_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_02_diff_2k.png", + "md5": "c85f263f2f12c868b069685095016d13", + "size": 1383740 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_01_metal_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_01_metal_2k.png", + "md5": "912d8e912ae2d47d17778638420c5807", + "size": 512745 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_02_metal_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_02_metal_2k.png", + "md5": "dd77ad78d1db6d554ddbd9bf20e727c9", + "size": 812103 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_01_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_01_diff_2k.png", + "md5": "9c078d09ac2d4a3bb267a74215bd9436", + "size": 938194 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wine_bottles_01/wine_bottles_01_metal_2k.exr", + "md5": "4dd7af67979cc24627304b1da22ac3ad", + "size": 31217 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_intertwine_01_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_intertwine_01_diff_2k.png", + "md5": "c3cc011e546d248f4d90df5b1479064f", + "size": 367307 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_ftero_vinea_01_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_ftero_vinea_01_rough_2k.png", + "md5": "f35b04c7c4f03751b627374c95e019de", + "size": 771290 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_intertwine_01_metal_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_intertwine_01_metal_2k.png", + "md5": "ac018ef2773b5fbf7ad1ceda8b809c51", + "size": 102118 + }, + { + "relative_path": "wine_bottles_01/textures/wine_bottles_01_label_intertwine_01_alpha_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/wine_bottles_01/wine_bottles_01_label_intertwine_01_alpha_2k.png", + "md5": "ff91c0308894454093b4d53c4e533a5d", + "size": 139169 + }, + { + "relative_path": "wooden_stool_02/wooden_stool_02_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/wooden_stool_02/wooden_stool_02_2k.usdc", + "md5": "4a6c816aa62537d54d70d25d266c820b", + "size": 538286 + }, + { + "relative_path": "wooden_stool_02/textures/wooden_stool_02_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_stool_02/wooden_stool_02_nor_gl_2k.exr", + "md5": "eb641857685a21e0e5a7e6462e9560b4", + "size": 7826420 + }, + { + "relative_path": "wooden_stool_02/textures/wooden_stool_02_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/wooden_stool_02/wooden_stool_02_diff_2k.jpg", + "md5": "5cec478bd65892ba3e54c71f15bbf004", + "size": 3208072 + }, + { + "relative_path": "wooden_stool_02/textures/wooden_stool_02_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_stool_02/wooden_stool_02_rough_2k.exr", + "md5": "9331b9dda36a83ed985a06cf110a7d82", + "size": 2512650 + }, + { + "relative_path": "wooden_crate_01/wooden_crate_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/wooden_crate_01/wooden_crate_01_2k.usdc", + "md5": "6b533b972d4f8c7eec7e48297113ed2f", + "size": 326282 + }, + { + "relative_path": "wooden_crate_01/textures/wooden_crate_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_crate_01/wooden_crate_01_nor_gl_2k.exr", + "md5": "ef1a1e8150768ff37de217f07188ed2b", + "size": 6069816 + }, + { + "relative_path": "wooden_crate_01/textures/wooden_crate_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/wooden_crate_01/wooden_crate_01_diff_2k.jpg", + "md5": "d4e0552359a0e8fddcb15827f9781cef", + "size": 2728494 + }, + { + "relative_path": "wooden_crate_01/textures/wooden_crate_01_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_crate_01/wooden_crate_01_metal_2k.exr", + "md5": "466c3d2aae9f908e12709edc43acbb30", + "size": 122318 + }, + { + "relative_path": "wooden_crate_01/textures/wooden_crate_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/wooden_crate_01/wooden_crate_01_rough_2k.exr", + "md5": "e6c9082c683c2fe9ead18527d22f071c", + "size": 2453665 + }, + { + "relative_path": "coffee_table_round_01/coffee_table_round_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/coffee_table_round_01/coffee_table_round_01_2k.usdc", + "md5": "43d4d1554d89393518a29e79552bf1de", + "size": 207133 + }, + { + "relative_path": "coffee_table_round_01/textures/coffee_table_round_01_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/coffee_table_round_01/coffee_table_round_01_metal_2k.exr", + "md5": "c48536d86d5e16cbe67c8c01a1c3299e", + "size": 678338 + }, + { + "relative_path": "coffee_table_round_01/textures/coffee_table_round_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/coffee_table_round_01/coffee_table_round_01_rough_2k.exr", + "md5": "e95c9de144eb674afb092a434afda96e", + "size": 4344859 + }, + { + "relative_path": "coffee_table_round_01/textures/coffee_table_round_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/coffee_table_round_01/coffee_table_round_01_nor_gl_2k.exr", + "md5": "930782e9c0a46365c4005731a4003010", + "size": 2835617 + }, + { + "relative_path": "coffee_table_round_01/textures/coffee_table_round_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/coffee_table_round_01/coffee_table_round_01_diff_2k.jpg", + "md5": "d4333b0c534f7bce97dead1bd9667efd", + "size": 1721075 + }, + { + "relative_path": "dining_chair_02/dining_chair_02_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/dining_chair_02/dining_chair_02_2k.usdc", + "md5": "1f8bb9e1007be57a5d1fd8b2b308020a", + "size": 1578004 + }, + { + "relative_path": "dining_chair_02/textures/dining_chair_02_rough_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/dining_chair_02/dining_chair_02_rough_2k.jpg", + "md5": "0bd4578133e1e0493706422f19c3aa94", + "size": 615889 + }, + { + "relative_path": "dining_chair_02/textures/dining_chair_02_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/dining_chair_02/dining_chair_02_diff_2k.jpg", + "md5": "be041803606b5bf7869f08ab58a1581f", + "size": 332586 + }, + { + "relative_path": "dining_chair_02/textures/dining_chair_02_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/dining_chair_02/dining_chair_02_metal_2k.exr", + "md5": "1463eb9adcff1ace0d4bf3e124df5500", + "size": 21649 + }, + { + "relative_path": "dining_chair_02/textures/dining_chair_02_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/dining_chair_02/dining_chair_02_nor_gl_2k.exr", + "md5": "e3151409207335aa92c19146994b2c53", + "size": 5235765 + }, + { + "relative_path": "dining_chair_02/textures/dining_chair_02_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/dining_chair_02/dining_chair_02_rough_2k.exr", + "md5": "98aba2001b5dae6ea415d50ea3a02fda", + "size": 3146072 + }, + { + "relative_path": "dining_table/dining_table_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/dining_table/dining_table_2k.usdc", + "md5": "cc33c595e54e970377d050c7b0583d12", + "size": 64334 + }, + { + "relative_path": "dining_table/textures/dining_table_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/dining_table/dining_table_diff_2k.jpg", + "md5": "dbe81f446c425edceafc4dd09f81cb8a", + "size": 3345927 + }, + { + "relative_path": "dining_table/textures/dining_table_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/dining_table/dining_table_nor_gl_2k.exr", + "md5": "5484e6b4219c4eaca30720f2fce96655", + "size": 7281319 + }, + { + "relative_path": "dining_table/textures/dining_table_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/dining_table/dining_table_rough_2k.exr", + "md5": "d588b522653314d9271e7af91d0ce72d", + "size": 2028469 + }, + { + "relative_path": "drawer_cabinet/drawer_cabinet_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/drawer_cabinet/drawer_cabinet_2k.usdc", + "md5": "2b93573f527cb585ef28048a5c4ebbcf", + "size": 1227991 + }, + { + "relative_path": "drawer_cabinet/textures/drawer_cabinet_metallic_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/drawer_cabinet/drawer_cabinet_metallic_2k.exr", + "md5": "a6619c101153f2bfe0e86126696b00ce", + "size": 27066 + }, + { + "relative_path": "drawer_cabinet/textures/drawer_cabinet_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/drawer_cabinet/drawer_cabinet_nor_gl_2k.exr", + "md5": "ad39960a25913609ed1519d7e2f2f872", + "size": 3263324 + }, + { + "relative_path": "drawer_cabinet/textures/drawer_cabinet_roughness_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/drawer_cabinet/drawer_cabinet_roughness_2k.jpg", + "md5": "f7ce6e7703fcd1886486fccd77577588", + "size": 309038 + }, + { + "relative_path": "drawer_cabinet/textures/drawer_cabinet_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/drawer_cabinet/drawer_cabinet_diff_2k.jpg", + "md5": "ecf30786b237f49412c4026e9d9eb7bd", + "size": 541585 + }, + { + "relative_path": "drawer_cabinet/textures/drawer_cabinet_roughness_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/drawer_cabinet/drawer_cabinet_roughness_2k.exr", + "md5": "9f482e7350f25d41cac6ae840b2dad6f", + "size": 1657706 + }, + { + "relative_path": "GothicBed_01/GothicBed_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/GothicBed_01/GothicBed_01_2k.usdc", + "md5": "fff4e67d1c313f5d1c12ce21715f60e1", + "size": 1309515 + }, + { + "relative_path": "GothicBed_01/textures/GothicBed_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/GothicBed_01/GothicBed_01_nor_gl_2k.exr", + "md5": "e53eed02e0d500124b1c9c38e5a27a5b", + "size": 4301585 + }, + { + "relative_path": "GothicBed_01/textures/GothicBed_01_metallic_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/GothicBed_01/GothicBed_01_metallic_2k.exr", + "md5": "45450f04bb5367d1226b2e67b4aadec4", + "size": 13296 + }, + { + "relative_path": "GothicBed_01/textures/GothicBed_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/GothicBed_01/GothicBed_01_diff_2k.jpg", + "md5": "5673f5209402253ff82b3657b2f3923b", + "size": 385789 + }, + { + "relative_path": "GothicBed_01/textures/GothicBed_01_roughness_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/GothicBed_01/GothicBed_01_roughness_2k.jpg", + "md5": "0c3e452643f883f3b45e8e4c09b24d9a", + "size": 388393 + }, + { + "relative_path": "GothicBed_01/textures/GothicBed_01_roughness_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/GothicBed_01/GothicBed_01_roughness_2k.exr", + "md5": "5702c99737c87d04651c06bdba8204ab", + "size": 2753233 + }, + { + "relative_path": "Shelf_01/Shelf_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/Shelf_01/Shelf_01_2k.usdc", + "md5": "79728fad4992a8ea33ac29354156c3a7", + "size": 15471 + }, + { + "relative_path": "Shelf_01/textures/Shelf_01_roughness_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/Shelf_01/Shelf_01_roughness_2k.jpg", + "md5": "3a9c11fe4a300c07b7452bdb86555d1e", + "size": 903768 + }, + { + "relative_path": "Shelf_01/textures/Shelf_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/Shelf_01/Shelf_01_nor_gl_2k.exr", + "md5": "adb3557bcb477fa73780f943a9ac7420", + "size": 8466827 + }, + { + "relative_path": "Shelf_01/textures/Shelf_01_metallic_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/Shelf_01/Shelf_01_metallic_2k.exr", + "md5": "3d165716bf628fb3aef868967f1d8e34", + "size": 13296 + }, + { + "relative_path": "Shelf_01/textures/Shelf_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/Shelf_01/Shelf_01_diff_2k.jpg", + "md5": "0dec8a0fb92a5a45b3f8d15694ab3520", + "size": 569169 + }, + { + "relative_path": "Shelf_01/textures/Shelf_01_roughness_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/Shelf_01/Shelf_01_roughness_2k.exr", + "md5": "8a36f300df854c8643a13b7c07404152", + "size": 4216725 + }, + { + "relative_path": "desk_lamp_arm_01/desk_lamp_arm_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/desk_lamp_arm_01/desk_lamp_arm_01_2k.usdc", + "md5": "b2c4a1bba7b88c2bbc98a3cee751d02a", + "size": 1393563 + }, + { + "relative_path": "desk_lamp_arm_01/textures/desk_lamp_arm_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/desk_lamp_arm_01/desk_lamp_arm_01_rough_2k.exr", + "md5": "29d2c85871ce704f68995e66bd8ffb92", + "size": 4633095 + }, + { + "relative_path": "desk_lamp_arm_01/textures/desk_lamp_arm_01_mask01_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/desk_lamp_arm_01/desk_lamp_arm_01_mask01_2k.png", + "md5": "e05fc4a0d21e2b39de5ce42ba50c0520", + "size": 21479 + }, + { + "relative_path": "desk_lamp_arm_01/textures/desk_lamp_arm_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/desk_lamp_arm_01/desk_lamp_arm_01_nor_gl_2k.exr", + "md5": "e2d78dce0b96ff9dd5dad9ba3241b518", + "size": 5306315 + }, + { + "relative_path": "desk_lamp_arm_01/textures/desk_lamp_arm_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/desk_lamp_arm_01/desk_lamp_arm_01_diff_2k.jpg", + "md5": "18b2a20186590642bf99537784bdc414", + "size": 2438937 + }, + { + "relative_path": "desk_lamp_arm_01/textures/desk_lamp_arm_01_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/desk_lamp_arm_01/desk_lamp_arm_01_metal_2k.exr", + "md5": "1ff25182395f59e496793fd9af8dfe97", + "size": 2804270 + }, + { + "relative_path": "ceiling_fan/ceiling_fan_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/ceiling_fan/ceiling_fan_2k.usdc", + "md5": "8d3e61760955e7c02dcae430430aa687", + "size": 789880 + }, + { + "relative_path": "ceiling_fan/textures/ceiling_fan_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/ceiling_fan/ceiling_fan_diff_2k.jpg", + "md5": "3b6574a538b13325c4946d35411da222", + "size": 1433732 + }, + { + "relative_path": "ceiling_fan/textures/ceiling_fan_emissive_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/ceiling_fan/ceiling_fan_emissive_2k.png", + "md5": "fa08e29752ff26d1b93b0f6c30f332ff", + "size": 75793 + }, + { + "relative_path": "ceiling_fan/textures/ceiling_fan_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/ceiling_fan/ceiling_fan_metal_2k.exr", + "md5": "e11f59321d24907e37f9cd8dcd00ed88", + "size": 619462 + }, + { + "relative_path": "ceiling_fan/textures/ceiling_fan_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/ceiling_fan/ceiling_fan_nor_gl_2k.exr", + "md5": "cb0f159c54e46aabb96665b7bb2c70e0", + "size": 2554786 + }, + { + "relative_path": "ceiling_fan/textures/ceiling_fan_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/ceiling_fan/ceiling_fan_rough_2k.exr", + "md5": "e9754152ffb1e1206bf0985cb9d21fb2", + "size": 1604185 + }, + { + "relative_path": "ceiling_fan/textures/ceiling_fan_spec_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/ceiling_fan/ceiling_fan_spec_2k.png", + "md5": "2e7af56c79a12f3fc45107b4b719ef3c", + "size": 35784 + }, + { + "relative_path": "electric_stove/electric_stove_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/electric_stove/electric_stove_2k.usdc", + "md5": "269dd5bbbd130e4ea7fb083723069f66", + "size": 726488 + }, + { + "relative_path": "electric_stove/textures/electric_stove_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/electric_stove/electric_stove_nor_gl_2k.exr", + "md5": "c70359a238b4468de6f00ff39eebed9b", + "size": 3532279 + }, + { + "relative_path": "electric_stove/textures/electric_stove_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/electric_stove/electric_stove_diff_2k.jpg", + "md5": "6d7b9ca5d9b05119a716bcbc48f5a72e", + "size": 1614960 + }, + { + "relative_path": "electric_stove/textures/electric_stove_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/electric_stove/electric_stove_rough_2k.exr", + "md5": "63dabe558a82f3c7c46442c888ef925e", + "size": 3252021 + }, + { + "relative_path": "electric_stove/textures/electric_stove_opacity_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/electric_stove/electric_stove_opacity_2k.png", + "md5": "dc53c0f8a5195985b13fa6f28040986e", + "size": 72905 + }, + { + "relative_path": "electric_stove/textures/electric_stove_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/electric_stove/electric_stove_metal_2k.exr", + "md5": "a8a1601056ddc563ad7baf1060aa7c0c", + "size": 2000937 + }, + { + "relative_path": "hand_truck/hand_truck_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/hand_truck/hand_truck_2k.usdc", + "md5": "0539be2a6815600c3481346f913a64fc", + "size": 583853 + }, + { + "relative_path": "hand_truck/textures/hand_truck_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/hand_truck/hand_truck_diff_2k.jpg", + "md5": "3714c3eb827c338ec0af4fde7b53102b", + "size": 2936808 + }, + { + "relative_path": "hand_truck/textures/hand_truck_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/hand_truck/hand_truck_metal_2k.exr", + "md5": "6fe526b7996b9a579762dea4ea4fcb26", + "size": 2798854 + }, + { + "relative_path": "hand_truck/textures/hand_truck_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/hand_truck/hand_truck_nor_gl_2k.exr", + "md5": "f4e769ecc211bbab9be99d2735fdc349", + "size": 8953419 + }, + { + "relative_path": "hand_truck/textures/hand_truck_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/hand_truck/hand_truck_rough_2k.exr", + "md5": "c50386f54d5a347de5259e0f2a84a392", + "size": 2812891 + }, + { + "relative_path": "industrial_storage_cart/industrial_storage_cart_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/industrial_storage_cart/industrial_storage_cart_2k.usdc", + "md5": "dd64dad032be7829fb3d43874b6475ca", + "size": 730216 + }, + { + "relative_path": "industrial_storage_cart/textures/industrial_storage_cart_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/industrial_storage_cart/industrial_storage_cart_diff_2k.jpg", + "md5": "462e1943aa6b6a211259476f4658e762", + "size": 2116931 + }, + { + "relative_path": "industrial_storage_cart/textures/industrial_storage_cart_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/industrial_storage_cart/industrial_storage_cart_metal_2k.exr", + "md5": "efa07f77aecc01296141838615460b16", + "size": 3321079 + }, + { + "relative_path": "industrial_storage_cart/textures/industrial_storage_cart_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/industrial_storage_cart/industrial_storage_cart_nor_gl_2k.exr", + "md5": "c20641d16bb3ba20909c9d07c265c3d2", + "size": 5135910 + }, + { + "relative_path": "industrial_storage_cart/textures/industrial_storage_cart_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/industrial_storage_cart/industrial_storage_cart_rough_2k.exr", + "md5": "471d970ef9f02957144452bd2da542cd", + "size": 2310052 + }, + { + "relative_path": "WetFloorSign_01/WetFloorSign_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/WetFloorSign_01/WetFloorSign_01_2k.usdc", + "md5": "10ff3e4f2221f00912d017485d4ea63f", + "size": 18173 + }, + { + "relative_path": "WetFloorSign_01/textures/WetFloorSign_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/WetFloorSign_01/WetFloorSign_01_nor_gl_2k.exr", + "md5": "3f6fe336a671d714bed26dd33e29b642", + "size": 1078837 + }, + { + "relative_path": "WetFloorSign_01/textures/WetFloorSign_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/WetFloorSign_01/WetFloorSign_01_diff_2k.jpg", + "md5": "cfe3f031a0ee80754338dfc41fd22912", + "size": 115837 + }, + { + "relative_path": "WetFloorSign_01/textures/WetFloorSign_01_metallic_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/WetFloorSign_01/WetFloorSign_01_metallic_2k.exr", + "md5": "7c1ca8c7cc0421161b7e077648850aad", + "size": 13296 + }, + { + "relative_path": "WetFloorSign_01/textures/WetFloorSign_01_roughness_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/WetFloorSign_01/WetFloorSign_01_roughness_2k.jpg", + "md5": "a07181912bebeb1e3e9040f1589ad21d", + "size": 385049 + }, + { + "relative_path": "WetFloorSign_01/textures/WetFloorSign_01_roughness_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/WetFloorSign_01/WetFloorSign_01_roughness_2k.exr", + "md5": "1cfcf3987e402b9e06ec109a7dbae73a", + "size": 2061428 + }, + { + "relative_path": "book_encyclopedia_set_01/book_encyclopedia_set_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_2k.usdc", + "md5": "32335aa87f76185ff712b97abc3b7093", + "size": 3226253 + }, + { + "relative_path": "book_encyclopedia_set_01/textures/book_encyclopedia_set_01_paper_roughness_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_paper_roughness_2k.png", + "md5": "a44b8ca05d7cd4df7fbd5aaddf34c8bb", + "size": 8597 + }, + { + "relative_path": "book_encyclopedia_set_01/textures/book_encyclopedia_set_01_cover_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_cover_diff_2k.png", + "md5": "cf8b3f56c749f1c07a096b93b60d07a5", + "size": 3727355 + }, + { + "relative_path": "book_encyclopedia_set_01/textures/book_encyclopedia_set_01_cover_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_cover_nor_gl_2k.png", + "md5": "2b9b67bae83579524b3e817efa606de3", + "size": 62824 + }, + { + "relative_path": "book_encyclopedia_set_01/textures/book_encyclopedia_set_01_cover_metallic_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_cover_metallic_2k.png", + "md5": "f871c9aa29c3bac12351d80edd4b6edd", + "size": 70467 + }, + { + "relative_path": "book_encyclopedia_set_01/textures/book_encyclopedia_set_01_cover_roughness_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_cover_roughness_2k.png", + "md5": "026ab031101ef9f34a15ca07f721473a", + "size": 2059998 + }, + { + "relative_path": "book_encyclopedia_set_01/textures/book_encyclopedia_set_01_paper_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_paper_nor_gl_2k.png", + "md5": "a1decf76becc5f75e30cea660c2641e2", + "size": 1374815 + }, + { + "relative_path": "book_encyclopedia_set_01/textures/book_encyclopedia_set_01_paper_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/book_encyclopedia_set_01/book_encyclopedia_set_01_paper_diff_2k.png", + "md5": "80be660cf34e7ed0784896dc638bde30", + "size": 1041521 + }, + { + "relative_path": "classic_laptop/classic_laptop_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/classic_laptop/classic_laptop_2k.usdc", + "md5": "758a4e9ef5b02918dec9b3276e048891", + "size": 719577 + }, + { + "relative_path": "classic_laptop/textures/classic_laptop_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/classic_laptop/classic_laptop_diff_2k.jpg", + "md5": "b875a93593e1e60d06719a686fa82154", + "size": 1842752 + }, + { + "relative_path": "classic_laptop/textures/classic_laptop_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/classic_laptop/classic_laptop_metal_2k.exr", + "md5": "5fce7c538217ba4c98b0c9bdec12b4f5", + "size": 2069307 + }, + { + "relative_path": "classic_laptop/textures/classic_laptop_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/classic_laptop/classic_laptop_nor_gl_2k.exr", + "md5": "9a46ea0dbe5056f2494b61b8ce1fc9b6", + "size": 2365876 + }, + { + "relative_path": "classic_laptop/textures/classic_laptop_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/classic_laptop/classic_laptop_rough_2k.exr", + "md5": "7242b9226239ec476f90bf24d25f547c", + "size": 1711912 + }, + { + "relative_path": "gamepad/gamepad_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/gamepad/gamepad_2k.usdc", + "md5": "5b29f0ee98120cb8046fe4daedfb9abf", + "size": 458071 + }, + { + "relative_path": "gamepad/textures/gamepad_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/gamepad/gamepad_metal_2k.exr", + "md5": "84f79976f3dc622a44263a11d42b5097", + "size": 27930 + }, + { + "relative_path": "gamepad/textures/gamepad_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/gamepad/gamepad_nor_gl_2k.exr", + "md5": "a0d060dff99c725c1381438249d048ff", + "size": 1958677 + }, + { + "relative_path": "gamepad/textures/gamepad_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/gamepad/gamepad_diff_2k.jpg", + "md5": "94501ef34af97f0221b263efb03ec74c", + "size": 1055624 + }, + { + "relative_path": "gamepad/textures/gamepad_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/gamepad/gamepad_rough_2k.exr", + "md5": "5a240fff494e039b357d840d1cb41fe6", + "size": 1797276 + }, + { + "relative_path": "boombox/boombox_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/boombox/boombox_2k.usdc", + "md5": "8efc2388026919529b251024b1bfc449", + "size": 666018 + }, + { + "relative_path": "boombox/textures/boombox_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/boombox/boombox_metal_2k.exr", + "md5": "7fddd5783da99b2f150c7c38fa5a16a5", + "size": 44172 + }, + { + "relative_path": "boombox/textures/boombox_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/boombox/boombox_nor_gl_2k.exr", + "md5": "28f745fce1c337446a4b5374e6a27e7b", + "size": 3794923 + }, + { + "relative_path": "boombox/textures/boombox_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/boombox/boombox_rough_2k.exr", + "md5": "b5228a238704098f4d63dbaeb4519b78", + "size": 1528847 + }, + { + "relative_path": "boombox/textures/boombox_speakers_metal_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/boombox/boombox_speakers_metal_2k.png", + "md5": "f6f35eae16ca86fb8766358de0dc78ad", + "size": 177397 + }, + { + "relative_path": "boombox/textures/boombox_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/boombox/boombox_diff_2k.jpg", + "md5": "0dec970ad3d1845534161ffeac1b8ecc", + "size": 1703290 + }, + { + "relative_path": "boombox/textures/boombox_speakers_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/boombox/boombox_speakers_diff_2k.png", + "md5": "fe45e8562bdafb3e11d785813fb80382", + "size": 2113113 + }, + { + "relative_path": "boombox/textures/boombox_speakers_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/boombox/boombox_speakers_rough_2k.png", + "md5": "82cfb64cae76414a34d7ca39a9bf8cb4", + "size": 1292065 + }, + { + "relative_path": "all_purpose_cleaner/all_purpose_cleaner_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/all_purpose_cleaner/all_purpose_cleaner_2k.usdc", + "md5": "36a95502b3cd52f9d8500187a9500ec4", + "size": 233432 + }, + { + "relative_path": "all_purpose_cleaner/textures/all_purpose_cleaner_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/all_purpose_cleaner/all_purpose_cleaner_rough_2k.exr", + "md5": "410b66f3b39ed924e72e030174d5ce0b", + "size": 2277960 + }, + { + "relative_path": "all_purpose_cleaner/textures/all_purpose_cleaner_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/all_purpose_cleaner/all_purpose_cleaner_nor_gl_2k.exr", + "md5": "e5bc6e906571378ed7a170eded2cbeca", + "size": 681200 + }, + { + "relative_path": "all_purpose_cleaner/textures/all_purpose_cleaner_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/all_purpose_cleaner/all_purpose_cleaner_diff_2k.jpg", + "md5": "58b73a47a10847c848a7ffd9e5c75f0d", + "size": 1212507 + }, + { + "relative_path": "bleach_bottle/bleach_bottle_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/bleach_bottle/bleach_bottle_2k.usdc", + "md5": "8aff5c952489e9ee319f0d4e02befa7b", + "size": 200900 + }, + { + "relative_path": "bleach_bottle/textures/bleach_bottle_01_nor_gl_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/bleach_bottle/bleach_bottle_01_nor_gl_2k.png", + "md5": "fec6f3401a61e0d517a84aa85d8272a8", + "size": 13358392 + }, + { + "relative_path": "bleach_bottle/textures/bleach_bottle_01_rough_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/bleach_bottle/bleach_bottle_01_rough_2k.png", + "md5": "779c745c40db22722b0a02271f3e9ec0", + "size": 5310870 + }, + { + "relative_path": "bleach_bottle/textures/bleach_bottle_01_diff_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/bleach_bottle/bleach_bottle_01_diff_2k.png", + "md5": "7f65d4281e90dae075515c939f671fb9", + "size": 15358426 + }, + { + "relative_path": "football/football_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/football/football_2k.usdc", + "md5": "a3984f31a20212f485cc2353f5197fbe", + "size": 225651 + }, + { + "relative_path": "football/textures/football_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/football/football_nor_gl_2k.exr", + "md5": "c0bd0225c52b10c9944e4c49ed153498", + "size": 8411041 + }, + { + "relative_path": "football/textures/football_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/football/football_rough_2k.exr", + "md5": "1e3bcef8eee5c301044ac9ff184126b9", + "size": 4056671 + }, + { + "relative_path": "football/textures/football_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/football/football_diff_2k.jpg", + "md5": "61e3d2bcda45060ee26be74999c171bf", + "size": 2813255 + }, + { + "relative_path": "anthurium_botany_01/anthurium_botany_01_2k.usdc", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/usd/2k/anthurium_botany_01/anthurium_botany_01_2k.usdc", + "md5": "3e78f7bb46dcdfc1bcabab90a3310d82", + "size": 12765481 + }, + { + "relative_path": "anthurium_botany_01/textures/anthurium_botany_01_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/anthurium_botany_01/anthurium_botany_01_nor_gl_2k.exr", + "md5": "e36c3d061cbf24d761fa0ba92fe71f28", + "size": 4308519 + }, + { + "relative_path": "anthurium_botany_01/textures/anthurium_botany_01_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/exr/2k/anthurium_botany_01/anthurium_botany_01_rough_2k.exr", + "md5": "67b2e9bfd7e907dc4007e12f6766c7d1", + "size": 3087710 + }, + { + "relative_path": "anthurium_botany_01/textures/anthurium_botany_01_disp_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/anthurium_botany_01/anthurium_botany_01_disp_2k.png", + "md5": "da8dce19fe6144cfa166f5a78970efd9", + "size": 3081059 + }, + { + "relative_path": "anthurium_botany_01/textures/anthurium_botany_01_alpha_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/png/2k/anthurium_botany_01/anthurium_botany_01_alpha_2k.png", + "md5": "2a14dde9381b983427adcba195c7d6c6", + "size": 95881 + }, + { + "relative_path": "anthurium_botany_01/textures/anthurium_botany_01_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Models/jpg/2k/anthurium_botany_01/anthurium_botany_01_diff_2k.jpg", + "md5": "0fc12b2b2db969ff4f5cc783ffdb807c", + "size": 1565878 + }, + { + "relative_path": "hdri:kiara_interior/kiara_interior_4k.hdr", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/4k/kiara_interior_4k.hdr", + "md5": "6614615db70a3d64b7632e493ad3444b", + "size": 26340595 + }, + { + "relative_path": "hdri:kiara_interior/preview.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/kiara_interior.jpg", + "md5": "17df3e469b1bfb8e4ef4c29d32bd53aa", + "size": 5369155 + }, + { + "relative_path": "hdri:blocky_photo_studio/blocky_photo_studio_4k.hdr", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/4k/blocky_photo_studio_4k.hdr", + "md5": "7deb0f4c5940fff4d81fd69b05f445b5", + "size": 24509398 + }, + { + "relative_path": "hdri:blocky_photo_studio/preview.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/blocky_photo_studio.jpg", + "md5": "97c2c8da3cbe7d99ba9860d9e1f64a90", + "size": 28500264 + }, + { + "relative_path": "hdri:empty_warehouse_01/empty_warehouse_01_4k.hdr", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/4k/empty_warehouse_01_4k.hdr", + "md5": "fbc3a9abe13f166bf1318f24fe4e80a4", + "size": 25713024 + }, + { + "relative_path": "hdri:empty_warehouse_01/preview.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/empty_warehouse_01.jpg", + "md5": "c8bade16362fe4ffcc2f8c176b84daba", + "size": 4072009 + }, + { + "relative_path": "hdri:garage/garage_4k.hdr", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/4k/garage_4k.hdr", + "md5": "db0addd6c347c7eb9e4b0388cb76b18e", + "size": 25306132 + }, + { + "relative_path": "hdri:garage/preview.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/garage.jpg", + "md5": "76867ecf2f2f2d9d210413d4648ff3c9", + "size": 4212895 + }, + { + "relative_path": "hdri:monochrome_studio_03/monochrome_studio_03_4k.hdr", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/4k/monochrome_studio_03_4k.hdr", + "md5": "cff03f9b8a47f8752fb35b28c8d54bea", + "size": 25533504 + }, + { + "relative_path": "hdri:monochrome_studio_03/preview.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/monochrome_studio_03.jpg", + "md5": "5bc5142589d3231aa46d230c0b0406d8", + "size": 21602179 + }, + { + "relative_path": "hdri:photo_studio_loft_hall/photo_studio_loft_hall_4k.hdr", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/4k/photo_studio_loft_hall_4k.hdr", + "md5": "eea88b864ed4133dcefc79880e8e4865", + "size": 25245847 + }, + { + "relative_path": "hdri:photo_studio_loft_hall/preview.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/HDRIs/extra/Tonemapped%20JPG/photo_studio_loft_hall.jpg", + "md5": "3456280ca1b1cb80ebe14f257bca296d", + "size": 39022433 + }, + { + "relative_path": "material:anti_skid_tiles/anti_skid_tiles_2k.blend", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/blend/2k/anti_skid_tiles/anti_skid_tiles_2k.blend", + "md5": "bfd28be0df31598c5097f803f34565ab", + "size": 214628 + }, + { + "relative_path": "material:anti_skid_tiles/textures/anti_skid_tiles_ao_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k/anti_skid_tiles/anti_skid_tiles_ao_2k.jpg", + "md5": "b7e3df9832671f2676af55405f8b9afd", + "size": 1900420 + }, + { + "relative_path": "material:anti_skid_tiles/textures/anti_skid_tiles_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k/anti_skid_tiles/anti_skid_tiles_diff_2k.jpg", + "md5": "2282c6205ed4712577731ec3ba2e5789", + "size": 2540461 + }, + { + "relative_path": "material:anti_skid_tiles/textures/anti_skid_tiles_disp_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/png/2k/anti_skid_tiles/anti_skid_tiles_disp_2k.png", + "md5": "da6030ed3f8760f30036d0b62bb0b612", + "size": 6599089 + }, + { + "relative_path": "material:anti_skid_tiles/textures/anti_skid_tiles_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/anti_skid_tiles/anti_skid_tiles_nor_gl_2k.exr", + "md5": "3f4aa424eda3c23b8638310a91dadfd3", + "size": 5399482 + }, + { + "relative_path": "material:anti_skid_tiles/textures/anti_skid_tiles_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/anti_skid_tiles/anti_skid_tiles_rough_2k.exr", + "md5": "455a0d903726fe5eddf0d134daa3431d", + "size": 2877677 + }, + { + "relative_path": "material:anti_slip_concrete/anti_slip_concrete_2k.blend", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/blend/2k/anti_slip_concrete/anti_slip_concrete_2k.blend", + "md5": "eb98ea1e7c626960777a9424340d6ded", + "size": 216679 + }, + { + "relative_path": "material:anti_slip_concrete/textures/anti_slip_concrete_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k/anti_slip_concrete/anti_slip_concrete_diff_2k.jpg", + "md5": "94c3dac5985f1c8c93c4fc532593d148", + "size": 4260182 + }, + { + "relative_path": "material:anti_slip_concrete/textures/anti_slip_concrete_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/anti_slip_concrete/anti_slip_concrete_nor_gl_2k.exr", + "md5": "669e8fbf5aff32590b15916399fbd66d", + "size": 8723816 + }, + { + "relative_path": "material:anti_slip_concrete/textures/anti_slip_concrete_disp_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/png/2k/anti_slip_concrete/anti_slip_concrete_disp_2k.png", + "md5": "0c9173436b4cb9f25a3ba123c222226c", + "size": 6556343 + }, + { + "relative_path": "material:anti_slip_concrete/textures/anti_slip_concrete_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/anti_slip_concrete/anti_slip_concrete_rough_2k.exr", + "md5": "f9915f1b22013d30ac5c8b807cad2bdc", + "size": 872421 + }, + { + "relative_path": "material:old_wood_floor/old_wood_floor_2k.blend", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/blend/2k/old_wood_floor/old_wood_floor_2k.blend", + "md5": "ae5b8db4a062565f3b8067d48da6cce3", + "size": 225208 + }, + { + "relative_path": "material:old_wood_floor/textures/old_wood_floor_disp_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/png/2k/old_wood_floor/old_wood_floor_disp_2k.png", + "md5": "d776cbab75da1679e3160fe88b74df19", + "size": 6965140 + }, + { + "relative_path": "material:old_wood_floor/textures/old_wood_floor_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k/old_wood_floor/old_wood_floor_diff_2k.jpg", + "md5": "b26ae70ec77367f421a5e0b3388b3e05", + "size": 3116403 + }, + { + "relative_path": "material:old_wood_floor/textures/old_wood_floor_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/old_wood_floor/old_wood_floor_rough_2k.exr", + "md5": "66bcd069934dc6e6fd9dce460769108e", + "size": 2469575 + }, + { + "relative_path": "material:old_wood_floor/textures/old_wood_floor_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/old_wood_floor/old_wood_floor_nor_gl_2k.exr", + "md5": "7b1d5b8bce501fd6227a2f03b453601b", + "size": 6581373 + }, + { + "relative_path": "material:plastered_wall/plastered_wall_2k.blend", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/blend/2k/plastered_wall/plastered_wall_2k.blend", + "md5": "73e1e0620a7f4f67d81987f6d32add3f", + "size": 237571 + }, + { + "relative_path": "material:plastered_wall/textures/plastered_wall_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/plastered_wall/plastered_wall_rough_2k.exr", + "md5": "c5a1771718a80620c54b5ae8526bc5e7", + "size": 3183287 + }, + { + "relative_path": "material:plastered_wall/textures/plastered_wall_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/plastered_wall/plastered_wall_nor_gl_2k.exr", + "md5": "9a8ff08c9cd64d5f6ece8dba8a10d5b0", + "size": 9188823 + }, + { + "relative_path": "material:plastered_wall/textures/plastered_wall_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k/plastered_wall/plastered_wall_diff_2k.jpg", + "md5": "1cacf2ddbccc137473e717f23db200a9", + "size": 2434531 + }, + { + "relative_path": "material:plastered_wall/textures/plastered_wall_disp_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/png/2k/plastered_wall/plastered_wall_disp_2k.png", + "md5": "85522c55c583cecc45678f79f5497ff9", + "size": 7494515 + }, + { + "relative_path": "material:interior_tiles/interior_tiles_2k.blend", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/blend/2k/interior_tiles/interior_tiles_2k.blend", + "md5": "75f7c45810b79e3799c01c857d787a29", + "size": 215734 + }, + { + "relative_path": "material:interior_tiles/textures/interior_tiles_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k/interior_tiles/interior_tiles_diff_2k.jpg", + "md5": "c33733a2bd26c440a0f0df5306ea8914", + "size": 2879908 + }, + { + "relative_path": "material:interior_tiles/textures/interior_tiles_disp_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/png/2k/interior_tiles/interior_tiles_disp_2k.png", + "md5": "44093eab1c2f1eb3c0f12bc2886a1a47", + "size": 6327724 + }, + { + "relative_path": "material:interior_tiles/textures/interior_tiles_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/interior_tiles/interior_tiles_nor_gl_2k.exr", + "md5": "211193b008333f12caee1f99e6582ae7", + "size": 4402327 + }, + { + "relative_path": "material:interior_tiles/textures/interior_tiles_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/interior_tiles/interior_tiles_rough_2k.exr", + "md5": "755bd5088abf06040ec427cfdd8718ad", + "size": 2373126 + }, + { + "relative_path": "material:metal_plate/metal_plate_2k.blend", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/blend/2k/metal_plate/metal_plate_2k.blend", + "md5": "8ebeb49d204fe445a12c862842ffa9c9", + "size": 221344 + }, + { + "relative_path": "material:metal_plate/textures/metal_plate_disp_2k.png", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/png/2k/metal_plate/metal_plate_disp_2k.png", + "md5": "6985ba99dd03ec75f1bea8d958a5e6b7", + "size": 6208394 + }, + { + "relative_path": "material:metal_plate/textures/metal_plate_metal_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/metal_plate/metal_plate_metal_2k.exr", + "md5": "b6a5c41ab47a403371083feb45778b5b", + "size": 5758083 + }, + { + "relative_path": "material:metal_plate/textures/metal_plate_nor_gl_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/metal_plate/metal_plate_nor_gl_2k.exr", + "md5": "24dc9e15fb1379ffe473ea1826043138", + "size": 4768374 + }, + { + "relative_path": "material:metal_plate/textures/metal_plate_diff_2k.jpg", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/jpg/2k/metal_plate/metal_plate_diff_2k.jpg", + "md5": "91b841e7e619e55588f0183a703fb644", + "size": 2670774 + }, + { + "relative_path": "material:metal_plate/textures/metal_plate_rough_2k.exr", + "url": "https://dl.polyhaven.org/file/ph-assets/Textures/exr/2k/metal_plate/metal_plate_rough_2k.exr", + "md5": "1c8aedff235003f1a486d05103aa106e", + "size": 4958857 + } + ] + }, + { + "name": "gso", + "kind": "direct", + "destination": "assets/high_quality/GSO-fuel", + "conversion": "Unzip source OBJ/MTL/PNG; convert to textured GLB/USD, preserve scale/orientation and validate against registered source hashes.", + "files": [ + { + "relative_path": "ACE_Coffee_Mug_Kristen_16_oz_cup/ACE_Coffee_Mug_Kristen_16_oz_cup.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/ACE_Coffee_Mug_Kristen_16_oz_cup.zip", + "md5": "b77d9ae46afcf2a5eb8de8bb2a4dab37", + "size": 6232969 + }, + { + "relative_path": "Orbit_Bubblemint_Mini_Bottle_6_ct/Orbit_Bubblemint_Mini_Bottle_6_ct.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Orbit_Bubblemint_Mini_Bottle_6_ct.zip", + "md5": "8f953eff297556b5de848d665913aad3", + "size": 8830834 + }, + { + "relative_path": "Footed_Bowl_Sand/Footed_Bowl_Sand.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Footed_Bowl_Sand.zip", + "md5": "ce3a30661aa32d5f5caf31442f961349", + "size": 5932979 + }, + { + "relative_path": "Victor_Reversible_Bookend/Victor_Reversible_Bookend.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Victor_Reversible_Bookend.zip", + "md5": "168b26fa0264cd1c1d845b470bbdfc1a", + "size": 4428316 + }, + { + "relative_path": "Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc/Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc.zip", + "md5": "ccf0752f00adabeef6c3b7c6fd51ed46", + "size": 7251776 + }, + { + "relative_path": "Target_Basket_Medium/Target_Basket_Medium.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Target_Basket_Medium.zip", + "md5": "a11aedac8925ff6b8fcfe09bb91273fa", + "size": 10758831 + }, + { + "relative_path": "HeavyDuty_Flashlight/HeavyDuty_Flashlight.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/HeavyDuty_Flashlight.zip", + "md5": "c1af24c97cb20b2ea94d5ad9f0f8e550", + "size": 4386214 + }, + { + "relative_path": "Diamond_Visions_Scissors_Red/Diamond_Visions_Scissors_Red.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Diamond_Visions_Scissors_Red.zip", + "md5": "51ac74ed07cbf2e4000a56166281f484", + "size": 2935793 + }, + { + "relative_path": "Threshold_Porcelain_Teapot_White/Threshold_Porcelain_Teapot_White.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Threshold_Porcelain_Teapot_White.zip", + "md5": "cf126b37cb7d72065e9694d919fa1338", + "size": 3063446 + }, + { + "relative_path": "Threshold_Porcelain_Pitcher_White/Threshold_Porcelain_Pitcher_White.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Threshold_Porcelain_Pitcher_White.zip", + "md5": "5b3afebd91c73b354bcc427de4ce16be", + "size": 2595281 + }, + { + "relative_path": "Threshold_Dinner_Plate_Square_Rim_White_Porcelain/Threshold_Dinner_Plate_Square_Rim_White_Porcelain.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Threshold_Dinner_Plate_Square_Rim_White_Porcelain.zip", + "md5": "9ecee5cb6711d3d95fc662e9c68d6a2a", + "size": 3476449 + }, + { + "relative_path": "Threshold_Bead_Cereal_Bowl_White/Threshold_Bead_Cereal_Bowl_White.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Threshold_Bead_Cereal_Bowl_White.zip", + "md5": "17dd37bfee2929a7bc2f024479c4f3be", + "size": 4207853 + }, + { + "relative_path": "Room_Essentials_Mug_White_Yellow/Room_Essentials_Mug_White_Yellow.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Room_Essentials_Mug_White_Yellow.zip", + "md5": "5c54b15524a768cca6fe2941d1a9de2e", + "size": 4658945 + }, + { + "relative_path": "Razer_Taipan_Black_Ambidextrous_Gaming_Mouse/Razer_Taipan_Black_Ambidextrous_Gaming_Mouse.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Razer_Taipan_Black_Ambidextrous_Gaming_Mouse.zip", + "md5": "cb4056f570a1102e6e6e0f344f6d756a", + "size": 5957654 + }, + { + "relative_path": "Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh/Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh.zip", + "md5": "2dba7f1e037c91f5d76bed7879c57ef7", + "size": 7625811 + }, + { + "relative_path": "Remington_TStudio_Hair_Dryer/Remington_TStudio_Hair_Dryer.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Remington_TStudio_Hair_Dryer.zip", + "md5": "c2dff9ec41c0fd1755cc008ab6601dfa", + "size": 6740668 + }, + { + "relative_path": "Rubbermaid_Large_Drainer/Rubbermaid_Large_Drainer.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Rubbermaid_Large_Drainer.zip", + "md5": "711eaf4e0fbdd4b976a18c658ff7e1e8", + "size": 6468895 + }, + { + "relative_path": "Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14/Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14.zip", + "md5": "0de75443ceb7e27e487507de634c66a0", + "size": 3507598 + }, + { + "relative_path": "Threshold_Bamboo_Ceramic_Soap_Dish/Threshold_Bamboo_Ceramic_Soap_Dish.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Threshold_Bamboo_Ceramic_Soap_Dish.zip", + "md5": "8685f4ccbeaa7b6cc684cce8b7843109", + "size": 5617617 + }, + { + "relative_path": "Sapota_Threshold_4_Ceramic_Round_Planter_Red/Sapota_Threshold_4_Ceramic_Round_Planter_Red.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Sapota_Threshold_4_Ceramic_Round_Planter_Red.zip", + "md5": "d471b7662d672abff8232b092ecd21a4", + "size": 4961105 + }, + { + "relative_path": "Shurtape_Tape_Purple_CP28/Shurtape_Tape_Purple_CP28.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Shurtape_Tape_Purple_CP28.zip", + "md5": "4577d82678d7604acff84eebc188a03a", + "size": 4317857 + }, + { + "relative_path": "TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black/TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black.zip", + "md5": "43dcf925d7d0f851398ca18502edaba4", + "size": 7315920 + }, + { + "relative_path": "Cole_Hardware_Mug_Classic_Blue/Cole_Hardware_Mug_Classic_Blue.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Cole_Hardware_Mug_Classic_Blue.zip", + "md5": "80791ea7f642a05fe235e76a510dc57f", + "size": 3688547 + }, + { + "relative_path": "Room_Essentials_Bowl_Turquiose/Room_Essentials_Bowl_Turquiose.zip", + "url": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/Room_Essentials_Bowl_Turquiose.zip", + "md5": "ae5c06e1ae9451661b88d8d06e7d656c", + "size": 4089776 + } + ] + } + ] +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/downloader.py b/docs/reproduction/public_download_control/downloader.py new file mode 100644 index 0000000000000000000000000000000000000000..3302e55703540a0c0e79559796f0cf36e6745624 --- /dev/null +++ b/docs/reproduction/public_download_control/downloader.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Download pinned public source assets into isolated, server-local storage.""" +import argparse +import concurrent.futures +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import shutil +import subprocess +import threading +import time +import zipfile +from urllib.parse import quote + +FETCH_LOCK = threading.Lock() +NEXT_FETCH = 0.0 + + +def atomic_json(path, value): + tmp = path.with_suffix(path.suffix + '.tmp') + tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2)) + tmp.replace(path) + + +def digest(path, kind): + h = hashlib.new(kind) + with path.open('rb') as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def fetch(url, target, resume=True, resolve=None): + global NEXT_FETCH + with FETCH_LOCK: + delay = NEXT_FETCH - time.monotonic() + if delay > 0: + time.sleep(delay) + NEXT_FETCH = time.monotonic() + 0.25 + target.parent.mkdir(parents=True, exist_ok=True) + cmd = ['curl', '-4', '--fail', '--location', '--silent', '--show-error', + '--connect-timeout', '15', '--max-time', '1800', '--retry', '6', + '--retry-delay', '10', '--retry-max-time', '600', '--speed-limit', '1024', '--speed-time', '60', + '--user-agent', 'RoboHomeGen-asset-migration/1.0'] + if resume and target.exists(): + cmd += ['--continue-at', '-'] + for address in resolve or []: + cmd += ['--resolve', address] + p = subprocess.run(cmd + ['--output', str(target), url], capture_output=True, text=True) + if p.returncode: + raise RuntimeError('curl rc=%d: %s' % (p.returncode, p.stderr[-500:])) + + +def safe_relative(value): + p = PurePosixPath(value) + if p.is_absolute() or '..' in p.parts or '\\' in value: + raise ValueError('Unsafe relative path: ' + value) + return p + + +def expand_hf(job, control): + repo, rev = job['repo'], job['revision'] + metadata = control / (job['name'] + '.upstream.json') + if not metadata.exists(): + fetch('https://hf-mirror.com/api/datasets/' + repo + '/revision/' + rev + '?blobs=true', metadata, False) + info = json.loads(metadata.read_text()) + if info.get('sha') != rev: + raise ValueError('Upstream revision differs from pinned revision') + rows = [] + for item in info['siblings']: + rel = item['rfilename'] + if PurePosixPath(rel).name == '.DS_Store': + continue + if any(rel == p or rel.startswith(p.rstrip('/') + '/') for p in job.get('exclude', [])): + continue + if job.get('include') and not any(rel == p or rel.startswith(p.rstrip('/') + '/') for p in job['include']): + continue + safe_relative(rel) + lfs = item.get('lfs') or {} + row = {'relative_path': rel, 'url': 'https://hf-mirror.com/datasets/' + repo + '/resolve/' + rev + '/' + quote(rel, safe='/'), + 'size': item.get('size', lfs.get('size'))} + if lfs.get('sha256'): + row['sha256'] = lfs['sha256'] + elif len(item.get('blobId', '')) == 40: + row['git_sha1'] = item['blobId'] + rows.append(row) + if not rows: + raise ValueError('No files selected') + return rows + + +def verify(path, item): + if not path.is_file(): + return False + if item.get('size') is not None and path.stat().st_size != item['size']: + return False + for kind in ('sha256', 'md5'): + if item.get(kind) and digest(path, kind) != item[kind]: + return False + if item.get('archive_type') == 'zip': + if not zipfile.is_zipfile(path): + return False + with zipfile.ZipFile(path) as archive: + if archive.testzip() is not None: + return False + if item.get('git_sha1'): + h = hashlib.sha1(('blob %d\0' % path.stat().st_size).encode()) + with path.open('rb') as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b''): + h.update(block) + if h.hexdigest() != item['git_sha1']: + return False + return True + + +def run_job(job, root, workers): + control = root / 'control' + target = root / job['destination'] + target.mkdir(parents=True, exist_ok=True) + state = {'name': job['name'], 'hostname': os.uname().nodename, 'pid': os.getpid(), + 'started_at': time.time(), 'state': 'listing', 'downloaded': 0, 'verified': 0, + 'bytes': 0, 'errors': {}, 'destination': str(target), + 'runtime_ready': False, 'conversion': job.get('conversion', 'validation_required')} + progress = control / (job['name'] + '.status.json') + atomic_json(progress, state) + try: + rows = expand_hf(job, control) if job['kind'] == 'hf' else job['files'] + atomic_json(control / (job['name'] + '.files.json'), rows) + state.update(state='downloading', total=len(rows), expected_bytes=sum(r.get('size') or 0 for r in rows)) + atomic_json(progress, state) + lock = threading.Lock() + + def one(item): + rel = str(safe_relative(item['relative_path'])) + dest = target / rel + try: + if shutil.disk_usage(root).free < 30 * 1024**3: + raise RuntimeError('Less than 30 GiB free; download stopped before exhausting disk') + reused = verify(dest, item) + if not reused: + part = dest.with_name(dest.name + '.download-partial') + if not verify(part, item): + fetch(item['url'], part, resolve=item.get('resolve')) + if not verify(part, item): + part.unlink(missing_ok=True) + raise ValueError('Source size or checksum mismatch') + part.replace(dest) + sha = digest(dest, 'sha256') + with lock: + state['verified'] += 1 + state['downloaded'] += int(not reused) + state['bytes'] += dest.stat().st_size + with (control / (job['name'] + '.verified.jsonl')).open('a') as receipt: + receipt.write(json.dumps({'path': rel, 'bytes': dest.stat().st_size, 'sha256': sha, 'verified_at': time.time()}) + '\n') + except Exception as exc: + with lock: + state['errors'][rel] = str(exc) + with lock: + state['updated_at'] = time.time() + state['elapsed_seconds'] = state['updated_at'] - state['started_at'] + atomic_json(progress, state) + + with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(one, rows)) + state['state'] = 'downloaded_needs_conversion_or_validation' if not state['errors'] else 'incomplete' + except Exception as exc: + state.update(state='failed', fatal_error=str(exc)) + state['finished_at'] = time.time() + state['elapsed_seconds'] = state['finished_at'] - state['started_at'] + atomic_json(progress, state) + print(json.dumps({k: v for k, v in state.items() if k != 'errors'}), flush=True) + return state + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--manifest', required=True) + parser.add_argument('--root', default='/data/RPHomeGen/public_assets_20261115') + parser.add_argument('--workers', type=int, default=6) + parser.add_argument('--wait-pid', type=int) + parser.add_argument('--retry-rounds', type=int, default=1) + args = parser.parse_args() + if args.wait_pid: + while True: + try: + os.kill(args.wait_pid, 0) + except ProcessLookupError: + break + time.sleep(10) + root = Path(args.root) + (root / 'control').mkdir(parents=True, exist_ok=True) + manifest = json.loads(Path(args.manifest).read_text()) + jobs = manifest['jobs'] + results = [] + for attempt in range(args.retry_rounds): + results = [run_job(job, root, args.workers) for job in jobs] + jobs = [job for job, result in zip(jobs, results) if result['state'] in ('incomplete', 'failed')] + if not jobs: + break + if attempt + 1 < args.retry_rounds: + time.sleep(20) + raise SystemExit(int(any(r['state'] in ('incomplete', 'failed') for r in results))) + + +if __name__ == '__main__': + main() diff --git a/docs/reproduction/public_download_control/gso.conversion.json b/docs/reproduction/public_download_control/gso.conversion.json new file mode 100644 index 0000000000000000000000000000000000000000..edb7b244e525fe05d4fcc20648579f4986becec6 --- /dev/null +++ b/docs/reproduction/public_download_control/gso.conversion.json @@ -0,0 +1,205 @@ +{ + "state": "converted_pending_validation", + "started_at": 1794696905.7804468, + "pid": 3098835, + "host": "zp-nc67", + "runtime_ready": false, + "source_revision": "07e817247c213def01d20e0cf381eb52dac8210b", + "readme": "conversion_code/README.md#high-fidelity-asset-preprocessing", + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115", + "texture_aliases": [ + { + "asset_id": "gso:Orbit_Bubblemint_Mini_Bottle_6_ct", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Orbit_Bubblemint_Mini_Bottle_6_ct/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Orbit_Bubblemint_Mini_Bottle_6_ct/meshes/texture.png", + "md5": "07f3ebaf7985d6f36425cdd5bb2a68e8" + }, + { + "asset_id": "gso:Room_Essentials_Bowl_Turquiose", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Bowl_Turquiose/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Bowl_Turquiose/meshes/texture.png", + "md5": "9183bec281b08e30f74bb59f12b855af" + }, + { + "asset_id": "gso:Victor_Reversible_Bookend", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Victor_Reversible_Bookend/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Victor_Reversible_Bookend/meshes/texture.png", + "md5": "d7d3d6205907634d4a666b1612696917" + }, + { + "asset_id": "gso:Room_Essentials_Mug_White_Yellow", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Mug_White_Yellow/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Mug_White_Yellow/meshes/texture.png", + "md5": "42d3c604971e8b6e89e114b4d3ba2a51" + }, + { + "asset_id": "gso:HeavyDuty_Flashlight", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/HeavyDuty_Flashlight/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/HeavyDuty_Flashlight/meshes/texture.png", + "md5": "ca1afd0dc3cfe9c3e7f4a0691002d199" + }, + { + "asset_id": "gso:Rubbermaid_Large_Drainer", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Rubbermaid_Large_Drainer/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Rubbermaid_Large_Drainer/meshes/texture.png", + "md5": "7959494f0ae63c739496baeedbf35cf5" + }, + { + "asset_id": "gso:Threshold_Bamboo_Ceramic_Soap_Dish", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bamboo_Ceramic_Soap_Dish/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bamboo_Ceramic_Soap_Dish/meshes/texture.png", + "md5": "004caa4cb741534e25db3ea9f9ed0b04" + }, + { + "asset_id": "gso:Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14/meshes/texture.png", + "md5": "11df983119c7eba48fa4e5eb557b9022" + }, + { + "asset_id": "gso:Cole_Hardware_Mug_Classic_Blue", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Cole_Hardware_Mug_Classic_Blue/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Cole_Hardware_Mug_Classic_Blue/meshes/texture.png", + "md5": "cbfad6eaf876bc7cc69422b8671c402a" + }, + { + "asset_id": "gso:Threshold_Dinner_Plate_Square_Rim_White_Porcelain", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Dinner_Plate_Square_Rim_White_Porcelain/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Dinner_Plate_Square_Rim_White_Porcelain/meshes/texture.png", + "md5": "6eeee75d446e7fca58fe712819ce8f11" + }, + { + "asset_id": "gso:Razer_Taipan_Black_Ambidextrous_Gaming_Mouse", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_Taipan_Black_Ambidextrous_Gaming_Mouse/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_Taipan_Black_Ambidextrous_Gaming_Mouse/meshes/texture.png", + "md5": "4c345504448f5c0188f829c60df3d03e" + }, + { + "asset_id": "gso:Threshold_Bead_Cereal_Bowl_White", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bead_Cereal_Bowl_White/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bead_Cereal_Bowl_White/meshes/texture.png", + "md5": "f30578d2d455b8022c1a3a95cb8928c9" + }, + { + "asset_id": "gso:Remington_TStudio_Hair_Dryer", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Remington_TStudio_Hair_Dryer/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Remington_TStudio_Hair_Dryer/meshes/texture.png", + "md5": "0cabe47fb99216c9d9e0bbd0e5a949bc" + }, + { + "asset_id": "gso:Diamond_Visions_Scissors_Red", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Diamond_Visions_Scissors_Red/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Diamond_Visions_Scissors_Red/meshes/texture.png", + "md5": "35fba1677af985fffeb63ea23c5dfa51" + }, + { + "asset_id": "gso:Sapota_Threshold_4_Ceramic_Round_Planter_Red", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sapota_Threshold_4_Ceramic_Round_Planter_Red/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sapota_Threshold_4_Ceramic_Round_Planter_Red/meshes/texture.png", + "md5": "920e2b6dc547764b98d525749a86e44c" + }, + { + "asset_id": "gso:ACE_Coffee_Mug_Kristen_16_oz_cup", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/ACE_Coffee_Mug_Kristen_16_oz_cup/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/ACE_Coffee_Mug_Kristen_16_oz_cup/meshes/texture.png", + "md5": "b7225c11584cd1ba62765b49207be6e4" + }, + { + "asset_id": "gso:Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh/meshes/texture.png", + "md5": "fabdec0c721e420323da279226a7f2e8" + }, + { + "asset_id": "gso:Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc/meshes/texture.png", + "md5": "37f744aa881d26587220d2b3b0269750" + }, + { + "asset_id": "gso:Footed_Bowl_Sand", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Footed_Bowl_Sand/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Footed_Bowl_Sand/meshes/texture.png", + "md5": "0d6320abea89b09188507a41b58ee2cb" + }, + { + "asset_id": "gso:TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black/meshes/texture.png", + "md5": "c93f2163049ba9868afddfe50e4c049e" + }, + { + "asset_id": "gso:Threshold_Porcelain_Teapot_White", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Teapot_White/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Teapot_White/meshes/texture.png", + "md5": "af2663bea0506269ebf6cd8673e11026" + }, + { + "asset_id": "gso:Target_Basket_Medium", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Target_Basket_Medium/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Target_Basket_Medium/meshes/texture.png", + "md5": "a98a8da0e798f1171fffa5e28123db7b" + }, + { + "asset_id": "gso:Threshold_Porcelain_Pitcher_White", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Pitcher_White/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Pitcher_White/meshes/texture.png", + "md5": "895ddc8a291ad18f9c582014bd33c5ab" + }, + { + "asset_id": "gso:Shurtape_Tape_Purple_CP28", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Shurtape_Tape_Purple_CP28/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Shurtape_Tape_Purple_CP28/meshes/texture.png", + "md5": "0b46fd06deeb78f67a807daaebaa90d4" + } + ], + "command": [ + "/data/RPHomeGen/public_assets_20261115/conversion_env/bin/python", + "/data/RPHomeGen/public_assets_20261115/conversion_code/scripts/preprocess_high_fidelity_assets.py", + "--asset-root", + "/data/RPHomeGen/public_assets_20261115/conversion_managed_inputs", + "--output", + "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115", + "--base-index", + "/data/RPHomeGen/nas_mirror/zhf/rp_robohavengen/asset_library/registry/asset_index.sqlite3", + "--stage", + "convert", + "--sources", + "gso,polyhaven", + "--blender", + "/data/rhg-wqz/runtime/4764ef211238289e78b85817e44f05e148969d8c510f45c14c5c2bd8d78443fd/blender", + "--usd-python", + "/data/RPHomeGen/public_assets_20261115/conversion_env/bin/python", + "--blender-batch-size", + "24", + "--usd-batch-size", + "128", + "--release-workers", + "4" + ], + "transferred_files_verified": 265, + "exit_code": 0, + "report": { + "schema_version": "1.0", + "created_at": "2026-11-14T22:55:20.446991+00:00", + "stage": "convert", + "plan": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/preprocess_plan.json", + "counts": { + "ready": 56 + }, + "duration_s": 7.039, + "release": null + }, + "counts": { + "ready": 24 + }, + "failed_items": [], + "name": "gso", + "finished_at": 1794696920.5190022, + "count": 24, + "technical_check": { + "passed": 24, + "total": 24, + "report": "/data/RPHomeGen/public_assets_20261115/control/readme-conversion-technical-check.json" + } +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/lightwheel-checks.json b/docs/reproduction/public_download_control/lightwheel-checks.json new file mode 100644 index 0000000000000000000000000000000000000000..6e5fd726f4f51de367b6a85ef911612402be2711 --- /dev/null +++ b/docs/reproduction/public_download_control/lightwheel-checks.json @@ -0,0 +1,1514 @@ +[ + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/2-StoryStaircase/2-StoryStaircase.usd", + "md5": "988c45489d4ba35b7eb1d3cecd35c711" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/2-StoryStaircase/Loft.usd", + "md5": "7c0eb715b94f6d1523bbdaa3a0172450" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_01_0.usd", + "md5": "326e1a721a60ed97a963252b59bb0ce5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_03_0.usd", + "md5": "8eb3a40b4702f9bab199f37c0ce6568d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_04_0.usd", + "md5": "9b33a97735aa793bb19edbf3318f0d0f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_05_0.usd", + "md5": "1dd13a853d3405bf594edd4b4cb590f8" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_06_0.usd", + "md5": "710a954f241c514050d13f30ee3a2f56" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_07_0.usd", + "md5": "a042aec3e73b234d749739a4edefc9a9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_08_0.usd", + "md5": "7eb0c7b9adbe1f855b9c5092f98309c3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_09_0.usd", + "md5": "293d010a4dd3d150f3fbd8ca9754bfda" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_10_0.usd", + "md5": "7f9f046b49578fe5586065ba66689ee6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_11_0.usd", + "md5": "068730b4e6279d368953450d812d1f2b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_12_0.usd", + "md5": "874b7d4ae2679f5d6ed84db8672d1d1a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_13_0.usd", + "md5": "5419d89efcb1aefcf2b30dbda0e12dbc" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_14_0.usd", + "md5": "66d527c0b63c26cb51aa6922daa27f82" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_15_0.usd", + "md5": "eb50dc28fb6b869fb3ed1f545bc2b0ef" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_bar_16_0.usd", + "md5": "5b60e0288432cbaf581a94da32762d23" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_building_01_0.usd", + "md5": "1aa265982a4af112efb3d954b12c8c16" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_carpet_18_0.usd", + "md5": "49bd73db28c57a8bc123b0bb79860ded" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_chair_01_0.usd", + "md5": "9e8a2ce5d424dd34eb280c2a31adf133" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_door_01_0.usd", + "md5": "1939ad30ce23908ff41dae94568f9b59" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_door_02_0.usd", + "md5": "afb8d335198088b3b8edd815e724f5a2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_fence_01_0.usd", + "md5": "1a43e8bfadee695af888bc1d99ba1b55" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_floor_01_0.usd", + "md5": "df8be884252da6df66bfc9b261c2b387" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_flower_04_0.usd", + "md5": "9eec376b499e536ba9dd2fe70ffc89f7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_kitchen_01_0.usd", + "md5": "99563d130c4934a0334e5ddbc3f8fca3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_kitchen_02_0.usd", + "md5": "eb44840ef0d3c1978590ca6e7b5cf37b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_kitchen_03_0.usd", + "md5": "e72376917eb621652ad2b9fcfce063df" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_kitchen_04_0.usd", + "md5": "5c0abab124d3d119f9e38e16066d6e60" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_lamp_05_1.usd", + "md5": "a53c521cc94cf31f7db6238d2f5dbc31" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_lamp_06_1.usd", + "md5": "8a8f0f3a50d63d13cd130c031325977c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_pillow_01_0.usd", + "md5": "74ee03be0799fbaec820077e36ceae04" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_pillow_02_0.usd", + "md5": "3a568af85d8779d25076371869b8d507" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_pillow_03_0.usd", + "md5": "9dec7e80d40d37837459b8da1fcc547d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_sofa_01_0.usd", + "md5": "e9d888add61c14e159eda38855f24809" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_table_01_0.usd", + "md5": "7da6a6ef4fefa2401cc744a810f57c64" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_table_02_0.usd", + "md5": "db5a3c4a159a984b6e2cb28421d76e60" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_tiles_01_0.usd", + "md5": "9e1398feeb88d0d70f557957a54bf062" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_tree_01_0.usd", + "md5": "65b7e1b9343cf19ed7e189bc660c5f25" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_tree_02_0.usd", + "md5": "96c4d482a9d2d6f36c18888e50ef1592" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_01_0.usd", + "md5": "7bdb87584bbbeac95292a860be6b2ec3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_03_0.usd", + "md5": "c0524b76a27f134dffc0a4a20040da5b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_04_0.usd", + "md5": "00c718fc886c13a6e53a8045c9c25f88" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_05_0.usd", + "md5": "8599e31e94f3fcd2faf74a0bd4874905" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_06_0.usd", + "md5": "fd36f45014f2ae35dd25948bb681bbcd" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_07_0.usd", + "md5": "7c1cbd63b0837ada7eff31cd2691fa2b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_11_0.usd", + "md5": "5b87bb4789a8f1da11f1d97ae7c6839c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_12_0.usd", + "md5": "5b44ff371fe319fa621a07c10cf1253e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_13_0.usd", + "md5": "c98f611ee8358207d965fac3f289409c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_15_0.usd", + "md5": "e6cff7f64653bef80eb6d32c600168a7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_16_0.usd", + "md5": "b745a0cbb7baf32e60684190d48ce9af" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_17_0.usd", + "md5": "ebd55e7fd33a1f2b36172ea33b56d480" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_18_0.usd", + "md5": "e2c58da52fb2da93a632b11b756ccab6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_20_0.usd", + "md5": "700449b59b08e65d968843ec3213ec77" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_21_0.usd", + "md5": "91d637c3bd6c124b8e3fde0ecdded77d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_22_0.usd", + "md5": "eba5a058024079f8515e75a80aac245a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_23_0.usd", + "md5": "a43717abf7111a244fedbf2fafd17023" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_24_0.usd", + "md5": "72f7a3e8f15564d60a8c054860a0838a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_26_0.usd", + "md5": "554a920c12101aeeb421fbaa32904405" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_27_0.usd", + "md5": "3557c8c584d4288611ed8841fbeecc4b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_28_0.usd", + "md5": "e1c066f910fb94d641c5286d7f5a7013" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_30_0.usd", + "md5": "09141c9a1e07a0fb7893eb1e11347b99" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_31_0.usd", + "md5": "28fcfbaedf8d05a1d66017f2294eecf7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wall_32_0.usd", + "md5": "a41e4072c113cbd4e6c89882dc4d990f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wardrobe_01_0.usd", + "md5": "b9450d4ea9d9bdfed06e3549e42f1011" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_wardrobe_02_0.usd", + "md5": "33c144cb26191c717e4f22b772fe8d3d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_window_01_0.usd", + "md5": "d32078a03f97e1fe7fb7394bd3320b13" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_window_03_1.usd", + "md5": "bd889fa3b3618106355b8263331cc7af" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/Props/SM_window_04_0.usd", + "md5": "fc0533bbaa6c535b97ba57e5a61cdc3c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Apartment/scene_04.usd", + "md5": "926cf09565564c8c405b48ca33d49f4c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Grass/E/InteractiveAsset/omron_franka.usd", + "md5": "bdab66f8360ea919ee21b02d852efcf1" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/Grass/Grass.usd", + "md5": "f418dc98925d75df3ca27b7fe9d8cd98" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/GravelGround/GravelGround.usd", + "md5": "f71716e875809bd697516999feabf7d5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/GravelGround/dirt_grass_track/dirt_grass_track.usd", + "md5": "8232985f2e312171a94250adf693e590" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/ClothDemo_002/cloth_demo_001.usd", + "md5": "b7c1f1d125ba1644fbc9400670c04fa2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/CoffeeMachine006/CoffeeMachine006.usd", + "md5": "1c96f1cda6ac18019cbd362b889c354e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Collected_waterbottle_7/D/RSS/Collected_waterbottle_4/Collected_KitchenRoom/Collected_KitchenRoom/Kitchen_InsularShelf/Kitchen_InsularShelf.usd", + "md5": "a49da1bfc6e37bd01281cfab53a1db07" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Collected_waterbottle_7/D/RSS/Collected_waterbottle_4/Isaac project/strawberry/Collected_emptyenv/Ground.usd", + "md5": "70773f2202e78b15f7e66d5d98f7a324" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Collected_waterbottle_7/D/RSS/Collected_waterbottle_4/Isaac project/strawberry/Collected_emptyenv/emptyenv.usd", + "md5": "6caf7a5fd96275192e36d31e3751866f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Collected_waterbottle_7/waterbottle_7.usd", + "md5": "9f1e12cd5b9481e0feb0ab0e811b2355" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Dishwasher054/Dishwasher054.usd", + "md5": "39bbf72052264a3a10b4b3886c2e77db" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Door012/Door012.usd", + "md5": "ef91d5ca96026bed7f4c8ad5a17c166f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Choppingboard_01/Collected_SM_P_Choppingboard_01/Props/SM_P_Choppingboard_01.usd", + "md5": "46690698e90c93c2feb3dfb48fe38203" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Choppingboard_01/Collected_SM_P_Choppingboard_01/SM_P_Choppingboard_01.usd", + "md5": "95f337632ee7a0a8a24e895b31ef8140" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Flavour_02/Collected_SM_P_Flavour_02/Props/SM_P_Flavour_02.usd", + "md5": "b06506d96765fff9d7061f3d4c88f7f8" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Flavour_02/Collected_SM_P_Flavour_02/Props/SM_P_Flavour_03.usd", + "md5": "a6d058d09ac901428126b3856f4eef6a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Flavour_02/Collected_SM_P_Flavour_02/Props/SM_P_Flavour_03_Cover.usd", + "md5": "38914f6a6c6e2b313dc3a1c0c7abd912" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Flavour_02/Collected_SM_P_Flavour_02/Props/SM_P_Flavour_04.usd", + "md5": "8fe80f9605b72e61d8af3de2e4433e75" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Flavour_02/Collected_SM_P_Flavour_02/Props/SM_P_Jar_01.usd", + "md5": "80f9fba3d2f9b777d445a390ac8e9321" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Flavour_02/Collected_SM_P_Flavour_02/Props/SM_P_Tray_01.usd", + "md5": "66764095067bd835ffe0a718cb16cd87" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/InteractiveAsset/SM_P_Flavour_02/Collected_SM_P_Flavour_02/SM_P_Flavour_02.usd", + "md5": "a3355b29d0c0e433db68aaf3569605b8" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/KitchenRoom.usd", + "md5": "46cfbc69981512619efa68a72d2122dc" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/KitchenRoom_RSS.usd", + "md5": "0f832ead23d12df0c00251b6b75cd55c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Cabinet001/Kitchen_Cabinet001.usd", + "md5": "fd2e5e100f6c7055812c288a93958427" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Cabinet002/Kitchen_Cabinet002.usd", + "md5": "40156a4666ae498bfae2d0ad12e1e889" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_InsularShelf/Kitchen_InsularShelf.usd", + "md5": "a49da1bfc6e37bd01281cfab53a1db07" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Basket.usd", + "md5": "f8bc8c813a5e3144cee2defa5033d285" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Bottle.usd", + "md5": "8c2270f49333f76090f3501116503742" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Bottle005.usd", + "md5": "a3fca2c1780a18c93be81797f84e5612" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Bottle006.usd", + "md5": "1cd533433e38781f93bfd2b62cf9176d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Bottle007.usd", + "md5": "740b801a655c55fdc60d457ae56cbfd2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Box.usd", + "md5": "739e336486ee391a9473c6fc40a66dc6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Box02.usd", + "md5": "c8f845a9d3470f46d0fb23dc73996df7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Box07.usd", + "md5": "4409f7ffbfe256dd97415e5d10b44673" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Disk001.usd", + "md5": "78c3f4c6e3e46ddeee321b97048abbba" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Disk002.usd", + "md5": "7a29ca0a09c2ebc02383b05984703703" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Flowers001.usd", + "md5": "2d915befbba1a3fdab5de5f0ee35ef73" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Flowers002.usd", + "md5": "32cfc55f8827b7eb3892b5fa326b46a4" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Hookrack001.usd", + "md5": "996ceae87fba18b7d85ef4bbe5db5fc3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_KnifeHolders001.usd", + "md5": "af06e5adb4450f134b8cae502122a37c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Orange001.usd", + "md5": "228b0b4f185d0dc0a06a8094678434d2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Orange002.usd", + "md5": "e8eaf9b1e9fbb9f6d7051e7ef5c7df75" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Paper.usd", + "md5": "b92a552fb40a525c153a98b58d3847bf" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_Shelf001.usd", + "md5": "ceb9a88871401f39c993b67dacd828c3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_bottle002.usd", + "md5": "ef7c26a64d1e0ea380cdc2f11a4c1c88" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_bottle003.usd", + "md5": "bf914d1d06c2bcd17273bceae407b115" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Other/Kitchen_bottle004.usd", + "md5": "15890c7b95a8412a74e81a81b7ec6315" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_TopCabinet/Kitchen_TopCabinet.usd", + "md5": "6e433ea3fb12444dced2c1618ff8162a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Kitchen_Wall001.usd", + "md5": "50ce8b96702cd3eae9ff93911f2f8518" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Microwave017/Microwave017.usd", + "md5": "eeb9336ca70563bffd261b746c4678ed" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Pot057/Pot057.usd", + "md5": "0e7d7f5e16e7500213f09693916caf77" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/RangeHood015/RangeHood015.usd", + "md5": "b46c0e04500d5130596c5c3cc73ba24b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Refrigerator001/Refrigerator001.usd", + "md5": "d1f26d8a72c664222af949d5bcedf601" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Sink054/Sink054.usd", + "md5": "aef6025b92fe9f4c436f8818cfd40df9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Stovetop012/Stovetop012.usd", + "md5": "c7fe82e0f736dc814a2c23fb966a2fb9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Table049/Table049.usd", + "md5": "2777a9a7418e094a8b291bcd01cd9f62" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/Toaster003/Toaster003.usd", + "md5": "3b7f38c6297ec495bbcede5c037bb354" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/WallStackOven004/WallStackOven004.usd", + "md5": "59c67a6937b03b2565a2dd26d3b384be" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/KitchenRoom/omniverse-content-production.s3.us-west-2.amazonaws.com/Assets/Extensions/Samples/Paint/cube.usd", + "md5": "98b82a85f10a1da65e15b55b6837f2b9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/MudGround/MudGround.usd", + "md5": "0b509e784fa5491e39201af2f1a9dd38" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/MudGround/tudi2/tudi2.usd", + "md5": "2dd552ac02b5de58b0f06cfe9b6d8d1a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/SLATEGround/Ground_stone.usd", + "md5": "f2e04ddf458fb351b2bcb9df9d23f6e3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/SLATEGround/SLATEGround.usd", + "md5": "b12cd5eeec5f3373f1336bd6be79b29f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/SnowGround/SnowGround.usd", + "md5": "cbde5465f97675116a3c1469c5222f76" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Locomotion/SnowGround/snow/Road/S_Modular_Snow_Road_uhpqdjvfa_lod3_Var1.usd", + "md5": "f9c9fc1122d0fe1db247eba98daf48b7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender001/Blender001.usd", + "md5": "0cc39532b2958c81690ae5ed4a8c2e84" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender002/Blender002.usd", + "md5": "5eae83fb5cd74bc13164ed1d766e92dc" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender003/Blender003.usd", + "md5": "f35913db71e679ca03f1bb35abc70af7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender004/Blender004.usd", + "md5": "22d346f0125e417f300173dabe9315c8" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender006/Blender006.usd", + "md5": "6357ad3ad04cf698e55ca65c6226c999" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender008/Blender008.usd", + "md5": "9d9eb0a92ce29c132a68c1e050993505" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender009/Blender009.usd", + "md5": "2311cef3b3b498ccc1cdd49d0f237549" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender010/Blender010.usd", + "md5": "d4617e4e0b8ed2f7c2d1b923b644c4aa" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender011/Blender011.usd", + "md5": "c000958f0c83bc9d7011409b39617dca" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender012/Blender012.usd", + "md5": "067d11b8e463de7bbfc25cf31d4ef67e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender013/Blender013.usd", + "md5": "7bc28cdf7810bc8160caa791f8ace782" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender014/Blender014.usd", + "md5": "752b9feb989c020f89101f6480e392ce" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Blender015/Blender015.usd", + "md5": "270db59ba31f6542897d1c86bca223b4" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine039/CoffeeMachine039.usd", + "md5": "f8684d08ec9bcdb834131a26d7883b51" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine041/CoffeeMachine041.usd", + "md5": "bf844a8ab8fb91763d445079d75fab16" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine044/CoffeeMachine044.usd", + "md5": "84411980100805565a1ff02894cd7238" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine045/CoffeeMachine045.usd", + "md5": "ad581c3ae0d5a1a4d779d6ab0376fd75" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine048/CoffeeMachine048.usd", + "md5": "d48795f7cd93972351df5667651522f9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine057/CoffeeMachine057.usd", + "md5": "e7a29deeb818117ff38bf0b2defb7624" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine059/CoffeeMachine059.usd", + "md5": "4c18183788047204622eccfb5d47806f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine060/CoffeeMachine060.usd", + "md5": "1261ae1379782ef8e7f8ca7a201f0721" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine064/CoffeeMachine064.usd", + "md5": "28b2327d1279bc0dfeff0dff4b700e88" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine067/CoffeeMachine067.usd", + "md5": "b566d4bd47e19f6cd6303114cd4e409b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine070/CoffeeMachine070.usd", + "md5": "894bdd240d771eeabcfbce6f64a3dd89" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine074/CoffeeMachine074.usd", + "md5": "a4b68210453e00e7bed1a84997f65fa5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine075/CoffeeMachine075.usd", + "md5": "4366385313468986f4241213beea4986" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine079/CoffeeMachine079.usd", + "md5": "8a9ef1b53fada9eeee42518a170168be" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine082/CoffeeMachine082.usd", + "md5": "6be5a5394e4f99100abbb65c112746cd" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine083/CoffeeMachine083.usd", + "md5": "3e7abadd45f1bc79a3fd554067229a5f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine086/CoffeeMachine086.usd", + "md5": "5ea4d72653675fa16ccaeb9910e8a7a1" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine087/CoffeeMachine087.usd", + "md5": "81322adb0923c8cc8623126616b73b6b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine090/CoffeeMachine090.usd", + "md5": "f1c735437201f1fbbdb560782d298d81" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine092/CoffeeMachine092.usd", + "md5": "99f511bfa7f214d648a0c727e159bd82" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine093/CoffeeMachine093.usd", + "md5": "eb2946c6f0d68ad8bc93abfb7a3ec674" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine094/CoffeeMachine094.usd", + "md5": "8db344c386826060daa281fca056138e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine099/CoffeeMachine099.usd", + "md5": "911012ebffe6125c7894a6b3234fc362" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine102/CoffeeMachine102.usd", + "md5": "8f2a997b2a3c1825471545664eeb8f21" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/CoffeeMachine103/CoffeeMachine103.usd", + "md5": "a9b426294094e58d761f7c45667a2112" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher032/Dishwasher032.usd", + "md5": "cc6bbf9c1fb3c3e33163974749fbf8d0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher036/Dishwasher036.usd", + "md5": "f64110f2202de7bd70db7fd0d9c6a125" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher039/Dishwasher039.usd", + "md5": "4d3d98891ae9fecc2b1410e57d394777" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher040/Dishwasher040.usd", + "md5": "33e08bf5ec94d27a2c685a97dce7411b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher042/Dishwasher042.usd", + "md5": "7c1b059179461086c04bbdbf8b86e048" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher043/Dishwasher043.usd", + "md5": "a136ff84b85ef98f6a370bbd837fa555" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher044/Dishwasher044.usd", + "md5": "beb0e1f848c02f3be948785adfb1541d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher048/Dishwasher048.usd", + "md5": "90e23037348217779d4ffe3662889dd2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher049/Dishwasher049.usd", + "md5": "adcbd297de853dde0fa1aff5a4594b95" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher051/Dishwasher051.usd", + "md5": "65dc71a6312829ea2c11aff5f20221d1" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher053/Dishwasher053.usd", + "md5": "eb717ef1a51e762ee7e35c7f93dbf4a0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher054/Dishwasher054.usd", + "md5": "6b3f299e1ebcbe325ca1e1920644af6f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Dishwasher059/Dishwasher059.usd", + "md5": "35acd825c2abcb086c9842ccf0b4f9d2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle001/ElectricKettle001.usd", + "md5": "ae9a19860119bb3c165f35fce237b34d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle002/ElectricKettle002.usd", + "md5": "4ab03a1e51e56dbeddef32ee2d5e901d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle003/ElectricKettle003.usd", + "md5": "a3679fbf13b9f8d718d22c467c786ea7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle004/ElectricKettle004.usd", + "md5": "5ea12531edeb13ac769490fde40bb390" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle005/ElectricKettle005.usd", + "md5": "0fc40d09c0506c98130f14440a774778" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle006/ElectricKettle006.usd", + "md5": "e0d3e30e28ac49e66ff98c52fcca2774" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle007/ElectricKettle007.usd", + "md5": "abf1616229a64a12b66ec9cb1fdea0e7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle008/ElectricKettle008.usd", + "md5": "aa5c6d52ba637c358eb97f6941f948b5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle009/ElectricKettle009.usd", + "md5": "6771085db37748b70092d5d1ead75e5e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle011/ElectricKettle011.usd", + "md5": "29c903ae384037a1b911daec6104bd0b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle013/ElectricKettle013.usd", + "md5": "5ef5a614daafd50801c020ff93ff99a4" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle014/ElectricKettle014.usd", + "md5": "0e0549b73a2159ae20e6b429ecc62a25" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ElectricKettle015/ElectricKettle015.usd", + "md5": "656ae5879ad75f5f8d6ee5f77e50d16a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave011/Microwave011.usd", + "md5": "ba024343a93bba673003d34c55c3459d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave031/Microwave031.usd", + "md5": "dc7afe4add54a47284fdab4034b1c5df" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave034/Microwave034.usd", + "md5": "20a73a41e5558942a0abf098c40d1bbc" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave035/Microwave035.usd", + "md5": "342e54337e312281f652373f70acb165" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave039/Microwave039.usd", + "md5": "da0b4e2c3a570f0bc8235c7beafb807c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave040/Microwave040.usd", + "md5": "bbcd42ee12cf8f1690e5170a47ab01b9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave041/Microwave041.usd", + "md5": "6d8c1b4f2eb590cf012ff3bc9aef7ad6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave043/Microwave043.usd", + "md5": "8abb738c3b69c569810f617e7ec4cca6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave044/Microwave044.usd", + "md5": "38a6ada42984980e6f4768bce8bf3e0a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave045/Microwave045.usd", + "md5": "a8b321227a7871f6a5ffc3e33c443d23" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave046/Microwave046.usd", + "md5": "042050fc4c66f5f8d54d61b0af63bd6f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave047/Microwave047.usd", + "md5": "b9b5f1d9c624c849aa6db91392b3a93f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave048/Microwave048.usd", + "md5": "6c31ec0dac76a2df4230c5ceca6d5063" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave049/Microwave049.usd", + "md5": "e5a4c79c5a128c78e034d002f1de5785" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave050/Microwave050.usd", + "md5": "a099fcbfe0bdf49a3adfa32d1bd24c94" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave052/Microwave052.usd", + "md5": "6b3ae95dc2658dca4e023d27085e3eea" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave053/Microwave053.usd", + "md5": "aeb665fee507b41857a6f74130bac1e0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave054/Microwave054.usd", + "md5": "fec5268c6efc96bcc9c4d71c648babce" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave055/Microwave055.usd", + "md5": "e56831d408ca218ff4a4a0aa964b0300" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave057/Microwave057.usd", + "md5": "1bdd7ac4b6dd7d0dbc0964db819d8443" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave058/Microwave058.usd", + "md5": "f2e843ce669714b82b18d40c5ddbc0e4" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave059/Microwave059.usd", + "md5": "b6ddc20e3f392ba6c6155cabc94f7f1e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave061/Microwave061.usd", + "md5": "b390d0b7ea31f1d54e80baa9354b0c23" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave062/Microwave062.usd", + "md5": "48a92269c86cd1cc85c8fe306a266d91" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Microwave064/Microwave064.usd", + "md5": "79d56bbcdbb08835fd3ebccc8ebd437c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven031/Oven031.usd", + "md5": "03a45aab808d551e3254521da3373604" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven032/Oven032.usd", + "md5": "4c8e59e7b0eb4f0b922e06451c85465d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven033/Oven033.usd", + "md5": "c84ab7e3eecffaec282669c210c2828b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven034/Oven034.usd", + "md5": "476fabfb08c4a956f012b3f18af53526" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven035/Oven035.usd", + "md5": "a5e369ec1347510d2d6e94fdb5ba8fed" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven036/Oven036.usd", + "md5": "279991b8d4564c9b31ae9df0f478f65d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven037/Oven037.usd", + "md5": "22a355447fec2f7dcfad88c44dd30ba6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven038/Oven038.usd", + "md5": "295563ce059c2960974e80490276033d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven039/Oven039.usd", + "md5": "1e87c169f26acd0cbaaaf494c9ebffc3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven040/Oven040.usd", + "md5": "5b599ca550d1a33651374dce38800043" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven041/Oven041.usd", + "md5": "586f1f62313ae44e4cf79c21c6e2a440" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Oven042/Oven042.usd", + "md5": "7c0659404a88c438a763e3f173e6ce7e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood006/RangeHood006.usd", + "md5": "382d3cdc48f4267f1f9a7bfd21994d03" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood008/RangeHood008.usd", + "md5": "b666c977354d23db79932ab79a257efd" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood009/RangeHood009.usd", + "md5": "772e88651faf55406e5875cfcdb2323b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood010/RangeHood010.usd", + "md5": "b0989a4bbc79dda3c1a663b6a6efd35b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood011/RangeHood011.usd", + "md5": "83df2675e557cd9aa6c3ff2018641c63" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood017/RangeHood017.usd", + "md5": "2407206d6e719b097c6238f2bcd581c6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood018/RangeHood018.usd", + "md5": "c754ee4819450a47fb6ce64ae3512daa" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood022/RangeHood022.usd", + "md5": "bf98f402858bb80b6ab9540505c35bfd" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood023/RangeHood023.usd", + "md5": "d4c2318c070b800291da04c33c5f6b38" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood027/RangeHood027.usd", + "md5": "68f68e5fccc22df46921630c037fb7b0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood028/RangeHood028.usd", + "md5": "d4e0a41925614c7170f4bbf46e88181c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/RangeHood029/RangeHood029.usd", + "md5": "b2c2134f12bd3c17f7ac17d2a6a6b675" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator031/Refrigerator031.usd", + "md5": "ae9367f5edced7097abff7edfff4a7fd" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator034/Refrigerator034.usd", + "md5": "71da3c39f22006b876fc21db3d50786c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator035/Refrigerator035.usd", + "md5": "3e483f3d5cbffbba663130c02c201223" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator036/Refrigerator036.usd", + "md5": "4a80fd72c9337c1d2979412d0e90da4c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator037/Refrigerator037.usd", + "md5": "c993aba0c95b961971a1728500827169" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator038/Refrigerator038.usd", + "md5": "8303ef2f88df5a78a0e7a163f928dbfc" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator039/Refrigerator039.usd", + "md5": "b274e0f24d8fd9673bdc9ee40822ae2d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator040/Refrigerator040.usd", + "md5": "4f2aafd67fcf49ecd1bd719285d438c6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator041/Refrigerator041.usd", + "md5": "10e9e9be4ebbfb7d2189160e3215a006" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator042/Refrigerator042.usd", + "md5": "9363f4d1b246159fe4adf7ba0bf45d96" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator043/Refrigerator043.usd", + "md5": "556281063de9b4e394e4a0fe7cdc6c6b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator044/Refrigerator044.usd", + "md5": "fbe9c863c44eb46604be47feb8293ab2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator045/Refrigerator045.usd", + "md5": "ef577fa29628d1c5f9feb74fa970b861" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator046/Refrigerator046.usd", + "md5": "63f32b829a07f34260205e9dbb153426" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator047/Refrigerator047.usd", + "md5": "3dd148be8025128ecf8c931bef72d983" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator048/Refrigerator048.usd", + "md5": "030f6e76ef0f588f5b43412ba0247332" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator049/Refrigerator049.usd", + "md5": "a64630ad7e8ad1bbe694ea676c580a58" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator050/Refrigerator050.usd", + "md5": "199b293edec3704484649946dee0b74e" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator051/Refrigerator051.usd", + "md5": "100d326f3b60e695731c27bb13a13231" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator052/Refrigerator052.usd", + "md5": "c241d8a7c849cb05a28b4ab42d9c7bb0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator053/Refrigerator053.usd", + "md5": "8fe8c5eec4c84996f7fa4050deab2650" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator054/Refrigerator054.usd", + "md5": "415ef83d7d53748f4ce505d0c144b7ec" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator055/Refrigerator055.usd", + "md5": "32632844fd52970eebeebe59b1ed7a50" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator056/Refrigerator056.usd", + "md5": "49491574f3d32e52453a303a9f8dde0c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Refrigerator057/Refrigerator057.usd", + "md5": "98fdceedabb13667821da906568eef52" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink001/Sink001.usd", + "md5": "946ffe579524331970d6cbcc3fc4e105" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink002/Sink002.usd", + "md5": "d4c9721137d6f5fbe7a6ca9e65147e45" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink003/Sink003.usd", + "md5": "6cae42229af8f928158b2793b2e682a2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink004/Sink004.usd", + "md5": "d8ff3996468c4305ce044c3fa7080526" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink006/Sink006.usd", + "md5": "9db5cad2e16db07304e5336d3efc1fb7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink007/Sink007.usd", + "md5": "041b8b966ea2d11e60d89f43405c3a6a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink008/Sink008.usd", + "md5": "2ce5c6ffd47405a156064c5249e20bc7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink009/Sink009.usd", + "md5": "3b606ee9c1d13f3bce7c332dbfaf9601" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink010/Sink010.usd", + "md5": "716ea9f83dc2ee013fddc1b2d64e9e7b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink011/Sink011.usd", + "md5": "8020eeb75ebfea7c686a3130b30617de" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink012/Sink012.usd", + "md5": "65cb6dcdf354ba23778bf3ac8a55234d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink013/Sink013.usd", + "md5": "51e57bac0d96a2a55bf4380634979806" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink014/Sink014.usd", + "md5": "bda7cafa483e3fa3be1b8015f95129a5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink015/Sink015.usd", + "md5": "974d01d384e132ab1213bd65c634667c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink016/Sink016.usd", + "md5": "9c07050740f02da9c01bc6aa65851cae" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink017/Sink017.usd", + "md5": "8032b65f4c178720f7c92c0c998b1fde" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink020/Sink020.usd", + "md5": "2043a04718d3d954438842485873d2a4" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink021/Sink021.usd", + "md5": "61efaf4fd828a44d2e1f171d1c7c0564" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink022/Sink022.usd", + "md5": "b44d6cf678cda5a9c27b4f32fb7ef8a9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink023/Sink023.usd", + "md5": "14ed5706ee7a93eefcdeab452a161412" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink025/Sink025.usd", + "md5": "06097c44958097b3468f2e4e952bb6f6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink047/Sink047.usd", + "md5": "9024a818969f002fa5c34f929499a8d2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink048/Sink048.usd", + "md5": "83ecf22108dad12d9a0fbc5bed2860d3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink054/Sink054.usd", + "md5": "3df7c1b4293d3a50843336e726266a22" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Sink060/Sink060.usd", + "md5": "662b70bef42407118db3fa955e1db650" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer003/StandMixer003.usd", + "md5": "eb81cbfa6d40beca6dc4946e61577fc9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer004/StandMixer004.usd", + "md5": "5ca668936a03eb7af5cf497783ebfa6a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer009/StandMixer009.usd", + "md5": "c7b61c5cf6551c521a9f2076d3b7f034" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer010/StandMixer010.usd", + "md5": "0686737497b6ea289e1d7c8ecef58a9d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer013/StandMixer013.usd", + "md5": "3236a6e0034a559b6d42d054eef79545" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer014/StandMixer014.usd", + "md5": "f12b85085a6aa9dec888500afc36d1e6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer015/StandMixer015.usd", + "md5": "a85b909c0823c2e9386ccf90c889e219" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer017/StandMixer017.usd", + "md5": "0e38ca89257527e029a1cf6f94be3334" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer020/StandMixer020.usd", + "md5": "67e62c2475e96e8f8a1c691ef0679bd9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer026/StandMixer026.usd", + "md5": "ff208c907e2386cb760d2b53edf701d8" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer029/StandMixer029.usd", + "md5": "93119bc0cba8a1f368d510572179967a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/StandMixer030/StandMixer030.usd", + "md5": "d49bce7c5b35babacabe938e7673504a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove001/Stove001.usd", + "md5": "810609f503ce3e2a2e1ccde13c1e571c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove002/Stove002.usd", + "md5": "6bef8892fe06c7ccde4bb45b8abff84f" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove028/Stove028.usd", + "md5": "527e5c362a1c8163a5cde22bcf8ad1ed" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove051/Stove051.usd", + "md5": "ca7093559d1535e18c20677ca872a421" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove063/Stove063.usd", + "md5": "dafbd18bdd3c1ebc6499ea1a2df6a85b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove066/Stove066.usd", + "md5": "38da3e6e893a03d87a027a2012af5cbe" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove068/Stove068.usd", + "md5": "dd4f6defc7f1557014694968d88dc684" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove070/Stove070.usd", + "md5": "dfdcc9c3103bf06e4fc5a3b3300b28d1" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove072/Stove072.usd", + "md5": "ce604ccdfc75c0b301f76d1e296ed1a2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stove074/Stove074.usd", + "md5": "50e60cc1307b85ea28f38d0d921ac4fa" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop002/Stovetop002.usd", + "md5": "b6dc44cedd9c172cf453da56eea03bc9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop005/Stovetop005.usd", + "md5": "35dadbc1ae44b4a7266c7acac57162ac" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop006/Stovetop006.usd", + "md5": "4c4a32b6fbbedf18743571cee6389ea0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop009/Stovetop009.usd", + "md5": "a8e7d03a64c599f24f648124a16b8e22" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop015/Stovetop015.usd", + "md5": "7bbc7ebf2919557f3d24b64234c25c87" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop019/Stovetop019.usd", + "md5": "4ada4279eb212be3b7f89748da09cade" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop022/Stovetop022.usd", + "md5": "bf0fab712e06d78ac5fff69072916ead" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Stovetop026/Stovetop026.usd", + "md5": "8fe371fd11fca4ab699f1e4ba1f42686" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster002/Toaster002.usd", + "md5": "71837e9df9e76ca4ad25f6d70d542a46" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster003/Toaster003.usd", + "md5": "1a1100caf19c24bf903a07ddfa484bf4" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster004/Toaster004.usd", + "md5": "f2b3a4d89b33e5ffce4a4f8f03432863" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster006/Toaster006.usd", + "md5": "1b211247e36abede6245599e1da3b6f0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster007/Toaster007.usd", + "md5": "3ed5bd14a21cce659fb7da419843be93" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster008/Toaster008.usd", + "md5": "7e1da308af8a69a92d471019f799e34a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster009/Toaster009.usd", + "md5": "0fd3afb9a11662888f802dd30fdbe684" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster010/Toaster010.usd", + "md5": "cf33a368c769bd5c9eed92ebbf6079c9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster012/Toaster012.usd", + "md5": "f433105cc44dcc5d6d5840db916c1ff5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster013/Toaster013.usd", + "md5": "f5c21671674dac37b5c72b9971ceb590" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster014/Toaster014.usd", + "md5": "2454385828daf661838fb62fe3b91ea2" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster015/Toaster015.usd", + "md5": "0e0c3ece887cd939066ea4a50a2b599c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster016/Toaster016.usd", + "md5": "3879e5fcd8fe1a52af5a8c1da954c0bf" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster017/Toaster017.usd", + "md5": "48650e35b6b7cbcecb12a26461470274" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster018/Toaster018.usd", + "md5": "524224abf5c602df6017de50c035716d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster019/Toaster019.usd", + "md5": "aa9e5802e17e1a20125c9ebd9ff2ab65" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster020/Toaster020.usd", + "md5": "61c0e8b41f2d544af917b1f36b2f224a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster022/Toaster022.usd", + "md5": "70ef4b8ebe9f53f4d60b0fb719b8b920" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster024/Toaster024.usd", + "md5": "c82c5583b22c48a5f0dd60338d0de863" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster026/Toaster026.usd", + "md5": "4d072fc0d9051a9ebac5bfcb6e0f7d91" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster028/Toaster028.usd", + "md5": "ad4d22975cd08c322141caa05b49efa7" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster029/Toaster029.usd", + "md5": "cdddfac1838fa7de401d5e191d88595a" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster031/Toaster031.usd", + "md5": "cfea71ee7a1fc212983c7c1e5e32af97" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster032/Toaster032.usd", + "md5": "1f765a22a18ce759adb2cf209a3d08c5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/Toaster033/Toaster033.usd", + "md5": "a242ef73293233a4c5c29174bcc43671" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven001/ToasterOven001.usd", + "md5": "e5f88315c83d6c718b2cd88c95e81014" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven002/ToasterOven002.usd", + "md5": "27948a9a6f24a8596bf68eaade88a8c0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven003/ToasterOven003.usd", + "md5": "de4cc5bb469ed00912cc671235001b71" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven004/ToasterOven004.usd", + "md5": "7ab14f6a66d28a983c34d257444f0941" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven005/ToasterOven005.usd", + "md5": "08bc9030ce04b6ee65ab68c5d39e17e6" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven006/ToasterOven006.usd", + "md5": "5d5261a7f8980459d5c52407fd5cdbd8" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven007/ToasterOven007.usd", + "md5": "9ab09d4cf78869b421c05d1afb7300cf" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven008/ToasterOven008.usd", + "md5": "201e6381c91fa7e04754147f7cb8c8eb" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven009/ToasterOven009.usd", + "md5": "1373f48f657571aa4a7387211d74584d" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven010/ToasterOven010.usd", + "md5": "f40ccc6a518f6d758f68714c64fe398b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven014/ToasterOven014.usd", + "md5": "077be700bdc66fcc8e0b1612e3e8660c" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven015/ToasterOven015.usd", + "md5": "b6152de2bea4ab8cabff67b85336e1d9" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven017/ToasterOven017.usd", + "md5": "5ab120ee56d58336519026404b7640fd" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven018/ToasterOven018.usd", + "md5": "5bcf9a5c02c0d6c82db37408f0a75811" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven023/ToasterOven023.usd", + "md5": "d1e632b3bdd0947b1632a7fbbfe9101b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven025/ToasterOven025.usd", + "md5": "5ade9183ee6271b570ed5f2c0ab4c576" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven035/ToasterOven035.usd", + "md5": "078050a60deee89048575f1caf4e57e3" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven038/ToasterOven038.usd", + "md5": "13908da8665b4cc682e5696685489bf0" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven054/ToasterOven054.usd", + "md5": "7cf83bb17014591784c0ddb8c4b733f5" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven056/ToasterOven056.usd", + "md5": "61c610bd7b0ef7e888bfa767f7e42914" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven057/ToasterOven057.usd", + "md5": "6d6b5f63a192a552714dcdc809886855" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven058/ToasterOven058.usd", + "md5": "28234a1f6f3fa89e2942180d7d10fffd" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven060/ToasterOven060.usd", + "md5": "4f83eaa10bceb46717608211f1324688" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven062/ToasterOven062.usd", + "md5": "455ea1082d812a1ade4e9b92ddcf7f4b" + }, + { + "path": "derived/lightwheel/Lightwheel_OpenSource/Manipulation/ToasterOven064/ToasterOven064.usd", + "md5": "1f1f35977e46d3c1b272ceb63210dc72" + } +] \ No newline at end of file diff --git a/docs/reproduction/public_download_control/lightwheel-prepare.log b/docs/reproduction/public_download_control/lightwheel-prepare.log new file mode 100644 index 0000000000000000000000000000000000000000..cf7ff77e7833526b7d6cd25092e14b43d766baf1 --- /dev/null +++ b/docs/reproduction/public_download_control/lightwheel-prepare.log @@ -0,0 +1 @@ +{"state": "extracted_needs_project_conversion_or_validation", "started_at": 1794696076.6780193, "runtime_ready": false, "files": 1329, "registry_checks_failed": [], "finished_at": 1794696133.3919177} diff --git a/docs/reproduction/public_download_control/lightwheel.files.json b/docs/reproduction/public_download_control/lightwheel.files.json new file mode 100644 index 0000000000000000000000000000000000000000..2b535f1241d8e0643abd9c8ead0b5f04540f4913 --- /dev/null +++ b/docs/reproduction/public_download_control/lightwheel.files.json @@ -0,0 +1,10 @@ +[ + { + "relative_path": "Lightwheel_OpenSource.zip", + "archive_type": "zip", + "url": "https://drive.usercontent.google.com/download?id=1S1W-vDNvsOOQU0qViEax_QS0zr0zGLfX&export=download&confirm=t", + "resolve": [ + "drive.usercontent.google.com:443:142.251.8.132" + ] + } +] \ No newline at end of file diff --git a/docs/reproduction/public_download_control/lightwheel.preparation.json b/docs/reproduction/public_download_control/lightwheel.preparation.json new file mode 100644 index 0000000000000000000000000000000000000000..8b5c5ee1cd24d4d986a973ed1a2c953d46e06526 --- /dev/null +++ b/docs/reproduction/public_download_control/lightwheel.preparation.json @@ -0,0 +1,8 @@ +{ + "state": "extracted_needs_project_conversion_or_validation", + "started_at": 1794696076.6780193, + "runtime_ready": false, + "files": 1329, + "registry_checks_failed": [], + "finished_at": 1794696133.3919177 +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/lightwheel.status.json b/docs/reproduction/public_download_control/lightwheel.status.json new file mode 100644 index 0000000000000000000000000000000000000000..e9dfc6f04bad6393362e8def6cfa833a18a142bb --- /dev/null +++ b/docs/reproduction/public_download_control/lightwheel.status.json @@ -0,0 +1,19 @@ +{ + "name": "lightwheel", + "hostname": "zp-nc67", + "pid": 2987423, + "started_at": 1794695622.1967118, + "state": "downloaded_needs_conversion_or_validation", + "downloaded": 1, + "verified": 1, + "bytes": 3409389226, + "errors": {}, + "destination": "/data/RPHomeGen/public_assets_20261115/archives", + "runtime_ready": false, + "conversion": "Extract original ZIP and preserve complete USD/MDL/texture tree; compare registered USD hashes and prepare Blender derivatives.", + "total": 1, + "expected_bytes": 0, + "updated_at": 1794696076.5861073, + "elapsed_seconds": 454.3904104232788, + "finished_at": 1794696076.5871222 +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/lightwheel.verified.jsonl b/docs/reproduction/public_download_control/lightwheel.verified.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..acf40ff622ad4b2e9db53d5b3effdf938afc9699 --- /dev/null +++ b/docs/reproduction/public_download_control/lightwheel.verified.jsonl @@ -0,0 +1 @@ +{"path": "Lightwheel_OpenSource.zip", "bytes": 3409389226, "sha256": "ef9466a045e9c6cafe566da08734892182b3e3bd39f5aba802f8d2277212260d", "verified_at": 1794696076.5859833} diff --git a/docs/reproduction/public_download_control/manifest.json b/docs/reproduction/public_download_control/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..37ea1e73500ba10c63e2e3564d132cb76ccfc21e --- /dev/null +++ b/docs/reproduction/public_download_control/manifest.json @@ -0,0 +1,21 @@ +{ + "host": "H200-1", + "jobs": [ + { + "name": "lightwheel", + "kind": "direct", + "destination": "archives", + "conversion": "Extract original ZIP and preserve complete USD/MDL/texture tree; compare registered USD hashes and prepare Blender derivatives.", + "files": [ + { + "relative_path": "Lightwheel_OpenSource.zip", + "archive_type": "zip", + "url": "https://drive.usercontent.google.com/download?id=1S1W-vDNvsOOQU0qViEax_QS0zr0zGLfX&export=download&confirm=t", + "resolve": [ + "drive.usercontent.google.com:443:142.251.8.132" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/polyhaven_models.conversion.json b/docs/reproduction/public_download_control/polyhaven_models.conversion.json new file mode 100644 index 0000000000000000000000000000000000000000..9611049eade9e9b2782295b92bd0eb8b91b75b32 --- /dev/null +++ b/docs/reproduction/public_download_control/polyhaven_models.conversion.json @@ -0,0 +1,205 @@ +{ + "state": "converted_pending_validation", + "started_at": 1794696905.7804468, + "pid": 3098835, + "host": "zp-nc67", + "runtime_ready": false, + "source_revision": "07e817247c213def01d20e0cf381eb52dac8210b", + "readme": "conversion_code/README.md#high-fidelity-asset-preprocessing", + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115", + "texture_aliases": [ + { + "asset_id": "gso:Orbit_Bubblemint_Mini_Bottle_6_ct", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Orbit_Bubblemint_Mini_Bottle_6_ct/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Orbit_Bubblemint_Mini_Bottle_6_ct/meshes/texture.png", + "md5": "07f3ebaf7985d6f36425cdd5bb2a68e8" + }, + { + "asset_id": "gso:Room_Essentials_Bowl_Turquiose", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Bowl_Turquiose/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Bowl_Turquiose/meshes/texture.png", + "md5": "9183bec281b08e30f74bb59f12b855af" + }, + { + "asset_id": "gso:Victor_Reversible_Bookend", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Victor_Reversible_Bookend/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Victor_Reversible_Bookend/meshes/texture.png", + "md5": "d7d3d6205907634d4a666b1612696917" + }, + { + "asset_id": "gso:Room_Essentials_Mug_White_Yellow", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Mug_White_Yellow/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Room_Essentials_Mug_White_Yellow/meshes/texture.png", + "md5": "42d3c604971e8b6e89e114b4d3ba2a51" + }, + { + "asset_id": "gso:HeavyDuty_Flashlight", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/HeavyDuty_Flashlight/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/HeavyDuty_Flashlight/meshes/texture.png", + "md5": "ca1afd0dc3cfe9c3e7f4a0691002d199" + }, + { + "asset_id": "gso:Rubbermaid_Large_Drainer", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Rubbermaid_Large_Drainer/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Rubbermaid_Large_Drainer/meshes/texture.png", + "md5": "7959494f0ae63c739496baeedbf35cf5" + }, + { + "asset_id": "gso:Threshold_Bamboo_Ceramic_Soap_Dish", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bamboo_Ceramic_Soap_Dish/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bamboo_Ceramic_Soap_Dish/meshes/texture.png", + "md5": "004caa4cb741534e25db3ea9f9ed0b04" + }, + { + "asset_id": "gso:Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14/meshes/texture.png", + "md5": "11df983119c7eba48fa4e5eb557b9022" + }, + { + "asset_id": "gso:Cole_Hardware_Mug_Classic_Blue", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Cole_Hardware_Mug_Classic_Blue/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Cole_Hardware_Mug_Classic_Blue/meshes/texture.png", + "md5": "cbfad6eaf876bc7cc69422b8671c402a" + }, + { + "asset_id": "gso:Threshold_Dinner_Plate_Square_Rim_White_Porcelain", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Dinner_Plate_Square_Rim_White_Porcelain/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Dinner_Plate_Square_Rim_White_Porcelain/meshes/texture.png", + "md5": "6eeee75d446e7fca58fe712819ce8f11" + }, + { + "asset_id": "gso:Razer_Taipan_Black_Ambidextrous_Gaming_Mouse", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_Taipan_Black_Ambidextrous_Gaming_Mouse/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_Taipan_Black_Ambidextrous_Gaming_Mouse/meshes/texture.png", + "md5": "4c345504448f5c0188f829c60df3d03e" + }, + { + "asset_id": "gso:Threshold_Bead_Cereal_Bowl_White", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bead_Cereal_Bowl_White/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Bead_Cereal_Bowl_White/meshes/texture.png", + "md5": "f30578d2d455b8022c1a3a95cb8928c9" + }, + { + "asset_id": "gso:Remington_TStudio_Hair_Dryer", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Remington_TStudio_Hair_Dryer/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Remington_TStudio_Hair_Dryer/meshes/texture.png", + "md5": "0cabe47fb99216c9d9e0bbd0e5a949bc" + }, + { + "asset_id": "gso:Diamond_Visions_Scissors_Red", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Diamond_Visions_Scissors_Red/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Diamond_Visions_Scissors_Red/meshes/texture.png", + "md5": "35fba1677af985fffeb63ea23c5dfa51" + }, + { + "asset_id": "gso:Sapota_Threshold_4_Ceramic_Round_Planter_Red", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sapota_Threshold_4_Ceramic_Round_Planter_Red/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Sapota_Threshold_4_Ceramic_Round_Planter_Red/meshes/texture.png", + "md5": "920e2b6dc547764b98d525749a86e44c" + }, + { + "asset_id": "gso:ACE_Coffee_Mug_Kristen_16_oz_cup", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/ACE_Coffee_Mug_Kristen_16_oz_cup/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/ACE_Coffee_Mug_Kristen_16_oz_cup/meshes/texture.png", + "md5": "b7225c11584cd1ba62765b49207be6e4" + }, + { + "asset_id": "gso:Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh/meshes/texture.png", + "md5": "fabdec0c721e420323da279226a7f2e8" + }, + { + "asset_id": "gso:Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc/meshes/texture.png", + "md5": "37f744aa881d26587220d2b3b0269750" + }, + { + "asset_id": "gso:Footed_Bowl_Sand", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Footed_Bowl_Sand/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Footed_Bowl_Sand/meshes/texture.png", + "md5": "0d6320abea89b09188507a41b58ee2cb" + }, + { + "asset_id": "gso:TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black/meshes/texture.png", + "md5": "c93f2163049ba9868afddfe50e4c049e" + }, + { + "asset_id": "gso:Threshold_Porcelain_Teapot_White", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Teapot_White/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Teapot_White/meshes/texture.png", + "md5": "af2663bea0506269ebf6cd8673e11026" + }, + { + "asset_id": "gso:Target_Basket_Medium", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Target_Basket_Medium/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Target_Basket_Medium/meshes/texture.png", + "md5": "a98a8da0e798f1171fffa5e28123db7b" + }, + { + "asset_id": "gso:Threshold_Porcelain_Pitcher_White", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Pitcher_White/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Threshold_Porcelain_Pitcher_White/meshes/texture.png", + "md5": "895ddc8a291ad18f9c582014bd33c5ab" + }, + { + "asset_id": "gso:Shurtape_Tape_Purple_CP28", + "source": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Shurtape_Tape_Purple_CP28/materials/textures/texture.png", + "alias": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/canonical/gso/Shurtape_Tape_Purple_CP28/meshes/texture.png", + "md5": "0b46fd06deeb78f67a807daaebaa90d4" + } + ], + "command": [ + "/data/RPHomeGen/public_assets_20261115/conversion_env/bin/python", + "/data/RPHomeGen/public_assets_20261115/conversion_code/scripts/preprocess_high_fidelity_assets.py", + "--asset-root", + "/data/RPHomeGen/public_assets_20261115/conversion_managed_inputs", + "--output", + "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115", + "--base-index", + "/data/RPHomeGen/nas_mirror/zhf/rp_robohavengen/asset_library/registry/asset_index.sqlite3", + "--stage", + "convert", + "--sources", + "gso,polyhaven", + "--blender", + "/data/rhg-wqz/runtime/4764ef211238289e78b85817e44f05e148969d8c510f45c14c5c2bd8d78443fd/blender", + "--usd-python", + "/data/RPHomeGen/public_assets_20261115/conversion_env/bin/python", + "--blender-batch-size", + "24", + "--usd-batch-size", + "128", + "--release-workers", + "4" + ], + "transferred_files_verified": 265, + "exit_code": 0, + "report": { + "schema_version": "1.0", + "created_at": "2026-11-14T22:55:20.446991+00:00", + "stage": "convert", + "plan": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/preprocess_plan.json", + "counts": { + "ready": 56 + }, + "duration_s": 7.039, + "release": null + }, + "counts": { + "ready": 32 + }, + "failed_items": [], + "name": "polyhaven_models", + "finished_at": 1794696920.5194395, + "count": 32, + "technical_check": { + "passed": 32, + "total": 32, + "report": "/data/RPHomeGen/public_assets_20261115/control/readme-conversion-technical-check.json" + } +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/prepare_archives.py b/docs/reproduction/public_download_control/prepare_archives.py new file mode 100644 index 0000000000000000000000000000000000000000..199e73488cf024f548754d879990511673a3e018 --- /dev/null +++ b/docs/reproduction/public_download_control/prepare_archives.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Unpack public asset sources and verify registered pre-conversion payloads.""" +import argparse +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import shutil +import subprocess +import tarfile +import time +import zipfile + + +def dump(path, value): + temp = path.with_suffix('.tmp.json') + temp.write_text(json.dumps(value, indent=2)) + temp.replace(path) + + +def target_for(root, name): + rel = PurePosixPath(name) + if rel.is_absolute() or '..' in rel.parts or '\\' in name or ':' in name: + raise ValueError('Unsafe archive path: ' + name) + dest = root.joinpath(*rel.parts) + if not dest.resolve().is_relative_to(root.resolve()): + raise ValueError('Archive path escapes destination') + return dest + + +def extract_tar(stream, root): + count = 0 + for member in stream: + target = target_for(root, member.name) + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + elif member.isfile(): + target.parent.mkdir(parents=True, exist_ok=True) + if target.exists() and target.stat().st_size == member.size: + count += 1 + continue + temp = target.with_name(target.name + '.extract-partial') + with stream.extractfile(member) as src, temp.open('wb') as dst: + shutil.copyfileobj(src, dst) + temp.replace(target) + count += 1 + else: + raise ValueError('Unsupported archive link or special entry: ' + member.name) + return count + + +def md5(path): + h = hashlib.md5() + with path.open('rb') as stream: + for b in iter(lambda: stream.read(4 * 1024 * 1024), b''): + h.update(b) + return h.hexdigest() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--root', default='/data/RPHomeGen/public_assets_20261115') + parser.add_argument('--mode', choices=['molmospaces', 'gso', 'ycb', 'lightwheel', 'replicacad'], required=True) + parser.add_argument('--checks') + args = parser.parse_args() + root = Path(args.root) + progress = root / 'control' / (args.mode + '.preparation.json') + state = dict(state='waiting_for_download', started_at=time.time(), runtime_ready=False, files=0) + dump(progress, state) + try: + while True: + source = root / 'control' / (args.mode + '.status.json') + status = json.loads(source.read_text()) if source.exists() else {} + if status.get('state') == 'downloaded_needs_conversion_or_validation': + break + if status.get('state') in ('incomplete', 'failed'): + raise RuntimeError('Download is incomplete; archive preparation deferred') + time.sleep(10) + state['state'] = 'extracting' + dump(progress, state) + destination = Path(status['destination']) + if args.mode == 'molmospaces': + for archive in destination.rglob('*.tar'): + packed = root / 'derived/molmospaces/packages' / archive.relative_to(destination).parent + with tarfile.open(archive) as stream: + state['files'] += extract_tar(stream, packed) + for package in packed.glob('*.tar.zst'): + unpacked = root / 'derived/molmospaces/unpacked' / archive.relative_to(destination).parents[1] / package.name.removesuffix('.tar.zst') + with subprocess.Popen(['zstd', '-dc', str(package)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process: + with tarfile.open(fileobj=process.stdout, mode='r|') as stream: + state['files'] += extract_tar(stream, unpacked) + error = process.stderr.read().decode(errors='replace') + if process.wait(): + raise RuntimeError(error) + state['updated_at'] = time.time() + dump(progress, state) + elif args.mode in ('gso', 'lightwheel', 'replicacad'): + archives = list(destination.glob('*/*.zip')) if args.mode == 'gso' else [destination / ('Lightwheel_OpenSource.zip' if args.mode == 'lightwheel' else 'ReplicaCAD_dataset_v1.4.zip')] + for archive in archives: + unpacked = root / ('derived/gso/' + archive.parent.name if args.mode == 'gso' else 'derived/' + args.mode) + with zipfile.ZipFile(archive) as stream: + for member in stream.infolist(): + target = target_for(unpacked, member.filename) + if member.is_dir(): + target.mkdir(parents=True, exist_ok=True) + continue + if (member.external_attr >> 16) & 0o170000 == 0o120000: + raise ValueError('Archive symlink is unsupported') + target.parent.mkdir(parents=True, exist_ok=True) + with stream.open(member) as src, target.open('wb') as dst: + shutil.copyfileobj(src, dst) + state['files'] += 1 + if args.mode == 'replicacad': + configs = list(unpacked.rglob('replicaCAD.scene_dataset_config.json')) + if len(configs) != 1: + raise ValueError('Original ReplicaCAD root is ambiguous') + source = configs[0].parent + output = root / 'assets/high_quality/ReplicaCAD_dataset_v1.4' + shutil.copytree(source, output, dirs_exist_ok=True, copy_function=os.link) + elif args.mode == 'ycb': + for archive in destination.glob('*.tgz'): + with tarfile.open(archive) as stream: + state['files'] += extract_tar(stream, root / 'derived/ycb/models') + if args.checks: + failed = [] + for item in json.loads(Path(args.checks).read_text()): + path = root / item['path'] + if not path.is_file() or md5(path) != item['md5']: + failed.append(str(path)) + state['registry_checks_failed'] = failed + if failed: + raise ValueError('Registered original payload checksum mismatch') + state.update(state='extracted_needs_project_conversion_or_validation', finished_at=time.time()) + except Exception as exc: + state.update(state='failed', error=str(exc), finished_at=time.time()) + dump(progress, state) + print(json.dumps(state), flush=True) + raise SystemExit(int(state['state'] == 'failed')) + + +if __name__ == '__main__': + main() diff --git a/docs/reproduction/public_download_control/readme-conversion-controller.log b/docs/reproduction/public_download_control/readme-conversion-controller.log new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/reproduction/public_download_control/readme-conversion-resource-check.json b/docs/reproduction/public_download_control/readme-conversion-resource-check.json new file mode 100644 index 0000000000000000000000000000000000000000..b44571f1a91e291795b5e06ffa21e716880eb764 --- /dev/null +++ b/docs/reproduction/public_download_control/readme-conversion-resource-check.json @@ -0,0 +1,394 @@ +[ + { + "asset_id": "polyhaven:CoffeeCart_01", + "mesh_count": 3, + "collision_count": 3, + "texture_count": 16, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:GothicBed_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:Shelf_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:WetFloorSign_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:all_purpose_cleaner", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:anthurium_botany_01", + "mesh_count": 6, + "collision_count": 6, + "texture_count": 7, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:bleach_bottle", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:book_encyclopedia_set_01", + "mesh_count": 20, + "collision_count": 20, + "texture_count": 14, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:boombox", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 14, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:cardboard_box_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:ceiling_fan", + "mesh_count": 2, + "collision_count": 2, + "texture_count": 11, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:classic_laptop", + "mesh_count": 3, + "collision_count": 3, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:coffee_table_round_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:desk_lamp_arm_01", + "mesh_count": 27, + "collision_count": 27, + "texture_count": 17, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:dining_chair_02", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:dining_table", + "mesh_count": 2, + "collision_count": 2, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:drawer_cabinet", + "mesh_count": 5, + "collision_count": 5, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:electric_stove", + "mesh_count": 19, + "collision_count": 19, + "texture_count": 18, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:football", + "mesh_count": 2, + "collision_count": 2, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:gamepad", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:hand_truck", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:industrial_storage_cart", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:modern_arm_chair_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 16, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:modern_wooden_cabinet", + "mesh_count": 3, + "collision_count": 3, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:round_wooden_table_01", + "mesh_count": 2, + "collision_count": 2, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:sofa_02", + "mesh_count": 2, + "collision_count": 2, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:steel_frame_shelves_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:wicker_basket_01", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:wine_bottles_01", + "mesh_count": 4, + "collision_count": 4, + "texture_count": 82, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:wooden_crate_01", + "mesh_count": 3, + "collision_count": 3, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:wooden_stool_02", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [] + }, + { + "asset_id": "polyhaven:wooden_table_02", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [] + }, + { + "asset_id": "gso:ACE_Coffee_Mug_Kristen_16_oz_cup", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Cole_Hardware_Mug_Classic_Blue", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Diamond_Visions_Scissors_Red", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Footed_Bowl_Sand", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:HeavyDuty_Flashlight", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Orbit_Bubblemint_Mini_Bottle_6_ct", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Razer_Taipan_Black_Ambidextrous_Gaming_Mouse", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Remington_TStudio_Hair_Dryer", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Room_Essentials_Bowl_Turquiose", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Room_Essentials_Mug_White_Yellow", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Rubbermaid_Large_Drainer", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Sapota_Threshold_4_Ceramic_Round_Planter_Red", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Shurtape_Tape_Purple_CP28", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Target_Basket_Medium", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Threshold_Bamboo_Ceramic_Soap_Dish", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Threshold_Bead_Cereal_Bowl_White", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Threshold_Dinner_Plate_Square_Rim_White_Porcelain", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Threshold_Porcelain_Pitcher_White", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Threshold_Porcelain_Teapot_White", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + }, + { + "asset_id": "gso:Victor_Reversible_Bookend", + "mesh_count": 1, + "collision_count": 1, + "texture_count": 0, + "missing_resources": [] + } +] \ No newline at end of file diff --git a/docs/reproduction/public_download_control/readme-conversion-technical-check.json b/docs/reproduction/public_download_control/readme-conversion-technical-check.json new file mode 100644 index 0000000000000000000000000000000000000000..0d92bef8b6ae8da7c7a10dce188479b8c8d6bc58 --- /dev/null +++ b/docs/reproduction/public_download_control/readme-conversion-technical-check.json @@ -0,0 +1,737 @@ +{ + "scope": "USD reopen, mesh, collision, texture bindings, dependencies and finite bounds", + "visual_acceptance": false, + "runtime_ready": false, + "results": [ + { + "asset_id": "polyhaven:CoffeeCart_01", + "passed": true, + "mesh_count": 3, + "collision_count": 3, + "texture_count": 16, + "missing_resources": [], + "dimensions": [ + 2.167636811733246, + 1.0732900500297546, + 1.7176724136807024 + ] + }, + { + "asset_id": "polyhaven:GothicBed_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.493751883506775, + 2.0399999022483826, + 1.5338402975614969 + ] + }, + { + "asset_id": "polyhaven:Shelf_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.003443717956543, + 0.2569795063869833, + 2.080310344696045 + ] + }, + { + "asset_id": "polyhaven:WetFloorSign_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 0.3000548481941223, + 0.3585093021392822, + 0.6295440040994436 + ] + }, + { + "asset_id": "polyhaven:all_purpose_cleaner", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 0.1568227931857109, + 0.11741002649068832, + 0.3197317017838941 + ] + }, + { + "asset_id": "polyhaven:anthurium_botany_01", + "passed": true, + "mesh_count": 6, + "collision_count": 6, + "texture_count": 7, + "missing_resources": [], + "dimensions": [ + 2.7951389849185944, + 1.7977479249238968, + 0.4911389034241438 + ] + }, + { + "asset_id": "polyhaven:bleach_bottle", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 0.08839113637804985, + 0.06121089309453964, + 0.2937394976615906 + ] + }, + { + "asset_id": "polyhaven:book_encyclopedia_set_01", + "passed": true, + "mesh_count": 20, + "collision_count": 20, + "texture_count": 14, + "missing_resources": [], + "dimensions": [ + 0.5512974252924323, + 0.16306233406066895, + 0.23741818653931634 + ] + }, + { + "asset_id": "polyhaven:boombox", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 14, + "missing_resources": [], + "dimensions": [ + 0.7237796187400818, + 0.18646465986967087, + 0.47010064125061035 + ] + }, + { + "asset_id": "polyhaven:cardboard_box_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 0.38702359795570374, + 0.5158704221248627, + 0.3417995572090149 + ] + }, + { + "asset_id": "polyhaven:ceiling_fan", + "passed": true, + "mesh_count": 2, + "collision_count": 2, + "texture_count": 11, + "missing_resources": [], + "dimensions": [ + 1.4629170894622803, + 1.4629170894622803, + 0.516343355178833 + ] + }, + { + "asset_id": "polyhaven:classic_laptop", + "passed": true, + "mesh_count": 3, + "collision_count": 3, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 0.6519346237182617, + 0.4859423041343689, + 0.5428108389023691 + ] + }, + { + "asset_id": "polyhaven:coffee_table_round_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.3013009428977966, + 1.3013015985488892, + 0.4910094439983368 + ] + }, + { + "asset_id": "polyhaven:desk_lamp_arm_01", + "passed": true, + "mesh_count": 27, + "collision_count": 27, + "texture_count": 17, + "missing_resources": [], + "dimensions": [ + 0.9561862349510193, + 0.7343336641788483, + 1.3366849422454834 + ] + }, + { + "asset_id": "polyhaven:dining_chair_02", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 0.4335707724094391, + 0.5764201134443283, + 0.9733776897192001 + ] + }, + { + "asset_id": "polyhaven:dining_table", + "passed": true, + "mesh_count": 2, + "collision_count": 2, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 2.255895972251892, + 1.3902360200881958, + 0.876989221200347 + ] + }, + { + "asset_id": "polyhaven:drawer_cabinet", + "passed": true, + "mesh_count": 5, + "collision_count": 5, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.1410778760910034, + 0.48808444291353226, + 1.881253957748413 + ] + }, + { + "asset_id": "polyhaven:electric_stove", + "passed": true, + "mesh_count": 19, + "collision_count": 19, + "texture_count": 18, + "missing_resources": [], + "dimensions": [ + 0.8918229341506958, + 0.90467569231987, + 1.3884786069393158 + ] + }, + { + "asset_id": "polyhaven:football", + "passed": true, + "mesh_count": 2, + "collision_count": 2, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 0.5088775902986526, + 0.2221573293209076, + 0.22188469767570496 + ] + }, + { + "asset_id": "polyhaven:gamepad", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 0.4040517807006836, + 0.4349614977836609, + 0.018924321746453643 + ] + }, + { + "asset_id": "polyhaven:hand_truck", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 0.5932528674602509, + 0.6925271153450012, + 1.40251275151968 + ] + }, + { + "asset_id": "polyhaven:industrial_storage_cart", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.6033486723899841, + 1.1027454733848572, + 1.3773844093084335 + ] + }, + { + "asset_id": "polyhaven:modern_arm_chair_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 16, + "missing_resources": [], + "dimensions": [ + 0.8203444182872772, + 0.9865616858005524, + 1.0228520567470696 + ] + }, + { + "asset_id": "polyhaven:modern_wooden_cabinet", + "passed": true, + "mesh_count": 3, + "collision_count": 3, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 2.4400004148483276, + 0.5200000107288361, + 0.6801425069570541 + ] + }, + { + "asset_id": "polyhaven:round_wooden_table_01", + "passed": true, + "mesh_count": 2, + "collision_count": 2, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.3993489742279053, + 1.3993489146232605, + 1.0050213932991028 + ] + }, + { + "asset_id": "polyhaven:sofa_02", + "passed": true, + "mesh_count": 2, + "collision_count": 2, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.8071673512458801, + 0.8177513778209686, + 0.7094889283180237 + ] + }, + { + "asset_id": "polyhaven:steel_frame_shelves_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.0974148511886597, + 0.5021176338195801, + 2.1405010361922905 + ] + }, + { + "asset_id": "polyhaven:wicker_basket_01", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 0.3832242637872696, + 0.29501520097255707, + 0.11742293369024992 + ] + }, + { + "asset_id": "polyhaven:wine_bottles_01", + "passed": true, + "mesh_count": 4, + "collision_count": 4, + "texture_count": 82, + "missing_resources": [], + "dimensions": [ + 0.6763246953487396, + 0.08056290075182915, + 0.331367195234634 + ] + }, + { + "asset_id": "polyhaven:wooden_crate_01", + "passed": true, + "mesh_count": 3, + "collision_count": 3, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 0.8252729177474976, + 0.4089537411928177, + 0.3496182831004262 + ] + }, + { + "asset_id": "polyhaven:wooden_stool_02", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 6, + "missing_resources": [], + "dimensions": [ + 0.2651771306991577, + 0.18312730640172958, + 0.18192848344915546 + ] + }, + { + "asset_id": "polyhaven:wooden_table_02", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 8, + "missing_resources": [], + "dimensions": [ + 1.13441663980484, + 0.7060248255729675, + 0.7995428870490286 + ] + }, + { + "asset_id": "gso:ACE_Coffee_Mug_Kristen_16_oz_cup", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.12632200121879578, + 0.13493600559559127, + 0.09062400087714198 + ] + }, + { + "asset_id": "gso:Cole_Hardware_Mug_Classic_Blue", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.1656619980931282, + 0.09476900136633051, + 0.12553999945521357 + ] + }, + { + "asset_id": "gso:Diamond_Visions_Scissors_Red", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.07666200026869774, + 0.014597000368667115, + 0.20956899970769882 + ] + }, + { + "asset_id": "gso:Footed_Bowl_Sand", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.16092800348997116, + 0.10883899885811846, + 0.16154299676418307 + ] + }, + { + "asset_id": "gso:HeavyDuty_Flashlight", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.0775969997048378, + 0.22920500696636736, + 0.07788499817252165 + ] + }, + { + "asset_id": "gso:Mens_ASV_Billfish_Boat_Shoe_in_Tan_Leather_wmUJ5PbwANc", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.10844000056385994, + 0.10585499860826536, + 0.28664499521255493 + ] + }, + { + "asset_id": "gso:Orbit_Bubblemint_Mini_Bottle_6_ct", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.21040599793195724, + 0.11940900368426813, + 0.0695769973099232 + ] + }, + { + "asset_id": "gso:Razer_BlackWidow_Stealth_2014_Keyboard_07VFzIVabgh", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.47208599746227264, + 0.09354099770280305, + 0.24570799618959427 + ] + }, + { + "asset_id": "gso:Razer_Taipan_Black_Ambidextrous_Gaming_Mouse", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.12254299968481064, + 0.040171999542508316, + 0.17452599853277206 + ] + }, + { + "asset_id": "gso:Remington_TStudio_Hair_Dryer", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.33000800013542175, + 0.08965000317857635, + 0.25134599208831787 + ] + }, + { + "asset_id": "gso:Room_Essentials_Bowl_Turquiose", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.1568870022892952, + 0.08256600304775932, + 0.1572210043668747 + ] + }, + { + "asset_id": "gso:Room_Essentials_Mug_White_Yellow", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.13683799654245377, + 0.10479399856194507, + 0.10219100117683413 + ] + }, + { + "asset_id": "gso:Rubbermaid_Large_Drainer", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.33929599821567535, + 0.12066300153128406, + 0.4423470050096512 + ] + }, + { + "asset_id": "gso:Sapota_Threshold_4_Ceramic_Round_Planter_Red", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.10599099844694138, + 0.09713699998792438, + 0.10955400019884112 + ] + }, + { + "asset_id": "gso:Shurtape_Tape_Purple_CP28", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.11814500018954277, + 0.050197999443526015, + 0.11704000085592271 + ] + }, + { + "asset_id": "gso:Sterilite_Caddy_Blue_Sky_17_58_x_12_58_x_9_14", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.3157079964876175, + 0.2344150069038734, + 0.4465889930725098 + ] + }, + { + "asset_id": "gso:Target_Basket_Medium", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.270455002784729, + 0.21750700353368307, + 0.26802599430084234 + ] + }, + { + "asset_id": "gso:Threshold_Bamboo_Ceramic_Soap_Dish", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.1246579997241497, + 0.05063099991093625, + 0.09807400032877923 + ] + }, + { + "asset_id": "gso:Threshold_Bead_Cereal_Bowl_White", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.16976100206375122, + 0.0707239969451621, + 0.16632499545812607 + ] + }, + { + "asset_id": "gso:Threshold_Dinner_Plate_Square_Rim_White_Porcelain", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.27096399664878845, + 0.038908001151867266, + 0.2735399901866913 + ] + }, + { + "asset_id": "gso:Threshold_Porcelain_Pitcher_White", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.23888199776411057, + 0.2784459873873857, + 0.16879899799823767 + ] + }, + { + "asset_id": "gso:Threshold_Porcelain_Teapot_White", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.18668599426746368, + 0.13634500352418405, + 0.18425899744033816 + ] + }, + { + "asset_id": "gso:TriStar_Products_PPC_Power_Pressure_Cooker_XL_in_Black", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.31186600029468536, + 0.3297270011289585, + 0.2937870025634767 + ] + }, + { + "asset_id": "gso:Victor_Reversible_Bookend", + "passed": true, + "mesh_count": 1, + "collision_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.2349410057067871, + 0.23643099937248735, + 0.10890099778771406 + ] + } + ], + "passed": 56, + "total": 56 +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/readme-conversion-textures-controller.log b/docs/reproduction/public_download_control/readme-conversion-textures-controller.log new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/reproduction/public_download_control/readme-conversion.log b/docs/reproduction/public_download_control/readme-conversion.log new file mode 100644 index 0000000000000000000000000000000000000000..11afa6fe80b42ea7a722837910e98d23bf523d36 --- /dev/null +++ b/docs/reproduction/public_download_control/readme-conversion.log @@ -0,0 +1,11 @@ +{ + "schema_version": "1.0", + "created_at": "2026-11-14T22:55:20.446991+00:00", + "stage": "convert", + "plan": "/data/RPHomeGen/public_assets_20261115/derived/readme_high_fidelity_textures_v2_20261115/preprocess_plan.json", + "counts": { + "ready": 56 + }, + "duration_s": 7.039, + "release": null +} diff --git a/docs/reproduction/public_download_control/readme_asset_conversion.py b/docs/reproduction/public_download_control/readme_asset_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5e3096075aa62ad8fbb24d296fd9748cb43f72 --- /dev/null +++ b/docs/reproduction/public_download_control/readme_asset_conversion.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Run the documented GSO/Poly Haven converter against verified local inputs.""" +import collections +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +ROOT = Path('/data/RPHomeGen/public_assets_20261115') +CONTROL = ROOT / 'control' +CODE = ROOT / 'conversion_code' +OUTPUT = ROOT / 'derived/readme_high_fidelity_textures_v2_20261115' +BLENDER = '/data/rhg-wqz/runtime/4764ef211238289e78b85817e44f05e148969d8c510f45c14c5c2bd8d78443fd/blender' +PYTHON = str(ROOT / 'conversion_env/bin/python') + + +def write(path, data): + temp = path.with_suffix('.tmp.json') + temp.write_text(json.dumps(data, indent=2)) + temp.replace(path) + + +def md5(path): + h = hashlib.md5() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def main(): + started = time.time() + names = ['gso', 'polyhaven_models'] + state = dict(state='verifying_conversion_inputs', started_at=started, pid=os.getpid(), + host=os.uname().nodename, runtime_ready=False, source_revision='07e817247c213def01d20e0cf381eb52dac8210b', + readme='conversion_code/README.md#high-fidelity-asset-preprocessing', output=str(OUTPUT)) + + def publish(): + for name in names: + write(CONTROL / (name + '.conversion.json'), dict(state, name=name)) + + publish() + try: + manifest = json.load(open(CONTROL / 'conversion-source-manifest.json')) + for job in manifest['jobs']: + source = ROOT / 'conversion_inputs' / job['destination'] + for item in job['files']: + path = source / item['relative_path'] + if not path.is_file() or path.stat().st_size != item['size'] or md5(path) != item['md5']: + raise ValueError('Transferred source differs from registry: ' + str(path)) + managed = ROOT / 'conversion_managed_inputs' + gso = managed / 'raw/gso_fuel_collection_full/collection-2022-06-13-snapshot-20260828/archives' + poly = managed / 'raw/polyhaven_models_full_2k/api-models-20260828-2k/models' + gso.mkdir(parents=True, exist_ok=True) + poly.mkdir(parents=True, exist_ok=True) + for path in (ROOT / 'conversion_inputs/assets/high_quality/GSO-fuel').glob('*/*.zip'): + target = gso / path.name + if not target.exists(): + os.link(path, target) + for path in (ROOT / 'conversion_inputs/assets/polyhaven').iterdir(): + target = poly / path.name + if path.is_dir() and not target.exists(): + target.symlink_to(path, target_is_directory=True) + helper = Path('/data/tutu/robohomegen/generic_20261101/snap_paper_20261110/engine/source/scripts/internal/scene_generation/real_assets/prepare_gso_source_assets.py') + spec = importlib.util.spec_from_file_location('project_gso_source', helper) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + aliases = [] + for archive in gso.glob('*.zip'): + working = OUTPUT / 'canonical/gso' / archive.stem + module.extract_source_archive(archive, working) + texture = working / 'materials/textures/texture.png' + alias = working / 'meshes/texture.png' + shutil.copyfile(texture, alias) + if md5(texture) != md5(alias): + raise ValueError('GSO texture alias differs from the original') + aliases.append(dict(asset_id='gso:' + archive.stem, source=str(texture), alias=str(alias), md5=md5(alias))) + state['texture_aliases'] = aliases + command = [PYTHON, str(CODE / 'scripts/preprocess_high_fidelity_assets.py'), + '--asset-root', str(managed), '--output', str(OUTPUT), + '--base-index', '/data/RPHomeGen/nas_mirror/zhf/rp_robohavengen/asset_library/registry/asset_index.sqlite3', + '--stage', 'convert', '--sources', 'gso,polyhaven', '--blender', BLENDER, + '--usd-python', PYTHON, '--blender-batch-size', '24', '--usd-batch-size', '128', + '--release-workers', '4'] + state.update(state='converting', command=command, transferred_files_verified=sum(len(j['files']) for j in manifest['jobs'])) + publish() + env = dict(os.environ, CUDA_VISIBLE_DEVICES='', NVIDIA_VISIBLE_DEVICES='none', + OMP_NUM_THREADS='4', OPENBLAS_NUM_THREADS='4', MKL_NUM_THREADS='4') + with (CONTROL / 'readme-conversion.log').open('w') as log: + result = subprocess.run(command, cwd=CODE, env=env, stdout=log, stderr=subprocess.STDOUT) + state['exit_code'] = result.returncode + report = OUTPUT / 'preprocess_report.json' + if report.exists(): + state['report'] = json.loads(report.read_text()) + plan = OUTPUT / 'preprocess_plan.json' + if plan.exists(): + items = json.loads(plan.read_text())['items'] + state['counts'] = dict(collections.Counter(i['status'] for i in items)) + state['failed_items'] = [i for i in items if i['status'] != 'ready'] + for name, source in [('gso', 'gso_zip_obj'), ('polyhaven_models', 'polyhaven_usd')]: + selected = [i for i in items if i['source_kind'] == source] + data = dict(state, name=name, finished_at=time.time(), count=len(selected), + counts=dict(collections.Counter(i['status'] for i in selected))) + data['state'] = 'converted_pending_validation' if result.returncode == 0 and selected and all(i['status'] == 'ready' for i in selected) else 'conversion_failed' + write(CONTROL / (name + '.conversion.json'), data) + else: + raise RuntimeError('Documented converter did not write a plan; inspect readme-conversion.log') + except Exception as exc: + state.update(state='conversion_failed', error=str(exc), finished_at=time.time()) + publish() + raise + + +if __name__ == '__main__': + main() diff --git a/docs/reproduction/public_download_control/worker.log b/docs/reproduction/public_download_control/worker.log new file mode 100644 index 0000000000000000000000000000000000000000..712606ec8137d195aca1d7fcd63beb4790bbb954 --- /dev/null +++ b/docs/reproduction/public_download_control/worker.log @@ -0,0 +1 @@ +{"name": "lightwheel", "hostname": "zp-nc67", "pid": 2987423, "started_at": 1794695622.1967118, "state": "downloaded_needs_conversion_or_validation", "downloaded": 1, "verified": 1, "bytes": 3409389226, "destination": "/data/RPHomeGen/public_assets_20261115/archives", "runtime_ready": false, "conversion": "Extract original ZIP and preserve complete USD/MDL/texture tree; compare registered USD hashes and prepare Blender derivatives.", "total": 1, "expected_bytes": 0, "updated_at": 1794696076.5861073, "elapsed_seconds": 454.3904104232788, "finished_at": 1794696076.5871222} diff --git a/docs/reproduction/public_download_control/ycb-003_cracker_box.log b/docs/reproduction/public_download_control/ycb-003_cracker_box.log new file mode 100644 index 0000000000000000000000000000000000000000..9dde4e002a4289c0cf5fa155ecdd00f79555e75f --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-003_cracker_box.log @@ -0,0 +1,9 @@ +{ + "schema_version": "1.0", + "source": "/data/RPHomeGen/public_assets_20261115/conversion_inputs/derived/ycb/models/003_cracker_box/google_16k/textured.obj", + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/003_cracker_box/asset.usdc", + "converter": "blender", + "dependencies_copied": 0, + "scoring_allowed": false, + "qa_status": "CONVERTED_VISUAL_ONLY" +} diff --git a/docs/reproduction/public_download_control/ycb-005_tomato_soup_can.log b/docs/reproduction/public_download_control/ycb-005_tomato_soup_can.log new file mode 100644 index 0000000000000000000000000000000000000000..f73c1100b9d8ce515a925b7e57691de05ca61272 --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-005_tomato_soup_can.log @@ -0,0 +1,9 @@ +{ + "schema_version": "1.0", + "source": "/data/RPHomeGen/public_assets_20261115/conversion_inputs/derived/ycb/models/005_tomato_soup_can/google_16k/textured.obj", + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/005_tomato_soup_can/asset.usdc", + "converter": "blender", + "dependencies_copied": 0, + "scoring_allowed": false, + "qa_status": "CONVERTED_VISUAL_ONLY" +} diff --git a/docs/reproduction/public_download_control/ycb-006_mustard_bottle.log b/docs/reproduction/public_download_control/ycb-006_mustard_bottle.log new file mode 100644 index 0000000000000000000000000000000000000000..022a92929c2f32dc15a3813610ac49766b8f2e93 --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-006_mustard_bottle.log @@ -0,0 +1,9 @@ +{ + "schema_version": "1.0", + "source": "/data/RPHomeGen/public_assets_20261115/conversion_inputs/derived/ycb/models/006_mustard_bottle/google_16k/textured.obj", + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/006_mustard_bottle/asset.usdc", + "converter": "blender", + "dependencies_copied": 0, + "scoring_allowed": false, + "qa_status": "CONVERTED_VISUAL_ONLY" +} diff --git a/docs/reproduction/public_download_control/ycb-025_mug.log b/docs/reproduction/public_download_control/ycb-025_mug.log new file mode 100644 index 0000000000000000000000000000000000000000..7f1ad0011cff4c430f7bd70e5b82a78b84def1a1 --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-025_mug.log @@ -0,0 +1,9 @@ +{ + "schema_version": "1.0", + "source": "/data/RPHomeGen/public_assets_20261115/conversion_inputs/derived/ycb/models/025_mug/google_16k/textured.obj", + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/025_mug/asset.usdc", + "converter": "blender", + "dependencies_copied": 0, + "scoring_allowed": false, + "qa_status": "CONVERTED_VISUAL_ONLY" +} diff --git a/docs/reproduction/public_download_control/ycb-035_power_drill.log b/docs/reproduction/public_download_control/ycb-035_power_drill.log new file mode 100644 index 0000000000000000000000000000000000000000..b355655111a57bf82733c6c15a38765551f19309 --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-035_power_drill.log @@ -0,0 +1,9 @@ +{ + "schema_version": "1.0", + "source": "/data/RPHomeGen/public_assets_20261115/conversion_inputs/derived/ycb/models/035_power_drill/google_16k/textured.obj", + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/035_power_drill/asset.usdc", + "converter": "blender", + "dependencies_copied": 0, + "scoring_allowed": false, + "qa_status": "CONVERTED_VISUAL_ONLY" +} diff --git a/docs/reproduction/public_download_control/ycb-author-jobs.json b/docs/reproduction/public_download_control/ycb-author-jobs.json new file mode 100644 index 0000000000000000000000000000000000000000..95c733a6de5ad547f6c968c2a83d48fcbfcddb02 --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-author-jobs.json @@ -0,0 +1 @@ +[{"asset_id": "ycb:003_cracker_box", "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/003_cracker_box/asset.usdc", "canonical_path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/003_cracker_box/asset.usdc"}, {"asset_id": "ycb:005_tomato_soup_can", "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/005_tomato_soup_can/asset.usdc", "canonical_path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/005_tomato_soup_can/asset.usdc"}, {"asset_id": "ycb:006_mustard_bottle", "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/006_mustard_bottle/asset.usdc", "canonical_path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/006_mustard_bottle/asset.usdc"}, {"asset_id": "ycb:025_mug", "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/025_mug/asset.usdc", "canonical_path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/025_mug/asset.usdc"}, {"asset_id": "ycb:035_power_drill", "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/035_power_drill/asset.usdc", "canonical_path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/035_power_drill/asset.usdc"}] \ No newline at end of file diff --git a/docs/reproduction/public_download_control/ycb-author-results.json b/docs/reproduction/public_download_control/ycb-author-results.json new file mode 100644 index 0000000000000000000000000000000000000000..e14131c571dfd5cca39181e4df96baf630f4cac9 --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-author-results.json @@ -0,0 +1,42 @@ +[ + { + "asset_id": "ycb:003_cracker_box", + "collision_mesh_count": 1, + "mesh_count": 1, + "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/003_cracker_box/asset.usdc", + "repaired_texture_dependencies": [], + "status": "authored" + }, + { + "asset_id": "ycb:005_tomato_soup_can", + "collision_mesh_count": 1, + "mesh_count": 1, + "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/005_tomato_soup_can/asset.usdc", + "repaired_texture_dependencies": [], + "status": "authored" + }, + { + "asset_id": "ycb:006_mustard_bottle", + "collision_mesh_count": 1, + "mesh_count": 1, + "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/006_mustard_bottle/asset.usdc", + "repaired_texture_dependencies": [], + "status": "authored" + }, + { + "asset_id": "ycb:025_mug", + "collision_mesh_count": 1, + "mesh_count": 1, + "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/025_mug/asset.usdc", + "repaired_texture_dependencies": [], + "status": "authored" + }, + { + "asset_id": "ycb:035_power_drill", + "collision_mesh_count": 1, + "mesh_count": 1, + "path": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115/035_power_drill/asset.usdc", + "repaired_texture_dependencies": [], + "status": "authored" + } +] diff --git a/docs/reproduction/public_download_control/ycb-author.log b/docs/reproduction/public_download_control/ycb-author.log new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/docs/reproduction/public_download_control/ycb-conversion-technical-check.json b/docs/reproduction/public_download_control/ycb-conversion-technical-check.json new file mode 100644 index 0000000000000000000000000000000000000000..4db15996365bffdbce12511aa80b08a80edc7b4e --- /dev/null +++ b/docs/reproduction/public_download_control/ycb-conversion-technical-check.json @@ -0,0 +1,68 @@ +{ + "passed": 5, + "total": 5, + "visual_acceptance": false, + "runtime_ready": false, + "results": [ + { + "asset_id": "ycb:003_cracker_box", + "mesh_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.07180000096559525, + 0.2134370065759868, + 0.1640360057353974 + ], + "passed": true + }, + { + "asset_id": "ycb:005_tomato_soup_can", + "mesh_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.06791100092232227, + 0.10185500085208334, + 0.06774300336837771 + ], + "passed": true + }, + { + "asset_id": "ycb:006_mustard_bottle", + "mesh_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.0971979983150959, + 0.19130100682377815, + 0.0666210008785129 + ], + "passed": true + }, + { + "asset_id": "ycb:025_mug", + "mesh_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.11698400229215622, + 0.08130299916956575, + 0.09313100017607213 + ], + "passed": true + }, + { + "asset_id": "ycb:035_power_drill", + "mesh_count": 1, + "texture_count": 1, + "missing_resources": [], + "dimensions": [ + 0.1842070035636425, + 0.05729300039820377, + 0.1875149980187416 + ], + "passed": true + } + ] +} \ No newline at end of file diff --git a/docs/reproduction/public_download_control/ycb.conversion.json b/docs/reproduction/public_download_control/ycb.conversion.json new file mode 100644 index 0000000000000000000000000000000000000000..67d3ab473fe9704fd461dcf9104c8ecb1e4e4158 --- /dev/null +++ b/docs/reproduction/public_download_control/ycb.conversion.json @@ -0,0 +1,25 @@ +{ + "name": "ycb", + "host": "zp-nc67", + "pid": 3106526, + "state": "converted_pending_validation", + "runtime_ready": false, + "started_at": 1794697006.719182, + "count": 5, + "counts": { + "ready": 5, + "failed": 0 + }, + "output": "/data/RPHomeGen/public_assets_20261115/derived/readme_ycb_20261115", + "readme": "README.md:316 scripts/convert_asset.py", + "source_revision": "07e817247c213def01d20e0cf381eb52dac8210b", + "finished_at": 1794697015.6858437, + "errors": [], + "usd_author_exit_code": 0, + "plan": "/data/RPHomeGen/public_assets_20261115/control/ycb-author-jobs.json", + "technical_check": { + "passed": 5, + "total": 5, + "report": "/data/RPHomeGen/public_assets_20261115/control/ycb-conversion-technical-check.json" + } +} \ No newline at end of file diff --git "a/docs/reproduction/\350\265\204\344\272\247\346\270\205\347\202\271\344\270\216\346\240\274\345\274\217\350\275\254\346\215\242_20261119.md" "b/docs/reproduction/\350\265\204\344\272\247\346\270\205\347\202\271\344\270\216\346\240\274\345\274\217\350\275\254\346\215\242_20261119.md" new file mode 100644 index 0000000000000000000000000000000000000000..6e84163c38053484e1782360ee0b08edc5dba78c --- /dev/null +++ "b/docs/reproduction/\350\265\204\344\272\247\346\270\205\347\202\271\344\270\216\346\240\274\345\274\217\350\275\254\346\215\242_20261119.md" @@ -0,0 +1,1255 @@ +# 资产清点:位置、目录、标签与格式转换 + +**目录** + +- [0. 项目根目录与简称](#roots) +- [1. 资产总览](#overview) +- [2. 资产清单](#inventory):[公开数据集](#inv-public) · [非公开与受限资产](#inv-restricted) · [项目衍生件](#inv-derived) · [索引与标注](#inv-index) · [检索库指向的文件](#inv-targets) · [生成场景](#inv-scenes) +- [3. 目录结构](#trees):[总体布局](#tree-layout) · [公开数据集](#tree-public) · [资产库](#tree-lib) · [非公开资产](#tree-render-assets) · [项目衍生件](#tree-derived) · [11-15 转换件](#tree-pub) · [生成场景](#tree-scenes) +- [4. 富文本标签](#tags):[生成方式与位置](#tags-source) · [属性记录格式](#tags-record) · [全库矩阵](#tags-corpus) · [关键词表](#tags-keywords) · [检索索引](#tags-index) · [8 字段基础标注](#tags-8fields) +- [5. 格式转换](#conversions):[总表](#conv-summary) · [T0](#t0) · [T1](#t1) · [T2](#t2) · [T3](#t3) · [T4](#t4) · [T5](#t5) · [T6](#t6) · [T7](#t7) · [T8](#t8) · [T9](#t9) · [T10](#t10) · [T11](#t11) · [T12](#t12) · [T13](#t13) · [T14](#t14) · [T15](#t15)不同T值代表不同的格式转换方式 +- [6. 注意事项](#notes) + +--- + + + +## 0. 项目根目录与简称 + +| 简称 | 项目 | 根目录(主机:路径;下文脚本路径都相对于此) | 说明文档 | +| ------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| RHG | RoboHouseGen 仓库,以 README 固定提交 `07e817247c213def01d20e0cf381eb52dac8210b` 为准 | H200-1 `/data/RPHomeGen/public_assets_20261115/conversion_code/`(只抽取了 `README.md`、`configs/`、`docs/`、`packages/`、`scripts/` 的一部分) | `README.md`、`docs/official-mdl-pipeline.md`、`docs/prepared_asset_pool.md`、`docs/asset-bundle-setup.md`。本机副本在 `~/RoboHomeGen/rphome_scripts/asset_downloads_20261115/conversion_reference/` | +| TREE | RoboHome 主分支代码树(candidate19,config F) | H200-1 `/data/RPHomeGen/candidate19_replay_20261115_1647/tree/` | `README.md` 只列了环境变量(如 `RHG_MDL_SDK_ROOT`、`RHG_PREPARED_MATERIAL_INDEX`),没有讲转换脚本 | +| AUDIT | 资产审计与修复 v1(2026-10-13) | NAS `/mnt/nas-h/zhf/rhg_asset_audit_20261013_v1/`;H200-1 镜像 `/data/RPHomeGen/nas_mirror/zhf/rhg_asset_audit_20261013_v1/` | 无 README,脚本都在根目录;汇总在 `release/summary.json` | +| REPAIR2 | 资产修复 v2(2026-10-13) | NAS `/mnt/nas-h/zhf/rhg_asset_repair_20261013_v2/`(H200-1 镜像只有一部分) | 只有 `release/USAGE.txt`;脚本在根目录 | +| STYLE | MDL 离线烘焙与材质验收 | NAS `/mnt/nas-h/zhf/rhg_style_joint_20261013/` | 无 | +| PUB | 2026-11-15 公开资产重新下载 | 各服务器 `/data/RPHomeGen/public_assets_20261115/` | 回执与驱动脚本在 `control/` | +| LIB | 资产库根(主分支的 `RHG_LIBRARY_ROOT`) | NAS `/mnt/nas-h/zhf/rp_robohavengen/asset_library/`;H200-1 镜像 `/data/RPHomeGen/nas_mirror/zhf/rp_robohavengen/asset_library/` | `registry/` | +| DATA | RoboHouseGenData(公开数据原件) | NAS `/mnt/nas-h/wyc/90_incoming/zp-nc576-data-root-20260901/wyc2/RoboHouseGenData/` | LIB 的 `models/robohousegen` 软链到 `DATA/assets` | + +--- + + + +## 1. 资产总览 + +大小按 `du` 计(1G = 1024³ 字节)。 + +| 类别 | 大小 | 文件数 | 主要内容 | 详见 | +|---|---:|---:|---|---| +| 公开数据集原件 | 43.4G | 112,692 | HSSD 13.1G、InteriorAgent 13.3G、ArtVIP 9.0G、Lightwheel 4.9G、MolmoSpaces 1.3G、Poly Haven 1.1G(含补充材质)、GSO/ReplicaCAD/YCB/ambientCG 共 0.8G | [2.1](#inv-public) | +| 非公开与受限资产 | 45.1G | 9,571 | 室内 Blender 材质库 36.2G、厨房模型与 PBR 5.2G、HDRI 天空 3.2G、Poliigon 0.5G | [2.2](#inv-restricted) | +| 项目衍生件 | 131.5G | — | AUDIT 85.6G(其中 HSSD 上游原版副本 34.5G)、STYLE MDL 烘焙件 23.4G、11-15 转换与解包 11.1G、REPAIR2 10.2G、法线缓存 1.1G | [2.3](#inv-derived) | +| 索引与标注 | 42.9G | — | artifact 缓存 12.5G、全库检索矩阵 9.9G、家具可用性 7.9G、检索索引与属性发布记录 5.9G、正面审计 3.7G、8 字段标注与注释索引 1.4G、风格属性 1.2G、资产池 0.3G | [2.4](#inv-index)、[4](#tags) | +| 主分支生成场景 | 61.4G | 43,070 | 60 次尝试,产出 55 个场景 | [2.6](#inv-scenes) | +| **合计** | **约 324G** | | | | + +| 条目 | 数量 | +|---|---| +| 主分支检索库条目 | 37,279:对象 29,577、材质 3,728、片段 3,288、房间/整场景 680、灯光 6 | +| 其中直接用原件 / 用修复或转换件 | 19,552 / 17,727([2.5](#inv-targets)) | +| 公开数据来源 | 10 个:HSSD、ArtVIP、InteriorAgent、Lightwheel、MolmoSpaces、ReplicaCAD、YCB、GSO、Poly Haven、ambientCG | +| 带富文本标签的对象 | 29,577 个有属性记录;其中风格 24,102、颜色 24,102、材质外观 24,105、形状描述 24,656;关键词 244,694 条([4](#tags)) | +| 格式转换与修复工序 | 16 道([5](#conversions)) | + +--- + + + +## 2. 资产清单 + + + +### 2.1 公开数据集 + +“11-15 重下载”一列指 PUB 下的位置,已逐文件校验(回执:`control/*.verified.jsonl`、`*.status.json`)。服务器直连 Hugging Face 不通,实际经 `hf-mirror.com` 下载同一 commit,再按上游 SHA-256 或 Git blob SHA-1 校验。 + +| 数据集 | 固定版本 / 来源 | 许可 | 原件格式 | 原件位置(DATA 下) | 11-15 重下载 | 检索库条目 | 转换 | +|---|---|---|---|---|---|---|---| +| HSSD | HF `hssd/hssd-hab` @ `4369cb9876214c7fbebcf552eb532380e4d287e4`。T4 用的未压缩版本:HF `hssd/hssd-models` @ `208ea6bc22d863bbc1cbaef1829b3e646600dfb6` | CC BY-NC 4.0 | GLB(几何压缩,贴图为 KTX2,`KHR_texture_basisu`)、URDF、support-surfaces、metadata | `assets/high_quality/hssd-hab/`,14G | H200-2 `assets/high_quality/hssd-hab/`,75,560 文件,12.07 GB | 18,228 | T4、T5 | +| ArtVIP | HF `X-Humanoid/ArtVIP` @ `d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e` | Apache-2.0 | USD + MDL + 贴图 | `ArtVIP/`,9.2G | H20-96-2,5,250 文件,9.69 GB | 2,152 | T6、T7、T8、T11 | +| InteriorAgent | HF `spatialverse/InteriorAgent` @ `ac599fe2d2285ed0ddfafb70ba56e489462e0650` | 仅限非商业研究与教育;禁止再分发(含部分);需引用 | USD/USDA + MDL + 贴图 + HDR,25 套房屋 | `InteriorAgent/`,14G | H20-96-3,13,471 文件,14.21 GB | 6,174 | T6、T7、T8、T11 | +| Lightwheel SimReady | 官方 GitHub `LightwheelAI/Lightwheel-simready-asset` 指向的 Google Drive 文件 `1S1W-vDNvsOOQU0qViEax_QS0zr0zGLfX`(`Lightwheel_OpenSource.zip`) | CC BY-NC 4.0 | USD + MDL + 贴图 | `Lightwheel-simready-c5f0feec/`,4.9G | H200-1 zip 3.41 GB,解包为 1,329 文件 | 378 | T0、T6、T8、T11 | +| MolmoSpaces(curated) | HF `allenai/MolmoSpaces` @ `5f802a46816ffc3520e59b5ef49fa8dafee8eeca`,两个分片:`isaac/objects/thor/20260128/shards/00000.tar`、`isaac/scenes/ithor/20260121/shards/00000.tar` | ODC-By 1.0 / CC BY 4.0 | 外层 TAR,内含每个资产一个 `.tar.zst`,解开后是 USDA/USDC | `MolmoSpaces-isaac-curated/`,1.3G | H20-96-1,1.33 GB,解包为 13,663 文件 | 5,841 + 502 | T10 | +| ReplicaCAD | 官方 `ReplicaCAD_dataset_v1.4.zip` | CC BY 4.0 | GLB + URDF + 配置 | `ReplicaCAD_dataset_v1.4/`,143M | H20-96-4,134 MB,600 文件 | 185 | T0 | +| YCB | 官方 S3 上 5 个 `google_16k.tgz`:003_cracker_box、005_tomato_soup_can、006_mustard_bottle、025_mug、035_power_drill | CC BY 4.0 | OBJ/MTL/PNG,另有 DAE、PLY、STL | `YCB-google-16k/`,132M | H20-96-4,48 MB | 5 | T0、T1 | +| GSO | Gazebo Fuel `GoogleResearch` 下 24 个模型 zip | CC BY 4.0 | zip 内为 OBJ/MTL/PNG + SDF | `GSO-fuel/`,405M | H20-96-4,129 MB,264 文件 | 24 | T0、T1、T2、T3 | +| Poly Haven | `dl.polyhaven.org`(URL 与 MD5 取自项目索引) | CC0 | 模型为 2k USDC + `textures/`(本身已是 Z-up、米制);材质为 `.blend`;HDRI 为 `.hdr` | `assets/polyhaven/`,783M | H20-96-4,241 文件,0.82 GB | 45 | T1、T2、T7 | +| Poly Haven 补充材质 | 7 个材质,共 42 个文件(`polyhaven_gap_fill_20261005/manifest.json`,含 SHA-256) | CC0 | PBR 贴图 + MTLX | LIB `materials/polyhaven_gap_fill_20261005/` | H20-96-4,0.33 GB | — | 无 | +| ambientCG | 17 个材质,如 PlasteredWall、Tiles139/141、Wood092 | CC0 | 官方 USDC 材质 + JPG 贴图 | DATA `third_party/SceneSmith/data/materials/`;LIB `materials/scenesmith_original/`(167 MB) | 未重下 | 17 | 无(T12、T13 处理的是室内材质库里的 ambientCG 图集) | + + + +### 2.2 非公开与受限资产 + +下表的 LIB 路径都是软链,实际文件在 NAS `/mnt/nas-h/zhf/rp_robohavengen/render_assets/`(目录树见第 3.4 节)。 + +| 资产 | 位置 | 大小 / 文件数 | 格式 | 来源与许可 | 转换 | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------- | +| 室内 Blender 材质库 | LIB `materials/interior_blender_20261009/` | 38.87 GB / 8,686 | 按中文类目(`01室内常用/`、`02特色与工业风/`、`03辅助细节/`)组织的 `.blend` 材质、`pack_*.blenddata`;贴图在 `资源依赖/{large,small}/`;索引为 `material_assets.jsonl`、`manifest.json` | 混合来源,其中注册了一批 ambientCG 图集;找不到能还原全部文件的公开包,不公开 | 检索库收 3,728 个 `.blend` 材质,直接使用。ambientCG 图集的法线在生成时做 T12。AUDIT 做过 T13,主分支没用 | +| 厨房模型 | LIB `models/kitchen_upload_20261005` → `render_assets/pbr_kitchen_20261005_003251/kitchen` | 1.18 GB / 263 | 上传的 ZIP、FBX/OBJ、3ds Max/Corona/V-Ray 文件 | 来源不明;目录与命名是 Poliigon 的打包格式(第 3.4 节),按第三方商业素材处理,不公开 | 无记录 | +| 厨房 PBR(含植物模型) | LIB `materials/pbr_upload_20261005/` | 4.40 GB / 456 | 按中文类别组织,如 `木纹/`、`植物/` | 来源不明;同为 Poliigon 打包格式,部分目录带淘宝店铺/公众号说明文件,按第三方商业素材处理,不公开 | 5 个植物 FBX 做过 T9,主分支没用 | +| Poliigon 补充材质 | LIB `materials/poliigon_supplement_20261005/` | 0.51 GB / 41 | 4 个商品下载包 | 商业授权,不公开 | 无 | +| HDRI 天空 | LIB `hdri/sky_collection_20261004_234305/` | 3.45 GB / 125 | 分级目录的 HDR 贴图 | PG Skies 商业资源,另有 VizPeople 的免费和非商用天空;不公开,公开版改用 Poly Haven CC0 HDRI | 无 | +| NVIDIA MDL 材质 | AUDIT `repairs/mdl/{isaacsim_core/{Base,mdl,Ue4,VRay,Blender,Nonvisual,Volume}, 2023_1, 2023_2_1}`;REPAIR2 `downloads/nvidia/Materials/…` | <0.1 GB | `.mdl` + 贴图 | NVIDIA Isaac Sim / Omniverse 材质,禁止再分发 | 用作 MDL 搜索路径;T7 改写过其中 4 个 MDL 的贴图路径 | + + + +### 2.3 项目衍生件 + +| 目录 | 大小 / 文件数 | 内容 | 来自 | 主分支是否引用 | +| ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- | --------------------------------------------------------------------- | -------- | ----------------------------- | +| AUDIT `repairs/hssd_originals/208ea6bc…/` | 35G | HSSD 未压缩官方版本(`hssd-models`)的副本 | T4 的输入 | 否 | +| AUDIT `repairs/hssd_restored/` | 33G / 10,940 | 贴图还原后的 HSSD GLB | T4 | 是:检索库 10,683 条,55 个场景用到 262 个 | +| AUDIT `repairs/hssd_original_variants/` | 404M / 186 | 官方原版 GLB(18 个物体、168 个房屋外壳),只改 MIME 元数据 | T5 | 是:16 条 | +| AUDIT `repairs/hssd_json_metadata_fixed/` | 587M / 196 | 删除空扩展数组后的 GLB | T5 | 是:194 条 | +| AUDIT `repairs/gso/` | 31M / 24 | 贴图路径改正后的 GSO USD | T3 | 是:22 条 | +| AUDIT `repairs/usd_dependency_paths/` | 2.3G / 958(957 个 USD 层) | 依赖路径改正后的 USD 层 | T6 | 是:820 条 | +| AUDIT `repairs/molmo_extracted/` | 3.3G | MolmoSpaces 逐个资产解包后的 USD | T10 | 是:5,841 条 | +| AUDIT `repairs/objects/thor/` | 1,275 个目录软链 | MolmoSpaces 依赖命名空间,软链指向 `molmo_extracted/`(H200-1 镜像里软链被展开成实际文件,870M) | T10 | 否 | +| AUDIT `repairs/mdl/` | 5.3M | NVIDIA MDL 搜索路径副本 | T6 的依赖来源 | 是(MDL 搜索路径) | +| AUDIT `repairs/ambientcg/` | 4.2G | 重新下载的 ambientCG 官方包 | T13 | 否 | +| AUDIT `repairs/interior_materials/` | 22M | `official_metal_materials.blend` | T13 | 否 | +| REPAIR2 `repairs/usd/` | 23M / 34 | 精确修复的 USD 层 | T7 | 是:30 条 | +| REPAIR2 `repairs/mdl/` | 16K / 4 | 改写了贴图路径的 MDL | T7 | 随 T7 | +| REPAIR2 `repairs/variants/` | 437M / 133 | 用替代材质的功能变体 USD | T8 | 是:116 条 | +| REPAIR2 `repairs/plants/` | 599M / 41 | 植物 FBX 的修复版 `.blend` 与 `.usdc` | T9 | 否 | +| STYLE `mdl_offline_assets_c15/bake_cache/` | 12G | MDL 烘焙出的线性 EXR 通道,以及 `request.json`、`result.json` | T11 | 是:55 个场景用到 49 个文件 | +| STYLE `mdl_offline_assets_c15/material_libraries/` | 12G | 打包的 Blender 材质库 `materials.blend` + `manifest.json` | T11 | 是:8 个文件 | +| H200-1 槽位缓存 `…/caches/s*/material_catalog/normal_dx_to_gl/`(candidate19 的 s00–s02;`hayfung/paper_runs/caches` 的 s00、s03–s05、s09–s11) | 55 个场景引用 402 个文件,1.11G | OpenGL 法线 `normal_gl.png` + 回执 `conversion.json` | T12 | 是 | +| PUB `derived/readme_high_fidelity_textures_v2_20261115/`(H200-1) | 1.1G | GSO 24 个 + Poly Haven 32 个规范 USD | T2 | 否(只做了技术检查) | +| PUB `derived/readme_high_fidelity_20261115/`(H200-1) | 698M | T2 第一次运行,GSO 贴图没有绑定,已作废 | T2 | 否 | +| PUB `derived/readme_ycb_20261115/`(H200-1) | 42M | YCB 5 个 USD | T1 | 否 | +| PUB `derived/lightwheel/Lightwheel_OpenSource`(H200-1) | 4.9G | Lightwheel 解包 | T0 | 否 | +| PUB `derived/molmospaces/{packages,unpacked}`(H20-96-1) | — | MolmoSpaces 两级解包 | T10 | 否 | +| DATA `assets/high_quality/GSO-fuel/usd/` | 24 个 `.usdc` + manifest | 上游的 GSO 转换件 | T1 | 是:2 条 | +| DATA `assets/high_quality/YCB-google-16k/models/{003_cracker_box,006_mustard_bottle}/textured.usd` | 2 个 + manifest | 上游的 YCB 转换件 | T1 | 是:2 条 | +| DATA `assets/converted/cardboard_box_01.usdc` | 1 个 + manifest | 上游的 Poly Haven USD 复制件 | T1 | 是:1 条 | +| LIB `runtime_derivatives/stable_real_assets_v1/` | 58 个文件,95M | 3 个 GSO 的 GLB 与原始包 | T14 | 否 | + + + +### 2.4 索引与标注(不涉及格式转换) + +| 内容 | 位置 | 大小 | 说明 | +|---|---|---|---| +| 检索/外观索引 `full_matrix_reviewed_compatibility.sqlite3` | H200-1 `/data/tutu/robohomegen/scene_evidence_repair_20261103/` | 830M | 37,279 条资产描述与标签;表 `asset_descriptors` 的 `canonical_path` 指向第 2.5 节所列的文件;标签见[第 4.5 节](#tags-index) | +| 属性发布记录 `records.jsonl` | 同上目录下 `front_probe/published/review_1793688076267784737/` | 732M | 29,577 个对象的 14 个属性字段(风格、颜色、材质外观、形状等),主分支读取;格式见[第 4.2 节](#tags-record) | +| 全库检索矩阵 `full_corpus/` | H200-1 `/data/tutu/robohomegen/wholehome_style_sets_20261030/full_corpus/` | 9.9G | 六组字段与关键词表,见[第 4.3 节](#tags-corpus) | +| 8 字段基础标注 `asset_annotations_23736.jsonl` | NAS `zhf/rhg_v16_77_trusted_visual_annotation_20261002/reports/…` | 1.0G | 见[第 4.6 节](#tags-8fields) | +| 注释索引 `annotation_index.sqlite3` | NAS `zhf/rhg_style_joint_20261013/inputs/` | 455M | 20,048 个资产,23,736 条注释 | +| 家具可用性、风格属性、正面审计 | NAS `zhf/rhg_furniture_usability_20261013_v1/`、`rhg_style_attributes_20261013_v1/`、`rhg_front_audit_20261014/` | 7.9G、1.2G、3.7G | 几何契约、包络、看图证据与渲染图、正面证书 | +| 资产池 `prepared_assets.sqlite3` | H200-1 `/data/tutu/robohomegen/current_vs_v31_20261031/rebuild_current_pool_v2/{full,supplement}/` | 341M | 309 + 102 个候选 | +| artifact 缓存 | H200-1 `/data/tutu/robohomegen/hayfung/rules_e2e/artifacts_v1_copy/` | 12.5G | prepare 阶段生成的运行缓存:`prepared/` 下有 281 个 `.blend`、716 个 `.exr`、5,115 个 sqlite3,其余是 JSON 和日志。可由流水线重建 | +| 资产注册表 | LIB `registry/` | 72M | 注册 jsonl、上传记录、工具脚本 | + + + +### 2.5 主分支检索库实际指向哪种文件 + +按 `asset_descriptors.canonical_path` 统计(共 37,279 条): + +| 来源 | 条目 | 指向原件 | 指向修复件 / 转换件 | +|---|---|---|---| +| HSSD | 18,228 | 5,816 个 GLB、1,519 个 URDF(hssd-hab) | 10,683 `hssd_restored`(T4);194 `hssd_json_metadata_fixed`、16 `hssd_original_variants`(T5) | +| InteriorAgent | 6,174 | 5,478 个 `.usd`、25 个整套房屋 `.usda` | 541 T6;18 T7;112 T8 | +| MolmoSpaces | 5,841 + 502 | 502 条归档定位 `molmospaces://…/00000.tar#<资产>.tar.zst` | 5,721 个 `.usda` + 120 个 `.usdc`,在 `molmo_extracted`(T10) | +| 室内 Blender 材质库 | 3,728 | 3,728 个 `.blend` 材质 | 无(ambientCG 图集的法线在生成时做 T12) | +| ArtVIP | 2,152 | 2,118 个 `.usd` | 24 T6;8 T7;2 T8 | +| Lightwheel | 378 | 121 个 `.usd` | 255 T6;2 T8 | +| ReplicaCAD | 185 | 173 个 GLB、12 个 URDF | 无 | +| Poly Haven | 45 | 27 个 `_2k.usdc`、6 个材质 `.blend`、6 个 HDRI `.hdr`、1 个 JPG | 4 T7;1 个 `converted/cardboard_box_01.usdc`(T1) | +| GSO | 24 | 0 | 22 `repairs/gso`(T3);2 条仍指向上游转换件 `GSO-fuel/usd/`(T1) | +| ambientCG | 17 | 17 个官方 `.usdc` 材质 | 无 | +| YCB | 5 | 3 个 `textured.obj` | 2 个上游 `textured.usd`(T1) | +| 合计 | 37,279 | 19,552 | 17,727 | + + + +### 2.6 主分支生成场景 + +- **位置:** H20-96-1 `/data/RPHomeGen/candidate19_replay_20261115_1647/tree/engine/runs//`,60 次尝试,产出 55 个场景,共 62G。 +- **格式:** 每个尝试目录有各阶段的 Blender 5.2.1 `.blend`(一个目录约 26 个)和 JSON 记录。最终场景在 `…/generated/fullhome_asset_v16_XXX/`,清单为 `composition_manifest.runtime.json`。 +- **资产在场景里的形态:** 组装时资产几何被导入并保存在 `.blend` 里,所以 `.blend` 含 InteriorAgent 几何,不能直接公开。贴图、HDRI、`.blend` 材质库和 MDL 烘焙件以外部路径引用。55 个场景引用的外部文件见同目录 `main55_scene_dependency_closure.tsv`(9,612 行)。 +- 场景本身没有再做格式转换。 + +--- + + + +## 3. 目录结构 + +- 大小单位同 `du -h`(1G = 1024³ 字节),比第 2 节表格里的十进制 GB 数略小。 +- ``、`<模型名>` 这类尖括号表示同一层有很多结构相同的条目,只展开一个作例子;`…` 表示省略的同类条目。 +- `->` 是软链及其目标。 +- 从 Hugging Face 下载的数据集(HSSD、ArtVIP、InteriorAgent、MolmoSpaces)根目录下都有 `.cache/huggingface/`,只是下载锁和元数据,树中省略。 + + + +### 3.1 总体布局 + +```text +NAS /mnt/nas-h/ +├── wyc/90_incoming/zp-nc576-data-root-20260901/wyc2/RoboHouseGenData/ # DATA +│ ├── assets/ # 66G +│ │ ├── high_quality/ # 各公开数据集(3.2 节) +│ │ ├── polyhaven/ # Poly Haven 模型、材质、HDRI +│ │ └── converted/ # T1 上游转换件 +│ └── third_party/SceneSmith/data/materials/ # ambientCG 材质 +└── zhf/ + ├── rp_robohavengen/ + │ ├── asset_library/ # LIB:大多是软链(3.3 节) + │ └── render_assets/ # 非公开材质、HDRI、厨房模型的实际位置(3.4 节) + ├── rhg_asset_audit_20261013_v1/ # AUDIT(3.5 节) + ├── rhg_asset_repair_20261013_v2/ # REPAIR2(3.5 节) + └── rhg_style_joint_20261013/ # STYLE,其中 mdl_offline_assets_c15/(3.5 节) + +H200-1 /data/RPHomeGen/public_assets_20261115/ # PUB:11-15 重下载与转换(3.6 节) +H200-1 /data/tutu/robohomegen/…/caches/s*/ # 主分支槽位缓存,含 T12 法线(3.5 节) +H20-96-1 /data/RPHomeGen/candidate19_replay_20261115_1647/tree/engine/runs/ # 主分支场景(3.7 节) +``` + + + +### 3.2 公开数据集原件(DATA) + +**总览:** `assets/high_quality/`,65.2G。 + +```text +high_quality/ +├── hssd-hab/ # 13.1G +├── InteriorAgent/ # 13.3G +├── ArtVIP/ # 9.1G +├── Lightwheel-simready-c5f0feec/ # 4.9G +├── MolmoSpaces-isaac-curated/ # 1.3G +├── GSO-fuel/ # 404M +├── ReplicaCAD_dataset_v1.4/ # 141M +├── YCB-google-16k/ # 132M +├── index/ # 457M,上游 RoboHouseGen 资产索引 +│ ├── asset_index.sqlite3 # LIB registry/asset_index.sqlite3 软链到这里 +│ ├── enriched_catalog.json asset_vectors.faiss asset_index_manifest.json +│ └── proxy/<2 位十六进制>/*.glb, *.sdf # 54 个代理模型 +├── sam-3d-objects/ # 12.3G,SAM 3D Objects 模型权重,不是资产 +├── sam3/ # 6.4G,SAM 3 模型权重,不是资产 +├── lightwheel-simready-c5f0feec.zip # 3.2G,与官方 zip 字节数相同 +├── ReplicaCAD_dataset_v1.4.zip # 129M +├── index-backups/ migration-backup-wyc2-20260811/ proxy-promotion-backup-bar-20260811/ # 备份,共约 0.5G +└── retrieval_catalog.json Lightwheel-simready-metadata/ lightwheel-simready-c5f0feec.tar.gz +``` + +**1、HSSD**(`hssd-hab/`,13.1G,约 9.1 万个文件) + +```text +hssd-hab/ +├── objects/ # 物体,9.7G,5.6 万个文件 +│ ├── 0/ 1/ … f/ x/ # 按 ID 首字符分 17 个目录;x/ 下是 xxxx 开头的 ID +│ │ ├── .glb # 物体模型:压缩几何 + KTX2 贴图(T4 的处理对象) +│ │ ├── .collider.glb # 碰撞代理 +│ │ ├── .filteredSupportSurface.glb # 可放置面(另有同名 .ply) +│ │ └── .object_config.json # Habitat 物体配置 +│ ├── decomposed// # 232 个可拆分物体 +│ │ └── _part_N.glb / .collider.glb / .object_config.json +│ └── openings/ # 门窗:.glb + .object_config.json,2,407 个文件 +├── urdf// # 1,519 个铰接物体,973M +│ ├── .urdf +│ ├── .ao_config.json +│ └── Dresser0212.glb、Dresser0212_drawer01.glb、…_receptacle_mesh.glb # 本体与各活动部件 +├── stages/ # 168 套房屋外壳:.glb + .stage_config.json +├── scenes/ # 168 个 .scene_instance.json +├── scenes-articulated/ # 161 个,铰接版 +├── scenes-uncluttered/ # 168 个,去杂物版 +├── scene_filter_files/ # .rec_filter.json,含 articulated_scene_filter_files/ +├── semantics/ # hssd-hab_semantic_lexicon.json、objects.csv、scenes/.semantic_config.json +├── support-surfaces// # 5,187 个:.supportSurface.{glb,json.gz,png} +├── metadata/ # objects.json、object_categories_filtered.csv 等 6 个 +├── hssd-hab.scene_dataset_config.json # 另有 -articulated、-uncluttered 两个变体 +├── scene_splits.yaml +└── README.md +``` + +**2、ArtVIP**(`ArtVIP/`,9.0G,5,270 个文件) + +```text +ArtVIP/ +├── Articulated_objects/ # 铰接物体,4.9G,3,442 个文件 +│ ├── Ikea_furniture/ Medical_equipment/ household_items/ industrial_machinery/ lab_items/ +│ ├── large_furniture/ major_appliances/ small_appliances/ small_furniture/ # 共 9 类 +│ └── large_furniture/wardrobe/open_wardrobe_1/ # 例:<类>/<子类>/<物体>/ +│ ├── model_open_wardrobe_1.usd # 入口 USD,检索库指向这一层 +│ ├── resource/ # 子层 .usd、贴图 .png、.json +│ ├── NVIDIA/ 或 omniverse-content-production.s3…/ # 部分物体随包带的 .mdl +│ └── .collect.mapping.json # Omniverse Collect 的路径映射 +├── Interactive_scene/ # 6 个可交互整屋,1.6G +│ └── kitchen/ childrenroom/ diningroom/ kitchen_with_parlor/ largelivingroom/ smalllivingroom/ +│ ├── Interactive_<场景>.usd # 整屋入口 +│ ├── <家具>/model_<家具>.usd + resource/ # 结构同上 +│ └── Isaac Sim 4.5/isaac-sim-assets/…/*.mdl +├── Scenes/ # 6 个静态整屋,1.6G,结构同 Interactive_scene +├── assets/ # README 用的 gif、png、mp4 +└── README.md +``` + +**3、InteriorAgent**(`InteriorAgent/`,13.3G,13,471 个文件) + +```text +InteriorAgent/ +├── kujiale_0003/ # 25 套房屋,kujiale_0003 … kujiale_0067 +│ ├── kujiale_0003.usda # 整套房屋入口(检索库有 25 条指向这类文件) +│ ├── Meshes/ # 每个家具或构件一个 USD,本例 321 个 +│ │ └── basin_0000.usd、bathroom_product_0000.usd、… +│ ├── Materials/ # MDL 材质(M_BaseMaterial*.mdl、MI_.mdl 等)和贴图 +│ ├── rooms.json # 房间划分 +│ ├── buikslotermeerplein_4k.hdr # 环境光,各套不同 +│ └── .thumbs/ +├── kujiale_0004/ … kujiale_0067/ +└── README.md +``` + +**4、Lightwheel SimReady**(`Lightwheel-simready-c5f0feec/`,4.9G,1,329 个文件) + +```text +Lightwheel-simready-c5f0feec/ +└── Lightwheel_OpenSource/ + ├── Locomotion/ # 8 个场景和地面,3.2G + │ ├── 2-StoryStaircase/ Apartment/ Grass/ GravelGround/ + │ ├── MudGround/ SLATEGround/ SnowGround/ + │ └── KitchenRoom/ # 例 + │ ├── KitchenRoom.usd KitchenRoom_RSS.usd + │ ├── CoffeeMachine006/ Dishwasher054/ Door012/ … # 各家具子目录 + │ ├── texture/ + │ └── .collect.mapping.json + └── Manipulation/ # 243 个可操作物体,1.7G + └── Blender001/ # 例 + ├── Blender001.usd + └── texture/T_Blender001_BC001.png、T_Blender001_ORM001.png +``` + +**5、MolmoSpaces**(`MolmoSpaces-isaac-curated/`,1.3G)。原件是归档,这里不解包;解包结果见 3.5、3.6 节。 + +```text +MolmoSpaces-isaac-curated/ +└── isaac/ + ├── objects/thor/20260128/ + │ ├── shards/00000.tar # 1.0G,内含 382 个 <资产>.tar.zst + │ ├── pkgs-00000-of-00001.parquet # 包索引 + │ ├── arrow_table.json + │ ├── mjthor_resource_file_to_size_mb.json + │ └── mjthor_resources_combined_meta.json.gz + └── scenes/ithor/20260121/ + ├── shards/00000.tar # 221M,内含 120 个场景 .tar.zst + └── (同上 4 个索引文件) +``` + +**6、ReplicaCAD**(`ReplicaCAD_dataset_v1.4/`,141M,600 个文件) + +```text +ReplicaCAD_dataset_v1.4/ +├── objects/ # 92 个物体:frl_apartment_*.glb +│ └── convex/ # 76 个凸分解碰撞体:*_cv_decomp.glb +├── urdf/ # 6 类铰接物体,12 个 .urdf + 部件 .glb +│ └── cabinet/ chest_of_drawers/ doors/ fridge/ kitchen_counter/ kitchen_cupboards/ +├── stages/ # 5 个公寓外壳:Stage_v3_sc*_staging.glb +├── configs/{objects,scenes,stages,lighting,ssd}/ # Habitat 配置 JSON +├── navmeshes/ navmeshes_default/ # 各 91 个 apt_*.navmesh +├── replicaCAD.scene_dataset_config.json +└── LICENSE.txt +``` + +**7、YCB**(`YCB-google-16k/`,132M) + +```text +YCB-google-16k/ +├── archives/_google_16k.tgz # 5 个原始压缩包 +└── models// # 003_cracker_box、005_tomato_soup_can、006_mustard_bottle、025_mug、035_power_drill + ├── google_16k/ # 解包内容 + │ ├── textured.obj textured.mtl texture_map.png # 带贴图网格,Z 向上 + │ ├── textured.dae + │ ├── nontextured.ply nontextured.stl + │ └── kinbody.xml + ├── textured.usd # T1 上游转换件,只有 003、006 有 + ├── textured.usd.manifest.json + └── textures/texture_map.png # 转换时复制的贴图 +``` + +**8、GSO**(`GSO-fuel/`,404M) + +```text +GSO-fuel/ +├── ACE_Coffee_Mug_Kristen_16_oz_cup/ # 24 个模型,以此为例 +│ ├── ACE_Coffee_Mug_Kristen_16_oz_cup.zip # Gazebo Fuel 原始包 +│ └── model/ # 解包内容 +│ ├── meshes/model.obj model.mtl # MTL 写的是 map_Kd texture.png,但图片不在这里 +│ ├── materials/textures/texture.png # 实际贴图 +│ ├── thumbnails/0.jpg … 4.jpg +│ ├── model.sdf model.config metadata.pbtxt +│ └── .complete +└── usd/ # T1 上游转换件 + ├── <模型名>.usdc + <模型名>.usdc.manifest.json # 24 对 + └── textures/ # 空目录(manifest 记 dependencies_copied: 0) +``` + +**9、Poly Haven**(`assets/polyhaven/`,782M) + +```text +polyhaven/ +├── CoffeeCart_01/ # 32 个模型,以此为例 +│ ├── CoffeeCart_01_2k.usdc # 原件已是 Z-up、米制 +│ └── textures/ # 2k 贴图(.exr/.png/.jpg) +├── render/ +│ ├── materials/<名称>/<名称>_2k.blend # 6 个材质,如 anti_skid_tiles +│ ├── hdris/<名称>/<名称>_4k.hdr + preview.jpg # 6 个 HDRI,如 blocky_photo_studio +│ └── render_catalog.json +└── catalog.json +``` + +**10、其他两处:** `assets/converted/` 和 SceneSmith 自带的 ambientCG 材质。 + +```text +assets/converted/ # T1 上游转换件 +├── cardboard_box_01.usdc # copy-usd +├── cardboard_box_01.usdc.manifest.json +└── textures/cardboard_box_01_{diff_2k.jpg, nor_gl_2k.exr, rough_2k.exr} + +third_party/SceneSmith/data/materials/ # 159M;LIB 的 materials/scenesmith_original 软链到这里 +├── Asphalt033/ # 18 个材质目录:Asphalt033、Grass005、…、Wood092、WoodFloor051 +│ ├── Asphalt033_1K-JPG.usdc # ambientCG 官方 USD 材质(检索库指向这类文件,共 17 个) +│ ├── Asphalt033_1K-JPG.mtlx .blend .tres # MaterialX、Blender、Godot 版本 +│ ├── Asphalt033_1K-JPG_{Color,Roughness,NormalGL,NormalDX,Displacement,AmbientOcclusion}.jpg +│ └── Asphalt033.png # 预览 +├── embeddings/ # clip_embeddings.npy 与两个索引 yaml +└── WoodFloor051_1K-JPG.zip +``` + + + +### 3.3 资产库(LIB,资产注册表的位置) + +主分支通过 `RHG_LIBRARY_ROOT` 指向这里。目录里的材质、HDRI 和厨房模型都是软链,实际文件在 `render_assets/`(3.4 节)。 + +```text +asset_library/ +├── models/ +│ ├── robohousegen -> /mnt/nas-h/wyc/…/RoboHouseGenData/assets # 公开数据原件(3.2 节) +│ └── kitchen_upload_20261005 -> ../render_assets/pbr_kitchen_20261005_003251/kitchen +├── materials/ +│ ├── interior_blender_20261009 -> ../render_assets/interior_blender_20261009 +│ ├── pbr_upload_20261005 -> ../render_assets/pbr_kitchen_20261005_003251/PBR +│ ├── poliigon_supplement_20261005 -> ../render_assets/poliigon_supplement_20261005 +│ ├── polyhaven_gap_fill_20261005 -> ../render_assets/polyhaven_gap_fill_20261005 +│ └── scenesmith_original -> /mnt/nas-h/wyc/…/RoboHouseGenData/third_party/SceneSmith/data/materials +├── hdri/ +│ └── sky_collection_20261004_234305 -> ../render_assets/hdri/sky_collection_20261004_234305 +├── registry/ # 资产注册表,72M +│ ├── assets.jsonl # 注册记录,26M +│ ├── manifest.json library.env verification.json source_layout.json supplemental_files.jsonl +│ ├── native_articulations.json idempotence_verification.json +│ ├── asset_index.sqlite3 -> /mnt/nas-h/wyc/…/assets/high_quality/index/asset_index.sqlite3 +│ ├── interior_materials_20261009.jsonl -> …/interior_blender_20261009/material_assets.jsonl +│ ├── interior_material_categories_20261009.json -> …/interior_blender_20261009/material_categories.json +│ ├── source_full_registry.json -> /mnt/nas-h/zhf/rhg_v16_76_full_asset_annotation_20261002/registry/… +│ ├── tools/ # 注册工具,如 asset_library.py +│ ├── upload_records/interior_blender_20261009/ +│ └── script_backups/ +├── runtime_derivatives/ +│ ├── stable_real_assets_v1/ # T14 产物:3 个 GSO 的 GLB,主分支不引用 +│ │ ├── ACE_Coffee_Mug_Kristen_16_oz_cup/ +│ │ │ ├── ACE_Coffee_Mug_Kristen_16_oz_cup.glb +│ │ │ ├── provenance.json candidate.json +│ │ │ └── original/ # 解包的原始 OBJ、贴图、SDF +│ │ ├── Footed_Bowl_Sand/ Threshold_Dinner_Plate_Square_Rim_White_Porcelain/ +│ │ ├── archives/ counter_component/ +│ │ └── library_preparation_report.json 等 +│ ├── asset_quality_20261013_v1 -> /mnt/nas-h/zhf/rhg_asset_audit_20261013_v1/release +│ └── asset_quality_20261013_v2 -> /mnt/nas-h/zhf/rhg_asset_repair_20261013_v2/release +├── incoming/ # 空 +└── README.md +``` + + + +### 3.4 非公开资产的实际位置(`render_assets/`,真实资产大文件) + +NAS `/mnt/nas-h/zhf/rp_robohavengen/render_assets/`: + +```text +render_assets/ +├── interior_blender_20261009/ # 室内 Blender 材质库,36.2G,8,686 个文件 +│ ├── 01室内常用/ # 16 个类目(01–15、18),149 个 .blend +│ │ ├── 01木地板与拼花/ # 例 +│ │ │ ├── 01_英文PBR贴图.blend # 文件名 = 来源包编号_来源类型 +│ │ │ ├── 09_中文程序化.blend +│ │ │ ├── 42_中文高清贴图.blend +│ │ │ └── 62_ambientCG贴图.blend 等 +│ │ └── 02木饰面与家具板材/ … 18吸音板与吊顶/ +│ ├── 02特色与工业风/ # 16装饰砖墙、17清水混凝土,20 个 .blend +│ ├── 03辅助细节/19表面细节与辅助贴图/ # 4 个 .blend +│ ├── 资源依赖/ # .blend 引用的贴图,35.9G +│ │ ├── large/<类别>/<名称>_2K-JPG/ # 23 类,如 bricks、fabric、woodfloor,12.8G +│ │ │ └── <名称>_2K_{Color,Roughness,NormalDX,Displacement,AmbientOcclusion,Metalness}.jpg # ambientCG 图集,T12 转换其中的 NormalDX +│ │ ├── small/<类别>/<名称>_2K-JPG/ # 16 类,如 bamboo、wallpaper +│ │ └── pack_01.blenddata … pack_64.blenddata # 53 个打包的 Blender 数据(编号不连续),约 22G +│ ├── 预览图/ # 3,719 张材质预览 p01_0002.png … +│ ├── 分类预览/ 抽样渲染/ +│ ├── material_assets.jsonl # 材质索引,检索库 3,728 条的来源 +│ ├── material_categories.json manifest.json blender_assets.cats.txt +│ └── 室内材质清单.csv 未收入清单.csv 需要检查的材质.csv 整理说明.md SERVER_UPLOAD_README.md verification.json render_verification.json 分类总览.jpg +├── pbr_kitchen_20261005_003251/ +│ ├── kitchen/ # 厨房模型,1.1G,263 个文件(LIB models/kitchen_upload_20261005) +│ │ ├── Toaster001/ # 7 个已解包产品,以此为例 +│ │ │ ├── Generic/ # Toaster001.fbx、Toaster001.obj、*_COL/GLOSS/NRM_*.jpg|png +│ │ │ ├── Software/3dsMax/*.max +│ │ │ ├── Textures/{METALNESS,SPECULAR}/ # 有的产品是 Textures/4K/ +│ │ │ └── Previews/*_Preview{1,2,3}.jpg +│ │ └── BowlsDesignerSet001.zip、… # 另有 14 个未解包的产品包(.zip + 预览 .jpg) +│ └── PBR/ # 厨房 PBR,4.1G,456 个文件(LIB materials/pbr_upload_20261005) +│ ├── 木纹/ 瓷砖/ 地毯/ Stucco/ # 贴图包:<名称>/{3K,4K,6K,Previews}/ 或 <名称>_3k/ +│ └── 植物/<名称>/ # 5 个植物模型,T9 的处理对象 +│ └── Generic/*.fbx Software/*.c4d Previews/ Textures/ +├── poliigon_supplement_20261005/ # 489M +│ ├── packages/ # 4 个商品包:Poliigon_*.zip、FabricPlainNaturalSheer009.zip +│ ├── textures/<商品号>/ # 6565、7174、7827、8060;贴图(jpg、png、tiff、mtlx)多在 4K/ 下 +│ └── evidence/ download_manifest.json README_ZH.md +├── polyhaven_gap_fill_20261005/ # 315M,7 个材质 +│ ├── textures/<名称>/ # 如 beige_wall_001、cotton_jersey、leather_white +│ │ ├── <名称>_{diff,ao,disp,nor_gl,rough}_4k.jpg +│ │ └── <名称>_4k.mtlx +│ └── manifest.json sha256.txt +└── hdri/sky_collection_20261004_234305/ + └── 05-高阶天空HDRI贴图/ # 3.2G,125 个文件:63 个 .hdr、3 个 .exr、59 张预览 .jpg + ├── 0707 dawn sun/0707 Dawn Sun.{hdr,jpg} # 54 个按时刻和天气命名的天空目录 + ├── … + └── VizPeople天空合集/ # VizPeople 的免费和非商用天空 +``` + +厨房模型与厨房 PBR 的来源判断见[第 6 节第 5 条](#notes)。 + + + +### 3.5 项目衍生件 + +**1、AUDIT**(NAS `/mnt/nas-h/zhf/rhg_asset_audit_20261013_v1/`,86G) + +```text +rhg_asset_audit_20261013_v1/ +├── restore_hssd_textures.py、repair_gso.py、… # 修复与审计脚本,都在根目录(T3–T6、T10、T13) +├── hssd_restoration_results.jsonl、gso_repair_receipt.json、dependency_path_repairs.json、… # 回执与日志 +├── hssd_restoration/.json # T4 每个资产一份回执 +├── tools/basisu # 审计时解码 KTX2 +├── runtime_paths.env # RHG_MDL_SEARCH_PATH +├── release/ # summary.json、asset_quality.sqlite3、remaining_gaps.jsonl、interior_materials_repaired.jsonl 等 +└── repairs/ # 修复件,78G,38,191 个文件 + ├── hssd_originals/208ea6bc…/ # T4 的输入:HSSD 未压缩官方版本,34.5G + │ ├── objects//.glb # 10,856 个 + │ └── stages/.glb # 168 个 + ├── hssd_restored/objects//.glb # T4 输出,10,940 个,32.9G + ├── hssd_original_variants/ # T5,186 个,403M + │ ├── objects//.glb # 18 个物体 + │ └── stages/.glb # 168 个房屋外壳 + ├── hssd_json_metadata_fixed/objects/0/.glb # T5,196 个,586M + ├── gso/<模型名>.usdc # T3,24 个 + ├── usd_dependency_paths/.usdc # T6,958 个,2.2G + ├── mdl/ # T6 用的 MDL 搜索路径 + │ ├── isaacsim_core/{Base,mdl,Ue4,VRay,Blender,Nonvisual,Volume}/ + │ ├── 2023_1/ 2023_2_1/ relative_import_repair/ + │ └── copy_receipt.json nvidia_public_template_receipt.json + ├── molmo_extracted// # T10,502 个归档父项,每个解出若干变体 + │ ├── Toaster_23/ # 例 + │ │ ├── Toaster_23.usda + │ │ └── Textures/*.png + │ ├── Toaster_23_mesh/ # 同结构 + │ └── Toaster_23_prim/ + ├── objects/thor/<资产名> -> /mnt/nas-h/zhf/rhg_asset_audit_20261013_v1/repairs/molmo_extracted//<资产名> # T10,1,275 个目录软链 + ├── ambientcg/<名称>_2K-JPG/ # T13,110 个,4.2G + │ ├── <名称>_2K-JPG.zip # 重新下载的官方包 + │ ├── <名称>_2K-JPG_{Color,Displacement,…}.jpg <名称>_2K-JPG.blend <名称>.png + │ └── *.json # 发布者元数据与校验记录 + └── interior_materials/ # T13 + ├── official_metal_materials.blend + ├── interior_materials_repaired.jsonl repair_receipt.json + └── initial_ambiguous_name_attempt/ +``` + +H200-1 的镜像里,`repairs/objects/` 的软链被展开成了实际文件,所以那份副本有 870M。 + +**2、REPAIR2**(NAS `/mnt/nas-h/zhf/rhg_asset_repair_20261013_v2/`) + +```text +rhg_asset_repair_20261013_v2/ +├── repair_exact.py、repair_variants.py、repair_plants.py、fetch_nvidia.py、… # T7–T9 脚本 +├── exact_repairs.json variant_repairs.json plant_repairs.json png_metadata_repairs.json … +├── downloads/nvidia/Materials/ # fetch_nvidia.py 取回的 NVIDIA 原件,65M +│ ├── 2023_2_1/… # 8 个 .mdl 与 14 张贴图 +│ └── Base/… # 6 张木纹贴图 +├── materials/ # T8 用的替代材质 +│ ├── palette.usdc palette.blend palette_provenance.json +│ ├── configured_templates.blend +│ └── textures/*_xtm.{jpg,png} # 另有 6 个 .original_bad_iccp:删 iCCP 块之前的备份 +├── repairs/ # 1.0G +│ ├── usd/.usdc # T7,34 个 +│ ├── mdl//<名称>.mdl # T7,4 个:Oak、Mahogany_Planks 等 +│ ├── variants/.usdc # T8,133 个 +│ └── plants// # T9,5 个植物 +│ ├── repaired.blend repaired.usdc +│ ├── repaired_material_complete.blend repaired_material_complete.usdc +│ ├── repaired_roughness_corrected.usdc +│ └── textures/ +└── release/ # USAGE.txt、available_models.jsonl、availability_summary.json 等 +``` + +**3、STYLE MDL 烘焙**(NAS `/mnt/nas-h/zhf/rhg_style_joint_20261013/mdl_offline_assets_c15/`,23.4G) + +```text +mdl_offline_assets_c15/ +├── bake_cache// # T11,2,322 个烘焙请求,11.6G +│ ├── request.json result.json worker.log +│ └── base_color.exr metallic.exr roughness.exr normal.exr anisotropy.exr anisotropy_rotation.exr # 只有非常量通道才有 EXR +├── material_libraries/// # T11,685 个材质库,11.2G +│ ├── materials.blend +│ └── manifest.json +├── cases/.json # 813 个验证案例 +├── results// # 每个案例的四视图渲染与验收 JSON,514M +├── code/ # mdl_benchmark_worker.py、render_mdl_benchmark.py +├── worker_runtime/ +└── cpu*.log +``` + +**4、槽位缓存里的 T12 法线**(H200-1 `/data/tutu/robohomegen/codex_stability_hardening_20261110/codex_candidate19_20261112/caches/s00/`,12.4G) + +```text +caches/s00/ +├── material_catalog/ # 987M +│ ├── normal_dx_to_gl/<源图 sha256>/ # T12,本槽位 191 个 +│ │ ├── normal_gl.png +│ │ ├── conversion.json +│ │ └── conversion.lock +│ └── structural_material_catalog_.json structural_material_catalog_.receipt.json +├── prepared/ # prepare 阶段缓存,11.4G +└── source_qualification/ activation_rejections/ +``` + + + +### 3.6 11-15 重下载与转换(PUB) + +H200-1 `/data/RPHomeGen/public_assets_20261115/`,11.3G。各下载机的目录结构相同,内容按分工不同。 + +```text +public_assets_20261115/ +├── control/ # 驱动脚本与回执 +│ ├── downloader.py prepare_archives.py readme_asset_conversion.py +│ ├── conversion-source-manifest.json manifest.json +│ ├── gso.conversion.json polyhaven_models.conversion.json ycb.conversion.json +│ ├── readme-conversion-technical-check.json ycb-conversion-technical-check.json +│ ├── lightwheel-checks.json lightwheel.verified.jsonl … +│ └── *.log +├── conversion_code/ # RHG 抽取副本:README.md、configs/、docs/、packages/、scripts/ +├── conversion_env/ # 转换用的 Python 环境(含 pxr) +├── archives/Lightwheel_OpenSource.zip # 3.2G +├── conversion_inputs/assets/{high_quality/GSO-fuel, polyhaven}/ # 从 H20-96-4 传来的输入 +├── conversion_managed_inputs/raw/ # 按 README 要求排好的输入 +│ ├── gso_fuel_collection_full/collection-2022-06-13-snapshot-20260828/archives/*.zip # 硬链 +│ └── polyhaven_models_full_2k/api-models-20260828-2k/models/<名称> -> …/conversion_inputs/assets/polyhaven/<名称> +└── derived/ + ├── readme_high_fidelity_textures_v2_20261115/ # T2 输出,1.1G + │ ├── canonical/gso/<模型名>/ # 24 个 + │ │ ├── asset.usdc # 转换结果,root prim 为 /Asset + │ │ ├── textures/texture.png # Blender 导出 USD 时复制的贴图 + │ │ ├── meshes/model.obj model.mtl texture.png # texture.png 是驱动第 2 步做的同字节别名 + │ │ ├── materials/textures/texture.png # 原始贴图 + │ │ └── thumbnails/ model.sdf model.config metadata.pbtxt + │ ├── canonical/polyhaven/<模型名>/ # 32 个:<模型名>_2k.usdc + textures/ + │ ├── jobs/ # gso_convert_00000.json、isaac_author_00000.json 及其 .result.json + │ ├── preprocess_plan.json + │ └── preprocess_report.json + ├── readme_high_fidelity_20261115/ # T2 第一次运行,GSO 贴图未绑定,作废 + ├── readme_ycb_20261115// # T1,5 个 + │ ├── asset.usdc asset.usdc.manifest.json + │ └── textures/texture_map.png + └── lightwheel/Lightwheel_OpenSource/ # T0 解包,结构同 3.2 节 +``` + +H20-96-1 上同名目录里的 MolmoSpaces 解包(T10,4.4G): + +```text +derived/molmospaces/ +├── packages/isaac/ # 外层 TAR 解出的 502 个 .tar.zst,1.2G +│ ├── objects/thor/20260128/*.tar.zst # 382 个 +│ └── scenes/ithor/20260121/*.tar.zst # 120 个 +└── unpacked/isaac/ # 逐个解开 .tar.zst,3.2G + ├── objects/thor/20260128/<资产>/ # 5,001 个 .usda、6,372 张贴图 + └── scenes/ithor/20260121/<场景>/ # 720 个 .usda、120 个 .usdc +``` + + + +### 3.7 主分支生成场景 + +以 H20-96-1 `…/engine/runs/seed1_scene_000_42/` 为例(732M,851 个文件): + +```text +seed1_scene_000_42/ +├── request.json scene_input.json approved_scene_spec.json asset_retrieval_audit.json … # 输入与各阶段记录,顶层 31 个 JSON +├── dynamic_selection/round_01/ … round_13/ # 资产检索与选择,每轮有 json、sqlite3、py +├── declared_layout/ layout/ projected_layout/ # 各布局阶段,每个含 fullhome_asset_v16_000/*.blend +├── layout_recovery/attempt_002/ … attempt_004/ # 布局修复尝试,体积主要在这里 +│ └── attempt_004/execution/chain/round_01/attempt_01/generated/fullhome_asset_v16_000/ # 最终场景,192M +│ ├── fullhome_asset_v16_000.blend # Blender 场景,132M +│ ├── composition_manifest.runtime.json # 资产 ID、文件路径与位姿,5.8M +│ ├── SceneManifest.v16.json BenchmarkEpisode.v16.json task_contract_v16.json +│ ├── asset_binding_report.json real_asset_import_audit.json saved_blend_verification.json … # 约 50 个审计 JSON +│ ├── original_template/ prepared_pool_evidence/ +│ └── logs/ +├── layout_recovery_evidence/ +├── execution/ # result.json、material_plan.json、room_program.json 等 +├── runtime/ shell_runtime/ bootstrap/ tmp/ +└── user/ # 隔离的空用户目录 +``` + +--- + + + +## 4. 富文本标签 + + + +### 4.1 生成方式与存放位置 + +**生成方式** + +- **流水线由 Codex 运行。** 每个资产用 Blender 5.2.1 按源材质渲染 4 个视角:`from_posX_negY`、`from_negX_posY`、`from_posX_posY`、`top`,中性光照、AgX 色彩变换。 +- **看图模型是 Qwen3-VL-32B-Instruct。** 它根据 4 张图输出类别、完整性、风格、颜色、材质外观、形状与部件、安装方式和用途,共覆盖 27,483 个对象(证据类型 `Qwen3_VL_asset_category_completeness_and_attributes`)。模型原始回复保留为证据 `direct_review_raw`。 +- **二次判定。** 结合实测尺寸和源数据自带的类别提示,再判一次类别、形状和摆放姿态,覆盖 24,656 个对象(证据 `contextual_asset_adjudication`)。上一轮的看图结果保留在 `provenance.superseded_image_only_prediction` 里。 +- **源文件解析。** 着色器颜色参数、材质定义、单位、上轴、关节和支撑面直接从源文件读出(证据 `source_facts`、`geometry_contract`),状态记为 `measured`。 +- **Codex 复核。** 正面方向有 36 条记录写明由 Codex 看图复核(`provenance.reviewer` 为 `Codex source-image review 2026-11-03` 或 `Codex supervising assistant; actual four-view visual review`)。 + +**存放位置** + +| 层 | 文件(主机:路径) | 格式 | 条目 | 内容 | +|---|---|---|---|---| +| 属性发布记录(主分支读取) | H200-1 `/data/tutu/robohomegen/scene_evidence_repair_20261103/front_probe/published/review_1793688076267784737/records.jsonl`;父版本 NAS `/mnt/nas-h/zhf/rhg_stable_visuals_20261014/r9_rebuild_v1/reviewed_attributes_v2/records.jsonl` | JSONL,每行一个对象,732M;schema `rhg.source_geometry_attributes.v1` | 29,577 个对象 | 每个对象 14 个属性字段,每个字段都带取值、状态、置信度、证据和来源(4.2 节) | +| 全库检索矩阵 | H200-1 `/data/tutu/robohomegen/wholehome_style_sets_20261030/full_corpus/full_asset_matrix.enriched_20261031.sqlite3`(3.3G);同目录 `records/normalized_assets.jsonl.gz`(198M) | SQLite(`corpus_*` 表与视图,含 FTS5 全文索引);JSONL.gz,schema `rhg.full_corpus_six_groups.v1` | 37,279 条 | 把属性记录按六组 102 个字段整理,并拆出关键词表 `corpus_tags`(4.3、4.4 节) | +| 主分支检索索引 | H200-1 `/data/tutu/robohomegen/scene_evidence_repair_20261103/full_matrix_reviewed_compatibility.sqlite3`(830M) | SQLite,11 张表;schema `rhg.annotation_integration.v1` | 37,279 条 | 由全库矩阵派生,生成器检索资产时读这里(4.5 节) | +| 8 字段基础标注 | NAS `/mnt/nas-h/zhf/rhg_v16_77_trusted_visual_annotation_20261002/reports/final_delivery_v16_77/…/asset_annotations_23736.jsonl`(1.0G);对应 SQLite `/mnt/nas-h/zhf/rhg_style_joint_20261013/inputs/annotation_index.sqlite3`(455M) | JSONL / SQLite | 23,736 个对象 | 语义、尺寸、功能、方向、入口、坐标变换、单位与上轴、轴心与层级(4.6 节) | + + + +### 4.2 属性记录的格式 + +每行一个 JSON 对象,顶层键如下: + +| 键 | 内容 | +|---|---| +| `asset_id`、`record_id` | 资产 ID、记录哈希 | +| `schema_version`、`annotation_release`、`scope_sha256` | 版本;主分支用的发布名是 `final_20261014_r9_reviewed_v2` 加正面复核扩展 | +| `identity` | `source`、`runtime`、`dependencies`、`canonical_transform`、`derivation`:源文件与运行文件的路径和 SHA-256、依赖闭包、规范变换矩阵 | +| `attributes` | 14 个属性字段,见下表 | +| `evidence_registry` | 证据表。键名(如 `image_0`、`review`、`render`、`source_facts`)对应 `{kind, uri, sha256, scope}`,属性里的 `evidence` 列表引用这些键 | +| `direct_usability` | 可用性结论(如 `usable_original_material`)、中英文类别、是否用了替代件 | +| `processing`、`scope` | 处理状态、导入范围;部分记录另有 `qualified_payload_fingerprint`、`field_revision_history` | + +每个属性字段的结构相同: + +```text +{ "value": …, "status": …, "confidence": …, "evidence": [证据键…], + "provenance": { "method": …, "limitations": …, "confidence_basis": …, "producer_sha256": …, "reviewer": …(部分) } } +``` + +14 个属性字段(29,577 个对象中各状态的数量): + +| 字段 | `value` 的主要键 | 来源 | 状态分布 | +|---|---|---|---| +| `style` | `labels[{name, score, reason}]`、`confidence` | 看图 | inferred 24,095;unknown 5,481;conflict 1 | +| `colors` | `rendered_appearance.palette[{color_name, approx_hex, region}]`;`authored_color_parameters[{shader_path, parameter, value, color_space}]` | 看图 + 着色器参数 | inferred 24,102;measured 1,109;unknown 4,366 | +| `materials` | `appearance.appearance[{material_appearance, region, confidence}]`、`shader_material_count`、`authored_material_definitions` | 看图 + 着色器解析 | inferred 24,105;measured 3,378;unknown 2,094 | +| `shape` | `description`、`parts[]` | 二次判定 | inferred 24,656;unknown 4,921 | +| `semantic_role` | `catalog_roles`、`contextual_category`、`asset_granularity`、`source_hint_agreement` | 二次判定 | inferred 24,048;unknown 4,921;conflict 608 | +| `installation` | `type`、`reason`、`confidence` | 看图或源数据 | inferred 23,975;unknown 5,601;conflict 1 | +| `usage_space` | `likely_rooms`、`action_access_description`、`movable_parts_visible`、`unconfirmed` | 看图 + 几何 | inferred 24,654;unknown 4,923 | +| `functional_front` | `axis`、`axis_frame`、`certificate` | 看图复核 | inferred 1,885;unknown 27,691;conflict 1 | +| `pose_qualification` | `current_pose`、`intended_up_axis_if_clear`、`reason` | 二次判定 | inferred 22,257;conflict 2,400;unknown 4,919;measured 1 | +| `geometry` | `dimensions_xyz_m`、`world_bbox_m`、`obb_m`、`visual_footprint_xy_m`、`source_unit_metadata` | 顶点实测 | measured 26,455;unknown 2,825;conflict 297 | +| `support` | `upward_planes[{area_m2, bbox_m, height_m}]`、`bottom_band_m` | 网格实测 | measured 26,752;unknown 2,825 | +| `opening_envelope` | `joint_envelopes[{joint_path, type, authored_limits, swept_bbox_m, …}]` | 关节限位扫掠 | measured 1,202;unknown 28,375 | +| `source_kinematics` | `joints[]`、`animated_attributes` | 源文件元数据 | measured 27,483;unknown 2,094 | +| `quality` | `source_import`、`material_completeness`、`appearance_review`、`direct_visual_review` | 证据汇总 | measured 26,752;failed 731;unknown 2,094 | + +状态词:`inferred`(推断)、`measured`(实测或从源文件读出)、`verified`(哈希核对)、`unknown`(无证据,不等于否定)、`conflict`(证据冲突)、`failed`。 + +**示例。** 下面取自实际记录(ArtVIP 的 BRUKSVARA 双门双抽衣柜),只保留部分字段,长列表截断: + +```json +{ + "asset_id": "artvip:Articulated_objects/Ikea_furniture/BRUKSVARA_wardrobe_with_2_doors_and_2 drawers_brown_79x57x201cm/model_…", + "annotation_release": "final_20261014_r9_reviewed_v2", + "attributes": { + "style": { + "value": {"confidence": 0.85, "labels": [ + {"name": "scandinavian", "score": 0.85, "reason": "Clean lines, light wood, simple form, functional design typical of Scandinavian style."}, + {"name": "minimalist", "score": 0.8, "reason": "Unadorned surfaces, neutral palette, emphasis on form and function over ornament."}, + {"name": "contemporary", "score": 0.75, "reason": "Modern silhouette with subtle texture, suitable for current interior trends."}]}, + "status": "inferred", "confidence": 0.85, + "evidence": ["render", "review", "image_0", "image_1", "image_2", "image_3"], + "provenance": {"method": "Qwen3-VL-32B-Instruct_multiview_review", "confidence_basis": "model_self_report_uncalibrated"} + }, + "colors": {"status": "inferred", "value": {"rendered_appearance": {"palette": [ + {"color_name": "light_oak", "approx_hex": "#D2B48C", "region": "front doors and side panels"}, + {"color_name": "black", "approx_hex": "#000000", "region": "base trim"}, "…"]}}}, + "materials": {"status": "inferred", "value": {"shader_material_count": 5, "appearance": {"appearance": [ + {"material_appearance": "wood_look", "region": "front doors and side panels", "confidence": 0.9}, + {"material_appearance": "metal_look", "region": "base trim", "confidence": 0.7}, "…"]}}}, + "shape": {"status": "inferred", "value": { + "description": "Tall rectangular cabinet with two doors and two drawers; light wood finish; top surface visible in D view.", + "parts": ["main cabinet body", "two front doors", "two drawers below doors", "top panel", "side panels"]}}, + "installation": {"status": "inferred", "value": {"type": "floor", "reason": "Base trim suggests floor-standing; no wall mounting hardware visible."}}, + "usage_space": {"status": "inferred", "value": {"likely_rooms": ["bedroom", "hallway", "living room"], "movable_parts_visible": ["doors", "drawers"]}}, + "functional_front": {"status": "inferred", "confidence": 0.98, + "value": {"axis": "-Y", "axis_frame": "labelled_canonical_camera_frame", "certificate": "v29_front_certificate"}, + "provenance": {"reviewer": "Codex source-image review 2026-11-03"}}, + "geometry": {"status": "measured", "value": {"dimensions_xyz_m": [0.796, 0.599, 2.005]}}, + "…": "semantic_role、pose_qualification、support、opening_envelope、source_kinematics、quality" + }, + "evidence_registry": { + "image_0": {"kind": "source_material_render", "scope": "from_posX_negY", "uri": "/mnt/nas-h/zhf/rhg_style_attributes_20261013_v1/evidence_images/.png", "sha256": "…"}, + "review": {"kind": "Qwen3-VL-32B-Instruct_visual_inference", "uri": "…/evidence_records/review/.json", "sha256": "…"}, + "…": "…" + } +} +``` + + + +### 4.3 全库检索矩阵(`full_asset_matrix.enriched_20261031.sqlite3`) + +把 37,279 条目录记录(29,577 个对象、3,728 个材质、3,288 个片段、680 个房间/整场景、6 个灯光)按六组整理。2026-10-31 补齐了 27,448 条资产的 84,153 个字段。 + +| 表 / 视图 | 行数 | 列 | 用途 | +|---|---:|---|---| +| `corpus_assets` | 37,279 | `asset_id, asset_kind, category, source, description, dim_x/y/z, review_status, source_usability, record_json, …` | 每个资产一行 | +| `corpus_tags` | 244,694 | `asset_id, facet, value, status, evidence_json` | **关键词表**,取值见 4.4 节 | +| `corpus_style_memberships` | 81,625 | `asset_id, style_id, score, status, reason, evidence_json` | 风格多标签及理由 | +| `corpus_style_taxonomy` | 15 | `style_id, name_zh, classification, record_json` | 风格词表 | +| `corpus_functions` | 67,101 | `asset_id, function_id, label, origin, scope, record_json` | 功能位,239 个不同标签 | +| `corpus_field_status` | 1,340,977 | `asset_id, content_group, field_name, state, source_status, reason` | 每个字段的状态 | +| `corpus_orientation_topics` | 223,674 | `asset_id, topic, status, frame, record_json` | 6 个朝向话题 | +| `corpus_search` | 37,279 | `asset_id, category, description, source, tags` | FTS5 全文索引,`tags` 是全部关键词拼成的检索串 | +| 其他 | — | `corpus_components`、`corpus_joint_motions`、`corpus_size_windows`、`corpus_evidence`、`corpus_source_links` 等 | 部件、关节、±10% 尺寸窗口、证据、来源绑定 | +| 视图 | — | `corpus_six_groups`、`corpus_same_size_candidates`、`corpus_style_function_matrix`、`corpus_asset_readiness`、`corpus_missing_dimensions` 等 | 查询入口 | + +**六组 102 个字段:** + +| 组 | 字段 | +|---|---| +| `semantic_function`(23) | `category`、`fine_type`、`semantic_role`、`description`、`description_zh`、`function_tags`、`functional_slots`、`asset_entry`、`asset_scope`、`source_quality`、`selection_verdict`、`component_inventory`、`catalog_category`、`material_catalog`、`registry_semantics`、`requested_function`、`existing_function_tags`,以及 `legacy_*`、`supplement_*` 字段 | +| `geometry_scale`(20) | `geometry`、`canonical_transform`、`source_units_and_axes`、`dimensions_xyz_m`、`footprint_and_bbox`、`measurement_frame`、`units_and_axes`、`visual_pose`、`orientation_up_and_frame`、`room_fit_verified`、`real_world_product_scale_verified`,以及 `legacy_*`、`partial_*`、`supplement_*` 字段 | +| `appearance_style`(10) | `style`、`style_suggestions`、`colors`、`rendered_palette`、`materials`、`material_appearance`、`material_category`、`previous_style`、`previous_colors`、`previous_materials` | +| `placement_space`(26) | `installation`、`installation_mode`、`usage_space`、`support`、`support_geometry`、`support_relation`、`surface_compatibility`、`opening_envelope`、`functional_front`、`functional_front_views`、`room_compatibility`、`placement_tags`、`placement_constraints_zh`、`assembly_dependencies`、`validated_clearance_m`、`orientation_{functional_front,mounting,handedness,equivalent_rotation}`、`unqualified_front_suggestion` 等 | +| `interaction_kinematics`(12) | `source_kinematics`、`authored_joints`、`movable_joint_count`、`visible_parts`、`pose_qualification`、`grasp_points`、`deformable_behavior`、`orientation_opening_motion`、`runtime_operation_status` 等 | +| `physics`(11) | `source_body_properties`、`source_collision_properties`、`source_physics_materials`、`source_stage_units`、`legacy_collision_declaration`、`whole_object_mass_kg`、`inertia_tensor`、`contact_friction`、`real_material_composition`、`simulation_verified`、`physics_simulation_verified` | + +字段状态只有 5 种:`present` 804,689、`missing` 411,387、`not_applicable` 62,629、`partial` 58,964、`conflict` 3,308。质量、摩擦、惯量和真实材料组成全部为 `missing` 或 `not_applicable`。 + +朝向话题有 6 个:`functional_front`、`up_and_frame`、`mounting`、`opening_motion`、`handedness`、`equivalent_rotation`。 + +完整的六组记录另存为 `records/normalized_assets.jsonl.gz`,每行一个资产,顶层键为 `schema, asset_id, entry_key, asset_kind, category, asset_scope, review_status, source_usability, source_identity, runtime_uri, source_uri, description, groups, orientation_topics, classification, current_file_identity`。 + + + +### 4.4 关键词表 + +**`corpus_tags` 的 8 个维度:** + +| 维度 `facet` | 行数 | 不同取值 | 覆盖资产 | 取值 | +|---|---:|---:|---:|---| +| `room` | 82,317 | 575 | 24,829 | 自由文本,同义写法未合并。最多的是 bedroom 12,792、living_room 10,574、kitchen 8,895、living room 5,975、bathroom 5,933、office 5,439、dining_room 5,180、entryway 4,622、hallway 2,687、study 2,631 | +| `color` | 57,139 | 1,580 | 24,102 | 颜色名,自由文本。最多的是 white 11,192、black 5,353、off-white 3,951、light gray 3,736、dark gray 3,379、silver 2,358、beige 2,096、gray 1,508、dark brown 1,267、light beige 1,246 | +| `material_appearance` | 53,067 | 14,005 | 24,105 | 材质外观描述,自由文本;其中带 `_look` 后缀的规范写法 650 种,最多的是 wood_look 2,473、metal_look 1,586、plastic_look 870、fabric_look 754、ceramic_look 304、glass_look 225、stone_look 171、leather_look 107、concrete_look 101、cardboard_look 85、marble_look 80 | +| `installation` | 23,976 | 6 | 23,976 | floor 9,632、surface 8,478、wall 4,941、ceiling 798、built_in 67、unknown 60 | +| `function_tag` | 23,565 | 55 | 22,153 | 见下方完整列表 | +| `material_category` | 3,728 | 19 | 3,728 | 室内材质库专用:metal 506、wood 496、tile 443、fabric 324、floor 262、stone 259、brick 241、concrete 221、wall 208、glass 133、carpet 122、leather 120、plastic 105、detail 72、ceramic 71、terrazzo 69、wicker 45、light 21、acoustic 10 | +| `reviewed_palette` | 548 | 74 | 354 | 人工复核子集的中文配色:白 179、黑 79、米白 28、灰 23、浅木 20、银灰 16、灰白 13 等 | +| `reviewed_installation` | 354 | 11 | 354 | 复核子集的安装方式:floor 197、surface 64、wall 59、ceiling 18、counter_inset 4 等 | + +`corpus_tags.status` 的取值:`inherited_visual`(看图得到)、`inherited_semantic`、`inferred_category_semantics`(按类别推断)、`inferred`、`catalog_declared`、`image_inferred`、`conflict`。 + +**风格(`corpus_style_taxonomy`,15 个;多标签,数量不能相加):** + +| `style_id` | 中文 | 类型 | 资产数 | +|---|---|---|---:| +| `minimalist` | 极简 | 审美 | 16,809 | +| `modern` | 现代 | 审美 | 16,591 | +| `contemporary` | 当代 | 审美 | 13,341 | +| `scandinavian` | 北欧 | 审美 | 3,571 | +| `traditional` | 传统 | 审美 | 2,872 | +| `industrial` | 工业 | 审美 | 2,503 | +| `luxury` | 奢华 | 审美 | 1,389 | +| `rustic` | 乡村质朴 | 审美 | 964 | +| `bohemian` | 波西米亚 | 审美 | 624 | +| `coastal` | 海岸 | 审美 | 383 | +| `mid_century` | 世纪中期现代 | 审美 | 364 | +| `transitional` | 过渡 | 审美 | 314 | +| `japanese` | 日式 | 审美 | 193 | +| `utilitarian` | 实用功能 | 功能(非审美风格) | 8,530 | +| `unclassified` | 风格待定 | 未知 | 13,177 | + +**功能标签(`function_tag`,55 个):** storage 4,832、support_surface 2,374、decoration 2,371、seating 2,324、containment 1,855、floor_covering 970、reading 786、resting 765、illumination 758、sleeping 656、lighting 639、container 587、appliance 438、washing 424、work_surface 385、cooking 383、reflection 356、graspable 334、time_display 239、visual_screening 211、greenery 196、media_display 192、water_fixture 174、sanitary_fixture 152、bathing 139、visual_display 139、waste_collection 121、cold_storage 100、tableware 90、ventilation 90、heating 83、pickable 80、dining_support 72、dining 46、readable 38、laundry_washing 25、toileting 25、cooking_ventilation 18、shower 18、drying 13、display 12、book_storage 11、dish_washing 9、sanitation 7、decor 5、laundry_drying 5、tableware_support 4、view 4、drinkware 3、desk_work 2、clinical_patient_support 1、clothing_support 1、medical 1、obstetric_delivery 1、wet_fixture 1。 + +**类别与功能位:** + +- **资产类型 `asset_kind`:** OBJECT 29,577、MATERIAL 3,728、FRAGMENT 3,288、ROOM 680、LIGHTING 6。 +- **语义类别 `category` / `canonical_role`:** 3,337 个不同值。最多的是 unknown 3,501、cabinet 1,578、shelf 1,511、decorative_object 1,310、picture 1,292、rug 1,088、cushion 900、book 804、plant 719、side_table 700、ceiling_light 656、architectural_part 605、furniture_component 600、bed 572、armchair 568。 +- **功能位:** `corpus_functions` 有 239 个不同标签;检索索引的 `functional_slots` 表有 3,420 个不同值。最多的是 表面材质 3,728、unknown 3,501、片段/部件资源 3,288、containment 1,844、cabinet_general 1,775、storage 1,770、decoration 1,661、cabinet 1,591、shelf 1,526、picture 1,469。其中“表面材质”“片段/部件资源”“房间/整场景”三个中文值分别标记材质、片段和整场景条目。 +- **描述 `description`:** 自由文本,检索索引里 37,279 条都有(英文 35,282,中文 1,997)。 + +**颜色和材质外观的结构。** 每条颜色是 `{color_name, approx_hex, region}`,例如 `{"light_oak", "#D2B48C", "front doors and side panels"}`。每条材质外观是 `{material_appearance, region, confidence}`。`region` 也是自由文本,常见值有 entire object、frame、body、legs、top surface、base、handle、upholstery。 + + + +### 4.5 主分支检索索引里的标签(`full_matrix_reviewed_compatibility.sqlite3`) + +| 表 | 行数 | 列 | 内容 | +|---|---:|---|---| +| `annotations` / `assets` | 37,279 | `asset_id, category, …, record_json` | `record_json` 的键:`description, style_tags, colors, materials, function_tags, functional_slots, canonical_role, primary_role, category, dimensions_m, dimensions_frame, canonical_transform, units_and_up_axis, annotation_status, field_values, matrix_reference, canonical_path, runtime_path, asset_sha256, …` | +| `records` | 37,279 | `asset_id, record_id, source_sha256, record_json` | `record_json.attributes` 含 `style, colors, materials, shape`,结构与 4.2 节相同 | +| `function_tags` | 23,565 | `asset_id, tag` | 55 个功能标签 | +| `functional_slots` | 67,186 | `asset_id, slot` | 3,420 个功能位 | +| `retrieval_styles` | 13 | `style_id, name_zh` | 13 个审美风格;`utilitarian` 和 `unclassified` 不参与检索 | +| `style_role_candidates` | 136,911 | `style_id, role, asset_id, membership_status` | 风格 × 角色 × 资产的候选池;`membership_status` 为 inferred 136,854、reviewed_label_normalization 32、reviewed_compatibility 25 | +| `reviewed_style_compatibility` | 19 | `review_id, asset_id, style_id, review_sha256, review_json` | 19 条人工外观兼容复核 | + +`record_json` 里各标签的覆盖:`style_tags` 23,773 个对象、`colors` 24,102 个、`function_tags` 22,153 个;`materials` 字段全部为空,材质外观只在 `records.record_json.attributes.materials` 和全库矩阵里。 + + + +### 4.6 8 字段基础标注(`asset_annotations_23736.jsonl`) + +时间更早的一层,覆盖原主索引的 23,736 个对象,每行一个对象。顶层键为 `asset_id, asset_kind, canonical_path, schema, fields, runtime_import, rejected_evidence, human_approved, formally_accepted, formally_published, generation_is_not_acceptance`。 + +每个 `fields.<名称>` 的结构是 `{value, status, strict_status, candidates, evidence, strict_evidence, subfield_statuses, confidence, reason, verification_scope, …}`。 + +| 字段 | `value` 的主要键 | 状态分布 | +|---|---|---| +| `semantic` | `canonical_role, primary_role, fine_type, object_description` | confirmed 6,058;candidate 17,642;blocked 36 | +| `dimensions` | `dimensions_m, unit, measurement_frame, source, confidence` | measured_unverified 23,399;candidate 224;confirmed 36;blocked 77 | +| `function` | `function_tags, functional_slots, mapping_scope, usage_scope, slot_*` | candidate 14,497;confirmed 6,032;pending 3,168;blocked 39 | +| `direction` | `front_axis, functional_front_axis, door_front_axis, screen_front_axis, render_front_axis, axis_frame, orientation_policy` | candidate 23,188;confirmed 167;pending 345;not_applicable 35;blocked 1 | +| `asset_entry` | `asset_id, canonical_path, format, loaded_source, mesh_count` | confirmed 22,848;generated 725;blocked 163 | +| `coordinate_transform` | `source_to_canonical`(4×4)、`source_to_offline_canonical`、`transform_scope` | measured_unverified 23,034;pending 503;blocked 163;confirmed 35;candidate 1 | +| `units_and_up_axis` | `up_axis, meters_per_unit, handedness, units_basis, physical_up_axis` | measured_unverified 23,033;pending 503;blocked 163;confirmed 36;generated 1 | +| `pivot_and_hierarchy` | `pivot_m, hierarchy, parent_asset_id, external_parent_verified, scale, policy` | confirmed 20,906;measured_unverified 2,164;candidate 498;blocked 163;pending 5 | + +**主要取值:** + +- **状态词:** `generated`、`candidate`、`measured_unverified`、`confirmed`、`not_applicable`、`pending`、`blocked`。 +- **方向轴:** `+X`、`-X`、`+Y`、`-Y`、`+Z`、`-Z`、`AMBIGUOUS`、`not_applicable`。`front_axis` 中 AMBIGUOUS 占 19,621 个。 +- **`orientation_policy`:** not_applicable 18,090、source_bound_existing_visual_candidate 2,355、symmetric 1,553、confirmed_axis 676、existing_axis798_candidate 672 等。 +- **`units_basis`:** glTF_2_spec_meters_right_handed_Y_up 14,740、USD_authored_stage_upAxis_and_metersPerUnit 6,891、URDF_SI_meters_source_joint_default_pose 1,500。 +- **`function_tags`:** 这一层只有 41 个,如 storage、support_surface、seating、resting、decoration、lighting;`functional_slots` 有 102 个。 +- **`object_description`:** 英文,15,413 个对象有,中位长度 126 字符。 + +--- + + + +## 5. 格式转换 + + + +### 5.0 总表 + +“README”一列:✅ 表示 RHG 的 `README.md` 或 `docs/` 写了这个脚本;— 表示没写。 + +| 编号 | 对象 | 格式变化 | 脚本(项目:相对路径) | README | 何时何地 | 主分支检索库 | +|---|---|---|---|---|---|---| +| T0 | Lightwheel、ReplicaCAD、GSO、YCB 的压缩包 | 只解包,格式不变 | PUB `control/prepare_archives.py` | — | 11-15,各下载机 | 不用 | +| T1 | GSO、YCB、单个 Poly Haven USD | OBJ → USD;USD 原样复制 | RHG `scripts/convert_asset.py`,辅助 `scripts/blender_convert_asset.py`;11-15 再加 `scripts/author_isaac_asset_metadata.py` | ✅ README 第 316–317 行 | 上游(2026-09 前);11-15 H200-1 | 5 条 | +| T2 | GSO 24、Poly Haven 32 | GSO:zip 内 OBJ → USDC;Poly Haven:复制 USDC。两者再写入 Z-up、米制和碰撞元数据 | RHG `scripts/preprocess_high_fidelity_assets.py`,辅助 `scripts/blender_convert_high_fidelity_batch.py`、`scripts/author_isaac_asset_metadata.py`;驱动 PUB `control/readme_asset_conversion.py` | ✅ README 第 319–385 行 | 11-15 H200-1 | 不用 | +| T3 | GSO USD | 只改贴图的资产路径 | AUDIT `repair_gso.py` | — | 10-13 | 22 条 | +| T4 | HSSD GLB | GLB 内 KTX2 贴图 → 原始 PNG/JPEG | AUDIT `download_upstream_stream.py`(下载)+ `restore_hssd_textures.py` | — | 10-13 | 10,683 条 | +| T5 | HSSD GLB | 改用官方原版并修正 MIME;删除空扩展数组 | AUDIT `recover_hssd_original_variants.py`、`consolidate_hssd.py` | — | 10-13 | 210 条 | +| T6 | ArtVIP、InteriorAgent、Lightwheel 的 USD | 只改依赖路径,另存为 `.usdc` | AUDIT `repair_dependency_paths.py`,校验 `verify_usd_repairs.py` | — | 10-13 | 820 条 | +| T7 | T6 之后仍缺依赖的 USD 层 | 依赖改指向精确原件;改写 MDL 里的贴图路径 | REPAIR2 `fetch_nvidia.py`(下载)+ `repair_exact.py` | — | 10-13 | 30 条 | +| T8 | 无法精确恢复的 USD 层 | 缺失贴图换成常量色、禁用缺失法线、换用替代 HDRI | REPAIR2 `build_material_palette.py` + `repair_variants.py` | — | 10-13 | 116 条 | +| T9 | 厨房 PBR 中 5 个植物 FBX | FBX → `.blend` + `.usdc` | REPAIR2 `repair_plants.py` | — | 10-13 | 不用 | +| T10 | MolmoSpaces | TAR → `.tar.zst` → USD 目录 | AUDIT `molmo_audit.py` + `assemble_molmo_namespace.py`;PUB `control/prepare_archives.py --mode molmospaces` | — | 10-13 NAS;11-15 H20-96-1 | 5,841 条 | +| T11 | USD 里 Blender 不能直接连接的 MDL 材质 | MDL → 线性 EXR 通道 → Blender 材质库 `.blend` | RHG `scripts/setup_mdl_sdk.py`、`scripts/prepare_asset_pool.py`、`scripts/validate_material_assets.py`、`scripts/seal_material_acceptance.py`;worker 为 TREE `engine/source/scripts/internal/scene_generation/real_assets/mdl_sdk_worker.py` | ✅ `docs/official-mdl-pipeline.md`(worker 文件未点名) | 10-13 STYLE | 场景用到 | +| T12 | 室内材质库里的 ambientCG 图集 | DirectX 法线 → OpenGL 法线(PNG) | TREE `engine/source/scripts/internal/scene_generation/real_assets/uploaded_interior_materials.py` | — | 每次生成时,结果进缓存 | 场景用到 | +| T13 | 室内材质库的 ambientCG 与金属材质 | 重下官方包;新的 USDA 材质修订;Blender 材质库 | AUDIT `recover_ambientcg.py`、`repair_ambientcg_bundle.py`、`build_repaired_blender_materials.py` | — | 10-13 | 不用 | +| T14 | GSO(3 个) | OBJ → GLB | TREE `engine/source/scripts/internal/scene_generation/real_assets/prepare_gso_source_assets.py` | — | 产物在 LIB `runtime_derivatives/stable_real_assets_v1/`;T2 借用了它的解压函数 | 不用 | +| T15 | RPLAN 户型 | Graph2Plan `data.mat` → 户型库 JSON → `rooms.json`、`floorplan.svg/png` | TREE `tools/rplan/convert_rplan.py`、`tools/rplan/screen_library.py`;本机 `release_prep/cases20_floorplans/rebuild_cases20_floorplans.py` | — | — | 20 个输入 | + + + +### 5.1 T0 只解包 + +- **脚本:** PUB `control/prepare_archives.py --mode {gso,lightwheel,replicacad,ycb,molmospaces}`。下载器是 `control/downloader.py`,清单格式为 `rphome.public_asset_download.v1`。各机清单由本机 `rphome_scripts/asset_downloads_20261115/build_manifests.py` 生成。 +- **做法:** 解 zip/tgz。成员路径不能越出目标目录;中途中断的文件先写 `.extract-partial`,完成后再改名。不改任何文件内容。 +- **校验**(回执在各下载机的 `control/` 下,本机 `rphome_scripts/asset_downloads_20261115/` 有副本): + - Lightwheel(H200-1):378 个 USD 的 MD5 与注册表一致(`lightwheel-checks.json`)。 + - ReplicaCAD(H20-96-4):185 项 MD5 一致(`replicacad-checks.json`)。必须用 v1.4 zip,HF 当前快照有 5 个 GLB 与之不同。 + - YCB(H20-96-4):OBJ 的 MD5 一致(`ycb-checks.json`)。tgz 解到 `derived/ycb/models/`。 +- **不经解包:** HSSD、ArtVIP、InteriorAgent 是 HF 快照逐文件下载,没有压缩包。 + + + +### 5.2 T1 `scripts/convert_asset.py`:网格 → USD + +- **README 依据:** 第 316–317 行:“`scripts/convert_asset.py` converts common mesh formats to USD”。同段说明,新资产在 Isaac 尺度、碰撞、质量和关节 QA 之前不能用于正式评分。 +- **做法:** + - `.usd/.usda/.usdc/.usdz`:直接复制,连同同级 `textures/`。manifest 记为 `converter: copy-usd`。 + - `.blend/.fbx/.glb/.gltf/.obj`:Blender 后台运行辅助脚本 `scripts/blender_convert_asset.py`。按扩展名导入:OBJ 用 `bpy.ops.wm.obj_import`(默认参数),glTF 用 `import_scene.gltf`,FBX 用 `import_scene.fbx`。然后 `bpy.ops.wm.usd_export(export_materials=True, relative_paths=True)`。manifest 记为 `converter: blender`。 + - URDF/MJCF:需另给 `--isaac-converter-command`,本项目没用到。 + - 每个输出旁写 `<输出>.manifest.json`,字段为 `source`、`output`、`converter`、`dependencies_copied`、`qa_status: CONVERTED_VISUAL_ONLY`、`scoring_allowed: false`。 +- **上游产物**(在 DATA 中,manifest 里的路径是 `/data/wyc/RoboHouseGenData/...`,没有运行日志): + - **GSO 24 个:** `GSO-fuel//model/meshes/model.obj` → `GSO-fuel/usd/.usdc`,`dependencies_copied: 0`。MTL 写的是 `texture.png`,图片实际在 `model/materials/textures/`,所以导出的 USD 引用了一个不存在的 `texture.png`。T3 修正了这个问题。 + - **YCB 2 个:** `models/{003_cracker_box,006_mustard_bottle}/google_16k/textured.obj` → `models//textured.usd`。另外 3 个没有转换,检索库直接指向 OBJ。 + - **Poly Haven 1 个:** `polyhaven/cardboard_box_01/cardboard_box_01_2k.usdc` → `converted/cardboard_box_01.usdc`。这是 copy-usd,复制了 3 个依赖。 +- **11-15 重跑(H200-1,Blender 5.2.1):** + - YCB 5 个 → PUB `derived/readme_ycb_20261115//{asset.usdc, asset.usdc.manifest.json, textures/}`。 + - 随后跑 `scripts/author_isaac_asset_metadata.py`,写入 Z-up、米制和碰撞(同 T2 第 4 步)。 + - 技术检查 5/5(`control/ycb-conversion-technical-check.json`),没有做视觉验收。 + +**朝向:** 这一步用默认轴向导入 OBJ,GSO、YCB 转换件侧躺,详见[第 6 节第 2 条](#notes)。 + + + +### 5.3 T2 `scripts/preprocess_high_fidelity_assets.py`:README 高保真预处理 + +- **README 依据:** “High-fidelity asset preprocessing”一节(第 319–385 行)。它把 GSO 和 Poly Haven 源包转成独立的规范 USD 库:Z-up、米制,每个网格显式加 `UsdPhysics.CollisionAPI`,保留 PBR 贴图包,经 USD 运行时验证;不修改原始的 `assets/raw`。 +- **驱动:** PUB `control/readme_asset_conversion.py`(11-15 由 Codex 编写,记录了 `source_revision=07e8172…`)。步骤如下: + 1. 按 `control/conversion-source-manifest.json` 逐个核对输入文件的大小和 MD5。然后用硬链或软链把输入排成 README 要求的目录:`conversion_managed_inputs/raw/gso_fuel_collection_full/collection-2022-06-13-snapshot-20260828/archives/` 和 `…/polyhaven_models_full_2k/api-models-20260828-2k/models/`。 + 2. **GSO 预处理:** + - 调用 TREE `engine/source/scripts/internal/scene_generation/real_assets/prepare_gso_source_assets.py` 的 `extract_source_archive()`,把 zip 安全解压到 `canonical/gso//`。驱动加载的是 snap_paper_20261110 树中的同名文件,与 TREE 中的文件 SHA-256 相同。 + - 把 `materials/textures/texture.png` 同字节复制为 `meshes/texture.png`(MTL 写的是 `map_Kd texture.png`),核对 MD5。24 条记录在 `control/gso.conversion.json` 的 `texture_aliases` 里。 + - 第一次运行(`derived/readme_high_fidelity_20261115`)缺这一步,GSO 贴图没有绑定,已作废。 + 3. 运行 `scripts/preprocess_high_fidelity_assets.py --stage convert --sources gso,polyhaven --blender --usd-python conversion_env/bin/python --blender-batch-size 24 --usd-batch-size 128`: + - **GSO**(`source_kind=gso_zip_obj`):Blender 后台运行 `scripts/blender_convert_high_fidelity_batch.py`。依次恢复出厂设置,用默认参数 `bpy.ops.wm.obj_import`,再 `bpy.ops.wm.usd_export(export_materials=True, relative_paths=True, root_prim_path="/Asset")`,输出 `canonical/gso//asset.usdc`。这一步有朝向问题,见[第 6 节第 2 条](#notes)。 + - **Poly Haven**(`source_kind=polyhaven_usd`):不经过 Blender。把 `_2k.usdc` 和同级 `textures/` 复制到 `canonical/polyhaven//`,权限改为 0644。 + 4. 两类都再跑 `scripts/author_isaac_asset_metadata.py`(USD Python): + - 没有 defaultPrim 时,设为第一个网格。 + - 设 `upAxis = Z`、`metersPerUnit = 1.0`。只改元数据,不旋转、不缩放几何。 + - 在根 prim 写 customData:`robothousegen:isaac_compatible = true`、`robothousegen:canonical_frame = "Z-up meters"`。 + - 贴图路径找不到时(Poly Haven 包里残留了发布者机器上的绝对路径),在 `textures/` 下按同名文件查找,改写为 `./textures/<文件名>`。 + - 对每个 Mesh 应用 `UsdPhysics.CollisionAPI`,设 `collisionEnabled = true`。 +- **输出:** PUB `derived/readme_high_fidelity_textures_v2_20261115/`(1.1G):`canonical/{gso,polyhaven}/`、`preprocess_plan.json`(56 项全部 `ready`)、`preprocess_report.json`、`jobs/`。 +- **校验:** `control/readme-conversion-technical-check.json` 56/56,范围是 USD 重新打开、网格、碰撞、贴图绑定、依赖和有限包围盒。 +- **局限:** 没有做视觉验收(`runtime_ready = false`),也没有执行 `--stage release`,所以没有生成新的 ACTIVE 检索索引。 + + + +### 5.4 T3 AUDIT `repair_gso.py`:GSO 贴图路径 + +- **输入:** T1 上游的 `GSO-fuel/usd/.usdc`。 +- **做法:** + - 先核对源 zip 里 `materials/textures/texture.png` 的 SHA-256 与解压出的贴图一致。 + - 用 `Sdf.Layer.CreateNew` + `TransferContent` 把层完整复制到 `repairs/gso/.usdc`。 + - 用 `UsdUtils.ModifyAssetPaths` 把文件名为 `texture.png` 的引用改为绝对路径 `…/GSO-fuel//model/materials/textures/texture.png`。 + - 把资产路径全部抹掉后比较新旧层的结构哈希,确认只有资产路径变了。 +- **结果:** 24 个,状态为 `repaired_verified`,回执 `gso_repair_receipt.json`。几何没有改动,所以继承了 T1 的侧躺朝向。 + + + +### 5.5 T4 AUDIT HSSD 贴图还原 + +- **为什么要做:** hssd-hab 的 GLB 贴图是 KTX2(`KHR_texture_basisu`),Blender 的 glTF 导入器读不了。 +- **上游原图:** `download_upstream_stream.py` 从 HF `hssd/hssd-models` @ `208ea6bc22d863bbc1cbaef1829b3e646600dfb6` 下载未压缩的官方 GLB,存到 `repairs/hssd_originals//`(35G)。回执为 `hssd_download_receipts.jsonl`。 +- **做法**(`restore_hssd_textures.py`,逐个 GLB): + 1. 核对上游文件的 SHA-256,并要求上游与压缩版的图像数量一致。上游图像必须是 GLB 内嵌的 PNG 或 JPEG。 + 2. 把上游每张图的原始字节追加到压缩版二进制缓冲区的末尾,作为新的 bufferView。`images[i]` 改为指向它,并写入对应的 `mimeType`。 + 3. 从每个 texture 删除 `KHR_texture_basisu` 扩展,并从 `extensionsUsed`、`extensionsRequired` 中删除该项。 + 4. 原二进制缓冲区(含压缩几何)逐字节不变,材质和采样器不变。图像不重新编码,也不经过 basisu 解码。 + 5. 保存后重新读回,逐张核对图像字节的 SHA-256。 +- **输出:** `repairs/hssd_restored/objects//.glb`,10,940 个(33G)。每个资产一份回执 `hssd_restoration/.json`,记录 `status=restored_verified`、每张图的尺寸和 SHA-256、`geometry_binary_prefix_preserved`、`material_sampler_contract_preserved`、`visual_render_status=pending`。汇总在 `hssd_restoration_results.jsonl`。 +- **未处理:** 3,141 个常量材质资产没有贴图,不需要还原。 +- **另一条 KTX2 路径:** AUDIT `tools/basisu` 是审计和渲染对比时解码 KTX2 用的,不参与生成还原件。RHG 的 `packages/asset_registry/basisu.py`(`normalize_basisu_glb`,需要 `RHG_KTX_TOOL`)只在 T2 加 `--include-base-active` 时用,本项目没用。 + + + +### 5.6 T5 AUDIT HSSD 原版变体与元数据修正 + +- **`recover_hssd_original_variants.py`:** 用于 T4 精确回填失败的资产,保留完整的官方上游 GLB。 + - 用 Pillow 识别每张内嵌图的真实格式,`mimeType` 写错时改正,只接受 PNG/JPEG。 + - 核对结构未变、几何和图像字节未变。 + - 输出 `repairs/hssd_original_variants/`,186 个(18 个物体、168 个房屋外壳),状态为 `official_original_variant_verified`,回执 `hssd_original_variant_receipts.json`。 +- **`consolidate_hssd.py`:** + - 对还原件,删除空的 `extensionsUsed`、`extensionsRequired` 数组,输出 `repairs/hssd_json_metadata_fixed/`(196 个)。 + - 合并 T4、T5 的结果,生成 `hssd_final_results.jsonl`,共 11,126 条(10,940 + 186)。 + + + +### 5.7 T6 AUDIT `repair_dependency_paths.py`:USD 依赖路径 + +- **对象:** ArtVIP、InteriorAgent、Lightwheel 等 USD 中缺失的依赖,以及要靠 MDL 搜索路径解析的依赖。 +- **解析来源:** + - 共享 MDL 搜索路径:`repairs/mdl/isaacsim_core/{Base,mdl,Ue4,VRay,Blender,Nonvisual,Volume}`、`repairs/mdl/2023_1`、`repairs/mdl/2023_2_1`(含 Library/AEC/Materials/Templates)。 + - 或者同一提供方内“路径后缀唯一、内容也唯一”的文件。 +- **做法:** 把受影响的 USD 层和引用它的上层复制为 `repairs/usd_dependency_paths/.usdc`,只改资产路径。写出的依赖是绝对路径,例如 `/mnt/nas-h/zhf/rhg_asset_audit_20261013_v1/repairs/mdl/isaacsim_core/Base/OmniPBR.mdl`。同时生成 `runtime_paths.env`(`RHG_MDL_SEARCH_PATH`)。 +- **校验:** 957 个 USD 层验证通过,解析了 1,190 条依赖记录。校验脚本 `verify_usd_repairs.py`,回执 `dependency_path_repairs.json`、`usd_repair_fresh_hash_verification.json`。 + + + +### 5.8 T7 REPAIR2 `repair_exact.py`:精确修复 + +- **对象:** T6 之后仍缺依赖的层(AUDIT `release/remaining_gaps.jsonl` 共 251 条)。 +- **依赖来源**(按顺序尝试): + - `fetch_nvidia.py` 从 NVIDIA Omniverse 内容 S3 取回的 `Materials/2023_2_1/…` 原件,递归抓取 MDL 依赖,存到 `downloads/nvidia/`。 + - NVIDIA `Materials/Base/Wood` 贴图,包括把导出器编号的副本名(`_1.`)还原为原名。 + - 同一资产包里的贴图(修正作者机器上的绝对路径)。 + - 同一场景里的同名贴图。 + - `WorldGridMaterial.mdl`。 +- **做法:** + - MDL 文件里 `texture_*("…")` 的贴图路径用正则改写,存到 `repairs/mdl//`。 + - USD 层用 `UsdUtils.ModifyAssetPaths` 改路径后 `Export` 为 `repairs/usd/.usdc`。 +- **结果:** 34 层、74 条依赖(`exact_repairs.json`)。 + + + +### 5.9 T8 REPAIR2 `repair_variants.py`:功能变体(替代材质) + +- **对象:** 无法精确恢复的层。 +- **做法:** 生成“功能性材质变体”,原件不覆盖: + - 缺失的可选法线贴图置空(`optional_missing_normal_disabled`)。 + - 缺失的 HDRI 换成 Poly Haven 摄影棚 HDRI。 + - 材质内缺失的贴图换成常量颜色 `inputs:color`。替代材质来自 `build_material_palette.py` 导出的 `palette.usdc`,选材记录在 `materials/palette_provenance.json`。 + - 导出后断言几何与原层一致。 +- **结果:** 133 层,另有 98 处内部引用修正(`variant_repairs.json`)。这些条目在发布清单中标为 `uses_substitute=true`,**外观不是原件**。检索库有 116 条指向它们(REPAIR2 `release/availability_summary.json` 的 `with_marked_substitution: 116`)。 +- **相关:** + - `configure_material_templates.py` 另配置了 16 个替代材质(`configured_material_substitutes.jsonl`)。 + - `png_metadata_repairs.json` 记录了 6 张 PNG 删除无效 `iCCP` 块的修复,像素流不变;没有找到对应的独立脚本。 + + + +### 5.10 T9 REPAIR2 `repair_plants.py`:植物 FBX + +- **对象:** `pbr_upload_20261005/植物/` 下 5 个 FBX。 +- **做法:** + - Blender 导入 FBX,从同一个 4K 高光工作流贴图包恢复贴图连线,存为 `repaired_material_complete.blend`。 + - 再 `wm.usd_export(export_materials=True, export_textures_mode='NEW', generate_preview_surface=True, relative_paths=False)`,得到 `repaired.usdc`。 + - 之后又修正了粗糙度节点,得到 `repaired_roughness_corrected.usdc`(`plant_usd_gloss_correction.json`)。 +- **输出:** `repairs/plants/`(41 个文件,599M)。主分支没用。 + + + +### 5.11 T10 MolmoSpaces 解包 + +- **AUDIT(主分支使用的版本):** + - `molmo_audit.py` 按检索库里的 `molmospaces://#<资产>.tar.zst` 定位,用 zstandard 解出每个资产的内层包,存到 `repairs/molmo_extracted//`。会检查成员路径是否安全,单包展开上限 16 GiB。 + - `assemble_molmo_namespace.py` 为审计发现缺失的 `objects/thor/…` 依赖,在 `repairs/objects/thor/` 下建目录软链,指向解包副本。 + - 结果:502 个归档父项,5,841 个模型变体(5,721 USDA + 120 USDC),格式不变。回执 `molmo_summary.jsonl`、`molmo_namespace_receipt.json`。 +- **PUB 11-15(H20-96-1):** `control/prepare_archives.py --mode molmospaces`。外层 `.tar` 解到 `derived/molmospaces/packages/`;每个 `*.tar.zst` 用 `zstd -dc | tar` 解到 `derived/molmospaces/unpacked/`;共 13,663 个文件。 + + + +### 5.12 T11 MDL 材质离线烘焙 + +- **README 依据:** `docs/official-mdl-pipeline.md`。Blender 读 USD 时,有些 MDL 材质图没能连接起来。对这类材质,用 NVIDIA MDL SDK 加载模块、构建类型化调用图、编译,蒸馏到 `transmissive_pbr` 并烘焙通道,再重建 Blender 节点。这一切只在离线准备阶段做。已连接的原生材质图保持不变;缺输入或资源时明确报错,不用灰色兜底。 +- **脚本**(RHG,均在 docs 中写明): + - `scripts/setup_mdl_sdk.py`:安装 MDL SDK 2026.0.2,校验官方压缩包的 SHA-256。 + - `scripts/prepare_asset_pool.py init/worker/finalize`:准备资产池并调用 worker。TREE 另有一份 `engine/source/scripts/prepare_asset_pool.py`。 + - `scripts/validate_material_assets.py init/worker`:每个材质渲染四个视角,供独立外观审查。 + - `scripts/seal_material_acceptance.py`:封存验收证据。 + - `scripts/qualify_runtime_release.py`:运行时变更时做源/运行时成对检查。该文件不在抽取副本里。 +- **worker:** TREE `engine/source/scripts/internal/scene_generation/real_assets/mdl_sdk_worker.py`。它在 SDK 自带的 Python 中运行,与 Blender 分开。bake_cache 里每个 `result.json`(schema `rhg.official_mdl_bake.v1`)都记录了 `worker_sha256 = ec5a12d6…`,与 TREE 中这个文件的 SHA-256 完全一致,说明 10-13 的烘焙就是这份代码做的。批量启动器在 STYLE `mdl_offline_assets_c15/code/mdl_benchmark_worker.py`。worker 的步骤如下: + 1. 读 `request.json`(schema `rhg.official_mdl_request.v1`)。里面有每个 Shader 节点的 MDL 模块路径与哈希、输入值、贴图的解析路径与 gamma。例如 Lightwheel 冰箱的 `OmniPBR.mdl`,取自 AUDIT `repairs/mdl/isaacsim_core/Base/`。 + 2. 构建调用图并编译。 + 3. 用 SDK 蒸馏器转换到 `transmissive_pbr`。 + 4. 在 CPU 上烘焙各通道,默认分辨率 1024×1024;常量通道烘成 1×1,值直接写进 `result.json`。 + 5. 非常量通道转为 `Rgb_fp`,导出线性 EXR(gamma 1.0),如 `base_color.exr`、`metallic.exr`、`roughness.exr`、`normal.exr`、`anisotropy.exr`、`anisotropy_rotation.exr`,并记录 SHA-256。 +- **输出:** 工具为 STYLE `mdl_sdk/MDL-SDK-2026.0.2-391700.2276-linux-x86-64`。 + - `mdl_offline_assets_c15/bake_cache//{*.exr, request.json, result.json, worker.log}`(12G)。 + - Blender 侧据此重建节点,打包为 `material_libraries///{materials.blend, manifest.json}`(12G)。manifest 绑定源/运行时哈希、规范变换矩阵、Blender 版本、网格拓扑、UV、材质槽、节点图和解码后的像素。 +- **验收:** 结果在 STYLE `material_acceptance_{B,C,D}_final/`;主分支使用 STYLE 根目录下的 `material_acceptance_D_combined_index.json`。 + - 10-13 主基准有 545 个原始资产案例:416 个通过材质库读回和四视图验收,129 个执行失败(111 个明确报错,18 个导入进程崩溃)。 + - 生成场景时不编译 MDL,只加载已封存的材质库(docs 记录为 0 次 MDL 编译请求)。 +- **局限:** docs 明确说蒸馏是近似,不是对源 MDL 的无损复现。 + + + +### 5.13 T12 法线贴图 DirectX → OpenGL + +- **脚本:** TREE `engine/source/scripts/internal/scene_generation/real_assets/uploaded_interior_materials.py`,函数 `convert_directx_normal()`,常量 `CONVERSION = 'normal_dx_to_gl_encoded_green_255_minus_g_v1'`。 +- **对象:** 室内材质库 `materials/interior_blender_20261009/资源依赖/{large,small}/<类目>/<名称>/` 中注册的 ambientCG 图集。每套要求 `<名称>_Color`、`_Roughness`、`_NormalDX`、`_Displacement`(jpg/png)各有且只有一张。 +- **做法:** + - 读入 `_NormalDX` 图(只接受 8 位 RGB/RGBA),绿色通道取 255 − G,R、B、A 不变,存为 PNG `normal_gl.png`。 + - 转换中途若源文件变化则报错。 + - 结果按源图 SHA-256 缓存:`<缓存>/material_catalog/normal_dx_to_gl/<源 sha256>/{normal_gl.png, conversion.json}`。回执 schema 为 `rhg.normal_conversion.v1`,记录 transform、源与结果的 SHA-256、尺寸、模式,以及 `source_convention=DirectX`、`target_convention=OpenGL`。再次运行时核对哈希,命中则复用。 + - Color、Roughness 原样使用;Displacement 保留,但不用于结构几何。 +- **时机:** 生成场景时执行,不是离线发布件。主分支 55 个场景引用了 196 张 `normal_gl.png` 和 206 个 JSON(402 个文件,1.11G),需要随场景一起打包。 + + + +### 5.14 T13 AUDIT ambientCG 与 Blender 材质修复 + +- **`recover_ambientcg.py`:** + - 对象:室内材质库里缺通道的 ambientCG 材质。 + - 先确认现有通道与官方包逐像素一致,再从 ambientCG 官方接口重新下载对应 zip。 + - 输出 `repairs/ambientcg/<名称>_<分辨率>-JPG/`(4.2G),日志 `ambientcg_recovery.jsonl`。 +- **`repair_ambientcg_bundle.py`:** 生成一致的新材质修订 `repaired_material.usda`,旧版保留,共 110 个。 +- **`build_repaired_blender_materials.py`:** 把发布者的原版 Blender 材质载入 `repairs/interior_materials/official_metal_materials.blend`,记录在 `release/interior_materials_repaired.jsonl`,共 110 个。 + + + +### 5.15 T14 TREE `prepare_gso_source_assets.py`:GSO → GLB(主分支未用) + +- **做法:** + 1. 校验 zip 的 MD5 和大小与注册记录一致,解压到 `//original/`。 + 2. 把贴图同字节复制到 MTL 旁边,MTL 本身不改。 + 3. Blender `wm.obj_import(forward_axis='Y', up_axis='Z')`,核对导入后尺寸与原始顶点一致。 + 4. 打包图像,`export_scene.gltf(export_format='GLB', export_yup=True)`。 + 5. 核对 GLB 内嵌贴图字节与源图一致,再导入一次核对尺寸不变。 + 6. 输出 `.glb` + `provenance.json`。 +- **输出与使用情况:** 产物在 LIB `runtime_derivatives/stable_real_assets_v1/`,共 3 个 GSO:ACE_Coffee_Mug_Kristen_16_oz_cup、Footed_Bowl_Sand、Threshold_Dinner_Plate_Square_Rim_White_Porcelain。主分支检索库的 GSO 条目都是 USD,没有用这些 GLB。T2 只借用了它的解压函数。 + + + +### 5.16 T15 RPLAN 户型转换 + +- **路径:** Graph2Plan `Data.zip` 的 `Network/data.mat`(RPLAN 派生)→ 每个案例一个户型库 `ext_libs/x_.json` → 共享输入 `rooms.json`、`floorplan.svg/png`。 +- **脚本:** + - TREE `tools/rplan/convert_rplan.py`、`tools/rplan/screen_library.py`:新转换器,用于 scene_018。 + - 十月转换用于其余 19 个,公式已写进本机 `release_prep/cases20_floorplans/rebuild_cases20_floorplans.py`。 +- **说明:** 分组、哈希与校验见 `release_prep/cases20_floorplans/README.md`。RPLAN 禁止再分发,公开版只给编号和转换脚本。 + +--- + + + +## 6. 注意事项 + +1. **HSSD 贴图的处理方式(更正)。** + - hssd-hab 的 GLB 贴图是 KTX2(`KHR_texture_basisu`),Blender 的 glTF 导入器读不了。 + - T4 的做法:从 HF `hssd/hssd-models` @ `208ea6bc22d863bbc1cbaef1829b3e646600dfb6` 的未压缩版本中,取出同序号的原始 PNG/JPEG 字节追加进 GLB,并删除 `KHR_texture_basisu` 扩展。压缩几何逐字节不变;图像不重新编码,也没有经过 basisu 解码。 + - 旧文档《服务器资产清点与复现准备》第 4.2、4.4 节原来写的是“basisu 解码”,已改正。 + - 还原件回执里 `visual_render_status` 仍是 `pending`,还没有逐个渲染核对。 +2. **GSO、YCB 转换件朝向错误(新发现)。** + - **原因:** T1、T2 用 Blender 默认参数导入 OBJ(forward −Z、up Y),即把 OBJ 的 Y 轴当作向上,导出 USD 时不再转换。结果是原始 OBJ 的 z 方向尺寸落到 USD 的 Y 轴上,舞台的 `upAxis` 却是 Z。 + - **后果:** GSO 和 YCB 的原始 OBJ 是 Z 向上,所以转换件绕 X 轴转了 90°,在 Z-up 舞台里侧躺。T3 只改贴图路径,同样侧躺。实测尺寸如下: + + | 资产 | 原始 OBJ 尺寸 x / y / z(m) | 转换后 USD 尺寸 X / Y / Z(m) | + |---|---|---| + | GSO ACE_Coffee_Mug_Kristen_16_oz_cup(杯高 0.135 m) | 0.126 / 0.091 / 0.135 | 0.126 / 0.135 / 0.091(T1 上游、T2、T3 相同) | + | GSO HeavyDuty_Flashlight | 0.078 / 0.078 / 0.229 | 0.078 / 0.229 / 0.078 | + | YCB 003_cracker_box | 0.072 / 0.164 / 0.213 | 0.072 / 0.213 / 0.164(T1 上游、11-15 相同) | + | YCB 025_mug(11-15) | 0.117 / 0.093 / 0.081 | 0.117 / 0.081 / 0.093 | + + - **不受影响的:** Poly Haven 原件本来就是 Z-up、米制的 USD,T2 只复制不导入(例如 dining_chair_02 高 0.973 m,转换前后都在 Z 轴)。TREE 的 `prepare_gso_source_assets.py`(T14)导入时用 `forward_axis='Y', up_axis='Z'`,并核对导入前后尺寸一致,也没有这个问题。 + - **影响范围:** 主分支 55 个场景没有用到 GSO 或 YCB,已有结果不受影响。以后要用这些转换件,需要改用正确的导入轴向重新转换。 +3. **README 只覆盖 3 道转换,且有文件缺失(因为后续有新资产补充,所以还需要更新readme)。** + - 16 道转换里,RoboHouseGen 的 README/docs 只写了 T1、T2、T11。其余都是 AUDIT、REPAIR2、TREE 的内部脚本,没有 README,路径与做法见第 5 节。 + - README/docs 提到、但 RHG 抽取副本里没有的文件: + - `scripts/download_polyhaven_assets.py`、`scripts/merge_asset_catalogs.py`、`scripts/enrich_asset_orientation_index.py` + - `scripts/qualify_runtime_release.py`、`scripts/query_assets.py`、`scripts/setup_asset_bundle.py` + - `configs/prepared_asset_quarantine.json`、`configs/asset_bundle.release.json` + - NAS 上的 `wyc2/RoboHouseGen` 是旧检出(HEAD `c2da12e`,2026-08-05),不含提交 `07e8172`,上面这些文件里只有前两个。发布前要从 RoboHouseGen 仓库的 `07e8172` 补齐。这些文件做的是下载、索引合并与增强、查询、部署和成对检查,都不是格式转换脚本。 +4. **项目修复脚本写死了 NAS 绝对路径。** AUDIT、REPAIR2 的脚本里写死了 `/mnt/nas-h/zhf/...`。T3、T6、T7、T8 的修复层写入的依赖也都是绝对路径(已抽查)。换机器要么保持同一路径,要么用 `docs/asset-bundle-setup.md` 说的路径别名(`sudo -n unshare` 只读挂载)。不要只改 SQLite 里的路径。 +5. **厨房模型和厨房 PBR 的来源。** 两处的目录与文件命名都是 Poliigon 的打包格式:`Generic/`、`Previews/`、`Software/` 目录,贴图后缀 `_COL_`、`_GLOSS_`、`_NRM_`。部分目录里还有“淘宝店铺 CG素材铺子.txt”“关注公众号AN素材库.png”这类文件。应按第三方商业素材处理,不能公开。 +6. **T8 是替代材质。** 116 条检索库条目的外观不是原件。只想用原件时,按 `uses_substitute=true` 过滤(REPAIR2 `release/USAGE.txt` 第 2 条)。 +7. **11-15 转换件不能替代项目修复件。** T1、T2 的 11-15 转换件只做了技术检查:没有视觉验收,`runtime_ready=false`,也没有执行 release。复现时用项目发布的修复件和检索索引。 +8. **验证尚不完整。** AUDIT 的渲染对比只做了 146 对(修复件)和 110 对(原生材质),几何全部一致,没有失败。全库视觉与物理认证都没有做(`whole_library_render_certified=false`、`physics_certified=false`)。 +9. **富文本标签的局限。** + - 置信度是模型自报,未经校准(`confidence_basis: model_self_report_uncalibrated`)。`unknown` 表示没有证据,不表示否定。 + - 房间、颜色、材质外观、区域都是自由文本,同义写法没有合并,例如 `living_room` 和 `living room`、`light_gray` 和 `light gray`。按关键词检索时要先归一化。 + - 主分支检索索引 `annotations.record_json` 的 `materials` 字段全部为空,材质外观只在属性记录和全库矩阵里有。 + - `utilitarian`(实用功能)不是审美风格,检索索引只收 13 个审美风格。 + - 质量、摩擦、惯量和真实材料组成全部缺失;看到木纹外观不代表真是木材。 +10. **主分支没用 BC7 贴图预算包。** README 开头 2026-10-21 一条提到交付烘焙的贴图预算包(BC7 颜色贴图 + PNG8 非颜色通道)。主分支 55 个场景的外部依赖里没有 DDS 或 KTX2 文件,没有用到这个预算包。 diff --git a/manifests/files.tsv b/manifests/files.tsv new file mode 100644 index 0000000000000000000000000000000000000000..f1684121e334e2fc0339cb841140bedb1679c3ec --- /dev/null +++ b/manifests/files.tsv @@ -0,0 +1,244 @@ +./.gitattributes 2504 +./README.md 1349 +./bundles/artvip_original.tar.zst 4204679184 +./bundles/artvip_original.tar.zst.sha256 141 +./bundles/converted_public.tar.zst 10757089 +./bundles/converted_public.tar.zst.sha256 142 +./bundles/gso_derived_public.tar.zst 11453865 +./bundles/gso_derived_public.tar.zst.sha256 144 +./bundles/gso_original.tar.zst 11451772 +./bundles/gso_original.tar.zst.sha256 138 +./bundles/hssd_derived_public.tar.zst 30853337563 +./bundles/hssd_derived_public.tar.zst.sha256 145 +./bundles/hssd_metadata_fixed.tar.zst 546208773 +./bundles/hssd_metadata_fixed.tar.zst.sha256 145 +./bundles/hssd_original.tar.zst 6673414377 +./bundles/hssd_original.tar.zst.sha256 139 +./bundles/hssd_original_variants.tar.zst 300862512 +./bundles/hssd_original_variants.tar.zst.sha256 148 +./bundles/lightwheel_original.tar.zst 236439581 +./bundles/lightwheel_original.tar.zst.sha256 145 +./bundles/molmospaces_extracted.tar.zst 831422559 +./bundles/molmospaces_extracted.tar.zst.sha256 147 +./bundles/polyhaven_original.tar.zst 18491217 +./bundles/polyhaven_original.tar.zst.sha256 144 +./bundles/replicacad_original.tar.zst 11420075 +./bundles/replicacad_original.tar.zst.sha256 145 +./docs/reproduction/asset_release_plan/hf_upload_manifest.tsv 5371 +./docs/reproduction/asset_release_plan/主分支资产类别与论文数字对照_20261121.md 8830 +./docs/reproduction/asset_release_plan/资产开源与复现准备_主分支_20261121.html 10747 +./docs/reproduction/asset_release_plan/资产开源与复现准备_主分支_20261121.md 17776 +./docs/reproduction/cases20_floorplans/README.md 5270 +./docs/reproduction/cases20_floorplans/cases20_public.json 59344 +./docs/reproduction/cases20_floorplans/rebuild_cases20_floorplans.py 24720 +./docs/reproduction/cases20_floorplans/recipes_cases20.json 40860 +./docs/reproduction/public_conversion_code/README.md 21705 +./docs/reproduction/public_conversion_code/configs/assets/front_axis_overrides_v1.json 2507 +./docs/reproduction/public_conversion_code/docs/asset-bundle-setup.md 4648 +./docs/reproduction/public_conversion_code/docs/official-mdl-pipeline.md 15300 +./docs/reproduction/public_conversion_code/packages/__init__.py 44 +./docs/reproduction/public_conversion_code/packages/__pycache__/__init__.cpython-311.pyc 235 +./docs/reproduction/public_conversion_code/packages/adapters/__init__.py 729 +./docs/reproduction/public_conversion_code/packages/adapters/arena.py 648 +./docs/reproduction/public_conversion_code/packages/adapters/embodiedgen.py 4259 +./docs/reproduction/public_conversion_code/packages/adapters/protocols.py 572 +./docs/reproduction/public_conversion_code/packages/adapters/rp1.py 2146 +./docs/reproduction/public_conversion_code/packages/adapters/rparena.py 31055 +./docs/reproduction/public_conversion_code/packages/adapters/rparena_baked.py 9137 +./docs/reproduction/public_conversion_code/packages/adapters/rparena_native.py 10147 +./docs/reproduction/public_conversion_code/packages/adapters/rparena_usd_worker.py 4619 +./docs/reproduction/public_conversion_code/packages/adapters/rparena_v16.py 59620 +./docs/reproduction/public_conversion_code/packages/adapters/sam3d.py 8366 +./docs/reproduction/public_conversion_code/packages/adapters/scenesmith.py 14218 +./docs/reproduction/public_conversion_code/packages/adapters/source_device.py 1551 +./docs/reproduction/public_conversion_code/packages/adapters/texture_compression.py 10118 +./docs/reproduction/public_conversion_code/packages/adapters/texture_metrics.py 3660 +./docs/reproduction/public_conversion_code/packages/asset_registry/__init__.py 621 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/__init__.cpython-311.pyc 980 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/admission.cpython-311.pyc 16532 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/basisu.cpython-311.pyc 10362 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/certification_models.cpython-311.pyc 10515 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/descriptors.cpython-311.pyc 20230 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/front_certification.cpython-311.pyc 40062 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/front_policy.cpython-311.pyc 2642 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/models.cpython-311.pyc 13133 +./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/release.cpython-311.pyc 112349 +./docs/reproduction/public_conversion_code/packages/asset_registry/admission.py 11409 +./docs/reproduction/public_conversion_code/packages/asset_registry/articulation.py 15455 +./docs/reproduction/public_conversion_code/packages/asset_registry/basisu.py 6857 +./docs/reproduction/public_conversion_code/packages/asset_registry/certification.py 15126 +./docs/reproduction/public_conversion_code/packages/asset_registry/certification_models.py 5800 +./docs/reproduction/public_conversion_code/packages/asset_registry/context_usd.py 16925 +./docs/reproduction/public_conversion_code/packages/asset_registry/descriptors.py 12249 +./docs/reproduction/public_conversion_code/packages/asset_registry/embeddings.py 2138 +./docs/reproduction/public_conversion_code/packages/asset_registry/expansion.py 5261 +./docs/reproduction/public_conversion_code/packages/asset_registry/front_certification.py 26640 +./docs/reproduction/public_conversion_code/packages/asset_registry/front_policy.py 2146 +./docs/reproduction/public_conversion_code/packages/asset_registry/index.py 18135 +./docs/reproduction/public_conversion_code/packages/asset_registry/ingestion.py 18218 +./docs/reproduction/public_conversion_code/packages/asset_registry/models.py 7177 +./docs/reproduction/public_conversion_code/packages/asset_registry/multiview.py 17282 +./docs/reproduction/public_conversion_code/packages/asset_registry/native_usd.py 33226 +./docs/reproduction/public_conversion_code/packages/asset_registry/parametric.py 7821 +./docs/reproduction/public_conversion_code/packages/asset_registry/preparation.py 19704 +./docs/reproduction/public_conversion_code/packages/asset_registry/proxy_sdf.py 3501 +./docs/reproduction/public_conversion_code/packages/asset_registry/release.py 75131 +./docs/reproduction/public_conversion_code/packages/asset_registry/repository.py 1566 +./docs/reproduction/public_conversion_code/packages/asset_registry/runtime_repair.py 6912 +./docs/reproduction/public_conversion_code/packages/asset_registry/source_reporting.py 6406 +./docs/reproduction/public_conversion_code/packages/asset_registry/style.py 9230 +./docs/reproduction/public_conversion_code/packages/asset_registry/task_aliases.py 3302 +./docs/reproduction/public_conversion_code/packages/asset_registry/usd_front_evidence.py 6901 +./docs/reproduction/public_conversion_code/packages/benchmark/__init__.py 91 +./docs/reproduction/public_conversion_code/packages/benchmark/artifact_lifecycle.py 14355 +./docs/reproduction/public_conversion_code/packages/benchmark/domain_randomization.py 18051 +./docs/reproduction/public_conversion_code/packages/benchmark/packager.py 5834 +./docs/reproduction/public_conversion_code/packages/benchmark/performance_compare.py 16900 +./docs/reproduction/public_conversion_code/packages/benchmark/portable.py 27267 +./docs/reproduction/public_conversion_code/packages/benchmark/request.py 8464 +./docs/reproduction/public_conversion_code/packages/benchmark/suite_builder.py 16518 +./docs/reproduction/public_conversion_code/packages/benchmark/suite_matrix.py 2883 +./docs/reproduction/public_conversion_code/packages/benchmark/task_library.py 4799 +./docs/reproduction/public_conversion_code/packages/config/__init__.py 138 +./docs/reproduction/public_conversion_code/packages/config/generation.py 5194 +./docs/reproduction/public_conversion_code/packages/core/__init__.py 39 +./docs/reproduction/public_conversion_code/packages/core/__pycache__/__init__.cpython-311.pyc 235 +./docs/reproduction/public_conversion_code/packages/core/__pycache__/files.cpython-311.pyc 2764 +./docs/reproduction/public_conversion_code/packages/core/contracts/__init__.py 1561 +./docs/reproduction/public_conversion_code/packages/core/contracts/asset.py 887 +./docs/reproduction/public_conversion_code/packages/core/contracts/providers.py 4895 +./docs/reproduction/public_conversion_code/packages/core/contracts/scene.py 8296 +./docs/reproduction/public_conversion_code/packages/core/file_lock.py 1388 +./docs/reproduction/public_conversion_code/packages/core/files.py 1069 +./docs/reproduction/public_conversion_code/packages/core/state_machine.py 1872 +./docs/reproduction/public_conversion_code/packages/evaluator/__init__.py 247 +./docs/reproduction/public_conversion_code/packages/evaluator/engine.py 16754 +./docs/reproduction/public_conversion_code/packages/evaluator/suite.py 2710 +./docs/reproduction/public_conversion_code/packages/generative/__init__.py 120 +./docs/reproduction/public_conversion_code/packages/generative/client.py 12012 +./docs/reproduction/public_conversion_code/packages/plugins/__init__.py 29 +./docs/reproduction/public_conversion_code/packages/plugins/tasks/__init__.py 916 +./docs/reproduction/public_conversion_code/packages/plugins/tasks/base.py 5140 +./docs/reproduction/public_conversion_code/packages/plugins/tasks/builtins.py 4387 +./docs/reproduction/public_conversion_code/packages/plugins/tasks/cabinet_open_close.py 15409 +./docs/reproduction/public_conversion_code/packages/plugins/tasks/pick_move_place.py 13019 +./docs/reproduction/public_conversion_code/packages/providers/__init__.py 267 +./docs/reproduction/public_conversion_code/packages/providers/assets/__init__.py 592 +./docs/reproduction/public_conversion_code/packages/providers/assets/base.py 4198 +./docs/reproduction/public_conversion_code/packages/providers/scenes/__init__.py 625 +./docs/reproduction/public_conversion_code/packages/providers/scenes/base.py 1557 +./docs/reproduction/public_conversion_code/packages/providers/scenes/metric_v2.py 1817 +./docs/reproduction/public_conversion_code/packages/providers/scenes/scenesmith_visual.py 3664 +./docs/reproduction/public_conversion_code/packages/robots/__init__.py 162 +./docs/reproduction/public_conversion_code/packages/robots/profiles.py 1831 +./docs/reproduction/public_conversion_code/packages/robots/task_constraints.py 3926 +./docs/reproduction/public_conversion_code/packages/runtime/__init__.py 278 +./docs/reproduction/public_conversion_code/packages/runtime/blender_resident.py 3432 +./docs/reproduction/public_conversion_code/packages/runtime/gpu_scheduler.py 5251 +./docs/reproduction/public_conversion_code/packages/runtime/isaac/__init__.py 647 +./docs/reproduction/public_conversion_code/packages/runtime/isaac/contracts.py 3696 +./docs/reproduction/public_conversion_code/packages/runtime/isaac/evaluator.py 2689 +./docs/reproduction/public_conversion_code/packages/runtime/isaac/injection.py 8209 +./docs/reproduction/public_conversion_code/packages/runtime/paths.py 1225 +./docs/reproduction/public_conversion_code/packages/runtime/scenesmith_parallel.py 79973 +./docs/reproduction/public_conversion_code/packages/runtime/scenesmith_process_bootstrap.py 815 +./docs/reproduction/public_conversion_code/packages/runtime/scenesmith_skill_policy.py 5300 +./docs/reproduction/public_conversion_code/packages/runtime/stack_batch.py 3303 +./docs/reproduction/public_conversion_code/packages/scenarios/__init__.py 212 +./docs/reproduction/public_conversion_code/packages/scenarios/router.py 877 +./docs/reproduction/public_conversion_code/packages/scenarios/stair_room.py 19235 +./docs/reproduction/public_conversion_code/packages/scene_generation/__init__.py 1358 +./docs/reproduction/public_conversion_code/packages/scene_generation/agent_executor.py 22406 +./docs/reproduction/public_conversion_code/packages/scene_generation/agent_orchestration.py 25533 +./docs/reproduction/public_conversion_code/packages/scene_generation/agent_runtime.py 23916 +./docs/reproduction/public_conversion_code/packages/scene_generation/asset_first.py 59904 +./docs/reproduction/public_conversion_code/packages/scene_generation/bundle_compiler.py 27580 +./docs/reproduction/public_conversion_code/packages/scene_generation/compiler.py 4216 +./docs/reproduction/public_conversion_code/packages/scene_generation/conflict_resampling.py 2342 +./docs/reproduction/public_conversion_code/packages/scene_generation/delivery_reports.py 23159 +./docs/reproduction/public_conversion_code/packages/scene_generation/dependency_graph.py 16571 +./docs/reproduction/public_conversion_code/packages/scene_generation/design_contract.py 16245 +./docs/reproduction/public_conversion_code/packages/scene_generation/deterministic_placement.py 61696 +./docs/reproduction/public_conversion_code/packages/scene_generation/functional_front.py 9964 +./docs/reproduction/public_conversion_code/packages/scene_generation/generation_profile.py 6776 +./docs/reproduction/public_conversion_code/packages/scene_generation/geometry_task.py 5796 +./docs/reproduction/public_conversion_code/packages/scene_generation/global_pose_repair.py 11502 +./docs/reproduction/public_conversion_code/packages/scene_generation/hierarchical_execution.py 12769 +./docs/reproduction/public_conversion_code/packages/scene_generation/local_optimization.py 8842 +./docs/reproduction/public_conversion_code/packages/scene_generation/manipulation_physics.py 12716 +./docs/reproduction/public_conversion_code/packages/scene_generation/metric_layout.py 71797 +./docs/reproduction/public_conversion_code/packages/scene_generation/motifs.py 13988 +./docs/reproduction/public_conversion_code/packages/scene_generation/multi_room.py 51196 +./docs/reproduction/public_conversion_code/packages/scene_generation/orchestrator.py 49821 +./docs/reproduction/public_conversion_code/packages/scene_generation/pbr.py 27075 +./docs/reproduction/public_conversion_code/packages/scene_generation/pick_move_place.py 27441 +./docs/reproduction/public_conversion_code/packages/scene_generation/production_agent_handlers.py 36098 +./docs/reproduction/public_conversion_code/packages/scene_generation/prompt_multi_room.py 7528 +./docs/reproduction/public_conversion_code/packages/scene_generation/robot_constraints.py 14037 +./docs/reproduction/public_conversion_code/packages/scene_generation/semantic_constraints.py 7808 +./docs/reproduction/public_conversion_code/packages/schemas/__init__.py 895 +./docs/reproduction/public_conversion_code/packages/schemas/models.py 13576 +./docs/reproduction/public_conversion_code/packages/supervisor/__init__.py 568 +./docs/reproduction/public_conversion_code/packages/supervisor/case.py 21506 +./docs/reproduction/public_conversion_code/packages/supervisor/models.py 5184 +./docs/reproduction/public_conversion_code/packages/supervisor/planner.py 4329 +./docs/reproduction/public_conversion_code/packages/supervisor/quality.py 51915 +./docs/reproduction/public_conversion_code/packages/supervisor/runner.py 43806 +./docs/reproduction/public_conversion_code/packages/supervisor/snapshot.py 11628 +./docs/reproduction/public_conversion_code/packages/supervisor/visual_preflight.py 1517 +./docs/reproduction/public_conversion_code/packages/task_agent/__init__.py 329 +./docs/reproduction/public_conversion_code/packages/task_agent/compiler.py 4048 +./docs/reproduction/public_conversion_code/packages/task_agent/declared_transfer.py 5866 +./docs/reproduction/public_conversion_code/packages/task_agent/generator.py 4509 +./docs/reproduction/public_conversion_code/packages/task_agent/service.py 1063 +./docs/reproduction/public_conversion_code/packages/task_agent/skills.py 821 +./docs/reproduction/public_conversion_code/packages/task_agent/spec_agent.py 29020 +./docs/reproduction/public_conversion_code/packages/task_catalog/__init__.py 84 +./docs/reproduction/public_conversion_code/packages/task_catalog/html_import.py 2088 +./docs/reproduction/public_conversion_code/packages/task_catalog/repository.py 2518 +./docs/reproduction/public_conversion_code/packages/usd_composer/__init__.py 82 +./docs/reproduction/public_conversion_code/packages/usd_composer/composer.py 11574 +./docs/reproduction/public_conversion_code/packages/validators/__init__.py 369 +./docs/reproduction/public_conversion_code/packages/validators/base.py 2060 +./docs/reproduction/public_conversion_code/packages/validators/task_plugin.py 5640 +./docs/reproduction/public_conversion_code/packages/version.py 134 +./docs/reproduction/public_conversion_code/scripts/author_isaac_asset_metadata.py 4335 +./docs/reproduction/public_conversion_code/scripts/blender_convert_asset.py 955 +./docs/reproduction/public_conversion_code/scripts/blender_convert_high_fidelity_batch.py 2458 +./docs/reproduction/public_conversion_code/scripts/convert_asset.py 2894 +./docs/reproduction/public_conversion_code/scripts/prepare_asset_pool.py 27727 +./docs/reproduction/public_conversion_code/scripts/preprocess_high_fidelity_assets.py 32221 +./docs/reproduction/public_conversion_code/scripts/seal_material_acceptance.py 7332 +./docs/reproduction/public_conversion_code/scripts/setup_mdl_sdk.py 3525 +./docs/reproduction/public_conversion_code/scripts/validate_material_assets.py 7108 +./docs/reproduction/public_download_control/conversion-source-manifest.json 81528 +./docs/reproduction/public_download_control/downloader.py 8415 +./docs/reproduction/public_download_control/gso.conversion.json 13613 +./docs/reproduction/public_download_control/lightwheel-checks.json 59859 +./docs/reproduction/public_download_control/lightwheel-prepare.log 200 +./docs/reproduction/public_download_control/lightwheel.files.json 289 +./docs/reproduction/public_download_control/lightwheel.preparation.json 213 +./docs/reproduction/public_download_control/lightwheel.status.json 627 +./docs/reproduction/public_download_control/lightwheel.verified.jsonl 172 +./docs/reproduction/public_download_control/manifest.json 646 +./docs/reproduction/public_download_control/polyhaven_models.conversion.json 13626 +./docs/reproduction/public_download_control/prepare_archives.py 6625 +./docs/reproduction/public_download_control/readme-conversion-controller.log 0 +./docs/reproduction/public_download_control/readme-conversion-resource-check.json 8891 +./docs/reproduction/public_download_control/readme-conversion-technical-check.json 17549 +./docs/reproduction/public_download_control/readme-conversion-textures-controller.log 0 +./docs/reproduction/public_download_control/readme-conversion.log 304 +./docs/reproduction/public_download_control/readme_asset_conversion.py 6135 +./docs/reproduction/public_download_control/worker.log 578 +./docs/reproduction/public_download_control/ycb-003_cracker_box.log 392 +./docs/reproduction/public_download_control/ycb-005_tomato_soup_can.log 400 +./docs/reproduction/public_download_control/ycb-006_mustard_bottle.log 398 +./docs/reproduction/public_download_control/ycb-025_mug.log 376 +./docs/reproduction/public_download_control/ycb-035_power_drill.log 392 +./docs/reproduction/public_download_control/ycb-author-jobs.json 1282 +./docs/reproduction/public_download_control/ycb-author-results.json 1376 +./docs/reproduction/public_download_control/ycb-author.log 0 +./docs/reproduction/public_download_control/ycb-conversion-technical-check.json 1459 +./docs/reproduction/public_download_control/ycb.conversion.json 751 +./docs/reproduction/资产清点与格式转换_20261119.md 116949 +./manifests/files.tsv 0 diff --git a/manifests/sha256sums.txt b/manifests/sha256sums.txt new file mode 100644 index 0000000000000000000000000000000000000000..9a187c07cabbe2d383dbb917bd7223da8c64c7c5 --- /dev/null +++ b/manifests/sha256sums.txt @@ -0,0 +1,245 @@ +9e75dd981de037ec3769f24f790e126bc5a160b6871f510214e68dc70649aeeb ./.gitattributes +93adb0c00d4ad209ded385e48c8ff9c596d2698146a58cc16ea949b00a514c86 ./README.md +51ffb9f1dbb3cca13eb9be534dfcfcd5a0a0ec1ea30d4cee5b3d729176abe5eb ./bundles/artvip_original.tar.zst +60b4fee7097ce1cef67243c74d45dc0a9300d511ca3baa65dfb954ed8010ad56 ./bundles/artvip_original.tar.zst.sha256 +7e018622fb958ee98b13364e0892944d618b81a53a68f861ccd0ccf3028003f2 ./bundles/converted_public.tar.zst +902cc5e325f7c4128deb27be787f137943be6fd53c1bb83cf11e0673e8d9d644 ./bundles/converted_public.tar.zst.sha256 +a7c6f37cb7159b930647cef61f611b65fbb82dc36dc73eff209064f57c6ee273 ./bundles/gso_derived_public.tar.zst +1b0205e8adac0b1e452b584c58adf6385098c50d882f539a92dfb4070697066b ./bundles/gso_derived_public.tar.zst.sha256 +eeb6cb3cdc87b9f647e406f11e217fe4fb66242978bf8958e8b950fa5e5540df ./bundles/gso_original.tar.zst +ad6f445f9e4bd56a6edf6516c54364516efb8a4bb6c8e9d8eaf1c44c91ca50ae ./bundles/gso_original.tar.zst.sha256 +1ded42b662da0a64d97ced1e58ac87bdfcde0bea99be32b82276117f37eb99e2 ./bundles/hssd_derived_public.tar.zst +01c0a82a5c563c15699f0f058256f159a33b1ab2105c70eb5bfcdaaefbfdc795 ./bundles/hssd_derived_public.tar.zst.sha256 +4248294578329e6bc97216c4fc782321f1d2e7032ec708ab608de9b88d52927d ./bundles/hssd_metadata_fixed.tar.zst +5c17423492e17f5f618dd823f940e901f9e67d6d3dbf55fade9619c473f4b502 ./bundles/hssd_metadata_fixed.tar.zst.sha256 +3036f7c62e6af3a45b3ee286d337484fa334a711f6d5f8a4e61c8735793bd89c ./bundles/hssd_original.tar.zst +5d6225c499cdc1f5cb326264d64aec07c0d7e4b2d037f71a743cae6e5abf5d83 ./bundles/hssd_original.tar.zst.sha256 +52c04ad61a8852f7d6cdb2cc5c7beabba0e50a2ec964454ff9e2326a9f67f2b7 ./bundles/hssd_original_variants.tar.zst +d41d7f7c9678f3e10230fee87c28db825aa5b3c0874f66a927aecbfb047ebde9 ./bundles/hssd_original_variants.tar.zst.sha256 +5187a073a6a515b76b2a4dc6b5bc30f2ba60f9b27667ecbb58783f18a65db8d4 ./bundles/lightwheel_original.tar.zst +095d2025fd6d06d52c2f8e2719738c9ab9c8603a687a3f430a86b264f2ce2126 ./bundles/lightwheel_original.tar.zst.sha256 +2af763aedc69ad5bad2f3f0da7b91c3de07cab304e5bc2329e32149646055184 ./bundles/molmospaces_extracted.tar.zst +7079c1156781f5aeb0d393719e1c8d340c82b5844467dffe24326a59b269db7d ./bundles/molmospaces_extracted.tar.zst.sha256 +b1c2532d2766aa6ca57f952a617cbdfc73aa9cfd0a43786715a5d13d8d31f799 ./bundles/polyhaven_original.tar.zst +1b52e15e2540f9d9d74325ad87c1eaa5b39e8d7cccf2287d4a832046b0104d97 ./bundles/polyhaven_original.tar.zst.sha256 +2dc4f25c2a068527ab32f5ec29d3d6062c32eb0b890525a9a625973edcdc7144 ./bundles/replicacad_original.tar.zst +616b1d2ed458b19f11207f6e4ccc8826ec902153d77408ec42f7b88e25066a99 ./bundles/replicacad_original.tar.zst.sha256 +c81ade7f9b18ec94cdf97e813e4f930770961b37756b6d2a49f8cf575386abc9 ./docs/reproduction/asset_release_plan/hf_upload_manifest.tsv +502d277d64c850a3436c5dcea8b900fb001c376668f5eacfad0361c3cdadad33 ./docs/reproduction/asset_release_plan/主分支资产类别与论文数字对照_20261121.md +753636a6814677ec202d06adfbe8cd9585de700bee22ed7b47a50bcfa13c918d ./docs/reproduction/asset_release_plan/资产开源与复现准备_主分支_20261121.html +71964d45acbffe646d4d728e3e6b06c6849dadced16d665f4583b441e2804c66 ./docs/reproduction/asset_release_plan/资产开源与复现准备_主分支_20261121.md +9a6f57e0295c95bd193ec9a59ee370f89e0b85c4c7bfc3b2f973a67c506dd279 ./docs/reproduction/cases20_floorplans/README.md +992d75055d47803a232724e0b019dadb834ea2b682545b4199a7e189808e57cb ./docs/reproduction/cases20_floorplans/cases20_public.json +9148eea689c58075c5c58520eed7c83a2588ffe550e36db9c84d5491cc13580a ./docs/reproduction/cases20_floorplans/rebuild_cases20_floorplans.py +1bf954c1aa68e057c5e684e4436598d89fa705cb111fe0bdf098eedec9d523c8 ./docs/reproduction/cases20_floorplans/recipes_cases20.json +c125e6b84d18fc416de25ef5430daf02749fd6dc26a03bfb0c9e85bfef3172b3 ./docs/reproduction/public_conversion_code/README.md +df0a794b26c7d844cebf073de9bfc27f7e248064c19670b1dcca683a5d25e5c0 ./docs/reproduction/public_conversion_code/configs/assets/front_axis_overrides_v1.json +5b804babfd544c0f8adfebe059d8e279cf3b366fafcd03c0aa42862d857dde0e ./docs/reproduction/public_conversion_code/docs/asset-bundle-setup.md +afa303d50fb1debaf1d304b92572a2623b7c9c730dbdcba4296dd43f1ca8bf8f ./docs/reproduction/public_conversion_code/docs/official-mdl-pipeline.md +8902e4d68881248e1cac341b76ef99b79836ca37bee4a0a9df420c1ead17bb66 ./docs/reproduction/public_conversion_code/packages/__init__.py +7fc4735e798e0fa30b5340a99a008adae71e6fd75836eea1072d6527b864d810 ./docs/reproduction/public_conversion_code/packages/__pycache__/__init__.cpython-311.pyc +be631a02576b5dd2ebe47de61acdb2331dd5e69ad10d4fba81da0f2a505a4bbe ./docs/reproduction/public_conversion_code/packages/adapters/__init__.py +e6f365cbdf9616bd05bae3108e11553ab22b71ce9d9cc763b125079d21fb272f ./docs/reproduction/public_conversion_code/packages/adapters/arena.py +0990d03695cad269d5e841f2a1aadd330c011991c980e74a7968d0bf4289d3d5 ./docs/reproduction/public_conversion_code/packages/adapters/embodiedgen.py +a2766770252ee233d6aecb145898ca0637d32ca95a2646a6f24520a58f19c9cc ./docs/reproduction/public_conversion_code/packages/adapters/protocols.py +97df1f97dc34a1d382c0eb66dd009ace84b49fc8126099b1bd7e6276fad43d67 ./docs/reproduction/public_conversion_code/packages/adapters/rp1.py +7d70286df3ffbcddf7b687cfbc12cd5ac56be0a60cd03872710d6fb03af2f237 ./docs/reproduction/public_conversion_code/packages/adapters/rparena.py +bdff335ab8d0628f995e07f1130ed3009b5bb62d82925f4fdd90f8d8f8926ca6 ./docs/reproduction/public_conversion_code/packages/adapters/rparena_baked.py +38a452c53dafc792b8178c354ecb00fd7724d2abd79d12a45fa0c18366516e81 ./docs/reproduction/public_conversion_code/packages/adapters/rparena_native.py +0bc39aeef9b4ea9aa0c0a3ae1c170bcbcd6b0c1a382540ea66ba805fd834567e ./docs/reproduction/public_conversion_code/packages/adapters/rparena_usd_worker.py +dd5598966f8146bc0f20d281a29eaff832143e7f7d785d6b849ad7a855c8c110 ./docs/reproduction/public_conversion_code/packages/adapters/rparena_v16.py +4678eb9cd0be6b7d498dea37aa8bcb794839124401ad4ef47747460356df9df2 ./docs/reproduction/public_conversion_code/packages/adapters/sam3d.py +4eb7635830c05c9773028cfbd4a915820105a8d93e43afb8ce9b5fd23608abd3 ./docs/reproduction/public_conversion_code/packages/adapters/scenesmith.py +de8e90959a8291107a67221ae894c0d000c2d99ccaa869753ef0a35379c0af09 ./docs/reproduction/public_conversion_code/packages/adapters/source_device.py +9b38c20897ec4d6d42a93405ddbd36eaa2b1f0a9c8f9b9d07e11d056743acc3f ./docs/reproduction/public_conversion_code/packages/adapters/texture_compression.py +9e88dbfe19978581e207c6978474c7e16720d5067336f91c707c3fb1eeb13318 ./docs/reproduction/public_conversion_code/packages/adapters/texture_metrics.py +296760cfce99cc0b75783105283c50d4918a308bf58d16cba85441a2e1d56fe2 ./docs/reproduction/public_conversion_code/packages/asset_registry/__init__.py +f6e6a9b44b62c0a8952aa77539bd77c50ecfc602955affb91378820b2491e0c8 ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/__init__.cpython-311.pyc +55a1c6d83ab1dd9ad2f0250999c3550396d9af59d06c1445ffce468d43383035 ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/admission.cpython-311.pyc +d46ef58a180dbd57faf73ff1e3098b5e949859e4cbfeb7070c1ae56cc267e3ec ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/basisu.cpython-311.pyc +b10e4b7324ac78768e03785e20df944abb22c40f26eca4d34b9f071c33223073 ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/certification_models.cpython-311.pyc +4da322d93dafe575215b88d373642d492aeedbbab199cfd4143430cacea11168 ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/descriptors.cpython-311.pyc +cf2204bf6876723872a1d9acb34c02d45be1740046f1840af0ff70d474fb5f57 ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/front_certification.cpython-311.pyc +4ccdb1604a6c5e612237bb50d92e358dcd885d2d80d3cf87761237d0e9746861 ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/front_policy.cpython-311.pyc +58002935dd4909cfedaf18f3d9107286db1051583923369324457ddd816a766d ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/models.cpython-311.pyc +262637d0cfce076d1608a561d0dc224834a39aa52b45e984c5b653d0cb36f6e8 ./docs/reproduction/public_conversion_code/packages/asset_registry/__pycache__/release.cpython-311.pyc +d844337bd9dda6adf55cd491892faa925146b4be6f415d5f28749e7e22874427 ./docs/reproduction/public_conversion_code/packages/asset_registry/admission.py +acedfb61d21a5a14a273c1e90a1a434f4700fd80df308df0635bdc75db5cf285 ./docs/reproduction/public_conversion_code/packages/asset_registry/articulation.py +3fe0cdca29284f4f3174a81f11aed5be403cdffbb4e4e30e685e2927c9982ed1 ./docs/reproduction/public_conversion_code/packages/asset_registry/basisu.py +c412acb9c2d842b316964efad1cf17a058854688cce6d39757bf847e779427f5 ./docs/reproduction/public_conversion_code/packages/asset_registry/certification.py +4a826dfc8097e766ceacf6f8ba3f7b2b6b28d9c86e7ce82f86af5d7e00b57f4d ./docs/reproduction/public_conversion_code/packages/asset_registry/certification_models.py +315eebfdee607319582803fc535c85eaf91094a3c346790c71a89093f12f7271 ./docs/reproduction/public_conversion_code/packages/asset_registry/context_usd.py +aad94c6208afc3d69e2eb8065174d85ef498ee9b765b6c86076eeb4754adb156 ./docs/reproduction/public_conversion_code/packages/asset_registry/descriptors.py +15329cbcc5e3ad009e574e0cc548b00174f363e8a701a404059b68acc0152729 ./docs/reproduction/public_conversion_code/packages/asset_registry/embeddings.py +94b0958f3606793aa7169b1762d11184a23f92c50b2d90bb8a87fab480e09fff ./docs/reproduction/public_conversion_code/packages/asset_registry/expansion.py +c9aabf64ebb8eb4f03558262f3e4b373fac964312abc4d47a39dde04f2f0b5f8 ./docs/reproduction/public_conversion_code/packages/asset_registry/front_certification.py +e29ad5a63e51ba41ad71a444b648ef375abdddd753718d797ba3f5f1799b7d59 ./docs/reproduction/public_conversion_code/packages/asset_registry/front_policy.py +9c6d4148b6ea667ceb01982b43c28a805060a2c55ab997041de5cede16d5a81c ./docs/reproduction/public_conversion_code/packages/asset_registry/index.py +23efa0982fecf5c7f7c7be97d38871bd9f0cae187e1eba32e647b19d4a22f3de ./docs/reproduction/public_conversion_code/packages/asset_registry/ingestion.py +958bbf65d532bb4a3fcb42edf4e19077b4dba0f80a41a97b9d570d057e9f8215 ./docs/reproduction/public_conversion_code/packages/asset_registry/models.py +f9ce4bb136cd5b3e0c2abf58fa9cd41c4dac45bb961015c64683fa4c1e01bf51 ./docs/reproduction/public_conversion_code/packages/asset_registry/multiview.py +15a28c980441ebed4701b05ea64bc28bf44fc0073e72207228bbbcf35843b642 ./docs/reproduction/public_conversion_code/packages/asset_registry/native_usd.py +b6c7c5e20b39dc38caddcf5921366a8ea0592c17ad26dfb3f35dfcd6ed648844 ./docs/reproduction/public_conversion_code/packages/asset_registry/parametric.py +f56c32cafd4aa048141a354edbce14c79380f1737fd32a1bcb9cf93778933998 ./docs/reproduction/public_conversion_code/packages/asset_registry/preparation.py +cd0851278ff9355c4f1158df39c554dd234c358f76a447f57dfd5ef225fc0dee ./docs/reproduction/public_conversion_code/packages/asset_registry/proxy_sdf.py +7247cee2d4b56a8c8ba20c800cc539af06461fba2652a522bf9101d41caeff91 ./docs/reproduction/public_conversion_code/packages/asset_registry/release.py +edb4b20eed588d2998b19555589e3cb5b742da25caeba8c4b79d1e6c602c652b ./docs/reproduction/public_conversion_code/packages/asset_registry/repository.py +83ea19fe02c215e346925aca74c7b2491b746bd1357363a4bee737b0522aaabe ./docs/reproduction/public_conversion_code/packages/asset_registry/runtime_repair.py +c28d5221ff45edb265ab9476d10888d4ab876b6b13c34008ead85484a4bcf04f ./docs/reproduction/public_conversion_code/packages/asset_registry/source_reporting.py +4004960e043b306709bba724ae5f1d26160c727bb6a4e75b5a06b29be7d118a7 ./docs/reproduction/public_conversion_code/packages/asset_registry/style.py +33b67b3169927a4b887a48e5e2ed198e345864e300f99a0a3550714b857703ed ./docs/reproduction/public_conversion_code/packages/asset_registry/task_aliases.py +778c06a0bb0ef1fee6aa2f0ab744c609a2497a0c08d6616c23bb2eb25b90be06 ./docs/reproduction/public_conversion_code/packages/asset_registry/usd_front_evidence.py +4cb97e5dd4484e4ca4c3f01df4e4477c5307610ab3620972ef11fc646fe29d5b ./docs/reproduction/public_conversion_code/packages/benchmark/__init__.py +fcf7458de68a1ad6c53322012462c2fd3e92febb95ecb4af29430c2ca40677a9 ./docs/reproduction/public_conversion_code/packages/benchmark/artifact_lifecycle.py +8682dd9b79d5018c81db82912a88d57f86703705cf825e30b56397cd26043832 ./docs/reproduction/public_conversion_code/packages/benchmark/domain_randomization.py +2409a7d77ecb8745f6fdaf519b44277fbfbc57b4efd1c029af54098060172cb5 ./docs/reproduction/public_conversion_code/packages/benchmark/packager.py +f5980dcd6d5d56aa0d8b7b5bef768ad3790cd1ef90b19b941b4d1cc189247294 ./docs/reproduction/public_conversion_code/packages/benchmark/performance_compare.py +ce1f4b462055f1ed30021b5647993b6ca0e46826bfc898a9724ed400877090f5 ./docs/reproduction/public_conversion_code/packages/benchmark/portable.py +f271377b7d8c8062d22f0853a3fdf2e37990de1e40bd7a509f9534ec7f2f0162 ./docs/reproduction/public_conversion_code/packages/benchmark/request.py +a13dabb2016e92eaba97755ee27362e200b848cdcf580df5e4174c9fab2ec15e ./docs/reproduction/public_conversion_code/packages/benchmark/suite_builder.py +98f5a91db9f2874cbc335774d6d1ccf12efb3e24604920170ee86f7399d0f9f8 ./docs/reproduction/public_conversion_code/packages/benchmark/suite_matrix.py +e220019c4b1de518622635cd71965765c0cada3d216a9e2654b282c361c56543 ./docs/reproduction/public_conversion_code/packages/benchmark/task_library.py +99536f2dbf8718d6816356dd25b785a13400634c051d7f299e4b5905dc2a6c36 ./docs/reproduction/public_conversion_code/packages/config/__init__.py +f1c326a4549a039e9468620a255e503f8ed3ea5768438bf073715372c19deecf ./docs/reproduction/public_conversion_code/packages/config/generation.py +a9f1e41132464e697bdf9d5d6e18b5deea4cf892210cfb067c9a68a28bfbf73b ./docs/reproduction/public_conversion_code/packages/core/__init__.py +0a2bef5478fa1936bf426dd015342e899756f15af575fa544d7d40c239c4700c ./docs/reproduction/public_conversion_code/packages/core/__pycache__/__init__.cpython-311.pyc +533fdb3d33078dab327f6df4ec208b46ebac38dd49fb8e0883fdd3c821076882 ./docs/reproduction/public_conversion_code/packages/core/__pycache__/files.cpython-311.pyc +ad0a1dbd3e0cfdcfb9fe7749e54aaa1bf478b6c406256ee278868ef699d83f31 ./docs/reproduction/public_conversion_code/packages/core/contracts/__init__.py +25f494f2577564b87f30eb0fc31aedc7bb34ac3a89dc05dfc06bfe5be3a13b0b ./docs/reproduction/public_conversion_code/packages/core/contracts/asset.py +031e0e7afe0e0804629c3611ca99bd00a1c53ac0d87e29e6d79b6a37711b8ec5 ./docs/reproduction/public_conversion_code/packages/core/contracts/providers.py +29db08ff20a980e7b7e630a57e2d7a6a3185a65adea2e510f03caf2f1966560f ./docs/reproduction/public_conversion_code/packages/core/contracts/scene.py +813a5221c189f8b8f253e5c3b143c6591a8b633f795dac573a0f0ff925f67e46 ./docs/reproduction/public_conversion_code/packages/core/file_lock.py +fdf9fd5d469b975793484fb4b296517bcf212c5e02f50b0ab2eec01740dd883f ./docs/reproduction/public_conversion_code/packages/core/files.py +bbc7ddb565a60a5308b00dceb907c010c6c243d0c795f3d94d5996756bcc21fd ./docs/reproduction/public_conversion_code/packages/core/state_machine.py +370fdd49d3d85afedbca741322272d91fda2fa923c5a24012e151fba4349a0cb ./docs/reproduction/public_conversion_code/packages/evaluator/__init__.py +f70f0d1a16948e7b0340c5ceb2e6d4c12c493246416d9b71cd956a4bd955515a ./docs/reproduction/public_conversion_code/packages/evaluator/engine.py +f966cde53b45eccec3a6c4b8006db17f242b507f5af12406c367f226cacc1dd3 ./docs/reproduction/public_conversion_code/packages/evaluator/suite.py +1db0f95a820b89507472e35ddabc80ce74c2bf2269fb1a65f3ca762257c5fa7d ./docs/reproduction/public_conversion_code/packages/generative/__init__.py +1710cf2055f3dd4bb164e173be4109dcc8c1af40cb6b4c1a148f54948c3bc000 ./docs/reproduction/public_conversion_code/packages/generative/client.py +c3a5e829355519973fbc6c1ccae20dd10521b1d37619b2df38bf3ae7fa5e1220 ./docs/reproduction/public_conversion_code/packages/plugins/__init__.py +a741b0cae80015a80ccd18e026af5e7acdb163beb8ec560db94ba4c32ea12e60 ./docs/reproduction/public_conversion_code/packages/plugins/tasks/__init__.py +2d92be497487b1e15bece916f1c972520988cb138ded7c5d7e45206765d70e0a ./docs/reproduction/public_conversion_code/packages/plugins/tasks/base.py +ffc18f354ced0e70e08b41f2f43d90e89f598cd6b5eed61cb18442d2cfd1d957 ./docs/reproduction/public_conversion_code/packages/plugins/tasks/builtins.py +1e515f2e6d22a9d385ed6af1b65d2b8febea0587a7d2fa534d3a2f862f287921 ./docs/reproduction/public_conversion_code/packages/plugins/tasks/cabinet_open_close.py +87aa3c4365c03ac9473cab768e26f6df4a4317f384a50c438b335272c73c12b3 ./docs/reproduction/public_conversion_code/packages/plugins/tasks/pick_move_place.py +709ac75f010ee4caecd6d19e6737da2d904996587e6b1095970646e449b0a7d7 ./docs/reproduction/public_conversion_code/packages/providers/__init__.py +0fe7572fdd67f7a555c6c6a034248174950673c9320d5b83212d97340ce7634e ./docs/reproduction/public_conversion_code/packages/providers/assets/__init__.py +ed3bf9cce53405aaf2d95cbf777ae8d1417a100efad2f24a8f8d93657a81bafe ./docs/reproduction/public_conversion_code/packages/providers/assets/base.py +ffe28063156ba0e76792543b90ba62309d7ccc88b5e2515ad55529753864d104 ./docs/reproduction/public_conversion_code/packages/providers/scenes/__init__.py +d39338d96650e367fd33b5ef658c0b15f6ec5f54e30db18c1f104714c14ea41b ./docs/reproduction/public_conversion_code/packages/providers/scenes/base.py +638a2eb210500acf1d72a19b7fffa3c3b2210f5e4c18eb213f4ecf0c23963d0b ./docs/reproduction/public_conversion_code/packages/providers/scenes/metric_v2.py +56b299a96edf0e07bec2dd37700ffd187e376bcc094e9349ea724c891e257a1c ./docs/reproduction/public_conversion_code/packages/providers/scenes/scenesmith_visual.py +0568005f9753c8fb0c7ecb0bd070de99614a5e32e58a575c8039710bcb878607 ./docs/reproduction/public_conversion_code/packages/robots/__init__.py +f9fd4c8e62d379c67c3b332d1f84065145b13ff02c366ddf8ca7d706a7b3b38a ./docs/reproduction/public_conversion_code/packages/robots/profiles.py +c94f159ba467c60b9c7f7a56e2e4a8508f1b054f8ab7f51dce59eacc2e69f220 ./docs/reproduction/public_conversion_code/packages/robots/task_constraints.py +31140a46f2fe094da538264a3e5373c737436836ab10d46381a2f3a8579494a3 ./docs/reproduction/public_conversion_code/packages/runtime/__init__.py +5070c0864a3c06fc38f53c528937685814b7ae129efad0dfae34acb6d2d8e4c8 ./docs/reproduction/public_conversion_code/packages/runtime/blender_resident.py +ce64b3ff8e397433770c52808e27bf2df2da91d8bea5df63f6a651981c468bee ./docs/reproduction/public_conversion_code/packages/runtime/gpu_scheduler.py +f8a34a480dc1fdd186cfada3dcf87ec06387d0af076b1df98cabc5a2cbe09d02 ./docs/reproduction/public_conversion_code/packages/runtime/isaac/__init__.py +1e0bd63c7f5ab9a4e070b9ff1930b4f5b7487fd1da6661686e6381f3f5d002a1 ./docs/reproduction/public_conversion_code/packages/runtime/isaac/contracts.py +5c482d91c5001ddfc6306a888b1f14bbf0fe0c69e9ab0e0be817e658b7d5f97a ./docs/reproduction/public_conversion_code/packages/runtime/isaac/evaluator.py +261d5b5d0c7021eed11213988538bf225f83ca14a89a3f0399a632fee3baaa02 ./docs/reproduction/public_conversion_code/packages/runtime/isaac/injection.py +f4b5758269d82de61302de1e68f90262be3aafa2eaf9c207fb576fddd9e41115 ./docs/reproduction/public_conversion_code/packages/runtime/paths.py +0e49c4c2f28d143919019830d92815434e1314b204c0773b0673bf596399e5ca ./docs/reproduction/public_conversion_code/packages/runtime/scenesmith_parallel.py +b2d4ed382c8410ed7bbd1a3410c015966297e35256dde6f8ead99c663cb6915e ./docs/reproduction/public_conversion_code/packages/runtime/scenesmith_process_bootstrap.py +18944adbe7dd4dac59bd972a964699e063beae2b0417986b539faa0fb4ee1eb1 ./docs/reproduction/public_conversion_code/packages/runtime/scenesmith_skill_policy.py +dfdc66b4c1ae251413e7c458e3ac6cdad846c97bd69784f67fc20cb65210caf1 ./docs/reproduction/public_conversion_code/packages/runtime/stack_batch.py +47242c36621a389a2cbada2f9fe9921f23303783d30daf8c18fb51effbe9afc5 ./docs/reproduction/public_conversion_code/packages/scenarios/__init__.py +a16c2b06cfdd40be7ec1837338ce59e564a972f54a1d83bfdba349188af0c8d6 ./docs/reproduction/public_conversion_code/packages/scenarios/router.py +90577bfab3efabb69dba76fa1c3f4d2d7549880456d72e6b057fe224422b6389 ./docs/reproduction/public_conversion_code/packages/scenarios/stair_room.py +29b0f41719ae5ee44e9cc55da28dd6af08699ac8161acacbf79b61b757aeae1d ./docs/reproduction/public_conversion_code/packages/scene_generation/__init__.py +9c92e3b56215e7c3b87ebc0e224d95822d8fcf74c0f844de219741ac79d7a6e1 ./docs/reproduction/public_conversion_code/packages/scene_generation/agent_executor.py +b9461aa401165364498a492821df28e8e1630bfccf44d60a12629791eb2f07bc ./docs/reproduction/public_conversion_code/packages/scene_generation/agent_orchestration.py +178a2ca3cd82a225f1683f83b127fb117f18a4ec3927a218aae6b4e28e144827 ./docs/reproduction/public_conversion_code/packages/scene_generation/agent_runtime.py +e1c142e28c7bd90b2700f1d757f0071f5501fd59e0a619d20ba213dde256e0da ./docs/reproduction/public_conversion_code/packages/scene_generation/asset_first.py +9b526cd1d2902498183e5a705cd7301b449b466b8500a871644d3ea4ab2fec8b ./docs/reproduction/public_conversion_code/packages/scene_generation/bundle_compiler.py +6b3c0e49e6e46a3364012a23108a22811c8e2a49b5e10b822248caaec17b4e3a ./docs/reproduction/public_conversion_code/packages/scene_generation/compiler.py +bcaa29cd002b6d5a0eefe4ffb0ce516415175f099fdcfca6b6663431deb8c543 ./docs/reproduction/public_conversion_code/packages/scene_generation/conflict_resampling.py +3f40be6c55efc7227cc09991d1f60690eb47fb367a7be4b786a507fa13d15bae ./docs/reproduction/public_conversion_code/packages/scene_generation/delivery_reports.py +a44ae98c22f14bb76cac1365b21778e1d5d893a977dcd09fd14d478817fdb64a ./docs/reproduction/public_conversion_code/packages/scene_generation/dependency_graph.py +bab55e1375aa129d51801ed3b15271a5365437fadfa43ad14f4bc27ea6f6a7b3 ./docs/reproduction/public_conversion_code/packages/scene_generation/design_contract.py +e2bdf328bd78f8f4413e49223e859609d2a61fd7405b5be6fb81ba979158dc5a ./docs/reproduction/public_conversion_code/packages/scene_generation/deterministic_placement.py +80ad44d559d1fe42ae430ad470e6f937f9cc8a100f58d8e5fde24a12d70509a4 ./docs/reproduction/public_conversion_code/packages/scene_generation/functional_front.py +7cb6c04e1a70a7787bb69feda7204c31d34c7958d71f0ea2ff0335a7d7ce6cf9 ./docs/reproduction/public_conversion_code/packages/scene_generation/generation_profile.py +298875b7348389293a3fed81a0da2386b6de389e8099006694c7cff9ff288702 ./docs/reproduction/public_conversion_code/packages/scene_generation/geometry_task.py +3cff2fc3304df7b7bcbed6ba5164b36842daeaa01c7a85f15ace31be4f2236f0 ./docs/reproduction/public_conversion_code/packages/scene_generation/global_pose_repair.py +36e5876168ec1d74746f8b6cfa8c277d80715937e9015dbd8c02f4e19cd62437 ./docs/reproduction/public_conversion_code/packages/scene_generation/hierarchical_execution.py +56cbf6a4db81ca3c76e94644808ef2a5d6ac2187b789b09d474089b75694b95e ./docs/reproduction/public_conversion_code/packages/scene_generation/local_optimization.py +f776e536befbb923fd6f167d6d0fca6fec699011e99c03c540e0a52e379911e9 ./docs/reproduction/public_conversion_code/packages/scene_generation/manipulation_physics.py +093ddb9221d4fe09b4ba4eaf20019e43cd616388dcdc781fd52d441e4a7001aa ./docs/reproduction/public_conversion_code/packages/scene_generation/metric_layout.py +5e253ae703ffdb9a86b402faf52f1a45d5c9bcdcc8a094ccc45196a81ab178fd ./docs/reproduction/public_conversion_code/packages/scene_generation/motifs.py +20ed4f273dea2c26da441d3f6c4b3b0c511749b57988f94f9fbc00dee1583e4b ./docs/reproduction/public_conversion_code/packages/scene_generation/multi_room.py +eba4e60923ecb0671ac00ce3cb85098d25acd201fc36f20159a6a5f25f92037f ./docs/reproduction/public_conversion_code/packages/scene_generation/orchestrator.py +4d1db1850421ebec8eb7297abd709e6554dde2b34441d634545efee60d5c3a35 ./docs/reproduction/public_conversion_code/packages/scene_generation/pbr.py +52de20790cb5d710127d7bf08be2ec163acf6057b7275efd2cd48eaeb33a9d87 ./docs/reproduction/public_conversion_code/packages/scene_generation/pick_move_place.py +a2fe806d02bc77090d0f17c6a072b4ef045d99e162d10b1cf8b2dee10e867a6c ./docs/reproduction/public_conversion_code/packages/scene_generation/production_agent_handlers.py +693f35b38927f4bcc97a1e3c12e6e4d72053979ba73482e5dc75720f71e1df21 ./docs/reproduction/public_conversion_code/packages/scene_generation/prompt_multi_room.py +69d34027045c5f171a8c206f249d1a21e2c3a4991918fea44e8438dd86be05c9 ./docs/reproduction/public_conversion_code/packages/scene_generation/robot_constraints.py +3346833395832a2dab4f3d8c0b76c6340628bc356a814ed68ec9eb66833e3954 ./docs/reproduction/public_conversion_code/packages/scene_generation/semantic_constraints.py +4c3d0401c5d699f52cd9038e6691a9ce83e309b20cd3a1559ec73a1480929cc9 ./docs/reproduction/public_conversion_code/packages/schemas/__init__.py +54095695de42ad9939c9feab658a573e72b6bc66b3d9e3857a511afdce8fd15f ./docs/reproduction/public_conversion_code/packages/schemas/models.py +e8e85762027df9986791a69797397dfdcac7a69d1a8bc643bc966ecc83c4074d ./docs/reproduction/public_conversion_code/packages/supervisor/__init__.py +7d5bb08cf9fb4a7b3e9b6076101d5ab3627683c448dd4a73c08478eee32d45f1 ./docs/reproduction/public_conversion_code/packages/supervisor/case.py +4e43fdd07929d7f3336894437cd637e1dde41952ad21454304fd709eaef24169 ./docs/reproduction/public_conversion_code/packages/supervisor/models.py +ba61c26d464826cfadd7cd512b752e2e2286d8c35bc2a9dbbb1d76e334a9721c ./docs/reproduction/public_conversion_code/packages/supervisor/planner.py +096be1df4fe07c72b55e9edb519ff533b4fe336494acc039d1ccf126eca72d75 ./docs/reproduction/public_conversion_code/packages/supervisor/quality.py +c1e5f47675f909cd144de32e29085f6b3e989292920217d0d75d8127ce00fdc2 ./docs/reproduction/public_conversion_code/packages/supervisor/runner.py +476d33bb078e0074cd89b378cc406ae8de70e3d580b454cec0f3cae48a57d37b ./docs/reproduction/public_conversion_code/packages/supervisor/snapshot.py +5d3df48e14d0dffaf20ea9a49e347238c09d292f27db44eecdce8b4a809b792b ./docs/reproduction/public_conversion_code/packages/supervisor/visual_preflight.py +c02b575e7196a9ec14dfde1f503f652c60fcc85e6347809301f7c6c9052df266 ./docs/reproduction/public_conversion_code/packages/task_agent/__init__.py +00c8a776b2853fd18190cc97b5d058f85a771b002a18e835f3f61721c9a38e8e ./docs/reproduction/public_conversion_code/packages/task_agent/compiler.py +341c7770058cabbc93bfea147a5d24c70b74c022007ea032dd693bfbb15ef860 ./docs/reproduction/public_conversion_code/packages/task_agent/declared_transfer.py +0b6b0ac17223c705768f42842a5e01ab8a8b9e34323a0449c6d5e487e067a2b6 ./docs/reproduction/public_conversion_code/packages/task_agent/generator.py +b4a7a3e003636d70be429be3eadc5c38d9639051078d6babc91e3c09d86b9452 ./docs/reproduction/public_conversion_code/packages/task_agent/service.py +d4c135fcb5b77e28d46fe44c17a344035544e26170a88ea300a0f108759b9413 ./docs/reproduction/public_conversion_code/packages/task_agent/skills.py +579570c12aa3c470b92d42862b9c6ca26d41518d713b839219f7af7837cd7946 ./docs/reproduction/public_conversion_code/packages/task_agent/spec_agent.py +b41a68eed632b6fe727397998c5abf6dcd5bda7606cd9379485d00b49afa65c9 ./docs/reproduction/public_conversion_code/packages/task_catalog/__init__.py +1dfdec2d796dec51b8aa6baadcd40fa22765092f5c10a464cf69a72d91a0a372 ./docs/reproduction/public_conversion_code/packages/task_catalog/html_import.py +ef7c1a4cbaa82f0b78a231f554a2a21eeb42981124878ceed8f87391d6b5435d ./docs/reproduction/public_conversion_code/packages/task_catalog/repository.py +1605747ac09610b098d4a6d7f04dab21f678998a3337bc9ec541b01d14ce5946 ./docs/reproduction/public_conversion_code/packages/usd_composer/__init__.py +695d27274f39c2764e83b68e9a93dd2c88a41927e9af590352c22750bfaa0271 ./docs/reproduction/public_conversion_code/packages/usd_composer/composer.py +2a4828e1ff30d8b5b0084087ec46f0c34c7e0bef6e986c794f7a3704487de345 ./docs/reproduction/public_conversion_code/packages/validators/__init__.py +0cd82e9b7b17bf8f4b52a7a6576235e8e5bd21c9b8a4e8109873a5c3734b3ee7 ./docs/reproduction/public_conversion_code/packages/validators/base.py +069db1e2989c5c587c4ec9ad59a4d70d7b757bfff87509138b69075e7c93cd2f ./docs/reproduction/public_conversion_code/packages/validators/task_plugin.py +8fcd6d59f1a1f724f91d17c8874b4262e87a2ec7050772b2b9865c65787c11ef ./docs/reproduction/public_conversion_code/packages/version.py +80eabcb57289d4810e4a71c9893c945f62e645a794d8512d0783dbbfd8a5bff5 ./docs/reproduction/public_conversion_code/scripts/author_isaac_asset_metadata.py +9f2a3e71802a929c33b63b6fa71eca84b998c0ecd7303e1329ca1d1be558e326 ./docs/reproduction/public_conversion_code/scripts/blender_convert_asset.py +149952238c2498815525329c4450dfd6940bbcea53930c0a0562e2295a9d4a38 ./docs/reproduction/public_conversion_code/scripts/blender_convert_high_fidelity_batch.py +a10b165086d640e7fbfbe555ec01183a2ee239e2639701f984c6e21b7d12460a ./docs/reproduction/public_conversion_code/scripts/convert_asset.py +9cb17e3a1f7af10a3f94a2c0f840a09b41c7577037421d12c9d06e77656ac826 ./docs/reproduction/public_conversion_code/scripts/prepare_asset_pool.py +7c4ba7618cda11231bb23f70e274fa4ce849f0b1fc5530c36e2f2f3e973c1c70 ./docs/reproduction/public_conversion_code/scripts/preprocess_high_fidelity_assets.py +b1da93666b82974b1d64a1e317e8bc196d6f9e8875364937722647572ce2a325 ./docs/reproduction/public_conversion_code/scripts/seal_material_acceptance.py +5c7a57e7cc539e1c0a96c81fd8659b537295e960c282c0056688503676a97c1c ./docs/reproduction/public_conversion_code/scripts/setup_mdl_sdk.py +cafdd2c7acd0d4af3579464ce0004e623215c947b8693eb1e27dcefa026b177c ./docs/reproduction/public_conversion_code/scripts/validate_material_assets.py +7def89923536eb98b3f0d00f0f132b6d5da9601cd7734ed99240073cdad9f9ff ./docs/reproduction/public_download_control/conversion-source-manifest.json +c830683d1874e1d4a786adeae854e6d0a7f76c735863f788ce032ae05c5391b1 ./docs/reproduction/public_download_control/downloader.py +827ff66a76231bfdce0015c5104cc641e1aa6fa9a895302c49d5407f3fa6dabb ./docs/reproduction/public_download_control/gso.conversion.json +b856233ae39f1f17ec8b955535b360a7e6d1b7d1b01102a9f9ae6e35eefe68a1 ./docs/reproduction/public_download_control/lightwheel-checks.json +7ba356baff24d9710c4bba749e1fd2c3167b6c3bdf3d2f11513c6ecfc746a46e ./docs/reproduction/public_download_control/lightwheel-prepare.log +0bc5ef435951bf4a85e7172404e0fee4cb5cf6c63fcf42a5265de36a34cf3ef1 ./docs/reproduction/public_download_control/lightwheel.files.json +30ed1e14b75e4b89aaf0ff1f5fc21712585a440d809952237a333eefae7dd4ea ./docs/reproduction/public_download_control/lightwheel.preparation.json +6ce8c446438a159403c2152a8b0431efd48ee2c46826e2ad7cad2dcfb2bd3e6a ./docs/reproduction/public_download_control/lightwheel.status.json +f03056769f7f43b872a3ed72936ec823dc87ef2e434997d71e27dba2fee7eece ./docs/reproduction/public_download_control/lightwheel.verified.jsonl +2953dbc393c42fd609ce3c5bb17ca8ebaf5e0a22d1865d03fa1b91a8b6ff26ac ./docs/reproduction/public_download_control/manifest.json +2c358fc87a0a8364b53b334049ad6c87463400952819a702292445eaff7ead39 ./docs/reproduction/public_download_control/polyhaven_models.conversion.json +35db309d09f8d47c2d00def52d2eb1304c72f4259ba2344e9d1c261d5acbbf12 ./docs/reproduction/public_download_control/prepare_archives.py +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./docs/reproduction/public_download_control/readme-conversion-controller.log +41a776d075d9bbff334bb071dda21b94e162476122686aa03a7b0dc3ccfa93fa ./docs/reproduction/public_download_control/readme-conversion-resource-check.json +1ac62b9699c183933913655127b414722814016944ce2100b11712f76237cadb ./docs/reproduction/public_download_control/readme-conversion-technical-check.json +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./docs/reproduction/public_download_control/readme-conversion-textures-controller.log +f5f03aa691c89417544a64545207c138d0f020f47d4473e1cfd6fcd0f773b34f ./docs/reproduction/public_download_control/readme-conversion.log +7ac77f85b420a40fe12786d655a43d1f83cd2c34fdd8f397004cb6c08f791e84 ./docs/reproduction/public_download_control/readme_asset_conversion.py +7a7be8a36f9dc714afd7b92fdaa8fa4d47d1cf2e94fdead23d018fca9898a15b ./docs/reproduction/public_download_control/worker.log +91bdb1c84627017d0c6a79ebb4ef922253e41b3713c7d8d8d7bd78f03267493e ./docs/reproduction/public_download_control/ycb-003_cracker_box.log +1c4866f9cfe2c906d93b2783800f4fd73e1e0ad5b6c6823d75a71f692d5cf7a5 ./docs/reproduction/public_download_control/ycb-005_tomato_soup_can.log +d3a8a614e650317cd790255b5b54ce077ad903690e7213026a7c5aa267bd049e ./docs/reproduction/public_download_control/ycb-006_mustard_bottle.log +594bc378839a7fcd042cf2c06c67e6246e08baac0631f97ce87b0528f7f2b54d ./docs/reproduction/public_download_control/ycb-025_mug.log +3a667346955cf2c6fa3d3d77f511aca249cffe38ab2110efb56f7ebeed1debbe ./docs/reproduction/public_download_control/ycb-035_power_drill.log +513137f20e21975ebad876804d93fea37449f5a1c53b1f5db4afe37a3f8f1e5a ./docs/reproduction/public_download_control/ycb-author-jobs.json +70c163d7c08dcb524b2aaa57550ef5711183eb8b7a39d23f97a4da632c41069e ./docs/reproduction/public_download_control/ycb-author-results.json +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./docs/reproduction/public_download_control/ycb-author.log +18329bca453768fb1d711432a33b48b069537769ba7611ea9a09d8c45408a0d1 ./docs/reproduction/public_download_control/ycb-conversion-technical-check.json +39276c822f2f3219a4e6ffdb4a5f9802407ed55823c685919441cd1812b0126f ./docs/reproduction/public_download_control/ycb.conversion.json +d05717f960b293bd00082ec63b557a69031899a83b4266dc5fa77a9565f97674 ./docs/reproduction/资产清点与格式转换_20261119.md +b6579903035810ae9a35d99472f596277a6f9de84872f20712a6a32a66649e55 ./manifests/files.tsv +eb658341d0558ff59131ebb060161eff24f23e8482fdfa8305ecedbb048ef0ca ./manifests/sha256sums.txt