diff --git a/.gitattributes b/.gitattributes index ac749cd957de1e3a8988cfd76ca9743d01cc5e94..fa83b1f68ea5049ab03a55d936aeafb748b655ef 100644 --- a/.gitattributes +++ b/.gitattributes @@ -53966,3 +53966,4 @@ HOI4D/shared-v1.1/data/ZY20210800004_H4_C17_N21_S134_s02_T1/ego/observation/dept HOI4D/shared-v1.1/data/ZY20210800004_H4_C17_N21_S134_s02_T1/ego/observation/rgb.mkv filter=lfs diff=lfs merge=lfs -text HOI4D/shared-v1.1/data/ZY20210800004_H4_C17_N21_S194_s01_T2/ego/annotation/segment/mask.mkv filter=lfs diff=lfs merge=lfs -text ReInterHand/shared-v1.1/**/*.mkv filter=lfs diff=lfs merge=lfs -text +ReInterHand/shared-v1.1/doc/validation/read_sequence_sweep.json filter=lfs diff=lfs merge=lfs -text diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400266/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400266/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..308d818de4a90c7c4459bfa47eaccef8e39118fa --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400266/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:927ea76651e2286918128f4f95aeb43140e68a00494999f24b09c5d9f7e636e8 +size 326503 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400266/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400266/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..7ef9aff31796aec36131fd62b9f6b0f6199a9ea4 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400266/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d8c34b2102a6df74b2f3ae85e192d9ca30ccfd90a4f9a1d89b1295651e5b5f7 +size 17015132 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400275/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400275/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..03648091e2ae8e5f47ea0d10eaa9784dd5c39d76 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400275/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8c86727c2e51c20c1a48fe5a61b14c1bdf442428280a130825d522f944ca711 +size 335463 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400275/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400275/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..7d380e904df8fed884e06bc8b93d24267943ee1f --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400275/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86bddd81b7bfef5f82a367b3bed01d82ff900d0da6d91a65aee8f36aa28285a9 +size 16280706 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400282/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400282/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..872e8ebf9a71776f4d531c053186bf70a1fe23d1 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400282/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:166f7bc3d3efef778195f9ed6b769774233752b1f8eb71d3a600ead6b5494a5e +size 325719 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400282/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400282/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..89ed2a59b1c3c195eafcd87d67442c6f71189d87 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400282/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5562c96842d710d99d00021d889aa91c3344bf963aa9dc48063864c86c2a77cc +size 17077516 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400293/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400293/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..bd0a8dcebf8671982a98f227dfae42d02eaeb5ae --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400293/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78ff07624eeb8dc9a1d9687e2b43f30cfd932c1e5b539c23dc4f5835e0b6892c +size 330524 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400293/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400293/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..98f9aeb36a4f7e11dd2b9d4e86c0ecde1c7e88dc --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400293/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e40e08b153f40c9a7c2773ff769130c058d5d9ece1dcb8788517fc942a33166 +size 17590651 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400313/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400313/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..8e4f85e619af054d5ab63dab55bfe4ca618fbf7e --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400313/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a20052ec5f13a92f67a9d09055959970e7fa7cb671541bc6dcfd8ce811da9bdf +size 340300 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400313/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400313/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..5b92c121f2e4bfd8769befe6f6e2507ed43cafb5 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400313/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30dd90c30365da17a2d90c42a109dcebc7b6bffa9205637b4726d082436c28a4 +size 18617439 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400317/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400317/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..549d6dd43a725ff5083e3d2782259c0855819aae --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400317/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2995988f95926bd09e38b74d27af400c1e1f8b56803a3a21bd61b8822764541 +size 329853 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400317/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400317/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..92865ea418b5f0e302142e01d2a809403399f2b5 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400317/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e7d8ed988a133d37ab236e120dee9df08f2385fb64fc0b55b0381a39ecfdcf1 +size 15769415 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400319/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400319/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..22b4cae616c4b87e22b0988228db1b7e456be7a4 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400319/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d69a4995d6afbc49e420502bb5e8757d46a5cd4c3dc7f3e659060050f42c024 +size 285883 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400319/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400319/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..008800a9a82c452d594b6696707fa0baad673e24 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400319/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:295d65b32203edabe0833ce61289cfc58ab4b96ab14eff6597c0d847379e7a58 +size 15861347 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400327/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400327/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..2d36b4b42ec93673a950dfc9a6af0021cb0e9321 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400327/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04ba4b2deda76f862cd2149a5d4f08693cbbfc5ffa20ecf7285f44f894ad34e6 +size 332957 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400327/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400327/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..2fd385bad6b7215868334adc0b2083cce212a40a --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400327/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7183045f6bdded4da2eddd0f25ed2ab1614808fbe043e35d56b9268d0564c84 +size 17974118 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400366/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400366/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..339d5092a7bc604d212366edee84d7250437d87e --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400366/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5aa46de6baf302a6ef190c86839991ff9b604b421309dbddbc13578e2758b1a3 +size 324883 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400366/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400366/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..3fe62a3a2829403ee982eeabb9fcb3cbb5c35f18 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400366/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b8b58091385a5883f793a6e53dd18571531ce825d9d0a9079e1ba0d36aded8e +size 18193830 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400367/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400367/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..290d329233d2ad7b0985f3cd5654ba8f1c88aeca --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400367/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a92a60a37a0d3b5a34cea174cf1eaa856afdfd313876a949097d12a58a1b0d0 +size 377746 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400367/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400367/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..e723579cbaa919f3c288cd1cea24fab3ab0c056f --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400367/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a58452dd6fc71d344674e08d0811bad9a8fb8ec964e3b1088512d41068bfa20 +size 16715673 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400374/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400374/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..a4a01a71db6ae4ec6c6a24d4252531dbed2beb6f --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400374/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1df8ce76d01fd2b214f18329e823a82b7f7a0068d307eba9fc48c4f0ca68a80 +size 313507 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400374/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400374/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..b48f222bf47d1413893683e110ced9b020a9b858 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400374/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5641bcb3e311260e270e88bc567b76700f152ac7f8af10d78670b43cd7ac3519 +size 16898351 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400375/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400375/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..a12ad28e3b95998d25170b1747f5d3b116d34e04 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400375/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7f1da7b23c180a7fccf226992c466530def64da3415f5d882f4f7095fc734c8 +size 369616 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400375/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400375/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..2c657acd94b13b1eafa37876496b7e6a6e6120db --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400375/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f2642fa7d9cb77977c0048fa2d2f07728fd0836ef0c89ef1a5bc6dd1a89b6e6 +size 17005083 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400419/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400419/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..92da260dd8121efe1eb8cbed6948be8e36dfcc2d --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400419/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b28f6a297610bf47b633d4afa1867dafa38e772652742eab5424c51e025c2ed +size 343041 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400419/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400419/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..f0654d1f972af15a20bdb223d3c9b43488c43a73 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400419/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:480e071c85d0f03cf5124d8e9a34405247323b5ca24072cdbb640c1796be5c0b +size 15702226 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400433/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400433/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..00968ee0b1588f72eeea20673594c72c74882f90 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400433/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a13b974dbbeacdcf6b0337cc88d698ab36509a7886bf8f4c4f4e4dcc69a46dfd +size 342395 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400433/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400433/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..812d58b9cde9b01096ba4da76256d6687a39bf19 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400433/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f826fc8a109084403dc5e98aab434e28ed36e531d6c557a18f3521754856629 +size 16516637 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400439/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400439/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..d451fa412154706652ab10d4402a242ff2708829 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400439/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eb1400c469b7e47669200a1a1abeb024b670d40a879bcfdbac590dfb07ee8c9 +size 374928 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400439/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400439/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..657873dd86b859224e0d8ef051a22f048582e2b0 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400439/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8eb71f5605ff7741c9c5d2df776e14dd1ec5e0337f24742048bb4a3f9658a681 +size 16974860 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400460/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400460/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..4b68fc4a75eab2017abff2d9f3b464461a1b2a88 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400460/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9755274d22f0e0cc95074007077c39a82f9cc6ad26747aba151aae4fec215649 +size 325820 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400460/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400460/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..aa0902a31ce9a545692e4c211a9a9964653129f2 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400460/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1cc7e9ff8dce2ce1c89435f1db24dce1e0d889cd253d170cfb899b3be1db6a5 +size 17627146 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400483/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400483/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..f2f131b863b97426a7c414a1457dadf28f18bf9c --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400483/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d691218059d67e3085498305456e2f446ef4de7513fbd6960b8cc669109c209 +size 306112 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400483/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400483/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..e595b5d335255dfdcd60ddcdd64c6f31d3312ade --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400483/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21c8886ab3fc95366382ff2acb1776885b338a70828a7fa8a7770a0c17b32c87 +size 17623234 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400485/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400485/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..e83ca152d089758d5c9557732f2a010976d849b0 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400485/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c345e1524d0229c8c4f5f15926c37e1cc28730589e0740db35392edeb37bd372 +size 337449 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400485/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400485/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..c8737d469a6556307eb2fcd0aaad4334d7a08b58 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400485/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa3e0d495c217db6ba10c355c5dc42e3084da2c09009a36e22a0629741a82466 +size 16716621 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400486/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400486/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..e059dc7878bbd4f4b50e8028ea8f085841aeaa74 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400486/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a7ce59472636fdbab0c1f8997782c0d2e41ddb8ba1400273bf6542216e313c6 +size 359504 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400486/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400486/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..54d2c9bd64e3a64764f6cd71877d9c025ded21fd --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400486/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e82bce6c380bbf95c722cb4743fca00448ffd8eef81e3e518d40a70ab2e748db +size 17101522 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400503/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400503/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..905ef958ac7a31c4c9cee2956f84a27739c3df20 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400503/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b669d57ea829e324ab274d4ef60c99803fd310ede68bab10a89f2261d774a36 +size 336658 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400503/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400503/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..f9ad9990aa6a499b0f0ee3b2f8ca559ee6abc2e6 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/400503/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f38e4ec96d77ed466f474ea6f8ae05f3073e5919f8d46a33d52b0aa769c2dd32 +size 15374072 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/ego/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/ego/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..1b733607ffb8f0b5f053902edb04b738b926284d --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/ego/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d0119547812417a493bdaf51cf613bdb9b60e8ce4277dad8a42c8dcd33353a5 +size 1707370 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/ego/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/ego/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..abe772c4f247ca67cc3a8ccdc849c499b26c554e --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__161844__162399/ego/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b5e3af64ba7e14bcf9ab712a9efe70abdf64752d730e02bca783c2efad3a38e +size 210651386 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400266/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400266/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..227ab32862591c64442bafecc1dadec6888667af --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400266/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27fd2dfeecb4b2c9470e722fefed0ba426c7b774028464de20817390b5393ea7 +size 423675 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400266/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400266/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..a49a1851d8bee933666152ddfa24401f8c7121c6 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400266/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f276aba94346fdd2dd4d4cfff2826960f231860c6bc5f3aa896cee9d7dc374fa +size 22405003 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400275/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400275/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..d9638298c94b62f3b04e6cc9ed9504c1a1f4c57f --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400275/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:483c67beb18d2d66fe645824a194573957a35039a98210f0b4226729026ca802 +size 462375 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400275/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400275/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..0502d79f7cac75bfec814b22c6bacd12b0c12635 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400275/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3967f850e6c4f5c86777ac36e1a997f8f56f2e01b4ea4afdd97cf860a02bf08b +size 22934174 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400282/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400282/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..9a269d5c707632912b145e61f14fa4293e3c07fe --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400282/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:832f5f333df0aac106aff75ad80bf890e6f8fdd1b5ff8974011a9d13e54ad72e +size 433824 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400282/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400282/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..b97df63e0f1917daf81a115cb35b5f63ed75e4c6 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400282/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f976a019b84633313cfbe4ccfb1eb33b9e995558f543782c7e5a380a9cdac7f1 +size 22424509 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400293/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400293/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..e5b0780c8039ad1639c6593f558b47ba58860417 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400293/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:248fa373ac2dedcdf010443a1891abb08eeebac681a3c36e8f210158a178d02b +size 428739 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400293/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400293/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..cdbf98649b2bed13a79f5c3ab900dd05e05af117 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400293/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:349d57b96fd109969d8958028c39450c316cc30fc677f83d959a468faaf172a6 +size 23497032 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400313/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400313/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..fe2be30023681491761855d8890d7d75a80ba1c2 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400313/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e75b0e252f7e83777b98a0ec3b68fbaa576e7b016ab6a153cc46935624501009 +size 436869 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400313/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400313/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..9fbed70ee540415a203ed7e39f847d99b48ec3a1 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400313/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72b3e58a13463f31c0d46b84185c1998c7d1cd4e2cd1084849dcc653adf7e01b +size 25923108 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400317/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400317/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..402a23c2b30d27dd16d5f5bbd2811c3b7505bdcb --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400317/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4d9b5357b30f1ae2da6a313b20a454f92159420621c636ff23288f8ea1c0ff1 +size 450752 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400317/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400317/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..0ca9afa275718230511067db0f623e76fb269d94 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400317/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60f9147f5073586e74d54140274ead060c7136f2ddec42b7eb3bbe21a4d7097f +size 22713357 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400319/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400319/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..e893ac34bca0f85b8d36e986a35b5ac0c20c2beb --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400319/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c0a47abc8059be0deccf4842ada063aa4333a27a6135eeda2a4a36bd46c8ca2 +size 412527 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400319/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400319/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..480a0688b16d8ca4c2c0429d4dc5949cabab49f6 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400319/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4af99abb411e70c65e331e1c5ee4a8b0bc29e96cbc25ebc03b168afb5573f7a9 +size 21400583 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400327/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400327/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..05350babd6aee5c1c979f3a5c50c32e7701b4c2b --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400327/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:261f1dc1c753f392a7aad52ea2c9633a4b82a410ca1189f40693bf02cba8fdba +size 424511 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400327/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400327/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..79395623a0d8cfddce70017e58df8bed1e7a219e --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400327/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d82414b4a9b7e2786b54a82ee038ad8e0db88a30a359bd1b15dd4f01c0b3dc3c +size 25063127 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400366/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400366/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..26151f23263c559a62d7b3df641961d0de0c5d11 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400366/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:167459d0897c4b0024db79516650bca799472b4f46294b600714dc54cce63999 +size 452366 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400366/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400366/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..26ec898945351d4b06275a26ef90a96a3ef316be --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400366/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c52bcdf3b05547a567cee09148772b17bc7362dc16cdbbcc97f601b6db2d867 +size 25418104 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400367/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400367/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..4e6cf2c3954f3ca8123d555fa71e252290c352a0 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400367/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8e92518beda2f1e626ab9e451316bdf18a79db9a733200a03a6c7e5983c9c14 +size 436839 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400367/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400367/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..db45b2317a17565ec6dc93fe93ff1e73cd0494f0 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400367/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83788b06f95057d78ddd6b87b7b1dc2093f6ae958c01ce9afad3d29bfb8a3ea9 +size 21332612 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400374/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400374/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..b869eb2eb81c21b3ffc818909eae02ff316f521f --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400374/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8adafca92e65920a949cc3837440457323d80577cb412edea3f73e17df98789f +size 392212 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400374/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400374/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..5abfc777a9a09ae6e0a11eba19cd78b4b846397c --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400374/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f2693cd48731d7d25fdc839443f041db9c477c36993974e81ad4661b2a637de +size 22046718 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400375/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400375/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..23cd6f4a80bc086cd0fc5953f416033c0218f172 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400375/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2015c5f9cb20d7623f708fa5a47b91898d4fabee9469ffc27745f1281cb91e5 +size 446312 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400375/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400375/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..4c9859683779bc385638e3c87bda9fba88a057bb --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400375/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cefa39e73aec302f1a1bc5e52b3ecd64cd880aa1e1c5423fd40b6bbfd468d8ff +size 21657047 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400419/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400419/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..2613f0894695d5c87ea5e2ddf54155f14f73dc12 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400419/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fa2ed08a345a2a471560ef85fcf867645110d09996a7a6b7c54f5e716ecb160 +size 442647 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400419/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400419/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..bdbf14a298b1a3e6e98902dc80dbdb21dde83591 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400419/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dac99e2e62bb965099db699edd285873991b3e276ed4c35aefe4bfa2dc8c124a +size 22343332 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400433/annotation/segment/mask.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400433/annotation/segment/mask.mkv new file mode 100644 index 0000000000000000000000000000000000000000..9e0e63f28c067a6a8bcfe70e9721757fc3904be8 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400433/annotation/segment/mask.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9b8fd6b87af06b9d70e2a9a62d95b791cdc97f6980afa42db9a8b8bed94787e +size 464970 diff --git a/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400433/observation/rgb.mkv b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400433/observation/rgb.mkv new file mode 100644 index 0000000000000000000000000000000000000000..875f4187db4b7a24a7902348285de8e82f7376f0 --- /dev/null +++ b/ReInterHand/shared-v1.1/data/m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__162809__163526/400433/observation/rgb.mkv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b85d8de439807b0490e96665986c073ca75adfd61af0352c48adec7a715bb28 +size 22768288 diff --git a/ReInterHand/shared-v1.1/doc/validation/read_sequence_sweep.json b/ReInterHand/shared-v1.1/doc/validation/read_sequence_sweep.json new file mode 100644 index 0000000000000000000000000000000000000000..51e0da7309b04e32e0b2d5fc99d76c8d8664bdec --- /dev/null +++ b/ReInterHand/shared-v1.1/doc/validation/read_sequence_sweep.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a722bc1ecbe92779dc038b7ff9bc2cc082a2e2346a46d3657dbb91bfa4f8e16a +size 20178501 diff --git a/ReInterHand/shared-v1.1/doc/validation/validate_report.json b/ReInterHand/shared-v1.1/doc/validation/validate_report.json new file mode 100644 index 0000000000000000000000000000000000000000..40424db61638a7cbaff5d4a5520788c8432a35cb --- /dev/null +++ b/ReInterHand/shared-v1.1/doc/validation/validate_report.json @@ -0,0 +1,133 @@ +{ + "passed": true, + "coverage": "full release", + "views": 6750, + "sequences": 500, + "counts": { + "test": { + "views": 1782, + "sequences": 132, + "frames": 392514 + }, + "train": { + "views": 4968, + "sequences": 368, + "frames": 1134281 + } + }, + "cells": { + "ego/envmap_per_frame": { + "views": 250, + "sequences": 250, + "modal_source_step": { + "2": 106, + "3": 144 + }, + "source_gap_histogram": { + "0": 180, + "1": 42, + "2": 20, + "3": 4, + "4": 4 + } + }, + "ego/envmap_per_segment": { + "views": 250, + "sequences": 250, + "modal_source_step": { + "2": 106, + "3": 144 + }, + "source_gap_histogram": { + "0": 180, + "1": 42, + "2": 20, + "3": 4, + "4": 4 + } + }, + "exo/envmap_per_frame": { + "views": 5000, + "sequences": 250, + "modal_source_step": { + "12": 2120, + "18": 2880 + }, + "source_gap_histogram": { + "0": 3880, + "1": 640, + "2": 320, + "3": 80, + "4": 80 + } + }, + "exo/envmap_per_segment": { + "views": 1250, + "sequences": 250, + "modal_source_step": { + "2": 530, + "3": 720 + }, + "source_gap_histogram": { + "0": 900, + "1": 210, + "2": 100, + "3": 20, + "4": 20 + } + } + }, + "frames": 1526795, + "files_per_view": 6, + "schema_version": "hand-warehouse/1.1", + "release_id": "shared-v1.1", + "bundles_per_view": 2, + "declared_media_schema_gaps": { + "rgb/uint8/v1/required.storage.encoded_size": 6750, + "rgb/uint8/v1/required.storage.decoder": 6750, + "rgb/uint8/v1/required.storage.encoder_parameters": 6750, + "rgb/uint8/v1/storage.profile.unregistered:mkv/ffv1_rgb24/v1": 6750, + "rgb/uint8/v1/storage.profile.not_allowed:mkv/ffv1_rgb24/v1": 6750, + "segment/foreground_intensity/v1/required.segmentation_type": 6750, + "segment/foreground_intensity/v1/required.coverage": 6750, + "segment/foreground_intensity/v1/required.entity_id": 6750, + "segment/foreground_intensity/v1/storage": 6750 + }, + "media": { + "declaration": "/data1/yanghonglei/Datasets/hand-warehouse/ReInterHand/tmp/reinterhand-tools/media-presence.json", + "materialised": [ + "m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__160929__161469", + "m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_segment__160929__161469" + ], + "declared_media_files": 13500, + "files_on_disk": 54 + }, + "rewrite_check": [ + { + "sequence_id": "m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__160929__161469", + "camera_id": "400266", + "bundles": [ + "annotation/mano/mano.pt", + "camera/camera.pt" + ], + "tensors_compared": 6 + }, + { + "sequence_id": "m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands__envmap_per_frame__160929__161469", + "camera_id": "400275", + "bundles": [ + "annotation/mano/mano.pt", + "camera/camera.pt" + ], + "tensors_compared": 6 + } + ], + "failures": [], + "scope": "released content and layout; does not independently prove official source correctness or visual quality", + "release_manifest": { + "path": "/data1/yanghonglei/Datasets/hand-warehouse/ReInterHand/tmp/reinterhand-tools/PUBLISH_MANIFEST.json", + "in_release_tree": false, + "files": 41195, + "note": "rebuilt by this run after this report was written, so it covers the report's final bytes; kept outside the release because a manifest inside it cannot hash itself" + } +} \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/provenance/operations/build_reinterhand_docs.py b/ReInterHand/shared-v1.1/script/provenance/operations/build_reinterhand_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..bf4fe6bde7118e6c4fd742a0db61b586fecb9907 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/provenance/operations/build_reinterhand_docs.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Assemble ReInterHand's ``doc/`` tree from the canonical v1.1 spec and the v1.0 record. + +Every published v1.1 release carries the same three spec documents, and each +dataset edits exactly the same three things in ``CONTRACT.md``: a status banner on +line 1, its own 状态 line, and the v1.0 link retargeted from the shared +``../hand-warehouse-1.0/CONTRACT.md`` to the copy kept as ``V1_0_SEMANTICS.md``. +Doing that by hand is how a release ends up with a banner that overstates what was +actually verified, so this script derives the banner and the 状态 line from +``doc/FULL_MIGRATION_SUMMARY.json`` -- the record of what the run actually did -- +and refuses to write a claim the record does not support. + +Adapted from ``RHD/shared-v1.1/script/provenance/operations/build_rhd_docs.py``, the +second-generation builder. Three things differ for ReInterHand, and all three are +about v1.0 material rather than about the v1.1 spec (which is shared, and checked +against its canonical digests below): + +* ``RAW_MAPPING.md`` keeps its v1.0-era name, as RHD's does, instead of the + ``RAW_TO_SHARED.md`` that ARCTIC, H2O and dex-ycb use. It is *checked*, not + rewritten: the mapping record is the dataset's own, and a builder that regenerated + it could silently drop a row. +* The v1.0 ``script/`` tree is snapshotted into ``script/v1_0_snapshot/script`` + alongside the v1.0 contract and schema in ``script/v1_0_snapshot/doc``. RHD's + builder leaves that copy alone; ReInterHand's produces it, because its v1.0 + ``script/`` is where the release's own producer lives (``preprocess_reinterhand.py``) + and a snapshot that is made by hand is one nobody can re-derive. +* ``doc/history-v1.0/`` is 752 MB, not 7 MB: ReInterHand's v1.0 ``doc/validation/`` + carries 114 rendered review clips. ARCTIC carries 412 MB the same way, so the whole + set is reproduced, verbatim and complete -- a "history" tree whose pages link to + videos that were left behind is not a reproduction. + +Run: python shared-v1.1/script/provenance/operations/build_reinterhand_docs.py + +Order inside a run: the two carried-over trees are produced first, then +``doc/RAW_MAPPING.md`` is checked, then the four spec documents are written. The +mapping record names ``script/v1_0_snapshot/`` as where the v1.0 scripts live, and this +script is what puts them there, so checking it first would fail on a tree built from +scratch -- the case where the check matters most. + +Idempotent: it rewrites the two transformed files, copies the two verbatim ones, +refreshes ``doc/history-v1.0/`` and re-snapshots the v1.0 scripts, so re-running after +the migration finishes refreshes the banner. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import shutil +import sys +from pathlib import Path + +OPERATIONS = Path(__file__).resolve().parent +SCRIPT_DIR = OPERATIONS.parent.parent # /script +RELEASE_ROOT = SCRIPT_DIR.parent # /shared-v1.1 +DATASET_ROOT = RELEASE_ROOT.parent # +SPEC = SCRIPT_DIR / "reinterhand_v1_1" / "spec" +DOC = RELEASE_ROOT / "doc" +V10 = DATASET_ROOT / "shared-v1.0" +HISTORY = DOC / "history-v1.0" +SNAPSHOT = SCRIPT_DIR / "v1_0_snapshot" + +#: the canonical spec, shared by every dataset. Checked rather than trusted: if +#: these do not match, the release would ship a spec it did not migrate against. +CANONICAL = { + "CONTRACT.md": "502dde9ac0549551237f684472489ddf6372bad3a26b1f6cca96f360c5dff158", + "MIGRATION.md": "773f5146d49f5060bfc13ef92c143c59b683a6dc633cad44897414d5299088a0", + "schema.json": "9f3769f950b36f75f3d571c77b5a661ca8e72afae20c9f1ddd1deef140e6cca8", +} + +#: ``../hand-warehouse-1.0/CONTRACT.md`` in the canonical text; the release keeps +#: its own copy of the v1.0 semantics beside it instead of reaching outside the tree +V10_LINK = "../hand-warehouse-1.0/CONTRACT.md" +V10_LINK_LOCAL = "V1_0_SEMANTICS.md" + +STATES = { + #: no summary yet: the migration has not finished, so claim nothing about it + "in_progress": { + "banner": "> ReInterHand shared-v1.1 本地全量迁移进行中;自动验收、人工复查与 HF 发布均未完成。", + "status": "状态:ReInterHand shared-v1.1 配套注册表与读写工具已适配;本地迁移、自动验收、人工复查与 HF 发布均未完成。", + }, + #: full acceptance recorded, human review and upload still outstanding + "accepted_pending_review": { + "banner": "> ReInterHand shared-v1.1 已完成本地全量迁移与自动验收(逐字段字节级比对);人工复查与 HF 发布尚未完成。", + "status": "状态:ReInterHand shared-v1.1 配套注册表与读写工具已适配;本地全量数值一致性及结构检查通过,发布清单已在发布树外重建(`tmp/reinterhand-tools/PUBLISH_MANIFEST.json`,树内不含清单)。人工复查不属于自动验收,尚未完成;HF 发布尚未进行。", + }, +} + + +def sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1 << 22), b""): + digest.update(chunk) + return digest.hexdigest() + + +def canonical_bytes(name): + """The shared spec verbatim, with its canonical digest confirmed.""" + path = SPEC / name + got = sha256(path) + if got != CANONICAL[name]: + raise SystemExit(f"{path} is not the canonical {name}: {got} != {CANONICAL[name]}") + return path.read_bytes() + + +def canonical_text(name): + """The shared spec as LF text, for a file this release transforms. + + The canonical ``CONTRACT.md`` and ``schema.json`` are CRLF; only the documents + this release edits are normalised. A file that is *copied* keeps its bytes -- + both published releases ship ``schema.json`` at the canonical 39043 bytes with + its CRLF intact -- so the two paths are kept apart rather than sharing one + round-trip through ``str``. + """ + return canonical_bytes(name).replace(b"\r\n", b"\n").decode("utf-8") + + +def state_name(): + """Which of STATES the recorded migration summary supports.""" + summary = DOC / "FULL_MIGRATION_SUMMARY.json" + if not summary.is_file(): + return "in_progress" + record = json.loads(summary.read_text(encoding="utf-8")) + if record.get("phase") != "local_finalized_not_uploaded": + raise SystemExit(f"{summary}: unexpected phase {record.get('phase')!r}") + if record.get("human_full_approval"): + raise SystemExit( + f"{summary}: records a human approval, but no published wording is " + "defined here; a published release needs its own banner" + ) + return "accepted_pending_review" + + +def build_contract(state): + """The canonical contract with the three dataset-specific edits applied.""" + text = canonical_text("CONTRACT.md") + lines = text.split("\n") + status_index = next( + index for index, line in enumerate(lines) if line.startswith("状态:") + ) + if lines[status_index].count("状态:") != 1 or not lines[status_index].startswith( + "状态:合同草案" + ): + raise SystemExit(f"line {status_index + 1} is not the canonical 状态 line") + if text.count(V10_LINK) != 1: + raise SystemExit(f"the canonical text no longer links {V10_LINK} exactly once") + lines[status_index] = STATES[state]["status"] + body = "\n".join(lines).replace(V10_LINK, V10_LINK_LOCAL) + #: banner, one blank line, then the canonical text; and no trailing newline, + #: which is how both published releases ship it + return f"{STATES[state]['banner']}\n\n{body}".rstrip("\n") + + +def check_mapping_record(dry_run=False): + """ReInterHand's own field mapping, kept under its v1.0-era name and cross-checked. + + This release does not rewrite the file, so the builder does the next best + thing: it confirms the mapping record is there and that every ``script/...`` + path it points a reader at actually exists. A restructured ``script/`` that + left these references stale would send the reviewer to a file that is gone. + + ``dry_run`` only relaxes the case a dry run cannot satisfy: the carried-over + trees are produced by this same script, and a dry run produces nothing, so a + reference into ``script/v1_0_snapshot/`` is reported as pending instead of + failing. Everything else is checked in both modes. + """ + path = DOC / "RAW_MAPPING.md" + if not path.is_file(): + raise SystemExit(f"{path} is missing; it is the 字段映射 CONTRACT 2 requires") + text = path.read_text(encoding="utf-8") + #: the record points a reader at entry points, not only at Python ones: it also + #: names the tool package's README, which is the file that documents how to run + #: the chain. Matching only ``.py`` would let that reference go stale unnoticed. + referenced = sorted( + set(re.findall(r"`(script/[A-Za-z0-9_./-]+\.(?:py|md|sh))`", text)) + | set(re.findall(r"`(script/v1_0_snapshot/[A-Za-z0-9_./-]*)`", text)) + ) + if not referenced: + raise SystemExit(f"{path} names no script/ entry point") + missing = [rel for rel in referenced if not (RELEASE_ROOT / rel).exists()] + if missing and not dry_run: + raise SystemExit(f"{path} points at {len(missing)} file(s) that are not in " + f"the release: {missing}") + if missing: + print(f" (dry run) {len(missing)} reference(s) do not exist yet and this run " + f"is what creates them: {missing}") + return path, referenced + + +def sync_tree(source, target, label): + """Reproduce ``source`` under ``target``, and drop what the source no longer has. + + Used for both carried-over sets: the v1.0 document tree and the v1.0 scripts. A + copy that only ever adds cannot drift *towards* the source, but it can keep a file + the source has since dropped, which would misrepresent what v1.0 was. + """ + if not source.is_dir(): + raise SystemExit(f"{source} is missing; it is what {label} reproduces") + wanted = {p.relative_to(source).as_posix() for p in source.rglob("*") if p.is_file()} + for path in sorted(source.rglob("*")): + if not path.is_file(): + continue + destination = target / path.relative_to(source) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, destination) + removed = [] + if target.is_dir(): + for path in sorted(target.rglob("*")): + if path.is_file() and path.relative_to(target).as_posix() not in wanted: + path.unlink() + removed.append(path.relative_to(RELEASE_ROOT).as_posix()) + return len(wanted), removed + + +def sync_history(): + """``doc/history-v1.0/`` is the v1.0 document set, reproduced. + + The published releases keep the previous version's documents here, so a reader + can compare the two without leaving the release. ReInterHand's v1.0 ``doc/`` is + the contract, its schema, the raw mapping and the release's own review pages -- + 548 files, 752 MB of which 749 MB is the 114 review clips those pages link to. + The whole set is carried (ARCTIC carries 412 MB the same way): dropping the clips + would leave ``validation/index.html`` pointing at nothing. + """ + return sync_tree(V10 / "doc", HISTORY, "history-v1.0") + + +def sync_snapshot(): + """``script/v1_0_snapshot/`` is the v1.0 scripts and the v1.0 contract pair. + + RHD keeps these two sets as well, but its builder does not produce them. Here the + snapshot is derived, so it can be re-made: the v1.0 ``script/`` is where this + release's producer lives, and the contract and schema pair is the document set the + data was written against. + """ + script_count, script_removed = sync_tree(V10 / "script", SNAPSHOT / "script", + "the v1.0 scripts") + doc_target = SNAPSHOT / "doc" + doc_target.mkdir(parents=True, exist_ok=True) + wanted = [] + for name in ("CONTRACT.md", "schema.json"): + source = V10 / "doc" / name + if not source.is_file(): + raise SystemExit(f"{source} is missing; the v1.0 contract pair is incomplete") + shutil.copy2(source, doc_target / name) + wanted.append(name) + removed = [rel for rel in script_removed] + for path in sorted(doc_target.iterdir()): + if path.is_file() and path.name not in wanted: + path.unlink() + removed.append(path.relative_to(RELEASE_ROOT).as_posix()) + return script_count, len(wanted), removed + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--dry-run", action="store_true", + help="report what would be written and change nothing") + args = parser.parse_args(argv) + + state = state_name() + print(f"banner state: {state}") + + #: The carried-over trees are produced *before* the mapping record is checked, + #: because that record is where a reader is told the v1.0 scripts live in + #: ``script/v1_0_snapshot/`` -- and this script is what puts them there. Checking + #: first would fail on a tree built from scratch, which is exactly the case the + #: check exists for; it would also mean the first run of a fresh build reports a + #: broken mapping record that is in fact correct. + if args.dry_run: + source = V10 / "doc" + print(f" would sync doc/history-v1.0/ from {source} " + f"({sum(1 for p in source.rglob('*') if p.is_file())} files)") + print(f" would snapshot {V10 / 'script'} into script/v1_0_snapshot/script") + else: + count, removed = sync_history() + print(f" doc/history-v1.0/: {count} files synced from {V10 / 'doc'}" + f"{f', {len(removed)} stale file(s) removed' if removed else ''}") + script_count, doc_count, removed = sync_snapshot() + print(f" script/v1_0_snapshot/: {script_count} script files + {doc_count} " + f"contract files synced from {V10}" + f"{f', {len(removed)} stale file(s) removed' if removed else ''}") + + mapping, referenced = check_mapping_record(args.dry_run) + print(f" doc/RAW_MAPPING.md: {sha256(mapping)[:16]} {mapping.stat().st_size} B " + f"(ReInterHand's own record, name kept; {len(referenced)} script reference(s) resolve)") + #: transformed documents are authored here and normalised to LF; copied ones + #: are other artifacts reproduced byte for byte, line endings included + transformed = { + "CONTRACT.md": build_contract(state).encode("utf-8"), + "MIGRATION.md": canonical_bytes("MIGRATION.md"), + } + copied = { + "schema.json": canonical_bytes("schema.json"), + "V1_0_SEMANTICS.md": (V10 / "doc" / "CONTRACT.md").read_bytes(), + } + for name, payload in transformed.items(): + write(DOC / name, payload, "transformed", args.dry_run) + for name, payload in copied.items(): + write(DOC / name, payload, "copied", args.dry_run) + if not args.dry_run: + print(f" doc/CONTRACT.md banner: {STATES[state]['banner']}") + return 0 + + +def write(target, payload, kind, dry_run): + if dry_run: + print(f" would write doc/{target.name} ({len(payload)} bytes, {kind})") + return + before = sha256(target) if target.is_file() else None + target.write_bytes(payload) + after = sha256(target) + print(f" doc/{target.name}: {len(payload)} bytes, {kind}, sha256 {after[:16]}" + f"{'' if before != after else ' (unchanged)'}") + + +if __name__ == "__main__": + sys.dont_write_bytecode = True + raise SystemExit(main()) \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/README.md b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e237a2e3934ce50900d1dc446866c64b7de1801b --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/README.md @@ -0,0 +1,334 @@ +# ReInterHand shared-v1.1 tools + +ReInterHand 的 `shared-v1.0 → shared-v1.1` 纯存储迁移工具,以及迁移之后的验收与复核。v1.1 只改一件事: +数值张量与其 `valid` 合并为每组一个 `.pt` 字典(叶子形如 `{"data": Tensor, "valid": BoolTensor}`)。 +语义、采样、帧数、dtype、逐元素数值、NaN 位置、有效性判据、单位、坐标系、手槽、划分、来源与 +`valid_policy` 全部不变(见 `spec/CONTRACT.md` §6.3)。 + +本数据集规模:500 个序列、6,750 个视图(6,250 `exo` + 500 `ego`)、1,526,795 条视图帧记录;`data/` 由 +68,554 个文件降为 40,554 个(并入 bundle 的源文件 41,500 个消失,新增 bundle 文件 13,500 个)。 + +``` +script/reinterhand_v1_1/ +├── warehouse.py v1.1 布局库:Registry.resolve / BundleWriter / BundleReader / raw_bytes / same_tensor +├── reinterhand_common.py ReInterHand 适配:路径、registry 驱动读写、形状符号解析、逐组件结构校验、 +│ 相机集合、跨相机 sync 判据、声明缺失媒体、游离 valid 检测 +├── migrate.py v1.0 → v1.1 迁移(可断点续跑) +├── verify.py 验收:逐视图对 v1.0 源做字节级比对(CONTRACT §6) +├── validate.py 全量结构校验 + 重新生成发布清单(清单写到发布树外) +├── read_sequence.py 读取器路径验收:整序列、全部组件(CONTRACT §6.5) +├── render.py 全量后抽样的人工复核页:27 个视图的 HTML + QC 报告 + index +├── mano_review.py 复核页用的 MANO 展开与投影(读 v1.0 的运行时快照) +├── spec/ 本版规范原文:CONTRACT.md、MIGRATION.md、schema.json +└── README.md +``` + +本目录**没有** RHD 那样的 `convert.py`:ReInterHand 的 raw→share 转换器是 v1.0 自己的 +`script/preprocess_reinterhand.py`,它随 v1.0 的 `script/` 原样保存在 `script/v1_0_snapshot/script/`, +v1.1 不另写一份。raw 不在本机(在云哲的目录与官方归档里),所以即便写了也无法端到端重跑。 + +`warehouse.py` 与各数据集共用,逐字节相同(sha256 `fe62f79f9228475e23764d57c923e781422951ad5ed6680337bf67e120a63db2`); +ReInterHand 自己的适配都在 `reinterhand_common.py`。v1.0 的 `script/` 与合同原样保存在 +`script/v1_0_snapshot/`,v1.0 的文档集在 `doc/history-v1.0/`。 + +## 运行 + +包位于 `/shared-v1.1/script/reinterhand_v1_1/`,所以发布树与数据集根无需传参: + +```bash +# 试跑,核对会迁移哪些视图(不写任何文件,不取锁) +python shared-v1.1/script/reinterhand_v1_1/migrate.py --dry-run + +# 只迁一个序列先看(序列目录名即一级 ID) +python shared-v1.1/script/reinterhand_v1_1/migrate.py --views + +# 迁移(可重复执行;已完成且 checkpoint 重新核验通过的视图跳过) +python shared-v1.1/script/reinterhand_v1_1/migrate.py --resume + +# 验收:每个已迁移视图与其 v1.0 源逐字段比对(CONTRACT §6) +# --complete 走的是 v1.0 源树里的全部视图,所以两棵树都齐了才用;增量期用 --views 限定范围。 +python shared-v1.1/script/reinterhand_v1_1/verify.py --complete \ + --report tmp/reinterhand-tools/acceptance.json + +# 增量期间加 --no-manifest:清单要遍历整棵树重算 sha256(CONTRACT §6.4),那是最终验收必须做的, +# 但边迁边验时每次都为一份随后会被覆盖的清单付一遍哈希不值得。接受发布的那一次不许带这个开关。 +python shared-v1.1/script/reinterhand_v1_1/verify.py --views --no-manifest + +# 读取器路径验收:按消费者读法打开整序列,查帧数↔媒体↔标注、相机身份、跨相机 sync、逐组件引用 +python shared-v1.1/script/reinterhand_v1_1/read_sequence.py \ + --report tmp/reinterhand-tools/read-sequence.json + +# 全量结构校验(只读发布树,不需要 v1.0 源;重建树外发布清单 tmp/reinterhand-tools/PUBLISH_MANIFEST.json) +# 6,750 视图与 1,526,795 帧数是**整份发布**的断言,所以只在这一趟全量运行里检查。 +python shared-v1.1/script/reinterhand_v1_1/validate.py --expect-views 6750 --rewrite-check 2 + +# 看树的一角:带 --views/--limit 的是**子集运行**,只断言选中的视图,报告标 coverage: partial subset +# 并写到 tmp/reinterhand-tools/validate-partial.json,且不重建清单(清单是对全树的断言,不该与局部报告并排)。 +# 拿它当验收不行——验收只能是上面那一趟没有选择开关的全量运行。 +python shared-v1.1/script/reinterhand_v1_1/validate.py --limit 3 +``` + +**跑之前请设 `PYTHONDONTWRITEBYTECODE=1`**(或 `export PYTHONDONTWRITEBYTECODE=1`)。发布树里不允许出现 +`__pycache__`:它不在清单里、不是发布内容,却会随工具运行落进 `script/`,让树与清单对不上。`render.py`、 +`validate.py`、`read_sequence.py` 在模块内设了 `sys.dont_write_bytecode`,所以自带这一纪律; +`migrate.py`、`verify.py` 没有设——它们的摘要已被 `registration.json` 记为 `hw11-migrate/1`,为加这一行而 +改动它们会让 `--resume` 触发一次全量重迁,因此保持原样,靠环境变量保证。 +(另:别用 `python -m py_compile` 做语法检查,它会写 `__pycache__`;用 `python -c "import ast; ast.parse(open(path).read())"`。) + +本机 `import torch` 要 90 秒以上(venv 在 `/data0`,要加载近 2 GB 的 `libtorch_cuda.so`),所以全量迁移 +用**单个长驻进程**靠 `--resume` 续跑,验收也尽量合并进同一次进程,别按视图反复起进程。 + +### 收尾验收顺序 + +发布清单**不在发布树里**。它记录发布树每个文件的 sha256,而树内的副本描述不了自己写下去之后的树—— +写完清单本身就又改了树,清单永远落后一次编辑;所以它按 H2O、dex-ycb 的约定落在树外 +`tmp/reinterhand-tools/PUBLISH_MANIFEST.json`(H2O README:`PUBLISH_MANIFEST.json` 在发布树外记录可发布 +路径、大小与 SHA256),发布树里不含清单,也就不需要从自己的哈希里排除任何东西。 + +顺序仍然是**清单最后重建**:`FULL_MIGRATION_SUMMARY.json` 与重建后的 `doc/{CONTRACT,MIGRATION}.md`、 +`doc/V1_0_SEMANTICS.md`、复核页都是发布树里的文件,先建清单再写它们,清单记下的就不是最终字节。 +反过来,汇总又引用校验报告的结论,所以两者的依赖是单向的——清单引用汇总,汇总只引用**更早那次**校验。 +全套顺序: + +```bash +cd + +# 1 收口迁移:把「已就绪但还没迁」的视图补齐,--resume 会重核 checkpoint。 +python shared-v1.1/script/reinterhand_v1_1/migrate.py --resume + +# 2 逐视图字节级验收(CONTRACT 6)。这里带 --no-manifest:清单要遍历整棵树重算 sha256,而它早于 +# 第 6、7 步,建了也会被第 8 步覆盖。发布清单由第 8 步的 validate.py 最后重建(CONTRACT 6.4 要求的 +# 是清单被重建且正确,不要求由本工具来写) +python shared-v1.1/script/reinterhand_v1_1/verify.py --complete --no-manifest \ + --report tmp/reinterhand-tools/acceptance.json + +# 3 读取器路径验收(CONTRACT 6.5),报告放进发布树随发布保留 +python shared-v1.1/script/reinterhand_v1_1/read_sequence.py --all --quiet \ + --report shared-v1.1/doc/validation/read_sequence_sweep.json + +# 4 全量结构校验,报告作为汇总的守卫依据。同样带 --no-manifest:本步写下的 +# doc/validation/validate_report.json 早于第 6、7 步的文件,此时建的清单描述的不是最终字节; +# 第 8 步会覆盖这份报告并最后重建清单 +python shared-v1.1/script/reinterhand_v1_1/validate.py --expect-views 6750 --rewrite-check 2 \ + --no-manifest + +# 5 复核页渲染:只对**本机带着媒体的**序列渲染(未拉媒体的视图无法渲染,这是预期)。必须在第 6 步 +# 之前:复核页是发布树里的文件,汇总要数到它们,清单要哈希它们的最终字节。本步同时写下供人工复核的 +# index.html 与 V1_1_VALIDATION.json +python shared-v1.1/script/reinterhand_v1_1/render.py --workers 4 + +# 6 汇总:每一步的数字都从上面几份报告读出来,不手写;条件不满足就拒写 +python tmp/reinterhand-tools/write_full_migration_summary.py --expect-views 6750 + +# 7 重建 doc/ 的规范与两份 ReInterHand 自有文档的横幅(banner 由第 6 步的汇总推出), +# 并刷新 doc/history-v1.0/ 与 script/v1_0_snapshot/ +python shared-v1.1/script/provenance/operations/build_reinterhand_docs.py + +# 8 最后重建发布清单(写到树外 tmp/reinterhand-tools/PUBLISH_MANIFEST.json),此时它才覆盖第 6、7 步 +# 写下的文件。这里带 --rewrite-check 2:随发布保留的 validate_report.json 是**本步**写下的那一份 +# (第 4 步的会被覆盖),所以重写检查的样本要留在这一步 +python shared-v1.1/script/reinterhand_v1_1/validate.py --expect-views 6750 --rewrite-check 2 +``` + +第 6 步的守卫是刻意的:迁移视图数不足、**源树**视图数不足、源里仍有未迁移视图,或者验收/校验没通过, +汇总都会被拒写,横幅也就翻不过去。注意守卫**不**要求验收那一次建过清单:发布清单是第 8 步的产物, +验收建的那份只会被覆盖。 + +第 5 步的抽样规则写进随发布保留的 `doc/validation/V1_1_VALIDATION.json`,可复现:种子 `20261015`, +**在「本机带着媒体的序列」里按渲染策略各抽 1 个**。本机只有 2 个序列带媒体(见下「媒体是按需拉的」), +所以这一趟实际渲染了这 2 个序列的**全部** 27 个视图(`envmap_per_frame` 21 个 + `envmap_per_segment` 6 个), +两种渲染策略、两种相机族(`pinhole` 与 `opencv_fisheye4`)都覆盖到。全发布 500 个序列里只有这 2 个能渲染, +这一点写在页面上,而不是让页面看起来像抽了 500 个序列里的 2 个。 + +驱动与证据补齐的脚本放在发布树**之外**的 `tmp/reinterhand-tools/`:汇总、源提交登记、反例对照、媒体声明 +都在那里,不随发布上传。 + +## 运行期的两条纪律(MIGRATION §3/§4) + +**单实例锁。** `migrate.py` 在 `tmp/migration-v11/migration.lock` 上取 `flock` 并持有到退出;第二个 +进程会被拒绝并打印持锁者,而不是交错写入。就地更新不是整体原子操作,两个迁移进程写同一个目标视图, +会各自留下一个描述着「已被对方覆盖的树」的 checkpoint——不可信的 checkpoint 比没有更糟。`--dry-run` +不取锁。 + +**登记自足。** `tmp/migration-v11/registration.json` 记源与目标的 release/schema 摘要、源路径、工具摘要 +(`migrate.py`、`warehouse.py`、`schema.json`、Python 与 torch 版本)、逐视图的源/目标 metainfo 摘要与 +产出 bundle 摘要、被替换的源引用、错误与 traceback。checkpoint 也记录同一份工具摘要,所以**改动 +`migrate.py`、`warehouse.py` 或 `schema.json` 会让 `--resume` 重新迁移**(MIGRATION §4.4:续跑必须核对 +输入与工具版本,不能只看文件存在)。摘要按文件点名,不含目录:改 `verify.py`、`validate.py`、 +`read_sequence.py`、`render.py` 只影响校验与页面,不会让已迁移的视图重做。 + +ReInterHand 的源 HF 固定提交登记在**发布树外**的 `tmp/reinterhand-tools/source_registration.json`(仓库、 +提交号、该提交下 `ReInterHand/shared-v1.0` 的逐文件清单与完整性结果、逐文件归属哪个分区、以及**已声明的 +差异**),而不是像 ARCTIC 那样由 `migrate.py --source-revision/--source-manifest` 写进 +`registration.json`:ARCTIC 是边拉边迁、拉取状态决定哪段可迁,提交号必须与迁移登记绑在一起;ReInterHand +是一次性拼全的(两个分区合到一棵树),把提交号写进迁移工具反而会让 `registration.json` 的工具摘要与树里 +那份对不上,白白触发一次全量重迁。汇总以 `source_release.pinned_commit_record` 一节引用该记录。 + +## 媒体是按需拉的,不是搬过来的 + +全发布编码后的媒体是 **13,500 个流**(每个视图一个 `rgb.mkv` 加一个 `mask.mkv`,合计约 1.08 TB)。 +`MIGRATION.md` §3/§6 要求未变化的媒体留在原处,所以本机**只拉了 2 个样本序列的媒体**共 54 个文件,作为 +迁移的媒体读取验证(计划阶段 4 第 3 步);其余 498 个序列的 13,446 个流在本机**故意缺失**。这件事由 +树外的 `tmp/reinterhand-tools/media-presence.json` **申报**,`validate.py`、`read_sequence.py`、 +`render.py` 都接受 `--media-declaration`(默认就是那份文件)并据此放行。 + +两点设计上的要点: + +- **申报在树外,所以发布树默认是严格模式。** 声明文件不在 `shared-v1.1/` 里,`tmp/` 也不随发布上传; + 到了发布树里找不到声明,工具就要求每个被声明的媒体文件都必须存在。也就是说这份「缺失许可」不会跟着 + 数据跑出去。想在本机强制严格,传 `--strict-media`。 +- **申报是许可,不是免检。** 只有声明里点名的序列允许媒体缺席,且那 2 个序列必须**每个视图的两个流都齐** + ——`validate.py` 每次都会重核这两半,半拉的序列直接失败。这正是 `migrate.py` 一行都不用改的原因:它的 + 透传循环是 `src_view.rglob("*")`,源里没有的 mkv 它根本不会去访问。已拉入的 54 个流是 v1.0 源文件的 + **硬链接**(同 inode,不额外占字节),所以上传时 LFS 侧应复用服务端已有 blob。 + +## 迁移对 ReInterHand 的六处适配 + +**1. 相机集合不是固定数字范围。** 视图路径恒为 `data///`,但 `camera_id` 是「数字 +ID(同一 capture 内复用,全数据集去重 90 个)+ 字符串 `ego`」的混合,且 `ego` 是与数字相机**并列**的一级 +目录(`camera_id="ego"`),不是视图内的子树。所以 `discover_views` 的 `data/*/*/metainfo.json` 原样可用, +而校验按「该序列实际出现的集合」做,不写死 `range(9)`。这里如果不查,是最容易照抄 ARCTIC 而直接失败的一处。 + +**2. 两条渲染策略决定视图构成。** `envmap_per_frame` 的序列是 20 个 exo + ego = 21 个视图, +`envmap_per_segment` 是 5 个 exo + ego = 6 个;`sample_type` 分别为 `image`/`video`,`source_fps` 分别为 +`null`/`30`。两个策略在 500 个序列里各占一半,`render.py` 的抽样正是按策略分层。 + +**3. 跨相机同步判据按 `sync_id` 的集合/区间做。** ARCTIC 的「9 路逐帧 `sync_id` 一致」在 ReInterHand +不成立:ego 是 30 fps、exo 是 5 fps,同一序列内各相机 `num_frames` 不同(例如两个样本序列都是 181 帧, +但各视图自己的帧数按策略与相机而异)。`reinterhand_common.py` 改成按 `sync_id` 做集合与区间一致性判据。 + +**4. `frames.jsonl` 没有 `source_annotation_index`。** ReInterHand 的字段是 +`frame_index / sample_id / source_frame_id / source_locator{...} / sync_id / timestamp_ns / clock_domain`, +所以 ARCTIC 那条依赖 `source_annotation_index` 的对齐规则与 `check_annotation_alignment` **被删掉**而不是 +留着空转——留一个永远不触发、也永远不可能触发的检查,会让「通过」看起来比实际更有内容。 + +**5. 畸变只在 ego,且取 CONTRACT §3 的共享分支。** 500 个 `ego` 视图是 `opencv_fisheye4`、带独立的 +`distortion` 分量;6,250 个 `exo` 视图是 `pinhole`、没有。`reinterhand_common.py` 断言「有 `distortion` +分量」等价于「该视图是 `opencv_fisheye4`」,所以将来 exo 侧冒出畸变向量会被当成未登记字段抓住。v1.0 的 +`intrinsic` 分量声明了 `distortion_ref`/`distortion_key` 但没有独立的 `distortion_valid_ref`,故 CONTRACT §3 +要求该向量的有效性**要么与所属相机组件的有效性共享、要么展开为已声明的全真标量**;本次全部 500 个视图 +取的是共享分支,由 `verify.py` 对着源字节逐视图确认(`acceptance.json` 的 500 条 `valid_origin` 记作 +`shared with intrinsic validity (CONTRACT 3)`),不是断言出来的。 + +**6. 状态旗标比 RHD 多。** ReInterHand 的视图级 metainfo 带 `upload_authorized`(本地全 `false`)、 +`full_output_human_review`(`"pending"`)、`full_conversion_complete`、`conversion_scope`,以及 +`omitted_components`、`source_rendering` 等;RHD 的 release 根本没有这些键,所以 RHD 的「有没有人看过」 +只能由汇总表达。ReInterHand 两者都有,且**两者都仍是否定的**:树里的旗标是 v1.0 原样搬过来的(`verify.py` +除 `schema_version`、`release_id`、`components` 三个迁移必改的键外,其余顶层键逐字比对),汇总里的 +`human_full_review: "pending"`、`publication_authorized: false`、`hf_writes: false` 也一条都没有翻。 +**迁移不会把任何旗标翻成已完成**,这是硬规则。 + +**7. 顶层键的第四条例外:`storage_revision`。** 上面那句「其余顶层键逐字比对」对 +`storage_revision` **不成立**,而且是**有意的**:v1.0 的生产端把它写死成 `lossless-video-2026-09-25`, +`doc/schema.json` 声明的是 `lossless-video-2026-09-18`,已上传的 RHD、ARCTIC 每个视图都是后者(H2O 省略 +这个键)。`migrate.py` 的 `normalize_storage_revision()` 把它指回注册表声明的值,`verify.py` **只接受** +这一种改写(别的值一律失败,源里没有这个键的视图也不许凭空多出一个),`reinterhand_common.check_view()` +在发布树上同样拒绝别的值。为什么改、改了哪些、证据在哪,见 `doc/PUBLICATION_PLAN.md` 的「本次收尾的 +两处对齐」。 + +## 已知的保留项 + +- **本机只有 2 个序列的媒体。** 见上节。因此第 5 步的复核页只覆盖那 27 个视图,`validate.py` 的 + `--rewrite-check` 重写检查也只对**非媒体**文件做(媒体是硬链接、不重写)。这不是缺陷,是「媒体留在 + 原处」这条要求的直接后果;但它意味着**媒体层没有被本工具链逐字节验收过**——验收的是「媒体文件在源与 + 目标同 inode」这一事实(54 个,`media_verified_by: "same inode"`),不是重新解码比对像素。 +- **本机保留一份 `shared-v1.0`,Hub 上那份由发布时移除**(注册表 `release_layout` 要求升级后只留 + `shared-v1.1`)。本机这份是本次迁移的输入与逐字节比对基准,**不是**要发布的第二份数据,发布不动它、 + 继续留作证据(它还是那份未上传的 2026-09-29 修复的唯一副本);Hub 上那份按用户 2026-10-15 的指示 + (`sharedv1.0 可以删掉,和其他数据集一样`)由候选 PR 移除——仓库已在 Hub 的 100 万文件上限上, + 不腾地方就放不下 54,641 个新路径。移除只发生在上传侧:iipl_100 自己仍留着 + `shared-v1.0/doc/validation/`,发布的 v1.0 树在合并前的修订上也仍可取回。详见 `doc/PUBLICATION_PLAN.md`。 +- **本地 v1.0 的 `doc/` 与 `script/` 与 Hub 上发布的不是同一版,而且有两类原因,必须分开说。** 一类是 + **2026-09-29 的一次本地修复**,那次修复**从未上传**(`tmp/doc-script-repair-v1/receipt.json`:`stage + "repaired_not_uploaded"`、`upload_authorized: false`、`data_changed: false`),所以 Hub 上 + `ReInterHand/shared-v1.0` 仍是修复前的副本;这一类是 3 个 `script/` 文件(`config.json` 的本地分区标识、 + `README.md` 的那段说明、`checksums.json` 的清单)。另一类**与那次修复无关**:`doc/validation/` 是 + **iipl_126 一个分区的复核记录**,Hub 上那份覆盖两个分区——本机 `doc/validation/full/sequences/` 是 272 个 + 文件、Hub 上是 500 个,`full_random/iipl_126/` 两边都是 62 个而 `full_random/iipl_100/` 本机一个都没有; + 本机独有的 `full_random/partition-scope.json` 自己就写着 `host: iipl_126`,本机 `full/summary.json` + 写着 `sequences: 272`。因此这一类里 Hub 有而本机没有的是 **376 个**文件,另有 **5 个**两边都有但内容不同, + 且那 5 个全是**聚合文件**——内容取决于「这份副本有哪几个序列」的那几份。 + 两类都由 `tmp/reinterhand-tools/source_registration.py` **声明**并**逐次断言其规模**(3 个具名路径、 + 加上一类 `doc/validation/` 前缀,376 与 5 这两个数每次都得对上),任何新增的缺口都会直接让运行停下而不是 + 被静默吸收。后果要说清楚:`doc/V1_0_SEMANTICS.md`、`doc/history-v1.0/`、`script/v1_0_snapshot/` 复现的是 + **本机的 v1.0**——既带着那 3 个修复后的脚本,`doc/validation/` 下又只有 iipl_126 的那一份记录(没有 + iipl_100 的序列与 checkpoint 明细,聚合数字说的也是 272 个序列而不是发布版的 500 个)。**`data/` 不受任何 + 一类影响**:68,554 个文件对着 Hub 逐个比对全部相同,所以「与已发布的 v1.0 逐字节一致」这个说法只对 + `data/` 成立,**不能**说成「全树逐文件比对通过」。 +- **v1.0 的历史文件名不改。** `doc/RAW_MAPPING.md` 沿用 v1.0 时代的名字(其余发布的对应文档叫 + `RAW_TO_SHARED.md`,RHD 也保留了它的历史名);`build_reinterhand_docs.py` 因此不重写这份文档,而是 + **核对**它(它指向的每个 `script/...` 路径必须真实存在),名字保留是刻意的。 +- **属性检查器查取值,不只查存在。** `reinterhand_common.check_attributes()` 现在按 + `doc/schema.json` 的 `allowed_dtypes` 与 `visibility_types` 校验 `visibility_type` 的**取值**,并拒绝 + 错配的 dtype/词组合、超出 `ratio_range` 的 ratio、以及「无效位置不是 NaN」的 ratio;配对由 + `schema_visibility_types()` 从 schema 按位推出,不写第二张表。RHD 复核发现的正是这条缺口(把 dtype 的 + 词 `"bool"` 写进那个字段也照样通过),ReInterHand 这里没有属性可修(6,750 个视图一个都没声明),所以补 + 的是**将来**:某次重渲染写错不会再静默通过。反例对照与回归测试在树外的 + `tmp/reinterhand-tools/{visibility_enum_gap.py,test_v1_1_review_fixes.py}`。 +- **`doc/history-v1.0/` 是 548 个文件、752 MB。** ARCTIC 同样带着 412 MB 的 v1.0 文档材料,所以整套带上是 + 既有约定,不是本数据集的特例;其中 749 MB 是 114 个复核短片,`validation/index.html` 正是指向它们—— + 砍掉片子会让那份页面指向空处,那就不是「复现」了。 +- **人工视觉验收未重做。** 本次改的是物理布局,像素内容与 v1.0 逐字节相同(媒体硬链接、数值字节相等), + 故 v1.0 的人工结论不受影响;但这是**推理**,不是本次的实测。 + +## 证据 + +- `doc/validation/validate_report.json`:全量结构校验结果(视图数、帧数、各判据、每视图文件数、bundle 数、 + 重写检查样本、发布清单的路径与文件数),由收尾顺序第 8 步写下。 +- `doc/validation/read_sequence_sweep.json`:CONTRACT §6.5 的读取器路径验收在全发布上的汇总(500 个序列、 + 读到的字段数、声明的媒体数、失败列表),由随发布的 `read_sequence.py --all` 产出。 +- `doc/validation/V1_1_VALIDATION.json`:复核页的抽样规则、种子、入选序列与逐视图 QC 报告,以及 + MANO-on-mask 的全量聚合。 +- `doc/FULL_MIGRATION_SUMMARY.json`:全量迁移汇总,逐项从上面的报告与 `tmp/` 记录里读出来;**当前哪几步 + 已经跑过、哪些还没跑,以这份文件为准**(本 README 描述的是顺序,不是完成声明)。 +- `tmp/reinterhand-tools/acceptance.json`(**树外**):`verify.py` 的逐视图逐字段字节级比对明细(6,750 视图、 + 21,250 个合并字段、54 个媒体文件、13,446 个声明缺失)。 +- `tmp/reinterhand-tools/source_registration.json`(**树外**):源 HF 固定提交、该提交下 + `ReInterHand/shared-v1.0` 的逐文件完整性结果、分区归属,以及已声明的差异与修复凭据。 +- `tmp/reinterhand-tools/media-presence.json`(**树外**):本机声明带着媒体的序列(缺失许可)。 +- `tmp/reinterhand-tools/negative_controls.{py,json}`(**树外**):反例对照。在一个**沙箱**里注入两类已知 + 缺陷,断言检查器具名拦下——对照 A 把 `intrinsic.data_ref` 拼成复数 `camera/intrinsics.pt` + (`Registry.resolve()` 匹配不到就返回 `None`,调用方把 `None` 读成「媒体/JSONL/资产,原样保留」,**迁移 + 会干净退出**,而真正的数值文件被当成资产留在树里:这是本迁移最危险的静默失败),对照 B 从 metainfo 里 + 删掉 `segment` 分量(使 `mask_valid.pt` 成为无主的游离 valid)。两个缺陷都让 `migrate.py` 报告成功, + 两个都被具名抓到。**「0 失败」只有在检查器能失败时才有内容**,这份对照就是那件事的证据。 + 对照 A 不是凭空选的:本地 v1.0 树里**真的有一个** `metainfo.json` 带着这个复数拼写 + (`...__envmap_per_frame__160929__161469/400266/`),它已按固定提交从 Hub 还原(6,450 B、sha256 + `7d812a7a…`,与 `tmp/post-audit-v1.0-iipl126/files.jsonl` 和发布清单里独立记下的值一致),该视图也已 + 从还原后的源重新迁移(checkpoint 的 `source_metainfo_sha256` 就是 `7d812a7a…`)。 +- `tmp/reinterhand-tools/PUBLISH_MANIFEST.json`(**树外**,不是发布内容):发布树逐文件 sha256,第 8 步最后 + 重建;按 H2O、dex-ycb 的约定放在树外,理由见上一节。 +- `doc/history-v1.0/`(548 个文件、752 MB)与 `script/v1_0_snapshot/{doc,script}`(2 + 6 个文件):原样搬运的 + v1.0 文档、合同与脚本,属 CONTRACT §6.4「未修改文件须对照原始可信摘要」。注意上一节那条限定:它们复现的 + 是**修复后的本地 v1.0**。 + +验收只证明「重新打包在数值上逐字节同一」,不等同于人工目视确认(CONTRACT §6.5)。 + +**逐视图 HTML 目视页。** 与 H2O、dex-ycb、ARCTIC、RHD 一样,本发布在 `doc/validation/` 里带一套逐视图的 +目视页,由本目录的 `render.py` 生成(收尾顺序第 5 步)。它**只读 v1.1 的 bundle**,不引入 v1.0 时代的渲染栈 +或新的外部模型资产:每个值都经**随发布保留的读取器**(`Registry`/`BundleReader` 加 +`reinterhand_common.check_view`,也就是 `validate.py` 与 `read_sequence.py` 已经在调的同一批调用)读出来, +所以页面展示的是发布**声明**的东西,而不是另算一份。27 页、28 个 HTML(含 `index.html`)、32.1 MB, +单页最大 1.47 MB,每页自包含(图片是内嵌 `data:` URI,无脚本、无外链),因为要随发布离线阅读。 + +**本发布独有的自检:MANO 落在 mask 上。** ReInterHand 是各发布里**唯一**同时发布「逐帧 MANO 参数」 +(`annotation/mano/mano.pt`)与「前景强度图」(`annotation/segment/mask.mkv`)的,于是「把发布的 MANO +按该视图自己声明的相机模型展开并投影,看它是否落在发布的 mask 前景上」成了这套数据自己就能做的核验, +不需要任何外部资产。页面做的是**全视图扫描**:27 个视图、1,887 帧逐帧投影关节与顶点并与 mask 比对(mask +整段流式读一遍,只有像素是按抽样帧解码的),其中 1,692 帧的 mask 非空、可用于覆盖统计(另 138 帧 mask 全空, +全部落在两个 ego 视图里:11 + 127)。实测:逐视图命中率的中位数 0.973008,最差视图 0.950514(exo +`400483`),最好 0.991003(exo `400460`);左手 26,273/26,597 个画内关节落在前景上、1,233,482/1,293,446 个 +顶点;右手 26,742/26,742 与 1,260,837/1,298,643。mask 的实测取值域恰好是 `[0,255]`,与它声明的范围一致。 +全量聚合写进 `V1_1_VALIDATION.json` 的 `mano_on_mask`。 + +**画外点怎么判定、怎么披露。** 页面**不**把「投影到画外」当异常:`envmap_per_segment` 的 ego 视图每只手 +只有 5/181 帧有效(源本身就是稀疏的),且它的左手整块落在画面外。这两件事都**写在页面上**(该视图报告的 +`hands_geometry_entirely_off_frame` 与 `hands_not_drawn`,27 个视图里分别有 1 处与 8 处记名),而不是让 +页面看起来像全绿。MANO 的展开还带一处载重的细节:左手层在**字典与 layer 两处**都做了 +`shapedirs[:, 0] *= -1`(v1.0 的左手修复),位移在 forward 之后加上且已在相机坐标系内,ego 用该帧自己的 +4 个鱼眼系数——`mano_review.py` 里这几条都有注释,因为照抄别的 release 会静默画错一只手的形状。 + +这套页面是**人工验收要看的材料**,不是训练输入。CONTRACT §6.5 区分「重打包在数值上逐字节同一」与 +「人工目视验收」,页面给的是后者;渲出页面不等于有人看过,树里的 `full_output_human_review: "pending"` +与汇总里的 `human_full_review: "pending"` 照旧。ReInterHand v1.0 自己的复核产物(548 个文件,含 114 个 +短片)随发布保留在 `doc/history-v1.0/`。 \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/mano_review.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/mano_review.py new file mode 100644 index 0000000000000000000000000000000000000000..48aa7c3644516d5006e63a9c83c7e146b229bbc0 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/mano_review.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""MANO geometry for the ReInterHand shared-v1.1 review pages, from an external runtime. + +``mano/axis_angle61/v1`` stores *parameters*, not a hand: 16-joint axis-angle (48), +shape betas (10) and the global translation (3). CONTRACT 5.2 keeps the surface +geometry out of the shared release -- "需要渲染或接触计算时由 MANO 参数生成" -- and says +the model weights are not shipped with it either ("模型权重不作为共享数据附带上传"). So a +page that wants to draw a hand has to bring its own model, and this module is the seam +where it is handed one: a *runtime directory* holding ``models/MANO_{LEFT,RIGHT}.pkl`` +and a ``site/`` where ``smplx`` can be imported from. With no runtime the caller draws +the other panels and says why, rather than pretending the parameters are not there. + +Ported from the published v1.0 renderer ``shared-v1.0/script/preprocess_reinterhand.py`` +(``ManoModel`` / ``model_data`` / ``model_reader_class`` / ``project_vertices``) rather +than re-derived, so a v1.1 page draws the same geometry its v1.0 counterpart drew and +the two can be read side by side. Four of that code's details are load-bearing and +easy to lose when re-writing it: + +* **The left hand's first shape direction is negated**, in the raw model dict *and* in + the ``smplx`` layer. ``flat_hand_mean=True`` against the released ``MANO_LEFT.pkl`` + needs the correction; without it the left hand comes out mirrored, which on a review + page looks like a plausible hand and is therefore the worst kind of silent error. + CONTRACT 5.2 records it as part of ``model_profile`` ("左手 shapedirs 修正状态"). +* **The model file is a chumpy pickle.** It is read through a restricted unpickler + that allows only the reconstructors it actually needs, never the default one, so a + substituted model file cannot execute on import. +* **The translation is added after the forward pass**, not fed to ``smplx``, and it is + already in the camera frame (CONTRACT 5.2: "全局平移 3 ... 位于当前相机系"), so no + extrinsic is applied anywhere here. It is *not* a wrist joint -- the contract says so + explicitly -- which is why the review page measures the geometry it generates rather + than claiming the translation sits on the hand. +* **The pinhole/fisheye split follows the view's own camera model.** Exo views are + ``pinhole`` and are projected by ``uv = K @ xyz``; ego views are ``opencv_fisheye4`` + and go through ``cv2.fisheye.projectPoints`` with the view's own four coefficients. + Projecting an ego view with the pinhole formula would put a plausible-looking hand in + the wrong place. + +Nothing here decides whether the geometry is *right*: it returns vertices and joints in +the camera frame plus their projection, and the page reports what it measured. +""" +from __future__ import annotations + +import codecs +import collections +import io +import pickle +import sys +from pathlib import Path +from types import SimpleNamespace + +#: the position of each MANO parameter block inside ``mano/axis_angle61/v1``'s 61 values +POSE = slice(0, 48) +BETAS = slice(48, 58) +TRANSLATION = slice(58, 61) +#: 778 vertices, 3 columns, 10 shape directions -- what ``model_data`` refuses to run +#: without, so a substituted or truncated model file fails here instead of downstream +EXPECTED_SHAPEDIRS = (778, 3, 10) +EXPECTED_J_REGRESSOR = (16, 778) +#: the runtime's own model filenames, as the v1.0 producer laid them out +MODEL_FILES = {"left": "MANO_LEFT.pkl", "right": "MANO_RIGHT.pkl"} + + +class StoredState: + """The chumpy objects in ``MANO_*.pkl`` unpickle into this and nothing else.""" + + def __setstate__(self, state): + self.__dict__.update(state) + + +def model_reader_class(np, torch): + """A pickle reader that knows exactly the classes the MANO file needs. + + The two dictionaries below are the v1.0 producer's own + (``shared-v1.0/script/preprocess_reinterhand.py``), ported verbatim because they are the + measured answer to "what is actually in these files" -- not a guess to be narrowed. The + first probe of this port used a shorter list and the model refused to open on + ``scipy.sparse.csc.csc_matrix``, which is how the ``J_regressor`` is really stored; the + ``chumpy`` classes are how ``shapedirs`` is stored, and ``torch._utils``/``torch.storage`` + appear because the file also carries tensors. + + * ``allowed`` are reconstructed as themselves -- the numpy/torch readers, plus + ``collections.OrderedDict`` and ``codecs.encode`` which a latin1 pickle of this vintage + can contain. + * ``special`` are reconstructed as :class:`StoredState`: the caller only ever reads named + attributes off them (``a.x``/``idxs``/``preferred_shape`` for ``shapedirs``, + ``_shape``/``indptr``/``indices``/``data`` for the sparse matrix), so the real classes + are neither needed nor wanted -- importing chumpy or scipy to unpickle a model file + would add two heavyweight dependencies, and scipy's is not guaranteed present at all. + + Everything else is refused, so a model file that has been substituted cannot run code + through this path. + """ + allowed = { + ("numpy.core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, + ("numpy._core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, + ("numpy", "ndarray"): np.ndarray, + ("numpy", "dtype"): np.dtype, + ("numpy.core.numeric", "_frombuffer"): np.core.numeric._frombuffer, + ("numpy._core.numeric", "_frombuffer"): np.core.numeric._frombuffer, + ("_codecs", "encode"): codecs.encode, + ("collections", "OrderedDict"): collections.OrderedDict, + ("torch._utils", "_rebuild_tensor_v2"): torch._utils._rebuild_tensor_v2, + ("torch.storage", "_load_from_bytes"): lambda value: torch.load( + io.BytesIO(value), map_location="cpu", weights_only=True), + } + special = { + ("chumpy.ch", "Ch"): StoredState, + ("chumpy.reordering", "Select"): StoredState, + ("scipy.sparse.csc", "csc_matrix"): StoredState, + ("__builtin__", "set"): set, + ("builtins", "set"): set, + } + + class Restricted(pickle.Unpickler): + def find_class(self, module, name): + if (module, name) in special: + return special[(module, name)] + if (module, name) not in allowed: + raise pickle.UnpicklingError( + f"Unsupported model class: {module}.{name}") + return allowed[(module, name)] + + return Restricted + + +def model_data(path: Path, np, torch) -> dict: + """The MANO model dict, with its two stored-as-chumpy arrays materialised. + + ``shapedirs`` unpickles as a state object holding a flat blob and an index array; + ``J_regressor`` as a sparse column form. Both are expanded to dense arrays and checked + against the expected shapes, which is also the check that the file really is a MANO model. + """ + with path.open("rb") as stream: + data = model_reader_class(np, torch)(stream, encoding="latin1").load() + shapedirs = data["shapedirs"] + if isinstance(shapedirs, StoredState): + data["shapedirs"] = shapedirs.a.x.reshape(-1)[shapedirs.idxs].reshape( + shapedirs.preferred_shape) + sparse = data["J_regressor"] + if isinstance(sparse, StoredState): + dense = np.zeros(sparse._shape) + for column in range(sparse._shape[1]): + begin, end = sparse.indptr[column:column + 2] + dense[sparse.indices[begin:end], column] = sparse.data[begin:end] + data["J_regressor"] = dense + if (tuple(data["shapedirs"].shape) != EXPECTED_SHAPEDIRS + or tuple(data["J_regressor"].shape) != EXPECTED_J_REGRESSOR): + raise RuntimeError(f"{path}: not a MANO model " + f"({data['shapedirs'].shape}, {data['J_regressor'].shape})") + return data + + +def _distribution_version(name: str): + """The installed version of a distribution, or its ``__version__``, or None. + + ``smplx`` exposes no ``__version__``, so ``getattr`` alone reports nothing -- but the + version is worth recording, because a review page that says which runtime produced its + geometry is the difference between a reproducible artifact and a picture. + """ + try: + from importlib.metadata import version + + return version(name) + except Exception: # pragma: no cover - depends on the runtime + return None + + +class ManoRuntime: + """One loaded MANO pair, plus the geometry and projection the page needs. + + ``runtime_dir`` is a directory with ``models/MANO_{LEFT,RIGHT}.pkl`` and a ``site/`` + holding ``smplx``. ``site`` is *appended* to ``sys.path`` rather than prepended: + this process has already imported its own numpy/torch/cv2/PIL, and a runtime that + carries different builds of them must not displace the ones the rest of the tool + runs on. Only ``smplx`` is taken from the runtime. + """ + + def __init__(self, runtime_dir: Path, np, torch): + self.runtime_dir = Path(runtime_dir) + models_dir = self.runtime_dir / "models" + if not all((models_dir / name).is_file() for name in MODEL_FILES.values()): + raise FileNotFoundError(f"{models_dir}: MANO model files are missing") + site = self.runtime_dir / "site" + if site.is_dir() and str(site) not in sys.path: + sys.path.append(str(site)) + try: + import smplx + except ImportError as error: # pragma: no cover - depends on the runtime + raise SystemExit(f"smplx is not importable, with {site} on sys.path: {error}") + self.smplx = smplx + self.np = np + self.torch = torch + self.layers = {} + for side, filename in MODEL_FILES.items(): + data = model_data(models_dir / filename, np, torch) + layer = smplx.MANO(model_path=str(models_dir), + data_struct=SimpleNamespace(**data), + is_rhand=(side == "right"), use_pca=False, + flat_hand_mean=True) + if side == "left": + #: see the module docstring: the released left model is used with its + #: first shape direction negated, and the raw dict has to agree with the + #: layer or the two disagree about the same betas + data["shapedirs"][:, 0] *= -1 + layer.shapedirs[:, 0] *= -1 + self.layers[side] = layer + #: the released face list is the same for both hands (the left model is the + #: right one mirrored), so one copy is enough for drawing + self.faces = np.asarray( + model_data(models_dir / MODEL_FILES["right"], np, torch)["f"], dtype=np.int64) + self.record = { + "runtime": str(self.runtime_dir), + "models": {side: (models_dir / name).name for side, name in MODEL_FILES.items()}, + "model_bytes": {side: (models_dir / name).stat().st_size + for side, name in MODEL_FILES.items()}, + #: the *module* is recorded too, because "which smplx" is the whole point of + #: appending rather than prepending the runtime's site: it should be the one in + #: the runtime directory, and it is running on this interpreter's numpy/torch + "smplx": _distribution_version("smplx"), + "smplx_module": getattr(smplx, "__file__", None), + "numpy_version": np.__version__, "torch_version": torch.__version__, + "use_pca": False, "flat_hand_mean": True, + "left_shapedirs_first_column_negated": True, + "vertices": int(self.faces.max()) + 1, "faces": int(len(self.faces)), + "note": "the model weights are not part of the shared release (CONTRACT 5.2); " + "they are read from this runtime directory only", + } + + def geometry(self, side: str, motion): + """Vertices and 16 joints in the camera frame for one hand's whole view. + + ``motion`` is the ``[T, 2, 61]`` tensor; ``side`` selects the slot. Rows whose + ``valid`` is false are still evaluated -- the caller decides what to do with + them, and a page that silently dropped them could not report how many there are. + """ + values = self.np.asarray(motion[:, 0 if side == "left" else 1, :]) + pose = self.torch.as_tensor(values[:, POSE].copy(), dtype=self.torch.float32) + betas = self.torch.as_tensor(values[:, BETAS].copy(), dtype=self.torch.float32) + with self.torch.no_grad(): + output = self.layers[side](global_orient=pose[:, :3], hand_pose=pose[:, 3:], + betas=betas) + offset = values[:, TRANSLATION].reshape(-1, 1, 3) + return output.vertices.numpy() + offset, output.joints.numpy()[:, :16] + offset + + +def project_vertices(vertices, intrinsic, distortion, np, cv2): + """Camera-frame ``xyz`` to pixels, by the view's own declared camera model. + + ``distortion is None`` means the view is ``pinhole`` and the projection is + ``uv = K @ xyz``. Otherwise the view is ``opencv_fisheye4`` and the four + coefficients go through ``cv2.fisheye.projectPoints``, which is the model the + release names. Returns the pixel coordinates (NaN where the point is not in front + of the camera) and the in-front mask. + """ + vertices = np.asarray(vertices, dtype=np.float64) + visible = vertices[:, 2] > 1e-6 + result = np.full((len(vertices), 2), np.nan, dtype=np.float64) + if len(vertices) == 0: + return result, visible + if distortion is None: + projected = vertices @ np.asarray(intrinsic, dtype=np.float64).T + result[visible] = projected[visible, :2] / projected[visible, 2:3] + else: + #: the *frame's* four coefficients, not the view's ``[T, 4]`` stack: OpenCV asserts + #: ``_D.total() == 4``, so handing it the whole stack fails loudly rather than + #: silently -- which is the only reason this is worth an explicit assertion too + coefficients = np.asarray(distortion, dtype=np.float64).reshape(-1) + if coefficients.size != 4: + raise ValueError(f"opencv_fisheye4 needs four coefficients per frame, got " + f"{coefficients.size}") + points, _ = cv2.fisheye.projectPoints( + vertices.reshape(-1, 1, 3), np.zeros(3), np.zeros(3), + np.asarray(intrinsic, dtype=np.float64).reshape(3, 3), coefficients) + result[visible] = points.reshape(-1, 2)[visible] + return result, visible + + +def drawable_faces(faces, points, width: int, height: int, np): + """The hand's triangles that can be drawn, as pixel polygons. + + A face is skipped when any of its vertices is not finite or the whole triangle falls + outside the picture. This is the v1.0 renderer's own test, kept: a NaN or a pixel at + 1e6 would otherwise reach ``ImageDraw`` as a degenerate polygon and fill the panel. + """ + yield from ( + [(float(point[0]), float(point[1])) for point in polygon] + for polygon in (points[np.asarray(face, dtype=np.int64)] for face in faces) + if np.isfinite(polygon).all() + and max(polygon[:, 0]) >= 0 and min(polygon[:, 0]) < width + and max(polygon[:, 1]) >= 0 and min(polygon[:, 1]) < height) \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/migrate.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/migrate.py new file mode 100644 index 0000000000000000000000000000000000000000..a92ddc06b4b69bc111996353e93109199602d514 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/migrate.py @@ -0,0 +1,760 @@ +#!/usr/bin/env python3 +"""Migrate the adjacent shared-v1.0 tree of this dataset to shared-v1.1. + +Only the tensor layout changes (CONTRACT 1-5): numeric tensors and their validity +move into per-group bundles, metainfo references gain ``data_key``/``valid_key`` +with ``pt/tensor_bundle/v1`` storage, and the two version fields are bumped. +Sampling, frame counts, dtypes, values, NaN bit patterns, validity judgements, +units, coordinate frames, hand slots, split and ``valid_policy`` are carried over +untouched (CONTRACT 6.3). + +The source tree is never written to: this is a copy-out. Unchanged media and +JSONL are hardlinked by default, so nothing is re-encoded and no bytes are +duplicated (MIGRATION 2, 6). Every view is checkpointed with source and output +digests so ``--resume`` re-verifies rather than trusting file existence +(MIGRATION 4.4). +""" + +from __future__ import annotations + +import argparse +import fcntl +import json +import os +import shutil +import sys +import time +import traceback +from contextlib import contextmanager +from pathlib import Path + +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from warehouse import ( # noqa: E402 + BUNDLE_PROFILE, + DATA_TERMINAL, + RELEASE_ID, + SCHEMA_VERSION, + VALID_TERMINAL, + BundleWriter, + Registry, + expanded_all_known, + sha256_bytes, + sha256_file, + same_tensor, +) + +V10_SCHEMA_VERSION = "hand-warehouse/1.0" +TOOL_ID = "hw11-migrate" +TOOL_REVISION = "1" + +#: this package lives in /shared-v1.1/script/reinterhand_v1_1, so the +#: release and the dataset root beside it need no arguments. +RELEASE_ROOT = Path(__file__).resolve().parent.parent.parent +DATASET_ROOT = RELEASE_ROOT.parent + + +# -------------------------------------------------------------------------- +# filesystem helpers +# -------------------------------------------------------------------------- + +@contextmanager +def migration_lock(work: Path): + """MIGRATION 3: one migrator per dataset, held for the whole run. + + The lock file lives in ``tmp/`` beside the checkpoints it protects, outside + the release tree. A second run is refused rather than interleaved: two + processes writing the same destination view would each leave behind a + checkpoint describing a tree the other had already overwritten, and a + checkpoint that cannot be trusted is worse than none. + """ + work.mkdir(parents=True, exist_ok=True) + path = work / "migration.lock" + with path.open("a+", encoding="utf-8") as stream: + try: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + holder = path.read_text(encoding="utf-8").strip() or "unknown" + raise SystemExit( + f"another migration already holds {path} ({holder}); " + "refusing to run two at once (MIGRATION 3)" + ) from error + stream.seek(0) + stream.truncate() + stream.write(f"pid {os.getpid()} started {time.strftime('%Y-%m-%dT%H:%M:%S%z')}\n") + stream.flush() + try: + yield + finally: + fcntl.flock(stream, fcntl.LOCK_UN) + + +def _clone(src: Path, dst: Path) -> None: + """FICLONE (reflink) copy where the filesystem supports it.""" + with open(src, "rb") as reader, open(dst, "wb") as writer: + fcntl.ioctl(writer.fileno(), 0x40049409, reader.fileno()) + + +def materialise(src: Path, dst: Path, mode: str) -> str: + """Place an unchanged file at ``dst`` without ever re-encoding it. + + An existing destination is never trusted on existence alone: it must be the + same inode as the source, or match it by SHA256, otherwise it is replaced. + """ + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists(): + if os.path.samefile(src, dst): + return "same-inode" + if dst.stat().st_size == src.stat().st_size and sha256_file(dst) == sha256_file(src): + return "present-verified" + temp = dst.with_name(dst.name + ".hw11-tmp") + temp.unlink(missing_ok=True) + shutil.copy2(src, temp) + os.replace(temp, dst) + if mode in ("hardlink", "reflink"): + link = os.link if mode == "hardlink" else (lambda a, b: _clone(Path(a), Path(b))) + try: + link(src, dst) + return mode + except OSError: + pass + shutil.copy2(src, dst) + return "copy" + + +def load_tensor(path: Path) -> torch.Tensor: + tensor = torch.load(path, map_location="cpu", weights_only=True) + if not isinstance(tensor, torch.Tensor): + raise TypeError(f"{path}: expected a Tensor, got {type(tensor).__name__}") + return tensor + + +# -------------------------------------------------------------------------- +# registry conformance +# -------------------------------------------------------------------------- + +#: what a registered schema *is*, as opposed to what it is called +SCHEMA_IDENTITY_FIELDS = ("dtype", "shape", "valid_shape", "unit") + + +def schema_id_note(registry: Registry, owner: str, spec: dict, entry: dict, + bundle_rel: str, field: str): + """Reconcile a v1.0 ``schema_id`` with the bundle entry's ``schema_ids`` list. + + A mismatch is recorded as a note, not raised. CONTRACT 6.3 forbids changing + ``schema_id``, so a v1.0 label the registry words differently cannot be + corrected here; ``schema_ids`` is documented nowhere in CONTRACT.md or + MIGRATION.md; and the registry's own ``note`` calls it "a declarative registry, + not a JSON Schema document or executable validator". The check keeps its real + purpose by refusing only when the declared schema is not *structurally* the + field the entry allows (dtype, shape, valid_shape, unit) -- which is what a + wrong bundle entry actually looks like. + + The case this was written for is a v1.0 that labels a field with one of the + entry's ``schema_ids`` while declaring a ``convention`` the registry pairs with + a *different* one of them, the two definitions being identical in every identity + field. ``notes`` stays empty as long as no view does that; the pilot asserts it, + and the check is the guard that keeps a schema mismatch from being silently + accepted if one ever appears. + """ + allowed = entry.get("schema_ids") + schema_id = spec.get("schema_id") + if allowed is None or schema_id in allowed: + return None + declared = registry.components.get(schema_id) + if declared is None: + raise ValueError(f"{owner}: schema_id {schema_id!r} is not registered") + equivalent = [name for name in allowed + if all(declared.get(key) == (registry.components.get(name) or {}).get(key) + for key in SCHEMA_IDENTITY_FIELDS)] + if not equivalent: + raise ValueError( + f"{owner}: schema_id {schema_id!r} not allowed in {bundle_rel}:{field} and " + f"is not structurally equivalent to any of {list(allowed)}") + return { + "owner": owner, + "entry": f"{bundle_rel}:{field}", + "declared_schema_id": schema_id, + "entry_schema_ids": list(allowed), + "structurally_equivalent_to": equivalent, + "reason": "CONTRACT 6.3 forbids changing schema_id; the entry allows a " + "schema identical in dtype, shape, valid_shape and unit", + } + + +def shared_distortion_valid(registry: Registry, owner: dict, entry: dict, + data: torch.Tensor, owner_valid): + """The bool an existing camera model pairs between intrinsic and distortion. + + CONTRACT 3: "既有相机模型要求内参与单独畸变向量共用有效性时,在两个字段内保存 + 相同 bool 值并校验一致". This is the path for a v1.0 that declares + ``distortion_ref`` with no distortion validity of its own: the owning component's + intrinsic validity is the pairing the model already had, so this restates it + rather than expanding an all-true tensor that was never declared. + + ReInterHand's ego views reach this helper, and it is the interesting case. Their + v1.0 splits the two roles across two declarations: ``intrinsic`` carries the + pointer (``distortion_ref``, no validity) while the standalone ``distortion`` + component carries the bool (``valid_ref = camera/distortion_valid.pt``). The + search below keys on the pointer, so ``camera_meta`` is ``intrinsic``, its + ``distortion_valid_ref`` is absent, and the pairing falls to this helper -- which + is exactly the CONTRACT 3 relationship the model requires. The verdict is + checked against the component's own declaration rather than trusted; see the + staged-identity guard at the call site. + """ + required = (registry.components.get(owner.get("schema_id")) or {}).get( + "required_metadata") or [] + if not any(key.startswith("distortion") for key in required) or owner_valid is None: + return None + declared = _distortion_valid_shape(registry, entry, data) + if declared is None or list(owner_valid.shape) != declared: + return None + return owner_valid + + +def _distortion_valid_shape(registry: Registry, entry: dict, data: torch.Tensor): + """Resolve the declared ``valid_shape`` of whichever distortion schema fits ``data``. + + Which of the entry's schemas applies is decided structurally, by the declared + ``shape`` matching the tensor, so nothing is assumed from the model's name. + """ + for schema_id in entry.get("schema_ids") or []: + shape = (registry.components.get(schema_id) or {}).get("shape") + if not shape or len(shape) != data.ndim: + continue + if not all(isinstance(dim, str) or int(dim) == size + for dim, size in zip(shape, data.shape)): + continue + valid_shape = (registry.components.get(schema_id) or {}).get("valid_shape") or [] + return [data.shape[axis] if isinstance(dim, str) else int(dim) + for axis, dim in enumerate(valid_shape)] + return None + + +# -------------------------------------------------------------------------- +# per-view migration +# -------------------------------------------------------------------------- + +def _declared_shape(registry: Registry, owner: str, spec: dict, kind: str): + """The registry's declared ``(shape, valid_shape)`` for this field.""" + if kind == "attribute": + return None, registry.visibility_valid_shape(spec["axes"]) + schema_id = spec.get("schema_id") + entry = registry.components.get(schema_id) + if entry is None: + raise KeyError(f"{owner}: schema_id {schema_id!r} is not registered") + return entry.get("shape"), entry.get("valid_shape") + + +def _rewrite_reference(spec: dict, bundle_rel: str, keys: list, valid: torch.Tensor) -> dict: + """CONTRACT 5: same-file data/valid refs plus explicit dictionary keys.""" + before = { + "data_ref": spec.get("data_ref"), + "valid_ref": spec.get("valid_ref"), + "valid": spec.pop("valid", ""), + "valid_axes": spec.get("valid_axes"), + } + spec["data_ref"] = bundle_rel + spec["data_key"] = list(keys) + [DATA_TERMINAL] + spec["valid_ref"] = bundle_rel + spec["valid_key"] = list(keys) + [VALID_TERMINAL] + spec["storage"] = {"profile": BUNDLE_PROFILE} + spec["valid_storage"] = {"profile": BUNDLE_PROFILE} + # visibility metadata requires valid_axes (tensor_attributes.visibility); + # v1.0 wrote it as axes[:valid.ndim], so deriving it restates the same value. + axes = spec.get("axes") + if axes and not spec.get("valid_axes"): + spec["valid_axes"] = list(axes)[:valid.ndim] + return before + + +def _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes, + owner, spec, kind, num_frames): + """Stage one registered numeric field into its bundle. No-op when unmerged. + + Returns the field's bool validity Tensor, or ``None`` when the reference is not + a registered numeric field (media / JSONL / assets, preserved verbatim). The + caller needs that Tensor because this function rewrites ``spec`` in place via + `_rewrite_reference`, so the same spec can no longer be resolved to its source + field once staged. + """ + ref = spec.get("data_ref") + if not ref: + return None + resolved = registry.resolve(ref) + if resolved is None: + return None # media / JSONL / assets: preserved verbatim + bundle_rel, keys, entry = resolved + field = "/".join(keys) + + note = schema_id_note(registry, owner, spec, entry, bundle_rel, field) + if note is not None: + notes.append(note) + if entry.get("attribute_id") and kind != "attribute": + raise ValueError(f"{owner}: {bundle_rel}:{field} is an attribute entry") + if kind == "attribute" and not entry.get("attribute_id"): + raise ValueError(f"{owner}: {bundle_rel}:{field} is not declared as an attribute") + + source = src_view / ref + if not source.is_file(): + raise FileNotFoundError(f"{owner}: {ref} is registered but missing") + + data = load_tensor(source) + declared_shape, declared_valid_shape = _declared_shape(registry, owner, spec, kind) + if declared_shape and declared_shape[0] == "T" and data.shape[0] != num_frames: + raise ValueError( + f"{owner}: {ref} has {data.shape[0]} frames but metainfo says {num_frames}") + + valid_ref = spec.get("valid_ref") + if valid_ref: + valid = load_tensor(src_view / valid_ref) + consumed.add(valid_ref) + origin = f"source tensor {valid_ref}" + else: + if spec.get("valid") is not True: + raise ValueError(f"{owner}: {ref} has neither valid_ref nor a declared all-known scalar") + valid = expanded_all_known(data, declared_valid_shape) + origin = "expanded declared all-known scalar (CONTRACT 3)" + + writer = writers.get(bundle_rel) + if writer is None: + writer = writers[bundle_rel] = BundleWriter(dst_view, bundle_rel) + + # The registry fixes one entry per numeric field, so two components may share + # it (RHD's uv and xyz both read the same source visibility). Staging it + # once is correct; a second owner with different bytes is a registry mismatch. + identity = (bundle_rel, field) + prior = staged.get(identity) + if prior is None: + writer.put(keys, data, valid) + staged[identity] = {"data": data, "valid": valid, "owners": [owner], + "source_data_ref": ref, "source_valid_ref": valid_ref} + shared_with = None + else: + if not (same_tensor(prior["data"], data) and same_tensor(prior["valid"], valid)): + raise ValueError( + f"{owner}: {identity[0]}:{field} is already staged from " + f"{prior['source_data_ref']} with different values") + prior["owners"].append(owner) + shared_with = list(prior["owners"]) + consumed.add(ref) + + before = _rewrite_reference(spec, bundle_rel, keys, valid) + records.append({ + "owner": owner, + "kind": kind, + "entry": f"{bundle_rel}:{field}", + "source_data_ref": before["data_ref"], + "source_valid_ref": before["valid_ref"], + "source_scalar_valid": before["valid"], + "source_valid_axes": before["valid_axes"], + "valid_origin": origin, + "shared_entry_owners": shared_with, + "dtype": str(data.dtype), + "shape": list(data.shape), + "valid_shape": list(valid.shape), + "valid_true": int(valid.sum()), + "valid_false": int((~valid).sum()), + "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, + }) + return valid + + +def normalize_storage_revision(registry: Registry, meta: dict) -> bool: + """Point the view's ``storage_revision`` at the revision the registry itself declares. + + v1.0's converter stamped ``lossless-video-2026-09-25`` into all 6,750 views, and + ``doc/schema.json`` -- including the copy v1.0 shipped -- declares no such revision: + its own is ``lossless-video-2026-09-18``, the value the published v1.1 siblings + (RHD, ARCTIC) carry in every view. Nothing else about the key is a claim this + migration may touch, so the value is read off the schema rather than restated here, + and a view that declares no ``storage_revision`` keeps declaring none (the registry + does not require the key, and H2O's published v1.1 omits it outright). Returns + whether this view's value actually changed. + """ + if "storage_revision" not in meta: + return False + declared = registry.schema["storage_revision"] + changed = meta["storage_revision"] != declared + meta["storage_revision"] = declared + return changed + + +def migrate_view(registry, src_root, dst_root, sequence, camera, link_mode): + """Migrate one ``/`` view and return its report entry.""" + src_view = src_root / sequence / camera + dst_view = dst_root / sequence / camera + meta_path = src_view / "metainfo.json" + meta = json.loads(meta_path.read_text(encoding="utf-8")) + if meta.get("schema_version") != V10_SCHEMA_VERSION: + raise ValueError(f"{meta_path}: not {V10_SCHEMA_VERSION}") + if (meta.get("sequence_id"), meta.get("camera_id")) != (sequence, camera): + raise ValueError(f"{meta_path}: sequence_id/camera_id do not match the directory") + num_frames = meta["num_frames"] + + dst_view.mkdir(parents=True, exist_ok=True) + writers, consumed, records, staged, notes = {}, set(), [], {}, [] + + #: each component's staged validity, for a camera model that pairs it with the + #: separate distortion vector (CONTRACT 3). Taken from _stage's return value: + #: _stage rewrites the component in place, so re-resolving ``data_ref`` here + #: would read the already-migrated bundle path and never match an entry. + staged_valid = {} + for name, component in meta["components"].items(): + if not component.get("available", True): + continue + staged_valid[name] = _stage( + registry, src_view, dst_view, writers, consumed, records, staged, notes, + name, component, "component", num_frames) + for attribute, spec in (component.get("attributes") or {}).items(): + _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes, + f"{name}.{attribute}", spec, "attribute", num_frames) + + # camera distortion lives beside the intrinsic parameters (CONTRACT 5). v1.0 + # declares it on the camera component that owns the calibration -- ARCTIC puts + # ``distortion_ref`` on ``intrinsic`` -- so the components are searched first + # and the ``camera`` block is only a fallback. + # + # ReInterHand's ego views are the second shape: v1.0 declares the distortion + # twice, as a standalone ``distortion`` component *and* as + # ``intrinsic.distortion_ref``. The loop above has therefore already staged + # that entry (with the standalone component's own ``distortion_valid_ref``) + # before this block runs, and the two declarations must agree. ARCTIC's + # unconditional ``writer.put`` below would silently overwrite the component's + # declaration with the intrinsic validity; that is value-neutral here (all 500 + # ego views were verified byte-for-byte equal, see + # ``tmp/reinterhand-tools/check_distortion_valid.py``) but it would discard a + # declaration rather than checking it. So the entry goes through the same + # staged-identity guard ``_stage`` uses. + distortion_meta, distortion_owner = None, None + for name, component in meta["components"].items(): + if component.get("distortion_ref"): + distortion_meta, distortion_owner = component, name + break + if distortion_meta is None and (meta.get("camera") or {}).get("distortion_ref"): + distortion_meta = meta["camera"] + if distortion_meta is not None: + camera_meta = distortion_meta + owner_label = (f"{distortion_owner}.distortion" if distortion_owner + else "camera.distortion") + ref = camera_meta["distortion_ref"] + resolved = registry.resolve(ref) + if resolved is None: + raise ValueError(f"camera.distortion_ref {ref!r} does not resolve to a bundle") + bundle_rel, keys, entry = resolved + data = load_tensor(src_view / ref) + valid_ref = camera_meta.get("distortion_valid_ref") + if valid_ref: + valid = load_tensor(src_view / valid_ref) + consumed.add(valid_ref) + origin = f"source tensor {valid_ref}" + else: + valid = shared_distortion_valid(registry, distortion_meta, entry, data, + staged_valid.get(distortion_owner)) + if valid is not None: + origin = "shared with intrinsic validity (CONTRACT 3)" + else: + valid = expanded_all_known(data, camera_meta.get("distortion_valid_shape")) + origin = "expanded declared all-known scalar (CONTRACT 3)" + writer = writers.get(bundle_rel) or writers.setdefault( + bundle_rel, BundleWriter(dst_view, bundle_rel)) + identity = (bundle_rel, "/".join(keys)) + prior = staged.get(identity) + if prior is None: + writer.put(keys, data, valid) + staged[identity] = {"data": data, "valid": valid, "owners": [owner_label], + "source_data_ref": ref, "source_valid_ref": valid_ref} + shared_with = None + else: + if not (same_tensor(prior["data"], data) and same_tensor(prior["valid"], valid)): + raise ValueError( + f"{owner_label}: {identity[0]}:{identity[1]} is already staged from " + f"{prior['source_data_ref']} with different values") + prior["owners"].append(owner_label) + shared_with = list(prior["owners"]) + origin = (f"entry already staged from {prior['source_data_ref']}; " + f"{origin} agrees byte-for-byte") + consumed.add(ref) + camera_meta["distortion_ref"] = bundle_rel + camera_meta["distortion_key"] = list(keys) + [DATA_TERMINAL] + camera_meta["distortion_valid_ref"] = bundle_rel + camera_meta["distortion_valid_key"] = list(keys) + [VALID_TERMINAL] + records.append({ + "owner": owner_label, + "kind": "component", + "entry": f"{bundle_rel}:{'/'.join(keys)}", + "source_data_ref": ref, + "source_valid_ref": valid_ref, + "source_scalar_valid": "", + "source_valid_axes": camera_meta.get("distortion_valid_axes"), + "valid_origin": origin, + "shared_entry_owners": shared_with, + "dtype": str(data.dtype), + "shape": list(data.shape), + "valid_shape": list(valid.shape), + "valid_true": int(valid.sum()), + "valid_false": int((~valid).sum()), + "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, + }) + + # everything not consumed into a bundle is preserved byte-for-byte + passthrough = {} + for path in sorted(src_view.rglob("*")): + if not path.is_file(): + continue + rel = path.relative_to(src_view).as_posix() + if rel in consumed or rel == "metainfo.json": + continue + passthrough[rel] = materialise(path, dst_view / rel, link_mode) + + # MIGRATION 4.2: write, re-read, compare field by field, byte-exactly + verification = [] + for bundle_rel, writer in sorted(writers.items()): + path = writer.save() + if path is None: + continue + reloaded = torch.load(path, map_location="cpu", weights_only=True) + for keys, leaf in _walk_leaf(writer.tree): + node = reloaded + for key in keys: + node = node[key] + for terminal in (DATA_TERMINAL, VALID_TERMINAL): + if not same_tensor(leaf[terminal], node[terminal]): + raise AssertionError(f"{bundle_rel}:{'/'.join(keys)}:{terminal} not byte-identical") + verification.append({ + "bundle": bundle_rel, + "sha256": sha256_file(path), + "size": path.stat().st_size, + "fields": sum(1 for _ in _walk_leaf(writer.tree)), + "comparison": "byte_view_exact_no_tolerance", + }) + + meta["schema_version"] = SCHEMA_VERSION + meta["release_id"] = RELEASE_ID + storage_revision_changed = normalize_storage_revision(registry, meta) + _write_json(dst_view / "metainfo.json", meta) + + return { + "sequence_id": sequence, + "camera_id": camera, + "num_frames": num_frames, + "storage_revision_changed": storage_revision_changed, + "source_metainfo_sha256": sha256_file(meta_path), + "source_metainfo_size": meta_path.stat().st_size, + "output_metainfo_sha256": sha256_file(dst_view / "metainfo.json"), + "bundles": verification, + "fields": records, + "schema_notes": notes, + "passthrough_files": len(passthrough), + "passthrough_modes": sorted(set(passthrough.values())), + "replaced_source_refs": sorted( + {r["source_data_ref"] for r in records} | {r["source_valid_ref"] for r in records if r["source_valid_ref"]}), + } + + +def _walk_leaf(tree, prefix=()): + for key, value in tree.items(): + if isinstance(value, dict) and set(value) == {DATA_TERMINAL, VALID_TERMINAL}: + yield prefix + (key,), value + elif isinstance(value, dict): + yield from _walk_leaf(value, prefix + (key,)) + + +def _write_json(path: Path, value) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_name(path.name + ".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", + encoding="utf-8") + temp.replace(path) + + +# -------------------------------------------------------------------------- +# dataset driver +# -------------------------------------------------------------------------- + +def discover_views(src_root: Path): + views = [] + for meta in sorted(src_root.glob("data/*/*/metainfo.json")): + views.append((meta.parent.parent.name, meta.parent.name)) + return views + + +def tool_digest(script_dir: Path, schema_path: Path) -> dict: + return { + "tool": f"{TOOL_ID}/{TOOL_REVISION}", + "migrate_sha256": sha256_file(Path(__file__).resolve()), + "layout_sha256": sha256_file(script_dir / "warehouse.py"), + "schema_sha256": sha256_file(schema_path), + "python": sys.version.split()[0], + "torch": torch.__version__, + } + + +def source_manifest(path: Path | None) -> dict | None: + """Describe the tree-API manifest the source bytes were pulled against. + + The registration has to be readable on its own: "this tree came from revision + X" means little without the file list and digests that revision published, so + the manifest's own digest and size travel with it (MIGRATION 3). + """ + if path is None: + return None + entries = json.loads(path.read_text(encoding="utf-8")) + entries = entries["files"] if isinstance(entries, dict) else entries + return { + "path": str(path.resolve()), + "sha256": sha256_file(path), + "files": len(entries), + "bytes": sum(int(entry.get("size", 0)) for entry in entries), + } + + +def checkpoint_ok(state_path: Path, expected: dict, digest: dict) -> bool: + """MIGRATION 4.4: re-verify inputs, tool revision and artefacts, not existence.""" + if not state_path.is_file(): + return False + try: + prior = json.loads(state_path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + return False + if prior.get("tool") != digest: + return False + # a checkpoint describes one destination; never let it vouch for another + if prior.get("dst_view") != str(expected["dst_view"]): + return False + if prior.get("source_metainfo_sha256") != expected["source_metainfo_sha256"]: + return False + for bundle in prior.get("bundles", []): + path = Path(prior["dst_view"]) / bundle["bundle"] + if not path.is_file() or sha256_file(path) != bundle["sha256"]: + return False + meta = Path(prior["dst_view"]) / "metainfo.json" + if not meta.is_file() or sha256_file(meta) != prior["output_metainfo_sha256"]: + return False + return True + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--src", type=Path, default=DATASET_ROOT, + help="dataset root holding shared-v1.0 (default: the dataset " + "this package is installed in)") + parser.add_argument("--dst", type=Path, default=RELEASE_ROOT, + help="output release directory (default /shared-v1.1)") + parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json", + help="v1.1 schema.json (default /doc/schema.json)") + parser.add_argument("--link", default="hardlink", choices=["hardlink", "reflink", "copy"], + help="how unchanged media/JSONL is placed (default hardlink)") + parser.add_argument("--views", nargs="*", default=None, + help="restrict to these sequence ids") + parser.add_argument("--limit", type=int, default=None, help="migrate at most N views") + parser.add_argument("--resume", action="store_true", + help="skip views whose checkpoint re-verifies") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--source-revision", default=None, metavar="SHA", + help="the pinned revision the shared-v1.0 bytes came from; " + "recorded in the registration (MIGRATION 3)") + parser.add_argument("--source-manifest", type=Path, default=None, + help="tree-API manifest of that revision; its digest and file " + "count are recorded so the registration is self-contained") + args = parser.parse_args(argv) + + src_release = args.src / "shared-v1.0" + dst_release = args.dst or (args.src / "shared-v1.1") + if not src_release.is_dir(): + parser.error(f"{src_release} is not a directory") + schema_path = args.schema or (dst_release / "doc" / "schema.json") + if not schema_path.is_file(): + parser.error(f"v1.1 schema not found at {schema_path} (pass --schema)") + registry = Registry.load(schema_path) + + src_root, dst_root = src_release / "data", dst_release / "data" + views = discover_views(src_release) + if not views: + parser.error(f"no //metainfo.json found under {src_root}") + first = src_root / views[0][0] / views[0][1] / "metainfo.json" + dataset_id = json.loads(first.read_text(encoding="utf-8"))["dataset_id"] + + work = args.src / "tmp" / "migration-v11" + state_dir = work / "checkpoints" + if args.views: + wanted = set(args.views) + views = [v for v in views if v[0] in wanted] + if args.limit: + views = views[:args.limit] + + digest = tool_digest(Path(__file__).resolve().parent, schema_path) + print(f"dataset={dataset_id} views={len(views)} src={src_release} dst={dst_release}") + print(f"tool={digest['tool']} link={args.link}") + if args.dry_run: + for sequence, camera in views: + print(f" would migrate {sequence}/{camera}") + return 0 + + with migration_lock(work): + registration = { + "dataset_id": dataset_id, + "source": {"release": "shared-v1.0", "schema_version": V10_SCHEMA_VERSION, + "schema_sha256": sha256_file(src_release / "doc" / "schema.json") + if (src_release / "doc" / "schema.json").is_file() else None, + "path": str(src_release.resolve()), + "revision": args.source_revision, + "manifest": source_manifest(args.source_manifest)}, + "target": {"release": RELEASE_ID, "schema_version": SCHEMA_VERSION, + "schema_sha256": sha256_file(schema_path), "path": str(dst_release.resolve())}, + "tool": digest, + "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "views_total": len(views), + "views": [], + "errors": [], + } + + done = skipped = failed = 0 + for index, (sequence, camera) in enumerate(views, 1): + state_path = state_dir / f"{sequence}__{camera}.json" + dst_view = dst_root / sequence / camera + try: + if args.resume and checkpoint_ok(state_path, { + "dst_view": str(dst_view), + "source_metainfo_sha256": sha256_file(src_root / sequence / camera / "metainfo.json"), + }, digest): + skipped += 1 + print(f"[{index}/{len(views)}] {sequence}/{camera} skip (checkpoint re-verified)") + continue + entry = migrate_view(registry, src_root, dst_root, sequence, camera, args.link) + entry["dst_view"] = str(dst_view) + entry["tool"] = digest + entry["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + _write_json(state_path, entry) + registration["views"].append({k: entry[k] for k in ( + "sequence_id", "camera_id", "num_frames", "source_metainfo_sha256", + "output_metainfo_sha256", "bundles", "passthrough_files", + "replaced_source_refs", "schema_notes")}) + done += 1 + print(f"[{index}/{len(views)}] {sequence}/{camera} ok " + f"fields={len(entry['fields'])} bundles={len(entry['bundles'])} " + f"passthrough={entry['passthrough_files']}") + except Exception as error: # noqa: BLE001 - recorded, never hidden + failed += 1 + registration["errors"].append({ + "sequence_id": sequence, "camera_id": camera, + "error": f"{type(error).__name__}: {error}", + "traceback": traceback.format_exc(), + }) + print(f"[{index}/{len(views)}] {sequence}/{camera} FAILED: {error}", file=sys.stderr) + _write_json(work / "registration.json", registration) + + registration["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + registration["stage"] = "complete" if failed == 0 else "failed" + registration["counts"] = {"migrated": done, "skipped": skipped, "failed": failed} + _write_json(work / "registration.json", registration) + print(f"done={done} skipped={skipped} failed={failed}") + print(f"registration: {work / 'registration.json'}") + return 1 if failed else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/read_sequence.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/read_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..53ee2ba9022c12304f3af1c6e064df34b9436f7f --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/read_sequence.py @@ -0,0 +1,507 @@ +"""CONTRACT 6.5: read complete sequences through the v1.1 reader, every component. + +Acceptance item 5 asks for a check the byte-level ones cannot give. ``verify.py`` +compares a view's bytes against its own v1.0 source, which proves repackaging preserved +them, but it never decodes media and never crosses views -- a release whose bundles are +each individually byte-perfect and whose RGB, camera and annotations no longer line up +would pass it. ``validate.py`` crosses components, but per view and against the schema, +on a tree whose media may not be materialised. + +So this opens the finished release the way a consumer would, through ``BundleReader`` +and the registry, and checks the joins: + + frames the RGB's real packet count (ffprobe, demux only -- ``nb_frames`` is absent + in Matroska) equals the metainfo ``num_frames``, and so does every field's + ``T`` axis, the length of ``frames.jsonl`` and both standalone validities + pixels where the media is materialised, its decoded width and height equal the + view's declared ``camera.image_size``, which the contract defines as + ``[W, H]`` -- so the ffprobe ``width`` is compared with the first element + and ``height`` with the second, and the exo views' 667-wide by 1024-tall + portrait frames are a match rather than a transposed declaration. What the + file really is -- codec, pixel format -- is recorded. The declared ``rgb`` + storage profile is one of the gaps ``DECLARED_MEDIA_SCHEMA_GAPS`` names, so + the media has to be measured rather than believed + camera the directory the view lives in, its ``camera_id``, its ``camera`` block + and the intrinsic component's ``schema_id`` all name the same camera + presence every declared file opens, or is absent exactly as the media declaration + says. A half-pulled sequence fails from either side + sequence the sequence-wide joins: one capture, one segment, one span, one split, + and a sequence id that is exactly ``______`` + cameras ReInterHand's own join -- what RHD's shared visibility attribute is for it. + The cameras of a sequence have to agree about which source frames they + saw. Measured over all 500 sequences: the per-segment cells store the + same source frames in the same order from every camera, and the per-frame + cells' exo renders are a strict subset of the ego render. That is why + ``sync_id`` works as a join across cameras here, and why the ARCTIC rule + ("every camera the same frame count") must not be copied: ego renders at + 30 fps and exo at 5, so their frame counts differ by design. + +What it does not do: it never decodes pixels, compares an image to anything, or forms an +opinion about whether a mask looks right. CONTRACT 6.5 keeps that -- human visual +acceptance -- separate from this, and this tool is on the packaging side of that line. +""" + +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from reinterhand_common import ( # noqa: E402 + CAMERA_BY_VIEW_TYPE, + CAMERA_FAMILY_BY_VIEW_TYPE, + DATASET_ID, + DEFAULT_MEDIA_DECLARATION, + EXO_CAMERAS_BY_POLICY, + FRAMES_REF, + RELEASE_ID, + RELEASE_ROOT, + SCHEMA_VERSION, + SPLIT_SCHEME, + SPLIT_VALUES, + TMP_ROOT, + MediaDeclaration, + check_frames, + load, +) +from warehouse import BundleReader, Registry # noqa: E402 + + +def wildcard(segment: str) -> bool: + return "<" in segment and ">" in segment + + +def registered_entry(registry, bundle_rel: str, keys: list) -> bool: + """Is ``bundle_rel`` + ``keys`` an entry the registry declares? + + ``Registry.resolve`` answers the migrator's question -- given a *v1.0* ref, where did + those bytes go. A consumer asks the other direction: the v1.1 metainfo names a bundle + and a key path, and that pair has to be a registered entry. Same templates, matched + from the target side. + """ + ref = Path(bundle_rel).parts + for bundle in registry.bundles.values(): + template = Path(bundle["path"]).parts + if len(ref) != len(template) or ref[-1] != template[-1]: + continue + if not all(wildcard(w) or w == g for w, g in zip(template[:-1], ref[:-1])): + continue + for name in bundle["entries"]: + wanted = name.split("/") + if len(wanted) == len(keys) and all(wildcard(w) or w == k for w, k in zip(wanted, keys)): + return True + return False + + +def probe(path: Path): + """Demux-only facts about a media file: packet count, shape, codec. + + Packets, not decoded frames, and ``nb_read_packets`` rather than ``nb_frames`` + because Matroska does not carry the latter. Returns ``None`` where ffprobe is not + installed, which the caller records as "not decoded" rather than as a pass. + """ + if shutil.which("ffprobe") is None: + return None + out = subprocess.run( + ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", + "-show_entries", "stream=width,height,codec_name,pix_fmt,nb_read_packets", + "-of", "json", str(path)], + capture_output=True, text=True, check=True).stdout + stream = (json.loads(out).get("streams") or [{}])[0] + return {"frames": int(stream["nb_read_packets"]), "width": stream.get("width"), + "height": stream.get("height"), "codec": stream.get("codec_name"), + "pix_fmt": stream.get("pix_fmt")} + + +def load_tensor(path: Path): + """A standalone ``.pt`` outside the registry, read the way the release stores it.""" + with path.open("rb") as stream: + return torch.load(stream, map_location="cpu", weights_only=True) + + +def view_dirs(root: Path, sequence: str) -> list: + sequence_dir = root / "data" / sequence + if not sequence_dir.is_dir(): + raise SystemExit(f"no such sequence in the release: {sequence}") + #: ego sorts after the numeric camera ids under a plain string sort, and a reader + #: wants the cameras in a stable order rather than in ASCII order + return sorted((p for p in sequence_dir.iterdir() if p.is_dir()), + key=lambda p: (len(p.name), p.name)) + + +def all_sequences(root: Path) -> list: + return sorted(p.name for p in (root / "data").iterdir() if p.is_dir()) + + +def read_media(media, view: Path, name: str, component: dict, meta: dict, + record: dict, problem) -> None: + """A preserved media file, its standalone validity, and what the file really is. + + The validity is checked whatever the media's own state is. ``rgb_valid.pt`` and + ``mask_valid.pt`` belong to the numeric layer this working copy ships, so an absent + ``rgb.mkv`` must not skip them -- returning early on the media is exactly the bug + that would let a half-pulled sequence read as complete. + """ + ref = view / component["data_ref"] + state = media.state(view, meta["sequence_id"], component["data_ref"]) + entry = {"component": name, "ref": component["data_ref"], "state": state, + "bytes": ref.stat().st_size if ref.is_file() else None, "frames": None, + "declared_T_axis": (list(component["axes"]).index("T") + if "T" in (component.get("axes") or []) else None)} + #: the declared axes name the frame axis; it has to be one this tool can count, or + #: the frame checks below would be silently comparing nothing + if entry["declared_T_axis"] is None: + problem(f"{name}: declares no T axis, so its frame count cannot be checked") + if state == "missing": + problem(f"{name}: declared file {component['data_ref']} is missing") + elif state == "unexpected": + problem(f"{name}: {component['data_ref']} is present although the declaration " + f"says this copy ships no media for {meta['sequence_id']}") + elif state == "present": + facts = probe(ref) + if facts is None: + entry["probe"] = "ffprobe not installed; file present but not opened" + else: + entry.update(facts) + if facts["frames"] != meta["num_frames"]: + problem(f"{name}: {facts['frames']} packets in {component['data_ref']}, " + f"metainfo declares {meta['num_frames']}") + declared_size = list(meta["camera"]["image_size"]) + #: CONTRACT: ``camera.image_size`` is the logical RGB size ``[W, H]``, so the + #: first element is the frame *width*. Comparing it with the height instead + #: passes silently on the ego views (1024x1024, square) and fails on every + #: exo view, whose frames really are 667 wide by 1024 tall. + if [facts["width"], facts["height"]] != declared_size: + problem(f"{name}: {component['data_ref']} decodes as " + f"{facts['width']}x{facts['height']}, metainfo declares " + f"{declared_size} [W, H]") + record["media"].append(entry) + + valid_ref = component.get("valid_ref") + if not valid_ref: + entry["valid"] = None + return + valid_path = view / valid_ref + if not valid_path.is_file(): + problem(f"{name}: declared validity {valid_ref} is missing") + return + if valid_ref.endswith(".pt"): + #: CONTRACT 4: media validity stays a standalone bool Tensor. It is not + #: registered as a bundle, so it cannot be addressed by key + payload = load_tensor(valid_path) + entry["valid"] = {"ref": valid_ref, "kind": "pt", "dtype": str(payload.dtype), + "shape": list(payload.shape)} + if payload.dtype != torch.bool: + problem(f"{name}: validity {valid_ref} is {payload.dtype}, not bool") + if payload.ndim != 1 or payload.shape[0] != meta["num_frames"]: + problem(f"{name}: validity {valid_ref} is {list(payload.shape)}, metainfo " + f"declares {meta['num_frames']} frames on a T axis") + if list(component.get("valid_axes") or []) != ["T"]: + problem(f"{name}: valid_axes {component.get('valid_axes')!r} is not ['T'], " + f"so its length is not the frame count") + else: + frames = (probe(valid_path) or {}).get("frames") + entry["valid"] = {"ref": valid_ref, "kind": "media", "frames": frames} + if frames != meta["num_frames"]: + problem(f"{name}: validity {valid_ref} holds {frames} packets, metainfo " + f"declares {meta['num_frames']}") + + +def read_view(registry, reader, media, view: Path): + """Open every component of one view; return ``(meta, what the reader found)``.""" + meta = load(view / "metainfo.json") + where = f"{view.parent.name}/{view.name}" + record = {"view": where, "camera_id": meta.get("camera_id"), + "view_type": meta.get("view_type"), "num_frames": meta.get("num_frames"), + "fields": [], "media": [], "absent": [], "problems": []} + problem = record["problems"].append + for key, want in (("schema_version", SCHEMA_VERSION), ("release_id", RELEASE_ID), + ("dataset_id", DATASET_ID)): + if meta.get(key) != want: + problem(f"{key} is {meta.get(key)!r}, expected {want!r}") + + #: the view's own directory name and its declared camera must agree; the whole release + #: is laid out as //, so a mismatch would mean the calibration + #: and the pixels come from different cameras + if meta.get("camera_id") != view.name: + problem(f"directory {view.name} but camera_id {meta.get('camera_id')!r}") + model, camera_schema = CAMERA_BY_VIEW_TYPE.get(meta.get("view_type"), (None, None)) + if model is None: + problem(f"view_type {meta.get('view_type')!r} is none of " + f"{sorted(CAMERA_BY_VIEW_TYPE)}") + else: + #: the camera model follows from the view type -- ego is the fisheye, every exo + #: view is pinhole -- and a view whose block disagrees cannot be opened as either + camera = meta.get("camera") or {} + if camera.get("model") != model or camera.get("schema_id") != camera_schema: + problem(f"camera block is {camera.get('model')!r}/{camera.get('schema_id')!r}, " + f"a {meta['view_type']} view is {model!r}/{camera_schema!r}") + #: the camera family is the first two fields of every ``sample_id``, so a view that + #: names the other family would file its frames under the wrong identity + family = (meta.get("source_rendering") or {}).get("camera_family") + if family != CAMERA_FAMILY_BY_VIEW_TYPE.get(meta.get("view_type")): + problem(f"camera_family {family!r} is not " + f"{CAMERA_FAMILY_BY_VIEW_TYPE.get(meta.get('view_type'))!r}") + + for name, component in meta["components"].items(): + ref = component.get("data_ref") + if not component.get("available", True): + #: an omitted component must not leave a file claiming otherwise + if ref and (view / ref).exists(): + problem(f"{name}: available=false but {ref} exists") + record["absent"].append(name) + continue + if not ref: + problem(f"{name}: available but declares no data_ref") + continue + #: a component carrying ``data_key`` is bundled numeric data; one with only + #: ``data_ref`` is a preserved media/JSONL file. The registry entry is matched + #: from the target side. + if "data_key" not in component: + read_media(media, view, name, component, meta, record, problem) + continue + leaves = [(name, component["data_ref"], component["data_key"], + component["valid_key"], list(component.get("axes") or []))] + for attribute, spec in (component.get("attributes") or {}).items(): + leaves.append((f"{name}.{attribute}", spec["data_ref"], spec["data_key"], + spec["valid_key"], list(spec.get("axes") or []))) + for owner, bundle, data_key, valid_key, axes in leaves: + try: + data = reader.get(view, bundle, data_key) + valid = reader.get(view, bundle, valid_key) + except (KeyError, TypeError, FileNotFoundError) as error: + problem(f"{owner}: reader could not open {bundle}: {error}") + continue + if not isinstance(data, torch.Tensor) or valid.dtype != torch.bool: + problem(f"{owner}: {bundle} does not hold (Tensor, bool Tensor)") + continue + frames = data.shape[axes.index("T")] if "T" in axes else None + if frames is not None and frames != meta["num_frames"]: + problem(f"{owner}: {frames} frames on its T axis, metainfo declares " + f"{meta['num_frames']}") + if valid.shape != tuple(data.shape[: valid.ndim]): + problem(f"{owner}: valid {list(valid.shape)} is not a prefix of data " + f"{list(data.shape)}") + if not registered_entry(registry, bundle, data_key[:-1]): + problem(f"{owner}: {bundle}:{'/'.join(data_key[:-1])} is not a registered " + f"bundle entry") + record["fields"].append({ + "component": owner, "entry": f"{bundle}:{'/'.join(data_key)}", + "dtype": str(data.dtype), "shape": list(data.shape), "T": frames, + "valid_true": int(valid.sum()), "valid_false": int((~valid).sum())}) + return meta, record + + +def check_sequence(metas: dict, ids_by_camera: dict) -> list: + """The joins that only exist across a sequence's views. + + Everything here is measured over the release (see the module docstring); nothing is + a schema rule, which is why a copied ARCTIC or RHD version of this function fails. + """ + problems = [] + #: every camera of a sequence states the same sequence id, so any of them can be the + #: one this function reads it off -- the disagreement is itself checked below + meta = metas[sorted(metas)[0]] + sequence = meta["sequence_id"] + + #: one capture, one segment, one span, one split, one render setting -- a sequence is + #: one rendered segment of one capture, so a second value anywhere means the views of + #: this sequence come from different source material. The rest of ``source_rendering`` + #: is *not* sequence-wide: ``camera_family`` and ``official_render_rate_fps`` differ + #: between the ego and exo renders by design, so comparing the whole block would fail + #: every sequence of the release. + for key in ("source_capture_id", "source_segment_id", "source_frame_span", "split"): + seen = {json.dumps(metas[name].get(key), sort_keys=True) for name in metas} + if len(seen) > 1: + problems.append(f"{key}: the cameras of {sequence} disagree ({sorted(seen)})") + policies = {(metas[name].get("source_rendering") or {}).get("background_policy") for name in metas} + if len(policies) > 1: + problems.append(f"background_policy: the cameras of {sequence} disagree " + f"({sorted(str(p) for p in policies)})") + capture = meta.get("source_capture_id") or "" + policy = (meta.get("source_rendering") or {}).get("background_policy") + if policy not in EXO_CAMERAS_BY_POLICY: + problems.append(f"render setting {policy!r} is none of " + f"{sorted(EXO_CAMERAS_BY_POLICY)}") + span = meta.get("source_frame_span") or [None, None] + if capture: + #: the sequence id is the capture, the render setting and the span, in that order: + #: 500 of 500 sequences rebuild exactly, so this states the identity rather than + #: merely agreeing with it + rebuilt = f"{capture}__{policy}__{span[0]}__{span[1]}" + if rebuilt != sequence: + problems.append(f"sequence id {sequence!r} is not {rebuilt!r}") + locator = meta.get("split_source_locator") or {} + if locator.get("capture_id") != capture: + problems.append(f"split_source_locator names capture " + f"{locator.get('capture_id')!r}, metadata names {capture!r}") + if not locator.get("url"): + problems.append("split_source_locator names no url, so the split cannot be " + "traced to the official scheme") + if meta.get("split_scheme") != SPLIT_SCHEME: + problems.append(f"split_scheme {meta.get('split_scheme')!r} is not {SPLIT_SCHEME!r}") + if meta.get("split") not in SPLIT_VALUES: + problems.append(f"split {meta.get('split')!r} is none of {list(SPLIT_VALUES)}") + + #: the camera set: one ego view, and the render setting's own number of exo cameras. + #: A sequence missing a camera would otherwise read as a smaller sequence. + ego = sorted(c for c in metas if metas[c].get("view_type") == "ego") + exo = sorted(c for c in metas if metas[c].get("view_type") != "ego") + if ego != ["ego"]: + problems.append(f"expected exactly one ego view, found {ego}") + if policy in EXO_CAMERAS_BY_POLICY and len(exo) != EXO_CAMERAS_BY_POLICY[policy]: + problems.append(f"{len(exo)} exo camera(s), a {policy} sequence has " + f"{EXO_CAMERAS_BY_POLICY[policy]}") + + #: ReInterHand's cross-camera join. Every camera of a per-segment sequence stores + #: the same source frames in the same order; a per-frame sequence stores the ego + #: render in full and samples it for exo, so the exo frames are a strict subset. + #: Both are what makes ``sync_id`` (:) a usable join, and + #: both were measured over all 500 sequences rather than inferred from the FPS. + if ego and len(ego) == 1: + reference = ids_by_camera.get(ego[0]) or [] + if not reference: + problems.append("the ego view stored no source frames to join the others to") + for camera in exo: + ids = ids_by_camera.get(camera) or [] + if policy == "envmap_per_segment": + if ids != reference: + problems.append(f"{camera}: its source frames are not the ego view's " + f"({len(ids)} vs {len(reference)} stored)") + elif policy == "envmap_per_frame": + if not set(ids) <= set(reference): + extra = sorted(set(ids) - set(reference))[:5] + problems.append(f"{camera}: stores source frames the ego view does " + f"not, e.g. {extra}") + if len(ids) >= len(reference): + problems.append(f"{camera}: {len(ids)} frames is not fewer than the " + f"ego view's {len(reference)}, so nothing was sampled") + return problems + + +def sweep(root: Path, registry, media, sequence: str, quiet: bool) -> dict: + """Read every view of one sequence, then the joins that span them.""" + reader = BundleReader() + records, metas, ids_by_camera, frames_measurements = [], {}, {}, {} + for view in view_dirs(root, sequence): + meta, record = read_view(registry, reader, media, view) + frames_ref = (meta.get("sampling") or {}).get("frames_ref") or FRAMES_REF + frames_path = view / frames_ref + rows = [json.loads(line) for line in frames_path.read_text(encoding="utf-8").splitlines() + if line.strip()] if frames_path.is_file() else [] + #: the frame table's own rules live in reinterhand_common, so this tool reads it + #: once for the ids it needs to join cameras and asks the shared checker for the + #: verdict -- two copies of those rules would drift, and the ARCTIC/RHD ones do + #: not hold here (no annotation index, per-cell strides) + try: + frames_measurements[view.name] = check_frames(view, meta, rows) + except AssertionError as error: + record["problems"].append(f"frames.jsonl: {error}") + ids_by_camera[view.name] = [int(row["source_frame_id"]) for row in rows] + record["frames_source_span"] = [ids_by_camera[view.name][0], + ids_by_camera[view.name][-1]] if rows else None + record["frames_measurement"] = frames_measurements.get(view.name) + records.append(record) + metas[view.name] = meta + + sequence_problems = check_sequence(metas, ids_by_camera) + per_view_problems = [(r["view"], p) for r in records for p in r["problems"]] + + if not quiet: + print(f"{sequence}: {len(records)} view(s)") + for record in records: + print(f" {record['view']:<28} {str(record['view_type']):<4} " + f"cam={record['camera_id']} frames={record['num_frames']} " + f"fields={len(record['fields'])} media={len(record['media'])} " + f"absent={len(record['absent'])}") + for field in record["fields"]: + print(f" {field['component']:<26} {field['dtype']:<14} " + f"{str(field['shape']):<20} invalid={field['valid_false']}") + for entry in record["media"]: + shape = "" if entry.get("width") is None else f" {entry['width']}x{entry['height']}" + codec = "" if entry.get("codec") is None else f" {entry['codec']}/{entry.get('pix_fmt')}" + print(f" {entry['component']:<26} {entry['ref']:<28} " + f"{entry['state']:<15} {entry['bytes']} B frames={entry['frames']}" + f"{shape}{codec}") + measurement = record.get("frames_measurement") + if measurement: + print(f" frames.jsonl{'':<15} rows={measurement['rows']} " + f"modal_step={measurement['modal_step']} " + f"source_gaps={measurement['source_gaps']} " + f"stored={measurement['spans']} cell={measurement['cell']}") + + for view, issue in per_view_problems: + print(f"FAIL {view}: {issue}", file=sys.stderr) + for issue in sequence_problems: + print(f"FAIL {sequence}: {issue}", file=sys.stderr) + + return { + "sequence": sequence, + "views": records, + "sequence_problems": sequence_problems, + "view_problems": {record["view"]: record["problems"] for record in records}, + "accepted": not sequence_problems and not per_view_problems, + "scope": "repackaging equivalent by reading the release; not visual acceptance", + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("sequence", nargs="?", help="sequence id (omit with --all)") + parser.add_argument("--all", action="store_true", help="walk every sequence in the release") + parser.add_argument("--root", type=Path, default=RELEASE_ROOT) + parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json", + help="v1.1 schema.json (default /doc/schema.json)") + parser.add_argument("--media-declaration", type=Path, default=DEFAULT_MEDIA_DECLARATION, + help="where this copy of the tree declares which preserved media it " + f"ships (default: {DEFAULT_MEDIA_DECLARATION})") + parser.add_argument("--strict-media", action="store_true", + help="ignore the media declaration and require every declared media " + "file to exist") + parser.add_argument("--report", type=Path, + help="write the full record here as JSON " + "(default: tmp/reinterhand-tools/read_sequence.json with --all)") + parser.add_argument("--quiet", action="store_true") + args = parser.parse_args(argv) + + if not args.sequence and not args.all: + parser.error("name a sequence, or pass --all to walk the release") + registry = Registry.load(args.schema) + media = MediaDeclaration("all") if args.strict_media else MediaDeclaration.load(args.media_declaration) + sequences = all_sequences(args.root) if args.all else [args.sequence] + + records = [sweep(args.root, registry, media, sequence, args.quiet) for sequence in sequences] + accepted = all(record["accepted"] for record in records) + failed = [record["sequence"] for record in records if not record["accepted"]] + + report = { + "release": RELEASE_ID, + "sequences": len(records), + "sequences_accepted": len(records) - len(failed), + "failed": failed, + "media_declaration": media.origin, + "records": records if args.all else records[0], + "accepted": accepted, + "scope": "repackaging equivalent by reading the release; not visual acceptance", + } + target = args.report or (TMP_ROOT / "read_sequence.json" if args.all else None) + if target: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(f"wrote {target}") + if not args.quiet and args.all: + print(f"{len(records) - len(failed)}/{len(records)} sequence(s) accepted") + print("ACCEPTANCE_PASS" if accepted else "ACCEPTANCE_FAIL") + return 0 if accepted else 1 + + +if __name__ == "__main__": + sys.dont_write_bytecode = True + raise SystemExit(main()) \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/reinterhand_common.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/reinterhand_common.py new file mode 100644 index 0000000000000000000000000000000000000000..4b41cc49adb120543ba1cd791aefebaf8b2b1b3b --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/reinterhand_common.py @@ -0,0 +1,584 @@ +"""Shared helpers for the published ReInterHand shared-v1.1 tools. + +Adapted from RHD's second-generation tools: numeric tensors and their validity now +live in per-group bundles (``camera/camera.pt``, ``annotation/mano/mano.pt``) +addressed by the dictionary keys registered in ``doc/schema.json``, instead of one +``.pt`` per component with a sibling ``*_valid.pt``. Media and JSONL validity files +keep their standalone bool Tensor form and are not bundled (CONTRACT 4). + +Four things differ from RHD and ARCTIC. Each is a fact measured over all 6,750 +views of this release (``tmp/reinterhand-tools/surface_recon.json``), not a +preference, and each one breaks a checker that was copied without reading it: + +* **``camera_id`` is not a closed numeric range.** A view is addressed by its + ``camera_id``, which is either a Mugsy camera number (reused across captures; 90 + distinct values over the release) or the literal ``"ego"``. Nothing may assume + ``range(9)``, nor that a sequence has exactly one camera: this release has 250 + sequences with 21 views and 250 with 6. +* **``frames.jsonl`` has no ``annotation_index``.** Its rows are ``frame_index / + sample_id / source_frame_id / source_locator / sync_id / timestamp_ns / + clock_domain``, so the alignment rule ARCTIC and RHD use ("the annotation index + equals the source frame id") has no field to read here. The stored frames are + also not a clean stride: each view advances the source frame by one dominant step + (12 or 18 for exo ``envmap_per_frame``, 2 or 3 for the other three cells) with up + to four larger gaps where the source itself is missing frames, and only three of + the four cells store the whole declared span. See :data:`RENDER_CELLS`. +* **The media layer is not materialised in this working copy.** 1.08 TB of encoded + video is deliberately absent, so a declared ``rgb.mkv``/``mask.mkv`` that does not + exist is a *declared* absence, not a loss -- and the declaration is checked, so a + half-pulled media layer cannot hide behind it. See :class:`MediaDeclaration`. +* **The published v1.0 media metadata does not satisfy the shared schema.** The + ``rgb`` storage block is missing three of the seven required keys, ``segment`` + carries no storage block at all, and the ``rgb`` profile string is not registered. + A numeric-only migration may not repair that, so the gaps are *declared* and + *counted* here rather than silently tolerated. See + :data:`DECLARED_MEDIA_SCHEMA_GAPS`. +""" +from pathlib import Path +import codecs, collections, hashlib, json, pickle, subprocess + +import numpy as np +import torch + +from warehouse import BUNDLE_PROFILE, BundleReader, BundleWriter, Registry, expanded_all_known + +#: this module lives in /shared-v1.1/script/reinterhand_v1_1, so the release +#: tree and the dataset root beside it are found without arguments. +SCRIPT_DIR = Path(__file__).resolve().parent +RELEASE_ROOT = SCRIPT_DIR.parent.parent +DATASET_ROOT = RELEASE_ROOT.parent +TMP_ROOT = DATASET_ROOT / "tmp" / "reinterhand-tools" +REGISTRY = Registry.load(RELEASE_ROOT / "doc/schema.json") +_FFMPEG_EXE = None + +SCHEMA_VERSION = "hand-warehouse/1.1" +RELEASE_ID = "shared-v1.1" +DATASET_ID = "ReInterHand" + +#: Measured vocabulary. ``doc/schema.json`` allows ``view_type: unknown`` and +#: constrains nothing else here, so the release's own values are asserted instead -- +#: a new one appearing unnoticed is exactly the kind of drift these tools exist for. +SPLIT_VALUES = ("train", "test") +SPLIT_SCHEME = "InterWild_official_capture_split" +CAMERA_BY_VIEW_TYPE = {"exo": ("pinhole", "camera/pinhole/v1"), + "ego": ("opencv_fisheye4", "camera/opencv_fisheye4/v1")} +#: the only view type whose camera model carries a separate distortion vector +DISTORTION_VIEW_TYPE = "ego" +#: The four render cells of this release, each with the facts that follow from it. +#: View counts measured over the whole tree: exo/per_frame 5,000; exo/per_segment +#: 1,250; ego/per_frame 250; ego/per_segment 250. +#: +#: ``modal_steps`` is the source-frame stride: the captures were rendered at rates +#: that differ per capture, and a view's stored frames advance by one dominant step +#: with up to four larger gaps where the source capture itself is missing frames -- +#: measured, not assumed: no cell has a single fixed step, and the largest observed +#: gap is 3,278. ``covers_span`` says whether the view stores the whole declared +#: ``source_frame_span``; the exo per-frame renders sample a subset of it (4,860 of +#: 5,000 views start late or end early), which is why "first stored == span start" +#: must not be asserted for that cell. +RENDER_CELLS = { + ("exo", "envmap_per_frame"): {"modal_steps": (12, 18), "covers_span": False, "sample_type": "image", + "sampling": "independent", "source_fps": None, + "sequence_id_role": "batch_identifier_only", "temporal_relationship": False}, + ("exo", "envmap_per_segment"): {"modal_steps": (2, 3), "covers_span": True, "sample_type": "video", + "sampling": "dense", "source_fps": 30, + "sequence_id_role": "temporal_sequence", "temporal_relationship": True}, + ("ego", "envmap_per_frame"): {"modal_steps": (2, 3), "covers_span": True, "sample_type": "image", + "sampling": "independent", "source_fps": None, + "sequence_id_role": "batch_identifier_only", "temporal_relationship": False}, + ("ego", "envmap_per_segment"): {"modal_steps": (2, 3), "covers_span": True, "sample_type": "video", + "sampling": "dense", "source_fps": 30, + "sequence_id_role": "temporal_sequence", "temporal_relationship": True}, +} +#: The camera family is part of every ``sample_id`` and follows from the view type: +#: 6,250 exo views say ``Mugsy_cameras``, 500 ego views ``Ego_cameras``, nothing else. +#: It is *not* shared across a sequence's cameras -- ``source_rendering`` differs between +#: the two families by design (ego renders at 30 fps, the per-frame exo captures at 5), +#: so only ``background_policy`` is a sequence-wide value. +CAMERA_FAMILY_BY_VIEW_TYPE = {"exo": "Mugsy_cameras", "ego": "Ego_cameras"} +#: Exo cameras per sequence, measured: the per-frame captures were rendered from 20 +#: Mugsy cameras, the per-segment ones from 5, and every sequence has exactly one +#: ``ego`` view besides (250 sequences per cell, 500 in all). Shared, so +#: ``validate.py``'s release census and ``read_sequence.py``'s per-sequence join +#: cannot drift apart about what a complete sequence is. +EXO_CAMERAS_BY_POLICY = {"envmap_per_frame": 20, "envmap_per_segment": 5} +FRAMES_REF = "camera/frames.jsonl" +FRAME_FIELDS = ("clock_domain", "frame_index", "sample_id", "source_frame_id", + "source_locator", "sync_id", "timestamp_ns") +LOCATOR_FIELDS = ("capture", "render_setting", "segment", "source_frame_id") +#: ReInterHand publishes no ``source_annotation_index``, so the v1.0/v1.1 alignment +#: rule ARCTIC and RHD use ("the annotation index equals the source frame id") has +#: no field to read here and must not be copied. ``sync_id`` is the join instead: +#: ``:``, shared by every camera that saw that frame. +SYNC_ID_SEPARATOR = ":" + +#: Schema requirements the published v1.0 does not meet and that a numeric-only +#: migration is not allowed to repair: the release contract for v1.1 is "merge each +#: group's numeric tensors, leave media, JSONL and metadata otherwise untouched". +#: Every entry was measured as uniform over all 6,750 views, both in the v1.0 source +#: and in the migrated tree, so nothing here is a migration defect -- and the map is +#: asserted against a whole-tree tally, so neither a new gap nor a silent repair can +#: slip past. Repairing one of these is a deliberate act: update the map, the +#: release notes and ``doc/PUBLICATION_PLAN.md`` together. +#: +#: Why they exist (v1.0 wrote the media components by hand, not through a +#: schema-driven writer): ``rgb`` records only four of ``video_metadata.required``'s +#: seven keys -- no ``encoded_size``, ``decoder`` or ``encoder_parameters`` -- and +#: names its profile ``mkv/ffv1_rgb24/v1``, which appears neither in +#: ``storage_profiles`` nor in ``rgb/uint8/v1.allowed_storage_profiles``; +#: ``segment`` declares no ``storage`` block and omits ``segmentation_type``, +#: ``coverage`` and ``entity_id``. The encoder facts cannot even be recovered here, +#: because the media that would state them is not materialised. +DECLARED_MEDIA_SCHEMA_GAPS = { + "rgb/uint8/v1/required.storage.encoded_size": 6750, + "rgb/uint8/v1/required.storage.decoder": 6750, + "rgb/uint8/v1/required.storage.encoder_parameters": 6750, + "rgb/uint8/v1/storage.profile.unregistered:mkv/ffv1_rgb24/v1": 6750, + "rgb/uint8/v1/storage.profile.not_allowed:mkv/ffv1_rgb24/v1": 6750, + "segment/foreground_intensity/v1/storage": 6750, + "segment/foreground_intensity/v1/required.segmentation_type": 6750, + "segment/foreground_intensity/v1/required.coverage": 6750, + "segment/foreground_intensity/v1/required.entity_id": 6750, +} + +#: Where the working copy declares which preserved media it actually ships. Kept +#: tree-external on purpose: a release must not ship a file that excuses missing +#: media, so the tools are strict unless a caller names a declaration. +DEFAULT_MEDIA_DECLARATION = TMP_ROOT / "media-presence.json" + +def ffmpeg_exe(): + """Resolve the bundled FFmpeg lazily: reading tensors must not require it.""" + global _FFMPEG_EXE + if _FFMPEG_EXE is None: + import imageio_ffmpeg + _FFMPEG_EXE = imageio_ffmpeg.get_ffmpeg_exe() + return _FFMPEG_EXE + +def load(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + +def save(path, value): + path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8") + tmp.replace(path) + +def write_jsonl(path, rows): + path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(json.dumps(x, ensure_ascii=False, allow_nan=False) + "\n" for x in rows), encoding="utf-8") + +def save_tensor(path, value): + """Standalone validity: a CPU bool Tensor at the root, never a dict (CONTRACT 4).""" + path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) + torch.save(torch.as_tensor(np.asarray(value).copy()), path) + +lines = write_jsonl +tensor = save_tensor + +def ffmpeg(args, data=None): + result = subprocess.run([ffmpeg_exe(), "-v", "error", "-y", *map(str, args)], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if result.returncode: + raise RuntimeError(result.stderr.decode(errors="replace")) + return result.stdout + +ff = ffmpeg + +class RestrictedUnpickler(pickle.Unpickler): + def find_class(self, module, name): + allowed = { + ("numpy.core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, + ("numpy._core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, + ("numpy", "ndarray"): np.ndarray, ("numpy", "dtype"): np.dtype, + ("numpy.core.numeric", "_frombuffer"): np.core.numeric._frombuffer, + ("numpy._core.numeric", "_frombuffer"): np.core.numeric._frombuffer, + ("_codecs", "encode"): codecs.encode, + ("collections", "OrderedDict"): collections.OrderedDict, + } + if (module, name) not in allowed: + raise pickle.UnpicklingError(f"Unsupported class: {module}.{name}") + return allowed[(module, name)] + +Restricted = RestrictedUnpickler + +class MediaDeclaration: + """Which preserved media files this copy of the tree actually ships. + + A published release carries every file its metainfo declares. This working copy + does not: the encoded video is 1.08 TB and is pulled sequence by sequence, so the + tools are handed a declaration saying which sequences have their media. The + distinction the class exists for is between a file that is *absent by + declaration* and one that is *missing*: + + * a declared-absent file is checked to be absent -- pulling half a sequence's + media fails instead of passing quietly behind the declaration; + * anything the declaration does not cover must exist. + + ``materialised`` is ``"all"``, ``"none"``, or a list of sequence ids. With no + declaration the default is ``"all"``: that is what a published tree looks like, + and it is what makes the sample sequences pulled for the media read-through + verifiable without a special case. + """ + + def __init__(self, materialised="all", origin=None): + self.materialised = materialised if materialised in ("all", "none") else set(materialised) + self.origin = origin + + @classmethod + def load(cls, path=None): + path = Path(path) if path is not None else DEFAULT_MEDIA_DECLARATION + if not path.is_file(): + return cls("all", origin=None) + doc = load(path) + return cls(doc["media_materialised"], origin=str(path)) + + def ships(self, sequence): + if self.materialised == "all": return True + if self.materialised == "none": return False + return sequence in self.materialised + + def state(self, base, sequence, ref): + """``present`` / ``declared absent`` / ``missing`` / ``unexpected``.""" + exists = (Path(base) / ref).is_file() + if self.ships(sequence): return "present" if exists else "missing" + return "unexpected" if exists else "declared absent" + +def declared_gap(token, gaps): + """Record a schema requirement this release knowingly does not meet. + + Returns True when the caller should skip its assertion. Counting instead of + merely skipping is the point: an undeclared gap still raises, and a declared one + that stops occurring shows up as a tally mismatch in ``validate.py``. + """ + if token not in DECLARED_MEDIA_SCHEMA_GAPS: + return False + gaps[token] = gaps.get(token, 0) + 1 + return True + +def walk_leaf(tree, prefix=()): + for key, value in tree.items(): + if isinstance(value, dict) and set(value) == {"data", "valid"}: + yield prefix + (key,), value + elif isinstance(value, dict): + yield from walk_leaf(value, prefix + (key,)) + +def raw_bytes(value): + value = value.detach().cpu().contiguous() + try: return value.numpy().tobytes() + except (TypeError, RuntimeError): return value.view(torch.uint8).numpy().tobytes() + +REGISTRY_READER = BundleReader() + +def stray_validity(rel, registry=REGISTRY): + """A standalone validity file whose data field the registry merges into a bundle. + + CONTRACT 6.1 names this failure explicitly: a numeric component's validity left + behind as its own file because its name was not recognised. Asked of the + registry rather than of a list of names, so it keeps catching new components. + Media validity (``rgb_valid.pt``, ``mask_valid.pt``) resolves to nothing and is + therefore not stray -- MIGRATION 2 forbids deleting those by glob. + """ + return rel.endswith('_valid.pt') and registry.resolve(rel[:-len('_valid.pt')] + '.pt') is not None + +def shape_symbols(meta, component, registry=REGISTRY): + """Authoritative values for the symbolic axes a registry template may use.""" + symbols = {"T": meta["num_frames"]} + schema = component.get("keypoint_schema") + if schema: symbols["K"] = registry.schema["keypoints"][schema]["count"] + return symbols + +def resolve_shape(template, tensor, symbols): + """Resolve a registry shape template against a real tensor. + + ``T`` and ``K`` come from the view metadata and the registry, so mismatches are + caught; any other symbolic axis falls back to the tensor's own extent. + """ + dims = [] + for axis, dim in enumerate(template): + assert axis < tensor.ndim, (list(template), list(tensor.shape)) + dims.append(symbols[dim] if isinstance(dim, str) and dim in symbols + else (tensor.shape[axis] if isinstance(dim, str) else dim)) + return dims + +def schema_visibility_types(registry=REGISTRY): + """``{dtype: visibility_type}`` exactly as ``doc/schema.json`` declares it. + + CONTRACT 5: an attribute's ``visibility_type`` is not a second dtype. It says how + the numbers are to be read -- ``"boolean"`` for bool data, ``"ratio"`` for float32 -- + and the schema lists ``allowed_dtypes`` and ``visibility_types`` in step, so the + pairing is read off that file rather than restated here. + """ + visibility = registry.schema["tensor_attributes"]["visibility"] + dtypes = list(visibility["allowed_dtypes"]) + types = list(visibility["visibility_types"]) + assert len(dtypes) == len(types), (dtypes, types) + return dict(zip(dtypes, types)) + + +def check_attributes(base, name, component, registry, reader=REGISTRY_READER, symbols=None): + """Validate every bundled numeric attribute on a component (CONTRACT 3, 5).""" + visibility = registry.schema["tensor_attributes"]["visibility"] + required = visibility["required_metadata"] + by_dtype = schema_visibility_types(registry) + assert symbols, (name, "caller must supply the view's shape symbols") + for attribute, spec in (component.get("attributes") or {}).items(): + where = f"{name}.{attribute}" + for key in required: + assert key in spec, (where, key) + #: the enum, and the dtype it pairs with. Presence, storage profile, dtype and + #: shape were all this checked before, so any word at all passed as a + #: ``visibility_type``: RHD's review found exactly that (its writer had put the + #: dtype word ``"bool"`` in a field whose only declared values are + #: ``"boolean"``/``"ratio"``). A ratio is float32, and its invalid entries are + #: the schema's ``unknown`` (NaN) rather than a second boolean mask. This + #: release declares no visibility attribute at all, so the branch is reached by + #: the regression test outside the tree, not by the release itself. + assert spec["dtype"] in visibility["allowed_dtypes"], (where, spec["dtype"]) + assert spec["visibility_type"] in visibility["visibility_types"], ( + where, spec["visibility_type"], visibility["visibility_types"]) + assert spec["visibility_type"] == by_dtype[spec["dtype"]], ( + where, spec["dtype"], spec["visibility_type"]) + assert spec["data_ref"] == spec["valid_ref"], (where, "must share one bundle file") + assert spec["storage"]["profile"] == BUNDLE_PROFILE, where + assert spec["valid_storage"]["profile"] == BUNDLE_PROFILE, where + data, valid = reader.field(base, spec) + assert valid.dtype == torch.bool, (where, "valid must be bool") + if spec["visibility_type"] == "boolean": + assert data.dtype == torch.bool, (where, data.dtype) + else: + assert data.dtype == torch.float32, (where, data.dtype) + invalid = ~valid + if bool(invalid.any()): + assert bool(torch.isnan(data[invalid]).all()), (where, "ratio must be NaN where invalid") + low, high = visibility["ratio_range"] + assert bool(((data[valid] >= low) & (data[valid] <= high)).all()), ( + where, "ratio outside", visibility["ratio_range"]) + expected = resolve_shape(registry.visibility_valid_shape(spec["axes"]), data, symbols) + assert list(data.shape) == expected, (where, list(data.shape), expected) + assert list(valid.shape) == list(data.shape), (where, "valid shape must match data") + assert list(spec["valid_axes"]) == list(spec["axes"])[:valid.ndim], (where, spec.get("valid_axes")) + assert bool(valid.all()), (where, "expanded all-known validity must be all true") + return set() + +def check_view(base, meta, registry=REGISTRY, reader=REGISTRY_READER, media=None, gaps=None): + """Structural checks for one view; returns the paths consumed into bundles. + + Shared by ``validate.py``, ``read_sequence.py`` and ``render.py`` so all three + exercise the same registry-driven reader instead of loading ``.pt`` files + directly. + + ``gaps`` accumulates the schema requirements declared in + :data:`DECLARED_MEDIA_SCHEMA_GAPS`; ``media`` is the :class:`MediaDeclaration` + for this copy of the tree. Asserts everything else, so an undeclared deviation + fails here instead of being counted. + """ + base = Path(base) + media = MediaDeclaration() if media is None else media + gaps = collections.Counter() if gaps is None else gaps + where = f"{meta.get('sequence_id')}/{meta.get('camera_id')}" + consumed = set() + + assert meta["schema_version"] == SCHEMA_VERSION, (where, meta.get("schema_version")) + assert meta["release_id"] == RELEASE_ID, (where, meta.get("release_id")) + assert meta["dataset_id"] == DATASET_ID, (where, meta.get("dataset_id")) + #: the view's storage revision is the registry's own. v1.0's converter stamped + #: ``lossless-video-2026-09-25``, which ``doc/schema.json`` declares nowhere; the + #: published v1.1 siblings carry the registry's ``lossless-video-2026-09-18`` in + #: every view, and migration points this one at the same value. Omitting the key + #: stays legal -- the registry does not list it in ``view_metadata.required_fields`` + #: -- so "absent" is accepted as declaring nothing rather than as a gap. + assert meta.get("storage_revision", registry.schema["storage_revision"]) \ + == registry.schema["storage_revision"], (where, meta.get("storage_revision")) + for key in registry.schema["view_metadata"]["required_fields"]: + assert key in meta, (where, "view metadata", key) + assert meta["view_type"] in registry.schema["view_metadata"]["view_type_values"], (where, meta["view_type"]) + assert meta["split"] in SPLIT_VALUES, (where, meta.get("split")) + assert meta["split_scheme"] == SPLIT_SCHEME, (where, meta.get("split_scheme")) + assert meta["hand_slots"] == ["left", "right"], (where, meta.get("hand_slots")) + + #: camera identity follows from the view type, and so does whether a separate + #: distortion vector exists -- ego is ``opencv_fisheye4`` and carries one, every + #: exo view is ``pinhole`` and carries none. Both facts are 6,750/6,750 uniform. + view_type = meta["view_type"] + assert view_type in CAMERA_BY_VIEW_TYPE, (where, view_type) + model, camera_schema = CAMERA_BY_VIEW_TYPE[view_type] + assert meta["camera"]["model"] == model, (where, meta["camera"].get("model"), model) + assert meta["camera"]["schema_id"] == camera_schema, (where, meta["camera"].get("schema_id"), camera_schema) + assert ("distortion" in meta["components"]) == (view_type == DISTORTION_VIEW_TYPE), ( + where, "distortion component", sorted(meta["components"])) + #: the split is a property of the capture, carried on every view of a sequence + assert meta["source_capture_id"] == meta["split_source_locator"]["capture_id"], ( + where, meta.get("source_capture_id"), meta["split_source_locator"].get("capture_id")) + + for name, component in meta["components"].items(): + schema_id = component.get("schema_id") + spec = registry.components.get(schema_id) + assert spec is not None, (where, name, schema_id, "unregistered") + if "data_key" in component: + #: a bundled numeric field: the migration owns it, the registry fixes its shape + for key in ("data_key", "valid_key", "storage", "valid_storage", "valid_ref", "valid_axes"): + assert key in component, (where, name, key) + assert component["data_ref"] == component["valid_ref"], (where, name, "bundled refs must share a file") + assert component["storage"]["profile"] == BUNDLE_PROFILE, (where, name, component["storage"]["profile"]) + assert component["valid_key"] == list(component["data_key"])[:-1] + ["valid"], (where, name, component["valid_key"]) + for key in spec.get("required_metadata", []): + assert key in component, (where, name, "required metadata", key) + data, valid = reader.field(base, component) + assert valid.dtype == torch.bool, (where, name, "valid must be bool") + symbols = shape_symbols(meta, component, registry) + assert list(data.shape) == resolve_shape(spec["shape"], data, symbols), (where, name, list(data.shape)) + assert list(valid.shape) == resolve_shape(spec["valid_shape"], valid, symbols), (where, name, list(valid.shape)) + assert list(component["valid_axes"]) == list(component["axes"])[:valid.ndim], (where, name, "valid_axes") + assert not data.is_floating_point() or bool(torch.isfinite(data[valid]).all()), (where, name, "non-finite where valid") + consumed.add(component["data_ref"]) + else: + #: a preserved media file: the migration leaves it alone, so its metadata + #: is v1.0's -- including the parts the shared schema would have wanted + assert "valid_key" not in component, (where, name, "media/JSONL must not carry valid_key") + is_media = component["data_ref"].endswith(".mkv") + state = media.state(base, meta["sequence_id"], component["data_ref"]) if is_media \ + else ("present" if (base / component["data_ref"]).is_file() else "missing") + assert state != "missing", (where, name, component["data_ref"], "absent with no declaration covering it") + assert state != "unexpected", (where, name, component["data_ref"], + "present although the declaration says this copy ships no media") + storage = component.get("storage") + for key in spec.get("required_metadata", []): + if key in component: continue + #: an absent storage block is one gap, not one per key inside it + token = f"{schema_id}/storage" if (key == "storage" and storage is None) \ + else f"{schema_id}/required.{key}" + if declared_gap(token, gaps): continue + raise AssertionError((where, name, "required metadata", key)) + if component["data_ref"].endswith(".pt"): + valid = torch.load(base / component["valid_ref"], map_location="cpu", weights_only=True) + assert valid.dtype == torch.bool, (where, name, "standalone validity must be a bool Tensor") + symbols = shape_symbols(meta, component, registry) + assert list(valid.shape) == resolve_shape(spec["valid_shape"], valid, symbols), (where, name, list(valid.shape)) + consumed.add(component["valid_ref"]) + elif storage is not None: + for key in registry.schema["video_metadata"]["required"]: + if key not in storage and declared_gap(f"{schema_id}/required.storage.{key}", gaps): continue + assert key in storage, (where, name, "storage metadata", key) + profile = storage.get("profile") + if profile not in registry.schema["storage_profiles"] \ + and declared_gap(f"{schema_id}/storage.profile.unregistered:{profile}", gaps): pass + else: + assert profile in registry.schema["storage_profiles"], (where, name, "unregistered profile", profile) + if profile not in spec.get("allowed_storage_profiles", []) \ + and declared_gap(f"{schema_id}/storage.profile.not_allowed:{profile}", gaps): pass + else: + assert profile in spec.get("allowed_storage_profiles", []), (where, name, "profile not allowed", profile) + consumed.add(component["data_ref"]) + check_attributes(base, name, component, registry, reader, shape_symbols(meta, component, registry)) + return consumed + +def check_frames(base, meta, rows=None): + """Validate ``frames.jsonl``; returns the measurements a whole-tree sweep adds up. + + ReInterHand's frame table is not ARCTIC's or RHD's, and the four render cells do + not share one rule, so the field rules and the stride both come from the measured + cell table in :data:`RENDER_CELLS` rather than from a copied rule: + + * the cell ``(view_type, background_policy)`` fixes ``sample_type``, the sampling + type, ``source_fps``, ``sequence_id_role`` and whether the view stores the whole + declared span; + * ``sample_id`` is ``:::: + `` and ``sync_id`` is ``:`` -- the + join between the cameras that saw the same source frame. There is no + annotation index to align against; + * ``source_frame_span`` repeats the trailing ``____`` of the sequence + id and must contain every stored frame, in strictly increasing order. + + The gap count -- steps larger than the cell's dominant stride -- is **reported, + not asserted**: the source captures genuinely skip frames, so any bound would + encode this tree's accidents as a rule. What must hold is the identity of every + row, its order, and the span it lives in. + + ``rows`` may be supplied by a caller that has already parsed the file. + """ + where = f"{meta.get('sequence_id')}/{meta.get('camera_id')}" + rendering = meta["source_rendering"] + cell = (meta["view_type"], rendering["background_policy"]) + assert cell in RENDER_CELLS, (where, "render cell", cell) + expected = RENDER_CELLS[cell] + assert meta["sample_type"] == expected["sample_type"], (where, meta.get("sample_type"), expected["sample_type"]) + assert meta["sequence_id_role"] == expected["sequence_id_role"], (where, meta.get("sequence_id_role")) + sampling = meta["sampling"] + assert sampling.get("type") == expected["sampling"], (where, sampling.get("type")) + assert sampling.get("source_fps") == expected["source_fps"], (where, sampling.get("source_fps")) + assert sampling.get("temporal_relationship") is expected["temporal_relationship"], (where, sampling.get("temporal_relationship")) + frames_ref = sampling.get("frames_ref") + assert frames_ref == FRAMES_REF, (where, "frames_ref", frames_ref) + + path = Path(base) / frames_ref + assert path.is_file(), (where, "frame table", frames_ref) + if rows is None: + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + assert len(rows) == meta["num_frames"], (where, "rows", len(rows), meta["num_frames"]) + assert rows, where + + capture = meta["source_capture_id"] + render_setting = f"{rendering['camera_family']}/{rendering['background_policy']}" + samples, syncs = set(), set() + for index, row in enumerate(rows): + assert set(row) == set(FRAME_FIELDS), (where, index, "frame fields", sorted(row)) + assert row["frame_index"] == index, (where, index, "frame_index", row["frame_index"]) + assert row["clock_domain"] is None and row["timestamp_ns"] is None, ( + where, index, "no clock is published for ReInterHand frames", row["clock_domain"], row["timestamp_ns"]) + parts = str(row["sample_id"]).split(SYNC_ID_SEPARATOR) + assert len(parts) == 5, (where, index, "sample_id", row["sample_id"]) + assert parts == [capture, rendering["camera_family"], rendering["background_policy"], + meta["camera_id"], str(row["source_frame_id"])], (where, index, "sample_id", row["sample_id"]) + assert row["sync_id"] == capture + SYNC_ID_SEPARATOR + str(row["source_frame_id"]), ( + where, index, "sync_id", row["sync_id"]) + locator = row["source_locator"] + assert set(locator) == set(LOCATOR_FIELDS), (where, index, "source_locator", sorted(locator)) + assert locator["capture"] == capture, (where, index, "locator capture", locator["capture"]) + assert locator["render_setting"] == render_setting, (where, index, "render_setting", locator["render_setting"]) + assert locator["segment"] == meta["source_segment_id"], (where, index, "locator segment", locator["segment"]) + assert str(locator["source_frame_id"]) == str(row["source_frame_id"]), (where, index, "locator frame id") + assert row["sample_id"] not in samples, (where, index, "duplicate sample_id", row["sample_id"]) + assert row["sync_id"] not in syncs, (where, index, "duplicate sync_id", row["sync_id"]) + samples.add(row["sample_id"]); syncs.add(row["sync_id"]) + + ids = [int(row["source_frame_id"]) for row in rows] + assert ids == sorted(ids) and len(set(ids)) == len(ids), (where, "source_frame_id must strictly increase") + steps = [b - a for a, b in zip(ids, ids[1:])] + assert all(step >= 1 for step in steps), (where, "source frame step", min(steps)) + modal, count = collections.Counter(steps).most_common(1)[0] + assert modal in expected["modal_steps"], (where, "dominant source frame step", modal, expected["modal_steps"]) + + #: the declared span repeats the sequence id and bounds every stored frame; the + #: three video/dense cells store all of it, the exo per-frame cell a subset of it + declared = [int(part) for part in meta["sequence_id"].split("__")[-2:]] + span = meta["source_frame_span"] + assert span == declared, (where, "source_frame_span", span, "sequence id", declared) + assert span[0] <= ids[0] and ids[-1] <= span[1], (where, "stored frame outside the declared span", [ids[0], ids[-1]], span) + if expected["covers_span"]: + assert span == [ids[0], ids[-1]], (where, "cell stores the whole span", [ids[0], ids[-1]], span) + return {"rows": len(rows), "modal_step": modal, "source_gaps": len(steps) - count, + "spans": [ids[0], ids[-1]], "covers_span": expected["covers_span"], "cell": list(cell)} + +def audit(base, meta, registry=REGISTRY, reader=REGISTRY_READER, media=None, rows=None): + """``(consumed, gaps, failures, frames)`` for one view -- never raises. + + The three tools sweep whole trees, where an exception per view would abort the + sweep and hide the rest. Both checkers run, so one failing does not mask the + other, and the failures are reported by name for the view that produced them. + ``frames`` is :func:`check_frames`' measurement record, or ``None`` if it failed. + """ + gaps, failures, consumed, frames = collections.Counter(), [], set(), None + for label, check in (("check_view", lambda: check_view(base, meta, registry, reader, media, gaps)), + ("check_frames", lambda: check_frames(base, meta, rows))): + try: + result = check() + if label == "check_view": consumed = result + else: frames = result + except AssertionError as error: + failures.append(f"{meta.get('sequence_id')}/{meta.get('camera_id')}: {label}: {error}") + return consumed, gaps, failures, frames + +def sha256(path): + h = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(8 << 20), b""): h.update(block) + return h.hexdigest() \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/render.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/render.py new file mode 100644 index 0000000000000000000000000000000000000000..e0daaa374cb295094c5804158c30d3ec0a61885c --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/render.py @@ -0,0 +1,1192 @@ +#!/usr/bin/env python3 +"""Render sampled ReInterHand shared-v1.1 views to self-contained HTML review pages. + +CONTRACT 6.5 keeps "the repackaging preserved the bytes" apart from "a human looked at +it". H2O, dex-ycb, ARCTIC and RHD all ship sampled per-view pages for the second half; +this gives ReInterHand the same artifact, written against the v1.1 layout rather than +ported from any of them: + +* every value is read through the released reader -- ``Registry``/``BundleReader`` plus + ``reinterhand_common.check_view``, the calls ``validate.py`` and ``read_sequence.py`` + already make -- so a page shows what the release declares rather than a re-derived copy + of it. ``data_key`` in a component marks a bundled numeric field; media, the standalone + ``*_valid.pt`` files beside it and the JSONL are read as the preserved files they are. +* the panels are the vocabulary of ReInterHand's **own** published v1.0 renderer + (``shared-v1.0/script/render_reinterhand_full_random.py`` and its pages under + ``doc/validation/full_random/``): native RGB, the MANO mesh in cyan for the left hand and + orange for the right, and the free-standing non-binary foreground mask as grayscale + intensity. That vocabulary is used unchanged so a reviewer can read a v1.1 page against + a v1.0 one -- including the one thing it is easy to get backwards, which is that this + release's MANO colours are **not** RHD's red/blue. +* the v1.0 renderer required a MANO runtime (``smplx`` plus the ``MANO_*.pkl`` weights) and + drew the geometry from it. Those weights are not part of the shared release (CONTRACT + 5.2: 模型权重不作为共享数据附带上传), so the runtime is an **optional input** here: with + ``--mano-runtime`` the MANO panel is drawn, without it the page names the missing runtime + and draws the rest. Either way the parameters are checked, because they are release + content. +* what the v1.0 pages could not do is measure the **join between the bundled parameters and + the preserved mask**, since there the two were separate files. v1.1 is where they live + one ``.pt`` apart, so this page projects the MANO geometry of *every* frame of the view + -- not only the sampled ones -- and reports how much of it lands on the mask's foreground. + The number is recorded, never asserted and never used to "fix" anything: a systematic + offset would be a finding about the release, not a reason to change a page. + +Per-frame validity is not uniform, and the pages have to survive that: over the two sample +sequences the exo views are valid on every frame while one sequence's ego view has only 5 of +181 frames valid per hand. Sampling therefore always includes the first valid and the first +invalid frame of each series, and a hand whose slot is invalid is left undrawn with the +reason on the panel rather than drawn from parameters the release marks invalid. + +Every page is one self-contained file (previews as base64 JPEG data URIs -- a lossy +*preview* of a lossless frame, which CONTRACT 6 does not forbid because the release's own +bytes are untouched; PNG was used for RHD's 320x320 frames, and at 667x1024 portrait it +would make the page set an order of magnitude larger). Only the sampled RGB frames are +decoded; the mask is streamed once, end to end, for the whole-view scan. + +Run -- the ordering matters, see the 收尾验收顺序 in script/reinterhand_v1_1/README.md: + + python shared-v1.1/script/reinterhand_v1_1/render.py \ + --mano-runtime ../../tmp/runtime-v1.0 +""" + +from __future__ import annotations + +import argparse +import base64 +import collections +import html +import io +import json +import multiprocessing +import os +import random +import subprocess +import sys +import time +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +#: set before the sibling imports below, not inside main(): the first ``import +#: reinterhand_common`` is what would write a __pycache__ into the release tree, and it +#: happens while this module body runs. The release must ship no bytecode cache, so the +#: switch has to be flipped before that line -- and inherited by the decoder children, +#: which re-import this module (os.environ, set in main, covers those) +sys.dont_write_bytecode = True + +import numpy as np +import torch +from PIL import Image, ImageDraw + +from reinterhand_common import ( + DATASET_ROOT, + DEFAULT_MEDIA_DECLARATION, + FRAMES_REF, + RENDER_CELLS, + MediaDeclaration, + check_view, + load, + save, +) +from warehouse import BundleReader, Registry + +import mano_review + +DECODE_SCOPE = ("ffmpeg demux over the preserved MKV; the sampled RGB frames are decoded " + "with select=, and the mask is streamed once from end to end for the " + "whole-view scan. Every frame's byte count is checked") +REPORT_SCOPE = ("v1.1 registry, keys, shapes, validity and timeline, plus the projection " + "of the bundled MANO parameters onto the preserved mask; not a media pixel " + "comparison of the released values themselves") +PROJECTION_SCOPE = ("bundled MANO parameters expanded to a camera-frame mesh and projected " + "through the view's own declared camera model (pinhole for exo, " + "opencv_fisheye4 for ego, both asserted by check_view before this runs), " + "then compared with the preserved mask's foreground. The mask has no " + "per-hand identity, so this measures coverage of both hands together, " + "not a per-hand match") + +#: ReInterHand's own published vocabulary, read off +#: ``shared-v1.0/script/preprocess_reinterhand.py`` (``draw_mano_meshes``) and the v1.0 +#: review pages: 青色=左手, 橙色=右手. RHD's red/blue is a different release's convention +#: and is deliberately not used. +HAND_COLORS = {"left": (0, 255, 255), "right": (255, 140, 0)} +#: the mask tint, likewise from ``draw_foreground_intensity``: magenta at 0.72 of the +#: intensity, capped so a saturated pixel does not hide the hand underneath +MASK_TINT = (255, 0, 200) +MASK_TINT_ALPHA = 0.72 +MASK_TINT_CAP = 190 +#: the preview box. Exo frames are 667 wide by 1024 tall and ego ones 1024x1024, so the +#: box is portrait-shaped; a preview is scaled down and never up +PREVIEW_BOX = (460, 700) +PREVIEW_QUALITY = 88 +#: the most sampled frames one page carries. A hard limit, met exactly by +#: ``select_frames``: the ends, the validity boundary cases and the caller's extra frames are +#: never dropped, and the quarter points fill whatever is left +FRAMES_CAP = 6 +#: the ``camera/frames.jsonl`` fields the captions print: a subset of the release's +#: ``FRAME_FIELDS``, chosen for what a reviewer needs to identify a frame +DISPLAY_FRAME_FIELDS = ("frame_index", "sample_id", "source_frame_id", "sync_id", + "timestamp_ns", "clock_domain") + + +# -- decoding --------------------------------------------------------------- + + +def _ffmpeg_threads() -> str: + return os.environ.get("HAND_WAREHOUSE_FFMPEG_THREADS", "1") + + +def decode(path: Path, indices, pix_fmt: str, dtype, width: int, height: int, + channels: int): + """Decode exactly the requested frames of a preserved video, keyed by frame index. + + Same recipe as the published renderers (``HAND_WAREHOUSE_FFMPEG_THREADS``, one decoder + thread by default), with ``select=`` so a 200-frame stream is not read end to end for a + handful of stills. The byte count is checked rather than trusted: a short read would + silently misalign every frame after it, and ``-vsync 0`` plus an explicit ``-frames:v`` + is what makes ``select=`` yield exactly ``len(indices)`` frames. + """ + order = sorted(indices) + select = "+".join(f"eq(n\\,{index})" for index in order) + threads = _ffmpeg_threads() + argv = ["ffmpeg", "-v", "error", "-nostdin", "-filter_threads", threads, + "-threads", threads, "-noautorotate", "-i", str(path), "-map", "0:v:0", + "-vf", f"select={select}", "-vsync", "0", "-frames:v", str(len(order)), + "-threads", threads, "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"] + raw = subprocess.run(argv, capture_output=True, check=True).stdout + #: rawvideo is bytes, so the count is elements times the itemsize -- a 16-bit mask + #: yields two bytes per pixel, and getting that wrong would silently reshape the stream + #: instead of failing + expected = len(order) * height * width * channels * np.dtype(dtype).itemsize + if len(raw) != expected: + raise ValueError(f"{path}: decoded {len(raw)} bytes, expected {expected}") + frames = np.frombuffer(raw, dtype=dtype).reshape(len(order), height, width, channels) + return {index: frames[position].copy() for position, index in enumerate(order)} + + +def stream(path: Path, pix_fmt: str, dtype, width: int, height: int, channels: int): + """Yield every frame of a preserved video in order, one at a time. + + The whole-view scan needs each mask frame once and nothing twice, so the decoder is read + as a pipe rather than collected into one array: a 667x1024 gray16le frame is 1.4 MB, and + all of a view's frames at once would be the largest thing this tool holds. + """ + threads = _ffmpeg_threads() + argv = ["ffmpeg", "-v", "error", "-nostdin", "-threads", threads, "-noautorotate", + "-i", str(path), "-map", "0:v:0", "-vsync", "0", "-threads", threads, + "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"] + frame_bytes = width * height * channels * np.dtype(dtype).itemsize + process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + while True: + block = process.stdout.read(frame_bytes) + if not block: + break + if len(block) != frame_bytes: + raise ValueError(f"{path}: short frame, {len(block)} of {frame_bytes} bytes") + yield np.frombuffer(block, dtype=dtype).reshape(height, width, channels) + finally: + process.stdout.close() + error = process.stderr.read().decode("utf-8", "replace").strip() + process.stderr.close() + if process.wait() != 0: + raise ValueError(f"{path}: ffmpeg failed: {error}") + + +def probe(path: Path): + """Demux-only facts about a media file: packet count, shape, codec.""" + out = subprocess.run( + ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", + "-show_entries", "stream=width,height,codec_name,pix_fmt,nb_read_packets", + "-of", "json", str(path)], + capture_output=True, text=True, check=True).stdout + facts = (json.loads(out).get("streams") or [{}])[0] + return {"frames": int(facts["nb_read_packets"]), "width": facts.get("width"), + "height": facts.get("height"), "codec": facts.get("codec_name"), + "pix_fmt": facts.get("pix_fmt")} + + +# -- previews --------------------------------------------------------------- + + +def picture(image: Image.Image) -> str: + """A preview as a JPEG data URI. The released tensors and videos are never resized. + + The preview *is* lossy, and every page says so: a 667x1024 PNG of a real photograph is + around 600 KB and a page carries four panels per sampled frame, so the page set would be + an order of magnitude larger than the evidence it carries. The decoded frame is full + size until this last step, and every measurement on the page is taken before it. + """ + preview = image.copy() + preview.thumbnail(PREVIEW_BOX) + output = io.BytesIO() + preview.save(output, format="JPEG", quality=PREVIEW_QUALITY) + return ('') + + +def label_panel(image: Image.Image, text: str) -> Image.Image: + """The v1.0 renderer's in-frame panel label, so the two page sets look alike.""" + result = image.copy() + painter = ImageDraw.Draw(result) + painter.rectangle((0, 0, min(result.width, 460), 26), fill=(0, 0, 0)) + painter.text((8, 6), text, fill=(255, 255, 255)) + return result + + +def mask_intensity_panel(mask: np.ndarray, shift: int) -> Image.Image: + """The preserved mask's own values, shown as intensity rather than hidden in RGB. + + ``segment/foreground_intensity/v1`` is a *non-binary* foreground intensity in 0..255 + with no per-hand identity, so it is drawn as grayscale with a scale bar and its frame + minimum and maximum. The container is ``gray16le``: decoding it as 8-bit ``gray`` would + make ffmpeg rescale 0..65535 down to 0..255 and collapse the native range to almost + black, so the stored words are read verbatim. ``shift`` is 0 for the declared range; a + frame holding a value above 255 -- possible, since the container is wider than the + declaration -- is drawn shifted down by 8 bits and the caption says so, never clamped + silently, which would draw a wrong picture. + """ + image = Image.fromarray((mask >> shift).astype(np.uint8), "L").convert("RGB") + painter = ImageDraw.Draw(image) + width, height = image.size + bar_width = min(280, max(120, width // 2)) + x0, y0 = 12, max(40, height - 40) + ramp = np.tile(np.arange(256, dtype=np.uint8), (14, 1)) + image.paste(Image.fromarray(ramp, "L").convert("RGB"), (x0, y0)) + painter.rectangle((x0 - 1, y0 - 1, x0 + bar_width, y0 + 14), outline=(255, 70, 70), + width=2) + painter.text((x0, max(2, y0 - 16)), "intensity 0 -> 255" + (" (>>8)" if shift else ""), + fill=(255, 70, 70)) + painter.text((x0, min(height - 10, y0 + 17)), + f"stored min={int(mask.min())} max={int(mask.max())}", fill=(255, 70, 70)) + return image + + +def mask_overlay(image: np.ndarray, mask: np.ndarray, shift: int) -> Image.Image: + """The v1.0 renderer's magenta foreground tint, so alignment can be judged by eye.""" + tint = Image.new("RGBA", (mask.shape[1], mask.shape[0]), (*MASK_TINT, 0)) + tint.putalpha(Image.fromarray((mask >> shift).astype(np.uint8), "L").point( + lambda value: min(MASK_TINT_CAP, int(value * MASK_TINT_ALPHA)))) + return Image.alpha_composite(Image.fromarray(image).convert("RGBA"), tint).convert("RGB") + + +def mano_overlay(image: np.ndarray, pixels_by_side: dict, faces, width: int, + height: int) -> tuple: + """The MANO mesh drawn the way the v1.0 pages drew it: translucent fill, solid edge. + + Returns the image and how many triangles each hand contributed, so a caption can say + whether a hand was drawn at all rather than leaving an empty panel unexplained. A side + whose slot is invalid arrives as ``None`` and contributes nothing. + """ + base = Image.fromarray(image).convert("RGBA") + overlay = Image.new("RGBA", base.size, (0, 0, 0, 0)) + painter = ImageDraw.Draw(overlay, "RGBA") + counts = {} + for side in ("left", "right"): + pixels = pixels_by_side.get(side) + polygons = (list(mano_review.drawable_faces(faces, pixels, width, height, np)) + if pixels is not None else []) + counts[side] = None if pixels is None else len(polygons) + colour = HAND_COLORS[side] + for polygon in polygons: + painter.polygon(polygon, fill=(*colour, 28)) + painter.line(polygon + [polygon[0]], fill=(*colour, 220), width=2) + return Image.alpha_composite(base, overlay).convert("RGB"), counts + + +# -- reading one view ------------------------------------------------------- + + +def numeric_records(meta: dict, reader, view: Path) -> dict: + """One JSON-safe record per series the view carries, read through the released reader. + + Two shapes of series live here and the report has to keep them apart: + + * a **bundled** field (``data_key`` present) lives in a bundle file beside its ``valid`` + and is read with ``reader.field`` -- intrinsic, extrinsic, distortion, mano. The + migration owns these. + * a **preserved** media component (``rgb``, ``segment``) keeps v1.0's layout: the payload + is the MKV and the validity is a standalone ``*_valid.pt`` sibling, read with the same + ``torch.load(..., weights_only=True)`` ``check_view`` uses. The migration leaves both + alone. + + ``check_view`` has already asserted every one of these; the records restate them for the + report so the page and the checker cannot disagree. The arrays themselves are not kept + here -- they would make the record un-serialisable -- and ``validity_arrays`` reads the + same series again for the per-frame panels. + """ + records = {} + for name, component in meta["components"].items(): + if not component.get("available", True): + continue + if "data_key" in component: + data, valid = reader.field(view, component) + records[name] = { + "kind": "bundled", "file": component["data_ref"], + "data_key": component["data_key"], "valid_key": component["valid_key"], + "shape": list(data.shape), "dtype": str(data.dtype), + "valid_true": int(valid.sum()), "valid_total": int(valid.numel()), + "nan_count": (int(torch.isnan(data).sum()) + if data.is_floating_point() else None), + } + elif component["data_ref"].endswith(".mkv"): + valid = standalone_validity(view, component) + records[name] = { + "kind": "preserved_media", "file": component["data_ref"], + "valid_file": component["valid_ref"], + "shape": None, "dtype": None, "valid_shape": list(valid.shape), + "valid_dtype": str(valid.dtype), "valid_true": int(valid.sum()), + "valid_total": int(valid.numel()), "nan_count": None, + } + else: + continue + counts = valid_counts(valid if "data_key" not in component + else reader.field(view, component)[1]) + records[name]["valid_true_per_series"] = counts + return records + + +def standalone_validity(view: Path, component: dict): + """A preserved media component's standalone ``*_valid.pt``, exactly as check_view reads it.""" + return torch.load(view / component["valid_ref"], map_location="cpu", weights_only=True) + + +def valid_counts(valid) -> list: + """``valid`` true-counts split along its last axis when that axis is a small series axis. + + ReInterHand's ``mano`` validity is ``[T, 2]`` -- one flag per hand -- and the pages report + the two hands separately, which is why the split is worth carrying. ``[T]`` series get a + single count. The threshold mirrors the release's own two ``hand_slots``. + """ + if valid.dim() > 1 and valid.shape[-1] <= 4: + return [int(valid[..., slot].sum()) for slot in range(valid.shape[-1])] + return [int(valid.sum())] + + +def select_frames(n: int, valids, extra=(), cap: int = FRAMES_CAP) -> list: + """Sampling driven by the release's own validity, so a page shows its boundary cases. + + Both ends, the first frame each series is valid and the first it is not (an invalid row + is exactly what a reviewer wants to see once, and on these sample sequences it is the + majority of one ego view's frames), and whatever the caller has already decided is worth + seeing -- this renderer passes the frame whose MANO geometry the mask covers least, found + by the whole-view scan. Quarter points fill the rest, so a temporal view shows its span. + + Priority is strict, and the cap is therefore exact rather than a target: the ends and the + boundary cases are claims about the release and are never dropped, ``extra`` is the + caller's explicit choice, and only the quarter points are expendable. A view whose + validity is busy can legitimately fill the whole budget with boundary cases, in which + case the page shows no quarter point at all -- which is the right trade, because the + quarter point is the one pick that carries no information the caption does not. + """ + keep = {0, n - 1} | {int(index) for index in extra} + optional = {n // 4, n // 2, 3 * n // 4} - keep + for valid in valids: + if valid is None: + continue + flags = np.asarray(valid, dtype=bool).reshape(n, -1).any(axis=1) + for present in (np.flatnonzero(flags), np.flatnonzero(~flags)): + if len(present): + keep.add(int(present[0])) + room = max(0, cap - len(keep)) + return sorted(keep | set(sorted(optional)[:room])) + + +def declared_cell(meta: dict) -> dict: + """Which of the release's four render cells this view is in, and what follows from it. + + Taken from :data:`RENDER_CELLS` rather than re-derived, so the caption and the checkers + cannot disagree about, say, whether the stored frames are a temporal sequence. A view + outside the four measured cells is reported as such rather than guessed about. + """ + policy = meta["source_rendering"].get("background_policy") + cell = RENDER_CELLS.get((meta["view_type"], policy)) + if cell is None: + return {"view_type": meta["view_type"], "background_policy": policy, "known": False} + return {"view_type": meta["view_type"], "background_policy": policy, "known": True, + "temporal_relationship": cell["temporal_relationship"], + "sample_type": cell["sample_type"], "sampling": cell["sampling"], + "covers_span": cell["covers_span"], + "modal_source_steps": list(cell["modal_steps"]), + "source_fps": cell["source_fps"], + "sequence_id_role": cell["sequence_id_role"]} + + +def frame_rows_of(view: Path) -> dict: + """``camera/frames.jsonl`` as ``frame_index -> row``, the join the captions display.""" + rows = [json.loads(line) for line in + (view / FRAMES_REF).read_text(encoding="utf-8").splitlines() if line.strip()] + return {int(row["frame_index"]): {key: row.get(key) for key in DISPLAY_FRAME_FIELDS} + for row in rows} + + +def project(index: int, geometry, intrinsic, distortion, width: int, height: int, + cv2) -> dict: + """One series' geometry at one frame, projected and classified against the picture. + + The single projection implementation, shared by the whole-view scan and the per-frame + panels, so the number the header quotes and the polygon the panel draws cannot come from + two different formulas. Returns every point's pixel (NaN where the point is not in front + of the camera), the in-front mask, which points are inside the picture, and those points + as integer rows/columns for indexing the mask. + + ``distortion`` is the view's whole ``[T, 4]`` stack (or ``None`` for a pinhole view); this + is where the frame's own row is selected, so no caller can pass the stack by mistake -- + OpenCV asserts on exactly four coefficients and would otherwise fail deep inside the + fisheye call with an argument-shape message that says nothing about the frame index. + """ + frame_distortion = None if distortion is None else distortion[index] + pixels, front = mano_review.project_vertices(geometry[index], intrinsic[index], + frame_distortion, np, cv2) + finite = front & np.isfinite(pixels).all(axis=-1) + inside = (finite & (pixels[:, 0] >= 0) & (pixels[:, 0] < width) + & (pixels[:, 1] >= 0) & (pixels[:, 1] < height)) + return {"pixels": pixels, "front": front, "inside": inside, + "points": np.clip(pixels[inside], 0, None).astype(np.int64)} + + +def mano_mask_scan(meta: dict, mask_path: Path, mask_valid, mano_valid, geometry, + intrinsic, distortion, cv2) -> dict: + """Project the MANO mesh of *every* frame and count how much lands on the foreground. + + This is the measurement the v1.0 pages could not make: there the parameters and the mask + were separate files and nothing tied them together. It is deliberately a *coverage* count + and not an assertion -- the mask carries no per-hand identity, so it cannot say which hand + a pixel belongs to, and a systematic offset would be a finding about the source rather than + a reason to change the page. Frames the release marks invalid for either series, and + frames whose mask is entirely zero (a ratio with a zero denominator is not a number), are + excluded from the ratios and counted separately. + """ + n = meta["num_frames"] + width, height = meta["camera"]["image_size"] + per_side = {side: {"frames_used": 0, "joints_projected": 0, "joints_in_frame": 0, + "joints_on_foreground": 0, "vertices_in_frame": 0, + "vertices_on_foreground": 0, "frames_with_joints_in_frame": 0} + for side in ("left", "right")} + observed_min, observed_max = None, None + frames_scanned = frames_mask_empty = valid_frames_skipped_empty = 0 + coverage, worst = [], None + for index, frame in enumerate(stream(mask_path, "gray16le", np.uint16, width, height, 1)): + if index >= n: + break + frames_scanned += 1 + mask = frame[..., 0] + low, high = int(mask.min()), int(mask.max()) + observed_min = low if observed_min is None else min(observed_min, low) + observed_max = high if observed_max is None else max(observed_max, high) + if high == 0: + frames_mask_empty += 1 + if bool(mask_valid[index]): + valid_frames_skipped_empty += 1 + continue + foreground = mask > 0 + total_in_frame = total_on = 0 + for slot, side in enumerate(("left", "right")): + if not bool(mano_valid[index, slot]): + continue + data = per_side[side] + data["frames_used"] += 1 + vertices = project(index, geometry[side][0], intrinsic, distortion, width, + height, cv2) + rows = vertices["points"] + on = int(foreground[rows[:, 1], rows[:, 0]].sum()) if len(rows) else 0 + data["vertices_in_frame"] += int(vertices["inside"].sum()) + data["vertices_on_foreground"] += on + total_in_frame += int(vertices["inside"].sum()) + total_on += on + joints = project(index, geometry[side][1], intrinsic, distortion, width, + height, cv2) + data["joints_projected"] += int(joints["front"].sum()) + data["joints_in_frame"] += int(joints["inside"].sum()) + if joints["inside"].any(): + data["frames_with_joints_in_frame"] += 1 + joint_rows = joints["points"] + data["joints_on_foreground"] += (int(foreground[joint_rows[:, 1], + joint_rows[:, 0]].sum()) + if len(joint_rows) else 0) + #: a frame the release marks invalid is counted but kept out of the ratios, so a + #: deliberately-flagged row cannot move the headline number + if bool(mask_valid[index]) and total_in_frame: + share = total_on / total_in_frame + coverage.append(share) + if worst is None or share < worst[1]: + worst = (index, share) + return { + "frames_scanned": frames_scanned, + "frames_the_mask_is_empty_on": frames_mask_empty, + "valid_frames_excluded_because_the_mask_is_empty": valid_frames_skipped_empty, + "observed_value_range": {"min": observed_min, "max": observed_max}, + "frames_used_for_coverage": len(coverage), + "in_frame_vertices_median_on_foreground": ( + round(float(np.median(coverage)), 6) if coverage else None), + "in_frame_vertices_min_on_foreground": (round(worst[1], 6) if worst else None), + "least_covered_frame": (worst[0] if worst else None), + "per_hand": per_side, + "note": "the mask is a left+right union with no per-hand identity, so the per-hand " + "counts describe the geometry each hand contributes, not a per-hand " + "agreement; frames the release marks invalid, and frames whose mask is " + "entirely zero, are excluded from the ratios and counted separately", + } + + +_CV2 = None +_RUNTIME: dict = {} + + +def _cv2(): + """``cv2`` imported on demand: only the fisheye projection needs it.""" + global _CV2 + if _CV2 is None: + import cv2 + _CV2 = cv2 + return _CV2 + + +def mano_runtime(path): + """One loaded MANO pair per process, however many views that process renders.""" + if "mano" not in _RUNTIME: + _RUNTIME["mano"] = mano_review.ManoRuntime(Path(path), np, torch) + return _RUNTIME["mano"] + + +# -- the page --------------------------------------------------------------- + + +def view_report(view: Path, meta: dict, records: dict, consumed: set, selected: list, + media: list, scan, gaps) -> dict: + """The published report shape, composed from the released checker's evidence.""" + bundles = sorted({component["data_ref"] for component in meta["components"].values() + if "data_key" in component}) + return { + "view": f"{view.parent.name}/{view.name}", + "sequence_id": meta["sequence_id"], + "camera_id": meta["camera_id"], + "view_type": meta["view_type"], + #: declared under source_rendering, and read_sequence.py asserts it against the + #: release's own CAMERA_FAMILY_BY_VIEW_TYPE, so this is the released value, not a + #: second derivation of it + "camera_family": meta["source_rendering"].get("camera_family"), + "split": meta["split"], + "num_frames": meta["num_frames"], + "camera": {"model": meta["camera"]["model"], + "schema_id": meta["camera"]["schema_id"], + "image_size": meta["camera"]["image_size"]}, + "render_cell": declared_cell(meta), + "series": records, + "bundle_files": bundles, + "media": media, + "mano_on_mask": scan, + "consumed_files": sorted(consumed), + "declared_media_schema_gaps_counted_here": dict(gaps), + "selected_frames": selected, + "decode_scope": DECODE_SCOPE, + "projection": {"model": meta["camera"]["model"], "scope": PROJECTION_SCOPE}, + "scope": REPORT_SCOPE, + } + + +def colour_legend() -> str: + """The colour vocabulary and what is deliberately not drawn, in one place.""" + def swatch(colour, label: str) -> str: + css = "rgb(" + ",".join(str(int(component)) for component in colour) + ")" + return ('    ' + html.escape(label)) + + return ('

配色沿用 ReInterHand v1.0 复核页自己的约定(' + "draw_mano_meshes:青左手、橙右手;前景用洋红叠加),便于与 " + "shared-v1.0/doc/validation/full_random/ 的页面并排读。" + "注意这不是 RHD 的红/蓝——照抄 RHD 会让复核者把左右手读反:" + + " · ".join([swatch(HAND_COLORS["left"], "左手(MANO 网格)"), + swatch(HAND_COLORS["right"], "右手(MANO 网格)"), + swatch(MASK_TINT, "前景强度叠加(洋红,α=0.72×强度)")]) + + "
mask 是 segment/foreground_intensity/v1:非二值前景" + "强度 0–255、左右手并集、无左右手身份,所以它按灰度强度显示并带刻度" + "条,而不是当成二值或按手着色。页面不画物体、不画接触、不画深度:这个 " + "release 没有这三类内容。

") + + +def scan_note(scan, mano_record) -> str: + """The header's account of the MANO-on-mask scan, with its own measured numbers.""" + median = scan["in_frame_vertices_median_on_foreground"] + sides = scan["per_hand"] + return ('

全视图扫描(不止抽样帧:本视图 ' + + str(scan["frames_scanned"]) + " 帧全部参与,mask 从头到尾流式解一遍):把每个" + "有效帧的 MANO 网格按其自身参数展开、经该视图声明的相机模型投到像素上,再看它" + "落在 mask 前景里的比例。取左右手都在画内的顶点合计,中位覆盖 " + + (f"{median:g}" if median is not None else "—(无可用帧)") + + ("(覆盖最低的一帧是 " + str(scan["least_covered_frame"]) + "," + + f"{scan['in_frame_vertices_min_on_foreground']:g})" + if scan["least_covered_frame"] is not None else "") + + ";进入比值的帧 " + str(scan["frames_used_for_coverage"]) + "。逐手:" + + "|".join(f"{side} 有效 {sides[side]['frames_used']} 帧、画内顶点 " + f"{sides[side]['vertices_in_frame']}、落在前景 " + f"{sides[side]['vertices_on_foreground']}、关节画内 " + f"{sides[side]['joints_in_frame']}" + for side in ("left", "right")) + + "。mask 全零的帧 " + str(scan["frames_the_mask_is_empty_on"]) + " 个" + + ("(其中 " + str(scan["valid_frames_excluded_because_the_mask_is_empty"]) + + " 个本身是有效帧,因分母为零而不进比值)" + if scan["valid_frames_excluded_because_the_mask_is_empty"] else "") + + "。实测值域 " + str(scan["observed_value_range"]["min"]) + "–" + + str(scan["observed_value_range"]["max"]) + "(声明 " + + str(scan.get("declared_value_range")) + ")。MANO 模型来自树外 runtime " + + html.escape(str(mano_record["runtime"])) + "(smplx " + + html.escape(str(mano_record.get("smplx"))) + ")。这个数只被记录,不被断言、" + "也不用来「修正」任何发布值:mask 没有左右手身份,所以它衡量的是「参数展开" + "出的几何是否落在前景上」这一件事,系统性偏移会是关于源的发现,而不是页面的" + "缺陷。

") + + +def render_one(view: Path, destination: Path, root: Path, declaration_path, + runtime_path) -> dict: + registry = Registry.load(root / "doc/schema.json") + meta = load(view / "metainfo.json") + n = meta["num_frames"] + width, height = meta["camera"]["image_size"] + components = meta["components"] + declaration = MediaDeclaration.load(declaration_path) + identity = {"view": f"{view.parent.name}/{view.name}", + "sequence_id": meta["sequence_id"], "camera_id": meta["camera_id"], + "view_type": meta["view_type"], "split": meta["split"], "num_frames": n} + + #: media first: this working copy ships the numeric layer for all 6,750 views and the + #: media of two sample sequences, so "not renderable" is the normal answer for most views + #: and has to be a named outcome rather than a crash + media_names = [name for name, component in components.items() + if str(component.get("data_ref", "")).endswith(".mkv")] + states = {name: declaration.state(view, meta["sequence_id"], + components[name]["data_ref"]) + for name in media_names} + blocked = {name: state for name, state in states.items() if state != "present"} + if blocked: + return dict(identity, rendered=False, media_states=states, + reason="this copy of the tree does not ship the media for this sequence " + "(" + ", ".join(sorted(set(blocked.values()))) + + "), so no frame can be decoded", + scope=REPORT_SCOPE) + + reader = BundleReader() + gaps = collections.Counter() + consumed = check_view(view, meta, registry, reader, media=declaration, gaps=gaps) + records = numeric_records(meta, reader, view) + + bundled = {name: reader.field(view, component) + for name, component in components.items() + if component.get("available", True) and "data_key" in component} + validity = {name: values[1].numpy() for name, values in bundled.items()} + intrinsic = bundled["intrinsic"][0].numpy().astype(np.float64) + motion = bundled["mano"][0].numpy().astype(np.float64) + mano_valid = bundled["mano"][1].numpy().astype(bool) + distortion = (bundled["distortion"][0].numpy().astype(np.float64) + if "distortion" in bundled else None) + #: check_view has already asserted the split; re-asserting it here is what keeps a fisheye + #: view from being projected with the pinhole formula by accident + assert (distortion is None) == (meta["camera"]["model"] == "pinhole"), ( + meta["camera"]["model"], distortion is not None) + rgb_valid = standalone_validity(view, components["rgb"]).numpy().astype(bool) + mask_valid = standalone_validity(view, components["segment"]).numpy().astype(bool) + validity["rgb"], validity["segment"] = rgb_valid, mask_valid + + media = [] + for name in media_names: + reference = view / components[name]["data_ref"] + entry = {"component": name, "ref": components[name]["data_ref"], "state": "present", + "bytes": reference.stat().st_size, + "valid_ref": components[name].get("valid_ref")} + entry.update(probe(reference)) + media.append(entry) + for entry in media: + assert entry["frames"] == n, (entry, n) + #: CONTRACT: camera.image_size is [W, H], and read_sequence.py checks it the same way + assert [entry["width"], entry["height"]] == [width, height], (entry, [width, height]) + + mano = mano_runtime(runtime_path) if runtime_path is not None else None + geometry, scan = None, None + if mano is not None: + geometry = {side: mano.geometry(side, motion) for side in ("left", "right")} + scan = mano_mask_scan(meta, view / components["segment"]["data_ref"], mask_valid, + mano_valid, geometry, intrinsic, distortion, _cv2()) + segment = components["segment"] + scan["declared_value_range"] = segment.get("value_range") + scan["declared_normalization_scale"] = segment.get("normalization_scale") + scan["foreground_category"] = segment.get("foreground_category") + scan["identity_semantics"] = segment.get("identity_semantics") + + rows = frame_rows_of(view) + selected = select_frames( + n, [mano_valid, rgb_valid, mask_valid], + extra=([scan["least_covered_frame"]] + if scan and scan["least_covered_frame"] is not None else [])) + rgb = decode(view / components["rgb"]["data_ref"], selected, "rgb24", np.uint8, + width, height, 3) + #: every mask frame the page shows, in one decoder call rather than one per frame + masks = {index: frame[..., 0] for index, frame in + decode(view / components["segment"]["data_ref"], selected, "gray16le", + np.uint16, width, height, 1).items()} + + panels_by_frame, details_by_frame = {}, {} + hands_not_drawn, hands_off_frame, mask_above_range = [], {}, [] + for index in selected: + panels = [] + image = rgb[index] + panels.append((f"原生 RGB(MKV 解出的第 {index} 帧,未重编码;预览为 JPEG 有损缩放)", + picture(label_panel( + Image.fromarray(image), + f"RGB | frame {index} | source " + f"{rows.get(index, {}).get('source_frame_id')}")))) + + #: ``pixels_by_side`` is the single source of truth for "was this hand drawn" -- a + #: side whose slot is invalid carries None, and everything downstream (the overlay, + #: the caption, the per-frame record) reads that rather than keeping its own tally + #: that can disagree + pixels_by_side, joints_by_side, drawn = {}, {}, {} + for slot, side in enumerate(("left", "right")): + if mano is None or not bool(mano_valid[index, slot]): + pixels_by_side[side] = None + joints_by_side[side] = None + hands_not_drawn.append({ + "frame_index": index, "side": side, + "why": "no MANO runtime" if mano is None + else "valid=false in the release"}) + continue + vertices = project(index, geometry[side][0], intrinsic, distortion, width, + height, _cv2()) + pixels_by_side[side] = vertices["pixels"] + joints = project(index, geometry[side][1], intrinsic, distortion, width, + height, _cv2()) + joints_by_side[side] = joints + if not joints["inside"].any(): + hands_off_frame[side] = hands_off_frame.get(side, 0) + 1 + + if mano is None: + panels.append(("MANO 面板未绘制:未提供 --mano-runtime;MANO 权重按 " + "CONTRACT 5.2 不属于共享发布,参数仍记录在报告中", None)) + else: + overlay, drawn = mano_overlay(image, pixels_by_side, mano.faces, width, height) + caption = ("共享 MANO 网格(由 mano/axis_angle61/v1 参数展开的相机系" + "顶点,经本视图自己的 " + html.escape(meta["camera"]["model"]) + + " 投到像素;青=左手、橙=右手;可绘三角形数 左 " + + str(drawn["left"]) + " / 右 " + str(drawn["right"]) + ")") + for side in ("left", "right"): + if pixels_by_side[side] is None: + caption += (f";{side} 本帧 valid=false,未绘制(参数存在但发布标记为无效," + "不拿它当结果画)") + caption += "。网格按 v1.0 口径渲染:平移已在相机系,未再乘外参" + panels.append((caption, picture(overlay))) + + mask = masks[index] + shift = 8 if int(mask.max()) > 255 else 0 + if shift: + mask_above_range.append({"frame_index": index, "max": int(mask.max())}) + panels.append((f"原生非二值 mask 强度(gray16le 原值,未二值化;本帧存储值 " + f"min={int(mask.min())} max={int(mask.max())}" + + (",超出声明值域,面板按 >>8 缩放显示)" if shift else ")"), + picture(mask_intensity_panel(mask, shift)))) + panels.append(("mask 叠加在 RGB 上(洋红=前景强度 ×0.72,上限 190,便于目视对齐;" + "这不是分类结果)", picture(mask_overlay(image, mask, shift)))) + + details = { + "frame_index": index, + "source": rows.get(index), + "validity_at_this_frame": { + #: a row of a ``[T, 2]`` series is two flags, not one, so the frame is + #: "valid" if any of its series is -- and the flags themselves are kept + name: ({"valid": bool(values[index].any()), + "per_series": [bool(flag) for flag in values[index]]} + if values.ndim > 1 and values.shape[-1] <= 4 + else {"valid": bool(values[index])}) + for name, values in validity.items()}, + "mano": {side: { + "valid": bool(mano_valid[index, slot]), + "triangles_drawn": drawn.get(side), + "joints_in_frame": (int(joints_by_side[side]["inside"].sum()) + if joints_by_side.get(side) else None), + "joints_on_foreground": ( + int((mask > 0)[joints_by_side[side]["points"][:, 1], + joints_by_side[side]["points"][:, 0]].sum()) + if joints_by_side.get(side) and len(joints_by_side[side]["points"]) + else None)} + for slot, side in enumerate(("left", "right"))}, + "mask": {"stored_min": int(mask.min()), "stored_max": int(mask.max()), + "panel_shift": shift, "nonzero_pixels": int((mask > 0).sum()), + "valid": bool(mask_valid[index])}, + } + panels_by_frame[index] = panels + details_by_frame[index] = details + + report = view_report(view, meta, records, consumed, selected, media, scan, gaps) + report.update(identity) + report["rendered"] = True + report["mano_runtime"] = mano.record if mano is not None else None + report["hands_not_drawn"] = hands_not_drawn + report["hands_geometry_entirely_off_frame"] = hands_off_frame + report["frames_with_a_mask_value_above_the_declared_range"] = mask_above_range + + title = f"{view.parent.name}_{view.name}" + sections = [] + for index in selected: + figures = [] + for caption, source in panels_by_frame.get(index) or []: + figures.append("
" + (source or "") + "
" + caption + + "
") + sections.append( + f"

帧 {index} / {n}

" + + '
' + "".join(figures) + "
" + + "
帧号、来源与各序列在本帧的有效性
"
+            + html.escape(json.dumps(details_by_frame[index], ensure_ascii=False, indent=2))
+            + "
") + + cell = declared_cell(meta) + temporal = ("真实时序视频序列:每帧之间的时间关系本身是发布内容(可作跟踪/时序监督)" + if cell.get("temporal_relationship") else + "独立图片集合:MKV 只是无损批容器,播放顺序不是时间,不得当作运动、" + "跟踪、速度或时序监督使用") + css = ("body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;" + "background:#f5f7fa;color:#18232f;line-height:1.5}" + "section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}" + "figure{margin:.5rem}figcaption{font-size:.85rem;max-width:460px}" + ".panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}" + "pre{white-space:pre-wrap;overflow:auto;font-size:12px}" + ".note{background:#fff7e6;border-left:3px solid #e0a800;padding:.6rem;" + "font-size:.9rem;max-width:1000px}" + ".legend{background:#eef3fa;border-left:3px solid #4a76a8;padding:.6rem;" + "font-size:.9rem;max-width:1000px}.swatch{border:1px solid #b9c3d0}") + header = ("

" + html.escape(title) + "

" + "

直接读取 v1.1 bundle(" + html.escape(meta["sequence_id"]) + + " 的 " + html.escape(meta["camera_id"]) + " 视图," + + html.escape(meta["view_type"]) + " / " + + html.escape(str(cell.get("background_policy"))) + ",split=" + + html.escape(meta["split"]) + ",共 " + str(n) + " 帧)。" + temporal + + "。预览仅供人工复核,不是训练输入(CONTRACT §6.5);本次只解码抽样的 " + + str(len(selected)) + " 帧 RGB,mask 则整段解过一遍。

") + header += colour_legend() + header += (scan_note(scan, mano.record) if scan is not None else + '

本次未提供 --mano-runtime,所以没有做 ' + 'MANO→mask 的投影扫描,MANO 面板也未绘制。这不是数据缺失:MANO 权重按 ' + 'CONTRACT 5.2 不属于共享发布,参数本身仍逐帧记录在上面的报告里。

') + header += ('

MANO 参数 schema ' + + html.escape(str(components["mano"].get("schema_id"))) + + ":48 维 16 关节轴角 + 10 维 shape + 3 维全局平移(共 61),姿态" + "弧度、平移米、已在当前相机系(CONTRACT 5.2),所以本页不对平移再乘" + "外参。平移是「模型输出顶点所加的全局平移」,不是某个腕关节坐标," + "所以页面画的是展开后的网格而不是一个点。左右手各占 hand 轴" + "一个槽位,valid 逐帧逐手,本视图的有效帧数见上。

") + if hands_off_frame: + header += ('

抽样帧里有 ' + html.escape(str(hands_off_frame)) + + " 次出现整只手都投到画外。ReInterHand 的 per_frame 单元每帧独立换背景、" + "相机也逐图随机,这属正常形态;此处只记录,不改判据。

") + if scan and scan["frames_the_mask_is_empty_on"]: + header += ('

本视图有 ' + str(scan["frames_the_mask_is_empty_on"]) + + " 帧 mask 前景全为 0。这些帧不进覆盖比值(分母为零的比例没有意义)," + "但若被抽样仍会显示,以便复核者自己看一眼。

") + if mask_above_range: + header += ('

抽样帧中有 ' + str(len(mask_above_range)) + + " 帧的 mask 存储值超过声明值域 [0,255](最高 " + + str(max(item["max"] for item in mask_above_range)) + + ")。容器是 gray16le,所以这可以表示;面板按 >>8 缩放显示并在图注" + "标明,未做静默截断。全视图实测值域见上。

") + page = ('' + + html.escape(title) + "" + header + + "".join(sections) + + "
全部组件元信息及原始来源
"
+            + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + "
" + + "
持久化复核结果(同 .report.json)
"
+            + html.escape(json.dumps(
+                {key: value for key, value in report.items() if not key.startswith("_")},
+                ensure_ascii=False, indent=2))
+            + "
") + + destination.mkdir(parents=True, exist_ok=True) + (destination / (title + ".html")).write_text(page, encoding="utf-8") + save(destination / (title + ".report.json"), + {key: value for key, value in report.items() if not key.startswith("_")}) + report["_page"] = title + ".html" + return report + + +def render_task(task): + for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", + "NUMEXPR_NUM_THREADS", "HAND_WAREHOUSE_FFMPEG_THREADS"): + os.environ[variable] = "1" + torch.set_num_threads(1) + view, destination, root, declaration, runtime = task + return render_one(Path(view), Path(destination), Path(root), + None if declaration is None else Path(declaration), + None if runtime is None else Path(runtime)) + + +# -- planning --------------------------------------------------------------- + + +def shard_facts(root: Path, sequence: str) -> dict: + """Split, frame count, view count and render policy of one sequence.""" + metas = [load(path) for path in + sorted((root / "data" / sequence).glob("*/metainfo.json"))] + if not metas: + raise SystemExit(f"{sequence}: no views found") + policies = {meta["source_rendering"].get("background_policy") for meta in metas} + types = {meta["view_type"] for meta in metas} + #: a complete sequence is exactly the two view types under one policy -- the same census + #: ``validate.py`` and ``read_sequence.py`` use, so a half-pulled sequence cannot be + #: rendered as if it were whole + if len(policies) != 1 or types != {"exo", "ego"}: + raise SystemExit(f"{sequence}: {sorted(types)} / {sorted(policies)} is not a complete " + f"sequence") + return {"sequence": sequence, "split": metas[0]["split"], "views": len(metas), + "num_frames": max(meta["num_frames"] for meta in metas), + "view_types": sorted(types), + "camera_ids": sorted(meta["camera_id"] for meta in metas), + "policy": sorted(policies)[0]} + + +def shippable(root: Path, declaration: MediaDeclaration) -> dict: + """Facts for the sequences whose declared media this copy of the tree actually ships.""" + facts = {} + for path in sorted((root / "data").iterdir()): + if path.is_dir() and declaration.ships(path.name): + facts[path.name] = shard_facts(root, path.name) + return facts + + +def plan_views(facts: dict, seed: int, per_policy: int) -> list: + """Stratified sample over the sequences that ship media, one stratum per render policy. + + ``background_policy`` is the only sequence-wide render value -- the camera family and + frame rate differ *between* a sequence's exo and ego views by design -- so a sequence, + not a view, is the sampling unit, and the strata are the policies rather than the four + (view type, policy) cells. Inside a stratum the sequences are drawn uniformly with the + seed, and every view of a drawn sequence is rendered, which is what the v1.0 pages did + ("展示抽中序列的全部相机和全部帧"). With the media declaration this working copy + carries, the pool is the two sample sequences, so the draw is the whole media read-through; + on a published tree, where every sequence ships its media, the same rule spreads the sample + over both policies. A draw with no candidate at all is refused rather than silently + returning nothing. + """ + rng = random.Random(seed) + strata = collections.defaultdict(list) + for sequence, fact in facts.items(): + strata[fact["policy"]].append(sequence) + drawn = [] + for policy in sorted(strata): + pool = sorted(strata[policy]) + drawn.extend(pool if len(pool) <= per_policy + else sorted(rng.sample(pool, per_policy))) + if not drawn: + raise SystemExit("no sequence ships its media, so nothing can be rendered") + return sorted(drawn) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[2], + help="the shared-v1.1 release root (default: this script's own)") + parser.add_argument("--out", type=Path, + help="where the pages go (default /doc/validation)") + parser.add_argument("--seed", type=int, default=20261015) + parser.add_argument("--per-policy", type=int, default=1, + help="sequences drawn per render policy; all their views are rendered") + parser.add_argument("--workers", type=int, default=4, + help="at most 8, one decoder thread each") + parser.add_argument("--views", nargs="+", + help="render these views (/) instead of sampling") + parser.add_argument("--media-declaration", type=Path, default=DEFAULT_MEDIA_DECLARATION, + help="which sequences' media this copy ships (default: the " + "tree-external declaration)") + parser.add_argument("--mano-runtime", type=Path, default=None, + help="directory with models/MANO_{LEFT,RIGHT}.pkl and a site/ holding " + "smplx; without it the MANO panel is not drawn (default: " + "/tmp/runtime-v1.0 when it exists)") + parser.add_argument("--report", type=Path, help="write the whole-run report here too") + args = parser.parse_args(argv) + if not 1 <= args.workers <= 8: + parser.error("at most 8 workers and one decoder thread each") + + root = args.root.resolve() + destination = (args.out or root / "doc/validation").resolve() + declaration = MediaDeclaration.load(args.media_declaration) + runtime = args.mano_runtime + if runtime is None: + candidate = DATASET_ROOT / "tmp" / "runtime-v1.0" + runtime = candidate if (candidate / "models").is_dir() else None + if runtime is not None and not (Path(runtime) / "models").is_dir(): + parser.error(f"--mano-runtime {runtime} has no models/ directory") + + release_sequences = sorted(path.name for path in (root / "data").iterdir() + if path.is_dir()) + if args.views: + views = [] + for token in args.views: + sequence, _, camera = token.partition("/") + view = root / "data" / sequence / camera + if not (view / "metainfo.json").is_file(): + parser.error(f"no such view: {token}") + views.append(view) + selected_sequences = sorted({view.parent.name for view in views}) + sampling = {"kind": "explicit", "views": args.views, + "rule": "explicit view list; no sampling applied"} + else: + facts = shippable(root, declaration) + selected_sequences = plan_views(facts, args.seed, args.per_policy) + views = [] + for sequence in selected_sequences: + views.extend(sorted(path.parent for path in + (root / "data" / sequence).glob("*/metainfo.json"))) + sampling = { + "seed": args.seed, + "rule": "sequences drawn uniformly inside each render policy, with the seed, from " + "the ones whose media this copy ships; every view of a drawn sequence is " + "rendered", + "per_policy": args.per_policy, + "sequences_in_release": len(release_sequences), + "sequences_shipping_media": len(facts), + "selections": [{"sequence": sequence, **facts[sequence]} + for sequence in selected_sequences], + } + + start = time.monotonic() + #: no .pyc may land in the release tree, and a spawn child re-imports this module before + #: any guard inside it runs -- so the switch has to be in the environment the children + #: inherit, not only in this interpreter + os.environ["PYTHONDONTWRITEBYTECODE"] = "1" + with ProcessPoolExecutor(max_workers=args.workers, + mp_context=multiprocessing.get_context("spawn")) as pool: + results = list(pool.map(render_task, + [(str(view), str(destination), str(root), + str(args.media_declaration), + None if runtime is None else str(runtime)) + for view in views])) + + rendered = [entry for entry in results if entry.get("rendered")] + skipped = [entry for entry in results if not entry.get("rendered")] + scanned = [entry["mano_on_mask"] for entry in rendered if entry["mano_on_mask"]] + medians = [scan["in_frame_vertices_median_on_foreground"] for scan in scanned + if scan["in_frame_vertices_median_on_foreground"] is not None] + report = { + "review_kind": "全量后抽样", + "dataset_id": "ReInterHand", + "release_id": "shared-v1.1", + "views_requested": len(views), + "views_rendered": len(rendered), + "views_not_renderable": len(skipped), + "sequences": len(selected_sequences), + "sampling": sampling, + "media_declaration": { + "path": str(args.media_declaration), "origin": declaration.origin, + "materialised": (sorted(declaration.materialised) + if isinstance(declaration.materialised, set) + else declaration.materialised)}, + "mano_runtime": (str(runtime) if runtime is not None else None), + "wall_seconds": round(time.monotonic() - start, 3), + "decode_scope": DECODE_SCOPE, + "mano_on_mask": { + "views_scanned": len(scanned), + "frames_scanned": sum(scan["frames_scanned"] for scan in scanned), + "frames_the_mask_is_empty_on": sum(scan["frames_the_mask_is_empty_on"] + for scan in scanned), + "frames_used_for_coverage": sum(scan["frames_used_for_coverage"] + for scan in scanned), + "observed_value_range": { + "min": min((scan["observed_value_range"]["min"] for scan in scanned), + default=None), + "max": max((scan["observed_value_range"]["max"] for scan in scanned), + default=None)}, + "declared_value_ranges": sorted({tuple(scan["declared_value_range"]) + for scan in scanned + if scan.get("declared_value_range") + is not None}), + "in_frame_vertices_on_foreground": { + "views": len(medians), + "median_of_view_medians": (round(float(np.median(medians)), 6) + if medians else None), + "worst_view_median": min(medians) if medians else None, + "best_view_median": max(medians) if medians else None}, + "per_hand": {side: {key: sum(scan["per_hand"][side][key] for scan in scanned) + for key in ("frames_used", "joints_projected", + "joints_in_frame", "joints_on_foreground", + "vertices_in_frame", "vertices_on_foreground", + "frames_with_joints_in_frame")} + for side in ("left", "right")}, + "scope": PROJECTION_SCOPE}, + "reports": [{key: value for key, value in entry.items() if not key.startswith("_")} + for entry in results], + "scope": "post-full sampled views, read directly from v1.1 bundles and decoded from " + "the preserved media; evidence for human acceptance, not training input; " + "manual review pending", + } + if args.report: + save(args.report, report) + save(destination / "V1_1_VALIDATION.json", report) + + index_css = ("body{font:16px sans-serif;max-width:1300px;margin:auto;padding:1rem;" + "background:#f5f7fa;color:#18232f;line-height:1.5}" + ".legend{background:#eef3fa;border-left:3px solid #4a76a8;padding:.6rem;" + "font-size:.9rem;max-width:1000px}.swatch{border:1px solid #b9c3d0}" + "table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccd3de;" + "padding:4px 8px;text-align:left;font-size:.85rem}" + ".note{background:#fff7e6;border-left:3px solid #e0a800;padding:.6rem;" + "font-size:.9rem;max-width:1000px}") + rows = [] + for entry in sorted(rendered, key=lambda item: (item["sequence_id"], item["camera_id"])): + scan = entry["mano_on_mask"] + median = scan["in_frame_vertices_median_on_foreground"] if scan else None + hands = (entry["series"].get("mano") or {}).get("valid_true_per_series") + value_range = (f"{scan['observed_value_range']['min']}–" + f"{scan['observed_value_range']['max']}" if scan else "—") + rows.append("" + + html.escape(entry["view"]) + "" + + html.escape(entry["split"]) + "" + + html.escape(str(entry["render_cell"].get("background_policy"))) + + "" + html.escape(entry["view_type"]) + "" + + str(entry["num_frames"]) + "" + + str(len(entry["selected_frames"])) + "" + + ("/".join(str(count) for count in hands) + f" / {entry['num_frames']}" + if hands else "—") + + "" + + " / ".join(str(item["bytes"] // 1024) + " KiB" + for item in entry["media"]) + + "" + (f"{median:g}" if median is not None else "—") + + "" + value_range + "") + skipped_rows = "".join( + "
  • " + html.escape(entry["view"]) + " — " + html.escape(entry["reason"]) + "
  • " + for entry in skipped) + index = ('' + "ReInterHand shared-v1.1 review" + "

    ReInterHand shared-v1.1 全量后抽样人工复查

    " + "

    数值按字节一致(CONTRACT §6);媒体不重新编码。抽样规则与种子见 " + "V1_1_VALIDATION.json,本页所列视图即全部入选视图:" + str(len(rendered)) + + " 个视图 / " + str(len(selected_sequences)) + " 段序列。逐字段字节验收见 " + "verify.py,全树结构校验见 validate.py,含媒体的完整" + "读取见 read_sequence.py,证据留档在发布树外的 " + "tmp/reinterhand-tools/。

    " + colour_legend() + + "

    每页只解码该视图抽样的帧 RGB;但 MANO↔mask 覆盖扫描跑的是每个入选" + "视图的全部帧(mask 整段流式解一遍),全量结果见 V1_1_VALIDATION.json 的 " + "mano_on_mask。表里的覆盖中位是「左右手合计的画内顶点落在 mask " + "前景里的比例」的中位;mask 无左右手身份,故不分手断言。「MANO 有效帧」列是" + "左右手各自 valid=true 的帧数(分母为总帧数)——本发布里逐帧有效并非普遍成立," + "ego 视图尤其稀疏。

    " + + "" + "" + "" + + "".join(rows) + "
    视图split背景策略类型帧数本页抽样帧MANO 有效帧 左/右媒体(rgb / mask)前景覆盖中位mask 实测值域
    " + + ('

    未渲染的视图

    这些视图的媒体在本工作副本里按声明缺失,' + "因此无法解码;这是预期,不是失败。

      " + skipped_rows + "
    " + if skipped else "") + + '' + '
      ' + "".join( + '
    • ' + + html.escape(name) + "
    • " + for name in sorted(path.name for path in destination.glob("*.html") + if path.name != "index.html")) + + "
    ") + destination.mkdir(parents=True, exist_ok=True) + (destination / "index.html").write_text(index, encoding="utf-8") + print("RENDER_DONE", len(rendered), "rendered,", len(skipped), "not renderable,", + round(report["wall_seconds"], 2), "seconds ->", destination / "index.html", + flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/CONTRACT.md b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..c237e8d95df74f237ec4be1b0a3b0ac06a0ca935 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/CONTRACT.md @@ -0,0 +1,161 @@ +# 手物数据仓库统一约定 v1.1:张量合并存储 + +格式版本:`hand-warehouse/1.1`。张量存储约定:`pt/tensor_bundle/v1`。 + +状态:合同草案,2026-10-09。本版规定新的文件布局与读取方式,配套 [schema.json](schema.json) 注册表已更新;尚未迁移现有数据,也未适配生产转换器、读取器或可执行校验器。不能仅修改现有 metainfo 的版本号就宣称符合本版。 + +本版以 [v1.0 合同](../hand-warehouse-1.0/CONTRACT.md) 为语义基础:任务范围、两层序列/相机组织、数据类型、单位、坐标系、时间对齐、左右手顺序、官方划分、view_type、来源、可用监督规则、媒体无损编码和验收要求均保留。下文仅替代数值张量组件的独立 Tensor 文件、对应 `*_valid.pt` 及文件引用规定;这些旧文件名仅用于识别对应逻辑字段。媒体和 JSONL 组件的有效性文件及引用保持 v1.0,不纳入合并。未明确改变的语义继续执行 v1.0。 + +本版按用户约定作为 v1.0 的小版本存储修订,后续所有数据集逐步迁移到 v1.1。数值字段与 valid 语义不变,但 `.pt` 物理结构和引用方式改变,旧读取器不能未经适配直接读取新字典。各数据集在原 `shared-v1.0` 目录内逐步升级,完整验收后将目录更名为 `shared-v1.1`,不长期保留两套发布树。最终 `metainfo.schema_version=hand-warehouse/1.1`、`release_id=shared-v1.1`;尚未迁移的数据集仍使用原目录和版本。升级与发布流程见 [MIGRATION.md](MIGRATION.md)。实施前须按配套 v1.1 注册表完成读写/校验工具;不得将 v1.0 的 schema.json 改个版本号作为已完成适配的证明。正式发布时须提供完整合同与匹配注册表,不依赖本地草案目录中的相对链接。 + +## 1. 合并边界 + +1. 数值张量与对应有效性必须在同一个 `.pt` 文件、同一个字段字典内保存:`{"data": Tensor, "valid": BoolTensor}`。这些数值张量组件不再生成独立的 `*_valid.pt`;媒体和 JSONL 的有效性文件不受此规则影响。 +2. 按组件合并经常一起读取的小张量:相机内参、外参、畸变放在一个 `camera.pt`;MANO 参数与整手可见性放在一个 `mano.pt`;手关键点的二维、三维与可见性放在一个 `keypoints.pt`。 +3. 每个物体的数值字段及全部部件数值字段合并为一个 `object.pt`。不同物体、不同相机、不同序列不合成一个全局大文件,以保留按需下载和读取能力。 +4. RGB、深度、栅格 mask 继续使用原无损媒体格式,不把解码后的大数组或媒体字节塞进 `.pt`。它们的有效性文件保持原文件名、Tensor/媒体格式、形状和引用方式,不包装为字典。 +5. `metainfo.json`、`camera/frames.jsonl`、实例映射、物体身份/运动学定义与网格资产保留原格式。此次不把 JSON、JSONL、OBJ、纹理全部打进一个字典。 + +合并只改变存储方式,不改变采样、帧数、张量内容或有效性判定。不为减少字段数而将多个组件的 valid 合成一个公共 valid。 + +## 2. 目录 + +```text +/shared-v1.1/ + doc/ # 完整合同、匹配 schema、字段映射、验收报告 + script/ # 转换、读取和校验代码 + data/// + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt # 原独立 bool Tensor,保持不变 + depth.mkv + depth_valid.mkv # 逐像素有效性,保留压缩媒体格式 + camera/ + frames.jsonl + camera.pt # intrinsic、extrinsic、distortion + annotation/ + mano/mano.pt # motion、visibility + keypoints/keypoints.pt # uv、xyz、visibility、whole_hand_visibility + object// + metainfo.json + articulation.json # 仅关节/部件结构实际存在时 + object.pt # 位姿、可见性、几何点、关节、部件数值 + assets/ # 原网格、材质、纹理及依赖 + segment/ + mask.mkv # 或 polygons.jsonl,按所选表示 + instances.jsonl # 仅需要实例/区域编码映射时 + mask_valid.pt # 原帧级 bool Tensor,保持不变 + contact/ + relations.jsonl + relations_valid.pt # 原帧级 bool Tensor,保持不变 + __/ + contact.pt # vertex_region、vertex_distance +``` + +只创建实际提供的组件和字段。以上不是每个数据集必须填满的模板;缺失内参、MANO、深度等不能通过占位文件伪装为已提供。序列/相机的两层结构不变,物体与模态目录属于相机内部组件。 + +## 3. 字典结构与有效性 + +本次合并的数值组件 `.pt` 根对象为字符串键的 Python `dict`,内部仅允许嵌套字符串键字典和 CPU `torch.Tensor`,不保存自定义类、模型、NumPy 对象或任意可执行对象。元信息、schema、单位和来源放在 metainfo,不在每个张量条目中重复保存。读取使用 `torch.load(path, map_location="cpu", weights_only=True)`。第 4 节保留的独立有效性 `.pt` 根对象仍为 CPU bool Tensor,不适用字典结构要求。 + +例如,`camera/camera.pt` 的逻辑结构为: + +```python +{ + "intrinsic": {"data": K, "valid": K_valid}, + "extrinsic": {"data": T_camera_from_world, "valid": extrinsic_valid}, + "distortion": {"data": distortion, "valid": distortion_valid}, +} +``` + +以上变量均为 Tensor。未提供的字段整个省略;例如无世界系外参时不保存 `extrinsic`,不填单位矩阵。没有单独畸变向量的模型不创建 `distortion`:Fisheye624 仍使用既定 `[T,15]` 内参参数布局。 + +数值字段统一为 `data` 与 `valid` 两个叶子。源属性原先显式声明全已知 `valid=true` 时,迁移可按该属性的有效性形状展开为全 true 的 bool Tensor;这是已有有效性声明的等价表示,不是根据数值或姿态推测有效性。有效性必须为 bool Tensor,不能用 Python `True` 代替字段内的 Tensor。静态数值字段同样配套 valid,形状采用其语义定义的标量或逐元素有效性;静态网格等外部资产仍可在 metainfo 中声明标量 valid。 + +valid 的形状不要求与 data 完全相同,但必须与该字段定义一致。例如 MANO 为 `[T,2,61]` / `[T,2]`,内参为 `[T,3,3]` / `[T]`,关键点为 `[T,2,K,3]` / `[T,2,K]`。按 schema 将 valid 扩展到相应数值维度,不允许依靠碰巧可广播推断语义。 + +浮点默认 float32,无效浮点位置仍为 NaN;bool 和整数沿用该组件的占位/保留值规则,不因没有 NaN 而视为有效。valid 表达可用监督,不只是“值有限”或“记录存在”;适用官方 QA 与已经确认的排除规则继续保留。不能用 `isfinite(data)` 重建 valid,不能因为迁移而把 false 改成 true。 + +不同字段的 valid 独立保存和解释。visibility 的 valid 不复用姿态 valid;内参 valid 不代替外参 valid。既有相机模型要求内参与单独畸变向量共用有效性时,在两个字段内保存相同 bool 值并校验一致,而不改变该模型的联合标定规则。 + +## 4. 固定分组与字段名 + +下表中的键路径用 `/` 展示字典层级;它不是文件系统路径。数值字段均在列出的键下继续存储 `data`、`valid`。 + +| 文件 | 数值字段键 | 内容 | +|---|---|---| +| `camera/camera.pt` | `intrinsic`、`extrinsic`、`distortion` | 逐帧标定;形状、参数顺序与相机模型定义不变 | +| `annotation/mano/mano.pt` | `motion`、`visibility` | MANO `[T,2,61]` 与源整手可见性;各有独立有效性 | +| `annotation/keypoints/keypoints.pt` | `uv`、`xyz`、`visibility`、`whole_hand_visibility` | 手关键点及源可见性;整手与逐点可见性不混用 | +| `annotation/object//object.pt` | `pose`、`visibility`、`dimensions`、`joint_state` | 该物体的数值标注 | +| 同上 | `keypoints/xyz`、`keypoints/template_xyz` | 相机系逐帧点或物体系静态模板点 | +| 同上 | `parts//pose`、`parts//dimensions`、`parts//keypoints/xyz`、`parts//keypoints/template_xyz` | 部件数值字段,部件身份仍由 articulation 登记 | +| 同上 | `meshes//vertex_part_ids` | `[V] int64` 顶点部件标签,valid 为 `[V]`,未知 -1 对应 false;每个 mesh 单独绑定拓扑 | +| `annotation/contact/__/contact.pt` | `vertex_region`、`vertex_distance` | 已登记拓扑上的接触区域/距离与同形有效性 | + +顶点部件标签使用注册类型 `object/vertex_part_ids/v1`。物体的 mesh_id、part_id 必须在 metainfo/运动学定义中可解析;不同拓扑不能误用同一顶点数组。未提供的可见性、关节值或模板点不生成空字段。 + +**媒体和 JSONL 的有效性保持原样,不参与字典合并:** + +| 数据本体 | 有效性文件 | 存储形式 | +|---|---|---| +| `observation/rgb.mkv` | `observation/rgb_valid.pt` | 独立 CPU bool Tensor `[T]` | +| `annotation/segment/mask.mkv` 或 `polygons.jsonl` | 原 `valid_ref` 指定的文件,通常为 `annotation/segment/mask_valid.pt` | 独立 CPU bool Tensor `[T]`;沿用原路径 | +| `annotation/contact/relations.jsonl` | `annotation/contact/relations_valid.pt` | 独立 CPU bool Tensor `[T]` | +| `observation/depth.mkv` | `observation/depth_valid.mkv` | 原逐像素 bool 无损视频 `[T,H,W]` | + +不新建仅包装上述 valid 的 observation.pt、segment.pt 或关系级 contact.pt。现有媒体/JSONL 的 `valid_ref`、`valid_axes` 及适用的 `valid_storage` 保持原定义;深度编码、NaN 位串还原与像素有效性规则不变。实体对的接触区域/距离是数值张量,仍按上表合并到各实体对的 contact.pt。 + +## 5. metainfo 的文件与字典键引用 + +文件定位与字典内部定位分开登记,不在文件名中拼接自定义分隔符: + +| 字段 | 定义 | +|---|---| +| `data_ref` | 相对当前相机视图根目录的 POSIX 文件路径 | +| `data_key` | 非空字符串列表,按顺序访问 `.pt` 嵌套字典,最终必须得到 data Tensor | +| `valid_ref` | 有效性所在文件;合并的数值字段必须与 data_ref 相同,媒体/JSONL 保留独立有效性文件 | +| `valid_key` | 非空字符串列表,最终必须得到 bool Tensor | +| `storage.profile` / `valid_storage.profile` | 合并字典采用 `pt/tensor_bundle/v1`;媒体及其独立有效性保持原配置,不将独立 bool Tensor 声明为 bundle | + +数值字段必须显式登记 data_key 与 valid_key。例如内参登记: + +```json +{ + "available": true, + "schema_id": "camera/pinhole/v1", + "data_ref": "camera/camera.pt", + "data_key": ["intrinsic", "data"], + "axes": ["T", "row", "column"], + "valid_ref": "camera/camera.pt", + "valid_key": ["intrinsic", "valid"], + "valid_axes": ["T"], + "storage": {"profile": "pt/tensor_bundle/v1"}, + "valid_storage": {"profile": "pt/tensor_bundle/v1"} +} +``` + +这是引用结构片段,实际组件仍须补齐 provenance、source_locator 等必填内容。MANO 的 schema_id 仍可为 `mano/axis_angle61/v1`:它描述解码后的数值语义,不因为物理文件合并而改动。顶层 schema_version 与 storage.profile 标识新的存储方式。 + +媒体和 JSONL 的 data_ref 不设置 data_key;RGB 的 valid_ref 仍为 `observation/rgb_valid.pt`,不设置 valid_key。分割、关系和深度的有效性同样保持原引用方式,不新增任何字典键字段。只有引用合并字典时才使用 data_key/valid_key。 + +同样规则适用于 attributes 中的可见性等数值字段。相机模型已有的 `distortion_ref` 改为指向 `camera/camera.pt`,新增 `distortion_key=["distortion", "data"]`;对应有效性由同组件的 `distortion_valid_ref` 与 `distortion_valid_key=["distortion", "valid"]` 登记。带 `_key` 的引用必须指向匹配的 bundle 文件,不能指向目录或媒体。 + +读取器按文件路径缓存已加载字典,再按 key 取字段。同一 camera.pt 的三个字段不应触发三次反序列化。按组件下载时取所需 bundle 的整个文件;本约定不承诺 `.pt` 内单个键的远端局部下载。组件合并会增加最小下载粒度,这是减少文件数的明确取舍。 + +## 6. 迁移与验收 + +各数据集分别迁移:先适配工具并做代表性完整序列验证,再迁移全量并核对结果,最后按授权更新远端发布;一个数据集完成不代表其他数据集已完成。迁移状态和输入/输出固定版本逐数据集登记。 + +本地先在既有 `shared-v1.0` 内完成受控升级,校验完成后更名为 `shared-v1.1`。暂存、回滚、锁、旧文件清理、版本更新及 HF 路径切换遵循 [MIGRATION.md](MIGRATION.md);不复制完整媒体、不改 raw、不重新编码。多文件原地更新期间须保持维护状态,不能让读取任务使用半迁移视图。 + +每次迁移必须检查: + +1. 所有组件、属性及其字典键可解析;无越界文件引用、缺失键或未登记字段;已合并的数值组件不得遗留旧独立 `*_valid.pt`。媒体/JSONL 的原独立有效性文件必须保留,不得误删或重打包。 +2. 每个迁移前后的数值字段 dtype、shape、逐元素值、NaN 位置以及 bool valid 完全一致。数值张量还应按统一连续字节视图比较,确认没有更改 NaN 位串等内容;不能用近似容差代替单纯重打包的一致性。 +3. T、帧映射、相机方向、手槽、split、来源和 valid_policy 不变。固定标定仍按既有 `[T,...]` 规则保存;本次不额外改成单份静态标定加广播。 +4. 媒体与其他未修改文件按原可信摘要核对。新 `.pt` 的文件 SHA256 通常改变,必须重新生成发布清单;新文件指纹不等于转换语义正确性的证明。 +5. 用新读取器运行代表性完整序列及所有相机,检查 RGB、相机与实际存在的标注是否正确关联;报告明确“重打包数值一致”与“人工视觉验收”的不同范围。 + +只有完成匹配注册表、读写工具及上述验收后才能生产/发布 v1.1。上传仍须单独得到授权;本文档更新本身不启动数据迁移或上传;被替代旧文件的清理属于后续迁移发布步骤,必须遵守MIGRATION.md 中先验收、安全切换和固定提交核验要求。 diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/MIGRATION.md b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/MIGRATION.md new file mode 100644 index 0000000000000000000000000000000000000000..b867163fccbc578f22eb6be8181f866bfecb6813 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/MIGRATION.md @@ -0,0 +1,68 @@ +# 数据集 v1.0 → v1.1 升级规范 + +日期:2026-10-09。目标格式:`hand-warehouse/1.1`。字段与字典布局见 [CONTRACT.md](CONTRACT.md)。 + +## 1. 升级单位与最终布局 + +以一个完整数据集为单位逐步升级。每个数据集在既有目录内完成数值文件重组、工具适配与验证,完成后将目录由 `shared-v1.0` 更名为 `shared-v1.1`。最终使用: + +```text +/ + raw/ # 保持原样 + shared-v1.1/ + data/ + doc/ + script/ +``` + +这是对“发布目录永久保持 shared-v1.0”安排的修订:不长期保留两套发布树,也不复制一整套媒体再制作新版本。尚未升级的数据集继续使用自己的 `shared-v1.0`;不同数据集处于不同版本是正常的。 + +完成后视图元数据统一为 `schema_version=hand-warehouse/1.1`、`release_id=shared-v1.1`。目录名与元数据版本均须正确,不能只更名而不改变内容。发布记录保留旧版本的固定提交以便追溯。 + +## 2. 变更范围 + +- 合并相机、MANO、关键点、物体、实体对接触等数值张量及各自 valid;具体分组遵循合同。 +- 保持媒体及其独立有效性文件不变,包括 RGB、深度、mask 和相应 valid。JSONL、资产按合同保留;不重新编码媒体,不改 raw。 +- 不改变张量 dtype、shape、数值、NaN 位串、valid、帧映射、T、单位、坐标系、左右手、划分及监督策略。 +- 更新匹配的 schema、读取/转换/校验脚本、metainfo 引用、发布清单和正式文档。不得仅替换版本字符串冒充工具适配。 +- 删除已经完整合并且验收通过的旧数值文件与对应独立 valid;不得按 `*_valid.pt` 通配删除,媒体/JSONL 有效性不在清理范围。 + +## 3. 启动与登记 + +启动前核对项目并行上限、实际进程、锁和空间。取得数据集迁移锁并暂停该目录的转换、发布和读取任务;多文件原地更新不是整体原子操作,不得让消费者读取半迁移视图。 + +在发布树外的 `tmp/` 为每个数据集登记:源 schema/release、源 HF 固定提交、源文件清单及摘要、目标版本、工具摘要、变更/删除的精确路径清单、checkpoint、阶段、错误和验收结果。原始数据长期保留。 + +准备可恢复的基线:保存即将被替换的小型元数据和脚本,以及旧数值文件的临时备份或已核验可恢复的远端固定版本。不复制未变化的大型媒体。空间预算包含临时新文件和回滚所需文件;空间不足时停止新增工作,不删 raw 腾空间。 + +## 4. 原地升级 + +1. 先选代表性完整序列及全部相机,在 `tmp/` 验证新写入器、读取器和引用;覆盖实际存在的组件与有效性组合。遵循项目人工验收要求后再全量。 +2. 全量按完整视图处理。读取旧数值及 valid,写临时字典,重新读取并逐字段精确比较;不得用近似误差判断纯重打包的一致性。 +3. 验证通过后在同一文件系统原子替换单个文件,再更新该视图 metainfo。只有新字段与引用完整可读、且回滚依据可用,才能移除该视图被替代的旧文件。 +4. 每个视图保存完成 checkpoint;续跑必须核对输入和工具版本、产物摘要及当前引用,不能只依据文件存在而跳过。整个数据集完成前保持维护状态。 +5. 完成全部视图后校验完整路径集合、无重复/缺失、所有键引用、全部数值一致性和未变文件摘要,并更新正式文档及脚本。生成直接读取新格式的随机完整序列报告,按项目流程人工确认。 + +失败时停止该数据集迁移,保留 checkpoint 和回滚材料,不伪装完成,不自动删除整棵目录或从 raw 重做转换。 + +## 5. 本地最终更名 + +全量验收通过后,在维护状态下统一设置最终 `release_id=shared-v1.1`,更新当前使用的配置、入口、清单和链接,然后将原目录重命名为 `shared-v1.1`。 + +重命名前核对源/目标绝对路径均位于该数据集根目录;目标目录必须不存在,不合并、不覆盖已有同名目录。同一文件系统内执行目录重命名,避免复制全部媒体。更名后再次解析相对引用并检查脚本默认路径,最后解除本地维护状态。 + +历史报告中说明当时版本的文字与固定摘要作为历史证据保留,不批量篡改;当前入口须明确报告所属版本,并链接本次迁移验收结果。 + +## 6. HF 发布与路径更换 + +本地目录重命名不等于 HF 路径已经更换。远端须在得到发布授权后,基于旧的固定提交执行受控更新;发布前再次核对源 HEAD 和相关文件内容,冲突时停止调查。 + +优先复用仓库已有内容,以平台实际支持且经过验证的服务端复制/提交操作,将未变化媒体映射到 `shared-v1.1`;仅新的字典、元数据、文档和脚本需要提供新内容。不承诺路径更换必然零网络传输或零耗时;先验证实际行为,不盲目重新上传全套媒体。 + +理想情况下,在一个提交中添加目标路径并删除旧路径,使默认分支完整切换。若文件数或 API 限制不允许,使用经过验证的临时分支准备与核验,完成后受控切换;若只能分批更新默认分支,必须明确维护状态,旧版本保留到目标完整核验通过,不提前删除唯一完整的旧树。短暂的核验用路径并存不代表长期发布两套版本。 + +最终必须在同一固定提交上验证:目标 `shared-v1.1` 的文件集合、大小与内容摘要全部匹配清单,所有引用有效;旧 `shared-v1.0` 路径已移除;raw 未变化。服务端更换路径仍须执行这些核验,不能用“文件名已改”替代。 + +完成后更新数据集登记与下载示例,记录最终提交,清理本次临时文件并通知一次,再安排下一个数据集。旧提交历史保留历史版本;本流程减少当前发布树的重复文件,不承诺清除 HF 历史存储。 + +本文仅规定后续实施流程,编写本文不等于已经启动迁移、修改数据或获得新的发布授权。 diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/schema.json b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..087342ba7440c3b656e342d1b954bd90a5878af1 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/spec/schema.json @@ -0,0 +1,1590 @@ +{ + "schema_version": "hand-warehouse/1.1", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "view_metadata": { + "required_fields": [ + "schema_version", + "dataset_id", + "release_id", + "sequence_id", + "camera_id", + "sample_type", + "num_frames", + "hand_slots", + "sampling", + "camera", + "components", + "split", + "view_type" + ], + "view_type_values": [ + "ego", + "exo", + "unknown" + ], + "view_type_policy": "required per camera view; use ego or exo whenever the source data or capture setup establishes the viewpoint; use unknown only when no trustworthy source determines it; never omit or guess", + "schema_version": "hand-warehouse/1.1", + "release_id": "shared-v1.1" + }, + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.1. Read CONTRACT.md and MIGRATION.md. This is a declarative registry, not a JSON Schema document or executable validator. Runtime readers/converters/validators still require adaptation.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + }, + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage", + "distortion_ref", + "distortion_key", + "distortion_valid_ref", + "distortion_valid_key" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage", + "distortion_ref", + "distortion_key", + "distortion_valid_ref", + "distortion_valid_key" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "pilot_status": "defined_not_empirically_validated", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "pilot_status": "defined_not_empirically_validated", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "object/vertex_part_ids/v1": { + "storage": "pt", + "tensor_container": "dict", + "dtype": "int64", + "shape": [ + "V" + ], + "valid_shape": [ + "V" + ], + "valid_dtype": "bool", + "static": true, + "unknown_value": -1, + "valid_rule": "data != -1; every valid integer resolves in part_id_mapping", + "required_metadata": [ + "mesh_ref", + "topology_id", + "part_id_mapping", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt" + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + }, + "pt/tensor_bundle/v1": { + "container": "pytorch_pt", + "root_type": "dict", + "dictionary_key_type": "nonempty_string", + "allowed_value_types": [ + "dict", + "CPU torch.Tensor" + ], + "tensor_entry": { + "required_keys": [ + "data", + "valid" + ], + "additional_keys": false, + "data_type": "CPU torch.Tensor", + "valid_type": "CPU torch.Tensor", + "valid_dtype": "bool" + }, + "metadata_location": "metainfo.json; do not duplicate strings, paths or custom objects inside bundles", + "missing_entry": "omit entire entry; never fabricate absent modalities", + "load": { + "map_location": "cpu", + "weights_only": true + }, + "valid_shape_rule": "Use the specific component or attribute valid_shape; do not infer broadcasting or share validity across independent fields.", + "validation": [ + "registered layout and key resolution", + "CPU tensors only", + "schema dtype and shape", + "independent bool validity", + "frame alignment unchanged", + "invalid floating positions NaN", + "pure migration exact data bytes and validity equality" + ], + "not_applicable_to": [ + "media payloads", + "media standalone validity tensors", + "JSONL standalone validity tensors" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + }, + "tensor_storage_revision": "tensor-bundle-2026-10-09", + "release_layout": { + "directory": "shared-v1.1", + "release_id": "shared-v1.1", + "migration": "Upgrade each dataset in place under shared-v1.0 during maintenance, validate completely, then rename to shared-v1.1; do not retain duplicate published trees. See MIGRATION.md." + }, + "tensor_attributes": { + "visibility": { + "storage_profile": "pt/tensor_bundle/v1", + "allowed_dtypes": [ + "bool", + "float32" + ], + "visibility_types": [ + "boolean", + "ratio" + ], + "ratio_range": [ + 0, + 1 + ], + "scopes": { + "whole_hand": { + "shape": [ + "T", + 2 + ], + "valid_shape": [ + "T", + 2 + ] + }, + "hand_keypoint": { + "shape": [ + "T", + 2, + "K" + ], + "valid_shape": [ + "T", + 2, + "K" + ] + }, + "object": { + "shape": [ + "T" + ], + "valid_shape": [ + "T" + ] + } + }, + "required_metadata": [ + "data_ref", + "data_key", + "axes", + "dtype", + "visibility_type", + "meaning", + "valid_ref", + "valid_key", + "valid_axes", + "storage", + "valid_storage", + "provenance", + "source_locator" + ], + "valid_dtype": "bool", + "unknown": "valid=false; ratio data NaN; boolean data is not interpretable without valid", + "all_known": "explicit all-true bool tensor; do not infer from pose validity", + "note": "No source visibility means omit. Expand explicitly declared all-known scalar validity during migration without changing semantics." + } + }, + "tensor_bundles": { + "camera": { + "path": "camera/camera.pt", + "entries": { + "intrinsic": { + "schema_ids": [ + "camera/pinhole/v1", + "camera/rational8/v1", + "camera/opencv_fisheye4/v1", + "camera/fisheye624/v1" + ] + }, + "extrinsic": { + "schema_ids": [ + "transform/se3/v1" + ] + }, + "distortion": { + "schema_ids": [ + "camera/distortion8/v1", + "camera/fisheye4_distortion/v1" + ] + } + } + }, + "mano": { + "path": "annotation/mano/mano.pt", + "entries": { + "motion": { + "schema_ids": [ + "mano/axis_angle61/v1" + ] + }, + "visibility": { + "attribute_id": "visibility", + "scope": "whole_hand" + } + } + }, + "keypoints": { + "path": "annotation/keypoints/keypoints.pt", + "entries": { + "uv": { + "schema_ids": [ + "keypoints/uv/v1" + ] + }, + "xyz": { + "schema_ids": [ + "keypoints/xyz/v1" + ] + }, + "visibility": { + "attribute_id": "visibility", + "scope": "hand_keypoint" + }, + "whole_hand_visibility": { + "attribute_id": "visibility", + "scope": "whole_hand" + } + } + }, + "object": { + "path": "annotation/object//object.pt", + "entries": { + "pose": { + "schema_ids": [ + "object/rigid/v1" + ] + }, + "visibility": { + "attribute_id": "visibility", + "scope": "object" + }, + "dimensions": { + "schema_ids": [ + "object/dimensions/v1" + ] + }, + "joint_state": { + "schema_ids": [ + "object/joint_state/v1" + ] + }, + "keypoints/xyz": { + "schema_ids": [ + "object_keypoints/camera/v1" + ] + }, + "keypoints/template_xyz": { + "schema_ids": [ + "object_keypoints/template/v1" + ] + }, + "parts//pose": { + "schema_ids": [ + "transform/se3/v1" + ], + "convention": "T_camera_from_part" + }, + "parts//dimensions": { + "schema_ids": [ + "object/dimensions/v1" + ] + }, + "parts//keypoints/xyz": { + "schema_ids": [ + "object_keypoints/camera/v1" + ] + }, + "parts//keypoints/template_xyz": { + "schema_ids": [ + "object_keypoints/template/v1" + ], + "coordinate_frame": "part" + }, + "meshes//vertex_part_ids": { + "schema_ids": [ + "object/vertex_part_ids/v1" + ] + } + } + }, + "contact_pair": { + "path": "annotation/contact/__/contact.pt", + "entries": { + "vertex_region": { + "schema_ids": [ + "contact/vertex_region/v1" + ] + }, + "vertex_distance": { + "schema_ids": [ + "contact/vertex_distance/v1" + ] + } + } + } + }, + "bundle_layout_rules": { + "entry_path_syntax": "Slash-separated dictionary keys in this registry only; serialize references as string arrays. Angle-bracket placeholders resolve to registered IDs, not literal keys.", + "entry_leaves": [ + "data", + "valid" + ], + "additional_entries": false, + "all_entries_optional": true, + "omit_empty_bundles": true, + "identifiers": "object/part/mesh and contact entity IDs must resolve in metadata; reject empty, dot, dot-dot or slash-containing IDs", + "per_view": true, + "no_cross_object_or_camera_merge": true, + "numeric_field_valid_ref_equals_data_ref": true, + "attributes_must_be_registered": true + }, + "reference_rules": { + "file_paths": { + "base": "current camera view root", + "format": "relative POSIX", + "reject": [ + "absolute paths", + "parent traversal", + "external URLs", + "unresolved placeholders" + ] + }, + "dictionary_keys": { + "type": "array", + "item_type": "nonempty_string", + "min_items": 1, + "traversal": "literal nested dictionary lookup; never eval; no automatic flattening", + "data_terminal": "data", + "valid_terminal": "valid", + "target_type": "CPU torch.Tensor" + }, + "bundle_component": { + "required": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "same_file": true, + "same_entry_prefix": true, + "storage_profile": "pt/tensor_bundle/v1", + "valid_storage_profile": "pt/tensor_bundle/v1" + }, + "media_jsonl": { + "forbidden": [ + "data_key", + "valid_key" + ], + "preserve_original_valid_ref": true, + "standalone_valid_pt_root": "CPU bool torch.Tensor; not dict", + "do_not_label_standalone_valid_as_bundle": true + }, + "camera_distortion": { + "models": { + "rational8": "camera/distortion8/v1", + "opencv_fisheye4": "camera/fisheye4_distortion/v1" + }, + "required": [ + "distortion_ref", + "distortion_key", + "distortion_valid_ref", + "distortion_valid_key" + ], + "distortion_ref": "camera/camera.pt", + "distortion_key": [ + "distortion", + "data" + ], + "distortion_valid_ref": "camera/camera.pt", + "distortion_valid_key": [ + "distortion", + "valid" + ], + "valid_equals_intrinsic_valid": true, + "models_without_separate_distortion": [ + "pinhole", + "fisheye624" + ] + }, + "reader_cache": "Cache bundle by resolved file path; loading different fields must not repeatedly deserialize the file." + }, + "standalone_validity": { + "rgb": { + "data_ref": "observation/rgb.mkv", + "valid_ref": "observation/rgb_valid.pt", + "dtype": "bool", + "shape": [ + "T" + ], + "container": "pt", + "root_type": "CPU Tensor" + }, + "segment": { + "data_refs": [ + "annotation/segment/mask.mkv", + "annotation/segment/polygons.jsonl" + ], + "valid_ref": "preserve source release reference; normally annotation/segment/mask_valid.pt", + "dtype": "bool", + "shape": [ + "T" + ], + "container": "pt", + "root_type": "CPU Tensor" + }, + "relations": { + "data_ref": "annotation/contact/relations.jsonl", + "valid_ref": "annotation/contact/relations_valid.pt", + "dtype": "bool", + "shape": [ + "T" + ], + "container": "pt", + "root_type": "CPU Tensor" + }, + "depth": { + "data_ref": "observation/depth.mkv", + "valid_ref": "observation/depth_valid.mkv", + "dtype": "bool", + "shape": [ + "T", + "H", + "W" + ], + "profile": "mkv/bool_ffv1/v1" + } + } +} diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/validate.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..b08e6104e6c606c86bab5fca76e44461aae5b3dd --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/validate.py @@ -0,0 +1,470 @@ +"""Validate the adjacent ReInterHand shared-v1.1 tree and fingerprint its bytes. + +Adapted from the RHD second-generation validator: numeric components are read +through their registered bundle keys instead of one ``.pt`` per component, media +validity must still be a standalone bool Tensor, and a merged field may not leave a +standalone ``*_valid.pt`` behind (CONTRACT 6.1, 6.5). ReInterHand's own rules are +added on top, and every one of them is a fact measured over the release +(``tmp/reinterhand-tools/surface_recon.json``) rather than a schema wish: + +* 6,750 views in 500 sequences, addressed by a ``camera_id`` that is either a Mugsy + camera number or the literal ``"ego"`` -- nothing here may assume ``range(9)`` or + one camera per sequence; +* the release is four render cells, and each cell fixes its own view count, its + cameras per sequence and its frame rule (``EXPECTED_CELLS``, and + ``reinterhand_common.RENDER_CELLS`` for the per-view half); +* ``frames.jsonl`` has no ``annotation_index``, so the alignment rule RHD and ARCTIC + use has no field to read; ``sync_id`` joins cameras instead; +* the media layer is not materialised in this working copy, so a declared + ``rgb.mkv``/``mask.mkv`` may be *absent by declaration* -- and the declaration is + checked from both sides, so a half-pulled sequence fails; +* the published v1.0 media metadata does not satisfy the shared schema, uniformly + over all 6,750 views. A numeric-only migration may not repair that, so the gaps + are declared, counted, and asserted to be exactly the declared set. + +Scope: this checks the released content and layout. It does not independently prove +official source correctness, and it is not human visual acceptance (CONTRACT 6). + +Run: python shared-v1.1/script/reinterhand_v1_1/validate.py \ + --report shared-v1.1/doc/validation/validate_report.json + +``--views``/``--limit`` are for checking a corner of the tree while working on it, and +a run that uses either is a *subset* run: it asserts only what its selected views can +support, marks its report partial, writes it to tmp rather than over the acceptance +report, and leaves the release manifest alone. Run it with no selection for the +acceptance pass -- that is the one that checks the 6,750-view count and the +1,134,281/392,514 frame census. + +``--strict-media`` ignores the media declaration, which is the honest way to see what +the declaration does: the same sweep then fails on the first ``rgb.mkv``. +""" + +from __future__ import annotations + +import argparse +import collections +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from reinterhand_common import ( # noqa: E402 + CAMERA_FAMILY_BY_VIEW_TYPE, + DECLARED_MEDIA_SCHEMA_GAPS, + DEFAULT_MEDIA_DECLARATION, + EXO_CAMERAS_BY_POLICY, + REGISTRY, + REGISTRY_READER, + RELEASE_ROOT, + TMP_ROOT, + MediaDeclaration, + audit, + load, + save, + sha256, + stray_validity, + walk_leaf, +) +from warehouse import BundleReader, BundleWriter, raw_bytes # noqa: E402 + +#: the manifest is written outside the release tree. A file inside the tree cannot +#: describe its own final bytes, and a copy that excludes itself leaves one release +#: file that no digest covers; RHD, ARCTIC, H2O and dex-ycb keep theirs in +#: ``tmp/-tools/`` for the same reason. +MANIFEST_PATH = TMP_ROOT / "PUBLISH_MANIFEST.json" + +#: The release census, keyed by the split the view metadata declares. Measured: +#: InterWild's official capture split puts 368 captures in ``train`` and 132 in +#: ``test``, and no capture contributes to both -- which is why ``split`` is uniform +#: across the views of a sequence and is asserted that way below. +EXPECTED_SPLIT = {"train": {"views": 4968, "sequences": 368, "frames": 1134281}, + "test": {"views": 1782, "sequences": 132, "frames": 392514}} +EXPECTED_SEQUENCES = 500 +EXPECTED_VIEWS = 6750 +#: The four render cells and how many views each holds. Every sequence also has exactly +#: one ``ego`` view and its policy's exo cameras (``EXO_CAMERAS_BY_POLICY``), so a +#: per-frame sequence has 21 camera directories and a per-segment one 6 -- 250 sequences +#: per cell, measured, and the reason a sequence count is not 500/4 in the per-view check. +EXPECTED_CELLS = {("exo", "envmap_per_frame"): 5000, ("exo", "envmap_per_segment"): 1250, + ("ego", "envmap_per_frame"): 250, ("ego", "envmap_per_segment"): 250} +EXPECTED_CELL_SEQUENCES = 250 +#: Every view declares exactly one ``rgb.mkv`` and one ``mask.mkv``: 2 x 6,750. +MEDIA_REFS_PER_VIEW = 2 +SCOPE = ("released content and layout; does not independently prove official source " + "correctness or visual quality") +PARTIAL_SCOPE = (SCOPE + "; this run covered a selected subset of the release, so it is " + "not the release-wide acceptance run") +#: where a subset run writes instead of the release's own report path. The name is load +#: bearing: it must not be the acceptance report, which describes the whole release and is +#: what FULL_MIGRATION_SUMMARY.json cites. +PARTIAL_REPORT = TMP_ROOT / "validate-partial.json" +ACCEPTANCE_REPORT = RELEASE_ROOT / "doc/validation/validate_report.json" + + +def release_files(): + """Every file of the release, in path order -- one definition, used twice. + + Both the report (written before the manifest) and the manifest itself need this + set. Two filters that could drift apart would let the report name a file count + the manifest it cites does not have. + """ + for path in sorted(RELEASE_ROOT.rglob("*")): + #: bytecode caches are not release content. Nothing else is skipped: the + #: manifest lives outside the tree, so it never has to exclude itself and the + #: release's byte total is the manifest's own total. + if not path.is_file() or ".cache" in path.parts or "__pycache__" in path.parts: + continue + yield path + + +def rewrite_check(view_dir, meta, work): + """Rebuild a view's bundles with ``BundleWriter`` and compare leaf bytes. + + ``verify.py`` proves the released bytes equal the *source* bytes; this proves the + writer that produced them is reproducible from the released metadata alone, which + is what makes the bundles readable by something other than the migration. + + ReInterHand declares no bundled attributes, so every field is a component's own + ``data_key``; the loop stays key-driven all the same, so a future attribute shows + up as a missing leaf rather than as a silently thinner comparison. + """ + where = f"{meta['sequence_id']}/{meta['camera_id']}" + rebuilt_root = Path(work) / f"{meta['sequence_id']}__{meta['camera_id']}" + writers, bundles = {}, [] + for component in meta["components"].values(): + if "data_key" not in component: + continue + ref = component["data_ref"] + if ref not in writers: + writers[ref] = BundleWriter(rebuilt_root, ref) + bundles.append(ref) + data, valid = REGISTRY_READER.field(view_dir, component) + writers[ref].put(component["data_key"][:-1], data, valid) + for ref in bundles: + writers[ref].save() + + compared = 0 + for ref in sorted(bundles): + released = REGISTRY_READER.bundle(view_dir, ref) + rebuilt = REGISTRY_READER.bundle(rebuilt_root, ref) + got = dict(walk_leaf(rebuilt)) + #: the key set has to match too: a field the writer dropped would otherwise + #: compare as zero leaves and pass as "nothing left to disagree about" + assert set(got) == set(dict(walk_leaf(released))), (where, ref, sorted(got)) + for keys, leaf in walk_leaf(released): + for terminal in ("data", "valid"): + left, right = leaf[terminal], got[keys][terminal] + assert left.dtype == right.dtype and tuple(left.shape) == tuple(right.shape), ( + where, ref, keys, terminal) + assert raw_bytes(left) == raw_bytes(right), (where, ref, keys, terminal) + compared += 1 + return {"sequence_id": meta["sequence_id"], "camera_id": meta["camera_id"], + "bundles": sorted(bundles), "tensors_compared": compared} + + +def census_checks(views, counts, cell_views, cell_sequences, sequence_cameras, + sequence_frames, sequence_policy): + """The release-wide census, asserted only where it can hold. + + A subset's counts are a fraction of these by construction, so comparing them would + fail a working check for a reason that has nothing to do with the views it read. + """ + assert len(views) == EXPECTED_VIEWS, len(views) + assert counts == EXPECTED_SPLIT, counts + assert len(sequence_policy) == EXPECTED_SEQUENCES, len(sequence_policy) + for cell, expected_views in EXPECTED_CELLS.items(): + view_type, policy = cell + assert cell_views[cell] == expected_views, (cell, cell_views[cell], expected_views) + sequences = cell_sequences[cell] + assert len(sequences) == EXPECTED_CELL_SEQUENCES, (cell, len(sequences)) + for sequence in sorted(sequences): + exo = sequence_cameras[sequence].get("exo", set()) + ego = sequence_cameras[sequence].get("ego", set()) + assert len(exo) == EXO_CAMERAS_BY_POLICY[policy], (sequence, cell, sorted(exo)) + assert ego == {"ego"}, (sequence, cell, sorted(ego)) + #: the render cell fixes the frame counts, and only there: a per-segment + #: render writes one video frame per source frame for every camera, while the + #: per-frame ego render keeps the whole capture and its exo renders sample it. + #: This is what ties the cell in the sequence id to the frame table's length. + frames = sequence_frames[sequence] + if policy == "envmap_per_segment": + assert len(set().union(*frames.values())) == 1, (sequence, sorted(frames.items())) + else: + assert max(frames["exo"]) < min(frames["ego"]), (sequence, sorted(frames.items())) + #: the two view types of a policy render the same sequences: every sequence has its + #: exo cameras *and* its single ego view, so a missing ego render cannot pass as a + #: smaller release + for policy in sorted({cell[1] for cell in EXPECTED_CELLS}): + assert cell_sequences[("ego", policy)] == cell_sequences[("exo", policy)], policy + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--views", nargs="*", default=None, help="restrict to these sequences") + parser.add_argument("--limit", type=int, default=None, help="validate at most N views") + parser.add_argument("--rewrite-check", type=int, default=0, metavar="N", + help="also re-serialise N views with BundleWriter and compare leaf bytes") + parser.add_argument("--expect-views", type=int, default=None, metavar="N", + help=f"fail unless exactly N views were checked (default: {EXPECTED_VIEWS}, " + "the full ReInterHand release, for a run with no --views/--limit; a " + "subset run defaults to the number of views it selected). Without it a " + "run that silently covered a fraction of the tree would still report a " + "pass.") + parser.add_argument("--media-declaration", type=Path, default=DEFAULT_MEDIA_DECLARATION, + help="where this copy of the tree declares which preserved media it ships " + f"(default: {DEFAULT_MEDIA_DECLARATION}). A missing file means every " + "declared media file must exist, which is what a published tree looks " + "like.") + parser.add_argument("--strict-media", action="store_true", + help="ignore the media declaration and require every declared media file to " + "exist. On this working copy that fails by design -- it is how the " + "declaration's own effect is shown to be real.") + parser.add_argument("--report", type=Path, default=None, + help="where the structural report is written (default: the release's " + "doc/validation/validate_report.json for a full run, " + f"{PARTIAL_REPORT} for a subset run, which must not overwrite the " + "acceptance report)") + parser.add_argument("--no-manifest", action="store_true", + help=f"do not rebuild the release manifest ({MANIFEST_PATH}). It hashes " + "the whole release tree whatever --views says, so an incremental " + "check would pay for a manifest the final run overwrites anyway. " + "The accepting run must not pass this (CONTRACT 6.4).") + args = parser.parse_args(argv) + + all_views = sorted((RELEASE_ROOT / "data").glob("*/*/metainfo.json")) + wanted = set(args.views) if args.views else None + if wanted is not None: + #: a name that matches nothing is a typo, and silently checking the other views + #: would let it pass as a green run over the wrong set + known = {view.parent.parent.name for view in all_views} + assert wanted <= known, ("no such sequence", sorted(wanted - known)) + views = [view for view in all_views if view.parent.parent.name in wanted] + else: + views = all_views + if args.limit: + views = views[: args.limit] + assert views, "no metainfo.json found under data/*/*/" + + #: "is this release complete?" and "is this view sound?" are different questions. + #: The frame census and the view count only mean anything over the whole tree, so a + #: run with --views/--limit checks its own selection instead and says so everywhere + #: its result is reported (see SCOPE/PARTIAL_SCOPE, the report's ``coverage``, and + #: the manifest it deliberately does not rebuild). + full = wanted is None and not args.limit + expect_views = args.expect_views if args.expect_views is not None else ( + EXPECTED_VIEWS if full else len(views)) + + media = MediaDeclaration("all") if args.strict_media else MediaDeclaration.load(args.media_declaration) + gaps, failures, rewrites = collections.Counter(), [], [] + split_views, split_frames, split_sequences = collections.Counter(), collections.Counter(), collections.defaultdict(set) + cell_views, cell_sequences, cell_steps = collections.Counter(), collections.defaultdict(set), collections.defaultdict(collections.Counter) + cell_gap_hist = collections.defaultdict(collections.Counter) + #: per-sequence bookkeeping. A sequence is one directory, so all of its views are + #: adjacent in path order and these collapse to one entry per sequence -- which is + #: what lets the sequence-wide facts be asserted below instead of trusted. + sequence_split, sequence_policy = collections.defaultdict(set), collections.defaultdict(set) + sequence_spans = collections.defaultdict(set) + sequence_cameras = collections.defaultdict(lambda: collections.defaultdict(set)) + sequence_frames = collections.defaultdict(lambda: collections.defaultdict(set)) + capture_splits = collections.defaultdict(set) + family_by_view_type = collections.defaultdict(set) + files_total, frames_total, declared_media, expected_media_on_disk, mkv_on_disk = 0, 0, 0, 0, 0 + + for position, path in enumerate(views, 1): + view_dir, meta = path.parent, load(path) + if position % 250 == 1 or position == len(views): + print(f" view {position}/{len(views)}: {view_dir.relative_to(RELEASE_ROOT)}", flush=True) + #: the path and the metadata have to name the same view, or a misplaced or + #: duplicated directory tree would validate as its own sound copy + assert meta["sequence_id"] == view_dir.parent.name, (path, meta.get("sequence_id")) + assert meta["camera_id"] == view_dir.name, (path, meta.get("camera_id")) + + sequence, camera = meta["sequence_id"], meta["camera_id"] + rendering = meta["source_rendering"] + cell = (meta["view_type"], rendering["background_policy"]) + family_by_view_type[meta["view_type"]].add(rendering["camera_family"]) + capture_splits[meta["source_capture_id"]].add(meta["split"]) + sequence_split[sequence].add(meta["split"]) + sequence_policy[sequence].add(rendering["background_policy"]) + sequence_spans[sequence].add(tuple(meta["source_frame_span"])) + sequence_cameras[sequence][meta["view_type"]].add(camera) + sequence_frames[sequence][meta["view_type"]].add(meta["num_frames"]) + cell_views[cell] += 1 + cell_sequences[cell].add(sequence) + split_views[meta["split"]] += 1 + split_frames[meta["split"]] += meta["num_frames"] + split_sequences[meta["split"]].add(sequence) + frames_total += meta["num_frames"] + + #: a fresh reader per view. A view's components share their bundles, so the cache + #: is what makes the pass read each file once -- but keeping it across the sweep + #: would hold 6,750 views x 2 bundles in memory, so the whole-tree tools scope it + #: to the view they are looking at (the module-level reader backs the single-view + #: tools, and rewrite_check below). + _consumed, view_gaps, view_failures, frames = audit(view_dir, meta, REGISTRY, BundleReader(), + media, None) + gaps.update(view_gaps) + failures.extend(view_failures) + if frames is not None: + cell_steps[cell][frames["modal_step"]] += 1 + cell_gap_hist[cell][frames["source_gaps"]] += 1 + + present = sorted(p.relative_to(view_dir).as_posix() + for p in view_dir.rglob("*") if p.is_file()) + files_total += len(present) + stray = [name for name in present if stray_validity(name)] + assert not stray, (view_dir, "merged field left a standalone validity file", stray) + #: media tallies, from both sides at once: what the metainfo declares, what the + #: declaration says this copy ships, and what the tree actually holds + mkv_refs = {c["data_ref"] for c in meta["components"].values() + if c["data_ref"].endswith(".mkv")} + declared_media += len(mkv_refs) + if media.ships(sequence): + expected_media_on_disk += len(mkv_refs) + mkv_on_disk += sum(1 for name in present if name.endswith(".mkv")) + if len(rewrites) < args.rewrite_check: + rewrites.append(rewrite_check(view_dir, meta, TMP_ROOT / "rewrite-check")) + + #: Everything from here on is an invariant of a *sound* tree, so it is asserted only + #: when the per-view sweep found nothing. A defective view can make several of these + #: meaningless -- a missing media file stops ``check_view`` before it tallies the + #: declaration gaps, and asserting the tally first would replace the named per-view + #: failure with an unrelated one, which is the failure mode ``audit`` exists to avoid. + #: A run with failures already reports itself as failed either way. + if not failures: + #: each of the nine declared gaps fires exactly once per view, so a gap that + #: *stopped* occurring is as much a finding as a new one: it would mean the media + #: metadata was repaired outside a numeric-only migration's contract. + assert dict(gaps) == {token: len(views) for token in DECLARED_MEDIA_SCHEMA_GAPS}, ( + "declared media schema gaps", dict(gaps)) + #: a subset may hold only exo views, so this checks the families it saw and leaves + #: "all four cells are present" to the census, the run that can speak for the + #: whole release + assert set(family_by_view_type) <= set(CAMERA_FAMILY_BY_VIEW_TYPE), sorted(family_by_view_type) + for view_type, families in family_by_view_type.items(): + assert families == {CAMERA_FAMILY_BY_VIEW_TYPE[view_type]}, (view_type, sorted(families)) + for label, mapping in (("capture", capture_splits), ("sequence", sequence_split), + ("sequence", sequence_policy), ("sequence", sequence_spans)): + multiple = sorted(name for name, seen in mapping.items() if len(seen) > 1) + assert not multiple, (f"{label} with more than one value", multiple[:5]) + #: the render cell is named in the sequence id, so a mislabelled policy cannot pass + for sequence, policy in sequence_policy.items(): + name = sorted(policy)[0] + assert f"__{name}__" in sequence, (sequence, name) + + #: the media declaration, checked from both sides. ``expected_media_on_disk`` + #: counts the streams the declaration says this copy ships and ``mkv_on_disk`` what + #: the tree holds: equal means no declared stream is missing *and* no undeclared one + #: is lying around -- which is what "half-pulled sequence" looks like from here. + assert declared_media == MEDIA_REFS_PER_VIEW * len(views), (declared_media, len(views)) + assert mkv_on_disk == expected_media_on_disk, ( + "media on disk disagrees with the declaration", mkv_on_disk, expected_media_on_disk) + + counts = {split: {"views": split_views[split], "sequences": len(split_sequences.get(split, ())), + "frames": split_frames[split]} for split in sorted(split_views)} + cells = {} + for (view_type, policy), count in sorted(cell_views.items()): + #: the modal step and the gap histogram are reported, not asserted: the source + #: captures genuinely skip frames, so a bound would encode this tree's accidents + #: as a rule. ``check_frames`` asserts the one thing that is a rule -- that the + #: modal step is one the cell declares. + cells[f"{view_type}/{policy}"] = { + "views": count, "sequences": len(cell_sequences[(view_type, policy)]), + "modal_source_step": {str(step): n for step, n in sorted(cell_steps[(view_type, policy)].items())}, + "source_gap_histogram": {str(gap): n for gap, n in sorted(cell_gap_hist[(view_type, policy)].items())}} + + if full and not failures: + census_checks(views, counts, cell_views, cell_sequences, sequence_cameras, + sequence_frames, sequence_policy) + #: per-view contract: the parts that hold release-wide rather than per view + assert len(views) == expect_views, (len(views), expect_views) + + result = { + "passed": not failures, + "coverage": "full release" if full else "partial subset", + "views": len(views), "sequences": len(sequence_policy), "counts": counts, "cells": cells, + "frames": frames_total, + "files_per_view": files_total // len(views), + "schema_version": REGISTRY.schema["view_metadata"]["schema_version"], + "release_id": REGISTRY.schema["view_metadata"]["release_id"], + "bundles_per_view": len({c["data_ref"] for c in load(views[0])["components"].values() + if "data_key" in c}), + "declared_media_schema_gaps": dict(gaps), + "media": {"declaration": media.origin, + "materialised": sorted(media.materialised) if isinstance(media.materialised, set) + else media.materialised, + "declared_media_files": declared_media, "files_on_disk": mkv_on_disk}, + "rewrite_check": rewrites, + "failures": failures, + "scope": SCOPE if full else PARTIAL_SCOPE, + } + report_path = args.report or (ACCEPTANCE_REPORT if full else PARTIAL_REPORT) + #: The tmp copy is a convenience for the migration loop, and its *name* is load + #: bearing. It must not be "acceptance.json": the documented chain writes verify.py's + #: byte-level acceptance report to tmp/reinterhand-tools/acceptance.json, so a + #: structural report saved under that name silently destroys the evidence + #: FULL_MIGRATION_SUMMARY.json is built from. + save(TMP_ROOT / "validate-latest.json", result) + save(report_path, result) + + skip_manifest = None + if failures: + #: the manifest is a claim about the whole release, so a run that found a defect + #: must not leave one behind that reads like an accepted tree + skip_manifest = "failed run; the release manifest is rebuilt only by a passing acceptance run" + elif args.no_manifest: + #: reported as skipped rather than as a manifest of 0 files, which would read + #: like an empty release + skip_manifest = "incremental check; not an acceptance run" + elif not full: + #: The manifest is a claim about the whole release -- it hashes every file -- and + #: the documented chain reads it together with the acceptance report. A subset run + #: must not leave the two disagreeing about what was accepted, so it reports the + #: manifest as skipped instead of rebuilding one to sit beside a partial report. + skip_manifest = "partial run; the release manifest is rebuilt by the full acceptance run" + if skip_manifest: + result["release_manifest"] = {"skipped": skip_manifest, "path": str(MANIFEST_PATH)} + save(TMP_ROOT / "validate-latest.json", result) + save(report_path, result) + print(json.dumps(result, ensure_ascii=False, indent=2)) + return 0 if result["passed"] else 1 + + #: Named, and counted, here -- before the manifest is rebuilt -- because the manifest + #: has to cover this report's final bytes, so the report cannot carry the manifest's + #: digest. The count is exact all the same: nothing adds or removes a release file + #: between this walk and the hash pass below. + result["release_manifest"] = { + "path": str(MANIFEST_PATH), + "in_release_tree": False, + "files": sum(1 for _ in release_files()), + "note": "rebuilt by this run after this report was written, so it covers the " + "report's final bytes; kept outside the release because a manifest inside " + "it cannot hash itself", + } + save(TMP_ROOT / "validate-latest.json", result) + save(report_path, result) + + manifest = [] + for path in release_files(): + rel = path.relative_to(RELEASE_ROOT).as_posix() + manifest.append({"path": rel, "size": path.stat().st_size, "sha256": sha256(path)}) + payload = { + "release": REGISTRY.schema["view_metadata"]["release_id"], + "scope": result["scope"], + "location": f"{MANIFEST_PATH} (outside the release tree, as in the published " + "RHD, ARCTIC, H2O and dex-ycb sets)", + "excludes": ["__pycache__/"], + "files": manifest, + "bytes": sum(entry["size"] for entry in manifest), + } + save(MANIFEST_PATH, payload) + print(f"manifest: {len(manifest)} files, {payload['bytes']} B -> {MANIFEST_PATH}") + + print(json.dumps(result, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.dont_write_bytecode = True + raise SystemExit(main()) \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/verify.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..0493e1b4d69db2d276e5268fefa74a7c892a3b4e --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/verify.py @@ -0,0 +1,516 @@ +#!/usr/bin/env python3 +"""Acceptance checks for a shared-v1.0 -> shared-v1.1 migration (CONTRACT 6). + +Compares the migrated tree against the source it came from, so every claim is +checked against real bytes rather than re-asserted from the migrator: + +1. every component/attribute and its dictionary keys resolve; no stray files, no + missing keys, no unregistered fields; merged numeric components leave no + standalone ``*_valid.pt``; media/JSONL validity files survive untouched +2. every numeric field is identical to its source in dtype, shape, element-wise + values, NaN positions and bool validity, compared as a unified contiguous byte + view with no tolerance +3. ``num_frames``, sampling, hand slots, split, camera, view type, provenance and + ``valid_policy`` are unchanged -- the metainfo diff must equal the allowed set +4. media and other preserved files match their source digests; the release + manifest is regenerated because merged ``.pt`` digests necessarily changed +5. the new reader resolves RGB, camera and every annotation present on + representative complete sequences + +The report distinguishes "repackaging is numerically identical" from "human +visual acceptance"; this tool produces evidence for the former only. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from warehouse import ( # noqa: E402 + BundleReader, + Registry, + same_tensor, + sha256_file, +) + +#: this package lives in /shared-v1.1/script/reinterhand_v1_1, so the +#: release and the dataset root beside it need no arguments. +RELEASE_ROOT = Path(__file__).resolve().parent.parent.parent +DATASET_ROOT = RELEASE_ROOT.parent +#: Where ``--manifest`` writes. The release manifest is a publication artifact and +#: lives *outside* the release tree: a manifest inside it could not hash its own final +#: bytes. ``reinterhand_common.MANIFEST_PATH`` holds the same path -- keep the two in +#: step; validate.py is what the documented chain rebuilds the shipping manifest with. +MANIFEST_PATH = DATASET_ROOT / "tmp" / "reinterhand-tools" / "PUBLISH_MANIFEST.json" + +V10_SCHEMA_VERSION = "hand-warehouse/1.0" +#: metainfo keys the migration is allowed to rewrite at the top level. Everything +#: else is a claim the source made and must survive verbatim -- ReInterHand's release +#: status flags (``upload_authorized``/``full_output_human_review``/ +#: ``full_conversion_complete``/``conversion_scope``), the omitted-component reasons, +#: the split bookkeeping. The version keys change by definition, and ``components`` +#: changes wherever a numeric field joins a bundle. +ALLOWED_TOP_LEVEL_CHANGES = {"schema_version", "release_id", "components"} +#: the one key that is neither "bumped by definition" nor "preserved verbatim": v1.0's +#: converter stamped ``lossless-video-2026-09-18``'s slot with a label of its own +#: (``lossless-video-2026-09-25``), which ``doc/schema.json`` declares nowhere, so +#: migration points it at the revision the registry itself declares -- the value every +#: published v1.1 sibling view carries. It is handled on its own rather than by adding +#: it to the set above, because the rewrite is allowed to one target value only, and a +#: view that never declared the key must not acquire one. +STORAGE_REVISION = "storage_revision" +#: component fields the migration adds when a numeric field joins a bundle +BUNDLE_FIELDS = {"data_key", "valid_key", "storage", "valid_storage"} +#: component fields that must survive any migration untouched +PRESERVED_FIELDS = ("provenance", "source_locator", "valid_policy", "axes", "valid_axes") + + +class Failure(Exception): + pass + + +def check(condition, message): + if not condition: + raise Failure(message) + + +def flatten(value, prefix=""): + """Flatten a JSON object into dotted leaf paths.""" + if isinstance(value, dict): + out = {} + for key, item in value.items(): + out.update(flatten(item, f"{prefix}{key}.")) + return out + if isinstance(value, list) and value and not isinstance(value[0], (dict, list)): + return {prefix[:-1]: json.dumps(value)} + return {prefix[:-1]: json.dumps(value)} + + +def is_stray_validity(registry: Registry, rel: str) -> bool: + """True when a standalone ``*_valid.pt`` belongs to a field that was merged. + + Catches the failure CONTRACT 6.1 names explicitly: a numeric component's + validity left behind as its own file because its name was not recognised. + """ + if not rel.endswith("_valid.pt"): + return False + return registry.resolve(rel[: -len("_valid.pt")] + ".pt") is not None + + +def compare_metainfo(source: dict, target: dict, sequence: str, camera: str, registry: Registry): + """Assert the metainfo diff is exactly the storage-layout change set.""" + where = f"{sequence}/{camera}" + check(source["schema_version"] == V10_SCHEMA_VERSION, + f"{where}: source is not {V10_SCHEMA_VERSION}") + for key in ("num_frames", "sampling", "hand_slots", "split", "camera", + "view_type", "dataset_id", "sequence_id", "camera_id", "sample_type"): + check(source.get(key) == target.get(key), + f"{where}: {key} changed ({source.get(key)!r} -> {target.get(key)!r})") + check(target["schema_version"] == "hand-warehouse/1.1", f"{where}: schema_version not bumped") + check(target["release_id"] == "shared-v1.1", f"{where}: release_id not bumped") + + #: every remaining top level key, compared to this view's own source rather than + #: to a constant: these are per-view claims made by the source, so "unchanged" + #: has to mean unchanged against *this view's* v1.0 bytes, not equal to one + #: expected value. ReInterHand's status flags happen to be uniform today (all + #: 6,750 views carry ``upload_authorized=false``, ``full_output_human_review= + #: "pending"``, ``full_conversion_complete=true``, ``conversion_scope="full"``); + #: comparing per-view is what keeps a future re-render with a different status + #: from being silently normalised into agreement. + for key in sorted(set(source) | set(target)): + if key in ALLOWED_TOP_LEVEL_CHANGES: + continue + check(key in source and key in target, + f"{where}: top level key {key!r} exists on only one side") + if key == STORAGE_REVISION: + #: one target value only, read off the registry rather than restated here. + check(target[key] == registry.schema[STORAGE_REVISION], + f"{where}: {key} must be the registry's own " + f"({target[key]!r} != {registry.schema[STORAGE_REVISION]!r})") + continue + check(source[key] == target[key], + f"{where}: {key} changed ({source[key]!r} -> {target[key]!r})") + + source_components = source["components"] + target_components = target["components"] + check(set(source_components) == set(target_components), + f"{where}: component set changed") + + for name, before in source_components.items(): + after = target_components[name] + for key in PRESERVED_FIELDS: + check(before.get(key) == after.get(key), + f"{where}/{name}: {key} changed") + check(before.get("schema_id") == after.get("schema_id"), + f"{where}/{name}: schema_id changed") + check(before.get("available") == after.get("available"), + f"{where}/{name}: availability changed") + # attributes (e.g. visibility) follow the same rules as components + before_attributes = before.get("attributes") or {} + after_attributes = after.get("attributes") or {} + check(set(before_attributes) == set(after_attributes), + f"{where}/{name}: attribute set changed") + for attribute, before_attribute in before_attributes.items(): + after_attribute = after_attributes[attribute] + for key in ("axes", "dtype", "visibility_type", "meaning", "provenance", + "source_locator"): + check(before_attribute.get(key) == after_attribute.get(key), + f"{where}/{name}.{attribute}: {key} changed") + if "data_key" in after_attribute: + check(before_attribute.get("valid") is True, + f"{where}/{name}.{attribute}: bundled without a declared all-known scalar") + check("valid" not in after_attribute, + f"{where}/{name}.{attribute}: scalar valid must give way to valid_key") + check(after_attribute["data_ref"] == after_attribute["valid_ref"], + f"{where}/{name}.{attribute}: data_ref and valid_ref must share a file") + + +def verify_distortion(registry, v10_view, v11_view, reader, name, source_component, + target_component, where, consumed): + """CONTRACT 5/3: the separate distortion vector joins the camera's own bundle. + + v1.0 declares it on the component that owns the calibration, with no validity + of its own: the camera model pairs the distortion vector with the intrinsic + validity, so the two fields must carry the same bool values. Returns the + field record, or ``None`` when the component declares no distortion. + """ + ref = source_component.get("distortion_ref") + if not ref: + return None + resolved = registry.resolve(ref) + if resolved is None: + check(target_component.get("distortion_ref") == ref, + f"{where}/{name}: distortion_ref changed for a preserved file") + check((v10_view / ref).read_bytes() == (v11_view / ref).read_bytes(), + f"{where}/{name}: preserved distortion {ref} differs") + consumed.add(ref) + return None + bundle_rel, keys, _ = resolved + check(target_component.get("distortion_ref") == bundle_rel + and target_component.get("distortion_valid_ref") == bundle_rel, + f"{where}/{name}: distortion refs must point at the camera bundle") + check(target_component.get("distortion_key") == keys + ["data"], + f"{where}/{name}: distortion_key mismatch") + check(target_component.get("distortion_valid_key") == keys + ["valid"], + f"{where}/{name}: distortion_valid_key mismatch") + + data = reader.get(v11_view, bundle_rel, keys + ["data"]) + valid = reader.get(v11_view, bundle_rel, keys + ["valid"]) + check(valid.dtype == torch.bool, f"{where}/{name}: distortion valid is not bool") + check(same_tensor(torch.load(v10_view / ref, map_location="cpu", weights_only=True), data), + f"{where}/{name}: distortion is not byte-identical") + + valid_ref = source_component.get("distortion_valid_ref") + if valid_ref: + check(same_tensor(torch.load(v10_view / valid_ref, map_location="cpu", + weights_only=True), valid), + f"{where}/{name}: distortion valid is not byte-identical") + consumed.add(valid_ref) + origin = f"source tensor {valid_ref}" + else: + # CONTRACT 3: with no validity of its own, the distortion vector either + # shares the owning component's validity or expands a declared all-known + # scalar. Both are checked against the source rather than re-asserted. + owner_valid_ref = source_component.get("valid_ref") + paired = (torch.load(v10_view / owner_valid_ref, map_location="cpu", weights_only=True) + if owner_valid_ref else None) + shared = (paired is not None and list(paired.shape) == list(valid.shape) + and same_tensor(paired, valid)) + check(shared or bool(valid.all()), + f"{where}/{name}: distortion validity matches neither the paired camera " + f"validity nor a declared all-known scalar") + origin = ("shared with intrinsic validity (CONTRACT 3)" if shared + else "expanded declared all-known scalar (CONTRACT 3)") + consumed.add(ref) + return { + "owner": f"{name}.distortion", "entry": f"{bundle_rel}:{'/'.join(keys)}", + "dtype": str(data.dtype), "shape": list(data.shape), + "valid_shape": list(valid.shape), + "valid_true": int(valid.sum()), "valid_false": int((~valid).sum()), + "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, + "valid_origin": origin, "byte_exact": True, + } + + +def same_bytes(left: Path, right: Path) -> tuple: + """``(same, how)`` for two paths: the same file, or the same bytes. + + Migration hardlinks media, so in the common case these are one inode and the + answer is structural. Re-reading a file to compare it with itself proves + nothing and costs the run, and on a published tree that read is most of the + acceptance time. ReInterHand's *local* tree has no media at all (the ``*.mkv`` + are deliberately outside the migration scope), so here the identity shortcut + almost never fires and nearly every shared file is settled by content -- cheap, + because the whole tree is ~2.7 GiB. When the inodes differ -- a tree that was + *copied* rather than linked -- the bytes are hashed in streams, so nothing is + assumed equal merely because the migration usually links. + + ``how`` travels into the report, so a reader can see which files were settled by + identity and which by content instead of having to trust that either ran. + """ + left_stat, right_stat = left.stat(), right.stat() + if (left_stat.st_dev, left_stat.st_ino) == (right_stat.st_dev, right_stat.st_ino): + return True, "same inode" + if left_stat.st_size != right_stat.st_size: + return False, "size differs" + return sha256_file(left) == sha256_file(right), "sha256" + + +def same_preserved(left: Path, right: Path) -> tuple: + """``(same, how)`` for a preserved file that may be *declared absent*. + + ReInterHand's local tree carries no ``*.mkv``: the media are 1.08 TB and were + deliberately left out of the migration scope, to be copied server-side at + publication time. A media ``data_ref`` is therefore missing from **both** + trees, and asking whether the two copies match has no answer -- ``same_bytes`` + raises ``FileNotFoundError`` on the first one. + + Absent on both sides is not a difference, it is the declared state: the claim + being verified is that the migration left the media exactly as absent as it + found them. Absent on *one* side only is a real failure and is reported as + such, because that would mean the migration dropped a file it should have + preserved (or invented one). + """ + if not left.exists() and not right.exists(): + return True, "declared absent (absent from both trees)" + if left.exists() != right.exists(): + return False, "present on only one side" + return same_bytes(left, right) + + +def verify_view(registry, v10_view, v11_view, reader): + """Run CONTRACT 6 checks for one view; return its evidence record.""" + where = f"{v10_view.parent.name}/{v10_view.name}" + source = json.loads((v10_view / "metainfo.json").read_text(encoding="utf-8")) + target = json.loads((v11_view / "metainfo.json").read_text(encoding="utf-8")) + compare_metainfo(source, target, v10_view.parent.name, v10_view.name, registry) + + consumed, fields, media = set(), [], [] + for name, component in source["components"].items(): + if not component.get("available", True): + continue + for owner, spec, kind in [(name, component, "component")] + [ + (f"{name}.{attribute}", attribute_spec, "attribute") + for attribute, attribute_spec in (component.get("attributes") or {}).items() + ]: + ref = spec.get("data_ref") + if not ref: + continue + resolved = registry.resolve(ref) + after = (target["components"][name] if kind == "component" + else target["components"][name]["attributes"][owner.split(".", 1)[1]]) + if resolved is None: + # preserved verbatim: same reference, same bytes + check(after.get("data_ref") == ref, f"{where}/{owner}: data_ref changed for a media file") + check("data_key" not in after, f"{where}/{owner}: media must not carry data_key") + same, how = same_preserved(v10_view / ref, v11_view / ref) + check(same, f"{where}/{owner}: preserved file {ref} differs") + valid_ref = spec.get("valid_ref") + valid_how = None + if valid_ref: + check(after.get("valid_ref") == valid_ref, + f"{where}/{owner}: media valid_ref changed") + check("valid_key" not in after, f"{where}/{owner}: media must not carry valid_key") + same, valid_how = same_preserved(v10_view / valid_ref, v11_view / valid_ref) + check(same, f"{where}/{owner}: preserved validity {valid_ref} differs") + media.append({"owner": owner, "data_ref": ref, "valid_ref": valid_ref, + "verified": how, "valid_verified": valid_how}) + continue + + bundle_rel, keys, entry = resolved + check(after["data_ref"] == bundle_rel and after["valid_ref"] == bundle_rel, + f"{where}/{owner}: bundled refs must be the same file") + check(after["data_key"] == keys + ["data"], f"{where}/{owner}: data_key mismatch") + check(after["valid_key"] == keys + ["valid"], f"{where}/{owner}: valid_key mismatch") + for key in ("storage", "valid_storage"): + check(after[key]["profile"] == "pt/tensor_bundle/v1", + f"{where}/{owner}: {key} profile must be pt/tensor_bundle/v1") + + data, valid = reader.field(v11_view, after) + check(valid.dtype == torch.bool, f"{where}/{owner}: valid is not bool") + if kind == "attribute": + check(after.get("valid_axes") == list(after["axes"])[:valid.ndim], + f"{where}/{owner}: valid_axes must be axes[:valid.ndim]") + check(after.get("valid_ref") == after.get("data_ref"), + f"{where}/{owner}: visibility must share one bundle file") + source_data = torch.load(v10_view / ref, map_location="cpu", weights_only=True) + check(same_tensor(source_data, data), f"{where}/{owner}: data is not byte-identical") + source_valid_ref = spec.get("valid_ref") + if source_valid_ref: + source_valid = torch.load(v10_view / source_valid_ref, + map_location="cpu", weights_only=True) + check(same_tensor(source_valid, valid), f"{where}/{owner}: valid is not byte-identical") + origin = f"source tensor {source_valid_ref}" + consumed.add(source_valid_ref) + else: + check(spec.get("valid") is True, + f"{where}/{owner}: no valid_ref and no declared all-known scalar") + check(bool(valid.all()), + f"{where}/{owner}: expanded all-known validity must be all true") + origin = "expanded declared all-known scalar" + consumed.add(ref) + fields.append({ + "owner": owner, "entry": f"{bundle_rel}:{'/'.join(keys)}", + "dtype": str(data.dtype), "shape": list(data.shape), + "valid_shape": list(valid.shape), + "valid_true": int(valid.sum()), "valid_false": int((~valid).sum()), + "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, + "valid_origin": origin, "byte_exact": True, + }) + distortion = verify_distortion(registry, v10_view, v11_view, reader, name, + component, target["components"][name], where, consumed) + if distortion is not None: + fields.append(distortion) + + # 1: no stray files, nothing lost + source_files = {p.relative_to(v10_view).as_posix() + for p in v10_view.rglob("*") if p.is_file()} + target_files = {p.relative_to(v11_view).as_posix() + for p in v11_view.rglob("*") if p.is_file()} + expected = (source_files - consumed - {"metainfo.json"}) | {"metainfo.json"} | { + f["entry"].split(":")[0] for f in fields} + check(target_files == expected, + f"{where}: file set mismatch; unexpected={sorted(target_files - expected)}, " + f"missing={sorted(expected - target_files)}") + strays = sorted(f for f in target_files if is_stray_validity(registry, f)) + check(not strays, f"{where}: merged numeric fields left standalone validity files: {strays}") + + return { + "sequence_id": v10_view.parent.name, "camera_id": v10_view.name, + "num_frames": source["num_frames"], + "source_files": len(source_files), "target_files": len(target_files), + "merged_fields": len(fields), "preserved_files": len(media), + "media_verified_by": {how: sum(1 for m in media if m["verified"] == how) + for how in sorted({m["verified"] for m in media})}, + "fields": fields, "media": media, + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--v10", type=Path, default=DATASET_ROOT / "shared-v1.0", + help="shared-v1.0 release directory") + parser.add_argument("--v11", type=Path, default=RELEASE_ROOT, + help="shared-v1.1 release directory") + parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json", + help="v1.1 schema.json") + parser.add_argument("--manifest", type=Path, default=MANIFEST_PATH, + help=f"write the v1.1 release manifest here (default: " + f"{MANIFEST_PATH}, outside the release tree)") + parser.add_argument("--report", type=Path, help="write the acceptance report here") + parser.add_argument("--sample", type=int, default=None, + help="verify at most N views (default: all migrated)") + parser.add_argument("--views", nargs="*", default=None, + help="restrict to these sequence ids") + parser.add_argument("--complete", action="store_true", + help="fail when a source view has no migrated counterpart") + parser.add_argument("--no-manifest", action="store_true", + help="skip regenerating the release manifest (CONTRACT 6.4). It " + "hashes every file of the tree regardless of --views, so an " + "incremental check while the pull is still running pays " + "minutes for a manifest the final run overwrites anyway. " + "The accepting run passes this as well: the manifest has to " + "be the last thing built, because it must cover this " + "release's own FULL_MIGRATION_SUMMARY.json and its rebuilt " + "doc/*.md, which are written after the acceptance -- " + "validate.py regenerates it at the end, so a manifest built " + "here would be overwritten unread. CONTRACT 6.4 asks that the " + "manifest be regenerated and correct, not that this tool be " + "the one to write it.") + args = parser.parse_args(argv) + + registry = Registry.load(args.schema) + reader = BundleReader() + source_views = sorted(p.parent for p in (args.v10 / "data").glob("*/*/metainfo.json")) + target_data = args.v11 / "data" + migrated, absent = [], [] + for view in source_views: + relative = view.relative_to(args.v10 / "data") + (migrated if (target_data / relative / "metainfo.json").is_file() else absent).append(view) + if args.views: + wanted = set(args.views) + migrated = [v for v in migrated if v.parent.name in wanted] + if args.sample: + migrated = migrated[:args.sample] + + report = {"source": str(args.v10.resolve()), "target": str(args.v11.resolve()), + "schema_sha256": sha256_file(args.schema), "views": [], "failures": [], + "views_in_source": len(source_views), "views_migrated": len(migrated), + "views_absent_from_target": [v.relative_to(args.v10 / "data").as_posix() + for v in absent]} + if args.complete: + for view in absent: + rel = view.relative_to(args.v10 / "data").as_posix() + report["failures"].append({"view": rel, "error": "view was not migrated"}) + print(f"FAIL {rel}: view was not migrated", file=sys.stderr) + for view in migrated: + relative = view.relative_to(args.v10 / "data") + target_view = target_data / relative + try: + report["views"].append(verify_view(registry, view, target_view, reader)) + except Failure as error: + report["failures"].append({"view": relative.as_posix(), "error": str(error)}) + print(f"FAIL {relative}: {error}", file=sys.stderr) + + # 4: regenerated release manifest + if args.no_manifest: + #: reported as skipped, not as "0 files" -- an empty manifest in the report + #: would read like a tree with nothing in it + report["manifest"] = {"skipped": "incremental check; not an acceptance run"} + else: + manifest = {} + #: The manifest normally lives outside the release (see MANIFEST_PATH), so it + #: is not part of the tree being hashed and there is nothing to exclude. Only + #: a ``--manifest`` pointed *into* the release has to be skipped: it cannot hash + #: itself without recording the digest it is about to have. + try: + manifest_rel = args.manifest.relative_to(args.v11).as_posix() + except ValueError: + manifest_rel = None + for path in sorted(args.v11.rglob("*")): + rel = path.relative_to(args.v11).as_posix() + if "__pycache__" in path.parts or rel == manifest_rel: + continue + if path.is_file(): + manifest[rel] = {"size": path.stat().st_size, "sha256": sha256_file(path)} + report["manifest"] = {"files": len(manifest), + "bytes": sum(v["size"] for v in manifest.values()), + "excludes": [x for x in (manifest_rel, "__pycache__/") if x]} + if args.manifest: + args.manifest.parent.mkdir(parents=True, exist_ok=True) + args.manifest.write_text( + json.dumps({"release": "shared-v1.1", + "location": str(args.manifest), + "in_release_tree": manifest_rel is not None, + "files": manifest}, + ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + report["passed"] = not report["failures"] + report["scope"] = ("repackaging numerically identical; this is not human visual acceptance") + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8") + + total_fields = sum(v["merged_fields"] for v in report["views"]) + media_modes = {} + for view in report["views"]: + for mode, count in view["media_verified_by"].items(): + media_modes[mode] = media_modes.get(mode, 0) + count + print(f"views={len(report['views'])} merged_fields={total_fields} " + f"failures={len(report['failures'])} " + + (f"manifest_files={report['manifest']['files']}" + if "files" in report["manifest"] else "manifest=skipped") + + f" media_verified_by={media_modes}") + print("ACCEPTANCE_PASS" if report["passed"] else "ACCEPTANCE_FAIL") + return 0 if report["passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/reinterhand_v1_1/warehouse.py b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/warehouse.py new file mode 100644 index 0000000000000000000000000000000000000000..01335de7742478a19d5ce5563bff6372f2446f53 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/reinterhand_v1_1/warehouse.py @@ -0,0 +1,254 @@ +"""hand-warehouse v1.1 tensor-bundle layout: resolution, writing, cached reading. + +The v1.1 registry (`doc/schema.json`) is declarative; its own `note` says runtime +readers/converters/validators still require adaptation. This module is that +adaptation for the parts every dataset shares: + +* ``Registry.resolve()`` v1.0 ``data_ref`` -> (bundle file, entry key path) +* ``BundleWriter`` builds one nested ``{"data": Tensor, "valid": Bool}`` tree +* ``BundleReader`` loads a bundle once, then fetches fields by key +* ``expanded_all_known()`` CONTRACT 3 expansion of a declared all-known scalar + +Section references are to ``doc/CONTRACT.md`` (hand-warehouse/1.1). +""" + +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path, PurePosixPath + +import torch + +SCHEMA_VERSION = "hand-warehouse/1.1" +RELEASE_ID = "shared-v1.1" +BUNDLE_PROFILE = "pt/tensor_bundle/v1" +DATA_TERMINAL = "data" +VALID_TERMINAL = "valid" + +#: CONTRACT 3: axes declared on the three visibility scopes. +VISIBILITY_AXES = { + ("T", "hand", "joint"): "hand_keypoint", + ("T", "hand"): "whole_hand", + ("T",): "object", +} + + +def _parts(value: str): + return PurePosixPath(value).parts + + +def _is_wildcard(segment: str) -> bool: + """A registry template segment is a wildcard when it carries a placeholder. + + Covers both ```` and the composite ``__`` + (CONTRACT 4 contact pairs). + """ + return "<" in segment and ">" in segment + + +def _entry_key(segment: str) -> str: + """``pose.pt`` -> ``pose``; ``parts`` -> ``parts`` (CONTRACT 4: keys, not paths).""" + return segment[:-3] if segment.endswith(".pt") else segment + + +class Registry: + """Read-only view over the declarative v1.1 registry.""" + + def __init__(self, schema: dict): + if schema.get("schema_version") != SCHEMA_VERSION: + raise ValueError(f"not a {SCHEMA_VERSION} registry: {schema.get('schema_version')!r}") + self.schema = schema + self.bundles = schema["tensor_bundles"] + self.components = schema["components"] + self.visibility_scopes = schema["tensor_attributes"]["visibility"]["scopes"] + + @classmethod + def load(cls, path) -> "Registry": + return cls(json.loads(Path(path).read_text(encoding="utf-8"))) + + # -- v1.0 reference -> v1.1 bundle entry -------------------------------- + + def resolve(self, data_ref: str): + """Map a numeric ``data_ref`` to ``(bundle_path, keys, entry_spec)``. + + Returns ``None`` for anything the contract keeps out of bundles: media, + JSONL, mesh/asset files, ``frames.jsonl``, ``metainfo.json``, + ``articulation.json``. The bundle's own entry table decides -- an + unmatched entry is never merged, so no path is guessed into a bundle. + """ + ref = _parts(data_ref) + for bundle in self.bundles.values(): + template = _parts(bundle["path"]) + dir_template, filename = template[:-1], template[-1] + if len(ref) <= len(dir_template): + continue + bound, matched = {}, True + for want, got in zip(dir_template, ref): + if _is_wildcard(want): + bound[want] = got + elif want != got: + matched = False + break + if not matched: + continue + keys = [_entry_key(segment) for segment in ref[len(dir_template):]] + spec = self._entry_spec(bundle, keys) + if spec is None: + continue + directory = [bound.get(segment, segment) for segment in dir_template] + return "/".join(directory + [filename]), keys, spec + return None + + @staticmethod + def _entry_spec(bundle: dict, keys: list): + for name, spec in bundle["entries"].items(): + template = name.split("/") + if len(template) != len(keys): + continue + if all(_is_wildcard(w) or w == k for w, k in zip(template, keys)): + return spec + return None + + def valid_shape_template(self, schema_id: str): + spec = self.components.get(schema_id) + if spec is None: + raise KeyError(f"schema_id {schema_id!r} is not registered") + return spec.get("valid_shape") + + def visibility_valid_shape(self, axes): + scope = VISIBILITY_AXES.get(tuple(axes)) + if scope is None: + raise ValueError(f"visibility axes {list(axes)} match no declared scope") + return self.visibility_scopes[scope]["valid_shape"] + + +def expanded_all_known(data: torch.Tensor, valid_shape) -> torch.Tensor: + """CONTRACT 3: explicit all-true bool tensor of the field's ``valid_shape``. + + Symbolic dims resolve positionally against the data tensor, so the result + restates the source's declared all-known validity -- it is never inferred + from values or from a pose validity (``tensor_attributes.visibility``). + """ + if valid_shape is None: + raise ValueError("field declares no valid_shape; cannot expand all-known validity") + if len(valid_shape) > data.ndim: + raise ValueError(f"valid_shape {list(valid_shape)} exceeds data rank {data.ndim}") + dims = [] + for axis, dim in enumerate(valid_shape): + dims.append(data.shape[axis] if isinstance(dim, str) else int(dim)) + return torch.ones(dims, dtype=torch.bool) + + +class BundleWriter: + """Accumulates one bundle's tree, then replaces the file atomically.""" + + def __init__(self, view_root, rel_path: str): + self.view_root = Path(view_root) + self.rel_path = rel_path + self.tree: dict = {} + + def put(self, keys, data: torch.Tensor, valid: torch.Tensor): + if not keys: + raise ValueError("empty key path") + if not isinstance(data, torch.Tensor) or not isinstance(valid, torch.Tensor): + raise TypeError(f"{'/'.join(keys)}: data and valid must both be Tensors") + if valid.dtype != torch.bool: + raise TypeError(f"{'/'.join(keys)}: valid must be a bool Tensor, got {valid.dtype}") + node = self.tree + for key in keys[:-1]: + node = node.setdefault(key, {}) + if not isinstance(node, dict): + raise TypeError(f"{'/'.join(keys)}: {key!r} already holds a leaf") + leaf = "/".join(keys) + if keys[-1] in node: + raise ValueError(f"duplicate field {leaf}") + node[keys[-1]] = {DATA_TERMINAL: data, VALID_TERMINAL: valid} + return leaf + + def save(self): + """Write to a sibling temp file, fsync, then ``os.replace`` (MIGRATION 4.3).""" + if not self.tree: + return None # bundle_layout_rules.omit_empty_bundles + path = self.view_root / self.rel_path + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_name(path.name + ".hw11-tmp") + torch.save(self.tree, temp) + fd = os.open(temp, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + os.replace(temp, path) + return path + + +class BundleReader: + """Reader cache required by ``reference_rules.reader_cache``.""" + + def __init__(self): + self._cache: dict = {} + + def bundle(self, view_root, rel_path: str): + key = (str(Path(view_root).resolve()), rel_path) + if key not in self._cache: + path = Path(view_root) / rel_path + if not path.is_file(): + raise FileNotFoundError(f"bundle {rel_path} not found in {view_root}") + self._cache[key] = torch.load(path, map_location="cpu", weights_only=True) + return self._cache[key] + + def get(self, view_root, rel_path: str, keys): + if not isinstance(keys, list) or not keys: + raise TypeError(f"{rel_path}: data_key/valid_key must be a non-empty list") + node = self.bundle(view_root, rel_path) + for depth, key in enumerate(keys): + if not isinstance(node, dict): + raise KeyError(f"{rel_path}: {'/'.join(keys[:depth])} is a leaf, not a dict") + if key not in node: + raise KeyError(f"{rel_path}: missing key {key!r} on path {'/'.join(keys)}") + node = node[key] + return node + + def field(self, view_root, component: dict): + """Fetch ``(data, valid)`` for a registered bundle component.""" + for required in ("data_ref", "data_key", "valid_ref", "valid_key"): + if required not in component: + raise KeyError(f"component is missing {required!r}") + data = self.get(view_root, component["data_ref"], component["data_key"]) + valid = self.get(view_root, component["valid_ref"], component["valid_key"]) + if not isinstance(data, torch.Tensor): + raise TypeError(f"{component['data_ref']}: data is {type(data).__name__}, not a Tensor") + if not isinstance(valid, torch.Tensor) or valid.dtype != torch.bool: + raise TypeError(f"{component['valid_ref']}: valid must be a bool Tensor") + return data, valid + + +def raw_bytes(tensor: torch.Tensor) -> bytes: + """Unified contiguous byte view (CONTRACT 6.2), NaN bit patterns included.""" + tensor = tensor.detach().cpu().contiguous() + try: + return tensor.numpy().tobytes() + except (TypeError, RuntimeError): + return tensor.view(torch.uint8).numpy().tobytes() + + +def same_tensor(left: torch.Tensor, right: torch.Tensor) -> bool: + return ( + left.dtype == right.dtype + and tuple(left.shape) == tuple(right.shape) + and raw_bytes(left) == raw_bytes(right) + ) + + +def sha256_file(path, block: int = 8 << 20) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(block), b""): + digest.update(chunk) + return digest.hexdigest() + + +def sha256_bytes(payload: bytes) -> str: + return hashlib.sha256(payload).hexdigest() \ No newline at end of file diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md b/ReInterHand/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..e80d21a1c4af1bfaa2f429b3395a4304e6af6eb0 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md @@ -0,0 +1,459 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +shared 层不是 raw 的完整镜像。处理者只需提取本次任务范围明确要求、语义已经核实且能够按本规范可靠转换的字段和模态。raw 中其余字段可以不纳入 shared,但必须在 `RAW_TO_SHARED.md` 中列出主要未纳入内容及原因。不得为了覆盖全部 raw 字段而猜测语义、虚构模态或保存未经定义的字段。未纳入 shared 不等于源数据不存在,原始信息仍以 raw 为准。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 必填,固定为 `ego/exo/unknown`。源数据或采集设置明确相机视角时必须填写 `ego` 或 `exo`;只有无法从可信来源确定时才填写 `unknown`,不得省略或主观猜测。多相机序列须逐视图分别填写。 | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/doc/schema.json b/ReInterHand/shared-v1.1/script/v1_0_snapshot/doc/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..edb7cf7ce8e8e282d1fbfb5b39ef02a60321d2fb --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/doc/schema.json @@ -0,0 +1,880 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "view_metadata": { + "required_fields": [ + "view_type" + ], + "view_type_values": [ + "ego", + "exo", + "unknown" + ], + "view_type_policy": "required per camera view; use ego or exo whenever the source data or capture setup establishes the viewpoint; use unknown only when no trustworthy source determines it; never omit or guess" + }, + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/README.md b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f1622b05af6dff6975bdeb8dc3ea06efdbc54a3a --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/README.md @@ -0,0 +1,91 @@ +# ReInterHand shared-v1.0 — reproduction and review + +Use Python 3.12 on Linux (the archived production converters use POSIX locks, +symlinks and archive streaming). No GPU is required. Two dataset workers and +two FFmpeg threads per worker are the production limits; numerical libraries +are limited to one thread by `run.py`. Leave at least 400 GB free. + +## Install + +Create a Python 3.12 virtual environment **outside** shared-v1.0: + +```sh +python3.12 -m venv ../runtime-env +. ../runtime-env/bin/activate +python -m pip install -r script/requirements-lock.txt +ffmpeg -version +ffprobe -version +``` + +Install FFmpeg/ffprobe separately (production ReInterHand used FFmpeg 6.1.1). +The package lock records direct Python dependencies, not a full OS image. +Acquire MANO v1.2 LEFT/RIGHT pickle files under the MANO license; they are not +redistributed here. Put them in the `models` directory in `script/config.json`. +For ReInterHand that directory must be `/models`. Install dependencies +in the activated environment; the optional `packages` path allows reuse of +the existing server installation. It may point to a nonexistent directory +when using the virtual environment. Paths in config are relative to the dataset +root (the parent of shared-v1.0), or may be absolute. Place raw at `/raw`. + +## Commands (from shared-v1.0) + +```sh +python script/run.py checksums +python script/run.py preflight +python script/run.py inventory +python script/run.py validate +python script/run.py validate --tensors +python script/run.py validate --tensors --media +python script/run.py review +``` + +`validate` reads every view's metadata, declared references and complete frame +mapping. `--tensors` also loads component data/valid tensors, checks T, dtype, +finite valid values and camera rotations. `--media` decodes all MKV streams +to count frames and check dimensions; it can take many hours. Neither mode +claims source pixel equivalence or independent official digest verification. +For machine reports use `python script/validate_release.py --output ../tmp/check`. + +`review` reads the current data and writes a new fixed-seed complete-sequence +review to config `review_output`; an existing output is rejected to preserve +earlier review evidence. New reports start pending and require new human review. + +## Reproduce conversion in a fresh root + +Copy this script directory into a fresh `/shared-v1.0/script`, configure +the models and put the verified raw at `/raw`. Pilot and production +should use separate output roots. After explicit pilot approval: + +```sh +python script/run.py pilot --sequence '' --segment +python script/run.py full +``` + +The safe handoff entry refuses conversion into a populated data directory. +For an interrupted run, investigate first, retain its tmp checkpoints and use +the archived converter directly with the same arguments, input, script and +configuration. Do not remove locks without checking the actual process. +ReInterHand historical checkpoints do not bind every script/input change; +do not reuse them after changing converter logic. Existing production data +was not reconverted during this documentation repair. + +## File responsibilities + +- `run.py`: simple release-local CLI, config loading, CPU limits and guards. +- `config.json`: paths, resources, deterministic review seed and optional partition. +- `preprocess_*.py`: archived dataset conversion implementation; retained filenames + preserve imports and production provenance. +- `validate_release.py`: independently rereads final files; no data writes. +- `render_*`: full-sequence review renderers, called by `run.py review`. +- `requirements-lock.txt`: pinned direct Python dependencies. +- `checksums.json`: all formal script file SHA256 values, excluding itself. +- `history/`: already-applied one-time repairs; never part of normal execution. + +Publication is deliberately external to this reproduction bundle. This repair +has no upload command and no upload authorization. Existing fixed-commit +verification evidence is in `../doc/validation/publication/`; a future release +must get authorization and create a new manifest before publication. +Raw is read-only. Scratch, logs, locks and model files stay outside shared-v1.0. +See `../doc/RAW_MAPPING.md` for time semantics, splits and modality mappings. + +For distributed reproduction, set captures_file to captures-iipl100.txt or captures-iipl126.txt, never both on one worker. The two lists are disjoint and cover all 10 captures. Set partition to the matching label for sampling. diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/captures-iipl100.txt b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/captures-iipl100.txt new file mode 100644 index 0000000000000000000000000000000000000000..ae1b4cb27bd1f6ea010383df978dc2dcf14fa40a --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/captures-iipl100.txt @@ -0,0 +1,5 @@ +m--20221007--1215--HIR112--pilot--ProjectGoliathScript--Hands--two-hands +m--20221111--0944--JFQ550--pilot--ProjectGoliathScript--Hands--two-hands +m--20221215--0949--RNS217--pilot--ProjectGoliathScript--Hands--two-hands +m--20221216--0953--NKC880--pilot--ProjectGoliathScript--Hands--two-hands +m--20230317--1433--TRO760--pilot--ProjectGoliath--Hands--two-hands diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/captures-iipl126.txt b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/captures-iipl126.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbd4838f63b69d22b5a5dd07ec15fbaf2fcc7813 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/captures-iipl126.txt @@ -0,0 +1,5 @@ +m--20210701--1058--0000000--pilot--relightablehandsy--participant0--two-hands +m--20220628--1327--BKS383--pilot--ProjectGoliath--ContinuousHandsy--two-hands +m--20221110--1033--TQH976--pilot--ProjectGoliathScript--Hands--two-hands +m--20230313--1433--TXB805--pilot--ProjectGoliath--Hands--two-hands +m--20230317--1130--QZX685--pilot--ProjectGoliath--Hands--two-hands diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/checksums.json b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/checksums.json new file mode 100644 index 0000000000000000000000000000000000000000..dcef7a0f3e868d18bf8c00b736d5a23424ee4d2e --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/checksums.json @@ -0,0 +1,14 @@ +{ + "README.md": "aad70e9784b981716426d875ec6cf45acc4fa3edd809ac8360b42abd879e5134", + "captures-iipl100.txt": "6ee17a2883335d71d67dc2f008a556bb975d2be7f9fce6f30aa9889c5b8ee105", + "captures-iipl126.txt": "788c05733087bbdf0f744828bb576ce986573269bd50ebb17fa7cbef66757bf7", + "config.json": "0f28fa80fc53a93d1b6eb9b3ee95b74f80cf6783e80d38335a4feb004d5d1b9f", + "history/README.md": "a73a1d97e8b50a6b20b1c2053ac19f1a2d910887c886ca5e6b163eb3def22d66", + "history/fix_reinterhand_full_metadata.py": "4bb2714dc23f99f90682a3c22125438190bd97bf426c38555eff827bda2727c1", + "preprocess_reinterhand.py": "a2c3b33a5ec407192ba53e18c39892686fe252722db414c91c817e6b1ad13d05", + "preprocess_reinterhand_full.py": "71ba51096097dcdffbdf88ab9f3f08c6ff17a63aa5252187586129034209e4f5", + "render_reinterhand_full_random.py": "9e849867c457fa0d1c5920434e33ef58b54bf4c8ad4926996ab488b7af237875", + "requirements-lock.txt": "dd41c8ddb00334f4b03ac76ee17a5c2b842eba00ae0666430f4f04c79127e31d", + "run.py": "b3946952a6075286199f19e6c29719b1b5d763739afea01db6befd5aa267dec5", + "validate_release.py": "5fd33342a3c0da33e5ea758dbd17ad3ae7320980ec7f65cf8233fc715f008f92" +} diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/config.json b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a9a8e6e1281ec26570c4c613651d0431ecde3112 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/config.json @@ -0,0 +1,12 @@ +{ + "dataset": "ReInterHand", + "packages": "tmp/runtime-v1.0/site", + "runtime": "tmp/runtime-v1.0", + "models": "tmp/runtime-v1.0/models", + "workers": 2, + "minimum_free_bytes": 400000000000, + "seed": 20260927, + "partition": "iipl_126", + "captures_file": "captures-iipl126.txt", + "review_output": "tmp/review-new" +} diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/history/README.md b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/history/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7d3e05db9243084d66e4621bc6c48b48b5f7faff --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/history/README.md @@ -0,0 +1 @@ +Historical one-time corrections, already applied to this release. Do not run these as pipeline stages. The normal converter contains the corrected behavior. Kept for provenance only. diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/history/fix_reinterhand_full_metadata.py b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/history/fix_reinterhand_full_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..9a65fa3612d3248ce2bc1e79a0480f12e3b19703 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/history/fix_reinterhand_full_metadata.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Remove pilot-only flags accidentally inherited by ReInterHand full output.""" + +from __future__ import annotations + +import argparse +import json +import os +from datetime import datetime, timezone +from pathlib import Path + + +def atomic_json(path: Path, value: object) -> None: + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8") + os.replace(temporary, path) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--receipt", required=True) + args = parser.parse_args() + root = Path(args.root).resolve() + release = root / "shared-v1.0" + changed = unchanged = 0 + sequences: set[str] = set() + cameras: set[str] = set() + for path in sorted((release / "data").glob("*/*/metainfo.json")): + value = json.loads(path.read_text(encoding="utf-8")) + if value.get("dataset_id") != "ReInterHand": + raise RuntimeError(f"unexpected dataset_id: {path}") + before = json.dumps(value, sort_keys=True) + for key in ("pilot", "pilot_complete", "pilot_human_review"): + value.pop(key, None) + value["conversion_scope"] = "full" + value["full_conversion_complete"] = True + value["full_output_human_review"] = "pending" + value["upload_authorized"] = False + after = json.dumps(value, sort_keys=True) + if before != after: + atomic_json(path, value) + changed += 1 + else: + unchanged += 1 + sequences.add(value["sequence_id"]) + cameras.add(str(value["camera_id"])) + receipt = { + "schema": "reinterhand-full-metadata-repair/v1", + "completed_at": datetime.now(timezone.utc).isoformat(), + "changed_views": changed, + "unchanged_views": unchanged, + "sequence_count": len(sequences), + "distinct_camera_ids": len(cameras), + "removed_fields": ["pilot", "pilot_complete", "pilot_human_review"], + "set_fields": { + "conversion_scope": "full", + "full_conversion_complete": True, + "full_output_human_review": "pending", + "upload_authorized": False, + }, + "media_modified": False, + } + atomic_json(Path(args.receipt).resolve(), receipt) + print(json.dumps(receipt, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/preprocess_reinterhand.py b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/preprocess_reinterhand.py new file mode 100644 index 0000000000000000000000000000000000000000..a432e14afcc7931262bee3646d47726a0112a589 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/preprocess_reinterhand.py @@ -0,0 +1,1458 @@ +"""ReInterHand hand-warehouse/1.0 preprocessing entry point. + +The first implemented stage extracts one complete named sequence from the +already verified split archives. Raw archives are opened read-only and are +never joined, renamed, or modified. Later conversion and validation stages +consume this deterministic extraction manifest. + +Example: + python preprocess_reinterhand.py extract-pilot \ + --root /data2/shaoyunzhe/hand-datasets/ReInterHand +""" + +from __future__ import annotations + +import argparse +import codecs +import collections +import hashlib +import io +import json +import os +from pathlib import Path, PurePosixPath +import pickle +import shutil +import subprocess +import sys +import tarfile +from datetime import datetime, timezone +from types import SimpleNamespace + + +CAPTURE = "m--20221110--1033--TQH976--pilot--ProjectGoliathScript--Hands--two-hands" +SEGMENT = "DOU_finger_occlusions" +INTERWILD_SPLIT_REVISION = "7c01e4ad4909652056a68af93b4c16ceabbce8fe" +INTERWILD_TEST_CAPTURES = { + "m--20221215--0949--RNS217--pilot--ProjectGoliathScript--Hands--two-hands", + "m--20221216--0953--NKC880--pilot--ProjectGoliathScript--Hands--two-hands", + "m--20230317--1130--QZX685--pilot--ProjectGoliath--Hands--two-hands", +} + + +def official_split_metadata(capture: str) -> dict: + """Return the capture-level split fixed by the official InterWild loader.""" + return { + "split": "test" if capture in INTERWILD_TEST_CAPTURES else "train", + "split_scheme": "InterWild_official_capture_split", + "split_source_locator": { + "url": ( + "https://github.com/facebookresearch/InterWild/blob/" + f"{INTERWILD_SPLIT_REVISION}/data/ReInterHand/ReInterHand.py" + ), + "capture_id": capture, + }, + } + + +def now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + ".tmp") + temporary.write_text(json.dumps(value, indent=2, sort_keys=True), encoding="utf-8") + os.replace(temporary, path) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def canonical_parts(folder: Path, prefix: str) -> list[Path]: + # Canonical archive parts end with exactly two lowercase letters. This + # intentionally excludes downloaded duplicate names such as .gzaa.1. + parts = sorted( + path + for path in folder.glob(prefix + "??") + if len(path.name) == len(prefix) + 2 and path.name[-2:].islower() + ) + if not parts: + raise FileNotFoundError(f"No canonical parts for {folder / (prefix + '??')}") + return parts + + +def safe_output(base: Path, member_name: str) -> Path: + member = PurePosixPath(member_name) + if member.is_absolute() or ".." in member.parts: + raise RuntimeError(f"Unsafe archive member: {member_name}") + output = base.joinpath(*member.parts) + if not output.resolve().is_relative_to(base.resolve()): + raise RuntimeError(f"Archive member escapes extraction root: {member_name}") + return output + + +def wanted(group: str, member_name: str, frame_tokens: set[str]) -> bool: + path = PurePosixPath(member_name) + if not path.name: + return False + stem = path.stem + normalized = stem.rsplit("_", 1)[0] if group == "mano_fits" else stem + if normalized.isdigit(): + normalized = str(int(normalized)) + selected = normalized in frame_tokens + if group == "Ego_cameras": + return selected and path.suffix.lower() in {".png", ".json"} or path.name == "truncation_ratio.json" + if group == "Mugsy_cameras": + return selected and path.suffix.lower() == ".png" + if group == "mano_fits": + return selected and path.suffix.lower() in {".json", ".obj", ".ply"} + raise ValueError(group) + + +def extract_archive( + group: str, + parts: list[Path], + output_root: Path, + frame_tokens: set[str], + status_path: Path, + status: dict, +) -> list[dict]: + destination = output_root / group + destination.mkdir(parents=True, exist_ok=True) + process = subprocess.Popen(["cat", *map(str, parts)], stdout=subprocess.PIPE) + assert process.stdout is not None + records: list[dict] = [] + scanned = 0 + try: + with tarfile.open(fileobj=process.stdout, mode="r|gz") as archive: + for member in archive: + if not member.isfile(): + continue + scanned += 1 + if not wanted(group, member.name, frame_tokens): + continue + output = safe_output(destination, member.name) + output.parent.mkdir(parents=True, exist_ok=True) + source = archive.extractfile(member) + if source is None: + raise RuntimeError(f"Cannot read selected member: {member.name}") + with source, output.open("wb") as target: + shutil.copyfileobj(source, target, length=8 * 1024 * 1024) + if output.stat().st_size != member.size: + raise RuntimeError(f"Size mismatch after extraction: {member.name}") + records.append( + { + "group": group, + "member": member.name, + "bytes": member.size, + "sha256": sha256(output), + "output": output.relative_to(output_root).as_posix(), + } + ) + status.update(updated_at=now(), active_group=group, members_scanned=scanned, selected_files=len(records)) + atomic_json(status_path, status) + finally: + process.stdout.close() + return_code = process.wait() + if return_code != 0: + raise RuntimeError(f"cat failed for {group}: exit {return_code}") + status.update(updated_at=now(), active_group=group, members_scanned=scanned, selected_files=len(records)) + atomic_json(status_path, status) + return records + + +def frame_ids(capture_root: Path, segment: str) -> list[int]: + rows = [line.split() for line in (capture_root / "frame_list.txt").read_text(encoding="utf-8").splitlines()] + result = [int(row[1]) for row in rows if len(row) >= 2 and row[0] == segment] + if not result or len(result) != len(set(result)) or result != sorted(result): + raise RuntimeError(f"Invalid or empty frame list for {segment}") + return result + + +def validate_extraction(output_root: Path, ids: list[int]) -> dict: + expected = {str(value) for value in ids} + images: dict[str, set[str]] = {} + for path in output_root.rglob("*.png"): + if "images" not in path.parts: + continue + stem = path.stem + if not stem.isdigit() or str(int(stem)) not in expected: + continue + relative = path.relative_to(output_root).parts + image_index = relative.index("images") + camera = "/".join(relative[: image_index + 1]) + if len(relative) > image_index + 2: + camera += "/" + "/".join(relative[image_index + 1 : -1]) + images.setdefault(camera, set()).add(str(int(stem))) + incomplete = {camera: sorted(expected - found, key=int) for camera, found in images.items() if found != expected} + mano = {"left": set(), "right": set()} + for path in (output_root / "mano_fits").rglob("*.json"): + for side in mano: + suffix = "_" + side + if path.stem.endswith(suffix) and path.stem[: -len(suffix)].isdigit(): + mano[side].add(str(int(path.stem[: -len(suffix)]))) + missing_mano = {side: sorted(expected - found, key=int) for side, found in mano.items() if found != expected} + if not images or incomplete or missing_mano: + raise RuntimeError( + "Pilot extraction coverage failed: " + + json.dumps({"cameras": sorted(images), "incomplete": incomplete, "missing_mano": missing_mano}) + ) + return { + "camera_count": len(images), + "camera_frames": {camera: len(found) for camera, found in sorted(images.items())}, + "mano_frames": {side: len(found) for side, found in mano.items()}, + } + + +def extract_pilot(root: Path, capture: str, segment: str) -> None: + capture_root = root / "raw" / "data" / capture + ids = frame_ids(capture_root, segment) + state = root / "tmp" / "pilot-v1.0" + output = state / "extracted" / f"{capture}__{segment}" + status_path = state / "status.json" + status = { + "schema": "reinterhand-pilot-status/v1", + "phase": "extracting", + "capture": capture, + "segment": segment, + "frames": len(ids), + "started_at": now(), + "updated_at": now(), + } + atomic_json(status_path, status) + sources = { + "Ego_cameras": canonical_parts(capture_root / "Ego_cameras", "envmap_per_segment.tar.gz"), + "Mugsy_cameras": canonical_parts(capture_root / "Mugsy_cameras", "envmap_per_segment.tar.gz"), + "mano_fits": canonical_parts(capture_root / "mano_fits", "mano_fits.tar.gz"), + } + records: list[dict] = [] + try: + for group, parts in sources.items(): + records.extend(extract_archive(group, parts, output, {str(value) for value in ids}, status_path, status)) + mugsy_camera = capture_root / "Mugsy_cameras" / "cam_params.json" + mugsy_target = output / "Mugsy_cameras" / "cam_params.json" + mugsy_target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(mugsy_camera, mugsy_target) + records.append( + { + "group": "Mugsy_cameras", + "member": "cam_params.json", + "bytes": mugsy_target.stat().st_size, + "sha256": sha256(mugsy_target), + "output": mugsy_target.relative_to(output).as_posix(), + } + ) + coverage = validate_extraction(output, ids) + manifest = { + "schema": "reinterhand-pilot-extraction/v1", + "capture": capture, + "segment": segment, + "source_frame_ids": ids, + "timestamp_policy": "unknown; preserve source_frame_id and sync_id, do not infer FPS", + "raw_read_only": True, + "source_archives": { + group: [{"path": path.relative_to(root).as_posix(), "bytes": path.stat().st_size} for path in parts] + for group, parts in sources.items() + }, + "coverage": coverage, + "files": records, + "completed_at": now(), + } + atomic_json(state / "extraction-manifest.json", manifest) + status.update(phase="extracted", updated_at=now(), files=len(records), coverage=coverage) + atomic_json(status_path, status) + except Exception as exc: + status.update(phase="failed", updated_at=now(), error_type=type(exc).__name__, error=str(exc)) + atomic_json(status_path, status) + raise + + +def extract_background_variant(root: Path, capture: str, segment: str, variant: str) -> None: + """Add one released RGB/background variant to the same read-only pilot extraction.""" + if variant not in {"envmap_per_frame", "envmap_per_segment"}: + raise ValueError(variant) + capture_root = root / "raw" / "data" / capture + ids = frame_ids(capture_root, segment) + state = root / "tmp" / "pilot-v1.0" + output = state / "extracted" / f"{capture}__{segment}" + status_path = state / "status.json" + status = json.loads(status_path.read_text(encoding="utf-8")) + status.update(phase="extracting_background_variant", variant=variant, updated_at=now()) + atomic_json(status_path, status) + sources = { + "Ego_cameras": canonical_parts(capture_root / "Ego_cameras", variant + ".tar.gz"), + "Mugsy_cameras": canonical_parts(capture_root / "Mugsy_cameras", variant + ".tar.gz"), + } + records: list[dict] = [] + for group, parts in sources.items(): + records.extend(extract_archive(group, parts, output, {str(value) for value in ids}, status_path, status)) + coverage = validate_extraction(output, ids) + manifest_path = state / "extraction-manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest.setdefault("background_variants", {})[variant] = { + "source_archives": { + group: [{"path": path.relative_to(root).as_posix(), "bytes": path.stat().st_size} for path in parts] + for group, parts in sources.items() + }, + "files": records, + "completed_at": now(), + } + manifest["coverage"] = coverage + atomic_json(manifest_path, manifest) + status.update(phase="background_variant_extracted", variant=variant, coverage=coverage, + selected_files=len(records), updated_at=now()) + atomic_json(status_path, status) + + +def runtime_imports(runtime: Path): + sys.path.insert(0, str(runtime / "site")) + import cv2 + import numpy as np + from PIL import Image + import smplx + import torch + + return np, torch, cv2, Image, smplx + + +class StoredState: + def __setstate__(self, state): + self.__dict__.update(state) + + +def model_reader_class(np, torch): + class Restricted(pickle.Unpickler): + def find_class(self, module, name): + allowed = { + ("numpy.core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, + ("numpy._core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, + ("numpy", "ndarray"): np.ndarray, + ("numpy", "dtype"): np.dtype, + ("numpy.core.numeric", "_frombuffer"): np.core.numeric._frombuffer, + ("numpy._core.numeric", "_frombuffer"): np.core.numeric._frombuffer, + ("_codecs", "encode"): codecs.encode, + ("collections", "OrderedDict"): collections.OrderedDict, + ("torch._utils", "_rebuild_tensor_v2"): torch._utils._rebuild_tensor_v2, + ("torch.storage", "_load_from_bytes"): lambda value: torch.load( + io.BytesIO(value), map_location="cpu", weights_only=True + ), + } + special = { + ("chumpy.ch", "Ch"): StoredState, + ("chumpy.reordering", "Select"): StoredState, + ("scipy.sparse.csc", "csc_matrix"): StoredState, + ("__builtin__", "set"): set, + } + if (module, name) in special: + return special[(module, name)] + if (module, name) not in allowed: + raise pickle.UnpicklingError(f"Unsupported model class: {module}.{name}") + return allowed[(module, name)] + + return Restricted + + +def model_data(model_path: Path, np, torch) -> dict: + Reader = model_reader_class(np, torch) + with model_path.open("rb") as stream: + data = Reader(stream, encoding="latin1").load() + shapedirs = data["shapedirs"] + if isinstance(shapedirs, StoredState): + data["shapedirs"] = shapedirs.a.x.reshape(-1)[shapedirs.idxs].reshape(shapedirs.preferred_shape) + sparse = data["J_regressor"] + if isinstance(sparse, StoredState): + dense = np.zeros(sparse._shape) + for column in range(sparse._shape[1]): + begin, end = sparse.indptr[column : column + 2] + dense[sparse.indices[begin:end], column] = sparse.data[begin:end] + data["J_regressor"] = dense + if data["shapedirs"].shape != (778, 3, 10) or data["J_regressor"].shape != (16, 778): + raise RuntimeError("Unexpected MANO model dimensions") + return data + + +class ManoModel: + def __init__(self, side, model_dir, np, torch, smplx): + self.side = side + self.np = np + self.torch = torch + self.data = model_data(model_dir / f"MANO_{side.upper()}.pkl", np, torch) + self.layer = smplx.MANO( + model_path=str(model_dir), + data_struct=SimpleNamespace(**self.data), + is_rhand=side == "right", + use_pca=False, + flat_hand_mean=True, + ) + + def geometry(self, pose, betas, translation=None): + np, torch = self.np, self.torch + pose_tensor = torch.as_tensor(np.asarray(pose).copy(), dtype=torch.float32).reshape(-1, 48) + beta_tensor = torch.as_tensor(np.asarray(betas).copy(), dtype=torch.float32).reshape(-1, 10) + with torch.no_grad(): + output = self.layer( + global_orient=pose_tensor[:, :3], hand_pose=pose_tensor[:, 3:], betas=beta_tensor + ) + vertices = output.vertices.numpy() + joints = output.joints.numpy()[:, :16] + if translation is not None: + offset = np.asarray(translation).reshape(-1, 1, 3) + vertices = vertices + offset + joints = joints + offset + return vertices, joints + + +def read_ply_vertices(path: Path, np): + lines = path.read_text(encoding="ascii").splitlines() + if lines[0] != "ply" or lines[1] != "format ascii 1.0": + raise RuntimeError(f"Unsupported source mesh: {path}") + vertex_line = next(line for line in lines if line.startswith("element vertex ")) + count = int(vertex_line.split()[-1]) + begin = lines.index("end_header") + 1 + return np.array([[float(value) for value in line.split()[:3]] for line in lines[begin : begin + count]]) / 1000 + + +def camera_mano(model, pose, betas, translation, extrinsic, np, cv2): + root = np.einsum( + "v,tvc->tc", + model.data["J_regressor"][0], + model.data["v_template"][None] + np.einsum("vci,ti->tvc", model.data["shapedirs"], betas), + ) + normalized_pose = pose.copy() + normalized_pose[:, :3] = np.stack( + [cv2.Rodrigues(E[:3, :3] @ cv2.Rodrigues(source[:3])[0])[0].ravel() for E, source in zip(extrinsic, pose)] + ) + normalized_translation = ( + np.einsum("tij,tj->ti", extrinsic[:, :3, :3], root + translation) + + extrinsic[:, :3, 3] + - root + ) + world_vertices, _ = model.geometry(pose, betas, translation) + camera_vertices, _ = model.geometry(normalized_pose, betas, normalized_translation) + expected = np.einsum("tij,tvj->tvi", extrinsic[:, :3, :3], world_vertices) + extrinsic[:, None, :3, 3] + error = float(np.linalg.norm(camera_vertices - expected, axis=-1).max()) + if error >= 2e-5: + raise RuntimeError(f"MANO camera transform error: {error}") + return np.concatenate([normalized_pose, betas, normalized_translation], axis=-1), error, camera_vertices + + +def save_tensor(path: Path, value, torch, np) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + array = np.asarray(value) + temporary = path.with_name(path.name + ".tmp") + torch.save(torch.from_numpy(array.copy()), temporary) + os.replace(temporary, path) + restored = torch.load(path, map_location="cpu", weights_only=True).numpy() + if not np.array_equal(restored, array, equal_nan=True): + raise RuntimeError(f"Tensor round-trip mismatch: {path}") + + +def write_jsonl(path: Path, rows: list[dict]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + ".tmp") + with temporary.open("w", encoding="utf-8", newline="\n") as stream: + for row in rows: + stream.write(json.dumps(row, sort_keys=True) + "\n") + os.replace(temporary, path) + + +def encode_lossless_video(paths: list[Path], output: Path, size: tuple[int, int], Image, hashlib_module=hashlib): + width, height = size + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_name(output.stem + ".tmp" + output.suffix) + ffmpeg_threads = str(max(1, int(os.environ.get("REINTERHAND_FFMPEG_THREADS", "2")))) + command = [ + "ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pixel_format", "rgb24", + "-video_size", f"{width}x{height}", "-framerate", "1", "-i", "pipe:0", + "-an", "-c:v", "ffv1", "-level", "3", "-g", "1", "-threads", ffmpeg_threads, str(temporary), + ] + process = subprocess.Popen(command, stdin=subprocess.PIPE) + hashes = [] + assert process.stdin is not None + try: + for path in paths: + image = Image.open(path).convert("RGB") + if image.size != size: + raise RuntimeError(f"Image size changed in view: {path}") + payload = image.tobytes() + hashes.append(hashlib_module.sha256(payload).hexdigest()) + process.stdin.write(payload) + finally: + process.stdin.close() + if process.wait() != 0: + raise RuntimeError(f"FFV1 encoder failed: {output}") + os.replace(temporary, output) + decoder = subprocess.Popen( + ["ffmpeg", "-v", "error", "-threads", "1", "-i", str(output), "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1"], + stdout=subprocess.PIPE, + ) + assert decoder.stdout is not None + frame_bytes = width * height * 3 + for expected in hashes: + payload = decoder.stdout.read(frame_bytes) + if len(payload) != frame_bytes or hashlib_module.sha256(payload).hexdigest() != expected: + raise RuntimeError(f"Full-frame RGB round-trip failed: {output}") + if decoder.stdout.read(1) or decoder.wait() != 0: + raise RuntimeError(f"Unexpected decoded frame count: {output}") + return hashes + + +def encode_mask_video(paths: list[Path], output: Path, size: tuple[int, int], Image, np): + width, height = size + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_name(output.stem + ".tmp" + output.suffix) + ffmpeg_threads = str(max(1, int(os.environ.get("REINTERHAND_FFMPEG_THREADS", "2")))) + process = subprocess.Popen( + [ + "ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pixel_format", "gray16le", + "-video_size", f"{width}x{height}", "-framerate", "1", "-i", "pipe:0", + "-an", "-c:v", "ffv1", "-level", "3", "-g", "1", "-threads", ffmpeg_threads, str(temporary), + ], + stdin=subprocess.PIPE, + ) + hashes = [] + histogram = np.zeros(256, dtype=np.int64) + assert process.stdin is not None + try: + for path in paths: + source = np.asarray(Image.open(path)) + if source.shape != (height, width) or source.dtype != np.uint8: + raise RuntimeError(f"Unexpected mask format: {path}") + histogram += np.bincount(source.ravel(), minlength=256) + payload = source.astype(" None: + np, torch, cv2, Image, smplx = runtime_imports(runtime) + state = root / "tmp" / "pilot-v1.0" + status_path = state / "status.json" + extraction = json.loads((state / "extraction-manifest.json").read_text(encoding="utf-8")) + if extraction["capture"] != capture or extraction["segment"] != segment: + raise RuntimeError("Pilot extraction selection differs from conversion request") + ids = [int(value) for value in extraction["source_frame_ids"]] + T = len(ids) + source = state / "extracted" / f"{capture}__{segment}" + sequence_id = f"{capture}__{segment}" + release = root / "shared-v1.0" + status = json.loads(status_path.read_text(encoding="utf-8")) + status.update(phase="converting", updated_at=now(), views_completed=[]) + atomic_json(status_path, status) + + models = [ + ManoModel("left", runtime / "models", np, torch, smplx), + ManoModel("right", runtime / "models", np, torch, smplx), + ] + left_fix = bool(np.abs(models[0].data["shapedirs"][:, 0] - models[1].data["shapedirs"][:, 0]).sum() < 1) + if left_fix: + models[0].data["shapedirs"][:, 0] *= -1 + with torch.no_grad(): + models[0].layer.shapedirs[:, 0] *= -1 + + native = {} + source_meshes = {} + source_mesh_errors = [] + for hand_index, side in enumerate(["left", "right"]): + rows = [json.loads((source / "mano_fits" / "params" / f"{frame}_{side}.json").read_text()) for frame in ids] + pose = np.stack([row["pose"] for row in rows]).astype(np.float64) + betas = np.stack([row["shape"] for row in rows]).astype(np.float64) + translation = np.stack([row["trans"] for row in rows]).astype(np.float64) + pose[:, 3:] += models[hand_index].data["hands_mean"] + predicted, _ = models[hand_index].geometry(pose, betas, translation) + meshes = np.stack( + [read_ply_vertices(source / "mano_fits" / "meshes" / f"{frame}_{side}.ply", np) for frame in ids] + ) + error = np.linalg.norm(predicted - meshes, axis=-1) + if float(error.max()) >= 1e-4: + raise RuntimeError(f"Source MANO parameters do not reproduce source {side} meshes: {error.max()}") + source_mesh_errors.append({"side": side, "max_m": float(error.max()), "mean_m": float(error.mean())}) + native[side] = (pose, betas, translation) + source_meshes[side] = meshes + + mugsy_params = json.loads((source / "Mugsy_cameras" / "cam_params.json").read_text()) + views = [] + ego_images = source / "Ego_cameras" / "envmap_per_segment" / "images" + views.append(("ego_envmap_per_segment", "ego", ego_images, None)) + mugsy_images = source / "Mugsy_cameras" / "envmap_per_segment" / "images" + for camera_dir in sorted(path for path in mugsy_images.iterdir() if path.is_dir()): + views.append((camera_dir.name, "exo", camera_dir, mugsy_params[camera_dir.name])) + + review = { + "schema": "reinterhand-pilot-validation/v1", + "dataset": "ReInterHand", + "sequence_id": sequence_id, + "capture": capture, + "segment": segment, + "frames": T, + "source_frame_ids": ids, + "source_fps": None, + "timestamp_policy": "No trustworthy source timestamps or FPS in this release; preserve frame order, source_frame_id and cross-camera sync_id only.", + "source_mesh_parameter_checks": source_mesh_errors, + "left_shapedirs_fix": left_fix, + "views": [], + "human_review": "pending", + } + + for camera_id, view_type, image_root, static_camera in views: + view = release / "data" / sequence_id / camera_id + image_paths = [image_root / f"{frame:06d}.png" for frame in ids] + first = Image.open(image_paths[0]).convert("RGB") + width, height = first.size + rgb_hashes = encode_lossless_video(image_paths, view / "observation" / "rgb.mkv", (width, height), Image) + + if view_type == "ego": + camera_rows = [ + json.loads( + (source / "Ego_cameras" / "envmap_per_segment" / "cam_params" / f"{frame:06d}.json").read_text() + ) + for frame in ids + ] + else: + camera_rows = [static_camera] * T + intrinsic = np.stack( + [ + [[row["focal"][0], 0, row["princpt"][0]], [0, row["focal"][1], row["princpt"][1]], [0, 0, 1]] + for row in camera_rows + ] + ).astype(np.float32) + extrinsic = np.broadcast_to(np.eye(4, dtype=np.float32), (T, 4, 4)).copy() + extrinsic[:, :3, :3] = np.stack([row["R"] for row in camera_rows]) + extrinsic[:, :3, 3] = np.stack([row["t"] for row in camera_rows]) / 1000 + distortion = np.stack([row["D"] for row in camera_rows]).astype(np.float32) if view_type == "ego" else None + + valid_frames = np.ones(T, dtype=bool) + save_tensor(view / "camera" / "intrinsic.pt", intrinsic, torch, np) + save_tensor(view / "camera" / "intrinsic_valid.pt", valid_frames, torch, np) + save_tensor(view / "camera" / "extrinsic.pt", extrinsic, torch, np) + save_tensor(view / "camera" / "extrinsic_valid.pt", valid_frames, torch, np) + if distortion is not None: + save_tensor(view / "camera" / "distortion.pt", distortion, torch, np) + save_tensor(view / "camera" / "distortion_valid.pt", valid_frames, torch, np) + + motion = np.empty((T, 2, 61), dtype=np.float32) + camera_meshes = {} + transform_checks = [] + for hand_index, side in enumerate(["left", "right"]): + pose, betas, translation = native[side] + converted, error, normalized_vertices = camera_mano( + models[hand_index], pose, betas, translation, extrinsic, np, cv2 + ) + motion[:, hand_index] = converted + camera_meshes[side] = normalized_vertices + transform_checks.append({"side": side, "max_vertex_error_m": error}) + save_tensor(view / "annotation" / "mano" / "motion.pt", motion, torch, np) + save_tensor(view / "annotation" / "mano" / "motion_valid.pt", np.ones((T, 2), dtype=bool), torch, np) + + components = { + "rgb": component( + "observation/rgb.mkv", "observation/rgb_valid.pt", "rgb/uint8/v1", + ["T", "height", "width", "channel"], ["T"], + {"archive_prefix": f"raw/data/{capture}/{'Ego_cameras' if view_type == 'ego' else 'Mugsy_cameras'}/envmap_per_segment.tar.gz", "member_template": f"envmap_per_segment/images/{'' if view_type == 'ego' else camera_id + '/'}{{source_frame_id:06d}}.png"}, + "Source PNG decoded to RGB and stored losslessly as FFV1; every frame decoded back and SHA256-compared", + storage={"profile": "mkv/ffv1_rgb24/v1", "codec": "ffv1", "pixel_format": "rgb24", "source_lossy": False}, + storage_fps=1, + timebase_role="index_only", + ), + "intrinsic": component( + "camera/intrinsic.pt", "camera/intrinsic_valid.pt", + "camera/opencv_fisheye4/v1" if view_type == "ego" else "camera/pinhole/v1", + ["T", "row", "column"], ["T"], + {"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/cam_params/{source_frame_id:06d}.json"} if view_type == "ego" else {"file": f"raw/data/{capture}/Mugsy_cameras/cam_params.json", "camera_id": camera_id}, + "Source focal and principal point retained in a 3x3 matrix", + ), + "extrinsic": component( + "camera/extrinsic.pt", "camera/extrinsic_valid.pt", "transform/se3/v1", + ["T", "row", "column"], ["T"], + {"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/cam_params/{source_frame_id:06d}.json"} if view_type == "ego" else {"file": f"raw/data/{capture}/Mugsy_cameras/cam_params.json", "camera_id": camera_id}, + "Source R retained and source t converted from millimetres to metres", + unit="m", convention="T_camera_from_world", + ), + "mano": component( + "annotation/mano/motion.pt", "annotation/mano/motion_valid.pt", "mano/axis_angle61/v1", + ["T", "hand", "parameter"], ["T", "hand"], + {"archive_prefix": f"raw/data/{capture}/mano_fits/mano_fits.tar.gz", "member_template": "params/{source_frame_id}_{left|right}.json"}, + "Native non-flat MANO mean expanded; root-corrected world-to-camera transform; verified against every source mesh and every transformed vertex", + unit="m", angle_unit="rad", coordinate_frame="camera", + model_profile={"version": "MANO-v1.2", "flat_hand_mean": True, "left_shapedirs_fix": left_fix}, + valid_policy={"semantics": "usable_annotation", "formula": "source_parameters_present AND numerically_finite AND source_mesh_reproduction_pass", "no_qa_source_rule": "No independent manual QA field exists in this raw release; no QA was invented."}, + ), + } + save_tensor(view / "observation" / "rgb_valid.pt", valid_frames, torch, np) + if distortion is not None: + components["intrinsic"]["distortion_ref"] = "camera/distortion.pt" + components["distortion"] = component( + "camera/distortion.pt", "camera/distortion_valid.pt", "camera/fisheye4_distortion/v1", + ["T", "parameter"], ["T"], + {"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/cam_params/{source_frame_id:06d}.json"}, + "Four native OpenCV fisheye coefficients retained", + parameter_names=["k1", "k2", "k3", "k4"], + ) + mask_paths = [source / "Ego_cameras" / "envmap_per_segment" / "masks" / f"{frame:06d}.png" for frame in ids] + histogram = encode_mask_video(mask_paths, view / "annotation" / "segment" / "mask.mkv", (width, height), Image, np) + save_tensor(view / "annotation" / "segment" / "mask_valid.pt", valid_frames, torch, np) + components["segment"] = component( + "annotation/segment/mask.mkv", "annotation/segment/mask_valid.pt", "segment/foreground_intensity/v1", + ["T", "height", "width"], ["T"], + {"archive_prefix": f"raw/data/{capture}/Ego_cameras/envmap_per_segment.tar.gz", "member_template": "envmap_per_segment/masks/{source_frame_id:06d}.png"}, + "Every native uint8 foreground intensity retained losslessly in gray16 FFV1; no thresholding or invented hand identity", + value_range=[0, 255], normalization_scale=1 / 255, + foreground_category="hand", identity_semantics="left and right union; no per-hand instance identity", + ) + else: + histogram = None + + frames = [ + { + "frame_index": index, + "source_frame_id": str(frame), + "timestamp_ns": None, + "clock_domain": None, + "sync_id": f"{capture}:{frame}", + "source_locator": {"capture": capture, "segment": segment, "source_frame_id": str(frame)}, + } + for index, frame in enumerate(ids) + ] + write_jsonl(view / "camera" / "frames.jsonl", frames) + metadata = { + "schema_version": "hand-warehouse/1.0", + "storage_revision": "lossless-video-2026-09-25", + "dataset_id": "ReInterHand", + "release_id": "shared-v1.0", + "sequence_id": sequence_id, + "camera_id": camera_id, + "sample_type": "video", + "num_frames": T, + "hand_slots": ["left", "right"], + "sampling": {"type": "dense", "source_fps": None, "frames_ref": "camera/frames.jsonl", "selection": "All released frames of the named action in official frame_list.txt", "time_semantics": "ordered source frame identifiers; no inferred timestamps"}, + "camera": {"model": "opencv_fisheye4" if view_type == "ego" else "pinhole", "schema_id": "camera/opencv_fisheye4/v1" if view_type == "ego" else "camera/pinhole/v1", "image_size": [width, height]}, + **official_split_metadata(capture), + "view_type": view_type, + "components": components, + "pilot": True, + "pilot_complete": True, + "pilot_human_review": "pending", + "full_output_human_review": "not_started", + "upload_authorized": False, + "omitted_components": {"depth": "No source depth selected by the unified contract", "contact": "No native contact labels in this raw release", "keypoints": "Intermediate source keypoint sets intentionally excluded by the contract; MANO parameters retained"}, + } + atomic_json(view / "metainfo.json", metadata) + review["views"].append( + { + "camera_id": camera_id, + "view_type": view_type, + "frames": T, + "image_size": [width, height], + "rgb_full_frame_roundtrip": "passed", + "rgb_frame_sha256_count": len(rgb_hashes), + "mano_camera_transform_checks": transform_checks, + "foreground_histogram": histogram, + } + ) + status["views_completed"].append(camera_id) + status.update(updated_at=now(), active_view=camera_id) + atomic_json(status_path, status) + + validation = release / "doc" / "validation" + validation.mkdir(parents=True, exist_ok=True) + atomic_json(validation / "report.json", review) + rows = "\n".join( + f"{item['camera_id']}{item['view_type']}{item['frames']}{item['image_size'][0]}×{item['image_size'][1]}passed" + for item in review["views"] + ) + html = f"""ReInterHand pilot validation + +

    ReInterHand complete-sequence pilot

    +

    Human review: pending

    +

    Capture: {capture}
    Action: {segment}
    Frames: {T}. Source FPS and timestamps are unknown; no timing was inferred. Cross-camera alignment uses the official frame identifiers recorded in camera/frames.jsonl.

    +

    All six actually available views were converted: one ego fisheye view and five exo Mugsy views. Every RGB frame completed a lossless FFV1 decode round-trip. Both hands' MANO parameters reproduced all source meshes within 0.1 mm and were root-corrected into each camera.

    +{rows}
    cameraview typeframessizeautomatic checks
    +

    Machine-readable evidence: report.json. Visual all-frame overlay videos are generated by the next validation stage before human approval.

    """ + (validation / "index.html").write_text(html, encoding="utf-8") + script_target = release / "script" / Path(__file__).name + script_target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(Path(__file__), script_target) + status.update(phase="converted_pending_visual_report", updated_at=now(), active_view=None) + atomic_json(status_path, status) + + +def project_vertices(vertices, intrinsic, distortion, np, cv2): + visible = vertices[:, 2] > 1e-6 + result = np.full((len(vertices), 2), np.nan, dtype=np.float64) + if distortion is None: + projected = vertices @ intrinsic.T + result[visible] = projected[visible, :2] / projected[visible, 2:3] + else: + points, _ = cv2.fisheye.projectPoints( + vertices.reshape(-1, 1, 3).astype(np.float64), + np.zeros(3), np.zeros(3), intrinsic.astype(np.float64), distortion.astype(np.float64), + ) + result[visible] = points.reshape(-1, 2)[visible] + return result, visible + + +def draw_mano_meshes(image, points_by_side, faces, Image): + from PIL import ImageDraw + + overlay = Image.new("RGBA", image.size, (0, 0, 0, 0)) + draw = ImageDraw.Draw(overlay, "RGBA") + colors = {"left": (0, 255, 255), "right": (255, 140, 0)} + width, height = image.size + for side, points in points_by_side.items(): + color = colors[side] + for face in faces: + polygon = [tuple(map(float, points[index])) for index in face] + if not all(float("-inf") < x < float("inf") and float("-inf") < y < float("inf") for x, y in polygon): + continue + xs, ys = zip(*polygon) + if max(xs) < 0 or min(xs) >= width or max(ys) < 0 or min(ys) >= height: + continue + draw.polygon(polygon, fill=(*color, 28)) + draw.line(polygon + [polygon[0]], fill=(*color, 220), width=2) + return Image.alpha_composite(image.convert("RGBA"), overlay).convert("RGB") + + +def draw_foreground_intensity(image, mask_path, Image): + if mask_path is None or not mask_path.exists(): + blank = Image.new("RGB", image.size, (25, 25, 25)) + return label_panel(blank, "no native pixel mask for this exo view", Image) + mask = Image.open(mask_path).convert("L") + tint = Image.new("RGBA", image.size, (255, 0, 200, 0)) + tint.putalpha(mask.point(lambda value: min(190, int(value * 0.72)))) + return Image.alpha_composite(image.convert("RGBA"), tint).convert("RGB") + + +def label_panel(image, text, Image): + from PIL import ImageDraw + + result = image.copy() + draw = ImageDraw.Draw(result) + draw.rectangle((0, 0, min(result.width, 360), 28), fill=(0, 0, 0)) + draw.text((8, 6), text, fill=(255, 255, 255)) + return result + + +def render_review_video(frames, output: Path, size: tuple[int, int], panels: int = 3): + width, height = size + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_name(output.stem + ".tmp" + output.suffix) + process = subprocess.Popen( + [ + "ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pixel_format", "rgb24", + "-video_size", f"{width * panels}x{height}", "-framerate", "12", "-i", "pipe:0", + "-an", "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-c:v", "libx264", "-crf", "18", "-preset", "medium", "-pix_fmt", "yuv420p", str(temporary), + ], + stdin=subprocess.PIPE, + ) + count = 0 + assert process.stdin is not None + try: + for frame in frames: + if frame.size != (width * panels, height): + raise RuntimeError("Review frame dimensions changed") + process.stdin.write(frame.tobytes()) + count += 1 + finally: + process.stdin.close() + if process.wait() != 0 or count == 0: + raise RuntimeError(f"Review video encoder failed: {output}") + os.replace(temporary, output) + return count + + +def render_pilot(root: Path, runtime: Path, capture: str, segment: str) -> None: + np, torch, cv2, Image, smplx = runtime_imports(runtime) + state = root / "tmp" / "pilot-v1.0" + status_path = state / "status.json" + status = json.loads(status_path.read_text(encoding="utf-8")) + status.update(phase="rendering_visual_report", updated_at=now(), review_views_completed=[]) + atomic_json(status_path, status) + extraction = json.loads((state / "extraction-manifest.json").read_text(encoding="utf-8")) + ids = [int(value) for value in extraction["source_frame_ids"]] + source = state / "extracted" / f"{capture}__{segment}" + sequence_id = f"{capture}__{segment}" + release = root / "shared-v1.0" + validation = release / "doc" / "validation" + report_path = validation / "report.json" + report = json.loads(report_path.read_text(encoding="utf-8")) + + models = [ + ManoModel("left", runtime / "models", np, torch, smplx), + ManoModel("right", runtime / "models", np, torch, smplx), + ] + if report["left_shapedirs_fix"]: + models[0].data["shapedirs"][:, 0] *= -1 + with torch.no_grad(): + models[0].layer.shapedirs[:, 0] *= -1 + + source_meshes = { + side: np.stack( + [read_ply_vertices(source / "mano_fits" / "meshes" / f"{frame}_{side}.ply", np) for frame in ids] + ) + for side in ["left", "right"] + } + view_lookup = {row["camera_id"]: row for row in report["views"]} + video_rows = [] + for view in sorted((release / "data" / sequence_id).iterdir()): + metadata = json.loads((view / "metainfo.json").read_text(encoding="utf-8")) + camera_id = metadata["camera_id"] + view_type = metadata["view_type"] + width, height = metadata["camera"]["image_size"] + intrinsic = torch.load(view / "camera" / "intrinsic.pt", map_location="cpu", weights_only=True).numpy() + extrinsic = torch.load(view / "camera" / "extrinsic.pt", map_location="cpu", weights_only=True).numpy() + distortion = ( + torch.load(view / "camera" / "distortion.pt", map_location="cpu", weights_only=True).numpy() + if (view / "camera" / "distortion.pt").exists() + else None + ) + motion = torch.load(view / "annotation" / "mano" / "motion.pt", map_location="cpu", weights_only=True).numpy() + current_meshes = {} + for index, side in enumerate(["left", "right"]): + current_meshes[side], _ = models[index].geometry( + motion[:, index, :48], motion[:, index, 48:58], motion[:, index, 58:] + ) + if view_type == "ego": + image_root = source / "Ego_cameras" / "envmap_per_segment" / "images" + else: + image_root = source / "Mugsy_cameras" / "envmap_per_segment" / "images" / camera_id + pixel_errors = [] + + def panels(): + for frame_index, source_frame in enumerate(ids): + original = Image.open(image_root / f"{source_frame:06d}.png").convert("RGB") + source_points = {} + current_points = {} + for side in ["left", "right"]: + source_camera = ( + source_meshes[side][frame_index] @ extrinsic[frame_index, :3, :3].T + + extrinsic[frame_index, :3, 3] + ) + src_uv, src_visible = project_vertices( + source_camera, + intrinsic[frame_index], + None if distortion is None else distortion[frame_index], + np, + cv2, + ) + cur_uv, cur_visible = project_vertices( + current_meshes[side][frame_index], + intrinsic[frame_index], + None if distortion is None else distortion[frame_index], + np, + cv2, + ) + good = src_visible & cur_visible & np.isfinite(src_uv).all(axis=1) & np.isfinite(cur_uv).all(axis=1) + if good.any(): + pixel_errors.extend(np.linalg.norm(src_uv[good] - cur_uv[good], axis=1).tolist()) + source_points[side] = src_uv[src_visible] + current_points[side] = cur_uv[cur_visible] + source_panel = draw_points(original, source_points, Image) + current_panel = draw_points(original, current_points, Image) + canvas = Image.new("RGB", (width * 3, height)) + canvas.paste(label_panel(original, f"original | frame {source_frame}", Image), (0, 0)) + canvas.paste(label_panel(source_panel, "source mesh projection", Image), (width, 0)) + canvas.paste(label_panel(current_panel, "shared MANO projection", Image), (width * 2, 0)) + yield canvas + + relative_video = Path("media") / f"{camera_id}.mp4" + rendered = render_review_video(panels(), validation / relative_video, (width, height)) + if rendered != len(ids) or not pixel_errors: + raise RuntimeError(f"Review coverage failed for {camera_id}") + row = view_lookup[camera_id] + row["visual_review_video"] = relative_video.as_posix() + row["visual_review_frames"] = rendered + row["source_vs_shared_projection_max_px"] = float(max(pixel_errors)) + row["source_vs_shared_projection_mean_px"] = float(sum(pixel_errors) / len(pixel_errors)) + video_rows.append(row) + status["review_views_completed"].append(camera_id) + status.update(updated_at=now(), active_view=camera_id) + atomic_json(status_path, status) + + report["views"] = video_rows + report["automatic_status"] = "passed" + report["visual_scope"] = "all 58 frames of every one of the six actually available views" + report["completed_at"] = now() + atomic_json(report_path, report) + blocks = [] + for item in video_rows: + blocks.append( + f"

    {item['camera_id']} · {item['view_type']}

    " + f"" + f"

    {item['frames']} frames; source/shared projection max {item['source_vs_shared_projection_max_px']:.4f}px; " + f"lossless RGB round-trip passed.

    " + ) + html = f"""ReInterHand pilot validation + +

    ReInterHand complete-sequence pilot

    +

    Human review: pending

    +

    Capture: {capture}
    Action: {segment}
    Coverage: all {len(ids)} frames in every actually available camera (one ego, five exo). Source FPS and timestamps are unknown; no timing was inferred. Alignment uses official source frame identifiers.

    +

    Each video shows original RGB, source MANO mesh projection, and the shared camera-space MANO projection. Cyan is left; orange is right. RGB, camera arrays, MANO arrays, masks, frame mapping, source-mesh reproduction and projection equivalence passed automatic checks. This does not replace human visual review.

    +{''.join(blocks)} +

    Machine-readable evidence: report.json.

    """ + (validation / "index.html").write_text(html, encoding="utf-8") + status.update(phase="pilot_ready_for_human_review", updated_at=now(), active_view=None) + atomic_json(status_path, status) + + +def render_expanded_review(root: Path, runtime: Path, capture: str, segment: str) -> None: + """Render both official background policies with a large, explicit MANO panel.""" + np, torch, cv2, Image, smplx = runtime_imports(runtime) + state = root / "tmp" / "pilot-v1.0" + status_path = state / "status.json" + status = json.loads(status_path.read_text(encoding="utf-8")) + status.update(phase="rendering_expanded_visual_report", updated_at=now(), review_streams_completed=[]) + atomic_json(status_path, status) + extraction = json.loads((state / "extraction-manifest.json").read_text(encoding="utf-8")) + ids = [int(value) for value in extraction["source_frame_ids"]] + source = state / "extracted" / f"{capture}__{segment}" + sequence_id = f"{capture}__{segment}" + release = root / "shared-v1.0" + validation = release / "doc" / "validation" + report_path = validation / "report.json" + previous_report = json.loads(report_path.read_text(encoding="utf-8")) + physical_rows = {row["camera_id"]: row for row in previous_report["views"]} + physical_views = sorted((release / "data" / sequence_id).iterdir()) + variants = ["envmap_per_frame", "envmap_per_segment"] + for variant in variants: + ego = source / "Ego_cameras" / variant / "images" + mugsy = source / "Mugsy_cameras" / variant / "images" + if not ego.is_dir() or not mugsy.is_dir(): + raise RuntimeError(f"Missing extracted background variant: {variant}") + + models = [ + ManoModel("left", runtime / "models", np, torch, smplx), + ManoModel("right", runtime / "models", np, torch, smplx), + ] + if previous_report["left_shapedirs_fix"]: + models[0].data["shapedirs"][:, 0] *= -1 + with torch.no_grad(): + models[0].layer.shapedirs[:, 0] *= -1 + faces = np.asarray(models[0].data["f"], dtype=np.int64) + source_meshes = { + side: np.stack([read_ply_vertices(source / "mano_fits" / "meshes" / f"{frame}_{side}.ply", np) for frame in ids]) + for side in ["left", "right"] + } + rows = [] + for variant in variants: + for view in physical_views: + metadata = json.loads((view / "metainfo.json").read_text(encoding="utf-8")) + camera_id = metadata["camera_id"] + view_type = metadata["view_type"] + width, height = metadata["camera"]["image_size"] + intrinsic = torch.load(view / "camera" / "intrinsic.pt", map_location="cpu", weights_only=True).numpy() + extrinsic = torch.load(view / "camera" / "extrinsic.pt", map_location="cpu", weights_only=True).numpy() + distortion = (torch.load(view / "camera" / "distortion.pt", map_location="cpu", weights_only=True).numpy() + if (view / "camera" / "distortion.pt").exists() else None) + motion = torch.load(view / "annotation" / "mano" / "motion.pt", map_location="cpu", weights_only=True).numpy() + current_meshes = {} + for index, side in enumerate(["left", "right"]): + current_meshes[side], _ = models[index].geometry( + motion[:, index, :48], motion[:, index, 48:58], motion[:, index, 58:]) + image_root = (source / "Ego_cameras" / variant / "images" if view_type == "ego" + else source / "Mugsy_cameras" / variant / "images" / camera_id) + mask_root = source / "Ego_cameras" / variant / "masks" if view_type == "ego" else None + pixel_errors = [] + + def mano_panels(): + for frame_index, source_frame in enumerate(ids): + original = Image.open(image_root / f"{source_frame:06d}.png").convert("RGB") + current_points = {} + for side in ["left", "right"]: + source_camera = (source_meshes[side][frame_index] @ extrinsic[frame_index, :3, :3].T + + extrinsic[frame_index, :3, 3]) + src_uv, src_visible = project_vertices(source_camera, intrinsic[frame_index], + None if distortion is None else distortion[frame_index], np, cv2) + cur_uv, cur_visible = project_vertices(current_meshes[side][frame_index], intrinsic[frame_index], + None if distortion is None else distortion[frame_index], np, cv2) + good = src_visible & cur_visible & np.isfinite(src_uv).all(axis=1) & np.isfinite(cur_uv).all(axis=1) + if good.any(): + pixel_errors.extend(np.linalg.norm(src_uv[good] - cur_uv[good], axis=1).tolist()) + current_points[side] = cur_uv + overlay = draw_mano_meshes(original, current_points, faces, Image) + canvas = Image.new("RGB", (width * 2, height)) + canvas.paste(label_panel(original, f"RGB | {variant} | frame {source_frame}", Image), (0, 0)) + canvas.paste(label_panel(overlay, "shared MANO mesh | cyan left, orange right", Image), (width, 0)) + yield canvas + + stem = f"{variant}__{camera_id}" + mano_video = Path("media") / f"{stem}__mano.mp4" + rendered = render_review_video(mano_panels(), validation / mano_video, (width, height), panels=2) + mask_video = None + if mask_root is not None: + def mask_panels(): + for source_frame in ids: + original = Image.open(image_root / f"{source_frame:06d}.png").convert("RGB") + mask = draw_foreground_intensity(original, mask_root / f"{source_frame:06d}.png", Image) + canvas = Image.new("RGB", (width * 2, height)) + canvas.paste(label_panel(original, f"RGB | {variant} | frame {source_frame}", Image), (0, 0)) + canvas.paste(label_panel(mask, "native foreground intensity (magenta)", Image), (width, 0)) + yield canvas + mask_video = Path("media") / f"{stem}__mask.mp4" + render_review_video(mask_panels(), validation / mask_video, (width, height), panels=2) + if rendered != len(ids) or not pixel_errors: + raise RuntimeError(f"Expanded review coverage failed for {stem}") + base = dict(physical_rows[camera_id]) + base.update(background_variant=variant, physical_camera_id=camera_id, + visual_review_video=mano_video.as_posix(), mask_review_video=None if mask_video is None else mask_video.as_posix(), + visual_review_frames=rendered, + source_vs_shared_projection_max_px=float(max(pixel_errors)), + source_vs_shared_projection_mean_px=float(sum(pixel_errors) / len(pixel_errors))) + rows.append(base) + status["review_streams_completed"].append(stem) + status.update(active_stream=stem, updated_at=now()) + atomic_json(status_path, status) + + report = dict(previous_report) + report["views"] = rows + report["physical_view_count"] = len(physical_views) + report["rendered_rgb_stream_count"] = len(rows) + report["background_variants"] = variants + report["modalities"] = { + "all_views": ["RGB", "camera intrinsics/extrinsics", "left/right MANO parameters", "source MANO OBJ/PLY meshes"], + "ego_only": ["fisheye distortion", "uint8 foreground-intensity mask", "truncation ratio"], + "not_present_in_this_release_scope": ["depth", "object pose/model", "contact labels"], + } + report["visual_scope"] = "all frames, six physical views, both official background variants; large MANO overlay for every stream" + report["completed_at"] = now() + atomic_json(report_path, report) + blocks = [] + for item in rows: + mask_html = (f"
    ego foreground-intensity mask
    " + if item["mask_review_video"] else "

    This exo stream has no native pixel mask.

    ") + blocks.append( + f"

    {item['physical_camera_id']} · {item['view_type']} · {item['background_variant']}

    " + f"" + f"

    All {item['frames']} frames. Right panel is the reconstructed shared MANO mesh: cyan left hand, orange right hand. " + f"Source/shared projection max {item['source_vs_shared_projection_max_px']:.4f}px.

    {mask_html}
    ") + html = f"""ReInterHand expanded pilot validation + +

    ReInterHand complete-sequence pilot · expanded coverage

    Human review: pending

    +

    Capture: {capture}
    Action: {segment}
    Physical views: one ego plus five active Mugsy exo cameras. RGB streams: 12, because every physical view is shown under both official policies: envmap_per_frame (background changes each frame) and envmap_per_segment (one background per action segment).

    +

    Modalities: every view has RGB, camera calibration and left/right MANO; source MANO OBJ/PLY meshes independently reproduce the converted MANO. Ego additionally has fisheye distortion, native uint8 foreground-intensity masks and truncation ratios. This scope has no native depth, object pose/model or contact labels.

    +

    Each main video now uses two large panels. The right panel draws full MANO triangle meshes instead of sparse points. Ego mask videos are separately expandable so MANO remains large and readable. All 58 frames are rendered; source FPS/timestamps remain unknown and alignment uses official frame IDs.

    +{''.join(blocks)}

    Machine-readable evidence: report.json.

    """ + (validation / "index.html").write_text(html, encoding="utf-8") + script_target = release / "script" / Path(__file__).name + script_target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(Path(__file__), script_target) + status.update(phase="pilot_ready_for_human_review", active_stream=None, + expanded_review=True, updated_at=now()) + atomic_json(status_path, status) + + +def convert_complete_pilot_v2(root: Path, runtime: Path, capture: str, segment: str) -> None: + """Convert every released camera/background setting represented by one action.""" + np, torch, cv2, Image, smplx = runtime_imports(runtime) + state = root / "tmp" / "pilot-v1.0" + status_path = state / "status.json" + source = state / "extracted" / f"{capture}__{segment}" + segment_ids = frame_ids(root / "raw" / "data" / capture, segment) + id_set = set(segment_ids) + models = [ManoModel("left", runtime / "models", np, torch, smplx), ManoModel("right", runtime / "models", np, torch, smplx)] + left_fix = bool(np.abs(models[0].data["shapedirs"][:, 0] - models[1].data["shapedirs"][:, 0]).sum() < 1) + if left_fix: + models[0].data["shapedirs"][:, 0] *= -1 + with torch.no_grad(): models[0].layer.shapedirs[:, 0] *= -1 + native, source_meshes, source_checks = {}, {}, [] + for hand_index, side in enumerate(["left", "right"]): + rows = [json.loads((source / "mano_fits/params" / f"{frame}_{side}.json").read_text()) for frame in segment_ids] + pose = np.stack([row["pose"] for row in rows]).astype(np.float64) + betas = np.stack([row["shape"] for row in rows]).astype(np.float64) + translation = np.stack([row["trans"] for row in rows]).astype(np.float64) + pose[:, 3:] += models[hand_index].data["hands_mean"] + predicted, _ = models[hand_index].geometry(pose, betas, translation) + meshes = np.stack([read_ply_vertices(source / "mano_fits/meshes" / f"{frame}_{side}.ply", np) for frame in segment_ids]) + error = np.linalg.norm(predicted - meshes, axis=-1) + if float(error.max()) >= 1e-4: raise RuntimeError(f"Source MANO mismatch: {side}") + native[side] = (pose, betas, translation) + source_meshes[side] = meshes + source_checks.append({"side": side, "max_m": float(error.max()), "mean_m": float(error.mean())}) + id_to_index = {frame: index for index, frame in enumerate(segment_ids)} + mugsy_params = json.loads((source / "Mugsy_cameras/cam_params.json").read_text()) + streams = [] + for family, view_type in [("Ego_cameras", "ego"), ("Mugsy_cameras", "exo")]: + for variant in ["envmap_per_frame", "envmap_per_segment"]: + image_base = source / family / variant / "images" + camera_dirs = [("ego", image_base)] if family == "Ego_cameras" else [(p.name, p) for p in sorted(image_base.iterdir()) if p.is_dir()] + for camera_id, image_root in camera_dirs: + ids = sorted(int(p.stem) for p in image_root.glob("*.png") if p.stem.isdigit() and int(p.stem) in id_set) + if family == "Mugsy_cameras" and variant == "envmap_per_frame": + if not ids: + raise RuntimeError(f"Empty official 5 FPS image subset: {family}/{variant}/{camera_id}") + elif ids != segment_ids: + missing = sorted(id_set - set(ids)) + raise RuntimeError(f"Camera-specific frame loss is forbidden: {family}/{variant}/{camera_id}; missing={missing[:20]}") + streams.append((family, view_type, variant, camera_id, image_root, ids)) + # Official release definition: 1+1 ego streams, 20 Mugsy per-frame and 5 Mugsy per-segment. + counts = collections.Counter((family, variant) for family, _, variant, _, _, _ in streams) + expected = {("Ego_cameras", "envmap_per_frame"): 1, ("Ego_cameras", "envmap_per_segment"): 1, + ("Mugsy_cameras", "envmap_per_frame"): 20, ("Mugsy_cameras", "envmap_per_segment"): 5} + if dict(counts) != expected: raise RuntimeError(f"Unexpected ReInterHand stream coverage: {dict(counts)}") + mugsy_per_frame_ids = [ids for family, _, variant, _, _, ids in streams if family == "Mugsy_cameras" and variant == "envmap_per_frame"] + if any(ids != mugsy_per_frame_ids[0] for ids in mugsy_per_frame_ids[1:]): + raise RuntimeError("Mugsy envmap_per_frame cameras do not share the same official 5 FPS frame subset") + report = {"schema":"reinterhand-pilot-validation/v2", "dataset":"ReInterHand", "capture":capture, + "segment":segment, "source_mesh_parameter_checks":source_checks, "left_shapedirs_fix":left_fix, + "official_settings":{"Mugsy_cameras/envmap_per_frame":{"cameras":20,"official_render_rate_fps":5,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False}, + "Mugsy_cameras/envmap_per_segment":{"cameras":5,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True}, + "Ego_cameras/envmap_per_frame":{"cameras":1,"official_render_rate_fps":30,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False}, + "Ego_cameras/envmap_per_segment":{"cameras":1,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True}}, + "views":[], "human_review":"pending"} + status = json.loads(status_path.read_text(encoding="utf-8")); status.update(phase="converting_complete_pilot_v2", streams_completed=[], updated_at=now()); atomic_json(status_path,status) + release = root / "shared-v1.0" + for family, view_type, variant, camera_id, image_root, ids in streams: + # Camera family belongs to the second-level view metadata. The first + # level identifies the parent capture, render setting and official + # source-frame span of the short sequence. + sequence_id = f"{capture}__{variant}__{segment_ids[0]}__{segment_ids[-1]}" + view = release / "data" / sequence_id / camera_id + positions = [id_to_index[frame] for frame in ids]; T=len(ids) + image_paths = [image_root / f"{frame:06d}.png" for frame in ids] + first=Image.open(image_paths[0]).convert("RGB"); width,height=first.size + rgb_hashes=encode_lossless_video(image_paths,view/"observation/rgb.mkv",(width,height),Image) + if view_type=="ego": + camera_rows=[json.loads((source/family/variant/"cam_params"/f"{frame:06d}.json").read_text()) for frame in ids] + else: camera_rows=[mugsy_params[camera_id]]*T + intrinsic=np.stack([[[r["focal"][0],0,r["princpt"][0]],[0,r["focal"][1],r["princpt"][1]],[0,0,1]] for r in camera_rows]).astype(np.float32) + extrinsic=np.broadcast_to(np.eye(4,dtype=np.float32),(T,4,4)).copy(); extrinsic[:,:3,:3]=np.stack([r["R"] for r in camera_rows]); extrinsic[:,:3,3]=np.stack([r["t"] for r in camera_rows])/1000 + distortion=np.stack([r["D"] for r in camera_rows]).astype(np.float32) if view_type=="ego" else None + valid=np.ones(T,dtype=bool) + mano_valid=np.ones((T,2),dtype=bool); truncation=None + if view_type=="ego": + truncation_map=json.loads((source/family/variant/"truncation_ratio.json").read_text()) + truncation=np.asarray([truncation_map[f"{frame:06d}"] for frame in ids],dtype=np.float32) + mano_valid[truncation < .2]=False + for name,value in [("intrinsic",intrinsic),("extrinsic",extrinsic)]: + save_tensor(view/"camera"/(name+".pt"),value,torch,np); save_tensor(view/"camera"/(name+"_valid.pt"),valid,torch,np) + if distortion is not None: + save_tensor(view/"camera/distortion.pt",distortion,torch,np); save_tensor(view/"camera/distortion_valid.pt",valid,torch,np) + motion=np.empty((T,2,61),dtype=np.float32); checks=[] + for hand_index,side in enumerate(["left","right"]): + pose,betas,translation=native[side] + converted,error,_=camera_mano(models[hand_index],pose[positions],betas[positions],translation[positions],extrinsic,np,cv2) + motion[:,hand_index]=converted; checks.append({"side":side,"max_vertex_error_m":error}) + save_tensor(view/"annotation/mano/motion.pt",motion,torch,np); save_tensor(view/"annotation/mano/motion_valid.pt",mano_valid,torch,np) + mask_root=source/family/variant/"masks"/(camera_id if view_type=="exo" else "") + mask_paths=[mask_root/f"{frame:06d}.png" for frame in ids] + if not all(p.is_file() for p in mask_paths): raise RuntimeError(f"Missing native masks: {family}/{variant}/{camera_id}") + histogram=encode_mask_video(mask_paths,view/"annotation/segment/mask.mkv",(width,height),Image,np) + save_tensor(view/"annotation/segment/mask_valid.pt",valid,torch,np); save_tensor(view/"observation/rgb_valid.pt",valid,torch,np) + archive=f"raw/data/{capture}/{family}/{variant}.tar.gz" + image_member=f"{variant}/images/{'' if view_type=='ego' else camera_id+'/' }{{source_frame_id:06d}}.png" + mask_member=f"{variant}/masks/{'' if view_type=='ego' else camera_id+'/' }{{source_frame_id:06d}}.png" + camera_locator=({"archive_prefix":archive,"member_template":f"{variant}/cam_params/{{source_frame_id:06d}}.json"} if view_type=="ego" else {"file":f"raw/data/{capture}/Mugsy_cameras/cam_params.json","camera_id":camera_id}) + components={ + "rgb":component("observation/rgb.mkv","observation/rgb_valid.pt","rgb/uint8/v1",["T","height","width","channel"],["T"],{"archive_prefix":archive,"member_template":image_member},"Source PNG decoded to RGB and losslessly stored as FFV1",storage={"profile":"mkv/ffv1_rgb24/v1","codec":"ffv1","pixel_format":"rgb24","source_lossy":False},storage_fps=1,timebase_role="index_only"), + "intrinsic":component("camera/intrinsic.pt","camera/intrinsic_valid.pt","camera/opencv_fisheye4/v1" if view_type=="ego" else "camera/pinhole/v1",["T","row","column"],["T"],camera_locator,"Native focal and principal point retained"), + "extrinsic":component("camera/extrinsic.pt","camera/extrinsic_valid.pt","transform/se3/v1",["T","row","column"],["T"],camera_locator,"Native R retained; t converted mm to m",unit="m",convention="T_camera_from_world"), + "mano":component("annotation/mano/motion.pt","annotation/mano/motion_valid.pt","mano/axis_angle61/v1",["T","hand","parameter"],["T","hand"],{"archive_prefix":f"raw/data/{capture}/mano_fits/mano_fits.tar.gz","member_template":"params/{source_frame_id}_{left|right}.json"},"Native MANO mean expanded and root-corrected into camera coordinates",unit="m",angle_unit="rad",coordinate_frame="camera",model_profile={"version":"MANO-v1.2","flat_hand_mean":True,"left_shapedirs_fix":left_fix},valid_policy={"semantics":"usable_annotation","formula":"source present and finite; for ego, official truncation_ratio >= 0.2"}), + "segment":component("annotation/segment/mask.mkv","annotation/segment/mask_valid.pt","segment/foreground_intensity/v1",["T","height","width"],["T"],{"archive_prefix":archive,"member_template":mask_member},"Native uint8 non-binary foreground intensity retained losslessly",value_range=[0,255],normalization_scale=1/255,foreground_category="hand",identity_semantics="left and right union; no per-hand identity")} + if distortion is not None: + components["intrinsic"]["distortion_ref"]="camera/distortion.pt"; components["distortion"]=component("camera/distortion.pt","camera/distortion_valid.pt","camera/fisheye4_distortion/v1",["T","parameter"],["T"],camera_locator,"Native four-coefficient fisheye distortion retained",parameter_names=["k1","k2","k3","k4"]) + independent = variant == "envmap_per_frame" + frames=[{"frame_index":i,"sample_id":f"{capture}:{family}:{variant}:{camera_id}:{frame}","source_frame_id":str(frame),"timestamp_ns":None,"clock_domain":None,"sync_id":f"{capture}:{frame}","source_locator":{"capture":capture,"segment":segment,"render_setting":f"{family}/{variant}","source_frame_id":str(frame)}} for i,frame in enumerate(ids)] + write_jsonl(view/"camera/frames.jsonl",frames) + official_render_rate_fps=5 if family=="Mugsy_cameras" and independent else 30 + sample_type="image" if independent else "video" + sampling={"type":"independent" if independent else "dense","source_fps":None if independent else official_render_rate_fps,"frames_ref":"camera/frames.jsonl","selection":"All available frames for this official action/render setting","time_semantics":"independent rendered images; container index is not time" if independent else "official video frame order and documented source FPS; timestamps not inferred","temporal_relationship":not independent} + metadata={"schema_version":"hand-warehouse/1.0","storage_revision":"lossless-video-2026-09-25","dataset_id":"ReInterHand","release_id":"shared-v1.0","sequence_id":sequence_id,"sequence_id_role":"batch_identifier_only" if independent else "temporal_sequence","source_capture_id":capture,"source_segment_id":segment,"source_frame_span":[segment_ids[0],segment_ids[-1]],"camera_id":camera_id,"sample_type":sample_type,"num_frames":T,"hand_slots":["left","right"],"sampling":sampling,"camera":{"model":"opencv_fisheye4" if view_type=="ego" else "pinhole","schema_id":"camera/opencv_fisheye4/v1" if view_type=="ego" else "camera/pinhole/v1","image_size":[width,height]},**official_split_metadata(capture),"view_type":view_type,"source_rendering":{"camera_family":family,"background_policy":variant,"synthetic_background_variant":True,"official_split_kind":"frame_based" if independent else "video_based","official_render_rate_fps":official_render_rate_fps,"camera_randomized_per_image":bool(independent and view_type=="ego")},"components":components,"pilot":True,"pilot_complete":True,"pilot_human_review":"pending","full_output_human_review":"not_started","upload_authorized":False,"omitted_components":{"depth":"not present","contact":"not present","keypoints_xyz":"orig_fits keypoints are an auxiliary fitting source; MANO and source meshes are retained as the selected geometric supervision"}} + atomic_json(view/"metainfo.json",metadata) + report["views"].append({"sequence_id":sequence_id,"camera_id":camera_id,"view_type":view_type,"camera_family":family,"background_variant":variant,"sample_type":sample_type,"sampling_type":sampling["type"],"source_fps":sampling["source_fps"],"official_render_rate_fps":official_render_rate_fps,"temporal_relationship":not independent,"frames":T,"source_frame_ids":ids,"image_size":[width,height],"rgb_full_frame_roundtrip":"passed","rgb_frame_sha256_count":len(rgb_hashes),"mano_camera_transform_checks":checks,"mano_valid_frames":int(mano_valid[:,0].sum()),"official_truncation_excluded_frames":0 if truncation is None else int((truncation<.2).sum()),"foreground_histogram":histogram}) + key=f"{family}/{variant}/{camera_id}"; status["streams_completed"].append(key); status.update(active_stream=key,updated_at=now()); atomic_json(status_path,status) + validation=release/"doc/validation"; validation.mkdir(parents=True,exist_ok=True); atomic_json(validation/"report.json",report) + shutil.copy2(Path(__file__),release/"script"/Path(__file__).name) + status.update(phase="complete_pilot_v2_converted_pending_render",active_stream=None,updated_at=now()); atomic_json(status_path,status) + + +def write_complete_pilot_v2_html(report: dict, validation: Path) -> None: + groups=[] + for setting,details in report["official_settings"].items(): + rows=[r for r in report["views"] if f"{r['camera_family']}/{r['background_variant']}"==setting] + cards=[] + independent = details["sample_type"] == "image" + for row in rows: + amount = (f"{row['frames']} independent images · index-only review container" + if independent else f"{row['frames']} frames @ {row['source_fps']} FPS") + cards.append(f"

    {row['camera_id']} · {row['view_type']} · {amount}

    Full MANO mesh: cyan left, orange right. Source/shared projection max {row['source_vs_shared_projection_max_px']:.4f}px. MANO valid {row['mano_valid_frames']}/{row['frames']}; official truncation exclusions {row['official_truncation_excluded_frames']}.

    Native foreground mask
    ") + semantics = (f"Frame-based independent-image split. These are not video frames: source FPS is null and adjacent container entries must not be treated as a continuous timeline. The official renderer sampled source motion at {details['official_render_rate_fps']} FPS. The MKV files below are lossless index-only packages for convenient review." + if independent else f"Video-based split. Temporal order is meaningful; official source rate {details['official_render_rate_fps']} FPS.") + groups.append(f"

    {setting}

    {details['cameras']} camera stream(s). {semantics}

    {''.join(cards)}") + segment=report["segment"] + html=f"""ReInterHand complete pilot validation

    ReInterHand pilot · all official settings

    Human review: pending

    Action {segment}. Coverage: 27 camera/setting streams: Mugsy frame-based 20 exo cameras, Mugsy video-based 5 exo cameras, Ego frame-based 1 view, and Ego video-based 1 view. These are rendering/background variants, not extra physical camera types.

    Media semantics: both envmap_per_frame settings are independent image collections, not videos. Ego additionally randomizes camera position for every image. Their MKV files are only lossless batch containers and review players; playback order must not be used as motion, tracking, timing, velocity, or temporal supervision. Both envmap_per_segment settings are genuine video-based sequences.

    Selected shared modalities: RGB, native non-binary foreground mask, camera intrinsics/extrinsics, ego fisheye distortion, and left/right MANO. Source MANO parameters reproduce the supplied PLY meshes before camera conversion. The raw release also contains orig_fits 3D keypoints used during fitting; they are disclosed but intentionally not duplicated because MANO is the selected standardized geometric supervision. No native depth, object pose/model or contact labels exist in this release scope.

    Main review players use two large panels so MANO is readable. Mask players are separate expanders. Every available item is rendered. Source frame IDs remain explicit; timestamps are absent.

    {''.join(groups)}

    Machine-readable report

    """ + (validation/"index.html").write_text(html,encoding="utf-8") + + +def fix_complete_pilot_v2_media_semantics(root: Path) -> None: + release=root/"shared-v1.0"; validation=release/"doc/validation"; report_path=validation/"report.json" + report=json.loads(report_path.read_text(encoding="utf-8")) + if report.get("schema")!="reinterhand-pilot-validation/v2": raise RuntimeError("Complete pilot v2 report required") + settings={ + "Mugsy_cameras/envmap_per_frame":{"cameras":20,"official_render_rate_fps":5,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False}, + "Mugsy_cameras/envmap_per_segment":{"cameras":5,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True}, + "Ego_cameras/envmap_per_frame":{"cameras":1,"official_render_rate_fps":30,"split_kind":"frame_based","sample_type":"image","temporal_relationship":False}, + "Ego_cameras/envmap_per_segment":{"cameras":1,"official_render_rate_fps":30,"split_kind":"video_based","sample_type":"video","temporal_relationship":True}} + report["official_settings"]=settings + for row in report["views"]: + key=f"{row['camera_family']}/{row['background_variant']}"; setting=settings[key]; independent=not setting["temporal_relationship"] + row.update(sample_type=setting["sample_type"],sampling_type="independent" if independent else "dense",source_fps=None if independent else setting["official_render_rate_fps"],official_render_rate_fps=setting["official_render_rate_fps"],temporal_relationship=not independent) + view=release/"data"/row["sequence_id"]/row["camera_id"] + metadata=json.loads((view/"metainfo.json").read_text(encoding="utf-8")) + metadata.update(sample_type=setting["sample_type"],sequence_id_role="batch_identifier_only" if independent else "temporal_sequence") + metadata["sampling"]={"type":"independent" if independent else "dense","source_fps":None if independent else setting["official_render_rate_fps"],"frames_ref":"camera/frames.jsonl","selection":"All available frames for this official action/render setting","time_semantics":"independent rendered images; container index is not time" if independent else "official video frame order and documented source FPS; timestamps not inferred","temporal_relationship":not independent} + metadata["source_rendering"].update(official_split_kind=setting["split_kind"],official_render_rate_fps=setting["official_render_rate_fps"],camera_randomized_per_image=bool(independent and row["view_type"]=="ego")) + atomic_json(view/"metainfo.json",metadata) + frames=[] + for frame in (view/"camera/frames.jsonl").read_text(encoding="utf-8").splitlines(): + item=json.loads(frame); item["sample_id"]=f"{report['capture']}:{row['camera_family']}:{row['background_variant']}:{row['camera_id']}:{item['source_frame_id']}"; frames.append(item) + write_jsonl(view/"camera/frames.jsonl",frames) + report["media_semantics"]={"envmap_per_frame":"independent images; MKV is an index-only lossless batch container; no temporal continuity","envmap_per_segment":"video sequence with temporal order","corrected_at":now()} + atomic_json(report_path,report); write_complete_pilot_v2_html(report,validation); shutil.copy2(Path(__file__),release/"script"/Path(__file__).name) + status_path=root/"tmp/pilot-v1.0/status.json"; status=json.loads(status_path.read_text(encoding="utf-8")); status.update(phase="pilot_ready_for_human_review",media_semantics_corrected=True,updated_at=now()); atomic_json(status_path,status) + + +def render_complete_pilot_v2(root: Path, runtime: Path, capture: str, segment: str) -> None: + np, torch, cv2, Image, smplx = runtime_imports(runtime) + state=root/"tmp/pilot-v1.0"; status_path=state/"status.json"; source=state/"extracted"/f"{capture}__{segment}" + release=root/"shared-v1.0"; validation=release/"doc/validation"; report_path=validation/"report.json"; report=json.loads(report_path.read_text()) + if report.get("schema")!="reinterhand-pilot-validation/v2": raise RuntimeError("Complete pilot v2 conversion report required") + models=[ManoModel("left",runtime/"models",np,torch,smplx),ManoModel("right",runtime/"models",np,torch,smplx)] + if report["left_shapedirs_fix"]: + models[0].data["shapedirs"][:,0]*=-1 + with torch.no_grad(): models[0].layer.shapedirs[:,0]*=-1 + faces=np.asarray(models[0].data["f"],dtype=np.int64) + all_ids=frame_ids(root/"raw/data"/capture,segment) + source_meshes={side:{frame:read_ply_vertices(source/"mano_fits/meshes"/f"{frame}_{side}.ply",np) for frame in all_ids} for side in ["left","right"]} + status=json.loads(status_path.read_text()); status.update(phase="rendering_complete_pilot_v2",review_streams_completed=[],updated_at=now()); atomic_json(status_path,status) + for row in report["views"]: + view=release/"data"/row["sequence_id"]/row["camera_id"]; ids=[int(x) for x in row["source_frame_ids"]] + family=row["camera_family"]; variant=row["background_variant"]; view_type=row["view_type"] + image_root=source/family/variant/"images"/(row["camera_id"] if view_type=="exo" else "") + mask_root=source/family/variant/"masks"/(row["camera_id"] if view_type=="exo" else "") + width,height=row["image_size"] + intrinsic=torch.load(view/"camera/intrinsic.pt",map_location="cpu",weights_only=True).numpy() + extrinsic=torch.load(view/"camera/extrinsic.pt",map_location="cpu",weights_only=True).numpy() + distortion=torch.load(view/"camera/distortion.pt",map_location="cpu",weights_only=True).numpy() if (view/"camera/distortion.pt").exists() else None + motion=torch.load(view/"annotation/mano/motion.pt",map_location="cpu",weights_only=True).numpy() + current={} + for index,side in enumerate(["left","right"]): current[side],_=models[index].geometry(motion[:,index,:48],motion[:,index,48:58],motion[:,index,58:]) + pixel_errors=[] + def mano_panels(): + for i,frame in enumerate(ids): + original=Image.open(image_root/f"{frame:06d}.png").convert("RGB"); points={} + for side in ["left","right"]: + source_camera=source_meshes[side][frame]@extrinsic[i,:3,:3].T+extrinsic[i,:3,3] + src_uv,src_visible=project_vertices(source_camera,intrinsic[i],None if distortion is None else distortion[i],np,cv2) + cur_uv,cur_visible=project_vertices(current[side][i],intrinsic[i],None if distortion is None else distortion[i],np,cv2) + good=src_visible&cur_visible&np.isfinite(src_uv).all(1)&np.isfinite(cur_uv).all(1) + if good.any(): pixel_errors.extend(np.linalg.norm(src_uv[good]-cur_uv[good],axis=1).tolist()) + points[side]=cur_uv + overlay=draw_mano_meshes(original,points,faces,Image); canvas=Image.new("RGB",(width*2,height)) + canvas.paste(label_panel(original,f"RGB | {variant} | source frame {frame}",Image),(0,0)); canvas.paste(label_panel(overlay,"shared MANO mesh | cyan left, orange right",Image),(width,0)); yield canvas + safe=f"{family[:-8].lower()}__{variant}__{row['camera_id']}"; mano_video=Path("media")/f"{safe}__mano.mp4" + rendered=render_review_video(mano_panels(),validation/mano_video,(width,height),panels=2) + def mask_panels(): + for frame in ids: + original=Image.open(image_root/f"{frame:06d}.png").convert("RGB"); mask=draw_foreground_intensity(original,mask_root/f"{frame:06d}.png",Image); canvas=Image.new("RGB",(width*2,height)); canvas.paste(label_panel(original,f"RGB | {variant} | source frame {frame}",Image),(0,0)); canvas.paste(label_panel(mask,"native non-binary foreground mask",Image),(width,0)); yield canvas + mask_video=Path("media")/f"{safe}__mask.mp4"; mask_rendered=render_review_video(mask_panels(),validation/mask_video,(width,height),panels=2) + if rendered!=len(ids) or mask_rendered!=len(ids) or not pixel_errors: raise RuntimeError(f"Review failure: {safe}") + row.update(visual_review_video=mano_video.as_posix(),mask_review_video=mask_video.as_posix(),visual_review_frames=rendered,source_vs_shared_projection_max_px=float(max(pixel_errors)),source_vs_shared_projection_mean_px=float(sum(pixel_errors)/len(pixel_errors))) + status["review_streams_completed"].append(safe); status.update(active_stream=safe,updated_at=now()); atomic_json(status_path,status) + report["automatic_status"]="passed"; report["visual_scope"]="every available frame in all 27 streams across all four official settings"; report["completed_at"]=now(); atomic_json(report_path,report) + write_complete_pilot_v2_html(report,validation); shutil.copy2(Path(__file__),release/"script"/Path(__file__).name) + status.update(phase="pilot_ready_for_human_review",active_stream=None,expanded_review=True,updated_at=now()); atomic_json(status_path,status) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + subcommands = parser.add_subparsers(dest="command", required=True) + extract = subcommands.add_parser("extract-pilot") + extract.add_argument("--root", type=Path, required=True) + extract.add_argument("--capture", default=CAPTURE) + extract.add_argument("--segment", default=SEGMENT) + convert = subcommands.add_parser("convert-pilot") + convert.add_argument("--root", type=Path, required=True) + convert.add_argument("--runtime", type=Path, required=True) + convert.add_argument("--capture", default=CAPTURE) + convert.add_argument("--segment", default=SEGMENT) + render = subcommands.add_parser("render-pilot") + render.add_argument("--root", type=Path, required=True) + render.add_argument("--runtime", type=Path, required=True) + render.add_argument("--capture", default=CAPTURE) + render.add_argument("--segment", default=SEGMENT) + variant = subcommands.add_parser("extract-background-variant") + variant.add_argument("--root", type=Path, required=True) + variant.add_argument("--capture", default=CAPTURE) + variant.add_argument("--segment", default=SEGMENT) + variant.add_argument("--variant", choices=["envmap_per_frame", "envmap_per_segment"], required=True) + expanded = subcommands.add_parser("render-expanded-review") + expanded.add_argument("--root", type=Path, required=True) + expanded.add_argument("--runtime", type=Path, required=True) + expanded.add_argument("--capture", default=CAPTURE) + expanded.add_argument("--segment", default=SEGMENT) + complete = subcommands.add_parser("convert-complete-pilot-v2") + complete.add_argument("--root", type=Path, required=True) + complete.add_argument("--runtime", type=Path, required=True) + complete.add_argument("--capture", default=CAPTURE) + complete.add_argument("--segment", default=SEGMENT) + semantics = subcommands.add_parser("fix-pilot-v2-media-semantics") + semantics.add_argument("--root", type=Path, required=True) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if args.command == "extract-pilot": + extract_pilot(args.root.resolve(), args.capture, args.segment) + elif args.command == "convert-pilot": + convert_pilot(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment) + elif args.command == "render-pilot": + render_pilot(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment) + elif args.command == "extract-background-variant": + extract_background_variant(args.root.resolve(), args.capture, args.segment, args.variant) + elif args.command == "render-expanded-review": + render_complete_pilot_v2(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment) + elif args.command == "convert-complete-pilot-v2": + convert_complete_pilot_v2(args.root.resolve(), args.runtime.resolve(), args.capture, args.segment) + elif args.command == "fix-pilot-v2-media-semantics": + fix_complete_pilot_v2_media_semantics(args.root.resolve()) + + +if __name__ == "__main__": + main() diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/preprocess_reinterhand_full.py b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/preprocess_reinterhand_full.py new file mode 100644 index 0000000000000000000000000000000000000000..c13f47281586491a7d473063ffa9e09cc80b8d5d --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/preprocess_reinterhand_full.py @@ -0,0 +1,379 @@ +"""Restartable full ReInterHand conversion using the accepted pilot logic. + +Each capture archive is streamed exactly once into a capture-local scratch +directory. Segments are converted independently and committed only after a +manifest has been written. Raw data is opened read-only. Capture scratch is +removed only after every official segment has a verified checkpoint. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import shutil +import subprocess +import sys +import tarfile +import time +import traceback + +import preprocess_reinterhand as pilot + + +def atomic_json(path: Path, value: object) -> None: + pilot.atomic_json(path, value) + + +def file_sha256(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as f: + for block in iter(lambda: f.read(8 * 1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def capture_names(root: Path) -> list[str]: + return sorted(p.name for p in (root / "raw" / "data").iterdir() + if p.is_dir() and (p / "frame_list.txt").is_file()) + + +def segment_names(capture_root: Path) -> list[str]: + result: list[str] = [] + seen: set[str] = set() + frame_ids: set[int] = set() + for line in (capture_root / "frame_list.txt").read_text(encoding="utf-8").splitlines(): + row = line.split() + if len(row) < 2: + continue + frame = int(row[1]) + if frame in frame_ids: + raise RuntimeError(f"Frame ID appears in multiple rows: {capture_root.name}:{frame}") + frame_ids.add(frame) + if row[0] not in seen: + result.append(row[0]); seen.add(row[0]) + if not result: + raise RuntimeError(f"No official segments: {capture_root}") + return result + + +def wanted(group: str, member_name: str, valid_frames: set[str]) -> bool: + return pilot.wanted(group, member_name, valid_frames) + + +def extract_group(group: str, parts: list[Path], destination: Path, + valid_frames: set[str], status_path: Path, status: dict) -> dict: + out_root = destination / group + out_root.mkdir(parents=True, exist_ok=True) + process = subprocess.Popen(["cat", *map(str, parts)], stdout=subprocess.PIPE) + assert process.stdout is not None + scanned = selected = selected_bytes = 0 + try: + with tarfile.open(fileobj=process.stdout, mode="r|gz") as archive: + for member in archive: + if not member.isfile(): + continue + scanned += 1 + if not wanted(group, member.name, valid_frames): + continue + rel = PurePosixPath(member.name) + if rel.is_absolute() or ".." in rel.parts: + raise RuntimeError(f"Unsafe member: {member.name}") + output = out_root.joinpath(*rel.parts) + if not output.resolve().is_relative_to(out_root.resolve()): + raise RuntimeError(f"Member escapes scratch: {member.name}") + output.parent.mkdir(parents=True, exist_ok=True) + source = archive.extractfile(member) + if source is None: + raise RuntimeError(f"Cannot read {member.name}") + temporary = output.with_name(output.name + ".partial") + with source, temporary.open("wb") as target: + shutil.copyfileobj(source, target, length=8 * 1024 * 1024) + if temporary.stat().st_size != member.size: + raise RuntimeError(f"Extracted size mismatch: {member.name}") + os.replace(temporary, output) + selected += 1; selected_bytes += member.size + if selected % 250 == 0: + status.update(phase="extracting", active_group=group, + members_scanned=scanned, selected_files=selected, + selected_bytes=selected_bytes, updated_at=pilot.now()) + atomic_json(status_path, status) + finally: + process.stdout.close() + code = process.wait() + if code != 0: + raise RuntimeError(f"cat failed for {group}: {code}") + return {"group": group, "members_scanned": scanned, + "selected_files": selected, "selected_bytes": selected_bytes} + + +def extract_capture(root: Path, capture: str, state: Path) -> Path: + capture_root = root / "raw" / "data" / capture + destination = state / "scratch" / capture + marker = destination / "extraction-complete.json" + if marker.exists(): + data = json.loads(marker.read_text(encoding="utf-8")) + if data.get("capture") == capture and data.get("complete") is True: + return destination + raise RuntimeError(f"Invalid extraction marker: {marker}") + destination.mkdir(parents=True, exist_ok=True) + status_path = state / "captures" / capture / "status.json" + status = {"schema":"reinterhand-full-capture-status/v1", "capture":capture, + "phase":"extracting", "started_at":pilot.now(), "updated_at":pilot.now()} + atomic_json(status_path, status) + all_ids = {str(value) for segment in segment_names(capture_root) + for value in pilot.frame_ids(capture_root, segment)} + sources = { + "Ego_cameras/envmap_per_frame": ("Ego_cameras", pilot.canonical_parts(capture_root / "Ego_cameras", "envmap_per_frame.tar.gz")), + "Ego_cameras/envmap_per_segment": ("Ego_cameras", pilot.canonical_parts(capture_root / "Ego_cameras", "envmap_per_segment.tar.gz")), + "Mugsy_cameras/envmap_per_frame": ("Mugsy_cameras", pilot.canonical_parts(capture_root / "Mugsy_cameras", "envmap_per_frame.tar.gz")), + "Mugsy_cameras/envmap_per_segment": ("Mugsy_cameras", pilot.canonical_parts(capture_root / "Mugsy_cameras", "envmap_per_segment.tar.gz")), + "mano_fits": ("mano_fits", pilot.canonical_parts(capture_root / "mano_fits", "mano_fits.tar.gz")), + } + results=[] + for label,(group,parts) in sources.items(): + status.update(active_archive=label, updated_at=pilot.now()); atomic_json(status_path,status) + results.append(extract_group(group, parts, destination, all_ids, status_path, status)) + target = destination / "Mugsy_cameras" / "cam_params.json" + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(capture_root / "Mugsy_cameras" / "cam_params.json", target) + atomic_json(marker, {"schema":"reinterhand-full-extraction/v1", "capture":capture, + "complete":True, "valid_frame_count":len(all_ids), + "archives":results, "completed_at":pilot.now()}) + return destination + + +def tree_manifest(base: Path) -> list[dict]: + rows=[] + for p in sorted(x for x in base.rglob("*") if x.is_file()): + rows.append({"path":p.relative_to(base).as_posix(), "bytes":p.stat().st_size, + "sha256":file_sha256(p)}) + return rows + + +def decoded_video_sha256(path: Path) -> str: + """Hash FFmpeg's per-frame checksums, excluding non-semantic MKV UIDs.""" + process = subprocess.Popen( + ["ffmpeg", "-v", "error", "-threads", "1", "-i", str(path), + "-f", "framemd5", "-"], stdout=subprocess.PIPE + ) + assert process.stdout is not None + h = hashlib.sha256() + for block in iter(lambda: process.stdout.read(1024 * 1024), b""): + h.update(block) + if process.wait() != 0: + raise RuntimeError(f"Cannot decode existing video for comparison: {path}") + return h.hexdigest() + + +def existing_matches(source: Path, target: Path, manifest: list[dict]) -> bool: + if not target.is_dir(): return False + current=[] + for row in manifest: + p=target/row["path"] + if not p.is_file() or p.stat().st_size != row["bytes"]: + return False + if file_sha256(p) != row["sha256"]: + candidate = source / row["path"] + if p.suffix.lower() != ".mkv" or decoded_video_sha256(p) != decoded_video_sha256(candidate): + return False + current.append(row["path"]) + return sorted(p.relative_to(target).as_posix() for p in target.rglob("*") if p.is_file()) == current + + +def regroup_camera_families(work: Path, report: dict, capture: str, segment: str) -> list[str]: + """Keep render setting in level one and all cameras/views in level two.""" + data = work / "shared-v1.0" / "data" + expected = {"envmap_per_frame": 21, "envmap_per_segment": 6} + ids=pilot.frame_ids(work/"raw/data"/capture,segment) + span_start,span_end=ids[0],ids[-1] + desired_ids=[] + for variant, camera_count in expected.items(): + desired_id=f"{capture}__{variant}__{span_start}__{span_end}" + desired=data/desired_id + legacy=[data/f"{capture}__{segment}__{family}__{variant}" for family in ("ego","mugsy")] + if desired.exists() and any(path.exists() for path in legacy): + raise RuntimeError(f"Mixed direct and legacy layouts: {desired_id}") + if not desired.exists(): + desired.mkdir(parents=True,exist_ok=False) + for old in legacy: + if not old.is_dir(): raise RuntimeError(f"Missing temporary family directory: {old}") + old_id=old.name + for camera in sorted(p for p in old.iterdir() if p.is_dir()): + target=desired/camera.name + if target.exists(): raise RuntimeError(f"Camera collision while regrouping: {target}") + metainfo=json.loads((camera/"metainfo.json").read_text(encoding="utf-8")) + if metainfo.get("sequence_id") != old_id: raise RuntimeError(f"Unexpected sequence_id: {camera}") + metainfo["sequence_id"]=desired_id + # The accepted pilot converter is reused for the numerical + # conversion, but committed production views must not + # advertise themselves as pilot output. + for key in ("pilot", "pilot_complete", "pilot_human_review"): + metainfo.pop(key, None) + metainfo["conversion_scope"]="full" + metainfo["full_conversion_complete"]=True + metainfo["full_output_human_review"]="pending" + atomic_json(camera/"metainfo.json",metainfo) + os.replace(camera,target) + old.rmdir() + cameras=sorted(p.name for p in desired.iterdir() if p.is_dir()) + if len(cameras)!=camera_count or "ego" not in cameras: + raise RuntimeError(f"Unexpected regrouped camera coverage: {desired_id}: {cameras}") + desired_ids.append(desired_id) + for row in report["views"]: + if row["background_variant"]==variant: + row["sequence_id"]=desired_id + return desired_ids + + +def convert_segment(root: Path, runtime: Path, state: Path, capture: str, + segment: str, extracted: Path) -> dict: + checkpoint = state / "checkpoints" / capture / f"{segment}.json" + if checkpoint.exists(): + value=json.loads(checkpoint.read_text(encoding="utf-8")) + if value.get("phase")=="complete": return value + raise RuntimeError(f"Non-complete checkpoint requires investigation: {checkpoint}") + work = state / "work" / capture / segment + if work.exists(): shutil.rmtree(work) + (work / "tmp" / "pilot-v1.0" / "extracted").mkdir(parents=True) + (work / "shared-v1.0" / "script").mkdir(parents=True) + os.symlink(root / "raw", work / "raw", target_is_directory=True) + os.symlink(extracted, work / "tmp" / "pilot-v1.0" / "extracted" / f"{capture}__{segment}", target_is_directory=True) + atomic_json(work/"tmp/pilot-v1.0/status.json", {"schema":"reinterhand-full-segment-status/v1", + "capture":capture,"segment":segment,"phase":"converting","started_at":pilot.now()}) + pilot.convert_complete_pilot_v2(work, runtime, capture, segment) + report=json.loads((work/"shared-v1.0/doc/validation/report.json").read_text(encoding="utf-8")) + if len(report.get("views",[])) != 27: + raise RuntimeError(f"Expected 27 streams, got {len(report.get('views',[]))}") + sequence_ids=regroup_camera_families(work,report,capture,segment) + committed=[]; all_manifest=[] + for sequence_id in sequence_ids: + source=work/"shared-v1.0/data"/sequence_id + manifest=tree_manifest(source) + target=root/"shared-v1.0/data"/sequence_id + if target.exists(): + if not existing_matches(source,target,manifest): + raise RuntimeError(f"Existing output differs: {target}") + shutil.rmtree(source) + else: + target.parent.mkdir(parents=True,exist_ok=True) + os.replace(source,target) + committed.append(sequence_id) + # The checkpoint always describes the actual committed tree. This is + # relevant when a previously accepted MKV is semantically identical + # but has a different Matroska segment UID. + all_manifest.extend({"sequence_id":sequence_id,**row} for row in tree_manifest(target)) + value={"schema":"reinterhand-full-segment-checkpoint/v1","phase":"complete", + "capture":capture,"segment":segment,"sequence_ids":committed, + "views":27,"files":len(all_manifest),"bytes":sum(x["bytes"] for x in all_manifest), + "manifest_sha256":hashlib.sha256(json.dumps(all_manifest,sort_keys=True,separators=(",",":")).encode()).hexdigest(), + "source_mesh_parameter_checks":report["source_mesh_parameter_checks"], + "completed_at":pilot.now()} + atomic_json(checkpoint,value) + shutil.rmtree(work) + return value + + +def capture_worker(root: Path, runtime: Path, state: Path, capture: str) -> None: + status_path=state/"captures"/capture/"status.json" + try: + extracted=extract_capture(root,capture,state) + segments=segment_names(root/"raw/data"/capture) + completed=[] + for index,segment in enumerate(segments): + atomic_json(status_path,{"schema":"reinterhand-full-capture-status/v1","capture":capture, + "phase":"converting","active_segment":segment,"segments_total":len(segments), + "segments_completed":completed,"updated_at":pilot.now()}) + result=convert_segment(root,runtime,state,capture,segment,extracted) + completed.append(segment) + atomic_json(status_path,{"schema":"reinterhand-full-capture-status/v1","capture":capture, + "phase":"complete","segments_total":len(segments),"segments_completed":completed, + "completed_at":pilot.now(),"updated_at":pilot.now()}) + shutil.rmtree(extracted) + except Exception as exc: + atomic_json(status_path,{"schema":"reinterhand-full-capture-status/v1","capture":capture, + "phase":"failed","error_type":type(exc).__name__,"error":str(exc), + "traceback":traceback.format_exc(),"updated_at":pilot.now()}) + raise + + +def selected_capture_names(root: Path, captures_file: Path | None) -> list[str]: + available = capture_names(root) + if captures_file is None: + return available + requested = [line.strip() for line in captures_file.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#")] + if not requested or len(requested) != len(set(requested)): + raise RuntimeError(f"Empty or duplicate capture allowlist: {captures_file}") + unknown = sorted(set(requested) - set(available)) + if unknown: + raise RuntimeError(f"Capture allowlist contains unavailable captures: {unknown}") + return requested + + +def run_controller(root: Path, runtime: Path, workers: int, + captures_file: Path | None = None) -> None: + if workers < 1 or workers > 2: raise RuntimeError("Approved worker range is 1..2") + state=root/"tmp/full-preprocess-v1.0"; state.mkdir(parents=True,exist_ok=True) + lock=state/"controller.lock" + fd=os.open(lock,os.O_CREAT|os.O_EXCL|os.O_WRONLY) + os.write(fd,str(os.getpid()).encode()); os.close(fd) + status_path=state/"status.json"; captures=selected_capture_names(root, captures_file) + env=os.environ.copy() + for key in ["OMP_NUM_THREADS","MKL_NUM_THREADS","OPENBLAS_NUM_THREADS","NUMEXPR_NUM_THREADS"]: env[key]="1" + env["REINTERHAND_FFMPEG_THREADS"]="2" + pending=list(captures); running={}; completed=[] + try: + while pending or running: + while pending and len(running) None: + pilot.atomic_json(path, value) + + +def decode(ffmpeg: str, path: Path, width: int, height: int, pixel_format: str, channels: int): + process = subprocess.Popen( + [ffmpeg, "-v", "error", "-threads", "1", "-i", str(path), "-f", "rawvideo", "-pix_fmt", pixel_format, "-"], + stdout=subprocess.PIPE, + ) + assert process.stdout is not None + size = width * height * channels + while True: + block = process.stdout.read(size) + if not block: + break + if len(block) != size: + raise RuntimeError(f"short decoded frame: {path}") + yield block + if process.wait() != 0: + raise RuntimeError(f"decode failed: {path}") + + +def mask_intensity_panel(mask, np, Image): + """Render the native non-binary mask itself, without hiding it in RGB.""" + gray = Image.fromarray(mask.astype(np.uint8), "L").convert("RGB") + from PIL import ImageDraw + + draw = ImageDraw.Draw(gray) + width, height = gray.size + bar_width = min(280, max(120, width // 3)) + x0, y0 = 12, max(34, height - 42) + gradient = np.tile(np.arange(256, dtype=np.uint8), (14, 1)) + gradient = Image.fromarray(gradient, "L").resize((bar_width, 14)).convert("RGB") + gray.paste(gradient, (x0, y0)) + draw.rectangle((x0 - 1, y0 - 1, x0 + bar_width, y0 + 14), outline=(255, 70, 70), width=2) + draw.text((x0, y0 - 17), "mask intensity: 0 black -> 255 white", fill=(255, 70, 70)) + draw.text((x0, y0 + 17), f"frame min={int(mask.min())}, max={int(mask.max())}", fill=(255, 70, 70)) + return gray + + +def mano_legend(image, Image): + """Put an in-frame color legend next to the actual MANO overlay.""" + from PIL import ImageDraw + + result = image.copy() + draw = ImageDraw.Draw(result) + x0, y0 = 12, max(34, result.height - 54) + draw.rectangle((x0 - 6, y0 - 6, x0 + 238, y0 + 40), fill=(0, 0, 0)) + draw.rectangle((x0, y0, x0 + 20, y0 + 14), fill=(0, 255, 255)) + draw.text((x0 + 28, y0), "LEFT hand", fill=(255, 255, 255)) + draw.rectangle((x0 + 116, y0, x0 + 136, y0 + 14), fill=(255, 140, 0)) + draw.text((x0 + 144, y0), "RIGHT hand", fill=(255, 255, 255)) + return result + + +def render_view(view: Path, output: Path, runtime: Path, models, faces, ffmpeg: str, modules) -> dict: + np, torch, cv2, Image, _ = modules + metadata = json.loads((view / "metainfo.json").read_text(encoding="utf-8")) + width, height = metadata["camera"]["image_size"] + total = int(metadata["num_frames"]) + intrinsic = torch.load(view / "camera/intrinsic.pt", map_location="cpu", weights_only=True).numpy() + distortion_path = view / "camera/distortion.pt" + distortion = torch.load(distortion_path, map_location="cpu", weights_only=True).numpy() if distortion_path.exists() else None + motion = torch.load(view / "annotation/mano/motion.pt", map_location="cpu", weights_only=True).numpy() + valid = torch.load(view / "annotation/mano/motion_valid.pt", map_location="cpu", weights_only=True).numpy().astype(bool) + meshes = {} + for index, side in enumerate(("left", "right")): + meshes[side], _ = models[index].geometry(motion[:, index, :48], motion[:, index, 48:58], motion[:, index, 58:]) + rgb_frames = decode(ffmpeg, view / "observation/rgb.mkv", width, height, "rgb24", 3) + # The lossless shared mask container is gray16le, while the preserved + # native samples occupy the uint8 range 0..255. Asking FFmpeg for 8-bit + # ``gray`` rescales 0..65535 to 0..255 and therefore collapses native + # values 0..255 to almost all black. Decode the stored words verbatim and + # only then display their native intensity. + mask_frames = decode(ffmpeg, view / "annotation/segment/mask.mkv", width, height, "gray16le", 2) + frame_rows = [json.loads(line) for line in (view / "camera/frames.jsonl").read_text(encoding="utf-8").splitlines()] + relative = Path("media") / f"{metadata['sequence_id']}__{metadata['camera_id']}.mp4" + + def panels(): + count = 0 + for index, (rgb_bytes, mask_bytes) in enumerate(zip(rgb_frames, mask_frames)): + rgb = np.frombuffer(rgb_bytes, dtype=np.uint8).reshape(height, width, 3) + mask16 = np.frombuffer(mask_bytes, dtype=" 255: + raise RuntimeError(f"native mask exceeds declared uint8 range: {view} frame {index}") + mask = mask16.astype(np.uint8) + original = Image.fromarray(rgb, "RGB") + points = {} + for hand_index, side in enumerate(("left", "right")): + if valid[index, hand_index]: + uv, _ = pilot.project_vertices(meshes[side][index], intrinsic[index], None if distortion is None else distortion[index], np, cv2) + points[side] = uv + mano = mano_legend(pilot.draw_mano_meshes(original, points, faces, Image), Image) + masked = mask_intensity_panel(mask, np, Image) + source_id = frame_rows[index].get("source_frame_id") + canvas = Image.new("RGB", (width * 3, height)) + canvas.paste(pilot.label_panel(original, f"RGB | source frame {source_id}", Image), (0, 0)) + canvas.paste(pilot.label_panel(mano, "shared MANO | cyan left, orange right", Image), (width, 0)) + canvas.paste(pilot.label_panel(masked, "native non-binary mask | grayscale intensity", Image), (width * 2, 0)) + count += 1 + yield canvas + if count != total: + raise RuntimeError(f"decoded {count}/{total}: {view}") + + rendered = pilot.render_review_video(panels(), output / relative, (width, height), panels=3) + return { + "camera_id": metadata["camera_id"], "view_type": metadata["view_type"], + "frames": rendered, "video": relative.as_posix(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--release", required=True) + parser.add_argument("--runtime", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--host-label", required=True) + parser.add_argument("--samples-per-render", type=int, default=1) + parser.add_argument("--seed", type=int, default=20260927) + parser.add_argument("--ffmpeg", default="ffmpeg") + args = parser.parse_args() + release, runtime, output = Path(args.release).resolve(), Path(args.runtime).resolve(), Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + modules = pilot.runtime_imports(runtime) + np, torch, _, _, smplx = modules + models = [pilot.ManoModel("left", runtime / "models", np, torch, smplx), pilot.ManoModel("right", runtime / "models", np, torch, smplx)] + with torch.no_grad(): + models[0].data["shapedirs"][:, 0] *= -1 + models[0].layer.shapedirs[:, 0] *= -1 + faces = np.asarray(models[0].data["f"], dtype=np.int64) + groups = {"envmap_per_frame": [], "envmap_per_segment": []} + for path in sorted((release / "data").iterdir()): + if path.is_dir(): + kind = "envmap_per_frame" if "__envmap_per_frame__" in path.name else "envmap_per_segment" + groups[kind].append(path.name) + rng = random.Random(f"{args.seed}:{args.host_label}") + selected = [name for kind in sorted(groups) for name in rng.sample(groups[kind], min(args.samples_per_render, len(groups[kind])))] + status = { + "schema": "reinterhand-full-random-status/v1", "stage": "rendering", "seed": args.seed, + "host_label": args.host_label, "selected": selected, "completed": [], + "sampling": "uniform complete-sequence sampling within render-type stratum on the fixed server partition", + } + atomic_json(output / "status.json", status) + cards = [] + for sequence in selected: + sequence_root = release / "data" / sequence + rows = [render_view(view, output, runtime, models, faces, args.ffmpeg, modules) + for view in sorted(sequence_root.iterdir()) if (view / "metainfo.json").is_file()] + atomic_json(output / f"{sequence}.json", {"sequence": sequence, "views": rows}) + status["completed"].append(sequence) + atomic_json(output / "status.json", status) + videos = "".join( + f"
    {html.escape(row['camera_id'])} · {row['view_type']} · {row['frames']} frames" + f"
    " + for row in rows + ) + semantics = "独立图片集合;MKV 仅为无损批容器,播放顺序不是时间。" if "__envmap_per_frame__" in sequence else "真实时序视频序列。" + cards.append(f"

    {html.escape(sequence)}

    {semantics}

    {videos}
    ") + atomic_json(output / "sampling.json", { + "schema": "hand-warehouse-full-random-sampling/v1", "dataset_id": "ReInterHand", + "seed": args.seed, "host_partition": args.host_label, + "method": status["sampling"], "population": {key: len(value) for key, value in groups.items()}, + "selected_sequences": selected, "all_cameras": True, "all_frames": True, + }) + atomic_json(output / "human-review.json", { + "dataset_id": "ReInterHand", "stage": "full_random", "status": "pending", + "reviewed_report": "index.html", "confirmed_at": None, "confirmed_by": None, + "notes": "Content fingerprints and automatic checks do not constitute human approval.", + }) + page = f""" +ReInterHand full random {html.escape(args.host_label)} +

    ReInterHand 全量随机抽查 · {html.escape(args.host_label)}

    人工审核:待确认

    +

    固定随机种子 {args.seed};按渲染类型分层抽取完整短序列,展示抽中序列的全部相机和全部帧。每个视频依次显示 RGB、MANO 网格投影、原生非二值 mask 强度图。

    +

    MANO 图例: 青色=左手; 橙色=右手。Mask 图例:黑色=0,白色=255;这是连续强度,不是左右手类别。

    +

    envmap_per_frame 是每帧独立更换背景的图片集合;envmap_per_segment 才具有视频时间关系。SHA256 只固定当前字节,不证明源一致性、语义或视觉质量。

    {''.join(cards)}""" + (output / "index.html").write_text(page, encoding="utf-8") + status["stage"] = "complete" + atomic_json(output / "status.json", status) + + +if __name__ == "__main__": + main() diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/requirements-lock.txt b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/requirements-lock.txt new file mode 100644 index 0000000000000000000000000000000000000000..db387d280008a67aa51ae960261da61c0d855bd1 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/requirements-lock.txt @@ -0,0 +1,6 @@ +--extra-index-url https://download.pytorch.org/whl/cpu +numpy==2.5.2 +torch==2.14.0+cpu +pillow==12.3.0 +smplx==0.1.28 +opencv-python-headless==5.0.0.93 diff --git a/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/run.py b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/run.py new file mode 100644 index 0000000000000000000000000000000000000000..e812b0df614650847e2d38ef5527b488e365c647 --- /dev/null +++ b/ReInterHand/shared-v1.1/script/v1_0_snapshot/script/run.py @@ -0,0 +1,80 @@ +"""Release-local entry point. See README.md; no --release argument is needed.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys + +SCRIPT=Path(__file__).resolve().parent +RELEASE=SCRIPT.parent +ROOT=RELEASE.parent +sys.dont_write_bytecode=True + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('command',choices=['preflight','inventory','pilot','full','validate','review','checksums']) + p.add_argument('--sequence',help='OakInk sequence; ReInterHand capture for pilot') + p.add_argument('--segment',help='ReInterHand pilot action') + p.add_argument('--tensors',action='store_true') + p.add_argument('--media',action='store_true') + a=p.parse_args() + c=json.loads((SCRIPT/'config.json').read_text()) + def path(k): + v=Path(c[k]); return v if v.is_absolute() else (ROOT/v).resolve() + env=os.environ.copy() + env['PYTHONDONTWRITEBYTECODE']='1' + for k in ('OMP_NUM_THREADS','MKL_NUM_THREADS','OPENBLAS_NUM_THREADS','NUMEXPR_NUM_THREADS'): env[k]='1' + packages=path('packages') + env['PYTHONPATH']=str(packages)+os.pathsep+env.get('PYTHONPATH','') + def run(name,args): + subprocess.run([sys.executable,str(SCRIPT/name),*map(str,args)],check=True,env=env) + reinter=c['dataset']=='ReInterHand' + if a.command=='checksums': + rows=json.loads((SCRIPT/'checksums.json').read_text()) + for rel,h in rows.items(): + if hashlib.sha256((SCRIPT/rel).read_bytes()).hexdigest()!=h: raise RuntimeError('script differs: '+rel) + print('Script checksums passed:',len(rows)); return + if a.command=='validate': + run('validate_release.py',(['--tensors'] if a.tensors else [])+(['--media'] if a.media else [])); return + if a.command=='preflight': + if not (ROOT/'raw').is_dir(): raise RuntimeError('Missing raw sibling') + if not all((path('models')/n).is_file() for n in ('MANO_LEFT.pkl','MANO_RIGHT.pkl')): raise RuntimeError('Configure licensed MANO files in config.json models') + subprocess.run([sys.executable,'-c','import numpy,torch,PIL,smplx'+(',cv2' if reinter else ',scipy,imageio_ffmpeg')],env=env,check=True) + subprocess.run(['ffmpeg','-version'],check=True,stdout=subprocess.DEVNULL) + import shutil + if shutil.disk_usage(ROOT).free0, 'invalid T' + assert m['sequence_id']==sequence.name and m['camera_id']==view.name, 'identity mismatch' + assert m['view_type'] in ('ego','exo','unknown'), 'view_type' + assert m['split'] in ('train','val','test','unknown'), 'split' + assert m['schema_version']=='hand-warehouse/1.0', 'schema_version' + frame_path=view/m['sampling']['frames_ref'] + frames=[json.loads(line) for line in frame_path.read_text().splitlines() if line.strip()] + assert len(frames)==T, 'frame count mismatch' + assert [r['frame_index'] for r in frames]==list(range(T)), 'frame_index' + assert all(r.get('source_frame_id') is not None for r in frames), 'source_frame_id missing' + assert len({str(r['source_frame_id']) for r in frames})==T, 'duplicate source IDs' + for key, rel in refs(m.get('components',{})): + p=(view/rel).resolve() + assert p.is_relative_to(release.resolve()), 'reference escapes release' + assert p.is_file(), 'missing reference '+rel + for name,c in m['components'].items(): + if not isinstance(c,dict) or not c.get('available',True): continue + rel=c.get('data_ref') + if not rel: continue + p=view/rel + if tensors and p.suffix=='.pt': + x=torch.load(p,map_location='cpu',weights_only=True) + assert isinstance(x,torch.Tensor), name+': not tensor' + if c.get('axes',[None])[0]=='T': assert x.shape[0]==T, name+': T' + valid_ref=c.get('valid_ref') + if valid_ref: + valid=torch.load(view/valid_ref,map_location='cpu',weights_only=True) + assert valid.dtype==torch.bool, name+': valid dtype' + assert valid.shape[0]==T, name+': valid T' + if x.is_floating_point(): + assert x.dtype==torch.float32, name+': float dtype' + mask=valid + while mask.ndim