#!/usr/bin/env python3 """Validate all shared frames; render every available modality in sampled views.""" import argparse from collections import defaultdict import hashlib import html import json import random from pathlib import Path import numpy as np from PIL import Image, ImageDraw import torch from acquire import sha from media import decode, rgb COLORS = [(0, 0, 0), (255, 70, 80), (50, 150, 255), (255, 180, 40), (80, 220, 100), (220, 80, 220), (140, 90, 40), (40, 220, 220), (150, 150, 255), (70, 70, 70)] EDGES = [(0, i) for i in (1, 5, 9, 13, 17)] + [(i, i+1) for i in range(1, 21) if i % 4 != 0] def read_json(path): return json.loads(path.read_text()) def read_jsonl(path): return [json.loads(line) for line in path.read_text().splitlines()] def pt(path): t = torch.load(path, map_location='cpu', weights_only=True) if not isinstance(t, torch.Tensor) or t.device.type != 'cpu': raise ValueError(f'Expected CPU Tensor: {path}') return t.numpy() def local_ref(view, ref): p = view / ref if not p.resolve().is_relative_to(view.resolve()) or not p.is_file(): raise ValueError(f'Broken/unsafe reference: {ref}') return p def check_inventory(root, expected): actual = {p.relative_to(root).as_posix(): sha(p) for p in root.rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.relative_to(root).as_posix() not in ('doc/validation/report.json', 'doc/validation/human_review.json')} if actual != expected: raise ValueError('Release contents changed after validation; revalidate and repeat human review') def validate_view(view, registry): m = read_json(view / 'metainfo.json') if m.get('dataset_id') != 'EgoHOS': raise ValueError('This v1.1 validator supports EgoHOS only') frames = read_jsonl(view / 'camera/frames.jsonl') t = m['num_frames'] if t < 1 or m['hand_slots'] != ['left', 'right'] or len(frames) != t: raise ValueError('Frame count/hand-slot error') required = registry['view_metadata']['required_fields'] if [k for k in required if k not in m]: raise ValueError(f'Missing required view metadata fields: {[k for k in required if k not in m]}') if (m['schema_version'] != registry['view_metadata']['schema_version'] or m['release_id'] != registry['release_layout']['release_id']): raise ValueError(f"Invalid schema/release version: {m['schema_version']}/{m['release_id']}") if m['view_type'] not in registry['view_metadata']['view_type_values']: raise ValueError('Invalid view_type') if [r['frame_index'] for r in frames] != list(range(t)) or len({r['sample_id'] for r in frames}) != t: raise ValueError('Invalid/duplicate frame IDs') for f in frames: for key in ['timestamp_ns', 'clock_domain', 'source_locator', 'source_frame_id']: if key not in f: raise ValueError(f'Missing frame field {key}') proofs = read_json(view / 'encoding_validation.json') for name, c in m['components'].items(): if not c['available']: if not c.get('reason'): raise ValueError('Missing unavailable reason') continue schema = registry['components'][c['schema_id']] data = local_ref(view, c['data_ref']) valid = pt(local_ref(view, c['valid_ref'])) if 'valid_ref' in c else None if valid is not None and valid.dtype != bool: raise ValueError('Validity must be bool') if 'valid_shape' in schema and valid is not None: shape = tuple(t if x == 'T' else x for x in schema['valid_shape']) if valid.shape != shape: raise ValueError(f'{name} valid shape {valid.shape} != {shape}') if data.suffix == '.pt': a = pt(data) shape = tuple(t if x == 'T' else x for x in schema['shape']) if a.shape != shape or a.dtype != np.dtype(schema['dtype']): raise ValueError(f'{name} tensor shape/dtype mismatch') ok = np.broadcast_to(valid.reshape(valid.shape + (1,)*(a.ndim-valid.ndim)), a.shape) if not np.isfinite(a[ok]).all() or not np.isnan(a[~ok]).all(): raise ValueError(f'{name}: finite valid / NaN invalid policy failed') if c['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'): r = a[valid, :3, :3] if not (np.allclose(np.swapaxes(r, 1, 2) @ r, np.eye(3), atol=1e-4) and np.allclose(np.linalg.det(r), 1, atol=1e-4)): raise ValueError('SE3 check failed') elif data.suffix == '.mkv': storage = c['storage'] if storage['profile'] not in schema['allowed_storage_profiles']: raise ValueError('Unregistered storage profile') for required in registry['video_metadata']['required']: if required not in storage: raise ValueError(f'Missing storage field {required}') chosen = next(x for x in proofs[name]['candidates'] if x['encoder'] == proofs[name]['selected']) hashes = [] mapping = read_jsonl(local_ref(view, c['mapping_ref'])) if name == 'segment' else None if mapping is not None and (len(mapping) != t or [x['frame_index'] for x in mapping] != list(range(t))): raise ValueError('Segmentation mapping timeline differs') for i, a in enumerate(decode(data, name == 'segment')): if list(a.shape[1::-1]) != m['camera']['image_size']: raise ValueError('Video dimensions differ from camera') hashes.append(hashlib.sha256(a.tobytes()).hexdigest()) if mapping is not None: codes = [x['mask_value'] for x in mapping[i]['labels']] if len(codes) != len(set(codes)) or not set(np.unique(a)).difference((0, 65535)).issubset(codes): raise ValueError('Invalid segment mapping') if len(hashes) != t or hashes != chosen['ordered_decoded_sha256']: raise ValueError('Video differs from exact source comparison proof') elif data.suffix == '.obj': if not any(line.startswith('v ') for line in data.read_text().splitlines()): raise ValueError('Empty mesh') return m, frames def clean_numbers(x): if isinstance(x, np.generic): return clean_numbers(x.item()) if isinstance(x, np.ndarray): return clean_numbers(x.tolist()) if isinstance(x, list): return [clean_numbers(v) for v in x] if isinstance(x, float) and not np.isfinite(x): return None return x def preview_view(root, view, m, frames, target, source_root=None): videos = {'rgb': decode(view / 'observation/rgb.mkv')} c = m['components'] if c.get('segment', {}).get('available'): videos['segment'] = decode(view / c['segment']['data_ref'], True) arrays = {name: pt(view / component['data_ref']) for name, component in c.items() if component['available'] and component.get('data_ref', '').endswith('.pt')} instances = read_jsonl(view / c['segment']['mapping_ref']) if 'segment' in videos else None objects = [read_json(p) for p in (view / 'annotation/object').glob('*/metainfo.json')] cards = [] mesh = None if c.get('object_mesh', {}).get('available'): mesh = np.array([[float(v) for v in line.split()[1:4]] for line in (view / c['object_mesh']['data_ref']).read_text().splitlines() if line.startswith('v ')]) # Display-only point sampling; full OBJ asset is retained unchanged in data/. mesh = mesh[::max(1, len(mesh)//3000)] for i, frame in enumerate(frames): name = hashlib.sha256(f'{view.relative_to(root)}/{i}'.encode()).hexdigest()[:20] rgb_array = next(videos['rgb']) image = Image.fromarray(rgb_array) overlay = image.copy() if 'segment' in videos: mask = next(videos['segment']) color = np.asarray(COLORS, dtype=np.uint8)[mask] mix = rgb_array.copy() foreground = (mask != 9) & (mask != 0) mix[foreground] = (rgb_array[foreground] * .45 + color[foreground] * .55).astype(np.uint8) overlay = Image.fromarray(mix) Image.fromarray(color).save(target / f'{name}-mask.png') draw = ImageDraw.Draw(overlay) if 'keypoints_uv' in arrays: pts = arrays['keypoints_uv'][i, 1] for a, b in EDGES: if np.isfinite(pts[[a, b]]).all(): draw.line([tuple(pts[a]), tuple(pts[b])], fill=(0, 255, 100), width=2) for k, xy in enumerate(pts): if np.isfinite(xy).all(): x, y = xy draw.ellipse((x-2, y-2, x+2, y+2), fill=(255, 50, 50)) draw.text((x+3, y), str(k), fill=(255, 255, 255)) objcam = None if mesh is not None and 'object_pose' in arrays: pose = arrays['object_pose'][i] objcam = mesh @ pose[:3, :3].T + pose[:3, 3] projected = objcam @ arrays['intrinsic'][i].T for x, y, z in projected[projected[:, 2] > 0]: draw.point((float(x/z), float(y/z)), fill=(255, 210, 0)) image.save(target / f'{name}-rgb.png') has_overlay = 'segment' in videos or 'keypoints_uv' in arrays or objcam is not None if has_overlay: overlay.save(target / f'{name}-overlay.png') raw_ref = None if source_root: src = source_root / frame['source_locator']['extracted_path'] if sha(src) != frame['source_locator']['extracted_sha256']: raise ValueError('Preview source differs from build source') Image.fromarray(rgb(src)).save(target / f'{name}-source.png') raw_ref = f'{name}-source.png' values = {key: clean_numbers(a[i]) for key, a in arrays.items()} valid = {key: clean_numbers(pt(view / item['valid_ref'])[i]) for key, item in c.items() if item['available'] and 'valid_ref' in item} cards.append({'id': frame['sample_id'], 'view': view.relative_to(root).as_posix(), 'rgb': f'{name}-rgb.png', 'overlay': f'{name}-overlay.png' if has_overlay else None, 'source': raw_ref, 'mask': f'{name}-mask.png' if 'segment' in videos else None, 'frame': frame, 'arrays': values, 'valid': valid, 'metainfo': m, 'annotations': {'segment_instances': instances[i] if instances else None, 'object_metainfo': objects}, 'object_points_camera': clean_numbers(objcam) if objcam is not None else None, 'object_points_canonical': clean_numbers(mesh) if mesh is not None else None}) return cards HTML = '''
待人工审核。自动无损校验通过 ≠ 标注语义或几何已获人工确认。只展示本报告列出的抽检样本;每个选中视图展示全部帧。未提供模态及原因在元信息中明确列出。
检查:源图与解码 RGB、左右手、标签颜色、源文件定位、valid、相机参数;有几何时检查 2D 投影和可旋转 3D 点云。绿色为手关键点,黄色为物体。3D 点云仅为显示抽样,完整模型见 data。