#!/usr/bin/env python3 """Validate public allowlists, split separation and every tar/frame checksum.""" import argparse,collections,hashlib,io,json,re,tarfile from pathlib import Path import numpy as np from PIL import Image from schema import TEXT_RISK,validate SECRET=re.compile(rb'\bhf_[A-Za-z0-9]{25,}|\bghp_[A-Za-z0-9]{25,}|\bsk-[A-Za-z0-9_-]{25,}|-----BEGIN [A-Z ]*PRIVATE KEY-----') def sha(path): h=hashlib.sha256() with Path(path).open('rb') as f: for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b) return h.hexdigest() def run(root,check_manifest=True): root=Path(root);records={};groups={};counts={} for split in ('train','heldout'): groups[split]=set();counts[split]=0 for line in (root/'data'/(split+'.jsonl')).open(): row=validate(json.loads(line)) if row['split']!=split or row['sample_id'] in records:raise ValueError('Wrong split or duplicate record') records[row['sample_id']]=row;groups[split].add(row['group_id']);counts[split]+=1 if groups['train']&groups['heldout'] or counts!={'train':14253,'heldout':3168}:raise ValueError('Split/count mismatch') media={};archive_members=collections.defaultdict(dict) for line in (root/'MEDIA_MANIFEST.jsonl').open(): row=json.loads(line);record=records.get(row['sample_id']) if record is None or row['sample_id'] in media:raise ValueError('Unknown/repeated media ID') for k in ('media_archive','media_member'): if row[k]!=record[k]:raise ValueError('Media reference mismatch') if row['sha256']!=record['media_sha256'] or len(row['encoded_frame_SHA256'])!=8:raise ValueError('Media hash/shape mismatch') media[row['sample_id']]=row;archive_members[row['media_archive']][row['media_member']]=row if len(media)!=len(records):raise ValueError('Media coverage incomplete') for shard in json.loads((root/'SHARDS.json').read_text())['shards']: path=root/shard['path'] if path.stat().st_size!=shard['bytes'] or sha(path)!=shard['sha256']:raise ValueError('Shard size/SHA256 mismatch') needed=dict(archive_members[shard['path']]);members=0 with tarfile.open(path,'r:') as handle: for member in handle: item=needed.pop(member.name,None) if not member.isfile() or item is None or member.uid or member.gid or member.mtime or member.uname or member.gname:raise ValueError('Unallowlisted tar member/metadata') value=handle.extractfile(member).read() if len(value)!=item['bytes'] or hashlib.sha256(value).hexdigest()!=item['sha256']:raise ValueError('Member readback mismatch') with np.load(io.BytesIO(value),allow_pickle=False) as arrays: if set(arrays.files)!={f'f{i}' for i in range(8)}:raise ValueError('Unallowlisted NPZ metadata') for n in range(8): a=arrays[f'f{n}'] if a.dtype!=np.uint8 or a.ndim!=1 or hashlib.sha256(a.tobytes()).hexdigest()!=item['encoded_frame_SHA256'][n]:raise ValueError('Frame bytes changed') im=Image.open(io.BytesIO(a.tobytes()));im.load() if im.getexif() or set(im.info)-{'jfif','jfif_version','jfif_unit','jfif_density','gamma','srgb'}:raise ValueError('Sensitive image metadata') if list(reversed(im.size))!=records[item['sample_id']]['hw']:raise ValueError('Image size changed') members+=1 if needed or members!=shard['members']:raise ValueError('Missing/repeated media') print(f'VERIFIED {shard["path"]}: {members} NPZ observations and all encoded frames',flush=True) rationales={};quality=collections.Counter() expected_fields={'sample_id','split','public_rationale','status','generation_source','human_approved','faithfulness_verified','future_GT_sent_to_generator','teacher_numeric_prediction_generated'} for line in (root/'data/public_rationales.jsonl').open(): r=json.loads(line) if set(r)!=expected_fields or r['sample_id'] not in records or r['sample_id'] in rationales:raise ValueError('Unallowlisted rationale') if r['split']!=records[r['sample_id']]['split'] or r['status'] not in ('eligible_weak_draft','held_for_review'):raise ValueError('Rationale split/status mismatch') if any(r[k] is not False for k in ('human_approved','faithfulness_verified','future_GT_sent_to_generator','teacher_numeric_prediction_generated')):raise ValueError('Unverified rationale claim') if TEXT_RISK.search(r['public_rationale']):raise ValueError('Sensitive rationale text') rationales[r['sample_id']]=r;quality[r['status']]+=1 if len(rationales)!=6219 or dict(quality)!={'eligible_weak_draft':3465,'held_for_review':2754}:raise ValueError('Rationale count mismatch') if check_manifest: m=json.loads((root/'PUBLIC_RELEASE_MANIFEST.json').read_text()) for row in m['files']: p=root/row['path'] if p.is_symlink() or not p.is_file() or p.stat().st_size!=row['bytes'] or sha(p)!=row['sha256']:raise ValueError('Release file changed') if p.suffix in ('.py','.json','.jsonl','.md','.txt') and SECRET.search(p.read_bytes()):raise ValueError('Credential-like release text') def client_runtime(p): rel=p.relative_to(root).parts return '__pycache__' in rel or rel[:3]==('.cache','huggingface','download') or rel==('.cache','huggingface','.gitignore') actual={p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file() and not client_runtime(p)} allowed={r['path'] for r in m['files']}|{'PUBLIC_RELEASE_MANIFEST.json','CHECKSUMS.sha256','.gitattributes'} if actual-allowed:raise ValueError('Unallowlisted files in release') print(json.dumps({'status':'verified','records':len(records),'public_rationales':len(rationales),'quality_counts':dict(quality),'all_observation_frame_bytes_verified':True,'credentials_or_original_ID_fields':False,'GPU_used':False},indent=2),flush=True) return {'records':len(records),'rationales':len(rationales),'quality_counts':dict(quality)} def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]);a=p.parse_args();run(a.root) if __name__=='__main__':main()