"""Checksum-specific recheck of public and newly produced teen/child TAR samples.""" import argparse from collections import Counter import fcntl import hashlib import io import json import os from pathlib import Path import sqlite3 import subprocess import tarfile import time import numpy as np from PIL import Image,ImageOps import torch from transformers import CLIPImageProcessor,CLIPVisionModelWithProjection from background_production import dump,utc,sha from minor_safety_gate import ROOT,STATE,MINOR_GROUPS from minor_safety_policy import decision as policy_decision BASE=ROOT/'experiments/character-production' BUFFER=Path('/tmp/vivarium-character-production') MODELS=Path('/tmp/vivarium-safety') REPO='laion/Vivarium-Greenscreen-Characters-FLUX-9B' def source(): c=sqlite3.connect(BASE/'queue.sqlite',timeout=120);c.row_factory=sqlite3.Row;return c def foreground(im): a=np.asarray(im).astype(np.int16) mask=~((a[:,:,1]>170)&(a[:,:,1]>a[:,:,0]+55)&(a[:,:,1]>a[:,:,2]+55)) ys,xs=np.where(mask);assert len(xs)>0 margin=24;crop=im.crop((max(0,int(xs.min())-margin),max(0,int(ys.min())-margin),min(im.width,int(xs.max())+margin+1),min(im.height,int(ys.max())+margin+1))) return ImageOps.pad(crop,(832,832),method=Image.Resampling.LANCZOS,color=(128,128,128)) def read_batch(batch,verified,remote): # Replacement writers hold the exclusive version of this lock. Check the # current database version while holding the shared lock before TAR reads. with (STATE/'replacement.lock').open('a') as lock: fcntl.flock(lock,fcntl.LOCK_SH) src=source();images=[] try: for m in batch: row=src.execute('SELECT metadata FROM images WHERE id=?',(m['id'],)).fetchone() current=json.loads(row[0]);s=dict(src.execute('SELECT * FROM shards WHERE name=?',(current['storage']['shard'],)).fetchone()) if current['image_sha256']!=m['image_sha256'] or s['status']=='safety_replacing':return None path=BUFFER/s['name'] if verified.get(s['name'])!=s['sha256']: assert path.stat().st_size==s['bytes'] and sha(path)==s['sha256'] if s['status']=='uploaded': f=remote.get('data/'+s['name']) if f is None or f.size!=s['bytes'] or f.lfs.sha256!=s['sha256']: from huggingface_hub import HfApi info=HfApi(token=False).dataset_info(REPO,files_metadata=True) remote.update({r.rfilename:r for r in info.siblings});f=remote['data/'+s['name']] assert f.size==s['bytes'] and f.lfs.sha256==s['sha256'],'Published TAR differs from local verified TAR' verified[s['name']]=s['sha256'] with tarfile.open(path,'r:') as tar:data=tar.extractfile(m['id']+'.png').read() assert hashlib.sha256(data).hexdigest()==m['image_sha256'] with Image.open(io.BytesIO(data)) as im:im.load();images.append(im.convert('RGB')) return images finally:src.close() def run(follow=False,limit=None): torch.set_num_threads(8);torch.backends.cuda.matmul.allow_tf32=False policy=json.loads((STATE/'policy.json').read_text());signature=policy['policy_sha256'] c=sqlite3.connect(STATE/'scores.sqlite',timeout=120);c.row_factory=sqlite3.Row registry=json.loads((MODELS/'clip-model.json').read_text()) device='cuda:0' if torch.cuda.is_available() else 'cpu' vision=CLIPVisionModelWithProjection.from_pretrained(registry['path'],local_files_only=True,dtype=torch.float32).to(device).eval() processor=CLIPImageProcessor.from_pretrained(registry['path'],local_files_only=True) env=os.environ.copy();env.update(CUDA_VISIBLE_DEVICES='',TF_CPP_MIN_LOG_LEVEL='2',TF_NUM_INTEROP_THREADS='2',TF_NUM_INTRAOP_THREADS='8') tf_log=(STATE/'logs/tensorflow.log');tf_log.parent.mkdir(exist_ok=True) with tf_log.open('a') as log: worker=subprocess.Popen([str(MODELS/'tf-venv/bin/python'),str(ROOT/'scripts/minor_safety_tf.py')],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log,text=True,env=env) ready=json.loads(worker.stdout.readline());assert ready['status']=='ready' models={} for repo in ['CLIP-based-NSFW-Detector','LAION-SAFETY']:models[repo]=json.loads((MODELS/'code'/repo/'revision.json').read_text()) models['CLIP_encoder']={**registry,'weights_sha256':sha(Path(registry['path'])/'model.safetensors')} models['efficientnet_weights_sha256']=sha(MODELS/'nsfweffnetv2-b02-3epochs.h5') models['binary_head_zip_sha256']=sha(MODELS/'code/CLIP-based-NSFW-Detector/clip_autokeras_binary_nsfw.zip') models.update(clip_embedding='L2-normalized OpenAI ViT-L/14 projected image embeddings,FP32', efficientnet_preprocessing='RGB float0..1,tf.image.resize260x260 antialias=True; softmax raw five-class logits', efficientnet_classes=['drawing','hentai','neutral','porn','sexy'],efficientnet_nsfw='sum(hentai,porn,sexy)', tf_version='2.15.1',torch_version=torch.__version__) dump(STATE/'detector-provenance.json',models) checked=0;verified={};remote=None;remote_when=0 from huggingface_hub import HfApi while True: src=source();shards={r['name']:dict(r) for r in src.execute('SELECT * FROM shards')} records=[json.loads(r[0]) for r in src.execute('SELECT metadata FROM images ORDER BY id')];src.close() minors=[r for r in records if r['age_group'] in MINOR_GROUPS] pending=[r for r in minors if c.execute('SELECT 1 FROM scores WHERE id=? AND image_sha256=? AND policy_sha256=?',(r['id'],r['image_sha256'],signature)).fetchone() is None] if pending and (remote is None or time.monotonic()-remote_when>120): info=HfApi(token=False).dataset_info(REPO,files_metadata=True);remote={r.rfilename:r for r in info.siblings};remote_when=time.monotonic();remote_revision=info.sha if limit is not None:pending=pending[:max(0,limit-checked)] for start in range(0,len(pending),16): batch=pending[start:start+16];images=read_batch(batch,verified,remote) if images is None:continue crops=[foreground(im) for im in images];views=images+crops pixels=processor(images=views,return_tensors='pt')['pixel_values'].to(device) with torch.inference_mode(): embeds=vision(pixel_values=pixels).image_embeds;embeds=embeds/embeds.norm(dim=-1,keepdim=True) input_path=MODELS/'batch-input.npz';output_path=MODELS/'batch-output.npz' np.savez(input_path,embeddings=embeds.cpu().numpy().astype('float64'),original=np.stack([np.asarray(im) for im in images]),foreground=np.stack([np.asarray(im) for im in crops])) worker.stdin.write(json.dumps(dict(input=str(input_path),output=str(output_path)))+'\n');worker.stdin.flush() response=worker.stdout.readline();assert response,tf_log.read_text()[-1500:] assert json.loads(response)['status']=='scored';scored=np.load(output_path) a=scored['clip'];b=scored['efficientnet'];assert len(a)==len(b)==2*len(batch) assert np.isfinite(a).all() and np.isfinite(b).all() and a.min()>=0 and a.max()<=1 for i,m in enumerate(batch): details={} for j,label in [(i,'original'),(i+len(batch),'foreground')]: details[label]=dict(clip_nsfw=float(a[j]),efficientnet_nsfw=float(b[j,[1,3,4]].sum()), efficientnet_classes={name:float(value) for name,value in zip(models['efficientnet_classes'],b[j])}) maximum=max(v[k] for v in details.values() for k in ['clip_nsfw','efficientnet_nsfw']) decision=policy_decision(dict(max_score=maximum,views=details),policy) r=dict(id=m['id'],personality_id=m['personality_id'],age_group=m['age_group'],emotion=m['emotion'],image_sha256=m['image_sha256'], policy_sha256=signature,decision=decision,max_score=maximum,views=details,utc=utc(),shard=m['storage']['shard'], source_was_uploaded=shards[m['storage']['shard']]['status']=='uploaded',remote_revision_checked=remote_revision) c.execute('INSERT OR REPLACE INTO scores VALUES(?,?,?,?,?,?)',(r['id'],r['image_sha256'],signature,decision,json.dumps(r),r['utc'])) c.commit();checked+=len(batch);input_path.unlink();output_path.unlink() current=[json.loads(r[0]) for r in c.execute('SELECT record FROM scores WHERE policy_sha256=?',(signature,))] summary=dict(status='checking',utc=utc(),expected_images=2760,scored_image_versions=len(current),decision_counts=dict(Counter(r['decision'] for r in current)), current_max_score=max(r['max_score'] for r in current),remote_revision_checked=remote_revision) dump(STATE/'progress.json',summary);print(json.dumps(summary),flush=True) # Generation and repairs can advance during inference: completion must # use current PNG digests, never the snapshot preceding a model batch. src=source();minors=[json.loads(r[0]) for r in src.execute('SELECT metadata FROM images') if json.loads(r[0])['age_group'] in MINOR_GROUPS];src.close();rows=[] for m in minors: q=c.execute('SELECT record FROM scores WHERE id=? AND image_sha256=? AND policy_sha256=?',(m['id'],m['image_sha256'],signature)).fetchone() if q:rows.append(json.loads(q[0])) with (STATE/'scores.jsonl').open('w') as f: for r in rows:f.write(json.dumps(r)+'\n') accepted=sum(r['decision']=='pass' for r in rows);raised=[r for r in rows if r['decision']!='pass'] dump(STATE/'flagged.json',raised) gallery_complete=(STATE/'lora-gallery-completion.json').exists() snapshot=dict(status='complete' if len(rows)==accepted==2760 and gallery_complete else 'checking',utc=utc(),expected_images=2760, current_images_checked=len(rows),current_images_passed=accepted,current_images_flagged=len(raised), expected_profiles=276,policy_sha256=signature,expected_public_model_examples=6,public_model_examples_complete=gallery_complete, checks=['Both LAION classifiers','Original and foreground views','Exact PNG SHA256','Uploaded TAR SHA256/size identity']) dump(STATE/'current-validation.json',snapshot) dump(STATE/'progress.json',{**snapshot,'scored_image_versions':c.execute('SELECT COUNT(*) FROM scores').fetchone()[0], 'decision_counts':dict(Counter(r['decision'] for r in rows)),'current_max_score':max([r['max_score'] for r in rows],default=0)}) if len(rows)==accepted==2760 and gallery_complete: dump(STATE/'completion.json',snapshot);print(json.dumps(snapshot),flush=True);break if not follow or (limit is not None and checked>=limit):break time.sleep(15) worker.stdin.write('{"stop":true}\n');worker.stdin.flush();worker.wait(timeout=30) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--follow',action='store_true');p.add_argument('--limit',type=int);a=p.parse_args();run(a.follow,a.limit)