"""Minimal output bookkeeping and representative-read checks, not a source audit.""" import argparse import json from pathlib import Path import av import numpy as np import pandas as pd import pyarrow.parquet as pq def check(root, source=None): mapping = json.loads((root / 'reports/episode_mapping.json').read_text(encoding='utf-8')) summary = json.loads((root / 'reports/summary.json').read_text(encoding='utf-8')) source_ids = [(x['source_session'], x['source_episode_index']) for x in mapping] assert len(source_ids) == len(set(source_ids)) == summary['total_episodes'] labels = json.loads((root / 'reports/task_labels.json').read_text(encoding='utf-8')) label_lookup = {(e['source_session'], e['source_episode_index']): e for e in labels['episodes']} assert set(source_ids) == set(label_lookup) assert {g['task_slug'] for g in summary['datasets']} == set(labels['tasks']) originals, source_infos, video_mapping = {}, {}, {} if source: manifest = json.loads((source / 'dataset_manifest.json').read_text(encoding='utf-8')) for item in manifest['datasets']: name = item['name'] source_infos[name] = json.loads((source / name / 'meta/info.json').read_text(encoding='utf-8')) for ep in pq.read_table(source / name / 'meta/episodes/chunk-000/file-000.parquet').to_pylist(): originals[(name, ep['episode_index'])] = ep assert set(source_ids) == set(originals) result = {'checks': [], 'checksum_audit': False, 'source_value_audit': False, 'exhaustive_video_decode': False, 'official_lerobot_loader_test': False} for group in summary['datasets']: dataset = root / group['root'] info = json.loads((dataset / 'meta/info.json').read_text()) episodes = pq.read_table(dataset / 'meta/episodes/chunk-000/file-000.parquet').to_pylist() data = pq.read_table(dataset / 'data/chunk-000/file-000.parquet') task_table = pd.read_parquet(dataset / 'meta/tasks.parquet') assert len(task_table) == info['total_tasks'] == 1 assert task_table.iloc[0]['task_index'] == 0 instruction = task_table.index[0] assert instruction == labels['tasks'][group['task_slug']]['instruction_en'] assert data.num_rows == info['total_frames'] == group['frames'] assert len(episodes) == info['total_episodes'] == group['episodes'] cameras = [k for k, v in info['features'].items() if v['dtype'] == 'video'] cursor = 0 for index, ep in enumerate(episodes): assert ep['episode_index'] == index assert ep['tasks'] == [instruction] assert ep['dataset_from_index'] == cursor cursor += ep['length'] assert ep['dataset_to_index'] == cursor selected = data.slice(ep['dataset_from_index'], ep['length']) # Bookkeeping created by this merger, not the raw action/state values. assert np.all(np.asarray(selected['episode_index']) == index) assert np.all(np.asarray(selected['task_index']) == 0) assert np.array_equal(np.asarray(selected['index']), np.arange(ep['dataset_from_index'], cursor)) source_mapping = next(m for m in mapping if m['destination_root'] == group['root'] and m['destination_episode_index'] == index) assert source_mapping['length'] == ep['length'] original_key = (source_mapping['source_session'], source_mapping['source_episode_index']) assert source_mapping['task_slug'] == label_lookup[original_key]['task_slug'] == group['task_slug'] for camera in cameras: path = dataset / info['video_path'].format( video_key=camera, chunk_index=ep[f'videos/{camera}/chunk_index'], file_index=ep[f'videos/{camera}/file_index']) assert path.is_file() start = ep[f'videos/{camera}/from_timestamp'] stop = ep[f'videos/{camera}/to_timestamp'] assert start >= 0 and stop > start assert abs((stop-start) - ep['length']/info['fps']) < 1e-5 if source: original = originals[original_key] assert ep['length'] == original['length'] assert start == original[f'videos/{camera}/from_timestamp'] assert stop == original[f'videos/{camera}/to_timestamp'] source_info = source_infos[original_key[0]] old_video = Path(original_key[0]) / source_info['video_path'].format( video_key=camera, chunk_index=original[f'videos/{camera}/chunk_index'], file_index=original[f'videos/{camera}/file_index']) output_relative = path.relative_to(root).as_posix() source_relative = old_video.as_posix() if output_relative in video_mapping: assert video_mapping[output_relative]['source_path'] == source_relative else: assert path.stat().st_size == (source / old_video).stat().st_size video_mapping[output_relative] = {'output_path': output_relative, 'source_path': source_relative, 'bytes': path.stat().st_size, 'operation': 'unmodified_file_copy', 'checksum_computed': False} # Sample a small number of representative reads per merged dataset. reads = 0 for index in sorted(set([0, len(episodes)//2, len(episodes)-1])): ep = episodes[index] for camera in cameras: path = dataset / info['video_path'].format( video_key=camera, chunk_index=ep[f'videos/{camera}/chunk_index'], file_index=ep[f'videos/{camera}/file_index']) timestamp = (ep[f'videos/{camera}/from_timestamp'] + ep[f'videos/{camera}/to_timestamp']) / 2 with av.open(str(path)) as container: stream = container.streams.video[0] container.seek(int(timestamp / stream.time_base), stream=stream, backward=True) for frame in container.decode(stream): if frame.time >= timestamp - 1/info['fps']: assert frame.width == info['features'][camera]['shape'][1] assert frame.height == info['features'][camera]['shape'][0] reads += 1 break else: raise AssertionError(f'Cannot read representative frame: {path}/{timestamp}') result['checks'].append({'root': group['root'], 'episodes': len(episodes), 'frames': data.num_rows, 'representative_frame_reads': reads, 'bookkeeping': 'passed', 'task_links': 'passed', 'video_references': 'passed'}) assert sum(c['frames'] for c in result['checks']) == summary['total_frames'] result['original_episode_coverage'] = 'exactly_once' if source else 'not_checked' result['source_video_timestamps'] = 'unchanged' if source else 'not_checked' result['source_video_reference_and_file_size_check'] = 'passed' if source else 'not_checked' if source: (root / 'reports/video_file_mapping.json').write_text(json.dumps(list(video_mapping.values()), indent=2)+'\n', encoding='utf-8') (root / 'reports/merge_checks.json').write_text(json.dumps(result, indent=2)+'\n', encoding='utf-8') print(json.dumps(result, indent=2)) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('root', type=Path) parser.add_argument('--source', type=Path) args = parser.parse_args() check(args.root, args.source)