Download source/finalize_generation.py from DanielNguyen121/DisEF-Cars: direct link, hf CLI and curl.
- Browser
- Download file 4.67 kB
-
https://huggingface.co/datasets/DanielNguyen121/DisEF-Cars/resolve/main/source/finalize_generation.py
- Command line
-
hf download hf://datasets/DanielNguyen121/DisEF-Cars/source/finalize_generation.py
-
curl -L -o finalize_generation.py https://huggingface.co/datasets/DanielNguyen121/DisEF-Cars/resolve/main/source/finalize_generation.py
4.67 kB
| #!/usr/bin/env python3 | |
| """Validate all Cars synthetic outputs, create compatible ZIP, and verify HF LFS SHA256.""" | |
| import collections,hashlib,json,os,zipfile | |
| from pathlib import Path | |
| from PIL import Image | |
| from huggingface_hub import HfApi | |
| ROOT=Path('/marimo/disef_cars');RUN=ROOT/'runs/generation_seed_1';OUT=ROOT/'data/synthetic/cars_disef_images.zip';REPORT=ROOT/'reports/generation_report.json' | |
| def sha(p): | |
| h=hashlib.sha256() | |
| with open(p,'rb') as f: | |
| for b in iter(lambda:f.read(2**20),b''):h.update(b) | |
| return h.hexdigest() | |
| def save(p,obj): | |
| p.parent.mkdir(parents=True,exist_ok=True);tmp=p.with_suffix(p.suffix+'.tmp');tmp.write_text(json.dumps(obj,indent=2,sort_keys=True));tmp.replace(p) | |
| def main(): | |
| if REPORT.exists() and json.loads(REPORT.read_text()).get('remote_verified'): | |
| print('ALREADY_VERIFIED',json.loads(REPORT.read_text())['remote_revision']);return | |
| state=json.loads((RUN/'state/cars_disef_state.json').read_text()) | |
| if state.get('completed')!=12544 or state.get('target')!=12544 or state.get('status')!='COMPLETED':raise RuntimeError('generation quota incomplete') | |
| support=json.loads((ROOT/'manifests/fewshot_seed_1_leakfree.json').read_text()) | |
| support_files={str(ROOT/'data/prepared/StanfordCars'/rel) for paths in support['support_by_class'].values() for rel in paths} | |
| records=list(state['records'].values()) | |
| if len(records)!=12544:raise ValueError('record count mismatch') | |
| per=collections.Counter();digests=set();paths=[];errors=[] | |
| for rec in records: | |
| try: | |
| assert rec['completion_status']=='COMPLETE' | |
| if rec.get('fallback_accept'): | |
| assert not rec.get('filter_pass') | |
| assert rec.get('recovery_variant')=='SPC-DisEF-SD2.1-Qwen-filter-plus-SAP-class-fallback-recovery' | |
| assert int(rec.get('fallback_class_candidates',0))>3200 | |
| else:assert rec.get('filter_pass') is True | |
| assert rec['source_image'] in support_files and rec['caption_source_image'] in support_files | |
| path=RUN/rec['synthetic_filename'];assert path.is_file() and path.parent.name==rec['class_folder'] | |
| with Image.open(path) as im:im.load();assert im.format=='JPEG' and im.size==(512,512) | |
| digest=sha(path);assert digest==rec['sha256'] and digest not in digests | |
| digests.add(digest);per[rec['class_folder']]+=1;paths.append(path) | |
| except Exception as e:errors.append({'task_id':rec.get('task_id'),'reason':str(e)}) | |
| if errors:save(ROOT/'reports/generation_qa_errors.json',errors);raise ValueError(f'{len(errors)} QA failures') | |
| if len(per)!=196 or min(per.values())!=64 or max(per.values())!=64:raise ValueError('per-class quota mismatch') | |
| OUT.parent.mkdir(parents=True,exist_ok=True);tmp=OUT.with_suffix('.zip.tmp') | |
| with zipfile.ZipFile(tmp,'w',compression=zipfile.ZIP_STORED,allowZip64=True) as z: | |
| for path in sorted(paths):z.write(path,arcname=str(path.relative_to(RUN/'images'))) | |
| os.replace(tmp,OUT) | |
| with zipfile.ZipFile(OUT) as z: | |
| names=z.namelist();assert len(names)==12544 and z.testzip() is None | |
| digest=sha(OUT);api=HfApi(token=os.environ['HF_TOKEN']);repo='DanielNguyen121/DisEF-datasets' | |
| existing=next((x for x in api.repo_info(repo,repo_type='dataset',files_metadata=True).siblings if x.rfilename==OUT.name),None) | |
| if existing and existing.lfs and existing.lfs.sha256==digest:revision=api.repo_info(repo,repo_type='dataset').sha | |
| else: | |
| api.upload_file(path_or_fileobj=str(OUT),path_in_repo=OUT.name,repo_id=repo,repo_type='dataset',commit_message='Add verified 12,544-image Stanford Cars DisEF-Qwen synthetic archive') | |
| info=api.repo_info(repo,repo_type='dataset',files_metadata=True);remote=next(x for x in info.siblings if x.rfilename==OUT.name) | |
| if not remote.lfs or remote.lfs.sha256!=digest or remote.size!=OUT.stat().st_size:raise RuntimeError('remote synthetic archive SHA/size mismatch') | |
| revision=info.sha | |
| report={'variant':'SPC-DisEF-SD2.1-Qwen-filter-plus-SAP-class-fallback-recovery','strict_filter_accepted':sum(bool(r.get('filter_pass')) for r in records),'reference_fallback_accepted':sum(bool(r.get('fallback_accept')) for r in records),'classes':196,'valid_images':12544,'per_class_min':64,'per_class_max':64,'generated_attempts':state.get('attempted'),'rejected':state.get('rejected'),'retried':state.get('retried'),'failed':state.get('failed'),'support_sha256':support['support_sha256'],'archive_filename':OUT.name,'archive_sha256':digest,'archive_bytes':OUT.stat().st_size,'remote_repo':repo,'remote_revision':revision,'remote_verified':True,'generation_config':json.loads((RUN/'metadata/generation_config.json').read_text()),'recovery_protocol':json.loads((RUN/'state/recovery_state.json').read_text())} | |
| save(REPORT,report);print('VERIFIED_ARCHIVE',digest,revision) | |
| if __name__=='__main__':main() | |