Hsyshasuzh/longmemory-geo / project /evaluation /audit_dior_queue_soda_validation.py
Hsyshasuzh's picture
download
raw
4.99 kB
"""Screen pending DIOR-R bridge images against selected SODA-A validation sources."""
import argparse
import hashlib
import json
import re
from collections import Counter
from pathlib import Path
from zipfile import ZipFile
from evaluation.audit_fair1m_dior_queue_duplicates import fingerprints
def sha(data):
return hashlib.sha256(data).hexdigest()
def audit(queue, inventory, annotations, images, source_subset=None):
inv_raw = inventory.read_bytes()
tile_ids = json.loads(inv_raw)['validation_tile_ids']
if not tile_ids or any(not isinstance(x, str) or not re.fullmatch(r'soda-a-val-[A-Za-z0-9_-]+:x\d+:y\d+', x) for x in tile_ids):
raise ValueError('only explicit SODA-A validation tile IDs are allowed')
source_ids = sorted({x.split(':', 1)[0].removeprefix('soda-a-val-') for x in tile_ids})
if source_subset is not None:
if not source_subset or len(set(source_subset)) != len(source_subset) or not set(source_subset) <= set(source_ids):
raise ValueError('source subset must contain unique IDs from the selected validation inventory')
source_ids = sorted(source_subset)
queue_raw = queue.read_bytes()
refs = []
for row in json.loads(queue_raw)['records']:
if row.get('training_eligible') is not False:
raise ValueError('queue must remain training-ineligible')
image = Path(row['image']).read_bytes()
if sha(image) != row['image_sha256']:
raise ValueError(f"queue hash mismatch: {row['id']}")
fp = fingerprints(image)
refs.append((row['id'], fp['pixel_sha256'], [int(x, 16) for x in fp['phashes']]))
if not refs:
raise ValueError('queue must not be empty')
matches, errors, selected = [], [], []
with ZipFile(annotations) as labels, ZipFile(images) as image_zip:
names = Counter(image_zip.namelist())
for identifier in source_ids:
annotation_name = f'val/{identifier}.json'
try:
document = json.loads(labels.read(annotation_name))
image_name = document['images']['file_name']
if not isinstance(image_name, str) or names[image_name] != 1:
raise ValueError('source image missing or ambiguous in archive')
payload = image_zip.read(image_name)
fp = fingerprints(payload)
selected.append({'source_id': identifier, 'image_member': image_name, 'image_sha256': sha(payload),
'annotation_member': annotation_name})
values = [int(x, 16) for x in fp['phashes']]
for queue_id, pixels, hashes in refs:
distance = min((a ^ b).bit_count() for a in values for b in hashes)
if pixels == fp['pixel_sha256'] or distance <= 6:
matches.append({'queue_id': queue_id, 'source_id': identifier,
'exact_rgb': pixels == fp['pixel_sha256'], 'minimum_phash_distance': distance})
except Exception as error:
errors.append({'source_id': identifier, 'error': str(error)})
return {'status': 'PENDING_REVIEW', 'queue_sha256': sha(queue_raw), 'inventory_sha256': sha(inv_raw),
'queue_images': len(refs), 'selected_source_images': len(source_ids), 'selected': selected,
'matches': matches, 'errors': errors, 'official_test_annotations_read': False,
'official_test_images_read': False, 'training_eligible': False, 'independence_established': False,
'limitations': ['Selected validation sources only; other validation and training imagery are not screened.',
'Whole-image exact RGB and coarse DCT cannot rule out crops, nearby acquisition, geography or pretraining.',
'No match cannot establish independence or approve labels.']}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--queue', type=Path, required=True)
parser.add_argument('--inventory', type=Path, required=True)
parser.add_argument('--annotations', type=Path, required=True)
parser.add_argument('--images', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--source-id', action='append', default=None,
help='selected validation source ID; repeat to screen a bounded subset')
args = parser.parse_args()
if args.output.exists(): raise FileExistsError(args.output)
result = audit(args.queue, args.inventory, args.annotations, args.images, args.source_id)
with args.output.open('x') as handle:
json.dump(result, handle, indent=2); handle.write('\n')
print(json.dumps({'sources': result['selected_source_images'], 'matches': len(result['matches']),
'errors': len(result['errors']), 'test_images_read': False}))
if __name__ == '__main__': main()

Xet Storage Details

Size:
4.99 kB
·
Xet hash:
1e7387d5a9f04b3cd856fc1855a6c028fb9333063d02a0fbfa402c547d77e5de

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.