#!/usr/bin/env python3 """Reconstruct imported native PNG objects from pinned original public ZIPs. Verifies archive, source JPEG, registered raster and expected encoded PNG hashes. Does not modify the frozen snapshot or publish files. Original archives live in the support directory, outside the monthly dataset staging root. """ import argparse from collections import Counter import hashlib import json import os import shutil from pathlib import Path import time from urllib.request import urlopen from zipfile import ZipFile from native_dataset_image import native_image from source_export import canonical, rooted, sha_file, write_json REVISION='b4856947ed7cb6312587258acc90e8cf88a4aa13' PINS={ 'train':('train.zip',59887779,'0a7cc5895afd76a4dc98e70efc9421ae82a6f580e6d60da3904911155e424853'), 'val':('val.zip',29740678,'13ca882129a4e024fc865fc4a3187514a4554f8e323f612e338144fd1ff189ea'), } def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--snapshot',type=Path,required=True) p.add_argument('--support-root',type=Path,required=True) p.add_argument('--original-package',type=Path,help='Retained original import package with objects/; prefer exact existing PNGs') args=p.parse_args(); os.umask(0o077) snapshot=json.loads((args.snapshot/'source-snapshot.json').read_text()) if sha_file(args.snapshot/'source-plan.jsonl')!=snapshot['source_plan_sha256']: raise ValueError('source_plan_changed') records=[] with (args.snapshot/'source-plan.jsonl').open() as f: for line in f: record=json.loads(line) if record['media']['kind']=='dataset': records.append(record) archives=args.support_root/'upstream-de134'/'archives'; archives.mkdir(parents=True,exist_ok=True) corpus=args.support_root/'corpus'; corpus.mkdir(parents=True,exist_ok=True) if args.original_package: verified=0; total=0; errors=[] for record in records: row,media=record['row'],record['media'] source=rooted(args.original_package,media['object_key'].removeprefix('datasets/')) target=rooted(corpus,media['object_key']) try: if sha_file(source)!=row['sha256'] or source.stat().st_size!=media['bytes']: raise ValueError('original_package_object_mismatch') target.parent.mkdir(parents=True,exist_ok=True) if not target.exists() or sha_file(target)!=row['sha256']: tmp=target.with_suffix('.png.part');shutil.copyfile(source,tmp);os.replace(tmp,target) if sha_file(target)!=row['sha256']: raise ValueError('copied_hash_mismatch') verified+=1;total+=target.stat().st_size except Exception as error: errors.append(dict(sample_id=row['sample_id'],error=str(error) if type(error) is ValueError else type(error).__name__)) receipt=dict(status='partial' if errors else 'complete',method='exact_retained_package_bytes',expected=len(records), verified=verified,bytes=total,source_plan_sha256=snapshot['source_plan_sha256'],errors=errors) write_json(args.support_root/'upstream-de134'/'restore-receipt.json',receipt) print(json.dumps({k:v for k,v in receipt.items() if k!='errors'}),flush=True) return 1 if errors else 0 zips={} for split,(filename,size,sha) in PINS.items(): path=archives/filename if not path.exists() or path.stat().st_size!=size or sha_file(path)!=sha: url=f'https://huggingface.co/datasets/Panoramax/classified_de_road_signs/resolve/{REVISION}/{filename}' tmp=path.with_suffix('.zip.part') with urlopen(url,timeout=60) as source,tmp.open('wb') as out: while block:=source.read(1024*1024): out.write(block) if tmp.stat().st_size!=size or sha_file(tmp)!=sha: raise ValueError('archive_pin_mismatch') os.replace(tmp,path) zips[split]=ZipFile(path) print(json.dumps({'stage':'archive_verified','split':split,'bytes':size}),flush=True) errors=[]; verified=0; total=0; started=time.time(); reused=0 for record in records: row,media=record['row'],record['media']; target=rooted(corpus,media['object_key']) try: if target.exists() and sha_file(target)==row['sha256']: reused+=1 else: member=row['source_memberships'][0]; split=member['split'] pin=PINS[split] if member['dataset_id']!='Panoramax/classified_de_road_signs' or member['revision']!=REVISION: raise ValueError('unexpected_dataset_revision') if member['provenance']['archive_sha256']!=pin[2]: raise ValueError('archive_membership_mismatch') info=zips[split].getinfo(member['member_path']) if info.file_size>16*1024**2: raise ValueError('oversized_member') original=zips[split].read(info) if hashlib.sha256(original).hexdigest()!=member['original_sha256']: raise ValueError('original_hash_mismatch') identity,png=native_image(original,jpeg_only=True) if identity['pixel_sha256']!=row['pixel_sha256']: raise ValueError('pixel_hash_mismatch') if [identity['width'],identity['height']]!=row['dimensions']: raise ValueError('dimensions_mismatch') if hashlib.sha256(png).hexdigest()!=row['sha256']: raise ValueError('encoded_hash_mismatch') if len(png)!=media['bytes']: raise ValueError('encoded_size_mismatch') target.parent.mkdir(parents=True,exist_ok=True); tmp=target.with_suffix('.png.part') tmp.write_bytes(png); os.replace(tmp,target) verified+=1; total+=target.stat().st_size except Exception as error: reason=str(error) if type(error) is ValueError else type(error).__name__ errors.append(dict(sample_id=row['sample_id'],error=reason)) if (verified+len(errors))%1000==0: print(json.dumps(dict(stage='native_objects',verified=verified,errors=len(errors),bytes=total)),flush=True) for archive in zips.values(): archive.close() receipt=dict(stage='native_objects',status='complete' if not errors else 'partial',expected=len(records), verified=verified,reused=reused,bytes=total,seconds=round(time.time()-started,2), corpus_root=str(corpus),source_plan_sha256=snapshot['source_plan_sha256'],revision=REVISION, native_image_source_sha256=sha_file(Path(__file__).with_name('native_dataset_image.py')), restore_source_sha256=sha_file(__file__),errors=errors) write_json(args.support_root/'upstream-de134'/'restore-receipt.json',receipt) print(json.dumps({k:v for k,v in receipt.items() if k!='errors'},sort_keys=True),flush=True) return 1 if errors else 0 if __name__=='__main__': raise SystemExit(main())