shaoyz commited on
Commit
d378823
·
verified ·
1 Parent(s): feed8dc

Simplify FreiHAND shared-v1.0 scripts

Browse files
FreiHAND/shared-v1.0/doc/RAW_MAPPING.md CHANGED
@@ -16,6 +16,6 @@
16
 
17
  标准 float32 数组的序列化逐值校验;float64 源 JSON 转为规范 float32 可能发生舍入,不能把整个语义转换称为源文件逐字节无损。RGB/分割视频编码相对于指定解码像素不增加损失;原 JPEG 已有的损失不会恢复。MANO 和源 xyz 是不同标注,拟合残差不能当作转换错误。
18
 
19
- 执行脚本为 convert_freihand_lossless.py,验收为 validate_freihand_release.py。依赖 Python、numpy、torch、Pillow、opencv-python、imageio-ffmpeg、smplx、requests,以及用户自行授权的 MANO v1.2 模型;模型权重不上传。脚本快照保留历史辅助模块,仅调用本发布转换入口;运行时 WORK 应指向工作目录,模型位于 tmp/pilot-models。完整原包直接按 ZIP 成员读取,不在 raw 中解压。
20
 
21
- 两个官方原始 ZIP 同时上传到 FreiHAND/raw/data,保持原字节不变。只有全量转换验收和 HF 固定提交下所有 raw ZIP 与 share 发布文件的大小与内容摘要匹配后,才允许删除 E 盘对应的两个原始 ZIP。doc 只保留原包 URL、大小、SHA256 等来源说明、字段映射与规范;script 保留转换代码。可分发的校验报告、人工预览、样本范围与验收结论保存在 doc/validation 并随 share 发布;运行日志、逐批调试记录与上传进度放 tmp,不上传,成功后清理。其他盘上的原始数据不会由该脚本删除。
 
16
 
17
  标准 float32 数组的序列化逐值校验;float64 源 JSON 转为规范 float32 可能发生舍入,不能把整个语义转换称为源文件逐字节无损。RGB/分割视频编码相对于指定解码像素不增加损失;原 JPEG 已有的损失不会恢复。MANO 和源 xyz 是不同标注,拟合残差不能当作转换错误。
18
 
19
+ 正式入口为 `script/convert_freihand.py`、`script/validate_freihand.py` 和 `script/render_full_random_review.py`,三者均无必填命令行参数,并从脚本自身位置定位本数据集的 `raw/`、`shared-v1.0/` 和 `tmp/`。依赖 Python、numpy、torch、Pillow、opencv-python、imageio-ffmpeg、smplx,以及用户自行授权的 MANO v1.2 模型;模型权重不上传。完整原包直接按 ZIP 成员读取,不在 raw 中解压。入口、内部模块及模型查找规则见 `script/README.md`。
20
 
21
+ 两个官方原始 ZIP 同时上传到 FreiHAND/raw/data,保持原字节不变。doc 只保留原包 URL、大小、SHA256 等来源说明、字段映射与规范;script 保留可直接运行的转换、校验和报告代码。可分发的校验报告、人工预览、样本范围与验收结论保存在 doc/validation 并随 share 发布;运行日志、逐批调试记录与上传进度放 tmp,不上传,成功后清理。转换和校验脚本不会删除或改写 raw;本地 raw 的保留或清理由项目级授权另行决定。
FreiHAND/shared-v1.0/script/README.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FreiHAND shared-v1.0 脚本
2
+
3
+ 本目录只服务于相邻的 `shared-v1.0`,所以命令不要求数据集路径、release 名称、分片大小或 split 参数。脚本可从任意工作目录运行,并根据自身位置找到:
4
+
5
+ - raw:`../../raw/data/`
6
+ - 产物:`../data/`
7
+ - 正式文档:`../doc/`
8
+ - 运行状态与内容指纹:`../../tmp/freihand-tools/`(不发布)
9
+
10
+ ## 标准命令
11
+
12
+ ```bash
13
+ python script/convert_freihand.py
14
+ python script/validate_freihand.py
15
+ python script/render_full_random_review.py
16
+ ```
17
+
18
+ 三个命令均无必填参数。`--help` 仅显示帮助。
19
+
20
+ ## 文件职责
21
+
22
+ - `convert_freihand.py`:从两个官方 ZIP 读取 RGB、相机、关键点、MANO 和分割,写入固定的 4096 张分片布局。完整的既有分片会跳过;不完整或布局不兼容的分片会使程序停止,避免混用产物。
23
+ - `validate_freihand.py`:按 `doc/schema.json` 检查全部视图、帧、组件、张量和媒体登记,核对官方 training/evaluation 数量,并为当前发布树生成 SHA256 内容指纹。SHA256 只固定审计时的字节,不能单独证明官方源正确、语义正确或视觉质量合格。
24
+ - `render_full_random_review.py`:使用固定种子从四种训练背景和 evaluation 分层抽样,直接读取全量产物,生成 `doc/validation/full_random/` 离线人工审查页面。
25
+ - `freihand_common.py`:上述入口共用的路径解析、JSON/张量写入、FFmpeg 和视图结构实现;不是单独入口。
26
+ - `mano_runtime.py`:只负责加载本地许可 MANO 模型并生成几何;模型不会复制到发布目录。
27
+
28
+ ## 环境
29
+
30
+ 需要 Python 3、NumPy、PyTorch、Pillow、OpenCV、`imageio-ffmpeg`、`smplx`。MANO v1.2 的 `MANO_RIGHT.pkl` 按下列顺序查找:
31
+
32
+ 1. 环境变量 `MANO_MODEL_DIR`
33
+ 2. `<FreiHAND>/tmp/models/mano/`
34
+ 3. `<FreiHAND>/tmp/pilot-models/`
35
+ 4. `~/.mano/models/`
36
+
37
+ 转换和报告会读取 MANO;结构校验不需要 MANO。脚本不会删除或改写 raw,不上传数据,也不会把自动检查写成人工通过。
FreiHAND/shared-v1.0/script/convert_freihand.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert the official FreiHAND archives into this shared-v1.0 release.
2
+
3
+ Run without arguments from any working directory. Existing complete shards are
4
+ validated and skipped; incomplete or incompatible shards stop the run.
5
+ """
6
+ from freihand_common import *
7
+ from mano_runtime import Mano
8
+ from PIL import Image
9
+ import argparse, io, re, zipfile
10
+ import hashlib
11
+
12
+ BaseView=View
13
+ class View(BaseView):
14
+ def finish(self):
15
+ lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
16
+ save(TMP_ROOT/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.json',{'checks':self.checks,'frames':self.T,'input':self.source})
17
+ print('Converted',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
18
+
19
+ def ff(args,data=None):
20
+ r=subprocess.run([FF,'-v','error','-y',*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
21
+ if r.returncode: raise RuntimeError(r.stderr.decode(errors='replace'))
22
+ return r.stdout
23
+
24
+ def storage(profile,codec,pix,size,lossy,params):
25
+ return dict(profile=profile,codec=codec,pixel_format=pix,encoded_size=size,source_lossy=lossy,
26
+ decoder=ff(['-version']).decode().splitlines()[0],encoder_parameters=params)
27
+
28
+ def main():
29
+ argparse.ArgumentParser(description='Convert FreiHAND raw archives into the adjacent shared-v1.0 release.').parse_args()
30
+ batch_size=4096;raw_root=RAW_ROOT
31
+ # Do not mix a new sharding layout with existing production intermediates.
32
+ existing=RELEASE_ROOT/'data'
33
+ for directory in existing.glob('*'):
34
+ if not directory.is_dir():continue
35
+ mp=directory/'camera/metainfo.json'
36
+ if not mp.exists():raise RuntimeError(f'Incomplete existing shard must be handled before rerun: {directory}')
37
+ previous=load(mp);start_index=int(directory.name.rsplit('_',1)[1])
38
+ total=130240 if directory.name.startswith('training_') else 3960
39
+ expected=min(batch_size,total-start_index)
40
+ if start_index%batch_size or previous['num_frames']!=expected:
41
+ raise RuntimeError(f'Existing shard layout differs from fixed {batch_size}: {directory}')
42
+ torch.set_num_threads(4)
43
+ model=None;summary=[]
44
+ for split,filename in [('training','FreiHAND_pub_v2.zip'),('evaluation','FreiHAND_pub_v2_eval.zip')]:
45
+ with zipfile.ZipFile(raw_root/filename) as z:
46
+ ks=np.asarray(json.loads(z.read(split+'_K.json')));xyz=np.asarray(json.loads(z.read(split+'_xyz.json')))
47
+ theta=np.asarray(json.loads(z.read(split+'_mano.json'))).reshape(-1,61)
48
+ n=len(ks);assert len(xyz)==len(theta)==n
49
+ rgbnames=sorted(s for s in z.namelist() if s.startswith(split+'/rgb/') and s.endswith('.jpg'))
50
+ assert len(rgbnames)==n*(4 if split=='training' else 1)
51
+ for start in range(0,len(rgbnames),batch_size):
52
+ names=rgbnames[start:start+batch_size];ids=[int(Path(s).stem) for s in names];ix=np.asarray(ids)%n;t=len(ids)
53
+ seq=f'{split}_{start:08d}';source_locator={'archive':'raw/data/'+filename}
54
+ complete=RELEASE_ROOT/'data'/seq/'camera/metainfo.json'
55
+ if complete.is_file():
56
+ old=load(complete)
57
+ required=['observation/rgb.mkv','annotation/segment/mask.mkv','annotation/mano/motion.pt','annotation/keypoints/xyz.pt','camera/intrinsic.pt','camera/frames.jsonl']
58
+ if old.get('num_frames')!=t or not all((complete.parent/r).is_file() for r in required):
59
+ raise RuntimeError(f'Existing shard is incomplete: {complete.parent}')
60
+ summary.append({'sequence':seq,'frames':t,'status':'already_complete'});continue
61
+ if model is None:model=Mano()
62
+ v=View('FreiHAND',seq,'camera',ids,[224,224],source_locator,kind='image',split='train' if split=='training' else 'test')
63
+ v.m['split_scheme']='FreiHAND_official_train_evaluation'
64
+ v.m['split_source_locator']={'archive':'raw/data/'+filename,'member_prefix':split+'/'}
65
+ v.m['schema_version']='hand-warehouse/1.0';v.m['storage_revision']='lossless-video-2026-09-18'
66
+ v.m['sampling']['type']='independent' if t>1 else 'single'
67
+ v.m['sampling']['shard_max_images']=batch_size
68
+ v.m['sampling']['selection']='all released RGB images, sorted by source RGB index; all background variants retained'
69
+ for f,i,base,name in zip(v.frames,ids,ix,names):
70
+ f.update(sample_id=f'FreiHAND/{split}/{i:08d}',image_variant={'base_sample_id':int(base),'variant_index':int(i//n)})
71
+ f['source_locator'].update(member=name,annotation_index=int(base))
72
+ jpg=b''.join(z.read(s) for s in names);path=v.p/'observation/rgb.mkv';path.parent.mkdir(parents=True,exist_ok=True)
73
+ ff(['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i','pipe:0','-c:v','copy',str(path)],jpg)
74
+ assert ff(['-i',str(path),'-c:v','copy','-f','image2pipe','pipe:1'])==jpg
75
+ decoded=ff(['-f','image2pipe','-c:v','mjpeg','-i','pipe:0','-f','rawvideo','-pix_fmt','rgb24','pipe:1'],jpg)
76
+ assert len(decoded)==t*224*224*3
77
+ assert ff(['-i',str(path),'-f','rawvideo','-pix_fmt','rgb24','pipe:1'])==decoded
78
+ # FFmpeg reports the actual source pixel format without printing image data.
79
+ info=subprocess.run([FF,'-hide_banner','-i',str(path)],capture_output=True).stderr.decode(errors='replace')
80
+ pix=re.search(r'Video: mjpeg[^\n]*?\b(yuvj?\d+p)\b',info)
81
+ if not pix: raise RuntimeError('Unrecognized JPEG pixel format: '+info)
82
+ v.add('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(t,bool),
83
+ storage=storage('mkv/mjpeg_copy/v1','mjpeg',pix.group(1),[224,224],True,{'mode':'stream_copy'}),storage_fps=1,timebase_role='index_only')
84
+ v.checks.append({'test':'all_rgb_packets_and_decoded_pixels_exact','frames':t})
85
+ v.intrinsic(ks[ix]);v.m['components']['intrinsic']['source_locator'].update(member=split+'_K.json',index_ref='camera/frames.jsonl:source_locator.annotation_index')
86
+ kp=np.full((t,2,21,3),np.nan);kp[:,1]=xyz[ix];valid=np.zeros((t,2,21),bool);valid[:,1]=True
87
+ v.array('keypoints_xyz','annotation/keypoints/xyz.pt','keypoints/xyz/v1',kp,valid,['T','hand','joint','coordinate'],unit='m',coordinate_frame='camera',keypoint_schema='mano21/v1')
88
+ v.m['components']['keypoints_xyz']['source_locator'].update(member=split+'_xyz.json',index_ref='camera/frames.jsonl:source_locator.annotation_index')
89
+ a=theta[ix];pose=a[:,:48].copy();pose[:,3:]+=model.data['hands_mean'];beta=a[:,48:58]
90
+ verts,joints,_=model.geometry(pose,beta)
91
+ focal=(ks[ix,0,0]+ks[ix,1,1])/2
92
+ root=np.concatenate([a[:,58:60]-ks[ix,:2,2],focal[:,None]],axis=1)/a[:,60,None]
93
+ translation=root-joints[:,9];motion=np.full((t,2,61),np.nan);motion[:,1]=np.concatenate([pose,beta,translation],axis=1)
94
+ valid=np.zeros((t,2),bool);valid[:,1]=True
95
+ v.array('mano','annotation/mano/motion.pt','mano/axis_angle61/v1',motion,valid,['T','hand','parameter'],unit='m',coordinate_frame='camera',angle_unit='rad',model_profile={'version':'MANO-v1.2','flat_hand_mean':True,'left_shapedirs_fix':False},method='Add MANO nonflat mean; recover source camera root from uv/scale; subtract posed middle MCP. No new fitting.')
96
+ v.m['components']['mano']['source_locator'].update(member=split+'_mano.json',index_ref='camera/frames.jsonl:source_locator.annotation_index')
97
+ _,restored,_=model.geometry(motion[:,1,:48],motion[:,1,48:58],motion[:,1,58:])
98
+ assert np.max(np.abs(restored[:,9]-root))<2e-6
99
+ masks=[];records=[]
100
+ for frame,(i,base) in enumerate(zip(ids,ix)):
101
+ member=f'training/mask/{base:08d}.jpg' if split=='training' else f'evaluation/segmap/{i:08d}.png'
102
+ arr=np.asarray(Image.open(io.BytesIO(z.read(member))))
103
+ if split=='training':
104
+ assert arr.shape==(224,224,3) and np.array_equal(arr[:,:,0],arr[:,:,1]) and np.array_equal(arr[:,:,0],arr[:,:,2])
105
+ arr=arr[:,:,0].astype(np.uint16)
106
+ else:
107
+ assert arr.shape==(224,224)
108
+ arr=arr.astype(np.uint16);arr[arr==0]=65534
109
+ records.append({'frame_index':frame,'labels':[dict(mask_value=int(c),category_id='background' if c==65534 else 'hand',entity_id=None if c==65534 else 'hand_right',part_id=None,source_instance_id=0 if c==65534 else int(c)) for c in np.unique(arr)]})
110
+ masks.append(arr)
111
+ pix='gray' if split=='training' else 'gray16le';raw=np.asarray(masks,dtype=np.uint8 if pix=='gray' else '<u2').tobytes();path=v.p/'annotation/segment/mask.mkv';path.parent.mkdir(parents=True,exist_ok=True)
112
+ ff(['-f','rawvideo','-pixel_format',pix,'-video_size','224x224','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3',str(path)],raw)
113
+ assert ff(['-i',str(path),'-f','rawvideo','-pix_fmt',pix,'pipe:1'])==raw
114
+ schema='segment/foreground_intensity/v1' if split=='training' else 'segment/uint16_labels/v1'
115
+ v.add('segment','annotation/segment/mask.mkv',schema,['T','height','width'],np.ones(t,bool),storage=storage('mkv/uint16_ffv1/v1','ffv1',pix,[224,224],split=='training',{'level':3}),storage_fps=1,timebase_role='index_only',coverage={'kind':'selected_entities','entities':['hand_right']})
116
+ seg=v.m['components']['segment'];seg['source_locator'].update(member_pattern='training/mask/{annotation_index:08d}.jpg' if split=='training' else 'evaluation/segmap/{source_frame_id:08d}.png')
117
+ if split=='training':seg.update(segmentation_type='semantic',value_range=[0,255],normalization_scale=1/255,foreground_category='hand',entity_id='hand_right')
118
+ else:
119
+ seg.update(segmentation_type='semantic',mapping_ref='annotation/segment/instances.jsonl');lines(v.p/'annotation/segment/instances.jsonl',records)
120
+ v.checks.extend([{'test':'all_mask_values_exact','frames':t},{'test':'MANO_middle_MCP_root_recovery','max_m':float(np.max(np.abs(restored[:,9]-root)))}])
121
+ v.finish();summary.append({'sequence':seq,'frames':t,'status':'converted'})
122
+ save(TMP_ROOT/'conversion_progress.json',{'complete':False,'batches':summary})
123
+ save(TMP_ROOT/'conversion_progress.json',{'complete':True,'split_selection':'all','batches':summary})
124
+ if __name__=='__main__':main()
FreiHAND/shared-v1.0/script/freihand_common.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers for the published FreiHAND shared-v1.0 tools."""
2
+ from pathlib import Path
3
+ import codecs, collections, hashlib, io, json, pickle, subprocess
4
+
5
+ import imageio_ffmpeg
6
+ import numpy as np
7
+ import torch
8
+
9
+ SCRIPT_DIR = Path(__file__).resolve().parent
10
+ RELEASE_ROOT = SCRIPT_DIR.parent
11
+ DATASET_ROOT = RELEASE_ROOT.parent
12
+ RAW_ROOT = DATASET_ROOT / "raw" / "data"
13
+ TMP_ROOT = DATASET_ROOT / "tmp" / "freihand-tools"
14
+ FFMPEG = imageio_ffmpeg.get_ffmpeg_exe()
15
+ FF = FFMPEG
16
+
17
+ def load(path):
18
+ return json.loads(Path(path).read_text(encoding="utf-8"))
19
+
20
+ def save(path, value):
21
+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
22
+ tmp = path.with_suffix(path.suffix + ".tmp")
23
+ tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8")
24
+ tmp.replace(path)
25
+
26
+ def write_jsonl(path, rows):
27
+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
28
+ path.write_text("".join(json.dumps(x, ensure_ascii=False, allow_nan=False) + "\n" for x in rows), encoding="utf-8")
29
+
30
+ def save_tensor(path, value):
31
+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
32
+ torch.save(torch.as_tensor(np.asarray(value).copy()), path)
33
+
34
+ lines = write_jsonl
35
+ tensor = save_tensor
36
+
37
+ def ffmpeg(args, data=None):
38
+ result = subprocess.run([FFMPEG, "-v", "error", "-y", *map(str, args)], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
39
+ if result.returncode:
40
+ raise RuntimeError(result.stderr.decode(errors="replace"))
41
+ return result.stdout
42
+
43
+ def storage(profile, codec, pixel_format, size, source_lossy, parameters):
44
+ version = ffmpeg(["-version"]).decode().splitlines()[0]
45
+ return {"profile": profile, "codec": codec, "pixel_format": pixel_format,
46
+ "encoded_size": size, "source_lossy": source_lossy,
47
+ "decoder": version, "encoder_parameters": parameters}
48
+
49
+ class RestrictedUnpickler(pickle.Unpickler):
50
+ def find_class(self, module, name):
51
+ allowed = {
52
+ ("numpy.core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct,
53
+ ("numpy._core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct,
54
+ ("numpy", "ndarray"): np.ndarray, ("numpy", "dtype"): np.dtype,
55
+ ("numpy.core.numeric", "_frombuffer"): np.core.numeric._frombuffer,
56
+ ("numpy._core.numeric", "_frombuffer"): np.core.numeric._frombuffer,
57
+ ("_codecs", "encode"): codecs.encode,
58
+ ("collections", "OrderedDict"): collections.OrderedDict,
59
+ }
60
+ if (module, name) not in allowed:
61
+ raise pickle.UnpicklingError(f"Unsupported class: {module}.{name}")
62
+ return allowed[(module, name)]
63
+
64
+ class View:
65
+ def __init__(self, dataset, sequence, camera, frame_ids, size, source, kind="image", split="unknown"):
66
+ assert dataset == "FreiHAND" and camera == "camera" and kind == "image"
67
+ self.root = RELEASE_ROOT
68
+ self.path = RELEASE_ROOT / "data" / sequence / camera
69
+ self.path.mkdir(parents=True, exist_ok=True)
70
+ self.count = len(frame_ids)
71
+ archive = Path(source["archive"]).name
72
+ self.source = dict(source)
73
+ self.checks = []
74
+ self.meta = {
75
+ "schema_version": "hand-warehouse/1.0", "dataset_id": "FreiHAND",
76
+ "release_id": "shared-v1.0", "sequence_id": sequence, "camera_id": "camera",
77
+ "sample_type": "image", "num_frames": self.count,
78
+ "hand_slots": ["left", "right"], "split": split,
79
+ "split_scheme": "FreiHAND_official_train_evaluation",
80
+ "split_source_locator": {"archive": "raw/data/" + archive, "member_prefix": split + "/"},
81
+ "sampling": {"type": "independent", "source_fps": None, "frames_ref": "camera/frames.jsonl",
82
+ "shard_max_images": 4096,
83
+ "selection": "all released RGB images, sorted by source RGB index; all background variants retained"},
84
+ "camera": {"model": "unknown", "schema_id": None, "image_size": size},
85
+ "components": {}, "storage_revision": "lossless-video-2026-09-18"}
86
+ self.frames = [{"frame_index": i, "source_frame_id": str(fid), "timestamp_ns": None,
87
+ "clock_domain": None, "source_locator": {**self.source, "source_frame_id": str(fid)}}
88
+ for i, fid in enumerate(frame_ids)]
89
+
90
+ @property
91
+ def p(self): return self.path
92
+ @property
93
+ def T(self): return self.count
94
+ @property
95
+ def m(self): return self.meta
96
+
97
+ def add(self, name, ref, schema, axes, valid, method="source values retained", **metadata):
98
+ valid_ref = Path(ref).with_name(Path(ref).stem + "_valid.pt").as_posix()
99
+ save_tensor(self.path / valid_ref, valid)
100
+ self.meta["components"][name] = {
101
+ "available": True, "schema_id": schema, "data_ref": ref, "axes": axes,
102
+ "valid_ref": valid_ref, "valid_axes": axes[:np.asarray(valid).ndim],
103
+ "provenance": {"kind": "format_conversion", "method": method},
104
+ "source_locator": dict(self.source), **metadata}
105
+
106
+ def array(self, name, ref, schema, value, valid, axes, **metadata):
107
+ value = np.asarray(value, np.float32).copy(); valid = np.asarray(valid, bool)
108
+ assert value.shape[:valid.ndim] == valid.shape and value.shape[0] == self.count
109
+ assert np.isfinite(value[valid]).all()
110
+ value[~valid] = np.nan; save_tensor(self.path / ref, value)
111
+ self.add(name, ref, schema, axes, valid, **metadata)
112
+ restored = torch.load(self.path / ref, map_location="cpu", weights_only=True).numpy()
113
+ assert np.array_equal(restored, value, equal_nan=True)
114
+ self.checks.append({"test": "tensor_serialization_exact", "file": ref,
115
+ "shape": list(value.shape), "valid_count": int(valid.sum())})
116
+
117
+ def intrinsic(self, value):
118
+ self.meta["camera"].update(model="pinhole", schema_id="camera/pinhole/v1")
119
+ self.array("intrinsic", "camera/intrinsic.pt", "camera/pinhole/v1", value,
120
+ np.ones(self.count, bool), ["T", "row", "column"])
121
+
122
+ def finish(self):
123
+ write_jsonl(self.path / "camera/frames.jsonl", self.frames)
124
+ save(self.path / "metainfo.json", self.meta)
125
+ save(TMP_ROOT / "checks" / f'{self.meta["sequence_id"]}__camera.checks.json',
126
+ {"checks": self.checks, "frames": self.count, "input": self.source})
127
+
128
+ def sha256(path):
129
+ h = hashlib.sha256()
130
+ with Path(path).open("rb") as stream:
131
+ for block in iter(lambda: stream.read(8 << 20), b""): h.update(block)
132
+ return h.hexdigest()
133
+
FreiHAND/shared-v1.0/script/mano_runtime.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal licensed-MANO runtime. Model files are discovered locally and never copied."""
2
+ import os
3
+ from pathlib import Path
4
+ from types import SimpleNamespace
5
+ import numpy as np
6
+ import torch
7
+ import smplx
8
+ from freihand_common import DATASET_ROOT, RestrictedUnpickler
9
+
10
+ class StoredState:
11
+ def __setstate__(self, state): self.__dict__.update(state)
12
+
13
+ class ManoReader(RestrictedUnpickler):
14
+ def find_class(self, module, name):
15
+ if (module, name) in [("chumpy.ch", "Ch"), ("chumpy.reordering", "Select"), ("scipy.sparse.csc", "csc_matrix")]:
16
+ return StoredState
17
+ if (module, name) == ("__builtin__", "set"): return set
18
+ return super().find_class(module, name)
19
+
20
+ def model_dir():
21
+ candidates = []
22
+ if os.environ.get("MANO_MODEL_DIR"): candidates.append(Path(os.environ["MANO_MODEL_DIR"]))
23
+ candidates += [DATASET_ROOT / "tmp/models/mano", DATASET_ROOT / "tmp/pilot-models", Path.home() / ".mano/models"]
24
+ for path in candidates:
25
+ if (path / "MANO_RIGHT.pkl").is_file(): return path
26
+ raise FileNotFoundError("MANO_RIGHT.pkl not found. Set MANO_MODEL_DIR or place it in <dataset>/tmp/models/mano.")
27
+
28
+ def model_data(path):
29
+ with path.open("rb") as stream: data = ManoReader(stream, encoding="latin1").load()
30
+ shapedirs = data["shapedirs"]
31
+ if isinstance(shapedirs, StoredState):
32
+ data["shapedirs"] = shapedirs.a.x.reshape(-1)[shapedirs.idxs].reshape(shapedirs.preferred_shape)
33
+ sparse = data["J_regressor"]
34
+ if isinstance(sparse, StoredState):
35
+ dense = np.zeros(sparse._shape)
36
+ for col in range(sparse._shape[1]):
37
+ begin, end = sparse.indptr[col:col + 2]; dense[sparse.indices[begin:end], col] = sparse.data[begin:end]
38
+ data["J_regressor"] = dense
39
+ return data
40
+
41
+ class Mano:
42
+ def __init__(self):
43
+ directory = model_dir(); self.data = model_data(directory / "MANO_RIGHT.pkl")
44
+ self.layer = smplx.MANO(model_path=str(directory), data_struct=SimpleNamespace(**self.data),
45
+ is_rhand=True, use_pca=False, flat_hand_mean=True)
46
+ def geometry(self, pose, betas, translation=None):
47
+ pose = torch.as_tensor(np.asarray(pose).copy(), dtype=torch.float32).reshape(-1, 48)
48
+ betas = torch.as_tensor(np.asarray(betas).copy(), dtype=torch.float32).reshape(-1, 10)
49
+ with torch.no_grad(): output = self.layer(global_orient=pose[:, :3], hand_pose=pose[:, 3:], betas=betas)
50
+ vertices = output.vertices.numpy(); joints = output.joints.numpy()[:, :16]
51
+ if translation is not None:
52
+ delta = np.asarray(translation).reshape(-1, 1, 3); vertices += delta; joints += delta
53
+ keypoints = np.stack([joints[:,0],joints[:,13],joints[:,14],joints[:,15],vertices[:,744],
54
+ joints[:,1],joints[:,2],joints[:,3],vertices[:,320],
55
+ joints[:,4],joints[:,5],joints[:,6],vertices[:,443],
56
+ joints[:,10],joints[:,11],joints[:,12],vertices[:,555],
57
+ joints[:,7],joints[:,8],joints[:,9],vertices[:,672]], axis=1)
58
+ return vertices, keypoints, joints
FreiHAND/shared-v1.0/script/render_full_random_review.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regenerate the fixed-seed full-release visual review; never uploads."""
2
+ from freihand_common import *
3
+ from mano_runtime import Mano
4
+ from PIL import Image, ImageDraw
5
+ import argparse, cv2, io, zipfile
6
+ import html, random, hashlib
7
+ from collections import defaultdict
8
+
9
+ def main():
10
+ argparse.ArgumentParser(description='Render FreiHAND full_random from the adjacent shared-v1.0 release.').parse_args()
11
+ root=RELEASE_ROOT;out=root/'doc/validation/full_random';out.mkdir(parents=True,exist_ok=True)
12
+ pools=defaultdict(list);selection=defaultdict(list);sample_records=[]
13
+ for mp in sorted((root/'data').glob('*/*/metainfo.json')):
14
+ for f in [json.loads(l) for l in (mp.parent/'camera/frames.jsonl').read_text().splitlines()]:
15
+ stratum='evaluation' if f['sample_id'].split('/')[1]=='evaluation' else 'training_variant_'+str(f['image_variant']['variant_index'])
16
+ pools[stratum].append((mp.parent.relative_to(root).as_posix(),f['frame_index']))
17
+ seed=20260918;rng=random.Random(seed)
18
+ for stratum in sorted(pools):
19
+ for view,idx in rng.sample(pools[stratum],6):selection[view].append(idx)
20
+ torch.set_num_threads(4)
21
+ model=Mano();cards=[];edges=[(0,1),(1,2),(2,3),(3,4),(0,5),(5,6),(6,7),(7,8),(0,9),(9,10),(10,11),(11,12),(0,13),(13,14),(14,15),(15,16),(0,17),(17,18),(18,19),(19,20)]
22
+ for mp in sorted((root/'data').glob('*/*/metainfo.json')):
23
+ m=load(mp);p=mp.parent;view=p.relative_to(root).as_posix()
24
+ if view not in selection:continue
25
+ indices=sorted(selection[view]);t=len(indices)
26
+ all_rows=[json.loads(l) for l in (p/'camera/frames.jsonl').read_text().splitlines()];rows=[all_rows[i] for i in indices]
27
+ expression='+'.join('eq(n\\,'+str(i)+')' for i in indices)
28
+ print('Reading full output',view,indices,flush=True)
29
+ def decode(path,pix,dtype,shape):
30
+ b=subprocess.check_output([FF,'-v','error','-i',str(path),'-vf','select='+expression,'-vsync','0','-frames:v',str(t),'-f','rawvideo','-pix_fmt',pix,'pipe:1']);return np.frombuffer(b,dtype=dtype).reshape(shape)
31
+ images=decode(p/'observation/rgb.mkv','rgb24',np.uint8,(t,224,224,3))
32
+ # FFmpeg gray8 -> gray16 rescales intensities by 257; decode native storage
33
+ # first and widen numerically in NumPy to preserve labels/intensities.
34
+ mask_pix=m['components']['segment']['storage']['pixel_format']
35
+ assert mask_pix in ['gray','gray16le']
36
+ masks=decode(p/'annotation/segment/mask.mkv',mask_pix,np.uint8 if mask_pix=='gray' else '<u2',(t,224,224)).astype(np.uint16)
37
+ motion=torch.load(p/'annotation/mano/motion.pt',weights_only=True).numpy()[indices];kp=torch.load(p/'annotation/keypoints/xyz.pt',weights_only=True).numpy()[indices];ks=torch.load(p/'camera/intrinsic.pt',weights_only=True).numpy()[indices]
38
+ verts,_,_=model.geometry(motion[:,1,:48],motion[:,1,48:58],motion[:,1,58:]);split='training' if m['split']=='train' else 'evaluation'
39
+ with zipfile.ZipFile(RAW_ROOT/('FreiHAND_pub_v2.zip' if split=='training' else 'FreiHAND_pub_v2_eval.zip')) as z:
40
+ for i,frame in enumerate(rows):
41
+ rgb=images[i].copy();parts=[rgb.copy()];mask=masks[i]
42
+ source_mask_member=f'training/mask/{frame["source_locator"]["annotation_index"]:08d}.jpg' if split=='training' else f'evaluation/segmap/{int(frame["source_frame_id"]):08d}.png'
43
+ source_mask=np.asarray(Image.open(io.BytesIO(z.read(source_mask_member))))
44
+ if split=='training':
45
+ source_mask=source_mask[:,:,0];assert mask.max()<=255
46
+ else:
47
+ source_mask=source_mask.astype(np.uint16);source_mask[source_mask==0]=65534
48
+ assert np.array_equal(mask,source_mask),'Preview mask differs from decoded source'
49
+ weight=mask/255 if split=='training' else ((mask!=65534)&(mask!=65535)&(mask!=0)).astype(float)
50
+ colored=rgb.astype(float)*(1-.5*weight[:,:,None])+np.array([0,255,100])*.5*weight[:,:,None];parts.append(colored.clip(0,255).astype(np.uint8))
51
+ xyz=kp[i,1];uv=xyz@ks[i].T;uv=uv[:,:2]/uv[:,2:];joint_im=rgb.copy()
52
+ for a,b in edges:cv2.line(joint_im,tuple(np.round(uv[a]).astype(int)),tuple(np.round(uv[b]).astype(int)),(255,230,0),1,cv2.LINE_AA)
53
+ for j,(x,y) in enumerate(uv):cv2.circle(joint_im,(round(float(x)),round(float(y))),2,(255,30,50),-1)
54
+ parts.append(joint_im);uv=verts[i]@ks[i].T;uv=uv[:,:2]/uv[:,2:];mesh_im=rgb.copy()
55
+ for face in model.data['f']:cv2.polylines(mesh_im,[np.round(uv[face]).astype(np.int32)],True,(50,220,255),1,cv2.LINE_AA)
56
+ parts.append(mesh_im)
57
+ canvas=Image.new('RGB',(896,250),'white');draw=ImageDraw.Draw(canvas)
58
+ for k,(im,title) in enumerate(zip(parts,['RGB (source JPEG copied)','Source segmentation','Native XYZ projected','Converted MANO projected'])):
59
+ canvas.paste(Image.fromarray(im),(k*224,26));draw.text((k*224+4,7),title,fill='black')
60
+ name=frame['sample_id'].replace('/','_')+'.png';canvas.save(out/name)
61
+ sample_records.append({'sample_id':frame['sample_id'],'view':view,'frame_index':frame['frame_index'],'annotation_index':frame['source_locator']['annotation_index'],'variant_index':frame['image_variant']['variant_index'],'preview':name,'rgb_decoded_sha256':hashlib.sha256(rgb.tobytes()).hexdigest(),'mask_uint16_sha256':hashlib.sha256(mask.astype('<u2').tobytes()).hexdigest(),'raw_mask_comparison':'passed'})
62
+ # Unmodified JPEG reference alongside the panel, for browser inspection.
63
+ rawname=name.replace('.png','_source.jpg');(out/rawname).write_bytes(z.read(frame['source_locator']['member']))
64
+ cards.append(f'<section><h2>{html.escape(frame["sample_id"])}</h2><p>Source annotation index: {frame["source_locator"]["annotation_index"]}; variant: {frame["image_variant"]["variant_index"]}. <a href="{rawname}">Original JPEG</a></p><img src="{name}" width="896"></section>')
65
+ text='''<!doctype html><meta charset="utf-8"><title>FreiHAND 全量随机抽查</title><style>body{font:16px system-ui;max-width:1100px;margin:32px auto;background:#f5f6f8;color:#19222f}section{background:white;padding:16px;margin:20px 0;border-radius:8px}img{max-width:100%;height:auto}li{margin:8px 0}</style><h1>FreiHAND:全量产物随机抽查</h1><p>从完整 134,200 张产物中分层随机选取 30 张:四种训练背景版本及评估集各 6 张。随机种子 20260918;分层等额抽样,不按全体样本占比加权,不能估计总体错误率。尚待人工确认。每行依次为 RGB、分割叠加、源 XYZ 投影、转换 MANO 投影。原始 JPEG 可单独打开。</p><ul><li>检查图片与标注是否同一只手、同一姿态;左右手、镜像、坐标尺度与相机方向是否合理。</li><li>检查分割边缘、前景范围和训练背景变体的对应关系;训练灰度保留原强度,未阈值化。</li><li>检查关键点顺序与投影;MANO 是拟合标注,不能要求与源 XYZ 完全重合。明显整体偏移、缩放或旋转须反馈。</li><li>检查原图细节是否一致。此页面用于视觉检查,编码数值一致性由转换器逐值验证。</li><li>请确认这份全量随机抽查结果,或指出样本 ID 和问题;确认前不上传。</li></ul>'''+''.join(cards)
66
+ (out/'index.html').write_text(text,encoding='utf8')
67
+ save(out/'samples.json',{'seed':seed,'method':'Python random.Random; sample without replacement separately in each sorted stratum; 6 per stratum','population_sizes':{k:len(v) for k,v in pools.items()},'human_review':'pending','source':'actual completed shared-v1.0 data, not pilot outputs','samples':sample_records})
68
+ assert len(sample_records)==30 and len({x['sample_id'] for x in sample_records})==30
69
+ report='# FreiHAND 全量产物随机抽查报告\n\n[打开离线预览](index.html) · [抽样清单及可复现参数](samples.json)\n\n全量共 134,200 张;按训练背景版本 0–3 与评估集分成五层,各随机抽取 6 张,共 30 张,种子为 20260918。属于分层等额随机抽样,不是总体均匀抽样,不据此估计全量错误率。样本来自已完成的 4096 张分片产物,直接读取其视频、相机及标注数组,未重新转换试点。\n\n每个选中 mask 均再次与 raw 对应帧逐值比较,通过后生成图。关键点和 MANO 使用全量产物数组投影;MANO 拟合不要求与源关键点无残差。自动检查通过不代表人工确认通过。\n\n**人工确认:待确认。尚未上传。**\n\n检查图片与标注对应、背景版本、分割边缘、关键点顺序及 MANO 投影;反馈样本 ID 即可。HTML 及配图使用相对链接,可下载后离线查看。\n'
70
+ (out/'REPORT.md').write_text(report,encoding='utf8')
71
+ parent_report=root/'doc/validation/REPORT.md';parent_text=parent_report.read_text(encoding='utf8')
72
+ if 'full_random/REPORT.md' not in parent_text:parent_report.write_text(parent_text+'\n\n## 全量随机抽查\n\n[查看独立随机抽查报告](full_random/REPORT.md) · [打开 30 张随机样本预览](full_random/index.html)。本次从全量产物抽取,人工确认待完成。\n',encoding='utf8')
73
+ evidence=root/'doc/validation/evidence.json';d=load(evidence);d['full_release_validation']['random_review_ref']='full_random/samples.json';save(evidence,d)
74
+ print(out/'index.html')
75
+ if __name__=='__main__':main()
FreiHAND/shared-v1.0/script/validate_freihand.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate the adjacent FreiHAND shared-v1.0 tree and fingerprint its current bytes."""
2
+ import argparse, hashlib, json
3
+ import numpy as np
4
+ import torch
5
+ from freihand_common import RELEASE_ROOT, TMP_ROOT, load, save
6
+
7
+ def main():
8
+ argparse.ArgumentParser(description='Validate the adjacent FreiHAND shared-v1.0 release.').parse_args()
9
+ registry = load(RELEASE_ROOT / 'doc/schema.json')
10
+ counts = {'training': 0, 'evaluation': 0}; seen = set(); views = 0
11
+ for path in sorted((RELEASE_ROOT / 'data').glob('*/*/metainfo.json')):
12
+ meta = load(path); base = path.parent; total = meta['num_frames']; views += 1
13
+ for key in ['schema_version','split_scheme','split_source_locator','sampling','camera','components']:
14
+ assert key in meta, (path,key)
15
+ assert meta['schema_version'] == 'hand-warehouse/1.0'
16
+ frames = [json.loads(line) for line in (base/'camera/frames.jsonl').read_text(encoding='utf-8').splitlines()]
17
+ assert len(frames) == total
18
+ for index, frame in enumerate(frames):
19
+ assert frame['frame_index'] == index and frame['sample_id'] not in seen
20
+ seen.add(frame['sample_id']); source_split = frame['sample_id'].split('/')[1]; counts[source_split] += 1
21
+ modulus = 32560 if source_split == 'training' else 3960
22
+ assert frame['source_locator']['annotation_index'] == int(frame['source_frame_id']) % modulus
23
+ for name, component in meta['components'].items():
24
+ definition = registry['components'][component['schema_id']]
25
+ required = ['available','data_ref','axes','valid_ref','valid_axes','provenance','source_locator',*definition.get('required_metadata',[])]
26
+ for key in required: assert key in component, (path,name,key)
27
+ assert (base/component['data_ref']).is_file()
28
+ valid = torch.load(base/component['valid_ref'], weights_only=True).numpy(); assert valid.dtype == bool
29
+ assert list(valid.shape) == [total if axis == 'T' else axis for axis in definition['valid_shape']]
30
+ if component['data_ref'].endswith('.pt'):
31
+ value = torch.load(base/component['data_ref'], weights_only=True).numpy()
32
+ assert value.dtype == np.float32
33
+ assert list(value.shape) == [total if axis == 'T' else axis for axis in definition['shape']]
34
+ assert np.isfinite(value[valid]).all() and np.isnan(value[~valid]).all()
35
+ else:
36
+ assert component['storage']['profile'] in definition['allowed_storage_profiles']
37
+ for key in registry['video_metadata']['required']: assert key in component['storage'], (name,key)
38
+ assert counts == {'training':130240,'evaluation':3960}, counts
39
+ result = {'passed':True,'views':views,'counts':counts,'schema_version':'hand-warehouse/1.0',
40
+ 'scope':'current content and layout; does not independently prove official source correctness or visual quality'}
41
+ save(TMP_ROOT/'acceptance.json', result)
42
+ manifest=[]
43
+ for path in sorted(RELEASE_ROOT.rglob('*')):
44
+ if not path.is_file() or '.cache' in path.parts: continue
45
+ digest=hashlib.sha256()
46
+ with path.open('rb') as stream:
47
+ for block in iter(lambda: stream.read(8 << 20), b''): digest.update(block)
48
+ manifest.append({'path':path.relative_to(RELEASE_ROOT).as_posix(),'size':path.stat().st_size,'sha256':digest.hexdigest()})
49
+ save(TMP_ROOT/'files.sha256.json',{'scope':result['scope'],'files':manifest,'bytes':sum(x['size'] for x in manifest)})
50
+ print(json.dumps(result,ensure_ascii=False))
51
+
52
+ if __name__ == '__main__': main()