File size: 23,169 Bytes
94a4005 6a4018d 94a4005 6a4018d 94a4005 6a4018d 94a4005 6a4018d 94a4005 6a4018d 94a4005 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | #!/usr/bin/env python3
"""Validate all shared frames; render capped samples of every available modality."""
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, selected_indices=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):
rgb_array = next(videos['rgb'])
current_mask = next(videos['segment']) if 'segment' in videos else None
if selected_indices is not None and i not in selected_indices:
continue
name = hashlib.sha256(f'{view.relative_to(root)}/{i}'.encode()).hexdigest()[:20]
image = Image.fromarray(rgb_array)
overlay = image.copy()
if 'segment' in videos:
mask = current_mask
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 = '''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>手物数据预处理检验</title>
<style>body{font:16px system-ui;margin:24px;background:#101724;color:#ecf3ff}button,select,input{font:inherit;padding:7px}h1{font-size:25px}a{color:#7bd5ff}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}img{width:100%;background:#000}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:13px monospace;max-height:420px;overflow:auto}figure{margin:0}figcaption{padding:6px}canvas{background:#162434;max-width:100%;touch-action:none}.warning{padding:14px;background:#493915}details{padding:10px;background:#1c293c;margin:10px 0}label{display:block;margin:10px 0}</style>
<h1>手物数据预处理检验</h1><p class="warning">待人工审核。自动无损校验通过 ≠ 标注语义或几何已获人工确认。只展示本报告列出的抽检样本;全量报告最多展示 192 帧。未提供模态及原因在元信息中明确列出。</p>
<p>检查:源图与解码 RGB、左右手、标签颜色、源文件定位、valid、相机参数;有几何时检查 2D 投影和可旋转 3D 点云。绿色为手关键点,黄色为物体。3D 点云仅为显示抽样,完整模型见 data。</p>
<label>样本 <select id="sample" aria-label="选择检验样本"></select></label><button id="prev">上一帧</button> <button id="next">下一帧</button><span id="counter"></span>
<h2 id="title"></h2><div class="grid"><figure><img id="source" alt="源 RGB"><figcaption>源文件固定解码 RGB</figcaption></figure><figure><img id="rgb" alt="处理后 RGB"><figcaption>shared MKV 解码 RGB</figcaption></figure><figure><img id="overlay" alt="分割或几何叠加"><figcaption>分割 / 手关键点 / 物体叠加</figcaption></figure><figure><img id="mask" alt="语义标签图"><figcaption>标签图:1 左手红;2 右手蓝;3–8 交互物体;9 源背景灰</figcaption></figure></div>
<section id="geometry"><p id="geometry-note"></p><div id="camera-geometry"><h2>相机系 3D(拖动旋转)</h2><canvas id="scene" width="700" height="460" aria-label="手物三维点云"></canvas></div><div id="canonical-geometry"><h2>物体规范坐标系 3D(拖动旋转)</h2><canvas id="canonical" width="700" height="460" aria-label="物体规范三维点云"></canvas></div></section>
<details open><summary>逐帧来源、时间与 split</summary><pre id="frame"></pre></details><details><summary>所有数值标注与有效性</summary><pre id="numbers"></pre></details><details><summary>所有组件 / 缺失原因 / 相机 / 存储与映射</summary><pre id="meta"></pre></details>
<script>const data=__DATA__;const $=x=>document.getElementById(x);let index=0,yaw=0,pitch=0;
data.forEach((d,i)=>{let o=document.createElement('option');o.value=i;o.textContent=d.id;$('sample').append(o)});
function cloud(canvas,points,colors){let ctx=canvas.getContext('2d');ctx.clearRect(0,0,canvas.width,canvas.height);if(!points.length)return;let center=[0,1,2].map(k=>points.reduce((s,p)=>s+p[k],0)/points.length);let q=points.map(p=>p.map((v,k)=>v-center[k]));let scale=180/Math.max(.00001,...q.flat().map(Math.abs));q.forEach((p,i)=>{let x=p[0]*Math.cos(yaw)+p[2]*Math.sin(yaw),z=-p[0]*Math.sin(yaw)+p[2]*Math.cos(yaw),y=p[1]*Math.cos(pitch)-z*Math.sin(pitch);ctx.fillStyle=colors[i];ctx.fillRect(350+x*scale,230+y*scale,3,3)})}
function redraw(){let d=data[index],hand=(d.arrays.keypoints_xyz||[]).flat().filter(p=>p&&p.every(v=>v!==null)),obj=d.object_points_camera||[];cloud($('scene'),obj.concat(hand),obj.map(()=> '#ffd23f').concat(hand.map(()=> '#50ff9f')));let can=d.object_points_canonical||[];cloud($('canonical'),can,can.map(()=> '#ffd23f'))}
function show(){let d=data[index];$('sample').value=index;$('title').textContent=d.id;$('counter').textContent=` ${index+1} / ${data.length}`;for(let k of ['source','rgb','overlay','mask']){let el=$(k);el.parentElement.hidden=!d[k];if(d[k])el.src=d[k];}$('frame').textContent=JSON.stringify(d.frame,null,2);$('numbers').textContent=JSON.stringify({arrays:d.arrays,valid:d.valid,annotations:d.annotations},null,2);$('meta').textContent=JSON.stringify(d.metainfo,null,2);$('geometry').hidden=!d.object_points_camera&&!d.object_points_canonical&&!d.arrays.keypoints_xyz;$('camera-geometry').hidden=!d.object_points_camera&&!d.arrays.keypoints_xyz;$('canonical-geometry').hidden=!d.object_points_canonical;$('geometry-note').textContent=d.object_points_canonical&&!d.object_points_camera?'仅有静态物体模型;缺少内参/位姿,不生成相机系叠加。':'';redraw()}
$('sample').onchange=e=>{index=+e.target.value;show()};$('prev').onclick=()=>{index=(index+data.length-1)%data.length;show()};$('next').onclick=()=>{index=(index+1)%data.length;show()};for(let c of [$('scene'),$('canonical')]){let last=null;c.onpointerdown=e=>{last=[e.clientX,e.clientY];c.setPointerCapture(e.pointerId)};c.onpointerup=()=>last=null;c.onpointermove=e=>{if(last){yaw+=(e.clientX-last[0])*.01;pitch+=(e.clientY-last[1])*.01;last=[e.clientX,e.clientY];redraw()}}}show();</script></html>'''
def sampled_indices(count, wanted, seed):
if wanted >= count:
return set(range(count))
fixed = {0, count - 1, count // 4, count // 2, 3 * count // 4}
rng = random.Random(seed)
remaining = [i for i in range(count) if i not in fixed]
fixed.update(rng.sample(remaining, wanted - len(fixed)))
return fixed
def check_release_versions(root, registry, build, versions):
"""The release directory, every view's metainfo and the build recipe must agree."""
if root.name != registry['release_layout']['directory']:
raise ValueError(f'Release directory {root.name!r} != registry '
f"release_layout.directory {registry['release_layout']['directory']!r}")
if len(versions) != 1:
raise ValueError(f'Mixed schema/release versions across views: {sorted(versions)}')
version, release = next(iter(versions))
if version != registry['schema_version'] or release != registry['release_layout']['release_id']:
raise ValueError(f'Views declare {version}/{release}, registry declares '
f"{registry['schema_version']}/{registry['release_layout']['release_id']}")
for name, digest in sorted(build['recipe']['code_sha256'].items()):
tool = root / 'script' / name
if not tool.is_file() or sha(tool) != digest:
raise ValueError(f'Build recipe digest does not describe this tree: script/{name}')
return version, release
def check_view_coverage(root, build):
"""Every view in the tree must be in the build recipe, and a recipe must cover something.
``validate_release`` walks ``build['views']``, so a recipe that lost a view -- or a release
that carries none -- would validate whatever it happens to list and still write the full
acceptance report under the ordinary name. A check that green-lights a smaller scope than
the release is not an acceptance check.
"""
on_disk = sorted(p.parent.relative_to(root).as_posix()
for p in (root / 'data').glob('*/*/metainfo.json'))
if not on_disk:
raise ValueError('No views found in the release tree; refusing to write an acceptance report')
if sorted(build['views']) != on_disk:
missing = sorted(set(on_disk) - set(build['views']))
extra = sorted(set(build['views']) - set(on_disk))
raise ValueError(f'Build recipe and tree disagree: {len(build["views"])} recipe views, '
f'{len(on_disk)} on disk; missing {missing[:3]}, extra {extra[:3]}')
return len(on_disk)
def validate_release(root, per_stratum=4, seed=20260928, all_views=False, source_root=None,
max_visual_frames=192):
build = read_json(root / 'doc/build.json')
registry = read_json(root / 'doc/schema.json')
results = {}
strata = defaultdict(list)
for relative in build['views']:
m, f = validate_view(root / relative, registry)
results[relative] = (m, f)
strata[(f[0]['source_split'], m['camera_id'])].append(relative)
version, release = check_release_versions(
root, registry, build, {(m['schema_version'], m['release_id']) for m, _ in results.values()})
check_view_coverage(root, build)
rng = random.Random(seed)
chosen = sorted(results) if all_views or build['phase'] == 'pilot' else sorted(
v for s in sorted(strata) for v in rng.sample(strata[s], min(per_stratum, len(strata[s]))))
target = root / 'doc/validation'
target.mkdir(parents=True, exist_ok=True)
# Revalidation invalidates old human review, even if the numeric result stays the same.
(target / 'human_review.json').unlink(missing_ok=True)
for p in target.glob('*.png'):
p.unlink()
cards = []
allocation = {relative: None for relative in chosen}
if not all_views and build['phase'] == 'full' and max_visual_frames:
if max_visual_frames < len(chosen):
raise ValueError('max_visual_frames must cover every selected view')
base, extra = divmod(max_visual_frames, len(chosen))
for position, relative in enumerate(chosen):
count = len(results[relative][1])
wanted = min(count, base + (position < extra))
stable_seed = int.from_bytes(hashlib.sha256(f'{seed}/{relative}'.encode()).digest()[:8], 'big')
allocation[relative] = sampled_indices(count, wanted, stable_seed)
for relative in chosen:
m, f = results[relative]
cards.extend(preview_view(root, root / relative, m, f, target, source_root, allocation[relative]))
payload = json.dumps(cards, ensure_ascii=False, allow_nan=False).replace('<', '\\u003c')
(target / 'index.html').write_text(HTML.replace('__DATA__', payload))
hashes = {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')}
report = {'dataset': build['dataset'], 'phase': build['phase'], 'recipe': build['recipe'],
'schema_version': version, 'release_id': release,
'registry_sha256': sha(root / 'doc/schema.json'),
'automatic_validation_passed': True, 'human_review': 'pending',
'all_views_checked': len(results), 'all_frames_checked': sum(m['num_frames'] for m, _ in results.values()),
'numeric_scope': 'every component, frame, shape, validity, registered schema and exact video decoded hash',
'visual_scope': 'all available modalities; deterministic frame samples from selected views',
'visual_selected_views': chosen, 'visual_sample_ids': [c['id'] for c in cards],
'visual_policy': {'maximum_frames': None if all_views else max_visual_frames,
'selection': 'per selected view: first, last, quartiles, then fixed-seed sample without replacement',
'frame_indices_by_view': {k: sorted(v) if v is not None else 'all' for k, v in allocation.items()}},
'seed': seed, 'file_hashes': hashes, 'limitations': build['limitations']}
(target / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
print(f'Validated {report["all_frames_checked"]} frames; HTML: {target / "index.html"}', flush=True)
return report
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('release', type=Path)
p.add_argument('--per-stratum', type=int, default=4)
p.add_argument('--seed', type=int, default=20260928)
p.add_argument('--all', action='store_true', help='Generate previews for every frame of every view; potentially large')
p.add_argument('--source-root', type=Path, help='Extracted input, to show source RGB alongside shared RGB')
p.add_argument('--max-visual-frames', type=int, default=192,
help='Full-release visual sample cap; automatic validation still checks every frame')
a = p.parse_args()
validate_release(a.release, a.per_stratum, a.seed, a.all, a.source_root, a.max_visual_frames)
|