File size: 6,650 Bytes
7bb6af4
 
 
 
 
 
 
 
 
226af47
7bb6af4
 
 
 
 
 
 
 
 
 
 
 
226af47
7bb6af4
 
 
 
 
 
 
226af47
7bb6af4
 
60afd4a
7bb6af4
 
60afd4a
 
 
7bb6af4
 
 
226af47
 
7bb6af4
 
60afd4a
 
7bb6af4
 
 
 
 
 
 
 
 
226af47
60afd4a
226af47
7bb6af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""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)