Datasets:
Download scripts/verify_data.py from SteveWCG/Attn_exp_data: direct link, hf CLI and curl.
- Browser
- Download file 7.78 kB
-
https://huggingface.co/datasets/SteveWCG/Attn_exp_data/resolve/main/scripts/verify_data.py
- Command line
-
hf download hf://datasets/SteveWCG/Attn_exp_data/scripts/verify_data.py
-
curl -L -o verify_data.py https://huggingface.co/datasets/SteveWCG/Attn_exp_data/resolve/main/scripts/verify_data.py
7.78 kB
| """Verify the portable dataset; optionally compare it with its source catalog.""" | |
| import argparse | |
| from collections import Counter, defaultdict | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import sys | |
| import numpy as np | |
| from PIL import Image | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| from groundguard_data import Dataset, decode_rle | |
| def digest(path): | |
| with path.open('rb') as stream: | |
| return hashlib.file_digest(stream, 'sha256').hexdigest() | |
| def require(ok, message): | |
| if not ok: | |
| raise ValueError(message) | |
| def verify(source=None): | |
| data = Dataset(ROOT / 'prepared_data') | |
| expected_files = set() | |
| image_specs = {} | |
| mask_specs = {} | |
| records = list(data.iter_samples(subset='all', condition='all')) | |
| for name, counts in data.report['datasets'].items(): | |
| manifest = data.root / 'manifests' / f'{name}.jsonl' | |
| selection = data.root / 'selections' / f'{name}.json' | |
| require(digest(manifest) == counts['manifest_sha256'], f'Manifest hash: {name}') | |
| require(digest(selection) == counts['selection_sha256'], f'Selection hash: {name}') | |
| ids = json.loads(selection.read_text()) | |
| require(ids['test_unit_ids'] == ids['selected_unit_ids'], f'All selected units must be test: {name}') | |
| require(ids['development_unit_ids'] == [], f'Unexpected development units: {name}') | |
| kept = set().union(*(ids[f'{s}_unit_ids'] for s in ('selected', 'test', 'development'))) | |
| rows = list(data.iter_samples(name, subset='all', condition='all')) | |
| require({r['unit_id'] for r in rows} == kept, f'Catalog scope: {name}') | |
| require(len(rows) == counts['catalog_records'], f'Record count: {name}') | |
| for split in ('selected', 'test', 'development'): | |
| subset = list(data.iter_samples(name, subset=split, condition='all')) | |
| 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()))) | |
| require(measured == counts[split], f'Split statistics: {name}/{split}') | |
| print(f'Checked {name}: {len(rows)} records', flush=True) | |
| split_rows = {s: list(data.iter_samples(subset=s, condition='all')) for s in ('test', 'development')} | |
| for field in ('source_group_id', 'pixel_sha256'): | |
| values = {s: {r[field] if field == 'source_group_id' else r['image'][field] for r in rows} | |
| for s, rows in split_rows.items()} | |
| require(not (values['test'] & values['development']), f'Split overlap: {field}') | |
| for row in records: | |
| spec = row['image'] | |
| path = spec['path'] | |
| require(path not in image_specs or image_specs[path] == spec, f'Conflicting image: {path}') | |
| image_specs[path] = spec | |
| expected_files.add(path) | |
| require(row['selection_eligible'], f'Ineligible record: {row["sample_id"]}') | |
| for region in row['reference']['regions'] + row.get('intervention_regions', []): | |
| x1, y1, x2, y2 = region['bbox_xyxy'] | |
| require(0 <= x1 < x2 <= spec['width'] and 0 <= y1 < y2 <= spec['height'], 'Invalid bbox') | |
| mask = region.get('mask') | |
| if mask: | |
| require(mask['size'] == [spec['height'], spec['width']], 'Mask/image dimensions') | |
| if mask['encoding'] == 'binary_png': | |
| expected_files.add(mask['path']) | |
| prior = mask_specs.setdefault(mask['path'], mask['size']) | |
| require(prior == mask['size'], 'Conflicting PNG mask dimensions') | |
| else: | |
| require(mask['encoding'] == 'coco_rle', 'Unknown mask encoding') | |
| binary = decode_rle(mask) | |
| require(binary.any(), 'Empty positive RLE mask') | |
| if 'area' in region: | |
| require(int(binary.sum()) == region['area'], 'RLE area mismatch') | |
| if row['pair_id']: | |
| pair = data.get_pair(row) | |
| require(set(pair) == {'factual_original', 'factual_replacement', | |
| 'counterfactual_original', 'counterfactual_replacement'}, 'Incomplete pair') | |
| for i, (relative, spec) in enumerate(sorted(image_specs.items()), 1): | |
| path = data._path(relative) | |
| require(digest(path) == spec['byte_sha256'], f'Image hash: {relative}') | |
| with Image.open(path) as image: | |
| image.load() | |
| require(image.size == (spec['width'], spec['height']), f'Image size: {relative}') | |
| pixels = f'{image.width},{image.height},RGB\0'.encode() + image.convert('RGB').tobytes() | |
| require(hashlib.sha256(pixels).hexdigest() == spec['pixel_sha256'], f'Pixel hash: {relative}') | |
| if i % 500 == 0: | |
| print(f'Checked {i}/{len(image_specs)} images', flush=True) | |
| for relative, size in mask_specs.items(): | |
| with Image.open(data._path(relative)) as image: | |
| require(list(image.size)[::-1] == size, f'PNG mask size: {relative}') | |
| require(np.asarray(image.convert('L')).any(), f'Empty positive PNG mask: {relative}') | |
| actual = {str(p.relative_to(data.root)) for name in ('images', 'masks') | |
| for p in (data.root / name).rglob('*') if p.is_file()} | |
| require(actual == expected_files, 'Missing or unused image/mask files') | |
| if source: | |
| original = Dataset(source) | |
| for row in records: | |
| require(row == original.get(row['sample_id']), f'Changed record: {row["sample_id"]}') | |
| for name in data.report['datasets']: | |
| current = json.loads((data.root / 'selections' / f'{name}.json').read_text()) | |
| previous = json.loads((original.root / 'selections' / f'{name}.json').read_text()) | |
| require(current['selected_unit_ids'] == previous['selected_unit_ids'], f'Changed selected units: {name}') | |
| for relative in expected_files: | |
| require(digest(data._path(relative)) == digest(original._path(relative)), f'Changed asset: {relative}') | |
| sums = ROOT / 'SHA256SUMS' | |
| if sums.exists(): | |
| for line in sums.read_text().splitlines(): | |
| expected, relative = line.split(' ', 1) | |
| path = (ROOT / relative).resolve() | |
| require(path.is_relative_to(ROOT) and digest(path) == expected, f'Payload checksum: {relative}') | |
| return dict(status='passed', records=len(records), units=len({r['unit_id'] for r in records}), | |
| image_files=len(image_specs), png_mask_files=len(mask_specs), asset_files=len(expected_files), | |
| complete_hallusegbench_pairs=len({r['pair_id'] for r in records if r['pair_id']}), | |
| development_test_exact_source_overlap=0, development_test_exact_image_overlap=0, | |
| source_equivalence_checked=source is not None, | |
| split_policy='test_only', development_units=0, | |
| checks=['manifest_and_selection_hashes', 'all_selected_units_are_test', 'complete_pairs', | |
| 'image_byte_and_pixel_hashes', 'image_decoding_and_dimensions', 'bbox_bounds', | |
| 'mask_dimensions_and_rle_areas', 'no_unused_or_missing_assets']) | |
| if __name__ == '__main__': | |
| cli = argparse.ArgumentParser(description=__doc__) | |
| cli.add_argument('--source', type=Path) | |
| cli.add_argument('--write-report', action='store_true') | |
| args = cli.parse_args() | |
| result = verify(args.source) | |
| if args.write_report: | |
| (ROOT / 'verification_report.json').write_text(json.dumps(result, indent=2) + '\n') | |
| print(json.dumps(result, indent=2)) | |