File size: 32,711 Bytes
94a4005
6a4018d
 
94a4005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a4018d
 
 
 
 
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
#!/usr/bin/env python3
"""EgoHOS -> the hand-warehouse layout declared by schema.json.
Legacy OakInk helpers are not a supported v1.1 conversion path."""
import argparse
from collections import defaultdict
from functools import lru_cache
import hashlib
import json
import os
import pickle
import random
import re
import shlex
import shutil
import sys
from pathlib import Path

import numpy as np
from PIL import Image
import torch

from acquire import sha, safe_path
from media import encode

HERE = Path(__file__).resolve().parent
# The registry next to this script is the single source of the release version: the
# metainfo written here and the upload target are derived from it, not hard-coded.
REGISTRY = json.loads((HERE / 'schema.json').read_text())
SCHEMA_VERSION = REGISTRY['schema_version']
RELEASE_ID = REGISTRY['release_layout']['release_id']
CAMS = ['north_east_color', 'south_east_color', 'north_west_color', 'south_west_color']
LABELS = ['background', 'left_hand', 'right_hand', 'first_order_left', 'first_order_right',
          'first_order_both', 'second_order_left', 'second_order_right', 'second_order_both']


def dump(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False) + '\n')


def jsonl(path, rows):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open('w') as f:
        for row in rows:
            f.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n')


def load(path):
    return json.loads(path.read_text())


def tensor(root, ref, value):
    p = root / ref
    p.parent.mkdir(parents=True, exist_ok=True)
    torch.save(torch.from_numpy(np.asarray(value).copy()).cpu(), p)


def component(schema, ref, axes, valid, vaxes, source, method, kind='format_conversion', **extra):
    return {'available': True, 'schema_id': schema, 'data_ref': ref, 'axes': axes,
            'valid_ref': valid, 'valid_axes': vaxes, 'provenance': {'kind': kind, 'method': method},
            'source_locator': source, **extra}


def source_index(root):
    path = root / 'sources.jsonl'
    if not path.exists():
        raise ValueError('Missing sources.jsonl; run acquire.py first or create a provenance inventory as documented')
    result = {}
    for line in path.read_text().splitlines():
        row = json.loads(line)
        if row['path'] in result:
            raise ValueError(f'Duplicate source path: {row["path"]}')
        safe_path(root, row['path'])
        result[row['path']] = row
    return result


@lru_cache(maxsize=64)
def source_digest(path, size, mtime_ns):
    return sha(path)


def locator(path, root, index):
    key = path.relative_to(root).as_posix()
    row = index.get(key)
    if row is None:
        raise ValueError(f'Missing provenance for {key}; add it to sources.jsonl')
    stat = path.stat()
    if source_digest(path, stat.st_size, stat.st_mtime_ns) != row['sha256']:
        raise ValueError(f'Source changed: {path}')
    return dict(row['source_locator'], extracted_path=key, extracted_sha256=row['sha256'])


@lru_cache(maxsize=128)
def find_one(root, name):
    matches = [p for p in root.rglob(name) if p.is_dir()]
    if len(matches) != 1:
        raise ValueError(f'Expected one {name}/ directory, found {len(matches)}')
    return matches[0]


def inventory_ego(root):
    rows = []
    for split in ('train', 'val', 'test_indomain', 'test_outdomain'):
        d = find_one(root, split)
        images = sorted(p for p in (d / 'image').iterdir() if p.suffix.lower() in ('.jpg', '.jpeg', '.png'))
        for p in images:
            label = d / 'label' / (p.stem + '.png')
            if not label.is_file():
                raise ValueError(f'Image without segmentation: {p}')
            rows.append({'image': p, 'mask': label, 'split': 'test' if split.startswith('test_') else split,
                         'source_split': split, 'camera_id': 'ego', 'sample_id': split + '/' + p.name})
    if not rows:
        raise ValueError('No EgoHOS images')
    return rows


def inventory_oak(root, annotations, split_scheme):
    stream = find_one(root, 'stream_release_v2')
    rows = []
    if annotations:
        info = load(annotations / 'seq_all.json')
        splits = {}
        for split in ('train', 'val', 'test'):
            relative = (f'split_train_val/{split_scheme}/example_split_{split}.json' if split != 'test'
                        else f'split/{split_scheme}/seq_test.json')
            file = annotations / relative
            if not file.is_file():
                raise ValueError(f'Official split missing: {file}')
            for x in load(file):
                key = tuple(x)
                if key in splits:
                    raise ValueError('Conflicting official splits')
                splits[key] = (split, relative)
        for x in info:
            seq, subject, frame, camera = x
            if camera not in range(4) or subject not in (0, 1):
                raise ValueError(f'Unexpected official sample key: {x}')
            name = '__'.join(map(str, x)).replace('/', '__')
            split, split_ref = splits.get(tuple(x), ('unknown', None))
            rows.append({'image': stream / seq / f'{CAMS[camera]}_{frame}.png',
                'camera_id': CAMS[camera], 'sequence': seq, 'source_frame_id': str(frame),
                'sample_id': name, 'subject': subject, 'split': split, 'source_split': split,
                'annotation_key': name, 'split_ref': split_ref})
    else:
        for p in sorted(stream.rglob('*.png')):
            m = re.fullmatch(r'(north_east|south_east|north_west|south_west)_color_(\d+)', p.stem)
            if not m or len(p.relative_to(stream).parts) != 3:
                raise ValueError(f'Unexpected OakInk image path: {p}')
            rows.append({'image': p, 'camera_id': m[1] + '_color',
                'sequence': p.parent.relative_to(stream).as_posix(), 'source_frame_id': m[2],
                'sample_id': p.relative_to(stream).as_posix(), 'subject': None,
                'split': 'unknown', 'source_split': 'unknown'})
    if not rows:
        raise ValueError('No OakInk images')
    return rows


def select_rows(rows, dataset, phase, count, seed):
    if phase == 'full':
        return rows
    strata = defaultdict(list)
    for r in rows:
        strata[r['source_split'] if dataset == 'EgoHOS' else (r['split'], r['camera_id'])].append(r)
    rng = random.Random(seed)
    return [r for key in sorted(strata) for r in rng.sample(strata[key], min(count, len(strata[key])))]


def groups(rows, dataset, chunk):
    buckets = defaultdict(list)
    for r in rows:
        with Image.open(r['image']) as im:
            size = im.size
        if dataset == 'EgoHOS':
            key = (r['source_split'], r['camera_id'], size)
        else:
            # Source frame-number intervals keep cameras under a common sequence namespace.
            key = (r['sequence'], r['subject'], int(r['source_frame_id']) // chunk, r['camera_id'], size)
        buckets[key].append(r)
    result = []
    for key in sorted(buckets, key=str):
        batch = sorted(buckets[key], key=lambda r: (int(r.get('source_frame_id', 0)), r['sample_id']))
        if dataset == 'EgoHOS':
            for start in range(0, len(batch), chunk):
                sequence = f'{key[0]}_{key[2][0]}x{key[2][1]}_{start//chunk:06d}'
                result.append((sequence, key[1], key[2], batch[start:start+chunk]))
        else:
            name = key[0].replace('/', '__')
            person = '' if key[1] is None else f'__person{key[1]}'
            sequence = f'{name}{person}__window{key[2]:06d}_{key[4][0]}x{key[4][1]}'
            result.append((sequence, key[3], key[4], batch))
    return result


def read_pickle(path):
    # Only called with explicit --trust-pickle for source annotation archives.
    with path.open('rb') as f:
        return pickle.load(f)


def numeric(value, shape, name):
    if isinstance(value, torch.Tensor):
        value = value.detach().cpu().numpy()
    a = np.asarray(value, dtype=np.float32)
    if a.shape != shape or not np.isfinite(a).all():
        raise ValueError(f'{name}: expected finite {shape}, got {a.shape}')
    return a


def se3(value, name):
    a = numeric(value, (4, 4), name)
    if not (np.allclose(a[3], [0, 0, 0, 1], atol=1e-5) and
            np.allclose(a[:3, :3].T @ a[:3, :3], np.eye(3), atol=1e-4) and
            np.isclose(np.linalg.det(a[:3, :3]), 1, atol=1e-4)):
        raise ValueError(f'Invalid rigid transform: {name}')
    return a


def copy_mesh(source, dst, root, index):
    lines = source.read_text().splitlines()
    materials = [n for line in lines if line.startswith('mtllib ') for n in shlex.split(line)[1:]]
    missing_materials = [n for n in materials if not safe_path(source.parent, n).is_file()]
    if missing_materials and len(missing_materials) != len(materials):
        raise ValueError(f'Partly missing OBJ materials need review: {source}: {missing_materials}')
    # Official OakInk loader uses skip_materials=True; dangling source references are documented.
    if missing_materials:
        lines = [line for line in lines if not line.startswith(('mtllib ', 'usemtl '))]
    vertices = np.array([[float(v) for v in line.split()[1:4]] for line in lines if line.startswith('v ')])
    if vertices.ndim != 2 or vertices.shape[1] != 3 or not np.isfinite(vertices).all():
        raise ValueError(f'Invalid OBJ: {source}')
    center = (vertices.min(0) + vertices.max(0)) / 2
    shifted = iter(vertices - center)
    output = []
    for line in lines:
        if line.startswith('v '):
            v = next(shifted)
            line = 'v ' + ' '.join(format(x, '.12g') for x in v) + (' ' + ' '.join(line.split()[4:]) if len(line.split()) > 4 else '')
        output.append(line)
    dst.parent.mkdir(parents=True, exist_ok=True)
    dst.write_text('\n'.join(output) + '\n')
    sources = [locator(source, root, index)]
    for line in lines:
        if line.startswith('mtllib '):
            for name in shlex.split(line)[1:]:
                mtl = safe_path(source.parent, name)
                dest = safe_path(dst.parent, name)
                dest.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(mtl, dest)
                sources.append(locator(mtl, root, index))
                for entry in mtl.read_text().splitlines():
                    if entry.strip().startswith(('map_', 'bump ', 'disp ', 'decal ', 'norm ')):
                        texture = shlex.split(entry)[-1]
                        src = safe_path(mtl.parent, texture)
                        to = safe_path(dest.parent, texture)
                        to.parent.mkdir(parents=True, exist_ok=True)
                        shutil.copy2(src, to)
                        sources.append(locator(src, root, index))
    return center.tolist(), sources, missing_materials


def oak_object_asset(view, rows, meta, root, index):
    objid = rows[0]['sequence'].split('/')[0].split('_')[0]
    mesh = find_one(root, 'obj') / (objid + '.obj')
    ref = f'annotation/object/{objid}/assets/{objid}.obj'
    center, sources, missing_materials = copy_mesh(mesh, view / ref, root, index)
    meta['components']['object_mesh'] = {'available': True, 'schema_id': 'mesh/obj/v1', 'data_ref': ref,
        'axes': [], 'valid': True, 'unit': 'm', 'source_locator': sources,
        'provenance': {'kind': 'format_conversion', 'method': 'subtract (min(vertices)+max(vertices))/2, official oikit load_object; remove dangling material bindings only if all referenced MTL files are absent in source',
                       'subtracted_center': center, 'source_missing_materials': missing_materials}}
    dump(view / f'annotation/object/{objid}/metainfo.json', {'object_id': objid, 'identity_scope': 'sequence',
        'scope_id': meta['sequence_id'], 'source_object_id': objid, 'has_model': True,
        'mesh_ref': ref, 'source_locator': sources, 'association_basis': 'official sequence prefix object ID'})


def oak_geometry(view, rows, frames, meta, root, index, anno, split_scheme):
    count = len(rows)
    keys = [r['annotation_key'] for r in rows]
    arrays = {'intrinsic': [], 'extrinsic': [], 'xyz': [], 'pose': []}
    objid = rows[0]['sequence'].split('/')[0].split('_')[0]
    for i, key in enumerate(keys):
        sources = {}
        for name in ('cam_intr', 'hand_j', 'general_info', 'obj_transf'):
            p = anno / name / (key + '.pkl')
            # Some documentation spells this directory obj_trasnf; code uses obj_transf.
            if name == 'obj_transf' and not p.exists():
                p = anno / 'obj_trasnf' / (key + '.pkl')
            sources[name] = locator(p, root, index)
            sources[name]['record'] = key
            value = read_pickle(p)
            if name == 'cam_intr':
                k = numeric(value, (3, 3), name)
                if not np.allclose(k[2], [0, 0, 1]) or min(k[0, 0], k[1, 1]) <= 0:
                    raise ValueError('Invalid pinhole K')
                arrays['intrinsic'].append(k)
            elif name == 'hand_j':
                arrays['xyz'].append(numeric(value, (21, 3), name))
            elif name == 'obj_transf':
                arrays['pose'].append(se3(value, name))
            else:
                arrays['extrinsic'].append(se3(value['cam_extr'], 'T_camera_from_world'))
        frames[i]['annotation_sources'] = sources
        frames[i]['source_subject_flag'] = rows[i]['subject']
        if rows[i]['split_ref']:
            frames[i]['split_source_locator'] = locator(anno / rows[i]['split_ref'], root, index)
        frames[i]['annotation_matches'] = {name: {'source_frame_id': key, 'source_timestamp_ns': None,
            'clock_domain': None, 'match_method': 'index_map', 'delta_ns': None} for name in sources}
    arrays = {k: np.stack(v) for k, v in arrays.items()}
    xyz = np.full((count, 2, 21, 3), np.nan, np.float32)
    xyz[:, 1] = arrays['xyz']
    valid = np.zeros((count, 2, 21), bool)
    valid[:, 1] = True
    uv = np.full((count, 2, 21, 2), np.nan, np.float32)
    homogeneous = np.einsum('tij,tkj->tki', arrays['intrinsic'], arrays['xyz'])
    projectable = homogeneous[:, :, 2] > 0
    uv[:, 1][projectable] = (homogeneous[:, :, :2][projectable] / homogeneous[:, :, 2:][projectable])
    uv_valid = valid.copy()
    uv_valid[:, 1] &= projectable
    common_source = {'file': 'camera/frames.jsonl', 'fields': ['annotation_sources'], 'records': 'all frame_index rows'}
    policy = {'rule': 'source present AND finite/numerical checks; no additional official QA input',
              'scope': 'per joint for keypoints; per frame for camera/pose',
              'official_split_is_not_visibility': True, 'local_excluded_frame_indices': []}
    specs = [('intrinsic', 'camera/pinhole/v1', 'camera/intrinsic.pt', arrays['intrinsic'], np.ones(count, bool), ['T', 3, 3]),
             ('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', arrays['extrinsic'], np.ones(count, bool), ['T', 4, 4]),
             ('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', xyz, valid, ['T', 'hand', 'keypoint', 'xyz']),
             ('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', uv, uv_valid, ['T', 'hand', 'keypoint', 'uv']),
             ('object_pose', 'object/rigid/v1', f'annotation/object/{objid}/pose.pt', arrays['pose'], np.ones(count, bool), ['T', 4, 4])]
    for name, schema, ref, data, ok, axes in specs:
        vref = ref.replace('.pt', '_valid.pt')
        tensor(view, ref, data)
        tensor(view, vref, ok)
        extra = {'valid_policy': policy}
        if name.startswith('keypoints'):
            extra.update(keypoint_schema='mano21/v1', coordinate_frame='camera',
                         unit='pixel' if name.endswith('uv') else 'm')
        if name in ('extrinsic', 'object_pose'):
            extra.update(unit='m', convention='T_camera_from_world' if name == 'extrinsic' else 'T_camera_from_object')
        meta['components'][name] = component(schema, ref, axes, vref, ['T', 'hand', 'keypoint'] if ok.ndim == 3 else ['T'],
            common_source, 'K @ official camera-space hand_j; positive Z only' if name.endswith('uv') else 'official per-sample array, float32; right-hand slot 1',
            kind='derived' if name.endswith('uv') else 'format_conversion', **extra)
    oak_object_asset(view, rows, meta, root, index)
    meta['camera'].update(model='pinhole', schema_id='camera/pinhole/v1')
    meta.update(split_scheme=split_scheme, split_source_locator={'file': 'camera/frames.jsonl', 'field': 'split_source_locator'})


def build_view(out, seq, cam, size, rows, args, index):
    view = out / 'data' / seq / cam
    view.mkdir(parents=True)
    frames = []
    for i, r in enumerate(rows):
        src = locator(r['image'], args.input, index)
        frames.append({'frame_index': i, 'sample_id': r['sample_id'], 'source_frame_id': r.get('source_frame_id', r['image'].name),
            'timestamp_ns': None, 'clock_domain': None, 'source_locator': src,
            'split': r['split'], 'source_split': r['source_split']})
        if 'mask' in r:
            frames[-1]['mask_source_locator'] = locator(r['mask'], args.input, index)
    source_ref = {'file': 'camera/frames.jsonl', 'field': 'source_locator', 'records': 'all frame_index rows'}
    count = len(rows)
    storage, proof = encode([r['image'] for r in rows], view / 'observation/rgb.mkv')
    tensor(view, 'observation/rgb_valid.pt', np.ones(count, bool))
    comps = {'rgb': component('rgb/uint8/v1', 'observation/rgb.mkv', ['T', 'height', 'width', 'RGB'],
        'observation/rgb_valid.pt', ['T'], source_ref, 'exact source JPEG remux or exact RGB round-trip re-encoding', storage=storage)}
    ego = args.dataset == 'EgoHOS'
    meta = {'schema_version': SCHEMA_VERSION, 'dataset_id': args.dataset, 'release_id': RELEASE_ID,
        'sequence_id': seq, 'camera_id': cam, 'sample_type': 'image' if ego else 'video',
        'num_frames': count, 'hand_slots': ['left', 'right'], 'view_type': 'ego' if ego else 'exo',
        'split': rows[0]['split'] if len({r['split'] for r in rows}) == 1 else 'unknown',
        'sampling': {'type': ('single' if count == 1 else 'independent') if ego else 'sparse',
            'source_fps': None, 'frames_ref': 'camera/frames.jsonl', 'strategy': args.phase,
            'seed': args.seed, 'timestamps': 'unknown; no timestamps inferred from filenames or MKV PTS'},
        'camera': {'model': 'unknown', 'schema_id': None, 'image_size': list(size)}, 'components': comps}
    proofs = {'rgb': proof}
    missing = {'depth': 'not provided by selected source image release',
        'mano': 'not exported: model profile/flat-hand-mean/translation conversion not empirically verified',
        'visibility': 'no independent source visibility input; never inferred from valid',
        'contact': 'no verified per-entity or vertex contact annotations in selected input'}
    if ego:
        meta.update(split_scheme='EgoHOS-official-four-directories', split_source_locator=source_ref)
        storage, proofs['segment'] = encode([r['mask'] for r in rows], view / 'annotation/segment/mask.mkv', labels=True)
        tensor(view, 'annotation/segment/mask_valid.pt', np.ones(count, bool))
        labels = [{'mask_value': 9 if i == 0 else i, 'category_id': name,
                   'entity_id': 'hand_left' if i == 1 else 'hand_right' if i == 2 else None,
                   'part_id': None, 'source_instance_id': None, 'source_attributes': {'source_class_id': i}}
                  for i, name in enumerate(LABELS)]
        jsonl(view / 'annotation/segment/instances.jsonl', [{'frame_index': i, 'labels': labels} for i in range(count)])
        comps['segment'] = component('segment/uint16_labels/v1', 'annotation/segment/mask.mkv', ['T', 'height', 'width'],
            'annotation/segment/mask_valid.pt', ['T'], {'file': 'camera/frames.jsonl', 'field': 'mask_source_locator'},
            'source 0 background -> 9; 1..8 unchanged; exact uint16 round-trip',
            storage=storage, segmentation_type='semantic', mapping_ref='annotation/segment/instances.jsonl',
            coverage={'kind': 'partial', 'meaning': 'hands and selected interacting object categories; background is source task background, not exhaustive object annotation'},
            valid_policy={'rule': 'paired source label exists, shape and integer categories verified; no additional official QA supplied', 'local_excluded_frame_indices': []})
        missing.update(intrinsic='source calibration absent', extrinsic='source calibration absent',
                       keypoints='source keypoints absent', object='semantic classes do not establish instance identity/mesh/pose',
                       contact='raw package lacks contact/; interaction-order categories are not per-entity contact labels')
    elif args.annotations:
        oak_geometry(view, rows, frames, meta, args.input, index, args.annotations, args.split_scheme)
    else:
        missing.update(intrinsic='anno_v2_1.zip missing', extrinsic='anno_v2_1.zip missing',
            keypoints='anno_v2_1.zip missing', object_pose='anno_v2_1.zip missing; canonical mesh does not establish camera-space pose')
        if args.object_assets_present:
            oak_object_asset(view, rows, meta, args.input, index)
        else:
            missing['object_mesh'] = 'image/obj.zip exists upstream but has not been downloaded/extracted into this input'
        meta['split_reason'] = 'official split files are in missing anno_v2_1.zip; unknown is not a new split'
    for name, reason in missing.items():
        comps[name] = {'available': False, 'reason': reason}
    jsonl(view / 'camera/frames.jsonl', frames)
    dump(view / 'metainfo.json', meta)
    dump(view / 'encoding_validation.json', proofs)
    return view.relative_to(out).as_posix()


def recipe(args):
    names = ['preprocess.py', 'media.py', 'validate.py', 'acquire.py', 'schema.json', 'CONTRACT.md']
    return {'dataset': args.dataset, 'chunk': args.chunk, 'seed': args.seed,
            'annotations': bool(args.annotations), 'split_scheme': args.split_scheme,
            'code_sha256': {n: sha(HERE / n) for n in names}}


def approve(root, reviewer):
    from validate import check_inventory
    report = root / 'doc/validation/report.json'
    d = load(report)
    check_inventory(root, d['file_hashes'])
    if not reviewer.strip() or not d['automatic_validation_passed']:
        raise ValueError('Reviewer and passing automatic checks required')
    # A human runs this only AFTER viewing the HTML. It is a record, not automatic approval.
    dump(root / 'doc/validation/human_review.json', {'reviewer': reviewer, 'phase': d['phase'],
        'report_sha256': sha(report), 'recipe': d['recipe'], 'approved': True,
        'statement': 'I inspected the listed HTML sample IDs and accept the documented scope and limitations.'})


def require_review(root):
    from validate import check_inventory
    report = root / 'doc/validation/report.json'
    reviewed = load(root / 'doc/validation/human_review.json')
    if not reviewed.get('approved') or reviewed['report_sha256'] != sha(report):
        raise ValueError('Missing/stale human review; inspect HTML and run approve')
    result = load(report)
    check_inventory(root, result['file_hashes'])
    return result


def run(args):
    if args.dataset != "EgoHOS":
        raise ValueError("This v1.1 builder supports EgoHOS only; OakInk numeric bundles are not adapted here")
    if args.dataset == 'OakInk-v1' and not args.annotations and not args.allow_rgb_only:
        raise ValueError('OakInk annotations absent. Supply --annotations + --trust-pickle, or explicitly select --allow-rgb-only (limited scope).')
    if args.annotations and (not args.trust_pickle or not args.annotations.resolve().is_relative_to(args.input.resolve())):
        raise ValueError('--annotations must be under --input and requires --trust-pickle; pickle can execute code')
    if args.out.exists():
        raise ValueError('Output exists; choose a fresh directory. Incomplete output is never reused as a release.')
    expected = recipe(args)
    if args.phase == 'full':
        if not args.pilot:
            raise ValueError('Full processing requires --pilot with a human review')
        reviewed = require_review(args.pilot)
        if reviewed['phase'] != 'pilot' or reviewed['recipe'] != expected:
            raise ValueError('Pilot recipe does not match; re-run and review pilot after code/config changes')
        acquisition = args.input / 'acquisition.json'
        if not acquisition.exists() or load(acquisition).get('command') != 'extract' or load(acquisition).get('dataset') != args.dataset:
            raise ValueError('Full processing requires complete, verified acquire.py extract input, not a partial pilot download')
    index = source_index(args.input)
    args.object_assets_present = any(p.is_dir() for p in args.input.rglob('obj')) if args.dataset == 'OakInk-v1' else False
    if args.phase == 'full':
        for pf in (args.pilot / 'data').glob('*/*/camera/frames.jsonl'):
            for line in pf.read_text().splitlines():
                f = json.loads(line)
                for field in ('source_locator', 'mask_source_locator'):
                    if field in f:
                        old = f[field]
                        current = index.get(old['extracted_path'])
                        if current is None or current['sha256'] != old['extracted_sha256']:
                            raise ValueError('Full input differs from reviewed pilot source samples')
    rows = inventory_ego(args.input) if args.dataset == 'EgoHOS' else inventory_oak(args.input, args.annotations, args.split_scheme)
    if args.phase == 'full' and args.dataset == 'EgoHOS':
        expected_counts = dict(train=8993, val=1124, test_indomain=1126, test_outdomain=500)
        actual_counts = {s: sum(r['source_split'] == s for r in rows) for s in expected_counts}
        if actual_counts != expected_counts:
            raise ValueError(f'Incomplete/wrong EgoHOS full inventory: {actual_counts}; expected {expected_counts}')
    ids = [r['sample_id'] for r in rows]
    if len(set(ids)) != len(ids):
        raise ValueError('Duplicate sample IDs')
    selected = select_rows(rows, args.dataset, args.phase, args.per_stratum, args.seed)
    plan = groups(selected, args.dataset, args.chunk)
    raw_bytes = sum(r['image'].stat().st_size for r in selected)
    # Conservative preflight, then check again before each view; no claim of exact compression ratio.
    estimated = max(raw_bytes * 4, max(w*h*len(rs)*8 for _, _, (w, h), rs in plan)) + 1024**3
    args.out.parent.mkdir(parents=True, exist_ok=True)
    if shutil.disk_usage(args.out.parent).free < estimated:
        raise ValueError(f'Estimated working/output space {estimated/1e9:.1f} GB exceeds free space')
    args.out.mkdir()
    (args.out / 'script').mkdir()
    (args.out / 'doc').mkdir()
    for p in HERE.glob('*.py'):
        shutil.copy2(p, args.out / 'script' / p.name)
    for name in ['schema.json', 'CONTRACT.md', 'requirements.txt', 'README.md',
                 'EgoHOS_DATA_MAPPING.md', 'OakInk-v1_DATA_MAPPING.md']:
        shutil.copy2(HERE / name, args.out / 'script' / name)
    shutil.copytree(HERE / 'source_evidence', args.out / 'script/source_evidence')
    for name in ['schema.json', 'CONTRACT.md']:
        shutil.copy2(HERE / name, args.out / 'doc' / name)
    mapping = HERE / f'{args.dataset}_DATA_MAPPING.md'
    for name in ['DATA_MAPPING.md', 'RAW_TO_SHARED.md']:
        shutil.copy2(mapping, args.out / 'doc' / name)
    shutil.copy2(HERE / 'README.md', args.out / 'doc/RUNBOOK.md')
    views = []
    for i, (seq, cam, size, batch) in enumerate(plan):
        if shutil.disk_usage(args.out).free < size[0]*size[1]*len(batch)*8 + 512*1024**2:
            raise RuntimeError('Low disk; stopped before next view, output remains incomplete')
        views.append(build_view(args.out, seq, cam, size, batch, args, index))
        print(f'{i+1}/{len(plan)} {seq}/{cam} T={len(batch)}', flush=True)
    manifest = {'dataset': args.dataset, 'phase': args.phase, 'recipe': expected,
        'inventory_samples': len(rows), 'selected_samples': len(selected), 'views': views,
        'input_sources_sha256': sha(args.input / 'sources.jsonl'),
        'sample_selection': {'seed': args.seed, 'per_stratum': args.per_stratum, 'pilot_strata': 'official source split or split x camera'},
        'source_inventory': {'sample_ids_sha256': hashlib.sha256('\n'.join(sorted(ids)).encode()).hexdigest()},
        'human_status': 'pending', 'command': sys.argv,
        'limitations': ['OakInk MANO conversion not implemented until model-profile and translation parity verified',
                       'OakInk-Shape/OakBase excluded: object-space grasp/knowledge assets are not synchronized camera observations',
                       'No source visibility/contact guessed from geometry or masks']}
    if args.phase == 'full':
        shutil.copy2(args.pilot / 'doc/validation/human_review.json', args.out / 'doc/pilot_human_review.json')
    dump(args.out / 'doc/build.json', manifest)
    from validate import validate_release
    validate_release(args.out, args.per_stratum, args.seed, source_root=args.input)


def main():
    p = argparse.ArgumentParser(description=__doc__)
    sub = p.add_subparsers(dest='command', required=True)
    b = sub.add_parser('build')
    b.add_argument('--dataset', choices=['EgoHOS', 'OakInk-v1'], required=True)
    b.add_argument('--input', type=Path, required=True)
    b.add_argument('--out', type=Path, required=True)
    b.add_argument('--phase', choices=['pilot', 'full'], default='pilot')
    b.add_argument('--pilot', type=Path)
    b.add_argument('--chunk', type=int, default=128)
    b.add_argument('--per-stratum', type=int, default=4)
    b.add_argument('--seed', type=int, default=20260928)
    b.add_argument('--annotations', type=Path)
    b.add_argument('--split-scheme', choices=['split0', 'split1', 'split2', 'split0_ho'], default='split0')
    b.add_argument('--trust-pickle', action='store_true')
    b.add_argument('--allow-rgb-only', action='store_true')
    a = sub.add_parser('approve', help='Human review record; never run automatically')
    a.add_argument('--release', type=Path, required=True)
    a.add_argument('--reviewer', required=True)
    u = sub.add_parser('upload', help='Upload reviewed FULL release to the requested raw repository')
    u.add_argument('--release', type=Path, required=True)
    args = p.parse_args()
    if args.command == 'build':
        if args.chunk < 1 or args.per_stratum < 1:
            p.error('chunk and per-stratum must be positive')
        run(args)
    elif args.command == 'approve':
        approve(args.release, args.reviewer)
    else:
        from validate import check_inventory
        d = load(args.release / 'doc/validation/report.json')
        if d['dataset'] != 'EgoHOS':
            raise ValueError('This v1.1 uploader supports EgoHOS only')
        d = require_review(args.release)
        if d['phase'] != 'full':
            raise ValueError(f'Pilot releases cannot be uploaded as {RELEASE_ID}')
        check_inventory(args.release, d['file_hashes'])
        from huggingface_hub import HfApi
        target = f'{d["dataset"]}/{RELEASE_ID}'
        api = HfApi()
        # Refuse to merge into an existing release with stale files.
        existing = api.list_repo_files('ParityLab/Hand-Datasets-Raw', repo_type='dataset')
        if any(x.startswith(target + '/') for x in existing):
            raise ValueError(f'Remote {target} already exists; publish a new version or review replacement separately')
        from huggingface_hub import CommitOperationAdd
        files = sorted((p for p in args.release.rglob('*') if p.is_file() and '__pycache__' not in p.parts),
                       key=lambda p: (p.relative_to(args.release).parts[0] == 'doc', p.as_posix()))
        # Bounded commits avoid a single enormous commit; publish build/review documents last.
        for start in range(0, len(files), 128):
            operations = [CommitOperationAdd(path_in_repo=target + '/' + f.relative_to(args.release).as_posix(),
                                              path_or_fileobj=f) for f in files[start:start+128]]
            result = api.create_commit(repo_id='ParityLab/Hand-Datasets-Raw', repo_type='dataset',
                operations=operations, commit_message=f'Add reviewed {target} files {start+1}-{min(start+128, len(files))}')
            print(result, flush=True)


if __name__ == '__main__':
    main()