File size: 5,394 Bytes
da10f80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Validate a portable RGB-only release without the processing stack."""
from pathlib import Path
import sys,json,hashlib,argparse,subprocess
sys.dont_write_bytecode=True
import cv2
import numpy as np
import polars as pl

def validate(root):
    root=Path(root).resolve();sys.path.insert(0,str(root))
    from observation_reader import ObservationDataset,camera_points
    import pyarrow.parquet as pq
    ds=ObservationDataset(root)
    assert ds.info['capture_mode']=='rgb_only' and ds.info['license']=='cc-by-4.0'
    assert ds.episodes
    report={'status':'passed','scope':'Full video decode, displayed PTS, frame identity tables, missing modalities, segment bounds, embedded preview schema and all checksums. No annotation accuracy or model training evaluation.','episodes':[]}
    for key,e in ds.episodes.items():
        mapping=ds.table(key,'frame_mapping');n=e['frame_count']
        assert mapping.height==n and mapping['rgb_frame_index'].to_list()==list(range(n))
        source=mapping['source_frame_index'].to_numpy()
        assert np.all(np.diff(source)==1) and source[0]==e['source']['selection']['first_source_frame'] and source[-1]==e['source']['selection']['last_source_frame']
        ts=mapping['t_s'].to_numpy();assert ts[0]==0 and np.all(np.isfinite(ts)) and np.all(np.diff(ts)>0)
        assert np.max(np.abs(np.diff(mapping['source_pts_s'].to_numpy())-np.diff(ts)))<1e-6
        assert mapping['rgb_decodable'].all()
        probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-show_streams','-show_packets','-of','json',str(root/e['video'])]))
        assert len(probe['streams'])==1
        stream=probe['streams'][0]
        assert stream['codec_name']=='h264' and stream['pix_fmt']=='yuv420p' and stream['color_transfer']=='bt709'
        pts=sorted(float(p['pts_time']) for p in probe['packets'] if 'pts_time' in p and 'D' not in p.get('flags',''))
        assert len(pts)==n and np.max(np.abs(np.array(pts)-mapping['video_pts_s'].to_numpy()))<2e-6
        cap=cv2.VideoCapture(str(root/e['video']));decoded=0
        try:
            while True:
                ok,frame=cap.read()
                if not ok:break
                assert frame.shape==(e['height'],e['width'],3)
                decoded+=1
        finally:cap.release()
        assert decoded==n,(key,decoded,n)
        indices=sorted({0,n//4,n//2,3*n//4,n-1})
        for index in indices:
            frame=ds.frame(key,index)
            assert frame['source_frame_index']==int(source[index]) and frame['timestamp_s']==ts[index]
            assert all(frame[k] is None for k in ('depth_m','depth_valid','confidence','K_rgb','camera_pose_xyzw','sensor_timestamp_s'))
            assert not any(v for k,v in frame['modalities'].items() if k!='rgb')
            try:camera_points(frame)
            except ValueError:pass
            else:raise AssertionError('RGB-only geometry must be unavailable')
        for name in ('hand_pose_raw','hand_pose'):
            if name not in e['signals']:continue
            hand=ds.table(key,name)
            assert all(hand[k].null_count()==hand.height for k in ('z','wx','wy','wz'))
            assert ds.annotations_near(key,name,1e6).height==0
        assert hashlib.file_digest((root/e['video']).open('rb'),'sha256').hexdigest()==e['video_sha256']
        report['episodes'].append({'capture_id':key,'decoded_frames':decoded,'timestamp_rows':n,'random_access_indices':indices,'metric_channels_absent':True})
        print(key,decoded,'decoded frames and timestamps verified',flush=True)
    segments=pl.read_parquet(root/'annotations/action_segments.parquet')
    for row in segments.to_dicts():
        assert row['capture_id'] in ds.episodes
        assert 0<=row['start_s']<row['end_s']<=ds.episodes[row['capture_id']]['duration_s']
        assert row['annotation_source']=='assistant_visual_review' and row['boundary_precision_s']==2.0
    catalog=pq.read_table(root/'data/episodes.parquet')
    features=json.loads(catalog.schema.metadata[b'huggingface'])['info']['features']
    assert features['video']['_type']=='Video' and catalog.num_rows==len(ds.episodes)
    for row in catalog.to_pylist():
        assert row['video']['bytes']==(root/ds.episodes[row['capture_id']]['preview']).read_bytes()
    seen=set()
    for line in (root/'checksums.sha256').read_text().splitlines():
        expected,rel=line.split('  ',1);target=(root/rel).resolve()
        assert target.is_relative_to(root) and rel not in seen
        assert hashlib.file_digest(target.open('rb'),'sha256').hexdigest()==expected,rel
        seen.add(rel)
    actual={p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file() and p.name!='checksums.sha256' and '__pycache__' not in p.parts and '.cache' not in p.parts}
    assert actual==seen,(actual-seen,seen-actual)
    report.update(verified_artifact_hashes=len(seen),action_segments=segments.height,huggingface_video_rows=catalog.num_rows,total_decoded_frames=sum(e['decoded_frames'] for e in report['episodes']))
    return report

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('root',type=Path);p.add_argument('--write-report',action='store_true');args=p.parse_args()
    report=validate(args.root)
    if args.write_report:(args.root/'validation.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
    print(json.dumps(report,indent=2))