Vivarium-Greenscreen-Characters-FLUX-9B / tools /validate_character_release.py
ChristophSchuhmann's picture
Add adult and fantasy/SF extension taxonomy, plans and progress (30/2500)
60afd4a verified
Raw History Blame
6.65 kB
"""Full PNG decode, planned distribution and neutral-reference linkage checks."""
import argparse
from collections import Counter
import hashlib
import io
import json
import tarfile
from PIL import Image
from character_production import STATE,BUFFER,connect
from background_production import sha,dump,utc,BASE_REV,LORA_REV
from character_pilot import LORA_SHA
def validate(complete=False,extension=False):
global STATE,BUFFER,connect
if extension:
from character_extension import STATE,BUFFER,connect
con=connect();persons={p['personality_id']:p for p in json.loads((STATE/'person-plan.json').read_text())}
plan={e['id']:(p,e) for p in persons.values() for e in p['expressions']}
shards=list(con.execute('SELECT * FROM shards ORDER BY name'));seen=set();neutral_hash={};references=[];groups={};index=[]
for shard in shards:
path=BUFFER/shard['name'];assert path.is_file(),f'Restore verified shard before decoding: {path}'
assert path.stat().st_size==shard['bytes'] and sha(path)==shard['sha256']
shard_types=set()
with tarfile.open(path,'r:') as tar:
members=tar.getmembers();assert len(members)==shard['count']*3 and len({m.name for m in members})==len(members)
for i in range(0,len(members),3):
png,j,t=members[i:i+3];ident=png.name.removesuffix('.png')
assert [png.name,j.name,t.name]==[ident+'.png',ident+'.json',ident+'.txt']
assert ident in plan and ident not in seen
person,expression=plan[ident];meta=json.loads(tar.extractfile(j).read());data=tar.extractfile(png).read()
shard_types.add(person.get('record_type','human'))
assert meta['id']==ident and meta['prompt']==tar.extractfile(t).read().decode()
for key,value in person.items():
if key not in ['expressions','seed']:assert meta[key]==value,(ident,key)
for key,value in expression.items():assert meta[key]==value,(ident,key)
digest=hashlib.sha256(data).hexdigest();assert meta['image_sha256']==digest
if extension:
from teen_generation_safety import approved_metadata
assert approved_metadata(meta),(ident,'under20 screening')
with Image.open(io.BytesIO(data)) as im:assert im.format=='PNG' and im.mode=='RGB' and im.size==(832,1248);im.verify()
with Image.open(io.BytesIO(data)) as im:im.load()
inf=meta['inference'];assert inf['revision']==BASE_REV and inf['lora_sha256']==LORA_SHA
assert inf['model']=='black-forest-labs/FLUX.2-klein-base-9B' and inf['lora_revision']==LORA_REV
assert (inf['width'],inf['height'])==(832,1248) and inf['lora_rank']==64 and inf['lora_alpha']==64
assert inf['steps']==50 and inf['guidance_scale']==4. and inf['lora_scale']==float(person.get('lora_scale',1.0))
assert inf['quantization'] is False and inf['distillation'] is False and inf['dtype']=='bfloat16'
assert inf['seed']==meta['seed']==expression['seed']
if person.get('seed_strategy')!='safety-per-emotion-attempt':assert meta['seed']==person['seed']
if expression['emotion']=='neutral':
assert not meta['reference_image_sha256'] and not meta['reference_id'];neutral_hash[person['personality_id']]=digest
else:
assert meta['reference_id']==person['personality_id']+'-neutral'
assert meta['reference_resize']==dict(width=416,height=624,resample='PIL BICUBIC')
references.append((person['personality_id'],meta['reference_image_sha256']))
assert meta['storage']['shard']==shard['name']
groups.setdefault(person['personality_id'],set()).add(expression['emotion']);seen.add(ident)
index.append(dict(id=ident,personality_id=person['personality_id'],emotion=expression['emotion'],shard=shard['name'],
repo_path=('extension-data/' if extension else 'data/')+shard['name'],
image_offset=png.offset_data,image_bytes=png.size,image_sha256=digest,seed=expression['seed']))
assert len(shard_types)==1,'Each shard must contain only one record family'
for person,digest in references:assert neutral_hash[person]==digest,(person,'neutral reference SHA mismatch')
assert all(g=={e['emotion'] for e in persons[p]['expressions']} for p,g in groups.items()),'Closed shards must contain complete planned expression groups'
if complete:
assert seen==set(plan) and len(seen)==(2500 if extension else 5000) and len(groups)==(340 if extension else 500)
assert all(s['status']=='uploaded' for s in shards)
allocation=json.loads((STATE/'planning/allocation.json').read_text())
humans=[p for p in groups if persons[p].get('record_type','human')=='human']
assert dict(Counter(persons[p]['gender'] for p in humans))==allocation['human_gender_counts' if extension else 'gender_counts']
assert dict(Counter(persons[p]['ethnicity'] for p in humans))==allocation['human_ethnicity_counts' if extension else 'ethnicity_counts']
assert dict(Counter(persons[p]['age_group']+'/'+persons[p]['gender'] for p in humans))==allocation['by_age_and_gender']
if extension:
assert dict(Counter(persons[p]['special_class'] for p in groups if p not in humans))==allocation['special_class_counts']
result=dict(status='passed',scope='complete' if complete else 'closed-shard snapshot',utc=utc(),images_verified=len(seen),
persons_verified=len(groups),shards_verified=len(shards),bytes_verified=sum(s['bytes'] for s in shards),
checks=['TAR SHA256 and byte size','three adjacent unique members per sample','PNG CRC and full decode','832x1248 RGB',
'unique expected IDs','every person and expression field matches plan','prompt/seed consistency','PNG SHA256',
'exact neutral reference linkage and416x624 resize','complete planned expressions per closed identity','50-step CFG4 BF16 pinned model/LoRA',
'no quantization or distillation']+(['complete age/gender/ethnicity prompt distribution'] if complete else []))
dump(STATE/'integrity-validation.json',result);dump(STATE/'sample-index.json',index);print(json.dumps(result,indent=2))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--complete',action='store_true');p.add_argument('--extension',action='store_true');a=p.parse_args();validate(a.complete,a.extension)