diff --git a/H2O/shared-v1.0/script/check_dexycb_projection.py b/H2O/shared-v1.0/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.0/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/config.json b/H2O/shared-v1.0/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..36d77ffb8ae7c4d8db5364324fac347a35522f99 --- /dev/null +++ b/H2O/shared-v1.0/script/config.json @@ -0,0 +1,24 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 4, + "view_backend": "processes", + "camera_pipeline": true, + "ffv1_slices": 16, + "view_workers": 16, + "ram_stage_dir": "/dev/shm/xuzhefeng-h2o-full-process16-20260930", + "ram_stage_gib": 32, + "stream_media": true, + "codec_threads": 10, + "decode_threads": 10, + "depth_threads": 4, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.0/script/convert_dexycb_v1.0.py b/H2O/shared-v1.0/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.0/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.0/script/convert_h2o_v1.0.py b/H2O/shared-v1.0/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..84c5878726db45a492347035386bf0f7ff30b8d6 --- /dev/null +++ b/H2O/shared-v1.0/script/convert_h2o_v1.0.py @@ -0,0 +1,678 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor +import io +import json +import multiprocessing +import os +import re +import shutil +import tarfile +import tempfile +import threading +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads, + stream_source=getattr(args, 'stream_media', False)) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(io.BytesIO(intr[0])).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(io.BytesIO(item[0])).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + depth_threads = getattr(args, 'depth_threads', 1) + def read_depth(f): + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + return np.asarray(im).astype(np.float32) / 1000.0 + return np.full((height, width), np.nan, np.float32) + def depths(): + if depth_threads == 1: + yield from map(read_depth, ids) + else: + with ThreadPoolExecutor(max_workers=depth_threads) as pool: + # Ordered batches bound decoded arrays to depth_threads frames per view. + for start in range(0, len(ids), depth_threads): + yield from pool.map(read_depth, ids[start:start + depth_threads]) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads, stream=getattr(args, 'stream_media', False)) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive, view_pool=None, ram_budget=None): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + published_views = set() + camera_jobs, closed_cameras = {}, set() + last_camera = None + pipeline_active = False + ram_reserved = 0 + try: + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd, \ + tempfile.TemporaryDirectory(prefix='h2o-ram-', dir=args.ram_stage_dir) as rd: + work, ram_work = Path(wd), Path(rd) + def queue_camera(cam): + if cam in closed_cameras: + return + closed_cameras.add(cam) + if cam not in published_views and rows.get(cam): + camera_jobs[cam] = view_pool.submit(convert_view, work / '.converted' / cam, + args, '/'.join(current), cam, rows[cam], intrinsics.get(cam), + splits, models, assets, asset_archive) + def flush(): + nonlocal done, ram_reserved + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + if pipeline_active: + for cam in pending: + queue_camera(cam) + failure = None + for cam, job in camera_jobs.items(): + try: + reports[cam] = job.result() + except Exception as exc: + failure = failure or exc + if failure is not None: + raise failure + with sequence_dir(out, seq.replace('/', '_')) as target: + if pipeline_active: + for cam in pending: + shutil.move(work / '.converted' / cam, target / cam) + elif view_pool is None: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + else: + jobs = {cam: view_pool.submit(convert_view, target / cam, args, seq, cam, + frames, intrinsics.get(cam), splits, models, assets, asset_archive) + for cam, frames in pending.items()} + failure = None + # Every sibling must finish before sequence_dir can remove its inputs. + for cam, job in jobs.items(): + try: + reports[cam] = job.result() + except Exception as exc: + failure = failure or exc + if failure is not None: + raise failure + build_record(out, seq.replace('/', '_'), reports) + for directory in (work, ram_work): + for staged in list(directory.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + if ram_budget is not None: + lock, used, limit = ram_budget + with lock: + used[0] -= ram_reserved + ram_reserved = 0 + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + try: + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + camera_jobs.clear() + closed_cameras.clear() + last_camera = None + pipeline_active = args.camera_pipeline + published_views = {view.name for view in + (out / 'data' / '_'.join(key)).glob('cam*') + if (view / 'metainfo.json').is_file()} + if selected_views and cam not in selected_views: + continue + if pipeline_active and cam != last_camera: + if last_camera is not None: + queue_camera(last_camera) + if cam in closed_cameras: + # Complete queued readers before accepting late fields for those cameras. + for job in camera_jobs.values(): + try: + job.result() + except Exception: + pass + shutil.rmtree(work / '.converted', ignore_errors=True) + camera_jobs.clear() + closed_cameras.clear() + pipeline_active = False + print(f'Camera-order fallback: {"/".join(current)}', flush=True) + last_camera = cam + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + if tail.endswith('.txt'): + payload = data # Small source annotations stay in RAM, not thousands of HDD files. + else: + staging = work + if ram_budget is not None and cam not in published_views: + lock, used, limit = ram_budget + needed = (len(data) + 4095) // 4096 * 4096 + with lock: + if used[0] + needed <= limit: + used[0] += needed + ram_reserved += needed + staging = ram_work + payload = safe_member(staging, member.name) + if cam not in published_views: + payload.parent.mkdir(parents=True, exist_ok=True) + payload.write_bytes(data) + # Published views still verify source bytes, but never read their staging paths. + item = (payload, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + finally: + # Never delete staging while a closed-camera job can still read from it. + for job in camera_jobs.values(): + try: + job.result() + except Exception: + pass + finally: + if ram_budget is not None: + lock, used, limit = ram_budget + with lock: + used[0] -= ram_reserved + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--view-backend', choices=('threads', 'processes'), default='threads', + help='Use spawn processes to isolate Python camera processing') + p.add_argument('--camera-pipeline', action='store_true', + help='Overlap contiguous-camera extraction and conversion; reject interleaved input') + p.add_argument('--ffv1-slices', type=int, choices=(16,), + help='Optional FFV1 v3 slice parallelism; decoded frames must still match exactly') + p.add_argument('--view-workers', type=int, choices=range(1, 17), default=1, + help='Shared camera-view conversion pool, independent of archive readers') + p.add_argument('--ram-stage-dir', type=Path, help='Optional tmpfs staging; excess PNGs fall back to disk') + p.add_argument('--ram-stage-gib', type=int, choices=range(1, 65), default=32, + help='Shared PNG tmpfs quota across all archive readers, not per worker') + p.add_argument('--stream-media', action='store_true', + help='Pipe RGB/depth frames to FFmpeg instead of spooling huge RAW files') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, + help='FFV1 slice threads per encode; default 4, use 10 for the current full run') + p.add_argument('--decode-threads', type=int, choices=(1, 2, 4, 8, 10), default=1, + help='FFmpeg threads for source RGB decoding and decoded-media checks') + p.add_argument('--depth-threads', type=int, choices=(1, 2, 4), default=1, + help='Bounded ordered source depth PNG loading per worker') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + if args.camera_pipeline and args.view_workers < 2: + p.error('--camera-pipeline requires at least two --view-workers') + os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = str(args.decode_threads) + if args.ffv1_slices is None: + os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES', None) + else: + os.environ['HAND_WAREHOUSE_FFV1_SLICES'] = str(args.ffv1_slices) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR', None) + ram_budget = None + if args.ram_stage_dir is not None: + args.ram_stage_dir = args.ram_stage_dir.expanduser().resolve() + if not args.ram_stage_dir.is_relative_to(Path('/dev/shm').resolve()): + p.error('--ram-stage-dir must be on /dev/shm; it is temporary input, not an output dataset') + args.ram_stage_dir.mkdir(parents=True, exist_ok=True) + limit = args.ram_stage_gib * 1024**3 + if shutil.disk_usage(args.ram_stage_dir).free < limit + 8 * 1024**3: + p.error('not enough tmpfs headroom for the requested shared staging quota') + ram_budget = (threading.Lock(), [0], limit) + if args.stream_media: + os.environ['HAND_WAREHOUSE_MEDIA_TMPDIR'] = str(args.ram_stage_dir) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + executor = ProcessPoolExecutor if args.view_backend == 'processes' else ThreadPoolExecutor + options = {'mp_context': multiprocessing.get_context('spawn')} if args.view_backend == 'processes' else {'thread_name_prefix': 'h2o-view'} + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd, \ + executor(max_workers=args.view_workers, **options) as views: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive, + views if args.view_workers > 1 else None, ram_budget) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.0/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.0/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.0/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.0/script/convert_visor_v1.0.py b/H2O/shared-v1.0/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.0/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-check-fallback.py b/H2O/shared-v1.0/script/provenance/operations/h2o-check-fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..96c33bf9e1c9db26ac0a555e174470827da026ad --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-check-fallback.py @@ -0,0 +1,137 @@ +"""Full coverage/numeric audit, plus representative persisted-media QC and offline HTML.""" +import os +for key in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS'): + os.environ[key]='1' +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS']='4' +os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES',None) +os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR',None) +import collections,datetime,hashlib,html,json,re,sys,time,zipfile +from concurrent.futures import ThreadPoolExecutor,as_completed +from pathlib import Path +from zoneinfo import ZoneInfo +import numpy as np +import torch +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +release=root/'H2O/shared-v1.0' +sys.path.insert(0,str(root/'frozen-code/scripts')) +from warehouse_v1_0 import SCHEMA,check_transform,check_valid_policy,check_view_type,safe_member,sha256 +from render_h2o_validation import render +out=release/'doc/validation/final-quick-check' +out.mkdir(exist_ok=True) +torch.set_num_threads(1) +started=time.monotonic() +expected={} +with zipfile.ZipFile('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip') as z: + for name in z.namelist(): + if '/action_' not in name:continue + for line in z.read(name).decode().splitlines(): + fields=line.split() + if len(fields)>1 and fields[1]!='path': + seq=fields[1].replace('/','_') + expected[seq]=max(expected.get(seq,0),int(fields[-1])+1) +folders={p.name:p for p in (release/'data').iterdir() if p.is_dir()} +assert set(folders)==set(expected),(sorted(set(expected)-set(folders)),sorted(set(folders)-set(expected))) +assert len(expected)==184 and sum(expected.values())==114329 +receipts={p.name.removesuffix('.build.json'):p for p in (release/'doc').glob('*.build.json')} +assert set(receipts)==set(expected) +assert 'EXIT=0' in (root/'full.status').read_text() +failures=[] +rows=[] +def require(ok,message): + if not ok:raise ValueError(message) +def load(path): + def cpu(storage,location): + require(location=='cpu',f'non-CPU storage: {path}') + return storage + obj=torch.load(path,map_location=cpu,weights_only=True) + require(type(obj) is torch.Tensor,f'non-tensor: {path}') + return obj.numpy() +def check_sequence(seq): + folder=folders[seq];n=expected[seq] + require({p.name for p in folder.iterdir() if p.is_dir()}=={f'cam{i}' for i in range(5)},'five-camera coverage') + receipt=json.loads(receipts[seq].read_text()) + require(receipt['sequence_id']==seq and set(receipt['views'])=={f'cam{i}' for i in range(5)},'build receipt') + result=[] + for i in range(5): + cam=f'cam{i}';view=folder/cam + meta=json.loads((view/'metainfo.json').read_text()) + require((meta['dataset_id'],meta['sequence_id'],meta['camera_id'],meta['num_frames'])==('H2O',seq,cam,n),'header/timeline') + require(meta['view_type']==('ego' if i==4 else 'exo'),'view role') + require(meta['sampling']['selection']=={'max_frames':None,'views':None},'unexpected subsampling') + check_view_type(meta) + components=meta['components'] + require(all(components[k].get('available') for k in ('rgb','depth','mano','keypoints_xyz','intrinsic','extrinsic')),'required modality absent') + require(not components['segment']['available'] and not components['relations']['available'],'unexpected synthesized component') + rgb_sources=[];depth_sources=[];rgb_count=depth_count=0 + with (view/'camera/frames.jsonl').open() as inp: + count=0 + for index,line in enumerate(inp): + f=json.loads(line) + require(f['frame_index']==index and f['source_frame_id']==index,'source frame index') + require(f['sync_id']==f'{seq.replace("_","/")}:{index}','synchronization ID') + sources=f['component_sources'] + for kind,loc in sources.items(): + require(re.fullmatch('[0-9a-f]{64}',loc.get('sha256','')) is not None,f'source SHA256: {kind}') + require(f'/{cam}/' in loc.get('member',''),'wrong source camera') + rgb_sources.append('rgb' in sources);depth_sources.append('depth' in sources) + rgb_count+=rgb_sources[-1];depth_count+=depth_sources[-1];count+=1 + require(count==n,'frames.jsonl length') + numeric=0 + object_names=[] + for key,c in components.items(): + if not c['available']:continue + for field in ('data_ref','valid_ref','mapping_ref'): + if c.get(field): + path=safe_member(view,c[field]) + require(path.is_file() and path.stat().st_size>0,f'missing/empty {c[field]}') + schema=SCHEMA['components'][c['schema_id']] + if c.get('valid_policy'):check_valid_policy(c,n) + valid=load(view/c['valid_ref']) if c.get('valid_ref','').endswith('.pt') else None + if valid is not None: + shape=schema.get('valid_shape') + require(valid.dtype==np.bool_ and valid.shape[0]==n,f'{key}: validity dtype/timeline') + if shape:require(len(shape)==valid.ndim and all(not isinstance(s,int) or valid.shape[j]==s for j,s in enumerate(shape)),f'{key}: validity shape') + if key=='rgb':require(np.array_equal(valid,np.asarray(rgb_sources)), 'RGB existence validity mismatch') + if c['data_ref'].endswith('.pt'): + arr=load(view/c['data_ref']);numeric+=1 + require(arr.dtype==np.float32 and arr.shape[0]==n,f'{key}: dtype/timeline') + shape=schema.get('shape') + if shape:require(len(shape)==arr.ndim and all(not isinstance(s,int) or arr.shape[j]==s for j,s in enumerate(shape)),f'{key}: tensor shape') + if valid is not None: + require(arr.shape[:valid.ndim]==valid.shape and np.isfinite(arr[valid]).all() and np.isnan(arr[~valid]).all(),f'{key}: finite/NaN validity semantics') + if c['schema_id'] in ('transform/se3/v1','object/rigid/v1'):check_transform(arr[valid]) + if key=='intrinsic':require(np.allclose(arr[:,2],[0,0,1]) and (arr[:,0,0]>0).all() and (arr[:,1,1]>0).all(),'camera intrinsics') + if key.startswith('mesh_'):object_names.append(key.removeprefix('mesh_')) + proof=receipt['views'][cam] + require(not proof['unresolved'],'unresolved QC components') + media={} + for p in proof['validation']: + if p.get('profile')==components['rgb']['storage']['profile'] and p.get('all_frames_exact') is True:media['rgb']=p + elif p.get('component') in ('depth','depth_valid'):media[p['component']]=p + require(set(media)=={'rgb','depth','depth_valid'},'media roundtrip proof missing') + for key,p in media.items(): + require(p.get('all_frames_exact') is True and re.fullmatch('[0-9a-f]{64}',p.get('decoded_sha256','')) is not None,f'{key}: failed original roundtrip proof') + require((view/'observation'/f'{key}.mkv').stat().st_size==p['bytes'],f'{key}: encoded file size changed since conversion') + result.append({'sequence_id':seq,'camera':cam,'frames':n,'numeric_components':numeric, + 'rgb_source_frames':rgb_count,'depth_source_frames':depth_count,'objects':sorted(object_names)}) + return result + +result=check_sequence('subject1_k2_6') +from warehouse_v1_0 import decoded_digest +receipt=json.loads(receipts['subject1_k2_6'].read_text()) +view=folders['subject1_k2_6']/'cam0' +meta=json.loads((view/'metainfo.json').read_text()) +proofs=receipt['views']['cam0']['validation'] +verified=[] +for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + p=next(x for x in proofs if (x.get('profile')==meta['components']['rgb']['storage']['profile'] if name=='rgb' else x.get('component')==name)) + digest,size,seconds=decoded_digest(view/'observation'/f'{name}.mkv',pix) + assert digest==p['decoded_sha256'],(name,digest,p['decoded_sha256']) + expected_bytes=expected['subject1_k2_6']*1280*720*({'rgb':3,'depth':4,'depth_valid':1}[name]) + assert size==expected_bytes,(name,size,expected_bytes) + verified.append({'component':name,'decoded_sha256':digest,'decoded_bytes':size,'seconds':seconds}) +page=render(view,out/'subject1_k2_6_cam0_fallback') +json_result={'passed':True,'views':result,'full_decode_comparison':verified,'html':str(page.relative_to(out)), + 'note':'Registered lossless H.264 fallback; all current decoded media digests equal original conversion receipts'} +(out/'H264_FALLBACK_CHECK.json').write_text(json.dumps(json_result,indent=2)+'\n') +print('FALLBACK_PASS',json.dumps(json_result),flush=True) diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-finalize-quick-validation.py b/H2O/shared-v1.0/script/provenance/operations/h2o-finalize-quick-validation.py new file mode 100644 index 0000000000000000000000000000000000000000..75a0c5f7db6f94423e22d2e8862125a674841dc6 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-finalize-quick-validation.py @@ -0,0 +1,39 @@ +import datetime,html,json,shutil +from pathlib import Path +from zoneinfo import ZoneInfo +release=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/H2O/shared-v1.0') +out=release/'doc/validation/final-quick-check' +report=json.loads((out/'QUICK_VALIDATION.json').read_text()) +assert report['failures']==[{'sequence':'subject1_k2_6','error':"ValueError('rgb: failed original roundtrip proof')"}] +fallback=json.loads((out/'H264_FALLBACK_CHECK.json').read_text());assert fallback['passed'] +shutil.copy2(out/'QUICK_VALIDATION.json',out/'INITIAL_CHECKER_ALERT.json') +rows=fallback['views'] +report['checked_sequences']+=1;report['checked_views']+=len(rows) +report['checked_view_frames']+=sum(r['frames'] for r in rows) +report['rgb_source_frames']+=sum(r['rgb_source_frames'] for r in rows) +report['depth_source_frames']+=sum(r['depth_source_frames'] for r in rows) +report['numeric_components']+=sum(r['numeric_components'] for r in rows) +report['samples'].append({'sequence_id':'subject1_k2_6','camera':'cam0','object':'espresso', + 'frames':678,'passed':True,'html':fallback['html'], + 'extra_check':'Full RGB/depth/valid current decoded digests equal original receipts'}) +report['resolved_alerts']=[{'view':'subject1_k2_6/cam0','classification':'Registered lossless H.264 fallback, not missing data or corruption', + 'original_checker_limitation':'First pass selected only FFV1 proofs; fixed to select the profile actually declared by metainfo', + 'followup':'All five cameras rechecked; problematic view RGB, depth and validity fully decoded and matched original SHA256/byte length'}] +report['failures']=[];report['passed']=True +report['time']=datetime.datetime.now(ZoneInfo('Asia/Shanghai')).isoformat() +report['sample_views']=len(report['samples']) +assert report['checked_sequences']==184 and report['checked_views']==920 +assert report['checked_view_frames']==report['rgb_source_frames']==report['depth_source_frames']==571645 +report['rgb_profiles']={} +for meta in (release/'data').glob('*/cam*/metainfo.json'): + name=json.loads(meta.read_text())['components']['rgb']['storage']['profile'] + report['rgb_profiles'][name]=report['rgb_profiles'].get(name,0)+1 +(out/'QUICK_VALIDATION.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') +summary={k:v for k,v in report.items() if k!='samples'} +(out/'index.html').write_text('H2O 全量后抽样验收

H2O 全量后抽样验收

自动检查通过不等于原始几何标注准确。覆盖四个 subject、八类物体、ego/exo;青色为源手部关节点投影,粉色为源物体点投影,仅用于预览。

'+html.escape(json.dumps(summary,ensure_ascii=False,indent=2))+'
') +operations=release/'script/provenance/operations' +for src in ('h2o-quick-validation.py','h2o-check-fallback.py','h2o-finalize-quick-validation.py'): + shutil.copy2(Path('/tmp')/src,operations/src) +shutil.copy2('/tmp/h2o-quick-validation.log',out/'INITIAL_RUN.log') +shutil.copy2('/tmp/h2o-fallback-check.log',out/'FALLBACK_RUN.log') +print(json.dumps(summary,ensure_ascii=False,indent=2),flush=True) diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-bench-job.sh b/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-bench-job.sh new file mode 100644 index 0000000000000000000000000000000000000000..5751d4926d5be28c5d00544b5e89f3d19424e827 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-bench-job.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -u +cd /home/xuzhefeng/Projects/uni-hoi-dataset || exit 1 +case "$1" in + old) code=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10/frozen-code/scripts/convert_h2o_v1.0.py; extra=();; + v8) code=/tmp/h2o-stream-v8-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 8 --stream-media);; + v8ram) code=/tmp/h2o-stream-v8ram-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 8 --stream-media --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-v8ram-20260930 --ram-stage-gib 32);; + s16) code=/tmp/h2o-stream-s16-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-s16-20260930 --ram-stage-gib 32);; + pipeline) code=/tmp/h2o-stream-pipeline-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --camera-pipeline --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-overlap-20260930 --ram-stage-gib 32);; + process) code=/tmp/h2o-process-pipeline-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --view-backend processes --camera-pipeline --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-process-20260930 --ram-stage-gib 32);; + v16) code=/tmp/h2o-stream-v8-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --stream-media);; + *) exit 2;; +esac +root=/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930 +caseout="$root/$1" +mkdir -p "$caseout/scratch" +export TMPDIR="$caseout/scratch" PYTHONUNBUFFERED=1 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +cat "/sys/fs/cgroup$cg/cpu.stat" > "$caseout/cpu.start" +date -Is > "$caseout/start" +.venv/bin/python "$code" --root "$root/raw" --out "$caseout" --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --max-frames 200 --mano-dir /home/xuzhefeng/Projects/WiLoR/mano_data "${extra[@]}" > "$caseout/convert.log" 2>&1 +code=$? +cat "/sys/fs/cgroup$cg/cpu.stat" > "$caseout/cpu.end" +printf '%s\n' "$code" > "$caseout/exit" +exit "$code" diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-benchmark.py b/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc90e6ead0eca79856b81000c60bff9d3b4f8b5 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-benchmark.py @@ -0,0 +1,48 @@ +import datetime,json,os,subprocess,time +from pathlib import Path +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +cpus=os.cpu_count() +records=[] +for mode in ('old','v8'): + unit=f'h2o-pipeline-{mode}-20260930.scope' + begin=time.monotonic() + proc=subprocess.Popen(['systemd-run','--user','--scope','--unit='+unit,'-p','CPUAccounting=yes', + '/bin/bash','/tmp/h2o-pipeline-bench-job.sh',mode]) + path=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') + samples=[] + while proc.poll() is None: + try: + stat=dict(line.split() for line in (path/'cpu.stat').read_text().splitlines()) + samples.append((time.monotonic()-begin,int(stat['usage_usec']))) + except (FileNotFoundError,PermissionError):pass + time.sleep(0.5) + elapsed=time.monotonic()-begin + assert proc.returncode==0,(mode,(root/mode/'convert.log').read_text()[-3000:]) + def usage(name):return int(dict(line.split() for line in (root/mode/name).read_text().splitlines())['usage_usec']) + total=usage('cpu.end')-usage('cpu.start') + peak=max(((b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[10:])),default=0) + row=dict(mode=mode,seconds=elapsed,cpu_seconds=total/1e6,cpu_percent_machine=total/elapsed/1e6/cpus*100, + peak_5s_cpu_percent_machine=peak,samples=samples) + records.append(row) + (root/'performance.json').write_text(json.dumps(records,indent=2)+'\n') + print(json.dumps({k:v for k,v in row.items() if k!='samples'}),flush=True) +# Prove actual media and every numeric tensor match, not just wall-clock speed. +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = '10' +import sys +sys.path.insert(0,'/tmp/h2o-stream-v8-recovery/scripts') +from warehouse_v1_0 import decoded_digest,validate_view +import torch +for view in sorted((root/'old/H2O/shared-v1.0/data').glob('*/cam*')): + rel=view.relative_to(root/'old/H2O/shared-v1.0/data') + candidate=root/'v8/H2O/shared-v1.0/data'/rel + assert validate_view(candidate)['validated'] + for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + aa=decoded_digest(view/'observation'/f'{name}.mkv',pix)[:2] + bb=decoded_digest(candidate/'observation'/f'{name}.mkv',pix)[:2] + assert aa==bb,(rel,name) + for pt in view.rglob('*.pt'): + aa=torch.load(pt,weights_only=True) + bb=torch.load(candidate/pt.relative_to(view),weights_only=True) + assert aa.shape==bb.shape and aa.dtype==bb.dtype and aa.numpy().tobytes()==bb.numpy().tobytes(),(rel,pt) +print('PASS all 10 real views: full RGB/depth/valid decoded digests and every numeric tensor match',flush=True) +(root/'validation.exit').write_text('0\n') diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-process-benchmark.py b/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-process-benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..b47120c02f15314c732031cbc4b05996c75b2c3e --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-process-benchmark.py @@ -0,0 +1,48 @@ +import datetime,json,os,subprocess,time +from pathlib import Path +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +cpus=os.cpu_count() +records=[] +for mode in ('process',): + unit=f'h2o-pipeline-{mode}-20260930.scope' + begin=time.monotonic() + proc=subprocess.Popen(['systemd-run','--user','--scope','--unit='+unit,'-p','CPUAccounting=yes', + '/bin/bash','/tmp/h2o-pipeline-bench-job.sh',mode]) + path=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') + samples=[] + while proc.poll() is None: + try: + stat=dict(line.split() for line in (path/'cpu.stat').read_text().splitlines()) + samples.append((time.monotonic()-begin,int(stat['usage_usec']))) + except (FileNotFoundError,PermissionError):pass + time.sleep(0.5) + elapsed=time.monotonic()-begin + assert proc.returncode==0,(mode,(root/mode/'convert.log').read_text()[-3000:]) + def usage(name):return int(dict(line.split() for line in (root/mode/name).read_text().splitlines())['usage_usec']) + total=usage('cpu.end')-usage('cpu.start') + peak=max(((b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[10:])),default=0) + row=dict(mode=mode,seconds=elapsed,cpu_seconds=total/1e6,cpu_percent_machine=total/elapsed/1e6/cpus*100, + peak_5s_cpu_percent_machine=peak,samples=samples) + records.append(row) + (root/'performance-process.json').write_text(json.dumps(records,indent=2)+'\n') + print(json.dumps({k:v for k,v in row.items() if k!='samples'}),flush=True) +# Prove actual media and every numeric tensor match, not just wall-clock speed. +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = '10' +import sys +sys.path.insert(0,'/tmp/h2o-process-pipeline-recovery/scripts') +from warehouse_v1_0 import decoded_digest,validate_view +import torch +for view in sorted((root/'old/H2O/shared-v1.0/data').glob('*/cam*')): + rel=view.relative_to(root/'old/H2O/shared-v1.0/data') + candidate=root/'process/H2O/shared-v1.0/data'/rel + assert validate_view(candidate)['validated'] + for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + aa=decoded_digest(view/'observation'/f'{name}.mkv',pix)[:2] + bb=decoded_digest(candidate/'observation'/f'{name}.mkv',pix)[:2] + assert aa==bb,(rel,name) + for pt in view.rglob('*.pt'): + aa=torch.load(pt,weights_only=True) + bb=torch.load(candidate/pt.relative_to(view),weights_only=True) + assert aa.shape==bb.shape and aa.dtype==bb.dtype and aa.numpy().tobytes()==bb.numpy().tobytes(),(rel,pt) +print('PASS all 10 real views: full RGB/depth/valid decoded digests and every numeric tensor match',flush=True) +(root/'validation-process.exit').write_text('0\n') diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-prepare-pipeline-bench.py b/H2O/shared-v1.0/script/provenance/operations/h2o-prepare-pipeline-bench.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbe75024965020f88eb282f2eeb448d491b8639 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-prepare-pipeline-bench.py @@ -0,0 +1,28 @@ +import json,os,tarfile,shutil +from pathlib import Path +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +root.mkdir(exist_ok=True) +raw=root/'raw'; raw.mkdir(exist_ok=True) +old=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10') +records=[] +for subj in ('subject3','subject4'): + subject=next((old/'scratch').glob('h2o-source-*/'+subj)) + sequences=[p for p in subject.glob('*/*') if all((p/f'cam{i}/rgb/000199.png').is_file() for i in range(5))] + assert sequences, (subj,subject) + seq=sequences[0] + snapshot=root/'input-snapshot'/subj/seq.relative_to(subject) + for src in seq.glob('cam*/*/*'): + if src.is_file() and src.parent.name in ('rgb','depth','cam_pose','hand_pose','hand_pose_mano','obj_pose','obj_pose_rt') and int(src.stem)<200: + dest=snapshot/src.relative_to(seq);dest.parent.mkdir(parents=True,exist_ok=True) + os.link(src,dest) + for src in seq.glob('cam*/cam_intrinsics.txt'): + dest=snapshot/src.relative_to(seq);dest.parent.mkdir(parents=True,exist_ok=True);os.link(src,dest) + archive=raw/f'{subj}_v1_1.tar.gz' + with tarfile.open(archive,'w:gz',compresslevel=0) as tf: + tf.add(snapshot,arcname=str(snapshot.relative_to(root/'input-snapshot'))) + records.append({'sequence':str(snapshot.relative_to(root/'input-snapshot')),'frames':200,'views':5,'archive':str(archive), + 'origin':str(seq),'gzip_compression_level':0}) +for name in ('object.zip','label_split.zip'): + os.link(Path('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data')/name,raw/name) +(root/'input-manifest.json').write_text(json.dumps(records,indent=2)+'\n') +print('PREPARED',records,flush=True) diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-prepare-process-full.py b/H2O/shared-v1.0/script/provenance/operations/h2o-prepare-process-full.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b73425e82cadf972633e303292f12f4f823fbf --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-prepare-process-full.py @@ -0,0 +1,45 @@ +"""Preserve complete persistent views; frozen process pipeline only changes execution/storage work.""" +import datetime,json,os,shutil +from pathlib import Path +old=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10') +new=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +new.mkdir() +shutil.copytree('/tmp/h2o-process-pipeline-recovery',new/'frozen-code') +release=new/'H2O/shared-v1.0' +for directory in ('data','doc/validation','script/provenance/previous-run','script/provenance/operations'): + (release/directory).mkdir(parents=True,exist_ok=True) +history=release/'script/provenance/previous-run' +shutil.copytree(old/'H2O/shared-v1.0/script',history/'script') +shutil.copytree(old/'frozen-code/docs',history/'docs') +for name in ('full.log','full.status','run-full.sh'): + shutil.copy2(old/name,history/name) +records=[] +for record in sorted((old/'H2O/shared-v1.0/doc').glob('*.build.json')): + build=json.loads(record.read_text());seq=build['sequence_id'] + assert Path(seq).name==seq and seq not in ('.','..') + assert set(build['views'])=={f'cam{i}' for i in range(5)} + folder=old/'H2O/shared-v1.0/data'/seq + for cam in build['views']:assert (folder/cam/'metainfo.json').is_file() + shutil.copytree(folder,release/'data'/seq,copy_function=os.link) + shutil.copy2(record,release/'doc'/record.name) + records.append({'sequence_id':seq,'original_script_sha256':build['scripts']}) +manifest={'time':datetime.datetime.now().astimezone().isoformat(),'source_run':str(old),'destination_run':str(new), + 'reason':'Native bytes unchanged; process/view pipeline, streaming RAW and bounded RAM staging', + 'target_cpu_percent_machine':80,'cpu_limit':None,'reused_sequences':records, + 'reuse':'Read-only hardlinks; original build records retained; source frame/component SHA256 checked on resume', + 'previous_run_provenance':'script/provenance/previous-run'} +(release/'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest,indent=2)+'\n') +operations=release/'script/provenance/operations' +for name in ('h2o-prepare-process-full.py','h2o-switch-process-full.sh','h2o-pipeline-benchmark.py', + 'h2o-pipeline-process-benchmark.py','h2o-pipeline-bench-job.sh','h2o-prepare-pipeline-bench.py', + 'h2o-process-final-tests.log','h2o-shared-final-tests.log'): + shutil.copy2(Path('/tmp')/name,operations/name) +bench=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +for p in bench.glob('performance*.json'):shutil.copy2(p,release/'doc/validation'/p.name) +shutil.copy2(bench/'input-manifest.json',release/'doc/validation/PIPELINE_BENCH_INPUTS.json') +shutil.copy2('/tmp/h2o-pipeline-process-benchmark.log',release/'doc/validation/PIPELINE_BENCHMARK.log') +shutil.copy2('/tmp/h2o-runtime-profile.log',release/'doc/validation/BEFORE_RUNTIME_PROFILE.log') +shutil.copy2('/tmp/h2o-current-iostat.log',release/'doc/validation/BEFORE_IOSTAT.log') +for destination in (new/'run-full.sh',release/'script/run-full.sh'): + shutil.copy2('/tmp/h2o-run-process-full.sh',destination) +print('REUSED_SEQUENCES',len(records),'REUSED_VIEWS',5*len(records),flush=True) diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-process-final-tests.log b/H2O/shared-v1.0/script/provenance/operations/h2o-process-final-tests.log new file mode 100644 index 0000000000000000000000000000000000000000..fdf27a753f61c8755e23e54721f766549a081d48 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-process-final-tests.log @@ -0,0 +1,39 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Verified existing subject1/h1/0 +Verified existing subject3/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Verified existing subject2/h1/0 +Verified existing subject4/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Camera-order fallback: subject1/h1/0 +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O pipe RGB/depth, RAM annotations, shared view pool 1/4/8, four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-quick-validation.py b/H2O/shared-v1.0/script/provenance/operations/h2o-quick-validation.py new file mode 100644 index 0000000000000000000000000000000000000000..45efdc32457710d01161b4ba227f903a941b1611 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-quick-validation.py @@ -0,0 +1,161 @@ +"""Full coverage/numeric audit, plus representative persisted-media QC and offline HTML.""" +import os +for key in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS'): + os.environ[key]='1' +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS']='4' +os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES',None) +os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR',None) +import collections,datetime,hashlib,html,json,re,sys,time,zipfile +from concurrent.futures import ThreadPoolExecutor,as_completed +from pathlib import Path +from zoneinfo import ZoneInfo +import numpy as np +import torch +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +release=root/'H2O/shared-v1.0' +sys.path.insert(0,str(root/'frozen-code/scripts')) +from warehouse_v1_0 import SCHEMA,check_transform,check_valid_policy,check_view_type,safe_member,sha256 +from render_h2o_validation import render +out=release/'doc/validation/final-quick-check' +out.mkdir(exist_ok=True) +torch.set_num_threads(1) +started=time.monotonic() +expected={} +with zipfile.ZipFile('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip') as z: + for name in z.namelist(): + if '/action_' not in name:continue + for line in z.read(name).decode().splitlines(): + fields=line.split() + if len(fields)>1 and fields[1]!='path': + seq=fields[1].replace('/','_') + expected[seq]=max(expected.get(seq,0),int(fields[-1])+1) +folders={p.name:p for p in (release/'data').iterdir() if p.is_dir()} +assert set(folders)==set(expected),(sorted(set(expected)-set(folders)),sorted(set(folders)-set(expected))) +assert len(expected)==184 and sum(expected.values())==114329 +receipts={p.name.removesuffix('.build.json'):p for p in (release/'doc').glob('*.build.json')} +assert set(receipts)==set(expected) +assert 'EXIT=0' in (root/'full.status').read_text() +failures=[] +rows=[] +def require(ok,message): + if not ok:raise ValueError(message) +def load(path): + def cpu(storage,location): + require(location=='cpu',f'non-CPU storage: {path}') + return storage + obj=torch.load(path,map_location=cpu,weights_only=True) + require(type(obj) is torch.Tensor,f'non-tensor: {path}') + return obj.numpy() +def check_sequence(seq): + folder=folders[seq];n=expected[seq] + require({p.name for p in folder.iterdir() if p.is_dir()}=={f'cam{i}' for i in range(5)},'five-camera coverage') + receipt=json.loads(receipts[seq].read_text()) + require(receipt['sequence_id']==seq and set(receipt['views'])=={f'cam{i}' for i in range(5)},'build receipt') + result=[] + for i in range(5): + cam=f'cam{i}';view=folder/cam + meta=json.loads((view/'metainfo.json').read_text()) + require((meta['dataset_id'],meta['sequence_id'],meta['camera_id'],meta['num_frames'])==('H2O',seq,cam,n),'header/timeline') + require(meta['view_type']==('ego' if i==4 else 'exo'),'view role') + require(meta['sampling']['selection']=={'max_frames':None,'views':None},'unexpected subsampling') + check_view_type(meta) + components=meta['components'] + require(all(components[k].get('available') for k in ('rgb','depth','mano','keypoints_xyz','intrinsic','extrinsic')),'required modality absent') + require(not components['segment']['available'] and not components['relations']['available'],'unexpected synthesized component') + rgb_sources=[];depth_sources=[];rgb_count=depth_count=0 + with (view/'camera/frames.jsonl').open() as inp: + count=0 + for index,line in enumerate(inp): + f=json.loads(line) + require(f['frame_index']==index and f['source_frame_id']==index,'source frame index') + require(f['sync_id']==f'{seq.replace("_","/")}:{index}','synchronization ID') + sources=f['component_sources'] + for kind,loc in sources.items(): + require(re.fullmatch('[0-9a-f]{64}',loc.get('sha256','')) is not None,f'source SHA256: {kind}') + require(f'/{cam}/' in loc.get('member',''),'wrong source camera') + rgb_sources.append('rgb' in sources);depth_sources.append('depth' in sources) + rgb_count+=rgb_sources[-1];depth_count+=depth_sources[-1];count+=1 + require(count==n,'frames.jsonl length') + numeric=0 + object_names=[] + for key,c in components.items(): + if not c['available']:continue + for field in ('data_ref','valid_ref','mapping_ref'): + if c.get(field): + path=safe_member(view,c[field]) + require(path.is_file() and path.stat().st_size>0,f'missing/empty {c[field]}') + schema=SCHEMA['components'][c['schema_id']] + if c.get('valid_policy'):check_valid_policy(c,n) + valid=load(view/c['valid_ref']) if c.get('valid_ref','').endswith('.pt') else None + if valid is not None: + shape=schema.get('valid_shape') + require(valid.dtype==np.bool_ and valid.shape[0]==n,f'{key}: validity dtype/timeline') + if shape:require(len(shape)==valid.ndim and all(not isinstance(s,int) or valid.shape[j]==s for j,s in enumerate(shape)),f'{key}: validity shape') + if key=='rgb':require(np.array_equal(valid,np.asarray(rgb_sources)), 'RGB existence validity mismatch') + if c['data_ref'].endswith('.pt'): + arr=load(view/c['data_ref']);numeric+=1 + require(arr.dtype==np.float32 and arr.shape[0]==n,f'{key}: dtype/timeline') + shape=schema.get('shape') + if shape:require(len(shape)==arr.ndim and all(not isinstance(s,int) or arr.shape[j]==s for j,s in enumerate(shape)),f'{key}: tensor shape') + if valid is not None: + require(arr.shape[:valid.ndim]==valid.shape and np.isfinite(arr[valid]).all() and np.isnan(arr[~valid]).all(),f'{key}: finite/NaN validity semantics') + if c['schema_id'] in ('transform/se3/v1','object/rigid/v1'):check_transform(arr[valid]) + if key=='intrinsic':require(np.allclose(arr[:,2],[0,0,1]) and (arr[:,0,0]>0).all() and (arr[:,1,1]>0).all(),'camera intrinsics') + if key.startswith('mesh_'):object_names.append(key.removeprefix('mesh_')) + proof=receipt['views'][cam] + require(not proof['unresolved'],'unresolved QC components') + media={} + for p in proof['validation']: + if p.get('profile')==components['rgb']['storage']['profile'] and p.get('all_frames_exact') is True:media['rgb']=p + elif p.get('component') in ('depth','depth_valid'):media[p['component']]=p + require(set(media)=={'rgb','depth','depth_valid'},'media roundtrip proof missing') + for key,p in media.items(): + require(p.get('all_frames_exact') is True and re.fullmatch('[0-9a-f]{64}',p.get('decoded_sha256','')) is not None,f'{key}: failed original roundtrip proof') + require((view/'observation'/f'{key}.mkv').stat().st_size==p['bytes'],f'{key}: encoded file size changed since conversion') + result.append({'sequence_id':seq,'camera':cam,'frames':n,'numeric_components':numeric, + 'rgb_source_frames':rgb_count,'depth_source_frames':depth_count,'objects':sorted(object_names)}) + return result +with ThreadPoolExecutor(max_workers=4) as pool: + jobs={pool.submit(check_sequence,seq):seq for seq in sorted(expected)} + for job in as_completed(jobs): + seq=jobs[job] + try:rows.extend(job.result()) + except Exception as exc:failures.append({'sequence':seq,'error':repr(exc)}) + if len(rows)%100==0:print('STRUCTURAL_VIEWS',len(rows),'FAILURES',len(failures),flush=True) +print('STRUCTURAL_COMPLETE',len(rows),'FAILURES',failures,flush=True) +# Balance subjects while covering all eight source object classes; include matching exo views. +objects=('book','espresso','lotion','spray','milk','cocoa','chips','cappuccino') +selected=[] +for j,name in enumerate(objects): + subject=f'subject{j%4+1}_' + candidates=[r for r in rows if r['camera']=='cam4' and name in r['objects']] + require(candidates,f'no output for object {name}') + own=[r for r in candidates if r['sequence_id'].startswith(subject)] + r=min(own or candidates,key=lambda x:(x['frames'],x['sequence_id'])) + selected.append((r['sequence_id'],'cam4',name)) + selected.append((r['sequence_id'],'cam0',name)) +samples=[] +def full_sample(item): + seq,cam,name=item + view=folders[seq]/cam + destination=out/f'{seq}_{cam}' + page=render(view,destination) # Reuse persisted contract QC, depth semantics, frame snapshots, native mesh preview. + return {'sequence_id':seq,'camera':cam,'object':name,'frames':expected[seq], + 'passed':True,'html':str(page.relative_to(out))} +with ThreadPoolExecutor(max_workers=4) as pool: + jobs={pool.submit(full_sample,item):item for item in selected} + for job in as_completed(jobs): + item=jobs[job] + try:samples.append(job.result());print('SAMPLE_PASS',item,flush=True) + except Exception as exc:failures.append({'sample':item,'error':repr(exc)});print('SAMPLE_FAIL',item,repr(exc),flush=True) +report={'time':datetime.datetime.now(ZoneInfo('Asia/Shanghai')).isoformat(),'elapsed_seconds':time.monotonic()-started, + 'release':str(release),'passed':not failures,'scope':'All sequence/camera coverage, frame/source manifests, all numeric tensors and original media receipts; 16 representative full persisted-view QC checks and offline previews. Not a new all-video source-pixel comparison.', + 'expected_sequences':len(expected),'expected_sync_frames':sum(expected.values()), + 'checked_sequences':len(rows)//5,'checked_views':len(rows),'checked_view_frames':sum(r['frames'] for r in rows), + 'rgb_source_frames':sum(r['rgb_source_frames'] for r in rows),'depth_source_frames':sum(r['depth_source_frames'] for r in rows), + 'numeric_components':sum(r['numeric_components'] for r in rows),'samples':samples,'failures':failures, + 'next_step':'Human inspection of representative offline HTML; automatic QC is not proof of source geometric accuracy.'} +(out/'QUICK_VALIDATION.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') +(out/'index.html').write_text('H2O 全量后抽样验收

H2O 全量后抽样验收

自动检查通过不等于源几何标注正确;以下为四个 subject、八类物体、ego/exo 的源数据预览。

'+html.escape(json.dumps({k:v for k,v in report.items() if k not in ('samples',)},ensure_ascii=False,indent=2))+'
') +print('FINAL_REPORT',json.dumps({k:v for k,v in report.items() if k!='samples'},ensure_ascii=False),flush=True) +raise SystemExit(0 if report['passed'] else 1) diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-shared-final-tests.log b/H2O/shared-v1.0/script/provenance/operations/h2o-shared-final-tests.log new file mode 100644 index 0000000000000000000000000000000000000000..9e8b3fadfef4187f122c1bcd295692cddf1d2523 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-shared-final-tests.log @@ -0,0 +1 @@ +PASS: RGB full/prefix hashes, source depth frames, depth/valid/segment bits and missing-frame rejection diff --git a/H2O/shared-v1.0/script/provenance/operations/h2o-switch-process-full.sh b/H2O/shared-v1.0/script/provenance/operations/h2o-switch-process-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..86ad70c2cc2df78859680827dad7973b5b14c576 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/h2o-switch-process-full.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/xuzhefeng/Projects/uni-hoi-dataset +test "$(cat /tmp/h2o-process-final-tests.exit)" = 0 +test "$(cat /tmp/h2o-shared-final-tests.exit)" = 0 +test "$(cat /tmp/h2o-pipeline-process-benchmark.exit)" = 0 +test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe +old=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10 +printf '\nRECONFIGURE=%s REASON=process16_camera_pipeline_ram32_streaming\n' "$(date -Is)" >> "$old/full.status" +systemctl --user stop h2o-full-d10-20260930.scope +.venv/bin/python /tmp/h2o-prepare-process-full.py +systemd-run --user --scope --unit=h2o-full-process16-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/run-full.sh diff --git a/H2O/shared-v1.0/script/provenance/operations/watch-steady-cpu.py b/H2O/shared-v1.0/script/provenance/operations/watch-steady-cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..06472a5229fde6c7b8ffa97c3eb92dc16e1df864 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/operations/watch-steady-cpu.py @@ -0,0 +1,38 @@ +"""Measure the whole process tree only after conversion FFmpeg is active; no CPU-fill work.""" +import datetime,json,os,time +from pathlib import Path +unit='h2o-full-process16-20260930.scope' +cg=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +report=root/'H2O/shared-v1.0/doc/validation/STEADY_CPU_5MIN.json' +start_wait=time.monotonic() +while time.monotonic()-start_wait<7200: + if not (cg/'cgroup.procs').exists(): + print('Scope exited before a steady conversion sample',flush=True);raise SystemExit(1) + ffmpeg=False + for pid in (cg/'cgroup.procs').read_text().split(): + try:ffmpeg |= Path('/proc',pid,'comm').read_text().strip()=='ffmpeg' + except FileNotFoundError:pass + if ffmpeg:break + time.sleep(5) +else: + print('No conversion FFmpeg within two hours; no steady CPU claim made',flush=True);raise SystemExit(2) +def sample(): + values=dict(line.split() for line in (cg/'cpu.stat').read_text().splitlines()) + return time.monotonic(),int(values['usage_usec']) +begin=datetime.datetime.now().astimezone().isoformat() +samples=[sample()] +for _ in range(60): + time.sleep(5) + try:samples.append(sample()) + except FileNotFoundError: + print('Scope exited during sample; inspect full.status',flush=True);raise SystemExit(1) +cpus=os.cpu_count() +intervals=[(b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[1:])] +result={'start':begin,'end':datetime.datetime.now().astimezone().isoformat(),'logical_cpus':cpus, + 'whole_scope_cpu_percent_machine':(samples[-1][1]-samples[0][1])/(samples[-1][0]-samples[0][0])/1e6/cpus*100, + 'highest_5sec_cpu_percent_machine':max(intervals),'lowest_5sec_cpu_percent_machine':min(intervals), + 'target_percent':80,'intervals_percent_machine':intervals,'samples':samples, + 'scope':unit,'includes':'All scope threads and child processes, including children already exited'} +report.write_text(json.dumps(result,indent=2)+'\n') +print(json.dumps({k:v for k,v in result.items() if k not in ('samples','intervals_percent_machine')}),flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/docs/CONTRACT.md b/H2O/shared-v1.0/script/provenance/previous-run/docs/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..f756d711647e109b6bb732ce1b9c84111730489d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/docs/CONTRACT.md @@ -0,0 +1,457 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 可选,`ego/exo/unknown` | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md b/H2O/shared-v1.0/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md new file mode 100644 index 0000000000000000000000000000000000000000..1f5cd6670065ebca7e08a8f0c0864e2474f2dbc5 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md @@ -0,0 +1,48 @@ +# H2O raw → shared-v1.0 + +## 范围与来源 + +本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN__/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。 + +| 源包/字段 | shared 文件/处理 | +| --- | --- | +| `subjectN_v1_1.tar.gz`: `camX/rgb/.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 | +| 同包 `camX/depth/.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 | +| `camX/cam_intrinsics.txt`、`camX/cam_pose/.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 | +| `camX/hand_pose_mano/.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 | +| `camX/hand_pose/.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 | +| `camX/obj_pose/.txt`、`obj_pose_rt/.txt` | `annotation/object//keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 | +| `object.zip` | `annotation/object//assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 | +| `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 | + +`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。 + +## 源资产文件名修复 + +源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。 + +## 加速与验收 + +四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码支持 `--codec-threads 1|2|4|8|10`,当前全量按用户要求使用 10;`--decode-threads 10` 通过现有 `HAND_WAREHOUSE_FFMPEG_THREADS` 控制源 RGB PNG→RGB24、完整视频解码摘要、深度/有效性语义校验与 RGB 索引抽取的解码线程,完整校验仍保留。深度 PNG 使用 `--depth-threads 4` 有序分批读取,每批最多读取 4 帧,避免缓存整条序列,缺帧仍按原时间轴写 NaN;不并行改写姿态、标注或原始包。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,历史 62 条目录不复用、不覆盖;调整并发时,在新的运行目录复用本次全量已经原子发布的完整序列,并从源重新核对帧号及逐组件 SHA256;已发布视图只读源包并核对摘要,不再把源 PNG/标注写入临时目录,待转换视图才正常暂存。未完成的临时序列不复用,原运行的脚本、配置及 QC 保留用于溯源。 + +先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。 + +2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。2026-09-30 用户取消 CPU 使用量上限,指定 4 个独立压缩包 worker、每个 FFV1 编码器 10 线程、每个校验解码器 10 线程、每 worker 深度 PNG 读取 4 线程;Python worker、读取及校验子进程不计入这最多 40 个编码线程,因此总线程数不固定为 40。该配置不代表已证明加速倍数。源包和旧产物保留;代码变化使用独立运行目录,已完成序列保留原始构建记录及生产脚本快照。 + + +## 多线程解码测速(2026-09-30) + +在 101 上以真实 `subject4/h1/0/cam0` 的完整 RGB、深度和有效性视频,以及源头 100 帧 PNG 测试;采用 1、10、10、1 的解码线程顺序,源深度 PNG 另比较 1/2/4 线程。逐字节摘要和输出长度必须相同,测速脚本、全部轮次及结果保存在 `script/provenance/operations/` 和 `doc/validation/`。测速期间旧全量任务仍运行,磁盘负载和缓存会影响结果;不得将阶段加速比冒充整套转换加速比。四个 gzip 包已经独立并行读取,暂不引入多进程重构或增加数值库线程;小矩阵及标注处理没有已测得的进一步并行收益。 + + +本次同输入结果(解码后长度和 SHA256 全部相同): + +| 阶段 | 1 线程(秒) | 新配置(秒) | 范围 | +| --- | ---: | ---: | --- | +| FFV1 RGB 解码与摘要 | 39.46 | 8.70(10 线程) | 完整 501 帧,中位数 | +| FFV1 深度位串解码与摘要 | 34.91 | 11.56(10 线程) | 完整 501 帧,中位数 | +| 有效性视频解码与摘要 | 2.24 | 2.27(10 线程) | 完整 501 帧;未获提速 | +| 源 RGB PNG 解码 | 2.67 | 1.49(10 线程) | 100 帧,1 线程使用热缓存轮次,不使用冷缓存较慢轮次来夸大提速 | +| 源深度 PNG 读取及毫米→米 | 4.67 | 2.61(4 线程) | 100 帧,中位数;帧序与数值相同 | + +这些结果只代表相应阶段;全流程还包括顺序 gzip 扫描、文件创建、源 SHA256、资产复制和磁盘读写,实际全量 ETA 待稳定吞吐后再更新。 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/docs/schema.json b/H2O/shared-v1.0/script/provenance/previous-run/docs/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d904a34272de7f3fd4428c8dc68a919e94a68fca --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/docs/schema.json @@ -0,0 +1,869 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/H2O/shared-v1.0/script/provenance/previous-run/full.log b/H2O/shared-v1.0/script/provenance/previous-run/full.log new file mode 100644 index 0000000000000000000000000000000000000000..7786507d0c59ad7f165cdc1b215d8d50ab9bd02d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/full.log @@ -0,0 +1,61 @@ +Verified existing subject1/h1/0 +Verified existing subject4/h1/0 +Verified existing subject3/h1/0 +Verified existing subject1/h1/6 +Verified existing subject2/h1/0 +Verified existing subject1/h1/3 +Verified existing subject2/h1/6 +Verified existing subject1/h1/7 +Converted subject3/h1/6 +Converted subject4/h1/6 +Verified existing subject1/h1/4 +Verified existing subject1/h1/2 +Verified existing subject2/h1/3 +Verified existing subject1/h1/1 +Verified existing subject1/h1/5 +Verified existing subject1/o1/0 +Converted subject3/h1/3 +Verified existing subject2/h1/7 +Verified existing subject1/o1/6 +Converted subject4/h1/3 +Verified existing subject1/o1/3 +Verified existing subject2/h1/4 +Verified existing subject1/o1/7 +Verified existing subject1/o1/4 +Verified existing subject2/h1/2 +Verified existing subject1/o1/2 +Converted subject3/h1/7 +Converted subject4/h1/7 +Verified existing subject1/o1/1 +Verified existing subject2/h1/1 +Verified existing subject1/o1/5 +Verified existing subject1/o2/0 +Converted subject3/h1/4 +Verified existing subject2/h1/5 +Verified existing subject1/o2/6 +Verified existing subject1/o2/3 +Verified existing subject2/o1/0 +Converted subject4/h1/4 +Verified existing subject1/o2/7 +Verified existing subject1/o2/4 +Converted subject3/h1/2 +Verified existing subject2/o1/6 +Converted subject4/h1/2 +Verified existing subject1/o2/2 +Verified existing subject2/o1/3 +Converted subject3/h1/1 +Verified existing subject1/o2/1 +Verified existing subject1/o2/5 +Verified existing subject1/k1/0 +Verified existing subject1/k1/6 +Verified existing subject2/o1/4 +Verified existing subject1/k1/3 +Converted subject3/h1/5 +Converted subject4/h1/1 +Verified existing subject1/k1/7 +Verified existing subject2/o1/2 +Converted subject4/h1/5 +Converted subject3/o1/0 +Converted subject1/k1/4 +Converted subject4/o1/0 +Verified existing subject2/o1/1 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/full.status b/H2O/shared-v1.0/script/provenance/previous-run/full.status new file mode 100644 index 0000000000000000000000000000000000000000..e8e02acf783f15b30d41ed45d921baf847c4db74 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/full.status @@ -0,0 +1,7 @@ +START=2026-09-30T11:03:05+08:00 +WORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=false +CPU_LIMIT=none +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-d10-20260930.scope +CPU_MAX=max controller_disabled + +RECONFIGURE=2026-09-30T15:47:55+08:00 REASON=process16_camera_pipeline_ram32_streaming diff --git a/H2O/shared-v1.0/script/provenance/previous-run/run-full.sh b/H2O/shared-v1.0/script/provenance/previous-run/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..eefa21bbb201a5ad30462ad7548f980793d762b0 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/run-full.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/full.status" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then + read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +else + quota=max + period=controller_disabled +fi +printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" != max ]]; then + printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi +exit "$code" diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/check_dexycb_projection.py b/H2O/shared-v1.0/script/provenance/previous-run/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/config.json b/H2O/shared-v1.0/script/provenance/previous-run/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9254fc637be8ba8821d246948787c09c5cb890c4 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/config.json @@ -0,0 +1,17 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 4, + "codec_threads": 10, + "decode_threads": 10, + "depth_threads": 4, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/convert_dexycb_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/convert_h2o_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..18418915638cf2f536e14fd1069b8441d10ea082 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_h2o_v1.0.py @@ -0,0 +1,545 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +import re +import shutil +import tarfile +import tempfile +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + depth_threads = getattr(args, 'depth_threads', 1) + def read_depth(f): + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + return np.asarray(im).astype(np.float32) / 1000.0 + return np.full((height, width), np.nan, np.float32) + def depths(): + if depth_threads == 1: + yield from map(read_depth, ids) + else: + with ThreadPoolExecutor(max_workers=depth_threads) as pool: + # Ordered batches bound decoded arrays to depth_threads frames per view. + for start in range(0, len(ids), depth_threads): + yield from pool.map(read_depth, ids[start:start + depth_threads]) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + published_views = set() + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + with sequence_dir(out, seq.replace('/', '_')) as target: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + build_record(out, seq.replace('/', '_'), reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + published_views = {view.name for view in + (out / 'data' / '_'.join(key)).glob('cam*') + if (view / 'metainfo.json').is_file()} + if selected_views and cam not in selected_views: + continue + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + if cam not in published_views: + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + # Published views still verify source bytes, but never read their staging paths. + item = (dest, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, + help='FFV1 slice threads per encode; default 4, use 10 for the current full run') + p.add_argument('--decode-threads', type=int, choices=(1, 2, 4, 8, 10), default=1, + help='FFmpeg threads for source RGB decoding and decoded-media checks') + p.add_argument('--depth-threads', type=int, choices=(1, 2, 4), default=1, + help='Bounded ordered source depth PNG loading per worker') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = str(args.decode_threads) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/convert_visor_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.py new file mode 100644 index 0000000000000000000000000000000000000000..f647011c5e5b0ce0a155f1ba6438e2802672db0e --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.py @@ -0,0 +1,74 @@ +"""Benchmark full FFV1 decodes, PNG RGB decodes, and source depth PNG loading; preserve every byte.""" +import hashlib +import json +import os +from pathlib import Path +import statistics +import subprocess +import time +from concurrent.futures import ThreadPoolExecutor +import numpy as np +from PIL import Image + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +bench = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-decode-bench-20260930') +bench.mkdir(exist_ok=True) +media = next((old / 'H2O/shared-v1.0/data').glob('subject4_h1_0*/cam0/observation/rgb.mkv')).parent +inputs = bench / 'inputs' +inputs.mkdir(exist_ok=True) +for name in ('rgb.mkv', 'depth.mkv', 'depth_valid.mkv'): + dest = inputs / name + if not dest.exists(): + os.link(media / name, dest) +source = next((old / 'scratch').glob('h2o-source-*/subject4/h1/0/cam0/rgb')).parent +for kind in ('rgb', 'depth'): + dest = inputs / kind + dest.mkdir(exist_ok=True) + for frame in sorted((source / kind).glob('*.png'))[:100]: + if not (dest / frame.name).exists(): + os.link(frame, dest / frame.name) +records = [] +expected = {} +def record(stage, threads, digest, size, seconds): + assert expected.setdefault(stage, (digest, size)) == (digest, size), stage + row = dict(stage=stage, threads=threads, seconds=seconds, sha256=digest, bytes=size) + records.append(row) + print(json.dumps(row), flush=True) + (bench / 'report.json').write_text(json.dumps(records, indent=2) + '\n') +def decode(stage, arguments, threads, pix_fmt): + cmd = ['ffmpeg','-v','error','-nostdin','-filter_threads',str(threads),'-threads',str(threads), + '-noautorotate',*arguments,'-map','0:v:0','-vsync','0','-threads',str(threads), + '-f','rawvideo','-pix_fmt',pix_fmt,'pipe:1'] + digest = hashlib.sha256() + size = 0 + start = time.monotonic() + with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: + while chunk := proc.stdout.read(1024*1024): + digest.update(chunk) + size += len(chunk) + stderr = proc.stderr.read() + assert proc.wait() == 0, stderr.decode() + record(stage, threads, digest.hexdigest(), size, time.monotonic()-start) +for threads in (1,10,10,1): + for name, pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + decode('ffv1_'+name, ['-i',str(inputs/(name+'.mkv'))], threads, pix) + decode('source_rgb_png_100', ['-framerate','30','-i',str(inputs/'rgb/%06d.png')], threads, 'rgb24') + files = sorted((inputs/'depth').glob('*.png')) + def read(path): + with Image.open(path) as im: + return np.asarray(im).astype(np.float32)/1000.0 + for depth_threads in (1,2,4): + digest = hashlib.sha256() + start = time.monotonic() + size = 0 + with ThreadPoolExecutor(max_workers=depth_threads) as pool: + # Bound decoded arrays to one small batch, as the production candidate would. + for begin in range(0,len(files),depth_threads): + for arr in pool.map(read,files[begin:begin+depth_threads]): + digest.update(arr.tobytes()) + size += arr.nbytes + record('source_depth_png_100', depth_threads, digest.hexdigest(), size, time.monotonic()-start) +print('MEDIANS',flush=True) +for stage in expected: + for threads in sorted({r['threads'] for r in records if r['stage']==stage}): + print(stage,threads,statistics.median(r['seconds'] for r in records if r['stage']==stage and r['threads']==threads),flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.py new file mode 100644 index 0000000000000000000000000000000000000000..69589418bb01420d8954893a9d19096062daf2c7 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.py @@ -0,0 +1,55 @@ +"""Reuse only atomically published sequences; preserve previous runtime provenance.""" +import datetime +import json +import os +from pathlib import Path +import shutil + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10') +snapshot = Path('/tmp/h2o-w4-c10-d10-recovery') +new.mkdir() +shutil.copytree(snapshot, new / 'frozen-code') +release = new / 'H2O/shared-v1.0' +for directory in ('data', 'doc/validation', 'script/provenance/previous-run', 'script/provenance/operations'): + (release / directory).mkdir(parents=True, exist_ok=True) +history = release / 'script/provenance/previous-run' +shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script') +shutil.copytree(old / 'frozen-code/docs', history / 'docs') +for name in ('full.log', 'full.status', 'run-full.sh'): + shutil.copy2(old / name, history / name) +records = [] +for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): + build = json.loads(record.read_text()) + seq = build['sequence_id'] + assert Path(seq).name == seq and seq not in ('.', '..') + assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq + data = old / 'H2O/shared-v1.0/data' / seq + frames = {} + for cam in build['views']: + json.loads((data / cam / 'metainfo.json').read_text()) + frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) + assert frames[cam] > 0 + shutil.copytree(data, release / 'data' / seq, copy_function=os.link) + shutil.copy2(record, release / 'doc' / record.name) + records.append({'sequence_id': seq, 'frames_by_camera': frames, + 'original_script_sha256': build['scripts']}) +manifest = {'time': datetime.datetime.now().astimezone().isoformat(), + 'source_run': str(old), 'destination_run': str(new), + 'configuration': {'workers': 4, 'codec_threads': 10, 'decode_threads': 10, + 'depth_threads': 4, 'cpu_limit': None}, + 'reuse': 'Hard-linked immutable completed views; source timeline/SHA256 still rechecked without staging published source frames', + 'excluded': 'Unpublished .tmp directories; historical 62-sequence output', + 'original_runtime_provenance': 'script/provenance/previous-run', 'sequences': records} +(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n') +operations = release / 'script/provenance/operations' +for name in ('h2o-prepare-d10.py', 'h2o-switch-d10.sh', 'h2o-benchmark-decode.py'): + shutil.copy2(Path('/tmp') / name, operations / name) +for src, dest in (('/tmp/h2o-run-d10.sh', new / 'run-full.sh'), + ('/tmp/h2o-run-d10.sh', release / 'script/run-full.sh'), + ('/tmp/h2o-decode-bench.log', release / 'doc/validation/DECODE_THREAD_BENCHMARK.log'), + ('/data/xuzhefeng/Datasets/uni-hoi-h2o-decode-bench-20260930/report.json', release / 'doc/validation/DECODE_THREAD_BENCHMARK.json'), + ('/tmp/h2o-d10-final-tests.log', operations / 'worker4-encode10-decode10-depth4-regression.log'), + ('/tmp/h2o-io-sample.log', release / 'doc/validation/IO_SAMPLE.log')): + shutil.copy2(src, dest) +print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.sh new file mode 100644 index 0000000000000000000000000000000000000000..16de8391f6058e7c0d16ab02070a6f8da8d5bb55 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/xuzhefeng/Projects/uni-hoi-dataset +test "$(cat /tmp/h2o-d10-final-tests.exit)" = 0 +test "$(cat /tmp/h2o-decode-bench.exit)" = 0 +test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10 +old=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 +# Let the already nearly complete fifth camera publish, instead of discarding four completed cameras. +while test ! -s "$old/H2O/shared-v1.0/doc/subject4_h1_0.build.json"; do + test "$(systemctl --user show --no-pager h2o-full-w4c10-r2-20260930.scope -p ActiveState --value)" = active + sleep 20 +done +printf '\nRECONFIGURE=%s REASON=decoder10_depth4_no_resume_png_writes\n' "$(date -Is)" >> "$old/full.status" +systemctl --user stop h2o-full-w4c10-r2-20260930.scope +.venv/bin/python /tmp/h2o-prepare-d10.py +systemd-run --user --scope --unit=h2o-full-d10-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10/run-full.sh diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.log b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..622982e748cfa8ca9981b3ce48c3e0b5c07c7acd --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.log @@ -0,0 +1,37 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Verified existing subject2/h1/0 +Verified existing subject1/h1/0 +Verified existing subject4/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Verified existing subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/workspace-regression.log b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/workspace-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..964660aa6c3b8130c1bf9bb607cf9762f9ca59a2 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/workspace-regression.log @@ -0,0 +1,37 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Verified existing subject4/h1/0 +Verified existing subject3/h1/0 +Verified existing subject1/h1/0 +Verified existing subject2/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.md b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..f756d711647e109b6bb732ce1b9c84111730489d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.md @@ -0,0 +1,457 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 可选,`ego/exo/unknown` | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md new file mode 100644 index 0000000000000000000000000000000000000000..431eeb6d59885c914d340d24e9ebe8b207ec84b3 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md @@ -0,0 +1,30 @@ +# H2O raw → shared-v1.0 + +## 范围与来源 + +本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN__/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。 + +| 源包/字段 | shared 文件/处理 | +| --- | --- | +| `subjectN_v1_1.tar.gz`: `camX/rgb/.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 | +| 同包 `camX/depth/.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 | +| `camX/cam_intrinsics.txt`、`camX/cam_pose/.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 | +| `camX/hand_pose_mano/.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 | +| `camX/hand_pose/.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 | +| `camX/obj_pose/.txt`、`obj_pose_rt/.txt` | `annotation/object//keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 | +| `object.zip` | `annotation/object//assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 | +| `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 | + +`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。 + +## 源资产文件名修复 + +源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。 + +## 加速与验收 + +四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码支持 `--codec-threads 1|2|4|8|10`,当前全量按用户要求使用 10,逐帧解码校验仍保留。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,历史 62 条目录不复用、不覆盖;调整并发时,在新的运行目录复用本次全量已经原子发布的完整序列,并从源重新核对帧号及逐组件 SHA256。未完成的临时序列不复用,原运行的脚本、配置及 QC 保留用于溯源。 + +先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。 + +2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。2026-09-30 用户取消 CPU 使用量上限,指定 4 个独立压缩包 worker、每个 FFV1 编码器 10 线程;Python worker、读取及校验子进程不计入这最多 40 个编码线程,因此总线程数不固定为 40。该配置不代表已证明加速倍数。源包和旧产物保留;代码变化使用独立运行目录,已完成序列保留原始构建记录及生产脚本快照。 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/schema.json b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d904a34272de7f3fd4428c8dc68a919e94a68fca --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/schema.json @@ -0,0 +1,869 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.log b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.log new file mode 100644 index 0000000000000000000000000000000000000000..88785c5ae24611caaf852eed171804ef5a164c18 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.log @@ -0,0 +1,8 @@ +Verified existing subject1/h1/0 +Verified existing subject2/h1/0 +Verified existing subject1/h1/6 +Verified existing subject1/h1/3 +Verified existing subject2/h1/6 +Converted subject3/h1/0 +Verified existing subject1/h1/7 +Converted subject4/h1/0 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.status b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.status new file mode 100644 index 0000000000000000000000000000000000000000..70a37e730f28768cec24b071afd0f74cbce3db74 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.status @@ -0,0 +1,7 @@ +START=2026-09-30T10:22:30+08:00 +WORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false +CPU_LIMIT=none +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-w4c10-r2-20260930.scope +CPU_MAX=max controller_disabled + +RECONFIGURE=2026-09-30T11:03:03+08:00 REASON=decoder10_depth4_no_resume_png_writes diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/run-full.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b9267d75a5fb7c4d1729397219e7f8ca2a688c4 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/run-full.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/full.status" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then + read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +else + quota=max + period=controller_disabled +fi +printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" != max ]]; then + printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi +exit "$code" diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/config.json b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f5f637095de54c1431bca56e19cd398949f4111a --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/config.json @@ -0,0 +1,15 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 4, + "codec_threads": 10, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..727461a74046ad8dc16ec26d6fdb365b9c304594 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +import re +import shutil +import tarfile +import tempfile +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + def depths(): + for f in ids: + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + else: + yield np.full((height, width), np.nan, np.float32) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + with sequence_dir(out, seq.replace('/', '_')) as target: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + build_record(out, seq.replace('/', '_'), reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + if selected_views and cam not in selected_views: + continue + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + item = (dest, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, + help='FFV1 slice threads per encode; default 4, use 10 for the current full run') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.py new file mode 100644 index 0000000000000000000000000000000000000000..a96df6f5773da6c009993e00cd413e1cdd305462 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.py @@ -0,0 +1,52 @@ +"""Preserve completed r1 sequences without re-encoding or touching source files.""" +import datetime +import json +import os +from pathlib import Path +import shutil + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1') +new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +snapshot = Path('/tmp/h2o-w4-c10-recovery') +new.mkdir() +shutil.copytree(snapshot / 'scripts', new / 'frozen-code/scripts') +shutil.copytree(snapshot / 'docs', new / 'frozen-code/docs') +shutil.copytree(snapshot / 'tests', new / 'frozen-code/tests') +release = new / 'H2O/shared-v1.0' +for directory in ('data', 'doc', 'script', 'script/provenance/r1', 'script/provenance/operations'): + (release / directory).mkdir(parents=True, exist_ok=True) +history = release / 'script/provenance/r1' +shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script') +shutil.copytree(old / 'frozen-code/docs', history / 'docs') +for name in ('full.log', 'full.status', 'run-full.sh'): + shutil.copy2(old / name, history / name) +records = [] +for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): + build = json.loads(record.read_text()) + seq = build['sequence_id'] + assert Path(seq).name == seq and seq not in ('.', '..') + assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq + data = old / 'H2O/shared-v1.0/data' / seq + frames = {} + for cam in build['views']: + meta = json.loads((data / cam / 'metainfo.json').read_text()) + frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) + assert frames[cam] > 0 + shutil.copytree(data, release / 'data' / seq, copy_function=os.link) + shutil.copy2(record, release / 'doc' / record.name) + records.append({'sequence_id': seq, 'frames_by_camera': frames, + 'original_script_sha256': build['scripts']}) +manifest = {'time': datetime.datetime.now().astimezone().isoformat(), + 'source_run': str(old), 'destination_run': str(new), + 'reason': 'User requested four archive workers, ten threads per encoder, no CPU quota', + 'reuse': 'Hard-linked immutable completed views; frames and component source SHA256 rechecked during resume', + 'excluded': 'Unpublished .tmp directories; historical 62-sequence output; failed initial full run', + 'original_runtime_provenance': 'script/provenance/r1', 'sequences': records} +(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n') +for source, target in (('/tmp/h2o-prepare-w4-c10.py', 'provenance/operations/prepare-w4-c10.py'), + ('/tmp/h2o-reconfigure-w4-c10.sh', 'reconfigure-w4-c10.sh'), + ('/tmp/h2o-run-w4-c10.sh', 'run-full.sh')): + shutil.copy2(source, release / 'script' / target) +shutil.copy2('/tmp/h2o-run-w4-c10.sh', new / 'run-full.sh') +shutil.copy2('/tmp/h2o-w4-c10-frozen-tests.log', history.parent / 'worker4-codec10-regression.log') +print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.sh new file mode 100644 index 0000000000000000000000000000000000000000..983a246b66440da976c7b929df289b0ec6427973 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +base=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 +script="$base/H2O/shared-v1.0/script" +mkdir -p "$script/provenance/operations" "$script/provenance/startup-failure" +mv "$script/prepare-w4-c10.py" "$script/provenance/startup-failure/prepare-w4-c10.py" +cp /tmp/h2o-prepare-w4-c10.py "$script/provenance/operations/prepare-w4-c10.py" +mv "$base/full.status" "$script/provenance/startup-failure/full.status" +mv "$base/full.log" "$script/provenance/startup-failure/full.log" +cp /tmp/h2o-retry-w4-c10.sh "$script/provenance/operations/retry-w4-c10.sh" +systemd-run --user --scope --unit=h2o-full-w4c10-r2-20260930 -p CPUAccounting=yes /bin/bash "$base/run-full.sh" diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.md b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..f756d711647e109b6bb732ce1b9c84111730489d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.md @@ -0,0 +1,457 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 可选,`ego/exo/unknown` | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/h2o-RAW_TO_SHARED.md b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/h2o-RAW_TO_SHARED.md new file mode 100644 index 0000000000000000000000000000000000000000..71253fa14376d7f6074f9a962ab4450e6db43306 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/h2o-RAW_TO_SHARED.md @@ -0,0 +1,30 @@ +# H2O raw → shared-v1.0 + +## 范围与来源 + +本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN__/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。 + +| 源包/字段 | shared 文件/处理 | +| --- | --- | +| `subjectN_v1_1.tar.gz`: `camX/rgb/.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 | +| 同包 `camX/depth/.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 | +| `camX/cam_intrinsics.txt`、`camX/cam_pose/.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 | +| `camX/hand_pose_mano/.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 | +| `camX/hand_pose/.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 | +| `camX/obj_pose/.txt`、`obj_pose_rt/.txt` | `annotation/object//keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 | +| `object.zip` | `annotation/object//assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 | +| `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 | + +`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。 + +## 源资产文件名修复 + +源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。 + +## 加速与验收 + +四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码使用 `--codec-threads 4`(经完整视图实测后选择),逐帧解码校验仍保留。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,已有旧版目录不复用、不覆盖。 + +先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。 + +2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。资源预算改为 H2O 整个进程组不超过 101 CPU 总容量的约 80%,用 systemd 用户 scope 的 CPUQuota 管理,包含 FFmpeg 子进程;不以线程个数作为硬上限。101 当前 40 个逻辑 CPU 对应 CPUQuota=3200%(32 个逻辑 CPU 等效)。这不是全机其他用户任务的负载上限。源包和旧产物保留;失败版本不覆盖,修复版本使用独立输出目录。 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/schema.json b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d904a34272de7f3fd4428c8dc68a919e94a68fca --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/schema.json @@ -0,0 +1,869 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.log b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.log new file mode 100644 index 0000000000000000000000000000000000000000..65931a5b8d015b51eddb13bde0be744e71687977 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.log @@ -0,0 +1,53 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/6 +Converted subject2/h1/6 +Converted subject1/h1/3 +Converted subject2/h1/3 +Converted subject1/h1/7 +Converted subject2/h1/7 +Converted subject1/h1/4 +Converted subject2/h1/4 +Converted subject1/h1/2 +Converted subject2/h1/2 +Converted subject1/h1/1 +Converted subject1/h1/5 +Converted subject2/h1/1 +Converted subject1/o1/0 +Converted subject2/h1/5 +Converted subject1/o1/6 +Converted subject2/o1/0 +Converted subject1/o1/3 +Converted subject2/o1/6 +Converted subject1/o1/7 +Converted subject2/o1/3 +Converted subject1/o1/4 +Converted subject1/o1/2 +Converted subject2/o1/4 +Converted subject1/o1/1 +Converted subject1/o1/5 +Converted subject2/o1/2 +Converted subject1/o2/0 +Converted subject1/o2/6 +Converted subject2/o1/1 +Converted subject1/o2/3 +Converted subject2/o1/5 +Converted subject1/o2/7 +Converted subject2/o2/0 +Converted subject1/o2/4 +Converted subject2/o2/6 +Converted subject2/o2/3 +Converted subject1/o2/2 +Converted subject2/o2/4 +Converted subject2/o2/2 +Converted subject1/o2/1 +Converted subject1/o2/5 +Converted subject2/o2/1 +Converted subject1/k1/0 +Converted subject2/o2/5 +Converted subject1/k1/6 +Converted subject2/k1/0 +Converted subject1/k1/3 +Converted subject2/k1/6 +Converted subject1/k1/7 +Converted subject2/k1/3 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.status b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.status new file mode 100644 index 0000000000000000000000000000000000000000..d53dae27bfc3a5a7669881f91405612f8b2495e4 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.status @@ -0,0 +1,7 @@ +START=2026-09-29T22:12:28+08:00 +WORKERS=2 CODEC_THREADS=4 SUBJECTS=1,2,3,4 CASA=false +CPU_BUDGET_PERCENT=80 LOGICAL_CPUS=40 +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-r1-20260929.scope +CPU_MAX=3200000 100000 + +RECONFIGURE=2026-09-30T10:20:40+08:00 REASON=user_requested_worker4_codec10 CPU_LIMIT=none diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/run-full.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d27d5547332f029b9d2e92108469ad40bc121e6 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/run-full.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260929-r1" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/H2O/shared-v1.0" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +cpus=$(getconf _NPROCESSORS_ONLN) +printf 'START=%s\nWORKERS=2 CODEC_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_BUDGET_PERCENT=80 LOGICAL_CPUS=%s\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cpus" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" == max ]] || (( quota * 100 > cpus * period * 80 )); then + printf 'EXIT=4 ERROR=CPU_QUOTA_NOT_ENFORCED\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 2 --codec-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status" +exit "$code" diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/check_dexycb_projection.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/config.json b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..76756f7bfa5e51a14928440034cf492eece3f6c2 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/config.json @@ -0,0 +1,15 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 2, + "codec_threads": 4, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_dexycb_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_h2o_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..f55e39721c261ad4483ad9ff45d3e15de817cbdf --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_h2o_v1.0.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +import re +import shutil +import tarfile +import tempfile +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + def depths(): + for f in ids: + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + else: + yield np.full((height, width), np.nan, np.float32) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + with sequence_dir(out, seq.replace('/', '_')) as target: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + build_record(out, seq.replace('/', '_'), reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + if selected_views and cam not in selected_views: + continue + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + item = (dest, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8), default=4, + help='FFV1 slice threads per encode; 4 chosen from full-view RGB benchmark') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_visor_v1.0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_dexycb_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_dexycb_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e8bb71e9ad9c5a44f85e5c50cee467a00512aa1d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_dexycb_validation.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Audit a finished Dex-YCB release and render persisted modalities for manual review.""" +from collections import Counter +import hashlib +import json +from pathlib import Path +import sys + +from render_hoi4d_validation import render + + +def inspect(root): + data, doc, scripts = root / 'data', root / 'doc', root / 'script' + sequences = sorted(p for p in data.iterdir() if p.is_dir()) + assert len(sequences) == 1000, f'expected 1000 sequences, got {len(sequences)}' + assert len(list(doc.glob('*.build.json'))) == 1000 + assert not list(data.glob('*.tmp-*')), 'unfinished temporary sequences' + config = json.loads((scripts / 'config.json').read_text()) + assert all(config.get(k) is None for k in ('limit', 'max_frames', 'subjects', 'views')) + hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in scripts.glob('*.py')} + subjects, splits, availability = Counter(), Counter(), Counter() + selected = [] + for seq in sequences: + views = sorted(p for p in seq.iterdir() if p.is_dir()) + assert len(views) == 8, (seq, len(views)) + build = json.loads((doc / (seq.name + '.build.json')).read_text()) + assert set(build['views']) == {p.name for p in views}, seq + assert all(hashes.get(k) == v for k, v in build['scripts'].items()), seq + subject = seq.name.split('_')[0] + subjects[subject] += 1 + if subjects[subject] == 1: + selected.append(views[0]) + if subject.endswith('subject-09'): + selected.append(views[-1]) # one more camera, different camera + if seq.name == '20201015-subject-09_20201015_150838': + selected.append(views[0]) # source-labelled left-hand sequence + for view in views: + meta = json.loads((view / 'metainfo.json').read_text()) + assert meta['sequence_id'] == seq.name and meta['camera_id'] == view.name, view + assert meta['dataset_id'] == 'dex-ycb' and meta['release_id'] == 'shared-v1.0', view + assert meta['num_frames'] > 0 and meta.get('view_type') == 'exo', view + assert (view / 'camera/frames.jsonl').is_file(), view + assert meta['components']['rgb']['available'], view + splits[meta['split']] += 1 + for key, part in meta['components'].items(): + if part.get('available'): + availability[key] += 1 + for ref in ('data_ref', 'valid_ref'): + if part.get(ref): + assert (view / part[ref]).is_file(), (view, key, ref) + assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects + assert availability['depth'] == availability['rgb'] == 8000, availability + report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects), + splits=dict(splits), available_views=dict(availability), config=config, + published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected], + scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.') + destination = doc / 'validation' + destination.mkdir(exist_ok=True) + (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + for view in selected: + render(view, destination) + return report + + +if __name__ == '__main__': + print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_h2o_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_h2o_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b89e7c0827f45ec7f854ff8651234cb9a4223f79 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_h2o_validation.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from render_hoi4d_validation import mesh_preview, picture, snapshot +from warehouse_v1_0 import unpack_depth, validate_view + + +def load(view, item, n): + if not item.get('available') or not item.get('data_ref', '').endswith('.pt'): + return None, None + values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy() + valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None + return (values, valid) if values.ndim and values.shape[0] == n else (None, None) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values, valid = load(view, item, n) + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
' + picture(photo) + '
RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
'] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
' + picture(Image.fromarray(luminance)) + '
深度 Z,黑=无效,白≥3 m;不改源深度
') + details = {'frame': frames[i]} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

帧 ' + str(i) + ' / ' + str(n) + '

' + ''.join(panels) + '
原帧号、全部数值标注及有效性
' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

' + html.escape(name) + '

' + mesh_preview(view / item['data_ref']) + '
源 OBJ 静态预览,不代表物体姿态投影
') + report = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

' + html.escape(title) + '

预览只作人工核查;仅显示真实存在的标注,不合成分割。

' + ''.join(pages) + '

源网格

' + ''.join(assets) + '
全部组件元数据
' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
持久化 QC
' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('

H2O 试点预览

') + return destination / (title + '.html') + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args() + for view in args.views: + print(render(view, args.out), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_source_review.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_source_review.py new file mode 100644 index 0000000000000000000000000000000000000000..79d7a58744572343670e9cbaecc4cc54ea07f1c1 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_source_review.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks.""" +import argparse +import html +import json +from pathlib import Path +import shutil +import zipfile + +import numpy as np +from PIL import Image, ImageDraw + +from render_hoi4d_validation import picture, snapshot + + +def source_parts(view): + rows = [] + for source in view.glob('annotation/object/*/assets/result.json'): + def visit(node): + if isinstance(node, list): + for child in node: + visit(child) + return + if node.get('objs'): + rows.append({'source_part_id': node['id'], 'source_part_name': node['name'], + 'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))}) + for child in node.get('children', []): + visit(child) + visit(json.loads(source.read_text())) + return rows + + +def render(view, z, output): + output.mkdir(parents=True, exist_ok=True) + meta = json.loads((view / 'metainfo.json').read_text()) + seq = meta['sampling']['selection']['source_sequence'] + w, h = meta['camera']['image_size'] + chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1}) + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen) + segment = meta['components'].get('segment', {}) + masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '

' + html.escape(seq) + f' / frame {native_id}

' + picture(image) + + '

仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。

' + + '
上游原记录与编码对照
'
+                      + html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '
') + parts = source_parts(view) + name = view.parent.name + '_' + view.name + '.html' + page = 'HOI4D source correspondence review

源姿态/原生分割/RGB 的证据图(非真值修改)

' + page += ''.join(panels) + '
CAD result.json 原生部件→OBJ;不等同逐帧姿态对应
'
+    page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '
' + (output / name).write_text(page) + print(name, 'native_part_links',len(parts),flush=True) + return name + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--raw-root', type=Path, required=True) + p.add_argument('--release', type=Path, required=True) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args(argv) + args.out.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z: + names = [] + for view in sorted((args.release / 'data').glob('*/ego')): + if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence'] + for category in ('2', '3', '14', '17')): + names.append(render(view, z, args.out)) + links = ''.join(f'
  • {html.escape(name)}
  • ' for name in names) + (args.out / 'index.html').write_text('

    源依据对照(非物体几何验收通过)

      ' + links + '
    ') + shutil.copyfile(Path(__file__), args.out / 'renderer.py') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7889a1b63b004e046b52fe4e4da0b2b4651b768 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_validation.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Standalone, offline HTML review of every persisted component in selected views.""" +import argparse +import base64 +import html +import io +import json +import random +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from warehouse_v1_0 import video_frames, unpack_depth, validate_view + + +def snapshot(video, fmt, shape, dtype, indices): + return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices} + + +def picture(image): + image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized. + output = io.BytesIO() + image.save(output, format='PNG') + return '' + + +def preview_color(value, dataset_id): + # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette + # gave it the same color as YCB object 15; keep data codes untouched. + if dataset_id == 'dex-ycb' and value == 255: + return (255, 32, 64) + return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131)) + + +def mesh_preview(path): + """Project the whole source asset; bound drawing cost without favoring early faces.""" + vertices, faces, referenced = [], [], set() + rng = random.Random(0) + face_count = 0 + with path.open(errors='replace') as stream: + for line in stream: + if line.startswith('v '): + vertices.append([float(v) for v in line.split()[1:4]]) + elif line.startswith('f '): + face = [] + for token in line.split()[1:]: + index = int(token.split('/')[0]) + face.append(index - 1 if index > 0 else len(vertices) + index) + if len(face) < 3: + continue + referenced.update(face) + face_count += 1 + # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail. + if len(faces) < 5000: + faces.append(face) + else: + pick = rng.randrange(face_count) + if pick < len(faces): + faces[pick] = face + if not vertices or not faces: + return 'OBJ 未提供可绘制的顶点/面' + if min(referenced) < 0 or max(referenced) >= len(vertices): + raise ValueError(f'invalid OBJ face index: {path}') + xyz = np.asarray(vertices, dtype=np.float64) + if not np.isfinite(xyz).all(): + raise ValueError(f'nonfinite OBJ vertex: {path}') + # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose. + projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2), + (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6))) + used = projected[np.fromiter(referenced, dtype=np.int64)] + lo, hi = used.min(axis=0), used.max(axis=0) + extent = (hi - lo).max() + if extent <= 0: + return 'OBJ 所有面投影到同一点' + projected = (projected - (lo + hi) / 2) * (380 / extent) + 215 + image = Image.new('RGB', (430, 430), 'white') + draw = ImageDraw.Draw(image) + for face in faces: + polygon = [tuple(projected[i]) for i in face] + draw.line(polygon + [polygon[0]], fill='#205caa', width=1) + return picture(image) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + n = meta['num_frames'] + width, height = meta['camera']['image_size'] + components = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + for item in components.values(): + ref = item.get('valid_ref', '') + if ref.endswith('.pt'): + valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy() + if valid.shape[0] == n: + matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(matching): + selected.add(int(matching[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '' + picture(image) + '
    RGB + 原生 2D 手关键点(若有)
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z(黑=无效,白≥3 m;仅预览)
    ') + if i in masks: + mask = masks[i] + colors = np.zeros((*mask.shape, 3), dtype=np.uint8) + for value in np.unique(mask): + if value not in (0, 65535): + colors[mask == value] = preview_color(int(value), meta['dataset_id']) + legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535)) + panels.append('
    ' + picture(Image.fromarray(colors)) + '
    原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')
    ') + active = (mask != 0) & (mask != 65535) + overlay = rgb[i].copy() + overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(overlay)) + '
    原生分割叠加 RGB(仅预览)
    ') + details = {'frame': frames[i], 'segment_labels': labels.get(i, [])} + for name, component in components.items(): + ref = component.get('data_ref', '') + if component.get('available') and ref.endswith('.pt'): + values = torch.load(view / ref, map_location='cpu', weights_only=True) + if values.ndim and values.shape[0] == n: + details[name] = {'value': values[i].tolist()} + if component.get('valid_ref', '').endswith('.pt'): + valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True) + details[name]['valid'] = valid[i].tolist() + sections.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + + '
    帧号、来源、全部数值组件与有效性
    '
    +                        + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, component in components.items(): + if component.get('available') and component['data_ref'].lower().endswith('.obj'): + ref = component['data_ref'] + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / ref) + + '
    仅展示网格原生形状;未验证尺度/位姿对应。
    ') + result = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。

    ' + ''.join(sections) + '

    原始物体模型(独立预览)

    ' + ''.join(assets) + '
    全部组件元信息及原始来源
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC 结果
    ' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2)) + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('' + html.escape(meta['dataset_id']) + ' review

    ' + html.escape(meta['dataset_id']) + ' 抽样人工审核

    选择视图;所有预览均来自已保存的 shared 数据。

    ') + print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + for view in args.views: + render(view, args.out or view.parents[2] / 'doc/validation') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/run-full.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d27d5547332f029b9d2e92108469ad40bc121e6 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/run-full.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260929-r1" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/H2O/shared-v1.0" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +cpus=$(getconf _NPROCESSORS_ONLN) +printf 'START=%s\nWORKERS=2 CODEC_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_BUDGET_PERCENT=80 LOGICAL_CPUS=%s\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cpus" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" == max ]] || (( quota * 100 > cpus * period * 80 )); then + printf 'EXIT=4 ERROR=CPU_QUOTA_NOT_ENFORCED\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 2 --codec-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status" +exit "$code" diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/warehouse_v1_0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/warehouse_v1_0.py new file mode 100644 index 0000000000000000000000000000000000000000..f705011bcea587bd320e1e228f99bed259b32b3a --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/warehouse_v1_0.py @@ -0,0 +1,931 @@ +"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis.""" +import argparse +from contextlib import contextmanager +from functools import lru_cache +import hashlib +import json +import math +import shlex +from pathlib import Path +import pickle +import random +import shutil +import subprocess +import tempfile +import time + +import numpy as np +from PIL import Image +import torch + +SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json', + Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file()) +SCHEMA = json.loads(SCHEMA_PATH.read_text()) +RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw' + + +def json_write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + + +def jsonl_write(path, rows): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w') as out: + for row in rows: + out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n') + + +def sha256(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() + + +def locator(path, member=None, data=None, **extra): + result = {'file': str(Path(path).resolve())} + if member is not None: + result['member'] = member + if data is not None: + result['sha256'] = hashlib.sha256(data).hexdigest() + return result | extra + + +def source(method='Copy source annotation; normalize storage only'): + return {'kind': 'format_conversion', 'method': method} + + +def run(args, **kwargs): + return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs) + + +@lru_cache(maxsize=1) +def ffversion(): + return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0] + + +def probe(path): + return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_streams', '-of', 'json', str(path)], + stdout=subprocess.PIPE).stdout)['streams'][0] + + +def decode_args(path, pixel_format): + return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', pixel_format] + + +def decoded_digest(path, pixel_format): + start = time.monotonic() + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], + stdout=subprocess.PIPE, stderr=err) + digest, size = hashlib.sha256(), 0 + with proc.stdout: + while chunk := proc.stdout.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + if proc.wait(): + err.seek(0) + raise RuntimeError(err.read().decode(errors='replace')) + return digest.hexdigest(), size, time.monotonic() - start + + +def video_frames(path, pixel_format, shape, dtype): + frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err) + completed = False + try: + while True: + data = proc.stdout.read(frame_bytes) + if not data: + break + if len(data) != frame_bytes: + raise ValueError('truncated decoded video frame') + yield np.frombuffer(data, dtype=dtype).reshape(shape) + if proc.wait(): + err.seek(0) + raise ValueError(err.read().decode(errors='replace')) + completed = True + finally: + proc.stdout.close() + if not completed and proc.poll() is None: + proc.terminate() + proc.wait() + + +def storage(path, profile, parameters, source_lossy): + info = probe(path) + if info['codec_name'] == 'h264': + frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0', + '-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames'] + parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]} + return {'profile': profile, 'codec': info['codec_name'], + 'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']], + 'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False, + 'color_space': info.get('color_space', 'unknown'), + 'color_range': info.get('color_range', 'unknown'), + 'color_primaries': info.get('color_primaries', 'unknown'), + 'color_transfer': info.get('color_transfer', 'unknown')}, + 'encoder_parameters': {'version': ffversion()} | parameters, + 'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'} + + +def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1): + start = time.monotonic() + run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-y', '-f', 'rawvideo', + '-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30', + '-i', str(raw), '-an', '-c:v', codec, '-threads', str(threads), *extra, str(target)]) + digest, size, decode_seconds = decoded_digest(target, pixel_format) + if size != Path(raw).stat().st_size or digest != sha256(raw): + raise ValueError(f'lossless roundtrip failed: {target}') + config = storage(target, profile, {'name': codec, 'arguments': list(extra), 'threads': threads}, False) + return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds, + 'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True} + + +def measure_rgb_access(video, raw, width, height, count): + index = count // 2 + start = time.monotonic() + data = run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(video), '-vf', f'select=eq(n\\,{index})', '-frames:v', '1', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], stdout=subprocess.PIPE).stdout + with raw.open('rb') as inp: + inp.seek(index * width * height * 3) + if data != inp.read(width * height * 3): + raise ValueError('exact indexed RGB read failed') + return {'random_access_strategy': 'decode from first keyframe; select exact presentation index', + 'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start} + + +def jpeg_sample_indices(sequence, camera, count): + seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big') + indices = {0, count - 1, count // 4, count // 2, 3 * count // 4} + indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices], + min(count, 16) - len(indices))) + return sorted(indices), seed + + +def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full): + packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)], + stdout=subprocess.PIPE).stdout)['packets'] + if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes: + raise ValueError('JPEG packet hashes/order/count differ') + info = probe(target) + if [info['width'], info['height']] != list(size): + raise ValueError('JPEG container dimensions differ') + indices, seed = jpeg_sample_indices(sequence, camera, len(paths)) + if full: + indices = list(range(len(paths))) + select = '+'.join(f'eq(n\\,{i})' for i in indices) + frame_bytes = size[0] * size[1] * 3 + # Spool selected frames to disk, keeping RAM bounded for full-view audits. + with tempfile.TemporaryFile() as decoded: + run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded) + decoded.seek(0) + for i in indices: + expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout + if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected: + raise ValueError(f'JPEG decoded pixels differ at frame {i}') + if decoded.read(1): + raise ValueError('JPEG selected pixel count differs') + return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed, + 'selected_frame_indices': indices, 'pixel_frames_checked': len(indices), + 'packet_frames_checked': len(paths), 'jpeg_packets_exact': True, + 'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True, + 'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full} + + +def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False, + ffv1_first=False, codec_threads=1): + """JPEG packet proof plus deterministic pixels; re-encodings compare all pixels.""" + target.parent.mkdir(parents=True, exist_ok=True) + raw = work / 'rgb.raw' + packets = [] + has_missing = video is None and any(p is None for p in paths) + if has_missing: + present = next((p for p in paths if p is not None), None) + if present is None: + raise ValueError('no source RGB image to establish the pixel format/grid') + original = probe(present) + width, height = original['width'], original['height'] + with raw.open('wb') as dest: + for path in paths: + if path is None: + dest.write(bytes(width * height * 3)) + else: + with Image.open(path) as im: + if im.mode != 'RGB' or im.size != (width, height): + raise ValueError('source RGB grid/type changes within view') + run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest) + lossy, count = 'unknown', len(paths) + input_args = None + elif video is None: + if not paths: + raise ValueError('RGB timeline must contain existing source images') + suffix = paths[0].suffix.lower() + if suffix not in ('.jpg', '.jpeg', '.png'): + raise ValueError('unsupported source RGB format') + images = work / 'rgb_source' + images.mkdir() + dimensions = None + for i, path in enumerate(paths): + with Image.open(path) as im: + if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size): + raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion') + dimensions = im.size + if im.format == 'PNG' and path.read_bytes()[24] != 8: + raise ValueError('high bit depth RGB needs a registered schema') + dest = images / f'{i:08d}{suffix}' + shutil.copyfile(path, dest) + packets.append(sha256(path)) + width, height = dimensions + input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))] + count = len(paths) + original = probe(paths[0]) + lossy = suffix in ('.jpg', '.jpeg') + else: + original = probe(video) + if int(original.get('bits_per_raw_sample') or 8) > 8 or any( + x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')): + raise ValueError('high bit depth RGB needs a registered schema') + width, height = original['width'], original['height'] + input_args = ['-i', str(video)] + lossy = 'unknown' + limits = ['-frames:v', str(count)] if count else [] + records = [] + if video is None and not has_missing and suffix in ('.jpg', '.jpeg'): + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + encode_seconds = time.monotonic() - start + validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg) + cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy) + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size, + 'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds}) + return cfg, [width, height], records, count + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + if not has_missing: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', '1', '-noautorotate', + *input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)]) + frame_bytes = width * height * 3 + actual, remainder = divmod(raw.stat().st_size, frame_bytes) + if remainder or not actual or (count is not None and actual != count): + raise ValueError('source RGB frame count mismatch') + expected_hash = sha256(raw) + can_copy = video is not None + if can_copy: + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + digest, size, seconds = decoded_digest(target, 'rgb24') + if digest != expected_hash or size != raw.stat().st_size: + raise ValueError('stream-copy RGB bytes/order/count mismatch') + cfg = storage(target, 'mkv/source_copy/v1', + {'stream_copy': True}, lossy) + if video: + cfg['storage_fps'] = original.get('avg_frame_rate') + cfg['preserve_source_pts'] = True + records.append({'profile': cfg['profile'], 'all_frames_exact': True, + 'decoded_sha256': digest, + 'bytes': target.stat().st_size, 'decode_seconds': seconds, + 'encode_seconds': time.monotonic() - start - seconds}) + records[-1].update(measure_rgb_access(target, raw, width, height, actual)) + return cfg, [width, height], records, actual + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'stream_copy', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + candidates = [] + for profile, codec, params in [ + ('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']), + ('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]: + path = work / (codec + '.mkv') + try: + cfg, record = encode_raw(raw, path, width, height, 'rgb24', profile, codec, params, + codec_threads if codec == 'ffv1' else 1) + cfg['source_lossy'] = lossy + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + record['profile'] = profile + record.update(measure_rgb_access(path, raw, width, height, actual)) + records.append(record) + candidates.append((path.stat().st_size, path, cfg)) + if ffv1_first and codec == 'ffv1': + break # Keep the H.264 fallback only if the preferred exact encoder fails. + except subprocess.CalledProcessError as exc: + records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')}) + if not candidates: + raise ValueError('no supported lossless RGB encoder') + _, chosen, cfg = min(candidates, key=lambda x: x[0]) + shutil.move(chosen, target) + return cfg, [width, height], records, actual + + +def pack_depth(depth): + bits = np.ascontiguousarray(depth, dtype='> 16).astype(' 0) + arr[~good] = np.nan + out.write(pack_depth(arr).tobytes()) + vo.write(good.astype(np.uint8).tobytes()) + else: + if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535: + raise ValueError('invalid segmentation region codes') + out.write(arr.astype(' vertices: + raise ValueError('empty or invalid mesh') + def dependency(parent, name): + dep = (parent / name).resolve() + if not dep.is_relative_to(asset_root) or not dep.is_file(): + raise ValueError(f'missing or escaping asset dependency: {name}') + return dep + dependencies = [] + for name in materials: + mtl = dependency(path.parent, name) + dependencies.append(mtl) + for line in mtl.read_text().splitlines(): + fields = shlex.split(line, comments=True) + if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')): + dependencies.append(dependency(mtl.parent, fields[-1])) + return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path), + 'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}} + + +def mesh_asset(view, oid, directory, obj, loc): + dest = view.path / f'annotation/object/{oid}/assets' + shutil.copytree(directory, dest) + ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix() + mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest) + view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check}) + view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m') + p = view.path / f'annotation/object/{oid}/metainfo.json' + info = json.loads(p.read_text()) + info.update(has_model=True, mesh_ref=ref) + json_write(p, info) + + +def safe_member(root, name): + path = (Path(root) / name).resolve() + if not path.is_relative_to(Path(root).resolve()): + raise ValueError(f'unsafe archive path: {name}') + return path + + +class ChumpyStub: + def __setstate__(self, state): + self.__dict__.update(state) + + +class ManoUnpickler(pickle.Unpickler): + def find_class(self, module, name): + if module.startswith('chumpy'): + return ChumpyStub + return super().find_class(module, name) + + +def mano_models(directory): + result = {} + if directory is None: + return result + for side in ('left', 'right'): + path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl' + if not path.exists(): + continue + with path.open('rb') as f: + data = ManoUnpickler(f, encoding='latin1').load() + result[side] = {'components': np.asarray(data['hands_components']), + 'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path), + 'file': path.name} + return result + + +def model_profile(models): + identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode() + return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True, + 'left_shapedirs_correction': 'not_applied', + 'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}} + + +def pca_to_axis_angle(coeffs, model): + coeffs = np.asarray(coeffs) + if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all(): + raise ValueError('invalid MANO PCA coefficients') + return coeffs @ model['components'] + model['mean'] + + +def parser(dataset, description): + p = argparse.ArgumentParser(description=description) + p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset) + p.add_argument('--out', type=Path, default=Path('converted')) + p.add_argument('--release-id', default='v1.0') + p.add_argument('--limit', type=int, help='Maximum sequences to convert') + p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)') + p.add_argument('--mano-dir', type=Path) + p.add_argument('--views', help='Comma-separated source camera IDs') + p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views') + return p + + +def roots(root): + root = Path(root).expanduser() + return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()] + + +def find_file(root, name): + return next((p / name for p in roots(root) if (p / name).exists()), None) + + +def release(args, dataset): + if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'): + raise ValueError('release-id must be a single directory name') + if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1: + raise ValueError('limits must be positive') + out = args.out.expanduser().resolve() / dataset / args.release_id + raw = args.root.expanduser().resolve() + if out == raw or out.is_relative_to(raw): + raise ValueError('output must not modify the raw source tree') + (out / 'data').mkdir(parents=True, exist_ok=True) + (out / 'doc').mkdir(exist_ok=True) + (out / 'script').mkdir(exist_ok=True) + scripts = list(Path(__file__).resolve().parent.glob('*.py')) + existing = {p.name for p in (out / 'script').glob('*.py')} + if existing and existing != {p.name for p in scripts}: + raise ValueError('converter files changed; choose a new --release-id') + copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')] + copies += [(path, out / 'script' / path.name) for path in scripts] + # Check every existing file before changing any published definition or script. + for src, dest in copies: + if dest.exists() and sha256(dest) != sha256(src): + raise ValueError('converter or contract changed within an existing release; choose a new --release-id') + for src, dest in copies: + if src.resolve() != dest.resolve(): + shutil.copyfile(src, dest) + json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}) + return out + + +@contextmanager +def sequence_dir(out, sequence): + if Path(sequence).name != sequence: + raise ValueError('sequence ID must be a single path component') + final = out / 'data' / sequence + with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd: + tmp = Path(wd) + yield tmp + if final.exists(): + if any((final / child.name).exists() for child in tmp.iterdir()): + raise FileExistsError('view already published; use a new release-id to preserve it') + for child in list(tmp.iterdir()): + child.rename(final / child.name) + else: + tmp.rename(final) + + +def build_record(out, sequence, reports): + path = out / 'doc' / (sequence + '.build.json') + previous = json.loads(path.read_text()) if path.exists() else {} + config = json.loads((out / 'script/config.json').read_text()) + for report in reports.values(): + report['configuration'] = config + json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'], + 'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')}, + 'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()}, + 'views': previous.get('views', {}) | reports}) + + +def check_view_type(meta): + # The pinned ARCTIC contract makes view_type optional; adapters still supply known views. + if 'view_type' not in meta: + return + if meta['view_type'] not in ('ego', 'exo', 'unknown'): + raise ValueError('view_type must be ego/exo/unknown') + expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id']) + if meta['dataset_id'] == 'H2O': + expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + if expected and meta['view_type'] not in (expected, 'unknown'): + raise ValueError('view_type contradicts known source capture setup') + + +def check_valid_policy(component, count): + policy = component.get('valid_policy', {}) + for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks', + 'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'): + if field not in policy: + raise ValueError(f'valid_policy missing {field}') + if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']: + raise ValueError('outdated annotation validity semantics') + if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']: + raise ValueError('incomplete validity rule/scope') + if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'): + raise ValueError('official QA requires a verified adapter; supervision acceptance paused') + excluded = policy['local_excluded_frame_indices'] + if any(type(i) is not int or not 0 <= i < count for i in excluded): + raise ValueError('invalid local exclusion frame index') + if excluded: + raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters') + if policy['visibility_independent'] is not True: + raise ValueError('visibility must remain independent of validity') + + +def validate_view(path): + """Validate the persisted contract, not a rendering of the source labels.""" + path = Path(path) + meta = json.loads((path / 'metainfo.json').read_text()) + n = meta['num_frames'] + check_view_type(meta) + if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1: + raise ValueError('invalid view header') + def resolve(ref): + if Path(ref).is_absolute() or '\\' in ref: + raise ValueError('component reference must be relative POSIX') + dest = safe_member(path, ref) + if not dest.is_file(): + raise ValueError(f'referenced file missing: {ref}') + return dest + def tensor(ref): + def cpu_storage(storage, location): + if location != 'cpu': + raise ValueError('PT storage must be on CPU') + return storage + value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True) + if not isinstance(value, torch.Tensor) or value.device.type != 'cpu': + raise ValueError('PT must contain only a CPU Tensor') + return value.numpy() + frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()] + if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)): + raise ValueError('frame index/count mismatch') + for f in frames: + if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')): + raise ValueError('incomplete frame provenance') + entities = {'hand_left', 'hand_right'} + parts = {} + for p in (path / 'annotation/object').glob('*/metainfo.json'): + obj = json.loads(p.read_text()) + if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'): + raise ValueError('invalid object identity') + entities.add(obj['object_id']) + if obj.get('mesh_ref'): + if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()): + raise ValueError('mesh must belong to its object') + if obj.get('articulation_ref'): + art = json.loads(resolve(obj['articulation_ref']).read_text()) + part_ids = {part['part_id'] for part in art['parts']} + if len(part_ids) != len(art['parts']): + raise ValueError('duplicate part ID') + parents = {part['part_id']: part['parent_id'] for part in art['parts']} + for part_id in parents: + visited, cur = set(), part_id + while cur is not None: + if cur in visited or cur not in parents: + raise ValueError('invalid or cyclic part hierarchy') + visited.add(cur) + cur = parents[cur] + parts[obj['object_id']] = part_ids + video_stats = {} + for key, component in meta['components'].items(): + if not component.get('available'): + if not component.get('reason'): + raise ValueError('unavailable component needs a reason') + continue + schema = SCHEMA['components'][component['schema_id']] + for required in ('axes', 'provenance', 'source_locator'): + if required not in component: + raise ValueError(f'{key}: {required} missing') + for required in schema.get('required_metadata', []): + if required not in component: + raise ValueError(f'{key}: {required} missing') + if component['provenance']['kind'] == 'derived': + raise ValueError('v1.0 must not synthesize annotations') + if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'): + if not component.get('valid_ref') or not component.get('valid_axes'): + raise ValueError(f'{key}: annotation validity reference/axes missing') + check_valid_policy(component, n) + data_path = resolve(component['data_ref']) + valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None + valid_shape = schema.get('valid_shape') + if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any( + isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))): + raise ValueError(f'{key}: validity schema shape mismatch') + if valid is not None and (valid.dtype != bool or valid.shape[0] != n): + raise ValueError(f'{key}: invalid validity tensor') + if component['schema_id'] == 'mesh/obj/v1': + objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None) + if objroot is None: + raise ValueError('mesh must be owned by an object') + check_mesh(data_path, objroot) + if data_path.suffix == '.pt': + arr = tensor(component['data_ref']) + if arr.dtype != np.float32 or arr.shape[0] != n: + raise ValueError(f'{key}: float dtype or timeline mismatch') + shape = schema.get('shape') + if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))): + raise ValueError(f'{key}: schema shape mismatch') + if valid is not None: + if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all(): + raise ValueError(f'{key}: invalid finite/NaN/validity values') + if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'): + check_transform(arr[valid]) + if data_path.suffix == '.mkv': + cfg = component['storage'] + if cfg['profile'] not in SCHEMA['storage_profiles']: + raise ValueError('unregistered video profile') + for field in SCHEMA['video_metadata']['required']: + if field not in cfg: + raise ValueError('video storage declaration incomplete') + w, h = meta['camera']['image_size'] + if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]: + raise ValueError('encoded raster differs from logical RGB grid') + actual = probe(data_path) + if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or + [actual['width'], actual['height']] != cfg['encoded_size']): + raise ValueError('video storage metadata differs from file') + if key == 'rgb': + fmt, bpp = 'rgb24', 3 + else: + fmt, bpp = 'gray16le', 2 + digest, size, _ = decoded_digest(data_path, fmt) + w, h = cfg['encoded_size'] + if size != n * w * h * bpp: + raise ValueError('raster timeline mismatch') + video_stats[key] = {'decoded_sha256': digest, 'frames': n} + if key == 'depth': + validity = component['valid_storage'] + vp = resolve(component['valid_ref']) + actual_valid = probe(vp) + if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1' + or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]): + raise ValueError('invalid depth validity video') + count = 0 + for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), ' 0)).all() or not np.isnan(depth[~good]).all(): + raise ValueError('invalid depth/validity semantics') + count += 1 + if count != n: + raise ValueError('depth validity timeline mismatch') + if component['schema_id'].startswith('segment/') and component.get('mapping_ref'): + rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()] + if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)): + raise ValueError('segmentation mapping timeline mismatch') + for row in rows: + labels = row['labels'] + if len({a['mask_value'] for a in labels}) != len(labels): + raise ValueError('duplicate region mapping') + for label in labels: + if label['entity_id'] is not None and label['entity_id'] not in entities: + raise ValueError('unresolved segmentation entity') + if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()): + raise ValueError('unresolved segmentation part') + if component['schema_id'] == 'segment/uint16_labels/v1': + width, height = meta['camera']['image_size'] + for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), ' + raise SystemExit(main()) + ^^^^^^ + File "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/frozen-code/scripts/convert_h2o_v1.0.py", line 316, in main + out = release(args, 'H2O') + ^^^^^^^^^^^^^^^^^^^^ + File "/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/frozen-code/scripts/warehouse_v1_0.py", line 676, in release + raise ValueError('converter files changed; choose a new --release-id') +ValueError: converter files changed; choose a new --release-id +Command exited with non-zero status 1 + Command being timed: ".venv/bin/python /home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/frozen-code/scripts/convert_h2o_v1.0.py --root /home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O --out /home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 --release-id shared-v1.0 --workers 4 --codec-threads 10 --mano-dir /home/xuzhefeng/Projects/WiLoR/mano_data" + User time (seconds): 1.71 + System time (seconds): 0.20 + Percent of CPU this job got: 99% + Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.93 + Average shared text size (kbytes): 0 + Average unshared data size (kbytes): 0 + Average stack size (kbytes): 0 + Average total size (kbytes): 0 + Maximum resident set size (kbytes): 229832 + Average resident set size (kbytes): 0 + Major (requiring I/O) page faults: 0 + Minor (reclaiming a frame) page faults: 39947 + Voluntary context switches: 42 + Involuntary context switches: 48 + Swaps: 0 + File system inputs: 0 + File system outputs: 8 + Socket messages sent: 0 + Socket messages received: 0 + Signals delivered: 0 + Page size (bytes): 4096 + Exit status: 1 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/full.status b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/full.status new file mode 100644 index 0000000000000000000000000000000000000000..58188531e6b6b0a46f29659f2317b364902fc1ed --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/full.status @@ -0,0 +1,10 @@ +START=2026-09-30T10:21:04+08:00 +WORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false +CPU_LIMIT=none +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-w4c10-20260930.scope +CPU_MAX=max controller_disabled +EXIT=1 END=2026-09-30T10:21:06+08:00 +usage_usec 1945180 +user_usec 1723590 +system_usec 221590 +core_sched.force_idle_usec 0 diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/prepare-w4-c10.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/prepare-w4-c10.py new file mode 100644 index 0000000000000000000000000000000000000000..ea7952ec80912d5efd7f6cba4d7dbb88999c3f06 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/prepare-w4-c10.py @@ -0,0 +1,52 @@ +"""Preserve completed r1 sequences without re-encoding or touching source files.""" +import datetime +import json +import os +from pathlib import Path +import shutil + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1') +new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +snapshot = Path('/tmp/h2o-w4-c10-recovery') +new.mkdir() +shutil.copytree(snapshot / 'scripts', new / 'frozen-code/scripts') +shutil.copytree(snapshot / 'docs', new / 'frozen-code/docs') +shutil.copytree(snapshot / 'tests', new / 'frozen-code/tests') +release = new / 'H2O/shared-v1.0' +for directory in ('data', 'doc', 'script', 'script/provenance/r1'): + (release / directory).mkdir(parents=True, exist_ok=True) +history = release / 'script/provenance/r1' +shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script') +shutil.copytree(old / 'frozen-code/docs', history / 'docs') +for name in ('full.log', 'full.status', 'run-full.sh'): + shutil.copy2(old / name, history / name) +records = [] +for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): + build = json.loads(record.read_text()) + seq = build['sequence_id'] + assert Path(seq).name == seq and seq not in ('.', '..') + assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq + data = old / 'H2O/shared-v1.0/data' / seq + frames = {} + for cam in build['views']: + meta = json.loads((data / cam / 'metainfo.json').read_text()) + frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) + assert frames[cam] > 0 + shutil.copytree(data, release / 'data' / seq, copy_function=os.link) + shutil.copy2(record, release / 'doc' / record.name) + records.append({'sequence_id': seq, 'frames_by_camera': frames, + 'original_script_sha256': build['scripts']}) +manifest = {'time': datetime.datetime.now().astimezone().isoformat(), + 'source_run': str(old), 'destination_run': str(new), + 'reason': 'User requested four archive workers, ten threads per encoder, no CPU quota', + 'reuse': 'Hard-linked immutable completed views; frames and component source SHA256 rechecked during resume', + 'excluded': 'Unpublished .tmp directories; historical 62-sequence output; failed initial full run', + 'original_runtime_provenance': 'script/provenance/r1', 'sequences': records} +(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n') +for source, target in (('/tmp/h2o-prepare-w4-c10.py', 'prepare-w4-c10.py'), + ('/tmp/h2o-reconfigure-w4-c10.sh', 'reconfigure-w4-c10.sh'), + ('/tmp/h2o-run-w4-c10.sh', 'run-full.sh')): + shutil.copy2(source, release / 'script' / target) +shutil.copy2('/tmp/h2o-run-w4-c10.sh', new / 'run-full.sh') +shutil.copy2('/tmp/h2o-w4-c10-frozen-tests.log', history.parent / 'worker4-codec10-regression.log') +print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-final-regression.log b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-final-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..1567daf867ed1a6ddda45dc8e52f659325c17b2c --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-final-regression.log @@ -0,0 +1,29 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject3/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec 1/4/10, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-regression.log b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..5382e73ffa63d0b26e08739134fe21ab7b25155a --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-regression.log @@ -0,0 +1,29 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec 1/4/10, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/reconfigure-w4-c10.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/reconfigure-w4-c10.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a6af7e0bec22e511e06d11ee33c8429cdd2a9bd --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/reconfigure-w4-c10.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/xuzhefeng/Projects/uni-hoi-dataset +test "$(cat /tmp/h2o-w4-c10-frozen-tests.exit)" = 0 +test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 +scope=h2o-full-r1-20260929.scope +test "$(systemctl --user show --no-pager "$scope" -p ActiveState --value)" = active +printf '\nRECONFIGURE=%s REASON=user_requested_worker4_codec10 CPU_LIMIT=none\n' "$(date -Is)" >> /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1/full.status +systemctl --user stop "$scope" +.venv/bin/python /tmp/h2o-prepare-w4-c10.py +systemd-run --user --scope --unit=h2o-full-w4c10-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/run-full.sh diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_dexycb_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_dexycb_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e8bb71e9ad9c5a44f85e5c50cee467a00512aa1d --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_dexycb_validation.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Audit a finished Dex-YCB release and render persisted modalities for manual review.""" +from collections import Counter +import hashlib +import json +from pathlib import Path +import sys + +from render_hoi4d_validation import render + + +def inspect(root): + data, doc, scripts = root / 'data', root / 'doc', root / 'script' + sequences = sorted(p for p in data.iterdir() if p.is_dir()) + assert len(sequences) == 1000, f'expected 1000 sequences, got {len(sequences)}' + assert len(list(doc.glob('*.build.json'))) == 1000 + assert not list(data.glob('*.tmp-*')), 'unfinished temporary sequences' + config = json.loads((scripts / 'config.json').read_text()) + assert all(config.get(k) is None for k in ('limit', 'max_frames', 'subjects', 'views')) + hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in scripts.glob('*.py')} + subjects, splits, availability = Counter(), Counter(), Counter() + selected = [] + for seq in sequences: + views = sorted(p for p in seq.iterdir() if p.is_dir()) + assert len(views) == 8, (seq, len(views)) + build = json.loads((doc / (seq.name + '.build.json')).read_text()) + assert set(build['views']) == {p.name for p in views}, seq + assert all(hashes.get(k) == v for k, v in build['scripts'].items()), seq + subject = seq.name.split('_')[0] + subjects[subject] += 1 + if subjects[subject] == 1: + selected.append(views[0]) + if subject.endswith('subject-09'): + selected.append(views[-1]) # one more camera, different camera + if seq.name == '20201015-subject-09_20201015_150838': + selected.append(views[0]) # source-labelled left-hand sequence + for view in views: + meta = json.loads((view / 'metainfo.json').read_text()) + assert meta['sequence_id'] == seq.name and meta['camera_id'] == view.name, view + assert meta['dataset_id'] == 'dex-ycb' and meta['release_id'] == 'shared-v1.0', view + assert meta['num_frames'] > 0 and meta.get('view_type') == 'exo', view + assert (view / 'camera/frames.jsonl').is_file(), view + assert meta['components']['rgb']['available'], view + splits[meta['split']] += 1 + for key, part in meta['components'].items(): + if part.get('available'): + availability[key] += 1 + for ref in ('data_ref', 'valid_ref'): + if part.get(ref): + assert (view / part[ref]).is_file(), (view, key, ref) + assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects + assert availability['depth'] == availability['rgb'] == 8000, availability + report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects), + splits=dict(splits), available_views=dict(availability), config=config, + published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected], + scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.') + destination = doc / 'validation' + destination.mkdir(exist_ok=True) + (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + for view in selected: + render(view, destination) + return report + + +if __name__ == '__main__': + print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_h2o_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_h2o_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b89e7c0827f45ec7f854ff8651234cb9a4223f79 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_h2o_validation.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from render_hoi4d_validation import mesh_preview, picture, snapshot +from warehouse_v1_0 import unpack_depth, validate_view + + +def load(view, item, n): + if not item.get('available') or not item.get('data_ref', '').endswith('.pt'): + return None, None + values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy() + valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None + return (values, valid) if values.ndim and values.shape[0] == n else (None, None) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values, valid = load(view, item, n) + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
    ' + picture(photo) + '
    RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z,黑=无效,白≥3 m;不改源深度
    ') + details = {'frame': frames[i]} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + '
    原帧号、全部数值标注及有效性
    ' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / item['data_ref']) + '
    源 OBJ 静态预览,不代表物体姿态投影
    ') + report = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览只作人工核查;仅显示真实存在的标注,不合成分割。

    ' + ''.join(pages) + '

    源网格

    ' + ''.join(assets) + '
    全部组件元数据
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC
    ' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('

    H2O 试点预览

    ') + return destination / (title + '.html') + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args() + for view in args.views: + print(render(view, args.out), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_source_review.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_source_review.py new file mode 100644 index 0000000000000000000000000000000000000000..79d7a58744572343670e9cbaecc4cc54ea07f1c1 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_source_review.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks.""" +import argparse +import html +import json +from pathlib import Path +import shutil +import zipfile + +import numpy as np +from PIL import Image, ImageDraw + +from render_hoi4d_validation import picture, snapshot + + +def source_parts(view): + rows = [] + for source in view.glob('annotation/object/*/assets/result.json'): + def visit(node): + if isinstance(node, list): + for child in node: + visit(child) + return + if node.get('objs'): + rows.append({'source_part_id': node['id'], 'source_part_name': node['name'], + 'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))}) + for child in node.get('children', []): + visit(child) + visit(json.loads(source.read_text())) + return rows + + +def render(view, z, output): + output.mkdir(parents=True, exist_ok=True) + meta = json.loads((view / 'metainfo.json').read_text()) + seq = meta['sampling']['selection']['source_sequence'] + w, h = meta['camera']['image_size'] + chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1}) + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen) + segment = meta['components'].get('segment', {}) + masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '

    ' + html.escape(seq) + f' / frame {native_id}

    ' + picture(image) + + '

    仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。

    ' + + '
    上游原记录与编码对照
    '
    +                      + html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '
    ') + parts = source_parts(view) + name = view.parent.name + '_' + view.name + '.html' + page = 'HOI4D source correspondence review

    源姿态/原生分割/RGB 的证据图(非真值修改)

    ' + page += ''.join(panels) + '
    CAD result.json 原生部件→OBJ;不等同逐帧姿态对应
    '
    +    page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '
    ' + (output / name).write_text(page) + print(name, 'native_part_links',len(parts),flush=True) + return name + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--raw-root', type=Path, required=True) + p.add_argument('--release', type=Path, required=True) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args(argv) + args.out.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z: + names = [] + for view in sorted((args.release / 'data').glob('*/ego')): + if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence'] + for category in ('2', '3', '14', '17')): + names.append(render(view, z, args.out)) + links = ''.join(f'
  • {html.escape(name)}
  • ' for name in names) + (args.out / 'index.html').write_text('

    源依据对照(非物体几何验收通过)

      ' + links + '
    ') + shutil.copyfile(Path(__file__), args.out / 'renderer.py') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7889a1b63b004e046b52fe4e4da0b2b4651b768 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_validation.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Standalone, offline HTML review of every persisted component in selected views.""" +import argparse +import base64 +import html +import io +import json +import random +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from warehouse_v1_0 import video_frames, unpack_depth, validate_view + + +def snapshot(video, fmt, shape, dtype, indices): + return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices} + + +def picture(image): + image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized. + output = io.BytesIO() + image.save(output, format='PNG') + return '' + + +def preview_color(value, dataset_id): + # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette + # gave it the same color as YCB object 15; keep data codes untouched. + if dataset_id == 'dex-ycb' and value == 255: + return (255, 32, 64) + return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131)) + + +def mesh_preview(path): + """Project the whole source asset; bound drawing cost without favoring early faces.""" + vertices, faces, referenced = [], [], set() + rng = random.Random(0) + face_count = 0 + with path.open(errors='replace') as stream: + for line in stream: + if line.startswith('v '): + vertices.append([float(v) for v in line.split()[1:4]]) + elif line.startswith('f '): + face = [] + for token in line.split()[1:]: + index = int(token.split('/')[0]) + face.append(index - 1 if index > 0 else len(vertices) + index) + if len(face) < 3: + continue + referenced.update(face) + face_count += 1 + # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail. + if len(faces) < 5000: + faces.append(face) + else: + pick = rng.randrange(face_count) + if pick < len(faces): + faces[pick] = face + if not vertices or not faces: + return 'OBJ 未提供可绘制的顶点/面' + if min(referenced) < 0 or max(referenced) >= len(vertices): + raise ValueError(f'invalid OBJ face index: {path}') + xyz = np.asarray(vertices, dtype=np.float64) + if not np.isfinite(xyz).all(): + raise ValueError(f'nonfinite OBJ vertex: {path}') + # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose. + projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2), + (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6))) + used = projected[np.fromiter(referenced, dtype=np.int64)] + lo, hi = used.min(axis=0), used.max(axis=0) + extent = (hi - lo).max() + if extent <= 0: + return 'OBJ 所有面投影到同一点' + projected = (projected - (lo + hi) / 2) * (380 / extent) + 215 + image = Image.new('RGB', (430, 430), 'white') + draw = ImageDraw.Draw(image) + for face in faces: + polygon = [tuple(projected[i]) for i in face] + draw.line(polygon + [polygon[0]], fill='#205caa', width=1) + return picture(image) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + n = meta['num_frames'] + width, height = meta['camera']['image_size'] + components = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + for item in components.values(): + ref = item.get('valid_ref', '') + if ref.endswith('.pt'): + valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy() + if valid.shape[0] == n: + matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(matching): + selected.add(int(matching[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '' + picture(image) + '
    RGB + 原生 2D 手关键点(若有)
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z(黑=无效,白≥3 m;仅预览)
    ') + if i in masks: + mask = masks[i] + colors = np.zeros((*mask.shape, 3), dtype=np.uint8) + for value in np.unique(mask): + if value not in (0, 65535): + colors[mask == value] = preview_color(int(value), meta['dataset_id']) + legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535)) + panels.append('
    ' + picture(Image.fromarray(colors)) + '
    原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')
    ') + active = (mask != 0) & (mask != 65535) + overlay = rgb[i].copy() + overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(overlay)) + '
    原生分割叠加 RGB(仅预览)
    ') + details = {'frame': frames[i], 'segment_labels': labels.get(i, [])} + for name, component in components.items(): + ref = component.get('data_ref', '') + if component.get('available') and ref.endswith('.pt'): + values = torch.load(view / ref, map_location='cpu', weights_only=True) + if values.ndim and values.shape[0] == n: + details[name] = {'value': values[i].tolist()} + if component.get('valid_ref', '').endswith('.pt'): + valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True) + details[name]['valid'] = valid[i].tolist() + sections.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + + '
    帧号、来源、全部数值组件与有效性
    '
    +                        + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, component in components.items(): + if component.get('available') and component['data_ref'].lower().endswith('.obj'): + ref = component['data_ref'] + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / ref) + + '
    仅展示网格原生形状;未验证尺度/位姿对应。
    ') + result = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。

    ' + ''.join(sections) + '

    原始物体模型(独立预览)

    ' + ''.join(assets) + '
    全部组件元信息及原始来源
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC 结果
    ' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2)) + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('' + html.escape(meta['dataset_id']) + ' review

    ' + html.escape(meta['dataset_id']) + ' 抽样人工审核

    选择视图;所有预览均来自已保存的 shared 数据。

    ') + print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + for view in args.views: + render(view, args.out or view.parents[2] / 'doc/validation') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/run-full.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b9267d75a5fb7c4d1729397219e7f8ca2a688c4 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/run-full.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/full.status" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then + read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +else + quota=max + period=controller_disabled +fi +printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" != max ]]; then + printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi +exit "$code" diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/warehouse_v1_0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/warehouse_v1_0.py new file mode 100644 index 0000000000000000000000000000000000000000..f705011bcea587bd320e1e228f99bed259b32b3a --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/warehouse_v1_0.py @@ -0,0 +1,931 @@ +"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis.""" +import argparse +from contextlib import contextmanager +from functools import lru_cache +import hashlib +import json +import math +import shlex +from pathlib import Path +import pickle +import random +import shutil +import subprocess +import tempfile +import time + +import numpy as np +from PIL import Image +import torch + +SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json', + Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file()) +SCHEMA = json.loads(SCHEMA_PATH.read_text()) +RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw' + + +def json_write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + + +def jsonl_write(path, rows): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w') as out: + for row in rows: + out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n') + + +def sha256(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() + + +def locator(path, member=None, data=None, **extra): + result = {'file': str(Path(path).resolve())} + if member is not None: + result['member'] = member + if data is not None: + result['sha256'] = hashlib.sha256(data).hexdigest() + return result | extra + + +def source(method='Copy source annotation; normalize storage only'): + return {'kind': 'format_conversion', 'method': method} + + +def run(args, **kwargs): + return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs) + + +@lru_cache(maxsize=1) +def ffversion(): + return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0] + + +def probe(path): + return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_streams', '-of', 'json', str(path)], + stdout=subprocess.PIPE).stdout)['streams'][0] + + +def decode_args(path, pixel_format): + return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', pixel_format] + + +def decoded_digest(path, pixel_format): + start = time.monotonic() + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], + stdout=subprocess.PIPE, stderr=err) + digest, size = hashlib.sha256(), 0 + with proc.stdout: + while chunk := proc.stdout.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + if proc.wait(): + err.seek(0) + raise RuntimeError(err.read().decode(errors='replace')) + return digest.hexdigest(), size, time.monotonic() - start + + +def video_frames(path, pixel_format, shape, dtype): + frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err) + completed = False + try: + while True: + data = proc.stdout.read(frame_bytes) + if not data: + break + if len(data) != frame_bytes: + raise ValueError('truncated decoded video frame') + yield np.frombuffer(data, dtype=dtype).reshape(shape) + if proc.wait(): + err.seek(0) + raise ValueError(err.read().decode(errors='replace')) + completed = True + finally: + proc.stdout.close() + if not completed and proc.poll() is None: + proc.terminate() + proc.wait() + + +def storage(path, profile, parameters, source_lossy): + info = probe(path) + if info['codec_name'] == 'h264': + frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0', + '-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames'] + parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]} + return {'profile': profile, 'codec': info['codec_name'], + 'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']], + 'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False, + 'color_space': info.get('color_space', 'unknown'), + 'color_range': info.get('color_range', 'unknown'), + 'color_primaries': info.get('color_primaries', 'unknown'), + 'color_transfer': info.get('color_transfer', 'unknown')}, + 'encoder_parameters': {'version': ffversion()} | parameters, + 'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'} + + +def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1): + start = time.monotonic() + run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-y', '-f', 'rawvideo', + '-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30', + '-i', str(raw), '-an', '-c:v', codec, '-threads', str(threads), *extra, str(target)]) + digest, size, decode_seconds = decoded_digest(target, pixel_format) + if size != Path(raw).stat().st_size or digest != sha256(raw): + raise ValueError(f'lossless roundtrip failed: {target}') + config = storage(target, profile, {'name': codec, 'arguments': list(extra), 'threads': threads}, False) + return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds, + 'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True} + + +def measure_rgb_access(video, raw, width, height, count): + index = count // 2 + start = time.monotonic() + data = run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(video), '-vf', f'select=eq(n\\,{index})', '-frames:v', '1', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], stdout=subprocess.PIPE).stdout + with raw.open('rb') as inp: + inp.seek(index * width * height * 3) + if data != inp.read(width * height * 3): + raise ValueError('exact indexed RGB read failed') + return {'random_access_strategy': 'decode from first keyframe; select exact presentation index', + 'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start} + + +def jpeg_sample_indices(sequence, camera, count): + seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big') + indices = {0, count - 1, count // 4, count // 2, 3 * count // 4} + indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices], + min(count, 16) - len(indices))) + return sorted(indices), seed + + +def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full): + packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)], + stdout=subprocess.PIPE).stdout)['packets'] + if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes: + raise ValueError('JPEG packet hashes/order/count differ') + info = probe(target) + if [info['width'], info['height']] != list(size): + raise ValueError('JPEG container dimensions differ') + indices, seed = jpeg_sample_indices(sequence, camera, len(paths)) + if full: + indices = list(range(len(paths))) + select = '+'.join(f'eq(n\\,{i})' for i in indices) + frame_bytes = size[0] * size[1] * 3 + # Spool selected frames to disk, keeping RAM bounded for full-view audits. + with tempfile.TemporaryFile() as decoded: + run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded) + decoded.seek(0) + for i in indices: + expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout + if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected: + raise ValueError(f'JPEG decoded pixels differ at frame {i}') + if decoded.read(1): + raise ValueError('JPEG selected pixel count differs') + return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed, + 'selected_frame_indices': indices, 'pixel_frames_checked': len(indices), + 'packet_frames_checked': len(paths), 'jpeg_packets_exact': True, + 'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True, + 'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full} + + +def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False, + ffv1_first=False, codec_threads=1): + """JPEG packet proof plus deterministic pixels; re-encodings compare all pixels.""" + target.parent.mkdir(parents=True, exist_ok=True) + raw = work / 'rgb.raw' + packets = [] + has_missing = video is None and any(p is None for p in paths) + if has_missing: + present = next((p for p in paths if p is not None), None) + if present is None: + raise ValueError('no source RGB image to establish the pixel format/grid') + original = probe(present) + width, height = original['width'], original['height'] + with raw.open('wb') as dest: + for path in paths: + if path is None: + dest.write(bytes(width * height * 3)) + else: + with Image.open(path) as im: + if im.mode != 'RGB' or im.size != (width, height): + raise ValueError('source RGB grid/type changes within view') + run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest) + lossy, count = 'unknown', len(paths) + input_args = None + elif video is None: + if not paths: + raise ValueError('RGB timeline must contain existing source images') + suffix = paths[0].suffix.lower() + if suffix not in ('.jpg', '.jpeg', '.png'): + raise ValueError('unsupported source RGB format') + images = work / 'rgb_source' + images.mkdir() + dimensions = None + for i, path in enumerate(paths): + with Image.open(path) as im: + if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size): + raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion') + dimensions = im.size + if im.format == 'PNG' and path.read_bytes()[24] != 8: + raise ValueError('high bit depth RGB needs a registered schema') + dest = images / f'{i:08d}{suffix}' + shutil.copyfile(path, dest) + packets.append(sha256(path)) + width, height = dimensions + input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))] + count = len(paths) + original = probe(paths[0]) + lossy = suffix in ('.jpg', '.jpeg') + else: + original = probe(video) + if int(original.get('bits_per_raw_sample') or 8) > 8 or any( + x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')): + raise ValueError('high bit depth RGB needs a registered schema') + width, height = original['width'], original['height'] + input_args = ['-i', str(video)] + lossy = 'unknown' + limits = ['-frames:v', str(count)] if count else [] + records = [] + if video is None and not has_missing and suffix in ('.jpg', '.jpeg'): + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + encode_seconds = time.monotonic() - start + validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg) + cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy) + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size, + 'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds}) + return cfg, [width, height], records, count + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + if not has_missing: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', '1', '-noautorotate', + *input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)]) + frame_bytes = width * height * 3 + actual, remainder = divmod(raw.stat().st_size, frame_bytes) + if remainder or not actual or (count is not None and actual != count): + raise ValueError('source RGB frame count mismatch') + expected_hash = sha256(raw) + can_copy = video is not None + if can_copy: + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + digest, size, seconds = decoded_digest(target, 'rgb24') + if digest != expected_hash or size != raw.stat().st_size: + raise ValueError('stream-copy RGB bytes/order/count mismatch') + cfg = storage(target, 'mkv/source_copy/v1', + {'stream_copy': True}, lossy) + if video: + cfg['storage_fps'] = original.get('avg_frame_rate') + cfg['preserve_source_pts'] = True + records.append({'profile': cfg['profile'], 'all_frames_exact': True, + 'decoded_sha256': digest, + 'bytes': target.stat().st_size, 'decode_seconds': seconds, + 'encode_seconds': time.monotonic() - start - seconds}) + records[-1].update(measure_rgb_access(target, raw, width, height, actual)) + return cfg, [width, height], records, actual + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'stream_copy', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + candidates = [] + for profile, codec, params in [ + ('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']), + ('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]: + path = work / (codec + '.mkv') + try: + cfg, record = encode_raw(raw, path, width, height, 'rgb24', profile, codec, params, + codec_threads if codec == 'ffv1' else 1) + cfg['source_lossy'] = lossy + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + record['profile'] = profile + record.update(measure_rgb_access(path, raw, width, height, actual)) + records.append(record) + candidates.append((path.stat().st_size, path, cfg)) + if ffv1_first and codec == 'ffv1': + break # Keep the H.264 fallback only if the preferred exact encoder fails. + except subprocess.CalledProcessError as exc: + records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')}) + if not candidates: + raise ValueError('no supported lossless RGB encoder') + _, chosen, cfg = min(candidates, key=lambda x: x[0]) + shutil.move(chosen, target) + return cfg, [width, height], records, actual + + +def pack_depth(depth): + bits = np.ascontiguousarray(depth, dtype='> 16).astype(' 0) + arr[~good] = np.nan + out.write(pack_depth(arr).tobytes()) + vo.write(good.astype(np.uint8).tobytes()) + else: + if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535: + raise ValueError('invalid segmentation region codes') + out.write(arr.astype(' vertices: + raise ValueError('empty or invalid mesh') + def dependency(parent, name): + dep = (parent / name).resolve() + if not dep.is_relative_to(asset_root) or not dep.is_file(): + raise ValueError(f'missing or escaping asset dependency: {name}') + return dep + dependencies = [] + for name in materials: + mtl = dependency(path.parent, name) + dependencies.append(mtl) + for line in mtl.read_text().splitlines(): + fields = shlex.split(line, comments=True) + if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')): + dependencies.append(dependency(mtl.parent, fields[-1])) + return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path), + 'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}} + + +def mesh_asset(view, oid, directory, obj, loc): + dest = view.path / f'annotation/object/{oid}/assets' + shutil.copytree(directory, dest) + ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix() + mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest) + view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check}) + view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m') + p = view.path / f'annotation/object/{oid}/metainfo.json' + info = json.loads(p.read_text()) + info.update(has_model=True, mesh_ref=ref) + json_write(p, info) + + +def safe_member(root, name): + path = (Path(root) / name).resolve() + if not path.is_relative_to(Path(root).resolve()): + raise ValueError(f'unsafe archive path: {name}') + return path + + +class ChumpyStub: + def __setstate__(self, state): + self.__dict__.update(state) + + +class ManoUnpickler(pickle.Unpickler): + def find_class(self, module, name): + if module.startswith('chumpy'): + return ChumpyStub + return super().find_class(module, name) + + +def mano_models(directory): + result = {} + if directory is None: + return result + for side in ('left', 'right'): + path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl' + if not path.exists(): + continue + with path.open('rb') as f: + data = ManoUnpickler(f, encoding='latin1').load() + result[side] = {'components': np.asarray(data['hands_components']), + 'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path), + 'file': path.name} + return result + + +def model_profile(models): + identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode() + return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True, + 'left_shapedirs_correction': 'not_applied', + 'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}} + + +def pca_to_axis_angle(coeffs, model): + coeffs = np.asarray(coeffs) + if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all(): + raise ValueError('invalid MANO PCA coefficients') + return coeffs @ model['components'] + model['mean'] + + +def parser(dataset, description): + p = argparse.ArgumentParser(description=description) + p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset) + p.add_argument('--out', type=Path, default=Path('converted')) + p.add_argument('--release-id', default='v1.0') + p.add_argument('--limit', type=int, help='Maximum sequences to convert') + p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)') + p.add_argument('--mano-dir', type=Path) + p.add_argument('--views', help='Comma-separated source camera IDs') + p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views') + return p + + +def roots(root): + root = Path(root).expanduser() + return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()] + + +def find_file(root, name): + return next((p / name for p in roots(root) if (p / name).exists()), None) + + +def release(args, dataset): + if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'): + raise ValueError('release-id must be a single directory name') + if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1: + raise ValueError('limits must be positive') + out = args.out.expanduser().resolve() / dataset / args.release_id + raw = args.root.expanduser().resolve() + if out == raw or out.is_relative_to(raw): + raise ValueError('output must not modify the raw source tree') + (out / 'data').mkdir(parents=True, exist_ok=True) + (out / 'doc').mkdir(exist_ok=True) + (out / 'script').mkdir(exist_ok=True) + scripts = list(Path(__file__).resolve().parent.glob('*.py')) + existing = {p.name for p in (out / 'script').glob('*.py')} + if existing and existing != {p.name for p in scripts}: + raise ValueError('converter files changed; choose a new --release-id') + copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')] + copies += [(path, out / 'script' / path.name) for path in scripts] + # Check every existing file before changing any published definition or script. + for src, dest in copies: + if dest.exists() and sha256(dest) != sha256(src): + raise ValueError('converter or contract changed within an existing release; choose a new --release-id') + for src, dest in copies: + if src.resolve() != dest.resolve(): + shutil.copyfile(src, dest) + json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}) + return out + + +@contextmanager +def sequence_dir(out, sequence): + if Path(sequence).name != sequence: + raise ValueError('sequence ID must be a single path component') + final = out / 'data' / sequence + with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd: + tmp = Path(wd) + yield tmp + if final.exists(): + if any((final / child.name).exists() for child in tmp.iterdir()): + raise FileExistsError('view already published; use a new release-id to preserve it') + for child in list(tmp.iterdir()): + child.rename(final / child.name) + else: + tmp.rename(final) + + +def build_record(out, sequence, reports): + path = out / 'doc' / (sequence + '.build.json') + previous = json.loads(path.read_text()) if path.exists() else {} + config = json.loads((out / 'script/config.json').read_text()) + for report in reports.values(): + report['configuration'] = config + json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'], + 'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')}, + 'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()}, + 'views': previous.get('views', {}) | reports}) + + +def check_view_type(meta): + # The pinned ARCTIC contract makes view_type optional; adapters still supply known views. + if 'view_type' not in meta: + return + if meta['view_type'] not in ('ego', 'exo', 'unknown'): + raise ValueError('view_type must be ego/exo/unknown') + expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id']) + if meta['dataset_id'] == 'H2O': + expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + if expected and meta['view_type'] not in (expected, 'unknown'): + raise ValueError('view_type contradicts known source capture setup') + + +def check_valid_policy(component, count): + policy = component.get('valid_policy', {}) + for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks', + 'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'): + if field not in policy: + raise ValueError(f'valid_policy missing {field}') + if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']: + raise ValueError('outdated annotation validity semantics') + if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']: + raise ValueError('incomplete validity rule/scope') + if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'): + raise ValueError('official QA requires a verified adapter; supervision acceptance paused') + excluded = policy['local_excluded_frame_indices'] + if any(type(i) is not int or not 0 <= i < count for i in excluded): + raise ValueError('invalid local exclusion frame index') + if excluded: + raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters') + if policy['visibility_independent'] is not True: + raise ValueError('visibility must remain independent of validity') + + +def validate_view(path): + """Validate the persisted contract, not a rendering of the source labels.""" + path = Path(path) + meta = json.loads((path / 'metainfo.json').read_text()) + n = meta['num_frames'] + check_view_type(meta) + if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1: + raise ValueError('invalid view header') + def resolve(ref): + if Path(ref).is_absolute() or '\\' in ref: + raise ValueError('component reference must be relative POSIX') + dest = safe_member(path, ref) + if not dest.is_file(): + raise ValueError(f'referenced file missing: {ref}') + return dest + def tensor(ref): + def cpu_storage(storage, location): + if location != 'cpu': + raise ValueError('PT storage must be on CPU') + return storage + value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True) + if not isinstance(value, torch.Tensor) or value.device.type != 'cpu': + raise ValueError('PT must contain only a CPU Tensor') + return value.numpy() + frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()] + if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)): + raise ValueError('frame index/count mismatch') + for f in frames: + if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')): + raise ValueError('incomplete frame provenance') + entities = {'hand_left', 'hand_right'} + parts = {} + for p in (path / 'annotation/object').glob('*/metainfo.json'): + obj = json.loads(p.read_text()) + if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'): + raise ValueError('invalid object identity') + entities.add(obj['object_id']) + if obj.get('mesh_ref'): + if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()): + raise ValueError('mesh must belong to its object') + if obj.get('articulation_ref'): + art = json.loads(resolve(obj['articulation_ref']).read_text()) + part_ids = {part['part_id'] for part in art['parts']} + if len(part_ids) != len(art['parts']): + raise ValueError('duplicate part ID') + parents = {part['part_id']: part['parent_id'] for part in art['parts']} + for part_id in parents: + visited, cur = set(), part_id + while cur is not None: + if cur in visited or cur not in parents: + raise ValueError('invalid or cyclic part hierarchy') + visited.add(cur) + cur = parents[cur] + parts[obj['object_id']] = part_ids + video_stats = {} + for key, component in meta['components'].items(): + if not component.get('available'): + if not component.get('reason'): + raise ValueError('unavailable component needs a reason') + continue + schema = SCHEMA['components'][component['schema_id']] + for required in ('axes', 'provenance', 'source_locator'): + if required not in component: + raise ValueError(f'{key}: {required} missing') + for required in schema.get('required_metadata', []): + if required not in component: + raise ValueError(f'{key}: {required} missing') + if component['provenance']['kind'] == 'derived': + raise ValueError('v1.0 must not synthesize annotations') + if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'): + if not component.get('valid_ref') or not component.get('valid_axes'): + raise ValueError(f'{key}: annotation validity reference/axes missing') + check_valid_policy(component, n) + data_path = resolve(component['data_ref']) + valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None + valid_shape = schema.get('valid_shape') + if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any( + isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))): + raise ValueError(f'{key}: validity schema shape mismatch') + if valid is not None and (valid.dtype != bool or valid.shape[0] != n): + raise ValueError(f'{key}: invalid validity tensor') + if component['schema_id'] == 'mesh/obj/v1': + objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None) + if objroot is None: + raise ValueError('mesh must be owned by an object') + check_mesh(data_path, objroot) + if data_path.suffix == '.pt': + arr = tensor(component['data_ref']) + if arr.dtype != np.float32 or arr.shape[0] != n: + raise ValueError(f'{key}: float dtype or timeline mismatch') + shape = schema.get('shape') + if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))): + raise ValueError(f'{key}: schema shape mismatch') + if valid is not None: + if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all(): + raise ValueError(f'{key}: invalid finite/NaN/validity values') + if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'): + check_transform(arr[valid]) + if data_path.suffix == '.mkv': + cfg = component['storage'] + if cfg['profile'] not in SCHEMA['storage_profiles']: + raise ValueError('unregistered video profile') + for field in SCHEMA['video_metadata']['required']: + if field not in cfg: + raise ValueError('video storage declaration incomplete') + w, h = meta['camera']['image_size'] + if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]: + raise ValueError('encoded raster differs from logical RGB grid') + actual = probe(data_path) + if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or + [actual['width'], actual['height']] != cfg['encoded_size']): + raise ValueError('video storage metadata differs from file') + if key == 'rgb': + fmt, bpp = 'rgb24', 3 + else: + fmt, bpp = 'gray16le', 2 + digest, size, _ = decoded_digest(data_path, fmt) + w, h = cfg['encoded_size'] + if size != n * w * h * bpp: + raise ValueError('raster timeline mismatch') + video_stats[key] = {'decoded_sha256': digest, 'frames': n} + if key == 'depth': + validity = component['valid_storage'] + vp = resolve(component['valid_ref']) + actual_valid = probe(vp) + if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1' + or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]): + raise ValueError('invalid depth validity video') + count = 0 + for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), ' 0)).all() or not np.isnan(depth[~good]).all(): + raise ValueError('invalid depth/validity semantics') + count += 1 + if count != n: + raise ValueError('depth validity timeline mismatch') + if component['schema_id'].startswith('segment/') and component.get('mapping_ref'): + rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()] + if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)): + raise ValueError('segmentation mapping timeline mismatch') + for row in rows: + labels = row['labels'] + if len({a['mask_value'] for a in labels}) != len(labels): + raise ValueError('duplicate region mapping') + for label in labels: + if label['entity_id'] is not None and label['entity_id'] not in entities: + raise ValueError('unresolved segmentation entity') + if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()): + raise ValueError('unresolved segmentation part') + if component['schema_id'] == 'segment/uint16_labels/v1': + width, height = meta['camera']['image_size'] + for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), ' 0 and meta.get('view_type') == 'exo', view + assert (view / 'camera/frames.jsonl').is_file(), view + assert meta['components']['rgb']['available'], view + splits[meta['split']] += 1 + for key, part in meta['components'].items(): + if part.get('available'): + availability[key] += 1 + for ref in ('data_ref', 'valid_ref'): + if part.get(ref): + assert (view / part[ref]).is_file(), (view, key, ref) + assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects + assert availability['depth'] == availability['rgb'] == 8000, availability + report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects), + splits=dict(splits), available_views=dict(availability), config=config, + published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected], + scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.') + destination = doc / 'validation' + destination.mkdir(exist_ok=True) + (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + for view in selected: + render(view, destination) + return report + + +if __name__ == '__main__': + print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/render_h2o_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/render_h2o_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b89e7c0827f45ec7f854ff8651234cb9a4223f79 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/render_h2o_validation.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from render_hoi4d_validation import mesh_preview, picture, snapshot +from warehouse_v1_0 import unpack_depth, validate_view + + +def load(view, item, n): + if not item.get('available') or not item.get('data_ref', '').endswith('.pt'): + return None, None + values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy() + valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None + return (values, valid) if values.ndim and values.shape[0] == n else (None, None) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values, valid = load(view, item, n) + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
    ' + picture(photo) + '
    RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z,黑=无效,白≥3 m;不改源深度
    ') + details = {'frame': frames[i]} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + '
    原帧号、全部数值标注及有效性
    ' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / item['data_ref']) + '
    源 OBJ 静态预览,不代表物体姿态投影
    ') + report = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览只作人工核查;仅显示真实存在的标注,不合成分割。

    ' + ''.join(pages) + '

    源网格

    ' + ''.join(assets) + '
    全部组件元数据
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC
    ' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('

    H2O 试点预览

    ') + return destination / (title + '.html') + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args() + for view in args.views: + print(render(view, args.out), flush=True) diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/render_hoi4d_source_review.py b/H2O/shared-v1.0/script/provenance/previous-run/script/render_hoi4d_source_review.py new file mode 100644 index 0000000000000000000000000000000000000000..79d7a58744572343670e9cbaecc4cc54ea07f1c1 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/render_hoi4d_source_review.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks.""" +import argparse +import html +import json +from pathlib import Path +import shutil +import zipfile + +import numpy as np +from PIL import Image, ImageDraw + +from render_hoi4d_validation import picture, snapshot + + +def source_parts(view): + rows = [] + for source in view.glob('annotation/object/*/assets/result.json'): + def visit(node): + if isinstance(node, list): + for child in node: + visit(child) + return + if node.get('objs'): + rows.append({'source_part_id': node['id'], 'source_part_name': node['name'], + 'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))}) + for child in node.get('children', []): + visit(child) + visit(json.loads(source.read_text())) + return rows + + +def render(view, z, output): + output.mkdir(parents=True, exist_ok=True) + meta = json.loads((view / 'metainfo.json').read_text()) + seq = meta['sampling']['selection']['source_sequence'] + w, h = meta['camera']['image_size'] + chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1}) + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen) + segment = meta['components'].get('segment', {}) + masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '

    ' + html.escape(seq) + f' / frame {native_id}

    ' + picture(image) + + '

    仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。

    ' + + '
    上游原记录与编码对照
    '
    +                      + html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '
    ') + parts = source_parts(view) + name = view.parent.name + '_' + view.name + '.html' + page = 'HOI4D source correspondence review

    源姿态/原生分割/RGB 的证据图(非真值修改)

    ' + page += ''.join(panels) + '
    CAD result.json 原生部件→OBJ;不等同逐帧姿态对应
    '
    +    page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '
    ' + (output / name).write_text(page) + print(name, 'native_part_links',len(parts),flush=True) + return name + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--raw-root', type=Path, required=True) + p.add_argument('--release', type=Path, required=True) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args(argv) + args.out.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z: + names = [] + for view in sorted((args.release / 'data').glob('*/ego')): + if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence'] + for category in ('2', '3', '14', '17')): + names.append(render(view, z, args.out)) + links = ''.join(f'
  • {html.escape(name)}
  • ' for name in names) + (args.out / 'index.html').write_text('

    源依据对照(非物体几何验收通过)

      ' + links + '
    ') + shutil.copyfile(Path(__file__), args.out / 'renderer.py') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/render_hoi4d_validation.py b/H2O/shared-v1.0/script/provenance/previous-run/script/render_hoi4d_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7889a1b63b004e046b52fe4e4da0b2b4651b768 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/render_hoi4d_validation.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Standalone, offline HTML review of every persisted component in selected views.""" +import argparse +import base64 +import html +import io +import json +import random +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from warehouse_v1_0 import video_frames, unpack_depth, validate_view + + +def snapshot(video, fmt, shape, dtype, indices): + return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices} + + +def picture(image): + image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized. + output = io.BytesIO() + image.save(output, format='PNG') + return '' + + +def preview_color(value, dataset_id): + # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette + # gave it the same color as YCB object 15; keep data codes untouched. + if dataset_id == 'dex-ycb' and value == 255: + return (255, 32, 64) + return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131)) + + +def mesh_preview(path): + """Project the whole source asset; bound drawing cost without favoring early faces.""" + vertices, faces, referenced = [], [], set() + rng = random.Random(0) + face_count = 0 + with path.open(errors='replace') as stream: + for line in stream: + if line.startswith('v '): + vertices.append([float(v) for v in line.split()[1:4]]) + elif line.startswith('f '): + face = [] + for token in line.split()[1:]: + index = int(token.split('/')[0]) + face.append(index - 1 if index > 0 else len(vertices) + index) + if len(face) < 3: + continue + referenced.update(face) + face_count += 1 + # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail. + if len(faces) < 5000: + faces.append(face) + else: + pick = rng.randrange(face_count) + if pick < len(faces): + faces[pick] = face + if not vertices or not faces: + return 'OBJ 未提供可绘制的顶点/面' + if min(referenced) < 0 or max(referenced) >= len(vertices): + raise ValueError(f'invalid OBJ face index: {path}') + xyz = np.asarray(vertices, dtype=np.float64) + if not np.isfinite(xyz).all(): + raise ValueError(f'nonfinite OBJ vertex: {path}') + # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose. + projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2), + (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6))) + used = projected[np.fromiter(referenced, dtype=np.int64)] + lo, hi = used.min(axis=0), used.max(axis=0) + extent = (hi - lo).max() + if extent <= 0: + return 'OBJ 所有面投影到同一点' + projected = (projected - (lo + hi) / 2) * (380 / extent) + 215 + image = Image.new('RGB', (430, 430), 'white') + draw = ImageDraw.Draw(image) + for face in faces: + polygon = [tuple(projected[i]) for i in face] + draw.line(polygon + [polygon[0]], fill='#205caa', width=1) + return picture(image) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + n = meta['num_frames'] + width, height = meta['camera']['image_size'] + components = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + for item in components.values(): + ref = item.get('valid_ref', '') + if ref.endswith('.pt'): + valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy() + if valid.shape[0] == n: + matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(matching): + selected.add(int(matching[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '' + picture(image) + '
    RGB + 原生 2D 手关键点(若有)
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z(黑=无效,白≥3 m;仅预览)
    ') + if i in masks: + mask = masks[i] + colors = np.zeros((*mask.shape, 3), dtype=np.uint8) + for value in np.unique(mask): + if value not in (0, 65535): + colors[mask == value] = preview_color(int(value), meta['dataset_id']) + legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535)) + panels.append('
    ' + picture(Image.fromarray(colors)) + '
    原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')
    ') + active = (mask != 0) & (mask != 65535) + overlay = rgb[i].copy() + overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(overlay)) + '
    原生分割叠加 RGB(仅预览)
    ') + details = {'frame': frames[i], 'segment_labels': labels.get(i, [])} + for name, component in components.items(): + ref = component.get('data_ref', '') + if component.get('available') and ref.endswith('.pt'): + values = torch.load(view / ref, map_location='cpu', weights_only=True) + if values.ndim and values.shape[0] == n: + details[name] = {'value': values[i].tolist()} + if component.get('valid_ref', '').endswith('.pt'): + valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True) + details[name]['valid'] = valid[i].tolist() + sections.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + + '
    帧号、来源、全部数值组件与有效性
    '
    +                        + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, component in components.items(): + if component.get('available') and component['data_ref'].lower().endswith('.obj'): + ref = component['data_ref'] + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / ref) + + '
    仅展示网格原生形状;未验证尺度/位姿对应。
    ') + result = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。

    ' + ''.join(sections) + '

    原始物体模型(独立预览)

    ' + ''.join(assets) + '
    全部组件元信息及原始来源
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC 结果
    ' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2)) + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('' + html.escape(meta['dataset_id']) + ' review

    ' + html.escape(meta['dataset_id']) + ' 抽样人工审核

    选择视图;所有预览均来自已保存的 shared 数据。

    ') + print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + for view in args.views: + render(view, args.out or view.parents[2] / 'doc/validation') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/run-full.sh b/H2O/shared-v1.0/script/provenance/previous-run/script/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..eefa21bbb201a5ad30462ad7548f980793d762b0 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/run-full.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/full.status" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then + read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +else + quota=max + period=controller_disabled +fi +printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" != max ]]; then + printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi +exit "$code" diff --git a/H2O/shared-v1.0/script/provenance/previous-run/script/warehouse_v1_0.py b/H2O/shared-v1.0/script/provenance/previous-run/script/warehouse_v1_0.py new file mode 100644 index 0000000000000000000000000000000000000000..7be8efc617500ab96912e563713d5a9219b01446 --- /dev/null +++ b/H2O/shared-v1.0/script/provenance/previous-run/script/warehouse_v1_0.py @@ -0,0 +1,934 @@ +"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis.""" +import argparse +from contextlib import contextmanager +from functools import lru_cache +import hashlib +import json +import math +import os +import shlex +from pathlib import Path +import pickle +import random +import shutil +import subprocess +import tempfile +import time + +import numpy as np +from PIL import Image +import torch + +SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json', + Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file()) +SCHEMA = json.loads(SCHEMA_PATH.read_text()) +RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw' + + +def json_write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + + +def jsonl_write(path, rows): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w') as out: + for row in rows: + out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n') + + +def sha256(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() + + +def locator(path, member=None, data=None, **extra): + result = {'file': str(Path(path).resolve())} + if member is not None: + result['member'] = member + if data is not None: + result['sha256'] = hashlib.sha256(data).hexdigest() + return result | extra + + +def source(method='Copy source annotation; normalize storage only'): + return {'kind': 'format_conversion', 'method': method} + + +def run(args, **kwargs): + return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs) + + +@lru_cache(maxsize=1) +def ffversion(): + return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0] + + +def probe(path): + return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_streams', '-of', 'json', str(path)], + stdout=subprocess.PIPE).stdout)['streams'][0] + + +def decode_args(path, pixel_format): + threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1') + return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', threads, '-threads', threads, '-noautorotate', + '-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', threads, + '-f', 'rawvideo', '-pix_fmt', pixel_format] + + +def decoded_digest(path, pixel_format): + start = time.monotonic() + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], + stdout=subprocess.PIPE, stderr=err) + digest, size = hashlib.sha256(), 0 + with proc.stdout: + while chunk := proc.stdout.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + if proc.wait(): + err.seek(0) + raise RuntimeError(err.read().decode(errors='replace')) + return digest.hexdigest(), size, time.monotonic() - start + + +def video_frames(path, pixel_format, shape, dtype): + frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err) + completed = False + try: + while True: + data = proc.stdout.read(frame_bytes) + if not data: + break + if len(data) != frame_bytes: + raise ValueError('truncated decoded video frame') + yield np.frombuffer(data, dtype=dtype).reshape(shape) + if proc.wait(): + err.seek(0) + raise ValueError(err.read().decode(errors='replace')) + completed = True + finally: + proc.stdout.close() + if not completed and proc.poll() is None: + proc.terminate() + proc.wait() + + +def storage(path, profile, parameters, source_lossy): + info = probe(path) + if info['codec_name'] == 'h264': + frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0', + '-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames'] + parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]} + return {'profile': profile, 'codec': info['codec_name'], + 'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']], + 'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False, + 'color_space': info.get('color_space', 'unknown'), + 'color_range': info.get('color_range', 'unknown'), + 'color_primaries': info.get('color_primaries', 'unknown'), + 'color_transfer': info.get('color_transfer', 'unknown')}, + 'encoder_parameters': {'version': ffversion()} | parameters, + 'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'} + + +def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1): + start = time.monotonic() + run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-y', '-f', 'rawvideo', + '-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30', + '-i', str(raw), '-an', '-c:v', codec, '-threads', str(threads), *extra, str(target)]) + digest, size, decode_seconds = decoded_digest(target, pixel_format) + if size != Path(raw).stat().st_size or digest != sha256(raw): + raise ValueError(f'lossless roundtrip failed: {target}') + config = storage(target, profile, {'name': codec, 'arguments': list(extra), 'threads': threads}, False) + return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds, + 'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True} + + +def measure_rgb_access(video, raw, width, height, count): + index = count // 2 + start = time.monotonic() + data = run(decode_args(video, 'rgb24') + + ['-vf', f'select=eq(n\\,{index})', '-frames:v', '1', 'pipe:1'], + stdout=subprocess.PIPE).stdout + with raw.open('rb') as inp: + inp.seek(index * width * height * 3) + if data != inp.read(width * height * 3): + raise ValueError('exact indexed RGB read failed') + return {'random_access_strategy': 'decode from first keyframe; select exact presentation index', + 'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start} + + +def jpeg_sample_indices(sequence, camera, count): + seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big') + indices = {0, count - 1, count // 4, count // 2, 3 * count // 4} + indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices], + min(count, 16) - len(indices))) + return sorted(indices), seed + + +def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full): + packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)], + stdout=subprocess.PIPE).stdout)['packets'] + if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes: + raise ValueError('JPEG packet hashes/order/count differ') + info = probe(target) + if [info['width'], info['height']] != list(size): + raise ValueError('JPEG container dimensions differ') + indices, seed = jpeg_sample_indices(sequence, camera, len(paths)) + if full: + indices = list(range(len(paths))) + select = '+'.join(f'eq(n\\,{i})' for i in indices) + frame_bytes = size[0] * size[1] * 3 + # Spool selected frames to disk, keeping RAM bounded for full-view audits. + with tempfile.TemporaryFile() as decoded: + run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded) + decoded.seek(0) + for i in indices: + expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout + if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected: + raise ValueError(f'JPEG decoded pixels differ at frame {i}') + if decoded.read(1): + raise ValueError('JPEG selected pixel count differs') + return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed, + 'selected_frame_indices': indices, 'pixel_frames_checked': len(indices), + 'packet_frames_checked': len(paths), 'jpeg_packets_exact': True, + 'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True, + 'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full} + + +def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False, + ffv1_first=False, codec_threads=1): + """JPEG packet proof plus deterministic pixels; re-encodings compare all pixels.""" + target.parent.mkdir(parents=True, exist_ok=True) + raw = work / 'rgb.raw' + packets = [] + has_missing = video is None and any(p is None for p in paths) + if has_missing: + present = next((p for p in paths if p is not None), None) + if present is None: + raise ValueError('no source RGB image to establish the pixel format/grid') + original = probe(present) + width, height = original['width'], original['height'] + with raw.open('wb') as dest: + for path in paths: + if path is None: + dest.write(bytes(width * height * 3)) + else: + with Image.open(path) as im: + if im.mode != 'RGB' or im.size != (width, height): + raise ValueError('source RGB grid/type changes within view') + run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest) + lossy, count = 'unknown', len(paths) + input_args = None + elif video is None: + if not paths: + raise ValueError('RGB timeline must contain existing source images') + suffix = paths[0].suffix.lower() + if suffix not in ('.jpg', '.jpeg', '.png'): + raise ValueError('unsupported source RGB format') + images = work / 'rgb_source' + images.mkdir() + dimensions = None + for i, path in enumerate(paths): + with Image.open(path) as im: + if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size): + raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion') + dimensions = im.size + if im.format == 'PNG' and path.read_bytes()[24] != 8: + raise ValueError('high bit depth RGB needs a registered schema') + dest = images / f'{i:08d}{suffix}' + shutil.copyfile(path, dest) + packets.append(sha256(path)) + width, height = dimensions + input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))] + count = len(paths) + original = probe(paths[0]) + lossy = suffix in ('.jpg', '.jpeg') + else: + original = probe(video) + if int(original.get('bits_per_raw_sample') or 8) > 8 or any( + x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')): + raise ValueError('high bit depth RGB needs a registered schema') + width, height = original['width'], original['height'] + input_args = ['-i', str(video)] + lossy = 'unknown' + limits = ['-frames:v', str(count)] if count else [] + records = [] + if video is None and not has_missing and suffix in ('.jpg', '.jpeg'): + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + encode_seconds = time.monotonic() - start + validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg) + cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy) + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size, + 'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds}) + return cfg, [width, height], records, count + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + if not has_missing: + threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1') + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', threads, '-noautorotate', + *input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', threads, + '-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)]) + frame_bytes = width * height * 3 + actual, remainder = divmod(raw.stat().st_size, frame_bytes) + if remainder or not actual or (count is not None and actual != count): + raise ValueError('source RGB frame count mismatch') + expected_hash = sha256(raw) + can_copy = video is not None + if can_copy: + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + digest, size, seconds = decoded_digest(target, 'rgb24') + if digest != expected_hash or size != raw.stat().st_size: + raise ValueError('stream-copy RGB bytes/order/count mismatch') + cfg = storage(target, 'mkv/source_copy/v1', + {'stream_copy': True}, lossy) + if video: + cfg['storage_fps'] = original.get('avg_frame_rate') + cfg['preserve_source_pts'] = True + records.append({'profile': cfg['profile'], 'all_frames_exact': True, + 'decoded_sha256': digest, + 'bytes': target.stat().st_size, 'decode_seconds': seconds, + 'encode_seconds': time.monotonic() - start - seconds}) + records[-1].update(measure_rgb_access(target, raw, width, height, actual)) + return cfg, [width, height], records, actual + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'stream_copy', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + candidates = [] + for profile, codec, params in [ + ('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']), + ('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]: + path = work / (codec + '.mkv') + try: + cfg, record = encode_raw(raw, path, width, height, 'rgb24', profile, codec, params, + codec_threads if codec == 'ffv1' else 1) + cfg['source_lossy'] = lossy + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + record['profile'] = profile + record.update(measure_rgb_access(path, raw, width, height, actual)) + records.append(record) + candidates.append((path.stat().st_size, path, cfg)) + if ffv1_first and codec == 'ffv1': + break # Keep the H.264 fallback only if the preferred exact encoder fails. + except subprocess.CalledProcessError as exc: + records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')}) + if not candidates: + raise ValueError('no supported lossless RGB encoder') + _, chosen, cfg = min(candidates, key=lambda x: x[0]) + shutil.move(chosen, target) + return cfg, [width, height], records, actual + + +def pack_depth(depth): + bits = np.ascontiguousarray(depth, dtype='> 16).astype(' 0) + arr[~good] = np.nan + out.write(pack_depth(arr).tobytes()) + vo.write(good.astype(np.uint8).tobytes()) + else: + if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535: + raise ValueError('invalid segmentation region codes') + out.write(arr.astype(' vertices: + raise ValueError('empty or invalid mesh') + def dependency(parent, name): + dep = (parent / name).resolve() + if not dep.is_relative_to(asset_root) or not dep.is_file(): + raise ValueError(f'missing or escaping asset dependency: {name}') + return dep + dependencies = [] + for name in materials: + mtl = dependency(path.parent, name) + dependencies.append(mtl) + for line in mtl.read_text().splitlines(): + fields = shlex.split(line, comments=True) + if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')): + dependencies.append(dependency(mtl.parent, fields[-1])) + return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path), + 'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}} + + +def mesh_asset(view, oid, directory, obj, loc): + dest = view.path / f'annotation/object/{oid}/assets' + shutil.copytree(directory, dest) + ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix() + mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest) + view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check}) + view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m') + p = view.path / f'annotation/object/{oid}/metainfo.json' + info = json.loads(p.read_text()) + info.update(has_model=True, mesh_ref=ref) + json_write(p, info) + + +def safe_member(root, name): + path = (Path(root) / name).resolve() + if not path.is_relative_to(Path(root).resolve()): + raise ValueError(f'unsafe archive path: {name}') + return path + + +class ChumpyStub: + def __setstate__(self, state): + self.__dict__.update(state) + + +class ManoUnpickler(pickle.Unpickler): + def find_class(self, module, name): + if module.startswith('chumpy'): + return ChumpyStub + return super().find_class(module, name) + + +def mano_models(directory): + result = {} + if directory is None: + return result + for side in ('left', 'right'): + path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl' + if not path.exists(): + continue + with path.open('rb') as f: + data = ManoUnpickler(f, encoding='latin1').load() + result[side] = {'components': np.asarray(data['hands_components']), + 'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path), + 'file': path.name} + return result + + +def model_profile(models): + identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode() + return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True, + 'left_shapedirs_correction': 'not_applied', + 'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}} + + +def pca_to_axis_angle(coeffs, model): + coeffs = np.asarray(coeffs) + if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all(): + raise ValueError('invalid MANO PCA coefficients') + return coeffs @ model['components'] + model['mean'] + + +def parser(dataset, description): + p = argparse.ArgumentParser(description=description) + p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset) + p.add_argument('--out', type=Path, default=Path('converted')) + p.add_argument('--release-id', default='v1.0') + p.add_argument('--limit', type=int, help='Maximum sequences to convert') + p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)') + p.add_argument('--mano-dir', type=Path) + p.add_argument('--views', help='Comma-separated source camera IDs') + p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views') + return p + + +def roots(root): + root = Path(root).expanduser() + return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()] + + +def find_file(root, name): + return next((p / name for p in roots(root) if (p / name).exists()), None) + + +def release(args, dataset): + if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'): + raise ValueError('release-id must be a single directory name') + if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1: + raise ValueError('limits must be positive') + out = args.out.expanduser().resolve() / dataset / args.release_id + raw = args.root.expanduser().resolve() + if out == raw or out.is_relative_to(raw): + raise ValueError('output must not modify the raw source tree') + (out / 'data').mkdir(parents=True, exist_ok=True) + (out / 'doc').mkdir(exist_ok=True) + (out / 'script').mkdir(exist_ok=True) + scripts = list(Path(__file__).resolve().parent.glob('*.py')) + existing = {p.name for p in (out / 'script').glob('*.py')} + if existing and existing != {p.name for p in scripts}: + raise ValueError('converter files changed; choose a new --release-id') + copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')] + copies += [(path, out / 'script' / path.name) for path in scripts] + # Check every existing file before changing any published definition or script. + for src, dest in copies: + if dest.exists() and sha256(dest) != sha256(src): + raise ValueError('converter or contract changed within an existing release; choose a new --release-id') + for src, dest in copies: + if src.resolve() != dest.resolve(): + shutil.copyfile(src, dest) + json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}) + return out + + +@contextmanager +def sequence_dir(out, sequence): + if Path(sequence).name != sequence: + raise ValueError('sequence ID must be a single path component') + final = out / 'data' / sequence + with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd: + tmp = Path(wd) + yield tmp + if final.exists(): + if any((final / child.name).exists() for child in tmp.iterdir()): + raise FileExistsError('view already published; use a new release-id to preserve it') + for child in list(tmp.iterdir()): + child.rename(final / child.name) + else: + tmp.rename(final) + + +def build_record(out, sequence, reports): + path = out / 'doc' / (sequence + '.build.json') + previous = json.loads(path.read_text()) if path.exists() else {} + config = json.loads((out / 'script/config.json').read_text()) + for report in reports.values(): + report['configuration'] = config + json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'], + 'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')}, + 'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()}, + 'views': previous.get('views', {}) | reports}) + + +def check_view_type(meta): + # The pinned ARCTIC contract makes view_type optional; adapters still supply known views. + if 'view_type' not in meta: + return + if meta['view_type'] not in ('ego', 'exo', 'unknown'): + raise ValueError('view_type must be ego/exo/unknown') + expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id']) + if meta['dataset_id'] == 'H2O': + expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + if expected and meta['view_type'] not in (expected, 'unknown'): + raise ValueError('view_type contradicts known source capture setup') + + +def check_valid_policy(component, count): + policy = component.get('valid_policy', {}) + for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks', + 'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'): + if field not in policy: + raise ValueError(f'valid_policy missing {field}') + if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']: + raise ValueError('outdated annotation validity semantics') + if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']: + raise ValueError('incomplete validity rule/scope') + if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'): + raise ValueError('official QA requires a verified adapter; supervision acceptance paused') + excluded = policy['local_excluded_frame_indices'] + if any(type(i) is not int or not 0 <= i < count for i in excluded): + raise ValueError('invalid local exclusion frame index') + if excluded: + raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters') + if policy['visibility_independent'] is not True: + raise ValueError('visibility must remain independent of validity') + + +def validate_view(path): + """Validate the persisted contract, not a rendering of the source labels.""" + path = Path(path) + meta = json.loads((path / 'metainfo.json').read_text()) + n = meta['num_frames'] + check_view_type(meta) + if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1: + raise ValueError('invalid view header') + def resolve(ref): + if Path(ref).is_absolute() or '\\' in ref: + raise ValueError('component reference must be relative POSIX') + dest = safe_member(path, ref) + if not dest.is_file(): + raise ValueError(f'referenced file missing: {ref}') + return dest + def tensor(ref): + def cpu_storage(storage, location): + if location != 'cpu': + raise ValueError('PT storage must be on CPU') + return storage + value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True) + if not isinstance(value, torch.Tensor) or value.device.type != 'cpu': + raise ValueError('PT must contain only a CPU Tensor') + return value.numpy() + frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()] + if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)): + raise ValueError('frame index/count mismatch') + for f in frames: + if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')): + raise ValueError('incomplete frame provenance') + entities = {'hand_left', 'hand_right'} + parts = {} + for p in (path / 'annotation/object').glob('*/metainfo.json'): + obj = json.loads(p.read_text()) + if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'): + raise ValueError('invalid object identity') + entities.add(obj['object_id']) + if obj.get('mesh_ref'): + if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()): + raise ValueError('mesh must belong to its object') + if obj.get('articulation_ref'): + art = json.loads(resolve(obj['articulation_ref']).read_text()) + part_ids = {part['part_id'] for part in art['parts']} + if len(part_ids) != len(art['parts']): + raise ValueError('duplicate part ID') + parents = {part['part_id']: part['parent_id'] for part in art['parts']} + for part_id in parents: + visited, cur = set(), part_id + while cur is not None: + if cur in visited or cur not in parents: + raise ValueError('invalid or cyclic part hierarchy') + visited.add(cur) + cur = parents[cur] + parts[obj['object_id']] = part_ids + video_stats = {} + for key, component in meta['components'].items(): + if not component.get('available'): + if not component.get('reason'): + raise ValueError('unavailable component needs a reason') + continue + schema = SCHEMA['components'][component['schema_id']] + for required in ('axes', 'provenance', 'source_locator'): + if required not in component: + raise ValueError(f'{key}: {required} missing') + for required in schema.get('required_metadata', []): + if required not in component: + raise ValueError(f'{key}: {required} missing') + if component['provenance']['kind'] == 'derived': + raise ValueError('v1.0 must not synthesize annotations') + if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'): + if not component.get('valid_ref') or not component.get('valid_axes'): + raise ValueError(f'{key}: annotation validity reference/axes missing') + check_valid_policy(component, n) + data_path = resolve(component['data_ref']) + valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None + valid_shape = schema.get('valid_shape') + if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any( + isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))): + raise ValueError(f'{key}: validity schema shape mismatch') + if valid is not None and (valid.dtype != bool or valid.shape[0] != n): + raise ValueError(f'{key}: invalid validity tensor') + if component['schema_id'] == 'mesh/obj/v1': + objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None) + if objroot is None: + raise ValueError('mesh must be owned by an object') + check_mesh(data_path, objroot) + if data_path.suffix == '.pt': + arr = tensor(component['data_ref']) + if arr.dtype != np.float32 or arr.shape[0] != n: + raise ValueError(f'{key}: float dtype or timeline mismatch') + shape = schema.get('shape') + if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))): + raise ValueError(f'{key}: schema shape mismatch') + if valid is not None: + if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all(): + raise ValueError(f'{key}: invalid finite/NaN/validity values') + if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'): + check_transform(arr[valid]) + if data_path.suffix == '.mkv': + cfg = component['storage'] + if cfg['profile'] not in SCHEMA['storage_profiles']: + raise ValueError('unregistered video profile') + for field in SCHEMA['video_metadata']['required']: + if field not in cfg: + raise ValueError('video storage declaration incomplete') + w, h = meta['camera']['image_size'] + if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]: + raise ValueError('encoded raster differs from logical RGB grid') + actual = probe(data_path) + if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or + [actual['width'], actual['height']] != cfg['encoded_size']): + raise ValueError('video storage metadata differs from file') + if key == 'rgb': + fmt, bpp = 'rgb24', 3 + else: + fmt, bpp = 'gray16le', 2 + digest, size, _ = decoded_digest(data_path, fmt) + w, h = cfg['encoded_size'] + if size != n * w * h * bpp: + raise ValueError('raster timeline mismatch') + video_stats[key] = {'decoded_sha256': digest, 'frames': n} + if key == 'depth': + validity = component['valid_storage'] + vp = resolve(component['valid_ref']) + actual_valid = probe(vp) + if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1' + or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]): + raise ValueError('invalid depth validity video') + count = 0 + for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), ' 0)).all() or not np.isnan(depth[~good]).all(): + raise ValueError('invalid depth/validity semantics') + count += 1 + if count != n: + raise ValueError('depth validity timeline mismatch') + if component['schema_id'].startswith('segment/') and component.get('mapping_ref'): + rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()] + if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)): + raise ValueError('segmentation mapping timeline mismatch') + for row in rows: + labels = row['labels'] + if len({a['mask_value'] for a in labels}) != len(labels): + raise ValueError('duplicate region mapping') + for label in labels: + if label['entity_id'] is not None and label['entity_id'] not in entities: + raise ValueError('unresolved segmentation entity') + if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()): + raise ValueError('unresolved segmentation part') + if component['schema_id'] == 'segment/uint16_labels/v1': + width, height = meta['camera']['image_size'] + for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), ' 0 and meta.get('view_type') == 'exo', view + assert (view / 'camera/frames.jsonl').is_file(), view + assert meta['components']['rgb']['available'], view + splits[meta['split']] += 1 + for key, part in meta['components'].items(): + if part.get('available'): + availability[key] += 1 + for ref in ('data_ref', 'valid_ref'): + if part.get(ref): + assert (view / part[ref]).is_file(), (view, key, ref) + assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects + assert availability['depth'] == availability['rgb'] == 8000, availability + report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects), + splits=dict(splits), available_views=dict(availability), config=config, + published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected], + scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.') + destination = doc / 'validation' + destination.mkdir(exist_ok=True) + (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + for view in selected: + render(view, destination) + return report + + +if __name__ == '__main__': + print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.0/script/render_h2o_validation.py b/H2O/shared-v1.0/script/render_h2o_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b89e7c0827f45ec7f854ff8651234cb9a4223f79 --- /dev/null +++ b/H2O/shared-v1.0/script/render_h2o_validation.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from render_hoi4d_validation import mesh_preview, picture, snapshot +from warehouse_v1_0 import unpack_depth, validate_view + + +def load(view, item, n): + if not item.get('available') or not item.get('data_ref', '').endswith('.pt'): + return None, None + values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy() + valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None + return (values, valid) if values.ndim and values.shape[0] == n else (None, None) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values, valid = load(view, item, n) + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
    ' + picture(photo) + '
    RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z,黑=无效,白≥3 m;不改源深度
    ') + details = {'frame': frames[i]} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + '
    原帧号、全部数值标注及有效性
    ' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / item['data_ref']) + '
    源 OBJ 静态预览,不代表物体姿态投影
    ') + report = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览只作人工核查;仅显示真实存在的标注,不合成分割。

    ' + ''.join(pages) + '

    源网格

    ' + ''.join(assets) + '
    全部组件元数据
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC
    ' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('

    H2O 试点预览

    ') + return destination / (title + '.html') + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args() + for view in args.views: + print(render(view, args.out), flush=True) diff --git a/H2O/shared-v1.0/script/render_hoi4d_source_review.py b/H2O/shared-v1.0/script/render_hoi4d_source_review.py new file mode 100644 index 0000000000000000000000000000000000000000..79d7a58744572343670e9cbaecc4cc54ea07f1c1 --- /dev/null +++ b/H2O/shared-v1.0/script/render_hoi4d_source_review.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks.""" +import argparse +import html +import json +from pathlib import Path +import shutil +import zipfile + +import numpy as np +from PIL import Image, ImageDraw + +from render_hoi4d_validation import picture, snapshot + + +def source_parts(view): + rows = [] + for source in view.glob('annotation/object/*/assets/result.json'): + def visit(node): + if isinstance(node, list): + for child in node: + visit(child) + return + if node.get('objs'): + rows.append({'source_part_id': node['id'], 'source_part_name': node['name'], + 'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))}) + for child in node.get('children', []): + visit(child) + visit(json.loads(source.read_text())) + return rows + + +def render(view, z, output): + output.mkdir(parents=True, exist_ok=True) + meta = json.loads((view / 'metainfo.json').read_text()) + seq = meta['sampling']['selection']['source_sequence'] + w, h = meta['camera']['image_size'] + chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1}) + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen) + segment = meta['components'].get('segment', {}) + masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '

    ' + html.escape(seq) + f' / frame {native_id}

    ' + picture(image) + + '

    仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。

    ' + + '
    上游原记录与编码对照
    '
    +                      + html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '
    ') + parts = source_parts(view) + name = view.parent.name + '_' + view.name + '.html' + page = 'HOI4D source correspondence review

    源姿态/原生分割/RGB 的证据图(非真值修改)

    ' + page += ''.join(panels) + '
    CAD result.json 原生部件→OBJ;不等同逐帧姿态对应
    '
    +    page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '
    ' + (output / name).write_text(page) + print(name, 'native_part_links',len(parts),flush=True) + return name + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--raw-root', type=Path, required=True) + p.add_argument('--release', type=Path, required=True) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args(argv) + args.out.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z: + names = [] + for view in sorted((args.release / 'data').glob('*/ego')): + if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence'] + for category in ('2', '3', '14', '17')): + names.append(render(view, z, args.out)) + links = ''.join(f'
  • {html.escape(name)}
  • ' for name in names) + (args.out / 'index.html').write_text('

    源依据对照(非物体几何验收通过)

      ' + links + '
    ') + shutil.copyfile(Path(__file__), args.out / 'renderer.py') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/render_hoi4d_validation.py b/H2O/shared-v1.0/script/render_hoi4d_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7889a1b63b004e046b52fe4e4da0b2b4651b768 --- /dev/null +++ b/H2O/shared-v1.0/script/render_hoi4d_validation.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Standalone, offline HTML review of every persisted component in selected views.""" +import argparse +import base64 +import html +import io +import json +import random +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from warehouse_v1_0 import video_frames, unpack_depth, validate_view + + +def snapshot(video, fmt, shape, dtype, indices): + return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices} + + +def picture(image): + image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized. + output = io.BytesIO() + image.save(output, format='PNG') + return '' + + +def preview_color(value, dataset_id): + # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette + # gave it the same color as YCB object 15; keep data codes untouched. + if dataset_id == 'dex-ycb' and value == 255: + return (255, 32, 64) + return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131)) + + +def mesh_preview(path): + """Project the whole source asset; bound drawing cost without favoring early faces.""" + vertices, faces, referenced = [], [], set() + rng = random.Random(0) + face_count = 0 + with path.open(errors='replace') as stream: + for line in stream: + if line.startswith('v '): + vertices.append([float(v) for v in line.split()[1:4]]) + elif line.startswith('f '): + face = [] + for token in line.split()[1:]: + index = int(token.split('/')[0]) + face.append(index - 1 if index > 0 else len(vertices) + index) + if len(face) < 3: + continue + referenced.update(face) + face_count += 1 + # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail. + if len(faces) < 5000: + faces.append(face) + else: + pick = rng.randrange(face_count) + if pick < len(faces): + faces[pick] = face + if not vertices or not faces: + return 'OBJ 未提供可绘制的顶点/面' + if min(referenced) < 0 or max(referenced) >= len(vertices): + raise ValueError(f'invalid OBJ face index: {path}') + xyz = np.asarray(vertices, dtype=np.float64) + if not np.isfinite(xyz).all(): + raise ValueError(f'nonfinite OBJ vertex: {path}') + # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose. + projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2), + (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6))) + used = projected[np.fromiter(referenced, dtype=np.int64)] + lo, hi = used.min(axis=0), used.max(axis=0) + extent = (hi - lo).max() + if extent <= 0: + return 'OBJ 所有面投影到同一点' + projected = (projected - (lo + hi) / 2) * (380 / extent) + 215 + image = Image.new('RGB', (430, 430), 'white') + draw = ImageDraw.Draw(image) + for face in faces: + polygon = [tuple(projected[i]) for i in face] + draw.line(polygon + [polygon[0]], fill='#205caa', width=1) + return picture(image) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + n = meta['num_frames'] + width, height = meta['camera']['image_size'] + components = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + for item in components.values(): + ref = item.get('valid_ref', '') + if ref.endswith('.pt'): + valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy() + if valid.shape[0] == n: + matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(matching): + selected.add(int(matching[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '' + picture(image) + '
    RGB + 原生 2D 手关键点(若有)
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z(黑=无效,白≥3 m;仅预览)
    ') + if i in masks: + mask = masks[i] + colors = np.zeros((*mask.shape, 3), dtype=np.uint8) + for value in np.unique(mask): + if value not in (0, 65535): + colors[mask == value] = preview_color(int(value), meta['dataset_id']) + legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535)) + panels.append('
    ' + picture(Image.fromarray(colors)) + '
    原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')
    ') + active = (mask != 0) & (mask != 65535) + overlay = rgb[i].copy() + overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(overlay)) + '
    原生分割叠加 RGB(仅预览)
    ') + details = {'frame': frames[i], 'segment_labels': labels.get(i, [])} + for name, component in components.items(): + ref = component.get('data_ref', '') + if component.get('available') and ref.endswith('.pt'): + values = torch.load(view / ref, map_location='cpu', weights_only=True) + if values.ndim and values.shape[0] == n: + details[name] = {'value': values[i].tolist()} + if component.get('valid_ref', '').endswith('.pt'): + valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True) + details[name]['valid'] = valid[i].tolist() + sections.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + + '
    帧号、来源、全部数值组件与有效性
    '
    +                        + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, component in components.items(): + if component.get('available') and component['data_ref'].lower().endswith('.obj'): + ref = component['data_ref'] + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / ref) + + '
    仅展示网格原生形状;未验证尺度/位姿对应。
    ') + result = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。

    ' + ''.join(sections) + '

    原始物体模型(独立预览)

    ' + ''.join(assets) + '
    全部组件元信息及原始来源
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC 结果
    ' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2)) + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('' + html.escape(meta['dataset_id']) + ' review

    ' + html.escape(meta['dataset_id']) + ' 抽样人工审核

    选择视图;所有预览均来自已保存的 shared 数据。

    ') + print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + for view in args.views: + render(view, args.out or view.parents[2] / 'doc/validation') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.0/script/run-full.sh b/H2O/shared-v1.0/script/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..0df31cac6098b370a6d9b450a717f57e34613404 --- /dev/null +++ b/H2O/shared-v1.0/script/run-full.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-process16-pipe" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +ram=/dev/shm/xuzhefeng-h2o-full-process16-20260930 +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" "$ram" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +test ! -e "$base/full.status" || exit 2 +printf 'START=%s\nARCHIVE_WORKERS=4 VIEW_WORKERS=16 VIEW_BACKEND=processes\nCODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 FFV1_SLICES=16\nCAMERA_PIPELINE=true STREAM_MEDIA=true PNG_RAM_GIB=32\nCPU_TARGET_PERCENT=80 CPU_LIMIT=none\n' "$(date -Is)" > "$base/full.status" +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --view-workers 16 --view-backend processes --camera-pipeline --stream-media --codec-threads 10 --decode-threads 10 --depth-threads 4 --ffv1-slices 16 --ram-stage-dir "$ram" --ram-stage-gib 32 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +exit "$code" diff --git a/H2O/shared-v1.0/script/warehouse_v1_0.py b/H2O/shared-v1.0/script/warehouse_v1_0.py new file mode 100644 index 0000000000000000000000000000000000000000..6673c5c3707266a4faae23b46c012b1815deb2e6 --- /dev/null +++ b/H2O/shared-v1.0/script/warehouse_v1_0.py @@ -0,0 +1,1032 @@ +"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis.""" +import argparse +from contextlib import contextmanager +from functools import lru_cache +import hashlib +import json +import math +import os +import shlex +from pathlib import Path +import pickle +import random +import shutil +import subprocess +import tempfile +import time + +import numpy as np +from PIL import Image +import torch + +SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json', + Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file()) +SCHEMA = json.loads(SCHEMA_PATH.read_text()) +RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw' + + +def json_write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + + +def jsonl_write(path, rows): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w') as out: + for row in rows: + out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n') + + +def sha256(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() + + +def locator(path, member=None, data=None, **extra): + result = {'file': str(Path(path).resolve())} + if member is not None: + result['member'] = member + if data is not None: + result['sha256'] = hashlib.sha256(data).hexdigest() + return result | extra + + +def source(method='Copy source annotation; normalize storage only'): + return {'kind': 'format_conversion', 'method': method} + + +def run(args, **kwargs): + return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs) + + +@lru_cache(maxsize=1) +def ffversion(): + return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0] + + +def probe(path): + return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_streams', '-of', 'json', str(path)], + stdout=subprocess.PIPE).stdout)['streams'][0] + + +def decode_args(path, pixel_format): + threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1') + return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', threads, '-threads', threads, '-noautorotate', + '-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', threads, + '-f', 'rawvideo', '-pix_fmt', pixel_format] + + +def decoded_digest(path, pixel_format): + start = time.monotonic() + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], + stdout=subprocess.PIPE, stderr=err) + digest, size = hashlib.sha256(), 0 + with proc.stdout: + while chunk := proc.stdout.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + if proc.wait(): + err.seek(0) + raise RuntimeError(err.read().decode(errors='replace')) + return digest.hexdigest(), size, time.monotonic() - start + + +def video_frames(path, pixel_format, shape, dtype): + frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err) + completed = False + try: + while True: + data = proc.stdout.read(frame_bytes) + if not data: + break + if len(data) != frame_bytes: + raise ValueError('truncated decoded video frame') + yield np.frombuffer(data, dtype=dtype).reshape(shape) + if proc.wait(): + err.seek(0) + raise ValueError(err.read().decode(errors='replace')) + completed = True + finally: + proc.stdout.close() + if not completed and proc.poll() is None: + proc.terminate() + proc.wait() + + +def storage(path, profile, parameters, source_lossy): + info = probe(path) + if info['codec_name'] == 'h264': + frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0', + '-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames'] + parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]} + return {'profile': profile, 'codec': info['codec_name'], + 'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']], + 'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False, + 'color_space': info.get('color_space', 'unknown'), + 'color_range': info.get('color_range', 'unknown'), + 'color_primaries': info.get('color_primaries', 'unknown'), + 'color_transfer': info.get('color_transfer', 'unknown')}, + 'encoder_parameters': {'version': ffversion()} | parameters, + 'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'} + + +def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1): + start = time.monotonic() + slices = os.environ.get('HAND_WAREHOUSE_FFV1_SLICES') + if codec == 'ffv1' and slices: + if slices != '16': + raise ValueError('only the verified FFV1 16-slice profile is enabled') + extra = (*extra, '-level', '3', '-slices', slices) + command = ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', + os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1'), '-y', '-f', 'rawvideo', + '-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30', + '-i', str(raw) if isinstance(raw, Path) else 'pipe:0', '-an', '-c:v', codec, + '-threads', str(threads), *extra, str(target)] + if isinstance(raw, Path): + run(command) + expected_size, expected_hash = raw.stat().st_size, sha256(raw) + else: + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=err) + expected_size, checksum = 0, hashlib.sha256() + try: + for frame in raw: + proc.stdin.write(frame) + checksum.update(frame) + expected_size += len(frame) + proc.stdin.close() + if proc.wait(): + err.seek(0) + raise RuntimeError(err.read().decode(errors='replace')) + except BaseException: + if proc.poll() is None: + proc.kill() + proc.stdin.close() + proc.wait() + raise + expected_hash = checksum.hexdigest() + digest, size, decode_seconds = decoded_digest(target, pixel_format) + if size != expected_size or digest != expected_hash: + raise ValueError(f'lossless roundtrip failed: {target}') + parameters = {'name': codec, 'arguments': list(extra)} + if threads != 1: + parameters['threads'] = threads + config = storage(target, profile, parameters, False) + return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds, + 'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True} + + +def measure_rgb_access(video, raw, width, height, count, source_video=None, source_image=None): + index = count // 2 + start = time.monotonic() + data = run(decode_args(video, 'rgb24') + + ['-vf', f'select=eq(n\\,{index})', '-frames:v', '1', 'pipe:1'], + stdout=subprocess.PIPE).stdout + if raw is None: + if source_image is not None: + expected = run(decode_args(source_image, 'rgb24') + ['-frames:v', '1', 'pipe:1'], + stdout=subprocess.PIPE).stdout + elif source_video is not None: + expected = run(decode_args(source_video, 'rgb24') + + ['-vf', f'select=eq(n\\,{index})', '-frames:v', '1', 'pipe:1'], + stdout=subprocess.PIPE).stdout + else: + raise ValueError('source video/image required for streaming RGB access check') + else: + with raw.open('rb') as inp: + inp.seek(index * width * height * 3) + expected = inp.read(width * height * 3) + if len(expected) != width * height * 3 or data != expected: + raise ValueError('exact indexed RGB read failed') + return {'random_access_strategy': 'decode from first keyframe; select exact presentation index', + 'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start} + + +def jpeg_sample_indices(sequence, camera, count): + seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big') + indices = {0, count - 1, count // 4, count // 2, 3 * count // 4} + indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices], + min(count, 16) - len(indices))) + return sorted(indices), seed + + +def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full): + packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)], + stdout=subprocess.PIPE).stdout)['packets'] + if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes: + raise ValueError('JPEG packet hashes/order/count differ') + info = probe(target) + if [info['width'], info['height']] != list(size): + raise ValueError('JPEG container dimensions differ') + indices, seed = jpeg_sample_indices(sequence, camera, len(paths)) + if full: + indices = list(range(len(paths))) + select = '+'.join(f'eq(n\\,{i})' for i in indices) + frame_bytes = size[0] * size[1] * 3 + # Spool selected frames to disk, keeping RAM bounded for full-view audits. + with tempfile.TemporaryFile() as decoded: + run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded) + decoded.seek(0) + for i in indices: + expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout + if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected: + raise ValueError(f'JPEG decoded pixels differ at frame {i}') + if decoded.read(1): + raise ValueError('JPEG selected pixel count differs') + return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed, + 'selected_frame_indices': indices, 'pixel_frames_checked': len(indices), + 'packet_frames_checked': len(paths), 'jpeg_packets_exact': True, + 'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True, + 'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full} + + +def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False, + ffv1_first=False, codec_threads=1, stream_source=False): + """JPEG packet proof plus deterministic pixels; re-encodings compare all pixels.""" + target.parent.mkdir(parents=True, exist_ok=True) + raw = work / 'rgb.raw' + packets = [] + has_missing = video is None and any(p is None for p in paths) + if has_missing: + present = next((p for p in paths if p is not None), None) + if present is None: + raise ValueError('no source RGB image to establish the pixel format/grid') + original = probe(present) + width, height = original['width'], original['height'] + with raw.open('wb') as dest: + for path in paths: + if path is None: + dest.write(bytes(width * height * 3)) + else: + with Image.open(path) as im: + if im.mode != 'RGB' or im.size != (width, height): + raise ValueError('source RGB grid/type changes within view') + run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest) + lossy, count = 'unknown', len(paths) + input_args = None + elif video is None: + if not paths: + raise ValueError('RGB timeline must contain existing source images') + suffix = paths[0].suffix.lower() + if suffix not in ('.jpg', '.jpeg', '.png'): + raise ValueError('unsupported source RGB format') + images = work / 'rgb_source' + images.mkdir() + dimensions = None + for i, path in enumerate(paths): + with Image.open(path) as im: + if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size): + raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion') + dimensions = im.size + if im.format == 'PNG': + with path.open('rb') as header: + if header.read(25)[24] != 8: + raise ValueError('high bit depth RGB needs a registered schema') + dest = images / f'{i:08d}{suffix}' + if stream_source and suffix == '.png': + try: + os.link(path, dest) # Immutable staging input; avoid a second PNG copy. + except OSError: + # Temporary alias only: RAM/disk staging may be on different filesystems. + os.symlink(path.resolve(), dest) + else: + shutil.copyfile(path, dest) + if suffix in ('.jpg', '.jpeg'): + packets.append(sha256(path)) + width, height = dimensions + input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))] + count = len(paths) + original = probe(paths[0]) + lossy = suffix in ('.jpg', '.jpeg') + else: + original = probe(video) + if int(original.get('bits_per_raw_sample') or 8) > 8 or any( + x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')): + raise ValueError('high bit depth RGB needs a registered schema') + width, height = original['width'], original['height'] + input_args = ['-i', str(video)] + lossy = 'unknown' + limits = ['-frames:v', str(count)] if count else [] + records = [] + if video is None and not has_missing and suffix in ('.jpg', '.jpeg'): + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + encode_seconds = time.monotonic() - start + validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg) + cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy) + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size, + 'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds}) + return cfg, [width, height], records, count + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + stream_images = stream_source and video is None and not has_missing and suffix == '.png' + if stream_images: + source_size, expected_hash = count * width * height * 3, None + elif stream_source and video is not None: + expected_hash, source_size, source_seconds = decoded_digest(video, 'rgb24', count) + else: + if not has_missing: + threads = os.environ.get('HAND_WAREHOUSE_FFMPEG_THREADS', '1') + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', threads, '-noautorotate', + *input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', threads, + '-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)]) + source_size, expected_hash = raw.stat().st_size, sha256(raw) + frame_bytes = width * height * 3 + actual, remainder = divmod(source_size, frame_bytes) + if remainder or not actual or (count is not None and actual != count): + raise ValueError('source RGB frame count mismatch') + can_copy = video is not None + if can_copy: + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + digest, size, seconds = decoded_digest(target, 'rgb24') + if digest != expected_hash or size != source_size: + raise ValueError('stream-copy RGB bytes/order/count mismatch') + cfg = storage(target, 'mkv/source_copy/v1', + {'stream_copy': True}, lossy) + if video: + cfg['storage_fps'] = original.get('avg_frame_rate') + cfg['preserve_source_pts'] = True + records.append({'profile': cfg['profile'], 'all_frames_exact': True, + 'decoded_sha256': digest, + 'bytes': target.stat().st_size, 'decode_seconds': seconds, + 'encode_seconds': time.monotonic() - start - seconds}) + records[-1].update(measure_rgb_access(target, None if stream_source else raw, width, height, actual, video)) + if stream_source: + records[-1]['source_decode_seconds'] = source_seconds + return cfg, [width, height], records, actual + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'stream_copy', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + if stream_source and video is not None: + # Exact fallback only: stream-copy normally avoids creating the source RGB spool. + run(decode_args(video, 'rgb24') + limits + [str(raw)]) + if raw.stat().st_size != source_size or sha256(raw) != expected_hash: + raise ValueError('streaming source RGB differs from fallback decode') + candidates = [] + for profile, codec, params in [ + ('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']), + ('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]: + path = work / (codec + '.mkv') + try: + streamed = stream_images + def source_frames(): + source_path = video if video is not None else images / ('%08d' + suffix) + frames = video_frames(source_path, 'rgb24', (height, width, 3), np.uint8) + try: + for _ in range(actual): + try: + frame = next(frames) + except StopIteration: + raise ValueError('source RGB frame count mismatch') from None + yield frame.tobytes() + finally: + frames.close() + cfg, record = encode_raw(source_frames() if streamed else raw, path, width, height, + 'rgb24', profile, codec, params, codec_threads) + if expected_hash is not None and record['decoded_sha256'] != expected_hash: + raise ValueError('source RGB digest/order differs from encoded output') + cfg['source_lossy'] = lossy + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + record['profile'] = profile + record.update(measure_rgb_access(path, None if streamed else raw, width, height, actual, + source_video=video, source_image=paths[actual // 2] if stream_images else None)) + records.append(record) + candidates.append((path.stat().st_size, path, cfg)) + if ffv1_first and codec == 'ffv1': + break # Keep the H.264 fallback only if the preferred exact encoder fails. + except subprocess.CalledProcessError as exc: + records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')}) + if not candidates: + raise ValueError('no supported lossless RGB encoder') + _, chosen, cfg = min(candidates, key=lambda x: x[0]) + shutil.move(chosen, target) + return cfg, [width, height], records, actual + + +def pack_depth(depth): + bits = np.ascontiguousarray(depth, dtype='> 16).astype(' 0) + arr[~good] = np.nan + vo.write(good.astype(np.uint8).tobytes()) + payload = pack_depth(arr).tobytes() + else: + if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535: + raise ValueError('invalid segmentation region codes') + payload = arr.astype(' vertices: + raise ValueError('empty or invalid mesh') + def dependency(parent, name): + dep = (parent / name).resolve() + if not dep.is_relative_to(asset_root) or not dep.is_file(): + raise ValueError(f'missing or escaping asset dependency: {name}') + return dep + dependencies = [] + for name in materials: + mtl = dependency(path.parent, name) + dependencies.append(mtl) + for line in mtl.read_text().splitlines(): + fields = shlex.split(line, comments=True) + if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')): + dependencies.append(dependency(mtl.parent, fields[-1])) + return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path), + 'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}} + + +def mesh_asset(view, oid, directory, obj, loc): + dest = view.path / f'annotation/object/{oid}/assets' + shutil.copytree(directory, dest) + ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix() + mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest) + view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check}) + view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m') + p = view.path / f'annotation/object/{oid}/metainfo.json' + info = json.loads(p.read_text()) + info.update(has_model=True, mesh_ref=ref) + json_write(p, info) + + +def safe_member(root, name): + path = (Path(root) / name).resolve() + if not path.is_relative_to(Path(root).resolve()): + raise ValueError(f'unsafe archive path: {name}') + return path + + +class ChumpyStub: + def __setstate__(self, state): + self.__dict__.update(state) + + +class ManoUnpickler(pickle.Unpickler): + def find_class(self, module, name): + if module.startswith('chumpy'): + return ChumpyStub + return super().find_class(module, name) + + +def mano_models(directory): + result = {} + if directory is None: + return result + for side in ('left', 'right'): + path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl' + if not path.exists(): + continue + with path.open('rb') as f: + data = ManoUnpickler(f, encoding='latin1').load() + result[side] = {'components': np.asarray(data['hands_components']), + 'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path), + 'file': path.name} + return result + + +def model_profile(models): + identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode() + return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True, + 'left_shapedirs_correction': 'not_applied', + 'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}} + + +def pca_to_axis_angle(coeffs, model): + coeffs = np.asarray(coeffs) + if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all(): + raise ValueError('invalid MANO PCA coefficients') + return coeffs @ model['components'] + model['mean'] + + +def parser(dataset, description): + p = argparse.ArgumentParser(description=description) + p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset) + p.add_argument('--out', type=Path, default=Path('converted')) + p.add_argument('--release-id', default='v1.0') + p.add_argument('--limit', type=int, help='Maximum sequences to convert') + p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)') + p.add_argument('--mano-dir', type=Path) + p.add_argument('--views', help='Comma-separated source camera IDs') + p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views') + return p + + +def roots(root): + root = Path(root).expanduser() + return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()] + + +def find_file(root, name): + return next((p / name for p in roots(root) if (p / name).exists()), None) + + +def release(args, dataset): + if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'): + raise ValueError('release-id must be a single directory name') + if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1: + raise ValueError('limits must be positive') + out = args.out.expanduser().resolve() / dataset / args.release_id + raw = args.root.expanduser().resolve() + if out == raw or out.is_relative_to(raw): + raise ValueError('output must not modify the raw source tree') + (out / 'data').mkdir(parents=True, exist_ok=True) + (out / 'doc').mkdir(exist_ok=True) + (out / 'script').mkdir(exist_ok=True) + scripts = list(Path(__file__).resolve().parent.glob('*.py')) + existing = {p.name for p in (out / 'script').glob('*.py')} + if existing and existing != {p.name for p in scripts}: + raise ValueError('converter files changed; choose a new --release-id') + copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')] + copies += [(path, out / 'script' / path.name) for path in scripts] + # Check every existing file before changing any published definition or script. + for src, dest in copies: + if dest.exists() and sha256(dest) != sha256(src): + raise ValueError('converter or contract changed within an existing release; choose a new --release-id') + for src, dest in copies: + if src.resolve() != dest.resolve(): + shutil.copyfile(src, dest) + json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}) + return out + + +@contextmanager +def sequence_dir(out, sequence): + if Path(sequence).name != sequence: + raise ValueError('sequence ID must be a single path component') + final = out / 'data' / sequence + with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd: + tmp = Path(wd) + yield tmp + if final.exists(): + if any((final / child.name).exists() for child in tmp.iterdir()): + raise FileExistsError('view already published; use a new release-id to preserve it') + for child in list(tmp.iterdir()): + child.rename(final / child.name) + else: + tmp.rename(final) + + +def build_record(out, sequence, reports): + path = out / 'doc' / (sequence + '.build.json') + previous = json.loads(path.read_text()) if path.exists() else {} + config = json.loads((out / 'script/config.json').read_text()) + for report in reports.values(): + report['configuration'] = config + json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'], + 'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')}, + 'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()}, + 'views': previous.get('views', {}) | reports}) + + +def check_view_type(meta): + # The pinned ARCTIC contract makes view_type optional; adapters still supply known views. + if 'view_type' not in meta: + return + if meta['view_type'] not in ('ego', 'exo', 'unknown'): + raise ValueError('view_type must be ego/exo/unknown') + expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id']) + if meta['dataset_id'] == 'H2O': + expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + if expected and meta['view_type'] not in (expected, 'unknown'): + raise ValueError('view_type contradicts known source capture setup') + + +def check_valid_policy(component, count): + policy = component.get('valid_policy', {}) + for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks', + 'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'): + if field not in policy: + raise ValueError(f'valid_policy missing {field}') + if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']: + raise ValueError('outdated annotation validity semantics') + if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']: + raise ValueError('incomplete validity rule/scope') + if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'): + raise ValueError('official QA requires a verified adapter; supervision acceptance paused') + excluded = policy['local_excluded_frame_indices'] + if any(type(i) is not int or not 0 <= i < count for i in excluded): + raise ValueError('invalid local exclusion frame index') + if excluded: + raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters') + if policy['visibility_independent'] is not True: + raise ValueError('visibility must remain independent of validity') + + +def validate_view(path): + """Validate the persisted contract, not a rendering of the source labels.""" + path = Path(path) + meta = json.loads((path / 'metainfo.json').read_text()) + n = meta['num_frames'] + check_view_type(meta) + if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1: + raise ValueError('invalid view header') + def resolve(ref): + if Path(ref).is_absolute() or '\\' in ref: + raise ValueError('component reference must be relative POSIX') + dest = safe_member(path, ref) + if not dest.is_file(): + raise ValueError(f'referenced file missing: {ref}') + return dest + def tensor(ref): + def cpu_storage(storage, location): + if location != 'cpu': + raise ValueError('PT storage must be on CPU') + return storage + value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True) + if not isinstance(value, torch.Tensor) or value.device.type != 'cpu': + raise ValueError('PT must contain only a CPU Tensor') + return value.numpy() + frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()] + if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)): + raise ValueError('frame index/count mismatch') + for f in frames: + if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')): + raise ValueError('incomplete frame provenance') + entities = {'hand_left', 'hand_right'} + parts = {} + for p in (path / 'annotation/object').glob('*/metainfo.json'): + obj = json.loads(p.read_text()) + if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'): + raise ValueError('invalid object identity') + entities.add(obj['object_id']) + if obj.get('mesh_ref'): + if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()): + raise ValueError('mesh must belong to its object') + if obj.get('articulation_ref'): + art = json.loads(resolve(obj['articulation_ref']).read_text()) + part_ids = {part['part_id'] for part in art['parts']} + if len(part_ids) != len(art['parts']): + raise ValueError('duplicate part ID') + parents = {part['part_id']: part['parent_id'] for part in art['parts']} + for part_id in parents: + visited, cur = set(), part_id + while cur is not None: + if cur in visited or cur not in parents: + raise ValueError('invalid or cyclic part hierarchy') + visited.add(cur) + cur = parents[cur] + parts[obj['object_id']] = part_ids + video_stats = {} + for key, component in meta['components'].items(): + if not component.get('available'): + if not component.get('reason'): + raise ValueError('unavailable component needs a reason') + continue + schema = SCHEMA['components'][component['schema_id']] + for required in ('axes', 'provenance', 'source_locator'): + if required not in component: + raise ValueError(f'{key}: {required} missing') + for required in schema.get('required_metadata', []): + if required not in component: + raise ValueError(f'{key}: {required} missing') + if component['provenance']['kind'] == 'derived': + raise ValueError('v1.0 must not synthesize annotations') + if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'): + if not component.get('valid_ref') or not component.get('valid_axes'): + raise ValueError(f'{key}: annotation validity reference/axes missing') + check_valid_policy(component, n) + data_path = resolve(component['data_ref']) + valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None + valid_shape = schema.get('valid_shape') + if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any( + isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))): + raise ValueError(f'{key}: validity schema shape mismatch') + if valid is not None and (valid.dtype != bool or valid.shape[0] != n): + raise ValueError(f'{key}: invalid validity tensor') + if component['schema_id'] == 'mesh/obj/v1': + objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None) + if objroot is None: + raise ValueError('mesh must be owned by an object') + check_mesh(data_path, objroot) + if data_path.suffix == '.pt': + arr = tensor(component['data_ref']) + if arr.dtype != np.float32 or arr.shape[0] != n: + raise ValueError(f'{key}: float dtype or timeline mismatch') + shape = schema.get('shape') + if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))): + raise ValueError(f'{key}: schema shape mismatch') + if valid is not None: + if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all(): + raise ValueError(f'{key}: invalid finite/NaN/validity values') + if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'): + check_transform(arr[valid]) + if data_path.suffix == '.mkv': + cfg = component['storage'] + if cfg['profile'] not in SCHEMA['storage_profiles']: + raise ValueError('unregistered video profile') + for field in SCHEMA['video_metadata']['required']: + if field not in cfg: + raise ValueError('video storage declaration incomplete') + w, h = meta['camera']['image_size'] + if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]: + raise ValueError('encoded raster differs from logical RGB grid') + actual = probe(data_path) + if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or + [actual['width'], actual['height']] != cfg['encoded_size']): + raise ValueError('video storage metadata differs from file') + if key == 'rgb': + fmt, bpp = 'rgb24', 3 + else: + fmt, bpp = 'gray16le', 2 + digest, size, _ = decoded_digest(data_path, fmt) + w, h = cfg['encoded_size'] + if size != n * w * h * bpp: + raise ValueError('raster timeline mismatch') + video_stats[key] = {'decoded_sha256': digest, 'frames': n} + if key == 'depth': + validity = component['valid_storage'] + vp = resolve(component['valid_ref']) + actual_valid = probe(vp) + if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1' + or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]): + raise ValueError('invalid depth validity video') + count = 0 + for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), ' 0)).all() or not np.isnan(depth[~good]).all(): + raise ValueError('invalid depth/validity semantics') + count += 1 + if count != n: + raise ValueError('depth validity timeline mismatch') + if component['schema_id'].startswith('segment/') and component.get('mapping_ref'): + rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()] + if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)): + raise ValueError('segmentation mapping timeline mismatch') + for row in rows: + labels = row['labels'] + if len({a['mask_value'] for a in labels}) != len(labels): + raise ValueError('duplicate region mapping') + for label in labels: + if label['entity_id'] is not None and label['entity_id'] not in entities: + raise ValueError('unresolved segmentation entity') + if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()): + raise ValueError('unresolved segmentation part') + if component['schema_id'] == 'segment/uint16_labels/v1': + width, height = meta['camera']['image_size'] + for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), '