"""Export frozen selected units as test-only data; keep the source intact.""" import argparse from collections import Counter import copy import hashlib import json from pathlib import Path import shutil def sha256(path): h = hashlib.sha256() with path.open('rb') as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b''): h.update(chunk) return h.hexdigest() def save_json(path, value): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n') def asset_paths(row): yield row['image']['path'] for region in row['reference']['regions'] + row.get('intervention_regions', []): mask = region.get('mask') if mask and mask['encoding'] == 'binary_png': yield mask['path'] def export(source, destination): source, destination = source.resolve(), destination.resolve() if destination.exists(): raise FileExistsError(destination) if destination.is_relative_to(source) or source.is_relative_to(destination): raise ValueError('Source and destination must be separate') original = json.loads((source / 'build_report.json').read_text()) if original['status'] != 'complete': raise ValueError('Source preparation is incomplete') report = copy.deepcopy(original) report['status'] = 'building' report['catalog_scope'] = 'frozen selected units only; all assigned to test' report['config'].pop('development_fraction', None) report['config']['hallusegbench'].pop('development_source', None) report['config']['split_policy'] = 'all_selected_are_test' report['split_policy'] = 'test_only' report['source_build_report_sha256'] = sha256(source / 'build_report.json') save_json(destination / 'build_report.json', report) assets = set() split_sources, split_images = {}, {} all_ids = set() export_counts = {} for name, counts in report['datasets'].items(): selection_path = source / 'selections' / f'{name}.json' selection = json.loads(selection_path.read_text()) allowed = set(selection['selected_unit_ids']) src_manifest = source / 'manifests' / f'{name}.jsonl' if sha256(src_manifest) != counts['manifest_sha256'] or sha256(selection_path) != counts['selection_sha256']: raise ValueError(f'Source checksums changed: {name}') counts['source_selection_sha256'] = counts['selection_sha256'] selection['test_unit_ids'] = list(selection['selected_unit_ids']) selection['development_unit_ids'] = [] selection['split_policy'] = 'test_only' selection['policy'] = report['config'][name] lines, rows = [], [] for line in src_manifest.read_text().splitlines(keepends=True): row = json.loads(line) if row['unit_id'] in allowed: if not row['selection_eligible'] or row['sample_id'] in all_ids: raise ValueError(f'Invalid selected sample: {row["sample_id"]}') all_ids.add(row['sample_id']) rows.append(row) lines.append(line) assets.update(asset_paths(row)) if {r['unit_id'] for r in rows} != allowed: raise ValueError(f'Missing selected units: {name}') if name == 'hallusegbench': pairs = {} for row in rows: pairs.setdefault(row['unit_id'], set()).add(row['condition']) expected = {'factual_original', 'factual_replacement', 'counterfactual_original', 'counterfactual_replacement'} if any(conditions != expected for conditions in pairs.values()): raise ValueError('Incomplete counterfactual pair') out_manifest = destination / 'manifests' / f'{name}.jsonl' out_manifest.parent.mkdir(parents=True, exist_ok=True) out_manifest.write_text(''.join(lines)) out_selection = destination / 'selections' / selection_path.name out_selection.parent.mkdir(parents=True, exist_ok=True) save_json(out_selection, selection) counts['selection_sha256'] = sha256(out_selection) counts['source_catalog_units'] = counts['catalog_units'] counts['source_catalog_records'] = counts['catalog_records'] counts['catalog_units'] = len(allowed) counts['catalog_records'] = len(rows) counts['manifest_sha256'] = sha256(out_manifest) counts['source_normalization'] = counts.pop('normalization') counts['normalization'] = dict( samples_with_annotation_canvas_scaling=sum('annotation_transform' in r['provenance'] for r in rows), masks_with_annotation_canvas_scaling=len({x['mask']['path'] for r in rows for x in r.get('intervention_regions', []) if 'annotation_transform' in x}), areas_recomputed_from_mask=sum(x.get('normalization_note') == 'area_recomputed_from_published_mask' for r in rows for x in r['reference']['regions']), excluded_invalid_units=[]) for split in ('selected', 'test', 'development'): subset = [r for r in rows if r['unit_id'] in set(selection[f'{split}_unit_ids'])] measured = dict(units=len({r['unit_id'] for r in subset}), image_query_records=len(subset), distinct_source_images=len({r['source_group_id'] for r in subset}), distinct_images=len({r['image']['pixel_sha256'] for r in subset}), task_counts=dict(sorted(Counter(r['task_type'] for r in subset if r['is_primary']).items()))) if split == 'selected' and measured != counts[split]: raise ValueError(f'Frozen selected statistics changed: {name}') counts[split] = measured split_sources.setdefault(split, set()).update(r['source_group_id'] for r in subset) split_images.setdefault(split, set()).update(r['image']['pixel_sha256'] for r in subset) export_counts[name] = dict(units=len(allowed), records=len(rows), removed_records=counts['source_catalog_records'] - len(rows)) print(name, export_counts[name], flush=True) if split_sources['test'] & split_sources['development'] or split_images['test'] & split_images['development']: raise ValueError('Development/test leakage') for relative in sorted(assets): src = (source / relative).resolve() dst = (destination / relative).resolve() if not src.is_relative_to(source) or not dst.is_relative_to(destination): raise ValueError(f'Unsafe asset path: {relative}') dst.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(src, dst) report['status'] = 'complete' report['export'] = dict(datasets=export_counts, asset_files=len(assets), asset_bytes=sum((destination / p).stat().st_size for p in assets), selected_unit_ids_unchanged=True, all_selected_units_are_test=True, development_units=0, sample_records_unchanged=True) save_json(destination / 'build_report.json', report) print(json.dumps(report['export'], ensure_ascii=False, indent=2)) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', type=Path, default=Path('prepared_data')) parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() export(args.source, args.output)