yhl826459 commited on
Commit
4c9286d
·
verified ·
1 Parent(s): 4b3d54e

Stage ARCTIC shared-v1.1 55417/55417

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_0.html +0 -0
  2. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_0.report.json +231 -0
  3. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_1.html +0 -0
  4. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_1.report.json +221 -0
  5. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_2.html +0 -0
  6. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_2.report.json +221 -0
  7. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_3.html +0 -0
  8. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_3.report.json +221 -0
  9. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_4.html +0 -0
  10. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_4.report.json +221 -0
  11. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_5.html +0 -0
  12. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_5.report.json +221 -0
  13. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_6.html +0 -0
  14. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_6.report.json +221 -0
  15. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_7.html +0 -0
  16. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_7.report.json +221 -0
  17. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_8.html +0 -0
  18. ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_8.report.json +221 -0
  19. ARCTIC/shared-v1.1/doc/validation/validate_report.json +242 -0
  20. ARCTIC/shared-v1.1/script/arctic_v1_1/README.md +238 -0
  21. ARCTIC/shared-v1.1/script/arctic_v1_1/arctic_common.py +475 -0
  22. ARCTIC/shared-v1.1/script/arctic_v1_1/migrate.py +697 -0
  23. ARCTIC/shared-v1.1/script/arctic_v1_1/read_sequence.py +291 -0
  24. ARCTIC/shared-v1.1/script/arctic_v1_1/render.py +965 -0
  25. ARCTIC/shared-v1.1/script/arctic_v1_1/spec/CONTRACT.md +161 -0
  26. ARCTIC/shared-v1.1/script/arctic_v1_1/spec/MIGRATION.md +68 -0
  27. ARCTIC/shared-v1.1/script/arctic_v1_1/spec/schema.json +1590 -0
  28. ARCTIC/shared-v1.1/script/arctic_v1_1/validate.py +464 -0
  29. ARCTIC/shared-v1.1/script/arctic_v1_1/verify.py +473 -0
  30. ARCTIC/shared-v1.1/script/arctic_v1_1/warehouse.py +254 -0
  31. ARCTIC/shared-v1.1/script/provenance/operations/build_arctic_docs.py +208 -0
  32. ARCTIC/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md +459 -0
  33. ARCTIC/shared-v1.1/script/v1_0_snapshot/doc/schema.json +880 -0
  34. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/README.md +28 -0
  35. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/config.json +12 -0
  36. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/convert.py +14 -0
  37. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/accelerated_media.py +128 -0
  38. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/arctic_object_review.py +223 -0
  39. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/audit_source_fields.py +55 -0
  40. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/convert_fresh_sequence_pilots.py +351 -0
  41. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/correct_arctic_source_fps_metadata.py +79 -0
  42. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/diagnose_arctic_review.py +125 -0
  43. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/finalize_arctic_objects_review.py +142 -0
  44. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/fresh_sequence_common.py +209 -0
  45. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_build.py +207 -0
  46. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_fetch.py +63 -0
  47. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_hot_normalize.py +39 -0
  48. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_mano.py +87 -0
  49. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/preprocess_fresh_full.py +356 -0
  50. ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/render_full_sequence_review.py +256 -0
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_0.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_0.report.json ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/0",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "0",
5
+ "view_type": "ego",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "rational8",
10
+ "schema_id": "camera/rational8/v1",
11
+ "image_size": [
12
+ 2800,
13
+ 2000
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "intrinsic.distortion": {
29
+ "shape": [
30
+ 622,
31
+ 8
32
+ ],
33
+ "dtype": "torch.float32",
34
+ "valid_true": 622,
35
+ "valid_total": 622,
36
+ "shares_intrinsic_validity": true
37
+ },
38
+ "extrinsic": {
39
+ "shape": [
40
+ 622,
41
+ 4,
42
+ 4
43
+ ],
44
+ "dtype": "torch.float32",
45
+ "valid_true": 621,
46
+ "valid_total": 622,
47
+ "shares_intrinsic_validity": null
48
+ },
49
+ "mano": {
50
+ "shape": [
51
+ 622,
52
+ 2,
53
+ 61
54
+ ],
55
+ "dtype": "torch.float32",
56
+ "valid_true": 1242,
57
+ "valid_total": 1244,
58
+ "shares_intrinsic_validity": null
59
+ },
60
+ "object_phone_root_pose": {
61
+ "shape": [
62
+ 622,
63
+ 4,
64
+ 4
65
+ ],
66
+ "dtype": "torch.float32",
67
+ "valid_true": 621,
68
+ "valid_total": 622,
69
+ "shares_intrinsic_validity": null
70
+ },
71
+ "object_phone_bottom_pose": {
72
+ "shape": [
73
+ 622,
74
+ 4,
75
+ 4
76
+ ],
77
+ "dtype": "torch.float32",
78
+ "valid_true": 621,
79
+ "valid_total": 622,
80
+ "shares_intrinsic_validity": null
81
+ },
82
+ "object_phone_top_pose": {
83
+ "shape": [
84
+ 622,
85
+ 4,
86
+ 4
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_joint": {
94
+ "shape": [
95
+ 622,
96
+ 1
97
+ ],
98
+ "dtype": "torch.float32",
99
+ "valid_true": 621,
100
+ "valid_total": 622,
101
+ "shares_intrinsic_validity": null
102
+ },
103
+ "object_phone_keypoints": {
104
+ "shape": [
105
+ 622,
106
+ 32,
107
+ 3
108
+ ],
109
+ "dtype": "torch.float32",
110
+ "valid_true": 19872,
111
+ "valid_total": 19904,
112
+ "shares_intrinsic_validity": null
113
+ }
114
+ },
115
+ "bundle_files": 3,
116
+ "bundles": [
117
+ "annotation/mano/mano.pt",
118
+ "annotation/object/phone/object.pt",
119
+ "camera/camera.pt"
120
+ ],
121
+ "media": [
122
+ {
123
+ "component": "object_phone_articulation",
124
+ "ref": "annotation/object/phone/articulation.json",
125
+ "pixels_decoded": 0
126
+ },
127
+ {
128
+ "component": "object_phone_mesh",
129
+ "ref": "annotation/object/phone/assets/mesh.obj",
130
+ "pixels_decoded": 0
131
+ },
132
+ {
133
+ "component": "rgb",
134
+ "ref": "observation/rgb.mkv",
135
+ "pixels_decoded": 5
136
+ }
137
+ ],
138
+ "consumed_files": [
139
+ "annotation/mano/mano.pt",
140
+ "annotation/object/phone/articulation.json",
141
+ "annotation/object/phone/articulation_valid.pt",
142
+ "annotation/object/phone/assets/mesh.obj",
143
+ "annotation/object/phone/assets/mesh_valid.pt",
144
+ "annotation/object/phone/object.pt",
145
+ "camera/camera.pt",
146
+ "observation/rgb.mkv",
147
+ "observation/rgb_valid.pt"
148
+ ],
149
+ "registry_gaps": [
150
+ {
151
+ "kind": "keypoint_schema_unregistered",
152
+ "schema": "arctic_object_keypoints/v1",
153
+ "resolved_from": "component.keypoint_names",
154
+ "count": 32
155
+ }
156
+ ],
157
+ "selected_frames": [
158
+ 0,
159
+ 155,
160
+ 311,
161
+ 466,
162
+ 621
163
+ ],
164
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
165
+ "projection": {
166
+ "model": "rational8",
167
+ "calibrated": true,
168
+ "points": 128,
169
+ "inside": 128,
170
+ "off_image": 0,
171
+ "frames": {
172
+ "0": {
173
+ "annotated": true,
174
+ "valid_points": 32,
175
+ "inside_points": 32,
176
+ "inside_ratio": 1.0,
177
+ "mostly_out_of_frame": false
178
+ },
179
+ "155": {
180
+ "annotated": true,
181
+ "valid_points": 32,
182
+ "inside_points": 32,
183
+ "inside_ratio": 1.0,
184
+ "mostly_out_of_frame": false
185
+ },
186
+ "311": {
187
+ "annotated": true,
188
+ "valid_points": 32,
189
+ "inside_points": 32,
190
+ "inside_ratio": 1.0,
191
+ "mostly_out_of_frame": false
192
+ },
193
+ "466": {
194
+ "annotated": true,
195
+ "valid_points": 32,
196
+ "inside_points": 32,
197
+ "inside_ratio": 1.0,
198
+ "mostly_out_of_frame": false
199
+ },
200
+ "621": {
201
+ "annotated": false,
202
+ "valid_points": 0,
203
+ "inside_points": 0,
204
+ "inside_ratio": null,
205
+ "mostly_out_of_frame": false
206
+ }
207
+ },
208
+ "coordinate_frame": "camera",
209
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
210
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
211
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
212
+ },
213
+ "omitted_components": {
214
+ "depth": "No depth images in this official raw release",
215
+ "segment": "No pixel segmentation in this official raw release",
216
+ "contact": "No source contact labels in selected official raw packages",
217
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
218
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
219
+ },
220
+ "source_hand_object_gt_available": null,
221
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
222
+ "geometry_panels": {
223
+ "keypoint_panels": 4,
224
+ "axis_panels": 8,
225
+ "mano_panels": 3,
226
+ "note_panels": 6,
227
+ "frames_noted": 5,
228
+ "frames_mostly_out_of_frame": 0,
229
+ "frames_mostly_out_of_frame_list": []
230
+ }
231
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_1.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_1.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/1",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "1",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2000,
13
+ 2800
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 4,
216
+ "note_panels": 5,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_2.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_2.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/2",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "2",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2000,
13
+ 2800
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 4,
216
+ "note_panels": 5,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_3.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_3.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/3",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "3",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2000,
13
+ 2800
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 3,
216
+ "note_panels": 6,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_4.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_4.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/4",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "4",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2800,
13
+ 2000
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 4,
216
+ "note_panels": 5,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_5.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_5.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/5",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "5",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2000,
13
+ 2800
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 4,
216
+ "note_panels": 5,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_6.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_6.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/6",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "6",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2000,
13
+ 2800
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 4,
216
+ "note_panels": 5,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_7.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_7.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/7",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "7",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2000,
13
+ 2800
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 3,
216
+ "note_panels": 6,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_8.html ADDED
The diff for this file is too large to render. See raw diff
 
ARCTIC/shared-v1.1/doc/validation/s10_phone_grab_01_8.report.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "s10_phone_grab_01/8",
3
+ "sequence_id": "s10_phone_grab_01",
4
+ "camera_id": "8",
5
+ "view_type": "exo",
6
+ "split": "train",
7
+ "num_frames": 622,
8
+ "camera": {
9
+ "model": "pinhole",
10
+ "schema_id": "camera/pinhole/v1",
11
+ "image_size": [
12
+ 2800,
13
+ 2000
14
+ ]
15
+ },
16
+ "numeric_components": {
17
+ "intrinsic": {
18
+ "shape": [
19
+ 622,
20
+ 3,
21
+ 3
22
+ ],
23
+ "dtype": "torch.float32",
24
+ "valid_true": 622,
25
+ "valid_total": 622,
26
+ "shares_intrinsic_validity": null
27
+ },
28
+ "extrinsic": {
29
+ "shape": [
30
+ 622,
31
+ 4,
32
+ 4
33
+ ],
34
+ "dtype": "torch.float32",
35
+ "valid_true": 622,
36
+ "valid_total": 622,
37
+ "shares_intrinsic_validity": null
38
+ },
39
+ "mano": {
40
+ "shape": [
41
+ 622,
42
+ 2,
43
+ 61
44
+ ],
45
+ "dtype": "torch.float32",
46
+ "valid_true": 1242,
47
+ "valid_total": 1244,
48
+ "shares_intrinsic_validity": null
49
+ },
50
+ "object_phone_root_pose": {
51
+ "shape": [
52
+ 622,
53
+ 4,
54
+ 4
55
+ ],
56
+ "dtype": "torch.float32",
57
+ "valid_true": 621,
58
+ "valid_total": 622,
59
+ "shares_intrinsic_validity": null
60
+ },
61
+ "object_phone_bottom_pose": {
62
+ "shape": [
63
+ 622,
64
+ 4,
65
+ 4
66
+ ],
67
+ "dtype": "torch.float32",
68
+ "valid_true": 621,
69
+ "valid_total": 622,
70
+ "shares_intrinsic_validity": null
71
+ },
72
+ "object_phone_top_pose": {
73
+ "shape": [
74
+ 622,
75
+ 4,
76
+ 4
77
+ ],
78
+ "dtype": "torch.float32",
79
+ "valid_true": 621,
80
+ "valid_total": 622,
81
+ "shares_intrinsic_validity": null
82
+ },
83
+ "object_phone_joint": {
84
+ "shape": [
85
+ 622,
86
+ 1
87
+ ],
88
+ "dtype": "torch.float32",
89
+ "valid_true": 621,
90
+ "valid_total": 622,
91
+ "shares_intrinsic_validity": null
92
+ },
93
+ "object_phone_keypoints": {
94
+ "shape": [
95
+ 622,
96
+ 32,
97
+ 3
98
+ ],
99
+ "dtype": "torch.float32",
100
+ "valid_true": 19872,
101
+ "valid_total": 19904,
102
+ "shares_intrinsic_validity": null
103
+ }
104
+ },
105
+ "bundle_files": 3,
106
+ "bundles": [
107
+ "annotation/mano/mano.pt",
108
+ "annotation/object/phone/object.pt",
109
+ "camera/camera.pt"
110
+ ],
111
+ "media": [
112
+ {
113
+ "component": "object_phone_articulation",
114
+ "ref": "annotation/object/phone/articulation.json",
115
+ "pixels_decoded": 0
116
+ },
117
+ {
118
+ "component": "object_phone_mesh",
119
+ "ref": "annotation/object/phone/assets/mesh.obj",
120
+ "pixels_decoded": 0
121
+ },
122
+ {
123
+ "component": "rgb",
124
+ "ref": "observation/rgb.mkv",
125
+ "pixels_decoded": 5
126
+ }
127
+ ],
128
+ "consumed_files": [
129
+ "annotation/mano/mano.pt",
130
+ "annotation/object/phone/articulation.json",
131
+ "annotation/object/phone/articulation_valid.pt",
132
+ "annotation/object/phone/assets/mesh.obj",
133
+ "annotation/object/phone/assets/mesh_valid.pt",
134
+ "annotation/object/phone/object.pt",
135
+ "camera/camera.pt",
136
+ "observation/rgb.mkv",
137
+ "observation/rgb_valid.pt"
138
+ ],
139
+ "registry_gaps": [
140
+ {
141
+ "kind": "keypoint_schema_unregistered",
142
+ "schema": "arctic_object_keypoints/v1",
143
+ "resolved_from": "component.keypoint_names",
144
+ "count": 32
145
+ }
146
+ ],
147
+ "selected_frames": [
148
+ 0,
149
+ 155,
150
+ 311,
151
+ 466,
152
+ 621
153
+ ],
154
+ "decode_scope": "ffmpeg select= demux filter over the preserved MKV; only the frames listed in selected_frames are decoded, each checked against height*width*3 bytes",
155
+ "projection": {
156
+ "model": "pinhole",
157
+ "calibrated": true,
158
+ "points": 128,
159
+ "inside": 128,
160
+ "off_image": 0,
161
+ "frames": {
162
+ "0": {
163
+ "annotated": true,
164
+ "valid_points": 32,
165
+ "inside_points": 32,
166
+ "inside_ratio": 1.0,
167
+ "mostly_out_of_frame": false
168
+ },
169
+ "155": {
170
+ "annotated": true,
171
+ "valid_points": 32,
172
+ "inside_points": 32,
173
+ "inside_ratio": 1.0,
174
+ "mostly_out_of_frame": false
175
+ },
176
+ "311": {
177
+ "annotated": true,
178
+ "valid_points": 32,
179
+ "inside_points": 32,
180
+ "inside_ratio": 1.0,
181
+ "mostly_out_of_frame": false
182
+ },
183
+ "466": {
184
+ "annotated": true,
185
+ "valid_points": 32,
186
+ "inside_points": 32,
187
+ "inside_ratio": 1.0,
188
+ "mostly_out_of_frame": false
189
+ },
190
+ "621": {
191
+ "annotated": false,
192
+ "valid_points": 0,
193
+ "inside_points": 0,
194
+ "inside_ratio": null,
195
+ "mostly_out_of_frame": false
196
+ }
197
+ },
198
+ "coordinate_frame": "camera",
199
+ "scope": "saved camera-frame xyz through the view's own intrinsic and distortion; not a media pixel comparison",
200
+ "out_of_frame_rule": "a sampled frame is marked 物体大部分落在画外 when fewer than half of its valid object keypoints land inside the image; every annotated frame's valid_points / inside_points / inside_ratio is recorded in projection.frames either way",
201
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the published projection_qc (saved xyz against saved uv) has no second series here; this counts what the release's own camera-frame geometry projects to."
202
+ },
203
+ "omitted_components": {
204
+ "depth": "No depth images in this official raw release",
205
+ "segment": "No pixel segmentation in this official raw release",
206
+ "contact": "No source contact labels in selected official raw packages",
207
+ "keypoints": "No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels",
208
+ "visibility": "Not supplied in selected raw annotations; fitting_err is outside current shared scope"
209
+ },
210
+ "source_hand_object_gt_available": null,
211
+ "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
212
+ "geometry_panels": {
213
+ "keypoint_panels": 4,
214
+ "axis_panels": 8,
215
+ "mano_panels": 4,
216
+ "note_panels": 5,
217
+ "frames_noted": 5,
218
+ "frames_mostly_out_of_frame": 0,
219
+ "frames_mostly_out_of_frame_list": []
220
+ }
221
+ }
ARCTIC/shared-v1.1/doc/validation/validate_report.json ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "passed": true,
3
+ "dataset_id": "ARCTIC",
4
+ "schema_version": "hand-warehouse/1.1",
5
+ "release_id": "shared-v1.1",
6
+ "schema_sha256": "9f3769f950b36f75f3d571c77b5a661ca8e72afae20c9f1ddd1deef140e6cca8",
7
+ "views": 3051,
8
+ "sequences": 339,
9
+ "counts_by_split": {
10
+ "test": 342,
11
+ "train": 2403,
12
+ "val": 306
13
+ },
14
+ "num_frames": 2193687,
15
+ "released_files": 54196,
16
+ "cameras_per_sequence": 9,
17
+ "camera_models": {
18
+ "pinhole": 2712,
19
+ "rational8": 301,
20
+ "unknown": 38
21
+ },
22
+ "uncalibrated_views": [
23
+ "s03_box_grab_01/0",
24
+ "s03_box_use_01/0",
25
+ "s03_box_use_01_retake/0",
26
+ "s03_box_use_02/0",
27
+ "s03_capsulemachine_grab_01/0",
28
+ "s03_capsulemachine_use_01/0",
29
+ "s03_capsulemachine_use_02/0",
30
+ "s03_capsulemachine_use_03/0",
31
+ "s03_capsulemachine_use_04/0",
32
+ "s03_espressomachine_grab_01/0",
33
+ "s03_espressomachine_use_01/0",
34
+ "s03_espressomachine_use_02_retake/0",
35
+ "s03_ketchup_grab_01/0",
36
+ "s03_ketchup_use_01/0",
37
+ "s03_ketchup_use_02/0",
38
+ "s03_laptop_grab_01/0",
39
+ "s03_laptop_use_01/0",
40
+ "s03_laptop_use_02/0",
41
+ "s03_microwave_grab_01/0",
42
+ "s03_microwave_use_01/0",
43
+ "s03_microwave_use_02/0",
44
+ "s03_mixer_grab_01/0",
45
+ "s03_mixer_use_01/0",
46
+ "s03_mixer_use_02/0",
47
+ "s03_notebook_grab_01/0",
48
+ "s03_notebook_use_01/0",
49
+ "s03_notebook_use_02/0",
50
+ "s03_notebook_use_03/0",
51
+ "s03_notebook_use_04/0",
52
+ "s03_phone_grab_01/0",
53
+ "s03_phone_use_01_retake/0",
54
+ "s03_phone_use_02/0",
55
+ "s03_scissors_grab_01/0",
56
+ "s03_scissors_use_01/0",
57
+ "s03_scissors_use_02/0",
58
+ "s03_waffleiron_grab_01/0",
59
+ "s03_waffleiron_use_01/0",
60
+ "s03_waffleiron_use_02/0"
61
+ ],
62
+ "status_flags": {
63
+ "full_output_human_review": [
64
+ "pending"
65
+ ],
66
+ "media_validation_policy": [
67
+ "jpeg-packets-all-rgb-sample16/v1",
68
+ null
69
+ ],
70
+ "pilot": [
71
+ false
72
+ ],
73
+ "pilot_complete": [
74
+ true
75
+ ],
76
+ "pilot_human_review": [
77
+ "approved"
78
+ ],
79
+ "production_complete": [
80
+ true
81
+ ],
82
+ "upload_authorized": [
83
+ false
84
+ ]
85
+ },
86
+ "status_flags_varying": [
87
+ "media_validation_policy"
88
+ ],
89
+ "registry_gaps": [
90
+ {
91
+ "kind": "keypoint_schema_unregistered",
92
+ "schema": "arctic_object_keypoints/v1",
93
+ "resolved_from": "component.keypoint_names",
94
+ "count": 32
95
+ }
96
+ ],
97
+ "meshes_dependencies": [
98
+ "annotation/object/box/assets/bottom.obj",
99
+ "annotation/object/box/assets/material.jpg",
100
+ "annotation/object/box/assets/material.mtl",
101
+ "annotation/object/box/assets/mesh_tex.obj",
102
+ "annotation/object/box/assets/top.obj",
103
+ "annotation/object/capsulemachine/assets/bottom.obj",
104
+ "annotation/object/capsulemachine/assets/material.jpg",
105
+ "annotation/object/capsulemachine/assets/material.mtl",
106
+ "annotation/object/capsulemachine/assets/mesh_tex.obj",
107
+ "annotation/object/capsulemachine/assets/top.obj",
108
+ "annotation/object/espressomachine/assets/bottom.obj",
109
+ "annotation/object/espressomachine/assets/material.jpg",
110
+ "annotation/object/espressomachine/assets/material.mtl",
111
+ "annotation/object/espressomachine/assets/mesh_tex.obj",
112
+ "annotation/object/espressomachine/assets/top.obj",
113
+ "annotation/object/ketchup/assets/bottom.obj",
114
+ "annotation/object/ketchup/assets/material.jpg",
115
+ "annotation/object/ketchup/assets/material.mtl",
116
+ "annotation/object/ketchup/assets/mesh_tex.obj",
117
+ "annotation/object/ketchup/assets/top.obj",
118
+ "annotation/object/laptop/assets/bottom.obj",
119
+ "annotation/object/laptop/assets/material.jpg",
120
+ "annotation/object/laptop/assets/material.mtl",
121
+ "annotation/object/laptop/assets/mesh_tex.obj",
122
+ "annotation/object/laptop/assets/top.obj",
123
+ "annotation/object/microwave/assets/bottom.obj",
124
+ "annotation/object/microwave/assets/material.jpg",
125
+ "annotation/object/microwave/assets/material.mtl",
126
+ "annotation/object/microwave/assets/mesh_tex.obj",
127
+ "annotation/object/microwave/assets/top.obj",
128
+ "annotation/object/mixer/assets/bottom.obj",
129
+ "annotation/object/mixer/assets/material.jpg",
130
+ "annotation/object/mixer/assets/material.mtl",
131
+ "annotation/object/mixer/assets/mesh_tex.obj",
132
+ "annotation/object/mixer/assets/top.obj",
133
+ "annotation/object/notebook/assets/bottom.obj",
134
+ "annotation/object/notebook/assets/material.jpg",
135
+ "annotation/object/notebook/assets/material.mtl",
136
+ "annotation/object/notebook/assets/mesh_tex.obj",
137
+ "annotation/object/notebook/assets/top.obj",
138
+ "annotation/object/phone/assets/bottom.obj",
139
+ "annotation/object/phone/assets/material.jpg",
140
+ "annotation/object/phone/assets/material.mtl",
141
+ "annotation/object/phone/assets/mesh_tex.obj",
142
+ "annotation/object/phone/assets/top.obj",
143
+ "annotation/object/scissors/assets/bottom.obj",
144
+ "annotation/object/scissors/assets/material.jpg",
145
+ "annotation/object/scissors/assets/material.mtl",
146
+ "annotation/object/scissors/assets/mesh_tex.obj",
147
+ "annotation/object/scissors/assets/top.obj",
148
+ "annotation/object/waffleiron/assets/bottom.obj",
149
+ "annotation/object/waffleiron/assets/material.jpg",
150
+ "annotation/object/waffleiron/assets/material.mtl",
151
+ "annotation/object/waffleiron/assets/mesh_tex.obj",
152
+ "annotation/object/waffleiron/assets/top.obj"
153
+ ],
154
+ "meshes_dependency_views": {
155
+ "annotation/object/box/assets/bottom.obj": 261,
156
+ "annotation/object/box/assets/material.jpg": 261,
157
+ "annotation/object/box/assets/material.mtl": 261,
158
+ "annotation/object/box/assets/mesh_tex.obj": 261,
159
+ "annotation/object/box/assets/top.obj": 261,
160
+ "annotation/object/capsulemachine/assets/bottom.obj": 288,
161
+ "annotation/object/capsulemachine/assets/material.jpg": 288,
162
+ "annotation/object/capsulemachine/assets/material.mtl": 288,
163
+ "annotation/object/capsulemachine/assets/mesh_tex.obj": 288,
164
+ "annotation/object/capsulemachine/assets/top.obj": 288,
165
+ "annotation/object/espressomachine/assets/bottom.obj": 279,
166
+ "annotation/object/espressomachine/assets/material.jpg": 279,
167
+ "annotation/object/espressomachine/assets/material.mtl": 279,
168
+ "annotation/object/espressomachine/assets/mesh_tex.obj": 279,
169
+ "annotation/object/espressomachine/assets/top.obj": 279,
170
+ "annotation/object/ketchup/assets/bottom.obj": 279,
171
+ "annotation/object/ketchup/assets/material.jpg": 279,
172
+ "annotation/object/ketchup/assets/material.mtl": 279,
173
+ "annotation/object/ketchup/assets/mesh_tex.obj": 279,
174
+ "annotation/object/ketchup/assets/top.obj": 279,
175
+ "annotation/object/laptop/assets/bottom.obj": 288,
176
+ "annotation/object/laptop/assets/material.jpg": 288,
177
+ "annotation/object/laptop/assets/material.mtl": 288,
178
+ "annotation/object/laptop/assets/mesh_tex.obj": 288,
179
+ "annotation/object/laptop/assets/top.obj": 288,
180
+ "annotation/object/microwave/assets/bottom.obj": 270,
181
+ "annotation/object/microwave/assets/material.jpg": 270,
182
+ "annotation/object/microwave/assets/material.mtl": 270,
183
+ "annotation/object/microwave/assets/mesh_tex.obj": 270,
184
+ "annotation/object/microwave/assets/top.obj": 270,
185
+ "annotation/object/mixer/assets/bottom.obj": 288,
186
+ "annotation/object/mixer/assets/material.jpg": 288,
187
+ "annotation/object/mixer/assets/material.mtl": 288,
188
+ "annotation/object/mixer/assets/mesh_tex.obj": 288,
189
+ "annotation/object/mixer/assets/top.obj": 288,
190
+ "annotation/object/notebook/assets/bottom.obj": 270,
191
+ "annotation/object/notebook/assets/material.jpg": 270,
192
+ "annotation/object/notebook/assets/material.mtl": 270,
193
+ "annotation/object/notebook/assets/mesh_tex.obj": 270,
194
+ "annotation/object/notebook/assets/top.obj": 270,
195
+ "annotation/object/phone/assets/bottom.obj": 288,
196
+ "annotation/object/phone/assets/material.jpg": 288,
197
+ "annotation/object/phone/assets/material.mtl": 288,
198
+ "annotation/object/phone/assets/mesh_tex.obj": 288,
199
+ "annotation/object/phone/assets/top.obj": 288,
200
+ "annotation/object/scissors/assets/bottom.obj": 243,
201
+ "annotation/object/scissors/assets/material.jpg": 243,
202
+ "annotation/object/scissors/assets/material.mtl": 243,
203
+ "annotation/object/scissors/assets/mesh_tex.obj": 243,
204
+ "annotation/object/scissors/assets/top.obj": 243,
205
+ "annotation/object/waffleiron/assets/bottom.obj": 297,
206
+ "annotation/object/waffleiron/assets/material.jpg": 297,
207
+ "annotation/object/waffleiron/assets/material.mtl": 297,
208
+ "annotation/object/waffleiron/assets/mesh_tex.obj": 297,
209
+ "annotation/object/waffleiron/assets/top.obj": 297
210
+ },
211
+ "unreferenced_files": [],
212
+ "unreferenced_file_views": {},
213
+ "rewrite_check": [
214
+ {
215
+ "sequence_id": "s01_box_grab_01",
216
+ "camera_id": "0",
217
+ "bundles": [
218
+ "annotation/mano/mano.pt",
219
+ "annotation/object/box/object.pt",
220
+ "camera/camera.pt"
221
+ ],
222
+ "tensors_compared": 18
223
+ },
224
+ {
225
+ "sequence_id": "s01_box_grab_01",
226
+ "camera_id": "1",
227
+ "bundles": [
228
+ "annotation/mano/mano.pt",
229
+ "annotation/object/box/object.pt",
230
+ "camera/camera.pt"
231
+ ],
232
+ "tensors_compared": 16
233
+ }
234
+ ],
235
+ "scope": "released content and layout; does not independently prove official source correctness or visual quality",
236
+ "release_manifest": {
237
+ "path": "/data1/yanghonglei/Datasets/hand-warehouse/ARCTIC/tmp/arctic-tools/PUBLISH_MANIFEST.json",
238
+ "in_release_tree": false,
239
+ "files": 55417,
240
+ "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"
241
+ }
242
+ }
ARCTIC/shared-v1.1/script/arctic_v1_1/README.md ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ARCTIC shared-v1.1 tools
2
+
3
+ ARCTIC 的 `shared-v1.0 → shared-v1.1` 纯存储迁移工具。v1.1 只改一件事:数值张量与其 `valid`
4
+ 合并为每组一个 `.pt` 字典(叶子形如 `{"data": Tensor, "valid": BoolTensor}`)。语义、采样、帧数、
5
+ 单位、坐标系、划分、来源与 `valid_policy` 全部不变(见 `spec/CONTRACT.md` §6.3)。
6
+
7
+ ```
8
+ script/arctic_v1_1/
9
+ ├── warehouse.py v1.1 布局库:Registry.resolve / BundleWriter / BundleReader / expanded_all_known
10
+ ├── arctic_common.py ARCTIC 适配:路径、形状符号解析、逐组件结构校验、畸变规则、游离文件检测
11
+ ├── migrate.py v1.0 → v1.1 迁移(可断点续跑)
12
+ ├── verify.py 验收:逐视图对 v1.0 源做字节级比对(CONTRACT §6)
13
+ ├── validate.py 全量结构校验 + 重新生成 release manifest
14
+ ├── read_sequence.py 读取器路径验收:整条序列、全部相机(CONTRACT §6.5)
15
+ ├── render.py 全量后抽样的人工复核页:54 个视图的 HTML + QC 报告 + index
16
+ ├── spec/ 本版规范原文:CONTRACT.md、MIGRATION.md、schema.json
17
+ └── README.md
18
+ ```
19
+
20
+ `warehouse.py` 与各数据集共用,逐字节相同;ARCTIC 自己的适配都在 `arctic_common.py`。
21
+
22
+ ## 运行
23
+
24
+ 包位于 `<dataset>/shared-v1.1/script/arctic_v1_1/`,所以发布树与数据集根无需传参:
25
+
26
+ ```bash
27
+ # 试跑,核对会迁移哪些视图(不写任何文件)
28
+ python shared-v1.1/script/arctic_v1_1/migrate.py --dry-run
29
+
30
+ # 换一段或几段先试
31
+ python shared-v1.1/script/arctic_v1_1/migrate.py --views s01_box_grab_01
32
+
33
+ # 迁移(可重复执行;已完成且 checkpoint 重新核验通过的视图跳过)
34
+ # 同时登记源数据出处:HF 固定提交 + 该提交的 tree-API 清单(MIGRATION 3)
35
+ python shared-v1.1/script/arctic_v1_1/migrate.py --resume \
36
+ --source-revision d4e2bb40cd30071e4f6483877889c1857b41b707 \
37
+ --source-manifest tmp/full-manifest.json
38
+
39
+ # 验收:每个已迁移视图与其 v1.0 源逐字段比对(CONTRACT §6)
40
+ # 注意 --complete 走的是 **v1.0 源树**里的全部视图,所以边拉边迁期间它会把「源里
41
+ # 已有、但还没迁」的视图报成 view was not migrated,那不是数据缺陷。增量期间用
42
+ # --views <段名...> 限定范围;收尾时 v1.0 与 v1.1 都齐了再用 --complete。
43
+ python shared-v1.1/script/arctic_v1_1/verify.py --complete \
44
+ --report tmp/arctic-tools/acceptance.json
45
+
46
+ # 增量期间加 --no-manifest:清单要遍历整棵树重算 sha256(CONTRACT §6.4),那是最终
47
+ # 验收必须做的,但边拉边迁时每次都为一份随后会被覆盖的清单付几十分钟不值得。
48
+ # 接受发布的**那一次**不许带这个开关。
49
+ python shared-v1.1/script/arctic_v1_1/verify.py --views s01_box_grab_01 --no-manifest
50
+
51
+ # 读取器路径验收:整条序列、全部九机位,查 RGB↔帧数↔标注、相机身份与同一次录制(CONTRACT §6.5)
52
+ python shared-v1.1/script/arctic_v1_1/read_sequence.py s01_box_grab_01 \
53
+ --report tmp/arctic-tools/read-sequence.json
54
+
55
+ # 全量结构校验(只读发布树,不需要 v1.0 源;重建树外发布清单 tmp/arctic-tools/PUBLISH_MANIFEST.json)
56
+ python shared-v1.1/script/arctic_v1_1/validate.py --expect-views 3051 --rewrite-check 2
57
+ ```
58
+
59
+ ### 收尾验收顺序
60
+
61
+ 发布清单**不在发布树里**。它记录发布树每个文件的 sha256,而树内的副本描述不了自己写下去之后的树——
62
+ 写完清单本身就又改了树,清单永远落后一次编辑;所以它按 H2O、dex-ycb 的约定落在树外
63
+ `tmp/arctic-tools/PUBLISH_MANIFEST.json`(H2O README:`PUBLISH_MANIFEST.json` 在发布树外记录可发布路径、
64
+ 大小与 SHA256),发布树里不含清单,也就不需要从自己的哈希里排除任何东西。
65
+
66
+ 顺序仍然是**清单最后重建**:`FULL_MIGRATION_SUMMARY.json` 与重建后的 `doc/{CONTRACT,RAW_TO_SHARED,MIGRATION}.md`
67
+ 都是发布树里的文件,先建清单再写它们,清单记下的就不是最终字节。反过来,汇总又引用校验报告的结论,
68
+ 所以两者的依赖是单向的——清单引用汇总,汇总只引用**更早那次**校验
69
+ (见汇总里 `all_current_file_hashes_verified_evidence.note`)。全套顺序:
70
+
71
+ ```bash
72
+ cd /data1/yanghonglei/Datasets/hand-warehouse/ARCTIC
73
+
74
+ # 1 收口迁移:把「已就绪但还没迁」的视图补齐,--resume 会重核 checkpoint
75
+ python shared-v1.1/script/arctic_v1_1/migrate.py --resume \
76
+ --source-revision d4e2bb40cd30071e4f6483877889c1857b41b707 \
77
+ --source-manifest tmp/full-manifest.json
78
+
79
+ # 2 逐视图字节级验收(CONTRACT 6)。这里带 --no-manifest:清单要遍历整棵树重算 sha256
80
+ # (737 GiB),而它早于第 6、7 步,建了也会被第 8 步覆盖,白哈希一遍。
81
+ # 发布清单由第 8 步的 validate.py 最后重建(CONTRACT 6.4 要求的是清单被重建且正确,
82
+ # 不要求由本工具来写)
83
+ python shared-v1.1/script/arctic_v1_1/verify.py --complete --no-manifest \
84
+ --report tmp/arctic-tools/acceptance.json
85
+
86
+ # 3 读取器路径验收(CONTRACT 6.5),报告放进发布树随发布保留
87
+ python tmp/arctic-tools/read_sequence_sweep.py --all --workers 4 \
88
+ --out shared-v1.1/doc/validation/read_sequence_sweep.json
89
+
90
+ # 4 全量结构校验,报告作为汇总的守卫依据。同样带 --no-manifest:本步写下的
91
+ # doc/validation/validate_report.json 早于第 6、7 步的文件,此时建的清单描述的不是最终字节,
92
+ # 属于和第 2 步一样的白哈希;第 8 步会覆盖这份报告并最后重建清单
93
+ python shared-v1.1/script/arctic_v1_1/validate.py --expect-views 3051 --rewrite-check 2 \
94
+ --no-manifest
95
+
96
+ # 5 复核页渲染:抽样 6 段(test 1、val 2、train 3)各自的全部 9 路相机 = 54 个视图,写进
97
+ # doc/validation/。必须在第 6 步之前:复核页是发布树里的文件,汇总要数到它们,清单要哈希
98
+ # 它们的最终字节。本步同时写下供人工复核的 index.html 与 V1_1_VALIDATION.json
99
+ python shared-v1.1/script/arctic_v1_1/render.py --workers 4
100
+
101
+ # 6 汇总:每一步的数字都从上面几份报告读出来,不手写;条件不满足就拒写
102
+ python tmp/arctic-tools/write_full_migration_summary.py --expect-views 3051
103
+
104
+ # 7 重建 doc/ 三份规范并翻转横幅(banner 由第 6 步的汇总推出)
105
+ python shared-v1.1/script/provenance/operations/build_arctic_docs.py
106
+
107
+ # 8 最后重建发布清单(写到树外 tmp/arctic-tools/PUBLISH_MANIFEST.json),此时它才覆盖第 6、7 步
108
+ # 写下的文件。这里带 --rewrite-check 2:随发布保留的 validate_report.json 是**本步**写下的
109
+ # 那一份(第 4 步的会被覆盖),所以重写检查的样本要留在这一步,否则发布里那份报告的重写检查是空的
110
+ python shared-v1.1/script/arctic_v1_1/validate.py --expect-views 3051 --rewrite-check 2
111
+ ```
112
+
113
+ 第 6 步的守卫是刻意的:增量期间的报告会被拒绝——迁移视图数不足、**源树**视图数不足(说明拉取未完成)、
114
+ 源里仍有未迁移视图,或者验收/校验没通过。所以边拉边迁期间**无法**写出一份声称已完成验收的汇总,
115
+ 横幅也就翻不过去。注意守卫**不**要求验收那一次建过清单:发布清单是第 8 步的产物,验收建的那份只会被覆盖。
116
+
117
+ 全量流程的编排不在这里:源数据要从 HF 拉 737 GiB,拉到哪一步、哪段可以迁移,取决于发布树**之外**
118
+ 的 `tmp/` 状态(`full-manifest.json`、`verified-sequences.json`、`migration-v11/registration.json`)。
119
+ 所以驱动脚本放在 `tmp/arctic-tools/`:`hf_pull.py` 拉取、`pull_gate.py` 按摘要判定哪段已完整、
120
+ `incremental_migration.sh` 边拉边迁、`record_validation_evidence.sh` 生成本目录引用的证据实录。
121
+
122
+ ## 运行期的两条纪律(MIGRATION §3/§4)
123
+
124
+ **单实例锁。** `migrate.py` 在 `tmp/migration-v11/migration.lock` 上取 `flock` 并持有到退出;第二个
125
+ 进程会被拒绝并打印持锁者,而不是交错写入。就地更新不是整体原子操作,两个迁移进程写同一个目标视图,
126
+ 会各自留下一个描述着「已被对方覆盖的树」的 checkpoint——不可信的 checkpoint 比没有更糟。`--dry-run`
127
+ 不取锁。
128
+
129
+ **登记自足。** `tmp/migration-v11/registration.json` 记源与目标的 release/schema 摘要、**源 HF 固定
130
+ 提交**、该提交的 tree-API 清单摘要与文件数/字节数、工具摘要(本脚本、`warehouse.py`、`schema.json`、
131
+ Python 与 torch 版本)、逐视图的源/目标 metainfo 摘要与产出 bundle 摘要、被替换的源引用、错误与
132
+ traceback。checkpoint 也记录同一份工具摘要,所以**改动 `migrate.py`、`warehouse.py` 或 `schema.json` 会让
133
+ `--resume` 重新迁移**(MIGRATION §4.4:续跑必须核对输入与工具版本,不能只看文件存在)。摘要按文件
134
+ 点名,不含目录:改 `verify.py`、`validate.py`、`read_sequence.py`、`render.py` 只影响校验与页面,
135
+ 不会让已迁移的视图重做
136
+ ——这几个脚本在边拉边迁期间本来就要改,若是整目录入摘要,修一次校验器就得把 737 GiB 全部重迁。
137
+
138
+ ## 迁移对 ARCTIC 的四处适配
139
+
140
+ **1. 九个相机视图,相机 `0` 是 ego。** v1.0 把 8 参数畸变向量直接放在持有标定的组件上
141
+ (`intrinsic.distortion_ref`),自身没有 valid;v1.1 把它并入 `camera/camera.pt` 的 `distortion`
142
+ 条目,并与内参共用同一份 valid(CONTRACT §3/§5)。`verify.py` 与 `validate.py` 都按注册表
143
+ `reference_rules.camera_distortion` 判定,而不是写死相机名:schema 条目要求 `distortion_ref` 的组件
144
+ 才带畸变,`models_without_separate_distortion`(pinhole、fisheye624)必须不带;
145
+ `valid_equals_intrinsic_valid` 逐字节比对内参与畸变两份 bool。
146
+
147
+ **2. `frames.jsonl` 是 ARCTIC 自己的同步表。** 每行一张已发布图像,`sync_id` 命名该图像,
148
+ `source_annotation_index` 指向官方标注数组中的行——当该图像在官方标注里没有记录时它是 `null`
149
+ (发布保留官方未标注的边界帧)。因此:**凡声明 `source_locator.index_ref` 的组件,在
150
+ `source_annotation_index` 为 null 的帧上必须 invalid**——valid 是"可用于监督"的声明
151
+ (`annotation_validity`),那里没有东西可用。反向不成立:标定与媒体在这些帧上仍然 valid。
152
+ 标注为 `derived` 的字段(物体关键点由模板与位姿算出)在"所有被索引字段都 invalid"的帧上也不得 valid。
153
+
154
+ **3. `arctic_object_keypoints/v1` 未登记在共享注册表里。** 注册表 `keypoints` 只登记了
155
+ `mano21/v1` 与 `rhd21/v1` 两套手部约定;物体的 `object_box_keypoints` 组件声明的是
156
+ `arctic_object_keypoints/v1`,其 32 个点由组件自身的 `keypoint_names` 声明。读取器据此解析 `K`,
157
+ 并把这条缺口写进校验报告的 `registry_gaps`,而不是静默忽略。(这是 v1.0 就有的状态,纯存储迁移
158
+ 不改语义,因此不在此处补注册表;如需登记应由注册表维护者统一决定。)
159
+
160
+ **4. `camera.model` 可以是 `unknown`,此时不得有标定。** 38 个 `s03_*` 测试段(每个恰好一个机位)
161
+ 不发布 ego 标定,声明 `camera: {model: "unknown", schema_id: null, image_size: [...]}` 并在
162
+ `omitted_components` 里说明原因;v1.0 语义 4.3 正是这么规定的(「模型未知使用 `unknown` 和 `null`,
163
+ 不猜成针孔」)。注册表 `camera` 段只登记四个**已标定**模型,所以校验器不去拿 `unknown` 查表,而是
164
+ 走 `check_camera()`:声明 `unknown` 就必须 `schema_id` 为 `null`、相机块上不得有 `distortion_ref`、
165
+ 且不得发布任何标定组件;否则 `schema_id` 必须是已登记组件、`model` 必须已登记、内参与
166
+ `camera.schema_id` 必须一致。两种状态分别计入校验报告的 `camera_models` 与 `uncalibrated_views`。
167
+ 不存在的组件(`available: false`)按其自身规则处理:允许缺省,但不得指向不存在的文件。
168
+
169
+ ## 已知的保留项
170
+
171
+ - `annotation/object/<id>/vertex_part_ids.pt` 仍以独立文件存在。注册表 `object` bundle 的条目是
172
+ `meshes/<mesh_id>/vertex_part_ids`,而 v1.0 的引用没有 `meshes/<mesh_id>/` 这一段,
173
+ `Registry.resolve()` 因此不会把它并入 bundle——合入需要凭空构造 mesh id 并改写对象子 metainfo,
174
+ 与"绝不猜测路径"冲突,故按原样保留。对象子 metainfo 的 `vertex_part_ids_ref` 仍指向它。
175
+ - **状态标志不是全发布统一的。** `media_validation_policy` 在 `s01_capsulemachine_grab_01` 的两个
176
+ 机位上是 `null`,其余是 `"jpeg-packets-all-rgb-sample16/v1"`;这是 v1.0 就有的内容,纯存储迁移
177
+ 原样保留(CONTRACT §6.3)。因此状态标志的「不变」只能逐视图对着**它自己的 v1.0 源**判定——
178
+ `verify.py` 正是这么做的(除 `schema_version`、`release_id`、`components` 三个迁移必改的键外,
179
+ 其余顶层键逐字比对);`validate.py` 只记录各标志在整个发布中的取值分布并打印多值项
180
+ (`status_flags_varying`),不假定唯一值。
181
+ - OBJ 的 MTL 与贴图(`material.mtl`、`material.jpg`、`bottom.obj`、`top.obj`、`mesh_tex.obj`)
182
+ 由 OBJ 资产自身引用,注册表 `mesh/obj/v1.dependencies` 要求随资产保留;校验把它们与"没有任何
183
+ 元数据引用的文件"分开报告。
184
+
185
+ ## 证据
186
+
187
+ - `doc/validation/negative_controls.txt`:两类证据的实录,由
188
+ `tmp/arctic-tools/record_validation_evidence.sh` 重新生成(先刷新被测代码副本再跑,避免对着旧
189
+ 副本通过)。
190
+ 1. **反向对照**:对一份真实视图逐一注入 11 类缺陷,确认校验器逐一被**具名检查**抓到,且未注入
191
+ 时基线通过——用于证明这些检查不是空转。
192
+ 2. **`unknown` 相机路径**:`s03_laptop_use_02`(P1 测试段,取自 HF 固定提交的真实字节)走通
193
+ 迁移 → 逐视图字节级验收 → 全量校验;视图 0 声明 `model: unknown`、`schema_id: null` 且不发布
194
+ 标定,视图 1 是 pinhole,两者都通过。这条路径对应反向对照里的
195
+ `claim_calibration_when_unknown`:**允许声明没有标定,不允许一边声明 unknown 一边留着标定**。
196
+ 3. **顶层键逐字保留这条规则的对照**:改掉 v1.1 视图的 `omitted_components` 或
197
+ `media_validation_policy`,`verify.py` 必须报出被改的键名并失败,还原后重新通过。
198
+ 4. **读取器路径的对照**:`tmp/arctic-tools/read_sequence_controls.py` 在一份硬链接
199
+ 副本上注入 8 项缺陷(RGB 截断、`num_frames` 改值、媒体缺失、`available: false`
200
+ 却留着文件、往 bundle 里塞注册表未登记的键、指向 bundle 里不存在的键、跨机位
201
+ `sync_id` 不一致、`camera_id` 与目录不符),每项都必须被 `read_sequence.py` 的
202
+ 具名检查抓到。硬链接与发布树共享 inode,所以改动一律先 `unlink` 再新建;脚本
203
+ 结尾会重读真实发布树,证明没有写穿。
204
+ - `doc/validation/validate_report.json`:全量结构校验结果(视图数、帧数、各判据、`camera_models`、
205
+ `uncalibrated_views`、registry_gaps、发布清单的路径与文件数)。
206
+ - `doc/FULL_MIGRATION_SUMMARY.json`:全量迁移汇总。
207
+ - `doc/validation/index.html` 与 `doc/validation/<序列>_<相机>.html` + `<同一个>.report.json`:第 5 步
208
+ 渲染的 54 个视图的目视页与各自的 QC 报告,附 `doc/validation/V1_1_VALIDATION.json`(抽样规则、
209
+ 种子、入选序列、逐视图的帧数与投影计数、耗时)。每页单文件自包含(图片是内嵌 `data:` URI,
210
+ 无脚本、无外链),因为要随发布离线阅读,也因为发布树里的相对链接指向的是同在树内的规范文档。
211
+ - `tmp/arctic-tools/PUBLISH_MANIFEST.json`(**树外**,不是发布内容):发布树逐文件 sha256,
212
+ 第 8 步最后重建;按 H2O、dex-ycb 的约定放在树外,理由见上一节。
213
+ - `doc/validation/read_sequence_sweep.json`:CONTRACT §6.5 的读取器路径验收在全发布上的汇总
214
+ (序列数、视图数、读到的字段数、声明的媒体数、失败列表)。驱动脚本是
215
+ `tmp/arctic-tools/read_sequence_sweep.py`,它 import 本目录的 `read_sequence.py` 而不是复刻其判据,
216
+ 所以通过意味着**发布的那个读取器**接受了这些序列。逐序列明细在该文件里。
217
+
218
+ **v1.0 遗留材料的摘要来源。** 发布树里 `doc/history-v1.0/`(1065 个文件、428942175 字节)与
219
+ `script/v1_0_snapshot/script/`(22 个文件、233676 字节)是**原样搬运**的 v1.0 材料,属 CONTRACT §6.4
220
+ 「未修改文件须对照原始可信摘要」。但 `tmp/full-manifest.json` 只覆盖 `ARCTIC/shared-v1.0/data`
221
+ (90626 条,`doc/` 与 `script/` 下**一条都没有**),所以这两棵子树另从同一固定提交拉取并单独摘要核验
222
+ (`tmp/arctic-tools/v10-doc-script-verification.json`:两份子树全部 `VERIFY_PASS`,搬运副本与核验源
223
+ 逐字节相同,`v1_0_snapshot/doc/` 的 `CONTRACT.md`/`schema.json` 分别命中规范 v1.0 的
224
+ `c34cdf66…`/`9a34b349…`)。这份记录放在 `tmp/` 而不是并进 `migration-v11/registration.json`:后者由
225
+ `migrate.py` 写出,而迁移工具把自己的 sha256 记进 checkpoint,改动它会让 737 GiB 全部重迁。
226
+ 汇总文件里以 `carryover_v1_0_material` 一节引用该记录。
227
+
228
+ 验收只证明"重新打包在数值上逐字节同一",不等同于人工目视确认(CONTRACT §6.5)。
229
+
230
+ **逐视图 HTML 目视页。** 与 H2O、dex-ycb 一样,本发布在 `doc/validation/` 里带一套逐视图的目视页,由本目录的 `render.py` 生成(收尾顺序第 5 步)。它**只读 v1.1 的 bundle**,不引入 v1.0 时代的解码与投影栈、外部模型资产或新依赖:解码用发布树里已有的媒体经 `ffmpeg` 的 `select=` 逐帧取原图(不重编码,逐帧校验字节数),投影用 `cv2.projectPoints`,画图用 PIL 与 numpy。抽样规则写进随发布保留的 `V1_1_VALIDATION.json`,可复现:种子 20261014;按 split 分层 test 1、val 2、train 3;每个槽位取一个别的入选序列没用过的物体类别;入选序列的**全部 9 路相机**都出页,6 段共 54 个视图。这是照 H2O「整段全相机」的规矩来的,其中 test 槽位落在 P1 测试段——正是那 38 个源不提供相机标定的视图之一。
231
+
232
+ 每页给出:抽样帧的原生 RGB;物体关键点的投影,按发布的 `keypoint_names` 把 top 与 bottom 分色;各部件位姿的坐标轴;MANO 根平移的落点;组件与部件网格的形状预览;以及该帧**全部**数值组件与有效性的逐帧明细。另配 `<视图>.report.json`(该视图的帧数、各数值组件的 shape/dtype/有效计数、抽样帧、投影计数)与 `index.html`。配色沿用 ARCTIC v1.0 自己的 `doc/history-v1.0/validation/` 用过的说法(顶盖紫、底座绿、左手青、右手橙),一处偏离写在页面上:v1.0 把那 32 个关键点画成同一种白色,本页按发布的关键点名分色。
233
+
234
+ 它**不做**的事同样写在页面上:不叠加手部骨架或手部网格——发布里的 `mano` 只有 61 个参数、没有 2D/3D 关节,正向运动学需要 `MANO_{LEFT,RIGHT}.pkl` 与 `smplx`,两者都不在发布树里,也不在本次迁移所用的机器上(v1.0 的页面画得出,是因为它跑在带这套资产的机器上);不做深度或分割叠加——源里没有;源缺的字段一律**不补造**,那 38 个没有标定的视图只显示 RGB 与源缺项,并在页面上写明原因。
235
+
236
+ **画外点怎么判定、怎么披露。** 页面只画发布自己的 camera 系几何,所以「物体大部分落在画外」是会真实发生的情形,而一个几乎空的面板光看是分不出「物体真的出画」和「投影坏了」的。抽样出的 54 个视图里只有 `s05_microwave_use_01/0` 命中:第 195 帧 32 个有效关键点只有 1 个落在画内,而**同一帧**的 8 路 exo 视图是 32/32——该视图是戴在头上的 ego 相机,物体正好在视野上缘之上,与发布声明的 `coordinate_frame: camera` 自洽,不是投影错误。处置是披露而不是改数:页面在标题下点名命中的帧并说明这是 ego 视图的视野问题,面板标题以「物体大部分落在画外(该帧 N 个有效关键点只有 M 个落在画内)」开头,规则一并写出(`inside_points / valid_points < 0.5` 即标记)。规则之外还逐帧记数:**每个抽样帧**的 `annotated`、`valid_points`、`inside_points`、`inside_ratio`、`mostly_out_of_frame` 都写进该视图报告的 `projection.frames`(源未标注的帧记 `annotated: false`,不省略),规则原文写进 `projection.out_of_frame_rule`,视图级计数写进 `geometry_panels.frames_mostly_out_of_frame`。门限只用于披露,不改动任何发布数据。
237
+
238
+ 这套页面是**人工验收要看的材料**,不是训练输入。CONTRACT §6.5 区分「重打包在数值上逐字节同一」与「人工目视验收」,页面给的是后者;渲出页面不等于有人看过,所以发布状态里的 `full_output_human_review` 与汇总里的 `human_full_review` 都仍是 `"pending"`。ARCTIC v1.0 自己的复核产物照旧随发布保留在 `doc/history-v1.0/validation/`。
ARCTIC/shared-v1.1/script/arctic_v1_1/arctic_common.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers for the published ARCTIC shared-v1.1 tools.
2
+
3
+ Adapted from the shared-v1.0 ARCTIC tooling and from the shared layout library:
4
+ numeric tensors and their validity now live in per-group bundles addressed by the
5
+ dictionary keys registered in ``doc/schema.json`` instead of one ``.pt`` per
6
+ component with a sibling ``*_valid.pt``. Media, JSONL and mesh assets keep their
7
+ standalone bool Tensor validity and are not bundled (CONTRACT 4).
8
+
9
+ Three adaptations are ARCTIC's own rather than the shared layout's:
10
+
11
+ * nine camera views per sequence, one of which is the moving ego camera. Its
12
+ calibration pairs a separate 8-parameter distortion vector with the intrinsic
13
+ validity (CONTRACT 3, 5), so the pairing is checked from the registry's own
14
+ ``reference_rules.camera_distortion`` instead of from a hard-coded camera name.
15
+ * ``frames.jsonl`` carries ARCTIC's sync fields -- ``source_annotation_index``,
16
+ ``sync_id``, ``annotation_matches`` -- and every component whose rows are indexed
17
+ by that file declares ``source_locator.index_ref``. A field may therefore not
18
+ claim an annotation on a frame the source has no record for.
19
+ * ``object_box_keypoints`` declares ``arctic_object_keypoints/v1``, which the shared
20
+ registry does not enumerate -- it registers the two hand conventions only -- so the
21
+ keypoint count comes from the component's own ``keypoint_names`` and the gap is
22
+ reported rather than silently ignored.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ from pathlib import Path
29
+
30
+ import torch
31
+
32
+ from warehouse import (
33
+ BUNDLE_PROFILE,
34
+ BundleReader,
35
+ Registry,
36
+ raw_bytes,
37
+ )
38
+
39
+ SCRIPT_DIR = Path(__file__).resolve().parent
40
+ RELEASE_ROOT = SCRIPT_DIR.parent.parent
41
+ DATASET_ROOT = RELEASE_ROOT.parent
42
+ TMP_ROOT = DATASET_ROOT / "tmp" / "arctic-tools"
43
+ DOC_ROOT = RELEASE_ROOT / "doc"
44
+ REGISTRY = Registry.load(DOC_ROOT / "schema.json")
45
+
46
+ DATASET_ID = "ARCTIC"
47
+ #: ``source_locator.index_ref`` of every component indexed by frames.jsonl
48
+ ANNOTATION_INDEX_REF = "camera/frames.jsonl:source_annotation_index"
49
+ #: The release manifest is a *publication* artifact, not release content, so it is
50
+ #: built outside the release tree. It hashes every file of that tree, so a copy kept
51
+ #: inside could only describe the tree as it stood before that copy existed -- and
52
+ #: writing the copy back changes the tree again, leaving the manifest permanently one
53
+ #: edit behind. The published H2O and dex-ycb sets keep theirs outside for exactly
54
+ #: this reason (H2O's README: ``PUBLISH_MANIFEST.json`` records the publishable paths,
55
+ #: sizes and SHA256s outside the release); ARCTIC follows them, so its release tree
56
+ #: carries no manifest at all and nothing in it is excluded from its own hash.
57
+ MANIFEST_PATH = TMP_ROOT / "PUBLISH_MANIFEST.json"
58
+ #: ARCTIC's own release-status flags, which the migration preserves verbatim
59
+ STATUS_FLAGS = (
60
+ "pilot",
61
+ "pilot_complete",
62
+ "pilot_human_review",
63
+ "production_complete",
64
+ "upload_authorized",
65
+ "full_output_human_review",
66
+ "media_validation_policy",
67
+ )
68
+
69
+ #: v1.0 semantics 4.3: a view whose calibration the source does not establish
70
+ #: declares ``model: "unknown"`` with a null ``schema_id`` -- "不提供可用 intrinsic,
71
+ #: 不声称可以投影" -- rather than being guessed into a registered model. ARCTIC's P1
72
+ #: test sequences release neither the ego calibration nor any hand/object annotation,
73
+ #: so this is real released content, and the registry's ``camera`` section registers
74
+ #: only the four calibrated models.
75
+ UNKNOWN_CAMERA_MODEL = "unknown"
76
+ #: the components that carry a calibration
77
+ CALIBRATION_COMPONENTS = ("intrinsic", "extrinsic")
78
+
79
+ REGISTRY_READER = BundleReader()
80
+
81
+
82
+ def load(path):
83
+ return json.loads(Path(path).read_text(encoding="utf-8"))
84
+
85
+
86
+ def save(path, value):
87
+ path = Path(path)
88
+ path.parent.mkdir(parents=True, exist_ok=True)
89
+ temp = path.with_suffix(path.suffix + ".tmp")
90
+ temp.write_text(
91
+ json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False),
92
+ encoding="utf-8",
93
+ )
94
+ temp.replace(path)
95
+
96
+
97
+ def sha256(path, block: int = 8 << 20) -> str:
98
+ import hashlib
99
+
100
+ digest = hashlib.sha256()
101
+ with Path(path).open("rb") as stream:
102
+ for chunk in iter(lambda: stream.read(block), b""):
103
+ digest.update(chunk)
104
+ return digest.hexdigest()
105
+
106
+
107
+ # -- registry-driven shape resolution ---------------------------------------
108
+
109
+
110
+ def shape_symbols(meta, component, registry=REGISTRY, notes=None):
111
+ """Authoritative values for the symbolic axes a registry template may use.
112
+
113
+ ``T`` is the view's frame count and ``J`` the component's declared joint order.
114
+ ``K`` comes from the registry when the component names a registered keypoint
115
+ schema; ARCTIC's object keypoint set is not registered, so its count is taken
116
+ from the ``keypoint_names`` the component declares beside it. The unregistered
117
+ schema is recorded in ``notes`` -- it is a gap in the shared registry, not
118
+ something this reader should paper over.
119
+ """
120
+ symbols = {"T": meta["num_frames"]}
121
+ if component.get("joint_order"):
122
+ symbols["J"] = len(component["joint_order"])
123
+ schema = component.get("keypoint_schema")
124
+ if not schema:
125
+ return symbols
126
+ registered = registry.schema["keypoints"].get(schema)
127
+ if registered is not None:
128
+ symbols["K"] = registered["count"]
129
+ return symbols
130
+ names = component.get("keypoint_names")
131
+ if names:
132
+ symbols["K"] = len(names)
133
+ if notes is not None:
134
+ notes.append(
135
+ {
136
+ "kind": "keypoint_schema_unregistered",
137
+ "schema": schema,
138
+ "resolved_from": "component.keypoint_names" if names else "tensor extent",
139
+ "count": symbols.get("K"),
140
+ }
141
+ )
142
+ return symbols
143
+
144
+
145
+ def resolve_shape(template, tensor, symbols):
146
+ """Resolve a registry shape template against a real tensor.
147
+
148
+ ``T``, ``J`` and ``K`` come from the view metadata, the component and the
149
+ registry, so mismatches are caught; any other symbolic axis falls back to the
150
+ tensor's own extent, which is where an undeclared axis would show up.
151
+ """
152
+ dims = []
153
+ for axis, dim in enumerate(template):
154
+ assert axis < tensor.ndim, (list(template), list(tensor.shape))
155
+ dims.append(
156
+ symbols[dim]
157
+ if isinstance(dim, str) and dim in symbols
158
+ else (tensor.shape[axis] if isinstance(dim, str) else dim)
159
+ )
160
+ return dims
161
+
162
+
163
+ # -- per-component checks ---------------------------------------------------
164
+
165
+
166
+ def check_attributes(base, name, component, registry, reader=REGISTRY_READER, symbols=None):
167
+ """Validate every bundled numeric attribute on a component (CONTRACT 3, 5).
168
+
169
+ ARCTIC publishes no visibility attributes -- the measured hand keypoints and
170
+ their visibility are outside this release's scope -- so this is a no-op here.
171
+ It stays because the registry is shared with datasets that do declare them, and
172
+ a future ARCTIC revision must be held to the same rule.
173
+ """
174
+ if not component.get("attributes"):
175
+ return
176
+ required = registry.schema["tensor_attributes"]["visibility"]["required_metadata"]
177
+ assert symbols, (name, "caller must supply the view's shape symbols")
178
+ for attribute, spec in component["attributes"].items():
179
+ where = f"{name}.{attribute}"
180
+ for key in required:
181
+ assert key in spec, (where, key)
182
+ assert spec["data_ref"] == spec["valid_ref"], (where, "must share one bundle file")
183
+ assert spec["storage"]["profile"] == BUNDLE_PROFILE, where
184
+ assert spec["valid_storage"]["profile"] == BUNDLE_PROFILE, where
185
+ data, valid = reader.field(base, spec)
186
+ assert data.dtype == torch.bool and valid.dtype == torch.bool, (where, data.dtype)
187
+ expected = resolve_shape(registry.visibility_valid_shape(spec["axes"]), data, symbols)
188
+ assert list(data.shape) == expected, (where, list(data.shape), expected)
189
+ assert list(valid.shape) == list(data.shape), (where, "valid shape must match data")
190
+ assert list(spec["valid_axes"]) == list(spec["axes"])[: valid.ndim], (where, spec)
191
+ assert bool(valid.all()), (where, "expanded all-known validity must be all true")
192
+
193
+
194
+ def check_distortion(base, meta, name, component, registry=REGISTRY, reader=REGISTRY_READER):
195
+ """CONTRACT 3, 5: the separate distortion vector that joins the camera bundle.
196
+
197
+ Whether a component carries one is decided by the registry, not by the camera
198
+ name: a schema entry listing ``distortion_ref`` among its required metadata must
199
+ carry all four references at the locations ``reference_rules.camera_distortion``
200
+ fixes, and its vector must be stored under the entry key the registry assigns to
201
+ that camera model. A model the registry lists under
202
+ ``models_without_separate_distortion`` must carry none. Returns the evidence
203
+ record, or ``None`` when the component declares no distortion vector.
204
+ """
205
+ rules = registry.schema["reference_rules"]["camera_distortion"]
206
+ spec = registry.components[component["schema_id"]]
207
+ if "distortion_ref" not in spec.get("required_metadata", []):
208
+ for key in rules["required"]:
209
+ assert key not in component, (name, key, "unexpected on this camera model")
210
+ return None
211
+
212
+ model = meta["camera"]["model"]
213
+ assert model in rules["models"], (name, model, "no registered distortion schema")
214
+ assert model not in rules["models_without_separate_distortion"], (name, model)
215
+ for key in rules["required"]:
216
+ assert key in component, (name, component["schema_id"], "missing", key)
217
+ assert component["distortion_ref"] == rules["distortion_ref"], (
218
+ name,
219
+ "distortion_ref",
220
+ component["distortion_ref"],
221
+ rules["distortion_ref"],
222
+ )
223
+ assert component["distortion_valid_ref"] == rules["distortion_valid_ref"], (
224
+ name,
225
+ "distortion_valid_ref",
226
+ component["distortion_valid_ref"],
227
+ )
228
+ assert component["distortion_key"] == rules["distortion_key"], (
229
+ name,
230
+ "distortion_key",
231
+ component["distortion_key"],
232
+ )
233
+ assert component["distortion_valid_key"] == rules["distortion_valid_key"], (
234
+ name,
235
+ "distortion_valid_key",
236
+ component["distortion_valid_key"],
237
+ )
238
+
239
+ expected = rules["models"][model]
240
+ entry = registry.bundles["camera"]["entries"]["distortion"]
241
+ assert expected in entry["schema_ids"], (name, expected, entry)
242
+ vector_spec = registry.components[expected]
243
+ data = reader.get(base, component["distortion_ref"], component["distortion_key"])
244
+ valid = reader.get(base, component["distortion_valid_ref"], component["distortion_valid_key"])
245
+ symbols = shape_symbols(meta, component, registry)
246
+ assert list(data.shape) == resolve_shape(vector_spec["shape"], data, symbols), (
247
+ name,
248
+ "distortion shape",
249
+ list(data.shape),
250
+ vector_spec["shape"],
251
+ )
252
+ assert list(valid.shape) == resolve_shape(vector_spec["valid_shape"], valid, symbols), (
253
+ name,
254
+ "distortion valid shape",
255
+ list(valid.shape),
256
+ )
257
+ assert valid.dtype == torch.bool, (name, "distortion valid must be bool", valid.dtype)
258
+ #: the vector's last axis is the camera model's own parameter count
259
+ names = registry.schema["camera"][model]["distortion"]
260
+ assert data.shape[-1] == len(names), (name, "distortion parameters", list(data.shape), names)
261
+
262
+ shared = None
263
+ if rules.get("valid_equals_intrinsic_valid") and "valid_key" in component:
264
+ intrinsic_valid = reader.get(base, component["valid_ref"], component["valid_key"])
265
+ shared = raw_bytes(intrinsic_valid) == raw_bytes(valid)
266
+ assert shared, (name, "distortion valid must equal the intrinsic valid (CONTRACT 3)")
267
+ return {
268
+ "owner": f"{name}.distortion",
269
+ "entry": f"{component['distortion_ref']}:{'/'.join(component['distortion_key'][:-1])}",
270
+ "schema_id": expected,
271
+ "shape": list(data.shape),
272
+ "valid_true": int(valid.sum()),
273
+ "shares_intrinsic_validity": shared,
274
+ }
275
+
276
+
277
+ def published(components, name):
278
+ """Whether a view offers this component: absent, or present and unavailable."""
279
+ component = components.get(name)
280
+ return component is not None and component.get("available", True)
281
+
282
+
283
+ def check_camera(base, meta, registry=REGISTRY):
284
+ """The camera block's own consistency, declared-unknown state included.
285
+
286
+ ``camera`` names the model every calibrated component in the view follows, so the
287
+ registry must register it and the intrinsic must name the same one. A view that
288
+ could establish no calibration instead declares ``model: unknown`` and a null
289
+ ``schema_id`` and publishes neither intrinsic nor extrinsic, rather than filling
290
+ in a placeholder matrix (v1.0 semantics 4.3: "未知标定 | 相机内外参允许缺省,
291
+ 不填单位阵冒充已知标定"). That state is accepted here and constrains the rest of
292
+ the view, so it cannot become a blanket excuse for a missing calibration: a
293
+ registered model still has to publish its intrinsic.
294
+ """
295
+ camera = meta["camera"]
296
+ components = meta["components"]
297
+ for key in ("model", "schema_id", "image_size"):
298
+ assert key in camera, (base, "camera must declare", key)
299
+ model = camera["model"]
300
+
301
+ if model == UNKNOWN_CAMERA_MODEL:
302
+ assert camera["schema_id"] is None, (
303
+ base,
304
+ "an unknown camera declares no schema_id",
305
+ camera["schema_id"],
306
+ )
307
+ assert "distortion_ref" not in camera, (base, "an unknown camera has no distortion vector")
308
+ calibrated = [name for name in CALIBRATION_COMPONENTS if published(components, name)]
309
+ assert not calibrated, (base, "an unknown camera must not publish a calibration", calibrated)
310
+ return {"model": model, "schema_id": None, "calibration": []}
311
+
312
+ assert registry.components.get(camera["schema_id"]) is not None, (
313
+ base,
314
+ camera["schema_id"],
315
+ "unregistered camera model",
316
+ )
317
+ assert model in registry.schema["camera"], (base, model, "unregistered camera model")
318
+ intrinsic = components.get("intrinsic")
319
+ assert intrinsic is not None and intrinsic.get("available", True), (
320
+ base,
321
+ model,
322
+ "a registered camera model must publish its intrinsic",
323
+ )
324
+ assert intrinsic["schema_id"] == camera["schema_id"], (
325
+ base,
326
+ "the camera block and its intrinsic component must name one model",
327
+ camera["schema_id"],
328
+ intrinsic["schema_id"],
329
+ )
330
+ return {
331
+ "model": model,
332
+ "schema_id": camera["schema_id"],
333
+ "calibration": [name for name in CALIBRATION_COMPONENTS if published(components, name)],
334
+ }
335
+
336
+
337
+ def check_view(base, meta, registry=REGISTRY, reader=REGISTRY_READER):
338
+ """Structural checks for one ARCTIC view.
339
+
340
+ Returns ``(consumed, fields, notes)``: the file paths read into bundles or
341
+ loaded as standalone tensors, one evidence record per bundled field, and any
342
+ registry gap the reader had to work around.
343
+ """
344
+ view_metadata = registry.schema["view_metadata"]
345
+ assert meta["schema_version"] == view_metadata["schema_version"], base
346
+ assert meta["release_id"] == view_metadata["release_id"], base
347
+ assert meta["dataset_id"] == DATASET_ID, (base, meta["dataset_id"])
348
+ for key in view_metadata["required_fields"]:
349
+ assert key in meta, (base, key)
350
+ assert meta["view_type"] in view_metadata["view_type_values"], (base, meta["view_type"])
351
+
352
+ check_camera(base, meta, registry)
353
+
354
+ consumed, fields, notes = set(), [], []
355
+ for name, component in meta["components"].items():
356
+ if not component.get("available", True):
357
+ #: CONTRACT 4: an absent component is omitted or marked unavailable, and
358
+ #: it must not point at a file that is not there
359
+ for key in ("data_ref", "valid_ref", "data_key", "valid_key", "distortion_ref"):
360
+ assert key not in component, (name, key, "an unavailable component references a file")
361
+ continue
362
+ spec = registry.components.get(component.get("schema_id"))
363
+ assert spec is not None, (name, component.get("schema_id"), "unregistered")
364
+ for key in spec.get("required_metadata", []):
365
+ assert key in component, (name, component["schema_id"], key)
366
+ symbols = shape_symbols(meta, component, registry, notes)
367
+
368
+ if "data_key" in component:
369
+ #: bundled numeric field
370
+ for key in ("data_key", "valid_key", "storage", "valid_storage", "valid_ref", "valid_axes"):
371
+ assert key in component, (name, key)
372
+ assert component["data_ref"] == component["valid_ref"], (
373
+ name,
374
+ "bundled refs must share one file",
375
+ )
376
+ assert component["storage"]["profile"] == BUNDLE_PROFILE, name
377
+ assert component["valid_storage"]["profile"] == BUNDLE_PROFILE, name
378
+ data, valid = reader.field(base, component)
379
+ assert valid.dtype == torch.bool, (name, "valid must be bool", valid.dtype)
380
+ assert list(data.shape) == resolve_shape(spec["shape"], data, symbols), (
381
+ name,
382
+ "data shape",
383
+ list(data.shape),
384
+ spec["shape"],
385
+ symbols,
386
+ )
387
+ assert list(valid.shape) == resolve_shape(spec["valid_shape"], valid, symbols), (
388
+ name,
389
+ "valid shape",
390
+ list(valid.shape),
391
+ spec["valid_shape"],
392
+ symbols,
393
+ )
394
+ assert list(component["valid_axes"]) == list(component["axes"])[: valid.ndim], (
395
+ name,
396
+ "valid_axes must be axes[:valid.ndim]",
397
+ component["valid_axes"],
398
+ )
399
+ assert not data.is_floating_point() or bool(torch.isfinite(data[valid]).all()), (
400
+ name,
401
+ "non-finite value where valid",
402
+ )
403
+ fields.append(
404
+ {
405
+ "owner": name,
406
+ "entry": f"{component['data_ref']}:{'/'.join(component['data_key'][:-1])}",
407
+ "dtype": str(data.dtype),
408
+ "shape": list(data.shape),
409
+ "valid_shape": list(valid.shape),
410
+ "valid_true": int(valid.sum()),
411
+ "valid_false": int((~valid).sum()),
412
+ }
413
+ )
414
+ else:
415
+ #: media, JSONL or mesh asset: standalone validity, preserved verbatim
416
+ assert "valid_key" not in component, (name, "media/JSONL must not carry valid_key")
417
+ assert (base / component["data_ref"]).is_file(), (name, component["data_ref"])
418
+ valid_ref = component.get("valid_ref")
419
+ if valid_ref:
420
+ valid = torch.load(base / valid_ref, map_location="cpu", weights_only=True)
421
+ assert valid.dtype == torch.bool, (name, "standalone validity must be a bool Tensor")
422
+ if spec.get("valid_shape") is not None:
423
+ assert list(valid.shape) == resolve_shape(spec["valid_shape"], valid, symbols), (
424
+ name,
425
+ list(valid.shape),
426
+ )
427
+ consumed.add(valid_ref)
428
+ if component["data_ref"].endswith(".mkv"):
429
+ for key in registry.schema["video_metadata"]["required"]:
430
+ assert key in component["storage"], (name, key)
431
+ assert component["storage"]["profile"] in spec["allowed_storage_profiles"], (
432
+ name,
433
+ component["storage"]["profile"],
434
+ )
435
+
436
+ distortion = check_distortion(base, meta, name, component, registry, reader)
437
+ if distortion is not None:
438
+ fields.append(distortion)
439
+ consumed.add(component["data_ref"])
440
+ check_attributes(base, name, component, registry, reader, symbols)
441
+
442
+ return consumed, fields, notes
443
+
444
+
445
+ # -- stray and leftover detection -------------------------------------------
446
+
447
+
448
+ def stray_validity(registry, rel):
449
+ """A standalone validity file whose data field the registry merges into a bundle.
450
+
451
+ This is the CONTRACT 6.1 failure mode named explicitly: a numeric component's
452
+ validity left behind as its own file because its name was not recognised.
453
+ """
454
+ if not rel.endswith("_valid.pt"):
455
+ return False
456
+ return registry.resolve(rel[: -len("_valid.pt")] + ".pt") is not None
457
+
458
+
459
+ def leftover_numeric(registry, rel):
460
+ """A v1.0 standalone numeric file the registry merges into a different bundle."""
461
+ if not rel.endswith(".pt") or rel.endswith("_valid.pt"):
462
+ return False
463
+ resolved = registry.resolve(rel)
464
+ return resolved is not None and resolved[0] != rel
465
+
466
+
467
+ def referenced_paths(meta, consumed):
468
+ """Every released path the view's metadata names, for an unreferenced-file report."""
469
+ refs = set(consumed)
470
+ refs.add(meta["sampling"].get("frames_ref"))
471
+ for component in meta["components"].values():
472
+ for key in ("data_ref", "valid_ref", "distortion_ref", "distortion_valid_ref"):
473
+ if component.get(key):
474
+ refs.add(component[key])
475
+ return {ref for ref in refs if ref}
ARCTIC/shared-v1.1/script/arctic_v1_1/migrate.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Migrate the adjacent shared-v1.0 tree of this dataset to shared-v1.1.
3
+
4
+ Only the tensor layout changes (CONTRACT 1-5): numeric tensors and their validity
5
+ move into per-group bundles, metainfo references gain ``data_key``/``valid_key``
6
+ with ``pt/tensor_bundle/v1`` storage, and the two version fields are bumped.
7
+ Sampling, frame counts, dtypes, values, NaN bit patterns, validity judgements,
8
+ units, coordinate frames, hand slots, split and ``valid_policy`` are carried over
9
+ untouched (CONTRACT 6.3).
10
+
11
+ The source tree is never written to: this is a copy-out. Unchanged media and
12
+ JSONL are hardlinked by default, so nothing is re-encoded and no bytes are
13
+ duplicated (MIGRATION 2, 6). Every view is checkpointed with source and output
14
+ digests so ``--resume`` re-verifies rather than trusting file existence
15
+ (MIGRATION 4.4).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import fcntl
22
+ import json
23
+ import os
24
+ import shutil
25
+ import sys
26
+ import time
27
+ import traceback
28
+ from contextlib import contextmanager
29
+ from pathlib import Path
30
+
31
+ import torch
32
+
33
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
34
+
35
+ from warehouse import ( # noqa: E402
36
+ BUNDLE_PROFILE,
37
+ DATA_TERMINAL,
38
+ RELEASE_ID,
39
+ SCHEMA_VERSION,
40
+ VALID_TERMINAL,
41
+ BundleWriter,
42
+ Registry,
43
+ expanded_all_known,
44
+ sha256_bytes,
45
+ sha256_file,
46
+ same_tensor,
47
+ )
48
+
49
+ V10_SCHEMA_VERSION = "hand-warehouse/1.0"
50
+ TOOL_ID = "hw11-migrate"
51
+ TOOL_REVISION = "1"
52
+
53
+ #: this package lives in <dataset>/shared-v1.1/script/arctic_v1_1, so the release
54
+ #: and the dataset root beside it need no arguments.
55
+ RELEASE_ROOT = Path(__file__).resolve().parent.parent.parent
56
+ DATASET_ROOT = RELEASE_ROOT.parent
57
+
58
+
59
+ # --------------------------------------------------------------------------
60
+ # filesystem helpers
61
+ # --------------------------------------------------------------------------
62
+
63
+ @contextmanager
64
+ def migration_lock(work: Path):
65
+ """MIGRATION 3: one migrator per dataset, held for the whole run.
66
+
67
+ The lock file lives in ``tmp/`` beside the checkpoints it protects, outside
68
+ the release tree. A second run is refused rather than interleaved: two
69
+ processes writing the same destination view would each leave behind a
70
+ checkpoint describing a tree the other had already overwritten, and a
71
+ checkpoint that cannot be trusted is worse than none.
72
+ """
73
+ work.mkdir(parents=True, exist_ok=True)
74
+ path = work / "migration.lock"
75
+ with path.open("a+", encoding="utf-8") as stream:
76
+ try:
77
+ fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
78
+ except BlockingIOError as error:
79
+ holder = path.read_text(encoding="utf-8").strip() or "unknown"
80
+ raise SystemExit(
81
+ f"another migration already holds {path} ({holder}); "
82
+ "refusing to run two at once (MIGRATION 3)"
83
+ ) from error
84
+ stream.seek(0)
85
+ stream.truncate()
86
+ stream.write(f"pid {os.getpid()} started {time.strftime('%Y-%m-%dT%H:%M:%S%z')}\n")
87
+ stream.flush()
88
+ try:
89
+ yield
90
+ finally:
91
+ fcntl.flock(stream, fcntl.LOCK_UN)
92
+
93
+
94
+ def _clone(src: Path, dst: Path) -> None:
95
+ """FICLONE (reflink) copy where the filesystem supports it."""
96
+ with open(src, "rb") as reader, open(dst, "wb") as writer:
97
+ fcntl.ioctl(writer.fileno(), 0x40049409, reader.fileno())
98
+
99
+
100
+ def materialise(src: Path, dst: Path, mode: str) -> str:
101
+ """Place an unchanged file at ``dst`` without ever re-encoding it.
102
+
103
+ An existing destination is never trusted on existence alone: it must be the
104
+ same inode as the source, or match it by SHA256, otherwise it is replaced.
105
+ """
106
+ dst.parent.mkdir(parents=True, exist_ok=True)
107
+ if dst.exists():
108
+ if os.path.samefile(src, dst):
109
+ return "same-inode"
110
+ if dst.stat().st_size == src.stat().st_size and sha256_file(dst) == sha256_file(src):
111
+ return "present-verified"
112
+ temp = dst.with_name(dst.name + ".hw11-tmp")
113
+ temp.unlink(missing_ok=True)
114
+ shutil.copy2(src, temp)
115
+ os.replace(temp, dst)
116
+ if mode in ("hardlink", "reflink"):
117
+ link = os.link if mode == "hardlink" else (lambda a, b: _clone(Path(a), Path(b)))
118
+ try:
119
+ link(src, dst)
120
+ return mode
121
+ except OSError:
122
+ pass
123
+ shutil.copy2(src, dst)
124
+ return "copy"
125
+
126
+
127
+ def load_tensor(path: Path) -> torch.Tensor:
128
+ tensor = torch.load(path, map_location="cpu", weights_only=True)
129
+ if not isinstance(tensor, torch.Tensor):
130
+ raise TypeError(f"{path}: expected a Tensor, got {type(tensor).__name__}")
131
+ return tensor
132
+
133
+
134
+ # --------------------------------------------------------------------------
135
+ # registry conformance
136
+ # --------------------------------------------------------------------------
137
+
138
+ #: what a registered schema *is*, as opposed to what it is called
139
+ SCHEMA_IDENTITY_FIELDS = ("dtype", "shape", "valid_shape", "unit")
140
+
141
+
142
+ def schema_id_note(registry: Registry, owner: str, spec: dict, entry: dict,
143
+ bundle_rel: str, field: str):
144
+ """Reconcile a v1.0 ``schema_id`` with the bundle entry's ``schema_ids`` list.
145
+
146
+ A mismatch is recorded as a note, not raised. CONTRACT 6.3 forbids changing
147
+ ``schema_id``, so a v1.0 label the registry words differently cannot be
148
+ corrected here; ``schema_ids`` is documented nowhere in CONTRACT.md or
149
+ MIGRATION.md; and the registry's own ``note`` calls it "a declarative registry,
150
+ not a JSON Schema document or executable validator". The check keeps its real
151
+ purpose by refusing only when the declared schema is not *structurally* the
152
+ field the entry allows (dtype, shape, valid_shape, unit) -- which is what a
153
+ wrong bundle entry actually looks like.
154
+
155
+ ARCTIC is the live case: v1.0 labels both part poses ``object/rigid/v1`` while
156
+ itself declaring ``convention: T_camera_from_part``, the convention the
157
+ registry pairs with ``transform/se3/v1``, and the two schema definitions are
158
+ identical in every identity field.
159
+ """
160
+ allowed = entry.get("schema_ids")
161
+ schema_id = spec.get("schema_id")
162
+ if allowed is None or schema_id in allowed:
163
+ return None
164
+ declared = registry.components.get(schema_id)
165
+ if declared is None:
166
+ raise ValueError(f"{owner}: schema_id {schema_id!r} is not registered")
167
+ equivalent = [name for name in allowed
168
+ if all(declared.get(key) == (registry.components.get(name) or {}).get(key)
169
+ for key in SCHEMA_IDENTITY_FIELDS)]
170
+ if not equivalent:
171
+ raise ValueError(
172
+ f"{owner}: schema_id {schema_id!r} not allowed in {bundle_rel}:{field} and "
173
+ f"is not structurally equivalent to any of {list(allowed)}")
174
+ return {
175
+ "owner": owner,
176
+ "entry": f"{bundle_rel}:{field}",
177
+ "declared_schema_id": schema_id,
178
+ "entry_schema_ids": list(allowed),
179
+ "structurally_equivalent_to": equivalent,
180
+ "reason": "CONTRACT 6.3 forbids changing schema_id; the entry allows a "
181
+ "schema identical in dtype, shape, valid_shape and unit",
182
+ }
183
+
184
+
185
+ def shared_distortion_valid(registry: Registry, owner: dict, entry: dict,
186
+ data: torch.Tensor, owner_valid):
187
+ """The bool an existing camera model pairs between intrinsic and distortion.
188
+
189
+ CONTRACT 3: "既有相机模型要求内参与单独畸变向量共用有效性时,在两个字段内保存
190
+ 相同 bool 值并校验一致". ARCTIC's v1.0 declares ``distortion_ref`` with no
191
+ distortion validity of its own, so the owning component's intrinsic validity is
192
+ the pairing the model already had -- this restates it rather than expanding an
193
+ all-true tensor that was never declared.
194
+ """
195
+ required = (registry.components.get(owner.get("schema_id")) or {}).get(
196
+ "required_metadata") or []
197
+ if not any(key.startswith("distortion") for key in required) or owner_valid is None:
198
+ return None
199
+ declared = _distortion_valid_shape(registry, entry, data)
200
+ if declared is None or list(owner_valid.shape) != declared:
201
+ return None
202
+ return owner_valid
203
+
204
+
205
+ def _distortion_valid_shape(registry: Registry, entry: dict, data: torch.Tensor):
206
+ """Resolve the declared ``valid_shape`` of whichever distortion schema fits ``data``.
207
+
208
+ Which of the entry's schemas applies is decided structurally, by the declared
209
+ ``shape`` matching the tensor, so nothing is assumed from the model's name.
210
+ """
211
+ for schema_id in entry.get("schema_ids") or []:
212
+ shape = (registry.components.get(schema_id) or {}).get("shape")
213
+ if not shape or len(shape) != data.ndim:
214
+ continue
215
+ if not all(isinstance(dim, str) or int(dim) == size
216
+ for dim, size in zip(shape, data.shape)):
217
+ continue
218
+ valid_shape = (registry.components.get(schema_id) or {}).get("valid_shape") or []
219
+ return [data.shape[axis] if isinstance(dim, str) else int(dim)
220
+ for axis, dim in enumerate(valid_shape)]
221
+ return None
222
+
223
+
224
+ # --------------------------------------------------------------------------
225
+ # per-view migration
226
+ # --------------------------------------------------------------------------
227
+
228
+ def _declared_shape(registry: Registry, owner: str, spec: dict, kind: str):
229
+ """The registry's declared ``(shape, valid_shape)`` for this field."""
230
+ if kind == "attribute":
231
+ return None, registry.visibility_valid_shape(spec["axes"])
232
+ schema_id = spec.get("schema_id")
233
+ entry = registry.components.get(schema_id)
234
+ if entry is None:
235
+ raise KeyError(f"{owner}: schema_id {schema_id!r} is not registered")
236
+ return entry.get("shape"), entry.get("valid_shape")
237
+
238
+
239
+ def _rewrite_reference(spec: dict, bundle_rel: str, keys: list, valid: torch.Tensor) -> dict:
240
+ """CONTRACT 5: same-file data/valid refs plus explicit dictionary keys."""
241
+ before = {
242
+ "data_ref": spec.get("data_ref"),
243
+ "valid_ref": spec.get("valid_ref"),
244
+ "valid": spec.pop("valid", "<absent>"),
245
+ "valid_axes": spec.get("valid_axes"),
246
+ }
247
+ spec["data_ref"] = bundle_rel
248
+ spec["data_key"] = list(keys) + [DATA_TERMINAL]
249
+ spec["valid_ref"] = bundle_rel
250
+ spec["valid_key"] = list(keys) + [VALID_TERMINAL]
251
+ spec["storage"] = {"profile": BUNDLE_PROFILE}
252
+ spec["valid_storage"] = {"profile": BUNDLE_PROFILE}
253
+ # visibility metadata requires valid_axes (tensor_attributes.visibility);
254
+ # v1.0 wrote it as axes[:valid.ndim], so deriving it restates the same value.
255
+ axes = spec.get("axes")
256
+ if axes and not spec.get("valid_axes"):
257
+ spec["valid_axes"] = list(axes)[:valid.ndim]
258
+ return before
259
+
260
+
261
+ def _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes,
262
+ owner, spec, kind, num_frames):
263
+ """Stage one registered numeric field into its bundle. No-op when unmerged.
264
+
265
+ Returns the field's bool validity Tensor, or ``None`` when the reference is not
266
+ a registered numeric field (media / JSONL / assets, preserved verbatim). The
267
+ caller needs that Tensor because this function rewrites ``spec`` in place via
268
+ `_rewrite_reference`, so the same spec can no longer be resolved to its source
269
+ field once staged.
270
+ """
271
+ ref = spec.get("data_ref")
272
+ if not ref:
273
+ return None
274
+ resolved = registry.resolve(ref)
275
+ if resolved is None:
276
+ return None # media / JSONL / assets: preserved verbatim
277
+ bundle_rel, keys, entry = resolved
278
+ field = "/".join(keys)
279
+
280
+ note = schema_id_note(registry, owner, spec, entry, bundle_rel, field)
281
+ if note is not None:
282
+ notes.append(note)
283
+ if entry.get("attribute_id") and kind != "attribute":
284
+ raise ValueError(f"{owner}: {bundle_rel}:{field} is an attribute entry")
285
+ if kind == "attribute" and not entry.get("attribute_id"):
286
+ raise ValueError(f"{owner}: {bundle_rel}:{field} is not declared as an attribute")
287
+
288
+ source = src_view / ref
289
+ if not source.is_file():
290
+ raise FileNotFoundError(f"{owner}: {ref} is registered but missing")
291
+
292
+ data = load_tensor(source)
293
+ declared_shape, declared_valid_shape = _declared_shape(registry, owner, spec, kind)
294
+ if declared_shape and declared_shape[0] == "T" and data.shape[0] != num_frames:
295
+ raise ValueError(
296
+ f"{owner}: {ref} has {data.shape[0]} frames but metainfo says {num_frames}")
297
+
298
+ valid_ref = spec.get("valid_ref")
299
+ if valid_ref:
300
+ valid = load_tensor(src_view / valid_ref)
301
+ consumed.add(valid_ref)
302
+ origin = f"source tensor {valid_ref}"
303
+ else:
304
+ if spec.get("valid") is not True:
305
+ raise ValueError(f"{owner}: {ref} has neither valid_ref nor a declared all-known scalar")
306
+ valid = expanded_all_known(data, declared_valid_shape)
307
+ origin = "expanded declared all-known scalar (CONTRACT 3)"
308
+
309
+ writer = writers.get(bundle_rel)
310
+ if writer is None:
311
+ writer = writers[bundle_rel] = BundleWriter(dst_view, bundle_rel)
312
+
313
+ # The registry fixes one entry per numeric field, so two components may share
314
+ # it (RHD's uv and xyz both read the same source visibility). Staging it
315
+ # once is correct; a second owner with different bytes is a registry mismatch.
316
+ identity = (bundle_rel, field)
317
+ prior = staged.get(identity)
318
+ if prior is None:
319
+ writer.put(keys, data, valid)
320
+ staged[identity] = {"data": data, "valid": valid, "owners": [owner],
321
+ "source_data_ref": ref, "source_valid_ref": valid_ref}
322
+ shared_with = None
323
+ else:
324
+ if not (same_tensor(prior["data"], data) and same_tensor(prior["valid"], valid)):
325
+ raise ValueError(
326
+ f"{owner}: {identity[0]}:{field} is already staged from "
327
+ f"{prior['source_data_ref']} with different values")
328
+ prior["owners"].append(owner)
329
+ shared_with = list(prior["owners"])
330
+ consumed.add(ref)
331
+
332
+ before = _rewrite_reference(spec, bundle_rel, keys, valid)
333
+ records.append({
334
+ "owner": owner,
335
+ "kind": kind,
336
+ "entry": f"{bundle_rel}:{field}",
337
+ "source_data_ref": before["data_ref"],
338
+ "source_valid_ref": before["valid_ref"],
339
+ "source_scalar_valid": before["valid"],
340
+ "source_valid_axes": before["valid_axes"],
341
+ "valid_origin": origin,
342
+ "shared_entry_owners": shared_with,
343
+ "dtype": str(data.dtype),
344
+ "shape": list(data.shape),
345
+ "valid_shape": list(valid.shape),
346
+ "valid_true": int(valid.sum()),
347
+ "valid_false": int((~valid).sum()),
348
+ "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None,
349
+ })
350
+ return valid
351
+
352
+
353
+ def migrate_view(registry, src_root, dst_root, sequence, camera, link_mode):
354
+ """Migrate one ``<sequence>/<camera>`` view and return its report entry."""
355
+ src_view = src_root / sequence / camera
356
+ dst_view = dst_root / sequence / camera
357
+ meta_path = src_view / "metainfo.json"
358
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
359
+ if meta.get("schema_version") != V10_SCHEMA_VERSION:
360
+ raise ValueError(f"{meta_path}: not {V10_SCHEMA_VERSION}")
361
+ if (meta.get("sequence_id"), meta.get("camera_id")) != (sequence, camera):
362
+ raise ValueError(f"{meta_path}: sequence_id/camera_id do not match the directory")
363
+ num_frames = meta["num_frames"]
364
+
365
+ dst_view.mkdir(parents=True, exist_ok=True)
366
+ writers, consumed, records, staged, notes = {}, set(), [], {}, []
367
+
368
+ #: each component's staged validity, for a camera model that pairs it with the
369
+ #: separate distortion vector (CONTRACT 3). Taken from _stage's return value:
370
+ #: _stage rewrites the component in place, so re-resolving ``data_ref`` here
371
+ #: would read the already-migrated bundle path and never match an entry.
372
+ staged_valid = {}
373
+ for name, component in meta["components"].items():
374
+ if not component.get("available", True):
375
+ continue
376
+ staged_valid[name] = _stage(
377
+ registry, src_view, dst_view, writers, consumed, records, staged, notes,
378
+ name, component, "component", num_frames)
379
+ for attribute, spec in (component.get("attributes") or {}).items():
380
+ _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes,
381
+ f"{name}.{attribute}", spec, "attribute", num_frames)
382
+
383
+ # camera distortion lives beside the intrinsic parameters (CONTRACT 5). v1.0
384
+ # declares it on the camera component that owns the calibration -- ARCTIC puts
385
+ # ``distortion_ref`` on ``intrinsic`` -- so the components are searched first
386
+ # and the ``camera`` block is only a fallback.
387
+ distortion_meta, distortion_owner = None, None
388
+ for name, component in meta["components"].items():
389
+ if component.get("distortion_ref"):
390
+ distortion_meta, distortion_owner = component, name
391
+ break
392
+ if distortion_meta is None and (meta.get("camera") or {}).get("distortion_ref"):
393
+ distortion_meta = meta["camera"]
394
+ if distortion_meta is not None:
395
+ camera_meta = distortion_meta
396
+ ref = camera_meta["distortion_ref"]
397
+ resolved = registry.resolve(ref)
398
+ if resolved is None:
399
+ raise ValueError(f"camera.distortion_ref {ref!r} does not resolve to a bundle")
400
+ bundle_rel, keys, entry = resolved
401
+ data = load_tensor(src_view / ref)
402
+ valid_ref = camera_meta.get("distortion_valid_ref")
403
+ if valid_ref:
404
+ valid = load_tensor(src_view / valid_ref)
405
+ consumed.add(valid_ref)
406
+ origin = f"source tensor {valid_ref}"
407
+ else:
408
+ valid = shared_distortion_valid(registry, distortion_meta, entry, data,
409
+ staged_valid.get(distortion_owner))
410
+ if valid is not None:
411
+ origin = "shared with intrinsic validity (CONTRACT 3)"
412
+ else:
413
+ valid = expanded_all_known(data, camera_meta.get("distortion_valid_shape"))
414
+ origin = "expanded declared all-known scalar (CONTRACT 3)"
415
+ writer = writers.get(bundle_rel) or writers.setdefault(
416
+ bundle_rel, BundleWriter(dst_view, bundle_rel))
417
+ writer.put(keys, data, valid)
418
+ consumed.add(ref)
419
+ camera_meta["distortion_ref"] = bundle_rel
420
+ camera_meta["distortion_key"] = list(keys) + [DATA_TERMINAL]
421
+ camera_meta["distortion_valid_ref"] = bundle_rel
422
+ camera_meta["distortion_valid_key"] = list(keys) + [VALID_TERMINAL]
423
+ records.append({
424
+ "owner": f"{distortion_owner}.distortion" if distortion_owner else "camera.distortion",
425
+ "kind": "component",
426
+ "entry": f"{bundle_rel}:{'/'.join(keys)}",
427
+ "source_data_ref": ref,
428
+ "source_valid_ref": valid_ref,
429
+ "source_scalar_valid": "<absent>",
430
+ "source_valid_axes": camera_meta.get("distortion_valid_axes"),
431
+ "valid_origin": origin,
432
+ "shared_entry_owners": None,
433
+ "dtype": str(data.dtype),
434
+ "shape": list(data.shape),
435
+ "valid_shape": list(valid.shape),
436
+ "valid_true": int(valid.sum()),
437
+ "valid_false": int((~valid).sum()),
438
+ "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None,
439
+ })
440
+
441
+ # everything not consumed into a bundle is preserved byte-for-byte
442
+ passthrough = {}
443
+ for path in sorted(src_view.rglob("*")):
444
+ if not path.is_file():
445
+ continue
446
+ rel = path.relative_to(src_view).as_posix()
447
+ if rel in consumed or rel == "metainfo.json":
448
+ continue
449
+ passthrough[rel] = materialise(path, dst_view / rel, link_mode)
450
+
451
+ # MIGRATION 4.2: write, re-read, compare field by field, byte-exactly
452
+ verification = []
453
+ for bundle_rel, writer in sorted(writers.items()):
454
+ path = writer.save()
455
+ if path is None:
456
+ continue
457
+ reloaded = torch.load(path, map_location="cpu", weights_only=True)
458
+ for keys, leaf in _walk_leaf(writer.tree):
459
+ node = reloaded
460
+ for key in keys:
461
+ node = node[key]
462
+ for terminal in (DATA_TERMINAL, VALID_TERMINAL):
463
+ if not same_tensor(leaf[terminal], node[terminal]):
464
+ raise AssertionError(f"{bundle_rel}:{'/'.join(keys)}:{terminal} not byte-identical")
465
+ verification.append({
466
+ "bundle": bundle_rel,
467
+ "sha256": sha256_file(path),
468
+ "size": path.stat().st_size,
469
+ "fields": sum(1 for _ in _walk_leaf(writer.tree)),
470
+ "comparison": "byte_view_exact_no_tolerance",
471
+ })
472
+
473
+ meta["schema_version"] = SCHEMA_VERSION
474
+ meta["release_id"] = RELEASE_ID
475
+ _write_json(dst_view / "metainfo.json", meta)
476
+
477
+ return {
478
+ "sequence_id": sequence,
479
+ "camera_id": camera,
480
+ "num_frames": num_frames,
481
+ "source_metainfo_sha256": sha256_file(meta_path),
482
+ "source_metainfo_size": meta_path.stat().st_size,
483
+ "output_metainfo_sha256": sha256_file(dst_view / "metainfo.json"),
484
+ "bundles": verification,
485
+ "fields": records,
486
+ "schema_notes": notes,
487
+ "passthrough_files": len(passthrough),
488
+ "passthrough_modes": sorted(set(passthrough.values())),
489
+ "replaced_source_refs": sorted(
490
+ {r["source_data_ref"] for r in records} | {r["source_valid_ref"] for r in records if r["source_valid_ref"]}),
491
+ }
492
+
493
+
494
+ def _walk_leaf(tree, prefix=()):
495
+ for key, value in tree.items():
496
+ if isinstance(value, dict) and set(value) == {DATA_TERMINAL, VALID_TERMINAL}:
497
+ yield prefix + (key,), value
498
+ elif isinstance(value, dict):
499
+ yield from _walk_leaf(value, prefix + (key,))
500
+
501
+
502
+ def _write_json(path: Path, value) -> None:
503
+ path = Path(path)
504
+ path.parent.mkdir(parents=True, exist_ok=True)
505
+ temp = path.with_name(path.name + ".tmp")
506
+ temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n",
507
+ encoding="utf-8")
508
+ temp.replace(path)
509
+
510
+
511
+ # --------------------------------------------------------------------------
512
+ # dataset driver
513
+ # --------------------------------------------------------------------------
514
+
515
+ def discover_views(src_root: Path):
516
+ views = []
517
+ for meta in sorted(src_root.glob("data/*/*/metainfo.json")):
518
+ views.append((meta.parent.parent.name, meta.parent.name))
519
+ return views
520
+
521
+
522
+ def tool_digest(script_dir: Path, schema_path: Path) -> dict:
523
+ return {
524
+ "tool": f"{TOOL_ID}/{TOOL_REVISION}",
525
+ "migrate_sha256": sha256_file(Path(__file__).resolve()),
526
+ "layout_sha256": sha256_file(script_dir / "warehouse.py"),
527
+ "schema_sha256": sha256_file(schema_path),
528
+ "python": sys.version.split()[0],
529
+ "torch": torch.__version__,
530
+ }
531
+
532
+
533
+ def source_manifest(path: Path | None) -> dict | None:
534
+ """Describe the tree-API manifest the source bytes were pulled against.
535
+
536
+ The registration has to be readable on its own: "this tree came from revision
537
+ X" means little without the file list and digests that revision published, so
538
+ the manifest's own digest and size travel with it (MIGRATION 3).
539
+ """
540
+ if path is None:
541
+ return None
542
+ entries = json.loads(path.read_text(encoding="utf-8"))
543
+ entries = entries["files"] if isinstance(entries, dict) else entries
544
+ return {
545
+ "path": str(path.resolve()),
546
+ "sha256": sha256_file(path),
547
+ "files": len(entries),
548
+ "bytes": sum(int(entry.get("size", 0)) for entry in entries),
549
+ }
550
+
551
+
552
+ def checkpoint_ok(state_path: Path, expected: dict, digest: dict) -> bool:
553
+ """MIGRATION 4.4: re-verify inputs, tool revision and artefacts, not existence."""
554
+ if not state_path.is_file():
555
+ return False
556
+ try:
557
+ prior = json.loads(state_path.read_text(encoding="utf-8"))
558
+ except (json.JSONDecodeError, OSError):
559
+ return False
560
+ if prior.get("tool") != digest:
561
+ return False
562
+ # a checkpoint describes one destination; never let it vouch for another
563
+ if prior.get("dst_view") != str(expected["dst_view"]):
564
+ return False
565
+ if prior.get("source_metainfo_sha256") != expected["source_metainfo_sha256"]:
566
+ return False
567
+ for bundle in prior.get("bundles", []):
568
+ path = Path(prior["dst_view"]) / bundle["bundle"]
569
+ if not path.is_file() or sha256_file(path) != bundle["sha256"]:
570
+ return False
571
+ meta = Path(prior["dst_view"]) / "metainfo.json"
572
+ if not meta.is_file() or sha256_file(meta) != prior["output_metainfo_sha256"]:
573
+ return False
574
+ return True
575
+
576
+
577
+ def main(argv=None):
578
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
579
+ parser.add_argument("--src", type=Path, default=DATASET_ROOT,
580
+ help="dataset root holding shared-v1.0 (default: the dataset "
581
+ "this package is installed in)")
582
+ parser.add_argument("--dst", type=Path, default=RELEASE_ROOT,
583
+ help="output release directory (default <src>/shared-v1.1)")
584
+ parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json",
585
+ help="v1.1 schema.json (default <dst>/doc/schema.json)")
586
+ parser.add_argument("--link", default="hardlink", choices=["hardlink", "reflink", "copy"],
587
+ help="how unchanged media/JSONL is placed (default hardlink)")
588
+ parser.add_argument("--views", nargs="*", default=None,
589
+ help="restrict to these sequence ids")
590
+ parser.add_argument("--limit", type=int, default=None, help="migrate at most N views")
591
+ parser.add_argument("--resume", action="store_true",
592
+ help="skip views whose checkpoint re-verifies")
593
+ parser.add_argument("--dry-run", action="store_true")
594
+ parser.add_argument("--source-revision", default=None, metavar="SHA",
595
+ help="the pinned revision the shared-v1.0 bytes came from; "
596
+ "recorded in the registration (MIGRATION 3)")
597
+ parser.add_argument("--source-manifest", type=Path, default=None,
598
+ help="tree-API manifest of that revision; its digest and file "
599
+ "count are recorded so the registration is self-contained")
600
+ args = parser.parse_args(argv)
601
+
602
+ src_release = args.src / "shared-v1.0"
603
+ dst_release = args.dst or (args.src / "shared-v1.1")
604
+ if not src_release.is_dir():
605
+ parser.error(f"{src_release} is not a directory")
606
+ schema_path = args.schema or (dst_release / "doc" / "schema.json")
607
+ if not schema_path.is_file():
608
+ parser.error(f"v1.1 schema not found at {schema_path} (pass --schema)")
609
+ registry = Registry.load(schema_path)
610
+
611
+ src_root, dst_root = src_release / "data", dst_release / "data"
612
+ views = discover_views(src_release)
613
+ if not views:
614
+ parser.error(f"no <sequence>/<camera>/metainfo.json found under {src_root}")
615
+ first = src_root / views[0][0] / views[0][1] / "metainfo.json"
616
+ dataset_id = json.loads(first.read_text(encoding="utf-8"))["dataset_id"]
617
+
618
+ work = args.src / "tmp" / "migration-v11"
619
+ state_dir = work / "checkpoints"
620
+ if args.views:
621
+ wanted = set(args.views)
622
+ views = [v for v in views if v[0] in wanted]
623
+ if args.limit:
624
+ views = views[:args.limit]
625
+
626
+ digest = tool_digest(Path(__file__).resolve().parent, schema_path)
627
+ print(f"dataset={dataset_id} views={len(views)} src={src_release} dst={dst_release}")
628
+ print(f"tool={digest['tool']} link={args.link}")
629
+ if args.dry_run:
630
+ for sequence, camera in views:
631
+ print(f" would migrate {sequence}/{camera}")
632
+ return 0
633
+
634
+ with migration_lock(work):
635
+ registration = {
636
+ "dataset_id": dataset_id,
637
+ "source": {"release": "shared-v1.0", "schema_version": V10_SCHEMA_VERSION,
638
+ "schema_sha256": sha256_file(src_release / "doc" / "schema.json")
639
+ if (src_release / "doc" / "schema.json").is_file() else None,
640
+ "path": str(src_release.resolve()),
641
+ "revision": args.source_revision,
642
+ "manifest": source_manifest(args.source_manifest)},
643
+ "target": {"release": RELEASE_ID, "schema_version": SCHEMA_VERSION,
644
+ "schema_sha256": sha256_file(schema_path), "path": str(dst_release.resolve())},
645
+ "tool": digest,
646
+ "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
647
+ "views_total": len(views),
648
+ "views": [],
649
+ "errors": [],
650
+ }
651
+
652
+ done = skipped = failed = 0
653
+ for index, (sequence, camera) in enumerate(views, 1):
654
+ state_path = state_dir / f"{sequence}__{camera}.json"
655
+ dst_view = dst_root / sequence / camera
656
+ try:
657
+ if args.resume and checkpoint_ok(state_path, {
658
+ "dst_view": str(dst_view),
659
+ "source_metainfo_sha256": sha256_file(src_root / sequence / camera / "metainfo.json"),
660
+ }, digest):
661
+ skipped += 1
662
+ print(f"[{index}/{len(views)}] {sequence}/{camera} skip (checkpoint re-verified)")
663
+ continue
664
+ entry = migrate_view(registry, src_root, dst_root, sequence, camera, args.link)
665
+ entry["dst_view"] = str(dst_view)
666
+ entry["tool"] = digest
667
+ entry["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
668
+ _write_json(state_path, entry)
669
+ registration["views"].append({k: entry[k] for k in (
670
+ "sequence_id", "camera_id", "num_frames", "source_metainfo_sha256",
671
+ "output_metainfo_sha256", "bundles", "passthrough_files",
672
+ "replaced_source_refs", "schema_notes")})
673
+ done += 1
674
+ print(f"[{index}/{len(views)}] {sequence}/{camera} ok "
675
+ f"fields={len(entry['fields'])} bundles={len(entry['bundles'])} "
676
+ f"passthrough={entry['passthrough_files']}")
677
+ except Exception as error: # noqa: BLE001 - recorded, never hidden
678
+ failed += 1
679
+ registration["errors"].append({
680
+ "sequence_id": sequence, "camera_id": camera,
681
+ "error": f"{type(error).__name__}: {error}",
682
+ "traceback": traceback.format_exc(),
683
+ })
684
+ print(f"[{index}/{len(views)}] {sequence}/{camera} FAILED: {error}", file=sys.stderr)
685
+ _write_json(work / "registration.json", registration)
686
+
687
+ registration["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
688
+ registration["stage"] = "complete" if failed == 0 else "failed"
689
+ registration["counts"] = {"migrated": done, "skipped": skipped, "failed": failed}
690
+ _write_json(work / "registration.json", registration)
691
+ print(f"done={done} skipped={skipped} failed={failed}")
692
+ print(f"registration: {work / 'registration.json'}")
693
+ return 1 if failed else 0
694
+
695
+
696
+ if __name__ == "__main__":
697
+ raise SystemExit(main())
ARCTIC/shared-v1.1/script/arctic_v1_1/read_sequence.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CONTRACT 6.5: read one complete sequence through the v1.1 reader, every camera.
2
+
3
+ Acceptance item 5 asks for a check the byte-level ones cannot give. ``verify.py``
4
+ compares a view's bytes against its own v1.0 source, which proves repackaging
5
+ preserved them, but it never decodes media and never crosses components -- a
6
+ release whose bundles are each individually byte-perfect and whose RGB, camera and
7
+ annotations no longer line up would pass it. ``validate.py`` does cross
8
+ components, but per view, and it reads ``frames.jsonl`` rather than the media.
9
+
10
+ So this opens the finished release the way a consumer would, through
11
+ ``Registry.resolve`` and ``BundleReader``, and checks the joins:
12
+
13
+ frames the RGB's real frame count (ffprobe, demux only -- ``nb_frames`` is
14
+ absent in Matroska) equals the metainfo ``num_frames`` and the length
15
+ of every field's ``T`` axis
16
+ camera the directory the view lives in, its ``camera_id``, its ``camera``
17
+ block, the intrinsic component's ``schema_id`` and the registry's
18
+ distortion rule all name the same camera
19
+ presence a component declaring ``available: false`` leaves no file behind, and
20
+ every declared one opens
21
+ recording across all nine cameras: one ``sequence_id``, one frame count, and one
22
+ shared ``sync_id`` per frame index -- the 9 views are the same
23
+ recording, so annotation row *i* in the ego view and in an exo view are
24
+ the same moment. That is the association the release claims, and it is
25
+ a property of the sequence that no per-view check can state
26
+
27
+ What it does not do: it never decodes pixels, compares an image to anything, or
28
+ forms an opinion about whether a mask looks right. CONTRACT 6.5 keeps that --
29
+ human visual acceptance -- separate from this, and this tool is on the packaging
30
+ side of that line.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import json
37
+ import subprocess
38
+ import sys
39
+ from pathlib import Path
40
+
41
+ import torch
42
+
43
+ from warehouse import BundleReader, Registry
44
+
45
+
46
+ def release_root() -> Path:
47
+ """``<dataset>/shared-v1.1``, from this file's own location."""
48
+ return Path(__file__).resolve().parents[2]
49
+
50
+
51
+ def wildcard(segment: str) -> bool:
52
+ return "<" in segment and ">" in segment
53
+
54
+
55
+ def registered_entry(registry, bundle_rel: str, keys: list) -> bool:
56
+ """Is ``bundle_rel`` + ``keys`` an entry the registry declares?
57
+
58
+ ``Registry.resolve`` answers the migrator's question -- given a *v1.0* ref,
59
+ where did those bytes go. A consumer asks the other direction: the v1.1
60
+ metainfo names a bundle and a key path, and that pair has to be a registered
61
+ entry. Same templates, matched from the target side.
62
+ """
63
+ ref = Path(bundle_rel).parts
64
+ for bundle in registry.bundles.values():
65
+ template = Path(bundle["path"]).parts
66
+ if len(ref) != len(template) or ref[-1] != template[-1]:
67
+ continue
68
+ if not all(wildcard(w) or w == g for w, g in zip(template[:-1], ref[:-1])):
69
+ continue
70
+ for name in bundle["entries"]:
71
+ wanted = name.split("/")
72
+ if len(wanted) == len(keys) and all(
73
+ wildcard(w) or w == k for w, k in zip(wanted, keys)
74
+ ):
75
+ return True
76
+ return False
77
+
78
+
79
+ def packet_count(path: Path) -> int:
80
+ """Frames in an encoded video, by demux -- not by decoding."""
81
+ out = subprocess.run(
82
+ ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets",
83
+ "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", str(path)],
84
+ capture_output=True, text=True, check=True,
85
+ ).stdout.strip()
86
+ return int(out)
87
+
88
+
89
+ def view_dirs(root: Path, sequence: str) -> list[Path]:
90
+ sequence_dir = root / "data" / sequence
91
+ if not sequence_dir.is_dir():
92
+ raise SystemExit(f"no such sequence in the release: {sequence}")
93
+ return sorted((p for p in sequence_dir.iterdir() if p.is_dir()),
94
+ key=lambda p: (len(p.name), p.name))
95
+
96
+
97
+ def read_view(registry, reader, view: Path) -> dict:
98
+ """Open every component of one view; return what the reader found."""
99
+ meta = json.loads((view / "metainfo.json").read_text(encoding="utf-8"))
100
+ where = f"{view.parent.name}/{view.name}"
101
+ record = {"view": where, "camera_id": meta.get("camera_id"),
102
+ "view_type": meta.get("view_type"), "num_frames": meta.get("num_frames"),
103
+ "fields": [], "media": [], "absent": [], "problems": []}
104
+ problem = record["problems"].append
105
+
106
+ #: the view's own directory name and its declared camera must agree; the whole
107
+ #: release is laid out as <sequence>/<camera_id>/, so a mismatch would mean the
108
+ #: calibration and the pixels come from different cameras
109
+ if meta.get("camera_id") != view.name:
110
+ problem(f"directory {view.name} but camera_id {meta.get('camera_id')!r}")
111
+
112
+ for name, component in meta["components"].items():
113
+ ref = component.get("data_ref")
114
+ if not component.get("available", True):
115
+ #: an omitted component must not leave a file claiming otherwise
116
+ if ref and (view / ref).exists():
117
+ problem(f"{name}: available=false but {ref} exists")
118
+ record["absent"].append(name)
119
+ continue
120
+ if not ref:
121
+ problem(f"{name}: available but declares no data_ref")
122
+ continue
123
+ #: the v1.1 metainfo names its own bundle entry, so the consumer path reads
124
+ #: what the release declares rather than re-deriving it. ``data_key`` is
125
+ #: what marks a bundled numeric field (validate.py rebuilds on the same
126
+ #: predicate); a component carrying only a ``data_ref`` is media or JSON.
127
+ leaves = []
128
+ if "data_key" in component:
129
+ leaves.append((name, component["data_ref"],
130
+ component["data_key"], component["valid_key"],
131
+ list(component.get("axes") or [])))
132
+ if "distortion_key" in component:
133
+ #: ARCTIC's distortion rides on the camera bundle's own entry, which no
134
+ #: component's data_key names -- read it by its declared keys
135
+ leaves.append((f"{name}.distortion", component["distortion_ref"],
136
+ component["distortion_key"], component["distortion_valid_key"],
137
+ list(component.get("distortion_axes") or [])))
138
+ if not leaves:
139
+ path = view / ref
140
+ if not path.is_file():
141
+ problem(f"{name}: preserved file {ref} is missing")
142
+ continue
143
+ record["media"].append({"component": name, "ref": ref,
144
+ "bytes": path.stat().st_size})
145
+ continue
146
+ for owner, bundle, data_key, valid_key, axes in leaves:
147
+ try:
148
+ data = reader.get(view, bundle, data_key)
149
+ valid = reader.get(view, bundle, valid_key)
150
+ except (KeyError, TypeError, FileNotFoundError) as error:
151
+ problem(f"{owner}: reader could not open {bundle}: {error}")
152
+ continue
153
+ if not isinstance(data, torch.Tensor) or valid.dtype != torch.bool:
154
+ problem(f"{owner}: {bundle} does not hold (Tensor, bool Tensor)")
155
+ continue
156
+ frames = data.shape[axes.index("T")] if "T" in axes else None
157
+ if frames is not None and frames != meta["num_frames"]:
158
+ problem(f"{owner}: {frames} frames on its T axis, "
159
+ f"metainfo declares {meta['num_frames']}")
160
+ if valid.shape != tuple(data.shape[: valid.ndim]):
161
+ problem(f"{owner}: valid {list(valid.shape)} is not a prefix of "
162
+ f"data {list(data.shape)}")
163
+ if not registered_entry(registry, bundle, data_key[:-1]):
164
+ problem(f"{owner}: {bundle}:{'/'.join(data_key[:-1])} is not a "
165
+ f"registered bundle entry")
166
+ record["fields"].append({
167
+ "component": owner, "entry": f"{bundle}:{'/'.join(data_key)}",
168
+ "dtype": str(data.dtype), "shape": list(data.shape),
169
+ "T": frames, "valid_true": int(valid.sum()),
170
+ "valid_false": int((~valid).sum()),
171
+ })
172
+
173
+ #: the RGB is the one component whose frame count the metainfo cannot vouch for:
174
+ #: num_frames is a claim about the file, so read the file
175
+ rgb = meta["components"].get("rgb") or {}
176
+ if rgb.get("available", True) and rgb.get("data_ref"):
177
+ path = view / rgb["data_ref"]
178
+ if path.is_file():
179
+ frames = packet_count(path)
180
+ record["rgb_frames"] = frames
181
+ if frames != meta["num_frames"]:
182
+ problem(f"rgb: {frames} packets, metainfo declares {meta['num_frames']}")
183
+ return record
184
+
185
+
186
+ def check_recording(views: list[dict], metas: dict[str, dict]) -> list[str]:
187
+ """The sequence-level claim: all cameras are the same recording."""
188
+ problems = []
189
+ sequences = {m.get("sequence_id") for m in metas.values()}
190
+ if len(sequences) != 1:
191
+ problems.append(f"views disagree on sequence_id: {sorted(sequences)}")
192
+ counts = {v["num_frames"] for v in views}
193
+ if len(counts) != 1:
194
+ problems.append(f"views disagree on num_frames: {sorted(counts)}")
195
+ #: one sync table per camera, but the frame at index i must be the same moment in
196
+ #: all of them -- otherwise an annotation row read from the ego view describes a
197
+ #: different instant than the RGB of an exo view
198
+ per_view = {}
199
+ for name, meta in metas.items():
200
+ stream = meta["components"].get("rgb") or {}
201
+ path = None
202
+ if stream.get("available", True) and stream.get("data_ref"):
203
+ path = stream["data_ref"]
204
+ rows = meta.get("_sync_rows")
205
+ if rows is None:
206
+ continue
207
+ per_view[name] = [row.get("sync_id") for row in rows]
208
+ if per_view:
209
+ lengths = {len(v) for v in per_view.values()}
210
+ if len(lengths) != 1:
211
+ problems.append(f"sync tables differ in length: {sorted(lengths)}")
212
+ else:
213
+ reference = None
214
+ for name in sorted(per_view):
215
+ if reference is None:
216
+ reference = (name, per_view[name])
217
+ continue
218
+ if per_view[name] != reference[1]:
219
+ differ = [i for i, (a, b) in
220
+ enumerate(zip(reference[1], per_view[name])) if a != b]
221
+ problems.append(
222
+ f"sync_id differs between {reference[0]} and {name} at "
223
+ f"{len(differ)} frame(s), first {differ[0]}")
224
+ return problems
225
+
226
+
227
+ def main(argv=None):
228
+ root = release_root()
229
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
230
+ parser.add_argument("sequence", help="e.g. s01_box_grab_01")
231
+ parser.add_argument("--root", type=Path, default=root)
232
+ parser.add_argument("--schema", type=Path, default=root / "doc" / "schema.json",
233
+ help="v1.1 schema.json (default <release>/doc/schema.json)")
234
+ parser.add_argument("--report", type=Path,
235
+ help="write the full record here as JSON")
236
+ parser.add_argument("--quiet", action="store_true")
237
+ args = parser.parse_args(argv)
238
+
239
+ registry = Registry.load(args.schema)
240
+ reader = BundleReader()
241
+ views = view_dirs(args.root, args.sequence)
242
+
243
+ metas, records = {}, []
244
+ for view in views:
245
+ meta = json.loads((view / "metainfo.json").read_text(encoding="utf-8"))
246
+ sync = view / "camera" / "frames.jsonl"
247
+ meta["_sync_rows"] = ([json.loads(line) for line in
248
+ sync.read_text(encoding="utf-8").splitlines() if line.strip()]
249
+ if sync.is_file() else [])
250
+ metas[view.name] = meta
251
+ records.append(read_view(registry, reader, view))
252
+
253
+ problems = check_recording(records, metas)
254
+ per_view_problems = [(r["view"], p) for r in records for p in r["problems"]]
255
+
256
+ if not args.quiet:
257
+ print(f"{args.sequence}: {len(records)} view(s)")
258
+ for record in records:
259
+ calib = metas[record["view"].split("/")[1]]["camera"]
260
+ print(f" {record['view']:<28} {record['view_type']:<4} "
261
+ f"cam={record['camera_id']} {calib.get('model'):<9} "
262
+ f"frames={record['num_frames']} fields={len(record['fields'])} "
263
+ f"media={len(record['media'])} absent={len(record['absent'])}")
264
+ for field in record["fields"]:
265
+ print(f" {field['component']:<26} {field['dtype']:<14} "
266
+ f"{str(field['shape']):<20} invalid={field['valid_false']}")
267
+
268
+ for view, problem in per_view_problems:
269
+ print(f"FAIL {view}: {problem}", file=sys.stderr)
270
+ for problem in problems:
271
+ print(f"FAIL {args.sequence}: {problem}", file=sys.stderr)
272
+
273
+ report = {
274
+ "sequence": args.sequence,
275
+ "views": records,
276
+ "sequence_problems": problems,
277
+ "view_problems": {record["view"]: record["problems"] for record in records},
278
+ "accepted": not problems and not per_view_problems,
279
+ "scope": "repackaging equivalent by reading the release; not visual acceptance",
280
+ }
281
+ if args.report:
282
+ args.report.parent.mkdir(parents=True, exist_ok=True)
283
+ args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2),
284
+ encoding="utf-8")
285
+ print(f"wrote {args.report}")
286
+ print("ACCEPTANCE_PASS" if report["accepted"] else "ACCEPTANCE_FAIL")
287
+ return 0 if report["accepted"] else 1
288
+
289
+
290
+ if __name__ == "__main__":
291
+ raise SystemExit(main())
ARCTIC/shared-v1.1/script/arctic_v1_1/render.py ADDED
@@ -0,0 +1,965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Render sampled ARCTIC shared-v1.1 views to self-contained HTML review pages.
3
+
4
+ CONTRACT 6.5 keeps "the repackaging preserved the bytes" apart from "a human looked
5
+ at it". The published H2O and dex-ycb sets carry sampled per-view pages for the
6
+ second half; ARCTIC shipped without them, and ``README.md`` in this directory records
7
+ that omission as a deliberate scope decision rather than a missing artifact. This
8
+ closes it, written against the v1.1 layout rather than ported from either published
9
+ renderer:
10
+
11
+ * every value is read through the released reader -- ``Registry``/``BundleReader``
12
+ plus ``arctic_common.check_view``, the calls ``validate.py`` and
13
+ ``read_sequence.py`` already make -- so a page shows what the release declares
14
+ instead of a re-derived copy of it. Media, JSONL and mesh assets are read as the
15
+ preserved files they are, on ``read_sequence.py``'s own split (``data_key`` marks a
16
+ bundled numeric field).
17
+ * the published renderers import ``snapshot``/``picture``/``mesh_preview`` from
18
+ ``render_hoi4d_validation`` in their own v1.0 snapshot. ARCTIC's v1.0 tree never
19
+ held that module, so those helpers and the ffmpeg decode recipe are carried here.
20
+ * ARCTIC publishes no 2D keypoints, no depth and no segmentation, so the published
21
+ ``projection_qc`` -- saved xyz against saved uv -- has no second series to compare
22
+ with. What can be projected is the released camera-frame geometry: object
23
+ keypoints, object and part poses, and the MANO root translation.
24
+ * no MANO mesh or skeleton is drawn. The release carries the 61 parameters; turning
25
+ them into joints needs the external MANO model asset and ``smplx``, which are in
26
+ neither this release nor this renderer's environment. ARCTIC's own v1.0 pages *did*
27
+ draw white MANO-derived joints -- ``doc/history-v1.0/validation/``, whose full-frame
28
+ videos ship with this release -- because that renderer required exactly that external
29
+ stack. The v1.1 pages say so where a reader would look for the hand, and show the
30
+ hand's released supervision as the projected root translation (schema
31
+ ``layout.translation``) plus per-frame numbers.
32
+
33
+ Every page is one self-contained file (PNG previews as base64 data URIs, no script,
34
+ no external reference), and the sampled frames are the only pixels decoded.
35
+
36
+ Run -- the ordering matters, see 收尾验收顺序 in README.md:
37
+ python shared-v1.1/script/arctic_v1_1/render.py --reference-sequences 6
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import argparse
43
+ import base64
44
+ import html
45
+ import io
46
+ import json
47
+ import multiprocessing
48
+ import os
49
+ import random
50
+ import subprocess
51
+ import sys
52
+ import time
53
+ from concurrent.futures import ProcessPoolExecutor
54
+ from pathlib import Path
55
+
56
+ #: set before the sibling imports below, not inside main(): the first ``import
57
+ #: arctic_common`` is what writes a __pycache__ into the release tree, and it happens
58
+ #: while this module body runs. The release must ship no bytecode cache, so the switch
59
+ #: has to be flipped before that line -- and inherited by the decoder children, which
60
+ #: re-import this module (os.environ, set in main, covers those)
61
+ sys.dont_write_bytecode = True
62
+
63
+ import cv2
64
+ import numpy as np
65
+ import torch
66
+ from PIL import Image, ImageDraw
67
+
68
+ from arctic_common import BundleReader, check_view, load, save
69
+ from warehouse import Registry
70
+
71
+ #: the released checker's own report shape, minus the module-level registry it
72
+ #: binds: this renderer is pointed at a root, so it loads that root's registry
73
+ PROJECTION_SCOPE = ("saved camera-frame xyz through the view's own intrinsic and "
74
+ "distortion; not a media pixel comparison")
75
+ REPORT_SCOPE = ("v1.1 registry, keys, shapes, validity and timeline; not a media "
76
+ "pixel comparison")
77
+ DECODE_SCOPE = ("ffmpeg select= demux filter over the preserved MKV; only the frames "
78
+ "listed in selected_frames are decoded, each checked against "
79
+ "height*width*3 bytes")
80
+
81
+ #: Preview colours are ARCTIC's own vocabulary rather than a new one. The v1.0 review
82
+ #: renderer drew 顶盖 magenta (230,80,230), 底座 green (100,240,90), 左手 cyan
83
+ #: (0,235,255) and 右手 orange (255,135,20) (v1_0_snapshot/script/internal/
84
+ #: render_full_sequence_review.py), and its pages state the same in words -- 「顶盖紫、
85
+ #: 底座绿,左手青、右手橙」 (doc/history-v1.0/validation/objects/*/index.html). Those
86
+ #: pages ship with this release, so a reviewer may read the two side by side; reusing
87
+ #: the vocabulary is what keeps that side-by-side reading correct.
88
+ #: Parts are coloured by the component's own name (``object_<id>_top_pose`` vs
89
+ #: ``_bottom_pose``), which also sidesteps the index swap v1.0 had to document and fix
90
+ #: (its ``parts`` 0/1 encoding); keypoints by the part their released ``keypoint_names``
91
+ #: declares, where v1.0 drew all 32 white -- the release's own names make the finer
92
+ #: split possible, so the difference is stated on the page.
93
+ PART_COLORS = {"top": "#e650e6", "bottom": "#64f05a"}
94
+ HAND_COLORS = {"left": "#00ebff", "right": "#ff8714"}
95
+ AXIS_COLORS = ("#ff2020", "#20c020", "#2040ff")
96
+
97
+ #: A frame whose object geometry lands mostly outside the picture is marked rather than
98
+ #: drawn as an ordinary, nearly empty panel. The case is real and is not a defect in the
99
+ #: projection: at s05_microwave_use_01/0 frame 195 one of 32 keypoints projects inside,
100
+ #: because the ego camera rides the head and the object sits just above the field of view
101
+ #: -- the same frame's eight exo views hold all 32, and the camera-frame geometry is the
102
+ #: one the release publishes. A reviewer reading a single dot with no warning has no way
103
+ #: to tell that from a broken projection, so the ratio is stated on the page and, for
104
+ #: every annotated frame and not only the flagged ones, recorded in the view report.
105
+ OUT_OF_FRAME_RATIO = 0.5
106
+ OUT_OF_FRAME_RULE = ("a sampled frame is marked 物体大部分落在画外 when fewer than half of "
107
+ "its valid object keypoints land inside the image; every annotated "
108
+ "frame's valid_points / inside_points / inside_ratio is recorded in "
109
+ "projection.frames either way")
110
+
111
+
112
+ # -- helpers carried from the published v1.0 renderer -----------------------
113
+
114
+
115
+ def snapshot(path: Path, indices, width: int, height: int):
116
+ """Decode exactly the requested frames of a preserved video.
117
+
118
+ Same recipe as the published renderer (``HAND_WAREHOUSE_FFMPEG_THREADS``, one
119
+ decoder thread by default), with ``select=`` so a 2800x2000 stream is not read
120
+ end to end for a handful of stills. The byte count is checked rather than
121
+ trusted: a short read would silently misalign every frame after it.
122
+ """
123
+ order = sorted(indices)
124
+ select = "+".join(f"eq(n\\,{i})" for i in order)
125
+ threads = os.environ.get("HAND_WAREHOUSE_FFMPEG_THREADS", "1")
126
+ argv = ["ffmpeg", "-v", "error", "-nostdin", "-filter_threads", threads,
127
+ "-threads", threads, "-noautorotate", "-i", str(path), "-map", "0:v:0",
128
+ "-vf", f"select={select}", "-vsync", "0", "-frames:v", str(len(order)),
129
+ "-threads", threads, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
130
+ raw = subprocess.run(argv, capture_output=True, check=True).stdout
131
+ expected = len(order) * height * width * 3
132
+ if len(raw) != expected:
133
+ raise ValueError(f"{path}: decoded {len(raw)} bytes, expected {expected}")
134
+ frames = np.frombuffer(raw, dtype=np.uint8).reshape(len(order), height, width, 3)
135
+ return {index: frames[position].copy() for position, index in enumerate(order)}
136
+
137
+
138
+ def picture(image: Image.Image) -> str:
139
+ """A preview as a data URI. Released tensors and videos are never resized."""
140
+ image = image.copy()
141
+ image.thumbnail((800, 450))
142
+ output = io.BytesIO()
143
+ image.save(output, format="PNG")
144
+ return ('<img loading="lazy" src="data:image/png;base64,'
145
+ + base64.b64encode(output.getvalue()).decode() + '">')
146
+
147
+
148
+ def mesh_preview(path: Path) -> str:
149
+ """Project a source mesh asset; bound drawing cost without favouring early faces.
150
+
151
+ The published helper, unchanged in behaviour: hand-rolled OBJ reader (no trimesh
152
+ in either environment), fixed orthonormal isometric basis -- geometry only, never
153
+ an inferred camera pose -- and a deterministic 5000-face cap.
154
+ """
155
+ vertices, faces, referenced = [], [], set()
156
+ rng = random.Random(0)
157
+ face_count = 0
158
+ with path.open(errors="replace") as stream:
159
+ for line in stream:
160
+ if line.startswith("v "):
161
+ vertices.append([float(v) for v in line.split()[1:4]])
162
+ elif line.startswith("f "):
163
+ face = []
164
+ for token in line.split()[1:]:
165
+ index = int(token.split("/")[0])
166
+ face.append(index - 1 if index > 0 else len(vertices) + index)
167
+ if len(face) < 3:
168
+ continue
169
+ referenced.update(face)
170
+ face_count += 1
171
+ if len(faces) < 5000:
172
+ faces.append(face)
173
+ else:
174
+ pick = rng.randrange(face_count)
175
+ if pick < len(faces):
176
+ faces[pick] = face
177
+ if not vertices or not faces:
178
+ return "OBJ 未提供可绘制的顶点/面"
179
+ if min(referenced) < 0 or max(referenced) >= len(vertices):
180
+ raise ValueError(f"invalid OBJ face index: {path}")
181
+ xyz = np.asarray(vertices, dtype=np.float64)
182
+ if not np.isfinite(xyz).all():
183
+ raise ValueError(f"nonfinite OBJ vertex: {path}")
184
+ projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2),
185
+ (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6)))
186
+ used = projected[np.fromiter(referenced, dtype=np.int64)]
187
+ lo, hi = used.min(axis=0), used.max(axis=0)
188
+ extent = (hi - lo).max()
189
+ if extent <= 0:
190
+ return "OBJ 所有面投影到同一点"
191
+ projected = (projected - (lo + hi) / 2) * (380 / extent) + 215
192
+ image = Image.new("RGB", (430, 430), "white")
193
+ draw = ImageDraw.Draw(image)
194
+ for face in faces:
195
+ polygon = [tuple(projected[i]) for i in face]
196
+ draw.line(polygon + [polygon[0]], fill="#205caa", width=1)
197
+ return picture(image)
198
+
199
+
200
+ # -- projection -------------------------------------------------------------
201
+
202
+
203
+ def project(xyz, intrinsic, distortion, width: int, height: int):
204
+ """Camera-frame points -> pixels, through this view's own calibration.
205
+
206
+ ARCTIC's rational8 distortion vector is declared k1,k2,p1,p2,k3,k4,k5,k6
207
+ (schema ``camera.rational8.distortion``), which is exactly the coefficient order
208
+ ``cv2.projectPoints`` expects; a pinhole view carries no separate vector
209
+ (``reference_rules.camera_distortion.models_without_separate_distortion``) and is
210
+ projected with zero distortion. Points behind the camera are not projected.
211
+ """
212
+ points = np.asarray(xyz, dtype=np.float64).reshape(-1, 3)
213
+ coeffs = (np.zeros(5) if distortion is None
214
+ else np.asarray(distortion, dtype=np.float64))
215
+ uv, _ = cv2.projectPoints(points.reshape(-1, 1, 3), np.zeros(3), np.zeros(3),
216
+ np.asarray(intrinsic, dtype=np.float64), coeffs)
217
+ uv = uv.reshape(-1, 2)
218
+ front = points[:, 2] > 1e-6
219
+ finite = np.isfinite(uv).all(axis=1)
220
+ inside = front & finite & (uv[:, 0] >= 0) & (uv[:, 0] < width) & \
221
+ (uv[:, 1] >= 0) & (uv[:, 1] < height)
222
+ return uv, front & finite, inside
223
+
224
+
225
+ def dot(draw: ImageDraw.ImageDraw, x: float, y: float, color: str, radius: int):
226
+ draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=color)
227
+
228
+
229
+ def draw_axes(draw, transform, intrinsic, distortion, width, height, radius):
230
+ """Root/part pose axes: three 5 cm segments in the camera frame, T then R.
231
+
232
+ The segment is drawn at its true projected length -- the caption says 5 cm, so a
233
+ scaled-up line would be a picture of something the release does not contain. An
234
+ axis whose far end leaves the frame is skipped rather than clipped, and the count
235
+ of drawn axes comes back so a frame with none says so instead of showing a bare dot.
236
+ """
237
+ transform = np.asarray(transform, dtype=np.float64)
238
+ origin = transform[:3, 3]
239
+ basis = transform[:3, :3]
240
+ points = [origin] + [origin + basis[:, axis] * 0.05 for axis in range(3)]
241
+ uv, front, inside = project(points, intrinsic, distortion, width, height)
242
+ if not front.all():
243
+ return 0
244
+ base, drawn = uv[0], 0
245
+ dot(draw, base[0], base[1], "#ffffff", max(2, radius // 2))
246
+ for axis in range(3):
247
+ if not inside[axis + 1]:
248
+ continue
249
+ draw.line((base[0], base[1], uv[axis + 1][0], uv[axis + 1][1]),
250
+ fill=AXIS_COLORS[axis], width=max(2, radius // 3))
251
+ drawn += 1
252
+ return drawn
253
+
254
+
255
+ # -- frame selection --------------------------------------------------------
256
+
257
+
258
+ def select_frames(n: int, valids, media_valid):
259
+ """The published sampling policy, driven by the release's own validity.
260
+
261
+ Quarter points plus both ends, plus the first frame each series is valid and the
262
+ first it is not -- an invalid row is exactly what a reviewer wants to see once.
263
+ Truncated to twelve and the last frame is always kept.
264
+ """
265
+ picks = {0, n // 4, n // 2, 3 * n // 4, n - 1}
266
+ for valid in valids:
267
+ if valid is None:
268
+ continue
269
+ flags = np.asarray(valid, dtype=bool).reshape(n, -1).any(axis=1)
270
+ for wanted, present in ((True, np.flatnonzero(flags)), (False, np.flatnonzero(~flags))):
271
+ if len(present):
272
+ picks.add(int(present[0]))
273
+ if media_valid is not None:
274
+ flags = np.asarray(media_valid, dtype=bool)
275
+ for wanted, present in ((True, np.flatnonzero(flags)), (False, np.flatnonzero(~flags))):
276
+ if len(present):
277
+ picks.add(int(present[0]))
278
+ return sorted(set(sorted(picks)[:12]) | {n - 1})
279
+
280
+
281
+ # -- per-view report --------------------------------------------------------
282
+
283
+
284
+ def view_report(view: Path, meta: dict, registry, reader, fields: list, consumed: set,
285
+ notes: list, selected: list, projection: dict) -> dict:
286
+ """The published report shape, composed from the released checker's evidence.
287
+
288
+ ``check_view`` returns one record per bundled field (dtype, shape, valid_true,
289
+ valid_false) and the paths it read; ``numeric_components`` and ``bundle_files``
290
+ restate those, never a recount. ARCTIC has no ``validate_view`` of its own --
291
+ its reader is registry-driven and the checks live in ``arctic_common`` -- so this
292
+ is the analogue, and ``scope`` says what it does and does not cover.
293
+
294
+ The distortion vector comes back from ``check_distortion`` in its own shape: it
295
+ names the schema and the valid count but carries no dtype or false count, since
296
+ its validity is the intrinsic's own (``valid_equals_intrinsic_valid``). Both are
297
+ filled from the release rather than assumed -- the dtype from the registry entry
298
+ the record names, the total by reading the tensor the checker read.
299
+ """
300
+ numeric = {}
301
+ for record in fields:
302
+ owner = record["owner"]
303
+ valid_total = record.get("valid_total")
304
+ if valid_total is None:
305
+ valid_total = record["valid_true"] + record.get("valid_false", 0)
306
+ if "valid_false" not in record:
307
+ component = meta["components"][owner.rsplit(".distortion", 1)[0]]
308
+ valid = reader.get(view, component["distortion_valid_ref"],
309
+ component["distortion_valid_key"])
310
+ valid_total = int(valid.numel())
311
+ dtype = record.get("dtype")
312
+ if dtype is None:
313
+ #: check_distortion names the schema but not the dtype; the registry entry it
314
+ #: names spells it bare ("float32"). Carry the prefix the checker's own
315
+ #: records use, so one report does not mix str(tensor.dtype) with registry
316
+ #: vocabulary -- the registry's set is float32/float64/int64/uint16/uint8/bool,
317
+ #: each of which str() renders as "torch.<name>".
318
+ dtype = "torch." + registry.components[record["schema_id"]]["dtype"]
319
+ numeric[owner] = {
320
+ "shape": record["shape"],
321
+ "dtype": dtype,
322
+ "valid_true": record["valid_true"],
323
+ "valid_total": valid_total,
324
+ "shares_intrinsic_validity": record.get("shares_intrinsic_validity"),
325
+ }
326
+ bundles = sorted({record["entry"].split(":")[0] for record in fields})
327
+ media = []
328
+ for name, component in meta["components"].items():
329
+ if not component.get("available", True) or component.get("data_key"):
330
+ continue
331
+ media.append({"component": name, "ref": component["data_ref"],
332
+ "pixels_decoded": len(selected) if name == "rgb" else 0})
333
+ return {
334
+ "view": f"{view.parent.name}/{view.name}",
335
+ "sequence_id": meta["sequence_id"],
336
+ "camera_id": meta["camera_id"],
337
+ "view_type": meta["view_type"],
338
+ "split": meta["split"],
339
+ "num_frames": meta["num_frames"],
340
+ "camera": {"model": meta["camera"]["model"],
341
+ "schema_id": meta["camera"]["schema_id"],
342
+ "image_size": meta["camera"]["image_size"]},
343
+ "numeric_components": numeric,
344
+ "bundle_files": len(bundles),
345
+ "bundles": bundles,
346
+ "media": media,
347
+ "consumed_files": sorted(consumed),
348
+ "registry_gaps": notes,
349
+ "selected_frames": selected,
350
+ "decode_scope": DECODE_SCOPE,
351
+ "projection": projection,
352
+ "omitted_components": meta.get("omitted_components"),
353
+ "source_hand_object_gt_available": meta.get("source_hand_object_gt_available"),
354
+ "scope": REPORT_SCOPE,
355
+ }
356
+
357
+
358
+ def colour_legend() -> str:
359
+ """The colour vocabulary and what is deliberately not drawn, in one place.
360
+
361
+ Both the per-view page and ``index.html`` carry it: a reviewer lands on the index
362
+ first, so the vocabulary belongs there too, and the per-view captions then point
363
+ back at it instead of repeating a paragraph of explanation under every panel.
364
+ """
365
+ def swatch(color: str, label: str) -> str:
366
+ return ('<span class="swatch" style="background:' + color
367
+ + '">&nbsp;&nbsp;&nbsp;</span> ' + html.escape(label))
368
+
369
+ return ('<p class="legend">配色沿用 ARCTIC v1.0 复核页自己的约定'
370
+ "(「顶盖紫、底座绿,左手青、右手橙」),便于两套页面并排读:<br>"
371
+ + " · ".join([
372
+ swatch(PART_COLORS["top"], "物体 top"),
373
+ swatch(PART_COLORS["bottom"], "物体 bottom"),
374
+ swatch(HAND_COLORS["left"], "左手"),
375
+ swatch(HAND_COLORS["right"], "右手"),
376
+ swatch(AXIS_COLORS[0], "位姿轴 x 红 /")
377
+ + " " + swatch(AXIS_COLORS[1], "y 绿 /") + " " + swatch(AXIS_COLORS[2], "z 蓝")])
378
+ + "<br>部件的 top/bottom 取自组件名(<code>object_&lt;id&gt;_top_pose</code> 等),"
379
+ "关键点取自发布的 <code>keypoint_names</code>;v1.0 页面把 32 个物体关键点"
380
+ "画成同一种白色,并用索引区分顶盖/底座。投影不做遮挡剔除,也不是分割真值。</p>"
381
+ '<p class="legend"><b>手部没有骨架</b>:release 的 <code>mano</code> 只有 61 个参数,'
382
+ "要还原成关节需要发布外的 MANO 模型资产与 <code>smplx</code>——本发布与本渲染"
383
+ "环境都没有。ARCTIC v1.0 页面上那层白色 MANO 派生关节点,正是靠那套外部依赖"
384
+ "画出来的。页面因此只画 schema <code>layout.translation</code> 声明的根平移"
385
+ "(青色/橙色点),手部监督的其余部分以逐帧数值呈现。</p>")
386
+
387
+
388
+ # -- one view ---------------------------------------------------------------
389
+
390
+
391
+ def unmarked(values) -> str:
392
+ """Why a frame carries no geometry, read off the release's own evidence.
393
+
394
+ ARCTIC marks a frame it does not annotate with ``valid=False`` and leaves the
395
+ tensors in place; the frames checked here hold NaN there -- the last frame of a
396
+ sequence, for instance, which v1.0's own pages also record as 无源标注. Naming
397
+ that is the point: "the source does not annotate this frame" and "the geometry
398
+ projected outside the image" are different findings, and a page that omits both
399
+ silently reports neither.
400
+ """
401
+ array = np.asarray(values)
402
+ if array.dtype.kind == "f" and not np.isfinite(array).all():
403
+ return "该帧 valid 为假(源未标注,该帧数值非有限值,故不投影)"
404
+ return "该帧 valid 为假(源未标注,故不投影)"
405
+
406
+
407
+ def render_one(view: Path, destination: Path, root: Path) -> dict:
408
+ registry = Registry.load(root / "doc/schema.json")
409
+ meta = load(view / "metainfo.json")
410
+ n = meta["num_frames"]
411
+ width, height = meta["camera"]["image_size"]
412
+ components = meta["components"]
413
+ reader = BundleReader()
414
+ consumed, fields, notes = check_view(view, meta, registry, reader)
415
+
416
+ bundled = {name: reader.field(view, component)
417
+ for name, component in components.items()
418
+ if component.get("available", True) and "data_key" in component}
419
+ intrinsic_component = components.get("intrinsic") or {}
420
+ distortion = None
421
+ if intrinsic_component.get("available", True) and intrinsic_component.get("distortion_key"):
422
+ distortion = reader.get(view, intrinsic_component["distortion_ref"],
423
+ intrinsic_component["distortion_key"])
424
+ media_valid = None
425
+ rgb_component = components.get("rgb")
426
+ if rgb_component and rgb_component.get("available", True) and rgb_component.get("valid_ref"):
427
+ media_valid = torch.load(view / rgb_component["valid_ref"], map_location="cpu",
428
+ weights_only=True).numpy()
429
+
430
+ selected = select_frames(n, [valid.numpy() for _, valid in bundled.values()], media_valid)
431
+ sync_rows = []
432
+ sync_file = view / meta["sampling"]["frames_ref"]
433
+ if sync_file.is_file():
434
+ sync_rows = [json.loads(line) for line in
435
+ sync_file.read_text(encoding="utf-8").splitlines() if line.strip()]
436
+
437
+ frames = {}
438
+ if rgb_component and rgb_component.get("available", True):
439
+ frames = snapshot(view / rgb_component["data_ref"], selected, width, height)
440
+
441
+ #: a view whose calibration the source does not establish declares model
442
+ #: "unknown" and publishes no intrinsic (arctic_common.UNKNOWN_CAMERA_MODEL); the
443
+ #: page then shows the RGB and says why nothing is projected onto it
444
+ calibrated = (meta["camera"]["model"] != "unknown"
445
+ and "intrinsic" in components and components["intrinsic"].get("available", True))
446
+ radius = max(3, round(width * 0.004))
447
+
448
+ projection = {"model": meta["camera"]["model"], "calibrated": calibrated,
449
+ "points": 0, "inside": 0, "off_image": 0, "frames": {},
450
+ "coordinate_frame": "camera", "scope": PROJECTION_SCOPE,
451
+ "out_of_frame_rule": OUT_OF_FRAME_RULE,
452
+ "note": "ARCTIC publishes no 2D keypoints and no uv series, so the "
453
+ "published projection_qc (saved xyz against saved uv) has no "
454
+ "second series here; this counts what the release's own "
455
+ "camera-frame geometry projects to."}
456
+ panels_by_frame, details_by_frame = {}, {}
457
+ totals = {"keypoint_panels": 0, "axis_panels": 0, "mano_panels": 0,
458
+ "note_panels": 0, "frames_noted": 0}
459
+ #: frames whose object geometry mostly left the picture, in frame order
460
+ out_of_frame = []
461
+ for index in selected:
462
+ panels = []
463
+ #: What was not drawn, and why. A page that silently omits an overlay reads as
464
+ #: "nothing to see here" when the truth is usually "the source does not
465
+ #: annotate this frame" or "it projects outside the image" -- different findings,
466
+ #: and the difference is the whole point of a review page.
467
+ skipped = []
468
+ #: Transform pairs drawn once because the published tensors are equal bit for
469
+ #: bit: a closed box publishes root == top == bottom, and three identical
470
+ #: pictures imply three findings where the release holds one.
471
+ folded = []
472
+ image = Image.fromarray(frames[index]) if index in frames else None
473
+ if image is not None:
474
+ panels.append(("原生 RGB(MKV 解出的第 " + str(index) + " 帧,未重编码)", picture(image)))
475
+
476
+ if not calibrated:
477
+ geometry = None
478
+ #: not repeated per frame: the reason is the whole view's, and the header
479
+ #: states it once. A view-level fact repeated on every frame reads as five
480
+ #: findings instead of one.
481
+ else:
482
+ key = intrinsic_component["data_key"]
483
+ valid_key = intrinsic_component.get("valid_key")
484
+ k_valid = True
485
+ if valid_key:
486
+ k_valid = bool(reader.get(view, intrinsic_component["valid_ref"], valid_key)[index])
487
+ if not k_valid:
488
+ geometry = None
489
+ projection["frames"][index] = {"intrinsic_valid": False}
490
+ skipped.append(("任何几何投影", "该帧 intrinsic 的 valid 为假"))
491
+ else:
492
+ K = reader.get(view, intrinsic_component["data_ref"], key)[index].numpy()
493
+ D = distortion[index].numpy() if distortion is not None else None
494
+ geometry = (K, D)
495
+
496
+ # object keypoints
497
+ for name, (data, valid) in bundled.items():
498
+ if not name.endswith("_keypoints") or geometry is None:
499
+ continue
500
+ K, D = geometry
501
+ flags = valid[index].numpy()
502
+ points = data[index].numpy()
503
+ if not flags.any():
504
+ #: recorded like any other frame, so the page's claim that every sampled
505
+ #: frame's numbers are in the report holds without exception -- and a
506
+ #: reviewer can tell "the source does not annotate this frame" from "the
507
+ #: record is missing"
508
+ projection["frames"][index] = {
509
+ "annotated": False, "valid_points": 0, "inside_points": 0,
510
+ "inside_ratio": None, "mostly_out_of_frame": False}
511
+ skipped.append((name, unmarked(points)))
512
+ continue
513
+ names = components[name].get("keypoint_names") or []
514
+ uv, front, inside = project(points, K, D, width, height)
515
+ valid_points = int((front & flags).sum())
516
+ inside_points = int((front & flags & inside).sum())
517
+ projection["points"] += valid_points
518
+ projection["inside"] += inside_points
519
+ projection["off_image"] += valid_points - inside_points
520
+ #: every annotated frame gets its own ratio, flagged or not: an aggregate
521
+ #: leaves a reviewer unable to tell a frame of scattered points from one
522
+ #: where the object had left the picture altogether
523
+ ratio = inside_points / valid_points
524
+ mostly_out = ratio < OUT_OF_FRAME_RATIO
525
+ projection["frames"][index] = {
526
+ "annotated": True, "valid_points": valid_points,
527
+ "inside_points": inside_points, "inside_ratio": round(ratio, 4),
528
+ "mostly_out_of_frame": bool(mostly_out)}
529
+ if mostly_out:
530
+ out_of_frame.append(index)
531
+ if not inside_points:
532
+ skipped.append((name, f"{valid_points} 个有效点全部落在画外"))
533
+ continue
534
+ drawn = image.copy()
535
+ painter = ImageDraw.Draw(drawn)
536
+ counts = {}
537
+ for position, point_name in enumerate(names):
538
+ if not (front[position] and flags[position] and inside[position]):
539
+ continue
540
+ part = point_name.split("_")[0]
541
+ color = PART_COLORS.get(part, "#ffffff")
542
+ counts[part] = counts.get(part, 0) + 1
543
+ dot(painter, uv[position][0], uv[position][1], color, radius)
544
+ object_id = name[len("object_"):-len("_keypoints")]
545
+ legend = "、".join(f"{part} {counts[part]} 点"
546
+ for part in sorted(PART_COLORS) if part in counts)
547
+ #: the warning is the caption's own opening words: a reviewer scanning panels
548
+ #: reads captions, and a nearly empty panel without one reads as a projection
549
+ #: that failed rather than as an object outside the camera's field of view
550
+ warning = (f"物体大部分落在画外(该帧 {valid_points} 个有效关键点只有 "
551
+ f"{inside_points} 个落在画内):" if mostly_out else "")
552
+ panels.append((warning
553
+ + f"物体 {html.escape(object_id)} 关键点投影(按发布的 keypoint_names "
554
+ f"分色:top 紫 / bottom 绿;v1.0 页面把这 32 点画成同一种白色。"
555
+ f"{valid_points} 个有效点,画内 {inside_points} 个={legend})",
556
+ picture(drawn)))
557
+ totals["keypoint_panels"] += 1
558
+
559
+ #: object and part pose axes, drawn once per distinct transform
560
+ drawn_poses = []
561
+ for name, (data, valid) in bundled.items():
562
+ if geometry is None or not (name.endswith("_pose")):
563
+ continue
564
+ pose = data[index].numpy()
565
+ if not bool(valid[index]):
566
+ skipped.append((name, unmarked(pose)))
567
+ continue
568
+ K, D = geometry
569
+ drawn = image.copy()
570
+ painter = ImageDraw.Draw(drawn)
571
+ drawn_axes = draw_axes(painter, pose, K, D, width, height, radius)
572
+ if not drawn_axes:
573
+ skipped.append((name, "三条轴的两端都落在画外,未在图上标出"))
574
+ continue
575
+ twin = next((other for other, matrix in drawn_poses
576
+ if np.array_equal(matrix, pose)), None)
577
+ if twin is not None:
578
+ folded.append((name, twin))
579
+ continue
580
+ drawn_poses.append((name, pose))
581
+ panels.append((f"{html.escape(name)} 位姿坐标轴(x 红 / y 绿 / z 蓝,每轴 5 cm,"
582
+ f"已画 {drawn_axes}/3 条;由已发布位姿与内参投影,仅示朝向)",
583
+ picture(drawn)))
584
+ totals["axis_panels"] += 1
585
+
586
+ # the released hand supervision: the MANO root translation only
587
+ for name, (data, valid) in bundled.items():
588
+ if not name.startswith("mano") or geometry is None:
589
+ continue
590
+ K, D = geometry
591
+ layout = registry.components[components[name]["schema_id"]]["layout"]
592
+ start, stop = layout["translation"]
593
+ flags = valid[index].numpy()
594
+ translation = data[index].numpy()[:, start:stop]
595
+ if not flags.any():
596
+ skipped.append((name, unmarked(translation)))
597
+ continue
598
+ uv, front, inside = project(translation, K, D, width, height)
599
+ slots = meta.get("hand_slots") or []
600
+ shown, off = [], []
601
+ for position, slot in enumerate(slots):
602
+ if not (front[position] and flags[position]):
603
+ continue
604
+ (shown if inside[position] else off).append(slot)
605
+ if not shown:
606
+ skipped.append((name, f"{len(off)} 个有效手({'、'.join(off)})的根平移全部落在画外"))
607
+ continue
608
+ drawn = image.copy()
609
+ painter = ImageDraw.Draw(drawn)
610
+ for position, slot in enumerate(slots):
611
+ if not (front[position] and flags[position] and inside[position]):
612
+ continue
613
+ dot(painter, uv[position][0], uv[position][1],
614
+ HAND_COLORS.get(slot, "#ffffff"), radius)
615
+ panels.append((f"MANO 根平移投影(schema layout.translation 第 {start}–{stop} 个参数,"
616
+ f"声明坐标系 " + str(components[name].get("coordinate_frame"))
617
+ + f",单位 m;画内 {'、'.join(shown)}"
618
+ + (f",画外 {'、'.join(off)}" if off else "")
619
+ + ")。不画骨架与网格,原因见「手部没有骨架」一节",
620
+ picture(drawn)))
621
+ totals["mano_panels"] += 1
622
+
623
+ if folded:
624
+ panels.append(("该帧这些部件的位姿与已画出的部件逐元素相同(部件静止),投影为同一图,"
625
+ "未重复绘制:" + "、".join(f"{html.escape(a)} = {html.escape(b)}"
626
+ for a, b in folded), None))
627
+ if skipped:
628
+ panels.append(("该帧未投影的几何:" + "".join(
629
+ "<br>· " + html.escape(what) + ":" + html.escape(why)
630
+ for what, why in skipped), None))
631
+ if skipped or folded:
632
+ totals["frames_noted"] += 1
633
+ totals["note_panels"] += int(bool(folded)) + int(bool(skipped))
634
+ panels_by_frame[index] = panels
635
+ # end frames
636
+
637
+ for index in selected:
638
+ details = {"frame": sync_rows[index] if index < len(sync_rows) else None}
639
+ media = {}
640
+ if media_valid is not None:
641
+ media["rgb"] = bool(media_valid[index])
642
+ details["media_validity"] = media
643
+ for name, (data, valid) in bundled.items():
644
+ if data.ndim and data.shape[0] == n:
645
+ entry = {"value": data[index].tolist(), "valid": valid[index].tolist()}
646
+ details[name] = entry
647
+ details_by_frame[index] = details
648
+
649
+ if geometry is None:
650
+ projection["frames"]["all"] = {"projected": False, "reason": "no usable calibration"}
651
+
652
+ report = view_report(view, meta, registry, reader, fields, consumed, notes,
653
+ selected, projection)
654
+ totals["frames_mostly_out_of_frame"] = len(out_of_frame)
655
+ totals["frames_mostly_out_of_frame_list"] = list(out_of_frame)
656
+ report["geometry_panels"] = dict(totals)
657
+
658
+ title = f"{view.parent.name}_{view.name}"
659
+ sections = []
660
+ for index in selected:
661
+ panels = panels_by_frame.get(index) or []
662
+ figures = []
663
+ for caption, source in panels:
664
+ if source is None:
665
+ figures.append('<figure><p class="note">' + caption + "</p></figure>")
666
+ else:
667
+ figures.append("<figure>" + source + "<figcaption>" + caption
668
+ + "</figcaption></figure>")
669
+ sections.append(
670
+ "<section><h2>帧 " + str(index) + " / " + str(n) + "</h2>"
671
+ + '<div class="panels">' + "".join(figures) + "</div>"
672
+ + "<details><summary>帧号、来源、全部数值组件与有效性</summary><pre>"
673
+ + html.escape(json.dumps(details_by_frame[index], ensure_ascii=False, indent=2))
674
+ + "</pre></details></section>")
675
+
676
+ assets = []
677
+ mesh_refs = []
678
+ for name, component in components.items():
679
+ if component.get("available", True) and name.endswith("_mesh"):
680
+ mesh_refs.append((name, component["data_ref"]))
681
+ articulation = components.get(name.rsplit("_mesh", 1)[0] + "_articulation") or {}
682
+ if articulation.get("available", True) and articulation.get("data_ref"):
683
+ path = view / articulation["data_ref"]
684
+ if path.is_file():
685
+ for part in load(path).get("parts") or []:
686
+ if part.get("mesh_ref"):
687
+ mesh_refs.append((f"{name}:{part['part_id']}", part["mesh_ref"]))
688
+ for name, ref in mesh_refs:
689
+ path = view / ref
690
+ if not path.is_file():
691
+ continue
692
+ assets.append("<figure><h3>" + html.escape(name) + "</h3>" + mesh_preview(path)
693
+ + "<figcaption>仅展示网格原生形状("
694
+ + html.escape(ref) + ");未验证尺度/位姿对应。</figcaption></figure>")
695
+
696
+ css = ("body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;"
697
+ "background:#f5f7fa;color:#18232f;line-height:1.5}"
698
+ "section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}"
699
+ "figure{margin:.5rem}figcaption{font-size:.85rem;max-width:800px}"
700
+ ".panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}"
701
+ "pre{white-space:pre-wrap;overflow:auto;font-size:12px}"
702
+ ".note{background:#fff7e6;border-left:3px solid #e0a800;padding:.6rem;"
703
+ "font-size:.9rem;max-width:800px}"
704
+ ".legend{background:#eef3fa;border-left:3px solid #4a76a8;padding:.6rem;"
705
+ "font-size:.9rem;max-width:800px}"
706
+ ".swatch{border:1px solid #b9c3d0}")
707
+ header = ("<h1>" + html.escape(title) + "</h1><p>直接读取 v1.1 bundle("
708
+ + html.escape(meta["sequence_id"]) + " 的 "
709
+ + html.escape(meta["view_type"]) + " 视图,split=" + html.escape(meta["split"])
710
+ + ")。预览仅供人工复核,不是训练输入(CONTRACT §6.5);这里只解码抽样帧,"
711
+ "不是全部帧。本 release 另带 v1.0 的全帧逐相机视频"
712
+ "(doc/history-v1.0/validation/),两者并存,本页不替代它。</p>")
713
+ header += colour_legend()
714
+ if out_of_frame:
715
+ #: A near-empty panel is ambiguous on its own: an object that really left the
716
+ #: field of view looks exactly like a projection that broke. The page does not
717
+ #: project anything but the release's own camera-frame geometry, so the honest
718
+ #: move is to name the frames and state the rule that flags them.
719
+ reason = ("该视图是戴在头上的 ego 相机,物体可以落在视野之外;"
720
+ if meta["view_type"] == "ego" else
721
+ "该相机的视野没有覆盖到物体;")
722
+ header += ('<p class="note">抽样的 ' + str(len(selected)) + " 帧里有 "
723
+ + str(len(out_of_frame)) + " 帧物体大部分落在画外(帧 "
724
+ + "、".join(str(index) for index in out_of_frame) + "):" + reason
725
+ + "本页只画发布的 camera 系几何,按该视图自己的标定投影,画外的点就是"
726
+ "真的画外,不是投影失败。每一帧的 valid_points / inside_points / "
727
+ "inside_ratio 都记在本视图报告的 projection.frames 里,标为 "
728
+ "mostly_out_of_frame 的即这些帧。判定规则:" + html.escape(OUT_OF_FRAME_RULE)
729
+ + "。</p>")
730
+ if not calibrated:
731
+ header += ('<p class="note">该视图无相机标定(camera.model='
732
+ + html.escape(str(meta["camera"]["model"]))
733
+ + "),只显示 RGB 与源缺项;按发布声明不填占位矩阵、不做任何投影。</p>")
734
+ omitted = meta.get("omitted_components") or {}
735
+ if omitted:
736
+ header += ("<details><summary>源未发布的组件及原始理由(不补造)</summary><pre>"
737
+ + html.escape(json.dumps(omitted, ensure_ascii=False, indent=2))
738
+ + "</pre></details>")
739
+ page = ("<!doctype html><html lang=\"zh\"><meta charset=\"utf-8\"><title>"
740
+ + html.escape(title) + "</title><style>" + css + "</style>" + header
741
+ + "".join(sections)
742
+ + "<h2>原始物体模型(独立预览)</h2><div class=\"panels\">" + "".join(assets)
743
+ + "</div><details><summary>全部组件元信息及原始来源</summary><pre>"
744
+ + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + "</pre></details>"
745
+ + "<details><summary>持久化 QC 结果</summary><pre>"
746
+ + html.escape(json.dumps(report, ensure_ascii=False, indent=2))
747
+ + "</pre></details></html>")
748
+
749
+ destination.mkdir(parents=True, exist_ok=True)
750
+ (destination / (title + ".html")).write_text(page, encoding="utf-8")
751
+ save(destination / (title + ".report.json"), report)
752
+ report["_page"] = title + ".html"
753
+ print(destination / (title + ".html"), "selected_frames", selected, flush=True)
754
+ return report
755
+
756
+
757
+ def render_task(task):
758
+ for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS",
759
+ "NUMEXPR_NUM_THREADS", "HAND_WAREHOUSE_FFMPEG_THREADS"):
760
+ os.environ[variable] = "1"
761
+ torch.set_num_threads(1)
762
+ view, destination, root = map(Path, task)
763
+ return render_one(view, destination, root)
764
+
765
+
766
+ # -- sampling ---------------------------------------------------------------
767
+
768
+
769
+ def sequence_facts(root: Path, sequence: str) -> dict:
770
+ """Split, object class, timeline and cameras of one sequence, from its own views."""
771
+ views = sorted((root / "data" / sequence).glob("*/metainfo.json"),
772
+ key=lambda p: (len(p.parent.name), p.parent.name))
773
+ if not views:
774
+ raise SystemExit(f"no views under {sequence}")
775
+ meta = load(views[0])
776
+ objects = [name[len("object_"):-len("_mesh")] for name in meta["components"]
777
+ if name.startswith("object_") and name.endswith("_mesh")]
778
+ if len(objects) != 1:
779
+ raise SystemExit(f"{sequence}: expected one object, found {objects}")
780
+ return {"sequence": sequence, "split": meta["split"], "object": objects[0],
781
+ "num_frames": meta["num_frames"],
782
+ "cameras": [p.parent.name for p in views]}
783
+
784
+
785
+ def plan_sequences(root: Path, seed: int, allocation: dict, facts: dict) -> list:
786
+ """Stratified sample: fixed split allocation, distinct object classes.
787
+
788
+ The published post-full sets sampled complete sequences and rendered all their
789
+ cameras; the strata are chosen so the sample is not one corner of the release --
790
+ every split, and as many object classes as there are slots (eleven are released,
791
+ six are drawn). The draw is a seeded uniform choice inside each split, and the
792
+ record in ``V1_1_VALIDATION.json`` is enough to repeat it.
793
+ """
794
+ rng = random.Random(seed)
795
+ order = ("test", "val", "train")
796
+ chosen, used = [], set()
797
+ by_split = {split: sorted(s for s, f in facts.items() if f["split"] == split)
798
+ for split in order}
799
+ for split in order:
800
+ want = allocation[split]
801
+ candidates = [s for s in by_split[split] if facts[s]["object"] not in used]
802
+ rng.shuffle(candidates)
803
+ #: the exclusion has to hold inside a split as well as across them, or the first
804
+ #: ``want`` of a shuffled list can carry the same class twice -- and the rule this
805
+ #: function writes into the report says every slot takes a class no other drawn
806
+ #: sequence uses, so the draw has to be the one that claim describes
807
+ picked, taken = [], set(used)
808
+ for sequence in candidates:
809
+ if facts[sequence]["object"] in taken:
810
+ continue
811
+ picked.append(sequence)
812
+ taken.add(facts[sequence]["object"])
813
+ if len(picked) == want:
814
+ break
815
+ if len(picked) < want:
816
+ raise SystemExit(f"{split}: only {len(picked)} of {want} slots can take an "
817
+ f"object class no other drawn sequence uses")
818
+ chosen.extend(sorted(picked))
819
+ used = taken
820
+ return chosen
821
+
822
+
823
+ def main(argv=None):
824
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
825
+ parser.add_argument("--root", type=Path,
826
+ default=Path(__file__).resolve().parents[2],
827
+ help="the shared-v1.1 release root (default: this script's own)")
828
+ parser.add_argument("--out", type=Path,
829
+ help="where the pages go (default <root>/doc/validation)")
830
+ parser.add_argument("--seed", type=int, default=20261014)
831
+ parser.add_argument("--reference-sequences", type=int, default=6,
832
+ help="sequences to sample; all their cameras are rendered")
833
+ parser.add_argument("--workers", type=int, default=4,
834
+ help="at most 8, one decoder thread each")
835
+ parser.add_argument("--views", nargs="+",
836
+ help="render these views (sequence/camera) instead of sampling")
837
+ args = parser.parse_args(argv)
838
+ if not 1 <= args.workers <= 8:
839
+ parser.error("at most 8 workers and one decoder thread each")
840
+
841
+ root = args.root.resolve()
842
+ destination = (args.out or root / "doc/validation").resolve()
843
+
844
+ allocation = {"test": 1, "val": 2, "train": 3}
845
+ if sum(allocation.values()) != args.reference_sequences:
846
+ parser.error(f"the split allocation {allocation} does not add up to "
847
+ f"--reference-sequences {args.reference_sequences}")
848
+
849
+ if args.views:
850
+ views = []
851
+ for token in args.views:
852
+ sequence, _, camera = token.partition("/")
853
+ view = root / "data" / sequence / camera
854
+ if not (view / "metainfo.json").is_file():
855
+ parser.error(f"no such view: {token}")
856
+ views.append(view)
857
+ sampling = {"kind": "explicit", "views": args.views,
858
+ "rule": "explicit view list; no sampling applied"}
859
+ sequences = sorted({view.parent.name for view in views})
860
+ else:
861
+ facts = {p.name: sequence_facts(root, p.name)
862
+ for p in sorted((root / "data").iterdir()) if p.is_dir()}
863
+ sequences = plan_sequences(root, args.seed, allocation, facts)
864
+ views = []
865
+ for sequence in sequences:
866
+ found = sorted((root / "data" / sequence).glob("*/metainfo.json"),
867
+ key=lambda p: (len(p.parent.name), p.parent.name))
868
+ if len(found) != len(facts[sequence]["cameras"]):
869
+ raise SystemExit(f"{sequence}: {len(found)} cameras enumerated")
870
+ views.extend(p.parent for p in found)
871
+ sampling = {
872
+ "seed": args.seed,
873
+ "rule": "equal allocation over the release's own splits (test 1, val 2, "
874
+ "train 3), drawn uniformly inside each split with the seed, "
875
+ "requiring a distinct object class for every slot; the test slot "
876
+ "is one of the 38 P1 test sequences, whose hand and object "
877
+ "annotations the official release withholds; every camera of a "
878
+ "drawn sequence is rendered",
879
+ "allocation": allocation,
880
+ "distinct_objects": len({facts[s]["object"] for s in sequences}),
881
+ "selections": [{"sequence": s, "split": facts[s]["split"],
882
+ "object": facts[s]["object"],
883
+ "num_frames": facts[s]["num_frames"],
884
+ "cameras": facts[s]["cameras"]} for s in sequences],
885
+ "pools": {split: sum(1 for f in facts.values() if f["split"] == split)
886
+ for split in allocation},
887
+ "sequences_in_release": len(facts),
888
+ }
889
+
890
+ start = time.monotonic()
891
+ #: no .pyc may land in the release tree, and a spawn child re-imports this
892
+ #: module before any guard inside it runs -- so the switch has to be in the
893
+ #: environment the children inherit, not only in this interpreter
894
+ os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
895
+ with ProcessPoolExecutor(max_workers=args.workers,
896
+ mp_context=multiprocessing.get_context("spawn")) as pool:
897
+ reports = list(pool.map(render_task,
898
+ [(str(v), str(destination), str(root)) for v in views]))
899
+
900
+ report = {
901
+ "review_kind": "全量后抽样",
902
+ "views": len(views),
903
+ "sequences": len(sequences),
904
+ "dataset_id": "ARCTIC",
905
+ "release_id": "shared-v1.1",
906
+ "sampling": sampling,
907
+ "wall_seconds": round(time.monotonic() - start, 3),
908
+ "decode_scope": DECODE_SCOPE,
909
+ "reports": reports,
910
+ "scope": "post-full sampled complete sequences, all cameras, read directly from "
911
+ "v1.1 bundles; evidence for human acceptance, not training input; "
912
+ "manual review pending",
913
+ }
914
+ save(destination / "V1_1_VALIDATION.json", report)
915
+
916
+ links = sorted(p.name for p in destination.glob("*.html") if p.name != "index.html")
917
+ objects = {item["sequence"]: item.get("object") for item in sampling.get("selections", [])}
918
+ uncalibrated = sum(1 for entry in reports if not entry["projection"]["calibrated"])
919
+ index_css = ("body{font:16px sans-serif;max-width:1100px;margin:auto;padding:1rem;"
920
+ "background:#f5f7fa;color:#18232f;line-height:1.5}"
921
+ ".legend{background:#eef3fa;border-left:3px solid #4a76a8;padding:.6rem;"
922
+ "font-size:.9rem;max-width:800px}.swatch{border:1px solid #b9c3d0}"
923
+ "table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccd3de;"
924
+ "padding:4px 8px;text-align:left;font-size:.9rem}")
925
+ #: what a reviewer needs to judge the sample before opening a page: which sequence,
926
+ #: which split and object, whether the view is ego or exo, and whether the release
927
+ #: establishes its calibration at all
928
+ rows = "".join(
929
+ "<tr><td><a href=\"" + html.escape(entry["_page"], quote=True) + "\">"
930
+ + html.escape(entry["view"]) + "</a></td><td>"
931
+ + html.escape(entry["split"]) + "</td><td>"
932
+ + html.escape(str(objects.get(entry["sequence_id"]) or "—")) + "</td><td>"
933
+ + html.escape(entry["view_type"]) + "</td><td>"
934
+ + html.escape(entry["camera"]["model"]) + "</td><td>"
935
+ + str(entry["num_frames"]) + "</td><td>"
936
+ + str(len(entry["selected_frames"])) + "</td></tr>"
937
+ for entry in sorted(reports, key=lambda e: (e["sequence_id"], e["camera_id"])))
938
+ index = ("<!doctype html><html lang=\"zh\"><meta charset=\"utf-8\">"
939
+ "<title>ARCTIC shared-v1.1 review</title><style>" + index_css + "</style>"
940
+ "<h1>ARCTIC shared-v1.1 全量后抽样人工复查</h1>"
941
+ "<p>数值按字节一致(CONTRACT §6);媒体不重新编码。抽样规则与种子见 "
942
+ "V1_1_VALIDATION.json,本页所列视图即全部入选视图:"
943
+ + str(len(views)) + " 个视图 / " + str(len(sequences)) + " 段,其中 "
944
+ + str(uncalibrated) + " 个视图源不提供相机标定(camera.model=unknown),"
945
+ "页面只显示 RGB 与源缺项。</p>"
946
+ + colour_legend()
947
+ + "<p>逐视图页面的每帧面板与逐帧数值在页面内;抽样帧之外的帧不在页面里,"
948
+ "v1.0 的全帧逐相机视频见 <code>../history-v1.0/validation/</code>。</p>"
949
+ "<table><tr><th>视图</th><th>split</th><th>物体</th><th>类型</th>"
950
+ "<th>相机模型</th><th>帧数</th><th>本页抽样帧</th></tr>" + rows + "</table>"
951
+ "<ul><li><a href=\"../CONTRACT.md\">CONTRACT.md</a></li>"
952
+ "<li><a href=\"../RAW_TO_SHARED.md\">RAW_TO_SHARED.md</a></li>"
953
+ "<li><a href=\"../FULL_MIGRATION_SUMMARY.json\">FULL_MIGRATION_SUMMARY.json</a></li>"
954
+ "<li><a href=\"V1_1_VALIDATION.json\">V1_1_VALIDATION.json</a></li></ul>"
955
+ "<ul>" + "".join('<li><a href="' + html.escape(name, quote=True) + '">'
956
+ + html.escape(name) + "</a></li>" for name in links)
957
+ + "</ul></html>")
958
+ (destination / "index.html").write_text(index, encoding="utf-8")
959
+ print("POST_FULL_HTML_DONE", len(views), "views", round(report["wall_seconds"], 2),
960
+ "seconds", destination / "index.html", flush=True)
961
+ return 0
962
+
963
+
964
+ if __name__ == "__main__":
965
+ raise SystemExit(main())
ARCTIC/shared-v1.1/script/arctic_v1_1/spec/CONTRACT.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 手物数据仓库统一约定 v1.1:张量合并存储
2
+
3
+ 格式版本:`hand-warehouse/1.1`。张量存储约定:`pt/tensor_bundle/v1`。
4
+
5
+ 状态:合同草案,2026-10-09。本版规定新的文件布局与读取方式,配套 [schema.json](schema.json) 注册表已更新;尚未迁移现有数据,也未适配生产转换器、读取器或可执行校验器。不能仅修改现有 metainfo 的版本号就宣称符合本版。
6
+
7
+ 本版以 [v1.0 合同](../hand-warehouse-1.0/CONTRACT.md) 为语义基础:任务范围、两层序列/相机组织、数据类型、单位、坐标系、时间对齐、左右手顺序、官方划分、view_type、来源、可用监督规则、媒体无损编码和验收要求均保留。下文仅替代数值张量组件的独立 Tensor 文件、对应 `*_valid.pt` 及文件引用规定;这些旧文件名仅用于识别对应逻辑字段。媒体和 JSONL 组件的有效性文件及引用保持 v1.0,不纳入合并。未明确改变的语义继续执行 v1.0。
8
+
9
+ 本版按用户约定作为 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 改个版本号作为已完成适配的证明。正式发布时须提供完整合同与匹配注册表,不依赖本地草案目录中的相对链接。
10
+
11
+ ## 1. 合并边界
12
+
13
+ 1. 数值张量与对应有效性必须在同一个 `.pt` 文件、同一个字段字典内保存:`{"data": Tensor, "valid": BoolTensor}`。这些数值张量组件不再生成独立的 `*_valid.pt`;媒体和 JSONL 的有效性文件不受此规则影响。
14
+ 2. 按组件合并经常一起读取的小张量:相机内参、外参、畸变放在一个 `camera.pt`;MANO 参数与整手可见性放在一个 `mano.pt`;手关键点的二维、三维与可见性放在一个 `keypoints.pt`。
15
+ 3. 每个物体的数值字段及全部部件数值字段合并为一个 `object.pt`。不同物体、不同相机、不同序列不合成一个全局大文件,以保留按需下载和读取能力。
16
+ 4. RGB、深度、栅格 mask 继续使用原无损媒体格式,不把解码后的大数组或媒体字节塞进 `.pt`。它们的有效性文件保持原文件名、Tensor/媒体格式、形状和引用方式,不包装为字典。
17
+ 5. `metainfo.json`、`camera/frames.jsonl`、实例映射、物体身份/运动学定义与网格资产保留原格式。此次不把 JSON、JSONL、OBJ、纹理全部打进一个字典。
18
+
19
+ 合并只改变存储方式,不改变采样、帧数、张量内容或有效性判定。不为减少字段数而将多个组件的 valid 合成一个公共 valid。
20
+
21
+ ## 2. 目录
22
+
23
+ ```text
24
+ <dataset>/shared-v1.1/
25
+ doc/ # 完整合同、匹配 schema、字段映射、验收报告
26
+ script/ # 转换、读取和校验代码
27
+ data/<sequence_id>/<camera_id>/
28
+ metainfo.json
29
+ observation/
30
+ rgb.mkv
31
+ rgb_valid.pt # 原独立 bool Tensor,保持不变
32
+ depth.mkv
33
+ depth_valid.mkv # 逐像素有效性,保留压缩媒体格式
34
+ camera/
35
+ frames.jsonl
36
+ camera.pt # intrinsic、extrinsic、distortion
37
+ annotation/
38
+ mano/mano.pt # motion、visibility
39
+ keypoints/keypoints.pt # uv、xyz、visibility、whole_hand_visibility
40
+ object/<object_id>/
41
+ metainfo.json
42
+ articulation.json # 仅关节/部件结构实际存在时
43
+ object.pt # 位姿、可见性、几何点、关节、部件数值
44
+ assets/ # 原网格、材质、纹理及依赖
45
+ segment/
46
+ mask.mkv # 或 polygons.jsonl,按所选表示
47
+ instances.jsonl # 仅需要实例/区域编码映射时
48
+ mask_valid.pt # 原帧级 bool Tensor,保持不变
49
+ contact/
50
+ relations.jsonl
51
+ relations_valid.pt # 原帧级 bool Tensor,保持不变
52
+ <subject_id>__<object_id>/
53
+ contact.pt # vertex_region、vertex_distance
54
+ ```
55
+
56
+ 只创建实际提供的组件和字段。以上不是每个数据集必须填满的模板;缺失内参、MANO、深度等不能通过占位文件伪装为已提供。序列/相机的两层结构不变,物体与模态目录属于相机内部组件。
57
+
58
+ ## 3. 字典结构与有效性
59
+
60
+ 本次合并的数值组件 `.pt` 根对象为字符���键的 Python `dict`,内部仅允许嵌套字符串键字典和 CPU `torch.Tensor`,不保存自定义类、模型、NumPy 对象或任意可执行对象。元信息、schema、单位和来源放在 metainfo,不在每个张量条目中重复保存。读取使用 `torch.load(path, map_location="cpu", weights_only=True)`。第 4 节保留的独立有效性 `.pt` 根对象仍为 CPU bool Tensor,不适用字典结构要求。
61
+
62
+ 例如,`camera/camera.pt` 的逻辑结构为:
63
+
64
+ ```python
65
+ {
66
+ "intrinsic": {"data": K, "valid": K_valid},
67
+ "extrinsic": {"data": T_camera_from_world, "valid": extrinsic_valid},
68
+ "distortion": {"data": distortion, "valid": distortion_valid},
69
+ }
70
+ ```
71
+
72
+ 以上变量均为 Tensor。未提供的字段整个省略;例如无世界系外参时不保存 `extrinsic`,不填单位矩阵。没有单独畸变向量的模型不创建 `distortion`:Fisheye624 仍使用既定 `[T,15]` 内参参数布局。
73
+
74
+ 数值字段统一为 `data` 与 `valid` 两个叶子。源属性原先显式声明全已知 `valid=true` 时,迁移可按该属性的有效性形状展开为全 true 的 bool Tensor;这是已有有效性声明的等价表示,不是根据数值或姿态推测有效性。有效性必须为 bool Tensor,不能用 Python `True` 代替字段内的 Tensor。静态数值字段同样配套 valid,形状采用其语义定义的标量或逐元素有效性;静态网格等外部资产仍可在 metainfo 中声明标量 valid。
75
+
76
+ valid 的形状不要求与 data 完全相同,但必须与该字段定义一致。例如 MANO 为 `[T,2,61]` / `[T,2]`,内参为 `[T,3,3]` / `[T]`,关键点为 `[T,2,K,3]` / `[T,2,K]`。按 schema 将 valid 扩展到相应数值维度,不允许依靠碰巧可广播推断语义。
77
+
78
+ 浮点默认 float32,无效浮点位置仍为 NaN;bool 和整数沿用该组件的占位/保留值规则,不因没有 NaN 而视为有效。valid 表达可用监督,不只是“值有限”或“记录存在”;适用官方 QA 与已经确认的排除规则继续保留。不能用 `isfinite(data)` 重建 valid,不能因为迁移而把 false 改成 true。
79
+
80
+ 不同字段的 valid 独立保存和解释。visibility 的 valid 不复用姿态 valid;内参 valid 不代替外参 valid。既有相机模型要求内参与单独畸变向量共用有效性时,在两个字段内保存相同 bool 值并校验一致,而不改变该模型的联合标定规则。
81
+
82
+ ## 4. 固定分组与字段名
83
+
84
+ 下表中的键路径用 `/` 展示字典层级;它不是文件系统路径。数值字段均在列出的键下继续存储 `data`、`valid`。
85
+
86
+ | 文件 | 数值字段键 | 内容 |
87
+ |---|---|---|
88
+ | `camera/camera.pt` | `intrinsic`、`extrinsic`、`distortion` | 逐帧标定;形状、参数顺序与相机模型定义不变 |
89
+ | `annotation/mano/mano.pt` | `motion`、`visibility` | MANO `[T,2,61]` 与源整手可见性;各有独立有效性 |
90
+ | `annotation/keypoints/keypoints.pt` | `uv`、`xyz`、`visibility`、`whole_hand_visibility` | 手关键点及源可见性;整手与逐点可见性不混用 |
91
+ | `annotation/object/<id>/object.pt` | `pose`、`visibility`、`dimensions`、`joint_state` | 该物体的数值标注 |
92
+ | 同上 | `keypoints/xyz`、`keypoints/template_xyz` | 相机系逐帧点或物体系静态模板点 |
93
+ | 同上 | `parts/<part_id>/pose`、`parts/<part_id>/dimensions`、`parts/<part_id>/keypoints/xyz`、`parts/<part_id>/keypoints/template_xyz` | 部件数值字段,部件身份仍由 articulation 登记 |
94
+ | 同上 | `meshes/<mesh_id>/vertex_part_ids` | `[V] int64` 顶点部件标签,valid 为 `[V]`,未知 -1 对应 false;每个 mesh 单独绑定拓扑 |
95
+ | `annotation/contact/<subject_id>__<object_id>/contact.pt` | `vertex_region`、`vertex_distance` | 已登记拓扑上的接触区域/距离与同形有效性 |
96
+
97
+ 顶点部件标签使用注册类型 `object/vertex_part_ids/v1`。物体的 mesh_id、part_id 必须在 metainfo/运动学定义中可解析;不同拓扑不能误用同一顶点数组。未提供的可见性、关节值或模板点不生成空字段。
98
+
99
+ **媒体和 JSONL 的有效性保持原样,不参与字典合并:**
100
+
101
+ | 数据本体 | 有效性文件 | 存储形式 |
102
+ |---|---|---|
103
+ | `observation/rgb.mkv` | `observation/rgb_valid.pt` | 独立 CPU bool Tensor `[T]` |
104
+ | `annotation/segment/mask.mkv` 或 `polygons.jsonl` | 原 `valid_ref` 指定的文件,通常为 `annotation/segment/mask_valid.pt` | 独立 CPU bool Tensor `[T]`;沿用原路径 |
105
+ | `annotation/contact/relations.jsonl` | `annotation/contact/relations_valid.pt` | 独立 CPU bool Tensor `[T]` |
106
+ | `observation/depth.mkv` | `observation/depth_valid.mkv` | 原逐像素 bool 无损视频 `[T,H,W]` |
107
+
108
+ 不新建仅包装上述 valid 的 observation.pt、segment.pt 或关系级 contact.pt。现有媒体/JSONL 的 `valid_ref`、`valid_axes` 及适用的 `valid_storage` 保持原定义;深度编码、NaN 位串还原与像素有效性规则不变。实体对的接触区域/距离是数值张量,仍���上表合并到各实体对的 contact.pt。
109
+
110
+ ## 5. metainfo 的文件与字典键引用
111
+
112
+ 文件定位与字典内部定位分开登记,不在文件名中拼接自定义分隔符:
113
+
114
+ | 字段 | 定义 |
115
+ |---|---|
116
+ | `data_ref` | 相对当前相机视图根目录的 POSIX 文件路径 |
117
+ | `data_key` | 非空字符串列表,按顺序访问 `.pt` 嵌套字典,最终必须得到 data Tensor |
118
+ | `valid_ref` | 有效性所在文件;合并的数值字段必须与 data_ref 相同,媒体/JSONL 保留独立有效性文件 |
119
+ | `valid_key` | 非空字符串列表,最终必须得到 bool Tensor |
120
+ | `storage.profile` / `valid_storage.profile` | 合并字典采用 `pt/tensor_bundle/v1`;媒体及其独立有效性保持原配置,不将独立 bool Tensor 声明为 bundle |
121
+
122
+ 数值字段必须显式登记 data_key 与 valid_key。例如内参登记:
123
+
124
+ ```json
125
+ {
126
+ "available": true,
127
+ "schema_id": "camera/pinhole/v1",
128
+ "data_ref": "camera/camera.pt",
129
+ "data_key": ["intrinsic", "data"],
130
+ "axes": ["T", "row", "column"],
131
+ "valid_ref": "camera/camera.pt",
132
+ "valid_key": ["intrinsic", "valid"],
133
+ "valid_axes": ["T"],
134
+ "storage": {"profile": "pt/tensor_bundle/v1"},
135
+ "valid_storage": {"profile": "pt/tensor_bundle/v1"}
136
+ }
137
+ ```
138
+
139
+ 这是引用结构片段,实际组件仍须补齐 provenance、source_locator 等必填内容。MANO 的 schema_id 仍可为 `mano/axis_angle61/v1`:它描述解码后的数值语义,不因为物理文件合并而改动。顶层 schema_version 与 storage.profile 标识新的存储方式。
140
+
141
+ 媒体和 JSONL 的 data_ref 不设置 data_key;RGB 的 valid_ref 仍为 `observation/rgb_valid.pt`,不设置 valid_key。分割、关系和深度的有效性同样保持原引用方式,不新增任何字典键字段。只有引用合并字典时才使用 data_key/valid_key。
142
+
143
+ 同样规则适用于 attributes 中的可见性等数值字段。相机模型已有的 `distortion_ref` 改为指向 `camera/camera.pt`,新增 `distortion_key=["distortion", "data"]`;对应有效性由同组件的 `distortion_valid_ref` 与 `distortion_valid_key=["distortion", "valid"]` 登记。带 `_key` 的引用必须指向匹配的 bundle 文件,不能指向目录或媒体。
144
+
145
+ 读取器按文件路径缓存已加载字典,再按 key 取字段。同一 camera.pt 的三个字段不应触发三次反序列化。按组件下载时取所需 bundle 的整个文件;本约定不承诺 `.pt` 内单个键的远端局部下载。组件合并会增加最小下载粒度,这是减少文件数的明确取舍。
146
+
147
+ ## 6. 迁移与验收
148
+
149
+ 各数据集分别迁移:先适配工具并做代表性完整序列验证,再迁移全量并核对结果,最后按授权更新远端发布;一个数据集完成不代表其他数据集已完成。迁移状态和输入/输出固定版本逐数据集登记。
150
+
151
+ 本地先在既有 `shared-v1.0` 内完成受控升级,校验完成后更名为 `shared-v1.1`。暂存、回滚、锁、旧文件清理、版本更新及 HF 路径切换遵循 [MIGRATION.md](MIGRATION.md);不复制完整媒体、不改 raw、不重新编码。多文件原地更新期间须保持维护状态,不能让读取任务使用半迁移视图。
152
+
153
+ 每次迁移必须检查:
154
+
155
+ 1. 所有组件、属性及其字典键可解析;无越界文件引用、缺失键或未登记字段;已合并的数值组件不得遗留旧独立 `*_valid.pt`。媒体/JSONL 的原独立有效性文件必须保留,不得误删或重打包。
156
+ 2. 每个迁移前后的数值字段 dtype、shape、逐元素值、NaN 位置以及 bool valid 完全一致。数值张量还应按统一连续字节视图比较,确认没有更改 NaN 位串等内容;不能用近似容差代替单纯重打包的一致性。
157
+ 3. T、帧映射、相机方向、手槽、split、来源和 valid_policy 不变。固定标定仍按既有 `[T,...]` 规则保存;本次不额外改成单份静态标定加广播。
158
+ 4. 媒体与其他未修改文件按原可信摘要核对。新 `.pt` 的文件 SHA256 通常改变,必须重新生成发布清单;新文件指纹不等于转换语义正确性的证明。
159
+ 5. 用新读取器运行代表性完整序列及所有相机,检查 RGB、相机与实际存在的标注是否正确关联;报告明确“重打包数值一致”与“人工视觉验收”的不同范围。
160
+
161
+ 只有完成匹配注册表、读写工具及上述验收后才能生产/发布 v1.1。上传仍须单独得到授权;本文档更新本身不启动数据迁移或上传;被替代旧文件的清理属于后续迁移发布步骤,必须遵守MIGRATION.md 中先验收、安全切换和固定提交核验要求。
ARCTIC/shared-v1.1/script/arctic_v1_1/spec/MIGRATION.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 数据集 v1.0 → v1.1 升级规范
2
+
3
+ 日期:2026-10-09。目标格式:`hand-warehouse/1.1`。字段与字典布局见 [CONTRACT.md](CONTRACT.md)。
4
+
5
+ ## 1. 升级单位与最终布局
6
+
7
+ 以一个完整数据集为单位逐步升级。每个数据集在既有目录内完成数值文件重组、工具适配与验证,完成后将目录由 `shared-v1.0` 更名为 `shared-v1.1`。最终使用:
8
+
9
+ ```text
10
+ <dataset>/
11
+ raw/ # 保持原样
12
+ shared-v1.1/
13
+ data/
14
+ doc/
15
+ script/
16
+ ```
17
+
18
+ 这是对“发布目录永久保持 shared-v1.0”安排的修订:不长期保留两套发布树,也不复制一整套媒体再制作新版本。尚未升级的数据集继续使用自己的 `shared-v1.0`;不同数据集处于不同版本是正常的。
19
+
20
+ 完成后视图元数据统一为 `schema_version=hand-warehouse/1.1`、`release_id=shared-v1.1`。目录名与元数据版本均须正确,不能只更名而不改变内容。发布记录保留旧版本的固定提交以便追溯。
21
+
22
+ ## 2. 变更范围
23
+
24
+ - 合并相机、MANO、关键点、物体、实体对接触等数值张量及各自 valid;具体分组遵循合同。
25
+ - 保持媒体及其独立有效性文件不变,包括 RGB、深度、mask 和相应 valid。JSONL、资产按合同保留;不重新编码媒体,不改 raw。
26
+ - 不改变张量 dtype、shape、数值、NaN 位串、valid、帧映射、T、单位、坐标系、左右手、划分及监督策略。
27
+ - 更新匹配的 schema、读取/转换/校验脚本、metainfo 引用、发布清单和正式文档。不得仅替换版本字符串冒充工具适配。
28
+ - 删除已经完整合并且验收通过的旧数值文件与对应独立 valid;不得按 `*_valid.pt` 通配删除,媒体/JSONL 有效性不在清理范围。
29
+
30
+ ## 3. 启动与登记
31
+
32
+ 启动前核对项目并行上限、实际进程、锁和空间。取得数据集迁移锁并暂停该目录的转换、发布和读取任务;多文件原地更新不是整体原子操作,不得让消费者读取半迁移视图。
33
+
34
+ 在发布树外的 `tmp/` 为每个数据集登记:源 schema/release、源 HF 固定提交、源文件清单及摘要、目标版本、工具摘要、变更/删除的精确路径清单、checkpoint、阶段、错误和验收结果。原始数据长期保留。
35
+
36
+ 准备可恢复的基线:保存即将被替换的小型元数据和脚本,以及旧数值文件的临时备份或已核验可恢复的远端固定版本。不复制未变化的大型媒体。空间预算包含临时新文件和回滚所需文件;空间不足时停止新增工作,不删 raw 腾空间。
37
+
38
+ ## 4. 原地升级
39
+
40
+ 1. 先选代表性完整序列及全部相机,在 `tmp/` 验证新写入器、读取器和引用;覆盖实际存在的组件与有效性组合。遵循项目人工验收要求后再全量。
41
+ 2. 全量按完整视图处理。读取旧数值及 valid,写临时字典,重新读取并逐字段精确比较;不得用近似误差判断纯重打包的一致性。
42
+ 3. 验证通过后在同一文件系统原子替换单个文件,再更新该视图 metainfo。只有新字段与引用完整可读、且回滚依据可用,才能移除该视图被替代的旧文件。
43
+ 4. 每个视图保存完成 checkpoint;续跑必须核对输入和工具版本、产物摘要及当前引用,不能只依据文件存在而跳过。整个数据集完成前保持维护状态。
44
+ 5. 完成全部视图后校验完整路径集合、无重复/缺失、所有键引用、全部数值一致性和未变文件摘要,并更新正式文档及脚本。生成直接读取新格式的随机完整序列报告,按项目流程人工确认。
45
+
46
+ 失败时停止该数据集迁移,保留 checkpoint 和回滚材料,不伪装完成,不自动删除整棵目录或从 raw 重做转换。
47
+
48
+ ## 5. 本地最终更名
49
+
50
+ 全量验收通过后,在维护状态下统一设置最终 `release_id=shared-v1.1`,更新当前使用的配置、入口、清单和链接,然后将原目录重命名为 `shared-v1.1`。
51
+
52
+ 重命名前核对源/目标绝对路径均位于该数据集根目录;目标目录必须不存在,不合并、不覆盖已有同名目录。同一文件系统内执行目录重命名,避免复制全部媒体。更名后再次解析相对引用并检查脚本默认路径,最后解除本地维护状态。
53
+
54
+ 历史报告中说明当时版本的文字与固定摘要作为历史证据保留,不批量篡改;当前入口须明确报告所属版本,并链接本次迁移验收结果。
55
+
56
+ ## 6. HF 发布与路径更换
57
+
58
+ 本地目录重命名不等于 HF 路径已经更换。远端须在得到发布授权后,基于旧的固定提交执行受控更新;发布前再次核对源 HEAD 和相关文件内容,冲突时停止调查。
59
+
60
+ 优先复用仓库已有内容,以平台实际支持且经过验证的服务端复制/提交操作,将未变化媒体映射到 `shared-v1.1`;仅新的字典、元数据、文档和脚本需要提供新内容。不承诺路径更换必然零网络传输或零耗时;先验证实际行为,不盲目重新上传全套媒体。
61
+
62
+ 理想情况下,在一个提交中添加目标路径并删除旧路径,使默认分支完整切换。若文件数或 API 限制不允许,使用经过验证的临时分支准备与核验,完成后受控切换;若只能分批更新默认分支,必须明确维护状态,旧版本保留到目标完整核验通过,不提前删除唯一完整的旧树。短暂的核验用路径并存不代表长期发布两套版本。
63
+
64
+ 最终必须在同一固定提交上验证:目标 `shared-v1.1` 的文件集合、大小与内容摘要全部匹配清单,所有引用有效;旧 `shared-v1.0` 路径已移除;raw 未变化。服务端更换路径仍须执行这些核验,不能用“文件名已改”替代。
65
+
66
+ 完成后更新数据集登记与下载示例,记录最终提交,清理本次临时文件并通知一次,再安排下一个数据集。旧提交历史保留历史版本;本流程减少当前发布树的重复文件,不承诺清除 HF 历史存储。
67
+
68
+ 本文仅规定后续实施流程,编写本文不等于已经启动迁移、修改数据或获得新的发布授权。
ARCTIC/shared-v1.1/script/arctic_v1_1/spec/schema.json ADDED
@@ -0,0 +1,1590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "hand-warehouse/1.1",
3
+ "validity_revision": "usable-annotation-2026-09-20",
4
+ "annotation_validity": {
5
+ "meaning": "annotation usable for supervision, not merely record presence",
6
+ "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion",
7
+ "without_official_qa": "omit QA term; declare source rules; do not fabricate QA",
8
+ "policy_field": "components.<name>.valid_policy",
9
+ "visibility_is_independent": true,
10
+ "invalid_float_value": "NaN",
11
+ "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",
12
+ "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100"
13
+ },
14
+ "hand_slots": [
15
+ "left",
16
+ "right"
17
+ ],
18
+ "view_metadata": {
19
+ "required_fields": [
20
+ "schema_version",
21
+ "dataset_id",
22
+ "release_id",
23
+ "sequence_id",
24
+ "camera_id",
25
+ "sample_type",
26
+ "num_frames",
27
+ "hand_slots",
28
+ "sampling",
29
+ "camera",
30
+ "components",
31
+ "split",
32
+ "view_type"
33
+ ],
34
+ "view_type_values": [
35
+ "ego",
36
+ "exo",
37
+ "unknown"
38
+ ],
39
+ "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",
40
+ "schema_version": "hand-warehouse/1.1",
41
+ "release_id": "shared-v1.1"
42
+ },
43
+ "keypoints": {
44
+ "mano21/v1": {
45
+ "count": 21,
46
+ "names": [
47
+ "wrist",
48
+ "thumb_1",
49
+ "thumb_2",
50
+ "thumb_3",
51
+ "thumb_4",
52
+ "index_1",
53
+ "index_2",
54
+ "index_3",
55
+ "index_4",
56
+ "middle_1",
57
+ "middle_2",
58
+ "middle_3",
59
+ "middle_4",
60
+ "ring_1",
61
+ "ring_2",
62
+ "ring_3",
63
+ "ring_4",
64
+ "little_1",
65
+ "little_2",
66
+ "little_3",
67
+ "little_4"
68
+ ],
69
+ "source_index_map": null,
70
+ "note": "adapter maps official MANO joint and fingertip convention"
71
+ },
72
+ "rhd21/v1": {
73
+ "count": 21,
74
+ "names": [
75
+ "wrist",
76
+ "thumb_1",
77
+ "thumb_2",
78
+ "thumb_3",
79
+ "thumb_4",
80
+ "index_1",
81
+ "index_2",
82
+ "index_3",
83
+ "index_4",
84
+ "middle_1",
85
+ "middle_2",
86
+ "middle_3",
87
+ "middle_4",
88
+ "ring_1",
89
+ "ring_2",
90
+ "ring_3",
91
+ "ring_4",
92
+ "little_1",
93
+ "little_2",
94
+ "little_3",
95
+ "little_4"
96
+ ],
97
+ "source_index_map_per_hand": [
98
+ 0,
99
+ 4,
100
+ 3,
101
+ 2,
102
+ 1,
103
+ 8,
104
+ 7,
105
+ 6,
106
+ 5,
107
+ 12,
108
+ 11,
109
+ 10,
110
+ 9,
111
+ 16,
112
+ 15,
113
+ 14,
114
+ 13,
115
+ 20,
116
+ 19,
117
+ 18,
118
+ 17
119
+ ]
120
+ }
121
+ },
122
+ "camera": {
123
+ "opencv_fisheye4": {
124
+ "K": [
125
+ 3,
126
+ 3
127
+ ],
128
+ "distortion": [
129
+ "k1",
130
+ "k2",
131
+ "k3",
132
+ "k4"
133
+ ],
134
+ "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand"
135
+ },
136
+ "pinhole": {
137
+ "K": [
138
+ 3,
139
+ 3
140
+ ]
141
+ },
142
+ "fisheye624": {
143
+ "parameters": [
144
+ "f",
145
+ "cx",
146
+ "cy",
147
+ "k0",
148
+ "k1",
149
+ "k2",
150
+ "k3",
151
+ "k4",
152
+ "k5",
153
+ "p0",
154
+ "p1",
155
+ "s0",
156
+ "s1",
157
+ "s2",
158
+ "s3"
159
+ ]
160
+ },
161
+ "rational8": {
162
+ "K": [
163
+ 3,
164
+ 3
165
+ ],
166
+ "distortion": [
167
+ "k1",
168
+ "k2",
169
+ "p1",
170
+ "p2",
171
+ "k3",
172
+ "k4",
173
+ "k5",
174
+ "k6"
175
+ ]
176
+ }
177
+ },
178
+ "segmentation": {
179
+ "segment/uint16_labels/v1": {
180
+ "storage": "mask.mkv",
181
+ "dtype": "uint16",
182
+ "mapping": "instances.jsonl",
183
+ "valid_shape": [
184
+ "T"
185
+ ],
186
+ "required_metadata": [
187
+ "segmentation_type",
188
+ "coverage",
189
+ "mapping_ref",
190
+ "storage"
191
+ ],
192
+ "shape": [
193
+ "T",
194
+ "H",
195
+ "W"
196
+ ],
197
+ "reserved_codes": {
198
+ "0": "unassigned",
199
+ "65535": "ignore"
200
+ },
201
+ "region_codes": [
202
+ 1,
203
+ 65534
204
+ ],
205
+ "allowed_storage_profiles": [
206
+ "mkv/uint16_ffv1/v1"
207
+ ]
208
+ },
209
+ "segment/instance_polygons/v1": {
210
+ "storage": "polygons.jsonl",
211
+ "mapping": "instances.jsonl",
212
+ "frame_keys": [
213
+ "frame_index",
214
+ "instances"
215
+ ],
216
+ "instance_keys": [
217
+ "mask_value",
218
+ "polygons"
219
+ ],
220
+ "coordinate_unit": "pixel",
221
+ "overlap_allowed": true,
222
+ "valid_shape": [
223
+ "T"
224
+ ],
225
+ "required_metadata": [
226
+ "segmentation_type",
227
+ "coverage",
228
+ "mapping_ref"
229
+ ],
230
+ "polygon_shape": [
231
+ "N",
232
+ 2
233
+ ],
234
+ "holes_supported": false
235
+ },
236
+ "segment/foreground_intensity/v1": {
237
+ "storage": "mask.mkv",
238
+ "dtype": "uint16",
239
+ "value_range": [
240
+ 0,
241
+ 255
242
+ ],
243
+ "normalization_scale": 0.00392156862745098,
244
+ "axes": [
245
+ "T",
246
+ "height",
247
+ "width"
248
+ ],
249
+ "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
250
+ "zero": "background",
251
+ "full_scale": "foreground",
252
+ "mapping": "foreground_category in component metadata",
253
+ "valid_shape": [
254
+ "T"
255
+ ],
256
+ "required_metadata": [
257
+ "segmentation_type",
258
+ "coverage",
259
+ "value_range",
260
+ "normalization_scale",
261
+ "foreground_category",
262
+ "entity_id",
263
+ "storage"
264
+ ],
265
+ "shape": [
266
+ "T",
267
+ "H",
268
+ "W"
269
+ ],
270
+ "allowed_storage_profiles": [
271
+ "mkv/uint16_ffv1/v1"
272
+ ]
273
+ }
274
+ },
275
+ "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.",
276
+ "components": {
277
+ "mano/axis_angle61/v1": {
278
+ "storage": "pt",
279
+ "dtype": "float32",
280
+ "shape": [
281
+ "T",
282
+ 2,
283
+ 61
284
+ ],
285
+ "valid_shape": [
286
+ "T",
287
+ 2
288
+ ],
289
+ "unit": "m",
290
+ "angle_unit": "rad",
291
+ "coordinate_frame": "camera",
292
+ "layout": {
293
+ "pose_axis_angle": [
294
+ 0,
295
+ 48
296
+ ],
297
+ "shape": [
298
+ 48,
299
+ 58
300
+ ],
301
+ "translation": [
302
+ 58,
303
+ 61
304
+ ]
305
+ },
306
+ "allowed_storage_profiles": [
307
+ "pt/tensor_bundle/v1"
308
+ ],
309
+ "allowed_valid_storage_profiles": [
310
+ "pt/tensor_bundle/v1"
311
+ ],
312
+ "valid_storage": "pt",
313
+ "tensor_container": "dict",
314
+ "valid_dtype": "bool",
315
+ "required_metadata": [
316
+ "data_ref",
317
+ "data_key",
318
+ "valid_ref",
319
+ "valid_key",
320
+ "storage",
321
+ "valid_storage"
322
+ ]
323
+ },
324
+ "keypoints/uv/v1": {
325
+ "storage": "pt",
326
+ "dtype": "float32",
327
+ "shape": [
328
+ "T",
329
+ 2,
330
+ 21,
331
+ 2
332
+ ],
333
+ "valid_shape": [
334
+ "T",
335
+ 2,
336
+ 21
337
+ ],
338
+ "unit": "pixel",
339
+ "required_metadata": [
340
+ "keypoint_schema",
341
+ "data_ref",
342
+ "data_key",
343
+ "valid_ref",
344
+ "valid_key",
345
+ "storage",
346
+ "valid_storage"
347
+ ],
348
+ "allowed_storage_profiles": [
349
+ "pt/tensor_bundle/v1"
350
+ ],
351
+ "allowed_valid_storage_profiles": [
352
+ "pt/tensor_bundle/v1"
353
+ ],
354
+ "valid_storage": "pt",
355
+ "tensor_container": "dict",
356
+ "valid_dtype": "bool"
357
+ },
358
+ "keypoints/xyz/v1": {
359
+ "storage": "pt",
360
+ "dtype": "float32",
361
+ "shape": [
362
+ "T",
363
+ 2,
364
+ 21,
365
+ 3
366
+ ],
367
+ "valid_shape": [
368
+ "T",
369
+ 2,
370
+ 21
371
+ ],
372
+ "unit": "m",
373
+ "required_metadata": [
374
+ "keypoint_schema",
375
+ "data_ref",
376
+ "data_key",
377
+ "valid_ref",
378
+ "valid_key",
379
+ "storage",
380
+ "valid_storage"
381
+ ],
382
+ "allowed_storage_profiles": [
383
+ "pt/tensor_bundle/v1"
384
+ ],
385
+ "allowed_valid_storage_profiles": [
386
+ "pt/tensor_bundle/v1"
387
+ ],
388
+ "valid_storage": "pt",
389
+ "tensor_container": "dict",
390
+ "valid_dtype": "bool"
391
+ },
392
+ "depth/z_float32/v1": {
393
+ "storage": "mkv",
394
+ "dtype": "float32",
395
+ "shape": [
396
+ "T",
397
+ "H",
398
+ "W"
399
+ ],
400
+ "valid_shape": [
401
+ "T",
402
+ "H",
403
+ "W"
404
+ ],
405
+ "unit": "m",
406
+ "depth_type": "z",
407
+ "pixel_grid": "current_rgb",
408
+ "coordinate_frame": "current_rgb_camera",
409
+ "valid_storage": "mkv",
410
+ "allowed_storage_profiles": [
411
+ "mkv/depth_float32_bits/v1"
412
+ ],
413
+ "allowed_valid_storage_profiles": [
414
+ "mkv/bool_ffv1/v1"
415
+ ],
416
+ "required_metadata": [
417
+ "storage",
418
+ "valid_storage",
419
+ "depth_origin"
420
+ ],
421
+ "depth_origin_values": [
422
+ "measured",
423
+ "rendered",
424
+ "unknown"
425
+ ]
426
+ },
427
+ "transform/se3/v1": {
428
+ "storage": "pt",
429
+ "dtype": "float32",
430
+ "shape": [
431
+ "T",
432
+ 4,
433
+ 4
434
+ ],
435
+ "valid_shape": [
436
+ "T"
437
+ ],
438
+ "unit": "m",
439
+ "required_metadata": [
440
+ "convention",
441
+ "data_ref",
442
+ "data_key",
443
+ "valid_ref",
444
+ "valid_key",
445
+ "storage",
446
+ "valid_storage"
447
+ ],
448
+ "allowed_storage_profiles": [
449
+ "pt/tensor_bundle/v1"
450
+ ],
451
+ "allowed_valid_storage_profiles": [
452
+ "pt/tensor_bundle/v1"
453
+ ],
454
+ "valid_storage": "pt",
455
+ "tensor_container": "dict",
456
+ "valid_dtype": "bool"
457
+ },
458
+ "object/rigid/v1": {
459
+ "storage": "pt",
460
+ "dtype": "float32",
461
+ "shape": [
462
+ "T",
463
+ 4,
464
+ 4
465
+ ],
466
+ "valid_shape": [
467
+ "T"
468
+ ],
469
+ "unit": "m",
470
+ "required_metadata": [
471
+ "convention",
472
+ "data_ref",
473
+ "data_key",
474
+ "valid_ref",
475
+ "valid_key",
476
+ "storage",
477
+ "valid_storage"
478
+ ],
479
+ "allowed_storage_profiles": [
480
+ "pt/tensor_bundle/v1"
481
+ ],
482
+ "allowed_valid_storage_profiles": [
483
+ "pt/tensor_bundle/v1"
484
+ ],
485
+ "valid_storage": "pt",
486
+ "tensor_container": "dict",
487
+ "valid_dtype": "bool"
488
+ },
489
+ "camera/pinhole/v1": {
490
+ "storage": "pt",
491
+ "dtype": "float32",
492
+ "shape": [
493
+ "T",
494
+ 3,
495
+ 3
496
+ ],
497
+ "valid_shape": [
498
+ "T"
499
+ ],
500
+ "allowed_storage_profiles": [
501
+ "pt/tensor_bundle/v1"
502
+ ],
503
+ "allowed_valid_storage_profiles": [
504
+ "pt/tensor_bundle/v1"
505
+ ],
506
+ "valid_storage": "pt",
507
+ "tensor_container": "dict",
508
+ "valid_dtype": "bool",
509
+ "required_metadata": [
510
+ "data_ref",
511
+ "data_key",
512
+ "valid_ref",
513
+ "valid_key",
514
+ "storage",
515
+ "valid_storage"
516
+ ]
517
+ },
518
+ "camera/rational8/v1": {
519
+ "storage": "pt",
520
+ "dtype": "float32",
521
+ "shape": [
522
+ "T",
523
+ 3,
524
+ 3
525
+ ],
526
+ "valid_shape": [
527
+ "T"
528
+ ],
529
+ "allowed_storage_profiles": [
530
+ "pt/tensor_bundle/v1"
531
+ ],
532
+ "allowed_valid_storage_profiles": [
533
+ "pt/tensor_bundle/v1"
534
+ ],
535
+ "valid_storage": "pt",
536
+ "tensor_container": "dict",
537
+ "valid_dtype": "bool",
538
+ "required_metadata": [
539
+ "data_ref",
540
+ "data_key",
541
+ "valid_ref",
542
+ "valid_key",
543
+ "storage",
544
+ "valid_storage",
545
+ "distortion_ref",
546
+ "distortion_key",
547
+ "distortion_valid_ref",
548
+ "distortion_valid_key"
549
+ ]
550
+ },
551
+ "camera/opencv_fisheye4/v1": {
552
+ "storage": "pt",
553
+ "dtype": "float32",
554
+ "shape": [
555
+ "T",
556
+ 3,
557
+ 3
558
+ ],
559
+ "valid_shape": [
560
+ "T"
561
+ ],
562
+ "allowed_storage_profiles": [
563
+ "pt/tensor_bundle/v1"
564
+ ],
565
+ "allowed_valid_storage_profiles": [
566
+ "pt/tensor_bundle/v1"
567
+ ],
568
+ "valid_storage": "pt",
569
+ "tensor_container": "dict",
570
+ "valid_dtype": "bool",
571
+ "required_metadata": [
572
+ "data_ref",
573
+ "data_key",
574
+ "valid_ref",
575
+ "valid_key",
576
+ "storage",
577
+ "valid_storage",
578
+ "distortion_ref",
579
+ "distortion_key",
580
+ "distortion_valid_ref",
581
+ "distortion_valid_key"
582
+ ]
583
+ },
584
+ "camera/fisheye624/v1": {
585
+ "storage": "pt",
586
+ "dtype": "float32",
587
+ "shape": [
588
+ "T",
589
+ 15
590
+ ],
591
+ "valid_shape": [
592
+ "T"
593
+ ],
594
+ "allowed_storage_profiles": [
595
+ "pt/tensor_bundle/v1"
596
+ ],
597
+ "allowed_valid_storage_profiles": [
598
+ "pt/tensor_bundle/v1"
599
+ ],
600
+ "valid_storage": "pt",
601
+ "tensor_container": "dict",
602
+ "valid_dtype": "bool",
603
+ "required_metadata": [
604
+ "data_ref",
605
+ "data_key",
606
+ "valid_ref",
607
+ "valid_key",
608
+ "storage",
609
+ "valid_storage"
610
+ ]
611
+ },
612
+ "camera/distortion8/v1": {
613
+ "storage": "pt",
614
+ "dtype": "float32",
615
+ "shape": [
616
+ "T",
617
+ 8
618
+ ],
619
+ "valid_shape": [
620
+ "T"
621
+ ],
622
+ "allowed_storage_profiles": [
623
+ "pt/tensor_bundle/v1"
624
+ ],
625
+ "allowed_valid_storage_profiles": [
626
+ "pt/tensor_bundle/v1"
627
+ ],
628
+ "valid_storage": "pt",
629
+ "tensor_container": "dict",
630
+ "valid_dtype": "bool",
631
+ "required_metadata": [
632
+ "data_ref",
633
+ "data_key",
634
+ "valid_ref",
635
+ "valid_key",
636
+ "storage",
637
+ "valid_storage"
638
+ ]
639
+ },
640
+ "camera/fisheye4_distortion/v1": {
641
+ "storage": "pt",
642
+ "dtype": "float32",
643
+ "shape": [
644
+ "T",
645
+ 4
646
+ ],
647
+ "valid_shape": [
648
+ "T"
649
+ ],
650
+ "allowed_storage_profiles": [
651
+ "pt/tensor_bundle/v1"
652
+ ],
653
+ "allowed_valid_storage_profiles": [
654
+ "pt/tensor_bundle/v1"
655
+ ],
656
+ "valid_storage": "pt",
657
+ "tensor_container": "dict",
658
+ "valid_dtype": "bool",
659
+ "required_metadata": [
660
+ "data_ref",
661
+ "data_key",
662
+ "valid_ref",
663
+ "valid_key",
664
+ "storage",
665
+ "valid_storage"
666
+ ]
667
+ },
668
+ "object/joint_state/v1": {
669
+ "storage": "pt",
670
+ "dtype": "float32",
671
+ "shape": [
672
+ "T",
673
+ "J"
674
+ ],
675
+ "valid_shape": [
676
+ "T",
677
+ "J"
678
+ ],
679
+ "required_metadata": [
680
+ "joint_order",
681
+ "data_ref",
682
+ "data_key",
683
+ "valid_ref",
684
+ "valid_key",
685
+ "storage",
686
+ "valid_storage"
687
+ ],
688
+ "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint",
689
+ "allowed_storage_profiles": [
690
+ "pt/tensor_bundle/v1"
691
+ ],
692
+ "allowed_valid_storage_profiles": [
693
+ "pt/tensor_bundle/v1"
694
+ ],
695
+ "valid_storage": "pt",
696
+ "tensor_container": "dict",
697
+ "valid_dtype": "bool"
698
+ },
699
+ "object_keypoints/camera/v1": {
700
+ "storage": "pt",
701
+ "dtype": "float32",
702
+ "shape": [
703
+ "T",
704
+ "K",
705
+ 3
706
+ ],
707
+ "valid_shape": [
708
+ "T",
709
+ "K"
710
+ ],
711
+ "unit": "m",
712
+ "coordinate_frame": "camera",
713
+ "required_metadata": [
714
+ "keypoint_schema",
715
+ "data_ref",
716
+ "data_key",
717
+ "valid_ref",
718
+ "valid_key",
719
+ "storage",
720
+ "valid_storage"
721
+ ],
722
+ "allowed_storage_profiles": [
723
+ "pt/tensor_bundle/v1"
724
+ ],
725
+ "allowed_valid_storage_profiles": [
726
+ "pt/tensor_bundle/v1"
727
+ ],
728
+ "valid_storage": "pt",
729
+ "tensor_container": "dict",
730
+ "valid_dtype": "bool"
731
+ },
732
+ "object/dimensions/v1": {
733
+ "storage": "pt",
734
+ "dtype": "float32",
735
+ "shape": [
736
+ "T",
737
+ 3
738
+ ],
739
+ "valid_shape": [
740
+ "T"
741
+ ],
742
+ "unit": "m",
743
+ "required_metadata": [
744
+ "dimensions_semantics",
745
+ "data_ref",
746
+ "data_key",
747
+ "valid_ref",
748
+ "valid_key",
749
+ "storage",
750
+ "valid_storage"
751
+ ],
752
+ "axis_order": [
753
+ "length",
754
+ "width",
755
+ "height"
756
+ ],
757
+ "scale_rule": "do not apply to mesh without source-supported size/scale relation",
758
+ "allowed_storage_profiles": [
759
+ "pt/tensor_bundle/v1"
760
+ ],
761
+ "allowed_valid_storage_profiles": [
762
+ "pt/tensor_bundle/v1"
763
+ ],
764
+ "valid_storage": "pt",
765
+ "tensor_container": "dict",
766
+ "valid_dtype": "bool"
767
+ },
768
+ "object_keypoints/template/v1": {
769
+ "storage": "pt",
770
+ "dtype": "float32",
771
+ "shape": [
772
+ "K",
773
+ 3
774
+ ],
775
+ "valid_shape": [
776
+ "K"
777
+ ],
778
+ "unit": "m",
779
+ "coordinate_frame": "object",
780
+ "static": true,
781
+ "required_metadata": [
782
+ "keypoint_schema",
783
+ "data_ref",
784
+ "data_key",
785
+ "valid_ref",
786
+ "valid_key",
787
+ "storage",
788
+ "valid_storage"
789
+ ],
790
+ "allowed_storage_profiles": [
791
+ "pt/tensor_bundle/v1"
792
+ ],
793
+ "allowed_valid_storage_profiles": [
794
+ "pt/tensor_bundle/v1"
795
+ ],
796
+ "valid_storage": "pt",
797
+ "tensor_container": "dict",
798
+ "valid_dtype": "bool"
799
+ },
800
+ "mesh/obj/v1": {
801
+ "storage": "obj",
802
+ "unit": "m",
803
+ "static": true,
804
+ "valid_shape": [],
805
+ "dependencies": "MTL and textures retained under owning object"
806
+ },
807
+ "rgb/uint8/v1": {
808
+ "storage": "mkv",
809
+ "dtype": "uint8",
810
+ "shape": [
811
+ "T",
812
+ "H",
813
+ "W",
814
+ 3
815
+ ],
816
+ "valid_shape": [
817
+ "T"
818
+ ],
819
+ "color_order": "RGB",
820
+ "allowed_storage_profiles": [
821
+ "mkv/mjpeg_copy/v1",
822
+ "mkv/source_copy/v1",
823
+ "mkv/h264_rgb_lossless/v1",
824
+ "mkv/ffv1_rgb/v1"
825
+ ],
826
+ "required_metadata": [
827
+ "storage"
828
+ ]
829
+ },
830
+ "contact/relations/v1": {
831
+ "storage": "jsonl",
832
+ "valid_shape": [
833
+ "T"
834
+ ],
835
+ "frame_keys": [
836
+ "frame_index",
837
+ "relations"
838
+ ],
839
+ "absence_semantics": "no record is not a negative contact annotation"
840
+ },
841
+ "contact/vertex_region/v1": {
842
+ "storage": "pt",
843
+ "dtype": "bool",
844
+ "shape": [
845
+ "T",
846
+ "V"
847
+ ],
848
+ "valid_shape": [
849
+ "T",
850
+ "V"
851
+ ],
852
+ "required_metadata": [
853
+ "source_geometry_ref",
854
+ "target_geometry_ref",
855
+ "topology_id",
856
+ "data_ref",
857
+ "data_key",
858
+ "valid_ref",
859
+ "valid_key",
860
+ "storage",
861
+ "valid_storage"
862
+ ],
863
+ "pilot_status": "defined_not_empirically_validated",
864
+ "allowed_storage_profiles": [
865
+ "pt/tensor_bundle/v1"
866
+ ],
867
+ "allowed_valid_storage_profiles": [
868
+ "pt/tensor_bundle/v1"
869
+ ],
870
+ "valid_storage": "pt",
871
+ "tensor_container": "dict",
872
+ "valid_dtype": "bool"
873
+ },
874
+ "contact/vertex_distance/v1": {
875
+ "storage": "pt",
876
+ "dtype": "float32",
877
+ "shape": [
878
+ "T",
879
+ "V"
880
+ ],
881
+ "valid_shape": [
882
+ "T",
883
+ "V"
884
+ ],
885
+ "unit": "m",
886
+ "required_metadata": [
887
+ "source_geometry_ref",
888
+ "target_geometry_ref",
889
+ "topology_id",
890
+ "distance_definition",
891
+ "data_ref",
892
+ "data_key",
893
+ "valid_ref",
894
+ "valid_key",
895
+ "storage",
896
+ "valid_storage"
897
+ ],
898
+ "pilot_status": "defined_not_empirically_validated",
899
+ "allowed_storage_profiles": [
900
+ "pt/tensor_bundle/v1"
901
+ ],
902
+ "allowed_valid_storage_profiles": [
903
+ "pt/tensor_bundle/v1"
904
+ ],
905
+ "valid_storage": "pt",
906
+ "tensor_container": "dict",
907
+ "valid_dtype": "bool"
908
+ },
909
+ "object/articulated/v1": {
910
+ "storage": "json",
911
+ "required_keys": [
912
+ "parts",
913
+ "joints"
914
+ ],
915
+ "part_keys": [
916
+ "part_id",
917
+ "parent_id",
918
+ "has_model",
919
+ "mesh_ref"
920
+ ],
921
+ "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints",
922
+ "acyclic": true
923
+ },
924
+ "segment/uint16_labels/v1": {
925
+ "storage": "mkv",
926
+ "dtype": "uint16",
927
+ "mapping": "instances.jsonl",
928
+ "valid_shape": [
929
+ "T"
930
+ ],
931
+ "required_metadata": [
932
+ "segmentation_type",
933
+ "coverage",
934
+ "mapping_ref",
935
+ "storage"
936
+ ],
937
+ "shape": [
938
+ "T",
939
+ "H",
940
+ "W"
941
+ ],
942
+ "reserved_codes": {
943
+ "0": "unassigned",
944
+ "65535": "ignore"
945
+ },
946
+ "region_codes": [
947
+ 1,
948
+ 65534
949
+ ],
950
+ "allowed_storage_profiles": [
951
+ "mkv/uint16_ffv1/v1"
952
+ ]
953
+ },
954
+ "segment/instance_polygons/v1": {
955
+ "storage": "jsonl",
956
+ "mapping": "instances.jsonl",
957
+ "frame_keys": [
958
+ "frame_index",
959
+ "instances"
960
+ ],
961
+ "instance_keys": [
962
+ "mask_value",
963
+ "polygons"
964
+ ],
965
+ "coordinate_unit": "pixel",
966
+ "overlap_allowed": true,
967
+ "valid_shape": [
968
+ "T"
969
+ ],
970
+ "required_metadata": [
971
+ "segmentation_type",
972
+ "coverage",
973
+ "mapping_ref"
974
+ ],
975
+ "polygon_shape": [
976
+ "N",
977
+ 2
978
+ ],
979
+ "holes_supported": false
980
+ },
981
+ "segment/foreground_intensity/v1": {
982
+ "storage": "mkv",
983
+ "dtype": "uint16",
984
+ "value_range": [
985
+ 0,
986
+ 255
987
+ ],
988
+ "normalization_scale": 0.00392156862745098,
989
+ "axes": [
990
+ "T",
991
+ "height",
992
+ "width"
993
+ ],
994
+ "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
995
+ "zero": "background",
996
+ "full_scale": "foreground",
997
+ "mapping": "foreground_category in component metadata",
998
+ "valid_shape": [
999
+ "T"
1000
+ ],
1001
+ "required_metadata": [
1002
+ "segmentation_type",
1003
+ "coverage",
1004
+ "value_range",
1005
+ "normalization_scale",
1006
+ "foreground_category",
1007
+ "entity_id",
1008
+ "storage"
1009
+ ],
1010
+ "shape": [
1011
+ "T",
1012
+ "H",
1013
+ "W"
1014
+ ],
1015
+ "allowed_storage_profiles": [
1016
+ "mkv/uint16_ffv1/v1"
1017
+ ]
1018
+ },
1019
+ "object/vertex_part_ids/v1": {
1020
+ "storage": "pt",
1021
+ "tensor_container": "dict",
1022
+ "dtype": "int64",
1023
+ "shape": [
1024
+ "V"
1025
+ ],
1026
+ "valid_shape": [
1027
+ "V"
1028
+ ],
1029
+ "valid_dtype": "bool",
1030
+ "static": true,
1031
+ "unknown_value": -1,
1032
+ "valid_rule": "data != -1; every valid integer resolves in part_id_mapping",
1033
+ "required_metadata": [
1034
+ "mesh_ref",
1035
+ "topology_id",
1036
+ "part_id_mapping",
1037
+ "data_ref",
1038
+ "data_key",
1039
+ "valid_ref",
1040
+ "valid_key",
1041
+ "storage",
1042
+ "valid_storage"
1043
+ ],
1044
+ "allowed_storage_profiles": [
1045
+ "pt/tensor_bundle/v1"
1046
+ ],
1047
+ "allowed_valid_storage_profiles": [
1048
+ "pt/tensor_bundle/v1"
1049
+ ],
1050
+ "valid_storage": "pt"
1051
+ }
1052
+ },
1053
+ "storage_revision": "lossless-video-2026-09-18",
1054
+ "sampling": {
1055
+ "image": {
1056
+ "single": {
1057
+ "T": 1
1058
+ },
1059
+ "independent": {
1060
+ "T": ">=2",
1061
+ "required_frame_fields": [
1062
+ "sample_id",
1063
+ "source_locator"
1064
+ ],
1065
+ "temporal_relationship": false
1066
+ },
1067
+ "source_fps": null
1068
+ },
1069
+ "video": {
1070
+ "sampling_types": [
1071
+ "dense",
1072
+ "sparse"
1073
+ ]
1074
+ }
1075
+ },
1076
+ "storage_profiles": {
1077
+ "mkv/mjpeg_copy/v1": {
1078
+ "container": "matroska",
1079
+ "codec": "mjpeg",
1080
+ "method": "stream_copy_from_source_jpeg",
1081
+ "logical_dtype": "uint8",
1082
+ "decoded_pixel_format": "rgb24",
1083
+ "validation": [
1084
+ "source_jpeg_packet_sha256_exact",
1085
+ "all_packet_count_order_and_dimensions_exact",
1086
+ "deterministic_decoded_rgb_sample_exact",
1087
+ "pilot_and_final_selected_whole_sequences_decoded_rgb_exact"
1088
+ ],
1089
+ "validation_policy": {
1090
+ "id": "jpeg-packets-all-rgb-sample16/v1",
1091
+ "sample_count_per_view": 16,
1092
+ "short_views": "all_frames_if_T_less_than_16",
1093
+ "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated",
1094
+ "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)",
1095
+ "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer",
1096
+ "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage",
1097
+ "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence"
1098
+ }
1099
+ },
1100
+ "mkv/source_copy/v1": {
1101
+ "container": "matroska",
1102
+ "codec": "source_codec_declared_in_metadata",
1103
+ "method": "stream_copy_only",
1104
+ "logical_dtype": "uint8",
1105
+ "decoded_pixel_format": "rgb24",
1106
+ "validation": [
1107
+ "no_reencoding",
1108
+ "all_decoded_rgb_frames_exact",
1109
+ "presentation_frame_order_exact"
1110
+ ]
1111
+ },
1112
+ "mkv/h264_rgb_lossless/v1": {
1113
+ "container": "matroska",
1114
+ "codec": "h264",
1115
+ "encoder": "libx264rgb",
1116
+ "crf": 0,
1117
+ "decoded_pixel_format": "rgb24",
1118
+ "logical_dtype": "uint8",
1119
+ "gop": "declared_in_encoder_parameters",
1120
+ "validation": [
1121
+ "all_decoded_rgb_frames_exact"
1122
+ ],
1123
+ "forbidden": [
1124
+ "lossy_rate_control",
1125
+ "rgb_to_yuv420_subsampling"
1126
+ ]
1127
+ },
1128
+ "mkv/ffv1_rgb/v1": {
1129
+ "container": "matroska",
1130
+ "codec": "ffv1",
1131
+ "decoded_pixel_format": "rgb24",
1132
+ "logical_dtype": "uint8",
1133
+ "validation": [
1134
+ "all_decoded_rgb_frames_exact"
1135
+ ]
1136
+ },
1137
+ "mkv/depth_float32_bits/v1": {
1138
+ "container": "matroska",
1139
+ "codec": "ffv1",
1140
+ "pixel_format": "gray16le",
1141
+ "logical_dtype": "float32",
1142
+ "logical_shape": [
1143
+ "T",
1144
+ "H",
1145
+ "W"
1146
+ ],
1147
+ "encoded_shape": [
1148
+ "T",
1149
+ "H",
1150
+ "2*W"
1151
+ ],
1152
+ "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns",
1153
+ "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))",
1154
+ "validation": [
1155
+ "all_float32_bits_exact_including_nan"
1156
+ ]
1157
+ },
1158
+ "mkv/bool_ffv1/v1": {
1159
+ "container": "matroska",
1160
+ "codec": "ffv1",
1161
+ "pixel_format": "gray",
1162
+ "logical_dtype": "bool",
1163
+ "stored_values": [
1164
+ 0,
1165
+ 1
1166
+ ],
1167
+ "validation": [
1168
+ "all_bool_values_exact"
1169
+ ]
1170
+ },
1171
+ "mkv/uint16_ffv1/v1": {
1172
+ "container": "matroska",
1173
+ "codec": "ffv1",
1174
+ "pixel_formats": [
1175
+ "gray",
1176
+ "gray16le"
1177
+ ],
1178
+ "logical_dtype": "uint16",
1179
+ "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion",
1180
+ "validation": [
1181
+ "all_integer_values_exact"
1182
+ ]
1183
+ },
1184
+ "pt/tensor_bundle/v1": {
1185
+ "container": "pytorch_pt",
1186
+ "root_type": "dict",
1187
+ "dictionary_key_type": "nonempty_string",
1188
+ "allowed_value_types": [
1189
+ "dict",
1190
+ "CPU torch.Tensor"
1191
+ ],
1192
+ "tensor_entry": {
1193
+ "required_keys": [
1194
+ "data",
1195
+ "valid"
1196
+ ],
1197
+ "additional_keys": false,
1198
+ "data_type": "CPU torch.Tensor",
1199
+ "valid_type": "CPU torch.Tensor",
1200
+ "valid_dtype": "bool"
1201
+ },
1202
+ "metadata_location": "metainfo.json; do not duplicate strings, paths or custom objects inside bundles",
1203
+ "missing_entry": "omit entire entry; never fabricate absent modalities",
1204
+ "load": {
1205
+ "map_location": "cpu",
1206
+ "weights_only": true
1207
+ },
1208
+ "valid_shape_rule": "Use the specific component or attribute valid_shape; do not infer broadcasting or share validity across independent fields.",
1209
+ "validation": [
1210
+ "registered layout and key resolution",
1211
+ "CPU tensors only",
1212
+ "schema dtype and shape",
1213
+ "independent bool validity",
1214
+ "frame alignment unchanged",
1215
+ "invalid floating positions NaN",
1216
+ "pure migration exact data bytes and validity equality"
1217
+ ],
1218
+ "not_applicable_to": [
1219
+ "media payloads",
1220
+ "media standalone validity tensors",
1221
+ "JSONL standalone validity tensors"
1222
+ ]
1223
+ }
1224
+ },
1225
+ "video_metadata": {
1226
+ "required": [
1227
+ "profile",
1228
+ "codec",
1229
+ "pixel_format",
1230
+ "encoded_size",
1231
+ "decoder",
1232
+ "encoder_parameters",
1233
+ "source_lossy"
1234
+ ],
1235
+ "source_lossy_values": [
1236
+ true,
1237
+ false,
1238
+ "unknown"
1239
+ ],
1240
+ "timebase_role": "index_only",
1241
+ "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits",
1242
+ "selection": "choose smaller complete candidate only after exact roundtrip validation"
1243
+ },
1244
+ "tensor_storage_revision": "tensor-bundle-2026-10-09",
1245
+ "release_layout": {
1246
+ "directory": "shared-v1.1",
1247
+ "release_id": "shared-v1.1",
1248
+ "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."
1249
+ },
1250
+ "tensor_attributes": {
1251
+ "visibility": {
1252
+ "storage_profile": "pt/tensor_bundle/v1",
1253
+ "allowed_dtypes": [
1254
+ "bool",
1255
+ "float32"
1256
+ ],
1257
+ "visibility_types": [
1258
+ "boolean",
1259
+ "ratio"
1260
+ ],
1261
+ "ratio_range": [
1262
+ 0,
1263
+ 1
1264
+ ],
1265
+ "scopes": {
1266
+ "whole_hand": {
1267
+ "shape": [
1268
+ "T",
1269
+ 2
1270
+ ],
1271
+ "valid_shape": [
1272
+ "T",
1273
+ 2
1274
+ ]
1275
+ },
1276
+ "hand_keypoint": {
1277
+ "shape": [
1278
+ "T",
1279
+ 2,
1280
+ "K"
1281
+ ],
1282
+ "valid_shape": [
1283
+ "T",
1284
+ 2,
1285
+ "K"
1286
+ ]
1287
+ },
1288
+ "object": {
1289
+ "shape": [
1290
+ "T"
1291
+ ],
1292
+ "valid_shape": [
1293
+ "T"
1294
+ ]
1295
+ }
1296
+ },
1297
+ "required_metadata": [
1298
+ "data_ref",
1299
+ "data_key",
1300
+ "axes",
1301
+ "dtype",
1302
+ "visibility_type",
1303
+ "meaning",
1304
+ "valid_ref",
1305
+ "valid_key",
1306
+ "valid_axes",
1307
+ "storage",
1308
+ "valid_storage",
1309
+ "provenance",
1310
+ "source_locator"
1311
+ ],
1312
+ "valid_dtype": "bool",
1313
+ "unknown": "valid=false; ratio data NaN; boolean data is not interpretable without valid",
1314
+ "all_known": "explicit all-true bool tensor; do not infer from pose validity",
1315
+ "note": "No source visibility means omit. Expand explicitly declared all-known scalar validity during migration without changing semantics."
1316
+ }
1317
+ },
1318
+ "tensor_bundles": {
1319
+ "camera": {
1320
+ "path": "camera/camera.pt",
1321
+ "entries": {
1322
+ "intrinsic": {
1323
+ "schema_ids": [
1324
+ "camera/pinhole/v1",
1325
+ "camera/rational8/v1",
1326
+ "camera/opencv_fisheye4/v1",
1327
+ "camera/fisheye624/v1"
1328
+ ]
1329
+ },
1330
+ "extrinsic": {
1331
+ "schema_ids": [
1332
+ "transform/se3/v1"
1333
+ ]
1334
+ },
1335
+ "distortion": {
1336
+ "schema_ids": [
1337
+ "camera/distortion8/v1",
1338
+ "camera/fisheye4_distortion/v1"
1339
+ ]
1340
+ }
1341
+ }
1342
+ },
1343
+ "mano": {
1344
+ "path": "annotation/mano/mano.pt",
1345
+ "entries": {
1346
+ "motion": {
1347
+ "schema_ids": [
1348
+ "mano/axis_angle61/v1"
1349
+ ]
1350
+ },
1351
+ "visibility": {
1352
+ "attribute_id": "visibility",
1353
+ "scope": "whole_hand"
1354
+ }
1355
+ }
1356
+ },
1357
+ "keypoints": {
1358
+ "path": "annotation/keypoints/keypoints.pt",
1359
+ "entries": {
1360
+ "uv": {
1361
+ "schema_ids": [
1362
+ "keypoints/uv/v1"
1363
+ ]
1364
+ },
1365
+ "xyz": {
1366
+ "schema_ids": [
1367
+ "keypoints/xyz/v1"
1368
+ ]
1369
+ },
1370
+ "visibility": {
1371
+ "attribute_id": "visibility",
1372
+ "scope": "hand_keypoint"
1373
+ },
1374
+ "whole_hand_visibility": {
1375
+ "attribute_id": "visibility",
1376
+ "scope": "whole_hand"
1377
+ }
1378
+ }
1379
+ },
1380
+ "object": {
1381
+ "path": "annotation/object/<object_id>/object.pt",
1382
+ "entries": {
1383
+ "pose": {
1384
+ "schema_ids": [
1385
+ "object/rigid/v1"
1386
+ ]
1387
+ },
1388
+ "visibility": {
1389
+ "attribute_id": "visibility",
1390
+ "scope": "object"
1391
+ },
1392
+ "dimensions": {
1393
+ "schema_ids": [
1394
+ "object/dimensions/v1"
1395
+ ]
1396
+ },
1397
+ "joint_state": {
1398
+ "schema_ids": [
1399
+ "object/joint_state/v1"
1400
+ ]
1401
+ },
1402
+ "keypoints/xyz": {
1403
+ "schema_ids": [
1404
+ "object_keypoints/camera/v1"
1405
+ ]
1406
+ },
1407
+ "keypoints/template_xyz": {
1408
+ "schema_ids": [
1409
+ "object_keypoints/template/v1"
1410
+ ]
1411
+ },
1412
+ "parts/<part_id>/pose": {
1413
+ "schema_ids": [
1414
+ "transform/se3/v1"
1415
+ ],
1416
+ "convention": "T_camera_from_part"
1417
+ },
1418
+ "parts/<part_id>/dimensions": {
1419
+ "schema_ids": [
1420
+ "object/dimensions/v1"
1421
+ ]
1422
+ },
1423
+ "parts/<part_id>/keypoints/xyz": {
1424
+ "schema_ids": [
1425
+ "object_keypoints/camera/v1"
1426
+ ]
1427
+ },
1428
+ "parts/<part_id>/keypoints/template_xyz": {
1429
+ "schema_ids": [
1430
+ "object_keypoints/template/v1"
1431
+ ],
1432
+ "coordinate_frame": "part"
1433
+ },
1434
+ "meshes/<mesh_id>/vertex_part_ids": {
1435
+ "schema_ids": [
1436
+ "object/vertex_part_ids/v1"
1437
+ ]
1438
+ }
1439
+ }
1440
+ },
1441
+ "contact_pair": {
1442
+ "path": "annotation/contact/<subject_id>__<object_id>/contact.pt",
1443
+ "entries": {
1444
+ "vertex_region": {
1445
+ "schema_ids": [
1446
+ "contact/vertex_region/v1"
1447
+ ]
1448
+ },
1449
+ "vertex_distance": {
1450
+ "schema_ids": [
1451
+ "contact/vertex_distance/v1"
1452
+ ]
1453
+ }
1454
+ }
1455
+ }
1456
+ },
1457
+ "bundle_layout_rules": {
1458
+ "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.",
1459
+ "entry_leaves": [
1460
+ "data",
1461
+ "valid"
1462
+ ],
1463
+ "additional_entries": false,
1464
+ "all_entries_optional": true,
1465
+ "omit_empty_bundles": true,
1466
+ "identifiers": "object/part/mesh and contact entity IDs must resolve in metadata; reject empty, dot, dot-dot or slash-containing IDs",
1467
+ "per_view": true,
1468
+ "no_cross_object_or_camera_merge": true,
1469
+ "numeric_field_valid_ref_equals_data_ref": true,
1470
+ "attributes_must_be_registered": true
1471
+ },
1472
+ "reference_rules": {
1473
+ "file_paths": {
1474
+ "base": "current camera view root",
1475
+ "format": "relative POSIX",
1476
+ "reject": [
1477
+ "absolute paths",
1478
+ "parent traversal",
1479
+ "external URLs",
1480
+ "unresolved placeholders"
1481
+ ]
1482
+ },
1483
+ "dictionary_keys": {
1484
+ "type": "array",
1485
+ "item_type": "nonempty_string",
1486
+ "min_items": 1,
1487
+ "traversal": "literal nested dictionary lookup; never eval; no automatic flattening",
1488
+ "data_terminal": "data",
1489
+ "valid_terminal": "valid",
1490
+ "target_type": "CPU torch.Tensor"
1491
+ },
1492
+ "bundle_component": {
1493
+ "required": [
1494
+ "data_ref",
1495
+ "data_key",
1496
+ "valid_ref",
1497
+ "valid_key",
1498
+ "storage",
1499
+ "valid_storage"
1500
+ ],
1501
+ "same_file": true,
1502
+ "same_entry_prefix": true,
1503
+ "storage_profile": "pt/tensor_bundle/v1",
1504
+ "valid_storage_profile": "pt/tensor_bundle/v1"
1505
+ },
1506
+ "media_jsonl": {
1507
+ "forbidden": [
1508
+ "data_key",
1509
+ "valid_key"
1510
+ ],
1511
+ "preserve_original_valid_ref": true,
1512
+ "standalone_valid_pt_root": "CPU bool torch.Tensor; not dict",
1513
+ "do_not_label_standalone_valid_as_bundle": true
1514
+ },
1515
+ "camera_distortion": {
1516
+ "models": {
1517
+ "rational8": "camera/distortion8/v1",
1518
+ "opencv_fisheye4": "camera/fisheye4_distortion/v1"
1519
+ },
1520
+ "required": [
1521
+ "distortion_ref",
1522
+ "distortion_key",
1523
+ "distortion_valid_ref",
1524
+ "distortion_valid_key"
1525
+ ],
1526
+ "distortion_ref": "camera/camera.pt",
1527
+ "distortion_key": [
1528
+ "distortion",
1529
+ "data"
1530
+ ],
1531
+ "distortion_valid_ref": "camera/camera.pt",
1532
+ "distortion_valid_key": [
1533
+ "distortion",
1534
+ "valid"
1535
+ ],
1536
+ "valid_equals_intrinsic_valid": true,
1537
+ "models_without_separate_distortion": [
1538
+ "pinhole",
1539
+ "fisheye624"
1540
+ ]
1541
+ },
1542
+ "reader_cache": "Cache bundle by resolved file path; loading different fields must not repeatedly deserialize the file."
1543
+ },
1544
+ "standalone_validity": {
1545
+ "rgb": {
1546
+ "data_ref": "observation/rgb.mkv",
1547
+ "valid_ref": "observation/rgb_valid.pt",
1548
+ "dtype": "bool",
1549
+ "shape": [
1550
+ "T"
1551
+ ],
1552
+ "container": "pt",
1553
+ "root_type": "CPU Tensor"
1554
+ },
1555
+ "segment": {
1556
+ "data_refs": [
1557
+ "annotation/segment/mask.mkv",
1558
+ "annotation/segment/polygons.jsonl"
1559
+ ],
1560
+ "valid_ref": "preserve source release reference; normally annotation/segment/mask_valid.pt",
1561
+ "dtype": "bool",
1562
+ "shape": [
1563
+ "T"
1564
+ ],
1565
+ "container": "pt",
1566
+ "root_type": "CPU Tensor"
1567
+ },
1568
+ "relations": {
1569
+ "data_ref": "annotation/contact/relations.jsonl",
1570
+ "valid_ref": "annotation/contact/relations_valid.pt",
1571
+ "dtype": "bool",
1572
+ "shape": [
1573
+ "T"
1574
+ ],
1575
+ "container": "pt",
1576
+ "root_type": "CPU Tensor"
1577
+ },
1578
+ "depth": {
1579
+ "data_ref": "observation/depth.mkv",
1580
+ "valid_ref": "observation/depth_valid.mkv",
1581
+ "dtype": "bool",
1582
+ "shape": [
1583
+ "T",
1584
+ "H",
1585
+ "W"
1586
+ ],
1587
+ "profile": "mkv/bool_ffv1/v1"
1588
+ }
1589
+ }
1590
+ }
ARCTIC/shared-v1.1/script/arctic_v1_1/validate.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate the adjacent ARCTIC shared-v1.1 tree and fingerprint its current bytes.
2
+
3
+ Adapted from the shared-v1.0 validator: numeric components are read through their
4
+ registered bundle keys instead of one ``.pt`` per component, media/JSONL/mesh
5
+ validity must still be a standalone bool Tensor, and a merged field may not leave a
6
+ standalone ``*_valid.pt`` behind (CONTRACT 6.1, 6.5). ARCTIC's own rules are added
7
+ on top:
8
+
9
+ * nine camera views per sequence, camera ``0`` the ego view and the rest exo, with
10
+ the ego calibration's separate distortion vector paired to the intrinsic validity
11
+ (CONTRACT 3, 5);
12
+ * ``frames.jsonl`` is one row per released image in sync order, and a field indexed
13
+ by it may not claim an annotation on a frame whose ``source_annotation_index`` is
14
+ null -- the release keeps boundary images the official annotations do not cover;
15
+ * a field the release marks ``derived`` cannot be valid where everything it derives
16
+ from is invalid;
17
+ * mesh dependencies and object assets named by the object's own sub-metainfo are
18
+ reported apart from files no metadata names at all.
19
+
20
+ Scope: this checks the released content and layout. It does not independently prove
21
+ official source correctness, and it is not human visual acceptance (CONTRACT 6).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import json
28
+ import shutil
29
+ import sys
30
+ from pathlib import Path, PurePosixPath
31
+
32
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
33
+
34
+ from arctic_common import ( # noqa: E402
35
+ ANNOTATION_INDEX_REF,
36
+ DATASET_ID,
37
+ MANIFEST_PATH,
38
+ REGISTRY,
39
+ RELEASE_ROOT,
40
+ STATUS_FLAGS,
41
+ TMP_ROOT,
42
+ UNKNOWN_CAMERA_MODEL,
43
+ check_camera,
44
+ check_view,
45
+ leftover_numeric,
46
+ load,
47
+ referenced_paths,
48
+ save,
49
+ sha256,
50
+ stray_validity,
51
+ )
52
+ from warehouse import BundleReader, BundleWriter, raw_bytes # noqa: E402
53
+
54
+ CAMERA_IDS = {str(index) for index in range(9)}
55
+ EGO_CAMERA = "0"
56
+ FRAMES_REF = "camera/frames.jsonl"
57
+
58
+
59
+ def release_files():
60
+ """Every file of the release, in path order -- one definition, used twice.
61
+
62
+ Both the report (written before the manifest) and the manifest itself need this
63
+ set. Two filters that could drift apart would let the report name a file count
64
+ the manifest it cites does not have.
65
+ """
66
+ for path in sorted(RELEASE_ROOT.rglob("*")):
67
+ #: bytecode caches are not release content. Nothing else is skipped: the
68
+ #: manifest lives outside the tree, so it never has to exclude itself and the
69
+ #: release's byte total is the manifest's own total.
70
+ if not path.is_file() or ".cache" in path.parts or "__pycache__" in path.parts:
71
+ continue
72
+ yield path
73
+
74
+
75
+ def walk_leaf(tree, prefix=()):
76
+ """Every ``{"data", "valid"}`` leaf of a bundle, keyed by its path."""
77
+ for key, value in tree.items():
78
+ if isinstance(value, dict) and set(value) == {"data", "valid"}:
79
+ yield prefix + (key,), value
80
+ elif isinstance(value, dict):
81
+ yield from walk_leaf(value, prefix + (key,))
82
+
83
+
84
+ def check_frames(view_dir, meta):
85
+ """ARCTIC's frames.jsonl: one row per released image, in sync order.
86
+
87
+ The sync fields are the source's own. ``sync_id`` names the released image,
88
+ ``source_annotation_index`` names the row of the official annotation array the
89
+ frame draws from, and it is null exactly when no source annotation record exists
90
+ for that image -- ARCTIC's selection keeps boundary images whose annotations the
91
+ official release does not include.
92
+ """
93
+ rows = [
94
+ json.loads(line)
95
+ for line in (view_dir / FRAMES_REF).read_text(encoding="utf-8").splitlines()
96
+ if line.strip()
97
+ ]
98
+ assert len(rows) == meta["num_frames"], (view_dir, len(rows), meta["num_frames"])
99
+ sync_ids, frame_ids, annotations, previous_frame = set(), set(), [], None
100
+ for index, row in enumerate(rows):
101
+ assert row["frame_index"] == index, (view_dir, index, row["frame_index"])
102
+ assert row["sync_id"] not in sync_ids, (view_dir, "duplicate sync_id", row["sync_id"])
103
+ sync_ids.add(row["sync_id"])
104
+ assert row["source_frame_id"] not in frame_ids, (view_dir, row["source_frame_id"])
105
+ frame_ids.add(row["source_frame_id"])
106
+ source_frame = int(row["source_frame_id"])
107
+ if previous_frame is not None:
108
+ assert source_frame > previous_frame, (view_dir, "source frames out of order", index)
109
+ previous_frame = source_frame
110
+
111
+ locator = row["source_locator"]
112
+ assert locator["camera_id"] == meta["camera_id"], (
113
+ view_dir,
114
+ index,
115
+ "source_locator.camera_id",
116
+ locator["camera_id"],
117
+ meta["camera_id"],
118
+ )
119
+ if locator.get("member_pattern") == "{camera_id}/{source_frame_id:05d}.jpg":
120
+ assert locator["member"] == f"{locator['camera_id']}/{source_frame:05d}.jpg", (
121
+ view_dir,
122
+ index,
123
+ "source_locator.member",
124
+ locator["member"],
125
+ )
126
+
127
+ present = [
128
+ match
129
+ for match in (row.get("annotation_matches") or {}).values()
130
+ if match.get("source_record_present")
131
+ ]
132
+ annotation_index = row["source_annotation_index"]
133
+ assert (annotation_index is None) == (not present), (
134
+ view_dir,
135
+ index,
136
+ "annotation index must be null exactly when the source has no record",
137
+ )
138
+ if annotation_index is not None:
139
+ assert isinstance(annotation_index, int) and annotation_index >= 0, (
140
+ view_dir,
141
+ index,
142
+ annotation_index,
143
+ )
144
+ annotations.append(annotation_index)
145
+ assert annotations == sorted(set(annotations)), (view_dir, "annotation indices not increasing")
146
+ return rows
147
+
148
+
149
+ def check_annotation_alignment(view_dir, meta, rows, reader):
150
+ """A field may not claim an annotation the source has no record for.
151
+
152
+ Every component declaring ``source_locator.index_ref`` draws its rows from the
153
+ official annotation array, so at a frame whose ``source_annotation_index`` is
154
+ null it must be invalid: validity is the release's statement that a value is
155
+ usable for supervision (``annotation_validity``), and there is nothing to use.
156
+ The converse is deliberately not asserted -- calibration and media stay valid on
157
+ those frames, and a source may mark an annotation unusable for its own reasons.
158
+
159
+ Returns ``(absent, all_invalid, checked)``: the unannotated frames, the frames on
160
+ which every indexed field is invalid, and which components were held to the rule.
161
+ """
162
+ absent = sorted(row["frame_index"] for row in rows if row["source_annotation_index"] is None)
163
+ per_frame, checked = {}, []
164
+ for name, component in meta["components"].items():
165
+ if component.get("source_locator", {}).get("index_ref") != ANNOTATION_INDEX_REF:
166
+ continue
167
+ if "valid_key" not in component:
168
+ continue # a static record carries a scalar validity, not a per-frame claim
169
+ valid = reader.get(view_dir, component["valid_ref"], component["valid_key"])
170
+ assert valid.ndim >= 1 and valid.shape[0] == meta["num_frames"], (name, list(valid.shape))
171
+ flat = valid.reshape(meta["num_frames"], -1)
172
+ for frame in absent:
173
+ assert not bool(flat[frame].any()), (
174
+ name,
175
+ frame,
176
+ "claims an annotation the source has no record for",
177
+ )
178
+ per_frame[name] = flat.any(dim=1)
179
+ checked.append(name)
180
+
181
+ all_invalid = []
182
+ if per_frame:
183
+ for frame in range(meta["num_frames"]):
184
+ if not any(flags[frame] for flags in per_frame.values()):
185
+ all_invalid.append(frame)
186
+ for name, component in meta["components"].items():
187
+ if component.get("provenance", {}).get("kind") != "derived" or "valid_key" not in component:
188
+ continue
189
+ valid = reader.get(view_dir, component["valid_ref"], component["valid_key"])
190
+ flat = valid.reshape(meta["num_frames"], -1)
191
+ for frame in all_invalid:
192
+ assert not bool(flat[frame].any()), (
193
+ name,
194
+ frame,
195
+ "derived field valid where everything it derives from is invalid",
196
+ )
197
+ return absent, all_invalid, checked
198
+
199
+
200
+ def unreferenced(view_dir, meta, consumed):
201
+ """Released files no metadata names, split by whether the registry expects them.
202
+
203
+ Mesh MTL and texture dependencies are named by the OBJ asset itself rather than by
204
+ metadata, and the registry requires them retained beside it
205
+ (``mesh/obj/v1.dependencies``); the object's own sub-metainfo names the remaining
206
+ assets. Everything else is reported rather than asserted -- the registry does not
207
+ enumerate a view's complete file set, so an unknown file is a finding, not a
208
+ failure.
209
+ """
210
+ named = referenced_paths(meta, consumed)
211
+ for sub in sorted(view_dir.glob("annotation/object/*/metainfo.json")):
212
+ for key, value in load(sub).items():
213
+ if key.endswith("_ref") and isinstance(value, str):
214
+ named.add(value)
215
+ named.add(sub.relative_to(view_dir).as_posix())
216
+ asset_dirs = {
217
+ PurePosixPath(component["data_ref"]).parent.as_posix()
218
+ for component in meta["components"].values()
219
+ if component.get("schema_id") == "mesh/obj/v1"
220
+ }
221
+ found = {"dependencies": [], "unreferenced": []}
222
+ for path in sorted(view_dir.rglob("*")):
223
+ if not path.is_file():
224
+ continue
225
+ rel = path.relative_to(view_dir).as_posix()
226
+ if rel == "metainfo.json" or rel in named:
227
+ continue
228
+ bucket = "dependencies" if any(rel.startswith(d + "/") for d in asset_dirs) else "unreferenced"
229
+ found[bucket].append(rel)
230
+ return found
231
+
232
+
233
+ def rewrite_check(view_dir, meta, tmp):
234
+ """Rebuild this view's bundles with the adapted writer and compare leaf bytes.
235
+
236
+ The migration's byte-exactness claim rests on the writer, so re-serialising the
237
+ released tree through it and comparing every leaf back to the released bundle
238
+ exercises that path against published bytes rather than against the converter's
239
+ in-memory values. The camera bundle's distortion entry is written from its own
240
+ references, which no component's ``data_key`` names.
241
+ """
242
+ target = tmp / meta["sequence_id"] / meta["camera_id"]
243
+ if target.exists():
244
+ shutil.rmtree(target)
245
+ reader = BundleReader()
246
+ writers, seen = {}, set()
247
+ for component in meta["components"].values():
248
+ entries = []
249
+ if "data_key" in component:
250
+ entries.append((component["data_ref"], component["data_key"], component["valid_key"]))
251
+ if "distortion_key" in component:
252
+ entries.append(
253
+ (component["distortion_ref"], component["distortion_key"], component["distortion_valid_key"])
254
+ )
255
+ for rel, data_key, valid_key in entries:
256
+ keys = tuple(data_key[:-1])
257
+ if (rel, keys) in seen:
258
+ continue
259
+ seen.add((rel, keys))
260
+ writer = writers.get(rel)
261
+ if writer is None:
262
+ writer = writers[rel] = BundleWriter(target, rel)
263
+ writer.put(list(keys), reader.get(view_dir, rel, data_key), reader.get(view_dir, rel, valid_key))
264
+
265
+ compared = 0
266
+ for rel in sorted(writers):
267
+ writers[rel].save()
268
+ released, rebuilt = reader.bundle(view_dir, rel), BundleReader().bundle(target, rel)
269
+ want, got = dict(walk_leaf(released)), dict(walk_leaf(rebuilt))
270
+ assert set(got) == set(want), (meta["sequence_id"], rel, sorted(got), sorted(want))
271
+ for keys, leaf in want.items():
272
+ for terminal in ("data", "valid"):
273
+ left, right = leaf[terminal], got[keys][terminal]
274
+ assert left.dtype == right.dtype and left.shape == right.shape, (rel, keys, terminal)
275
+ assert raw_bytes(left) == raw_bytes(right), (rel, keys, terminal)
276
+ compared += 1
277
+ return {
278
+ "sequence_id": meta["sequence_id"],
279
+ "camera_id": meta["camera_id"],
280
+ "bundles": sorted(writers),
281
+ "tensors_compared": compared,
282
+ }
283
+
284
+
285
+ def main(argv=None):
286
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
287
+ parser.add_argument("--views", nargs="*", default=None, help="restrict to these sequences")
288
+ parser.add_argument("--limit", type=int, default=None, help="validate at most N views")
289
+ parser.add_argument("--expect-views", type=int, default=None, metavar="N",
290
+ help="fail unless exactly N views are released")
291
+ parser.add_argument("--rewrite-check", type=int, default=0, metavar="N",
292
+ help="also re-serialise N views with the adapted writer and compare field bytes")
293
+ parser.add_argument("--report", type=Path, default=RELEASE_ROOT / "doc/validation/validate_report.json")
294
+ parser.add_argument("--no-manifest", action="store_true",
295
+ help=f"do not rebuild the release manifest ({MANIFEST_PATH}). It "
296
+ "hashes the whole release tree whatever --views says, so an "
297
+ "incremental check would pay minutes for a manifest the final "
298
+ "run overwrites anyway. The accepting run must not pass this "
299
+ "(CONTRACT 6.4).")
300
+ args = parser.parse_args(argv)
301
+
302
+ views = sorted((RELEASE_ROOT / "data").glob("*/*/metainfo.json"))
303
+ if args.views:
304
+ wanted = set(args.views)
305
+ views = [view for view in views if view.parent.parent.name in wanted]
306
+ if args.limit:
307
+ views = views[: args.limit]
308
+
309
+ counts, sequences, flags, gaps, assets = {}, {}, {}, {}, {"dependencies": {}, "unreferenced": {}}
310
+ models, uncalibrated = {}, []
311
+ frames_total, files_total = 0, 0
312
+ rewrites = []
313
+ for position, path in enumerate(views, 1):
314
+ view_dir, meta = path.parent, load(path)
315
+ sequence, camera_id = meta["sequence_id"], meta["camera_id"]
316
+ if position % 200 == 1 or position == len(views):
317
+ print(f" view {position}/{len(views)}: {view_dir.relative_to(RELEASE_ROOT)}", flush=True)
318
+
319
+ for key in ("dataset_id", "split_scheme", "split_source_locator", "sampling", "camera",
320
+ "components", "view_type"):
321
+ assert key in meta, (path, key)
322
+ assert meta["dataset_id"] == DATASET_ID, (path, meta["dataset_id"])
323
+ assert camera_id in CAMERA_IDS, (path, camera_id)
324
+ assert meta["view_type"] == ("ego" if camera_id == EGO_CAMERA else "exo"), (
325
+ path,
326
+ camera_id,
327
+ meta["view_type"],
328
+ )
329
+ assert meta["sampling"].get("frames_ref") == FRAMES_REF, (path, meta["sampling"].get("frames_ref"))
330
+ assert meta["sampling"]["type"] in REGISTRY.schema["sampling"]["video"]["sampling_types"], (
331
+ path,
332
+ meta["sampling"]["type"],
333
+ )
334
+ #: camera models are counted rather than assumed: the P1 test sequences
335
+ #: publish no ego calibration and declare model=unknown with no intrinsic,
336
+ #: which the rule accepts as a declared state, not as a missing field
337
+ state = check_camera(view_dir, meta, REGISTRY)
338
+ models[state["model"]] = models.get(state["model"], 0) + 1
339
+ if state["model"] == UNKNOWN_CAMERA_MODEL:
340
+ uncalibrated.append(f"{sequence}/{camera_id}")
341
+ rows = check_frames(view_dir, meta)
342
+ reader = BundleReader() # one view at a time: the cache must not span the release
343
+ consumed, fields, notes = check_view(view_dir, meta, REGISTRY, reader)
344
+ for note in notes:
345
+ gaps.setdefault(json.dumps(note, sort_keys=True), note)
346
+ check_annotation_alignment(view_dir, meta, rows, reader)
347
+
348
+ present = sorted(p.relative_to(view_dir).as_posix() for p in view_dir.rglob("*") if p.is_file())
349
+ stray = [rel for rel in present if stray_validity(REGISTRY, rel)]
350
+ assert not stray, (view_dir, "merged numeric fields left standalone validity files", stray)
351
+ leftover = [rel for rel in present if leftover_numeric(REGISTRY, rel)]
352
+ assert not leftover, (view_dir, "v1.0 standalone numeric files survived", leftover)
353
+ census = unreferenced(view_dir, meta, consumed)
354
+ for bucket, paths in census.items():
355
+ for rel in paths:
356
+ assets[bucket][rel] = assets[bucket].get(rel, 0) + 1
357
+
358
+ counts[meta["split"]] = counts.get(meta["split"], 0) + 1
359
+ sequences.setdefault(sequence, set()).add(camera_id)
360
+ for flag in STATUS_FLAGS:
361
+ flags.setdefault(flag, set()).add(json.dumps(meta.get(flag), ensure_ascii=False))
362
+ frames_total += meta["num_frames"]
363
+ files_total += len(present)
364
+ if len(rewrites) < args.rewrite_check:
365
+ rewrites.append(rewrite_check(view_dir, meta, TMP_ROOT / "rewrite-check"))
366
+
367
+ if not (args.views or args.limit):
368
+ for sequence, cameras in sorted(sequences.items()):
369
+ assert cameras == CAMERA_IDS, (sequence, sorted(cameras))
370
+ if args.expect_views is not None:
371
+ assert len(views) == args.expect_views, (len(views), args.expect_views)
372
+ #: ARCTIC's status flags are per-view claims and the release is NOT uniform:
373
+ #: ``media_validation_policy`` is null on some sequences and a policy string on
374
+ #: others, and that is the v1.0 content, not a migration defect. That each view
375
+ #: kept its own value verbatim is verify.py's check (it compares the whole
376
+ #: metainfo against the v1.0 source); here the values are recorded and printed,
377
+ #: so a surprising distribution is visible instead of being asserted away.
378
+ #: sorted as JSON text: a null value and a string cannot be compared directly
379
+ varying = {flag: [json.loads(value) for value in sorted(values)]
380
+ for flag, values in sorted(flags.items()) if len(values) > 1}
381
+ for flag, values in sorted(varying.items()):
382
+ print(f" note: {flag} declares {len(values)} values across the release: {values}")
383
+
384
+ result = {
385
+ "passed": True,
386
+ "dataset_id": DATASET_ID,
387
+ "schema_version": REGISTRY.schema["view_metadata"]["schema_version"],
388
+ "release_id": REGISTRY.schema["view_metadata"]["release_id"],
389
+ "schema_sha256": sha256(RELEASE_ROOT / "doc/schema.json"),
390
+ "views": len(views),
391
+ "sequences": len(sequences),
392
+ "counts_by_split": dict(sorted(counts.items())),
393
+ "num_frames": frames_total,
394
+ "released_files": files_total,
395
+ "cameras_per_sequence": 9,
396
+ "camera_models": dict(sorted(models.items())),
397
+ "uncalibrated_views": uncalibrated,
398
+ "status_flags": {flag: [json.loads(value) for value in sorted(values)]
399
+ for flag, values in sorted(flags.items())},
400
+ "status_flags_varying": sorted(varying),
401
+ "registry_gaps": [gaps[key] for key in sorted(gaps)],
402
+ "meshes_dependencies": sorted(assets["dependencies"]),
403
+ "meshes_dependency_views": assets["dependencies"],
404
+ "unreferenced_files": sorted(assets["unreferenced"]),
405
+ "unreferenced_file_views": assets["unreferenced"],
406
+ "rewrite_check": rewrites,
407
+ "scope": "released content and layout; does not independently prove official source "
408
+ "correctness or visual quality",
409
+ }
410
+ #: The tmp copy is a convenience for the migration loop, and its *name* is load
411
+ #: bearing. It must not be "acceptance.json": the documented chain writes
412
+ #: verify.py's byte-level acceptance report to tmp/arctic-tools/acceptance.json,
413
+ #: so a structural report saved under that name silently destroys the evidence
414
+ #: FULL_MIGRATION_SUMMARY.json is built from -- which is exactly what happened
415
+ #: once, and cost a re-run of the whole acceptance to recover.
416
+ save(TMP_ROOT / "validate-latest.json", result)
417
+ save(args.report, result)
418
+
419
+ if args.no_manifest:
420
+ #: reported as skipped rather than as a manifest of 0 files, which would
421
+ #: read like an empty release
422
+ result["release_manifest"] = {"skipped": "incremental check; not an acceptance run",
423
+ "path": str(MANIFEST_PATH)}
424
+ save(TMP_ROOT / "validate-latest.json", result)
425
+ save(args.report, result)
426
+ print(json.dumps(result, ensure_ascii=False, indent=2))
427
+ return 0 if result["passed"] else 1
428
+
429
+ #: Named, and counted, here -- before the manifest is rebuilt -- because the
430
+ #: manifest has to cover this report's final bytes, so the report cannot carry the
431
+ #: manifest's digest. The count is exact all the same: nothing adds or removes a
432
+ #: release file between this walk and the hash pass below.
433
+ result["release_manifest"] = {
434
+ "path": str(MANIFEST_PATH),
435
+ "in_release_tree": False,
436
+ "files": sum(1 for _ in release_files()),
437
+ "note": "rebuilt by this run after this report was written, so it covers the "
438
+ "report's final bytes; kept outside the release because a manifest "
439
+ "inside it cannot hash itself",
440
+ }
441
+ save(TMP_ROOT / "validate-latest.json", result)
442
+ save(args.report, result)
443
+
444
+ manifest = []
445
+ for path in release_files():
446
+ rel = path.relative_to(RELEASE_ROOT).as_posix()
447
+ manifest.append({"path": rel, "size": path.stat().st_size, "sha256": sha256(path)})
448
+ payload = {
449
+ "release": REGISTRY.schema["view_metadata"]["release_id"],
450
+ "scope": result["scope"],
451
+ "location": f"{MANIFEST_PATH} (outside the release tree, as in the published "
452
+ "H2O and dex-ycb sets)",
453
+ "excludes": ["__pycache__/"],
454
+ "files": manifest,
455
+ "bytes": sum(entry["size"] for entry in manifest),
456
+ }
457
+ save(MANIFEST_PATH, payload)
458
+
459
+ print(json.dumps(result, ensure_ascii=False, indent=2))
460
+ return 0
461
+
462
+
463
+ if __name__ == "__main__":
464
+ raise SystemExit(main())
ARCTIC/shared-v1.1/script/arctic_v1_1/verify.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Acceptance checks for a shared-v1.0 -> shared-v1.1 migration (CONTRACT 6).
3
+
4
+ Compares the migrated tree against the source it came from, so every claim is
5
+ checked against real bytes rather than re-asserted from the migrator:
6
+
7
+ 1. every component/attribute and its dictionary keys resolve; no stray files, no
8
+ missing keys, no unregistered fields; merged numeric components leave no
9
+ standalone ``*_valid.pt``; media/JSONL validity files survive untouched
10
+ 2. every numeric field is identical to its source in dtype, shape, element-wise
11
+ values, NaN positions and bool validity, compared as a unified contiguous byte
12
+ view with no tolerance
13
+ 3. ``num_frames``, sampling, hand slots, split, camera, view type, provenance and
14
+ ``valid_policy`` are unchanged -- the metainfo diff must equal the allowed set
15
+ 4. media and other preserved files match their source digests; the release
16
+ manifest is regenerated because merged ``.pt`` digests necessarily changed
17
+ 5. the new reader resolves RGB, camera and every annotation present on
18
+ representative complete sequences
19
+
20
+ The report distinguishes "repackaging is numerically identical" from "human
21
+ visual acceptance"; this tool produces evidence for the former only.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import json
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ import torch
32
+
33
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
34
+
35
+ from warehouse import ( # noqa: E402
36
+ BundleReader,
37
+ Registry,
38
+ same_tensor,
39
+ sha256_file,
40
+ )
41
+
42
+ #: this package lives in <dataset>/shared-v1.1/script/arctic_v1_1, so the release
43
+ #: and the dataset root beside it need no arguments.
44
+ RELEASE_ROOT = Path(__file__).resolve().parent.parent.parent
45
+ DATASET_ROOT = RELEASE_ROOT.parent
46
+ #: Where ``--manifest`` writes. The release manifest is a publication artifact and
47
+ #: lives *outside* the release tree: a manifest inside it could not hash its own final
48
+ #: bytes. ``arctic_common.MANIFEST_PATH`` holds the same path -- keep the two in step;
49
+ #: validate.py is what the documented chain rebuilds the shipping manifest with.
50
+ MANIFEST_PATH = DATASET_ROOT / "tmp" / "arctic-tools" / "PUBLISH_MANIFEST.json"
51
+
52
+ V10_SCHEMA_VERSION = "hand-warehouse/1.0"
53
+ #: metainfo keys the migration is allowed to rewrite at the top level. Everything
54
+ #: else is a claim the source made and must survive verbatim -- ARCTIC's release
55
+ #: status flags, the omitted-component reasons, the split bookkeeping. The version
56
+ #: keys change by definition, and ``components`` changes wherever a numeric field
57
+ #: joins a bundle.
58
+ ALLOWED_TOP_LEVEL_CHANGES = {"schema_version", "release_id", "components"}
59
+ #: component fields the migration adds when a numeric field joins a bundle
60
+ BUNDLE_FIELDS = {"data_key", "valid_key", "storage", "valid_storage"}
61
+ #: component fields that must survive any migration untouched
62
+ PRESERVED_FIELDS = ("provenance", "source_locator", "valid_policy", "axes", "valid_axes")
63
+
64
+
65
+ class Failure(Exception):
66
+ pass
67
+
68
+
69
+ def check(condition, message):
70
+ if not condition:
71
+ raise Failure(message)
72
+
73
+
74
+ def flatten(value, prefix=""):
75
+ """Flatten a JSON object into dotted leaf paths."""
76
+ if isinstance(value, dict):
77
+ out = {}
78
+ for key, item in value.items():
79
+ out.update(flatten(item, f"{prefix}{key}."))
80
+ return out
81
+ if isinstance(value, list) and value and not isinstance(value[0], (dict, list)):
82
+ return {prefix[:-1]: json.dumps(value)}
83
+ return {prefix[:-1]: json.dumps(value)}
84
+
85
+
86
+ def is_stray_validity(registry: Registry, rel: str) -> bool:
87
+ """True when a standalone ``*_valid.pt`` belongs to a field that was merged.
88
+
89
+ Catches the failure CONTRACT 6.1 names explicitly: a numeric component's
90
+ validity left behind as its own file because its name was not recognised.
91
+ """
92
+ if not rel.endswith("_valid.pt"):
93
+ return False
94
+ return registry.resolve(rel[: -len("_valid.pt")] + ".pt") is not None
95
+
96
+
97
+ def compare_metainfo(source: dict, target: dict, sequence: str, camera: str):
98
+ """Assert the metainfo diff is exactly the storage-layout change set."""
99
+ where = f"{sequence}/{camera}"
100
+ check(source["schema_version"] == V10_SCHEMA_VERSION,
101
+ f"{where}: source is not {V10_SCHEMA_VERSION}")
102
+ for key in ("num_frames", "sampling", "hand_slots", "split", "camera",
103
+ "view_type", "dataset_id", "sequence_id", "camera_id", "sample_type"):
104
+ check(source.get(key) == target.get(key),
105
+ f"{where}: {key} changed ({source.get(key)!r} -> {target.get(key)!r})")
106
+ check(target["schema_version"] == "hand-warehouse/1.1", f"{where}: schema_version not bumped")
107
+ check(target["release_id"] == "shared-v1.1", f"{where}: release_id not bumped")
108
+
109
+ #: every remaining top level key, compared to this view's own source rather than
110
+ #: to a constant: ARCTIC's release status flags are per-view claims and are NOT
111
+ #: uniform across the release (``media_validation_policy`` is null on some
112
+ #: sequences and a policy string on others), so "unchanged" has to mean
113
+ #: unchanged against the v1.0 bytes, not equal to one expected value.
114
+ for key in sorted(set(source) | set(target)):
115
+ if key in ALLOWED_TOP_LEVEL_CHANGES:
116
+ continue
117
+ check(key in source and key in target,
118
+ f"{where}: top level key {key!r} exists on only one side")
119
+ check(source[key] == target[key],
120
+ f"{where}: {key} changed ({source[key]!r} -> {target[key]!r})")
121
+
122
+ source_components = source["components"]
123
+ target_components = target["components"]
124
+ check(set(source_components) == set(target_components),
125
+ f"{where}: component set changed")
126
+
127
+ for name, before in source_components.items():
128
+ after = target_components[name]
129
+ for key in PRESERVED_FIELDS:
130
+ check(before.get(key) == after.get(key),
131
+ f"{where}/{name}: {key} changed")
132
+ check(before.get("schema_id") == after.get("schema_id"),
133
+ f"{where}/{name}: schema_id changed")
134
+ check(before.get("available") == after.get("available"),
135
+ f"{where}/{name}: availability changed")
136
+ # attributes (e.g. visibility) follow the same rules as components
137
+ before_attributes = before.get("attributes") or {}
138
+ after_attributes = after.get("attributes") or {}
139
+ check(set(before_attributes) == set(after_attributes),
140
+ f"{where}/{name}: attribute set changed")
141
+ for attribute, before_attribute in before_attributes.items():
142
+ after_attribute = after_attributes[attribute]
143
+ for key in ("axes", "dtype", "visibility_type", "meaning", "provenance",
144
+ "source_locator"):
145
+ check(before_attribute.get(key) == after_attribute.get(key),
146
+ f"{where}/{name}.{attribute}: {key} changed")
147
+ if "data_key" in after_attribute:
148
+ check(before_attribute.get("valid") is True,
149
+ f"{where}/{name}.{attribute}: bundled without a declared all-known scalar")
150
+ check("valid" not in after_attribute,
151
+ f"{where}/{name}.{attribute}: scalar valid must give way to valid_key")
152
+ check(after_attribute["data_ref"] == after_attribute["valid_ref"],
153
+ f"{where}/{name}.{attribute}: data_ref and valid_ref must share a file")
154
+
155
+
156
+ def verify_distortion(registry, v10_view, v11_view, reader, name, source_component,
157
+ target_component, where, consumed):
158
+ """CONTRACT 5/3: the separate distortion vector joins the camera's own bundle.
159
+
160
+ v1.0 declares it on the component that owns the calibration, with no validity
161
+ of its own: the camera model pairs the distortion vector with the intrinsic
162
+ validity, so the two fields must carry the same bool values. Returns the
163
+ field record, or ``None`` when the component declares no distortion.
164
+ """
165
+ ref = source_component.get("distortion_ref")
166
+ if not ref:
167
+ return None
168
+ resolved = registry.resolve(ref)
169
+ if resolved is None:
170
+ check(target_component.get("distortion_ref") == ref,
171
+ f"{where}/{name}: distortion_ref changed for a preserved file")
172
+ check((v10_view / ref).read_bytes() == (v11_view / ref).read_bytes(),
173
+ f"{where}/{name}: preserved distortion {ref} differs")
174
+ consumed.add(ref)
175
+ return None
176
+ bundle_rel, keys, _ = resolved
177
+ check(target_component.get("distortion_ref") == bundle_rel
178
+ and target_component.get("distortion_valid_ref") == bundle_rel,
179
+ f"{where}/{name}: distortion refs must point at the camera bundle")
180
+ check(target_component.get("distortion_key") == keys + ["data"],
181
+ f"{where}/{name}: distortion_key mismatch")
182
+ check(target_component.get("distortion_valid_key") == keys + ["valid"],
183
+ f"{where}/{name}: distortion_valid_key mismatch")
184
+
185
+ data = reader.get(v11_view, bundle_rel, keys + ["data"])
186
+ valid = reader.get(v11_view, bundle_rel, keys + ["valid"])
187
+ check(valid.dtype == torch.bool, f"{where}/{name}: distortion valid is not bool")
188
+ check(same_tensor(torch.load(v10_view / ref, map_location="cpu", weights_only=True), data),
189
+ f"{where}/{name}: distortion is not byte-identical")
190
+
191
+ valid_ref = source_component.get("distortion_valid_ref")
192
+ if valid_ref:
193
+ check(same_tensor(torch.load(v10_view / valid_ref, map_location="cpu",
194
+ weights_only=True), valid),
195
+ f"{where}/{name}: distortion valid is not byte-identical")
196
+ consumed.add(valid_ref)
197
+ origin = f"source tensor {valid_ref}"
198
+ else:
199
+ # CONTRACT 3: with no validity of its own, the distortion vector either
200
+ # shares the owning component's validity or expands a declared all-known
201
+ # scalar. Both are checked against the source rather than re-asserted.
202
+ owner_valid_ref = source_component.get("valid_ref")
203
+ paired = (torch.load(v10_view / owner_valid_ref, map_location="cpu", weights_only=True)
204
+ if owner_valid_ref else None)
205
+ shared = (paired is not None and list(paired.shape) == list(valid.shape)
206
+ and same_tensor(paired, valid))
207
+ check(shared or bool(valid.all()),
208
+ f"{where}/{name}: distortion validity matches neither the paired camera "
209
+ f"validity nor a declared all-known scalar")
210
+ origin = ("shared with intrinsic validity (CONTRACT 3)" if shared
211
+ else "expanded declared all-known scalar (CONTRACT 3)")
212
+ consumed.add(ref)
213
+ return {
214
+ "owner": f"{name}.distortion", "entry": f"{bundle_rel}:{'/'.join(keys)}",
215
+ "dtype": str(data.dtype), "shape": list(data.shape),
216
+ "valid_shape": list(valid.shape),
217
+ "valid_true": int(valid.sum()), "valid_false": int((~valid).sum()),
218
+ "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None,
219
+ "valid_origin": origin, "byte_exact": True,
220
+ }
221
+
222
+
223
+ def same_bytes(left: Path, right: Path) -> tuple:
224
+ """``(same, how)`` for two paths: the same file, or the same bytes.
225
+
226
+ Migration hardlinks media, so in the common case these are one inode and the
227
+ answer is structural. Reading ~300 MiB twice to compare a file with itself
228
+ proves nothing and costs the run -- ARCTIC's tree is 737 GiB, so that read was
229
+ most of the acceptance time. When the inodes differ -- a tree that was *copied*
230
+ rather than linked -- the bytes are hashed in streams, so nothing is assumed
231
+ equal merely because the migration usually links.
232
+
233
+ ``how`` travels into the report, so a reader can see which files were settled by
234
+ identity and which by content instead of having to trust that either ran.
235
+ """
236
+ left_stat, right_stat = left.stat(), right.stat()
237
+ if (left_stat.st_dev, left_stat.st_ino) == (right_stat.st_dev, right_stat.st_ino):
238
+ return True, "same inode"
239
+ if left_stat.st_size != right_stat.st_size:
240
+ return False, "size differs"
241
+ return sha256_file(left) == sha256_file(right), "sha256"
242
+
243
+
244
+ def verify_view(registry, v10_view, v11_view, reader):
245
+ """Run CONTRACT 6 checks for one view; return its evidence record."""
246
+ where = f"{v10_view.parent.name}/{v10_view.name}"
247
+ source = json.loads((v10_view / "metainfo.json").read_text(encoding="utf-8"))
248
+ target = json.loads((v11_view / "metainfo.json").read_text(encoding="utf-8"))
249
+ compare_metainfo(source, target, v10_view.parent.name, v10_view.name)
250
+
251
+ consumed, fields, media = set(), [], []
252
+ for name, component in source["components"].items():
253
+ if not component.get("available", True):
254
+ continue
255
+ for owner, spec, kind in [(name, component, "component")] + [
256
+ (f"{name}.{attribute}", attribute_spec, "attribute")
257
+ for attribute, attribute_spec in (component.get("attributes") or {}).items()
258
+ ]:
259
+ ref = spec.get("data_ref")
260
+ if not ref:
261
+ continue
262
+ resolved = registry.resolve(ref)
263
+ after = (target["components"][name] if kind == "component"
264
+ else target["components"][name]["attributes"][owner.split(".", 1)[1]])
265
+ if resolved is None:
266
+ # preserved verbatim: same reference, same bytes
267
+ check(after.get("data_ref") == ref, f"{where}/{owner}: data_ref changed for a media file")
268
+ check("data_key" not in after, f"{where}/{owner}: media must not carry data_key")
269
+ same, how = same_bytes(v10_view / ref, v11_view / ref)
270
+ check(same, f"{where}/{owner}: preserved file {ref} differs")
271
+ valid_ref = spec.get("valid_ref")
272
+ valid_how = None
273
+ if valid_ref:
274
+ check(after.get("valid_ref") == valid_ref,
275
+ f"{where}/{owner}: media valid_ref changed")
276
+ check("valid_key" not in after, f"{where}/{owner}: media must not carry valid_key")
277
+ same, valid_how = same_bytes(v10_view / valid_ref, v11_view / valid_ref)
278
+ check(same, f"{where}/{owner}: preserved validity {valid_ref} differs")
279
+ media.append({"owner": owner, "data_ref": ref, "valid_ref": valid_ref,
280
+ "verified": how, "valid_verified": valid_how})
281
+ continue
282
+
283
+ bundle_rel, keys, entry = resolved
284
+ check(after["data_ref"] == bundle_rel and after["valid_ref"] == bundle_rel,
285
+ f"{where}/{owner}: bundled refs must be the same file")
286
+ check(after["data_key"] == keys + ["data"], f"{where}/{owner}: data_key mismatch")
287
+ check(after["valid_key"] == keys + ["valid"], f"{where}/{owner}: valid_key mismatch")
288
+ for key in ("storage", "valid_storage"):
289
+ check(after[key]["profile"] == "pt/tensor_bundle/v1",
290
+ f"{where}/{owner}: {key} profile must be pt/tensor_bundle/v1")
291
+
292
+ data, valid = reader.field(v11_view, after)
293
+ check(valid.dtype == torch.bool, f"{where}/{owner}: valid is not bool")
294
+ if kind == "attribute":
295
+ check(after.get("valid_axes") == list(after["axes"])[:valid.ndim],
296
+ f"{where}/{owner}: valid_axes must be axes[:valid.ndim]")
297
+ check(after.get("valid_ref") == after.get("data_ref"),
298
+ f"{where}/{owner}: visibility must share one bundle file")
299
+ source_data = torch.load(v10_view / ref, map_location="cpu", weights_only=True)
300
+ check(same_tensor(source_data, data), f"{where}/{owner}: data is not byte-identical")
301
+ source_valid_ref = spec.get("valid_ref")
302
+ if source_valid_ref:
303
+ source_valid = torch.load(v10_view / source_valid_ref,
304
+ map_location="cpu", weights_only=True)
305
+ check(same_tensor(source_valid, valid), f"{where}/{owner}: valid is not byte-identical")
306
+ origin = f"source tensor {source_valid_ref}"
307
+ consumed.add(source_valid_ref)
308
+ else:
309
+ check(spec.get("valid") is True,
310
+ f"{where}/{owner}: no valid_ref and no declared all-known scalar")
311
+ check(bool(valid.all()),
312
+ f"{where}/{owner}: expanded all-known validity must be all true")
313
+ origin = "expanded declared all-known scalar"
314
+ consumed.add(ref)
315
+ fields.append({
316
+ "owner": owner, "entry": f"{bundle_rel}:{'/'.join(keys)}",
317
+ "dtype": str(data.dtype), "shape": list(data.shape),
318
+ "valid_shape": list(valid.shape),
319
+ "valid_true": int(valid.sum()), "valid_false": int((~valid).sum()),
320
+ "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None,
321
+ "valid_origin": origin, "byte_exact": True,
322
+ })
323
+ distortion = verify_distortion(registry, v10_view, v11_view, reader, name,
324
+ component, target["components"][name], where, consumed)
325
+ if distortion is not None:
326
+ fields.append(distortion)
327
+
328
+ # 1: no stray files, nothing lost
329
+ source_files = {p.relative_to(v10_view).as_posix()
330
+ for p in v10_view.rglob("*") if p.is_file()}
331
+ target_files = {p.relative_to(v11_view).as_posix()
332
+ for p in v11_view.rglob("*") if p.is_file()}
333
+ expected = (source_files - consumed - {"metainfo.json"}) | {"metainfo.json"} | {
334
+ f["entry"].split(":")[0] for f in fields}
335
+ check(target_files == expected,
336
+ f"{where}: file set mismatch; unexpected={sorted(target_files - expected)}, "
337
+ f"missing={sorted(expected - target_files)}")
338
+ strays = sorted(f for f in target_files if is_stray_validity(registry, f))
339
+ check(not strays, f"{where}: merged numeric fields left standalone validity files: {strays}")
340
+
341
+ return {
342
+ "sequence_id": v10_view.parent.name, "camera_id": v10_view.name,
343
+ "num_frames": source["num_frames"],
344
+ "source_files": len(source_files), "target_files": len(target_files),
345
+ "merged_fields": len(fields), "preserved_files": len(media),
346
+ "media_verified_by": {how: sum(1 for m in media if m["verified"] == how)
347
+ for how in sorted({m["verified"] for m in media})},
348
+ "fields": fields, "media": media,
349
+ }
350
+
351
+
352
+ def main(argv=None):
353
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
354
+ parser.add_argument("--v10", type=Path, default=DATASET_ROOT / "shared-v1.0",
355
+ help="shared-v1.0 release directory")
356
+ parser.add_argument("--v11", type=Path, default=RELEASE_ROOT,
357
+ help="shared-v1.1 release directory")
358
+ parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json",
359
+ help="v1.1 schema.json")
360
+ parser.add_argument("--manifest", type=Path, default=MANIFEST_PATH,
361
+ help=f"write the v1.1 release manifest here (default: "
362
+ f"{MANIFEST_PATH}, outside the release tree)")
363
+ parser.add_argument("--report", type=Path, help="write the acceptance report here")
364
+ parser.add_argument("--sample", type=int, default=None,
365
+ help="verify at most N views (default: all migrated)")
366
+ parser.add_argument("--views", nargs="*", default=None,
367
+ help="restrict to these sequence ids")
368
+ parser.add_argument("--complete", action="store_true",
369
+ help="fail when a source view has no migrated counterpart")
370
+ parser.add_argument("--no-manifest", action="store_true",
371
+ help="skip regenerating the release manifest (CONTRACT 6.4). It "
372
+ "hashes every file of the tree regardless of --views, so an "
373
+ "incremental check while the pull is still running pays "
374
+ "minutes for a manifest the final run overwrites anyway. "
375
+ "The accepting run passes this as well: the manifest has to "
376
+ "be the last thing built, because it must cover this "
377
+ "release's own FULL_MIGRATION_SUMMARY.json and its rebuilt "
378
+ "doc/*.md, which are written after the acceptance -- "
379
+ "validate.py regenerates it at the end, so a manifest built "
380
+ "here would be overwritten unread. CONTRACT 6.4 asks that the "
381
+ "manifest be regenerated and correct, not that this tool be "
382
+ "the one to write it.")
383
+ args = parser.parse_args(argv)
384
+
385
+ registry = Registry.load(args.schema)
386
+ reader = BundleReader()
387
+ source_views = sorted(p.parent for p in (args.v10 / "data").glob("*/*/metainfo.json"))
388
+ target_data = args.v11 / "data"
389
+ migrated, absent = [], []
390
+ for view in source_views:
391
+ relative = view.relative_to(args.v10 / "data")
392
+ (migrated if (target_data / relative / "metainfo.json").is_file() else absent).append(view)
393
+ if args.views:
394
+ wanted = set(args.views)
395
+ migrated = [v for v in migrated if v.parent.name in wanted]
396
+ if args.sample:
397
+ migrated = migrated[:args.sample]
398
+
399
+ report = {"source": str(args.v10.resolve()), "target": str(args.v11.resolve()),
400
+ "schema_sha256": sha256_file(args.schema), "views": [], "failures": [],
401
+ "views_in_source": len(source_views), "views_migrated": len(migrated),
402
+ "views_absent_from_target": [v.relative_to(args.v10 / "data").as_posix()
403
+ for v in absent]}
404
+ if args.complete:
405
+ for view in absent:
406
+ rel = view.relative_to(args.v10 / "data").as_posix()
407
+ report["failures"].append({"view": rel, "error": "view was not migrated"})
408
+ print(f"FAIL {rel}: view was not migrated", file=sys.stderr)
409
+ for view in migrated:
410
+ relative = view.relative_to(args.v10 / "data")
411
+ target_view = target_data / relative
412
+ try:
413
+ report["views"].append(verify_view(registry, view, target_view, reader))
414
+ except Failure as error:
415
+ report["failures"].append({"view": relative.as_posix(), "error": str(error)})
416
+ print(f"FAIL {relative}: {error}", file=sys.stderr)
417
+
418
+ # 4: regenerated release manifest
419
+ if args.no_manifest:
420
+ #: reported as skipped, not as "0 files" -- an empty manifest in the report
421
+ #: would read like a tree with nothing in it
422
+ report["manifest"] = {"skipped": "incremental check; not an acceptance run"}
423
+ else:
424
+ manifest = {}
425
+ #: The manifest normally lives outside the release (see MANIFEST_PATH), so it
426
+ #: is not part of the tree being hashed and there is nothing to exclude. Only
427
+ #: a ``--manifest`` pointed *into* the release has to be skipped: it cannot hash
428
+ #: itself without recording the digest it is about to have.
429
+ try:
430
+ manifest_rel = args.manifest.relative_to(args.v11).as_posix()
431
+ except ValueError:
432
+ manifest_rel = None
433
+ for path in sorted(args.v11.rglob("*")):
434
+ rel = path.relative_to(args.v11).as_posix()
435
+ if "__pycache__" in path.parts or rel == manifest_rel:
436
+ continue
437
+ if path.is_file():
438
+ manifest[rel] = {"size": path.stat().st_size, "sha256": sha256_file(path)}
439
+ report["manifest"] = {"files": len(manifest),
440
+ "bytes": sum(v["size"] for v in manifest.values()),
441
+ "excludes": [x for x in (manifest_rel, "__pycache__/") if x]}
442
+ if args.manifest:
443
+ args.manifest.parent.mkdir(parents=True, exist_ok=True)
444
+ args.manifest.write_text(
445
+ json.dumps({"release": "shared-v1.1",
446
+ "location": str(args.manifest),
447
+ "in_release_tree": manifest_rel is not None,
448
+ "files": manifest},
449
+ ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
450
+
451
+ report["passed"] = not report["failures"]
452
+ report["scope"] = ("repackaging numerically identical; this is not human visual acceptance")
453
+ if args.report:
454
+ args.report.parent.mkdir(parents=True, exist_ok=True)
455
+ args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n",
456
+ encoding="utf-8")
457
+
458
+ total_fields = sum(v["merged_fields"] for v in report["views"])
459
+ media_modes = {}
460
+ for view in report["views"]:
461
+ for mode, count in view["media_verified_by"].items():
462
+ media_modes[mode] = media_modes.get(mode, 0) + count
463
+ print(f"views={len(report['views'])} merged_fields={total_fields} "
464
+ f"failures={len(report['failures'])} "
465
+ + (f"manifest_files={report['manifest']['files']}"
466
+ if "files" in report["manifest"] else "manifest=skipped")
467
+ + f" media_verified_by={media_modes}")
468
+ print("ACCEPTANCE_PASS" if report["passed"] else "ACCEPTANCE_FAIL")
469
+ return 0 if report["passed"] else 1
470
+
471
+
472
+ if __name__ == "__main__":
473
+ raise SystemExit(main())
ARCTIC/shared-v1.1/script/arctic_v1_1/warehouse.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hand-warehouse v1.1 tensor-bundle layout: resolution, writing, cached reading.
2
+
3
+ The v1.1 registry (`doc/schema.json`) is declarative; its own `note` says runtime
4
+ readers/converters/validators still require adaptation. This module is that
5
+ adaptation for the parts every dataset shares:
6
+
7
+ * ``Registry.resolve()`` v1.0 ``data_ref`` -> (bundle file, entry key path)
8
+ * ``BundleWriter`` builds one nested ``{"data": Tensor, "valid": Bool}`` tree
9
+ * ``BundleReader`` loads a bundle once, then fetches fields by key
10
+ * ``expanded_all_known()`` CONTRACT 3 expansion of a declared all-known scalar
11
+
12
+ Section references are to ``doc/CONTRACT.md`` (hand-warehouse/1.1).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import json
19
+ import os
20
+ from pathlib import Path, PurePosixPath
21
+
22
+ import torch
23
+
24
+ SCHEMA_VERSION = "hand-warehouse/1.1"
25
+ RELEASE_ID = "shared-v1.1"
26
+ BUNDLE_PROFILE = "pt/tensor_bundle/v1"
27
+ DATA_TERMINAL = "data"
28
+ VALID_TERMINAL = "valid"
29
+
30
+ #: CONTRACT 3: axes declared on the three visibility scopes.
31
+ VISIBILITY_AXES = {
32
+ ("T", "hand", "joint"): "hand_keypoint",
33
+ ("T", "hand"): "whole_hand",
34
+ ("T",): "object",
35
+ }
36
+
37
+
38
+ def _parts(value: str):
39
+ return PurePosixPath(value).parts
40
+
41
+
42
+ def _is_wildcard(segment: str) -> bool:
43
+ """A registry template segment is a wildcard when it carries a placeholder.
44
+
45
+ Covers both ``<object_id>`` and the composite ``<subject_id>__<object_id>``
46
+ (CONTRACT 4 contact pairs).
47
+ """
48
+ return "<" in segment and ">" in segment
49
+
50
+
51
+ def _entry_key(segment: str) -> str:
52
+ """``pose.pt`` -> ``pose``; ``parts`` -> ``parts`` (CONTRACT 4: keys, not paths)."""
53
+ return segment[:-3] if segment.endswith(".pt") else segment
54
+
55
+
56
+ class Registry:
57
+ """Read-only view over the declarative v1.1 registry."""
58
+
59
+ def __init__(self, schema: dict):
60
+ if schema.get("schema_version") != SCHEMA_VERSION:
61
+ raise ValueError(f"not a {SCHEMA_VERSION} registry: {schema.get('schema_version')!r}")
62
+ self.schema = schema
63
+ self.bundles = schema["tensor_bundles"]
64
+ self.components = schema["components"]
65
+ self.visibility_scopes = schema["tensor_attributes"]["visibility"]["scopes"]
66
+
67
+ @classmethod
68
+ def load(cls, path) -> "Registry":
69
+ return cls(json.loads(Path(path).read_text(encoding="utf-8")))
70
+
71
+ # -- v1.0 reference -> v1.1 bundle entry --------------------------------
72
+
73
+ def resolve(self, data_ref: str):
74
+ """Map a numeric ``data_ref`` to ``(bundle_path, keys, entry_spec)``.
75
+
76
+ Returns ``None`` for anything the contract keeps out of bundles: media,
77
+ JSONL, mesh/asset files, ``frames.jsonl``, ``metainfo.json``,
78
+ ``articulation.json``. The bundle's own entry table decides -- an
79
+ unmatched entry is never merged, so no path is guessed into a bundle.
80
+ """
81
+ ref = _parts(data_ref)
82
+ for bundle in self.bundles.values():
83
+ template = _parts(bundle["path"])
84
+ dir_template, filename = template[:-1], template[-1]
85
+ if len(ref) <= len(dir_template):
86
+ continue
87
+ bound, matched = {}, True
88
+ for want, got in zip(dir_template, ref):
89
+ if _is_wildcard(want):
90
+ bound[want] = got
91
+ elif want != got:
92
+ matched = False
93
+ break
94
+ if not matched:
95
+ continue
96
+ keys = [_entry_key(segment) for segment in ref[len(dir_template):]]
97
+ spec = self._entry_spec(bundle, keys)
98
+ if spec is None:
99
+ continue
100
+ directory = [bound.get(segment, segment) for segment in dir_template]
101
+ return "/".join(directory + [filename]), keys, spec
102
+ return None
103
+
104
+ @staticmethod
105
+ def _entry_spec(bundle: dict, keys: list):
106
+ for name, spec in bundle["entries"].items():
107
+ template = name.split("/")
108
+ if len(template) != len(keys):
109
+ continue
110
+ if all(_is_wildcard(w) or w == k for w, k in zip(template, keys)):
111
+ return spec
112
+ return None
113
+
114
+ def valid_shape_template(self, schema_id: str):
115
+ spec = self.components.get(schema_id)
116
+ if spec is None:
117
+ raise KeyError(f"schema_id {schema_id!r} is not registered")
118
+ return spec.get("valid_shape")
119
+
120
+ def visibility_valid_shape(self, axes):
121
+ scope = VISIBILITY_AXES.get(tuple(axes))
122
+ if scope is None:
123
+ raise ValueError(f"visibility axes {list(axes)} match no declared scope")
124
+ return self.visibility_scopes[scope]["valid_shape"]
125
+
126
+
127
+ def expanded_all_known(data: torch.Tensor, valid_shape) -> torch.Tensor:
128
+ """CONTRACT 3: explicit all-true bool tensor of the field's ``valid_shape``.
129
+
130
+ Symbolic dims resolve positionally against the data tensor, so the result
131
+ restates the source's declared all-known validity -- it is never inferred
132
+ from values or from a pose validity (``tensor_attributes.visibility``).
133
+ """
134
+ if valid_shape is None:
135
+ raise ValueError("field declares no valid_shape; cannot expand all-known validity")
136
+ if len(valid_shape) > data.ndim:
137
+ raise ValueError(f"valid_shape {list(valid_shape)} exceeds data rank {data.ndim}")
138
+ dims = []
139
+ for axis, dim in enumerate(valid_shape):
140
+ dims.append(data.shape[axis] if isinstance(dim, str) else int(dim))
141
+ return torch.ones(dims, dtype=torch.bool)
142
+
143
+
144
+ class BundleWriter:
145
+ """Accumulates one bundle's tree, then replaces the file atomically."""
146
+
147
+ def __init__(self, view_root, rel_path: str):
148
+ self.view_root = Path(view_root)
149
+ self.rel_path = rel_path
150
+ self.tree: dict = {}
151
+
152
+ def put(self, keys, data: torch.Tensor, valid: torch.Tensor):
153
+ if not keys:
154
+ raise ValueError("empty key path")
155
+ if not isinstance(data, torch.Tensor) or not isinstance(valid, torch.Tensor):
156
+ raise TypeError(f"{'/'.join(keys)}: data and valid must both be Tensors")
157
+ if valid.dtype != torch.bool:
158
+ raise TypeError(f"{'/'.join(keys)}: valid must be a bool Tensor, got {valid.dtype}")
159
+ node = self.tree
160
+ for key in keys[:-1]:
161
+ node = node.setdefault(key, {})
162
+ if not isinstance(node, dict):
163
+ raise TypeError(f"{'/'.join(keys)}: {key!r} already holds a leaf")
164
+ leaf = "/".join(keys)
165
+ if keys[-1] in node:
166
+ raise ValueError(f"duplicate field {leaf}")
167
+ node[keys[-1]] = {DATA_TERMINAL: data, VALID_TERMINAL: valid}
168
+ return leaf
169
+
170
+ def save(self):
171
+ """Write to a sibling temp file, fsync, then ``os.replace`` (MIGRATION 4.3)."""
172
+ if not self.tree:
173
+ return None # bundle_layout_rules.omit_empty_bundles
174
+ path = self.view_root / self.rel_path
175
+ path.parent.mkdir(parents=True, exist_ok=True)
176
+ temp = path.with_name(path.name + ".hw11-tmp")
177
+ torch.save(self.tree, temp)
178
+ fd = os.open(temp, os.O_RDONLY)
179
+ try:
180
+ os.fsync(fd)
181
+ finally:
182
+ os.close(fd)
183
+ os.replace(temp, path)
184
+ return path
185
+
186
+
187
+ class BundleReader:
188
+ """Reader cache required by ``reference_rules.reader_cache``."""
189
+
190
+ def __init__(self):
191
+ self._cache: dict = {}
192
+
193
+ def bundle(self, view_root, rel_path: str):
194
+ key = (str(Path(view_root).resolve()), rel_path)
195
+ if key not in self._cache:
196
+ path = Path(view_root) / rel_path
197
+ if not path.is_file():
198
+ raise FileNotFoundError(f"bundle {rel_path} not found in {view_root}")
199
+ self._cache[key] = torch.load(path, map_location="cpu", weights_only=True)
200
+ return self._cache[key]
201
+
202
+ def get(self, view_root, rel_path: str, keys):
203
+ if not isinstance(keys, list) or not keys:
204
+ raise TypeError(f"{rel_path}: data_key/valid_key must be a non-empty list")
205
+ node = self.bundle(view_root, rel_path)
206
+ for depth, key in enumerate(keys):
207
+ if not isinstance(node, dict):
208
+ raise KeyError(f"{rel_path}: {'/'.join(keys[:depth])} is a leaf, not a dict")
209
+ if key not in node:
210
+ raise KeyError(f"{rel_path}: missing key {key!r} on path {'/'.join(keys)}")
211
+ node = node[key]
212
+ return node
213
+
214
+ def field(self, view_root, component: dict):
215
+ """Fetch ``(data, valid)`` for a registered bundle component."""
216
+ for required in ("data_ref", "data_key", "valid_ref", "valid_key"):
217
+ if required not in component:
218
+ raise KeyError(f"component is missing {required!r}")
219
+ data = self.get(view_root, component["data_ref"], component["data_key"])
220
+ valid = self.get(view_root, component["valid_ref"], component["valid_key"])
221
+ if not isinstance(data, torch.Tensor):
222
+ raise TypeError(f"{component['data_ref']}: data is {type(data).__name__}, not a Tensor")
223
+ if not isinstance(valid, torch.Tensor) or valid.dtype != torch.bool:
224
+ raise TypeError(f"{component['valid_ref']}: valid must be a bool Tensor")
225
+ return data, valid
226
+
227
+
228
+ def raw_bytes(tensor: torch.Tensor) -> bytes:
229
+ """Unified contiguous byte view (CONTRACT 6.2), NaN bit patterns included."""
230
+ tensor = tensor.detach().cpu().contiguous()
231
+ try:
232
+ return tensor.numpy().tobytes()
233
+ except (TypeError, RuntimeError):
234
+ return tensor.view(torch.uint8).numpy().tobytes()
235
+
236
+
237
+ def same_tensor(left: torch.Tensor, right: torch.Tensor) -> bool:
238
+ return (
239
+ left.dtype == right.dtype
240
+ and tuple(left.shape) == tuple(right.shape)
241
+ and raw_bytes(left) == raw_bytes(right)
242
+ )
243
+
244
+
245
+ def sha256_file(path, block: int = 8 << 20) -> str:
246
+ digest = hashlib.sha256()
247
+ with Path(path).open("rb") as stream:
248
+ for chunk in iter(lambda: stream.read(block), b""):
249
+ digest.update(chunk)
250
+ return digest.hexdigest()
251
+
252
+
253
+ def sha256_bytes(payload: bytes) -> str:
254
+ return hashlib.sha256(payload).hexdigest()
ARCTIC/shared-v1.1/script/provenance/operations/build_arctic_docs.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Assemble ARCTIC's ``doc/`` tree from the canonical v1.1 spec and the v1.0 record.
3
+
4
+ Every published v1.1 release carries the same three spec documents, and each
5
+ dataset edits exactly the same three things in ``CONTRACT.md``: a status banner on
6
+ line 1, its own 状态 line, and the v1.0 link retargeted from the shared
7
+ ``../hand-warehouse-1.0/CONTRACT.md`` to the copy kept as ``V1_0_SEMANTICS.md``.
8
+ Doing that by hand is how a release ends up with a banner that overstates what was
9
+ actually verified, so this script derives the banner and the 状态 line from
10
+ ``doc/FULL_MIGRATION_SUMMARY.json`` -- the record of what the run actually did --
11
+ and refuses to write a claim the record does not support.
12
+
13
+ Run: python shared-v1.1/script/provenance/operations/build_arctic_docs.py
14
+
15
+ Idempotent: it rewrites the three transformed files and copies the two verbatim
16
+ ones, so re-running after the migration finishes refreshes the banner.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import hashlib
23
+ import json
24
+ import shutil
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ OPERATIONS = Path(__file__).resolve().parent
29
+ SCRIPT_DIR = OPERATIONS.parent.parent # <release>/script
30
+ RELEASE_ROOT = SCRIPT_DIR.parent # <dataset>/shared-v1.1
31
+ DATASET_ROOT = RELEASE_ROOT.parent # <dataset>
32
+ SPEC = SCRIPT_DIR / "arctic_v1_1" / "spec"
33
+ DOC = RELEASE_ROOT / "doc"
34
+ V10 = DATASET_ROOT / "shared-v1.0"
35
+
36
+ #: the canonical spec, shared by every dataset. Checked rather than trusted: if
37
+ #: these do not match, the release would ship a spec it did not migrate against.
38
+ CANONICAL = {
39
+ "CONTRACT.md": "502dde9ac0549551237f684472489ddf6372bad3a26b1f6cca96f360c5dff158",
40
+ "MIGRATION.md": "773f5146d49f5060bfc13ef92c143c59b683a6dc633cad44897414d5299088a0",
41
+ "schema.json": "9f3769f950b36f75f3d571c77b5a661ca8e72afae20c9f1ddd1deef140e6cca8",
42
+ }
43
+
44
+ #: ``../hand-warehouse-1.0/CONTRACT.md`` in the canonical text; the release keeps
45
+ #: its own copy of the v1.0 semantics beside it instead of reaching outside the tree
46
+ V10_LINK = "../hand-warehouse-1.0/CONTRACT.md"
47
+ V10_LINK_LOCAL = "V1_0_SEMANTICS.md"
48
+
49
+ STATES = {
50
+ #: no summary yet: the migration has not finished, so claim nothing about it
51
+ "in_progress": {
52
+ "banner": "> ARCTIC shared-v1.1 本地全量迁移进行中;自动验收、人工复查与 HF 发布均未完成。",
53
+ "status": "状态:ARCTIC shared-v1.1 配套注册表与读写工具已适配;本地迁移、自动验收、人工复查与 HF 发布均未完成。",
54
+ },
55
+ #: full acceptance recorded, human review and upload still outstanding
56
+ "accepted_pending_review": {
57
+ "banner": "> ARCTIC shared-v1.1 已完成本地全量迁移与自动验收(逐字段字节级比对);人工复查与 HF 发布尚未完成。",
58
+ "status": "状态:ARCTIC shared-v1.1 配套注册表与读写工具已适配;本地全量数值一致性及结构检查通过,发布清单已在发布树外重建(`tmp/arctic-tools/PUBLISH_MANIFEST.json`,树内不含清单)。人工复查不属于自动验收,尚未完成;HF 发布尚未进行。",
59
+ },
60
+ }
61
+
62
+ V11_SECTION = """
63
+ ## v1.1 纯存储迁移
64
+
65
+ 原始 RGB 码流、帧索引、官方划分、手槽与物体身份保持不变。本次不从 raw 重转、不重新编码媒体、不合成源缺失的模态。
66
+
67
+ | v1.0 文件 | v1.1 文件与字典条目 |
68
+ |---|---|
69
+ | camera/intrinsic.pt + valid | camera/camera.pt → intrinsic/{data,valid} |
70
+ | camera/extrinsic.pt + valid | camera/camera.pt → extrinsic/{data,valid} |
71
+ | camera/distortion.pt(无独立 valid,与内参共用) | camera/camera.pt → distortion/{data,valid} |
72
+ | annotation/mano/motion.pt + valid | annotation/mano/mano.pt → motion/{data,valid} |
73
+ | annotation/object/<id>/pose.pt + valid | annotation/object/<id>/object.pt → pose/{data,valid} |
74
+ | annotation/object/<id>/parts/<part>/pose.pt + valid | annotation/object/<id>/object.pt → parts/<part>/pose/{data,valid} |
75
+ | annotation/object/<id>/joint_state.pt + valid | annotation/object/<id>/object.pt → joint_state/{data,valid} |
76
+ | annotation/object/<id>/keypoints/xyz.pt + valid | annotation/object/<id>/object.pt → keypoints/xyz/{data,valid} |
77
+
78
+ 媒体/JSONL/网格资产保留独立 bool 有效性文件,不并入 bundle:`observation/rgb.mkv`+`rgb_valid.pt`、`annotation/object/<id>/articulation.json`+`articulation_valid.pt`、`assets/mesh.obj`+`mesh_valid.pt`。相机 0 的畸变向量 v1.0 直接挂在持有标定的组件上、自身没有 valid,v1.1 按注册表 `reference_rules.camera_distortion` 与内参共用同一份 bool(逐字节相同)。
79
+
80
+ `annotation/object/<id>/vertex_part_ids.pt` 仍以独立文件存在:注册表 `object` bundle 的条目是 `meshes/<mesh_id>/vertex_part_ids`,而 v1.0 的引用没有 `meshes/<mesh_id>/` 这一段,合入需要凭空构造 mesh id 并改写对象子 metainfo,与"绝不猜测路径"冲突,故按原样保留。没有新增缺失组件。
81
+
82
+ 迁移实现见 `script/arctic_v1_1/`(`migrate.py` 迁移、`verify.py` 逐视图字节级验收、`validate.py` 全量结构校验,并在**发布树外**重建发布清单 `tmp/arctic-tools/PUBLISH_MANIFEST.json`);公共布局库 `warehouse.py` 与各数据集逐字节相同,ARCTIC 的适配在 `arctic_common.py`。原 v1.0 文档及构建记录保留于 `doc/history-v1.0/`;旧转换实现及配套规范在 `script/v1_0_snapshot/`。
83
+ """
84
+
85
+
86
+ def sha256(path):
87
+ digest = hashlib.sha256()
88
+ with Path(path).open("rb") as stream:
89
+ for chunk in iter(lambda: stream.read(1 << 22), b""):
90
+ digest.update(chunk)
91
+ return digest.hexdigest()
92
+
93
+
94
+ def canonical_bytes(name):
95
+ """The shared spec verbatim, with its canonical digest confirmed."""
96
+ path = SPEC / name
97
+ got = sha256(path)
98
+ if got != CANONICAL[name]:
99
+ raise SystemExit(f"{path} is not the canonical {name}: {got} != {CANONICAL[name]}")
100
+ return path.read_bytes()
101
+
102
+
103
+ def canonical_text(name):
104
+ """The shared spec as LF text, for a file this release transforms.
105
+
106
+ The canonical ``CONTRACT.md`` and ``schema.json`` are CRLF; only the documents
107
+ this release edits are normalised. A file that is *copied* keeps its bytes --
108
+ both published releases ship ``schema.json`` at the canonical 39043 bytes with
109
+ its CRLF intact -- so the two paths are kept apart rather than sharing one
110
+ round-trip through ``str``.
111
+ """
112
+ return canonical_bytes(name).replace(b"\r\n", b"\n").decode("utf-8")
113
+
114
+
115
+ def state_name():
116
+ """Which of STATES the recorded migration summary supports."""
117
+ summary = DOC / "FULL_MIGRATION_SUMMARY.json"
118
+ if not summary.is_file():
119
+ return "in_progress"
120
+ record = json.loads(summary.read_text(encoding="utf-8"))
121
+ if record.get("phase") != "local_finalized_not_uploaded":
122
+ raise SystemExit(f"{summary}: unexpected phase {record.get('phase')!r}")
123
+ if record.get("human_full_approval"):
124
+ raise SystemExit(
125
+ f"{summary}: records a human approval, but no published wording is "
126
+ "defined here; a published release needs its own banner"
127
+ )
128
+ return "accepted_pending_review"
129
+
130
+
131
+ def build_contract(state):
132
+ """The canonical contract with the three dataset-specific edits applied."""
133
+ text = canonical_text("CONTRACT.md")
134
+ lines = text.split("\n")
135
+ status_index = next(
136
+ index for index, line in enumerate(lines) if line.startswith("状态:")
137
+ )
138
+ if lines[status_index].count("状态:") != 1 or not lines[status_index].startswith(
139
+ "状态:合同草案"
140
+ ):
141
+ raise SystemExit(f"line {status_index + 1} is not the canonical 状态 line")
142
+ if text.count(V10_LINK) != 1:
143
+ raise SystemExit(f"the canonical text no longer links {V10_LINK} exactly once")
144
+ lines[status_index] = STATES[state]["status"]
145
+ body = "\n".join(lines).replace(V10_LINK, V10_LINK_LOCAL)
146
+ #: banner, one blank line, then the canonical text; and no trailing newline,
147
+ #: which is how both published releases ship it
148
+ return f"{STATES[state]['banner']}\n\n{body}".rstrip("\n")
149
+
150
+
151
+ def build_raw_to_shared():
152
+ """v1.0's own mapping record, kept verbatim, with the v1.1 table appended."""
153
+ source = V10 / "doc" / "RAW_TO_SHARED.md"
154
+ if not source.is_file():
155
+ raise SystemExit(f"{source} is missing; the v1.0 record is the base of this file")
156
+ text = source.read_text(encoding="utf-8")
157
+ if "## v1.1 纯存储迁移" in text:
158
+ raise SystemExit(f"{source} already carries a v1.1 section")
159
+ return text.rstrip("\n") + "\n" + V11_SECTION
160
+
161
+
162
+ def copy_verbatim(source, target, label):
163
+ target.parent.mkdir(parents=True, exist_ok=True)
164
+ shutil.copy2(source, target)
165
+ return f"{label}: {sha256(target)[:16]} {target.relative_to(RELEASE_ROOT)}"
166
+
167
+
168
+ def main(argv=None):
169
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
170
+ parser.add_argument("--dry-run", action="store_true",
171
+ help="report what would be written and change nothing")
172
+ args = parser.parse_args(argv)
173
+
174
+ state = state_name()
175
+ print(f"banner state: {state}")
176
+ #: transformed documents are authored here and normalised to LF; copied ones
177
+ #: are other artifacts reproduced byte for byte, line endings included
178
+ transformed = {
179
+ "CONTRACT.md": build_contract(state).encode("utf-8"),
180
+ "RAW_TO_SHARED.md": build_raw_to_shared().encode("utf-8"),
181
+ "MIGRATION.md": canonical_bytes("MIGRATION.md"),
182
+ }
183
+ copied = {
184
+ "schema.json": canonical_bytes("schema.json"),
185
+ "V1_0_SEMANTICS.md": (V10 / "doc" / "CONTRACT.md").read_bytes(),
186
+ }
187
+ for name, payload in transformed.items():
188
+ write(DOC / name, payload, "transformed", args.dry_run)
189
+ for name, payload in copied.items():
190
+ write(DOC / name, payload, "copied", args.dry_run)
191
+ if not args.dry_run:
192
+ print(f" doc/CONTRACT.md banner: {STATES[state]['banner']}")
193
+ return 0
194
+
195
+
196
+ def write(target, payload, kind, dry_run):
197
+ if dry_run:
198
+ print(f" would write doc/{target.name} ({len(payload)} bytes, {kind})")
199
+ return
200
+ before = sha256(target) if target.is_file() else None
201
+ target.write_bytes(payload)
202
+ after = sha256(target)
203
+ print(f" doc/{target.name}: {len(payload)} bytes, {kind}, sha256 {after[:16]}"
204
+ f"{'' if before != after else ' (unchanged)'}")
205
+
206
+
207
+ if __name__ == "__main__":
208
+ raise SystemExit(main())
ARCTIC/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 手物数据仓库统一约定 v1.0
2
+
3
+ 格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。
4
+
5
+ 范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。
6
+
7
+ shared 层不是 raw 的完整镜像。处理者只需提取本次任务范围明确要求、语义已经核实且能够按本规范可靠转换的字段和模态。raw 中其余字段可以不纳入 shared,但必须在 `RAW_TO_SHARED.md` 中列出主要未纳入内容及原因。不得为了覆盖全部 raw 字段而猜测语义、虚构模态或保存未经定义的字段。未纳入 shared 不等于源数据不存在,原始信息仍以 raw 为准。
8
+
9
+ 本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。
10
+
11
+ ## 1. 目录
12
+
13
+ ```text
14
+ hand-datasets/
15
+ <dataset_name>/
16
+ raw/
17
+ doc/ # 官方说明、来源与校验记录
18
+ script/ # 官方下载脚本、必要包装脚本
19
+ data/ # 保留原始包,不原地解压或改写
20
+ <dataset_version>/
21
+ doc/ # 发布说明、schema、来源清单
22
+ script/ # 转换、校验脚本及运行配置
23
+ data/
24
+ <sequence_id>/
25
+ <camera_id>/
26
+ metainfo.json
27
+ observation/
28
+ rgb.mkv
29
+ rgb_valid.pt
30
+ depth.mkv # float32 深度的可逆视频编码
31
+ depth_valid.mkv # 逐像素 bool 的无损视频编码
32
+ camera/
33
+ frames.jsonl
34
+ intrinsic.pt
35
+ intrinsic_valid.pt
36
+ extrinsic.pt
37
+ extrinsic_valid.pt
38
+ annotation/
39
+ mano/
40
+ motion.pt
41
+ motion_valid.pt
42
+ visibility.pt
43
+ keypoints/
44
+ uv.pt
45
+ uv_valid.pt
46
+ xyz.pt
47
+ xyz_valid.pt
48
+ visibility.pt # 源数据有时提供
49
+ object/
50
+ <object_id>/
51
+ assets/ # 该物体的网格、材质、纹理及部件资产
52
+ <mesh_id>.obj
53
+ pose.pt
54
+ pose_valid.pt
55
+ visibility.pt
56
+ metainfo.json # 物体身份、类别、mesh、尺寸与部件引用
57
+ articulation.json
58
+ keypoints/
59
+ vertex_part_ids.pt
60
+ joint_state.pt
61
+ joint_state_valid.pt
62
+ parts/<part_id>/pose.pt
63
+ parts/<part_id>/pose_valid.pt
64
+ segment/
65
+ mask.mkv
66
+ mask_valid.pt
67
+ instances.jsonl
68
+ contact/
69
+ relations.jsonl
70
+ <subject_id>__<object_id>/ # 对应实体间的距离/接触区域
71
+ ```
72
+
73
+ 目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。
74
+
75
+ ## 2. 相机视图的 metainfo.json
76
+
77
+ ### 2.1 顶层字段与发布信息
78
+
79
+ 每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填:
80
+
81
+ | 字段 | 填写内容 |
82
+ |---|---|
83
+ | schema_version | 结构版本,本版为 `hand-warehouse/1.0` |
84
+ | dataset_id | 数据集的逻辑标识 |
85
+ | release_id | 本次数据发布版本,对应目录中的 dataset_version |
86
+ | sequence_id | 所属序列或独立图片样本的标识 |
87
+ | camera_id | 当前相机视图标识 |
88
+ | sample_type | `image` 或 `video`,规则见 2.2 |
89
+ | num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 |
90
+ | hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 |
91
+ | sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 |
92
+ | camera | 当前相机模型与图像尺寸,见 2.3 |
93
+ | components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 |
94
+ | split | `train/val/test/unknown`,划分协议见 2.4 |
95
+ | view_type | 必填,固定为 `ego/exo/unknown`。源数据或采集设置明确相机视角时必须填写 `ego` 或 `exo`;只有无法从可信来源确定时才填写 `unknown`,不得省略或主观猜测。多相机序列须逐视图分别填写。 |
96
+
97
+ `dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。
98
+
99
+ ### 2.2 图片、视频与 sampling
100
+
101
+ `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。合成背景变体不视为真实多相机。
102
+
103
+ `sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。
104
+
105
+ shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。
106
+
107
+ `sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。
108
+
109
+ ### 2.3 camera 模型声明
110
+
111
+ `camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。
112
+
113
+ ### 2.4 split 与划分协议
114
+
115
+ 保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。
116
+
117
+ 有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。
118
+
119
+ ### 2.5 components 组件登记
120
+
121
+ 组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。
122
+
123
+ | 字段 | 约定 |
124
+ |---|---|
125
+ | available | 本发布是否提供该组件;缺省也表示未提供 |
126
+ | schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 |
127
+ | data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 |
128
+ | axes | 数组各维度的含义 |
129
+ | valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 |
130
+ | storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 |
131
+ | provenance | source / format_conversion / derived,以及转换或生成方法 |
132
+ | source_locator | 原文件、压缩包成员和记录/帧的定位信息 |
133
+
134
+ 不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。
135
+
136
+ `provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。
137
+
138
+ `.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。
139
+
140
+ 机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。
141
+
142
+ ## 3. observation 观测数据
143
+
144
+ ### 3.1 rgb.mkv 与 rgb_valid.pt
145
+
146
+ RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。
147
+
148
+ **无损指共享层不增加信息损失。** 源 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 位冒充无损。
149
+
150
+ #### 3.1.1 允许的 RGB 存储 profile
151
+
152
+ | storage.profile | 编码方式 | 适用规则 |
153
+ |---|---|---|
154
+ | mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 |
155
+ | mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 |
156
+ | mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 |
157
+ | mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 |
158
+
159
+ 优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。
160
+
161
+ 普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。
162
+
163
+ #### 3.1.2 视频配置与校验
164
+
165
+ 每个视频组件在 metainfo 中登记 `storage`,至少包含:
166
+
167
+ | 字段 | 内容 |
168
+ |---|---|
169
+ | profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 |
170
+ | codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec |
171
+ | pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 |
172
+ | encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 |
173
+ | decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB |
174
+ | encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy |
175
+ | source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 |
176
+
177
+ 无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。
178
+
179
+ 逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。
180
+
181
+ 所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。
182
+
183
+ ### 3.2 depth.mkv 与 depth_valid.mkv
184
+
185
+ 深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。
186
+
187
+ #### 3.2.1 float32 的可逆视频编码
188
+
189
+ 采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是��规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。
190
+
191
+ ```text
192
+ u = reinterpret_uint32(depth_float32)
193
+ encoded[:, :, :W] = uint16(u & 65535)
194
+ encoded[:, :, W:] = uint16(u >> 16)
195
+ u_restored = uint32(low) | (uint32(high) << 16)
196
+ depth_float32 = reinterpret_float32(u_restored)
197
+ ```
198
+
199
+ 统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。
200
+
201
+ #### 3.2.2 逐像素有效性
202
+
203
+ `depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。
204
+
205
+ 登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写):
206
+
207
+ ```json
208
+ {
209
+ "available": true,
210
+ "schema_id": "depth/z_float32/v1",
211
+ "data_ref": "observation/depth.mkv",
212
+ "axes": ["T", "height", "width"],
213
+ "valid_ref": "observation/depth_valid.mkv",
214
+ "valid_axes": ["T", "height", "width"],
215
+ "unit": "m",
216
+ "depth_type": "z",
217
+ "depth_origin": "measured",
218
+ "invalid_value": "NaN",
219
+ "storage": {
220
+ "profile": "mkv/depth_float32_bits/v1",
221
+ "codec": "ffv1",
222
+ "pixel_format": "gray16le",
223
+ "encoded_size": [1280, 480],
224
+ "source_lossy": false,
225
+ "decoder": {"name": "ffmpeg", "version": "填写实际版本"},
226
+ "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"}
227
+ },
228
+ "valid_storage": {
229
+ "profile": "mkv/bool_ffv1/v1",
230
+ "codec": "ffv1",
231
+ "pixel_format": "gray",
232
+ "encoded_size": [640, 480],
233
+ "source_lossy": false,
234
+ "decoder": {"name": "ffmpeg", "version": "填写实际版本"},
235
+ "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"}
236
+ },
237
+ "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"},
238
+ "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"}
239
+ }
240
+ ```
241
+
242
+ 深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。
243
+
244
+ ## 4. camera 相机、帧索引与标定
245
+
246
+ ### 4.1 frames.jsonl:索引、时间与对应关系
247
+
248
+ `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` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。
249
+
250
+ 每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。
251
+
252
+ ### 4.2 坐标系与标定通则
253
+
254
+ | 项目 | 统一约定 |
255
+ |---|---|
256
+ | 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 |
257
+ | 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` |
258
+ | 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel |
259
+ | 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 |
260
+ | 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 |
261
+ | 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 |
262
+
263
+ ### 4.3 intrinsic.pt 与畸变参数
264
+
265
+ | model / schema_id | intrinsic.pt 的固定结构 |
266
+ |---|---|
267
+ | pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 |
268
+ | fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`��采用 Project Aria Fisheye624 投影定义 |
269
+ | opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 |
270
+ | rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` |
271
+ | unknown / null | 不提供可用 intrinsic,不声称可以投影 |
272
+
273
+ 有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。
274
+
275
+ `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。
276
+
277
+ 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 保存。
278
+
279
+ 内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。
280
+
281
+ ### 4.4 extrinsic.pt 与 extrinsic_valid.pt
282
+
283
+ `extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。
284
+
285
+ ## 5. annotation 标注数据
286
+
287
+ ### 5.1 标注通则:手槽、valid 与 visibility
288
+
289
+ 手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。
290
+
291
+ #### 5.1.1 valid:标注是否可用于监督
292
+
293
+ 标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。
294
+
295
+ **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 有效监督。
296
+
297
+ 本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。
298
+
299
+ 源字段必须按官方语义映射,不能直接按名字复制:
300
+
301
+ | 来源 | 官方含义 | 映射原则 |
302
+ |---|---|---|
303
+ | [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 |
304
+ | [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 |
305
+ | [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 |
306
+ | [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 输入 |
307
+
308
+ 源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。
309
+
310
+ `valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。
311
+
312
+ #### 5.1.2 visibility:可见性属性
313
+
314
+ 附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。
315
+
316
+ 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,不与逐关键点可见性混用。
317
+
318
+ `valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。
319
+
320
+ | 情况 | 手标注 valid | visibility |
321
+ |---|---|---|
322
+ | RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 |
323
+ | 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 |
324
+ | 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 |
325
+ | 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 |
326
+ | 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false |
327
+
328
+ visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。
329
+
330
+ 不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。
331
+
332
+ ### 5.2 mano:参数与整手可见性
333
+
334
+ 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。
335
+
336
+ `model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。
337
+
338
+ `mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。
339
+
340
+ 手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。
341
+
342
+ ### 5.3 keypoints:二维点、三维点与逐点可见性
343
+
344
+ 关键点独立于 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` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。
345
+
346
+ | keypoint_schema | K 与固定索引 |
347
+ |---|---|
348
+ | mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 |
349
+ | rhd21/v1 | 21;保持 wrist���然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO |
350
+
351
+ 具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。
352
+
353
+ 每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。
354
+
355
+ ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。
356
+
357
+ manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。
358
+
359
+ `keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。
360
+
361
+ 不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。
362
+
363
+ ### 5.4 object:身份、资产、位姿与几何
364
+
365
+ #### 5.4.1 metainfo.json:物体身份与跟踪作用域
366
+
367
+ 手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object/<object_id>/metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。
368
+
369
+ `identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。
370
+
371
+ #### 5.4.2 assets:网格、材质与纹理
372
+
373
+ 资产属于物体,统一存放在 `annotation/object/<object_id>/` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。
374
+
375
+ 网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。
376
+
377
+ #### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt
378
+
379
+ 刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。
380
+
381
+ `object/<id>/visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。
382
+
383
+ #### 5.4.4 articulation.json、部件位姿与 joint_state.pt
384
+
385
+ 关节物体: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]`,不与父局部变换混装。
386
+
387
+ 若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。
388
+
389
+ 部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。
390
+
391
+ #### 5.4.5 dimensions、几何关键点与顶点部件标签
392
+
393
+ `dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。
394
+
395
+ 物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。
396
+
397
+ 源物体关键点放 `object/<id>/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。每个发布选择一套源几何点并记录选择,不另建方法分支。
398
+
399
+ `vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。
400
+
401
+ ### 5.5 segment:分割类别、编码与覆盖范围
402
+
403
+ 每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。
404
+
405
+ | schema_id | 文件与数值语义 |
406
+ |---|---|
407
+ | segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 |
408
+ | segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 |
409
+ | segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 |
410
+
411
+ #### 5.5.1 uint16 标签图与 instances.jsonl
412
+
413
+ 组件声明 `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。
414
+
415
+ `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 中每个非保留编码必须有且仅有一个映射。
416
+
417
+ FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。
418
+
419
+ #### 5.5.2 重叠实例多边形
420
+
421
+ 每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。
422
+
423
+ #### 5.5.3 灰度前景强度
424
+
425
+ 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 的数值含义不同,不能将该文件按整数类别图解码。
426
+
427
+ FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。
428
+
429
+ #### 5.5.4 coverage 与有效性
430
+
431
+ `coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。
432
+
433
+ 三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。
434
+
435
+ ### 5.6 contact:接触、抓取、区域与距离
436
+
437
+ #### 5.6.1 relations.jsonl 与 relations_valid.pt
438
+
439
+ `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。
440
+
441
+ 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 保存;不得当作逐顶点接触。
442
+
443
+ relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。
444
+
445
+ #### 5.6.2 实体对的顶点区域与距离
446
+
447
+ 已发布的接触区域/距离按参与关系的 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 后才可转换,不能随意栅格化宣称等价。
448
+
449
+ 顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。
450
+
451
+ ## 附录:任务范围
452
+
453
+ 不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。
454
+
455
+ 不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。
456
+
457
+ schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。
458
+
459
+ 本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。
ARCTIC/shared-v1.1/script/v1_0_snapshot/doc/schema.json ADDED
@@ -0,0 +1,880 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "hand-warehouse/1.0",
3
+ "validity_revision": "usable-annotation-2026-09-20",
4
+ "annotation_validity": {
5
+ "meaning": "annotation usable for supervision, not merely record presence",
6
+ "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion",
7
+ "without_official_qa": "omit QA term; declare source rules; do not fabricate QA",
8
+ "policy_field": "components.<name>.valid_policy",
9
+ "visibility_is_independent": true,
10
+ "invalid_float_value": "NaN",
11
+ "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",
12
+ "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100"
13
+ },
14
+ "hand_slots": [
15
+ "left",
16
+ "right"
17
+ ],
18
+ "view_metadata": {
19
+ "required_fields": [
20
+ "view_type"
21
+ ],
22
+ "view_type_values": [
23
+ "ego",
24
+ "exo",
25
+ "unknown"
26
+ ],
27
+ "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"
28
+ },
29
+ "keypoints": {
30
+ "mano21/v1": {
31
+ "count": 21,
32
+ "names": [
33
+ "wrist",
34
+ "thumb_1",
35
+ "thumb_2",
36
+ "thumb_3",
37
+ "thumb_4",
38
+ "index_1",
39
+ "index_2",
40
+ "index_3",
41
+ "index_4",
42
+ "middle_1",
43
+ "middle_2",
44
+ "middle_3",
45
+ "middle_4",
46
+ "ring_1",
47
+ "ring_2",
48
+ "ring_3",
49
+ "ring_4",
50
+ "little_1",
51
+ "little_2",
52
+ "little_3",
53
+ "little_4"
54
+ ],
55
+ "source_index_map": null,
56
+ "note": "adapter maps official MANO joint and fingertip convention"
57
+ },
58
+ "rhd21/v1": {
59
+ "count": 21,
60
+ "names": [
61
+ "wrist",
62
+ "thumb_1",
63
+ "thumb_2",
64
+ "thumb_3",
65
+ "thumb_4",
66
+ "index_1",
67
+ "index_2",
68
+ "index_3",
69
+ "index_4",
70
+ "middle_1",
71
+ "middle_2",
72
+ "middle_3",
73
+ "middle_4",
74
+ "ring_1",
75
+ "ring_2",
76
+ "ring_3",
77
+ "ring_4",
78
+ "little_1",
79
+ "little_2",
80
+ "little_3",
81
+ "little_4"
82
+ ],
83
+ "source_index_map_per_hand": [
84
+ 0,
85
+ 4,
86
+ 3,
87
+ 2,
88
+ 1,
89
+ 8,
90
+ 7,
91
+ 6,
92
+ 5,
93
+ 12,
94
+ 11,
95
+ 10,
96
+ 9,
97
+ 16,
98
+ 15,
99
+ 14,
100
+ 13,
101
+ 20,
102
+ 19,
103
+ 18,
104
+ 17
105
+ ]
106
+ }
107
+ },
108
+ "camera": {
109
+ "opencv_fisheye4": {
110
+ "K": [
111
+ 3,
112
+ 3
113
+ ],
114
+ "distortion": [
115
+ "k1",
116
+ "k2",
117
+ "k3",
118
+ "k4"
119
+ ],
120
+ "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand"
121
+ },
122
+ "pinhole": {
123
+ "K": [
124
+ 3,
125
+ 3
126
+ ]
127
+ },
128
+ "fisheye624": {
129
+ "parameters": [
130
+ "f",
131
+ "cx",
132
+ "cy",
133
+ "k0",
134
+ "k1",
135
+ "k2",
136
+ "k3",
137
+ "k4",
138
+ "k5",
139
+ "p0",
140
+ "p1",
141
+ "s0",
142
+ "s1",
143
+ "s2",
144
+ "s3"
145
+ ]
146
+ },
147
+ "rational8": {
148
+ "K": [
149
+ 3,
150
+ 3
151
+ ],
152
+ "distortion": [
153
+ "k1",
154
+ "k2",
155
+ "p1",
156
+ "p2",
157
+ "k3",
158
+ "k4",
159
+ "k5",
160
+ "k6"
161
+ ]
162
+ }
163
+ },
164
+ "segmentation": {
165
+ "segment/uint16_labels/v1": {
166
+ "storage": "mask.mkv",
167
+ "dtype": "uint16",
168
+ "mapping": "instances.jsonl",
169
+ "valid_shape": [
170
+ "T"
171
+ ],
172
+ "required_metadata": [
173
+ "segmentation_type",
174
+ "coverage",
175
+ "mapping_ref",
176
+ "storage"
177
+ ],
178
+ "shape": [
179
+ "T",
180
+ "H",
181
+ "W"
182
+ ],
183
+ "reserved_codes": {
184
+ "0": "unassigned",
185
+ "65535": "ignore"
186
+ },
187
+ "region_codes": [
188
+ 1,
189
+ 65534
190
+ ],
191
+ "allowed_storage_profiles": [
192
+ "mkv/uint16_ffv1/v1"
193
+ ]
194
+ },
195
+ "segment/instance_polygons/v1": {
196
+ "storage": "polygons.jsonl",
197
+ "mapping": "instances.jsonl",
198
+ "frame_keys": [
199
+ "frame_index",
200
+ "instances"
201
+ ],
202
+ "instance_keys": [
203
+ "mask_value",
204
+ "polygons"
205
+ ],
206
+ "coordinate_unit": "pixel",
207
+ "overlap_allowed": true,
208
+ "valid_shape": [
209
+ "T"
210
+ ],
211
+ "required_metadata": [
212
+ "segmentation_type",
213
+ "coverage",
214
+ "mapping_ref"
215
+ ],
216
+ "polygon_shape": [
217
+ "N",
218
+ 2
219
+ ],
220
+ "holes_supported": false
221
+ },
222
+ "segment/foreground_intensity/v1": {
223
+ "storage": "mask.mkv",
224
+ "dtype": "uint16",
225
+ "value_range": [
226
+ 0,
227
+ 255
228
+ ],
229
+ "normalization_scale": 0.00392156862745098,
230
+ "axes": [
231
+ "T",
232
+ "height",
233
+ "width"
234
+ ],
235
+ "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
236
+ "zero": "background",
237
+ "full_scale": "foreground",
238
+ "mapping": "foreground_category in component metadata",
239
+ "valid_shape": [
240
+ "T"
241
+ ],
242
+ "required_metadata": [
243
+ "segmentation_type",
244
+ "coverage",
245
+ "value_range",
246
+ "normalization_scale",
247
+ "foreground_category",
248
+ "entity_id",
249
+ "storage"
250
+ ],
251
+ "shape": [
252
+ "T",
253
+ "H",
254
+ "W"
255
+ ],
256
+ "allowed_storage_profiles": [
257
+ "mkv/uint16_ffv1/v1"
258
+ ]
259
+ }
260
+ },
261
+ "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.",
262
+ "components": {
263
+ "mano/axis_angle61/v1": {
264
+ "storage": "pt",
265
+ "dtype": "float32",
266
+ "shape": [
267
+ "T",
268
+ 2,
269
+ 61
270
+ ],
271
+ "valid_shape": [
272
+ "T",
273
+ 2
274
+ ],
275
+ "unit": "m",
276
+ "angle_unit": "rad",
277
+ "coordinate_frame": "camera",
278
+ "layout": {
279
+ "pose_axis_angle": [
280
+ 0,
281
+ 48
282
+ ],
283
+ "shape": [
284
+ 48,
285
+ 58
286
+ ],
287
+ "translation": [
288
+ 58,
289
+ 61
290
+ ]
291
+ }
292
+ },
293
+ "keypoints/uv/v1": {
294
+ "storage": "pt",
295
+ "dtype": "float32",
296
+ "shape": [
297
+ "T",
298
+ 2,
299
+ 21,
300
+ 2
301
+ ],
302
+ "valid_shape": [
303
+ "T",
304
+ 2,
305
+ 21
306
+ ],
307
+ "unit": "pixel",
308
+ "required_metadata": [
309
+ "keypoint_schema"
310
+ ]
311
+ },
312
+ "keypoints/xyz/v1": {
313
+ "storage": "pt",
314
+ "dtype": "float32",
315
+ "shape": [
316
+ "T",
317
+ 2,
318
+ 21,
319
+ 3
320
+ ],
321
+ "valid_shape": [
322
+ "T",
323
+ 2,
324
+ 21
325
+ ],
326
+ "unit": "m",
327
+ "required_metadata": [
328
+ "keypoint_schema"
329
+ ]
330
+ },
331
+ "depth/z_float32/v1": {
332
+ "storage": "mkv",
333
+ "dtype": "float32",
334
+ "shape": [
335
+ "T",
336
+ "H",
337
+ "W"
338
+ ],
339
+ "valid_shape": [
340
+ "T",
341
+ "H",
342
+ "W"
343
+ ],
344
+ "unit": "m",
345
+ "depth_type": "z",
346
+ "pixel_grid": "current_rgb",
347
+ "coordinate_frame": "current_rgb_camera",
348
+ "valid_storage": "mkv",
349
+ "allowed_storage_profiles": [
350
+ "mkv/depth_float32_bits/v1"
351
+ ],
352
+ "allowed_valid_storage_profiles": [
353
+ "mkv/bool_ffv1/v1"
354
+ ],
355
+ "required_metadata": [
356
+ "storage",
357
+ "valid_storage",
358
+ "depth_origin"
359
+ ],
360
+ "depth_origin_values": [
361
+ "measured",
362
+ "rendered",
363
+ "unknown"
364
+ ]
365
+ },
366
+ "transform/se3/v1": {
367
+ "storage": "pt",
368
+ "dtype": "float32",
369
+ "shape": [
370
+ "T",
371
+ 4,
372
+ 4
373
+ ],
374
+ "valid_shape": [
375
+ "T"
376
+ ],
377
+ "unit": "m",
378
+ "required_metadata": [
379
+ "convention"
380
+ ]
381
+ },
382
+ "object/rigid/v1": {
383
+ "storage": "pt",
384
+ "dtype": "float32",
385
+ "shape": [
386
+ "T",
387
+ 4,
388
+ 4
389
+ ],
390
+ "valid_shape": [
391
+ "T"
392
+ ],
393
+ "unit": "m",
394
+ "required_metadata": [
395
+ "convention"
396
+ ]
397
+ },
398
+ "camera/pinhole/v1": {
399
+ "storage": "pt",
400
+ "dtype": "float32",
401
+ "shape": [
402
+ "T",
403
+ 3,
404
+ 3
405
+ ],
406
+ "valid_shape": [
407
+ "T"
408
+ ]
409
+ },
410
+ "camera/rational8/v1": {
411
+ "storage": "pt",
412
+ "dtype": "float32",
413
+ "shape": [
414
+ "T",
415
+ 3,
416
+ 3
417
+ ],
418
+ "valid_shape": [
419
+ "T"
420
+ ]
421
+ },
422
+ "camera/opencv_fisheye4/v1": {
423
+ "storage": "pt",
424
+ "dtype": "float32",
425
+ "shape": [
426
+ "T",
427
+ 3,
428
+ 3
429
+ ],
430
+ "valid_shape": [
431
+ "T"
432
+ ]
433
+ },
434
+ "camera/fisheye624/v1": {
435
+ "storage": "pt",
436
+ "dtype": "float32",
437
+ "shape": [
438
+ "T",
439
+ 15
440
+ ],
441
+ "valid_shape": [
442
+ "T"
443
+ ]
444
+ },
445
+ "camera/distortion8/v1": {
446
+ "storage": "pt",
447
+ "dtype": "float32",
448
+ "shape": [
449
+ "T",
450
+ 8
451
+ ],
452
+ "valid_shape": [
453
+ "T"
454
+ ]
455
+ },
456
+ "camera/fisheye4_distortion/v1": {
457
+ "storage": "pt",
458
+ "dtype": "float32",
459
+ "shape": [
460
+ "T",
461
+ 4
462
+ ],
463
+ "valid_shape": [
464
+ "T"
465
+ ]
466
+ },
467
+ "object/joint_state/v1": {
468
+ "storage": "pt",
469
+ "dtype": "float32",
470
+ "shape": [
471
+ "T",
472
+ "J"
473
+ ],
474
+ "valid_shape": [
475
+ "T",
476
+ "J"
477
+ ],
478
+ "required_metadata": [
479
+ "joint_order"
480
+ ],
481
+ "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint"
482
+ },
483
+ "object_keypoints/camera/v1": {
484
+ "storage": "pt",
485
+ "dtype": "float32",
486
+ "shape": [
487
+ "T",
488
+ "K",
489
+ 3
490
+ ],
491
+ "valid_shape": [
492
+ "T",
493
+ "K"
494
+ ],
495
+ "unit": "m",
496
+ "coordinate_frame": "camera",
497
+ "required_metadata": [
498
+ "keypoint_schema"
499
+ ]
500
+ },
501
+ "object/dimensions/v1": {
502
+ "storage": "pt",
503
+ "dtype": "float32",
504
+ "shape": [
505
+ "T",
506
+ 3
507
+ ],
508
+ "valid_shape": [
509
+ "T"
510
+ ],
511
+ "unit": "m",
512
+ "required_metadata": [
513
+ "dimensions_semantics"
514
+ ],
515
+ "axis_order": [
516
+ "length",
517
+ "width",
518
+ "height"
519
+ ],
520
+ "scale_rule": "do not apply to mesh without source-supported size/scale relation"
521
+ },
522
+ "object_keypoints/template/v1": {
523
+ "storage": "pt",
524
+ "dtype": "float32",
525
+ "shape": [
526
+ "K",
527
+ 3
528
+ ],
529
+ "valid_shape": [
530
+ "K"
531
+ ],
532
+ "unit": "m",
533
+ "coordinate_frame": "object",
534
+ "static": true,
535
+ "required_metadata": [
536
+ "keypoint_schema"
537
+ ]
538
+ },
539
+ "mesh/obj/v1": {
540
+ "storage": "obj",
541
+ "unit": "m",
542
+ "static": true,
543
+ "valid_shape": [],
544
+ "dependencies": "MTL and textures retained under owning object"
545
+ },
546
+ "rgb/uint8/v1": {
547
+ "storage": "mkv",
548
+ "dtype": "uint8",
549
+ "shape": [
550
+ "T",
551
+ "H",
552
+ "W",
553
+ 3
554
+ ],
555
+ "valid_shape": [
556
+ "T"
557
+ ],
558
+ "color_order": "RGB",
559
+ "allowed_storage_profiles": [
560
+ "mkv/mjpeg_copy/v1",
561
+ "mkv/source_copy/v1",
562
+ "mkv/h264_rgb_lossless/v1",
563
+ "mkv/ffv1_rgb/v1"
564
+ ],
565
+ "required_metadata": [
566
+ "storage"
567
+ ]
568
+ },
569
+ "contact/relations/v1": {
570
+ "storage": "jsonl",
571
+ "valid_shape": [
572
+ "T"
573
+ ],
574
+ "frame_keys": [
575
+ "frame_index",
576
+ "relations"
577
+ ],
578
+ "absence_semantics": "no record is not a negative contact annotation"
579
+ },
580
+ "contact/vertex_region/v1": {
581
+ "storage": "pt",
582
+ "dtype": "bool",
583
+ "shape": [
584
+ "T",
585
+ "V"
586
+ ],
587
+ "valid_shape": [
588
+ "T",
589
+ "V"
590
+ ],
591
+ "required_metadata": [
592
+ "source_geometry_ref",
593
+ "target_geometry_ref",
594
+ "topology_id"
595
+ ],
596
+ "pilot_status": "defined_not_empirically_validated"
597
+ },
598
+ "contact/vertex_distance/v1": {
599
+ "storage": "pt",
600
+ "dtype": "float32",
601
+ "shape": [
602
+ "T",
603
+ "V"
604
+ ],
605
+ "valid_shape": [
606
+ "T",
607
+ "V"
608
+ ],
609
+ "unit": "m",
610
+ "required_metadata": [
611
+ "source_geometry_ref",
612
+ "target_geometry_ref",
613
+ "topology_id",
614
+ "distance_definition"
615
+ ],
616
+ "pilot_status": "defined_not_empirically_validated"
617
+ },
618
+ "object/articulated/v1": {
619
+ "storage": "json",
620
+ "required_keys": [
621
+ "parts",
622
+ "joints"
623
+ ],
624
+ "part_keys": [
625
+ "part_id",
626
+ "parent_id",
627
+ "has_model",
628
+ "mesh_ref"
629
+ ],
630
+ "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints",
631
+ "acyclic": true
632
+ },
633
+ "segment/uint16_labels/v1": {
634
+ "storage": "mkv",
635
+ "dtype": "uint16",
636
+ "mapping": "instances.jsonl",
637
+ "valid_shape": [
638
+ "T"
639
+ ],
640
+ "required_metadata": [
641
+ "segmentation_type",
642
+ "coverage",
643
+ "mapping_ref",
644
+ "storage"
645
+ ],
646
+ "shape": [
647
+ "T",
648
+ "H",
649
+ "W"
650
+ ],
651
+ "reserved_codes": {
652
+ "0": "unassigned",
653
+ "65535": "ignore"
654
+ },
655
+ "region_codes": [
656
+ 1,
657
+ 65534
658
+ ],
659
+ "allowed_storage_profiles": [
660
+ "mkv/uint16_ffv1/v1"
661
+ ]
662
+ },
663
+ "segment/instance_polygons/v1": {
664
+ "storage": "jsonl",
665
+ "mapping": "instances.jsonl",
666
+ "frame_keys": [
667
+ "frame_index",
668
+ "instances"
669
+ ],
670
+ "instance_keys": [
671
+ "mask_value",
672
+ "polygons"
673
+ ],
674
+ "coordinate_unit": "pixel",
675
+ "overlap_allowed": true,
676
+ "valid_shape": [
677
+ "T"
678
+ ],
679
+ "required_metadata": [
680
+ "segmentation_type",
681
+ "coverage",
682
+ "mapping_ref"
683
+ ],
684
+ "polygon_shape": [
685
+ "N",
686
+ 2
687
+ ],
688
+ "holes_supported": false
689
+ },
690
+ "segment/foreground_intensity/v1": {
691
+ "storage": "mkv",
692
+ "dtype": "uint16",
693
+ "value_range": [
694
+ 0,
695
+ 255
696
+ ],
697
+ "normalization_scale": 0.00392156862745098,
698
+ "axes": [
699
+ "T",
700
+ "height",
701
+ "width"
702
+ ],
703
+ "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
704
+ "zero": "background",
705
+ "full_scale": "foreground",
706
+ "mapping": "foreground_category in component metadata",
707
+ "valid_shape": [
708
+ "T"
709
+ ],
710
+ "required_metadata": [
711
+ "segmentation_type",
712
+ "coverage",
713
+ "value_range",
714
+ "normalization_scale",
715
+ "foreground_category",
716
+ "entity_id",
717
+ "storage"
718
+ ],
719
+ "shape": [
720
+ "T",
721
+ "H",
722
+ "W"
723
+ ],
724
+ "allowed_storage_profiles": [
725
+ "mkv/uint16_ffv1/v1"
726
+ ]
727
+ }
728
+ },
729
+ "storage_revision": "lossless-video-2026-09-18",
730
+ "sampling": {
731
+ "image": {
732
+ "single": {
733
+ "T": 1
734
+ },
735
+ "independent": {
736
+ "T": ">=2",
737
+ "required_frame_fields": [
738
+ "sample_id",
739
+ "source_locator"
740
+ ],
741
+ "temporal_relationship": false
742
+ },
743
+ "source_fps": null
744
+ },
745
+ "video": {
746
+ "sampling_types": [
747
+ "dense",
748
+ "sparse"
749
+ ]
750
+ }
751
+ },
752
+ "storage_profiles": {
753
+ "mkv/mjpeg_copy/v1": {
754
+ "container": "matroska",
755
+ "codec": "mjpeg",
756
+ "method": "stream_copy_from_source_jpeg",
757
+ "logical_dtype": "uint8",
758
+ "decoded_pixel_format": "rgb24",
759
+ "validation": [
760
+ "source_jpeg_packet_sha256_exact",
761
+ "all_packet_count_order_and_dimensions_exact",
762
+ "deterministic_decoded_rgb_sample_exact",
763
+ "pilot_and_final_selected_whole_sequences_decoded_rgb_exact"
764
+ ],
765
+ "validation_policy": {
766
+ "id": "jpeg-packets-all-rgb-sample16/v1",
767
+ "sample_count_per_view": 16,
768
+ "short_views": "all_frames_if_T_less_than_16",
769
+ "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated",
770
+ "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)",
771
+ "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer",
772
+ "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage",
773
+ "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence"
774
+ }
775
+ },
776
+ "mkv/source_copy/v1": {
777
+ "container": "matroska",
778
+ "codec": "source_codec_declared_in_metadata",
779
+ "method": "stream_copy_only",
780
+ "logical_dtype": "uint8",
781
+ "decoded_pixel_format": "rgb24",
782
+ "validation": [
783
+ "no_reencoding",
784
+ "all_decoded_rgb_frames_exact",
785
+ "presentation_frame_order_exact"
786
+ ]
787
+ },
788
+ "mkv/h264_rgb_lossless/v1": {
789
+ "container": "matroska",
790
+ "codec": "h264",
791
+ "encoder": "libx264rgb",
792
+ "crf": 0,
793
+ "decoded_pixel_format": "rgb24",
794
+ "logical_dtype": "uint8",
795
+ "gop": "declared_in_encoder_parameters",
796
+ "validation": [
797
+ "all_decoded_rgb_frames_exact"
798
+ ],
799
+ "forbidden": [
800
+ "lossy_rate_control",
801
+ "rgb_to_yuv420_subsampling"
802
+ ]
803
+ },
804
+ "mkv/ffv1_rgb/v1": {
805
+ "container": "matroska",
806
+ "codec": "ffv1",
807
+ "decoded_pixel_format": "rgb24",
808
+ "logical_dtype": "uint8",
809
+ "validation": [
810
+ "all_decoded_rgb_frames_exact"
811
+ ]
812
+ },
813
+ "mkv/depth_float32_bits/v1": {
814
+ "container": "matroska",
815
+ "codec": "ffv1",
816
+ "pixel_format": "gray16le",
817
+ "logical_dtype": "float32",
818
+ "logical_shape": [
819
+ "T",
820
+ "H",
821
+ "W"
822
+ ],
823
+ "encoded_shape": [
824
+ "T",
825
+ "H",
826
+ "2*W"
827
+ ],
828
+ "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns",
829
+ "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))",
830
+ "validation": [
831
+ "all_float32_bits_exact_including_nan"
832
+ ]
833
+ },
834
+ "mkv/bool_ffv1/v1": {
835
+ "container": "matroska",
836
+ "codec": "ffv1",
837
+ "pixel_format": "gray",
838
+ "logical_dtype": "bool",
839
+ "stored_values": [
840
+ 0,
841
+ 1
842
+ ],
843
+ "validation": [
844
+ "all_bool_values_exact"
845
+ ]
846
+ },
847
+ "mkv/uint16_ffv1/v1": {
848
+ "container": "matroska",
849
+ "codec": "ffv1",
850
+ "pixel_formats": [
851
+ "gray",
852
+ "gray16le"
853
+ ],
854
+ "logical_dtype": "uint16",
855
+ "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion",
856
+ "validation": [
857
+ "all_integer_values_exact"
858
+ ]
859
+ }
860
+ },
861
+ "video_metadata": {
862
+ "required": [
863
+ "profile",
864
+ "codec",
865
+ "pixel_format",
866
+ "encoded_size",
867
+ "decoder",
868
+ "encoder_parameters",
869
+ "source_lossy"
870
+ ],
871
+ "source_lossy_values": [
872
+ true,
873
+ false,
874
+ "unknown"
875
+ ],
876
+ "timebase_role": "index_only",
877
+ "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits",
878
+ "selection": "choose smaller complete candidate only after exact roundtrip validation"
879
+ }
880
+ }
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/README.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ARCTIC shared-v1.0 脚本
2
+
3
+ 这里仅保留能够解释和复现当前 shared-v1.0 的入口、配置与实现。所有脚本默认假定数据集根目录仍采用生产时的 `raw/`、`shared-v1.0/`、`tmp/` 布局,并要求项目根目录中的 hand-warehouse/1.0 规范与运行环境可用。
4
+
5
+ ## 入口
6
+
7
+ - `convert.py`:生产转换/断点续跑入口;无参数时执行原受控队列。
8
+ - `validate.py VIEW`:校验一个相机视图目录的结构、帧映射、张量和媒体声明。
9
+ - `render_review.py`:重建已登记的完整序列试点报告。
10
+ - `config.json`:生产时采用的媒体并行与存储配置快照。
11
+ - `internal/`:上述入口依赖的冻结生产实现;通常无需直接调用。
12
+
13
+
14
+ ARCTIC 的 `internal/correct_arctic_source_fps_metadata.py` 是已执行并发布的 30 FPS 元数据修正工具;它不修改 MKV。对象扩展审核由 `internal/arctic_object_review.py` 与 `internal/finalize_arctic_objects_review.py` 复现。
15
+
16
+ ## 常用命令
17
+
18
+ ```powershell
19
+ python script/convert.py
20
+ python script/validate.py <shared-v1.0/data/序列/相机目录>
21
+ python script/render_review.py
22
+ ```
23
+
24
+ 转换入口保持原来的单实例锁、摘要、空间和断点检查。已完成数据集会按封存记录核验并跳过,不应通过删除状态文件强制重跑。
25
+
26
+ ## 历史证据
27
+
28
+ `doc/validation/` 中的脚本清单和 SHA256 描述的是对应生产/验收发生时的代码快照,继续作为历史证据保留。旧代码不再重复放进当前 `script/history/`;远端 Git 提交历史及这些固定指纹可用于追溯。运行日志、上传状态、缓存和临时文件属于 `tmp/`,不在本目录发布。
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "media_policy": "jpeg-packets-all-rgb-sample16/v1",
3
+ "workers_by_dataset": {
4
+ "ARCTIC": 3,
5
+ "HOT3D": 2
6
+ },
7
+ "torch_threads": 4,
8
+ "max_heavy_dataset_workers": 1,
9
+ "selection_method": "Median of comparable runs; exclude HOT3D initial cold-file read and use its repeated 1-worker trial; choose fewer workers if within 3% of fastest measured; >=1 GB observed available memory",
10
+ "authorized_by": "User requested stopping old production and switching to accelerated version with measured optimal parallelism",
11
+ "created_at": "2026-09-20T22:27:01.369591+08:00"
12
+ }
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/convert.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resume the verified ARCTIC production queue."""
2
+ from pathlib import Path
3
+ import argparse, os, runpy, sys
4
+ q=argparse.ArgumentParser(description='Resume the ARCTIC conversion queue using its existing plan and checkpoints.')
5
+ q.add_argument('--mode',choices=['run','migrate'],default='run')
6
+ q.add_argument('--sequence',help='advanced: process exactly one source sequence')
7
+ a=q.parse_args()
8
+ HERE=Path(__file__).resolve().parent
9
+ sys.path.insert(0,str(HERE/'internal'))
10
+ os.environ['HAND_DATASET_SCOPE']='ARCTIC'
11
+ if a.sequence: sys.argv=[sys.argv[0],'worker','--dataset','ARCTIC','--sequence',a.sequence]
12
+ elif a.mode=='migrate': sys.argv=[sys.argv[0],'migrate','--dataset','ARCTIC']
13
+ else: sys.argv=[sys.argv[0],'run']
14
+ runpy.run_path(str(HERE/'internal'/'preprocess_fresh_full.py'),run_name='__main__')
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/accelerated_media.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """All JPEG packets verified; deterministic RGB sample verification without re-encoding."""
2
+ from pathlib import Path
3
+ import hashlib,io,json,random,subprocess,time,zipfile
4
+ import fresh_sequence_common as c
5
+
6
+ POLICY='jpeg-packets-all-rgb-sample16/v1'
7
+
8
+ def indices_for(sequence,camera,count):
9
+ assert count>0,'Empty media sequence'
10
+ seed=int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8],'big')
11
+ indices={0,count-1,count//4,count//2,3*count//4}
12
+ rng=random.Random(seed)
13
+ remaining=[i for i in range(count) if i not in indices]
14
+ indices.update(rng.sample(remaining,min(len(remaining),max(0,16-len(indices)))))
15
+ return sorted(indices),seed
16
+
17
+ def rgb_hashes(args,width,height,count):
18
+ """Same FFmpeg rgb24 decode, accelerated SHA256 via hashlib/OpenSSL; bounded RAM."""
19
+ cmd=[str(c.FF),'-v','error','-threads','2','-noautorotate',*map(str,args),'-map','0:v:0','-pix_fmt','rgb24','-threads','2','-fps_mode','passthrough','-f','rawvideo','pipe:1']
20
+ p=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
21
+ size=width*height*3;rows=[]
22
+ try:
23
+ for i in range(count):
24
+ block=p.stdout.read(size);assert len(block)==size,('early RGB EOF',i,count)
25
+ rows.append((size,hashlib.sha256(block).hexdigest()))
26
+ assert not p.stdout.read(1),'Unexpected extra RGB frames'
27
+ error=p.stderr.read();assert p.wait()==0,error.decode(errors='replace')[-2000:]
28
+ finally:
29
+ if p.poll() is None:p.kill();p.wait()
30
+ p.stdout.close();p.stderr.close()
31
+ return rows
32
+
33
+ def zip_members(path,names):
34
+ with zipfile.ZipFile(path) as z:
35
+ for name in names:yield name,z.read(name)
36
+
37
+ def file_members(paths):
38
+ for path in paths:yield path.name,path.read_bytes()
39
+
40
+ def view_members(p,m,frames):
41
+ source=m['components']['rgb']['source_locator'];base=c.DATA_ROOT/m['dataset_id']
42
+ if 'archive' in source:
43
+ return zip_members(base/source['archive'],[f['source_locator']['member'] for f in frames])
44
+ paths=sorted((base/'tmp'/c.RUN/m['sequence_id']/'images').glob(m['camera_id']+'-*.jpg'))
45
+ assert len(paths)==len(frames)
46
+ return file_members(paths)
47
+
48
+ def verify(p,m,members,tmp,write=False,full_pixels=False):
49
+ start=time.perf_counter();tmp.mkdir(parents=True,exist_ok=True)
50
+ prefix=m['sequence_id']+'__'+m['camera_id'];total=m['num_frames'];W,H=m['camera']['image_size']
51
+ sample,seed=indices_for(m['sequence_id'],m['camera_id'],total)
52
+ if full_pixels:sample=list(range(total))
53
+ chosen=set(sample);spool=tmp/(prefix+'.mjpeg');sample_source=tmp/(prefix+'.sample-source.mjpeg');sample_output=tmp/(prefix+'.sample-output.mjpeg')
54
+ hashes=[];modes=set();created=[sample_source,sample_output]
55
+ sink=spool.open('wb') if write else None
56
+ if write:created.append(spool)
57
+ try:
58
+ with sample_source.open('wb') as selected:
59
+ for i,(name,content) in enumerate(members):
60
+ assert content[:2]==b'\xff\xd8',name
61
+ with c.Image.open(io.BytesIO(content)) as image:
62
+ assert list(image.size)==[W,H],(name,image.size,[W,H])
63
+ modes.add(image.mode)
64
+ hashes.append((len(content),hashlib.sha256(content).hexdigest()))
65
+ if sink:sink.write(content)
66
+ if i in chosen:selected.write(content)
67
+ if sink:sink.close();sink=None
68
+ assert len(hashes)==total
69
+ source_s=time.perf_counter()-start
70
+ dst=p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
71
+ if write:c.command([c.FF,'-v','error','-y','-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',spool,'-map','0:v:0','-c:v','copy',dst])
72
+ mux_s=time.perf_counter()-start-source_s
73
+ packet=c.framehash(['-i',str(dst)],copy=True);assert packet==hashes,'JPEG count/order/payload changed'
74
+ packet_s=time.perf_counter()-start-source_s-mux_s
75
+ if full_pixels:
76
+ c.command([c.FF,'-v','error','-y','-i',dst,'-map','0:v:0','-c:v','copy','-f','image2pipe',sample_output])
77
+ else:
78
+ # n is the zero-based packet index. No bitstream noise is added.
79
+ keep='+'.join(f'eq(n,{i})' for i in sample)
80
+ c.command([c.FF,'-v','error','-y','-i',dst,'-map','0:v:0','-c:v','copy','-bsf:v',f"noise=amount=0:drop='not({keep})'",'-f','image2pipe',sample_output])
81
+ sample_args=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(sample_output)]
82
+ selected_packets=c.framehash(sample_args,copy=True)
83
+ assert selected_packets==[hashes[i] for i in sample],'Sample extraction changed bytes or indices'
84
+ native_args=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(sample_source)]
85
+ before=rgb_hashes(native_args,W,H,len(sample))
86
+ # Decode directly from the MKV so container-level color/rotation semantics are tested.
87
+ if full_pixels:
88
+ after=rgb_hashes(['-i',str(dst)],W,H,total)
89
+ else:
90
+ # MJPEG is all-intra. Seek by index-only 1fps PTS; validate the selected
91
+ # packet at each seek before RGB comparison to guard off-by-one seeking.
92
+ after=[]
93
+ for i in sample:
94
+ seek=['-ss',str(i),'-i',str(dst)]
95
+ check=c.command([c.FF,'-v','error',*seek,'-map','0:v:0','-frames:v','1','-c:v','copy','-f','framehash','-hash','sha256','pipe:1']).decode()
96
+ rows=[s for s in check.splitlines() if s and not s.startswith('#')]
97
+ assert len(rows)==1 and (int(rows[0].split(',')[-2]),rows[0].split(',')[-1].strip())==hashes[i]
98
+ after.extend(rgb_hashes([*seek,'-frames:v','1'],W,H,1))
99
+ assert before==after,'Decoded RGB differs'
100
+ info=subprocess.run([str(c.FF),'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
101
+ stream=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
102
+ record={'test':'all_source_JPEG_packets_exact','passed':True,'frames':total,'policy':POLICY,'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),'all_JPEG_dimensions_checked':True,'source_JPEG_modes':sorted(modes),'output_bytes':dst.stat().st_size}
103
+ rgb={'test':'source_RGB_pixels_exact','passed':True,'scope':'all_frames' if full_pixels else 'deterministic_sample','frames':total,'sampled_frames':len(sample),'frame_indices':sample,'seed':seed,'seed_method':'first 8 bytes SHA256(sequence/camera/20260920), big-endian','pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'hash_implementation':'hashlib.sha256/OpenSSL','decoded_from_container':True}
104
+ timings={'source_read_hash_s':source_s,'mux_s':mux_s,'packet_check_s':packet_s,'RGB_check_s':time.perf_counter()-start-source_s-mux_s-packet_s,'total_s':time.perf_counter()-start}
105
+ return record,rgb,stream,hashes,after,timings
106
+ finally:
107
+ if sink:sink.close()
108
+ for path in created:
109
+ assert path.resolve().is_relative_to(tmp.resolve())
110
+ if path.exists():path.unlink()
111
+
112
+ def write_video(view,members):
113
+ assert c.shutil.disk_usage(c.DATA_ROOT).free>400_000_000_000,'Disk reserve reached; raw retained'
114
+ record,rgb,stream,packets,pixels,timings=verify(view.p,view.m,members,view.tmp/'accelerated-media',write=True)
115
+ pixel=c.re.search(r'Video: mjpeg[^,]*,\s*(\w+)',stream).group(1);version=c.command([c.FF,'-version']).decode().splitlines()[0]
116
+ view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],c.np.ones(view.T,bool),source=view.source,
117
+ method='Original JPEG packets copied into MKV; every payload/order/dimension checked; declared deterministic RGB sample checked',
118
+ storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':view.m['camera']['image_size'],'source_lossy':True,
119
+ 'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':stream},'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
120
+ view.checks.extend([record,rgb]);view.m['media_validation_policy']=POLICY
121
+ c.save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':packets,'pixel_sample':{'indices':rgb['frame_indices'],'values':pixels},'policy':POLICY,'timings':timings})
122
+ print('MEDIA_CHECK_COMPLETE',view.m['sequence_id'],view.m['camera_id'],round(timings['total_s'],2),flush=True)
123
+
124
+ def revalidate(p,full_pixels=False):
125
+ m=c.load(p/'metainfo.json');frames=[json.loads(l) for l in (p/'camera/frames.jsonl').read_text().splitlines()]
126
+ tmp=c.DATA_ROOT/m['dataset_id']/'tmp'/c.RUN/'accelerated-revalidation'
127
+ rec,rgb,_,_,_,timings=verify(p,m,view_members(p,m,frames),tmp,full_pixels=full_pixels)
128
+ return {'sequence_id':m['sequence_id'],'camera_id':m['camera_id'],'checks':[rec,rgb],'timings':timings}
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/arctic_object_review.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Eleven-object, complete-sequence review. No full-dataset conversion or upload.
2
+
3
+ Raw archives stay immutable. Two bounded camera workers, sequence-scoped caches.
4
+ """
5
+ from fresh_sequence_common import *
6
+ from convert_fresh_sequence_pilots import arctic
7
+ from diagnose_arctic_review import official_object, OFFICIAL
8
+ from review_fresh_sequence_pilots import arr, validate_view
9
+ from render_full_sequence_review import render_view, asset_preview
10
+ import concurrent.futures, html
11
+
12
+ BASE=DATA_ROOT/'ARCTIC';OUT=BASE/RELEASE
13
+ TMP=BASE/'tmp/object-review-11';DOC=OUT/'doc/validation/objects'
14
+ SELECTION=WORK/'tmp/arctic-object-selection.json'
15
+ torch.set_num_threads(3)
16
+
17
+ def context(item):
18
+ seq=item['sequence'];sid,action=seq.split('/');oid=item['object']
19
+ return seq,sid,oid,seq.replace('/','_'),DOC/oid,TMP/seq.replace('/','_')
20
+
21
+ def prepare(item):
22
+ seq,sid,oid,seqid,doc,tmp=context(item);doc.mkdir(parents=True,exist_ok=True);tmp.mkdir(parents=True,exist_ok=True)
23
+ target=tmp/'reference.npz'
24
+ if target.exists() and (doc/'reference.json').exists():return
25
+ with zipfile.ZipFile(BASE/'raw/data/meta.zip') as z:
26
+ pref=f'meta/object_vtemplates/{oid}/';params=json.loads(z.read(pref+'object_params.json'));parts=np.asarray(json.loads(z.read(pref+'parts.json')),np.int64)
27
+ vertices=np.array([[float(x) for x in r.split()[1:4]] for r in z.read(pref+'mesh.obj').decode().splitlines() if r.startswith('v ')])/1000
28
+ misc=json.loads(z.read('meta/misc.json'))[sid]
29
+ with zipfile.ZipFile(BASE/'raw/data/raw_seqs.zip') as z:
30
+ objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'));hand=native_npy_bytes(z.read(f'raw_seqs/{seq}.mano.npy'));ego=native_npy_bytes(z.read(f'raw_seqs/{seq}.egocam.dist.npy'))
31
+ with zipfile.ZipFile(BASE/'raw/data/images_zips'/f'{seq}.zip') as z:
32
+ names=[n for n in z.namelist() if n.endswith('.jpg')];cams=sorted({n.split('/')[0] for n in names});assert cams==list(map(str,range(9)))
33
+ image_counts={c:sum(n.startswith(c+'/') for n in names) for c in cams}
34
+ assert len(parts)==len(vertices) and set(np.unique(parts))=={0,1} and objects.shape[1]==7
35
+ world=[];keypoints=[]
36
+ for start in range(0,len(objects),24):
37
+ v,k=official_object(objects[start:start+24],vertices,parts,params,oid);world.append(v);keypoints.append(k)
38
+ world=np.concatenate(world);keypoints=np.concatenate(keypoints)
39
+ # Deliberately wrong part IDs, angle sign, and units must diverge from upstream.
40
+ i=int(np.argmax(objects[:,0]));o=objects[i];R=Rotation.from_rotvec(o[1:4]);H=Rotation.from_rotvec([0,0,-o[0]])
41
+ negative={}
42
+ for name,selector,angle in [('swapped_parts',parts==1,-o[0]),('reversed_joint_angle',parts==0,o[0])]:
43
+ v=vertices.copy();v[selector]=Rotation.from_rotvec([0,0,angle]).apply(v[selector]);v=R.apply(v)+o[4:7]/1000
44
+ negative[name]=float(np.linalg.norm(v-world[i],axis=-1).max());assert negative[name]>1e-4,(oid,name)
45
+ negative['millimetres_as_metres']=float(np.linalg.norm(world[i]*1000-world[i],axis=-1).max());assert negative['millimetres_as_metres']>1
46
+ hands=[]
47
+ for side in ['left','right']:
48
+ model=Mano(side);h=hand[side];pose=np.c_[h['rot'],h['pose']];pose[:,3:]+=model.data['hands_mean'];v=[]
49
+ for start in range(0,len(pose),64):
50
+ q=pose[start:start+64];v.append(model.geometry(q,np.broadcast_to(h['shape'],(len(q),10)),h['trans'][start:start+64])[0])
51
+ hands.append(np.concatenate(v).astype(np.float32))
52
+ np.savez(target,object_world=world,keypoints_world=keypoints,hand_left=hands[0],hand_right=hands[1],vertices=vertices,parts=parts,
53
+ object_params=objects,world2cam=np.asarray(misc['world2cam']),Kexo=np.asarray(misc['intris_mat']),Rego=ego['R_k_cam_np'],Tego=ego['T_k_cam_np'],Kego=ego['intrinsics'],Dego=ego['dist8'])
54
+ save(doc/'reference.json',{'object':oid,'sequence':seq,'annotation_frames':len(objects),'image_frames_per_camera':image_counts,'vertices':len(vertices),'ioi_offset':misc['ioi_offset'],
55
+ 'angle_min_max_rad':[float(objects[:,0].min()),float(objects[:,0].max())],'negative_control_max_error_m':negative,
56
+ 'reference_method':'Pinned official ObjectTensors.forward executed with raw state; SciPy quaternion primitives, all vertices and annotation frames; raw world MANO reconstructed separately.',
57
+ 'official_code':'https://github.com/zc-alexfan/arctic/blob/49f3eb4b7f01663172576357bb3d95695d7a7689/common/object_tensors.py',
58
+ 'official_code_sha256':digest(OFFICIAL/'common/object_tensors.py'),'scope_limit':'Comparison proves faithful conversion, not source-to-image accuracy. Human acceptance remains pending.'})
59
+ print('REFERENCE_READY',oid,len(objects),len(vertices),flush=True)
60
+
61
+ def check_geometry(item,p):
62
+ seq,sid,oid,seqid,doc,tmp=context(item);m,frames,structure=validate_view(p);cam=m['camera_id'];ref=load(doc/'reference.json')
63
+ with np.load(tmp/'reference.npz') as loaded:a={k:loaded[k] for k in loaded.files}
64
+ ix=np.array([int(f['source_frame_id'])-ref['ioi_offset'] for f in frames]);known=(ix>=0)&(ix<len(a['object_world']))
65
+ assert [f['source_annotation_index'] for f in frames]==[int(j) if ok else None for j,ok in zip(ix,known)]
66
+ E=arr(p/'camera/extrinsic.pt');K=arr(p/'camera/intrinsic.pt');op=p/'annotation/object'/oid;meta=load(op/'metainfo.json')
67
+ vertices=np.array([[float(x) for x in row.split()[1:4]] for row in (p/meta['mesh_ref']).read_text().splitlines() if row.startswith('v ')])
68
+ assert np.max(np.abs(vertices-a['vertices']))<1e-10
69
+ part=arr(p/meta['vertex_part_ids_ref']);assert np.array_equal(part,1-a['parts'])
70
+ expectedE=np.broadcast_to(np.eye(4),(len(frames),4,4)).copy()
71
+ if cam=='0':
72
+ expectedE[:]=np.nan;expectedE[known]=np.eye(4);expectedE[known,:3,:3]=a['Rego'][ix[known]];expectedE[known,:3,3]=a['Tego'][ix[known]].reshape(-1,3)
73
+ expectedK=a['Kego'];assert np.max(np.abs(arr(p/'camera/distortion.pt')-a['Dego']))<1e-5
74
+ else:expectedE[:]=a['world2cam'][int(cam)-1];expectedK=a['Kexo'][int(cam)-1]
75
+ assert np.max(np.abs(E[known]-expectedE[known]))<2e-6 and np.max(np.abs(K-expectedK))<.002
76
+ pose=arr(op/'pose.pt');top=arr(op/'parts/top/pose.pt');joint=arr(op/'joint_state.pt');valid=arr(op/'pose_valid.pt');kp=arr(op/'keypoints/xyz.pt')
77
+ errors={'object_vertices_m':0.,'object_keypoints_m':0.,'hand_vertices_m':0.};angleerror=float(np.max(np.abs(joint[valid,0]-a['object_params'][ix[valid],0])))
78
+ assert angleerror<1e-6
79
+ articulation=load(op/'articulation.json');assert articulation['joints'][0]['axis']==[0,0,-1]
80
+ for i in np.flatnonzero(valid):
81
+ v=vertices@pose[i,:3,:3].T+pose[i,:3,3];sel=part==1;v[sel]=vertices[sel]@top[i,:3,:3].T+top[i,:3,3]
82
+ golden=a['object_world'][ix[i]]@expectedE[i,:3,:3].T+expectedE[i,:3,3]
83
+ golden_k=a['keypoints_world'][ix[i]]@expectedE[i,:3,:3].T+expectedE[i,:3,3]
84
+ errors['object_vertices_m']=max(errors['object_vertices_m'],float(np.linalg.norm(v-golden,axis=-1).max()))
85
+ errors['object_keypoints_m']=max(errors['object_keypoints_m'],float(np.linalg.norm(kp[i]-golden_k,axis=-1).max()))
86
+ motion=arr(p/'annotation/mano/motion.pt');hv=arr(p/'annotation/mano/motion_valid.pt')
87
+ for side,name in enumerate(['left','right']):
88
+ model=Mano(name);indices=np.flatnonzero(hv[:,side])
89
+ for start in range(0,len(indices),64):
90
+ ii=indices[start:start+64];v=motion[ii,side];actual=model.geometry(v[:,:48],v[:,48:58],v[:,58:])[0]
91
+ golden=a['hand_'+name][ix[ii]]@expectedE[ii,:3,:3].transpose(0,2,1)+expectedE[ii,None,:3,3]
92
+ errors['hand_vertices_m']=max(errors['hand_vertices_m'],float(np.linalg.norm(actual-golden,axis=-1).max()))
93
+ assert max(errors.values())<2e-5,(oid,cam,errors)
94
+ # Separate top/bottom/textured meshes have their own topology; validate their
95
+ # native canonical coordinates independently, never reuse mesh.obj part IDs.
96
+ asset_checks=[]
97
+ with zipfile.ZipFile(BASE/'raw/data/meta.zip') as z:
98
+ for name in ['mesh.obj','mesh_tex.obj','top.obj','bottom.obj']:
99
+ source=z.read(f'meta/object_vtemplates/{oid}/{name}').decode().splitlines();dest=(op/'assets'/name).read_text().splitlines()
100
+ sv=np.array([[float(x) for x in r.split()[1:4]] for r in source if r.startswith('v ')])/1000
101
+ dv=np.array([[float(x) for x in r.split()[1:4]] for r in dest if r.startswith('v ')])
102
+ assert sv.shape==dv.shape and np.max(np.abs(sv-dv))<1e-10
103
+ assert [r for r in source if r.startswith(('f ','vt ','vn '))]==[r for r in dest if r.startswith(('f ','vt ','vn '))]
104
+ asset_checks.append({'mesh':name,'vertices':len(sv),'canonical_scale_topology_UV_normals':'passed'})
105
+ result={'camera_id':cam,'sequence_id':seqid,'passed':True,'max_errors':errors,'tolerance_m':2e-5,'checked_object_frames':int(valid.sum()),
106
+ 'checked_vertices_per_frame':len(vertices),'mano_frames_per_side':hv.sum(0).tolist(),'asset_checks':asset_checks,'joint_angle_error_rad':angleerror}
107
+ save(doc/'checks'/f'{cam}.json',result)
108
+ return result
109
+
110
+ def snapshots_for(item,p):
111
+ oid=item['object'];q=arr(p/f'annotation/object/{oid}/joint_state.pt')[:,0];T=len(q);finite=np.flatnonzero(np.isfinite(q));later=finite[finite>=min(12,T//10)]
112
+ ix=[0,1,T-1,*np.linspace(2,T-2,13,dtype=int).tolist(),int(later[np.argmin(q[later])]),int(later[np.argmax(q[later])])]
113
+ return sorted(set(i for i in ix if 0<=i<T))
114
+
115
+ def worker(item,cam):
116
+ seq,sid,oid,seqid,doc,tmp=context(item);p=OUT/'data'/seqid/cam;resultfile=doc/'checks'/f'{cam}-complete.json'
117
+ if resultfile.exists():
118
+ result=load(resultfile)
119
+ if (doc/result['video']['video_ref']).exists() and digest(doc/result['video']['video_ref'])==result['video']['video_sha256']:
120
+ print('RESUME_CAMERA',oid,cam,flush=True);return
121
+ if shutil.disk_usage(BASE).free<400_000_000_000:raise RuntimeError('E free space below 400 GB')
122
+ arctic(seq,[cam],initialize=False)
123
+ numeric=check_geometry(item,p);indices=snapshots_for(item,p)
124
+ video=render_view(p,'ARCTIC',None,doc=doc,tmp=tmp/'render',snapshot_indices=indices)
125
+ save(resultfile,{'object':oid,'sequence':seq,'camera_id':cam,'numeric':numeric,'video':video,'visual_sample_indices':indices,'human_review':'pending'})
126
+ print('CAMERA_DONE',oid,cam,flush=True)
127
+
128
+ def contact_sheets(item,results):
129
+ seq,sid,oid,seqid,doc,tmp=context(item);files=[]
130
+ for r in results:
131
+ cam=r['camera_id'];p=OUT/'data'/seqid/cam;q=arr(p/f'annotation/object/{oid}/joint_state.pt')[:,0]
132
+ picks=r['visual_sample_indices'];canvas=Image.new('RGB',(4*480,((len(picks)+3)//4)*285),(20,20,20));draw=ImageDraw.Draw(canvas)
133
+ for cell,i in enumerate(picks):
134
+ row,col=divmod(cell,4)
135
+ im=Image.open(doc/'video_snapshots'/cam/f'{i:06d}.jpg').convert('RGB');a=np.array(im)
136
+ # Identify colored rendered geometry to crop both original and
137
+ # overlay by the same region. This is a review crop, no data edit.
138
+ mid=a[40:552,512:1024];diff=np.abs(mid.astype(int)-a[40:552,:512].astype(int)).max(2)>35
139
+ yy,xx=np.where(diff)
140
+ if len(xx):
141
+ x0=max(0,int(xx.min())-25);x1=min(512,int(xx.max())+26);y0=max(0,int(yy.min())-25);y1=min(512,int(yy.max())+26)
142
+ else:x0,y0,x1,y1=0,0,512,512
143
+ for side,xoff in enumerate([0,512]):
144
+ crop=im.crop((xoff+x0,40+y0,xoff+x1,40+y1));crop.thumbnail((236,246))
145
+ canvas.paste(crop,(col*480+side*240+(236-crop.width)//2,row*285+30))
146
+ draw.text((col*480+6,row*285+5),f'{oid} cam {cam} idx {i} q={q[i]:.2f}: RGB | projection',fill='white')
147
+ file=doc/f'contact-camera-{cam}.jpg';canvas.save(file,quality=94);files.append(file.name)
148
+ return files
149
+
150
+ def object_page(item):
151
+ seq,sid,oid,seqid,doc,tmp=context(item);cameras=load(SELECTION)['cameras'];results=[load(doc/'checks'/f'{c}-complete.json') for c in cameras]
152
+ contacts=contact_sheets(item,results)
153
+ asset=asset_preview(OUT/'data'/seqid/cameras[0]/'annotation/object'/oid,doc/'assets'/f'{oid}.mp4')
154
+ worst=max(max(r['numeric']['max_errors'].values()) for r in results)
155
+ ref=load(doc/'reference.json');dark={r['camera_id']:r['video']['exposure_diagnostics']['suspect_dark_frame_indices'] for r in results}
156
+ report={'object':oid,'sequence':seq,'camera_count':len(cameras),'camera_frames':sum(r['video']['frames'] for r in results),'full_frame_numeric_checks':'passed','maximum_geometry_error_m':worst,
157
+ 'reference':ref,'views':results,'contact_sheets':contacts,'asset_preview':asset,'agent_visual_review':{'status':'pending'},'human_review':'pending',
158
+ 'dark_candidates':dark,'valid_policy_note':'Existing laptop reviewed exposure exclusion is retained. New sequences preserve source availability; dark candidates and suspicious alignment are reported, not silently blacklisted.'}
159
+ save(doc/'report.json',report);write_object_html(report)
160
+ print('OBJECT_READY',oid,report['camera_frames'],worst,flush=True)
161
+ return report
162
+
163
+ STYLE='body{font:16px/1.6 system-ui;max-width:1550px;margin:24px auto;padding:0 20px;background:#f2f5f9;color:#162137}section,header{background:white;padding:20px;margin:18px 0;border-radius:10px}video,img{max-width:100%}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccd3de;padding:8px;text-align:left}.warn{color:#9b4414}a{color:#1265a7}'
164
+
165
+ def write_object_html(r):
166
+ doc=DOC/r['object'];status=r['agent_visual_review'];cards=''
167
+ review_text=html.escape(status.get('summary',status['status']))
168
+ if status.get('notes'):review_text+='<ul>'+''.join('<li>'+html.escape(n)+'</li>' for n in status['notes'])+'</ul>'
169
+ for v in r['views']:
170
+ vv=v['video'];cards+=f'<section><h2>Camera {v["camera_id"]} · {vv["frames"]}帧</h2><video controls preload="metadata" src="{vv["video_ref"]}"></video><p>几何数值检查通过;暗帧候选索引:{r["dark_candidates"][v["camera_id"]]}。有效MANO左右:{vv["mano_valid_counts"]}。</p></section>'
171
+ page=f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>ARCTIC {r["object"]} 完整序列验收</title><style>{STYLE}</style><header><a href="../index.html">全部物体</a><h1>{r["object"]} · {r["sequence"]}</h1><p>固定相机6、{r["camera_frames"]}个相机帧,全部已渲染。最大几何数值差{r["maximum_geometry_error_m"]:.3g}米。<a href="report.json">完整结果</a> · <a href="reference.json">官方对照及反例测试</a></p><p class="warn">代理视觉检查:{html.escape(json.dumps(status,ensure_ascii=False))};用户人工确认待完成,不自动全量或上传。</p><p>左:shared原图;中:源参数诊断投影;右:shared当前valid监督。顶盖紫、底座绿,左手青、右手橙。透视线框显示遮挡面,不是分割。播放30fps仅用于预览,源采集FPS未知。</p><p>暗帧指标仅作候选;除已有laptop曝光规则外,未添加按帧号的人工屏蔽。��序列通过不代表该物体全部序列通过。</p></header>'+cards+'<section><h2>资产及纹理</h2><video controls src="'+r['asset_preview']['video_ref']+'"></video></section><section><h2>视觉抽查对照(不代替完整视频)</h2>'+''.join(f'<a href="{f}"><img src="{f}"></a>' for f in r['contact_sheets'])+'</section><script>document.querySelectorAll("video").forEach(v=>v.addEventListener("play",()=>document.querySelectorAll("video").forEach(o=>{if(o!==v)o.pause()})));</script></html>'
172
+ page=page.replace(html.escape(json.dumps(status,ensure_ascii=False)),review_text)
173
+ page=page.replace('<p class="warn">代理视觉检查:','<div class="warn">代理视觉检查:').replace('用户人工确认待完成,不自动全量或上传。</p>','用户人工确认待完成,不自动全量或上传。</div>')
174
+ (doc/'index.html').write_text(page,encoding='utf-8')
175
+
176
+ def overview(selection):
177
+ rows=[];reports=[]
178
+ for item in selection['objects']:
179
+ doc=DOC/item['object'];p=doc/'report.json'
180
+ if p.exists():
181
+ r=load(p);reports.append(r);state='数值通过;'+('视觉已抽查(见问题记录)' if r['agent_visual_review']['status']=='reviewed_with_findings' else '视觉待检查');count=r['camera_frames'];link=f'<a href="{item["object"]}/index.html">{item["object"]}</a>'
182
+ else:state='制作中';count='—';link=item['object']
183
+ rows.append(f'<tr><td>{link}</td><td>{item["sequence"]}</td><td>{count}</td><td>{state}</td></tr>')
184
+ DOC.mkdir(parents=True,exist_ok=True)
185
+ player=''
186
+ if reports:
187
+ options=''.join(f'<option value="{r["object"]}">{r["object"]} · {r["camera_frames"]}帧</option>' for r in reports)
188
+ player='<section><h2>固定相机6,切换物体</h2><label>物体 <select id="object-picker">'+options+'</select></label> · <a id="object-detail">该物体检查记录与原图对照</a><p id="object-result"></p><video id="object-video" controls preload="metadata" style="width:100%"></video></section>'
189
+ data={r['object']:{'video':r['object']+'/'+r['views'][0]['video']['video_ref'],'summary':r['agent_visual_review'].get('summary','数值通过;视觉检查待完成')} for r in reports}
190
+ player+='<script>const objects='+json.dumps(data,ensure_ascii=False)+';const picker=document.getElementById("object-picker"),video=document.getElementById("object-video");function choose(){const k=picker.value;video.pause();video.src=objects[k].video;document.getElementById("object-detail").href=k+"/index.html";document.getElementById("object-result").textContent=objects[k].summary;video.load();}picker.addEventListener("change",choose);choose();</script>'
191
+ (DOC/'index.html').write_text(f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>ARCTIC 11种物体完整序列验收</title><style>{STYLE}</style><header><h1>ARCTIC · 11种物体逐项验收</h1><p>新增组统一采用s06的固定相机6,11种物体各一段完整序列;相机内外参保持一致。<a href="../index.html">原s09 laptop九路相机预览</a>保留。按明显开合幅度选择较短完整序列,不裁切源帧。</p><p>已完成{len(reports)}/11种物体。<a href="selection.json">选择依据</a> · <a href="REPORT.md">验收结论</a> · <a href="report.json">总报告</a></p><p class="warn">自动数值通过≠图像对齐无误≠用户人工通过。未开始全量处理或上传。</p></header>'+player+'<section><table><tr><th>物体/完整视频</th><th>序列</th><th>相机帧数</th><th>检查状态</th></tr>'+''.join(rows)+'</table></section></html>',encoding='utf-8')
192
+ save(DOC/'selection.json',selection);save(DOC/'report.json',{'scope':'11 whole sequences, fixed subject s06 and fixed static camera 6; original laptop 9-camera group retained separately','completed_objects':len(reports),'expected_objects':11,'objects':[{'object':r['object'],'sequence':r['sequence'],'camera_frames':r['camera_frames'],'maximum_geometry_error_m':r['maximum_geometry_error_m'],'agent_visual_review':r['agent_visual_review']} for r in reports],'human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
193
+
194
+ def run():
195
+ selection=load(SELECTION);TMP.mkdir(parents=True,exist_ok=True);DOC.mkdir(parents=True,exist_ok=True)
196
+ state=load(WORK/'tmp/dataset-work-state.json');state['active']['ARCTIC'].update(stage='pilot_all_objects_rendering',object_review_scope=selection['objects']);save(WORK/'tmp/dataset-work-state.json',state)
197
+ setup('ARCTIC','eleven_object_review');overview(selection)
198
+ def launch(item):
199
+ seq,sid,oid,seqid,doc,tmp=context(item)
200
+ for cam in selection['cameras']:
201
+ log=tmp/f'worker-{cam}.log'
202
+ with log.open('ab') as f:
203
+ proc=subprocess.run([sys.executable,'-u',str(Path(__file__).resolve()),'worker','--object',oid,'--camera',cam],stdout=f,stderr=subprocess.STDOUT)
204
+ if proc.returncode:raise RuntimeError(f'{oid} camera {cam} failed, see {log}')
205
+ return item
206
+ with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
207
+ futures=[]
208
+ for item in selection['objects']:
209
+ prepare(item)
210
+ if (context(item)[4]/'report.json').exists():print('RESUME_OBJECT',item['object'],flush=True);continue
211
+ futures.append(pool.submit(launch,item))
212
+ for future in concurrent.futures.as_completed(futures):
213
+ item=future.result();object_page(item);overview(selection)
214
+ save(TMP/'status.json',{'object':item['object'],'stage':'converting_rendering','completed_views_total':len(list(DOC.glob('*/checks/*-complete.json')))})
215
+ # Do not repopulate the organized script root while rendering review artifacts.
216
+ save(TMP/'status.json',{'stage':'all_objects_rendered_pending_visual_inspection','completed_views_total':len(selection['objects'])*len(selection['cameras'])})
217
+ print('ALL_OBJECTS_RENDERED',flush=True)
218
+
219
+ if __name__=='__main__':
220
+ parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['run','worker','overview']);parser.add_argument('--object');parser.add_argument('--camera');args=parser.parse_args()
221
+ if args.mode=='worker':worker(next(x for x in load(SELECTION)['objects'] if x['object']==args.object),args.camera)
222
+ elif args.mode=='overview':overview(load(SELECTION))
223
+ else:run()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/audit_source_fields.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read small existing native annotations; do not convert or download data."""
2
+ from pilot_build import *
3
+
4
+ def shape_tree(x, depth=0):
5
+ if isinstance(x,(np.ndarray,torch.Tensor)):
6
+ if isinstance(x,np.ndarray) and x.dtype==object and x.shape==():return shape_tree(x.item(),depth)
7
+ return {'shape':list(x.shape),'dtype':str(x.dtype)}
8
+ if isinstance(x,dict):
9
+ if len(x)>30:return {'count':len(x),'first_key':str(next(iter(x))),'first_value':shape_tree(next(iter(x.values())),depth+1)}
10
+ return {str(k):shape_tree(v,depth+1) for k,v in x.items()}
11
+ if isinstance(x,(list,tuple)):
12
+ try:
13
+ a=np.asarray(x)
14
+ if a.dtype.kind in 'biuf':return {'shape':list(a.shape),'dtype':str(a.dtype)}
15
+ except (ValueError,TypeError):pass
16
+ return {'count':len(x),'first':shape_tree(x[0],depth+1) if x else None}
17
+ return x if isinstance(x,(str,int,float,bool)) or x is None else type(x).__name__
18
+
19
+ def native_npy(p):
20
+ with p.open('rb') as f:
21
+ version=np.lib.format.read_magic(f)
22
+ if version==(1,0):_,_,dtype=np.lib.format.read_array_header_1_0(f)
23
+ else:_,_,dtype=np.lib.format.read_array_header_2_0(f)
24
+ if dtype.hasobject:return Restricted(f,encoding='latin1').load()
25
+ return np.load(p,allow_pickle=False)
26
+
27
+ def main():
28
+ rows=[]
29
+ def add(ds,p,x,detail=None):rows.append({'dataset':ds,'path':str(p.relative_to(WORK)).replace('\\','/'),'fields':shape_tree(x),'detail':detail})
30
+ p=next((WORK/'tmp/pilot-dex').rglob('labels_000001.npz'))
31
+ with np.load(p,allow_pickle=False) as z:add('Dex-YCB',p,{k:z[k] for k in z.files})
32
+ p=next((ROOT/'VISOR/raw/data').rglob('P01_03.json'));x=load(p);frames=x['video_annotations'];keys=sorted({k for f in frames for a in f['annotations'] for k in a})
33
+ add('VISOR',p,frames[0],{'top_level_keys':list(x),'annotation_keys_all_local_frames':keys,'frames':len(frames),'image_keys':sorted({k for f in frames for k in f['image']})})
34
+ for folder in ['hand_pose','hand_pose_mano','cam_pose']:
35
+ p=ROOT/'H2O/raw/data/local_subset/subject4_ego/h1/0/cam4'/folder/'000000.txt';add('H2O',p,np.loadtxt(p))
36
+ p=next((ROOT/'HOI4D/raw/data').rglob('*.pickle'));add('HOI4D',p,read_pickle(p))
37
+ for name in ['training_K.json','training_mano.json','training_scale.json']:
38
+ p=next((ROOT/'FreiHAND/raw/data').rglob(name));x=load(p);add('FreiHAND',p,x[0],{'rows':len(x)})
39
+ p=next((ROOT/'RHD/raw/data').rglob('anno_evaluation.pickle'));x=read_pickle(p);a=x[0];add('RHD',p,a,{'records':len(x),'visibility_values':np.unique(a['uv_vis'][:,2]).tolist(),'invisible_points_first_sample':int((a['uv_vis'][:,2]==0).sum())})
40
+ p=next((ROOT/'ARCTIC/raw/data').rglob('*.mano.npy'));add('ARCTIC',p,native_npy(p))
41
+ p=next((ROOT/'ARCTIC/raw/data').rglob('*.egocam.dist.npy'));x=native_npy(p).item();add('ARCTIC',p,x,{'dist8':np.asarray(x['dist8']).tolist()})
42
+ p=next((ROOT/'OakInk2/raw/data').rglob('*.pkl'));x=read_pickle(p);add('OakInk2',p,x,{'frame_ids_first':x['frame_id_list'][:5],'mocap_ids_first':x['mocap_frame_id_list'][:5],'object_ids':x['obj_list']})
43
+ p=next((ROOT/'ReInterHand/raw/data').rglob('*_left.json'));add('ReInterHand',p,load(p))
44
+ p=OLD/'HOT3D/P0001_10a27bf7/mano_hand_pose_trajectory.jsonl';add('HOT3D',p,json.loads(p.open().readline()))
45
+ p=next((ROOT/'HOT3D/raw/data').glob('*ground_truth.zip'))
46
+ with zipfile.ZipFile(p) as z:
47
+ headers={}
48
+ for name in z.namelist():
49
+ if name.endswith('.csv'):
50
+ with z.open(name) as f:headers[name]=f.readline().decode().strip()
51
+ add('HOT3D',p,headers)
52
+ save(WORK/'docs/source-field-audit-evidence.json',{'purpose':'native field shape probe; not a full conversion or whole-dataset validation','records':rows})
53
+ print(json.dumps({'datasets':sorted({r['dataset'] for r in rows}),'records':len(rows),'output':'docs/source-field-audit-evidence.json'},indent=2))
54
+
55
+ if __name__=='__main__':main()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/convert_fresh_sequence_pilots.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert one complete, freshly downloaded sequence per dataset, all cameras.
2
+
3
+ Run: python scripts/convert_fresh_sequence_pilots.py ARCTIC|HOT3D
4
+ Requires the local CPU runtime and licensed MANO models described in README.md.
5
+ No full-dataset conversion or upload is performed by this entry point.
6
+ """
7
+ from fresh_sequence_common import *
8
+ from pilot_hot_normalize import csv_transform, transform
9
+ from accelerated_media import zip_members,file_members
10
+ import concurrent.futures
11
+
12
+ ARCTIC_SEQ='s09/laptop_use_03'
13
+ HOT3D_SEQ='P0015_179e1b84'
14
+
15
+ def loadzipcsv(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
16
+
17
+ def expand(rows,indices,shape):
18
+ a=np.full(shape,np.nan);good=(indices>=0)&(indices<len(rows));a[good]=np.asarray(rows)[indices[good]]
19
+ return a,good
20
+
21
+ def arctic_unlabelled(seq,cameras=None):
22
+ """Official held-out s03 RGB: static calibration/assets, no hidden GT guesses."""
23
+ base=DATA_ROOT/'ARCTIC';raw=base/'raw/data';sid,action=seq.split('/');oid=action.split('_')[0];seqid=seq.replace('/','_')
24
+ with zipfile.ZipFile(raw/'splits_json.zip') as z:splitdef=json.loads(z.read('splits_json/protocol_p1.json'))
25
+ assert seq in splitdef['test']
26
+ source={'archive':f'raw/data/images_zips/{seq}.zip','member_pattern':'{camera_id}/{source_frame_id:05d}.jpg'}
27
+ with zipfile.ZipFile(raw/'meta.zip') as za,zipfile.ZipFile(raw/f'images_zips/{seq}.zip') as zi:
28
+ misc=json.loads(za.read('meta/misc.json'))[sid];prefix=f'meta/object_vtemplates/{oid}/'
29
+ native_parts=np.asarray(json.loads(za.read(prefix+'parts.json')),np.int64)
30
+ names=sorted(n for n in zi.namelist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',n))
31
+ for cam in sorted({n.split('/')[0] for n in names},key=int):
32
+ if cameras is not None and cam not in cameras:continue
33
+ selected=[n for n in names if n.split('/')[0]==cam];ids=[int(Path(n).stem) for n in selected]
34
+ size=list(Image.open(io.BytesIO(zi.read(selected[0]))).size);assert size==misc['image_size'][int(cam)]
35
+ v=FreshView('ARCTIC',seqid,cam,ids,size,dict(source,camera_id=cam))
36
+ if (v.p/'metainfo.json').exists() and load(v.p/'metainfo.json').get('pilot_complete'):
37
+ print('RESUME verified view',seq,cam,flush=True);continue
38
+ t=v.T;v.m.update(split='test',split_scheme='ARCTIC_protocol_p1',split_source_locator={'archive':'raw/data/splits_json.zip','member':'splits_json/protocol_p1.json','sequence':seq},view_type='ego' if cam=='0' else 'exo',source_hand_object_gt_available=False)
39
+ v.m['sampling'].update(source_fps=None,source_fps_reason='Capture FPS not asserted by supplied source; original image numbers retained')
40
+ if cam!='0':
41
+ src={'archive':'raw/data/meta.zip','member':'meta/misc.json','record':sid}
42
+ v.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
43
+ K=np.broadcast_to(misc['intris_mat'][int(cam)-1],(t,3,3));E=np.broadcast_to(misc['world2cam'][int(cam)-1],(t,4,4))
44
+ v.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',K,np.ones(t,bool),['T','row','column'],source=src)
45
+ v.array('extrinsic','camera/extrinsic.pt','transform/se3/v1',E,np.ones(t,bool),['T','row','column'],source=src,unit='m',convention='T_camera_from_world');assert_se3(E)
46
+ for row,name in zip(v.frames,selected):row.update(sync_id=f'{seq}:{row["source_frame_id"]}',source_annotation_index=None);row['source_locator'].update(member=name)
47
+ rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';object_textured_assets(za,prefix,assets)
48
+ parts=1-native_parts;tensor(op/'vertex_part_ids.pt',parts)
49
+ articulation={'hierarchy_semantics':'mechanical_articulation','parts':[{'part_id':'bottom','parent_id':None,'has_model':True,'mesh_ref':rel+'/assets/bottom.obj'},{'part_id':'top','parent_id':'bottom','has_model':True,'mesh_ref':rel+'/assets/top.obj'}],
50
+ 'joints':[{'joint_id':'hinge','parent_part':'bottom','child_part':'top','type':'revolute','unit':'rad','axis':[0,0,-1],'axis_frame':'parent_part','zero_transform':np.eye(4).tolist(),'positive_direction':'right_hand_rule_about_axis','limits':None}],'joint_order':['hinge']}
51
+ save(op/'articulation.json',articulation);sourceasset={'archive':'raw/data/meta.zip','member_prefix':prefix}
52
+ v.component('object_'+oid+'_articulation',rel+'/articulation.json','object/articulated/v1',[],np.array(True),source=sourceasset,static=True)
53
+ v.mesh(oid,rel+'/assets/mesh.obj',sourceasset)
54
+ original=np.asarray([[float(x) for x in l.split()[1:4]] for l in za.read(prefix+'mesh.obj').decode().splitlines() if l.startswith('v ')])/1000
55
+ actual=np.asarray([[float(x) for x in l.split()[1:4]] for l in (assets/'mesh.obj').read_text().splitlines() if l.startswith('v ')])
56
+ assert np.array_equal(original,actual) and len(parts)==len(actual)
57
+ save(op/'metainfo.json',{'object_id':oid,'identity_scope':'sequence','scope_id':seqid,'association_basis':'official_sequence_object_name; no per-frame object pose released','has_model':True,'mesh_ref':rel+'/assets/mesh.obj','articulation_ref':rel+'/articulation.json','vertex_part_ids_ref':rel+'/vertex_part_ids.pt','topology_id':'sha256:'+digest(assets/'mesh.obj'),'part_mapping':{'0':'bottom','1':'top'},'part_id_conversion':{'formula':'shared_id = 1 - raw_parts_json_value','source_locator':dict(sourceasset,member=prefix+'parts.json')},'unit':'m','source_locator':sourceasset})
58
+ v.checks.append({'test':'source_static_mesh_vertices_metres_and_part_ids','passed':True,'vertices':len(actual)})
59
+ v.m['omitted_components']={'mano':'Official test ground truth withheld: no sequence MANO file in raw_seqs.zip','object_pose':'Official test ground truth withheld: no sequence object trajectory, joint states or camera-frame keypoints','keypoints':'No released sequence hand keypoint supervision','visibility':'Not provided in selected official release','depth':'No source depth images','segment':'No source pixel masks','contact':'No native contact labels in downloaded scope'}
60
+ if cam=='0':v.m['omitted_components'].update(intrinsic='No test sequence egocam.dist.npy; do not reuse another subject calibration',extrinsic='No released egocentric trajectory for test sequence')
61
+ print('MEDIA ARCTIC',cam,t,flush=True);submit_media(v,lambda archive=raw/f'images_zips/{seq}.zip',items=tuple(selected):zip_members(archive,items))
62
+
63
+ def arctic(sequence=None,cameras=None,initialize=True):
64
+ dataset='ARCTIC';seq=sequence or ARCTIC_SEQ;sid,action=seq.split('/');oid=action.split('_')[0];seqid=seq.replace('/','_')
65
+ if initialize:setup(dataset,seqid)
66
+ base=DATA_ROOT/dataset;raw=base/'raw/data'
67
+ with zipfile.ZipFile(raw/'raw_seqs.zip') as z:
68
+ if f'raw_seqs/{seq}.mano.npy' not in z.namelist():
69
+ assert all(f'raw_seqs/{seq}.{x}.npy' not in z.namelist() for x in ['object','egocam.dist'])
70
+ return arctic_unlabelled(seq,cameras)
71
+ hand=native_npy_bytes(z.read(f'raw_seqs/{seq}.mano.npy'))
72
+ ego=native_npy_bytes(z.read(f'raw_seqs/{seq}.egocam.dist.npy'))
73
+ objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'))
74
+ with zipfile.ZipFile(raw/'splits_json.zip') as z:splitdef=json.loads(z.read('splits_json/protocol_p1.json'))
75
+ split=next((k for k,v in splitdef.items() if seq in v),'unknown')
76
+ if split=='val':split='val'
77
+ za=zipfile.ZipFile(raw/'meta.zip');misc=json.loads(za.read('meta/misc.json'))[sid]
78
+ params=json.loads(za.read(f'meta/object_vtemplates/{oid}/object_params.json'))
79
+ native_parts=np.asarray(json.loads(za.read(f'meta/object_vtemplates/{oid}/parts.json')),np.int64)
80
+ models=[Mano('left'),Mano('right')];N=len(objects)
81
+ world=np.broadcast_to(np.eye(4),(N,4,4)).copy();world[:,:3,:3]=Rotation.from_rotvec(objects[:,1:4]).as_matrix();world[:,:3,3]=objects[:,4:7]/1000
82
+ hinge=np.broadcast_to(np.eye(4),(N,4,4)).copy();hinge[:,:3,:3]=Rotation.from_rotvec(np.c_[np.zeros((N,2)),-objects[:,0]]).as_matrix()
83
+ kp=np.concatenate([params['keypoints_top'],params['keypoints_bottom']])/1000;n_top=len(params['keypoints_top'])
84
+ source={'archive':f'raw/data/images_zips/{seq}.zip','member_pattern':'{camera_id}/{source_frame_id:05d}.jpg'}
85
+ zimage=zipfile.ZipFile(raw/f'images_zips/{seq}.zip')
86
+ names=sorted(n for n in zimage.namelist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',n))
87
+ extra=[n for n in zimage.namelist() if n.endswith('.jpg') and not re.fullmatch(r'[0-8]/[0-9]+\.jpg',n)]
88
+ assert all(n.startswith('__MACOSX/') or Path(n).name.startswith('._') for n in extra),extra[:5]
89
+ for cam in sorted({n.split('/')[0] for n in names},key=int):
90
+ if cameras is not None and cam not in cameras:continue
91
+ selected=[n for n in names if n.split('/')[0]==cam];ids=np.asarray([int(Path(n).stem) for n in selected]);ix=ids-misc['ioi_offset']
92
+ size=list(Image.open(io.BytesIO(zimage.read(selected[0]))).size)
93
+ assert size==misc['image_size'][int(cam)]
94
+ v=FreshView(dataset,seqid,cam,ids,size,dict(source,camera_id=cam))
95
+ if (v.p/'metainfo.json').exists():
96
+ old=load(v.p/'metainfo.json')
97
+ if old.get('pilot_complete') and old.get('num_frames')==len(ids):print('RESUME verified view',seq,cam,flush=True);continue
98
+ t=v.T;good=(ix>=0)&(ix<N)
99
+ v.m.update(split=split,split_scheme='ARCTIC_protocol_p1',split_source_locator={'archive':'raw/data/splits_json.zip','member':'splits_json/protocol_p1.json','sequence':seq},view_type='ego' if cam=='0' else 'exo')
100
+ v.m['sampling'].update(source_fps=30.0,source_fps_basis='ARCTIC paper v3, Sec. 3.2 Acquisition Setup: 8 static allocentric and 1 moving egocentric RGB views captured at 30 FPS',source_fps_evidence_url='https://arxiv.org/html/2204.13662v3#S3.SS2',source_timestamp_status='not_released; do not invent measured timestamp_ns',selection='Every released image of this selected camera in the complete official sequence ZIP; boundary images without annotations retained')
101
+ srcanno={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.mano.npy','index_ref':'camera/frames.jsonl:source_annotation_index'}
102
+ srccam={'archive':'raw/data/meta.zip','member':'meta/misc.json','record':sid}
103
+ E=np.broadcast_to(np.eye(4),(t,4,4)).copy()
104
+ if cam=='0':
105
+ K=np.broadcast_to(ego['intrinsics'],(t,3,3));D=np.broadcast_to(ego['dist8'],(t,8))
106
+ E[:]=np.nan;E[good]=np.eye(4);E[good,:3,:3]=ego['R_k_cam_np'][ix[good]];E[good,:3,3]=ego['T_k_cam_np'][ix[good]].reshape(-1,3)
107
+ src={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.egocam.dist.npy'}
108
+ v.m['camera'].update(model='rational8',schema_id='camera/rational8/v1')
109
+ v.array('intrinsic','camera/intrinsic.pt','camera/rational8/v1',K,np.ones(t,bool),['T','row','column'],source=src,distortion_ref='camera/distortion.pt')
110
+ tensor(v.p/'camera/distortion.pt',np.asarray(D,np.float32));validE=good
111
+ else:
112
+ K=np.broadcast_to(misc['intris_mat'][int(cam)-1],(t,3,3));D=None;E[:]=misc['world2cam'][int(cam)-1];validE=np.ones(t,bool);src=srccam
113
+ v.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
114
+ v.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',K,np.ones(t,bool),['T','row','column'],source=srccam)
115
+ v.array('extrinsic','camera/extrinsic.pt','transform/se3/v1',E,validE,['T','row','column'],source=src,unit='m',convention='T_camera_from_world')
116
+ assert_se3(E[validE]);motion=np.full((t,2,61),np.nan)
117
+ for side,model in enumerate(models):
118
+ h=hand[['left','right'][side]];pose=np.c_[h['rot'],h['pose']].copy();pose[:,3:]+=model.data['hands_mean']
119
+ result,err=camera_mano(model,pose[ix[good]],np.broadcast_to(h['shape'],(good.sum(),10)),h['trans'][ix[good]],E[good])
120
+ motion[good,side]=result
121
+ # Independent source-model mean configuration, separate from camera conversion algebra.
122
+ from types import SimpleNamespace
123
+ import smplx
124
+ native=smplx.MANO(model_path=str(WORK/'tmp/pilot-models'),data_struct=SimpleNamespace(**model.data),is_rhand=side==1,use_pca=False,flat_hand_mean=False)
125
+ checkidx=np.arange(0,N,max(1,N//12));b=torch.tensor(np.broadcast_to(h['shape'],(len(checkidx),10)).copy(),dtype=torch.float32)
126
+ with torch.no_grad():expected=native(global_orient=torch.tensor(h['rot'][checkidx]),hand_pose=torch.tensor(h['pose'][checkidx]),betas=b,transl=torch.tensor(h['trans'][checkidx])).vertices.numpy()
127
+ actual=model.geometry(pose[checkidx],b.numpy(),h['trans'][checkidx])[0]
128
+ delta=float(np.max(np.linalg.norm(expected-actual,axis=-1)));assert delta<2e-6
129
+ v.checks.append({'test':'MANO_mean_and_camera_transform','side':side,'all_aligned_frames':int(good.sum()),'camera_max_m':err,'native_mean_max_m':delta,'passed':True})
130
+ v.array('mano','annotation/mano/motion.pt','mano/axis_angle61/v1',motion,np.broadcast_to(good[:,None],(t,2)),['T','hand','parameter'],source=srcanno,unit='m',angle_unit='rad',coordinate_frame='camera',model_profile={'version':'MANO-v1.2','flat_hand_mean':True,'left_shapedirs_fix':False},method='Official nonflat mean expanded; shape-dependent root corrected during world-to-camera conversion; image index minus official ioi_offset')
131
+ for i,(row,name,j) in enumerate(zip(v.frames,selected,ix)):
132
+ row.update(source_annotation_index=int(j) if good[i] else None,sync_id=f'{seq}:{ids[i]}')
133
+ row['source_locator'].update(member=name)
134
+ row['annotation_matches']={'mano':{'source_frame_id':str(j) if good[i] else None,'source_timestamp_ns':None,'clock_domain':None,'match_method':'index_map','delta_ns':None,'mapping':'image_number - misc.ioi_offset','source_record_present':bool(good[i])}}
135
+ rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';object_textured_assets(za,f'meta/object_vtemplates/{oid}/',assets)
136
+ # Parse exact OBJ vertex ordering before loading a render-oriented mesh.
137
+ vertices=np.array([[float(x) for x in r.split()[1:4]] for r in (assets/'mesh.obj').read_text().splitlines() if r.startswith('v ')])
138
+ # Official ObjectTensors adds 1 to raw parts, then articulates ==1: raw 0 is TOP.
139
+ shared_parts=1-native_parts
140
+ assert len(vertices)==len(native_parts);tensor(op/'vertex_part_ids.pt',shared_parts)
141
+ P=np.full((t,4,4),np.nan);top=P.copy();P[good]=E[good]@world[ix[good]];top[good]=P[good]@hinge[ix[good]]
142
+ srcobj={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.object.npy','index_ref':'camera/frames.jsonl:source_annotation_index'}
143
+ for name,data in [('root',P),('bottom',P),('top',top)]:
144
+ path=rel+('/pose.pt' if name=='root' else f'/parts/{name}/pose.pt')
145
+ v.array(f'object_{oid}_{name}_pose',path,'object/rigid/v1',data,good,['T','row','column'],source=srcobj,unit='m',convention='T_camera_from_object' if name=='root' else 'T_camera_from_part')
146
+ assert_se3(data[good])
147
+ joint,_=expand(objects[:,:1],ix,(t,1));v.array(f'object_{oid}_joint',rel+'/joint_state.pt','object/joint_state/v1',joint,good[:,None],['T','joint'],source=srcobj,joint_order=['hinge'],unit='rad')
148
+ articulation={'hierarchy_semantics':'mechanical_articulation','parts':[{'part_id':'bottom','parent_id':None,'has_model':True,'mesh_ref':rel+'/assets/bottom.obj'},{'part_id':'top','parent_id':'bottom','has_model':True,'mesh_ref':rel+'/assets/top.obj'}],
149
+ 'joints':[{'joint_id':'hinge','parent_part':'bottom','child_part':'top','type':'revolute','unit':'rad','axis':[0,0,-1],'axis_frame':'parent_part','zero_transform':np.eye(4).tolist(),'positive_direction':'right_hand_rule_about_axis','limits':None}],'joint_order':['hinge']}
150
+ save(op/'articulation.json',articulation)
151
+ v.component('object_'+oid+'_articulation',rel+'/articulation.json','object/articulated/v1',[],np.array(True),source=srcobj,static=True)
152
+ sourceasset={'archive':'raw/data/meta.zip','member_prefix':f'meta/object_vtemplates/{oid}/'}
153
+ v.mesh(oid,rel+'/assets/mesh.obj',sourceasset)
154
+ topology=digest(assets/'mesh.obj')
155
+ save(op/'metainfo.json',{'object_id':oid,'identity_scope':'sequence','scope_id':seqid,'association_basis':'official_sequence_object_identity_shared_across_cameras','has_model':True,'mesh_ref':rel+'/assets/mesh.obj','articulation_ref':rel+'/articulation.json','vertex_part_ids_ref':rel+'/vertex_part_ids.pt','topology_id':'sha256:'+topology,'part_mapping':{'0':'bottom','1':'top'},'part_id_conversion':{'formula':'shared_id = 1 - raw_parts_json_value','source_locator':dict(sourceasset,member=f'meta/object_vtemplates/{oid}/parts.json')},'unit':'m','source_locator':srcobj})
156
+ xyz=np.full((t,len(kp),3),np.nan);errs=[]
157
+ for i in np.flatnonzero(good):
158
+ xyz[i]=kp@P[i,:3,:3].T+P[i,:3,3];xyz[i,:n_top]=kp[:n_top]@top[i,:3,:3].T+top[i,:3,3]
159
+ ref=vertices.copy();j=ix[i];ref[native_parts==0]=Rotation.from_rotvec([0,0,-float(objects[j,0])]).apply(ref[native_parts==0]);ref=Rotation.from_rotvec(objects[j,1:4]).apply(ref)+objects[j,4:7]/1000;ref=ref@E[i,:3,:3].T+E[i,:3,3]
160
+ out=vertices@P[i,:3,:3].T+P[i,:3,3];out[shared_parts==1]=vertices[shared_parts==1]@top[i,:3,:3].T+top[i,:3,3];errs.append(float(np.linalg.norm(out-ref,axis=1).max()))
161
+ assert max(errs)<2e-5
162
+ v.array('object_'+oid+'_keypoints',rel+'/keypoints/xyz.pt','object_keypoints/camera/v1',xyz,np.broadcast_to(good[:,None],(t,len(kp))),['T','joint','coordinate'],source=sourceasset,unit='m',coordinate_frame='camera',keypoint_schema='arctic_object_keypoints/v1',keypoint_names=[f'top_{i}' for i in range(n_top)]+[f'bottom_{i}' for i in range(len(kp)-n_top)],kind='derived',method='Official template keypoints driven by released articulation and camera transforms')
163
+ v.checks.append({'test':'all_frame_articulated_geometry_independent_scipy_rotation','passed':True,'max_m':max(errs),'angle_min_max_rad':[float(objects[:,0].min()),float(objects[:,0].max())]})
164
+ v.m['omitted_components']={'depth':'No depth images in this official raw release','segment':'No pixel segmentation in this official raw release','contact':'No source contact labels in selected official raw packages','keypoints':'No separate measured hand keypoints in raw; MANO available. Render-only joints are not published as additional labels','visibility':'Not supplied in selected raw annotations; fitting_err is outside current shared scope'}
165
+ print('MEDIA',dataset,cam,t,flush=True);submit_media(v,lambda archive=raw/f'images_zips/{seq}.zip',items=tuple(selected):zip_members(archive,items))
166
+ zimage.close();za.close()
167
+
168
+ def vrs_records(path,cam):
169
+ import hot3d_storage as storage
170
+ if storage.enabled():return storage.records(path,cam)
171
+ raw=command([VRS,'print-json',path,'+',cam,'+','data']).decode(errors='replace')
172
+ rows=[]
173
+ for line in raw.splitlines():
174
+ if line.startswith('{"data_layout"'):rows.append({x['name']:x['value'] for x in json.loads(line)['data_layout']})
175
+ return rows
176
+
177
+ def nearest(times,query,limit):
178
+ times=np.asarray(times,np.int64);q=np.asarray(query,np.int64)
179
+ if not len(times):return np.zeros(len(q),np.int64),np.zeros(len(q),bool),np.zeros(len(q),np.int64)
180
+ j=np.searchsorted(times,q);a=np.clip(j-1,0,len(times)-1);b=np.clip(j,0,len(times)-1)
181
+ ix=np.where(np.abs(times[a]-q)<=np.abs(times[b]-q),a,b);delta=times[ix]-q
182
+ return ix,np.abs(delta)<=limit,delta
183
+
184
+ def verify_hot3d_frame_order_and_metadata(sequence=None):
185
+ """Independent extraction-index and VRS capture-rate check, also on resume."""
186
+ seq=sequence or HOT3D_SEQ
187
+ base=DATA_ROOT/'HOT3D';src=base/'raw/data/Aria'/seq;recording=next(src.glob('*.vrs'))
188
+ extract=base/'tmp'/RUN/seq/'images'
189
+ import hot3d_storage as storage
190
+ if storage.enabled():extract=storage.images(recording)
191
+ for cam in ['214-1','1201-1','1201-2']:
192
+ p=base/RELEASE/'data'/seq/cam;m=load(p/'metainfo.json');rows=vrs_records(recording,cam)
193
+ paths=sorted(extract.glob(cam+'-*.jpg'))
194
+ indices=[int(x.name.split('-')[-2]) for x in paths];assert indices==list(range(1,len(rows)+1))
195
+ file_times=np.array([float(x.stem.split('-')[-1]) for x in paths]);times=np.array([r['capture_timestamp_ns'] for r in rows])/1e9
196
+ assert np.max(np.abs(file_times-times))<.001,'extracted images do not match camera record ordering'
197
+ if storage.enabled():cfg=storage.records(recording,cam,'configuration')[0]
198
+ else:
199
+ raw=command([VRS,'print-json',recording,'+',cam,'+','configuration']).decode(errors='replace')
200
+ cfg=[{x['name']:x.get('value') for x in json.loads(line)['data_layout']} for line in raw.splitlines() if line.startswith('{"data_layout"')][0]
201
+ rate=cfg['nominal_rate'];assert abs(np.median(np.diff(times))-1/rate)<.001
202
+ m['sampling']['source_fps']=rate
203
+ m['sampling']['source_fps_basis']='VRS camera configuration nominal_rate; actual intervals checked separately'
204
+ m['sampling']['duration_seconds']=float(times[-1]-times[0])
205
+ frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
206
+ for frame in frames:
207
+ for match in frame['annotation_matches'].values():
208
+ if 'available' in match:match['source_record_present']=match.pop('available')
209
+ lines(p/'camera/frames.jsonl',frames)
210
+ info=load(base/'raw/data/assets/object_models/models_info.json')
211
+ reverse={str(v['original_id']):str(k) for k,v in info.items()}
212
+ for op in (p/'annotation/object').glob('*'):
213
+ om=load(op/'metainfo.json');oid=om['object_id'];idx=int(reverse[oid])
214
+ glb=base/'raw/data/assets/object_models'/f'obj_{idx:06d}.glb';assert glb.is_file()
215
+ # Retain the official material-bearing companion byte-for-byte. OBJ remains the declared standard mesh.
216
+ target=op/'assets'/glb.name;shutil.copyfile(glb,target)
217
+ assert digest(glb)==digest(target)
218
+ om.update(category_name=info[str(idx)]['name'],original_glb_ref=target.relative_to(p).as_posix(),original_glb_source_locator={'file':glb.relative_to(base).as_posix(),'semantics':'native companion; standard geometry is the referenced metre OBJ'})
219
+ save(op/'metainfo.json',om)
220
+ save(p/'metainfo.json',m)
221
+ checkpath=base/'tmp'/RUN/'checks'/f'{seq}__{cam}.json';checks=load(checkpath)
222
+ checks['checks']=[c for c in checks['checks'] if c['test']!='VRS_extracted_filename_order_and_nominal_rate']
223
+ checks['checks'].append({'test':'VRS_extracted_filename_order_and_nominal_rate','frames':len(rows),'nominal_fps':rate,'filename_rounding_max_ms':float(np.max(np.abs(file_times-times))*1000),'passed':True});save(checkpath,checks)
224
+
225
+ def hot3d(sequence=None,initialize=True):
226
+ dataset='HOT3D';seq=sequence or HOT3D_SEQ
227
+ if initialize:setup(dataset,seq)
228
+ base=DATA_ROOT/dataset;raw=base/'raw/data';src=raw/'Aria'/seq;tmp=base/'tmp'/RUN
229
+ recording=next(src.glob('*.vrs'));extract=tmp/seq/'images'
230
+ import hot3d_storage as storage
231
+ if storage.enabled():extract=storage.images(recording)
232
+ elif not (tmp/seq/'extracted.json').exists() or not extract.exists() or not any(extract.glob('*.jpg')):
233
+ extract.mkdir(parents=True,exist_ok=True)
234
+ log=tmp/seq/'vrs-extraction.log'
235
+ with log.open('wb') as out:
236
+ run=subprocess.run([str(VRS),'extract-images',str(recording),'--to',str(extract),'+','214-1','+','1201-1','+','1201-2'],stdout=out,stderr=subprocess.STDOUT)
237
+ assert run.returncode==0,'VRS extraction failed; see tmp log'
238
+ save(tmp/seq/'extracted.json',{'source':recording.name,'streams':['214-1','1201-1','1201-2'],'complete':True})
239
+ gt=zipfile.ZipFile(next(src.glob('*ground_truth.zip')));handszip=zipfile.ZipFile(next(src.glob('*hand_data.zip')))
240
+ meta=json.loads(gt.read('metadata.json'));cams=json.loads(gt.read('camera_models.json'));mapping=loadzipcsv(gt,'timecode_devicetime_mapping.csv');mapping.sort(key=lambda r:int(r['devicetime_ns']))
241
+ assert meta['headset']=='Aria' and meta['recording_name']==seq
242
+ dev=np.array([int(r['devicetime_ns']) for r in mapping],np.int64);tc=np.array([int(r['timecode_ns']) for r in mapping],np.int64)
243
+ heads={int(r['timestamp[ns]']):csv_transform(r) for r in loadzipcsv(gt,'headset_trajectory.csv')};head_times=sorted(heads)
244
+ hands={r['timestamp_ns']:r['hand_poses'] for r in map(json.loads,handszip.read('mano_hand_pose_trajectory.jsonl').splitlines())};hand_times=sorted(hands)
245
+ objects=loadzipcsv(gt,'dynamic_objects.csv');vis_h=loadzipcsv(gt,'box2d_hands.csv');vis_o=loadzipcsv(gt,'box2d_objects.csv')
246
+ models=[Mano('left'),Mano('right')];fixed=np.abs(models[0].data['shapedirs'][:,0]-models[1].data['shapedirs'][:,0]).sum()<1
247
+ if fixed:
248
+ models[0].data['shapedirs'][:,0]*=-1
249
+ with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
250
+ assetszip=zipfile.ZipFile(raw/'assets/hot3d_models.zip');assetinfo=json.loads(assetszip.read('models/models_info.json'));reverse={str(v['original_id']):str(k) for k,v in assetinfo.items()}
251
+ for camera in cams:
252
+ cam=camera['stream_id'];rows=vrs_records(recording,cam);paths=sorted(extract.glob(cam+'-*.jpg'))
253
+ assert len(rows)==len(paths)>1,(cam,len(rows),len(paths))
254
+ v=FreshView(dataset,seq,cam,[r['frame_number'] for r in rows],[camera['imageWidth'],camera['imageHeight']],{'file':recording.relative_to(base).as_posix(),'stream_id':cam})
255
+ if (v.p/'metainfo.json').exists() and load(v.p/'metainfo.json').get('pilot_complete'):print('RESUME verified view',cam,flush=True);continue
256
+ t=v.T;capture=np.array([int(r['capture_timestamp_ns']) for r in rows],np.int64)
257
+ ix,good,delta=nearest(dev,capture,1000);assert good.all(),'Missing official device-time/timecode mapping'
258
+ times=tc[ix];sourcegt={'archive':next(src.glob('*ground_truth.zip')).relative_to(base).as_posix()}
259
+ test_ids={'P0004','P0005','P0006','P0008','P0016','P0020'}
260
+ split='test' if meta['participant_id'] in test_ids else 'train'
261
+ assert meta['have_hand_object_pose_gt']==(split=='train')
262
+ v.m.update(view_type='ego',split=split,split_scheme='HOT3D_official_participant_split',split_source_locator={'url':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#testtrain-split','participant_id':meta['participant_id'],'archive':sourcegt['archive'],'member':'metadata.json'},source_hand_object_gt_available=meta['have_hand_object_pose_gt'])
263
+ v.m['sampling'].update(source_fps=30,source_fps_basis='camera VRS nominal_rate; confirmed against capture timestamps',selection='All data records in each of the three camera streams of the complete official VRS',capture_interval_median_ns=int(np.median(np.diff(capture))))
264
+ v.m['camera'].update(model='fisheye624',schema_id='camera/fisheye624/v1',native_channel_semantics='RGB' if cam=='214-1' else 'monochrome; unified RGB decoder repeats intensity in three channels',max_solid_angle=camera['maxSolidAngle'])
265
+ v.array('intrinsic','camera/intrinsic.pt','camera/fisheye624/v1',np.broadcast_to(camera['projectionParams'],(t,15)),np.ones(t,bool),['T','parameter'],source=dict(sourcegt,member='camera_models.json',stream_id=cam))
266
+ dc=camera['T_Device_Camera'];Tdc=transform(dc['quaternion_wxyz'],dc['translation_xyz'])
267
+ hi,hvalid,hdelta=nearest(head_times,times,1_000_000);E=np.full((t,4,4),np.nan)
268
+ for i in np.flatnonzero(hvalid):E[i]=np.linalg.inv(heads[head_times[hi[i]]]@Tdc)
269
+ assert hvalid.all(),'Headset GT missing at image times'
270
+ assert_se3(E);v.array('extrinsic','camera/extrinsic.pt','transform/se3/v1',E,hvalid,['T','row','column'],source=dict(sourcegt,member='headset_trajectory.csv',calibration_member='camera_models.json'),unit='m',convention='T_camera_from_world',method='inverse(T_world_from_device @ T_device_from_camera); official timecode mapping then <=1ms nearest source pose')
271
+ mi,mvalid,mdelta=nearest(hand_times,times,1_000_000);motion=np.full((t,2,61),np.nan);valid=np.zeros((t,2),bool)
272
+ for side,model in enumerate(models):
273
+ chosen=[i for i in range(t) if mvalid[i] and str(side) in hands[hand_times[mi[i]]]]
274
+ if not chosen:continue
275
+ native=[hands[hand_times[mi[i]]][str(side)] for i in chosen];pose=[];beta=[];trans=[]
276
+ for h in native:
277
+ wrist=h['wrist_xform'];pose.append(np.r_[Rotation.from_quat(np.roll(wrist['q_wxyz'],-1)).as_rotvec(),np.asarray(h['pose'])@model.data['hands_components'][:15]+model.data['hands_mean']]);beta.append(h['betas']);trans.append(wrist['t_xyz'])
278
+ motion[chosen,side],err=camera_mano(model,pose,beta,trans,E[chosen]);valid[chosen,side]=True
279
+ # Official source model uses PCA15 and nonflat mean, unlike output AA48.
280
+ import smplx
281
+ from types import SimpleNamespace
282
+ native_model=smplx.MANO(model_path=str(WORK/'tmp/pilot-models'),data_struct=SimpleNamespace(**model.data),is_rhand=side==1,use_pca=True,num_pca_comps=15,flat_hand_mean=False)
283
+ ixcheck=np.arange(0,len(chosen),max(1,len(chosen)//16));arr=np.asarray(pose);bet=np.asarray(beta);tr=np.asarray(trans)
284
+ with torch.no_grad():expected=native_model(global_orient=torch.tensor(arr[ixcheck,:3],dtype=torch.float32),hand_pose=torch.tensor(np.array([native[i]['pose'] for i in ixcheck]),dtype=torch.float32),betas=torch.tensor(bet[ixcheck],dtype=torch.float32),transl=torch.tensor(tr[ixcheck],dtype=torch.float32)).vertices.numpy()
285
+ actual=model.geometry(arr[ixcheck],bet[ixcheck],tr[ixcheck])[0];pcaerr=float(np.max(np.linalg.norm(expected-actual,axis=-1)));assert pcaerr<2e-6
286
+ v.checks.append({'test':'official_PCA15_vs_AA48_and_camera_geometry','side':side,'camera_max_m':err,'pca_max_m':pcaerr,'valid_frames':len(chosen),'passed':True})
287
+ if hand_times:
288
+ v.array('mano','annotation/mano/motion.pt','mano/axis_angle61/v1',motion,valid,['T','hand','parameter'],source={'archive':next(src.glob('*hand_data.zip')).relative_to(base).as_posix(),'member':'mano_hand_pose_trajectory.jsonl','time_index_ref':'camera/frames.jsonl:annotation_matches.mano'},unit='m',angle_unit='rad',coordinate_frame='camera',model_profile={'version':'MANO-v1.2','flat_hand_mean':True,'left_shapedirs_fix':bool(fixed)},method='Official PCA15 expanded with model mean and handedness fix; transform all matched MANO parameters into current camera')
289
+ def vis_values(records,identity_field,identities):
290
+ out=np.full((t,len(identities)),np.nan)
291
+ for c,identity in enumerate(identities):
292
+ values={int(r['timestamp[ns]']):float(r['visibility_ratio[%]']) for r in records if r['stream_id']==cam and str(r[identity_field])==str(identity) and r['visibility_ratio[%]']!=''}
293
+ if not values:continue
294
+ ts=sorted(values);ii,vv,dd=nearest(ts,times,1_000_000)
295
+ for i in np.flatnonzero(vv):out[i,c]=values[ts[ii[i]]]
296
+ return out
297
+ if hand_times and vis_h:
298
+ visibility=vis_values(vis_h,'hand_index',[0,1]);v.attribute('mano','annotation/mano/visibility.pt',visibility,['T','hand'],dict(sourcegt,member='box2d_hands.csv',stream_id=cam,match_method='nearest',max_delta_ns=1000000),'whole_hand')
299
+ for i,row in enumerate(v.frames):
300
+ row.update(timestamp_ns=int(capture[i]),clock_domain='device_time',timecode_ns=int(times[i]),timecode_clock_domain='timecode',mapping_delta_ns=int(delta[i]))
301
+ row['source_locator'].update(record_index=i,capture_timestamp_ns=int(capture[i]))
302
+ row['annotation_matches']={}
303
+ for key,ts,idxs,flags,dd in [('extrinsic',head_times,hi,hvalid,hdelta),('mano',hand_times,mi,mvalid,mdelta)]:
304
+ row['annotation_matches'][key]={'source_frame_id':str(ts[idxs[i]]) if flags[i] else None,'source_timestamp_ns':int(ts[idxs[i]]) if flags[i] else None,'clock_domain':'timecode','match_method':'exact' if dd[i]==0 else 'nearest','max_delta_ns':1000000,'delta_ns':int(dd[i]) if flags[i] else None,'image_time_ref':'timecode_ns','source_record_present':bool(flags[i])}
305
+ for oid in sorted(set(meta['object_uids'])|{r['object_uid'] for r in objects}):
306
+ rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';assets.mkdir(parents=True,exist_ok=True)
307
+ sourceposes={int(r['timestamp[ns]']):csv_transform(r) for r in objects if r['object_uid']==oid};ts=sorted(sourceposes);oi,ok,od=nearest(ts,times,1_000_000)
308
+ P=np.full((t,4,4),np.nan)
309
+ for i in np.flatnonzero(ok):P[i]=E[i]@sourceposes[ts[oi[i]]]
310
+ key=f'object_{oid}_pose'
311
+ if sourceposes:
312
+ assert_se3(P[ok]);v.array(key,rel+'/pose.pt','object/rigid/v1',P,ok,['T','row','column'],source=dict(sourcegt,member='dynamic_objects.csv',object_uid=oid),unit='m',convention='T_camera_from_object')
313
+ for i,row in enumerate(v.frames):row['annotation_matches'][key]={'source_frame_id':str(ts[oi[i]]) if ok[i] else None,'source_timestamp_ns':int(ts[oi[i]]) if ok[i] else None,'clock_domain':'timecode','match_method':'exact' if od[i]==0 else 'nearest','max_delta_ns':1000000,'delta_ns':int(od[i]) if ok[i] else None,'image_time_ref':'timecode_ns','source_record_present':bool(ok[i])}
314
+ if sourceposes and vis_o:
315
+ ov=vis_values(vis_o,'object_uid',[oid])[:,0];v.attribute(key,rel+'/visibility.pt',ov,['T'],dict(sourcegt,member='box2d_objects.csv',stream_id=cam,object_uid=oid,match_method='nearest',max_delta_ns=1000000),'whole_object')
316
+ idx=int(reverse[oid]);prefix=f'models/obj_{idx:06d}'
317
+ for member in assetszip.namelist():
318
+ if member.startswith(prefix+'.'):(assets/Path(member).name).write_bytes(assetszip.read(member))
319
+ ply=assets/f'obj_{idx:06d}.ply';mesh=trimesh.load(ply,process=False,force='mesh');mesh.vertices=np.asarray(mesh.vertices)*.001
320
+ expected_extent=np.array([assetinfo[str(idx)]['size_'+x] for x in 'xyz']);assert np.allclose(mesh.extents,expected_extent,atol=1e-5)
321
+ text,textures=trimesh.exchange.obj.export_obj(mesh,return_texture=True,digits=12);meshpath=assets/f'obj_{idx:06d}.obj';meshpath.write_text(text)
322
+ for filename,data in textures.items():(assets/filename).write_bytes(data)
323
+ restored=trimesh.load(meshpath,process=False,force='mesh');assert np.allclose(restored.triangles,mesh.triangles,atol=1e-7)
324
+ assert np.array_equal(np.asarray(restored.visual.material.image),np.asarray(mesh.visual.material.image))
325
+ # Keep the official GLB as a companion asset so richer original material properties remain available.
326
+ glb=raw/'assets'/f'{oid}.glb'
327
+ if glb.exists():shutil.copyfile(glb,assets/glb.name)
328
+ # The millimetre PLY was a temporary converter input, not a second shared geometry convention.
329
+ assert ply.resolve().is_relative_to(assets.resolve());ply.unlink()
330
+ sourceasset={'archive':'raw/data/assets/hot3d_models.zip','member':prefix+'.ply','original_id':oid,'bop_id':idx}
331
+ v.mesh(oid,meshpath.relative_to(v.p).as_posix(),sourceasset)
332
+ save(op/'metainfo.json',{'object_id':oid,'source_object_id':oid,'identity_scope':'sequence','scope_id':seq,'association_basis':'official_object_uid_in_shared_world_coordinates','has_model':True,'mesh_ref':meshpath.relative_to(v.p).as_posix(),'unit':'m','source_locator':dict(sourcegt,member='dynamic_objects.csv' if sourceposes else 'metadata.json',object_uid=oid),'original_glb_ref':(assets/glb.name).relative_to(v.p).as_posix() if glb.exists() else None})
333
+ v.checks.append({'test':'object_mesh_scale_triangle_and_texture_roundtrip','object_id':oid,'vertices':len(mesh.vertices),'faces':len(mesh.faces),'extent_m':mesh.extents.tolist(),'passed':True})
334
+ v.checks.append({'test':'all_camera_frame_device_time_mapping','frames':t,'max_delta_ns':int(np.abs(delta).max()),'passed':True})
335
+ v.m['omitted_components']={'depth':'No depth stream in selected official Aria raw recording','segment':'Ground-truth masks/*.csv are frame-selection predicates, not pixel masks; no source pixel segmentation provided here','contact':'No native contact labels in downloaded scope','keypoints':'No independent MANO21 keypoint array in this raw release; selected MANO parameters retained','alternative_hand_model':'UmeTrack representation retained in raw; this shared contract selects MANO','alternative_camera_estimates':'Raw MPS online calibration and SLAM trajectories retained; shared uses the official GT camera_models and headset trajectory'}
336
+ if not hand_times:v.m['omitted_components']['mano']='Official MANO trajectory is empty; no pose labels released for this sequence'
337
+ if not objects:v.m['omitted_components']['object_pose']='Official object trajectory is empty; static source models retained without fabricated pose arrays'
338
+ print('MEDIA',dataset,cam,t,flush=True);submit_media(v,lambda files=tuple(paths):file_members(files))
339
+ assetszip.close();gt.close();handszip.close()
340
+
341
+ if __name__=='__main__':
342
+ p=argparse.ArgumentParser();p.add_argument('dataset',choices=['ARCTIC','HOT3D']);a=p.parse_args()
343
+ torch.set_num_threads(4)
344
+ {'ARCTIC':arctic,'HOT3D':hot3d}[a.dataset]()
345
+ if a.dataset=='HOT3D':
346
+ verify_hot3d_frame_order_and_metadata()
347
+ from apply_hot3d_qa import apply_qa
348
+ apply_qa()
349
+ elif (DATA_ROOT/'ARCTIC'/RELEASE/'doc/validation/exposure.json').exists():
350
+ from repair_arctic_pilot import repair
351
+ repair()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/correct_arctic_source_fps_metadata.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Correct ARCTIC's documented source FPS without changing MKV containers."""
3
+
4
+ import json, os
5
+ from datetime import datetime
6
+ from pathlib import Path, PurePosixPath
7
+
8
+ ROOT = Path("E:/hand-datasets/ARCTIC/shared-v1.0")
9
+ MANIFEST = Path("tmp/arctic-publication-v1.0/manifest.json")
10
+ STATE = Path("tmp/arctic-fps30-correction/metadata-status.json")
11
+ EVIDENCE = (
12
+ "ARCTIC paper v3, Sec. 3.2 Acquisition Setup: 8 static allocentric and "
13
+ "1 moving egocentric RGB views captured at 30 FPS"
14
+ )
15
+ EVIDENCE_URL = "https://arxiv.org/html/2204.13662v3#S3.SS2"
16
+
17
+ def save_json(path, value):
18
+ temporary = path.with_name(path.name + ".tmp")
19
+ temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
20
+ os.replace(temporary, path)
21
+
22
+ manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
23
+ paths = []
24
+ for item in manifest["files"]:
25
+ local = PurePosixPath(item["local"])
26
+ if item.get("layer") == "shared" and len(local.parts) == 5 and local.parts[:2] == ("shared-v1.0", "data") and local.name == "metainfo.json":
27
+ paths.append(ROOT.joinpath(*local.parts[1:]))
28
+ paths = sorted(set(paths))
29
+ if len(paths) != 3051:
30
+ raise RuntimeError(f"expected 3051 views, found {len(paths)}")
31
+
32
+ updated = 0
33
+ for ordinal, path in enumerate(paths, 1):
34
+ meta = json.loads(path.read_text(encoding="utf-8"))
35
+ if meta.get("dataset_id") != "ARCTIC":
36
+ raise RuntimeError(f"unexpected dataset: {path}")
37
+ sampling = meta["sampling"]
38
+ sampling["source_fps"] = 30.0
39
+ sampling.pop("source_fps_reason", None)
40
+ sampling["source_fps_basis"] = EVIDENCE
41
+ sampling["source_fps_evidence_url"] = EVIDENCE_URL
42
+ sampling["source_timestamp_status"] = "not_released; do not invent measured timestamp_ns"
43
+ # The already-published MKV remains a 1 FPS index container by user choice.
44
+ rgb = meta["components"]["rgb"]
45
+ if rgb.get("storage_fps") != 1 or rgb.get("timebase_role") != "index_only":
46
+ raise RuntimeError(f"unexpected storage timing before metadata-only correction: {path}")
47
+ save_json(path, meta)
48
+ updated += 1
49
+ if ordinal % 100 == 0:
50
+ save_json(STATE, {"stage":"running", "time":datetime.now().astimezone().isoformat(), "updated":updated, "total":len(paths)})
51
+
52
+ # Correct current explanatory documents; historical benchmark evidence remains untouched.
53
+ replacements = {
54
+ "当前 raw 未提供可直接核实的逐帧时间,timestamp_ns 与 source_fps 保留 null,不用容器 1 fps 伪造真实采集时间。":
55
+ "官方论文第3.2节明确九路RGB相机以30 FPS采集,因此source_fps=30;发布物未提供可核实的逐帧采集时间戳,timestamp_ns仍为null,不用容器时间戳伪造实测时间。",
56
+ "预览30fps仅用于播放,不代表真实采集帧率":
57
+ "预览帧率与官方声明的名义采集帧率均为30 FPS;发布物未提供逐帧实测采集时间戳",
58
+ "播放30fps仅用于预览,源采集FPS未知。":
59
+ "播放帧率与官方声明的名义采集帧率均为30 FPS;发布物未提供逐帧实测采集时间戳。",
60
+ }
61
+ document_paths = [ROOT / "doc/RAW_TO_SHARED.md", ROOT / "doc/validation/REPORT.md", ROOT / "doc/validation/index.html", ROOT / "doc/validation/report.json"]
62
+ document_paths.extend((ROOT / "doc/validation/objects").glob("*/index.html"))
63
+ for path in document_paths:
64
+ if not path.is_file():
65
+ continue
66
+ text = path.read_text(encoding="utf-8")
67
+ changed = text
68
+ for before, after in replacements.items():
69
+ changed = changed.replace(before, after)
70
+ if changed != text:
71
+ temporary = path.with_name(path.name + ".tmp")
72
+ temporary.write_text(changed, encoding="utf-8")
73
+ os.replace(temporary, path)
74
+
75
+ save_json(STATE, {
76
+ "stage":"complete", "time":datetime.now().astimezone().isoformat(), "updated":updated,
77
+ "total":len(paths), "source_fps":30.0, "mkv_storage_fps":1,
78
+ "mkv_changed":False, "evidence":EVIDENCE, "evidence_url":EVIDENCE_URL,
79
+ })
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/diagnose_arctic_review.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inspect source exposure and execute upstream articulation for the selected pilot.
2
+
3
+ Read-only for raw and shared data. Writes portable evidence under doc/validation.
4
+ """
5
+ from fresh_sequence_common import *
6
+ from review_fresh_sequence_pilots import arr, project_for_view
7
+ import ast
8
+
9
+ SEQ='s09_laptop_use_03'
10
+ BASE=DATA_ROOT/'ARCTIC'
11
+ ROOT=BASE/RELEASE
12
+ DOC=ROOT/'doc/validation'
13
+ OFFICIAL=WORK/'tmp/fresh-sequence-pilot/official/ARCTIC'
14
+
15
+ def exposure():
16
+ result={}
17
+ with zipfile.ZipFile(BASE/'raw/data/images_zips/s09/laptop_use_03.zip') as z:
18
+ for cam in map(str,range(9)):
19
+ names=sorted(n for n in z.namelist() if n.startswith(cam+'/') and n.endswith('.jpg'))
20
+ rows=[];canvas=Image.new('RGB',(10*160,180),(20,20,20))
21
+ from PIL import ImageDraw
22
+ draw=ImageDraw.Draw(canvas)
23
+ for i,n in enumerate(names):
24
+ im=Image.open(io.BytesIO(z.read(n)));im.draft('RGB',(160,160));im.thumbnail((160,150));gray=np.asarray(im.convert('L'))
25
+ rows.append({'frame_index':i,'source_frame_id':int(Path(n).stem),'median_luma':float(np.median(gray)),
26
+ 'p95_luma':float(np.percentile(gray,95)),'mean_luma':float(gray.mean()),'fraction_gt_32':float((gray>32).mean())})
27
+ if i<10:canvas.paste(im,(i*160,25));draw.text((i*160+3,5),f'idx {i}, src {i+1}',fill='white')
28
+ path=DOC/'diagnosis'/f'exposure-{cam}.jpg';path.parent.mkdir(parents=True,exist_ok=True);canvas.save(path,quality=94)
29
+ result[cam]={'method':'Official raw JPEG, PIL draft preview <=160x150, 8bit luma; diagnostics, not a general exposure classifier','frames':rows,'preview_ref':path.relative_to(DOC).as_posix()}
30
+ print('EXPOSURE',cam,'first10_p95',[r['p95_luma'] for r in rows[:10]],'p95_lt_35_indices',[r['frame_index'] for r in rows if r['p95_luma']<35],flush=True)
31
+ save(DOC/'exposure.json',result)
32
+ return result
33
+
34
+ class Xdict(dict):
35
+ def overwrite(self,k,v):self[k]=v
36
+
37
+ def official_object(objects,vertices,raw_parts,params,object_id='laptop'):
38
+ # Execute the pinned official class, bypassing its multi-object file loader.
39
+ # Only quaternion primitives use a SciPy implementation; no semantic rewriting.
40
+ tree=ast.parse((OFFICIAL/'common/object_tensors.py').read_text())
41
+ klass=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name=='ObjectTensors')
42
+ def aa_quat(a):
43
+ a=a.numpy();q=Rotation.from_rotvec(a.reshape(-1,3)).as_quat().reshape(a.shape[:-1]+(4,))
44
+ return torch.tensor(q[...,[3,0,1,2]],dtype=torch.float32)
45
+ def qapply(q,v):
46
+ q=q.numpy();v=v.numpy();shape=np.broadcast_shapes(q.shape[:-1],v.shape[:-1]);qs=np.broadcast_to(q,shape+(4,)).reshape(-1,4)
47
+ out=Rotation.from_quat(qs[:,[1,2,3,0]]).apply(np.broadcast_to(v,shape+(3,)).reshape(-1,3)).reshape(shape+(3,))
48
+ return torch.tensor(out,dtype=torch.float32)
49
+ ns={'nn':torch.nn,'torch':torch,'np':np,'xdict':Xdict,'axis_angle_to_quaternion':aa_quat,'quaternion_apply':qapply}
50
+ exec(compile(ast.Module(body=[klass],type_ignores=[]),'pinned_ARCTIC_ObjectTensors','exec'),ns)
51
+ layer=ns['ObjectTensors'].__new__(ns['ObjectTensors']);torch.nn.Module.__init__(layer)
52
+ n=len(vertices);ft=lambda a:torch.tensor(np.asarray(a),dtype=torch.float32)
53
+ d={'names':[object_id],'diameter':ft([1]),'f':torch.zeros((1,1,3),dtype=torch.long),'f_len':torch.tensor([1]),'v_len':torch.tensor([n]),
54
+ 'v':ft(vertices[None]),'mask':ft(np.ones((1,n))),'v_sub':ft(vertices[None]),
55
+ 'parts_ids':torch.tensor(raw_parts[None]+1),'parts_sub_ids':torch.tensor(raw_parts[None]+1),'z_axis':ft([[0,0,-1]])}
56
+ for out,key in [('bbox_top','bbox_top'),('bbox_bottom','bbox_bottom'),('kp_top','keypoints_top'),('kp_bottom','keypoints_bottom')]:d[out]=ft([np.array(params[key])/1000])
57
+ layer.obj_tensors=d
58
+ out=layer.forward(ft(objects[:,:1]),ft(objects[:,1:4]),ft(objects[:,4:7]/1000),[object_id]*len(objects))
59
+ return out['v'].numpy(),out['kp3d'].numpy()
60
+
61
+ def geometry():
62
+ with zipfile.ZipFile(BASE/'raw/data/meta.zip') as z:
63
+ pref='meta/object_vtemplates/laptop/'
64
+ vertices=np.array([[float(x) for x in r.split()[1:4]] for r in z.read(pref+'mesh.obj').decode().splitlines() if r.startswith('v ')])/1000
65
+ parts=np.array(json.loads(z.read(pref+'parts.json')),int);params=json.loads(z.read(pref+'object_params.json'))
66
+ misc=json.loads(z.read('meta/misc.json'))['s09']
67
+ with zipfile.ZipFile(BASE/'raw/data/raw_seqs.zip') as z:
68
+ objects=native_npy_bytes(z.read('raw_seqs/s09/laptop_use_03.object.npy'))
69
+ hand=native_npy_bytes(z.read('raw_seqs/s09/laptop_use_03.mano.npy'))
70
+ # Every annotation frame, a uniform vertex subset; plus every vertex at source 271.
71
+ vi=np.arange(0,len(vertices),max(1,len(vertices)//500));native,kp=official_object(objects,vertices[vi],parts[vi],params)
72
+ hands=[]
73
+ for side in ['left','right']:
74
+ model=Mano(side);h=hand[side];pose=np.c_[h['rot'],h['pose']];pose[:,3:]+=model.data['hands_mean']
75
+ xyz=model.geometry(pose,np.broadcast_to(h['shape'],(len(pose),10)),h['trans'])[0];hands.append(xyz)
76
+ tests=[]
77
+ for meta in sorted((ROOT/'data'/SEQ).glob('*/metainfo.json')):
78
+ p=meta.parent;m=load(meta);cam=m['camera_id'];source=BASE/'tmp/full-video-review-v2/diagnostic'/cam
79
+ if not (source/'snapshot.json').exists():source=p
80
+ E=arr(source/'camera/extrinsic.pt');P=arr(source/'annotation/object/laptop/pose.pt');top=arr(source/'annotation/object/laptop/parts/top/pose.pt')
81
+ actual=vertices[vi][None]@P[1:,:3,:3].transpose(0,2,1)+P[1:,None,:3,3]
82
+ sel=parts[vi]==0;actual[:,sel]=vertices[vi][sel][None]@top[1:,:3,:3].transpose(0,2,1)+top[1:,None,:3,3]
83
+ expected=native@E[1:,:3,:3].transpose(0,2,1)+E[1:,None,:3,3]
84
+ error=float(np.max(np.linalg.norm(actual-expected,axis=-1)));assert error<2e-5
85
+ motion=arr(source/'annotation/mano/motion.pt');handerrs=[]
86
+ for side in range(2):
87
+ model=Mano(['left','right'][side]);a=motion[1:,side];shared=model.geometry(a[:,:48],a[:,48:58],a[:,58:])[0]
88
+ expected_hand=hands[side]@E[1:,:3,:3].transpose(0,2,1)+E[1:,None,:3,3]
89
+ err=float(np.max(np.linalg.norm(shared-expected_hand,axis=-1)));assert err<2e-5;handerrs.append(err)
90
+ tests.append({'camera_id':cam,'annotation_frames':540,'vertices_per_frame':len(vi),'official_object_max_m':error,'source_to_shared_MANO_max_m':handerrs})
91
+ print('GEOMETRY',tests[-1],flush=True)
92
+ report={'issue':'Raw parts.json 0=top,1=bottom; previous converter wrongly treated 1 as top. Official code adds 1 and articulates parts_ids==1.',
93
+ 'correction':'Shared convention remains 0=bottom,1=top; shared_id=1-raw_id. No time shift, pose change or image edit.',
94
+ 'upstream_code':'https://github.com/zc-alexfan/arctic/blob/49f3eb4b7f01663172576357bb3d95695d7a7689/common/object_tensors.py',
95
+ 'method':'Executed pinned upstream ObjectTensors class with actual raw tensor state and SciPy quaternion primitives, compared all 540 frames and 9 cameras. MANO verified independently from source world parameters.',
96
+ 'tests':tests,'limitation':'Numerical agreement with source geometry does not establish source-to-image accuracy. Residual hand alignment remains for full-video human review.'}
97
+ save(DOC/'diagnosis.json',report)
98
+ return report
99
+
100
+ def comparison():
101
+ from render_full_sequence_review import model_vertices, fast_edges, dots
102
+ p=ROOT/'data'/SEQ/'6';m=load(p/'metainfo.json');i=270
103
+ source=BASE/'tmp/full-video-review-v2/diagnostic/6'
104
+ if not (source/'snapshot.json').exists():source=p
105
+ with zipfile.ZipFile(BASE/'raw/data/images_zips/s09/laptop_use_03.zip') as z:rgb=np.array(Image.open(io.BytesIO(z.read('6/00271.jpg'))).convert('RGB').resize((500,700)))
106
+ with zipfile.ZipFile(BASE/'raw/data/meta.zip') as z:parts=np.array(json.loads(z.read('meta/object_vtemplates/laptop/parts.json')))
107
+ vertices=np.array([[float(x) for x in r.split()[1:4]] for r in (p/'annotation/object/laptop/assets/mesh.obj').read_text().splitlines() if r.startswith('v ')])
108
+ pose=arr(p/'annotation/object/laptop/pose.pt')[i];top=arr(p/'annotation/object/laptop/parts/top/pose.pt')[i]
109
+ K=arr(p/'camera/intrinsic.pt')[i];scale=np.array([.25,.25]);motion=arr(source/'annotation/mano/motion.pt')[i:i+1];valid=arr(source/'annotation/mano/motion_valid.pt')[i:i+1]
110
+ panels=[rgb.copy(),rgb.copy(),rgb.copy()]
111
+ for col,sel in [(1,parts==1),(2,parts==0)]:
112
+ xyz=vertices@pose[:3,:3].T+pose[:3,3];xyz[sel]=vertices[sel]@top[:3,:3].T+top[:3,3]
113
+ uv=project_for_view(xyz,m,(K,None),scale);dots(panels[col],uv[::4],(100,245,90),1)
114
+ for side,color in [(0,(0,225,240)),(1,(255,160,20))]:
115
+ v,j,e=model_vertices(motion,valid,side,False);uv=project_for_view(v[0],m,(K,None),scale)
116
+ for im in panels[1:]:fast_edges(im,uv,e,color)
117
+ canvas=np.full((750,1500,3),22,np.uint8)
118
+ for col,(im,title) in enumerate(zip(panels,['RAW source 271','OLD wrong object parts','FIXED official object parts'])):
119
+ canvas[45:745,col*500:(col+1)*500]=im;cv2.putText(canvas,title,(col*500+10,26),cv2.FONT_HERSHEY_SIMPLEX,.62,(250,250,250),1)
120
+ Image.fromarray(canvas).save(DOC/'diagnosis/camera6-270-before-after.jpg',quality=95)
121
+
122
+ if __name__=='__main__':
123
+ import argparse
124
+ ap=argparse.ArgumentParser();ap.add_argument('mode',choices=['exposure','geometry','comparison']);args=ap.parse_args()
125
+ {'exposure':exposure,'geometry':geometry,'comparison':comparison}[args.mode]()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/finalize_arctic_objects_review.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble evidence after the bounded eleven-object review; never authorizes production."""
2
+ from arctic_object_review import *
3
+ from html.parser import HTMLParser
4
+ from urllib.parse import unquote, urlsplit
5
+
6
+ NOTES=WORK/'tmp/arctic-object-visual-review.json'
7
+
8
+ def asset_contacts():
9
+ selection=load(SELECTION);outputs=[]
10
+ for item in selection['objects']:
11
+ _,_,oid,seqid,doc,tmp=context(item)
12
+ video=doc/'assets'/f'{oid}.mp4'
13
+ if not video.exists():continue
14
+ asset=asset_preview(OUT/'data'/seqid/'6'/'annotation/object'/oid,video)
15
+ r=load(doc/'report.json');r['asset_preview']=asset;save(doc/'report.json',r)
16
+ target=tmp/'asset-angles.jpg'
17
+ command([FF,'-v','error','-y','-threads','2','-i',video,'-vf',
18
+ 'select=eq(n\\,12)+eq(n\\,36)+eq(n\\,60),scale=480:-1,tile=3x1',
19
+ '-frames:v','1','-threads','2',target])
20
+ outputs.append((oid,target))
21
+ for group,start in enumerate(range(0,len(outputs),6),1):
22
+ chosen=outputs[start:start+6];images=[Image.open(p).convert('RGB') for _,p in chosen]
23
+ height=max(im.height for im in images)+32
24
+ sheet=Image.new('RGB',(1440,height*len(images)),(20,20,20));draw=ImageDraw.Draw(sheet)
25
+ for i,((oid,_),im) in enumerate(zip(chosen,images)):
26
+ draw.text((10,i*height+6),f'{oid}: turntable frames 12 / 36 / 60',fill='white')
27
+ sheet.paste(im,(0,i*height+32))
28
+ target=DOC/f'assets-contact-{group}.jpg';sheet.save(target,quality=94);print(target,flush=True)
29
+
30
+ class Links(HTMLParser):
31
+ def __init__(self):super().__init__();self.links=[]
32
+ def handle_starttag(self,tag,attrs):
33
+ for k,v in attrs:
34
+ if k in ('href','src','poster') and v:self.links.append(v)
35
+
36
+ def finalize():
37
+ selection=load(SELECTION);notes=json.loads(NOTES.read_text(encoding='utf-8-sig'))
38
+ assert set(notes)=={x['object'] for x in selection['objects']}
39
+ assert load(TMP/'status.json')['stage'] in ('all_objects_rendered_pending_visual_inspection','review_complete_pending_user')
40
+ reports=[];cameras=[];extra=[];old=load(DOC.parent/'report.json')
41
+ for item in selection['objects']:
42
+ seq,sid,oid,seqid,doc,tmp=context(item);r=load(doc/'report.json');p=OUT/'data'/seqid/'6'
43
+ assert r['reference']['ioi_offset']==1 and r['camera_frames']==r['reference']['annotation_frames']+1
44
+ assert notes[oid]['status']=='reviewed_with_findings' and notes[oid].get('asset_visual_review')
45
+ r['agent_visual_review']=notes[oid]
46
+ r['agent_visual_review']['inspected_frame_indices']=r['views'][0]['visual_sample_indices']
47
+ r['agent_visual_review']['entire_video_watched']=False
48
+ r['agent_visual_review']['sample_method']='beginning/end, uniform temporal samples, joint-angle extremes; exact indices recorded'
49
+ K=arr(p/'camera/intrinsic.pt');E=arr(p/'camera/extrinsic.pt')
50
+ assert np.array_equal(K,np.broadcast_to(K[0],K.shape)) and np.array_equal(E,np.broadcast_to(E[0],E.shape))
51
+ cameras.append((K[0],E[0]))
52
+ m=load(p/'metainfo.json');assert not m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices')
53
+ m['sampling']['selection']='Every released image of this selected camera in the complete official sequence ZIP; boundary images without annotations retained'
54
+ save(p/'metainfo.json',m)
55
+ view=r['views'][0];v=doc/view['video']['video_ref'];assert digest(v)==view['video']['video_sha256']
56
+ decoded=framehash(['-i',str(v)]);assert len(decoded)==r['camera_frames']
57
+ asset=doc/r['asset_preview']['video_ref'];assert len(framehash(['-i',str(asset)]))==72
58
+ texture_checks=[]
59
+ with zipfile.ZipFile(BASE/'raw/data/meta.zip') as z:
60
+ for f in (p/f'annotation/object/{oid}/assets').rglob('*'):
61
+ if f.suffix.lower() in ('.mtl','.jpg','.jpeg','.png'):
62
+ source=z.read(f'meta/object_vtemplates/{oid}/'+f.name)
63
+ assert f.read_bytes()==source
64
+ texture_checks.append({'file':f.name,'sha256':digest(f),'raw_bytes_equal':True})
65
+ r['delivery_checks']={'preview_fully_decoded_frames':len(decoded),'preview_sha256':digest(v),
66
+ 'asset_preview_frames':72,'asset_video_sha256':digest(asset),'texture_and_material_files':texture_checks}
67
+ save(doc/'report.json',r);write_object_html(r);reports.append(r)
68
+ extra.append({'object':oid,'preview_frames':len(decoded),'asset_frames':72,'texture_files_checked':len(texture_checks)})
69
+ print('FINAL_CHECK',oid,len(decoded),flush=True)
70
+ assert all(np.array_equal(k,cameras[0][0]) and np.array_equal(e,cameras[0][1]) for k,e in cameras)
71
+ oldviews=old['full_video_views'];assert len(oldviews)==9
72
+ for v in oldviews:assert digest(DOC.parent/v['video_ref'])==v['video_sha256']
73
+ # The same canonical laptop asset is shared by both review groups; fix its
74
+ # original report's texture preview too, without touching its nine frame videos.
75
+ laptop=next(r for r in reports if r['object']=='laptop')
76
+ shutil.copyfile(DOC/'laptop'/laptop['asset_preview']['video_ref'],DOC.parent/'assets/laptop.mp4')
77
+ old['asset_previews']=[laptop['asset_preview']]
78
+ overview(selection)
79
+ total=sum(r['camera_frames'] for r in reports);n=sum(len(r['views'][0]['visual_sample_indices']) for r in reports)
80
+ maximum=max(r['maximum_geometry_error_m'] for r in reports)
81
+ rows='\n'.join(f'| [{r["object"]}]({r["object"]}/index.html) | {r["sequence"]} | {r["camera_frames"]} | {r["maximum_geometry_error_m"]:.3g} | {r["agent_visual_review"]["summary"]} |' for r in reports)
82
+ text=f'''# ARCTIC 11种物体验收结果
83
+
84
+ [固定相机切换物体](index.html) · [原laptop九视角](../index.html) · [方法](README.md)
85
+
86
+ 新增组:s06、静态相机6,11个完整序列,共{total}帧;内外参逐帧恒定且在11个物体间完全一致。原s09/laptop_use_03九视角视频摘要未变。
87
+
88
+ **转换数值检查通过;源图像和标注质量仍有已知问题,用户确认待完成。** 不据此启动全量处理或上传。
89
+
90
+ | 物体 | 完整序列 | 帧数 | 最大几何差/m | 视觉抽查结果 |
91
+ |---|---|---:|---:|---|
92
+ {rows}
93
+
94
+ ## 检查边界
95
+
96
+ - 数值:全部有标注帧、全部物体顶点/关键点和双手MANO几何,对照raw及固定官方实现;最大差{maximum:.6g}m,容差2e-5m。交换部件、反转关节角、误用毫米的反例在11个物体上均被检出。
97
+ - 媒体:全部原JPEG包和统一解码RGB逐帧一致;完整预览视频再次全部解码,无缺帧/解码错误。MP4仅用于doc展示,不替代原码流MKV。
98
+ - 视觉:实际查看{n}个原图/投影对照时刻(每段的起止、均匀样本及开合极值),检查资产旋转预览的3个方位。完整视频已全部渲染;代理未逐帧人工观看全部视频。
99
+ - 模态:MANO、物体姿态/铰接/32个模板关键点、内外参、同步索引、RGB、资产纹理、valid均有检查/展示。未提供的深度、像素分割、接触、源visibility没有伪造。
100
+ - 开头暗帧与局部手指贴合误差如实记录;本轮没有修改按帧号的排除mask。末帧无源动捕标注是源范围边界,RGB保留、几何valid=false。
101
+ - 数值忠实不证明原标注准确;本次检查11种物体各一段,不能推导其它所有序列质量通过。
102
+
103
+ [资产预览抽查1](assets-contact-1.jpg) · [资产预览抽查2](assets-contact-2.jpg)
104
+ '''
105
+ (DOC/'REPORT.md').write_text(text,encoding='utf-8')
106
+ summary=load(DOC/'report.json');summary.update(camera_parameter_equality='exact_across_all_11_views_and_all_frames',
107
+ total_frames=total,visually_inspected_frame_count=n,maximum_geometry_error_m=maximum,
108
+ original_nine_camera_videos_unchanged=True,delivery_checks=extra,known_issues=['Source dark opening frames','Residual hand-to-image fit differences','Source annotation absent on final image'],
109
+ interpretation='All-frame faithful conversion passed; sampled visual review has findings; source quality and human acceptance not asserted')
110
+ save(DOC/'report.json',summary)
111
+ # Add navigation to the original page without rebuilding or replacing its nine videos.
112
+ home=DOC.parent/'index.html';body=home.read_text(encoding='utf-8');marker='id="eleven-object-review"'
113
+ if marker not in body:
114
+ body=body.replace('</header>','<p id="eleven-object-review"><strong>新增:</strong><a href="objects/index.html">固定相机6,切换11种物体的完整序列预览</a> · <a href="objects/REPORT.md">逐物体验收结果</a></p></header>',1)
115
+ home.write_text(body,encoding='utf-8')
116
+ mapping=OUT/'doc/RAW_TO_SHARED.md';body=mapping.read_text(encoding='utf-8')
117
+ if '## 新增固定相机物体组' not in body:
118
+ body+='\n## 新增固定相机物体组\n\n在原s09/laptop_use_03九视角之外,新增s06相机6的11物体完整序列。字段规则相同,具体选择、来源、帧数和校验见[逐物体报告](validation/objects/REPORT.md)及[来源摘要](validation/objects/source-manifest.json)。本组ioi_offset=1,图像编号减1对应标注索引;末图超出标注范围,保留RGB且几何valid=false。本组前两帧暗图只记录,没有套用旧s09曝光排除。仍非全量验收。\n'
119
+ mapping.write_text(body,encoding='utf-8')
120
+ manifest=[{'path':p.relative_to(OUT).as_posix(),'sha256':digest(p)} for p in sorted((OUT/'script').rglob('*.py'))]
121
+ save(DOC/'script-manifest.json',manifest)
122
+ old.setdefault('previous_script_manifest_before_object_review',old['script_manifest']);old['script_manifest']=manifest
123
+ old['additional_fixed_camera_group']={'report_ref':'objects/report.json','sequence_count':11,'camera_id':'6','subject_id':'s06','human_review':'pending'}
124
+ save(DOC.parent/'report.json',old)
125
+ missing=[]
126
+ for page in [home,*DOC.rglob('*.html')]:
127
+ parser=Links();parser.feed(page.read_text(encoding='utf-8'))
128
+ for url in parser.links:
129
+ parts=urlsplit(url)
130
+ if parts.scheme or not parts.path:continue
131
+ if not (page.parent/unquote(parts.path)).exists():missing.append([str(page),url])
132
+ assert not missing,missing
133
+ artifacts=[{'path':p.relative_to(DOC).as_posix(),'size':p.stat().st_size,'sha256':digest(p)} for p in sorted(DOC.rglob('*')) if p.is_file() and p.name!='artifact-manifest.json']
134
+ save(DOC/'artifact-manifest.json',{'files':artifacts,'offline_html_links':'passed','log_files_in_report':False})
135
+ status={'stage':'review_complete_pending_user','completed_views_total':11,'human_review':'pending','report':str(DOC/'index.html'),'full_preprocessing_authorized':False,'upload_authorized':False}
136
+ save(TMP/'status.json',status);save(DOC.parent/'status.json',status)
137
+ state=load(WORK/'tmp/dataset-work-state.json');state['active']['ARCTIC'].update(stage='pilot_two_group_review_awaiting_human_review',object_review_report=str(DOC/'index.html'),object_review_completed=11);save(WORK/'tmp/dataset-work-state.json',state)
138
+ print('FINALIZED',total,n,maximum,flush=True)
139
+
140
+ if __name__=='__main__':
141
+ parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['assets','finalize']);args=parser.parse_args()
142
+ asset_contacts() if args.mode=='assets' else finalize()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/fresh_sequence_common.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for the fresh ARCTIC/HOT3D whole-sequence v1.0 pilots.
2
+
3
+ Original archives are read only. Temporary extraction is outside raw.
4
+ Licensed MANO weights stay in the local model directory and are never published.
5
+ """
6
+ from sequence_pilot_world import camera_mano, Mano
7
+ from pilot_build import *
8
+ from scipy.spatial.transform import Rotation
9
+ import hashlib
10
+ import re
11
+ import time
12
+ import trimesh
13
+ from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED
14
+ from contextlib import contextmanager
15
+
16
+ DATA_ROOT = Path('E:/hand-datasets')
17
+ RELEASE = 'shared-v1.0'
18
+ RUN = 'fresh-sequence-pilot-20260920'
19
+ VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
20
+ MEDIA_POOL=None
21
+ MEDIA_PENDING=[]
22
+ MEDIA_WORKERS=1
23
+ MEDIA_POLICY='legacy_full_pixels'
24
+ OUTPUT_OVERRIDE=None
25
+ TMP_OVERRIDE=None
26
+
27
+ @contextmanager
28
+ def media_pipeline(workers=1,policy='jpeg-packets-all-rgb-sample16/v1'):
29
+ global MEDIA_POOL,MEDIA_PENDING,MEDIA_WORKERS,MEDIA_POLICY
30
+ assert MEDIA_POOL is None and not MEDIA_PENDING
31
+ MEDIA_WORKERS=workers;MEDIA_POLICY=policy
32
+ MEDIA_POOL=ThreadPoolExecutor(max_workers=workers)
33
+ try:
34
+ yield
35
+ for future in MEDIA_PENDING:future.result()
36
+ finally:
37
+ MEDIA_POOL.shutdown(wait=True,cancel_futures=True)
38
+ MEDIA_POOL=None;MEDIA_PENDING=[];MEDIA_POLICY='legacy_full_pixels'
39
+
40
+ def submit_media(view,members_factory):
41
+ global MEDIA_PENDING
42
+ def execute():
43
+ jpeg_video(view,members_factory());view.m['pilot_complete']=True;view.finish()
44
+ if MEDIA_POOL is None:execute();return
45
+ # Bound pending views and source/video spools, not only running FFmpeg tasks.
46
+ while len(MEDIA_PENDING)>=MEDIA_WORKERS:
47
+ finished,_=wait(MEDIA_PENDING,return_when=FIRST_COMPLETED)
48
+ for future in finished:future.result()
49
+ MEDIA_PENDING=[f for f in MEDIA_PENDING if f not in finished]
50
+ MEDIA_PENDING.append(MEDIA_POOL.submit(execute))
51
+
52
+ def digest(p):
53
+ h=hashlib.sha256()
54
+ with Path(p).open('rb') as f:
55
+ for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
56
+ return h.hexdigest()
57
+
58
+ def native_npy_bytes(data):
59
+ f=io.BytesIO(data);version=np.lib.format.read_magic(f)
60
+ shape,order,dtype=np.lib.format._read_array_header(f,version)
61
+ if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
62
+ return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()
63
+
64
+ def command(args):
65
+ r=subprocess.run([str(x) for x in args],capture_output=True)
66
+ if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
67
+ return r.stdout
68
+
69
+ def framehash(args,copy=False):
70
+ output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
71
+ *(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
72
+ '-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
73
+ return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]
74
+
75
+ def jpeg_video(view, members):
76
+ """members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
77
+ if MEDIA_POLICY!='legacy_full_pixels':
78
+ from accelerated_media import write_video
79
+ return write_video(view,members)
80
+ temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
81
+ temporary.parent.mkdir(parents=True,exist_ok=True)
82
+ hashes=[]
83
+ with temporary.open('wb') as out:
84
+ for locator,b in members:
85
+ assert b[:2]==b'\xff\xd8',locator
86
+ hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
87
+ assert len(hashes)==view.T
88
+ dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
89
+ source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
90
+ command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
91
+ packet=framehash(['-i',str(dst)],True)
92
+ assert packet==hashes,'source JPEG packets changed in MKV'
93
+ before=framehash(source);after=framehash(['-i',str(dst)])
94
+ assert before==after and len(before)==view.T,'RGB decoding differs'
95
+ w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
96
+ info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
97
+ line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
98
+ pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
99
+ version=command([FF,'-version']).decode().splitlines()[0]
100
+ view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
101
+ source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
102
+ storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
103
+ 'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
104
+ 'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
105
+ view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
106
+ 'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
107
+ 'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
108
+ save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
109
+ # This precise file was created by this call within the current run's temporary directory.
110
+ assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()
111
+
112
+ class FreshView:
113
+ def __init__(self,dataset,seq,cam,ids,size,source):
114
+ self.root=(OUTPUT_OVERRIDE/dataset/RELEASE if OUTPUT_OVERRIDE else DATA_ROOT/dataset/RELEASE);self.p=self.root/'data'/seq/cam
115
+ self.tmp=(TMP_OVERRIDE/dataset/RUN if TMP_OVERRIDE else DATA_ROOT/dataset/'tmp'/RUN);self.p.mkdir(parents=True,exist_ok=True)
116
+ self.T=len(ids);self.source=source;self.checks=[]
117
+ self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
118
+ 'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
119
+ 'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
120
+ 'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
121
+ 'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
122
+ self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
123
+ 'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
124
+ def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
125
+ valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
126
+ self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
127
+ 'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
128
+ 'source_locator':source or self.source,**kw}
129
+ def array(self,name,path,schema,data,valid,axes,**kw):
130
+ a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
131
+ assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
132
+ assert np.isfinite(a[valid]).all(),name
133
+ a[~valid]=np.nan;tensor(self.p/path,a)
134
+ self.component(name,path,schema,axes,valid,**kw)
135
+ restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
136
+ assert np.array_equal(a,restored,equal_nan=True)
137
+ self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
138
+ def attribute(self,parent,path,data,axes,source,meaning):
139
+ data=np.asarray(data,np.float32);valid=np.isfinite(data)
140
+ assert ((data[valid]>=0)&(data[valid]<=1)).all()
141
+ vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
142
+ self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
143
+ 'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
144
+ 'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
145
+ def mesh(self,oid,path,source):
146
+ self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
147
+ method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
148
+ def finish(self):
149
+ lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
150
+ save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
151
+ print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
152
+
153
+ def assert_se3(a):
154
+ a=np.asarray(a);assert a.shape[-2:]==(4,4)
155
+ # A component may exist while QA leaves no usable poses in this view.
156
+ if a.size==0:return
157
+ assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
158
+ r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
159
+ assert np.max(np.abs(np.linalg.det(r)-1))<2e-5
160
+
161
+ def setup(dataset,seq):
162
+ base=DATA_ROOT/dataset;out=base/RELEASE
163
+ for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
164
+ for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
165
+ save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
166
+ # The organized script bundle is already self-contained; runtime work must not repopulate its root.
167
+ (base/'tmp'/RUN).mkdir(parents=True,exist_ok=True)
168
+
169
+ def object_textured_assets(z,prefix,target):
170
+ target.mkdir(parents=True,exist_ok=True)
171
+ for name in z.namelist():
172
+ if not name.startswith(prefix) or name.endswith('/'):continue
173
+ rel=Path(name[len(prefix):]);dest=target/rel
174
+ assert dest.resolve().is_relative_to(target.resolve());dest.parent.mkdir(parents=True,exist_ok=True)
175
+ if dest.suffix.lower() in ('.obj','.mtl','.jpg','.jpeg','.png'):
176
+ b=z.read(name)
177
+ if dest.suffix=='.obj':
178
+ rows=b.decode().splitlines()
179
+ for i,row in enumerate(rows):
180
+ if row.startswith('v '):
181
+ v=row.split();v[1:4]=[format(float(x)/1000,'.17g') for x in v[1:4]];rows[i]=' '.join(v)
182
+ b=('\n'.join(rows)+'\n').encode()
183
+ dest.write_bytes(b)
184
+ repair_arctic_material_refs(target)
185
+
186
+ def repair_arctic_material_refs(target):
187
+ """Repair a source filename mismatch only when material identifiers agree."""
188
+ material=target/'material.mtl'
189
+ if not material.exists():return
190
+ ids={x.split(maxsplit=1)[1] for x in material.read_text().splitlines() if x.startswith('newmtl ')}
191
+ for obj in target.glob('*.obj'):
192
+ text=obj.read_text();rows=text.splitlines();used={x.split(maxsplit=1)[1] for x in rows if x.startswith('usemtl ')}
193
+ if 'mtllib material_0.mtl' in rows and not (target/'material_0.mtl').exists():
194
+ assert used and used.issubset(ids),(obj,used,ids)
195
+ obj.write_text(text.replace('mtllib material_0.mtl','mtllib material.mtl'))
196
+
197
+ def project_points(xyz,camera,params):
198
+ xyz=np.asarray(xyz,float);uv=np.full((len(xyz),2),np.nan);good=np.isfinite(xyz).all(1)&(xyz[:,2]>1e-6)
199
+ if camera=='fisheye624':
200
+ p=np.asarray(params);xy=xyz[good,:2]/xyz[good,2,None];r=np.linalg.norm(xy,axis=1);th=np.arctan(r)
201
+ radial=th*(1+sum(p[3+i]*th**(2*i+2) for i in range(6)))
202
+ xy=xy*np.divide(radial,r,out=np.ones_like(r),where=r>1e-12)[:,None]
203
+ x,y=xy.T;rr=x*x+y*y
204
+ xd=x+(2*x*x+rr)*p[9]+2*x*y*p[10]+p[11]*rr+p[12]*rr*rr
205
+ yd=y+(2*y*y+rr)*p[10]+2*x*y*p[9]+p[13]*rr+p[14]*rr*rr
206
+ uv[good]=p[0]*np.stack([xd,yd],1)+p[1:3]
207
+ else:
208
+ K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
209
+ return uv
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_build.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small, source-traceable dataset pilot. Originals are copied, never edited.
2
+
3
+ Run with Python + numpy + torch + Pillow + opencv and imageio-ffmpeg.
4
+ Optional runtime installed at tmp/pilot-runtime. Outputs: hand-datasets/.
5
+ """
6
+ from pathlib import Path
7
+ import argparse, codecs, collections, csv, io, json, pickle, shutil, subprocess, sys, zipfile
8
+ sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tmp/pilot-runtime'))
9
+ import numpy as np
10
+ import torch
11
+ from PIL import Image, ImageDraw
12
+ import cv2
13
+ from pilot_fetch import ROOT, sha
14
+
15
+ WORK=ROOT.parent
16
+ OLD=WORK/'datasets'
17
+ sys.path.insert(0,str(WORK/'tmp/pilot-runtime'))
18
+ import imageio_ffmpeg
19
+ FF=imageio_ffmpeg.get_ffmpeg_exe()
20
+ N=16
21
+
22
+ def save(p,value):
23
+ p.parent.mkdir(parents=True,exist_ok=True)
24
+ p.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
25
+ def lines(p,rows):
26
+ p.parent.mkdir(parents=True,exist_ok=True)
27
+ p.write_text(''.join(json.dumps(x,ensure_ascii=False,allow_nan=False)+'\n' for x in rows),encoding='utf-8')
28
+ def tensor(p,a):
29
+ p.parent.mkdir(parents=True,exist_ok=True);torch.save(torch.as_tensor(np.asarray(a).copy()),p)
30
+ def load(p):return json.loads(p.read_text(encoding='utf-8'))
31
+
32
+ class Restricted(pickle.Unpickler):
33
+ def find_class(self,module,name):
34
+ allowed={('numpy.core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
35
+ ('numpy._core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
36
+ ('numpy','ndarray'):np.ndarray,('numpy','dtype'):np.dtype,
37
+ ('numpy.core.numeric','_frombuffer'):np.core.numeric._frombuffer,
38
+ ('numpy._core.numeric','_frombuffer'):np.core.numeric._frombuffer,
39
+ ('_codecs','encode'):codecs.encode,
40
+ ('collections','OrderedDict'):collections.OrderedDict,
41
+ ('torch._utils','_rebuild_tensor_v2'):torch._utils._rebuild_tensor_v2,
42
+ ('torch.storage','_load_from_bytes'):lambda b:torch.load(io.BytesIO(b),map_location='cpu',weights_only=True)}
43
+ if (module,name) not in allowed:raise pickle.UnpicklingError(f'Unsupported class: {module}.{name}')
44
+ return allowed[(module,name)]
45
+ def read_pickle(p):
46
+ with p.open('rb') as f:return Restricted(f,encoding='latin1').load()
47
+
48
+ class Build:
49
+ def __init__(self,name):
50
+ self.name=name;self.base=ROOT/name;self.out=self.base/'pilot-v0';self.refs=[];self.views=[];self.checks=[]
51
+ for p in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(self.base/p).mkdir(parents=True,exist_ok=True)
52
+ def copy(self,src):
53
+ rel=src.relative_to(OLD/self.name);dst=self.base/'raw/data/local_subset'/rel
54
+ dst.parent.mkdir(parents=True,exist_ok=True)
55
+ if not dst.exists():shutil.copyfile(src,dst)
56
+ source_hash=sha(src);assert sha(dst)==source_hash
57
+ self.refs.append({'source':str(src),'stored':str(dst.relative_to(self.base)), 'sha256':source_hash,'bytes':src.stat().st_size,'kind':'historical_extracted_file_copy','official_archive_verified':False})
58
+ return dst
59
+ def view(self,seq,cam,ids,**meta):
60
+ p=self.out/'data'/seq/cam;p.mkdir(parents=True,exist_ok=True)
61
+ m={'schema_version':'pilot-v0','dataset':self.name,'sequence_id':seq,'camera_id':cam,'num_frames':len(ids),'fps':None,'split':None,'view_type':None,'time_semantics':'unknown','missing_modalities':{},**meta}
62
+ self.views.append((p,m))
63
+ lines(p/'frames.jsonl',[{'frame_index':i,'source_frame_id':str(s),'timestamp_ns':None,'clock_domain':None} for i,s in enumerate(ids)])
64
+ return p,m
65
+ def video(self,p,arrays):
66
+ a=np.stack(arrays);h,w=a.shape[1:3]
67
+ pixel='rgb24' if a.ndim==4 else ('gray16le' if a.dtype==np.uint16 else 'gray')
68
+ if pixel=='gray16le':a=a.astype('<u2')
69
+ a=np.ascontiguousarray(a);p.parent.mkdir(parents=True,exist_ok=True)
70
+ command=[FF,'-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format',pixel,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-an','-c:v','ffv1','-level','3','-g','1',str(p)]
71
+ subprocess.run(command,input=a.tobytes(),check=True,capture_output=True)
72
+ decoded=subprocess.run([FF,'-v','error','-i',str(p),'-f','rawvideo','-pix_fmt',pixel,'pipe:1'],check=True,capture_output=True).stdout
73
+ assert decoded==a.tobytes(),f'Lossless roundtrip failed: {p}'
74
+ self.checks.append({'file':str(p.relative_to(self.out)),'test':'decode_all_frames_pixel_exact','passed':True,'frames':len(a),'dtype':str(a.dtype),'shape':list(a.shape)})
75
+ return {'codec':'FFV1','pixel_format':pixel,'container_fps':1,'container_time_is_capture_time':False}
76
+ def finish(self,notes):
77
+ for p,m in self.views:save(p/'metainfo.json',m)
78
+ save(self.base/'raw/doc/local_subset_manifest.json',self.refs)
79
+ report={'dataset':self.name,'views':len(self.views),'observations':sum(m['num_frames'] for _,m in self.views),'checks':self.checks,'notes':notes,'status':'partial' if notes else 'passed'}
80
+ save(self.out/'doc/report.json',report)
81
+ # Script provenance is supplied by the organized bundle and validation manifests.
82
+ files=[{'path':str(p.relative_to(self.out)), 'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted((self.out/'data').rglob('*')) if p.is_file()]
83
+ save(self.out/'doc/output_manifest.json',files)
84
+ print(json.dumps(report,ensure_ascii=False),flush=True)
85
+ return report
86
+
87
+ def h2o():
88
+ b=Build('H2O');src=OLD/'H2O/subject4_ego/h1/0/cam4';ids=list(range(N))
89
+ p,m=b.view('subject4_h1_0','cam4',ids,split='test',view_type='ego',time_semantics='ordered_source_frames; acquisition FPS not yet verified')
90
+ for folder in ['rgb','depth','hand_pose','hand_pose_mano','cam_pose']:
91
+ for i in ids:b.copy(src/folder/f'{i:06d}.{ "png" if folder in ["rgb","depth"] else "txt"}')
92
+ intr=np.loadtxt(b.copy(src/'cam_intrinsics.txt'));fx,fy,cx,cy,w,h=intr
93
+ tensor(p/'camera/intrinsic.pt',np.array([[fx,0,cx],[0,fy,cy],[0,0,1]],np.float32))
94
+ ext=np.stack([np.loadtxt(src/'cam_pose'/f'{i:06d}.txt').reshape(4,4) for i in ids])
95
+ tensor(p/'camera/extrinsic.pt',np.linalg.inv(ext).astype(np.float32))
96
+ m['camera']={'model':'pinhole','width':int(w),'height':int(h),'extrinsic':'T_camera_from_world','source_extrinsic':'T_world_from_camera','unit':'m','distortion':'not supplied in selected intrinsics'}
97
+ a=np.stack([np.loadtxt(src/'hand_pose_mano'/f'{i:06d}.txt').reshape(2,62) for i in ids])
98
+ valid=a[:,:,0]==1;motion=np.concatenate([a[:,:,4:52],a[:,:,52:62],a[:,:,1:4]],axis=-1).astype(np.float32)
99
+ motion[~valid]=np.nan;tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',valid)
100
+ m['mano']={'layout':['pose_axis_angle:48','betas:10','translation:3'],'shape':[N,2,61],'slots':['left','right'],'coordinate_frame':'camera','translation_unit':'m','flat_hand_mean':True,'model_version':'not supplied; MANO model not bundled','valid_flag':'source annotation flag, not visibility','geometry_validation':'not_tested; model unavailable'}
101
+ joints=np.stack([np.loadtxt(src/'hand_pose'/f'{i:06d}.txt').reshape(2,64) for i in ids]);tensor(p/'annotation/keypoints/xyz.pt',joints[:,:,1:].reshape(N,2,21,3).astype(np.float32));tensor(p/'annotation/keypoints/valid_flag.pt',joints[:,:,0]==1)
102
+ rgb=[np.asarray(Image.open(src/'rgb'/f'{i:06d}.png').convert('RGB')) for i in ids]
103
+ depth=[np.asarray(Image.open(src/'depth'/f'{i:06d}.png'),dtype=np.uint16) for i in ids]
104
+ m['rgb']=b.video(p/'observation/rgb.mkv',rgb);m['depth']={**b.video(p/'observation/depth.mkv',depth),'unit':'mm','scale_to_meters':0.001,'invalid_value':0,'rgb_registration':'not_tested'}
105
+ m['missing_modalities']={'object':'not present in selected historical subset','segmentation':'no native mask in selected subset'}
106
+ # Independent check: 3D keypoint projections must be finite where the source flags valid.
107
+ xyz=joints[:,:,1:].reshape(N,2,21,3);projection=xyz@np.array([[fx,0,cx],[0,fy,cy],[0,0,1]]).T
108
+ uv=projection[...,:2]/projection[...,2:];assert np.isfinite(uv[joints[:,:,0]==1]).all()
109
+ image=Image.fromarray(rgb[0]);draw=ImageDraw.Draw(image)
110
+ for side in range(2):
111
+ for u,v in uv[0,side]:draw.ellipse((u-3,v-3,u+3,v+3),fill=('red' if side==0 else 'cyan'))
112
+ image.save(b.out/'doc/keypoints_overlay.png')
113
+ return b.finish(['MANO geometry not rendered; model asset unavailable. RGB-depth registration not tested. No native segmentation or object input in subset.'])
114
+
115
+ def visor():
116
+ b=Build('VISOR');raw=b.base/'raw/data/GroundTruth-SparseAnnotations';jp=raw/'annotations/train/P01_03.json';zp=raw/'rgb_frames/train/P01/P01_03.zip'
117
+ source=load(jp);annotations=source['video_annotations'][:N]
118
+ ids=[x['image']['name'] for x in annotations];p,m=b.view('P01_03','ego',ids,split='train',view_type='ego',time_semantics='sparse_annotations; use source frame IDs; MKV timestamps are storage indices')
119
+ rgbs=[];masks=[];records=[]
120
+ with zipfile.ZipFile(zp) as z:
121
+ assert z.testzip() is None
122
+ for i,frame in enumerate(annotations):
123
+ rgb=np.asarray(Image.open(io.BytesIO(z.read(frame['image']['name']))).convert('RGB'));rgbs.append(rgb)
124
+ mask=np.zeros((1080,1920),np.uint16);entities=[]
125
+ for value,entity in enumerate(frame['annotations'],1):
126
+ # Same polygon rasterization primitive and integer conversion as official VISOR-VIS.
127
+ polygons=[np.asarray(poly,dtype=np.int32) for poly in entity['segments'] if len(poly)>=3]
128
+ if polygons:cv2.fillPoly(mask,polygons,int(value))
129
+ entities.append({'mask_value':value,'instance_id':entity['id'],'track_id':None,'source':{k:v for k,v in entity.items() if k!='segments'}})
130
+ if mask.shape!=rgb.shape[:2]:mask=cv2.resize(mask,(rgb.shape[1],rgb.shape[0]),interpolation=cv2.INTER_NEAREST)
131
+ masks.append(mask);records.append({'frame_index':i,'source_frame_id':frame['image']['name'],'subsequence':frame['image']['subsequence'],'annotation_valid':True,'instances':entities})
132
+ assert set(np.unique(mask)) <= {0,*[x['mask_value'] for x in entities]}
133
+ m['rgb']=b.video(p/'observation/rgb.mkv',rgbs);m['segmentation']={**b.video(p/'annotation/segmentation/mask.mkv',masks),'provenance':'native_sparse_polygon_rasterized','background_value':0,'background_semantics':'unlabeled/background; source is not globally exhaustive','ignore_value':None,'polygon_canvas':[1920,1080],'overlap_policy':'source annotation order; last polygon wins','track_id':'unknown; no heuristic tracking'}
134
+ lines(p/'annotation/segmentation/instances.jsonl',records)
135
+ m['missing_modalities']={'mano':'not supplied','depth':'not supplied','camera':'not supplied','object_pose_mesh':'not supplied'}
136
+ im=rgbs[2].copy();mask=masks[2];colors=np.array([[0,0,0],[240,70,70],[70,240,90],[70,100,240],[230,190,60],[150,80,200]],np.uint8)
137
+ used=mask>0;im[used]=(im[used]*0.55+colors[mask[used]%len(colors)]*0.45).astype(np.uint8)
138
+ Image.fromarray(im).save(b.out/'doc/segmentation_overlay.png')
139
+ b.checks.append({'test':'official_zip_crc_all_members','passed':True,'members':len(zipfile.ZipFile(zp).namelist())})
140
+ b.checks.append({'test':'all_mask_values_resolve_to_frame_instances','passed':True})
141
+ return b.finish([])
142
+
143
+ def rhd():
144
+ b=Build('RHD');src=OLD/'RHD/RHD_published_v2/evaluation';ann=read_pickle(b.copy(src/'anno_evaluation.pickle'))
145
+ for i in range(N):
146
+ p,m=b.view(f'evaluation_{i:05d}','camera',[i],split='evaluation',time_semantics='independent_image')
147
+ rgb=np.asarray(Image.open(b.copy(src/'color'/f'{i:05d}.png')).convert('RGB'))
148
+ depth=np.asarray(Image.open(b.copy(src/'depth'/f'{i:05d}.png')).convert('RGB'),dtype=np.uint16)
149
+ code=depth[:,:,0]*256+depth[:,:,1]
150
+ m['rgb']=b.video(p/'observation/rgb.mkv',[rgb]);m['depth']={**b.video(p/'observation/depth.mkv',[code]),'encoding':'source R*256+G','metric_unit':None,'metric_conversion_status':'not_tested; preserved integer code only'}
151
+ tensor(p/'camera/intrinsic.pt',ann[i]['K']);tensor(p/'annotation/keypoints/xyz.pt',ann[i]['xyz'].reshape(1,2,21,3));tensor(p/'annotation/keypoints/uv.pt',ann[i]['uv_vis'][:,:2].reshape(1,2,21,2));tensor(p/'annotation/keypoints/visible.pt',(ann[i]['uv_vis'][:,2]==1).reshape(1,2,21))
152
+ m['keypoints']={'unit':'m','layout':'source 42-joint order reshaped as 2x21','hand_order':['left','right'],'joint_order':'official RHD: wrist then thumb/index/middle/ring/pinky, fingers tip-to-palm','definition_reference':'raw/doc/dataset_README.txt','visibility':'per joint; invisible does not mean unannotated'}
153
+ m['missing_modalities']={'mano':'not supplied by source','segmentation':'omitted by historical downloader','extrinsic':'not supplied in selected annotations'}
154
+ return b.finish(['Depth metric conversion pending; segmentation absent from historical input.'])
155
+
156
+ def freihand():
157
+ b=Build('FreiHAND');src=OLD/'FreiHAND';K=load(b.copy(src/'training_K.json'));mano=load(b.copy(src/'training_mano.json'));scale=load(b.copy(src/'training_scale.json'))
158
+ for base in range(4):
159
+ for variant in range(4):
160
+ i=base+variant*32560;p,m=b.view(f'training_{base:08d}',f'variant_{variant}',[i],split='training',time_semantics='independent_image',base_sample_id=str(base),variant_id=variant)
161
+ m['camera_group_semantics']='image_variant_not_physical_camera';m['physical_camera_id']=None
162
+ rgb=np.asarray(Image.open(b.copy(src/'training/rgb'/f'{i:08d}.jpg')).convert('RGB'));m['rgb']=b.video(p/'observation/rgb.mkv',[rgb])
163
+ tensor(p/'camera/intrinsic.pt',np.asarray(K[base],np.float32));tensor(p/'annotation/mano/source_theta.pt',np.asarray(mano[base],np.float32));tensor(p/'annotation/mano/source_scale.pt',np.asarray(scale[base],np.float32))
164
+ m['mano']={'source_theta_layout':['pose48','shape10','uv_root2','scale1'],'motion_status':'not_generated','reason':'To recover MANO translation, official code subtracts posed joint 9 from backprojected root. Requires correct MANO model; last three source values are not translation.'}
165
+ m['missing_modalities']={'depth':'not supplied','segmentation':'not present in historical input','extrinsic':'not supplied','normalized_mano':'model dependency unresolved'}
166
+ return b.finish(['Preserved source MANO theta; no misleading motion.pt produced. Correct model needed for normalized translation.'])
167
+
168
+ def hoi4d():
169
+ b=Build('HOI4D');rel=Path('ZY20210800001/H1/C20/N18/S286/s01/T1');src=OLD/'HOI4D/Hand_pose/handpose_left_hand'/rel
170
+ files=sorted(src.glob('*.pickle'),key=lambda p:int(p.stem))[:N];ids=[x.stem for x in files]
171
+ p,m=b.view('H1_C20_N18_S286_s01_T1','ZY20210800001',ids,view_type='ego',time_semantics='annotation_frame_ids_only')
172
+ a=np.full((len(ids),2,61),np.nan,np.float32);v=np.zeros((len(ids),2),bool);uv=np.full((len(ids),2,21,2),np.nan,np.float32)
173
+ for i,frame in enumerate(ids):
174
+ for side,folder in enumerate(['handpose_left_hand','handpose_right_hand']):
175
+ f=OLD/'HOI4D/Hand_pose'/folder/rel/(frame+'.pickle')
176
+ if not f.exists():continue
177
+ x=read_pickle(b.copy(f));a[i,side]=np.concatenate([x['poseCoeff'].reshape(-1),x['beta'].reshape(-1),x['trans'].reshape(-1)]);v[i,side]=True;uv[i,side]=x['kps2D']
178
+ tensor(p/'annotation/mano/motion.pt',a);tensor(p/'annotation/mano/valid_flag.pt',v);tensor(p/'annotation/keypoints/uv.pt',uv)
179
+ tensor(p/'camera/intrinsic.pt',np.load(b.copy(OLD/'HOI4D/camera_params/ZY20210800001/intrin.npy'),allow_pickle=False))
180
+ m['mano']={'layout':['pose_axis_angle48','betas10','translation3'],'slots':['left','right'],'translation_unit':'m','coordinate_frame':'camera','flat_hand_mean':True,'valid_flag':'source file present and parsed; not visibility','geometry_validation':'not_tested'}
181
+ m['missing_modalities']={'rgb':'not downloaded','depth':'not downloaded','segmentation':'not downloaded','extrinsic':'not available in selected subset','object':'not available in selected subset'}
182
+ return b.finish(['Annotation-only mini; no matching RGB/depth/segmentation downloaded. MANO geometry not rendered.'])
183
+
184
+ def reinterhand():
185
+ b=Build('ReInterHand');src=next(p for p in sorted((OLD/'ReInterHand').glob('m--*')) if (p/'mano_fits/params').exists());files=sorted((src/'mano_fits/params').glob('*_left.json'))[:N];ids=[x.stem.rsplit('_',1)[0] for x in files]
186
+ # Capture-level poses have no established camera transform in current local subset.
187
+ p,m=b.view(src.name,'source_unresolved',ids,time_semantics='capture_annotations_only; not a camera observation')
188
+ rows=[]
189
+ for frame in ids:
190
+ row={'source_frame_id':frame,'hands':{}}
191
+ for side in ['left','right']:
192
+ f=src/'mano_fits/params'/f'{frame}_{side}.json'
193
+ if f.exists():row['hands'][side]=load(b.copy(f))
194
+ rows.append(row)
195
+ lines(p/'annotation/mano/source_parameters.jsonl',rows)
196
+ m['missing_modalities']={'rgb':'not extracted from incomplete archive set','camera':'not available','normalized_mano':'source-to-camera mapping unresolved'}
197
+ m['not_a_real_camera']=True
198
+ return b.finish(['Source-only annotation sample. source_unresolved is an explicit staging group, not an invented camera.'])
199
+
200
+ def main():
201
+ parser=argparse.ArgumentParser();parser.add_argument('--dataset',nargs='*',default=['VISOR','H2O','RHD','FreiHAND','HOI4D','ReInterHand']);args=parser.parse_args()
202
+ funcs={'VISOR':visor,'H2O':h2o,'RHD':rhd,'FreiHAND':freihand,'HOI4D':hoi4d,'ReInterHand':reinterhand}
203
+ for name in args.dataset:
204
+ try:funcs[name]()
205
+ except Exception as e:
206
+ save(ROOT/name/'pilot-v0/doc/build_error.json',{'error':str(e)});raise
207
+ if __name__=='__main__':main()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_fetch.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download bounded official pilot inputs; keep archives intact. No upstream code execution."""
2
+ from pathlib import Path
3
+ import concurrent.futures, hashlib, json, requests
4
+
5
+ ROOT = Path(__file__).resolve().parents[1] / 'hand-datasets'
6
+ REFS = {
7
+ 'Dex-YCB': ('NVlabs/dex-ycb-toolkit', ['README.md','dex_ycb_toolkit/dex_ycb.py','dex_ycb_toolkit/sequence_loader.py']),
8
+ 'VISOR': ('epic-kitchens/VISOR-VIS', ['README.md','vis.py']),
9
+ 'H2O': ('taeinkwon/h2odataset', ['README.md','download_script.py']),
10
+ 'HOI4D': ('leolyliu/HOI4D-Instructions', ['README.md','utils/parse_2Dmask_img.py','utils/color_map.py']),
11
+ 'ARCTIC': ('zc-alexfan/arctic', ['docs/data/README.md','docs/data/data_doc.md']),
12
+ 'FreiHAND': ('lmb-freiburg/freihand', ['README.md','utils/model.py','utils/fh_utils.py','view_samples.py']),
13
+ 'RHD': ('lmb-freiburg/hand3d', ['README.md','create_binary_db.py']),
14
+ 'HOT3D': ('facebookresearch/hot3d', ['README.md','hot3d/data_loaders/loader_hand_poses.py']),
15
+ 'OakInk2': ('oakink/OakInk2', ['README.md']),
16
+ 'ReInterHand': ('facebookresearch/InterWild', ['tool/ReInterHand/download/download_checksum_framelist.py','tool/ReInterHand/download/download_ego_per_frame.py','tool/ReInterHand/download/download_mano_fits.py']),
17
+ }
18
+ BASE='https://data.bris.ac.uk/datasets/2v6cgv1x04ol22qp9rm9x2j6a7/'
19
+
20
+ def sha(p):
21
+ h=hashlib.sha256()
22
+ with p.open('rb') as f:
23
+ for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
24
+ return h.hexdigest()
25
+
26
+ def fetch(dataset, url, relative, limit=30_000_000):
27
+ p=ROOT/dataset/'raw'/relative;p.parent.mkdir(parents=True,exist_ok=True)
28
+ receipt=p.with_name(p.name+'.receipt.json')
29
+ if p.exists() and receipt.exists():
30
+ info=json.loads(receipt.read_text()); assert sha(p)==info['sha256'];return info
31
+ part=p.with_name(p.name+'.part')
32
+ with requests.get(url,stream=True,headers={'Accept-Encoding':'identity'},timeout=(15,40)) as r:
33
+ r.raise_for_status(); expected=int(r.headers.get('Content-Length',0))
34
+ if expected>limit:raise ValueError(f'File exceeds pilot limit: {expected}')
35
+ size=0
36
+ with part.open('wb') as f:
37
+ for chunk in r.iter_content(1024*1024):
38
+ size+=len(chunk)
39
+ if size>limit:raise ValueError('Stream exceeds pilot limit')
40
+ f.write(chunk)
41
+ if expected and not r.headers.get('Content-Encoding') and size!=expected:raise ValueError('Incomplete transfer')
42
+ part.replace(p)
43
+ info={'url':url,'path':str(p.relative_to(ROOT/dataset)), 'bytes':size,'sha256':sha(p),'official_checksum':None,'verification':'HTTP success; content length where supplied; locally computed SHA256'}
44
+ receipt.write_text(json.dumps(info,indent=2),encoding='utf-8');return info
45
+
46
+ def reference(item):
47
+ name,(repo,paths)=item;results=[]
48
+ for section in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(ROOT/name/section).mkdir(parents=True,exist_ok=True)
49
+ for path in paths:
50
+ try:results.append(fetch(name,f'https://raw.githubusercontent.com/{repo}/HEAD/{path}',('script/' if path.endswith('.py') else 'doc/')+path))
51
+ except Exception as e:results.append({'path':path,'error':str(e)})
52
+ return name,results
53
+
54
+ def main():
55
+ results=dict(concurrent.futures.ThreadPoolExecutor(6).map(reference,REFS.items()))
56
+ for path in ['GroundTruth-SparseAnnotations/annotations/train/P01_03.json','GroundTruth-SparseAnnotations/rgb_frames/train/P01/P01_03.zip','EPIC_100_noun_classes_v2.csv','frame_mapping.json']:
57
+ try:results['VISOR'].append(fetch('VISOR',BASE+path,'data/'+path))
58
+ except Exception as e:results['VISOR'].append({'path':path,'error':str(e)})
59
+ for name,rows in results.items():
60
+ (ROOT/name/'raw/doc/download_manifest.json').write_text(json.dumps(rows,indent=2),encoding='utf-8')
61
+ print(name,[(r.get('path'),r.get('bytes',r.get('error'))) for r in rows],flush=True)
62
+
63
+ if __name__=='__main__':main()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_hot_normalize.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pilot_mano import *
2
+
3
+ def transform(q,t):
4
+ q=np.asarray(q,float);q=q/np.linalg.norm(q);w,x,y,z=q
5
+ R=np.array([[1-2*(y*y+z*z),2*(x*y-z*w),2*(x*z+y*w)],[2*(x*y+z*w),1-2*(x*x+z*z),2*(y*z-x*w)],[2*(x*z-y*w),2*(y*z+x*w),1-2*(x*x+y*y)]])
6
+ T=np.eye(4);T[:3,:3]=R;T[:3,3]=t;return T
7
+ def csv_transform(row):return transform([float(row['q_wo_'+a]) for a in ['w','x','y','z']],[float(row[f't_wo_{a}[m]']) for a in ['x','y','z']])
8
+ def main():
9
+ base=ROOT/'HOT3D/pilot-v0';p=next((base/'data').rglob('metainfo.json')).parent;m=load(p/'metainfo.json');frames=[json.loads(l) for l in (p/'frames.jsonl').read_text().splitlines()];source=OLD/'HOT3D/P0001_10a27bf7'
10
+ camera=next(c for c in load(source/'camera_models.json') if c['stream_id']=='214-1');dc=camera['T_Device_Camera'];Tdc=transform(dc['quaternion_wxyz'],dc['translation_xyz'])
11
+ device={int(r['timestamp[ns]']):csv_transform(r) for r in csv.DictReader((source/'headset_trajectory.csv').open())}
12
+ Tcws=np.stack([np.linalg.inv(device[f['timecode_ns']]@Tdc) for f in frames]);tensor(p/'camera/extrinsic.pt',Tcws.astype(np.float32));tensor(p/'camera/intrinsic.pt',np.array(camera['projectionParams'],np.float32))
13
+ m['camera']={'projection_model':'FISHEYE624','intrinsic_layout':'15 native projectionParams, not a 3x3 K','width':camera['imageWidth'],'height':camera['imageHeight'],'extrinsic':'T_camera_from_world','unit':'m','calibration_source':'static camera_models.json + exact timecode headset trajectory; online calibration not substituted'}
14
+ models=[Mano('left'),Mano('right')]
15
+ # Match the explicitly documented fix in HOT3D official mano_layer.py.
16
+ fixed=np.abs(models[0].data['shapedirs'][:,0]-models[1].data['shapedirs'][:,0]).sum()<1
17
+ if fixed:
18
+ models[0].data['shapedirs'][:,0]*=-1
19
+ with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
20
+ rows=[json.loads(l) for l in (p/'annotation/mano/source_parameters.jsonl').read_text().splitlines()];motion=np.full((len(rows),2,61),np.nan,np.float32);valid=np.zeros((len(rows),2),bool);errors=[]
21
+ for i,row in enumerate(rows):
22
+ for side,hand in row['source_annotation']['hand_poses'].items():
23
+ side=int(side);model=models[side];beta=np.array(hand['betas']);wrist=hand['wrist_xform'];Tw=transform(wrist['q_wxyz'],wrist['t_xyz']);pose=np.r_[cv2.Rodrigues(Tw[:3,:3])[0].ravel(),np.array(hand['pose'])@model.data['hands_components'][:15]+model.data['hands_mean']]
24
+ world_vertices,_,_=model.geometry(pose,beta,Tw[:3,3]);root=model.data['J_regressor'][0]@(model.data['v_template']+np.einsum('vci,i->vc',model.data['shapedirs'],beta))
25
+ Tc=Tcws[i];camera_pose=pose.copy();camera_pose[:3]=cv2.Rodrigues(Tc[:3,:3]@Tw[:3,:3])[0].ravel();camera_t=Tc[:3,:3]@(root+Tw[:3,3])+Tc[:3,3]-root
26
+ camera_vertices,_,_=model.geometry(camera_pose,beta,camera_t);transformed=world_vertices@Tc[:3,:3].T+Tc[:3,3];error=float(np.linalg.norm(camera_vertices-transformed,axis=-1).max());errors.append(error);assert error<1e-5
27
+ motion[i,side]=np.r_[camera_pose,beta,camera_t];valid[i,side]=True
28
+ tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',valid)
29
+ m['mano']={'layout':['pose_axis_angle48','betas10','translation3'],'slots':['left','right'],'coordinate_frame':'camera','translation_unit':'m','flat_hand_mean':True,'model_version':'MANO v1.2','left_shapedirs_fix':bool(fixed),'conversion':'official 15-PCA expansion; world-to-camera rotation and shape-dependent root correction','valid_flag':'source annotation present, not visibility'}
30
+ objects=[json.loads(l) for l in (p/'annotation/object/source_world_poses.jsonl').read_text().splitlines()];object_ids=sorted({r['object_uid'] for r in objects})
31
+ for oid in object_ids:
32
+ lookup={int(r['timestamp[ns]']):r for r in objects if r['object_uid']==oid};poses=np.full((len(frames),4,4),np.nan,np.float32);flags=np.zeros(len(frames),bool)
33
+ for i,frame in enumerate(frames):
34
+ if frame['timecode_ns'] in lookup:poses[i]=Tcws[i]@csv_transform(lookup[frame['timecode_ns']]);flags[i]=True
35
+ tensor(p/'annotation/object'/oid/'pose.pt',poses);tensor(p/'annotation/object'/oid/'valid_flag.pt',flags)
36
+ m['object']={'pose':'T_camera_from_object','unit':'m','mesh_status':'not downloaded','object_ids':object_ids};save(p/'metainfo.json',m)
37
+ save(base/'doc/mano_validation.json',{'test':'camera-space vertices equal transformed world-space vertices','max_vertex_error_m':max(errors),'passed':True,'limitation':'algebraic transform check; no independent fisheye reprojection evaluation','left_shapedirs_fix':bool(fixed)})
38
+ print('HOT3D normalized',motion.shape,'max transform error',max(errors))
39
+ if __name__=='__main__':main()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/pilot_mano.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local licensed MANO model dependency; never copies models into shared outputs."""
2
+ from pilot_build import *
3
+ from types import SimpleNamespace
4
+ import smplx
5
+
6
+ class StoredState:
7
+ def __setstate__(self,state):self.__dict__.update(state)
8
+ class ModelReader(Restricted):
9
+ def find_class(self,module,name):
10
+ if (module,name) in [('chumpy.ch','Ch'),('chumpy.reordering','Select'),('scipy.sparse.csc','csc_matrix')]:return StoredState
11
+ if (module,name)==('__builtin__','set'):return set
12
+ return super().find_class(module,name)
13
+
14
+ def model_data(side):
15
+ p=WORK/'tmp/pilot-models'/f'MANO_{side.upper()}.pkl'
16
+ with p.open('rb') as f:d=ModelReader(f,encoding='latin1').load()
17
+ # Materialize only the two known serialized structures; execute no Chumpy code.
18
+ s=d['shapedirs']
19
+ if isinstance(s,StoredState):d['shapedirs']=s.a.x.reshape(-1)[s.idxs].reshape(s.preferred_shape)
20
+ sparse=d['J_regressor'];dense=np.zeros(sparse._shape)
21
+ for col in range(sparse._shape[1]):
22
+ a,z=sparse.indptr[col:col+2];dense[sparse.indices[a:z],col]=sparse.data[a:z]
23
+ d['J_regressor']=dense
24
+ assert d['shapedirs'].shape==(778,3,10) and dense.shape==(16,778)
25
+ return d
26
+
27
+ class Mano:
28
+ def __init__(self,side):
29
+ self.side=side
30
+ self.data=model_data(side)
31
+ self.layer=smplx.MANO(model_path=str(WORK/'tmp/pilot-models'),data_struct=SimpleNamespace(**self.data),is_rhand=side=='right',use_pca=False,flat_hand_mean=True)
32
+ def geometry(self,pose,betas,translation=None,keypoint_convention='freihand'):
33
+ pose=torch.as_tensor(np.asarray(pose).copy(),dtype=torch.float32).reshape(-1,48);betas=torch.as_tensor(np.asarray(betas).copy(),dtype=torch.float32).reshape(-1,10)
34
+ with torch.no_grad():o=self.layer(global_orient=pose[:,:3],hand_pose=pose[:,3:],betas=betas)
35
+ v=o.vertices.numpy();j=o.joints.numpy()[:,:16]
36
+ if translation is not None:
37
+ t=np.asarray(translation).reshape(-1,1,3);v=v+t;j=j+t
38
+ # Standard wrist + thumb,index,middle,ring,pinky proximal-to-distal order.
39
+ coords=[]
40
+ for k in [0,13,14,15,1,2,3,4,5,6,10,11,12,7,8,9]:coords.append(j[:,k])
41
+ out=np.stack([j[:,0],j[:,13],j[:,14],j[:,15],v[:,744],j[:,1],j[:,2],j[:,3],v[:,320],j[:,4],j[:,5],j[:,6],v[:,443],j[:,10],j[:,11],j[:,12],v[:,555],j[:,7],j[:,8],j[:,9],v[:,672]],axis=1)
42
+ if keypoint_convention=='manopth':out[:,[4,8,12,16,20]]=v[:,[745,317,444 if self.side=='right' else 445,556,673]]
43
+ return v,out,j
44
+
45
+ def freihand_normalize():
46
+ base=ROOT/'FreiHAND/pilot-v0';model=Mano('right');reports=[]
47
+ for meta_file in sorted((base/'data').rglob('metainfo.json')):
48
+ p=meta_file.parent;m=load(meta_file);theta=torch.load(p/'annotation/mano/source_theta.pt',weights_only=True).numpy().reshape(1,61)
49
+ K=torch.load(p/'camera/intrinsic.pt',weights_only=True).numpy();focal=(K[0,0]+K[1,1])/2
50
+ root=np.r_[(theta[0,58:60]-K[:2,2]),focal]/theta[0,60]
51
+ pose=theta[:,:48].copy();pose[:,3:]+=model.data['hands_mean']
52
+ _,_,j=model.geometry(pose,theta[:,48:58]);translation=root-j[0,4]
53
+ motion=np.full((1,2,61),np.nan,np.float32);motion[0,1]=np.r_[pose[0],theta[0,48:58],translation]
54
+ tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',[[False,True]])
55
+ _,keypoints,_=model.geometry(pose,theta[:,48:58],translation)
56
+ assert np.allclose(keypoints[0,9],root,atol=1e-6)
57
+ m['mano']={'layout':['pose_axis_angle48','betas10','translation3'],'slots':['left','right'],'coordinate_frame':'camera','translation_unit':'m','flat_hand_mean':True,'model_version':'MANO v1.2','conversion':'source non-flat mean added to finger pose; official orthographic root recovery minus posed MANO joint 4 (21-joint index9)','valid_flag':'right-hand source annotation available; left not supplied'}
58
+ m['missing_modalities'].pop('normalized_mano',None);save(meta_file,m)
59
+ reports.append({'path':str(p.relative_to(base)),'root_recovery_error_m':float(np.linalg.norm(keypoints[0,9]-root))})
60
+ save(base/'doc/mano_validation.json',{'status':'passed_algebraic_root_check','model_sha256':sha(WORK/'tmp/pilot-models/MANO_RIGHT.pkl'),'samples':reports,'limit':'No independent 3D ground truth currently in input; algebraic check does not prove fit accuracy.'})
61
+ print('FreiHAND normalized',len(reports))
62
+
63
+ def validate_mano(name):
64
+ base=ROOT/name/'pilot-v0';models=[Mano('left'),Mano('right')];summaries=[]
65
+ for mp in (base/'data').rglob('metainfo.json'):
66
+ p=mp.parent;motionp=p/'annotation/mano/motion.pt'
67
+ if not motionp.exists():continue
68
+ a=torch.load(motionp,weights_only=True).numpy();valid=torch.load(p/'annotation/mano/valid_flag.pt',weights_only=True).numpy();K=torch.load(p/'camera/intrinsic.pt',weights_only=True).numpy();pred=np.full((len(a),2,21,3),np.nan,np.float32)
69
+ for side,model in enumerate(models):
70
+ ix=np.flatnonzero(valid[:,side])
71
+ if len(ix):_,pred[ix,side],_=model.geometry(a[ix,side,:48],a[ix,side,48:58],a[ix,side,58:],keypoint_convention='manopth')
72
+ tensor(p/'annotation/mano/derived_keypoints.pt',pred)
73
+ uv=pred@K.T;uv=uv[...,:2]/uv[...,2:]
74
+ row={'sequence':str(p.relative_to(base)),'keypoint_convention':'official manopth, including handedness-specific fingertip vertices','finite_valid_geometry':bool(np.isfinite(pred[valid]).all())}
75
+ target=p/('annotation/keypoints/xyz.pt' if name=='H2O' else 'annotation/keypoints/uv.pt')
76
+ if target.exists():
77
+ gt=torch.load(target,weights_only=True).numpy();err=np.linalg.norm((pred if name=='H2O' else uv)-gt,axis=-1);good=np.isfinite(err)&valid[:,:,None]
78
+ row['mean_error']=float(err[good].mean());row['max_error']=float(err[good].max());row['unit']='m' if name=='H2O' else 'pixels'
79
+ summaries.append(row)
80
+ meta=load(p/'metainfo.json');meta['mano']['geometry_validation']='measured against source keypoints; see doc/mano_validation.json';meta['mano']['model_version']='MANO v1.2'
81
+ meta['mano']['derived_keypoints_convention']='official manopth 21 joints, including side-specific fingertip vertices'
82
+ save(p/'metainfo.json',meta)
83
+ save(base/'doc/mano_validation.json',{'status':'measured_not_auto_accepted','samples':summaries,'model_sha256':{s:sha(WORK/'tmp/pilot-models'/f'MANO_{s.upper()}.pkl') for s in ['left','right']}})
84
+ print(name,summaries)
85
+
86
+ if __name__=='__main__':
87
+ freihand_normalize();validate_mano('H2O');validate_mano('HOI4D')
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/preprocess_fresh_full.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authorized ARCTIC/HOT3D production queue. One heavy converter, immutable raw.
2
+
3
+ Checkpoints and logs live under dataset/tmp; distributable validation lives in doc.
4
+ No upload or raw deletion. All output is independently checked before completion.
5
+ """
6
+ from fresh_sequence_common import *
7
+ from convert_fresh_sequence_pilots import arctic,hot3d,verify_hot3d_frame_order_and_metadata
8
+ from review_fresh_sequence_pilots import validate_view,arr
9
+ from apply_hot3d_qa import apply_qa
10
+ from diagnose_arctic_review import official_object
11
+ from datetime import datetime
12
+ import os,ctypes,msvcrt,traceback,html,random
13
+ import fresh_sequence_common as common
14
+ from accelerated_media import POLICY as MEDIA_POLICY,revalidate as revalidate_media
15
+
16
+ JOB='full-preprocess-v1.0'
17
+ CONTROL=WORK/'tmp'/JOB
18
+ RESERVE=400_000_000_000
19
+ SCRIPT=Path(__file__).resolve()
20
+ TEST_IDS={'P0004','P0005','P0006','P0008','P0016','P0020'}
21
+ torch.set_num_threads(4)
22
+
23
+ def now():return datetime.now().astimezone().isoformat()
24
+
25
+ def atomic(p,value):
26
+ p.parent.mkdir(parents=True,exist_ok=True);q=p.with_name(p.name+'.writing')
27
+ q.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8');os.replace(q,p)
28
+
29
+ def temporary(ds):return DATA_ROOT/ds/'tmp'/JOB
30
+
31
+ PRODUCTION_SCRIPTS=sorted(p.name for p in SCRIPT.parent.glob('*.py'))
32
+
33
+ def code_manifest():
34
+ return [{'path':'script/internal/'+f,'sha256':digest(SCRIPT.parent/f)} for f in PRODUCTION_SCRIPTS]
35
+
36
+ def verify_completed(ds,row,source):
37
+ root=DATA_ROOT/ds/RELEASE;record=temporary(ds)/'completed'/f'{row["sequence_id"]}.json';done=load(record)
38
+ migration_file=temporary(ds)/'acceleration-migrations'/f'{row["sequence_id"]}.json'
39
+ migration=load(migration_file) if migration_file.exists() else None
40
+ migration_matches=bool(migration and migration['checkpoint_sha256']==digest(record) and migration['new_scripts']==code_manifest() and migration['passed'] and migration['source']==source)
41
+ assert done['source']==source or migration_matches,'Completed source identity changed without verified migration'
42
+ if done.get('scripts')!=code_manifest():
43
+ assert migration_matches,'Code changed without a matching successful explicit revalidation'
44
+ verified={f['path']:f for f in migration['verified_files']} if migration_matches else {}
45
+ for f in done['files']:
46
+ path=root/f['path'];stat=path.stat();assert stat.st_size==f['size'],path
47
+ cached=verified.get(f['path'])
48
+ if not cached or cached['mtime_ns']!=stat.st_mtime_ns or cached['sha256']!=f['sha256']:
49
+ assert digest(path)==f['sha256'],path
50
+ return done
51
+
52
+ def migrate_completed(ds):
53
+ """Revalidate existing outputs once; preserve historical code and full-pixel proof."""
54
+ rows={r['sequence_id']:r for r in load(CONTROL/'plan.json')['datasets'][ds]['sequences']};records=inputs(ds)
55
+ for checkpoint in sorted((temporary(ds)/'completed').glob('*.json')):
56
+ done=load(checkpoint);row=rows[done['sequence_id']];source_files=list(row['inputs'])
57
+ if ds=='HOT3D':source_files+=sorted(rel for rel in records if rel.startswith('assets/'))
58
+ source=[check_input(ds,rel,records) for rel in source_files]
59
+ # Older smoke records did not yet list assets; validate their recorded inputs
60
+ # and add the verified complete dependency list to this migration record.
61
+ by_path={x['file']:x for x in source};assert all(by_path[x['file']]==x for x in done['source'])
62
+ legacy=load(CONTROL/'acceleration/legacy-script-manifest.json')['files']
63
+ assert done.get('scripts') in [None,legacy,code_manifest()],'Unknown historical code revision'
64
+ views=[]
65
+ for camera in row['cameras']:
66
+ _,_,report=validate_view(DATA_ROOT/ds/RELEASE/'data'/row['sequence_id']/camera);views.append(report)
67
+ verified=[];root=DATA_ROOT/ds/RELEASE
68
+ for file in done['files']:
69
+ path=root/file['path'];stat=path.stat();assert stat.st_size==file['size'] and digest(path)==file['sha256'],path
70
+ verified.append(dict(file,mtime_ns=stat.st_mtime_ns))
71
+ result={'passed':True,'dataset':ds,'sequence':row['sequence'],'checked_at':now(),'checkpoint_sha256':digest(checkpoint),'new_scripts':code_manifest(),'source':source,'verified_files':verified,'view_checks':views,'numerical_proof':'Every historical output byte/digest rechecked and current schema/validity validators rerun; unchanged source geometry proofs retained; no relabelling or tensor conversion','media_proof':'Historical complete JPEG and RGB equality proof retained for byte-identical files'}
72
+ atomic(temporary(ds)/'acceleration-migrations'/checkpoint.name,result)
73
+ atomic(root/'doc/validation/full/acceleration-revalidation'/checkpoint.name,result)
74
+ print('MIGRATED_VERIFIED',ds,row['sequence_id'],len(verified),flush=True)
75
+
76
+ def snapshot_scripts(ds):
77
+ root=DATA_ROOT/ds/RELEASE
78
+ target=root/'script/internal';target.mkdir(parents=True,exist_ok=True)
79
+ for f in PRODUCTION_SCRIPTS:
80
+ src=SCRIPT.parent/f;dst=target/f
81
+ if src.resolve()!=dst.resolve():shutil.copyfile(src,dst)
82
+ atomic(root/'doc/validation/full/script-manifest.json',{'created_at':now(),'scope':'Current organized production implementation under script/internal; earlier manifests retain historical paths and hashes','files':code_manifest()})
83
+
84
+ def inputs(ds):
85
+ base=DATA_ROOT/ds
86
+ name='archive_checksums.json' if ds=='ARCTIC' else 'file_checksums.json'
87
+ return load(base/'raw/doc'/name)
88
+
89
+ def check_input(ds,rel,records):
90
+ p=DATA_ROOT/ds/'raw/data'/rel;r=records[rel];st=p.stat()
91
+ assert st.st_size==r['size'],f'Raw size changed: {p}'
92
+ assert r.get('official_sha256_match',r.get('official_digest_match',False))
93
+ if st.st_mtime_ns!=r['mtime_ns']:
94
+ assert digest(p)==r['sha256'],f'Raw digest changed: {p}'
95
+ if p.suffix=='.zip':
96
+ with zipfile.ZipFile(p) as z:assert z.testzip() is None
97
+ return {'file':'raw/data/'+rel,'size':st.st_size,'sha256':r['sha256'],'download_checksum_and_crc_record_reused':st.st_mtime_ns==r['mtime_ns']}
98
+
99
+ def plan():
100
+ CONTROL.mkdir(parents=True,exist_ok=True);out={'created_at':now(),'order':['ARCTIC','HOT3D'],'datasets':{},'reserve_bytes':RESERVE}
101
+ for ds in out['order']:
102
+ base=DATA_ROOT/ds;records=inputs(ds)
103
+ for rel in records:check_input(ds,rel,records)
104
+ rows=[];auxiliary=[]
105
+ if ds=='ARCTIC':
106
+ with zipfile.ZipFile(base/'raw/data/splits_json.zip') as z:splits=json.loads(z.read('splits_json/protocol_p1.json'))
107
+ for p in sorted((base/'raw/data/images_zips').rglob('*.zip')):
108
+ seq=p.relative_to(base/'raw/data/images_zips').with_suffix('').as_posix()
109
+ if '/' not in seq:
110
+ assert seq=='backgrounds',seq
111
+ auxiliary.append({'file':'raw/data/images_zips/backgrounds.zip','handling':'retain original archive in raw; background reference photographs are not hand-object capture sequences'})
112
+ continue
113
+ with zipfile.ZipFile(p) as z:
114
+ im=[i for i in z.infolist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',i.filename)]
115
+ extra=[i.filename for i in z.infolist() if i.filename.endswith('.jpg') and not re.fullmatch(r'[0-8]/[0-9]+\.jpg',i.filename)]
116
+ assert all(n.startswith('__MACOSX/') or Path(n).name.startswith('._') for n in extra),(p,extra[:5])
117
+ cams=sorted({i.filename.split('/')[0] for i in im},key=int)
118
+ counts={c:sum(i.filename.startswith(c+'/') for i in im) for c in cams}
119
+ b=sum(i.file_size for i in im)
120
+ assert cams,(seq,counts)
121
+ rows.append({'sequence':seq,'sequence_id':seq.replace('/','_'),'object':seq.split('/')[1].split('_')[0],
122
+ 'cameras':cams,'frames_per_camera':counts,'jpeg_bytes':b,'split':next((k for k,v in splits.items() if seq in v),'unknown'),
123
+ 'inputs':['raw_seqs.zip','meta.zip','splits_json.zip','images_zips/'+seq+'.zip']})
124
+ budget=sum(r['jpeg_bytes'] for r in rows)+160_000_000_000
125
+ else:
126
+ for p in sorted((base/'raw/data/Aria').iterdir()):
127
+ if not p.is_dir():continue
128
+ gt=next(p.glob('*ground_truth.zip'));hz=next(p.glob('*hand_data.zip'));vrs=next(p.glob('*.vrs'))
129
+ with zipfile.ZipFile(gt) as z:
130
+ m=json.loads(z.read('metadata.json'));cams=json.loads(z.read('camera_models.json'))
131
+ assert m['headset']=='Aria'
132
+ hasgt=m['have_hand_object_pose_gt'];split='test' if m['participant_id'] in TEST_IDS else 'train';assert hasgt==(split=='train')
133
+ if hasgt:assert 'masks/mask_qa_pass.csv' in z.namelist()
134
+ with zipfile.ZipFile(hz) as z:mano_bytes=z.getinfo('mano_hand_pose_trajectory.jsonl').file_size
135
+ assert hasgt or mano_bytes==0
136
+ rows.append({'sequence':p.name,'sequence_id':p.name,'cameras':[c['stream_id'] for c in cams],'split':split,
137
+ 'source_gt_available':hasgt,'vrs_bytes':vrs.stat().st_size,'inputs':[q.relative_to(base/'raw/data').as_posix() for q in [gt,hz,vrs]]})
138
+ # Includes persistent extracted JPEGs, current media spool, meshes, tensors and reports.
139
+ budget=sum(r['vrs_bytes'] for r in rows)*3+150_000_000_000
140
+ assert len(rows)==(339 if ds=='ARCTIC' else 198)
141
+ out['datasets'][ds]={'sequences':rows,'count':len(rows),'views':sum(len(r['cameras']) for r in rows),'additional_budget_bytes':budget,'raw_files_verified':len(records),'auxiliary_raw_only':auxiliary}
142
+ print('PLAN',ds,len(rows),out['datasets'][ds]['views'],budget,flush=True)
143
+ out['free_bytes_at_plan']=shutil.disk_usage(DATA_ROOT).free
144
+ out['additional_peak_budget_bytes']=sum(v['additional_budget_bytes'] for v in out['datasets'].values())
145
+ assert out['free_bytes_at_plan']-out['additional_peak_budget_bytes']>=RESERVE,out
146
+ atomic(CONTROL/'plan.json',out)
147
+ return out
148
+
149
+ def approve():
150
+ p=load(CONTROL/'plan.json');confirmation={'confirmed_at':now(),'user_statement':'HOT3D和ARCTIC我都确认了,可以开始做预处理了。',
151
+ 'scope':'Reviewed pilots accepted; full preprocessing authorized for ARCTIC and HOT3D Aria only',
152
+ 'full_preprocessing_authorized':True,'full_output_review':'pending','upload_authorized':False,'raw_retention':True}
153
+ atomic(CONTROL/'authorization.json',confirmation)
154
+ state=load(WORK/'tmp/dataset-work-state.json')
155
+ for ds in p['order']:
156
+ root=DATA_ROOT/ds/RELEASE;doc=root/'doc/validation'
157
+ atomic(doc/'pilot-human-confirmation.json',confirmation)
158
+ for rp in [doc/'report.json',*sorted((doc/'objects').glob('*/report.json')),*([doc/'objects/report.json'] if (doc/'objects/report.json').exists() else [])]:
159
+ r=load(rp);r.update(human_review='approved',full_preprocessing_authorized=True,upload_authorized=False,pilot_confirmation=confirmation)
160
+ atomic(rp,r)
161
+ for page in [doc/'index.html',*sorted((doc/'objects').rglob('index.html'))]:
162
+ if not page.exists():continue
163
+ s=page.read_text(encoding='utf-8')
164
+ s=s.replace('人工确认待完成','试点人工确认已通过;全量产物待单独验收').replace('用户人工确认待完成','用户试点确认已通过').replace('用户确认前不全量处理','用户已确认试点,允许全量预处理')
165
+ if 'id="production-authorization"' not in s:
166
+ s=s.replace('<header>','<header><p id="production-authorization" style="color:#176b3a"><strong>用户已确认本页试点,授权全量预处理。</strong> 全量完成后另行随机抽查;尚未授权上传。</p>',1)
167
+ page.write_text(s,encoding='utf-8')
168
+ if (doc/'objects/artifact-manifest.json').exists():
169
+ mp=doc/'objects/artifact-manifest.json';a=load(mp)
170
+ for f in a['files']:
171
+ file=mp.parent/f['path'];f.update(size=file.stat().st_size,sha256=digest(file))
172
+ atomic(mp,a)
173
+ for meta in (root/'data').glob('*/*/metainfo.json'):
174
+ m=load(meta);m['pilot_human_review']='approved';m['full_preprocessing_authorized']=True
175
+ if 'acceptance' in m:m['acceptance'].update(status='pilot_user_approved',training_release_approved=False,reason='Pilot confirmed; full outputs and release still require separate review')
176
+ atomic(meta,m)
177
+ state['active'][ds].update(stage='full_preprocessing_queued',human_sample_review='approved',full_preprocessing_authorized=True,upload_authorized=False,
178
+ production_plan=str(CONTROL/'plan.json'),full_sequence_count=p['datasets'][ds]['count'],full_view_count=p['datasets'][ds]['views'])
179
+ atomic(doc/'status.json',{'stage':'full_preprocessing_queued','pilot_review':'approved','full_output_review':'pending','upload_authorized':False})
180
+ docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
181
+ atomic(docprod/'plan.json',p['datasets'][ds])
182
+ (docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
183
+ snapshot_scripts(ds)
184
+ atomic(WORK/'tmp/dataset-work-state.json',state)
185
+
186
+ def official_arctic_check(row,views):
187
+ base=DATA_ROOT/'ARCTIC';seq=row['sequence'];oid=row['object'];sid=seq.split('/')[0]
188
+ if row['split']=='test':
189
+ with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:
190
+ assert all(f'raw_seqs/{seq}.{x}.npy' not in z.namelist() for x in ['mano','object','egocam.dist'])
191
+ for p in views:
192
+ m=load(p/'metainfo.json');assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
193
+ if p.name=='0':assert 'intrinsic' not in m['components'] and 'extrinsic' not in m['components'] and m['camera']['schema_id'] is None
194
+ return {'passed':True,'test':'official_held_out_test_ground_truth_omitted; static_mesh_metres_and_part_ids_checked_per_view','source_gt_available':False}
195
+ with zipfile.ZipFile(base/'raw/data/meta.zip') as z:
196
+ pre=f'meta/object_vtemplates/{oid}/';verts=np.array([[float(x) for x in s.split()[1:4]] for s in z.read(pre+'mesh.obj').decode().splitlines() if s.startswith('v ')])/1000
197
+ parts=np.asarray(json.loads(z.read(pre+'parts.json')),np.int64);params=json.loads(z.read(pre+'object_params.json'));offset=json.loads(z.read('meta/misc.json'))[sid]['ioi_offset']
198
+ with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'))
199
+ world=[];kp=[]
200
+ for start in range(0,len(objects),32):
201
+ v,k=official_object(objects[start:start+32],verts,parts,params,oid);world.append(v);kp.append(k)
202
+ world=np.concatenate(world);kp=np.concatenate(kp);worst=0.;checked=0
203
+ for p in views:
204
+ frames=[json.loads(l) for l in (p/'camera/frames.jsonl').read_text().splitlines()];ix=np.array([int(f['source_frame_id'])-offset for f in frames]);op=p/'annotation/object'/oid
205
+ E=arr(p/'camera/extrinsic.pt');P=arr(op/'pose.pt');top=arr(op/'parts/top/pose.pt');valid=arr(op/'pose_valid.pt');ids=arr(op/'vertex_part_ids.pt');points=arr(op/'keypoints/xyz.pt')
206
+ assert np.array_equal(ids,1-parts)
207
+ for i in np.flatnonzero(valid):
208
+ actual=verts@P[i,:3,:3].T+P[i,:3,3];sel=ids==1;actual[sel]=verts[sel]@top[i,:3,:3].T+top[i,:3,3]
209
+ expected=world[ix[i]]@E[i,:3,:3].T+E[i,:3,3];expected_kp=kp[ix[i]]@E[i,:3,:3].T+E[i,:3,3]
210
+ worst=max(worst,float(np.linalg.norm(actual-expected,axis=-1).max()),float(np.linalg.norm(points[i]-expected_kp,axis=-1).max()));checked+=1
211
+ assert worst<2e-5,(seq,worst)
212
+ return {'test':'all_valid_frames_all_vertices_and_keypoints_vs_pinned_official_ObjectTensors','passed':True,'camera_frames':checked,'vertices_per_frame':len(verts),'max_error_m':worst}
213
+
214
+ def worker(ds,seq):
215
+ plan=load(CONTROL/'plan.json');row=next(r for r in plan['datasets'][ds]['sequences'] if r['sequence']==seq)
216
+ assert load(CONTROL/'authorization.json')['full_preprocessing_authorized']
217
+ base=DATA_ROOT/ds;root=base/RELEASE;tmp=temporary(ds);result=tmp/'completed'/f'{row["sequence_id"]}.json';records=inputs(ds)
218
+ source_files=list(row['inputs'])
219
+ if ds=='HOT3D':source_files+=sorted(rel for rel in records if rel.startswith('assets/'))
220
+ source=[check_input(ds,rel,records) for rel in source_files]
221
+ if result.exists():
222
+ verify_completed(ds,row,source)
223
+ print('VERIFIED_RESUME',ds,seq,flush=True);return
224
+ assert shutil.disk_usage(base).free>RESERVE+15_000_000_000,'Disk reserve reached'
225
+ reused={c for c in row['cameras'] if (root/'data'/row['sequence_id']/c/'metainfo.json').exists() and load(root/'data'/row['sequence_id']/c/'metainfo.json').get('pilot_complete')}
226
+ config=load(CONTROL/'acceleration-config.json');assert config['media_policy']==MEDIA_POLICY
227
+ conversion_start=time.perf_counter()
228
+ media_workers=min(config['workers_by_dataset'][ds],len(row['cameras']))
229
+ print('ACCELERATED_MEDIA',ds,seq,media_workers,MEDIA_POLICY,flush=True)
230
+ with common.media_pipeline(media_workers):
231
+ if ds=='ARCTIC':arctic(seq,initialize=False)
232
+ else:hot3d(seq,initialize=False)
233
+ conversion_seconds=time.perf_counter()-conversion_start
234
+ if ds=='HOT3D':
235
+ verify_hot3d_frame_order_and_metadata(seq)
236
+ if row['source_gt_available']:apply_qa(seq,publish=False)
237
+ views=[root/'data'/row['sequence_id']/cam for cam in row['cameras']]
238
+ results=[]
239
+ for p in views:
240
+ m,frames,r=validate_view(p);m.update(pilot=False,production_complete=True,pilot_human_review='approved',full_output_human_review='pending',upload_authorized=False)
241
+ if p.name in reused:
242
+ r['reused_media_revalidation']=revalidate_media(p)
243
+ if ds=='HOT3D' and not row['source_gt_available']:
244
+ assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
245
+ atomic(p/'metainfo.json',m);results.append(r)
246
+ independent=official_arctic_check(row,views) if ds=='ARCTIC' else {'passed':True,'test':'all_frame_camera_MANO_geometry_PCA_and_source_QA_per_view' if row['source_gt_available'] else 'all_frame_media_camera_geometry_and_omitted_pose_components','source_gt_available':row['source_gt_available']}
247
+ files=[]
248
+ for p in sorted((root/'data'/row['sequence_id']).rglob('*')):
249
+ if p.is_file():files.append({'path':p.relative_to(root).as_posix(),'size':p.stat().st_size,'sha256':digest(p)})
250
+ done={'dataset':ds,'sequence':seq,'sequence_id':row['sequence_id'],'completed_at':now(),'source':source,'scripts':code_manifest(),'views':results,'independent_geometry':independent,
251
+ 'files':files,'bytes':sum(f['size'] for f in files),'frames':sum(v['frames'] for v in results),'processing':{'media_policy':MEDIA_POLICY,'media_workers':media_workers,'conversion_seconds':conversion_seconds,'total_seconds':time.perf_counter()-conversion_start},'full_output_human_review':'pending','upload_authorized':False}
252
+ atomic(root/'doc/validation/full/sequences'/f'{row["sequence_id"]}.json',done);atomic(result,done)
253
+ print('SEQUENCE_COMPLETE',ds,seq,done['frames'],done['bytes'],flush=True)
254
+
255
+ def random_review(ds,rows):
256
+ from render_full_sequence_review import render_view,asset_preview
257
+ doc=DATA_ROOT/ds/RELEASE/'doc/validation/full_random';doc.mkdir(parents=True,exist_ok=True);rng=random.Random(20260920);selected=[]
258
+ if ds=='ARCTIC':
259
+ for oid in sorted({r['object'] for r in rows}):
260
+ group=[r for r in rows if r['object']==oid and r['split']!='test'];r=rng.choice(group);selected.append((r,rng.choice(r['cameras']),'labelled_object:'+oid,len(group)))
261
+ if not any(c=='0' for _,c,_,_ in selected):
262
+ group=[r for r in rows if '0' in r['cameras'] and r['split']!='test'];r=rng.choice(group);selected.append((r,'0','labelled_ego_camera_coverage',len(group)))
263
+ for split in ['train','val','test']:
264
+ if not any(r['split']==split for r,_,_,_ in selected):
265
+ group=[r for r in rows if r['split']==split];r=rng.choice(group);selected.append((r,'0' if split=='test' else rng.choice(r['cameras']),'split_coverage:'+split,len(group)))
266
+ else:
267
+ for split in ['train','test']:
268
+ group=[r for r in rows if r['split']==split];r=rng.choice(group)
269
+ for cam in r['cameras']:selected.append((r,cam,'split:'+split,len(group)))
270
+ sampling={'seed':20260920,'method':'ARCTIC: equal allocation by object among labelled train/val, uniform sequence then available camera; add labelled ego and missing train/val/test strata. Held-out test uses ego to show missing calibration/pose. HOT3D: equal allocation train/test, uniform whole sequence per split, every camera. Not frame-weighted; whole selected sequence is rendered.',
271
+ 'human_review':'pending','selections':[{'sequence_id':r['sequence_id'],'camera_id':c,'stratum':s,'stratum_sequences':n,'frame_indices':'all'} for r,c,s,n in selected]}
272
+ atomic(doc/'sampling.json',sampling);cards=[];results=[];assets={}
273
+ for row,cam,_,_ in selected:
274
+ st={'stage':'generating_full_random_review','dataset':ds,'sequence':row['sequence'],'camera_id':cam,'pid':os.getpid(),'time':now(),'completed_previews':len(results),'total_previews':len(selected)}
275
+ atomic(temporary(ds)/'status.json',st);atomic(CONTROL/'status.json',st)
276
+ p=DATA_ROOT/ds/RELEASE/'data'/row['sequence_id']/cam;sub=doc/row['sequence_id'];tmp=temporary(ds)/'random-review'/row['sequence_id'];qa=None
277
+ qfile=DATA_ROOT/ds/'tmp'/RUN/'qa'/f'{row["sequence_id"]}.json'
278
+ if ds=='HOT3D' and row['source_gt_available']:
279
+ if not qfile.exists():apply_qa(row['sequence'],publish=False)
280
+ qa=load(qfile)
281
+ pixel_proof=revalidate_media(p,full_pixels=True)
282
+ atomic(sub/'pixel-validation'/f'{cam}.json',pixel_proof)
283
+ result=render_view(p,ds,qa,doc=sub,tmp=tmp);result['whole_sequence_source_RGB_validation']=pixel_proof;results.append(result)
284
+ for op in (p/'annotation/object').glob('*'):
285
+ out=sub/'assets'/f'{op.name}.mp4'
286
+ if not out.exists():asset_preview(op,out)
287
+ assets[out.relative_to(doc).as_posix()]=row['sequence_id']+' / '+op.name
288
+ cards.append(f'<section><h2>{row["sequence_id"]} · camera {cam} · {result["frames"]}帧</h2><video controls preload="metadata" src="{row["sequence_id"]}/{result["video_ref"]}"></video></section>')
289
+ for ref,label in assets.items():cards.append(f'<section><h2>物体资产 · {label}</h2><video controls preload="metadata" src="{ref}"></video></section>')
290
+ atomic(doc/'report.json',{'dataset':ds,'sampling':sampling,'views':results,'asset_previews':assets,'human_review':'pending','upload_authorized':False})
291
+ (doc/'index.html').write_text('<!doctype html><meta charset="utf-8"><title>'+ds+' 全量随机抽查</title><style>body{font:16px/1.7 system-ui;max-width:1536px;margin:25px auto;background:#f3f5f9}section,header{background:white;padding:20px;margin:20px}video{width:100%}</style><header><h1>'+ds+' 全量随机抽查</h1><p>从全部完成产物读取,选中序列全部帧已渲染;用户人工确认待完成,不自动上传。</p><a href="sampling.json">随机种子与抽样范围/权重</a> · <a href="report.json">逐模态检查</a></header>'+''.join(cards),encoding='utf-8')
292
+ (doc/'REPORT.md').write_text('# 全量随机抽查\n\n[离线完整序列](index.html) · [抽样定义](sampling.json) · [模态检查](report.json)\n\n人工确认待完成。源缺失模态缺省,不以数值通过替代视觉质量确认。\n',encoding='utf-8')
293
+
294
+ def run():
295
+ assert not (CONTROL/'maintenance.json').exists() or not load(CONTROL/'maintenance.json')['active'],'Maintenance in progress; production start disabled'
296
+ CONTROL.mkdir(parents=True,exist_ok=True);guard=(CONTROL/'process.lock').open('a+b');guard.seek(0)
297
+ try:msvcrt.locking(guard.fileno(),msvcrt.LK_NBLCK,1)
298
+ except OSError:raise RuntimeError('Another production queue owns the lock')
299
+ assert load(CONTROL/'authorization.json')['full_preprocessing_authorized'];p=load(CONTROL/'plan.json')
300
+ power=ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
301
+ try:
302
+ scope=os.environ.get('HAND_DATASET_SCOPE')
303
+ for ds in [name for name in p['order'] if scope is None or name==scope]:
304
+ snapshot_scripts(ds)
305
+ rows=p['datasets'][ds]['sequences'];tmp=temporary(ds);tmp.mkdir(parents=True,exist_ok=True)
306
+ records=inputs(ds)
307
+ # Smaller full sequences first; sequence boundaries remain unchanged.
308
+ rows=sorted(rows,key=lambda r:r.get('jpeg_bytes',r.get('vrs_bytes',0)))
309
+ for n,row in enumerate(rows):
310
+ st={'stage':'converting','dataset':ds,'sequence':row['sequence'],'completed_sequences':n,'total_sequences':len(rows),'pid':os.getpid(),'time':now(),'media_policy':MEDIA_POLICY,'media_workers':load(CONTROL/'acceleration-config.json')['workers_by_dataset'][ds]}
311
+ atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
312
+ registry=load(WORK/'tmp/dataset-work-state.json');registry['active'][ds].update(stage='full_preprocessing',production_status=str(tmp/'status.json'),production_process_id=os.getpid());atomic(WORK/'tmp/dataset-work-state.json',registry)
313
+ assert shutil.disk_usage(DATA_ROOT).free>RESERVE+15_000_000_000,'Disk reserve reached'
314
+ checkpoint=tmp/'completed'/f'{row["sequence_id"]}.json'
315
+ if checkpoint.exists():
316
+ dependencies=list(row['inputs'])
317
+ if ds=='HOT3D':dependencies+=sorted(rel for rel in records if rel.startswith('assets/'))
318
+ verify_completed(ds,row,[check_input(ds,rel,records) for rel in dependencies])
319
+ print('VERIFIED_RESUME',ds,row['sequence'],flush=True)
320
+ continue
321
+ log=tmp/'logs'/f'{row["sequence_id"]}.log';log.parent.mkdir(parents=True,exist_ok=True)
322
+ with log.open('ab') as out:
323
+ child=subprocess.Popen([sys.executable,'-u',str(SCRIPT),'worker','--dataset',ds,'--sequence',row['sequence']],stdout=out,stderr=subprocess.STDOUT)
324
+ while child.poll() is None:
325
+ st.update(worker_pid=child.pid,time=now(),log=str(log));atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
326
+ if shutil.disk_usage(DATA_ROOT).free<RESERVE:child.terminate();child.wait();raise RuntimeError('Disk reserve reached; active sequence stopped, raw retained')
327
+ time.sleep(20)
328
+ if child.returncode:raise RuntimeError(f'Worker failed: {ds} {row["sequence"]}; see {log}')
329
+ print('QUEUE_PROGRESS',ds,n+1,len(rows),row['sequence'],flush=True)
330
+ st={'stage':'generating_full_random_review','dataset':ds,'pid':os.getpid(),'time':now(),'completed_sequences':len(rows),'total_sequences':len(rows)}
331
+ atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
332
+ state=load(WORK/'tmp/dataset-work-state.json');state['active'][ds].update(stage='generating_full_random_review');atomic(WORK/'tmp/dataset-work-state.json',state)
333
+ random_review(ds,rows)
334
+ state=load(WORK/'tmp/dataset-work-state.json');state['active'][ds].update(stage='full_random_awaiting_human_review',full_output_human_review='pending',upload_authorized=False);atomic(WORK/'tmp/dataset-work-state.json',state)
335
+ atomic(tmp/'status.json',{'stage':'full_random_awaiting_human_review','time':now(),'completed_sequences':len(rows),'total_sequences':len(rows),'report':str(DATA_ROOT/ds/RELEASE/'doc/validation/full_random/index.html')})
336
+ atomic(CONTROL/'status.json',{'stage':'all_preprocessing_complete_awaiting_full_random_review','time':now(),'upload_authorized':False})
337
+ except BaseException as e:
338
+ error={'stage':'failed_needs_attention','time':now(),'error':str(e),'dataset':locals().get('ds'),'sequence':locals().get('row',{}).get('sequence')}
339
+ atomic(CONTROL/'status.json',error)
340
+ if 'ds' in locals():atomic(temporary(ds)/'status.json',error)
341
+ raise
342
+ finally:ctypes.windll.kernel32.SetThreadExecutionState(0x80000000);guard.close()
343
+
344
+ if __name__=='__main__':
345
+ ap=argparse.ArgumentParser();ap.add_argument('mode',choices=['plan','approve','worker','run','migrate']);ap.add_argument('--dataset',choices=['ARCTIC','HOT3D']);ap.add_argument('--sequence');a=ap.parse_args()
346
+ if a.mode in ['worker','migrate']:
347
+ CONTROL.mkdir(parents=True,exist_ok=True)
348
+ with (CONTROL/'worker.lock').open('a+b') as lock:
349
+ lock.seek(0)
350
+ try:msvcrt.locking(lock.fileno(),msvcrt.LK_NBLCK,1)
351
+ except OSError:raise RuntimeError('A production worker is already active; refusing overlapping conversion')
352
+ if a.mode=='migrate':migrate_completed(a.dataset)
353
+ else:worker(a.dataset,a.sequence)
354
+ elif a.mode=='plan':plan()
355
+ elif a.mode=='approve':approve()
356
+ else:run()
ARCTIC/shared-v1.1/script/v1_0_snapshot/script/internal/render_full_sequence_review.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-frame, all-camera diagnostic videos read from actual shared tensors/media.
2
+
3
+ Preview MP4 is explicitly display-only; warehouse MKV packets remain untouched.
4
+ """
5
+ from fresh_sequence_common import *
6
+ from review_fresh_sequence_pilots import arr, validate_view, project_for_view
7
+ from datetime import datetime
8
+ import html
9
+
10
+ VIDEO_RUN='full-video-review-v2'
11
+ CELL=512
12
+ WIDTH=3*CELL
13
+ HEIGHT=800
14
+ COLORS=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
15
+
16
+ def text(im,txt,xy,color=(235,235,235),size=.5):cv2.putText(im,txt,xy,cv2.FONT_HERSHEY_SIMPLEX,size,color,1,cv2.LINE_AA)
17
+
18
+ def fast_edges(im,uv,edges,color):
19
+ xy=uv[edges];good=np.isfinite(xy).all((1,2)) & (np.max(np.nan_to_num(np.abs(xy),nan=CELL*20),axis=(1,2))<CELL*12)
20
+ xy=xy[good];xy=xy[np.linalg.norm(xy[:,0]-xy[:,1],axis=1)<CELL*.7]
21
+ if len(xy):cv2.polylines(im,np.rint(xy).astype(np.int32),False,color,1,cv2.LINE_AA)
22
+
23
+ def dots(im,uv,color,radius=2):
24
+ good=np.isfinite(uv).all(1)&(uv[:,0]>=0)&(uv[:,0]<im.shape[1])&(uv[:,1]>=0)&(uv[:,1]<im.shape[0])
25
+ xy=np.rint(uv[good]).astype(int);xy[:,0]=np.clip(xy[:,0],0,im.shape[1]-1);xy[:,1]=np.clip(xy[:,1],0,im.shape[0]-1)
26
+ for d in range(max(1,radius)):
27
+ im[np.clip(xy[:,1]+d,0,im.shape[0]-1),xy[:,0]]=color
28
+ im[xy[:,1],np.clip(xy[:,0]+d,0,im.shape[1]-1)]=color
29
+
30
+ def model_vertices(motion,valid,side,fix):
31
+ model=Mano(['left','right'][side])
32
+ if side==0 and fix:
33
+ model.data['shapedirs'][:,0]*=-1
34
+ with torch.no_grad():model.layer.shapedirs[:,0]*=-1
35
+ verts=np.full((len(motion),778,3),np.nan,np.float32);joints=np.full((len(motion),16,3),np.nan,np.float32)
36
+ ids=np.flatnonzero(valid[:,side])
37
+ for start in range(0,len(ids),64):
38
+ ix=ids[start:start+64];a=motion[ix,side];verts[ix],_,joints[ix]=model.geometry(a[:,:48],a[:,48:58],a[:,58:])
39
+ faces=np.asarray(model.layer.faces);edges=np.unique(np.sort(np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]),axis=1),axis=0)
40
+ return verts,joints,edges
41
+
42
+ def encoder(path,fps,log,size=(WIDTH,HEIGHT)):
43
+ path.parent.mkdir(parents=True,exist_ok=True)
44
+ return subprocess.Popen([str(FF),'-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{size[0]}x{size[1]}','-r',str(fps),'-i','pipe:0',
45
+ '-an','-c:v','libx264','-preset','veryfast','-crf','19','-pix_fmt','yuv420p','-threads','2','-bf','0','-g','60','-movflags','+faststart',str(path)],stdin=subprocess.PIPE,stderr=log)
46
+
47
+ def read_exact(pipe,n):
48
+ chunks=[];count=0
49
+ while count<n:
50
+ b=pipe.read(n-count)
51
+ if not b:break
52
+ chunks.append(b);count+=len(b)
53
+ return b''.join(chunks)
54
+
55
+ def trajectory_plot(E,width=265,height=145):
56
+ good=np.isfinite(E).all((1,2));xyz=np.full((len(E),3),np.nan)
57
+ xyz[good]=-(np.swapaxes(E[good,:3,:3],1,2)@E[good,:3,3,None])[:,:,0]
58
+ base=np.full((height,width,3),24,np.uint8);xy=xyz[:,[0,2]];valid=np.isfinite(xy).all(1)
59
+ if not valid.any():return base,np.zeros((len(E),2),int),xyz
60
+ lo=np.nanmin(xy,0);hi=np.nanmax(xy,0);span=np.maximum(hi-lo,.05);scale=min((width-24)/span[0],(height-35)/span[1]);pix=(xy-lo)*scale+12
61
+ pix[:,1]=height-12-pix[:,1];pixels=np.nan_to_num(pix).astype(int)
62
+ for i in range(1,len(E)):
63
+ if valid[i-1] and valid[i]:cv2.line(base,tuple(pixels[i-1]),tuple(pixels[i]),(110,110,110),1)
64
+ text(base,'camera world trajectory X/Z (m)',(7,15),size=.38)
65
+ return base,pixels,xyz
66
+
67
+ def object_specs(p,source):
68
+ result=[]
69
+ for k,op in enumerate(sorted((p/'annotation/object').glob('*'))):
70
+ if not (op/'pose.pt').exists():continue
71
+ om=load(op/'metainfo.json');rel=op.relative_to(p);mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
72
+ rawpose=arr(source/rel/'pose.pt');rawvalid=arr(source/rel/'pose_valid.pt');valid=arr(op/'pose_valid.pt')
73
+ spec={'id':om['object_id'],'name':om.get('category_name',om['object_id']),'color':COLORS[k%len(COLORS)],'P':rawpose,'rawvalid':rawvalid,'valid':valid,'op':op}
74
+ if 'vertex_part_ids_ref' in om:
75
+ xyz=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
76
+ part=arr(p/om['vertex_part_ids_ref']);idx=np.arange(0,len(xyz),max(1,len(xyz)//4500))
77
+ spec.update(vertices=xyz[idx],parts=part[idx],top=arr(source/rel/'parts/top/pose.pt'),edges=None,
78
+ keypoints=arr(source/rel/'keypoints/xyz.pt'),joint=arr(source/rel/'joint_state.pt')[:,0])
79
+ else:
80
+ edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//1100)]
81
+ unique,inv=np.unique(edges,return_inverse=True);spec.update(vertices=np.asarray(mesh.vertices)[unique],edges=inv.reshape(-1,2),parts=None)
82
+ spec['visibility']=arr(op/'visibility.pt') if (op/'visibility.pt').exists() else None
83
+ spec['raw_visibility']=arr(source/rel/'visibility.pt') if (source/rel/'visibility.pt').exists() else None
84
+ result.append(spec)
85
+ return result
86
+
87
+ def render_view(p,dataset,qa_data,doc=None,tmp=None,source=None,snapshot_indices=None):
88
+ m,frames,structural=validate_view(p);cam=m['camera_id'];T=m['num_frames'];root=DATA_ROOT/dataset/RELEASE
89
+ doc=doc or root/'doc/validation';tmp=tmp or DATA_ROOT/dataset/'tmp'/VIDEO_RUN;tmp.mkdir(parents=True,exist_ok=True)
90
+ if source is None:
91
+ source=p
92
+ for candidate in [DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/m['sequence_id']/cam,DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/cam]:
93
+ if (candidate/'snapshot.json').exists() and Path(load(candidate/'snapshot.json')['source_view']).resolve()==p.resolve():source=candidate;break
94
+ qa=np.array(qa_data[cam]['qa_pass'],bool) if dataset=='HOT3D' and qa_data and qa_data[cam].get('qa_pass') is not None else None
95
+ if 'mano' in m['components']:
96
+ motion=arr(source/'annotation/mano/motion.pt');present=arr(source/'annotation/mano/motion_valid.pt');valid=arr(p/'annotation/mano/motion_valid.pt')
97
+ else:motion=np.full((T,2,61),np.nan);present=np.zeros((T,2),bool);valid=present.copy()
98
+ visibility=arr(p/'annotation/mano/visibility.pt') if (p/'annotation/mano/visibility.pt').exists() else None
99
+ rawvis=arr(source/'annotation/mano/visibility.pt') if (source/'annotation/mano/visibility.pt').exists() else None
100
+ hands=[model_vertices(motion,present,s,m['components'].get('mano',{}).get('model_profile',{}).get('left_shapedirs_fix',False)) for s in range(2)]
101
+ objs=object_specs(p,source);K=arr(p/'camera/intrinsic.pt') if (p/'camera/intrinsic.pt').exists() else np.full((T,3,3),np.nan);D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None;E=arr(p/'camera/extrinsic.pt') if (p/'camera/extrinsic.pt').exists() else np.full((T,4,4),np.nan)
102
+ W,H=m['camera']['image_size'];scale0=min(CELL/W,CELL/H);w=int(W*scale0)//2*2;h=int(H*scale0)//2*2;scale=np.array([w/W,h/H])
103
+ fps=m['sampling']['source_fps'] or 30;path=doc/'videos'/f'{cam}-full.mp4';logpath=tmp/f'render-{cam}.log';log=logpath.open('wb')
104
+ dec=subprocess.Popen([str(FF),'-v','error','-threads','2','-noautorotate','-i',str(p/'observation/rgb.mkv'),'-vf',f'scale={w}:{h}','-pix_fmt','rgb24','-fps_mode','passthrough','-f','rawvideo','pipe:1'],stdout=subprocess.PIPE,stderr=log)
105
+ enc=encoder(path,fps,log);traj,tp,world=trajectory_plot(E);rendered=0;exposure=[]
106
+ snapshots=sorted(set(snapshot_indices or [0,1,26,27,179,180,T//4,T//2,3*T//4,T-1]))
107
+ timeline=np.zeros((12,WIDTH,3),np.uint8)
108
+ for x in range(WIDTH):timeline[:,x]=(40,135,65) if qa is not None and qa[min(T-1,x*T//WIDTH)] else ((170,42,50) if qa is not None else (75,80,95))
109
+ for i in range(T):
110
+ b=read_exact(dec.stdout,w*h*3);assert len(b)==w*h*3,(cam,i,'decoder ended early')
111
+ original=np.frombuffer(b,np.uint8).reshape(h,w,3).copy();raw=original.copy();usable=original.copy()
112
+ gray=cv2.cvtColor(cv2.resize(original,(96,96)),cv2.COLOR_RGB2GRAY)
113
+ exposure.append({'frame_index':i,'p95_luma':float(np.percentile(gray,95)),'median_luma':float(np.median(gray))})
114
+ params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
115
+ for side,(verts,joints,edges) in enumerate(hands):
116
+ if not present[i,side]:continue
117
+ uv=project_for_view(verts[i],m,params,scale);color=(0,235,255) if side==0 else (255,135,20)
118
+ fast_edges(raw,uv,edges,color)
119
+ if valid[i,side]:fast_edges(usable,uv,edges,color)
120
+ # White MANO joints are a diagnostic derivation, not a new keypoint component.
121
+ dots(raw,project_for_view(joints[i],m,params,scale),(255,255,255),2)
122
+ if valid[i,side]:dots(usable,project_for_view(joints[i],m,params,scale),(255,255,255),2)
123
+ for obj in objs:
124
+ if not obj['rawvalid'][i]:continue
125
+ P=obj['P'][i];xyz=obj['vertices']@P[:3,:3].T+P[:3,3]
126
+ if obj['parts'] is not None:
127
+ top=obj['top'][i];sel=obj['parts']==1;xyz[sel]=obj['vertices'][sel]@top[:3,:3].T+top[:3,3]
128
+ uv=project_for_view(xyz,m,params,scale)
129
+ for image,enabled in [(raw,True),(usable,obj['valid'][i])]:
130
+ if not enabled:continue
131
+ if obj['edges'] is not None:fast_edges(image,uv,obj['edges'],obj['color'])
132
+ else:
133
+ dots(image,uv[obj['parts']==0],(100,240,90));dots(image,uv[obj['parts']==1],(230,80,230))
134
+ dots(image,project_for_view(obj['keypoints'][i],m,params,scale),(255,255,255),3)
135
+ # Local object axes in metres make pose orientation visible.
136
+ axes=np.vstack([np.zeros(3),np.eye(3)*.045])@P[:3,:3].T+P[:3,3];auv=project_for_view(axes,m,params,scale)
137
+ for j,c in enumerate([(255,60,60),(60,255,60),(60,120,255)]):fast_edges(image,auv,np.array([[0,j+1]]),c)
138
+ canvas=np.full((HEIGHT,WIDTH,3),20,np.uint8)
139
+ for col,(im,label) in enumerate([(original,'SOURCE RGB'),(raw,'NATIVE LABEL DIAGNOSTIC'),(usable,'SHARED USABLE SUPERVISION')]):
140
+ canvas[40+(CELL-h)//2:40+(CELL-h)//2+h,col*CELL+(CELL-w)//2:col*CELL+(CELL-w)//2+w]=im
141
+ text(canvas,label,(col*CELL+12,25),size=.58)
142
+ status='NO OFFICIAL QA PROVIDED' if qa is None else ('OFFICIAL QA PASS' if qa[i] else 'OFFICIAL QA FAIL - NOT SUPERVISION')
143
+ if dataset=='ARCTIC' and i in m['components'].get('mano',{}).get('valid_policy',{}).get('local_excluded_frame_indices',[]):status='LOCAL REVIEW REJECT - NOT HAND SUPERVISION'
144
+ color=(235,195,65) if qa is None else ((80,240,110) if qa[i] else (255,90,90))
145
+ text(canvas,f'{dataset} {cam} index={i}/{T-1} source={frames[i]["source_frame_id"]} {status}',(12,578),color,.6)
146
+ text(canvas,f'MANO source L/R={int(present[i,0])}/{int(present[i,1])} shared valid L/R={int(valid[i,0])}/{int(valid[i,1])} (m/rad)',(12,603),size=.49)
147
+ def vals(a):return 'n/a' if a is None else ','.join('unknown' if not np.isfinite(x) else f'{100*x:.1f}%' for x in np.atleast_1d(a))
148
+ text(canvas,f'visibility native L/R: {vals(rawvis[i] if rawvis is not None else None)} usable: {vals(visibility[i] if visibility is not None else None)}',(12,626),size=.48)
149
+ text(canvas,f'camera={m["camera"]["model"]}; intrinsic '+np.array2string(K[i].ravel()[:5],precision=2),(12,649),size=.45)
150
+ text(canvas,'camera world position (m): '+np.array2string(world[i],precision=3),(12,672),size=.45)
151
+ clock=frames[i]['timestamp_ns'];text(canvas,f'timestamp_ns={clock} clock={frames[i]["clock_domain"]}',(12,695),size=.44)
152
+ text(canvas,f'preview FPS={fps}; '+('capture FPS unknown, playback only' if m['sampling']['source_fps'] is None else 'source capture time is stored separately'),(12,718),size=.44)
153
+ text(canvas,'cyan=left; orange=right; white=derived MANO joints / source object points',(12,741),size=.41)
154
+ text(canvas,'Projection shows hidden surfaces; it is NOT native segmentation.',(12,762),(180,180,180),.43)
155
+ for j,obj in enumerate(objs):
156
+ a=obj['raw_visibility'];v=obj['visibility'];s=f'{obj["name"]}: valid={int(obj["valid"][i])}'
157
+ if a is not None:s+=f' vis={vals(v[i])} (raw {vals(a[i])})'
158
+ if 'joint' in obj:s+=f' hinge={obj["joint"][i]:.3f}rad keypoints=32'
159
+ text(canvas,s,(660,603+j*24),obj['color'],.44)
160
+ tr=traj.copy()
161
+ if np.isfinite(world[i]).all():cv2.circle(tr,tuple(tp[i]),4,(255,220,70),-1)
162
+ canvas[610:755,WIDTH-277:WIDTH-12]=tr
163
+ canvas[-12:]=timeline;cursor=min(WIDTH-1,int(i*WIDTH/T));canvas[-12:,cursor:cursor+2]=255
164
+ enc.stdin.write(canvas.tobytes());rendered+=1
165
+ if i in snapshots:
166
+ snap=doc/'video_snapshots'/cam;snap.mkdir(parents=True,exist_ok=True);Image.fromarray(canvas).save(snap/f'{i:06d}.jpg',quality=92)
167
+ if i%200==0:print('VIDEO_FRAME',dataset,cam,i,T,flush=True)
168
+ assert not dec.stdout.read(1),'extra source frames';dec.stdout.close();assert dec.wait()==0
169
+ enc.stdin.close();assert enc.wait()==0;log.close();assert rendered==T
170
+ packets=framehash(['-i',str(path)],copy=True);assert len(packets)==T
171
+ result={'sequence_id':m['sequence_id'],'camera_id':cam,'frames':T,'rendered_frames':rendered,'video_ref':path.relative_to(doc).as_posix(),'video_sha256':digest(path),'preview_fps':fps,
172
+ 'preview_is_training_data':False,'preview_encoding':'H264 CRF19, scaled, display only; shared original MKV unchanged',
173
+ 'source_labels_from':'raw-derived diagnostic cache' if source!=p else 'shared unfiltered source-compatible labels',
174
+ 'all_source_and_shared_valid_masks_used':True,'structure_checks':structural,'mano_valid_counts':valid.sum(0).tolist(),
175
+ 'official_qa_pass_frames':int(qa.sum()) if qa is not None else None,'official_qa_fail_frames':int((~qa).sum()) if qa is not None else None,
176
+ 'exposure_diagnostics':{'method':'scaled shared decoded RGB to 96x96 gray; p95<35 flags a candidate only, does not modify valid','suspect_dark_frame_indices':[x['frame_index'] for x in exposure if x['p95_luma']<35]}}
177
+ save(tmp/f'{cam}-exposure.json',exposure)
178
+ save(tmp/f'{cam}-video-result.json',result);print('VIDEO_COMPLETE',dataset,cam,T,flush=True)
179
+ return result
180
+
181
+ def asset_preview(op,out):
182
+ """Textured point-splat turntable plus the source texture; diagnostic, not photoreal rendering."""
183
+ p=op.parents[2];m=load(op/'metainfo.json');meshpath=p/m['mesh_ref']
184
+ if (op/'assets/mesh_tex.obj').exists():meshpath=op/'assets/mesh_tex.obj'
185
+ mesh=trimesh.load(meshpath,process=False,force='mesh');xyz=np.asarray(mesh.vertices);idx=np.arange(0,len(xyz),max(1,len(xyz)//35000));xyz=xyz[idx]
186
+ texture=getattr(mesh.visual.material,'image',None) if hasattr(mesh.visual,'material') else None
187
+ texture_source=None
188
+ if meshpath.name=='mesh_tex.obj' and op.relative_to(DATA_ROOT).parts[0]=='ARCTIC':
189
+ # The loader can silently return a 2x2 default material. Resolve the
190
+ # official single-texture MTL explicitly instead of accepting that placeholder.
191
+ mtl=[r.split(maxsplit=1)[1] for r in meshpath.read_text().splitlines() if r.startswith('mtllib ')]
192
+ diffuse=[]
193
+ for name in mtl:
194
+ material=meshpath.parent/name
195
+ diffuse.extend(material.parent/r.split(maxsplit=1)[1] for r in material.read_text().splitlines() if r.startswith('map_Kd '))
196
+ diffuse=list(set(diffuse));assert len(diffuse)==1,(meshpath,diffuse)
197
+ assert diffuse[0].resolve().is_relative_to(meshpath.parent.resolve())
198
+ texture=Image.open(diffuse[0]).convert('RGB');assert min(texture.size)>2
199
+ texture_source={'file':diffuse[0].relative_to(p).as_posix(),'sha256':digest(diffuse[0]),'size':list(texture.size),'resolution_method':'explicit official MTL map_Kd; reject loader placeholder'}
200
+ if texture is not None and getattr(mesh.visual,'uv',None) is not None:
201
+ tex=np.asarray(texture.convert('RGB'));uv=np.asarray(mesh.visual.uv)[idx]
202
+ rgb=tex[np.clip(np.rint((1-uv[:,1])*(len(tex)-1)).astype(int),0,len(tex)-1),np.clip(np.rint(uv[:,0]*(tex.shape[1]-1)).astype(int),0,tex.shape[1]-1)]
203
+ else:rgb=np.broadcast_to([150,210,245],xyz.shape).astype(np.uint8)
204
+ extent=np.ptp(xyz,axis=0);xyz=xyz-(xyz.min(0)+xyz.max(0))/2;scale=300/max(np.linalg.norm(extent),.001)
205
+ logpath=DATA_ROOT/op.relative_to(DATA_ROOT).parts[0]/'tmp'/VIDEO_RUN/'assets.log'
206
+ logpath.parent.mkdir(parents=True,exist_ok=True)
207
+ out.parent.mkdir(parents=True,exist_ok=True)
208
+ with logpath.open('ab') as log:
209
+ enc=encoder(out,12,log,size=(800,480))
210
+ for i in range(72):
211
+ image=np.full((480,800,3),24,np.uint8);R=Rotation.from_euler('xy',[.35,i*2*np.pi/72]).as_matrix();v=xyz@R.T
212
+ order=np.argsort(v[:,2]);xy=np.rint(v[:,:2]*scale+[220,220]).astype(int)
213
+ good=(xy[:,0]>=0)&(xy[:,0]<430)&(xy[:,1]>=35)&(xy[:,1]<400);order=order[good[order]]
214
+ for dx,dy in [(0,0),(1,0),(0,1)]:image[np.clip(xy[order,1]+dy,0,479),np.clip(xy[order,0]+dx,0,429)]=rgb[order]
215
+ if texture is not None:
216
+ thumb=texture.convert('RGB');thumb.thumbnail((350,345));image[40:40+thumb.height,440:440+thumb.width]=np.asarray(thumb)
217
+ text(image,m.get('category_name',m['object_id']),(12,25),size=.65)
218
+ text(image,'TEXTURED 3D POINT PREVIEW',(12,420),size=.55);text(image,'SOURCE MATERIAL TEXTURE',(445,420),size=.5)
219
+ text(image,'OBJ extent (m): '+np.array2string(extent,precision=4),(12,450),size=.5);enc.stdin.write(image.tobytes())
220
+ enc.stdin.close();assert enc.wait()==0
221
+ assert len(framehash(['-i',str(out)],copy=True))==72
222
+ return {'object_id':m['object_id'],'video_ref':'assets/'+out.name,'frames':72,'texture_present':texture is not None,'texture_source':texture_source,'extent_m':extent.tolist(),'method':'diagnostic textured point turntable, not photoreal material rendering'}
223
+
224
+ def publish_review(dataset,results,assets):
225
+ root=DATA_ROOT/dataset/RELEASE;doc=root/'doc/validation'
226
+ scope=[('RGB','全部帧原图与逐帧码流/像素校验'),('相机内参/畸变','投影使用声明模型和全部参数;HUD显示相机模型'),('相机外参','全帧姿态、米制相机位置与世界XZ轨迹'),('MANO','逐帧网格线框、派生关节点、左右手valid'),('物体姿态/几何','逐帧轮廓、局部XYZ轴、物体ID'),('材质/纹理','每个物体的原纹理与完整旋转预览')]
227
+ scope+=([('部件/关节','底座/顶盖分别着色,逐帧关节角'),('物体关键点','源32个物体点逐帧叠加'),('visibility','原数据未提供,明确缺省')] if dataset=='ARCTIC' else [('visibility','原值0–1已修正,原生/可用比例同时显示'),('官方QA','完整红绿时间带;QA失败帧保留诊断、停用监督'),('部件/关节、独立物体关键点','本序列无该源模态,不虚构')])
228
+ scope+=[('深度/像素分割/接触','本次raw范围未提供,不以投影或帧筛选CSV冒充')]
229
+ table=''.join(f'<tr><td>{a}</td><td>{b}</td></tr>' for a,b in scope)
230
+ cards=''.join(f'<section><h2>Camera {r["camera_id"]} · {r["frames"]} 帧 · 有效MANO左右 {r["mano_valid_counts"]}</h2><video controls preload="metadata" src="{r["video_ref"]}"></video><p>全部{r["rendered_frames"]}帧已渲染,无码帧跳过。官方QA通过/未通过:{r["official_qa_pass_frames"]}/{r["official_qa_fail_frames"]}(null表示来源无此QA)。</p></section>' for r in results)
231
+ gallery=''.join(f'<section><h3>物体 {a["object_id"]}</h3><video controls loop preload="metadata" src="{a["video_ref"]}"></video><p>纹理点云旋转预览及原始材质图;此预览不证明完整PBR渲染等价。</p></section>' for a in assets)
232
+ known=('已修正转换器颠倒顶盖/底座编码的错误:原parts.json的0是顶盖、1是底座,共享层重新映射为0底座/1顶盖。9路相机前两帧均为源欠曝图,已排除对应几何监督;camera 6 index 270的手部偏移作为已知问题记录,按用户要求撤销单帧屏蔽,恢复原标注和valid。整套试点仍待验收。中栏显示源参数诊断,右栏按当前valid绘制。详见 <a href="ARCTIC_FINDINGS.md">问题与修复证据</a>、<a href="diagnosis/camera6-270-before-after.jpg">修复前后对照</a>。预览30fps仅用于播放,不代表真实采集帧率;没有源准确性QA。' if dataset=='ARCTIC' else '原始开头帧存在明显错位,官方QA为False;源头戴位姿开头27帧保持不变,帧号/时间/包顺序均未人为移动。中栏保留原始诊断投影,右栏只绘制当前valid监督。已修正visibility误除100。QA按相机整帧保守筛选,不能断言具体哪个实体错。')
233
+ page=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 完整视频审核 v2</title><style>body{{font:16px/1.7 system-ui;background:#edf1f7;color:#172136;max-width:1550px;margin:25px auto;padding:0 20px}}header,section{{background:white;padding:22px;border-radius:12px;margin-bottom:20px}}video{{width:100%;background:#151515}}h1{{margin:0}}.warn{{color:#a71d2b;font-weight:bold}}table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #ccd4df;padding:8px;text-align:left}}.assets{{display:grid;grid-template-columns:repeat(auto-fit,minmax(500px,1fr));gap:18px}}a{{color:#1567a3}}</style><header><h1>{dataset} · 完整序列审核 v2</h1><p class="warn">人工确认待完成。旧“抽帧投影通过”结论撤回,本页替代旧报告;尚未全量或发布。</p><p>视频三栏:原图 | 原始标注诊断 | 共享层有效监督。所有相机、所有帧都已渲染;青=左手,橙=右手,其他色=物体/部件,白点=MANO派生关节点或源物体关键点。投影不做遮挡剔除,也不是分割真值。</p><p>{known}</p><p>标注 valid=实际标注存在且数值合法,并通过适用官方QA及已明确登记的本地排除规则;可见性不代替valid,剩余帧不因此自动认定人工通过。诊断中被排除的参数不进入有效监督,raw保留。MP4经过缩放与展示编码,仅为doc预览,训练输入仍是无新增损失的shared MKV。</p><p><a href="REPORT.md">正式说明</a> · <a href="report.json">逐相机检查结果</a> · <a href="../RAW_TO_SHARED.md">字段映射</a> · <a href="../CONTRACT.md">更新后的valid定义</a></p><h2>逐模态检查覆盖</h2><table><tr><th>模态</th><th>检查/可视化方式</th></tr>{table}</table></header>{cards}<h2>物体资产检查</h2><div class="assets">{gallery}</div><script>document.querySelectorAll('video').forEach(v=>v.addEventListener('play',()=>document.querySelectorAll('video').forEach(o=>{{if(o!==v)o.pause()}})));</script></html>'''
234
+ (doc/'index.html').write_text(page,encoding='utf-8')
235
+ old=load(doc/'report.json');old.update(stage='full_video_review_awaiting_human',human_review='pending',review_revision='full-video-v2',
236
+ old_sample_projection_conclusion='withdrawn',full_video_views=results,asset_previews=assets,modality_coverage=[{'modality':a,'check':b} for a,b in scope],known_issues=known,
237
+ agent_visual_inspection={'status':'pending_new_full_video_review','not_equivalent_to_user_approval':True},created_at=datetime.now().astimezone().isoformat())
238
+ old.pop('views',None);old.pop('offline_artifact_check',None);save(doc/'report.json',old)
239
+ save(doc/'status.json',{'stage':'full_video_review_awaiting_human','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
240
+ rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | {r["rendered_frames"]} | {r["mano_valid_counts"]} | {r["official_qa_pass_frames"]} |' for r in results)
241
+ (doc/'REPORT.md').write_text(f'# {dataset} 完整序列审核 v2\n\n[离线完整视频](index.html) · [机器结果](report.json)\n\n人工确认待完成;旧抽帧投影通过结论撤回。{known}\n\n|相机|源帧数|渲染帧数|左右手有效标注帧数|官方QA通过帧数|\n|---|---:|---:|---|---:|\n{rows}\n\n## 逐模态覆盖\n\n'+''.join(f'- {a}:{b}。\n' for a,b in scope)+'\n完整视频表示每帧已渲染,并不等于每帧人工审核通过。被官方QA排除的源标注仅在诊断栏显示;不挪帧、不隐藏原始异常。所有有效性筛选、可见性与图像编码验收分开记录。源标注质量问题无法通过格式转换修好;通过valid屏蔽,并保留raw溯源。\n',encoding='utf-8')
242
+ for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,root/'doc'/f)
243
+ # Keep the published script bundle immutable while regenerating review artifacts.
244
+ print('FULL_VIDEO_REVIEW_READY',dataset,flush=True)
245
+
246
+ if __name__=='__main__':
247
+ ap=argparse.ArgumentParser();ap.add_argument('dataset',choices=['HOT3D','ARCTIC']);a=ap.parse_args();torch.set_num_threads(3)
248
+ root=DATA_ROOT/a.dataset/RELEASE;qa=load(root/'doc/validation/source_qa.json') if a.dataset=='HOT3D' else None
249
+ # This entry point owns the original single-sequence report. Other review
250
+ # sequences have their own output directories in arctic_object_review.py.
251
+ sequence={'ARCTIC':'s09_laptop_use_03','HOT3D':'P0015_179e1b84'}[a.dataset]
252
+ views=sorted(p.parent for p in (root/'data'/sequence).glob('*/metainfo.json'));results=[]
253
+ for p in views:results.append(render_view(p,a.dataset,qa))
254
+ assets=[]
255
+ for op in sorted((views[0]/'annotation/object').iterdir()):assets.append(asset_preview(op,root/'doc/validation/assets'/f'{op.name}.mp4'))
256
+ publish_review(a.dataset,results,assets)