shaoyz commited on
Commit
c91cf46
·
verified ·
1 Parent(s): a173f26

Organize HOT3D and ARCTIC shared scripts

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.0/doc/validation/full/MEDIA_VALIDATION.md +1 -1
  2. ARCTIC/shared-v1.0/script/README.md +28 -2
  3. ARCTIC/shared-v1.0/script/{acceleration-config.json → config.json} +0 -0
  4. ARCTIC/shared-v1.0/script/convert.py +14 -0
  5. ARCTIC/shared-v1.0/script/diagnose_hot3d_alignment.py +0 -47
  6. ARCTIC/shared-v1.0/script/document_fresh_sequence_pilots.py +0 -90
  7. ARCTIC/shared-v1.0/script/finalize_fresh_sequence_review.py +0 -48
  8. ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/apply_hot3d_qa.py +0 -65
  9. ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/convert_fresh_sequence_pilots.py +0 -344
  10. ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/diagnose_arctic_review.py +0 -125
  11. ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/fresh_sequence_common.py +0 -176
  12. ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/preprocess_fresh_full.py +0 -301
  13. ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/review_fresh_sequence_pilots.py +0 -221
  14. ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/script-manifest.json +0 -62
  15. ARCTIC/shared-v1.0/script/{accelerated_media.py → internal/accelerated_media.py} +0 -0
  16. ARCTIC/shared-v1.0/script/{arctic_object_review.py → internal/arctic_object_review.py} +0 -0
  17. ARCTIC/shared-v1.0/script/{audit_source_fields.py → internal/audit_source_fields.py} +0 -0
  18. ARCTIC/shared-v1.0/script/{convert_fresh_sequence_pilots.py → internal/convert_fresh_sequence_pilots.py} +12 -4
  19. ARCTIC/shared-v1.0/script/internal/correct_arctic_source_fps_metadata.py +79 -0
  20. ARCTIC/shared-v1.0/script/{diagnose_arctic_review.py → internal/diagnose_arctic_review.py} +0 -0
  21. ARCTIC/shared-v1.0/script/{finalize_arctic_objects_review.py → internal/finalize_arctic_objects_review.py} +0 -0
  22. ARCTIC/shared-v1.0/script/{fresh_sequence_common.py → internal/fresh_sequence_common.py} +0 -0
  23. ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_build.py +0 -0
  24. ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_fetch.py +0 -0
  25. ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_hot_normalize.py +0 -0
  26. ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_mano.py +0 -0
  27. ARCTIC/shared-v1.0/script/{preprocess_fresh_full.py → internal/preprocess_fresh_full.py} +355 -354
  28. ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/render_full_sequence_review.py +0 -0
  29. ARCTIC/shared-v1.0/script/{review_fresh_sequence_pilots.py → internal/review_fresh_sequence_pilots.py} +0 -0
  30. ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/sequence_pilot_common.py +0 -0
  31. ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/sequence_pilot_world.py +0 -0
  32. ARCTIC/shared-v1.0/script/render_review.py +8 -0
  33. ARCTIC/shared-v1.0/script/repair_arctic_pilot.py +0 -57
  34. ARCTIC/shared-v1.0/script/validate.py +9 -0
  35. HOT3D/shared-v1.0/doc/validation/full/MEDIA_VALIDATION.md +1 -1
  36. HOT3D/shared-v1.0/script/README.md +28 -2
  37. HOT3D/shared-v1.0/script/apply_hot3d_qa.py +0 -65
  38. HOT3D/shared-v1.0/script/audit_source_fields.py +0 -55
  39. HOT3D/shared-v1.0/script/{acceleration-config.json → config.json} +0 -0
  40. HOT3D/shared-v1.0/script/convert.py +14 -0
  41. HOT3D/shared-v1.0/script/diagnose_arctic_review.py +0 -125
  42. HOT3D/shared-v1.0/script/diagnose_hot3d_alignment.py +0 -47
  43. HOT3D/shared-v1.0/script/document_fresh_sequence_pilots.py +0 -90
  44. HOT3D/shared-v1.0/script/finalize_fresh_sequence_review.py +0 -48
  45. HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/apply_hot3d_qa.py +0 -65
  46. HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/audit_source_fields.py +0 -55
  47. HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/convert_fresh_sequence_pilots.py +0 -344
  48. HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/diagnose_arctic_review.py +0 -125
  49. HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/fresh_sequence_common.py +0 -176
  50. HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/pilot_build.py +0 -209
ARCTIC/shared-v1.0/doc/validation/full/MEDIA_VALIDATION.md CHANGED
@@ -6,6 +6,6 @@
6
 
7
  并行只发生于同一数据集内部的媒体任务;一个序列的数值计算与媒体任务交错,最多一个重型数据集 worker。实测范围、各并行度耗时和可用内存见 [加速验收](acceleration-benchmark.json),实际设置见 [配置](../../../script/acceleration-config.json)。完整像素回归包含 ARCTIC 全分辨率相机及 HOT3D 彩色/灰度相机。
8
 
9
- 切换前已完成产物保留原来的逐帧像素证明。旧脚本快照在 `script/history/pre-acceleration-20260920/`;当前脚本在 `script/`。一次性重新核验所有已完成产物的内容摘要和现行结构/valid 规则,记录在 `acceleration-revalidation/`,不修改旧检查点的历史脚本摘要。早期 HOT3D 烟雾测试没有内嵌脚本摘要,重新核验另补全输入资产依赖,不能将其视为当时已记录代码指纹。
10
 
11
  以上是自动检查;全量人工确认仍待完成,未授权发布。运行日志只在 tmp,原始包永久保留。
 
6
 
7
  并行只发生于同一数据集内部的媒体任务;一个序列的数值计算与媒体任务交错,最多一个重型数据集 worker。实测范围、各并行度耗时和可用内存见 [加速验收](acceleration-benchmark.json),实际设置见 [配置](../../../script/acceleration-config.json)。完整像素回归包含 ARCTIC 全分辨率相机及 HOT3D 彩色/灰度相机。
8
 
9
+ 切换前已完成产物保留原来的逐帧像素证明。旧脚本版本由本报告保留的脚本清单与 SHA256、以及仓库固定提交历史追溯;当前入口与冻结实现位于 `script/`。一次性重新核验所有已完成产物的内容摘要和现行结构/valid 规则,记录在 `acceleration-revalidation/`,不修改旧检查点的历史脚本摘要。早期 HOT3D 烟雾测试没有内嵌脚本摘要,重新核验另补全输入资产依赖,不能将其视为当时已记录代码指纹。
10
 
11
  以上是自动检查;全量人工确认仍待完成,未授权发布。运行日志只在 tmp,原始包永久保留。
ARCTIC/shared-v1.0/script/README.md CHANGED
@@ -1,2 +1,28 @@
1
- 运行条件与配置见 ../doc/RAW_TO_SHARED.md。
2
- 模型权重不分发;日志与提取缓存不分发。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.0/script/{acceleration-config.json → config.json} RENAMED
File without changes
ARCTIC/shared-v1.0/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.0/script/diagnose_hot3d_alignment.py DELETED
@@ -1,47 +0,0 @@
1
- """Independent native pose/bbox checks for the HOT3D opening-frame complaint."""
2
- from fresh_sequence_common import *
3
- from review_fresh_sequence_pilots import arr
4
-
5
- def pose(row):
6
- T=np.eye(4);T[:3,:3]=Rotation.from_quat([float(row['q_wo_'+k]) for k in 'xyzw']).as_matrix();T[:3,3]=[float(row['t_wo_'+k+'[m]']) for k in 'xyz'];return T
7
-
8
- def rows(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
9
-
10
- def diagnose():
11
- base=DATA_ROOT/'HOT3D';root=base/RELEASE;seq='P0015_179e1b84';src=base/'raw/data/Aria'/seq;cache=base/'tmp/full-video-review-v2/diagnostic';doc=root/'doc/validation'
12
- with zipfile.ZipFile(next(src.glob('*ground_truth.zip'))) as z:
13
- cams=json.loads(z.read('camera_models.json'));heads={int(r['timestamp[ns]']):pose(r) for r in rows(z,'headset_trajectory.csv')}
14
- objects={(int(r['timestamp[ns]']),r['object_uid']):pose(r) for r in rows(z,'dynamic_objects.csv')};boxes=rows(z,'box2d_objects.csv');masks=rows(z,'masks/mask_qa_pass.csv')
15
- diagnostics=[];plate='248247003992116'
16
- for c in cams:
17
- cam=c['stream_id'];p=root/'data'/seq/cam;fr=[json.loads(x) for x in (p/'camera/frames.jsonl').read_text().splitlines()];meta=load(p/'metainfo.json')
18
- dc=c['T_Device_Camera'];Tdc=np.eye(4);Tdc[:3,:3]=Rotation.from_quat(np.roll(dc['quaternion_wxyz'],-1)).as_matrix();Tdc[:3,3]=dc['translation_xyz']
19
- nativeE=np.stack([np.linalg.inv(heads[f['timecode_ns']]@Tdc) for f in fr]);storedE=arr(p/'camera/extrinsic.pt');eerr=float(np.max(np.abs(nativeE-storedE)));assert eerr<2e-6
20
- rawhead=np.stack([heads[f['timecode_ns']] for f in fr]);firstchange=next(i for i in range(len(fr)) if not np.array_equal(rawhead[i],rawhead[0]))
21
- op=p/'annotation/object'/plate;om=load(op/'metainfo.json');mesh=trimesh.load(p/om['original_glb_ref'],process=False,force='mesh');v=np.asarray(mesh.vertices)
22
- storedP=arr(cache/cam/'annotation/object'/plate/'pose.pt');qa={int(r['timestamp[ns]']):r['mask']=='True' for r in masks if r['stream_id']==cam}
23
- lookup={int(r['timestamp[ns]']):r for r in boxes if r['stream_id']==cam and r['object_uid']==plate}
24
- tests=[]
25
- for i in [0,1,26,27,179,180,253,507,760]:
26
- ts=fr[i]['timecode_ns'];P=nativeE[i]@objects[(ts,plate)];error=float(np.max(np.abs(P-storedP[i])));assert error<2e-6
27
- xyz=v@P[:3,:3].T+P[:3,3];uv=project_points(xyz,'fisheye624',c['projectionParams']);good=np.isfinite(uv).all(1)
28
- box=lookup.get(ts);diff=None;expected=None
29
- if box and box['x_min[pixel]'] and good.all():
30
- expected=np.array([float(box[k]) for k in ['x_min[pixel]','y_min[pixel]','x_max[pixel]','y_max[pixel]']]);bb=np.r_[uv.min(0),uv.max(0)];diff=float(np.max(np.abs(expected-bb)))
31
- tests.append({'frame_index':i,'source_frame_id':fr[i]['source_frame_id'],'official_qa_pass':qa[ts],'native_vs_cached_pose_max_abs':error,'source_plate_bbox_vs_projection_max_pixel':diff})
32
- if i in [0,180]:
33
- files=sorted((base/'tmp'/RUN/seq/'images').glob(cam+'-*.jpg'));image=np.asarray(Image.open(files[i]).convert('RGB')).copy()
34
- if expected is not None:cv2.rectangle(image,tuple(expected[:2].astype(int)),tuple(expected[2:].astype(int)),(255,235,0),2)
35
- inds=np.arange(0,len(uv),max(1,len(uv)//5000));pix=uv[inds];ok=np.isfinite(pix).all(1)&(pix[:,0]>=0)&(pix[:,0]<image.shape[1])&(pix[:,1]>=0)&(pix[:,1]<image.shape[0]);pix=np.rint(pix[ok]).astype(int)
36
- image[np.clip(pix[:,1],0,image.shape[0]-1),np.clip(pix[:,0],0,image.shape[1]-1)]=[50,255,80]
37
- cv2.putText(image,f'idx {i}: native QA={qa[ts]} | yellow=official box, green=native pose',(8,24),cv2.FONT_HERSHEY_SIMPLEX,.45,(255,255,255),1)
38
- out=doc/'diagnosis';out.mkdir(parents=True,exist_ok=True);Image.fromarray(image).save(out/f'{cam}-{i:04d}.png')
39
- diagnostics.append({'camera_id':cam,'native_vs_shared_extrinsic_max_abs':eerr,'initial_identical_headset_pose_frames':firstchange,'tests':tests})
40
- report={'conclusion':'Native official hand/object poses already fail official manual QA at the complained frames. Shared media order and native timestamp matching are unchanged; independent native pose reconstruction reproduces the diagnostic geometry. Do not time-shift labels to hide rejected source data.',
41
- 'unproven':'Exact upstream reason for each QA rejection is not provided; initial repeated headset poses are an observation, not a claim of the unique cause.',
42
- 'official_qa_semantics':'Manual QA found no issue with poses of visible hands/objects when true; pose_available does not assess accuracy.',
43
- 'source':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#using-mask-files','cameras':diagnostics}
44
- save(doc/'diagnosis.json',report)
45
- for d in diagnostics:print(d['camera_id'],'head frozen frames',d['initial_identical_headset_pose_frames'],'native box errors',[x['source_plate_bbox_vs_projection_max_pixel'] for x in d['tests']],flush=True)
46
-
47
- if __name__=='__main__':diagnose()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/document_fresh_sequence_pilots.py DELETED
@@ -1,90 +0,0 @@
1
- """Write source-to-contract mappings for the two fresh sequence pilots."""
2
- from fresh_sequence_common import *
3
-
4
- COMMON='''
5
- ## 公共约定与运行
6
-
7
- 这是完整短序列试点,不是全量发布。每个视图使用 [CONTRACT.md](CONTRACT.md) 与 [schema.json](schema.json)。输入是本轮全新下载的 E 盘 raw,不读取 F 盘旧数据或旧试点产物。原始 ZIP/VRS 不改写,临时解包与日志只在数据集 tmp。
8
-
9
- 统一下标 `frame_index=0..T-1`;原帧号与已知时间在 `camera/frames.jsonl`。数值张量是 CPU float32,长度为米,角度为弧度;布尔 valid 表示是否有对应可用标注,缺失的浮点位置填 NaN。valid 不表示可见性。手槽固定左、右。
10
-
11
- 图像由源 JPEG 直接装入 MJPEG/MKV,每包字节不变。容器使用 1 fps、`timebase_role=index_only`,不能按播放器的时长推断真实时间。FFmpeg 固定关闭自动旋转、输出 rgb24,源/目标逐帧 SHA256 相等。实际版本与像素格式写入各视图 metainfo。预览图缩小以方便审核,不是训练输入。
12
-
13
- 校验范围和数值结果见 [validation/REPORT.md](validation/REPORT.md) 与 [validation/report.json](validation/report.json),原始输入 SHA256 见 [pilot-source-manifest.json](pilot-source-manifest.json)。源官方摘要和原包 CRC 在 raw/doc 的下载验收记录中。人工确认仍待完成,不以数学一致性替代投影核验。
14
-
15
- 运行脚本来自本项目 scripts;已将所需本地模块快照放入本发布 script。当前运行环境为 Python 3、PyTorch 2.5.1 CPU、NumPy、smplx、SciPy、Pillow、OpenCV、trimesh、imageio-ffmpeg;HOT3D 另需官方 VRS 工具。MANO v1.2 模型由使用者依授权在本地提供,不包含在发布目录。
16
-
17
- 脚本默认 `E:/hand-datasets` 数据根目录,项目 `tmp/pilot-runtime` 运行环境和 `tmp/pilot-models` 模型目录;迁移时需按机器调整 `fresh_sequence_common.py` 的 DATA_ROOT/VRS 和本地模型路径。这份试点脚本不是无需配置的独立安装包。
18
-
19
- ```text
20
- python scripts/convert_fresh_sequence_pilots.py ARCTIC
21
- python scripts/convert_fresh_sequence_pilots.py HOT3D
22
- python scripts/document_fresh_sequence_pilots.py
23
- python scripts/diagnose_arctic_review.py exposure
24
- python scripts/diagnose_arctic_review.py geometry
25
- python scripts/repair_arctic_pilot.py
26
- python scripts/render_full_sequence_review.py ARCTIC
27
- python scripts/render_full_sequence_review.py HOT3D
28
- ```
29
- '''
30
-
31
- ARCTIC='''# ARCTIC:raw → shared 字段映射
32
-
33
- 本序列原包的 top.obj / bottom.obj 引用 material_0.mtl,但包内实际为 material.mtl;已核对 newmtl/usemtl 均为 material_0。共享层仅修正 mtllib 文件路径,不改材质、UV或纹理,raw 原包保持不变。
34
-
35
- 本次选择 `s09/laptop_use_03`,原图 ZIP 的全部九路相机各 541 张。输出序列名 `s09_laptop_use_03`;相机 0 为 ego,其余 1–8 为 exo。选择官方 P1,split=train。
36
-
37
- 2026-09-20复核:此前顶盖/底座编码解释反了,现已按官方ObjectTensors重新映射。9路相机的index 0/1是原始欠曝图,各动态几何组件valid=false;camera 6的index 270手部对齐问题仅记录,按用户要求撤销单帧屏蔽,恢复原MANO数值及valid=true。不针对单个可疑投影硬编码排除。曝光筛选不构成其他帧质量保证。整套试点未验收,详见[问题与证据](validation/ARCTIC_FINDINGS.md)。
38
-
39
- | raw 中实际数据 | 共享层 | 转换与保留范围 |
40
- |---|---|---|
41
- | images_zips/s09/laptop_use_03.zip,0–8/00001.jpg…00541.jpg | observation/rgb.mkv | 所有原图,无裁剪、缩放、旋转或重新压缩;全部 4869 帧 |
42
- | meta.zip:misc.json 的 ioi_offset=2 | camera/frames.jsonl | 动捕索引=原图编号−2;原图 1 没有标注,2…541 对应标注 0…539;同步标识含源序列和图号 |
43
- | raw_seqs.zip:*.egocam.dist.npy 的 intrinsics、dist8、R_k_cam_np、T_k_cam_np | camera/intrinsic.pt、distortion.pt、extrinsic.pt | 相机 0 rational8,畸变顺序 k1,k2,p1,p2,k3,k4,k5,k6;外参 camera_from_world;首图外参缺失,其余 540 帧有效 |
44
- | meta.zip:misc.json 的 intris_mat、world2cam | 八个外部相机的 camera/ | 官方 processing.forward_project2d 以针孔模型投影;静态参数展开为 T 份,全部 541 帧有标定 |
45
- | raw_seqs.zip:*.mano.npy,左右 rot、pose、shape、trans | annotation/mano/motion.pt [541,2,61] | 非平手均值加回,48 轴角+10形状+3平移;世界系转相机系,按形状相关腕根修正 translation;首帧两手 valid=false |
46
- | raw_seqs.zip:*.object.npy [540,7] | object/laptop/pose.pt、parts/*/pose.pt、joint_state.pt | 角度 rad;全局旋转轴角转 SE(3);物体平移 mm→m;顶盖相对底座绕 -Z 旋转,首帧无效 |
47
- | meta.zip:object_vtemplates/laptop/mesh.obj、top.obj、bottom.obj、MTL/JPG | object/laptop/assets/ | OBJ 顶点 mm→m;顶点顺序/拓扑/UV、材质和纹理引用保留;每个视图一份 |
48
- | 同目录 parts.json | object/laptop/vertex_part_ids.pt 和 metainfo.json | 源0顶盖/1底座,转换为 int64:shared_id=1-source_id,统一0底座/1顶盖;绑定 mesh_ref 和 topology_id |
49
- | object_params.json:keypoints_top、keypoints_bottom | object/laptop/keypoints/xyz.pt [541,32,3] | 原模板各16点的固定顺序,按已发布姿态驱动到相机系;标记 derived,不冒充实测手关键点 |
50
- | splits_json.zip:protocol_p1.json | 视图 metainfo 的 split 与来源 | 保留官方划分;不随意拆帧 |
51
-
52
- 未作为 shared 模态发布:fitting_err、身体数据、动捕 marker、替代采样产物。选定原始包没有独立深度图、像素分割、接触标签或实测手关键点数组;MANO 派生网格只在内存中做校验,不保存 hand_mesh。当前 raw 未提供可直接核实的逐帧时间,timestamp_ns 与 source_fps 保留 null,不用容器 1 fps 伪造真实采集时间。
53
-
54
- 依据固定官方提交 [`49f3eb4`](https://github.com/zc-alexfan/arctic/tree/49f3eb4b7f01663172576357bb3d95695d7a7689):`src/datasets/arctic_dataset.py` 的 ioi_offset 映射、`common/body_models.py` 的非平手均值、`common/object_tensors.py` 的 -Z 关节轴与毫米单位、`src/arctic/processing.py` 和 `common/transforms.py` 的九相机投影。
55
- '''
56
-
57
- HOT='''# HOT3D:raw → shared 字段映射
58
-
59
- 源标注边界:原始 MANO JSONL 共3042条相机时刻记录,2418条含手参数,624条 hand_poses 为空。各视图1014帧中806帧含双手参数、208帧无参数;最终 valid 还要与该相机官方 mask_qa_pass 取交集,不把806称为有效监督数。官方QA是人工检查可见手/物体姿态是否有问题,无法定位到某一实体;这里保守排除整相机帧的手物监督。图像保留,源QA记录和逐帧计数见 validation/source_qa.json。
60
-
61
- 本次选择完整 Aria 序列 `P0015_179e1b84`。三路相机各 1014 帧,源 nominal_rate=30 Hz,首尾采集时间跨度约33.77秒;没有 Quest。
62
-
63
- | raw 中实际数据 | 共享层 | 转换与保留范围 |
64
- |---|---|---|
65
- | *_main_recording.vrs:214-1、1201-1、1201-2 | 各视图 observation/rgb.mkv | 原 JPEG 包;RGB 1408×1408,两灰度640×480。统一读取uint8 RGB,灰度重复到三通道;保留相机类型说明 |
66
- | VRS data 的 frame_number、capture_timestamp_ns | camera/frames.jsonl | 原设备时间与帧号;检查提取文件的记录序号和时间与 VRS 一致 |
67
- | ground_truth.zip:timecode_devicetime_mapping.csv | frames 的 timecode_ns、mapping_delta_ns | 官方 device→timecode 映射,允许最多1000ns定位差并记录实差;标注在 timecode 域内匹配 |
68
- | ground_truth.zip:camera_models.json | camera/intrinsic.pt [1014,15] | 官方静态 FISHEYE624 模型,保留全部15参数及 maxSolidAngle;不改成针孔或人为去畸变 |
69
- | ground_truth.zip:headset_trajectory.csv 和 T_Device_Camera | camera/extrinsic.pt [1014,4,4] | inverse(world_from_device @ device_from_camera),平移米;原标注与图像 timecode 最近邻,最大允许1ms,并记录实际偏差 |
70
- | hand_data.zip:mano_hand_pose_trajectory.jsonl | annotation/mano/motion.pt [1014,2,61] | 源 PCA15 按 MANO v1.2 官方主成分展开+均值;保留10维shape,源q_wxyz转轴角;修正官方左手shapedirs问题;转当前相机系 |
71
- | ground_truth.zip:box2d_hands.csv 的 visibility_ratio[%] | annotation/mano/visibility.pt [1014,2] | 实际源值已在0–1,按官方加载器直接保留,不除100;独立有效性还需通过姿态QA;0可见比例不是缺失;不引入quality |
72
- | ground_truth.zip:dynamic_objects.csv,6个object_uid | object/<uid>/pose.pt [1014,4,4] | 源 world_from_object 转 camera_from_object;米,固定实例UID在序列各相机间保持对应 |
73
- | ground_truth.zip:box2d_objects.csv 的 visibility_ratio[%] | 各物体 visibility.pt [1014] | 比例与独立有效性,归所属物体组件属性 |
74
- | assets/hot3d_models.zip 的 BOP PLY+PNG+models_info.json | object/<uid>/assets/*.obj、MTL、纹理 | BOP id 通过 original_id 对应原UID;PLY顶点mm→m。检查尺寸、三角形及纹理像素往返一致 |
75
- | assets/object_models/obj_*.glb | 各物体 assets 中原生材质伴随资产 | 按 BOP id 对齐,原文件字节不变,保留可能超出 OBJ/MTL 的材质信息;标准 mesh_ref 始终指向米制 OBJ |
76
-
77
- 本序列使用6个物体:spatula_red、potato_masher、can_parmesan、plate_bamboo、carton_oj、bottle_ranch。部件为刚体,未伪造机械关节。图像/手/物体的标注匹配与最大误差在各帧 annotation_matches 明确保存。整手/物体 visibility 的源时间匹配阈值另在属性 source_locator 声明。
78
-
79
- 缺省与选择:无深度相机流;`masks/*.csv` 是帧条件,不是像素分割,QA已合入手/物体valid及依赖姿态的visibility有效性。没有额外生成接触、手关键点或独立hand_mesh。UmeTrack参数、MPS在线相机与SLAM轨迹保留在raw;本版shared选择MANO和ground_truth内相机参数。依据固定提交官方README的参与者划分,P0015属于train,metainfo记录来源。
80
-
81
- 转换语义依据 HOT3D 官方固定提交 [`146b34a`](https://github.com/facebookresearch/hot3d/tree/146b34afef8c1a32adeef7e981c070109f225c87) 的 `mano_layer.py`、`loader_hand_poses.py`、`AriaDataProvider.py`。物体包依据官方 BOP HOT3D仓库固定提交 [`30fe967`](https://huggingface.co/datasets/bop-benchmark/hot3d/tree/30fe9674782f32e1e5edba98476b6ff4300132c5)。Fisheye624预览按Project Aria官方FisheyeRadTanThinPrism公式实现;内参原值不修改。
82
- '''
83
-
84
- if __name__=='__main__':
85
- for dataset,text in [('ARCTIC',ARCTIC),('HOT3D',HOT)]:
86
- root=DATA_ROOT/dataset/RELEASE
87
- (root/'doc/RAW_TO_SHARED.md').write_text(text+COMMON,encoding='utf-8')
88
- shutil.copyfile(Path(__file__),root/'script'/Path(__file__).name)
89
- (root/'script/README.md').write_text('运行条件与配置见 ../doc/RAW_TO_SHARED.md。\n模型权重不分发;日志与提取缓存不分发。\n',encoding='utf-8')
90
- print('DOCUMENTED',dataset)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/finalize_fresh_sequence_review.py DELETED
@@ -1,48 +0,0 @@
1
- """Check full-video artifacts; never infer visual acceptance from numeric success."""
2
- from fresh_sequence_common import *
3
- from review_fresh_sequence_pilots import validate_view, arr
4
- from html.parser import HTMLParser
5
-
6
- class Links(HTMLParser):
7
- def __init__(self):super().__init__();self.refs=[];self.videos=[]
8
- def handle_starttag(self,tag,attrs):
9
- a=dict(attrs)
10
- for k in ['href','src']:
11
- if a.get(k):self.refs.append(a[k])
12
- if tag=='video':self.videos.append(a.get('src'))
13
-
14
- def finalize():
15
- for ds,n in [('ARCTIC',9),('HOT3D',3)]:
16
- root=DATA_ROOT/ds/RELEASE;doc=root/'doc/validation';r=load(doc/'report.json')
17
- assert r['human_review']=='pending' and len(r['full_video_views'])==n
18
- parser=Links();parser.feed((doc/'index.html').read_text(encoding='utf-8'))
19
- assert len(parser.videos)==n+len(r['asset_previews'])
20
- for ref in parser.refs:
21
- if not ref.startswith(('http:','https:','#')):assert (doc/ref).is_file(),ref
22
- for view in r['full_video_views']:
23
- file=doc/view['video_ref'];assert digest(file)==view['video_sha256']
24
- assert len(framehash(['-i',str(file)],copy=True))==view['frames']==view['rendered_frames']
25
- for p in (root/'data').glob('*/*/metainfo.json'):validate_view(p.parent)
26
- if ds=='ARCTIC':
27
- with zipfile.ZipFile(DATA_ROOT/ds/'raw/data/meta.zip') as z:raw=np.asarray(json.loads(z.read('meta/object_vtemplates/laptop/parts.json')),np.int64)
28
- for mp in (root/'data/s09_laptop_use_03').glob('*/metainfo.json'):
29
- p=mp.parent;m=load(mp);assert np.array_equal(arr(p/'annotation/object/laptop/vertex_part_ids.pt'),1-raw)
30
- for c in m['components'].values():
31
- if c.get('valid_policy',{}).get('local_excluded_frame_indices'):
32
- indices=c['valid_policy']['local_excluded_frame_indices'];assert not arr(p/c['valid_ref'])[indices].any()
33
- assert m['acceptance']['training_release_approved'] is False
34
- r['stage']='blocked_pending_visual_review';r['agent_visual_inspection']={'status':'known_residual_hand_alignment_issue','scope':'user screenshots, camera6 frame270 before/after, source exposure contact sheets and selected video snapshots','remaining':'full-camera sequence human acceptance; no claim of all-frame visual pass'}
35
- else:
36
- r['agent_visual_inspection']={'status':'source_QA_failures_excluded_new_full_video_review_pending','scope':'official QA, independent native pose/bbox checks; diagnostic snapshots','remaining':'human review of full sequence'}
37
- for p in (root/'script').glob('*.py'):compile(p.read_text(encoding='utf-8-sig'),str(p),'exec')
38
- assert not list(root.rglob('*.log')) and not list((root/'data').rglob('hand_mesh*'))
39
- r['offline_artifact_check']={'relative_links':'passed','full_camera_videos':n,'frames':sum(v['frames'] for v in r['full_video_views']),'video_hash_and_frame_counts':'passed','tensor_validity_and_refs':'passed','script_compile':'passed','visual_acceptance':'not_granted'}
40
- save(doc/'report.json',r);save(doc/'status.json',{'stage':r['stage'],'human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
41
- shutil.copyfile(Path(__file__),root/'script'/Path(__file__).name)
42
- print(ds,'ARTIFACT_CHECK_PASSED','human acceptance remains pending',flush=True)
43
- p=WORK/'tmp/dataset-work-state.json';state=load(p)
44
- for ds in ['ARCTIC','HOT3D']:
45
- state['active'][ds].update(stage='blocked_pending_visual_review' if ds=='ARCTIC' else 'pilot_full_video_awaiting_human_review',human_sample_review='pending',full_preprocessing_authorized=False,upload_authorized=False)
46
- save(p,state)
47
-
48
- if __name__=='__main__':finalize()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/apply_hot3d_qa.py DELETED
@@ -1,65 +0,0 @@
1
- """Apply native HOT3D manual QA to supervision validity, preserving raw diagnostics."""
2
- from fresh_sequence_common import *
3
-
4
- VIDEO_RUN='full-video-review-v2'
5
- SEQ='P0015_179e1b84'
6
-
7
- def csvrows(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
8
-
9
- def apply_qa(sequence=None,publish=True):
10
- seq=sequence or SEQ
11
- base=DATA_ROOT/'HOT3D';root=base/RELEASE;src=base/'raw/data/Aria'/seq
12
- gtfile=next(src.glob('*ground_truth.zip'));qa_report={}
13
- with zipfile.ZipFile(gtfile) as z:
14
- masks=csvrows(z,'masks/mask_qa_pass.csv');hands=csvrows(z,'box2d_hands.csv');objects=csvrows(z,'box2d_objects.csv')
15
- for meta in sorted((root/'data'/seq).glob('*/metainfo.json')):
16
- p=meta.parent;m=load(meta);cam=m['camera_id'];T=m['num_frames'];frames=[json.loads(x) for x in (p/'camera/frames.jsonl').read_text().splitlines()]
17
- cache=base/'tmp'/VIDEO_RUN/'diagnostic'/(cam if seq==SEQ else seq+'/'+cam)
18
- if (cache/'snapshot.json').exists():assert Path(load(cache/'snapshot.json')['source_view']).resolve()==p.resolve()
19
- if not (cache/'snapshot.json').exists():
20
- cache.mkdir(parents=True,exist_ok=True)
21
- for file in p.rglob('*.pt'):
22
- target=cache/file.relative_to(p);target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(file,target)
23
- save(cache/'metainfo.json',m);save(cache/'snapshot.json',{'purpose':'pre-QA native parameter diagnostics only; not shared usable labels','source_view':str(p),'frames':T})
24
- lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in masks if r['stream_id']==cam}
25
- qa=np.array([lookup[f['timecode_ns']] for f in frames],bool)
26
- source={'archive':gtfile.relative_to(base).as_posix(),'member':'masks/mask_qa_pass.csv','stream_id':cam,'time_index_ref':'camera/frames.jsonl:timecode_ns'}
27
- policy={'semantics':'usable_annotation','formula':'source_annotation_present AND source_numerically_valid AND official_manual_qa_pass',
28
- 'qa_scope':'all visible hand/object poses in this camera frame; conservatively exclude all hand/object supervision if false',
29
- 'source_locator':source,'no_qa_source_rule':'use the component source-validity rules; do not invent QA'}
30
- for key,c in m['components'].items():
31
- # Camera calibration and RGB are not labels covered by this manual hand/object QA flag.
32
- if key=='mano' or c['schema_id'] in ['object/rigid/v1','object/joint_state/v1','object_keypoints/camera/v1']:
33
- values=torch.load(cache/c['data_ref'],weights_only=True).numpy();present=torch.load(cache/c['valid_ref'],weights_only=True).numpy()
34
- valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));values=values.copy();values[~valid]=np.nan
35
- tensor(p/c['data_ref'],values);tensor(p/c['valid_ref'],valid);c['valid_policy']=policy
36
- for attrname,a in c.get('attributes',{}).items():
37
- if attrname!='visibility':continue
38
- ishand=key=='mano';oid=c['source_locator'].get('object_uid');ids=[0,1] if ishand else [oid]
39
- rows=hands if ishand else objects;identity='hand_index' if ishand else 'object_uid'
40
- native={(int(r['timestamp[ns]']),str(r[identity])):float(r['visibility_ratio[%]']) for r in rows if r['stream_id']==cam and r['visibility_ratio[%]']!=''}
41
- values=np.array([[native.get((f['timecode_ns'],str(k)),np.nan) for k in ids] for f in frames],np.float32)
42
- if not ishand:values=values[:,0]
43
- present=np.isfinite(values);assert ((values[present]>=0)&(values[present]<=1)).all()
44
- # Correct the diagnostic copy as well: these values are fractions, despite the source header.
45
- tensor(cache/a['data_ref'],values);tensor(cache/a['valid_ref'],present)
46
- valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));filtered=values.copy();filtered[~valid]=np.nan
47
- tensor(p/a['data_ref'],filtered);tensor(p/a['valid_ref'],valid)
48
- a['provenance']={'kind':'source','method':'native [0,1] ratio retained; official loader does not divide misleading [%] header by 100'}
49
- a['valid_policy']={'semantics':'usable_visibility_annotation','formula':'source_ratio_present AND official_manual_qa_pass','source_locator':source}
50
- a['source_locator']['match_method']='exact'
51
- m['validity_revision']='usable-annotation-2026-09-20'
52
- m['split']='train';m['split_scheme']='HOT3D_official_participant_split';m.pop('split_reason',None)
53
- m['split_source_locator']={'url':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#testtrain-split','participant_id':seq.split('_')[0]}
54
- assert seq.split('_')[0] not in {'P0004','P0005','P0006','P0008','P0016','P0020'}
55
- save(meta,m)
56
- qa_report[cam]={'frames':T,'qa_pass':qa.tolist(),'passed_count':int(qa.sum()),'source_locator':source,
57
- 'interpretation':'manual QA of visible hand/object poses; not RGB validity or individual error localization'}
58
- print('QA_APPLIED',cam,'pass',int(qa.sum()),'fail',int((~qa).sum()),flush=True)
59
- save(root/'doc/validation/source_qa.json' if publish else base/'tmp'/RUN/'qa'/f'{seq}.json',qa_report)
60
- if publish:
61
- for f in ['apply_hot3d_qa.py','fresh_sequence_common.py','convert_fresh_sequence_pilots.py']:
62
- shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
63
- return qa_report
64
-
65
- if __name__=='__main__':apply_qa()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/convert_fresh_sequence_pilots.py DELETED
@@ -1,344 +0,0 @@
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
- import concurrent.futures
10
-
11
- ARCTIC_SEQ='s09/laptop_use_03'
12
- HOT3D_SEQ='P0015_179e1b84'
13
-
14
- def loadzipcsv(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
15
-
16
- def expand(rows,indices,shape):
17
- a=np.full(shape,np.nan);good=(indices>=0)&(indices<len(rows));a[good]=np.asarray(rows)[indices[good]]
18
- return a,good
19
-
20
- def arctic_unlabelled(seq,cameras=None):
21
- """Official held-out s03 RGB: static calibration/assets, no hidden GT guesses."""
22
- base=DATA_ROOT/'ARCTIC';raw=base/'raw/data';sid,action=seq.split('/');oid=action.split('_')[0];seqid=seq.replace('/','_')
23
- with zipfile.ZipFile(raw/'splits_json.zip') as z:splitdef=json.loads(z.read('splits_json/protocol_p1.json'))
24
- assert seq in splitdef['test']
25
- source={'archive':f'raw/data/images_zips/{seq}.zip','member_pattern':'{camera_id}/{source_frame_id:05d}.jpg'}
26
- with zipfile.ZipFile(raw/'meta.zip') as za,zipfile.ZipFile(raw/f'images_zips/{seq}.zip') as zi:
27
- misc=json.loads(za.read('meta/misc.json'))[sid];prefix=f'meta/object_vtemplates/{oid}/'
28
- native_parts=np.asarray(json.loads(za.read(prefix+'parts.json')),np.int64)
29
- names=sorted(n for n in zi.namelist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',n))
30
- for cam in sorted({n.split('/')[0] for n in names},key=int):
31
- if cameras is not None and cam not in cameras:continue
32
- selected=[n for n in names if n.split('/')[0]==cam];ids=[int(Path(n).stem) for n in selected]
33
- size=list(Image.open(io.BytesIO(zi.read(selected[0]))).size);assert size==misc['image_size'][int(cam)]
34
- v=FreshView('ARCTIC',seqid,cam,ids,size,dict(source,camera_id=cam))
35
- if (v.p/'metainfo.json').exists() and load(v.p/'metainfo.json').get('pilot_complete'):
36
- print('RESUME verified view',seq,cam,flush=True);continue
37
- 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)
38
- v.m['sampling'].update(source_fps=None,source_fps_reason='Capture FPS not asserted by supplied source; original image numbers retained')
39
- if cam!='0':
40
- src={'archive':'raw/data/meta.zip','member':'meta/misc.json','record':sid}
41
- v.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
42
- 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))
43
- v.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',K,np.ones(t,bool),['T','row','column'],source=src)
44
- 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)
45
- 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)
46
- rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';object_textured_assets(za,prefix,assets)
47
- parts=1-native_parts;tensor(op/'vertex_part_ids.pt',parts)
48
- 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'}],
49
- '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']}
50
- save(op/'articulation.json',articulation);sourceasset={'archive':'raw/data/meta.zip','member_prefix':prefix}
51
- v.component('object_'+oid+'_articulation',rel+'/articulation.json','object/articulated/v1',[],np.array(True),source=sourceasset,static=True)
52
- v.mesh(oid,rel+'/assets/mesh.obj',sourceasset)
53
- 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
54
- 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 ')])
55
- assert np.array_equal(original,actual) and len(parts)==len(actual)
56
- 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})
57
- v.checks.append({'test':'source_static_mesh_vertices_metres_and_part_ids','passed':True,'vertices':len(actual)})
58
- 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'}
59
- 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')
60
- print('MEDIA ARCTIC',cam,t,flush=True);jpeg_video(v,((n,zi.read(n)) for n in selected));v.m['pilot_complete']=True;v.finish()
61
-
62
- def arctic(sequence=None,cameras=None,initialize=True):
63
- dataset='ARCTIC';seq=sequence or ARCTIC_SEQ;sid,action=seq.split('/');oid=action.split('_')[0];seqid=seq.replace('/','_')
64
- if initialize:setup(dataset,seqid)
65
- base=DATA_ROOT/dataset;raw=base/'raw/data'
66
- with zipfile.ZipFile(raw/'raw_seqs.zip') as z:
67
- if f'raw_seqs/{seq}.mano.npy' not in z.namelist():
68
- assert all(f'raw_seqs/{seq}.{x}.npy' not in z.namelist() for x in ['object','egocam.dist'])
69
- return arctic_unlabelled(seq,cameras)
70
- hand=native_npy_bytes(z.read(f'raw_seqs/{seq}.mano.npy'))
71
- ego=native_npy_bytes(z.read(f'raw_seqs/{seq}.egocam.dist.npy'))
72
- objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'))
73
- with zipfile.ZipFile(raw/'splits_json.zip') as z:splitdef=json.loads(z.read('splits_json/protocol_p1.json'))
74
- split=next((k for k,v in splitdef.items() if seq in v),'unknown')
75
- if split=='val':split='val'
76
- za=zipfile.ZipFile(raw/'meta.zip');misc=json.loads(za.read('meta/misc.json'))[sid]
77
- params=json.loads(za.read(f'meta/object_vtemplates/{oid}/object_params.json'))
78
- native_parts=np.asarray(json.loads(za.read(f'meta/object_vtemplates/{oid}/parts.json')),np.int64)
79
- models=[Mano('left'),Mano('right')];N=len(objects)
80
- 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
81
- 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()
82
- kp=np.concatenate([params['keypoints_top'],params['keypoints_bottom']])/1000;n_top=len(params['keypoints_top'])
83
- source={'archive':f'raw/data/images_zips/{seq}.zip','member_pattern':'{camera_id}/{source_frame_id:05d}.jpg'}
84
- zimage=zipfile.ZipFile(raw/f'images_zips/{seq}.zip')
85
- names=sorted(n for n in zimage.namelist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',n))
86
- extra=[n for n in zimage.namelist() if n.endswith('.jpg') and not re.fullmatch(r'[0-8]/[0-9]+\.jpg',n)]
87
- assert all(n.startswith('__MACOSX/') or Path(n).name.startswith('._') for n in extra),extra[:5]
88
- for cam in sorted({n.split('/')[0] for n in names},key=int):
89
- if cameras is not None and cam not in cameras:continue
90
- 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']
91
- size=list(Image.open(io.BytesIO(zimage.read(selected[0]))).size)
92
- assert size==misc['image_size'][int(cam)]
93
- v=FreshView(dataset,seqid,cam,ids,size,dict(source,camera_id=cam))
94
- if (v.p/'metainfo.json').exists():
95
- old=load(v.p/'metainfo.json')
96
- if old.get('pilot_complete') and old.get('num_frames')==len(ids):print('RESUME verified view',seq,cam,flush=True);continue
97
- t=v.T;good=(ix>=0)&(ix<N)
98
- 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')
99
- v.m['sampling'].update(source_fps=None,source_fps_reason='Actual capture FPS not asserted by the selected raw files; frame indices and official synchronization offset retained',selection='Every released image of this selected camera in the complete official sequence ZIP; boundary images without annotations retained')
100
- srcanno={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.mano.npy','index_ref':'camera/frames.jsonl:source_annotation_index'}
101
- srccam={'archive':'raw/data/meta.zip','member':'meta/misc.json','record':sid}
102
- E=np.broadcast_to(np.eye(4),(t,4,4)).copy()
103
- if cam=='0':
104
- K=np.broadcast_to(ego['intrinsics'],(t,3,3));D=np.broadcast_to(ego['dist8'],(t,8))
105
- 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)
106
- src={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.egocam.dist.npy'}
107
- v.m['camera'].update(model='rational8',schema_id='camera/rational8/v1')
108
- v.array('intrinsic','camera/intrinsic.pt','camera/rational8/v1',K,np.ones(t,bool),['T','row','column'],source=src,distortion_ref='camera/distortion.pt')
109
- tensor(v.p/'camera/distortion.pt',np.asarray(D,np.float32));validE=good
110
- else:
111
- 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
112
- v.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
113
- v.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',K,np.ones(t,bool),['T','row','column'],source=srccam)
114
- v.array('extrinsic','camera/extrinsic.pt','transform/se3/v1',E,validE,['T','row','column'],source=src,unit='m',convention='T_camera_from_world')
115
- assert_se3(E[validE]);motion=np.full((t,2,61),np.nan)
116
- for side,model in enumerate(models):
117
- h=hand[['left','right'][side]];pose=np.c_[h['rot'],h['pose']].copy();pose[:,3:]+=model.data['hands_mean']
118
- result,err=camera_mano(model,pose[ix[good]],np.broadcast_to(h['shape'],(good.sum(),10)),h['trans'][ix[good]],E[good])
119
- motion[good,side]=result
120
- # Independent source-model mean configuration, separate from camera conversion algebra.
121
- from types import SimpleNamespace
122
- import smplx
123
- 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)
124
- checkidx=np.arange(0,N,max(1,N//12));b=torch.tensor(np.broadcast_to(h['shape'],(len(checkidx),10)).copy(),dtype=torch.float32)
125
- 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()
126
- actual=model.geometry(pose[checkidx],b.numpy(),h['trans'][checkidx])[0]
127
- delta=float(np.max(np.linalg.norm(expected-actual,axis=-1)));assert delta<2e-6
128
- 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})
129
- 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')
130
- for i,(row,name,j) in enumerate(zip(v.frames,selected,ix)):
131
- row.update(source_annotation_index=int(j) if good[i] else None,sync_id=f'{seq}:{ids[i]}')
132
- row['source_locator'].update(member=name)
133
- 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])}}
134
- rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';object_textured_assets(za,f'meta/object_vtemplates/{oid}/',assets)
135
- # Parse exact OBJ vertex ordering before loading a render-oriented mesh.
136
- 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 ')])
137
- # Official ObjectTensors adds 1 to raw parts, then articulates ==1: raw 0 is TOP.
138
- shared_parts=1-native_parts
139
- assert len(vertices)==len(native_parts);tensor(op/'vertex_part_ids.pt',shared_parts)
140
- 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]]
141
- srcobj={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.object.npy','index_ref':'camera/frames.jsonl:source_annotation_index'}
142
- for name,data in [('root',P),('bottom',P),('top',top)]:
143
- path=rel+('/pose.pt' if name=='root' else f'/parts/{name}/pose.pt')
144
- 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')
145
- assert_se3(data[good])
146
- 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')
147
- 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'}],
148
- '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']}
149
- save(op/'articulation.json',articulation)
150
- v.component('object_'+oid+'_articulation',rel+'/articulation.json','object/articulated/v1',[],np.array(True),source=srcobj,static=True)
151
- sourceasset={'archive':'raw/data/meta.zip','member_prefix':f'meta/object_vtemplates/{oid}/'}
152
- v.mesh(oid,rel+'/assets/mesh.obj',sourceasset)
153
- topology=digest(assets/'mesh.obj')
154
- 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})
155
- xyz=np.full((t,len(kp),3),np.nan);errs=[]
156
- for i in np.flatnonzero(good):
157
- 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]
158
- 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]
159
- 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()))
160
- assert max(errs)<2e-5
161
- 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')
162
- 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())]})
163
- 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'}
164
- print('MEDIA',dataset,cam,t,flush=True);jpeg_video(v,((n,zimage.read(n)) for n in selected))
165
- v.m['pilot_complete']=True;v.finish()
166
- zimage.close();za.close()
167
-
168
- def vrs_records(path,cam):
169
- raw=command([VRS,'print-json',path,'+',cam,'+','data']).decode(errors='replace')
170
- rows=[]
171
- for line in raw.splitlines():
172
- if line.startswith('{"data_layout"'):rows.append({x['name']:x['value'] for x in json.loads(line)['data_layout']})
173
- return rows
174
-
175
- def nearest(times,query,limit):
176
- times=np.asarray(times,np.int64);q=np.asarray(query,np.int64)
177
- if not len(times):return np.zeros(len(q),np.int64),np.zeros(len(q),bool),np.zeros(len(q),np.int64)
178
- j=np.searchsorted(times,q);a=np.clip(j-1,0,len(times)-1);b=np.clip(j,0,len(times)-1)
179
- ix=np.where(np.abs(times[a]-q)<=np.abs(times[b]-q),a,b);delta=times[ix]-q
180
- return ix,np.abs(delta)<=limit,delta
181
-
182
- def verify_hot3d_frame_order_and_metadata(sequence=None):
183
- """Independent extraction-index and VRS capture-rate check, also on resume."""
184
- seq=sequence or HOT3D_SEQ
185
- base=DATA_ROOT/'HOT3D';src=base/'raw/data/Aria'/seq;recording=next(src.glob('*.vrs'))
186
- extract=base/'tmp'/RUN/seq/'images'
187
- for cam in ['214-1','1201-1','1201-2']:
188
- p=base/RELEASE/'data'/seq/cam;m=load(p/'metainfo.json');rows=vrs_records(recording,cam)
189
- paths=sorted(extract.glob(cam+'-*.jpg'))
190
- indices=[int(x.name.split('-')[-2]) for x in paths];assert indices==list(range(1,len(rows)+1))
191
- 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
192
- assert np.max(np.abs(file_times-times))<.001,'extracted images do not match camera record ordering'
193
- raw=command([VRS,'print-json',recording,'+',cam,'+','configuration']).decode(errors='replace')
194
- 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]
195
- rate=cfg['nominal_rate'];assert abs(np.median(np.diff(times))-1/rate)<.001
196
- m['sampling']['source_fps']=rate
197
- m['sampling']['source_fps_basis']='VRS camera configuration nominal_rate; actual intervals checked separately'
198
- m['sampling']['duration_seconds']=float(times[-1]-times[0])
199
- frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
200
- for frame in frames:
201
- for match in frame['annotation_matches'].values():
202
- if 'available' in match:match['source_record_present']=match.pop('available')
203
- lines(p/'camera/frames.jsonl',frames)
204
- info=load(base/'raw/data/assets/object_models/models_info.json')
205
- reverse={str(v['original_id']):str(k) for k,v in info.items()}
206
- for op in (p/'annotation/object').glob('*'):
207
- om=load(op/'metainfo.json');oid=om['object_id'];idx=int(reverse[oid])
208
- glb=base/'raw/data/assets/object_models'/f'obj_{idx:06d}.glb';assert glb.is_file()
209
- # Retain the official material-bearing companion byte-for-byte. OBJ remains the declared standard mesh.
210
- target=op/'assets'/glb.name;shutil.copyfile(glb,target)
211
- assert digest(glb)==digest(target)
212
- 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'})
213
- save(op/'metainfo.json',om)
214
- save(p/'metainfo.json',m)
215
- checkpath=base/'tmp'/RUN/'checks'/f'{seq}__{cam}.json';checks=load(checkpath)
216
- checks['checks']=[c for c in checks['checks'] if c['test']!='VRS_extracted_filename_order_and_nominal_rate']
217
- 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)
218
-
219
- def hot3d(sequence=None,initialize=True):
220
- dataset='HOT3D';seq=sequence or HOT3D_SEQ
221
- if initialize:setup(dataset,seq)
222
- base=DATA_ROOT/dataset;raw=base/'raw/data';src=raw/'Aria'/seq;tmp=base/'tmp'/RUN
223
- recording=next(src.glob('*.vrs'));extract=tmp/seq/'images'
224
- if not (tmp/seq/'extracted.json').exists() or not extract.exists() or not any(extract.glob('*.jpg')):
225
- extract.mkdir(parents=True,exist_ok=True)
226
- log=tmp/seq/'vrs-extraction.log'
227
- with log.open('wb') as out:
228
- run=subprocess.run([str(VRS),'extract-images',str(recording),'--to',str(extract),'+','214-1','+','1201-1','+','1201-2'],stdout=out,stderr=subprocess.STDOUT)
229
- assert run.returncode==0,'VRS extraction failed; see tmp log'
230
- save(tmp/seq/'extracted.json',{'source':recording.name,'streams':['214-1','1201-1','1201-2'],'complete':True})
231
- gt=zipfile.ZipFile(next(src.glob('*ground_truth.zip')));handszip=zipfile.ZipFile(next(src.glob('*hand_data.zip')))
232
- 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']))
233
- assert meta['headset']=='Aria' and meta['recording_name']==seq
234
- 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)
235
- heads={int(r['timestamp[ns]']):csv_transform(r) for r in loadzipcsv(gt,'headset_trajectory.csv')};head_times=sorted(heads)
236
- 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)
237
- objects=loadzipcsv(gt,'dynamic_objects.csv');vis_h=loadzipcsv(gt,'box2d_hands.csv');vis_o=loadzipcsv(gt,'box2d_objects.csv')
238
- models=[Mano('left'),Mano('right')];fixed=np.abs(models[0].data['shapedirs'][:,0]-models[1].data['shapedirs'][:,0]).sum()<1
239
- if fixed:
240
- models[0].data['shapedirs'][:,0]*=-1
241
- with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
242
- 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()}
243
- for camera in cams:
244
- cam=camera['stream_id'];rows=vrs_records(recording,cam);paths=sorted(extract.glob(cam+'-*.jpg'))
245
- assert len(rows)==len(paths)>1,(cam,len(rows),len(paths))
246
- 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})
247
- if (v.p/'metainfo.json').exists() and load(v.p/'metainfo.json').get('pilot_complete'):print('RESUME verified view',cam,flush=True);continue
248
- t=v.T;capture=np.array([int(r['capture_timestamp_ns']) for r in rows],np.int64)
249
- ix,good,delta=nearest(dev,capture,1000);assert good.all(),'Missing official device-time/timecode mapping'
250
- times=tc[ix];sourcegt={'archive':next(src.glob('*ground_truth.zip')).relative_to(base).as_posix()}
251
- test_ids={'P0004','P0005','P0006','P0008','P0016','P0020'}
252
- split='test' if meta['participant_id'] in test_ids else 'train'
253
- assert meta['have_hand_object_pose_gt']==(split=='train')
254
- 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'])
255
- 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))))
256
- 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'])
257
- 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))
258
- dc=camera['T_Device_Camera'];Tdc=transform(dc['quaternion_wxyz'],dc['translation_xyz'])
259
- hi,hvalid,hdelta=nearest(head_times,times,1_000_000);E=np.full((t,4,4),np.nan)
260
- for i in np.flatnonzero(hvalid):E[i]=np.linalg.inv(heads[head_times[hi[i]]]@Tdc)
261
- assert hvalid.all(),'Headset GT missing at image times'
262
- 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')
263
- mi,mvalid,mdelta=nearest(hand_times,times,1_000_000);motion=np.full((t,2,61),np.nan);valid=np.zeros((t,2),bool)
264
- for side,model in enumerate(models):
265
- chosen=[i for i in range(t) if mvalid[i] and str(side) in hands[hand_times[mi[i]]]]
266
- if not chosen:continue
267
- native=[hands[hand_times[mi[i]]][str(side)] for i in chosen];pose=[];beta=[];trans=[]
268
- for h in native:
269
- 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'])
270
- motion[chosen,side],err=camera_mano(model,pose,beta,trans,E[chosen]);valid[chosen,side]=True
271
- # Official source model uses PCA15 and nonflat mean, unlike output AA48.
272
- import smplx
273
- from types import SimpleNamespace
274
- 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)
275
- ixcheck=np.arange(0,len(chosen),max(1,len(chosen)//16));arr=np.asarray(pose);bet=np.asarray(beta);tr=np.asarray(trans)
276
- 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()
277
- 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
278
- 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})
279
- if hand_times:
280
- 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')
281
- def vis_values(records,identity_field,identities):
282
- out=np.full((t,len(identities)),np.nan)
283
- for c,identity in enumerate(identities):
284
- 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[%]']!=''}
285
- if not values:continue
286
- ts=sorted(values);ii,vv,dd=nearest(ts,times,1_000_000)
287
- for i in np.flatnonzero(vv):out[i,c]=values[ts[ii[i]]]
288
- return out
289
- if hand_times and vis_h:
290
- 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')
291
- for i,row in enumerate(v.frames):
292
- 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]))
293
- row['source_locator'].update(record_index=i,capture_timestamp_ns=int(capture[i]))
294
- row['annotation_matches']={}
295
- for key,ts,idxs,flags,dd in [('extrinsic',head_times,hi,hvalid,hdelta),('mano',hand_times,mi,mvalid,mdelta)]:
296
- 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])}
297
- for oid in sorted(set(meta['object_uids'])|{r['object_uid'] for r in objects}):
298
- rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';assets.mkdir(parents=True,exist_ok=True)
299
- 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)
300
- P=np.full((t,4,4),np.nan)
301
- for i in np.flatnonzero(ok):P[i]=E[i]@sourceposes[ts[oi[i]]]
302
- key=f'object_{oid}_pose'
303
- if sourceposes:
304
- 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')
305
- 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])}
306
- if sourceposes and vis_o:
307
- 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')
308
- idx=int(reverse[oid]);prefix=f'models/obj_{idx:06d}'
309
- for member in assetszip.namelist():
310
- if member.startswith(prefix+'.'):(assets/Path(member).name).write_bytes(assetszip.read(member))
311
- ply=assets/f'obj_{idx:06d}.ply';mesh=trimesh.load(ply,process=False,force='mesh');mesh.vertices=np.asarray(mesh.vertices)*.001
312
- expected_extent=np.array([assetinfo[str(idx)]['size_'+x] for x in 'xyz']);assert np.allclose(mesh.extents,expected_extent,atol=1e-5)
313
- text,textures=trimesh.exchange.obj.export_obj(mesh,return_texture=True,digits=12);meshpath=assets/f'obj_{idx:06d}.obj';meshpath.write_text(text)
314
- for filename,data in textures.items():(assets/filename).write_bytes(data)
315
- restored=trimesh.load(meshpath,process=False,force='mesh');assert np.allclose(restored.triangles,mesh.triangles,atol=1e-7)
316
- assert np.array_equal(np.asarray(restored.visual.material.image),np.asarray(mesh.visual.material.image))
317
- # Keep the official GLB as a companion asset so richer original material properties remain available.
318
- glb=raw/'assets'/f'{oid}.glb'
319
- if glb.exists():shutil.copyfile(glb,assets/glb.name)
320
- # The millimetre PLY was a temporary converter input, not a second shared geometry convention.
321
- assert ply.resolve().is_relative_to(assets.resolve());ply.unlink()
322
- sourceasset={'archive':'raw/data/assets/hot3d_models.zip','member':prefix+'.ply','original_id':oid,'bop_id':idx}
323
- v.mesh(oid,meshpath.relative_to(v.p).as_posix(),sourceasset)
324
- 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})
325
- 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})
326
- v.checks.append({'test':'all_camera_frame_device_time_mapping','frames':t,'max_delta_ns':int(np.abs(delta).max()),'passed':True})
327
- 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'}
328
- if not hand_times:v.m['omitted_components']['mano']='Official MANO trajectory is empty; no pose labels released for this sequence'
329
- if not objects:v.m['omitted_components']['object_pose']='Official object trajectory is empty; static source models retained without fabricated pose arrays'
330
- print('MEDIA',dataset,cam,t,flush=True);jpeg_video(v,((p.name,p.read_bytes()) for p in paths))
331
- v.m['pilot_complete']=True;v.finish()
332
- assetszip.close();gt.close();handszip.close()
333
-
334
- if __name__=='__main__':
335
- p=argparse.ArgumentParser();p.add_argument('dataset',choices=['ARCTIC','HOT3D']);a=p.parse_args()
336
- torch.set_num_threads(4)
337
- {'ARCTIC':arctic,'HOT3D':hot3d}[a.dataset]()
338
- if a.dataset=='HOT3D':
339
- verify_hot3d_frame_order_and_metadata()
340
- from apply_hot3d_qa import apply_qa
341
- apply_qa()
342
- elif (DATA_ROOT/'ARCTIC'/RELEASE/'doc/validation/exposure.json').exists():
343
- from repair_arctic_pilot import repair
344
- repair()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/diagnose_arctic_review.py DELETED
@@ -1,125 +0,0 @@
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.0/script/history/pre-acceleration-20260920/fresh_sequence_common.py DELETED
@@ -1,176 +0,0 @@
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
-
14
- DATA_ROOT = Path('E:/hand-datasets')
15
- RELEASE = 'shared-v1.0'
16
- RUN = 'fresh-sequence-pilot-20260920'
17
- VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
18
-
19
- def digest(p):
20
- h=hashlib.sha256()
21
- with Path(p).open('rb') as f:
22
- for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
23
- return h.hexdigest()
24
-
25
- def native_npy_bytes(data):
26
- f=io.BytesIO(data);version=np.lib.format.read_magic(f)
27
- shape,order,dtype=np.lib.format._read_array_header(f,version)
28
- if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
29
- return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()
30
-
31
- def command(args):
32
- r=subprocess.run([str(x) for x in args],capture_output=True)
33
- if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
34
- return r.stdout
35
-
36
- def framehash(args,copy=False):
37
- output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
38
- *(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
39
- '-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
40
- return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]
41
-
42
- def jpeg_video(view, members):
43
- """members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
44
- temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
45
- temporary.parent.mkdir(parents=True,exist_ok=True)
46
- hashes=[]
47
- with temporary.open('wb') as out:
48
- for locator,b in members:
49
- assert b[:2]==b'\xff\xd8',locator
50
- hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
51
- assert len(hashes)==view.T
52
- dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
53
- source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
54
- command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
55
- packet=framehash(['-i',str(dst)],True)
56
- assert packet==hashes,'source JPEG packets changed in MKV'
57
- before=framehash(source);after=framehash(['-i',str(dst)])
58
- assert before==after and len(before)==view.T,'RGB decoding differs'
59
- w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
60
- info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
61
- line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
62
- pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
63
- version=command([FF,'-version']).decode().splitlines()[0]
64
- view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
65
- source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
66
- storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
67
- 'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
68
- 'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
69
- view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
70
- 'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
71
- 'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
72
- save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
73
- # This precise file was created by this call within the current run's temporary directory.
74
- assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()
75
-
76
- class FreshView:
77
- def __init__(self,dataset,seq,cam,ids,size,source):
78
- self.root=DATA_ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
79
- self.tmp=DATA_ROOT/dataset/'tmp'/RUN;self.p.mkdir(parents=True,exist_ok=True)
80
- self.T=len(ids);self.source=source;self.checks=[]
81
- self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
82
- 'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
83
- 'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
84
- 'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
85
- 'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
86
- self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
87
- 'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
88
- def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
89
- valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
90
- self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
91
- 'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
92
- 'source_locator':source or self.source,**kw}
93
- def array(self,name,path,schema,data,valid,axes,**kw):
94
- a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
95
- assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
96
- assert np.isfinite(a[valid]).all(),name
97
- a[~valid]=np.nan;tensor(self.p/path,a)
98
- self.component(name,path,schema,axes,valid,**kw)
99
- restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
100
- assert np.array_equal(a,restored,equal_nan=True)
101
- self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
102
- def attribute(self,parent,path,data,axes,source,meaning):
103
- data=np.asarray(data,np.float32);valid=np.isfinite(data)
104
- assert ((data[valid]>=0)&(data[valid]<=1)).all()
105
- vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
106
- self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
107
- 'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
108
- 'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
109
- def mesh(self,oid,path,source):
110
- self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
111
- method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
112
- def finish(self):
113
- lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
114
- save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
115
- print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
116
-
117
- def assert_se3(a):
118
- a=np.asarray(a);assert a.shape[-2:]==(4,4)
119
- # A component may exist while QA leaves no usable poses in this view.
120
- if a.size==0:return
121
- assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
122
- r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
123
- assert np.max(np.abs(np.linalg.det(r)-1))<2e-5
124
-
125
- def setup(dataset,seq):
126
- base=DATA_ROOT/dataset;out=base/RELEASE
127
- for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
128
- for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
129
- save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
130
- sources=['fresh_sequence_common.py','convert_fresh_sequence_pilots.py','pilot_build.py','pilot_fetch.py','pilot_mano.py',
131
- 'sequence_pilot_common.py','sequence_pilot_world.py','pilot_hot_normalize.py','audit_source_fields.py']
132
- for name in sources:
133
- if (WORK/'scripts'/name).exists():shutil.copyfile(WORK/'scripts'/name,out/'script'/name)
134
- (base/'tmp'/RUN).mkdir(parents=True,exist_ok=True)
135
-
136
- def object_textured_assets(z,prefix,target):
137
- target.mkdir(parents=True,exist_ok=True)
138
- for name in z.namelist():
139
- if not name.startswith(prefix) or name.endswith('/'):continue
140
- rel=Path(name[len(prefix):]);dest=target/rel
141
- assert dest.resolve().is_relative_to(target.resolve());dest.parent.mkdir(parents=True,exist_ok=True)
142
- if dest.suffix.lower() in ('.obj','.mtl','.jpg','.jpeg','.png'):
143
- b=z.read(name)
144
- if dest.suffix=='.obj':
145
- rows=b.decode().splitlines()
146
- for i,row in enumerate(rows):
147
- if row.startswith('v '):
148
- v=row.split();v[1:4]=[format(float(x)/1000,'.17g') for x in v[1:4]];rows[i]=' '.join(v)
149
- b=('\n'.join(rows)+'\n').encode()
150
- dest.write_bytes(b)
151
- repair_arctic_material_refs(target)
152
-
153
- def repair_arctic_material_refs(target):
154
- """Repair a source filename mismatch only when material identifiers agree."""
155
- material=target/'material.mtl'
156
- if not material.exists():return
157
- ids={x.split(maxsplit=1)[1] for x in material.read_text().splitlines() if x.startswith('newmtl ')}
158
- for obj in target.glob('*.obj'):
159
- text=obj.read_text();rows=text.splitlines();used={x.split(maxsplit=1)[1] for x in rows if x.startswith('usemtl ')}
160
- if 'mtllib material_0.mtl' in rows and not (target/'material_0.mtl').exists():
161
- assert used and used.issubset(ids),(obj,used,ids)
162
- obj.write_text(text.replace('mtllib material_0.mtl','mtllib material.mtl'))
163
-
164
- def project_points(xyz,camera,params):
165
- xyz=np.asarray(xyz,float);uv=np.full((len(xyz),2),np.nan);good=np.isfinite(xyz).all(1)&(xyz[:,2]>1e-6)
166
- if camera=='fisheye624':
167
- p=np.asarray(params);xy=xyz[good,:2]/xyz[good,2,None];r=np.linalg.norm(xy,axis=1);th=np.arctan(r)
168
- radial=th*(1+sum(p[3+i]*th**(2*i+2) for i in range(6)))
169
- xy=xy*np.divide(radial,r,out=np.ones_like(r),where=r>1e-12)[:,None]
170
- x,y=xy.T;rr=x*x+y*y
171
- xd=x+(2*x*x+rr)*p[9]+2*x*y*p[10]+p[11]*rr+p[12]*rr*rr
172
- yd=y+(2*y*y+rr)*p[10]+2*x*y*p[9]+p[13]*rr+p[14]*rr*rr
173
- uv[good]=p[0]*np.stack([xd,yd],1)+p[1:3]
174
- else:
175
- K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
176
- return uv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/preprocess_fresh_full.py DELETED
@@ -1,301 +0,0 @@
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
-
14
- JOB='full-preprocess-v1.0'
15
- CONTROL=WORK/'tmp'/JOB
16
- RESERVE=400_000_000_000
17
- SCRIPT=Path(__file__).resolve()
18
- TEST_IDS={'P0004','P0005','P0006','P0008','P0016','P0020'}
19
- torch.set_num_threads(4)
20
-
21
- def now():return datetime.now().astimezone().isoformat()
22
-
23
- def atomic(p,value):
24
- p.parent.mkdir(parents=True,exist_ok=True);q=p.with_name(p.name+'.writing')
25
- q.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8');os.replace(q,p)
26
-
27
- def temporary(ds):return DATA_ROOT/ds/'tmp'/JOB
28
-
29
- PRODUCTION_SCRIPTS=['preprocess_fresh_full.py','convert_fresh_sequence_pilots.py','apply_hot3d_qa.py','review_fresh_sequence_pilots.py','render_full_sequence_review.py','fresh_sequence_common.py','diagnose_arctic_review.py','pilot_build.py','pilot_fetch.py','pilot_mano.py','sequence_pilot_common.py','sequence_pilot_world.py','pilot_hot_normalize.py','audit_source_fields.py']
30
-
31
- def code_manifest():
32
- return [{'path':'script/'+f,'sha256':digest(WORK/'scripts'/f)} for f in PRODUCTION_SCRIPTS]
33
-
34
- def snapshot_scripts(ds):
35
- root=DATA_ROOT/ds/RELEASE
36
- for f in PRODUCTION_SCRIPTS:shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
37
- atomic(root/'doc/validation/full/script-manifest.json',{'created_at':now(),'scope':'Current production converter and validation scripts; earlier pilot manifests describe their historical run','files':code_manifest()})
38
-
39
- def inputs(ds):
40
- base=DATA_ROOT/ds
41
- name='archive_checksums.json' if ds=='ARCTIC' else 'file_checksums.json'
42
- return load(base/'raw/doc'/name)
43
-
44
- def check_input(ds,rel,records):
45
- p=DATA_ROOT/ds/'raw/data'/rel;r=records[rel];st=p.stat()
46
- assert st.st_size==r['size'],f'Raw size changed: {p}'
47
- assert r.get('official_sha256_match',r.get('official_digest_match',False))
48
- if st.st_mtime_ns!=r['mtime_ns']:
49
- assert digest(p)==r['sha256'],f'Raw digest changed: {p}'
50
- if p.suffix=='.zip':
51
- with zipfile.ZipFile(p) as z:assert z.testzip() is None
52
- 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']}
53
-
54
- def plan():
55
- CONTROL.mkdir(parents=True,exist_ok=True);out={'created_at':now(),'order':['ARCTIC','HOT3D'],'datasets':{},'reserve_bytes':RESERVE}
56
- for ds in out['order']:
57
- base=DATA_ROOT/ds;records=inputs(ds)
58
- for rel in records:check_input(ds,rel,records)
59
- rows=[];auxiliary=[]
60
- if ds=='ARCTIC':
61
- with zipfile.ZipFile(base/'raw/data/splits_json.zip') as z:splits=json.loads(z.read('splits_json/protocol_p1.json'))
62
- for p in sorted((base/'raw/data/images_zips').rglob('*.zip')):
63
- seq=p.relative_to(base/'raw/data/images_zips').with_suffix('').as_posix()
64
- if '/' not in seq:
65
- assert seq=='backgrounds',seq
66
- auxiliary.append({'file':'raw/data/images_zips/backgrounds.zip','handling':'retain original archive in raw; background reference photographs are not hand-object capture sequences'})
67
- continue
68
- with zipfile.ZipFile(p) as z:
69
- im=[i for i in z.infolist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',i.filename)]
70
- 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)]
71
- assert all(n.startswith('__MACOSX/') or Path(n).name.startswith('._') for n in extra),(p,extra[:5])
72
- cams=sorted({i.filename.split('/')[0] for i in im},key=int)
73
- counts={c:sum(i.filename.startswith(c+'/') for i in im) for c in cams}
74
- b=sum(i.file_size for i in im)
75
- assert cams,(seq,counts)
76
- rows.append({'sequence':seq,'sequence_id':seq.replace('/','_'),'object':seq.split('/')[1].split('_')[0],
77
- 'cameras':cams,'frames_per_camera':counts,'jpeg_bytes':b,'split':next((k for k,v in splits.items() if seq in v),'unknown'),
78
- 'inputs':['raw_seqs.zip','meta.zip','splits_json.zip','images_zips/'+seq+'.zip']})
79
- budget=sum(r['jpeg_bytes'] for r in rows)+160_000_000_000
80
- else:
81
- for p in sorted((base/'raw/data/Aria').iterdir()):
82
- if not p.is_dir():continue
83
- gt=next(p.glob('*ground_truth.zip'));hz=next(p.glob('*hand_data.zip'));vrs=next(p.glob('*.vrs'))
84
- with zipfile.ZipFile(gt) as z:
85
- m=json.loads(z.read('metadata.json'));cams=json.loads(z.read('camera_models.json'))
86
- assert m['headset']=='Aria'
87
- hasgt=m['have_hand_object_pose_gt'];split='test' if m['participant_id'] in TEST_IDS else 'train';assert hasgt==(split=='train')
88
- if hasgt:assert 'masks/mask_qa_pass.csv' in z.namelist()
89
- with zipfile.ZipFile(hz) as z:mano_bytes=z.getinfo('mano_hand_pose_trajectory.jsonl').file_size
90
- assert hasgt or mano_bytes==0
91
- rows.append({'sequence':p.name,'sequence_id':p.name,'cameras':[c['stream_id'] for c in cams],'split':split,
92
- '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]]})
93
- # Includes persistent extracted JPEGs, current media spool, meshes, tensors and reports.
94
- budget=sum(r['vrs_bytes'] for r in rows)*3+150_000_000_000
95
- assert len(rows)==(339 if ds=='ARCTIC' else 198)
96
- 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}
97
- print('PLAN',ds,len(rows),out['datasets'][ds]['views'],budget,flush=True)
98
- out['free_bytes_at_plan']=shutil.disk_usage(DATA_ROOT).free
99
- out['additional_peak_budget_bytes']=sum(v['additional_budget_bytes'] for v in out['datasets'].values())
100
- assert out['free_bytes_at_plan']-out['additional_peak_budget_bytes']>=RESERVE,out
101
- atomic(CONTROL/'plan.json',out)
102
- return out
103
-
104
- def approve():
105
- p=load(CONTROL/'plan.json');confirmation={'confirmed_at':now(),'user_statement':'HOT3D和ARCTIC我都确认了,可以开始做预处理了。',
106
- 'scope':'Reviewed pilots accepted; full preprocessing authorized for ARCTIC and HOT3D Aria only',
107
- 'full_preprocessing_authorized':True,'full_output_review':'pending','upload_authorized':False,'raw_retention':True}
108
- atomic(CONTROL/'authorization.json',confirmation)
109
- state=load(WORK/'tmp/dataset-work-state.json')
110
- for ds in p['order']:
111
- root=DATA_ROOT/ds/RELEASE;doc=root/'doc/validation'
112
- atomic(doc/'pilot-human-confirmation.json',confirmation)
113
- for rp in [doc/'report.json',*sorted((doc/'objects').glob('*/report.json')),*([doc/'objects/report.json'] if (doc/'objects/report.json').exists() else [])]:
114
- r=load(rp);r.update(human_review='approved',full_preprocessing_authorized=True,upload_authorized=False,pilot_confirmation=confirmation)
115
- atomic(rp,r)
116
- for page in [doc/'index.html',*sorted((doc/'objects').rglob('index.html'))]:
117
- if not page.exists():continue
118
- s=page.read_text(encoding='utf-8')
119
- s=s.replace('人工确认待完成','试点人工确认已通过;全量产物待单独验收').replace('用户人工确认待完成','用户试点确认已通过').replace('用户确认前不全量处理','用户已确认试点,允许全量预处理')
120
- if 'id="production-authorization"' not in s:
121
- s=s.replace('<header>','<header><p id="production-authorization" style="color:#176b3a"><strong>用户已确认本页试点,授权全量预处理。</strong> 全量完成后另行随机抽查;尚未授权上传。</p>',1)
122
- page.write_text(s,encoding='utf-8')
123
- if (doc/'objects/artifact-manifest.json').exists():
124
- mp=doc/'objects/artifact-manifest.json';a=load(mp)
125
- for f in a['files']:
126
- file=mp.parent/f['path'];f.update(size=file.stat().st_size,sha256=digest(file))
127
- atomic(mp,a)
128
- for meta in (root/'data').glob('*/*/metainfo.json'):
129
- m=load(meta);m['pilot_human_review']='approved';m['full_preprocessing_authorized']=True
130
- 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')
131
- atomic(meta,m)
132
- state['active'][ds].update(stage='full_preprocessing_queued',human_sample_review='approved',full_preprocessing_authorized=True,upload_authorized=False,
133
- production_plan=str(CONTROL/'plan.json'),full_sequence_count=p['datasets'][ds]['count'],full_view_count=p['datasets'][ds]['views'])
134
- atomic(doc/'status.json',{'stage':'full_preprocessing_queued','pilot_review':'approved','full_output_review':'pending','upload_authorized':False})
135
- docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
136
- atomic(docprod/'plan.json',p['datasets'][ds])
137
- (docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
138
- for f in ['preprocess_fresh_full.py','convert_fresh_sequence_pilots.py','apply_hot3d_qa.py','review_fresh_sequence_pilots.py','render_full_sequence_review.py','fresh_sequence_common.py','diagnose_arctic_review.py']:
139
- shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
140
- atomic(WORK/'tmp/dataset-work-state.json',state)
141
-
142
- def official_arctic_check(row,views):
143
- base=DATA_ROOT/'ARCTIC';seq=row['sequence'];oid=row['object'];sid=seq.split('/')[0]
144
- if row['split']=='test':
145
- with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:
146
- assert all(f'raw_seqs/{seq}.{x}.npy' not in z.namelist() for x in ['mano','object','egocam.dist'])
147
- for p in views:
148
- m=load(p/'metainfo.json');assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
149
- if p.name=='0':assert 'intrinsic' not in m['components'] and 'extrinsic' not in m['components'] and m['camera']['schema_id'] is None
150
- return {'passed':True,'test':'official_held_out_test_ground_truth_omitted; static_mesh_metres_and_part_ids_checked_per_view','source_gt_available':False}
151
- with zipfile.ZipFile(base/'raw/data/meta.zip') as z:
152
- 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
153
- 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']
154
- with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'))
155
- world=[];kp=[]
156
- for start in range(0,len(objects),32):
157
- v,k=official_object(objects[start:start+32],verts,parts,params,oid);world.append(v);kp.append(k)
158
- world=np.concatenate(world);kp=np.concatenate(kp);worst=0.;checked=0
159
- for p in views:
160
- 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
161
- 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')
162
- assert np.array_equal(ids,1-parts)
163
- for i in np.flatnonzero(valid):
164
- 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]
165
- 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]
166
- 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
167
- assert worst<2e-5,(seq,worst)
168
- 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}
169
-
170
- def worker(ds,seq):
171
- plan=load(CONTROL/'plan.json');row=next(r for r in plan['datasets'][ds]['sequences'] if r['sequence']==seq)
172
- assert load(CONTROL/'authorization.json')['full_preprocessing_authorized']
173
- base=DATA_ROOT/ds;root=base/RELEASE;tmp=temporary(ds);result=tmp/'completed'/f'{row["sequence_id"]}.json';records=inputs(ds)
174
- source_files=list(row['inputs'])
175
- if ds=='HOT3D':source_files+=sorted(rel for rel in records if rel.startswith('assets/'))
176
- source=[check_input(ds,rel,records) for rel in source_files]
177
- if result.exists() and load(result).get('scripts'):
178
- assert load(result)['scripts']==code_manifest(),'Converter code changed since checkpoint; explicit revalidation is required'
179
- if result.exists() and load(result).get('scripts')==code_manifest():
180
- done=load(result)
181
- assert done['source']==source
182
- for f in done['files']:
183
- p=root/f['path'];assert p.stat().st_size==f['size'] and digest(p)==f['sha256'],p
184
- print('VERIFIED_RESUME',ds,seq,flush=True);return
185
- assert shutil.disk_usage(base).free>RESERVE+15_000_000_000,'Disk reserve reached'
186
- 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')}
187
- if ds=='ARCTIC':arctic(seq,initialize=False)
188
- else:
189
- hot3d(seq,initialize=False);verify_hot3d_frame_order_and_metadata(seq)
190
- if row['source_gt_available']:apply_qa(seq,publish=False)
191
- views=[root/'data'/row['sequence_id']/cam for cam in row['cameras']]
192
- results=[]
193
- for p in views:
194
- 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)
195
- if p.name in reused:
196
- media=next(x for x in r['conversion_checks'] if x['test']=='all_source_JPEG_packets_and_RGB_pixels_exact')
197
- for copy,key in [(True,'packet_manifest_sha256'),(False,'pixel_manifest_sha256')]:
198
- actual=framehash(['-i',str(p/'observation/rgb.mkv')],copy=copy)
199
- assert len(actual)==m['num_frames'] and hashlib.sha256(json.dumps(actual).encode()).hexdigest()==media[key],(p,'reused media changed',key)
200
- r['reused_media_revalidated']=True
201
- if ds=='HOT3D' and not row['source_gt_available']:
202
- assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
203
- atomic(p/'metainfo.json',m);results.append(r)
204
- 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']}
205
- files=[]
206
- for p in sorted((root/'data'/row['sequence_id']).rglob('*')):
207
- if p.is_file():files.append({'path':p.relative_to(root).as_posix(),'size':p.stat().st_size,'sha256':digest(p)})
208
- done={'dataset':ds,'sequence':seq,'sequence_id':row['sequence_id'],'completed_at':now(),'source':source,'scripts':code_manifest(),'views':results,'independent_geometry':independent,
209
- 'files':files,'bytes':sum(f['size'] for f in files),'frames':sum(v['frames'] for v in results),'full_output_human_review':'pending','upload_authorized':False}
210
- atomic(root/'doc/validation/full/sequences'/f'{row["sequence_id"]}.json',done);atomic(result,done)
211
- print('SEQUENCE_COMPLETE',ds,seq,done['frames'],done['bytes'],flush=True)
212
-
213
- def random_review(ds,rows):
214
- from render_full_sequence_review import render_view,asset_preview
215
- doc=DATA_ROOT/ds/RELEASE/'doc/validation/full_random';doc.mkdir(parents=True,exist_ok=True);rng=random.Random(20260920);selected=[]
216
- if ds=='ARCTIC':
217
- for oid in sorted({r['object'] for r in rows}):
218
- 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)))
219
- if not any(c=='0' for _,c,_,_ in selected):
220
- 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)))
221
- for split in ['train','val','test']:
222
- if not any(r['split']==split for r,_,_,_ in selected):
223
- 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)))
224
- else:
225
- for split in ['train','test']:
226
- group=[r for r in rows if r['split']==split];r=rng.choice(group)
227
- for cam in r['cameras']:selected.append((r,cam,'split:'+split,len(group)))
228
- 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.',
229
- '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]}
230
- atomic(doc/'sampling.json',sampling);cards=[];results=[];assets={}
231
- for row,cam,_,_ in selected:
232
- 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)}
233
- atomic(temporary(ds)/'status.json',st);atomic(CONTROL/'status.json',st)
234
- 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
235
- qfile=DATA_ROOT/ds/'tmp'/RUN/'qa'/f'{row["sequence_id"]}.json'
236
- if ds=='HOT3D' and row['source_gt_available']:
237
- if not qfile.exists():apply_qa(row['sequence'],publish=False)
238
- qa=load(qfile)
239
- result=render_view(p,ds,qa,doc=sub,tmp=tmp);results.append(result)
240
- for op in (p/'annotation/object').glob('*'):
241
- out=sub/'assets'/f'{op.name}.mp4'
242
- if not out.exists():asset_preview(op,out)
243
- assets[out.relative_to(doc).as_posix()]=row['sequence_id']+' / '+op.name
244
- 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>')
245
- for ref,label in assets.items():cards.append(f'<section><h2>物体资产 · {label}</h2><video controls preload="metadata" src="{ref}"></video></section>')
246
- atomic(doc/'report.json',{'dataset':ds,'sampling':sampling,'views':results,'asset_previews':assets,'human_review':'pending','upload_authorized':False})
247
- (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')
248
- (doc/'REPORT.md').write_text('# 全量随机抽查\n\n[离线完整序列](index.html) · [抽样定义](sampling.json) · [模态检查](report.json)\n\n人工确认待完成。源缺失模态缺省,不以数值通过替代视觉质量确认。\n',encoding='utf-8')
249
-
250
- def run():
251
- CONTROL.mkdir(parents=True,exist_ok=True);guard=(CONTROL/'process.lock').open('a+b');guard.seek(0)
252
- try:msvcrt.locking(guard.fileno(),msvcrt.LK_NBLCK,1)
253
- except OSError:raise RuntimeError('Another production queue owns the lock')
254
- assert load(CONTROL/'authorization.json')['full_preprocessing_authorized'];p=load(CONTROL/'plan.json')
255
- power=ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
256
- try:
257
- for ds in p['order']:
258
- snapshot_scripts(ds)
259
- rows=p['datasets'][ds]['sequences'];tmp=temporary(ds);tmp.mkdir(parents=True,exist_ok=True)
260
- # Smaller full sequences first; sequence boundaries remain unchanged.
261
- rows=sorted(rows,key=lambda r:r.get('jpeg_bytes',r.get('vrs_bytes',0)))
262
- for n,row in enumerate(rows):
263
- st={'stage':'converting','dataset':ds,'sequence':row['sequence'],'completed_sequences':n,'total_sequences':len(rows),'pid':os.getpid(),'time':now()}
264
- atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
265
- 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)
266
- assert shutil.disk_usage(DATA_ROOT).free>RESERVE+15_000_000_000,'Disk reserve reached'
267
- log=tmp/'logs'/f'{row["sequence_id"]}.log';log.parent.mkdir(parents=True,exist_ok=True)
268
- with log.open('ab') as out:
269
- child=subprocess.Popen([sys.executable,'-u',str(SCRIPT),'worker','--dataset',ds,'--sequence',row['sequence']],stdout=out,stderr=subprocess.STDOUT)
270
- while child.poll() is None:
271
- st.update(worker_pid=child.pid,time=now(),log=str(log));atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
272
- if shutil.disk_usage(DATA_ROOT).free<RESERVE:child.terminate();child.wait();raise RuntimeError('Disk reserve reached; active sequence stopped, raw retained')
273
- time.sleep(20)
274
- if child.returncode:raise RuntimeError(f'Worker failed: {ds} {row["sequence"]}; see {log}')
275
- print('QUEUE_PROGRESS',ds,n+1,len(rows),row['sequence'],flush=True)
276
- st={'stage':'generating_full_random_review','dataset':ds,'pid':os.getpid(),'time':now(),'completed_sequences':len(rows),'total_sequences':len(rows)}
277
- atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
278
- 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)
279
- random_review(ds,rows)
280
- 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)
281
- 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')})
282
- atomic(CONTROL/'status.json',{'stage':'all_preprocessing_complete_awaiting_full_random_review','time':now(),'upload_authorized':False})
283
- except BaseException as e:
284
- error={'stage':'failed_needs_attention','time':now(),'error':str(e),'dataset':locals().get('ds'),'sequence':locals().get('row',{}).get('sequence')}
285
- atomic(CONTROL/'status.json',error)
286
- if 'ds' in locals():atomic(temporary(ds)/'status.json',error)
287
- raise
288
- finally:ctypes.windll.kernel32.SetThreadExecutionState(0x80000000);guard.close()
289
-
290
- if __name__=='__main__':
291
- ap=argparse.ArgumentParser();ap.add_argument('mode',choices=['plan','approve','worker','run']);ap.add_argument('--dataset',choices=['ARCTIC','HOT3D']);ap.add_argument('--sequence');a=ap.parse_args()
292
- if a.mode=='worker':
293
- CONTROL.mkdir(parents=True,exist_ok=True)
294
- with (CONTROL/'worker.lock').open('a+b') as lock:
295
- lock.seek(0)
296
- try:msvcrt.locking(lock.fileno(),msvcrt.LK_NBLCK,1)
297
- except OSError:raise RuntimeError('A production worker is already active; refusing overlapping conversion')
298
- worker(a.dataset,a.sequence)
299
- elif a.mode=='plan':plan()
300
- elif a.mode=='approve':approve()
301
- else:run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/review_fresh_sequence_pilots.py DELETED
@@ -1,221 +0,0 @@
1
- """Validate actual shared outputs and create portable, offline pilot reviews.
2
-
3
- Run after convert_fresh_sequence_pilots.py. Never authorizes full processing.
4
- """
5
- from fresh_sequence_common import *
6
- import html
7
- from datetime import datetime
8
-
9
- def arr(p):
10
- value=torch.load(p,map_location='cpu',weights_only=True)
11
- assert isinstance(value,torch.Tensor) and value.device.type=='cpu'
12
- return value.numpy()
13
-
14
- def safe_ref(root,ref):
15
- path=(root/ref).resolve()
16
- assert path.is_relative_to(root.resolve()) and path.is_file(),ref
17
- return path
18
-
19
- def validate_view(p):
20
- m=load(p/'metainfo.json');T=m['num_frames'];registry=load(WORK/'distribution/hand-warehouse-1.0/schema.json')
21
- assert m['schema_version']==registry['schema_version'] and m['pilot_complete']
22
- frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
23
- assert len(frames)==T and [f['frame_index'] for f in frames]==list(range(T))
24
- assert len({f['source_frame_id'] for f in frames})==T
25
- for frame in frames:
26
- for match in frame.get('annotation_matches',{}).values():
27
- if 'available' in match:match['source_record_present']=match.pop('available')
28
- lines(p/'camera/frames.jsonl',frames)
29
- summary=[]
30
- for key,c in m['components'].items():
31
- assert c['schema_id'] in registry['components'],(key,c['schema_id'])
32
- assert c['available'] and c['source_locator'] and c['provenance']['kind'] in ['source','derived','format_conversion']
33
- data=safe_ref(p,c['data_ref']);valid=arr(safe_ref(p,c['valid_ref']))
34
- assert valid.dtype==bool and valid.ndim==len(c['valid_axes'])
35
- if data.suffix=='.pt':
36
- a=arr(data);assert a.dtype==np.float32 and a.shape[0]==T
37
- assert a.shape[:valid.ndim]==valid.shape and len(c['axes'])==a.ndim
38
- assert np.isfinite(a[valid]).all() and np.isnan(a[~valid]).all()
39
- if c['schema_id'] in ['object/rigid/v1','transform/se3/v1']:assert_se3(a[valid])
40
- if c['schema_id']=='mano/axis_angle61/v1':assert a.shape==(T,2,61)
41
- elif data.suffix=='.mkv':
42
- assert c['storage']['profile'] in registry['storage_profiles']
43
- assert valid.shape==(T,) and valid.all()
44
- for attr in c.get('attributes',{}).values():
45
- a=arr(safe_ref(p,attr['data_ref']));b=arr(safe_ref(p,attr['valid_ref']))
46
- assert b.dtype==bool and a.shape==b.shape
47
- assert np.isfinite(a[b]).all() and ((a[b]>=0)&(a[b]<=1)).all() and np.isnan(a[~b]).all()
48
- if 'distortion_ref' in c:
49
- d=arr(safe_ref(p,c['distortion_ref']));assert d.shape==(T,8) and np.isfinite(d).all()
50
- summary.append({'component':key,'schema':c['schema_id'],'valid':int(valid.sum()),'total':int(valid.size)})
51
- for op in sorted((p/'annotation/object').glob('*')):
52
- om=load(op/'metainfo.json');mesh=safe_ref(p,om['mesh_ref'])
53
- if 'vertex_part_ids_ref' in om:
54
- ids=arr(safe_ref(p,om['vertex_part_ids_ref']));assert ids.dtype==np.int64
55
- assert len(ids)==sum(line.startswith('v ') for line in mesh.read_text().splitlines())
56
- assert om['topology_id']=='sha256:'+digest(mesh)
57
- if not (op/'pose.pt').exists():
58
- assert m.get('omitted_components',{}).get('object_pose')
59
- else:
60
- root=arr(op/'pose.pt');top=arr(op/'parts/top/pose.pt');joint=arr(op/'joint_state.pt')[:,0]
61
- ok=arr(op/'pose_valid.pt');H=np.broadcast_to(np.eye(4),(ok.sum(),4,4)).copy()
62
- H[:,:3,:3]=Rotation.from_rotvec(np.c_[np.zeros((ok.sum(),2)),-joint[ok]]).as_matrix()
63
- if ok.any():assert np.max(np.abs(root[ok]@H-top[ok]))<2e-6
64
- for obj in (op/'assets').glob('*.obj'):
65
- for row in obj.read_text().splitlines():
66
- if row.startswith('mtllib '):
67
- material=safe_ref(obj.parent,row.split(maxsplit=1)[1])
68
- for r in material.read_text().splitlines():
69
- if r.lower().startswith('map_kd '):safe_ref(material.parent,r.split(maxsplit=1)[1])
70
- records=load(DATA_ROOT/m['dataset_id']/'tmp'/RUN/'checks'/f'{m["sequence_id"]}__{m["camera_id"]}.json')['checks']
71
- assert records and all(x.get('passed',False) for x in records)
72
- media=next(r for r in records if r['test']=='all_source_JPEG_packets_and_RGB_pixels_exact');assert media['frames']==T
73
- if 'mano' not in m['components']:
74
- assert m.get('omitted_components',{}).get('mano')
75
- assert not (p/'annotation/mano/motion.pt').exists()
76
- return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed','mano':'source modality absent, omitted'}
77
- actual=arr(p/'annotation/mano/motion_valid.pt')
78
- if m['dataset_id']=='HOT3D':
79
- src=m['components']['mano']['source_locator']
80
- with zipfile.ZipFile(DATA_ROOT/'HOT3D'/src['archive']) as z:
81
- native={r['timestamp_ns']:r['hand_poses'] for r in map(json.loads,z.read(src['member']).splitlines())}
82
- expected=np.array([[str(side) in native.get(f['annotation_matches']['mano']['source_timestamp_ns'],{}) for side in range(2)] for f in frames],bool)
83
- else:expected=np.array([[f['source_annotation_index'] is not None]*2 for f in frames],bool)
84
- if m['dataset_id']=='HOT3D' and m['components']['mano'].get('valid_policy'):
85
- source=m['components']['mano']['valid_policy']['source_locator']
86
- with zipfile.ZipFile(DATA_ROOT/'HOT3D'/source['archive']) as z:
87
- lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in csv.DictReader(io.StringIO(z.read(source['member']).decode())) if r['stream_id']==m['camera_id']}
88
- qa=[lookup[f['timecode_ns']] for f in frames]
89
- expected &= np.array(qa,bool)[:,None]
90
- if m['dataset_id']=='ARCTIC':
91
- rejected=m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices',[])
92
- expected[rejected]=False
93
- assert np.array_equal(expected,actual),'annotation validity disagrees with declared source and QA/local policy'
94
- records.append({'test':'all_frame_source_annotation_and_QA_policy','passed':True,'left_right_valid_counts':actual.sum(0).tolist(),'frames_without_usable_hand':int((~actual.any(1)).sum())})
95
- return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed'}
96
-
97
- def select_images(p,indices,dest):
98
- dest.mkdir(parents=True,exist_ok=True)
99
- selection='+'.join(f'eq(n,{i})' for i in indices)
100
- command([FF,'-v','error','-y','-threads','2','-noautorotate','-i',p/'observation/rgb.mkv',
101
- '-vf',f"select='{selection}',scale=900:900:force_original_aspect_ratio=decrease",'-fps_mode','vfr',dest/'decoded-%03d.png'])
102
- output=sorted(dest.glob('decoded-*.png'));assert len(output)==len(indices)
103
- return dict(zip(indices,output))
104
-
105
- def project_for_view(points,m,params,scale):
106
- uv=project_points(points,m['camera']['model'],params)
107
- if m['camera']['model']=='fisheye624':
108
- angle=np.arctan2(np.linalg.norm(points[:,:2],axis=1),points[:,2])
109
- uv[angle>m['camera']['max_solid_angle']]=np.nan
110
- return uv*scale
111
-
112
- def draw_edges(canvas,uv,edges,color):
113
- H,W=canvas.shape[:2]
114
- for a,b in edges:
115
- xy=uv[[a,b]]
116
- if not np.isfinite(xy).all():continue
117
- if np.max(np.abs(xy))>max(W,H)*20:continue
118
- xy=np.rint(xy).astype(int)
119
- if np.linalg.norm(xy[0]-xy[1])>max(W,H)*.35:continue
120
- ok,start,end=cv2.clipLine((0,0,W,H),tuple(xy[0]),tuple(xy[1]))
121
- if ok:cv2.line(canvas,start,end,color,1,cv2.LINE_AA)
122
-
123
- def review_view(p,m,frames,dest):
124
- T=m['num_frames'];indices=sorted(set([0,1,T//4,T//2,3*T//4,T-1]));imgs=select_images(p,indices,dest)
125
- K=arr(p/'camera/intrinsic.pt');D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None
126
- motion=arr(p/'annotation/mano/motion.pt');valid=arr(p/'annotation/mano/motion_valid.pt');models=[Mano('left'),Mano('right')]
127
- if m['components']['mano']['model_profile']['left_shapedirs_fix']:
128
- models[0].data['shapedirs'][:,0]*=-1
129
- with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
130
- objects=[]
131
- for op in sorted((p/'annotation/object').iterdir()):
132
- om=load(op/'metainfo.json');mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
133
- if 'vertex_part_ids_ref' in om:
134
- vertices=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 ')])
135
- # trimesh may split OBJ vertices along UV seams; render exact source-ordered vertices as points.
136
- objects.append((op,om,vertices,None,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),arr(p/om['vertex_part_ids_ref']),arr(op/'parts/top/pose.pt')))
137
- else:
138
- edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//2500)]
139
- objects.append((op,om,np.asarray(mesh.vertices),edges,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),None,None))
140
- records=[]
141
- for i,source in imgs.items():
142
- original=np.asarray(Image.open(source).convert('RGB'));overlay=original.copy()
143
- scale=np.array([original.shape[1]/m['camera']['image_size'][0],original.shape[0]/m['camera']['image_size'][1]])
144
- params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
145
- for side,model in enumerate(models):
146
- if not valid[i,side]:continue
147
- h=motion[i,side];vertices,_,_=model.geometry(h[:48],h[48:58],h[58:]);uv=project_for_view(vertices[0],m,params,scale)
148
- faces=np.asarray(model.layer.faces);edges=np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]);draw_edges(overlay,uv,edges,(0,235,255) if side==0 else (255,135,20))
149
- palette=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
150
- for c,(op,om,vertices,edges,P,ok,parts,top) in enumerate(objects):
151
- if not ok[i]:continue
152
- xyz=vertices@P[i,:3,:3].T+P[i,:3,3]
153
- if parts is not None:xyz[parts==1]=vertices[parts==1]@top[i,:3,:3].T+top[i,:3,3]
154
- uv=project_for_view(xyz,m,params,scale)
155
- if edges is not None:draw_edges(overlay,uv,edges,palette[c%len(palette)])
156
- else:
157
- for xy in uv[::max(1,len(uv)//6000)]:
158
- if np.isfinite(xy).all() and 0<=xy[0]<overlay.shape[1] and 0<=xy[1]<overlay.shape[0]:cv2.circle(overlay,tuple(np.rint(xy).astype(int)),1,palette[c%len(palette)],-1)
159
- blended=cv2.addWeighted(overlay,.8,original,.2,0);output=dest/f'frame-{i:06d}-overlay.png';raw=dest/f'frame-{i:06d}-rgb.png'
160
- Image.fromarray(blended).save(output);source.replace(raw)
161
- records.append({'frame_index':i,'source_frame_id':frames[i]['source_frame_id'],'rgb':raw.name,'overlay':output.name,'mano_valid':valid[i].tolist()})
162
- return records
163
-
164
- def write_reports(dataset,views):
165
- base=DATA_ROOT/dataset;root=base/RELEASE;doc=root/'doc';review=doc/'validation';reports=[];cards=[];thumbs=[]
166
- rawpaths=set()
167
- for p in views:
168
- if dataset=='ARCTIC':
169
- for assets in (p/'annotation/object').glob('*/assets'):repair_arctic_material_refs(assets)
170
- m,frames,summary=validate_view(p);cam=m['camera_id'];samples=review_view(p,m,frames,review/'images'/cam)
171
- summary['visual_samples']=samples;reports.append(summary)
172
- # All actually consumed source files; camera/mano/object locators name source archives.
173
- rawpaths.add(m['components']['rgb']['source_locator'].get('archive',m['components']['rgb']['source_locator'].get('file')))
174
- for comp in m['components'].values():
175
- src=comp['source_locator']
176
- if 'archive' in src:rawpaths.add(src['archive'])
177
- if dataset=='ARCTIC':rawpaths.add('raw/data/splits_json.zip')
178
- for op in (p/'annotation/object').iterdir():
179
- glb=load(op/'metainfo.json').get('original_glb_ref')
180
- if glb:rawpaths.add(load(op/'metainfo.json')['original_glb_source_locator']['file'])
181
- opts=''.join(f'<option value="{i}"'+(' selected' if s['frame_index']==m['num_frames']//2 else '')+f'>index {s["frame_index"]} · source {s["source_frame_id"]} · valid {s["mano_valid"]}</option>' for i,s in enumerate(samples))
182
- samples_js=json.dumps([{k:(f'images/{cam}/'+s[k] if k in ('rgb','overlay') else s[k]) for k in s} for s in samples])
183
- cards.append(f'<section class="card" data-samples=\'{html.escape(samples_js,quote=True)}\'><h2>Camera {cam} · {m["camera"]["model"]} · {m["num_frames"]} 帧</h2><select onchange="show(this.closest(\'.card\'))">{opts}</select><label><input type="checkbox" checked onchange="show(this.closest(\'.card\'))"> 显示投影</label><br><a class="zoom" target="_blank"><img alt="共享产物实际帧与投影"></a><p class="caption"></p></section>')
184
- middle=samples[len(samples)//2];thumb=Image.open(review/'images'/cam/middle['overlay']).convert('RGB');thumb.thumbnail((400,320));tile=Image.new('RGB',(420,355),'#18202b');tile.paste(thumb,((420-thumb.width)//2,28));ImageDraw.Draw(tile).text((10,8),f'{dataset} camera {cam} / frame {middle["frame_index"]}',fill='white');thumbs.append(tile)
185
- print('REVIEWED',dataset,cam,flush=True)
186
- cols=3;grid=Image.new('RGB',(cols*420,((len(thumbs)+cols-1)//cols)*355),'#18202b')
187
- for i,t in enumerate(thumbs):grid.paste(t,((i%cols)*420,(i//cols)*355))
188
- grid.save(review/'overview.png')
189
- source_manifest=[]
190
- ledger=load(base/'raw/doc'/('archive_checksums.json' if dataset=='ARCTIC' else 'file_checksums.json'))
191
- for rel in sorted(x for x in rawpaths if x):
192
- file=base/rel;sha=digest(file);record=ledger[rel.removeprefix('raw/data/')]
193
- assert record['sha256']==sha and record['size']==file.stat().st_size
194
- assert record.get('official_sha256_match',record.get('official_digest_match')) is True
195
- if file.suffix=='.zip':assert record['zip_crc']=='passed_all_members'
196
- if dataset=='HOT3D':assert record['fresh_download_run']=='2026-09-18-aria-fresh'
197
- source_manifest.append({'path':rel,'bytes':file.stat().st_size,'sha256':sha,'matches_verified_official_download':True,'zip_crc_at_download':record.get('zip_crc')})
198
- save(doc/'pilot-source-manifest.json',source_manifest)
199
- script_manifest=[]
200
- for name in ['review_fresh_sequence_pilots.py','fresh_sequence_common.py','convert_fresh_sequence_pilots.py']:
201
- shutil.copyfile(WORK/'scripts'/name,root/'script'/name)
202
- for p in sorted((root/'script').glob('*.py')):script_manifest.append({'path':p.relative_to(root).as_posix(),'sha256':digest(p)})
203
- full={'dataset':dataset,'stage':'pilot_awaiting_human_review','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False,
204
- 'scope':'One complete selected sequence, every released camera frame; not full-dataset acceptance','views':reports,
205
- 'sources_manifest':'../pilot-source-manifest.json','script_manifest':script_manifest,'preview_selection':'Deterministic boundary and quartile samples per camera; not random or full-dataset review',
206
- 'preview_rendering':'Derived MANO/object projections from shared tensors, not segmentation ground truth; no depth occlusion test, hidden surfaces may be drawn',
207
- 'created_at':datetime.now().astimezone().isoformat()}
208
- save(review/'report.json',full);save(review/'status.json',{k:full[k] for k in ['dataset','stage','human_review','full_preprocessing_authorized','upload_authorized']})
209
- notes=('首帧 RGB 存在,动捕标注无对应项,valid=false;已保留。相机 0 使用 rational8 畸变,外部八相机使用官方针孔投影。关节绕父坐标系 -Z 轴旋转,部件点/网格保持米制。' if dataset=='ARCTIC' else 'Aria 三路相机均保留;RGB 与两路灰度均由原 JPEG 直接封装。device time 经官方映射对齐 timecode;原始 visibility 按百分比转 [0,1],独立于标注 valid。三路按时间匹配,不假定相同行号自动同步。')
210
- if dataset=='HOT3D':notes+=' 每相机双手各806帧有MANO、208帧原始手参数为空;画面中有手但无投影的末尾帧属于源标注缺失,已验证并保留为valid=false。'
211
- if dataset=='ARCTIC':notes+=' 原始部件OBJ的材质文件名引用错误已在共享层修正为实际存在的material.mtl,材质标识与纹理不变。'
212
- missing=('本次官方 raw 中无独立深度、像素分割、接触标签、实测手关键点数组。保留 MANO,供任务层按需生成关键点;未把预览投影写成新增标注。' if dataset=='ARCTIC' else '本范围无深度流或像素分割;masks/*.csv 是帧筛选条件,不能当作像素 mask。UmeTrack 与 MPS 替代估计保留在 raw;shared 选择 MANO 和官方 GT 相机。没有额外生成关键点或接触标签。')
213
- text=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 序列试点审核</title><style>body{{font:16px/1.65 system-ui;background:#f3f5f8;color:#18202b;max-width:1450px;margin:24px auto;padding:0 20px}}header,.card{{background:white;padding:22px;border-radius:14px;margin-bottom:18px}}.status{{color:#9a5800;font-weight:bold}}.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(360px,1fr));gap:18px}}.card img{{max-width:100%;max-height:670px;margin-top:12px}}select{{max-width:100%;padding:8px}}a{{color:#1766ab}}label{{display:inline-block;margin:10px}}h1{{margin:0}}.caption{{font-size:14px}}</style><header><h1>{dataset} · 完整序列试点</h1><p class="status">自动校验已完成;人工审核待确认。尚未开始全量预处理或上传。</p><p>共 {len(views)} 路相机、{sum(r['frames'] for r in reports):,} 个相机帧。全部源 JPEG 码流、全部解码 RGB 帧已逐一比较一致;数值转换、有效性和引用检查通过。</p><p>{notes}</p><p>{missing}</p><p>下方是从 shared 实际产物读取的边界及四分位样本。青色=左手,橙色=右手,其余颜色=物体。投影仅用于几何核验,<b>不是源分割,也没有做遮挡剔除</b>。点击图像可放大;取消勾选可查看原图。</p><p><a href="REPORT.md">验收说明</a> · <a href="report.json">机器可读结果</a> · <a href="../RAW_TO_SHARED.md">raw → share 对照</a> · <a href="../CONTRACT.md">约定</a> · <a href="overview.png">全部相机总览</a></p></header><main class="grid">{''.join(cards)}</main><script>function show(card){{let s=JSON.parse(card.dataset.samples)[Number(card.querySelector('select').value)];let path=card.querySelector('input').checked?s.overlay:s.rgb;card.querySelector('img').src=path;card.querySelector('.zoom').href=path;card.querySelector('.caption').textContent='frame_index='+s.frame_index+' / 原帧 '+s.source_frame_id+' / 左右手 valid='+s.mano_valid;}}document.querySelectorAll('.card').forEach(show)</script></html>'''
214
- (review/'index.html').write_text(text,encoding='utf-8')
215
- rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | '+', '.join(str(x['frame_index']) for x in r['visual_samples'])+' | 通过 |' for r in reports)
216
- report=f'''# {dataset} 完整序列试点验收\n\n状态:**自动检查通过,人工确认待完成**。本报告不是全量验收或发布许可。\n\n[离线预览](index.html) · [机器结果](report.json) · [原始包摘要](../pilot-source-manifest.json)\n\n| 相机 | 全序列帧数 | 可视化帧索引 | 自动校验 |\n|---|---:|---|---|\n{rows}\n\n## 已验证\n\n- 完整所选序列的每一张源 JPEG 与 MKV 取回的压缩包 SHA256 相同;全部帧在同一 FFmpeg/noautorotate/rgb24 配置下解码字节相同,顺序和数量一致。不是有损重编码。\n- 全部有效 MANO 帧的相机坐标变换与直接变换几何一致;独立源模型配置抽样校验非平手均值/PCA 展开。张量 float32 保存读取一致,invalid 为 NaN,valid 为 bool。\n- SE(3) 正交性、单位与资产引用检查;ARCTIC 部件关节运动与源旋转公式逐帧对照,HOT3D 物体 OBJ 尺度、三角形及纹理像素往返一致。\n- 所有实际组件使用现有注册 schema;没有为缺省��态伪造值。\n\n## 帧对应和缺省范围\n\n{notes}\n\n{missing}\n\n## 人工核验边界\n\n每相机选序列起点、紧邻帧、四分位、中点、四分之三及终点,不是随机抽查。预览只用于核对几何对齐;投影线条/点不是分割真值,遮挡表面可能被画出。数值自洽不等于图像投影正确,请检查所有相机和多个时刻。此处一序列通过不能覆盖全数据集、其他物体或异常序列。全量处理后仍需独立随机抽查和用户发布确认。\n'''
217
- (review/'REPORT.md').write_text(report,encoding='utf-8')
218
- return full
219
-
220
- if __name__=='__main__':
221
- raise SystemExit('Static-sample review is retired. Use render_full_sequence_review.py DATASET and finalize_fresh_sequence_review.py; validate_view remains a reusable numeric helper.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/history/pre-acceleration-20260920/script-manifest.json DELETED
@@ -1,62 +0,0 @@
1
- {
2
- "created_at": "2026-09-20T13:24:10.057497+08:00",
3
- "scope": "Current production converter and validation scripts; earlier pilot manifests describe their historical run",
4
- "files": [
5
- {
6
- "path": "script/preprocess_fresh_full.py",
7
- "sha256": "a28ac6aaf5298a18980ea21ffed28c9537b9b43b239dd01a21e6e4c54146b1bf"
8
- },
9
- {
10
- "path": "script/convert_fresh_sequence_pilots.py",
11
- "sha256": "d6f378a15a89d54112543876697710f87a71f4adf0aafb487484f1bab65d5999"
12
- },
13
- {
14
- "path": "script/apply_hot3d_qa.py",
15
- "sha256": "7158b0512e59220930d88d04e15f7f6684acdccd0279f3179095d27b66ed3f7b"
16
- },
17
- {
18
- "path": "script/review_fresh_sequence_pilots.py",
19
- "sha256": "eb04564e0e2dacaca126b5f9a2333dc7232ef83b178c277b266f81c33bfa5815"
20
- },
21
- {
22
- "path": "script/render_full_sequence_review.py",
23
- "sha256": "5b471845025266f8a82dfebb185dda213bfbeaba8e98d0e6cc467826efa9e628"
24
- },
25
- {
26
- "path": "script/fresh_sequence_common.py",
27
- "sha256": "17bc18af25ee5c66a24c88d059cfffaea69e62227b7128394f2644f28311713b"
28
- },
29
- {
30
- "path": "script/diagnose_arctic_review.py",
31
- "sha256": "75a264b9b2cb4749e7705770a7e1141b860679b2fbee7d710e0414c83814802d"
32
- },
33
- {
34
- "path": "script/pilot_build.py",
35
- "sha256": "b45c92503fae4ee1d5163a52179b3bcb136338231096f100e721489e80cb0ac2"
36
- },
37
- {
38
- "path": "script/pilot_fetch.py",
39
- "sha256": "05ed8bc88df4492861ba46471906647a95e5392dd93f1a4eb419f2c396511e2d"
40
- },
41
- {
42
- "path": "script/pilot_mano.py",
43
- "sha256": "96ceb450b07bff040015072b6572e11af3aec310d54e575d2eb549da8d80bed0"
44
- },
45
- {
46
- "path": "script/sequence_pilot_common.py",
47
- "sha256": "9fdce711983c18be88f79fbbace8ed0e42fabb6a375cf167c98041a80a89579e"
48
- },
49
- {
50
- "path": "script/sequence_pilot_world.py",
51
- "sha256": "271c4829cae29af87c3fcb1b1668dfcab1df369aaabfc8a333de9965fb580126"
52
- },
53
- {
54
- "path": "script/pilot_hot_normalize.py",
55
- "sha256": "fea5bfaaac248a1f33bd799d837760cf23080a9efc1cf715436e2358825f433a"
56
- },
57
- {
58
- "path": "script/audit_source_fields.py",
59
- "sha256": "bdcc4818189a8f4bc74f75c2b507d2feec5c2d0b59040c69cd99ab86ba92eac5"
60
- }
61
- ]
62
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/{accelerated_media.py → internal/accelerated_media.py} RENAMED
File without changes
ARCTIC/shared-v1.0/script/{arctic_object_review.py → internal/arctic_object_review.py} RENAMED
File without changes
ARCTIC/shared-v1.0/script/{audit_source_fields.py → internal/audit_source_fields.py} RENAMED
File without changes
ARCTIC/shared-v1.0/script/{convert_fresh_sequence_pilots.py → internal/convert_fresh_sequence_pilots.py} RENAMED
@@ -97,7 +97,7 @@ def arctic(sequence=None,cameras=None,initialize=True):
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=None,source_fps_reason='Actual capture FPS not asserted by the selected raw files; frame indices and official synchronization offset retained',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()
@@ -166,6 +166,8 @@ def arctic(sequence=None,cameras=None,initialize=True):
166
  zimage.close();za.close()
167
 
168
  def vrs_records(path,cam):
 
 
169
  raw=command([VRS,'print-json',path,'+',cam,'+','data']).decode(errors='replace')
170
  rows=[]
171
  for line in raw.splitlines():
@@ -184,14 +186,18 @@ def verify_hot3d_frame_order_and_metadata(sequence=None):
184
  seq=sequence or HOT3D_SEQ
185
  base=DATA_ROOT/'HOT3D';src=base/'raw/data/Aria'/seq;recording=next(src.glob('*.vrs'))
186
  extract=base/'tmp'/RUN/seq/'images'
 
 
187
  for cam in ['214-1','1201-1','1201-2']:
188
  p=base/RELEASE/'data'/seq/cam;m=load(p/'metainfo.json');rows=vrs_records(recording,cam)
189
  paths=sorted(extract.glob(cam+'-*.jpg'))
190
  indices=[int(x.name.split('-')[-2]) for x in paths];assert indices==list(range(1,len(rows)+1))
191
  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
192
  assert np.max(np.abs(file_times-times))<.001,'extracted images do not match camera record ordering'
193
- raw=command([VRS,'print-json',recording,'+',cam,'+','configuration']).decode(errors='replace')
194
- 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]
 
 
195
  rate=cfg['nominal_rate'];assert abs(np.median(np.diff(times))-1/rate)<.001
196
  m['sampling']['source_fps']=rate
197
  m['sampling']['source_fps_basis']='VRS camera configuration nominal_rate; actual intervals checked separately'
@@ -221,7 +227,9 @@ def hot3d(sequence=None,initialize=True):
221
  if initialize:setup(dataset,seq)
222
  base=DATA_ROOT/dataset;raw=base/'raw/data';src=raw/'Aria'/seq;tmp=base/'tmp'/RUN
223
  recording=next(src.glob('*.vrs'));extract=tmp/seq/'images'
224
- if not (tmp/seq/'extracted.json').exists() or not extract.exists() or not any(extract.glob('*.jpg')):
 
 
225
  extract.mkdir(parents=True,exist_ok=True)
226
  log=tmp/seq/'vrs-extraction.log'
227
  with log.open('wb') as out:
 
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()
 
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():
 
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'
 
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:
ARCTIC/shared-v1.0/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.0/script/{diagnose_arctic_review.py → internal/diagnose_arctic_review.py} RENAMED
File without changes
ARCTIC/shared-v1.0/script/{finalize_arctic_objects_review.py → internal/finalize_arctic_objects_review.py} RENAMED
File without changes
ARCTIC/shared-v1.0/script/{fresh_sequence_common.py → internal/fresh_sequence_common.py} RENAMED
File without changes
ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_build.py RENAMED
File without changes
ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_fetch.py RENAMED
File without changes
ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_hot_normalize.py RENAMED
File without changes
ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/pilot_mano.py RENAMED
File without changes
ARCTIC/shared-v1.0/script/{preprocess_fresh_full.py → internal/preprocess_fresh_full.py} RENAMED
@@ -1,354 +1,355 @@
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=['preprocess_fresh_full.py','accelerated_media.py','convert_fresh_sequence_pilots.py','apply_hot3d_qa.py','review_fresh_sequence_pilots.py','render_full_sequence_review.py','fresh_sequence_common.py','diagnose_arctic_review.py','pilot_build.py','pilot_fetch.py','pilot_mano.py','sequence_pilot_common.py','sequence_pilot_world.py','pilot_hot_normalize.py','audit_source_fields.py']
32
-
33
- def code_manifest():
34
- return [{'path':'script/'+f,'sha256':digest(WORK/'scripts'/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
- for f in PRODUCTION_SCRIPTS:shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
79
- shutil.copyfile(CONTROL/'acceleration-config.json',root/'script/acceleration-config.json')
80
- atomic(root/'doc/validation/full/script-manifest.json',{'created_at':now(),'scope':'Current production converter and validation scripts; earlier pilot manifests describe their historical run','files':code_manifest()})
81
-
82
- def inputs(ds):
83
- base=DATA_ROOT/ds
84
- name='archive_checksums.json' if ds=='ARCTIC' else 'file_checksums.json'
85
- return load(base/'raw/doc'/name)
86
-
87
- def check_input(ds,rel,records):
88
- p=DATA_ROOT/ds/'raw/data'/rel;r=records[rel];st=p.stat()
89
- assert st.st_size==r['size'],f'Raw size changed: {p}'
90
- assert r.get('official_sha256_match',r.get('official_digest_match',False))
91
- if st.st_mtime_ns!=r['mtime_ns']:
92
- assert digest(p)==r['sha256'],f'Raw digest changed: {p}'
93
- if p.suffix=='.zip':
94
- with zipfile.ZipFile(p) as z:assert z.testzip() is None
95
- 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']}
96
-
97
- def plan():
98
- CONTROL.mkdir(parents=True,exist_ok=True);out={'created_at':now(),'order':['ARCTIC','HOT3D'],'datasets':{},'reserve_bytes':RESERVE}
99
- for ds in out['order']:
100
- base=DATA_ROOT/ds;records=inputs(ds)
101
- for rel in records:check_input(ds,rel,records)
102
- rows=[];auxiliary=[]
103
- if ds=='ARCTIC':
104
- with zipfile.ZipFile(base/'raw/data/splits_json.zip') as z:splits=json.loads(z.read('splits_json/protocol_p1.json'))
105
- for p in sorted((base/'raw/data/images_zips').rglob('*.zip')):
106
- seq=p.relative_to(base/'raw/data/images_zips').with_suffix('').as_posix()
107
- if '/' not in seq:
108
- assert seq=='backgrounds',seq
109
- auxiliary.append({'file':'raw/data/images_zips/backgrounds.zip','handling':'retain original archive in raw; background reference photographs are not hand-object capture sequences'})
110
- continue
111
- with zipfile.ZipFile(p) as z:
112
- im=[i for i in z.infolist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',i.filename)]
113
- 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)]
114
- assert all(n.startswith('__MACOSX/') or Path(n).name.startswith('._') for n in extra),(p,extra[:5])
115
- cams=sorted({i.filename.split('/')[0] for i in im},key=int)
116
- counts={c:sum(i.filename.startswith(c+'/') for i in im) for c in cams}
117
- b=sum(i.file_size for i in im)
118
- assert cams,(seq,counts)
119
- rows.append({'sequence':seq,'sequence_id':seq.replace('/','_'),'object':seq.split('/')[1].split('_')[0],
120
- 'cameras':cams,'frames_per_camera':counts,'jpeg_bytes':b,'split':next((k for k,v in splits.items() if seq in v),'unknown'),
121
- 'inputs':['raw_seqs.zip','meta.zip','splits_json.zip','images_zips/'+seq+'.zip']})
122
- budget=sum(r['jpeg_bytes'] for r in rows)+160_000_000_000
123
- else:
124
- for p in sorted((base/'raw/data/Aria').iterdir()):
125
- if not p.is_dir():continue
126
- gt=next(p.glob('*ground_truth.zip'));hz=next(p.glob('*hand_data.zip'));vrs=next(p.glob('*.vrs'))
127
- with zipfile.ZipFile(gt) as z:
128
- m=json.loads(z.read('metadata.json'));cams=json.loads(z.read('camera_models.json'))
129
- assert m['headset']=='Aria'
130
- hasgt=m['have_hand_object_pose_gt'];split='test' if m['participant_id'] in TEST_IDS else 'train';assert hasgt==(split=='train')
131
- if hasgt:assert 'masks/mask_qa_pass.csv' in z.namelist()
132
- with zipfile.ZipFile(hz) as z:mano_bytes=z.getinfo('mano_hand_pose_trajectory.jsonl').file_size
133
- assert hasgt or mano_bytes==0
134
- rows.append({'sequence':p.name,'sequence_id':p.name,'cameras':[c['stream_id'] for c in cams],'split':split,
135
- '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]]})
136
- # Includes persistent extracted JPEGs, current media spool, meshes, tensors and reports.
137
- budget=sum(r['vrs_bytes'] for r in rows)*3+150_000_000_000
138
- assert len(rows)==(339 if ds=='ARCTIC' else 198)
139
- 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}
140
- print('PLAN',ds,len(rows),out['datasets'][ds]['views'],budget,flush=True)
141
- out['free_bytes_at_plan']=shutil.disk_usage(DATA_ROOT).free
142
- out['additional_peak_budget_bytes']=sum(v['additional_budget_bytes'] for v in out['datasets'].values())
143
- assert out['free_bytes_at_plan']-out['additional_peak_budget_bytes']>=RESERVE,out
144
- atomic(CONTROL/'plan.json',out)
145
- return out
146
-
147
- def approve():
148
- p=load(CONTROL/'plan.json');confirmation={'confirmed_at':now(),'user_statement':'HOT3D和ARCTIC我都确认了,可以开始做预处理了。',
149
- 'scope':'Reviewed pilots accepted; full preprocessing authorized for ARCTIC and HOT3D Aria only',
150
- 'full_preprocessing_authorized':True,'full_output_review':'pending','upload_authorized':False,'raw_retention':True}
151
- atomic(CONTROL/'authorization.json',confirmation)
152
- state=load(WORK/'tmp/dataset-work-state.json')
153
- for ds in p['order']:
154
- root=DATA_ROOT/ds/RELEASE;doc=root/'doc/validation'
155
- atomic(doc/'pilot-human-confirmation.json',confirmation)
156
- for rp in [doc/'report.json',*sorted((doc/'objects').glob('*/report.json')),*([doc/'objects/report.json'] if (doc/'objects/report.json').exists() else [])]:
157
- r=load(rp);r.update(human_review='approved',full_preprocessing_authorized=True,upload_authorized=False,pilot_confirmation=confirmation)
158
- atomic(rp,r)
159
- for page in [doc/'index.html',*sorted((doc/'objects').rglob('index.html'))]:
160
- if not page.exists():continue
161
- s=page.read_text(encoding='utf-8')
162
- s=s.replace('人工确认待完成','试点人工确认已通过;全量产物待单独验收').replace('用户人工确认待完成','用户试点确认已通过').replace('用户确认前不全量处理','用户已确认试点,允许全量预处理')
163
- if 'id="production-authorization"' not in s:
164
- s=s.replace('<header>','<header><p id="production-authorization" style="color:#176b3a"><strong>用户已确认本页试点,授权全量预处理。</strong> 全量完成后另行随机抽查;尚未授权上传。</p>',1)
165
- page.write_text(s,encoding='utf-8')
166
- if (doc/'objects/artifact-manifest.json').exists():
167
- mp=doc/'objects/artifact-manifest.json';a=load(mp)
168
- for f in a['files']:
169
- file=mp.parent/f['path'];f.update(size=file.stat().st_size,sha256=digest(file))
170
- atomic(mp,a)
171
- for meta in (root/'data').glob('*/*/metainfo.json'):
172
- m=load(meta);m['pilot_human_review']='approved';m['full_preprocessing_authorized']=True
173
- 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')
174
- atomic(meta,m)
175
- state['active'][ds].update(stage='full_preprocessing_queued',human_sample_review='approved',full_preprocessing_authorized=True,upload_authorized=False,
176
- production_plan=str(CONTROL/'plan.json'),full_sequence_count=p['datasets'][ds]['count'],full_view_count=p['datasets'][ds]['views'])
177
- atomic(doc/'status.json',{'stage':'full_preprocessing_queued','pilot_review':'approved','full_output_review':'pending','upload_authorized':False})
178
- docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
179
- atomic(docprod/'plan.json',p['datasets'][ds])
180
- (docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
181
- for f in ['preprocess_fresh_full.py','convert_fresh_sequence_pilots.py','apply_hot3d_qa.py','review_fresh_sequence_pilots.py','render_full_sequence_review.py','fresh_sequence_common.py','diagnose_arctic_review.py']:
182
- shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
183
- atomic(WORK/'tmp/dataset-work-state.json',state)
184
-
185
- def official_arctic_check(row,views):
186
- base=DATA_ROOT/'ARCTIC';seq=row['sequence'];oid=row['object'];sid=seq.split('/')[0]
187
- if row['split']=='test':
188
- with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:
189
- assert all(f'raw_seqs/{seq}.{x}.npy' not in z.namelist() for x in ['mano','object','egocam.dist'])
190
- for p in views:
191
- m=load(p/'metainfo.json');assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
192
- if p.name=='0':assert 'intrinsic' not in m['components'] and 'extrinsic' not in m['components'] and m['camera']['schema_id'] is None
193
- return {'passed':True,'test':'official_held_out_test_ground_truth_omitted; static_mesh_metres_and_part_ids_checked_per_view','source_gt_available':False}
194
- with zipfile.ZipFile(base/'raw/data/meta.zip') as z:
195
- 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
196
- 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']
197
- with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'))
198
- world=[];kp=[]
199
- for start in range(0,len(objects),32):
200
- v,k=official_object(objects[start:start+32],verts,parts,params,oid);world.append(v);kp.append(k)
201
- world=np.concatenate(world);kp=np.concatenate(kp);worst=0.;checked=0
202
- for p in views:
203
- 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
204
- 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')
205
- assert np.array_equal(ids,1-parts)
206
- for i in np.flatnonzero(valid):
207
- 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]
208
- 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]
209
- 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
210
- assert worst<2e-5,(seq,worst)
211
- 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}
212
-
213
- def worker(ds,seq):
214
- plan=load(CONTROL/'plan.json');row=next(r for r in plan['datasets'][ds]['sequences'] if r['sequence']==seq)
215
- assert load(CONTROL/'authorization.json')['full_preprocessing_authorized']
216
- base=DATA_ROOT/ds;root=base/RELEASE;tmp=temporary(ds);result=tmp/'completed'/f'{row["sequence_id"]}.json';records=inputs(ds)
217
- source_files=list(row['inputs'])
218
- if ds=='HOT3D':source_files+=sorted(rel for rel in records if rel.startswith('assets/'))
219
- source=[check_input(ds,rel,records) for rel in source_files]
220
- if result.exists():
221
- verify_completed(ds,row,source)
222
- print('VERIFIED_RESUME',ds,seq,flush=True);return
223
- assert shutil.disk_usage(base).free>RESERVE+15_000_000_000,'Disk reserve reached'
224
- 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')}
225
- config=load(CONTROL/'acceleration-config.json');assert config['media_policy']==MEDIA_POLICY
226
- conversion_start=time.perf_counter()
227
- media_workers=min(config['workers_by_dataset'][ds],len(row['cameras']))
228
- print('ACCELERATED_MEDIA',ds,seq,media_workers,MEDIA_POLICY,flush=True)
229
- with common.media_pipeline(media_workers):
230
- if ds=='ARCTIC':arctic(seq,initialize=False)
231
- else:hot3d(seq,initialize=False)
232
- conversion_seconds=time.perf_counter()-conversion_start
233
- if ds=='HOT3D':
234
- verify_hot3d_frame_order_and_metadata(seq)
235
- if row['source_gt_available']:apply_qa(seq,publish=False)
236
- views=[root/'data'/row['sequence_id']/cam for cam in row['cameras']]
237
- results=[]
238
- for p in views:
239
- 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)
240
- if p.name in reused:
241
- r['reused_media_revalidation']=revalidate_media(p)
242
- if ds=='HOT3D' and not row['source_gt_available']:
243
- assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
244
- atomic(p/'metainfo.json',m);results.append(r)
245
- 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']}
246
- files=[]
247
- for p in sorted((root/'data'/row['sequence_id']).rglob('*')):
248
- if p.is_file():files.append({'path':p.relative_to(root).as_posix(),'size':p.stat().st_size,'sha256':digest(p)})
249
- done={'dataset':ds,'sequence':seq,'sequence_id':row['sequence_id'],'completed_at':now(),'source':source,'scripts':code_manifest(),'views':results,'independent_geometry':independent,
250
- '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}
251
- atomic(root/'doc/validation/full/sequences'/f'{row["sequence_id"]}.json',done);atomic(result,done)
252
- print('SEQUENCE_COMPLETE',ds,seq,done['frames'],done['bytes'],flush=True)
253
-
254
- def random_review(ds,rows):
255
- from render_full_sequence_review import render_view,asset_preview
256
- doc=DATA_ROOT/ds/RELEASE/'doc/validation/full_random';doc.mkdir(parents=True,exist_ok=True);rng=random.Random(20260920);selected=[]
257
- if ds=='ARCTIC':
258
- for oid in sorted({r['object'] for r in rows}):
259
- 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)))
260
- if not any(c=='0' for _,c,_,_ in selected):
261
- 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)))
262
- for split in ['train','val','test']:
263
- if not any(r['split']==split for r,_,_,_ in selected):
264
- 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)))
265
- else:
266
- for split in ['train','test']:
267
- group=[r for r in rows if r['split']==split];r=rng.choice(group)
268
- for cam in r['cameras']:selected.append((r,cam,'split:'+split,len(group)))
269
- 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.',
270
- '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]}
271
- atomic(doc/'sampling.json',sampling);cards=[];results=[];assets={}
272
- for row,cam,_,_ in selected:
273
- 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)}
274
- atomic(temporary(ds)/'status.json',st);atomic(CONTROL/'status.json',st)
275
- 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
276
- qfile=DATA_ROOT/ds/'tmp'/RUN/'qa'/f'{row["sequence_id"]}.json'
277
- if ds=='HOT3D' and row['source_gt_available']:
278
- if not qfile.exists():apply_qa(row['sequence'],publish=False)
279
- qa=load(qfile)
280
- pixel_proof=revalidate_media(p,full_pixels=True)
281
- atomic(sub/'pixel-validation'/f'{cam}.json',pixel_proof)
282
- result=render_view(p,ds,qa,doc=sub,tmp=tmp);result['whole_sequence_source_RGB_validation']=pixel_proof;results.append(result)
283
- for op in (p/'annotation/object').glob('*'):
284
- out=sub/'assets'/f'{op.name}.mp4'
285
- if not out.exists():asset_preview(op,out)
286
- assets[out.relative_to(doc).as_posix()]=row['sequence_id']+' / '+op.name
287
- 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>')
288
- for ref,label in assets.items():cards.append(f'<section><h2>物体资产 · {label}</h2><video controls preload="metadata" src="{ref}"></video></section>')
289
- atomic(doc/'report.json',{'dataset':ds,'sampling':sampling,'views':results,'asset_previews':assets,'human_review':'pending','upload_authorized':False})
290
- (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')
291
- (doc/'REPORT.md').write_text('# 全量随机抽查\n\n[离线完整序列](index.html) · [抽样定义](sampling.json) · [模态检查](report.json)\n\n人工确认待完成。源缺失模态缺省,不以数值通过替代视觉质量确认。\n',encoding='utf-8')
292
-
293
- def run():
294
- assert not (CONTROL/'maintenance.json').exists() or not load(CONTROL/'maintenance.json')['active'],'Maintenance in progress; production start disabled'
295
- CONTROL.mkdir(parents=True,exist_ok=True);guard=(CONTROL/'process.lock').open('a+b');guard.seek(0)
296
- try:msvcrt.locking(guard.fileno(),msvcrt.LK_NBLCK,1)
297
- except OSError:raise RuntimeError('Another production queue owns the lock')
298
- assert load(CONTROL/'authorization.json')['full_preprocessing_authorized'];p=load(CONTROL/'plan.json')
299
- power=ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
300
- try:
301
- for ds in p['order']:
302
- snapshot_scripts(ds)
303
- rows=p['datasets'][ds]['sequences'];tmp=temporary(ds);tmp.mkdir(parents=True,exist_ok=True)
304
- records=inputs(ds)
305
- # Smaller full sequences first; sequence boundaries remain unchanged.
306
- rows=sorted(rows,key=lambda r:r.get('jpeg_bytes',r.get('vrs_bytes',0)))
307
- for n,row in enumerate(rows):
308
- 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]}
309
- atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
310
- 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)
311
- assert shutil.disk_usage(DATA_ROOT).free>RESERVE+15_000_000_000,'Disk reserve reached'
312
- checkpoint=tmp/'completed'/f'{row["sequence_id"]}.json'
313
- if checkpoint.exists():
314
- dependencies=list(row['inputs'])
315
- if ds=='HOT3D':dependencies+=sorted(rel for rel in records if rel.startswith('assets/'))
316
- verify_completed(ds,row,[check_input(ds,rel,records) for rel in dependencies])
317
- print('VERIFIED_RESUME',ds,row['sequence'],flush=True)
318
- continue
319
- log=tmp/'logs'/f'{row["sequence_id"]}.log';log.parent.mkdir(parents=True,exist_ok=True)
320
- with log.open('ab') as out:
321
- child=subprocess.Popen([sys.executable,'-u',str(SCRIPT),'worker','--dataset',ds,'--sequence',row['sequence']],stdout=out,stderr=subprocess.STDOUT)
322
- while child.poll() is None:
323
- st.update(worker_pid=child.pid,time=now(),log=str(log));atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
324
- if shutil.disk_usage(DATA_ROOT).free<RESERVE:child.terminate();child.wait();raise RuntimeError('Disk reserve reached; active sequence stopped, raw retained')
325
- time.sleep(20)
326
- if child.returncode:raise RuntimeError(f'Worker failed: {ds} {row["sequence"]}; see {log}')
327
- print('QUEUE_PROGRESS',ds,n+1,len(rows),row['sequence'],flush=True)
328
- st={'stage':'generating_full_random_review','dataset':ds,'pid':os.getpid(),'time':now(),'completed_sequences':len(rows),'total_sequences':len(rows)}
329
- atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
330
- 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)
331
- random_review(ds,rows)
332
- 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)
333
- 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')})
334
- atomic(CONTROL/'status.json',{'stage':'all_preprocessing_complete_awaiting_full_random_review','time':now(),'upload_authorized':False})
335
- except BaseException as e:
336
- error={'stage':'failed_needs_attention','time':now(),'error':str(e),'dataset':locals().get('ds'),'sequence':locals().get('row',{}).get('sequence')}
337
- atomic(CONTROL/'status.json',error)
338
- if 'ds' in locals():atomic(temporary(ds)/'status.json',error)
339
- raise
340
- finally:ctypes.windll.kernel32.SetThreadExecutionState(0x80000000);guard.close()
341
-
342
- if __name__=='__main__':
343
- 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()
344
- if a.mode in ['worker','migrate']:
345
- CONTROL.mkdir(parents=True,exist_ok=True)
346
- with (CONTROL/'worker.lock').open('a+b') as lock:
347
- lock.seek(0)
348
- try:msvcrt.locking(lock.fileno(),msvcrt.LK_NBLCK,1)
349
- except OSError:raise RuntimeError('A production worker is already active; refusing overlapping conversion')
350
- if a.mode=='migrate':migrate_completed(a.dataset)
351
- else:worker(a.dataset,a.sequence)
352
- elif a.mode=='plan':plan()
353
- elif a.mode=='approve':approve()
354
- else:run()
 
 
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=['preprocess_fresh_full.py','accelerated_media.py','convert_fresh_sequence_pilots.py','apply_hot3d_qa.py','review_fresh_sequence_pilots.py','render_full_sequence_review.py','fresh_sequence_common.py','diagnose_arctic_review.py','pilot_build.py','pilot_fetch.py','pilot_mano.py','sequence_pilot_common.py','sequence_pilot_world.py','pilot_hot_normalize.py','audit_source_fields.py']
32
+
33
+ def code_manifest():
34
+ return [{'path':'script/'+f,'sha256':digest(WORK/'scripts'/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
+ for f in PRODUCTION_SCRIPTS:shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
79
+ shutil.copyfile(CONTROL/'acceleration-config.json',root/'script/acceleration-config.json')
80
+ atomic(root/'doc/validation/full/script-manifest.json',{'created_at':now(),'scope':'Current production converter and validation scripts; earlier pilot manifests describe their historical run','files':code_manifest()})
81
+
82
+ def inputs(ds):
83
+ base=DATA_ROOT/ds
84
+ name='archive_checksums.json' if ds=='ARCTIC' else 'file_checksums.json'
85
+ return load(base/'raw/doc'/name)
86
+
87
+ def check_input(ds,rel,records):
88
+ p=DATA_ROOT/ds/'raw/data'/rel;r=records[rel];st=p.stat()
89
+ assert st.st_size==r['size'],f'Raw size changed: {p}'
90
+ assert r.get('official_sha256_match',r.get('official_digest_match',False))
91
+ if st.st_mtime_ns!=r['mtime_ns']:
92
+ assert digest(p)==r['sha256'],f'Raw digest changed: {p}'
93
+ if p.suffix=='.zip':
94
+ with zipfile.ZipFile(p) as z:assert z.testzip() is None
95
+ 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']}
96
+
97
+ def plan():
98
+ CONTROL.mkdir(parents=True,exist_ok=True);out={'created_at':now(),'order':['ARCTIC','HOT3D'],'datasets':{},'reserve_bytes':RESERVE}
99
+ for ds in out['order']:
100
+ base=DATA_ROOT/ds;records=inputs(ds)
101
+ for rel in records:check_input(ds,rel,records)
102
+ rows=[];auxiliary=[]
103
+ if ds=='ARCTIC':
104
+ with zipfile.ZipFile(base/'raw/data/splits_json.zip') as z:splits=json.loads(z.read('splits_json/protocol_p1.json'))
105
+ for p in sorted((base/'raw/data/images_zips').rglob('*.zip')):
106
+ seq=p.relative_to(base/'raw/data/images_zips').with_suffix('').as_posix()
107
+ if '/' not in seq:
108
+ assert seq=='backgrounds',seq
109
+ auxiliary.append({'file':'raw/data/images_zips/backgrounds.zip','handling':'retain original archive in raw; background reference photographs are not hand-object capture sequences'})
110
+ continue
111
+ with zipfile.ZipFile(p) as z:
112
+ im=[i for i in z.infolist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',i.filename)]
113
+ 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)]
114
+ assert all(n.startswith('__MACOSX/') or Path(n).name.startswith('._') for n in extra),(p,extra[:5])
115
+ cams=sorted({i.filename.split('/')[0] for i in im},key=int)
116
+ counts={c:sum(i.filename.startswith(c+'/') for i in im) for c in cams}
117
+ b=sum(i.file_size for i in im)
118
+ assert cams,(seq,counts)
119
+ rows.append({'sequence':seq,'sequence_id':seq.replace('/','_'),'object':seq.split('/')[1].split('_')[0],
120
+ 'cameras':cams,'frames_per_camera':counts,'jpeg_bytes':b,'split':next((k for k,v in splits.items() if seq in v),'unknown'),
121
+ 'inputs':['raw_seqs.zip','meta.zip','splits_json.zip','images_zips/'+seq+'.zip']})
122
+ budget=sum(r['jpeg_bytes'] for r in rows)+160_000_000_000
123
+ else:
124
+ for p in sorted((base/'raw/data/Aria').iterdir()):
125
+ if not p.is_dir():continue
126
+ gt=next(p.glob('*ground_truth.zip'));hz=next(p.glob('*hand_data.zip'));vrs=next(p.glob('*.vrs'))
127
+ with zipfile.ZipFile(gt) as z:
128
+ m=json.loads(z.read('metadata.json'));cams=json.loads(z.read('camera_models.json'))
129
+ assert m['headset']=='Aria'
130
+ hasgt=m['have_hand_object_pose_gt'];split='test' if m['participant_id'] in TEST_IDS else 'train';assert hasgt==(split=='train')
131
+ if hasgt:assert 'masks/mask_qa_pass.csv' in z.namelist()
132
+ with zipfile.ZipFile(hz) as z:mano_bytes=z.getinfo('mano_hand_pose_trajectory.jsonl').file_size
133
+ assert hasgt or mano_bytes==0
134
+ rows.append({'sequence':p.name,'sequence_id':p.name,'cameras':[c['stream_id'] for c in cams],'split':split,
135
+ '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]]})
136
+ # Includes persistent extracted JPEGs, current media spool, meshes, tensors and reports.
137
+ budget=sum(r['vrs_bytes'] for r in rows)*3+150_000_000_000
138
+ assert len(rows)==(339 if ds=='ARCTIC' else 198)
139
+ 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}
140
+ print('PLAN',ds,len(rows),out['datasets'][ds]['views'],budget,flush=True)
141
+ out['free_bytes_at_plan']=shutil.disk_usage(DATA_ROOT).free
142
+ out['additional_peak_budget_bytes']=sum(v['additional_budget_bytes'] for v in out['datasets'].values())
143
+ assert out['free_bytes_at_plan']-out['additional_peak_budget_bytes']>=RESERVE,out
144
+ atomic(CONTROL/'plan.json',out)
145
+ return out
146
+
147
+ def approve():
148
+ p=load(CONTROL/'plan.json');confirmation={'confirmed_at':now(),'user_statement':'HOT3D和ARCTIC我都确认了,可以开始做预处理了。',
149
+ 'scope':'Reviewed pilots accepted; full preprocessing authorized for ARCTIC and HOT3D Aria only',
150
+ 'full_preprocessing_authorized':True,'full_output_review':'pending','upload_authorized':False,'raw_retention':True}
151
+ atomic(CONTROL/'authorization.json',confirmation)
152
+ state=load(WORK/'tmp/dataset-work-state.json')
153
+ for ds in p['order']:
154
+ root=DATA_ROOT/ds/RELEASE;doc=root/'doc/validation'
155
+ atomic(doc/'pilot-human-confirmation.json',confirmation)
156
+ for rp in [doc/'report.json',*sorted((doc/'objects').glob('*/report.json')),*([doc/'objects/report.json'] if (doc/'objects/report.json').exists() else [])]:
157
+ r=load(rp);r.update(human_review='approved',full_preprocessing_authorized=True,upload_authorized=False,pilot_confirmation=confirmation)
158
+ atomic(rp,r)
159
+ for page in [doc/'index.html',*sorted((doc/'objects').rglob('index.html'))]:
160
+ if not page.exists():continue
161
+ s=page.read_text(encoding='utf-8')
162
+ s=s.replace('人工确认待完成','试点人工确认已通过;全量产物待单独验收').replace('用户人工确认待完成','用户试点确认已通过').replace('用户确认前不全量处理','用户已确认试点,允许全量预处理')
163
+ if 'id="production-authorization"' not in s:
164
+ s=s.replace('<header>','<header><p id="production-authorization" style="color:#176b3a"><strong>用户已确认本页试点,授权全量预处理。</strong> 全量完成后另行随机抽查;尚未授权上传。</p>',1)
165
+ page.write_text(s,encoding='utf-8')
166
+ if (doc/'objects/artifact-manifest.json').exists():
167
+ mp=doc/'objects/artifact-manifest.json';a=load(mp)
168
+ for f in a['files']:
169
+ file=mp.parent/f['path'];f.update(size=file.stat().st_size,sha256=digest(file))
170
+ atomic(mp,a)
171
+ for meta in (root/'data').glob('*/*/metainfo.json'):
172
+ m=load(meta);m['pilot_human_review']='approved';m['full_preprocessing_authorized']=True
173
+ 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')
174
+ atomic(meta,m)
175
+ state['active'][ds].update(stage='full_preprocessing_queued',human_sample_review='approved',full_preprocessing_authorized=True,upload_authorized=False,
176
+ production_plan=str(CONTROL/'plan.json'),full_sequence_count=p['datasets'][ds]['count'],full_view_count=p['datasets'][ds]['views'])
177
+ atomic(doc/'status.json',{'stage':'full_preprocessing_queued','pilot_review':'approved','full_output_review':'pending','upload_authorized':False})
178
+ docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
179
+ atomic(docprod/'plan.json',p['datasets'][ds])
180
+ (docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
181
+ for f in ['preprocess_fresh_full.py','convert_fresh_sequence_pilots.py','apply_hot3d_qa.py','review_fresh_sequence_pilots.py','render_full_sequence_review.py','fresh_sequence_common.py','diagnose_arctic_review.py']:
182
+ shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
183
+ atomic(WORK/'tmp/dataset-work-state.json',state)
184
+
185
+ def official_arctic_check(row,views):
186
+ base=DATA_ROOT/'ARCTIC';seq=row['sequence'];oid=row['object'];sid=seq.split('/')[0]
187
+ if row['split']=='test':
188
+ with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:
189
+ assert all(f'raw_seqs/{seq}.{x}.npy' not in z.namelist() for x in ['mano','object','egocam.dist'])
190
+ for p in views:
191
+ m=load(p/'metainfo.json');assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
192
+ if p.name=='0':assert 'intrinsic' not in m['components'] and 'extrinsic' not in m['components'] and m['camera']['schema_id'] is None
193
+ return {'passed':True,'test':'official_held_out_test_ground_truth_omitted; static_mesh_metres_and_part_ids_checked_per_view','source_gt_available':False}
194
+ with zipfile.ZipFile(base/'raw/data/meta.zip') as z:
195
+ 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
196
+ 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']
197
+ with zipfile.ZipFile(base/'raw/data/raw_seqs.zip') as z:objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'))
198
+ world=[];kp=[]
199
+ for start in range(0,len(objects),32):
200
+ v,k=official_object(objects[start:start+32],verts,parts,params,oid);world.append(v);kp.append(k)
201
+ world=np.concatenate(world);kp=np.concatenate(kp);worst=0.;checked=0
202
+ for p in views:
203
+ 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
204
+ 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')
205
+ assert np.array_equal(ids,1-parts)
206
+ for i in np.flatnonzero(valid):
207
+ 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]
208
+ 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]
209
+ 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
210
+ assert worst<2e-5,(seq,worst)
211
+ 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}
212
+
213
+ def worker(ds,seq):
214
+ plan=load(CONTROL/'plan.json');row=next(r for r in plan['datasets'][ds]['sequences'] if r['sequence']==seq)
215
+ assert load(CONTROL/'authorization.json')['full_preprocessing_authorized']
216
+ base=DATA_ROOT/ds;root=base/RELEASE;tmp=temporary(ds);result=tmp/'completed'/f'{row["sequence_id"]}.json';records=inputs(ds)
217
+ source_files=list(row['inputs'])
218
+ if ds=='HOT3D':source_files+=sorted(rel for rel in records if rel.startswith('assets/'))
219
+ source=[check_input(ds,rel,records) for rel in source_files]
220
+ if result.exists():
221
+ verify_completed(ds,row,source)
222
+ print('VERIFIED_RESUME',ds,seq,flush=True);return
223
+ assert shutil.disk_usage(base).free>RESERVE+15_000_000_000,'Disk reserve reached'
224
+ 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')}
225
+ config=load(CONTROL/'acceleration-config.json');assert config['media_policy']==MEDIA_POLICY
226
+ conversion_start=time.perf_counter()
227
+ media_workers=min(config['workers_by_dataset'][ds],len(row['cameras']))
228
+ print('ACCELERATED_MEDIA',ds,seq,media_workers,MEDIA_POLICY,flush=True)
229
+ with common.media_pipeline(media_workers):
230
+ if ds=='ARCTIC':arctic(seq,initialize=False)
231
+ else:hot3d(seq,initialize=False)
232
+ conversion_seconds=time.perf_counter()-conversion_start
233
+ if ds=='HOT3D':
234
+ verify_hot3d_frame_order_and_metadata(seq)
235
+ if row['source_gt_available']:apply_qa(seq,publish=False)
236
+ views=[root/'data'/row['sequence_id']/cam for cam in row['cameras']]
237
+ results=[]
238
+ for p in views:
239
+ 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)
240
+ if p.name in reused:
241
+ r['reused_media_revalidation']=revalidate_media(p)
242
+ if ds=='HOT3D' and not row['source_gt_available']:
243
+ assert 'mano' not in m['components'] and not list((p/'annotation/object').glob('*/pose.pt'))
244
+ atomic(p/'metainfo.json',m);results.append(r)
245
+ 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']}
246
+ files=[]
247
+ for p in sorted((root/'data'/row['sequence_id']).rglob('*')):
248
+ if p.is_file():files.append({'path':p.relative_to(root).as_posix(),'size':p.stat().st_size,'sha256':digest(p)})
249
+ done={'dataset':ds,'sequence':seq,'sequence_id':row['sequence_id'],'completed_at':now(),'source':source,'scripts':code_manifest(),'views':results,'independent_geometry':independent,
250
+ '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}
251
+ atomic(root/'doc/validation/full/sequences'/f'{row["sequence_id"]}.json',done);atomic(result,done)
252
+ print('SEQUENCE_COMPLETE',ds,seq,done['frames'],done['bytes'],flush=True)
253
+
254
+ def random_review(ds,rows):
255
+ from render_full_sequence_review import render_view,asset_preview
256
+ doc=DATA_ROOT/ds/RELEASE/'doc/validation/full_random';doc.mkdir(parents=True,exist_ok=True);rng=random.Random(20260920);selected=[]
257
+ if ds=='ARCTIC':
258
+ for oid in sorted({r['object'] for r in rows}):
259
+ 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)))
260
+ if not any(c=='0' for _,c,_,_ in selected):
261
+ 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)))
262
+ for split in ['train','val','test']:
263
+ if not any(r['split']==split for r,_,_,_ in selected):
264
+ 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)))
265
+ else:
266
+ for split in ['train','test']:
267
+ group=[r for r in rows if r['split']==split];r=rng.choice(group)
268
+ for cam in r['cameras']:selected.append((r,cam,'split:'+split,len(group)))
269
+ 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.',
270
+ '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]}
271
+ atomic(doc/'sampling.json',sampling);cards=[];results=[];assets={}
272
+ for row,cam,_,_ in selected:
273
+ 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)}
274
+ atomic(temporary(ds)/'status.json',st);atomic(CONTROL/'status.json',st)
275
+ 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
276
+ qfile=DATA_ROOT/ds/'tmp'/RUN/'qa'/f'{row["sequence_id"]}.json'
277
+ if ds=='HOT3D' and row['source_gt_available']:
278
+ if not qfile.exists():apply_qa(row['sequence'],publish=False)
279
+ qa=load(qfile)
280
+ pixel_proof=revalidate_media(p,full_pixels=True)
281
+ atomic(sub/'pixel-validation'/f'{cam}.json',pixel_proof)
282
+ result=render_view(p,ds,qa,doc=sub,tmp=tmp);result['whole_sequence_source_RGB_validation']=pixel_proof;results.append(result)
283
+ for op in (p/'annotation/object').glob('*'):
284
+ out=sub/'assets'/f'{op.name}.mp4'
285
+ if not out.exists():asset_preview(op,out)
286
+ assets[out.relative_to(doc).as_posix()]=row['sequence_id']+' / '+op.name
287
+ 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>')
288
+ for ref,label in assets.items():cards.append(f'<section><h2>物体资产 · {label}</h2><video controls preload="metadata" src="{ref}"></video></section>')
289
+ atomic(doc/'report.json',{'dataset':ds,'sampling':sampling,'views':results,'asset_previews':assets,'human_review':'pending','upload_authorized':False})
290
+ (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')
291
+ (doc/'REPORT.md').write_text('# 全量随机抽查\n\n[离线完整序列](index.html) · [抽样定义](sampling.json) · [模态检查](report.json)\n\n人工确认待完成。源缺失模态缺省,不以数值通过替代视觉质量确认。\n',encoding='utf-8')
292
+
293
+ def run():
294
+ assert not (CONTROL/'maintenance.json').exists() or not load(CONTROL/'maintenance.json')['active'],'Maintenance in progress; production start disabled'
295
+ CONTROL.mkdir(parents=True,exist_ok=True);guard=(CONTROL/'process.lock').open('a+b');guard.seek(0)
296
+ try:msvcrt.locking(guard.fileno(),msvcrt.LK_NBLCK,1)
297
+ except OSError:raise RuntimeError('Another production queue owns the lock')
298
+ assert load(CONTROL/'authorization.json')['full_preprocessing_authorized'];p=load(CONTROL/'plan.json')
299
+ power=ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
300
+ try:
301
+ scope=os.environ.get('HAND_DATASET_SCOPE')
302
+ for ds in [name for name in p['order'] if scope is None or name==scope]:
303
+ snapshot_scripts(ds)
304
+ rows=p['datasets'][ds]['sequences'];tmp=temporary(ds);tmp.mkdir(parents=True,exist_ok=True)
305
+ records=inputs(ds)
306
+ # Smaller full sequences first; sequence boundaries remain unchanged.
307
+ rows=sorted(rows,key=lambda r:r.get('jpeg_bytes',r.get('vrs_bytes',0)))
308
+ for n,row in enumerate(rows):
309
+ 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]}
310
+ atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
311
+ 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)
312
+ assert shutil.disk_usage(DATA_ROOT).free>RESERVE+15_000_000_000,'Disk reserve reached'
313
+ checkpoint=tmp/'completed'/f'{row["sequence_id"]}.json'
314
+ if checkpoint.exists():
315
+ dependencies=list(row['inputs'])
316
+ if ds=='HOT3D':dependencies+=sorted(rel for rel in records if rel.startswith('assets/'))
317
+ verify_completed(ds,row,[check_input(ds,rel,records) for rel in dependencies])
318
+ print('VERIFIED_RESUME',ds,row['sequence'],flush=True)
319
+ continue
320
+ log=tmp/'logs'/f'{row["sequence_id"]}.log';log.parent.mkdir(parents=True,exist_ok=True)
321
+ with log.open('ab') as out:
322
+ child=subprocess.Popen([sys.executable,'-u',str(SCRIPT),'worker','--dataset',ds,'--sequence',row['sequence']],stdout=out,stderr=subprocess.STDOUT)
323
+ while child.poll() is None:
324
+ st.update(worker_pid=child.pid,time=now(),log=str(log));atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
325
+ if shutil.disk_usage(DATA_ROOT).free<RESERVE:child.terminate();child.wait();raise RuntimeError('Disk reserve reached; active sequence stopped, raw retained')
326
+ time.sleep(20)
327
+ if child.returncode:raise RuntimeError(f'Worker failed: {ds} {row["sequence"]}; see {log}')
328
+ print('QUEUE_PROGRESS',ds,n+1,len(rows),row['sequence'],flush=True)
329
+ st={'stage':'generating_full_random_review','dataset':ds,'pid':os.getpid(),'time':now(),'completed_sequences':len(rows),'total_sequences':len(rows)}
330
+ atomic(tmp/'status.json',st);atomic(CONTROL/'status.json',st)
331
+ 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)
332
+ random_review(ds,rows)
333
+ 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)
334
+ 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')})
335
+ atomic(CONTROL/'status.json',{'stage':'all_preprocessing_complete_awaiting_full_random_review','time':now(),'upload_authorized':False})
336
+ except BaseException as e:
337
+ error={'stage':'failed_needs_attention','time':now(),'error':str(e),'dataset':locals().get('ds'),'sequence':locals().get('row',{}).get('sequence')}
338
+ atomic(CONTROL/'status.json',error)
339
+ if 'ds' in locals():atomic(temporary(ds)/'status.json',error)
340
+ raise
341
+ finally:ctypes.windll.kernel32.SetThreadExecutionState(0x80000000);guard.close()
342
+
343
+ if __name__=='__main__':
344
+ 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()
345
+ if a.mode in ['worker','migrate']:
346
+ CONTROL.mkdir(parents=True,exist_ok=True)
347
+ with (CONTROL/'worker.lock').open('a+b') as lock:
348
+ lock.seek(0)
349
+ try:msvcrt.locking(lock.fileno(),msvcrt.LK_NBLCK,1)
350
+ except OSError:raise RuntimeError('A production worker is already active; refusing overlapping conversion')
351
+ if a.mode=='migrate':migrate_completed(a.dataset)
352
+ else:worker(a.dataset,a.sequence)
353
+ elif a.mode=='plan':plan()
354
+ elif a.mode=='approve':approve()
355
+ else:run()
ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/render_full_sequence_review.py RENAMED
File without changes
ARCTIC/shared-v1.0/script/{review_fresh_sequence_pilots.py → internal/review_fresh_sequence_pilots.py} RENAMED
File without changes
ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/sequence_pilot_common.py RENAMED
File without changes
ARCTIC/shared-v1.0/script/{history/pre-acceleration-20260920 → internal}/sequence_pilot_world.py RENAMED
File without changes
ARCTIC/shared-v1.0/script/render_review.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Regenerate the registered complete-sequence review for ARCTIC."""
2
+ from pathlib import Path
3
+ import argparse, runpy, sys
4
+ argparse.ArgumentParser(description='Regenerate the ARCTIC complete-sequence review.').parse_args()
5
+ HERE=Path(__file__).resolve().parent
6
+ sys.path.insert(0,str(HERE/'internal'))
7
+ sys.argv=[sys.argv[0],'ARCTIC']
8
+ runpy.run_path(str(HERE/'internal'/'render_full_sequence_review.py'),run_name='__main__')
ARCTIC/shared-v1.0/script/repair_arctic_pilot.py DELETED
@@ -1,57 +0,0 @@
1
- """Repair ARCTIC pilot part IDs and exclude confirmed unusable supervision.
2
-
3
- These exclusions are specific to the reviewed sequence; no general dark-image
4
- threshold or blanket first-two-frame rule is applied to other sequences.
5
- """
6
- from fresh_sequence_common import *
7
- from review_fresh_sequence_pilots import arr
8
-
9
- def repair():
10
- base=DATA_ROOT/'ARCTIC';root=base/RELEASE;seq='s09_laptop_use_03'
11
- exposure=load(root/'doc/validation/exposure.json');evidence=load(root/'doc/validation/diagnosis.json')
12
- with zipfile.ZipFile(base/'raw/data/meta.zip') as z:
13
- rawids=np.array(json.loads(z.read('meta/object_vtemplates/laptop/parts.json')),np.int64)
14
- assert set(np.unique(rawids))=={0,1}
15
- records={}
16
- for meta in sorted((root/'data'/seq).glob('*/metainfo.json')):
17
- p=meta.parent;m=load(meta);cam=m['camera_id'];T=m['num_frames']
18
- cache=base/'tmp/full-video-review-v2/diagnostic'/cam
19
- if not (cache/'snapshot.json').exists():
20
- cache.mkdir(parents=True,exist_ok=True)
21
- for f in p.rglob('*.pt'):
22
- target=cache/f.relative_to(p);target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(f,target)
23
- save(cache/'metainfo.json',m);save(cache/'snapshot.json',{'purpose':'before local supervision exclusion; raw-compatible parameter diagnostics','source_view':str(p)})
24
- obj=p/'annotation/object/laptop';tensor(obj/'vertex_part_ids.pt',1-rawids)
25
- om=load(obj/'metainfo.json');om['part_mapping']={'0':'bottom','1':'top'}
26
- om['part_id_conversion']={'formula':'shared_id = 1 - raw_parts_json_value','source_mapping':{'0':'top','1':'bottom'},'upstream_code':evidence['upstream_code']}
27
- save(obj/'metainfo.json',om)
28
- # Selection is explicitly reviewed. Statistics only verify the observed prefix.
29
- first=exposure[cam]['frames'];assert all(first[i]['p95_luma']<35 for i in [0,1]) and first[2]['p95_luma']>100
30
- image_ok=np.ones(T,bool);image_ok[[0,1]]=False
31
- hand_ok=image_ok.copy()
32
- for key,c in m['components'].items():
33
- if key!='mano' and c['schema_id'] not in ['object/rigid/v1','object/joint_state/v1','object_keypoints/camera/v1']:continue
34
- values=arr(cache/c['data_ref']).copy();present=arr(cache/c['valid_ref']);gate=hand_ok if key=='mano' else image_ok
35
- valid=present & gate.reshape((T,)+(1,)*(present.ndim-1));values[~valid]=np.nan
36
- tensor(p/c['data_ref'],values);tensor(p/c['valid_ref'],valid)
37
- c['valid_policy']={'semantics':'usable_annotation','formula':'source_annotation_present AND source_numerically_valid AND local_review_pass_for_known_exclusions',
38
- 'official_accuracy_qa':'not provided by selected raw; ARCTIC geometric framing validity is not image alignment QA',
39
- 'local_excluded_frame_indices':np.flatnonzero(~gate).tolist(),
40
- 'local_exclusion_reasons':{'0,1':'confirmed severe source underexposure; both raw and shared images preserved'},
41
- 'source_locator':{'review':'doc/validation/ARCTIC_FINDINGS.md','exposure':'doc/validation/exposure.json','geometry':'doc/validation/diagnosis.json'},
42
- 'limitation':'Not a claim that remaining frames pass manual review; entire pilot remains blocked pending all-camera video review'}
43
- m['validity_revision']='usable-annotation-2026-09-20';m['acceptance']={'status':'blocked_pending_visual_review','training_release_approved':False,'reason':'known source dark frames excluded; parts fixed; residual source-compatible hand misalignment requires review'}
44
- save(meta,m)
45
- checksfile=base/'tmp'/RUN/'checks'/f'{seq}__{cam}.json';checks=load(checksfile)
46
- checks['checks']=[r for r in checks['checks'] if r['test'] not in ['all_frame_articulated_geometry_independent_scipy_rotation','pinned_official_ObjectTensors_articulation_after_part_remap']]
47
- checks['checks'].append({'test':'pinned_official_ObjectTensors_articulation_after_part_remap','passed':True,**next(x for x in evidence['tests'] if x['camera_id']==cam)})
48
- save(checksfile,checks)
49
- records[cam]={'image_exclusions':[0,1],'mano_exclusions':np.flatnonzero(~hand_ok).tolist(),'usable_mano_frames':arr(p/'annotation/mano/motion_valid.pt').sum(0).tolist()}
50
- print('ARCTIC_REPAIRED',cam,records[cam],flush=True)
51
- evidence['repair_applied']=True;evidence['local_exclusions']=records;save(root/'doc/validation/diagnosis.json',evidence)
52
- findings=WORK/'docs/ARCTIC-pilot-findings-2026-09-20.md'
53
- if findings.exists():shutil.copyfile(findings,root/'doc/validation/ARCTIC_FINDINGS.md')
54
- for f in ['repair_arctic_pilot.py','diagnose_arctic_review.py','convert_fresh_sequence_pilots.py','review_fresh_sequence_pilots.py','render_full_sequence_review.py']:
55
- shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
56
-
57
- if __name__=='__main__':repair()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ARCTIC/shared-v1.0/script/validate.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """Validate one camera-view directory against hand-warehouse/1.0."""
2
+ from pathlib import Path
3
+ import argparse, json, sys
4
+ q=argparse.ArgumentParser();q.add_argument('view',type=Path);a=q.parse_args()
5
+ HERE=Path(__file__).resolve().parent
6
+ sys.path.insert(0,str(HERE/'internal'))
7
+ from review_fresh_sequence_pilots import validate_view
8
+ _,_,report=validate_view(a.view)
9
+ print(json.dumps(report,ensure_ascii=False,indent=2))
HOT3D/shared-v1.0/doc/validation/full/MEDIA_VALIDATION.md CHANGED
@@ -6,6 +6,6 @@
6
 
7
  并行只发生于同一数据集内部的媒体任务;一个序列的数值计算与媒体任务交错,最多一个重型数据集 worker。实测范围、各并行度耗时和可用内存见 [加速验收](acceleration-benchmark.json),实际设置见 [配置](../../../script/acceleration-config.json)。完整像素回归包含 ARCTIC 全分辨率相机及 HOT3D 彩色/灰度相机。
8
 
9
- 切换前已完成产物保留原来的逐帧像素证明。旧脚本快照在 `script/history/pre-acceleration-20260920/`;当前脚本在 `script/`。一次性重新核验所有已完成产物的内容摘要和现行结构/valid 规则,现汇总在 [acceleration-revalidation.json](acceleration-revalidation.json),每条仍保留原文件名和原 JSON 字节 SHA256。早期 HOT3D 烟雾测试没有内嵌脚本摘要,重新核验另补全输入资产依赖,不能将其视为当时已记录代码指纹。
10
 
11
  以上是自动检查;后续全量随机与扩展抽查已获人工确认并完成发布,确认范围见 [human-review.json](../full_random/human-review.json)。运行日志只在 tmp,原始包永久保留。
 
6
 
7
  并行只发生于同一数据集内部的媒体任务;一个序列的数值计算与媒体任务交错,最多一个重型数据集 worker。实测范围、各并行度耗时和可用内存见 [加速验收](acceleration-benchmark.json),实际设置见 [配置](../../../script/acceleration-config.json)。完整像素回归包含 ARCTIC 全分辨率相机及 HOT3D 彩色/灰度相机。
8
 
9
+ 切换前已完成产物保留原来的逐帧像素证明。旧脚本版本由本报告保留的脚本清单与 SHA256、以及仓库固定提交历史追溯;当前入口与冻结实现位于 `script/`。一次性重新核验所有已完成产物的内容摘要和现行结构/valid 规则,现汇总在 [acceleration-revalidation.json](acceleration-revalidation.json),每条仍保留原文件名和原 JSON 字节 SHA256。早期 HOT3D 烟雾测试没有内嵌脚本摘要,重新核验另补全输入资产依赖,不能将其视为当时已记录代码指纹。
10
 
11
  以上是自动检查;后续全量随机与扩展抽查已获人工确认并完成发布,确认范围见 [human-review.json](../full_random/human-review.json)。运行日志只在 tmp,原始包永久保留。
HOT3D/shared-v1.0/script/README.md CHANGED
@@ -1,2 +1,28 @@
1
- 运行条件与配置见 ../doc/RAW_TO_SHARED.md。
2
- 模型权重不分发;日志与提取缓存不分发。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HOT3D 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
+ HOT3D 的官方 QA 应用、SSD 暂存和扩展审核实现分别位于 `internal/apply_hot3d_qa.py`、`internal/hot3d_storage.py` 与 `internal/extend_hot3d_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/`,不在本目录发布。
HOT3D/shared-v1.0/script/apply_hot3d_qa.py DELETED
@@ -1,65 +0,0 @@
1
- """Apply native HOT3D manual QA to supervision validity, preserving raw diagnostics."""
2
- from fresh_sequence_common import *
3
-
4
- VIDEO_RUN='full-video-review-v2'
5
- SEQ='P0015_179e1b84'
6
-
7
- def csvrows(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
8
-
9
- def apply_qa(sequence=None,publish=True):
10
- seq=sequence or SEQ
11
- base=DATA_ROOT/'HOT3D';root=base/RELEASE;src=base/'raw/data/Aria'/seq
12
- gtfile=next(src.glob('*ground_truth.zip'));qa_report={}
13
- with zipfile.ZipFile(gtfile) as z:
14
- masks=csvrows(z,'masks/mask_qa_pass.csv');hands=csvrows(z,'box2d_hands.csv');objects=csvrows(z,'box2d_objects.csv')
15
- for meta in sorted((root/'data'/seq).glob('*/metainfo.json')):
16
- p=meta.parent;m=load(meta);cam=m['camera_id'];T=m['num_frames'];frames=[json.loads(x) for x in (p/'camera/frames.jsonl').read_text().splitlines()]
17
- cache=base/'tmp'/VIDEO_RUN/'diagnostic'/(cam if seq==SEQ else seq+'/'+cam)
18
- if (cache/'snapshot.json').exists():assert Path(load(cache/'snapshot.json')['source_view']).resolve()==p.resolve()
19
- if not (cache/'snapshot.json').exists():
20
- cache.mkdir(parents=True,exist_ok=True)
21
- for file in p.rglob('*.pt'):
22
- target=cache/file.relative_to(p);target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(file,target)
23
- save(cache/'metainfo.json',m);save(cache/'snapshot.json',{'purpose':'pre-QA native parameter diagnostics only; not shared usable labels','source_view':str(p),'frames':T})
24
- lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in masks if r['stream_id']==cam}
25
- qa=np.array([lookup[f['timecode_ns']] for f in frames],bool)
26
- source={'archive':gtfile.relative_to(base).as_posix(),'member':'masks/mask_qa_pass.csv','stream_id':cam,'time_index_ref':'camera/frames.jsonl:timecode_ns'}
27
- policy={'semantics':'usable_annotation','formula':'source_annotation_present AND source_numerically_valid AND official_manual_qa_pass',
28
- 'qa_scope':'all visible hand/object poses in this camera frame; conservatively exclude all hand/object supervision if false',
29
- 'source_locator':source,'no_qa_source_rule':'use the component source-validity rules; do not invent QA'}
30
- for key,c in m['components'].items():
31
- # Camera calibration and RGB are not labels covered by this manual hand/object QA flag.
32
- if key=='mano' or c['schema_id'] in ['object/rigid/v1','object/joint_state/v1','object_keypoints/camera/v1']:
33
- values=torch.load(cache/c['data_ref'],weights_only=True).numpy();present=torch.load(cache/c['valid_ref'],weights_only=True).numpy()
34
- valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));values=values.copy();values[~valid]=np.nan
35
- tensor(p/c['data_ref'],values);tensor(p/c['valid_ref'],valid);c['valid_policy']=policy
36
- for attrname,a in c.get('attributes',{}).items():
37
- if attrname!='visibility':continue
38
- ishand=key=='mano';oid=c['source_locator'].get('object_uid');ids=[0,1] if ishand else [oid]
39
- rows=hands if ishand else objects;identity='hand_index' if ishand else 'object_uid'
40
- native={(int(r['timestamp[ns]']),str(r[identity])):float(r['visibility_ratio[%]']) for r in rows if r['stream_id']==cam and r['visibility_ratio[%]']!=''}
41
- values=np.array([[native.get((f['timecode_ns'],str(k)),np.nan) for k in ids] for f in frames],np.float32)
42
- if not ishand:values=values[:,0]
43
- present=np.isfinite(values);assert ((values[present]>=0)&(values[present]<=1)).all()
44
- # Correct the diagnostic copy as well: these values are fractions, despite the source header.
45
- tensor(cache/a['data_ref'],values);tensor(cache/a['valid_ref'],present)
46
- valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));filtered=values.copy();filtered[~valid]=np.nan
47
- tensor(p/a['data_ref'],filtered);tensor(p/a['valid_ref'],valid)
48
- a['provenance']={'kind':'source','method':'native [0,1] ratio retained; official loader does not divide misleading [%] header by 100'}
49
- a['valid_policy']={'semantics':'usable_visibility_annotation','formula':'source_ratio_present AND official_manual_qa_pass','source_locator':source}
50
- a['source_locator']['match_method']='exact'
51
- m['validity_revision']='usable-annotation-2026-09-20'
52
- m['split']='train';m['split_scheme']='HOT3D_official_participant_split';m.pop('split_reason',None)
53
- m['split_source_locator']={'url':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#testtrain-split','participant_id':seq.split('_')[0]}
54
- assert seq.split('_')[0] not in {'P0004','P0005','P0006','P0008','P0016','P0020'}
55
- save(meta,m)
56
- qa_report[cam]={'frames':T,'qa_pass':qa.tolist(),'passed_count':int(qa.sum()),'source_locator':source,
57
- 'interpretation':'manual QA of visible hand/object poses; not RGB validity or individual error localization'}
58
- print('QA_APPLIED',cam,'pass',int(qa.sum()),'fail',int((~qa).sum()),flush=True)
59
- save(root/'doc/validation/source_qa.json' if publish else base/'tmp'/RUN/'qa'/f'{seq}.json',qa_report)
60
- if publish:
61
- for f in ['apply_hot3d_qa.py','fresh_sequence_common.py','convert_fresh_sequence_pilots.py']:
62
- shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
63
- return qa_report
64
-
65
- if __name__=='__main__':apply_qa()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/audit_source_fields.py DELETED
@@ -1,55 +0,0 @@
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/{acceleration-config.json → config.json} RENAMED
File without changes
HOT3D/shared-v1.0/script/convert.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resume the verified HOT3D production queue."""
2
+ from pathlib import Path
3
+ import argparse, os, runpy, sys
4
+ q=argparse.ArgumentParser(description='Resume the HOT3D 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']='HOT3D'
11
+ if a.sequence: sys.argv=[sys.argv[0],'worker','--dataset','HOT3D','--sequence',a.sequence]
12
+ elif a.mode=='migrate': sys.argv=[sys.argv[0],'migrate','--dataset','HOT3D']
13
+ else: sys.argv=[sys.argv[0],'run']
14
+ runpy.run_path(str(HERE/'internal'/'preprocess_fresh_full.py'),run_name='__main__')
HOT3D/shared-v1.0/script/diagnose_arctic_review.py DELETED
@@ -1,125 +0,0 @@
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]()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/diagnose_hot3d_alignment.py DELETED
@@ -1,47 +0,0 @@
1
- """Independent native pose/bbox checks for the HOT3D opening-frame complaint."""
2
- from fresh_sequence_common import *
3
- from review_fresh_sequence_pilots import arr
4
-
5
- def pose(row):
6
- T=np.eye(4);T[:3,:3]=Rotation.from_quat([float(row['q_wo_'+k]) for k in 'xyzw']).as_matrix();T[:3,3]=[float(row['t_wo_'+k+'[m]']) for k in 'xyz'];return T
7
-
8
- def rows(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
9
-
10
- def diagnose():
11
- base=DATA_ROOT/'HOT3D';root=base/RELEASE;seq='P0015_179e1b84';src=base/'raw/data/Aria'/seq;cache=base/'tmp/full-video-review-v2/diagnostic';doc=root/'doc/validation'
12
- with zipfile.ZipFile(next(src.glob('*ground_truth.zip'))) as z:
13
- cams=json.loads(z.read('camera_models.json'));heads={int(r['timestamp[ns]']):pose(r) for r in rows(z,'headset_trajectory.csv')}
14
- objects={(int(r['timestamp[ns]']),r['object_uid']):pose(r) for r in rows(z,'dynamic_objects.csv')};boxes=rows(z,'box2d_objects.csv');masks=rows(z,'masks/mask_qa_pass.csv')
15
- diagnostics=[];plate='248247003992116'
16
- for c in cams:
17
- cam=c['stream_id'];p=root/'data'/seq/cam;fr=[json.loads(x) for x in (p/'camera/frames.jsonl').read_text().splitlines()];meta=load(p/'metainfo.json')
18
- dc=c['T_Device_Camera'];Tdc=np.eye(4);Tdc[:3,:3]=Rotation.from_quat(np.roll(dc['quaternion_wxyz'],-1)).as_matrix();Tdc[:3,3]=dc['translation_xyz']
19
- nativeE=np.stack([np.linalg.inv(heads[f['timecode_ns']]@Tdc) for f in fr]);storedE=arr(p/'camera/extrinsic.pt');eerr=float(np.max(np.abs(nativeE-storedE)));assert eerr<2e-6
20
- rawhead=np.stack([heads[f['timecode_ns']] for f in fr]);firstchange=next(i for i in range(len(fr)) if not np.array_equal(rawhead[i],rawhead[0]))
21
- op=p/'annotation/object'/plate;om=load(op/'metainfo.json');mesh=trimesh.load(p/om['original_glb_ref'],process=False,force='mesh');v=np.asarray(mesh.vertices)
22
- storedP=arr(cache/cam/'annotation/object'/plate/'pose.pt');qa={int(r['timestamp[ns]']):r['mask']=='True' for r in masks if r['stream_id']==cam}
23
- lookup={int(r['timestamp[ns]']):r for r in boxes if r['stream_id']==cam and r['object_uid']==plate}
24
- tests=[]
25
- for i in [0,1,26,27,179,180,253,507,760]:
26
- ts=fr[i]['timecode_ns'];P=nativeE[i]@objects[(ts,plate)];error=float(np.max(np.abs(P-storedP[i])));assert error<2e-6
27
- xyz=v@P[:3,:3].T+P[:3,3];uv=project_points(xyz,'fisheye624',c['projectionParams']);good=np.isfinite(uv).all(1)
28
- box=lookup.get(ts);diff=None;expected=None
29
- if box and box['x_min[pixel]'] and good.all():
30
- expected=np.array([float(box[k]) for k in ['x_min[pixel]','y_min[pixel]','x_max[pixel]','y_max[pixel]']]);bb=np.r_[uv.min(0),uv.max(0)];diff=float(np.max(np.abs(expected-bb)))
31
- tests.append({'frame_index':i,'source_frame_id':fr[i]['source_frame_id'],'official_qa_pass':qa[ts],'native_vs_cached_pose_max_abs':error,'source_plate_bbox_vs_projection_max_pixel':diff})
32
- if i in [0,180]:
33
- files=sorted((base/'tmp'/RUN/seq/'images').glob(cam+'-*.jpg'));image=np.asarray(Image.open(files[i]).convert('RGB')).copy()
34
- if expected is not None:cv2.rectangle(image,tuple(expected[:2].astype(int)),tuple(expected[2:].astype(int)),(255,235,0),2)
35
- inds=np.arange(0,len(uv),max(1,len(uv)//5000));pix=uv[inds];ok=np.isfinite(pix).all(1)&(pix[:,0]>=0)&(pix[:,0]<image.shape[1])&(pix[:,1]>=0)&(pix[:,1]<image.shape[0]);pix=np.rint(pix[ok]).astype(int)
36
- image[np.clip(pix[:,1],0,image.shape[0]-1),np.clip(pix[:,0],0,image.shape[1]-1)]=[50,255,80]
37
- cv2.putText(image,f'idx {i}: native QA={qa[ts]} | yellow=official box, green=native pose',(8,24),cv2.FONT_HERSHEY_SIMPLEX,.45,(255,255,255),1)
38
- out=doc/'diagnosis';out.mkdir(parents=True,exist_ok=True);Image.fromarray(image).save(out/f'{cam}-{i:04d}.png')
39
- diagnostics.append({'camera_id':cam,'native_vs_shared_extrinsic_max_abs':eerr,'initial_identical_headset_pose_frames':firstchange,'tests':tests})
40
- report={'conclusion':'Native official hand/object poses already fail official manual QA at the complained frames. Shared media order and native timestamp matching are unchanged; independent native pose reconstruction reproduces the diagnostic geometry. Do not time-shift labels to hide rejected source data.',
41
- 'unproven':'Exact upstream reason for each QA rejection is not provided; initial repeated headset poses are an observation, not a claim of the unique cause.',
42
- 'official_qa_semantics':'Manual QA found no issue with poses of visible hands/objects when true; pose_available does not assess accuracy.',
43
- 'source':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#using-mask-files','cameras':diagnostics}
44
- save(doc/'diagnosis.json',report)
45
- for d in diagnostics:print(d['camera_id'],'head frozen frames',d['initial_identical_headset_pose_frames'],'native box errors',[x['source_plate_bbox_vs_projection_max_pixel'] for x in d['tests']],flush=True)
46
-
47
- if __name__=='__main__':diagnose()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/document_fresh_sequence_pilots.py DELETED
@@ -1,90 +0,0 @@
1
- """Write source-to-contract mappings for the two fresh sequence pilots."""
2
- from fresh_sequence_common import *
3
-
4
- COMMON='''
5
- ## 公共约定与运行
6
-
7
- 这是完整短序列试点,不是全量发布。每个视图使用 [CONTRACT.md](CONTRACT.md) 与 [schema.json](schema.json)。输入是本轮全新下载的 E 盘 raw,不读取 F 盘旧数据或旧试点产物。原始 ZIP/VRS 不改写,临时解包与日志只在数据集 tmp。
8
-
9
- 统一下标 `frame_index=0..T-1`;原帧号与已知时间在 `camera/frames.jsonl`。数值张量是 CPU float32,长度为米,角度为弧度;布尔 valid 表示是否有对应可用标注,缺失的浮点位置填 NaN。valid 不表示可见性。手槽固定左、右。
10
-
11
- 图像由源 JPEG 直接装入 MJPEG/MKV,每包字节不变。容器使用 1 fps、`timebase_role=index_only`,不能按播放器的时长推断真实时间。FFmpeg 固定关闭自动旋转、输出 rgb24,源/目标逐帧 SHA256 相等。实际版本与像素格式写入各视图 metainfo。预览图缩小以方便审核,不是训练输入。
12
-
13
- 校验范围和数值结果见 [validation/REPORT.md](validation/REPORT.md) 与 [validation/report.json](validation/report.json),原始输入 SHA256 见 [pilot-source-manifest.json](pilot-source-manifest.json)。源官方摘要和原包 CRC 在 raw/doc 的下载验收记录中。人工确认仍待完成,不以数学一致性替代投影核验。
14
-
15
- 运行脚本来自本项目 scripts;已将所需本地模块快照放入本发布 script。当前运行环境为 Python 3、PyTorch 2.5.1 CPU、NumPy、smplx、SciPy、Pillow、OpenCV、trimesh、imageio-ffmpeg;HOT3D 另需官方 VRS 工具。MANO v1.2 模型由使用者依授权在本地提供,不包含在发布目录。
16
-
17
- 脚本默认 `E:/hand-datasets` 数据根目录,项目 `tmp/pilot-runtime` 运行环境和 `tmp/pilot-models` 模型目录;迁移时需按机器调整 `fresh_sequence_common.py` 的 DATA_ROOT/VRS 和本地模型路径。这份试点脚本不是无需配置的独立安装包。
18
-
19
- ```text
20
- python scripts/convert_fresh_sequence_pilots.py ARCTIC
21
- python scripts/convert_fresh_sequence_pilots.py HOT3D
22
- python scripts/document_fresh_sequence_pilots.py
23
- python scripts/diagnose_arctic_review.py exposure
24
- python scripts/diagnose_arctic_review.py geometry
25
- python scripts/repair_arctic_pilot.py
26
- python scripts/render_full_sequence_review.py ARCTIC
27
- python scripts/render_full_sequence_review.py HOT3D
28
- ```
29
- '''
30
-
31
- ARCTIC='''# ARCTIC:raw → shared 字段映射
32
-
33
- 本序列原包的 top.obj / bottom.obj 引用 material_0.mtl,但包内实际为 material.mtl;已核对 newmtl/usemtl 均为 material_0。共享层仅修正 mtllib 文件路径,不改材质、UV或纹理,raw 原包保持不变。
34
-
35
- 本次选择 `s09/laptop_use_03`,原图 ZIP 的全部九路相机各 541 张。输出序列名 `s09_laptop_use_03`;相机 0 为 ego,其余 1–8 为 exo。选择官方 P1,split=train。
36
-
37
- 2026-09-20复核:此前顶盖/底座编码解释反了,现已按官方ObjectTensors重新映射。9路相机的index 0/1是原始欠曝图,各动态几何组件valid=false;camera 6的index 270手部对齐仍有问题,手部valid=false,其余模态按自身情况保留。以上是本试点明确登记的排除范围,不是对其余所有帧质量的保证。整套试点未验收,详见[问题与证据](validation/ARCTIC_FINDINGS.md)。
38
-
39
- | raw 中实际数据 | 共享层 | 转换与保留范围 |
40
- |---|---|---|
41
- | images_zips/s09/laptop_use_03.zip,0–8/00001.jpg…00541.jpg | observation/rgb.mkv | 所有原图,无裁剪、缩放、旋转或重新压缩;全部 4869 帧 |
42
- | meta.zip:misc.json 的 ioi_offset=2 | camera/frames.jsonl | 动捕索引=原图编号−2;原图 1 没有标注,2…541 对应标注 0…539;同步标识含源序列和图号 |
43
- | raw_seqs.zip:*.egocam.dist.npy 的 intrinsics、dist8、R_k_cam_np、T_k_cam_np | camera/intrinsic.pt、distortion.pt、extrinsic.pt | 相机 0 rational8,畸变顺序 k1,k2,p1,p2,k3,k4,k5,k6;外参 camera_from_world;首图外参缺失,其余 540 帧有效 |
44
- | meta.zip:misc.json 的 intris_mat、world2cam | 八个外部相机的 camera/ | 官方 processing.forward_project2d 以针孔模型投影;静态参数展开为 T 份,全部 541 帧有标定 |
45
- | raw_seqs.zip:*.mano.npy,左右 rot、pose、shape、trans | annotation/mano/motion.pt [541,2,61] | 非平手均值加回,48 轴角+10形状+3平移;世界系转相机系,按形状相关腕根修正 translation;首帧两手 valid=false |
46
- | raw_seqs.zip:*.object.npy [540,7] | object/laptop/pose.pt、parts/*/pose.pt、joint_state.pt | 角度 rad;全局旋转轴角转 SE(3);物体平移 mm→m;顶盖相对底座绕 -Z 旋转,首帧无效 |
47
- | meta.zip:object_vtemplates/laptop/mesh.obj、top.obj、bottom.obj、MTL/JPG | object/laptop/assets/ | OBJ 顶点 mm→m;顶点顺序/拓扑/UV、材质和纹理引用保留;每个视图一份 |
48
- | 同目录 parts.json | object/laptop/vertex_part_ids.pt 和 metainfo.json | 源0顶盖/1底座,转换为 int64:shared_id=1-source_id,统一0底座/1顶盖;绑定 mesh_ref 和 topology_id |
49
- | object_params.json:keypoints_top、keypoints_bottom | object/laptop/keypoints/xyz.pt [541,32,3] | 原模板各16点的固定顺序,按已发布姿态驱动到相机系;标记 derived,不冒充实测手关键点 |
50
- | splits_json.zip:protocol_p1.json | 视图 metainfo 的 split 与来源 | 保留官方划分;不随意拆帧 |
51
-
52
- 未作为 shared 模态发布:fitting_err、身体数据、动捕 marker、替代采样产物。选定原始包没有独立深度图、像素分割、接触标签或实测手关键点数组;MANO 派生网格只在内存中做校验,不保存 hand_mesh。当前 raw 未提供可直接核实的逐帧时间,timestamp_ns 与 source_fps 保留 null,不用容器 1 fps 伪造真实采集时间。
53
-
54
- 依据固定官方提交 [`49f3eb4`](https://github.com/zc-alexfan/arctic/tree/49f3eb4b7f01663172576357bb3d95695d7a7689):`src/datasets/arctic_dataset.py` 的 ioi_offset 映射、`common/body_models.py` 的非平手均值、`common/object_tensors.py` 的 -Z 关节轴与毫米单位、`src/arctic/processing.py` 和 `common/transforms.py` 的九相机投影。
55
- '''
56
-
57
- HOT='''# HOT3D:raw → shared 字段映射
58
-
59
- 源标注边界:原始 MANO JSONL 共3042条相机时刻记录,2418条含手参数,624条 hand_poses 为空。各视图1014帧中806帧含双手参数、208帧无参数;最终 valid 还要与该相机官方 mask_qa_pass 取交集,不把806称为有效监督数。官方QA是人工检查可见手/物体姿态是否有问题,无法定位到某一实体;这里保守排除整相机帧的手物监督。图像保留,源QA记录和逐帧计数见 validation/source_qa.json。
60
-
61
- 本次选择完整 Aria 序列 `P0015_179e1b84`。三路相机各 1014 帧,源 nominal_rate=30 Hz,首尾采集时间跨度约33.77秒;没有 Quest。
62
-
63
- | raw 中实际数据 | 共享层 | 转换与保留范围 |
64
- |---|---|---|
65
- | *_main_recording.vrs:214-1、1201-1、1201-2 | 各视图 observation/rgb.mkv | 原 JPEG 包;RGB 1408×1408,两灰度640×480。统一读取uint8 RGB,灰度重复到三通道;保留相机类型说明 |
66
- | VRS data 的 frame_number、capture_timestamp_ns | camera/frames.jsonl | 原设备时间与帧号;检查提取文件的记录序号和时间与 VRS 一致 |
67
- | ground_truth.zip:timecode_devicetime_mapping.csv | frames 的 timecode_ns、mapping_delta_ns | 官方 device→timecode 映射,允许最多1000ns定位差并记录实差;标注在 timecode 域内匹配 |
68
- | ground_truth.zip:camera_models.json | camera/intrinsic.pt [1014,15] | 官方静态 FISHEYE624 模型,保留全部15参数及 maxSolidAngle;不改成针孔或人为去畸变 |
69
- | ground_truth.zip:headset_trajectory.csv 和 T_Device_Camera | camera/extrinsic.pt [1014,4,4] | inverse(world_from_device @ device_from_camera),平移米;原标注与图像 timecode 最近邻,最大允许1ms,并记录实际偏差 |
70
- | hand_data.zip:mano_hand_pose_trajectory.jsonl | annotation/mano/motion.pt [1014,2,61] | 源 PCA15 按 MANO v1.2 官方主成分展开+均值;保留10维shape,源q_wxyz转轴角;修正官方左手shapedirs问题;转当前相机系 |
71
- | ground_truth.zip:box2d_hands.csv 的 visibility_ratio[%] | annotation/mano/visibility.pt [1014,2] | 实际源值已在0–1,按官方加载器直接保留,不除100;独立有效性还需通过姿态QA;0可见比例不是缺失;不引入quality |
72
- | ground_truth.zip:dynamic_objects.csv,6个object_uid | object/<uid>/pose.pt [1014,4,4] | 源 world_from_object 转 camera_from_object;米,固定实例UID在序列各相机间保持对应 |
73
- | ground_truth.zip:box2d_objects.csv 的 visibility_ratio[%] | 各物体 visibility.pt [1014] | 比例与独立有效性,归所属物体组件属性 |
74
- | assets/hot3d_models.zip 的 BOP PLY+PNG+models_info.json | object/<uid>/assets/*.obj、MTL、纹理 | BOP id 通过 original_id 对应原UID;PLY顶点mm→m。检查尺寸、三角形及纹理像素往返一致 |
75
- | assets/object_models/obj_*.glb | 各物体 assets 中原生材质伴随资产 | 按 BOP id 对齐,原文件字节不变,保留可能超出 OBJ/MTL 的材质信息;标准 mesh_ref 始终指向米制 OBJ |
76
-
77
- 本序列使用6个物体:spatula_red、potato_masher、can_parmesan、plate_bamboo、carton_oj、bottle_ranch。部件为刚体,未伪造机械关节。图像/手/物体的标注匹配与最大误差在各帧 annotation_matches 明确保存。整手/物体 visibility 的源时间匹配阈值另在属性 source_locator 声明。
78
-
79
- 缺省与选择:无深度相机流;`masks/*.csv` 是帧条件,不是像素分割,QA已合入手/物体valid及依赖姿态的visibility有效性。没有额外生成接触、手关键点或独立hand_mesh。UmeTrack参数、MPS在线相机与SLAM轨迹保留在raw;本版shared选择MANO和ground_truth内相机参数。依据固定提交官方README的参与者划分,P0015属于train,metainfo记录来源。
80
-
81
- 转换语义依据 HOT3D 官方固定提交 [`146b34a`](https://github.com/facebookresearch/hot3d/tree/146b34afef8c1a32adeef7e981c070109f225c87) 的 `mano_layer.py`、`loader_hand_poses.py`、`AriaDataProvider.py`。物体包依据官方 BOP HOT3D仓库固定提交 [`30fe967`](https://huggingface.co/datasets/bop-benchmark/hot3d/tree/30fe9674782f32e1e5edba98476b6ff4300132c5)。Fisheye624预览按Project Aria官方FisheyeRadTanThinPrism公式实现;内参原值不修改。
82
- '''
83
-
84
- if __name__=='__main__':
85
- for dataset,text in [('ARCTIC',ARCTIC),('HOT3D',HOT)]:
86
- root=DATA_ROOT/dataset/RELEASE
87
- (root/'doc/RAW_TO_SHARED.md').write_text(text+COMMON,encoding='utf-8')
88
- shutil.copyfile(Path(__file__),root/'script'/Path(__file__).name)
89
- (root/'script/README.md').write_text('运行条件与配置见 ../doc/RAW_TO_SHARED.md。\n模型权重不分发;日志与提取缓存不分发。\n',encoding='utf-8')
90
- print('DOCUMENTED',dataset)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/finalize_fresh_sequence_review.py DELETED
@@ -1,48 +0,0 @@
1
- """Check full-video artifacts; never infer visual acceptance from numeric success."""
2
- from fresh_sequence_common import *
3
- from review_fresh_sequence_pilots import validate_view, arr
4
- from html.parser import HTMLParser
5
-
6
- class Links(HTMLParser):
7
- def __init__(self):super().__init__();self.refs=[];self.videos=[]
8
- def handle_starttag(self,tag,attrs):
9
- a=dict(attrs)
10
- for k in ['href','src']:
11
- if a.get(k):self.refs.append(a[k])
12
- if tag=='video':self.videos.append(a.get('src'))
13
-
14
- def finalize():
15
- for ds,n in [('ARCTIC',9),('HOT3D',3)]:
16
- root=DATA_ROOT/ds/RELEASE;doc=root/'doc/validation';r=load(doc/'report.json')
17
- assert r['human_review']=='pending' and len(r['full_video_views'])==n
18
- parser=Links();parser.feed((doc/'index.html').read_text(encoding='utf-8'))
19
- assert len(parser.videos)==n+len(r['asset_previews'])
20
- for ref in parser.refs:
21
- if not ref.startswith(('http:','https:','#')):assert (doc/ref).is_file(),ref
22
- for view in r['full_video_views']:
23
- file=doc/view['video_ref'];assert digest(file)==view['video_sha256']
24
- assert len(framehash(['-i',str(file)],copy=True))==view['frames']==view['rendered_frames']
25
- for p in (root/'data').glob('*/*/metainfo.json'):validate_view(p.parent)
26
- if ds=='ARCTIC':
27
- with zipfile.ZipFile(DATA_ROOT/ds/'raw/data/meta.zip') as z:raw=np.asarray(json.loads(z.read('meta/object_vtemplates/laptop/parts.json')),np.int64)
28
- for mp in (root/'data').glob('*/*/metainfo.json'):
29
- p=mp.parent;m=load(mp);assert np.array_equal(arr(p/'annotation/object/laptop/vertex_part_ids.pt'),1-raw)
30
- for c in m['components'].values():
31
- if c.get('valid_policy',{}).get('local_excluded_frame_indices'):
32
- indices=c['valid_policy']['local_excluded_frame_indices'];assert not arr(p/c['valid_ref'])[indices].any()
33
- assert m['acceptance']['training_release_approved'] is False
34
- r['stage']='blocked_pending_visual_review';r['agent_visual_inspection']={'status':'known_residual_hand_alignment_issue','scope':'user screenshots, camera6 frame270 before/after, source exposure contact sheets and selected video snapshots','remaining':'full-camera sequence human acceptance; no claim of all-frame visual pass'}
35
- else:
36
- r['agent_visual_inspection']={'status':'source_QA_failures_excluded_new_full_video_review_pending','scope':'official QA, independent native pose/bbox checks; diagnostic snapshots','remaining':'human review of full sequence'}
37
- for p in (root/'script').glob('*.py'):compile(p.read_text(encoding='utf-8-sig'),str(p),'exec')
38
- assert not list(root.rglob('*.log')) and not list((root/'data').rglob('hand_mesh*'))
39
- r['offline_artifact_check']={'relative_links':'passed','full_camera_videos':n,'frames':sum(v['frames'] for v in r['full_video_views']),'video_hash_and_frame_counts':'passed','tensor_validity_and_refs':'passed','script_compile':'passed','visual_acceptance':'not_granted'}
40
- save(doc/'report.json',r);save(doc/'status.json',{'stage':r['stage'],'human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
41
- shutil.copyfile(Path(__file__),root/'script'/Path(__file__).name)
42
- print(ds,'ARTIFACT_CHECK_PASSED','human acceptance remains pending',flush=True)
43
- p=WORK/'tmp/dataset-work-state.json';state=load(p)
44
- for ds in ['ARCTIC','HOT3D']:
45
- state['active'][ds].update(stage='blocked_pending_visual_review' if ds=='ARCTIC' else 'pilot_full_video_awaiting_human_review',human_sample_review='pending',full_preprocessing_authorized=False,upload_authorized=False)
46
- save(p,state)
47
-
48
- if __name__=='__main__':finalize()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/apply_hot3d_qa.py DELETED
@@ -1,65 +0,0 @@
1
- """Apply native HOT3D manual QA to supervision validity, preserving raw diagnostics."""
2
- from fresh_sequence_common import *
3
-
4
- VIDEO_RUN='full-video-review-v2'
5
- SEQ='P0015_179e1b84'
6
-
7
- def csvrows(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
8
-
9
- def apply_qa(sequence=None,publish=True):
10
- seq=sequence or SEQ
11
- base=DATA_ROOT/'HOT3D';root=base/RELEASE;src=base/'raw/data/Aria'/seq
12
- gtfile=next(src.glob('*ground_truth.zip'));qa_report={}
13
- with zipfile.ZipFile(gtfile) as z:
14
- masks=csvrows(z,'masks/mask_qa_pass.csv');hands=csvrows(z,'box2d_hands.csv');objects=csvrows(z,'box2d_objects.csv')
15
- for meta in sorted((root/'data'/seq).glob('*/metainfo.json')):
16
- p=meta.parent;m=load(meta);cam=m['camera_id'];T=m['num_frames'];frames=[json.loads(x) for x in (p/'camera/frames.jsonl').read_text().splitlines()]
17
- cache=base/'tmp'/VIDEO_RUN/'diagnostic'/(cam if seq==SEQ else seq+'/'+cam)
18
- if (cache/'snapshot.json').exists():assert Path(load(cache/'snapshot.json')['source_view']).resolve()==p.resolve()
19
- if not (cache/'snapshot.json').exists():
20
- cache.mkdir(parents=True,exist_ok=True)
21
- for file in p.rglob('*.pt'):
22
- target=cache/file.relative_to(p);target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(file,target)
23
- save(cache/'metainfo.json',m);save(cache/'snapshot.json',{'purpose':'pre-QA native parameter diagnostics only; not shared usable labels','source_view':str(p),'frames':T})
24
- lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in masks if r['stream_id']==cam}
25
- qa=np.array([lookup[f['timecode_ns']] for f in frames],bool)
26
- source={'archive':gtfile.relative_to(base).as_posix(),'member':'masks/mask_qa_pass.csv','stream_id':cam,'time_index_ref':'camera/frames.jsonl:timecode_ns'}
27
- policy={'semantics':'usable_annotation','formula':'source_annotation_present AND source_numerically_valid AND official_manual_qa_pass',
28
- 'qa_scope':'all visible hand/object poses in this camera frame; conservatively exclude all hand/object supervision if false',
29
- 'source_locator':source,'no_qa_source_rule':'use the component source-validity rules; do not invent QA'}
30
- for key,c in m['components'].items():
31
- # Camera calibration and RGB are not labels covered by this manual hand/object QA flag.
32
- if key=='mano' or c['schema_id'] in ['object/rigid/v1','object/joint_state/v1','object_keypoints/camera/v1']:
33
- values=torch.load(cache/c['data_ref'],weights_only=True).numpy();present=torch.load(cache/c['valid_ref'],weights_only=True).numpy()
34
- valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));values=values.copy();values[~valid]=np.nan
35
- tensor(p/c['data_ref'],values);tensor(p/c['valid_ref'],valid);c['valid_policy']=policy
36
- for attrname,a in c.get('attributes',{}).items():
37
- if attrname!='visibility':continue
38
- ishand=key=='mano';oid=c['source_locator'].get('object_uid');ids=[0,1] if ishand else [oid]
39
- rows=hands if ishand else objects;identity='hand_index' if ishand else 'object_uid'
40
- native={(int(r['timestamp[ns]']),str(r[identity])):float(r['visibility_ratio[%]']) for r in rows if r['stream_id']==cam and r['visibility_ratio[%]']!=''}
41
- values=np.array([[native.get((f['timecode_ns'],str(k)),np.nan) for k in ids] for f in frames],np.float32)
42
- if not ishand:values=values[:,0]
43
- present=np.isfinite(values);assert ((values[present]>=0)&(values[present]<=1)).all()
44
- # Correct the diagnostic copy as well: these values are fractions, despite the source header.
45
- tensor(cache/a['data_ref'],values);tensor(cache/a['valid_ref'],present)
46
- valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));filtered=values.copy();filtered[~valid]=np.nan
47
- tensor(p/a['data_ref'],filtered);tensor(p/a['valid_ref'],valid)
48
- a['provenance']={'kind':'source','method':'native [0,1] ratio retained; official loader does not divide misleading [%] header by 100'}
49
- a['valid_policy']={'semantics':'usable_visibility_annotation','formula':'source_ratio_present AND official_manual_qa_pass','source_locator':source}
50
- a['source_locator']['match_method']='exact'
51
- m['validity_revision']='usable-annotation-2026-09-20'
52
- m['split']='train';m['split_scheme']='HOT3D_official_participant_split';m.pop('split_reason',None)
53
- m['split_source_locator']={'url':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#testtrain-split','participant_id':seq.split('_')[0]}
54
- assert seq.split('_')[0] not in {'P0004','P0005','P0006','P0008','P0016','P0020'}
55
- save(meta,m)
56
- qa_report[cam]={'frames':T,'qa_pass':qa.tolist(),'passed_count':int(qa.sum()),'source_locator':source,
57
- 'interpretation':'manual QA of visible hand/object poses; not RGB validity or individual error localization'}
58
- print('QA_APPLIED',cam,'pass',int(qa.sum()),'fail',int((~qa).sum()),flush=True)
59
- save(root/'doc/validation/source_qa.json' if publish else base/'tmp'/RUN/'qa'/f'{seq}.json',qa_report)
60
- if publish:
61
- for f in ['apply_hot3d_qa.py','fresh_sequence_common.py','convert_fresh_sequence_pilots.py']:
62
- shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
63
- return qa_report
64
-
65
- if __name__=='__main__':apply_qa()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/audit_source_fields.py DELETED
@@ -1,55 +0,0 @@
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/convert_fresh_sequence_pilots.py DELETED
@@ -1,344 +0,0 @@
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
- import concurrent.futures
10
-
11
- ARCTIC_SEQ='s09/laptop_use_03'
12
- HOT3D_SEQ='P0015_179e1b84'
13
-
14
- def loadzipcsv(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
15
-
16
- def expand(rows,indices,shape):
17
- a=np.full(shape,np.nan);good=(indices>=0)&(indices<len(rows));a[good]=np.asarray(rows)[indices[good]]
18
- return a,good
19
-
20
- def arctic_unlabelled(seq,cameras=None):
21
- """Official held-out s03 RGB: static calibration/assets, no hidden GT guesses."""
22
- base=DATA_ROOT/'ARCTIC';raw=base/'raw/data';sid,action=seq.split('/');oid=action.split('_')[0];seqid=seq.replace('/','_')
23
- with zipfile.ZipFile(raw/'splits_json.zip') as z:splitdef=json.loads(z.read('splits_json/protocol_p1.json'))
24
- assert seq in splitdef['test']
25
- source={'archive':f'raw/data/images_zips/{seq}.zip','member_pattern':'{camera_id}/{source_frame_id:05d}.jpg'}
26
- with zipfile.ZipFile(raw/'meta.zip') as za,zipfile.ZipFile(raw/f'images_zips/{seq}.zip') as zi:
27
- misc=json.loads(za.read('meta/misc.json'))[sid];prefix=f'meta/object_vtemplates/{oid}/'
28
- native_parts=np.asarray(json.loads(za.read(prefix+'parts.json')),np.int64)
29
- names=sorted(n for n in zi.namelist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',n))
30
- for cam in sorted({n.split('/')[0] for n in names},key=int):
31
- if cameras is not None and cam not in cameras:continue
32
- selected=[n for n in names if n.split('/')[0]==cam];ids=[int(Path(n).stem) for n in selected]
33
- size=list(Image.open(io.BytesIO(zi.read(selected[0]))).size);assert size==misc['image_size'][int(cam)]
34
- v=FreshView('ARCTIC',seqid,cam,ids,size,dict(source,camera_id=cam))
35
- if (v.p/'metainfo.json').exists() and load(v.p/'metainfo.json').get('pilot_complete'):
36
- print('RESUME verified view',seq,cam,flush=True);continue
37
- 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)
38
- v.m['sampling'].update(source_fps=None,source_fps_reason='Capture FPS not asserted by supplied source; original image numbers retained')
39
- if cam!='0':
40
- src={'archive':'raw/data/meta.zip','member':'meta/misc.json','record':sid}
41
- v.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
42
- 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))
43
- v.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',K,np.ones(t,bool),['T','row','column'],source=src)
44
- 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)
45
- 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)
46
- rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';object_textured_assets(za,prefix,assets)
47
- parts=1-native_parts;tensor(op/'vertex_part_ids.pt',parts)
48
- 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'}],
49
- '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']}
50
- save(op/'articulation.json',articulation);sourceasset={'archive':'raw/data/meta.zip','member_prefix':prefix}
51
- v.component('object_'+oid+'_articulation',rel+'/articulation.json','object/articulated/v1',[],np.array(True),source=sourceasset,static=True)
52
- v.mesh(oid,rel+'/assets/mesh.obj',sourceasset)
53
- 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
54
- 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 ')])
55
- assert np.array_equal(original,actual) and len(parts)==len(actual)
56
- 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})
57
- v.checks.append({'test':'source_static_mesh_vertices_metres_and_part_ids','passed':True,'vertices':len(actual)})
58
- 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'}
59
- 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')
60
- print('MEDIA ARCTIC',cam,t,flush=True);jpeg_video(v,((n,zi.read(n)) for n in selected));v.m['pilot_complete']=True;v.finish()
61
-
62
- def arctic(sequence=None,cameras=None,initialize=True):
63
- dataset='ARCTIC';seq=sequence or ARCTIC_SEQ;sid,action=seq.split('/');oid=action.split('_')[0];seqid=seq.replace('/','_')
64
- if initialize:setup(dataset,seqid)
65
- base=DATA_ROOT/dataset;raw=base/'raw/data'
66
- with zipfile.ZipFile(raw/'raw_seqs.zip') as z:
67
- if f'raw_seqs/{seq}.mano.npy' not in z.namelist():
68
- assert all(f'raw_seqs/{seq}.{x}.npy' not in z.namelist() for x in ['object','egocam.dist'])
69
- return arctic_unlabelled(seq,cameras)
70
- hand=native_npy_bytes(z.read(f'raw_seqs/{seq}.mano.npy'))
71
- ego=native_npy_bytes(z.read(f'raw_seqs/{seq}.egocam.dist.npy'))
72
- objects=native_npy_bytes(z.read(f'raw_seqs/{seq}.object.npy'))
73
- with zipfile.ZipFile(raw/'splits_json.zip') as z:splitdef=json.loads(z.read('splits_json/protocol_p1.json'))
74
- split=next((k for k,v in splitdef.items() if seq in v),'unknown')
75
- if split=='val':split='val'
76
- za=zipfile.ZipFile(raw/'meta.zip');misc=json.loads(za.read('meta/misc.json'))[sid]
77
- params=json.loads(za.read(f'meta/object_vtemplates/{oid}/object_params.json'))
78
- native_parts=np.asarray(json.loads(za.read(f'meta/object_vtemplates/{oid}/parts.json')),np.int64)
79
- models=[Mano('left'),Mano('right')];N=len(objects)
80
- 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
81
- 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()
82
- kp=np.concatenate([params['keypoints_top'],params['keypoints_bottom']])/1000;n_top=len(params['keypoints_top'])
83
- source={'archive':f'raw/data/images_zips/{seq}.zip','member_pattern':'{camera_id}/{source_frame_id:05d}.jpg'}
84
- zimage=zipfile.ZipFile(raw/f'images_zips/{seq}.zip')
85
- names=sorted(n for n in zimage.namelist() if re.fullmatch(r'[0-8]/[0-9]+\.jpg',n))
86
- extra=[n for n in zimage.namelist() if n.endswith('.jpg') and not re.fullmatch(r'[0-8]/[0-9]+\.jpg',n)]
87
- assert all(n.startswith('__MACOSX/') or Path(n).name.startswith('._') for n in extra),extra[:5]
88
- for cam in sorted({n.split('/')[0] for n in names},key=int):
89
- if cameras is not None and cam not in cameras:continue
90
- 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']
91
- size=list(Image.open(io.BytesIO(zimage.read(selected[0]))).size)
92
- assert size==misc['image_size'][int(cam)]
93
- v=FreshView(dataset,seqid,cam,ids,size,dict(source,camera_id=cam))
94
- if (v.p/'metainfo.json').exists():
95
- old=load(v.p/'metainfo.json')
96
- if old.get('pilot_complete') and old.get('num_frames')==len(ids):print('RESUME verified view',seq,cam,flush=True);continue
97
- t=v.T;good=(ix>=0)&(ix<N)
98
- 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')
99
- v.m['sampling'].update(source_fps=None,source_fps_reason='Actual capture FPS not asserted by the selected raw files; frame indices and official synchronization offset retained',selection='Every released image of this selected camera in the complete official sequence ZIP; boundary images without annotations retained')
100
- srcanno={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.mano.npy','index_ref':'camera/frames.jsonl:source_annotation_index'}
101
- srccam={'archive':'raw/data/meta.zip','member':'meta/misc.json','record':sid}
102
- E=np.broadcast_to(np.eye(4),(t,4,4)).copy()
103
- if cam=='0':
104
- K=np.broadcast_to(ego['intrinsics'],(t,3,3));D=np.broadcast_to(ego['dist8'],(t,8))
105
- 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)
106
- src={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.egocam.dist.npy'}
107
- v.m['camera'].update(model='rational8',schema_id='camera/rational8/v1')
108
- v.array('intrinsic','camera/intrinsic.pt','camera/rational8/v1',K,np.ones(t,bool),['T','row','column'],source=src,distortion_ref='camera/distortion.pt')
109
- tensor(v.p/'camera/distortion.pt',np.asarray(D,np.float32));validE=good
110
- else:
111
- 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
112
- v.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
113
- v.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',K,np.ones(t,bool),['T','row','column'],source=srccam)
114
- v.array('extrinsic','camera/extrinsic.pt','transform/se3/v1',E,validE,['T','row','column'],source=src,unit='m',convention='T_camera_from_world')
115
- assert_se3(E[validE]);motion=np.full((t,2,61),np.nan)
116
- for side,model in enumerate(models):
117
- h=hand[['left','right'][side]];pose=np.c_[h['rot'],h['pose']].copy();pose[:,3:]+=model.data['hands_mean']
118
- result,err=camera_mano(model,pose[ix[good]],np.broadcast_to(h['shape'],(good.sum(),10)),h['trans'][ix[good]],E[good])
119
- motion[good,side]=result
120
- # Independent source-model mean configuration, separate from camera conversion algebra.
121
- from types import SimpleNamespace
122
- import smplx
123
- 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)
124
- checkidx=np.arange(0,N,max(1,N//12));b=torch.tensor(np.broadcast_to(h['shape'],(len(checkidx),10)).copy(),dtype=torch.float32)
125
- 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()
126
- actual=model.geometry(pose[checkidx],b.numpy(),h['trans'][checkidx])[0]
127
- delta=float(np.max(np.linalg.norm(expected-actual,axis=-1)));assert delta<2e-6
128
- 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})
129
- 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')
130
- for i,(row,name,j) in enumerate(zip(v.frames,selected,ix)):
131
- row.update(source_annotation_index=int(j) if good[i] else None,sync_id=f'{seq}:{ids[i]}')
132
- row['source_locator'].update(member=name)
133
- 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])}}
134
- rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';object_textured_assets(za,f'meta/object_vtemplates/{oid}/',assets)
135
- # Parse exact OBJ vertex ordering before loading a render-oriented mesh.
136
- 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 ')])
137
- # Official ObjectTensors adds 1 to raw parts, then articulates ==1: raw 0 is TOP.
138
- shared_parts=1-native_parts
139
- assert len(vertices)==len(native_parts);tensor(op/'vertex_part_ids.pt',shared_parts)
140
- 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]]
141
- srcobj={'archive':'raw/data/raw_seqs.zip','member':f'raw_seqs/{seq}.object.npy','index_ref':'camera/frames.jsonl:source_annotation_index'}
142
- for name,data in [('root',P),('bottom',P),('top',top)]:
143
- path=rel+('/pose.pt' if name=='root' else f'/parts/{name}/pose.pt')
144
- 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')
145
- assert_se3(data[good])
146
- 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')
147
- 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'}],
148
- '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']}
149
- save(op/'articulation.json',articulation)
150
- v.component('object_'+oid+'_articulation',rel+'/articulation.json','object/articulated/v1',[],np.array(True),source=srcobj,static=True)
151
- sourceasset={'archive':'raw/data/meta.zip','member_prefix':f'meta/object_vtemplates/{oid}/'}
152
- v.mesh(oid,rel+'/assets/mesh.obj',sourceasset)
153
- topology=digest(assets/'mesh.obj')
154
- 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})
155
- xyz=np.full((t,len(kp),3),np.nan);errs=[]
156
- for i in np.flatnonzero(good):
157
- 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]
158
- 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]
159
- 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()))
160
- assert max(errs)<2e-5
161
- 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')
162
- 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())]})
163
- 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'}
164
- print('MEDIA',dataset,cam,t,flush=True);jpeg_video(v,((n,zimage.read(n)) for n in selected))
165
- v.m['pilot_complete']=True;v.finish()
166
- zimage.close();za.close()
167
-
168
- def vrs_records(path,cam):
169
- raw=command([VRS,'print-json',path,'+',cam,'+','data']).decode(errors='replace')
170
- rows=[]
171
- for line in raw.splitlines():
172
- if line.startswith('{"data_layout"'):rows.append({x['name']:x['value'] for x in json.loads(line)['data_layout']})
173
- return rows
174
-
175
- def nearest(times,query,limit):
176
- times=np.asarray(times,np.int64);q=np.asarray(query,np.int64)
177
- if not len(times):return np.zeros(len(q),np.int64),np.zeros(len(q),bool),np.zeros(len(q),np.int64)
178
- j=np.searchsorted(times,q);a=np.clip(j-1,0,len(times)-1);b=np.clip(j,0,len(times)-1)
179
- ix=np.where(np.abs(times[a]-q)<=np.abs(times[b]-q),a,b);delta=times[ix]-q
180
- return ix,np.abs(delta)<=limit,delta
181
-
182
- def verify_hot3d_frame_order_and_metadata(sequence=None):
183
- """Independent extraction-index and VRS capture-rate check, also on resume."""
184
- seq=sequence or HOT3D_SEQ
185
- base=DATA_ROOT/'HOT3D';src=base/'raw/data/Aria'/seq;recording=next(src.glob('*.vrs'))
186
- extract=base/'tmp'/RUN/seq/'images'
187
- for cam in ['214-1','1201-1','1201-2']:
188
- p=base/RELEASE/'data'/seq/cam;m=load(p/'metainfo.json');rows=vrs_records(recording,cam)
189
- paths=sorted(extract.glob(cam+'-*.jpg'))
190
- indices=[int(x.name.split('-')[-2]) for x in paths];assert indices==list(range(1,len(rows)+1))
191
- 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
192
- assert np.max(np.abs(file_times-times))<.001,'extracted images do not match camera record ordering'
193
- raw=command([VRS,'print-json',recording,'+',cam,'+','configuration']).decode(errors='replace')
194
- 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]
195
- rate=cfg['nominal_rate'];assert abs(np.median(np.diff(times))-1/rate)<.001
196
- m['sampling']['source_fps']=rate
197
- m['sampling']['source_fps_basis']='VRS camera configuration nominal_rate; actual intervals checked separately'
198
- m['sampling']['duration_seconds']=float(times[-1]-times[0])
199
- frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
200
- for frame in frames:
201
- for match in frame['annotation_matches'].values():
202
- if 'available' in match:match['source_record_present']=match.pop('available')
203
- lines(p/'camera/frames.jsonl',frames)
204
- info=load(base/'raw/data/assets/object_models/models_info.json')
205
- reverse={str(v['original_id']):str(k) for k,v in info.items()}
206
- for op in (p/'annotation/object').glob('*'):
207
- om=load(op/'metainfo.json');oid=om['object_id'];idx=int(reverse[oid])
208
- glb=base/'raw/data/assets/object_models'/f'obj_{idx:06d}.glb';assert glb.is_file()
209
- # Retain the official material-bearing companion byte-for-byte. OBJ remains the declared standard mesh.
210
- target=op/'assets'/glb.name;shutil.copyfile(glb,target)
211
- assert digest(glb)==digest(target)
212
- 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'})
213
- save(op/'metainfo.json',om)
214
- save(p/'metainfo.json',m)
215
- checkpath=base/'tmp'/RUN/'checks'/f'{seq}__{cam}.json';checks=load(checkpath)
216
- checks['checks']=[c for c in checks['checks'] if c['test']!='VRS_extracted_filename_order_and_nominal_rate']
217
- 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)
218
-
219
- def hot3d(sequence=None,initialize=True):
220
- dataset='HOT3D';seq=sequence or HOT3D_SEQ
221
- if initialize:setup(dataset,seq)
222
- base=DATA_ROOT/dataset;raw=base/'raw/data';src=raw/'Aria'/seq;tmp=base/'tmp'/RUN
223
- recording=next(src.glob('*.vrs'));extract=tmp/seq/'images'
224
- if not (tmp/seq/'extracted.json').exists() or not extract.exists() or not any(extract.glob('*.jpg')):
225
- extract.mkdir(parents=True,exist_ok=True)
226
- log=tmp/seq/'vrs-extraction.log'
227
- with log.open('wb') as out:
228
- run=subprocess.run([str(VRS),'extract-images',str(recording),'--to',str(extract),'+','214-1','+','1201-1','+','1201-2'],stdout=out,stderr=subprocess.STDOUT)
229
- assert run.returncode==0,'VRS extraction failed; see tmp log'
230
- save(tmp/seq/'extracted.json',{'source':recording.name,'streams':['214-1','1201-1','1201-2'],'complete':True})
231
- gt=zipfile.ZipFile(next(src.glob('*ground_truth.zip')));handszip=zipfile.ZipFile(next(src.glob('*hand_data.zip')))
232
- 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']))
233
- assert meta['headset']=='Aria' and meta['recording_name']==seq
234
- 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)
235
- heads={int(r['timestamp[ns]']):csv_transform(r) for r in loadzipcsv(gt,'headset_trajectory.csv')};head_times=sorted(heads)
236
- 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)
237
- objects=loadzipcsv(gt,'dynamic_objects.csv');vis_h=loadzipcsv(gt,'box2d_hands.csv');vis_o=loadzipcsv(gt,'box2d_objects.csv')
238
- models=[Mano('left'),Mano('right')];fixed=np.abs(models[0].data['shapedirs'][:,0]-models[1].data['shapedirs'][:,0]).sum()<1
239
- if fixed:
240
- models[0].data['shapedirs'][:,0]*=-1
241
- with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
242
- 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()}
243
- for camera in cams:
244
- cam=camera['stream_id'];rows=vrs_records(recording,cam);paths=sorted(extract.glob(cam+'-*.jpg'))
245
- assert len(rows)==len(paths)>1,(cam,len(rows),len(paths))
246
- 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})
247
- if (v.p/'metainfo.json').exists() and load(v.p/'metainfo.json').get('pilot_complete'):print('RESUME verified view',cam,flush=True);continue
248
- t=v.T;capture=np.array([int(r['capture_timestamp_ns']) for r in rows],np.int64)
249
- ix,good,delta=nearest(dev,capture,1000);assert good.all(),'Missing official device-time/timecode mapping'
250
- times=tc[ix];sourcegt={'archive':next(src.glob('*ground_truth.zip')).relative_to(base).as_posix()}
251
- test_ids={'P0004','P0005','P0006','P0008','P0016','P0020'}
252
- split='test' if meta['participant_id'] in test_ids else 'train'
253
- assert meta['have_hand_object_pose_gt']==(split=='train')
254
- 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'])
255
- 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))))
256
- 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'])
257
- 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))
258
- dc=camera['T_Device_Camera'];Tdc=transform(dc['quaternion_wxyz'],dc['translation_xyz'])
259
- hi,hvalid,hdelta=nearest(head_times,times,1_000_000);E=np.full((t,4,4),np.nan)
260
- for i in np.flatnonzero(hvalid):E[i]=np.linalg.inv(heads[head_times[hi[i]]]@Tdc)
261
- assert hvalid.all(),'Headset GT missing at image times'
262
- 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')
263
- mi,mvalid,mdelta=nearest(hand_times,times,1_000_000);motion=np.full((t,2,61),np.nan);valid=np.zeros((t,2),bool)
264
- for side,model in enumerate(models):
265
- chosen=[i for i in range(t) if mvalid[i] and str(side) in hands[hand_times[mi[i]]]]
266
- if not chosen:continue
267
- native=[hands[hand_times[mi[i]]][str(side)] for i in chosen];pose=[];beta=[];trans=[]
268
- for h in native:
269
- 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'])
270
- motion[chosen,side],err=camera_mano(model,pose,beta,trans,E[chosen]);valid[chosen,side]=True
271
- # Official source model uses PCA15 and nonflat mean, unlike output AA48.
272
- import smplx
273
- from types import SimpleNamespace
274
- 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)
275
- ixcheck=np.arange(0,len(chosen),max(1,len(chosen)//16));arr=np.asarray(pose);bet=np.asarray(beta);tr=np.asarray(trans)
276
- 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()
277
- 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
278
- 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})
279
- if hand_times:
280
- 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')
281
- def vis_values(records,identity_field,identities):
282
- out=np.full((t,len(identities)),np.nan)
283
- for c,identity in enumerate(identities):
284
- 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[%]']!=''}
285
- if not values:continue
286
- ts=sorted(values);ii,vv,dd=nearest(ts,times,1_000_000)
287
- for i in np.flatnonzero(vv):out[i,c]=values[ts[ii[i]]]
288
- return out
289
- if hand_times and vis_h:
290
- 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')
291
- for i,row in enumerate(v.frames):
292
- 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]))
293
- row['source_locator'].update(record_index=i,capture_timestamp_ns=int(capture[i]))
294
- row['annotation_matches']={}
295
- for key,ts,idxs,flags,dd in [('extrinsic',head_times,hi,hvalid,hdelta),('mano',hand_times,mi,mvalid,mdelta)]:
296
- 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])}
297
- for oid in sorted(set(meta['object_uids'])|{r['object_uid'] for r in objects}):
298
- rel=f'annotation/object/{oid}';op=v.p/rel;assets=op/'assets';assets.mkdir(parents=True,exist_ok=True)
299
- 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)
300
- P=np.full((t,4,4),np.nan)
301
- for i in np.flatnonzero(ok):P[i]=E[i]@sourceposes[ts[oi[i]]]
302
- key=f'object_{oid}_pose'
303
- if sourceposes:
304
- 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')
305
- 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])}
306
- if sourceposes and vis_o:
307
- 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')
308
- idx=int(reverse[oid]);prefix=f'models/obj_{idx:06d}'
309
- for member in assetszip.namelist():
310
- if member.startswith(prefix+'.'):(assets/Path(member).name).write_bytes(assetszip.read(member))
311
- ply=assets/f'obj_{idx:06d}.ply';mesh=trimesh.load(ply,process=False,force='mesh');mesh.vertices=np.asarray(mesh.vertices)*.001
312
- expected_extent=np.array([assetinfo[str(idx)]['size_'+x] for x in 'xyz']);assert np.allclose(mesh.extents,expected_extent,atol=1e-5)
313
- text,textures=trimesh.exchange.obj.export_obj(mesh,return_texture=True,digits=12);meshpath=assets/f'obj_{idx:06d}.obj';meshpath.write_text(text)
314
- for filename,data in textures.items():(assets/filename).write_bytes(data)
315
- restored=trimesh.load(meshpath,process=False,force='mesh');assert np.allclose(restored.triangles,mesh.triangles,atol=1e-7)
316
- assert np.array_equal(np.asarray(restored.visual.material.image),np.asarray(mesh.visual.material.image))
317
- # Keep the official GLB as a companion asset so richer original material properties remain available.
318
- glb=raw/'assets'/f'{oid}.glb'
319
- if glb.exists():shutil.copyfile(glb,assets/glb.name)
320
- # The millimetre PLY was a temporary converter input, not a second shared geometry convention.
321
- assert ply.resolve().is_relative_to(assets.resolve());ply.unlink()
322
- sourceasset={'archive':'raw/data/assets/hot3d_models.zip','member':prefix+'.ply','original_id':oid,'bop_id':idx}
323
- v.mesh(oid,meshpath.relative_to(v.p).as_posix(),sourceasset)
324
- 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})
325
- 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})
326
- v.checks.append({'test':'all_camera_frame_device_time_mapping','frames':t,'max_delta_ns':int(np.abs(delta).max()),'passed':True})
327
- 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'}
328
- if not hand_times:v.m['omitted_components']['mano']='Official MANO trajectory is empty; no pose labels released for this sequence'
329
- if not objects:v.m['omitted_components']['object_pose']='Official object trajectory is empty; static source models retained without fabricated pose arrays'
330
- print('MEDIA',dataset,cam,t,flush=True);jpeg_video(v,((p.name,p.read_bytes()) for p in paths))
331
- v.m['pilot_complete']=True;v.finish()
332
- assetszip.close();gt.close();handszip.close()
333
-
334
- if __name__=='__main__':
335
- p=argparse.ArgumentParser();p.add_argument('dataset',choices=['ARCTIC','HOT3D']);a=p.parse_args()
336
- torch.set_num_threads(4)
337
- {'ARCTIC':arctic,'HOT3D':hot3d}[a.dataset]()
338
- if a.dataset=='HOT3D':
339
- verify_hot3d_frame_order_and_metadata()
340
- from apply_hot3d_qa import apply_qa
341
- apply_qa()
342
- elif (DATA_ROOT/'ARCTIC'/RELEASE/'doc/validation/exposure.json').exists():
343
- from repair_arctic_pilot import repair
344
- repair()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/diagnose_arctic_review.py DELETED
@@ -1,125 +0,0 @@
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]()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/fresh_sequence_common.py DELETED
@@ -1,176 +0,0 @@
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
-
14
- DATA_ROOT = Path('E:/hand-datasets')
15
- RELEASE = 'shared-v1.0'
16
- RUN = 'fresh-sequence-pilot-20260920'
17
- VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
18
-
19
- def digest(p):
20
- h=hashlib.sha256()
21
- with Path(p).open('rb') as f:
22
- for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
23
- return h.hexdigest()
24
-
25
- def native_npy_bytes(data):
26
- f=io.BytesIO(data);version=np.lib.format.read_magic(f)
27
- shape,order,dtype=np.lib.format._read_array_header(f,version)
28
- if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
29
- return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()
30
-
31
- def command(args):
32
- r=subprocess.run([str(x) for x in args],capture_output=True)
33
- if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
34
- return r.stdout
35
-
36
- def framehash(args,copy=False):
37
- output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
38
- *(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
39
- '-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
40
- return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]
41
-
42
- def jpeg_video(view, members):
43
- """members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
44
- temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
45
- temporary.parent.mkdir(parents=True,exist_ok=True)
46
- hashes=[]
47
- with temporary.open('wb') as out:
48
- for locator,b in members:
49
- assert b[:2]==b'\xff\xd8',locator
50
- hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
51
- assert len(hashes)==view.T
52
- dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
53
- source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
54
- command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
55
- packet=framehash(['-i',str(dst)],True)
56
- assert packet==hashes,'source JPEG packets changed in MKV'
57
- before=framehash(source);after=framehash(['-i',str(dst)])
58
- assert before==after and len(before)==view.T,'RGB decoding differs'
59
- w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
60
- info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
61
- line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
62
- pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
63
- version=command([FF,'-version']).decode().splitlines()[0]
64
- view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
65
- source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
66
- storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
67
- 'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
68
- 'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
69
- view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
70
- 'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
71
- 'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
72
- save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
73
- # This precise file was created by this call within the current run's temporary directory.
74
- assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()
75
-
76
- class FreshView:
77
- def __init__(self,dataset,seq,cam,ids,size,source):
78
- self.root=DATA_ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
79
- self.tmp=DATA_ROOT/dataset/'tmp'/RUN;self.p.mkdir(parents=True,exist_ok=True)
80
- self.T=len(ids);self.source=source;self.checks=[]
81
- self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
82
- 'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
83
- 'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
84
- 'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
85
- 'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
86
- self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
87
- 'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
88
- def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
89
- valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
90
- self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
91
- 'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
92
- 'source_locator':source or self.source,**kw}
93
- def array(self,name,path,schema,data,valid,axes,**kw):
94
- a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
95
- assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
96
- assert np.isfinite(a[valid]).all(),name
97
- a[~valid]=np.nan;tensor(self.p/path,a)
98
- self.component(name,path,schema,axes,valid,**kw)
99
- restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
100
- assert np.array_equal(a,restored,equal_nan=True)
101
- self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
102
- def attribute(self,parent,path,data,axes,source,meaning):
103
- data=np.asarray(data,np.float32);valid=np.isfinite(data)
104
- assert ((data[valid]>=0)&(data[valid]<=1)).all()
105
- vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
106
- self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
107
- 'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
108
- 'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
109
- def mesh(self,oid,path,source):
110
- self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
111
- method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
112
- def finish(self):
113
- lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
114
- save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
115
- print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
116
-
117
- def assert_se3(a):
118
- a=np.asarray(a);assert a.shape[-2:]==(4,4)
119
- # A component may exist while QA leaves no usable poses in this view.
120
- if a.size==0:return
121
- assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
122
- r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
123
- assert np.max(np.abs(np.linalg.det(r)-1))<2e-5
124
-
125
- def setup(dataset,seq):
126
- base=DATA_ROOT/dataset;out=base/RELEASE
127
- for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
128
- for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
129
- save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
130
- sources=['fresh_sequence_common.py','convert_fresh_sequence_pilots.py','pilot_build.py','pilot_fetch.py','pilot_mano.py',
131
- 'sequence_pilot_common.py','sequence_pilot_world.py','pilot_hot_normalize.py','audit_source_fields.py']
132
- for name in sources:
133
- if (WORK/'scripts'/name).exists():shutil.copyfile(WORK/'scripts'/name,out/'script'/name)
134
- (base/'tmp'/RUN).mkdir(parents=True,exist_ok=True)
135
-
136
- def object_textured_assets(z,prefix,target):
137
- target.mkdir(parents=True,exist_ok=True)
138
- for name in z.namelist():
139
- if not name.startswith(prefix) or name.endswith('/'):continue
140
- rel=Path(name[len(prefix):]);dest=target/rel
141
- assert dest.resolve().is_relative_to(target.resolve());dest.parent.mkdir(parents=True,exist_ok=True)
142
- if dest.suffix.lower() in ('.obj','.mtl','.jpg','.jpeg','.png'):
143
- b=z.read(name)
144
- if dest.suffix=='.obj':
145
- rows=b.decode().splitlines()
146
- for i,row in enumerate(rows):
147
- if row.startswith('v '):
148
- v=row.split();v[1:4]=[format(float(x)/1000,'.17g') for x in v[1:4]];rows[i]=' '.join(v)
149
- b=('\n'.join(rows)+'\n').encode()
150
- dest.write_bytes(b)
151
- repair_arctic_material_refs(target)
152
-
153
- def repair_arctic_material_refs(target):
154
- """Repair a source filename mismatch only when material identifiers agree."""
155
- material=target/'material.mtl'
156
- if not material.exists():return
157
- ids={x.split(maxsplit=1)[1] for x in material.read_text().splitlines() if x.startswith('newmtl ')}
158
- for obj in target.glob('*.obj'):
159
- text=obj.read_text();rows=text.splitlines();used={x.split(maxsplit=1)[1] for x in rows if x.startswith('usemtl ')}
160
- if 'mtllib material_0.mtl' in rows and not (target/'material_0.mtl').exists():
161
- assert used and used.issubset(ids),(obj,used,ids)
162
- obj.write_text(text.replace('mtllib material_0.mtl','mtllib material.mtl'))
163
-
164
- def project_points(xyz,camera,params):
165
- xyz=np.asarray(xyz,float);uv=np.full((len(xyz),2),np.nan);good=np.isfinite(xyz).all(1)&(xyz[:,2]>1e-6)
166
- if camera=='fisheye624':
167
- p=np.asarray(params);xy=xyz[good,:2]/xyz[good,2,None];r=np.linalg.norm(xy,axis=1);th=np.arctan(r)
168
- radial=th*(1+sum(p[3+i]*th**(2*i+2) for i in range(6)))
169
- xy=xy*np.divide(radial,r,out=np.ones_like(r),where=r>1e-12)[:,None]
170
- x,y=xy.T;rr=x*x+y*y
171
- xd=x+(2*x*x+rr)*p[9]+2*x*y*p[10]+p[11]*rr+p[12]*rr*rr
172
- yd=y+(2*y*y+rr)*p[10]+2*x*y*p[9]+p[13]*rr+p[14]*rr*rr
173
- uv[good]=p[0]*np.stack([xd,yd],1)+p[1:3]
174
- else:
175
- K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
176
- return uv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
HOT3D/shared-v1.0/script/history/pre-acceleration-20260920/pilot_build.py DELETED
@@ -1,209 +0,0 @@
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
- for script in ['pilot_build.py','pilot_fetch.py']:
82
- shutil.copyfile(WORK/'scripts'/script,self.out/'script'/script)
83
- (self.out/'script/README.md').write_text('执行入口:工作区 scripts/pilot_build.py --dataset '+self.name+'。此目录为脚本快照;脚本当前依赖工作区的 datasets 与 tmp/pilot-runtime,尚不是独立发布包。\n',encoding='utf-8')
84
- 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()]
85
- save(self.out/'doc/output_manifest.json',files)
86
- print(json.dumps(report,ensure_ascii=False),flush=True)
87
- return report
88
-
89
- def h2o():
90
- b=Build('H2O');src=OLD/'H2O/subject4_ego/h1/0/cam4';ids=list(range(N))
91
- p,m=b.view('subject4_h1_0','cam4',ids,split='test',view_type='ego',time_semantics='ordered_source_frames; acquisition FPS not yet verified')
92
- for folder in ['rgb','depth','hand_pose','hand_pose_mano','cam_pose']:
93
- for i in ids:b.copy(src/folder/f'{i:06d}.{ "png" if folder in ["rgb","depth"] else "txt"}')
94
- intr=np.loadtxt(b.copy(src/'cam_intrinsics.txt'));fx,fy,cx,cy,w,h=intr
95
- tensor(p/'camera/intrinsic.pt',np.array([[fx,0,cx],[0,fy,cy],[0,0,1]],np.float32))
96
- ext=np.stack([np.loadtxt(src/'cam_pose'/f'{i:06d}.txt').reshape(4,4) for i in ids])
97
- tensor(p/'camera/extrinsic.pt',np.linalg.inv(ext).astype(np.float32))
98
- 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'}
99
- a=np.stack([np.loadtxt(src/'hand_pose_mano'/f'{i:06d}.txt').reshape(2,62) for i in ids])
100
- valid=a[:,:,0]==1;motion=np.concatenate([a[:,:,4:52],a[:,:,52:62],a[:,:,1:4]],axis=-1).astype(np.float32)
101
- motion[~valid]=np.nan;tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',valid)
102
- 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'}
103
- 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)
104
- rgb=[np.asarray(Image.open(src/'rgb'/f'{i:06d}.png').convert('RGB')) for i in ids]
105
- depth=[np.asarray(Image.open(src/'depth'/f'{i:06d}.png'),dtype=np.uint16) for i in ids]
106
- 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'}
107
- m['missing_modalities']={'object':'not present in selected historical subset','segmentation':'no native mask in selected subset'}
108
- # Independent check: 3D keypoint projections must be finite where the source flags valid.
109
- xyz=joints[:,:,1:].reshape(N,2,21,3);projection=xyz@np.array([[fx,0,cx],[0,fy,cy],[0,0,1]]).T
110
- uv=projection[...,:2]/projection[...,2:];assert np.isfinite(uv[joints[:,:,0]==1]).all()
111
- image=Image.fromarray(rgb[0]);draw=ImageDraw.Draw(image)
112
- for side in range(2):
113
- for u,v in uv[0,side]:draw.ellipse((u-3,v-3,u+3,v+3),fill=('red' if side==0 else 'cyan'))
114
- image.save(b.out/'doc/keypoints_overlay.png')
115
- return b.finish(['MANO geometry not rendered; model asset unavailable. RGB-depth registration not tested. No native segmentation or object input in subset.'])
116
-
117
- def visor():
118
- 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'
119
- source=load(jp);annotations=source['video_annotations'][:N]
120
- 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')
121
- rgbs=[];masks=[];records=[]
122
- with zipfile.ZipFile(zp) as z:
123
- assert z.testzip() is None
124
- for i,frame in enumerate(annotations):
125
- rgb=np.asarray(Image.open(io.BytesIO(z.read(frame['image']['name']))).convert('RGB'));rgbs.append(rgb)
126
- mask=np.zeros((1080,1920),np.uint16);entities=[]
127
- for value,entity in enumerate(frame['annotations'],1):
128
- # Same polygon rasterization primitive and integer conversion as official VISOR-VIS.
129
- polygons=[np.asarray(poly,dtype=np.int32) for poly in entity['segments'] if len(poly)>=3]
130
- if polygons:cv2.fillPoly(mask,polygons,int(value))
131
- entities.append({'mask_value':value,'instance_id':entity['id'],'track_id':None,'source':{k:v for k,v in entity.items() if k!='segments'}})
132
- if mask.shape!=rgb.shape[:2]:mask=cv2.resize(mask,(rgb.shape[1],rgb.shape[0]),interpolation=cv2.INTER_NEAREST)
133
- masks.append(mask);records.append({'frame_index':i,'source_frame_id':frame['image']['name'],'subsequence':frame['image']['subsequence'],'annotation_valid':True,'instances':entities})
134
- assert set(np.unique(mask)) <= {0,*[x['mask_value'] for x in entities]}
135
- 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'}
136
- lines(p/'annotation/segmentation/instances.jsonl',records)
137
- m['missing_modalities']={'mano':'not supplied','depth':'not supplied','camera':'not supplied','object_pose_mesh':'not supplied'}
138
- 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)
139
- used=mask>0;im[used]=(im[used]*0.55+colors[mask[used]%len(colors)]*0.45).astype(np.uint8)
140
- Image.fromarray(im).save(b.out/'doc/segmentation_overlay.png')
141
- b.checks.append({'test':'official_zip_crc_all_members','passed':True,'members':len(zipfile.ZipFile(zp).namelist())})
142
- b.checks.append({'test':'all_mask_values_resolve_to_frame_instances','passed':True})
143
- return b.finish([])
144
-
145
- def rhd():
146
- b=Build('RHD');src=OLD/'RHD/RHD_published_v2/evaluation';ann=read_pickle(b.copy(src/'anno_evaluation.pickle'))
147
- for i in range(N):
148
- p,m=b.view(f'evaluation_{i:05d}','camera',[i],split='evaluation',time_semantics='independent_image')
149
- rgb=np.asarray(Image.open(b.copy(src/'color'/f'{i:05d}.png')).convert('RGB'))
150
- depth=np.asarray(Image.open(b.copy(src/'depth'/f'{i:05d}.png')).convert('RGB'),dtype=np.uint16)
151
- code=depth[:,:,0]*256+depth[:,:,1]
152
- 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'}
153
- 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))
154
- 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'}
155
- m['missing_modalities']={'mano':'not supplied by source','segmentation':'omitted by historical downloader','extrinsic':'not supplied in selected annotations'}
156
- return b.finish(['Depth metric conversion pending; segmentation absent from historical input.'])
157
-
158
- def freihand():
159
- 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'))
160
- for base in range(4):
161
- for variant in range(4):
162
- 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)
163
- m['camera_group_semantics']='image_variant_not_physical_camera';m['physical_camera_id']=None
164
- 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])
165
- 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))
166
- 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.'}
167
- m['missing_modalities']={'depth':'not supplied','segmentation':'not present in historical input','extrinsic':'not supplied','normalized_mano':'model dependency unresolved'}
168
- return b.finish(['Preserved source MANO theta; no misleading motion.pt produced. Correct model needed for normalized translation.'])
169
-
170
- def hoi4d():
171
- b=Build('HOI4D');rel=Path('ZY20210800001/H1/C20/N18/S286/s01/T1');src=OLD/'HOI4D/Hand_pose/handpose_left_hand'/rel
172
- files=sorted(src.glob('*.pickle'),key=lambda p:int(p.stem))[:N];ids=[x.stem for x in files]
173
- p,m=b.view('H1_C20_N18_S286_s01_T1','ZY20210800001',ids,view_type='ego',time_semantics='annotation_frame_ids_only')
174
- 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)
175
- for i,frame in enumerate(ids):
176
- for side,folder in enumerate(['handpose_left_hand','handpose_right_hand']):
177
- f=OLD/'HOI4D/Hand_pose'/folder/rel/(frame+'.pickle')
178
- if not f.exists():continue
179
- 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']
180
- tensor(p/'annotation/mano/motion.pt',a);tensor(p/'annotation/mano/valid_flag.pt',v);tensor(p/'annotation/keypoints/uv.pt',uv)
181
- tensor(p/'camera/intrinsic.pt',np.load(b.copy(OLD/'HOI4D/camera_params/ZY20210800001/intrin.npy'),allow_pickle=False))
182
- 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'}
183
- m['missing_modalities']={'rgb':'not downloaded','depth':'not downloaded','segmentation':'not downloaded','extrinsic':'not available in selected subset','object':'not available in selected subset'}
184
- return b.finish(['Annotation-only mini; no matching RGB/depth/segmentation downloaded. MANO geometry not rendered.'])
185
-
186
- def reinterhand():
187
- 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]
188
- # Capture-level poses have no established camera transform in current local subset.
189
- p,m=b.view(src.name,'source_unresolved',ids,time_semantics='capture_annotations_only; not a camera observation')
190
- rows=[]
191
- for frame in ids:
192
- row={'source_frame_id':frame,'hands':{}}
193
- for side in ['left','right']:
194
- f=src/'mano_fits/params'/f'{frame}_{side}.json'
195
- if f.exists():row['hands'][side]=load(b.copy(f))
196
- rows.append(row)
197
- lines(p/'annotation/mano/source_parameters.jsonl',rows)
198
- m['missing_modalities']={'rgb':'not extracted from incomplete archive set','camera':'not available','normalized_mano':'source-to-camera mapping unresolved'}
199
- m['not_a_real_camera']=True
200
- return b.finish(['Source-only annotation sample. source_unresolved is an explicit staging group, not an invented camera.'])
201
-
202
- def main():
203
- parser=argparse.ArgumentParser();parser.add_argument('--dataset',nargs='*',default=['VISOR','H2O','RHD','FreiHAND','HOI4D','ReInterHand']);args=parser.parse_args()
204
- funcs={'VISOR':visor,'H2O':h2o,'RHD':rhd,'FreiHAND':freihand,'HOI4D':hoi4d,'ReInterHand':reinterhand}
205
- for name in args.dataset:
206
- try:funcs[name]()
207
- except Exception as e:
208
- save(ROOT/name/'pilot-v0/doc/build_error.json',{'error':str(e)});raise
209
- if __name__=='__main__':main()