"""Independent queue for the automatic post-5000 character extension.""" import argparse import hashlib import io import json import os from pathlib import Path import sqlite3 import tarfile import time from background_production import add_member,sha,dump,utc ROOT=Path(__file__).resolve().parents[1] STATE=ROOT/'experiments/character-extension' BUFFER=Path('/tmp/vivarium-character-extension') REPO='laion/Vivarium-Greenscreen-Characters-FLUX-9B' PILOT_IDS=['special-0001','special-0009','special-0013','special-0029','special-0085','special-0053'] def connect(): STATE.mkdir(parents=True,exist_ok=True) con=sqlite3.connect(STATE/'queue.sqlite',timeout=120);con.row_factory=sqlite3.Row con.execute('PRAGMA journal_mode=WAL');con.execute('PRAGMA busy_timeout=120000') return con def init(): con=connect();con.executescript(''' CREATE TABLE IF NOT EXISTS people (id TEXT PRIMARY KEY,position INTEGER,record TEXT,status TEXT DEFAULT 'queued',worker INTEGER,started TEXT,finished TEXT); CREATE TABLE IF NOT EXISTS images (id TEXT PRIMARY KEY,person_id TEXT,emotion TEXT,shard TEXT,metadata TEXT); CREATE TABLE IF NOT EXISTS shards (name TEXT PRIMARY KEY,worker INTEGER,count INTEGER,bytes INTEGER,sha256 TEXT,status TEXT,revision TEXT,created TEXT,uploaded TEXT); CREATE TABLE IF NOT EXISTS events (time TEXT,worker INTEGER,kind TEXT,detail TEXT); ''') plan=json.loads((STATE/'person-plan.json').read_text());lookup={p['personality_id']:p for p in plan} groups={} for p in plan: if p['record_type']=='human':groups.setdefault((p['age_group'],p['gender']),[]).append(p) order=[lookup[k] for k in PILOT_IDS] for i in range(50): for cell in groups.values(): if i=p.started""").fetchone()[0] return dict(utc=utc(),people=people,shards={r[0]:r[1] for r in con.execute('SELECT status,COUNT(*) FROM shards GROUP BY status')}, images_generated=closed+opened,images_in_closed_shards=closed, images_uploaded=con.execute("SELECT COALESCE(SUM(count),0) FROM shards WHERE status='uploaded'").fetchone()[0], target_identities=340,target_images=2500,quality_gate_passed=(STATE/'quality-gate-passed.json').is_file()) def release_specials(): assert (STATE/'quality-gate-passed.json').is_file(),'Visual pilot review must precede release' con=connect();con.execute("UPDATE people SET status='queued' WHERE status='held'");con.commit() print(json.dumps(status(con),indent=2)) def worker(gpu): import torch from PIL import Image from native_flux_inference import create_native_pipeline,generate_native_image,encode_text from character_pilot import metadata con=connect();con.execute("UPDATE people SET status='queued',worker=NULL WHERE status='running' AND worker=?",(gpu,));con.commit() event(con,gpu,'loading');scale=1.0 pipe=create_native_pipeline('characters',device='cuda:0',compile_mode='default',cfg_mode='batched',adapter_scale=scale) event(con,gpu,'loaded');BUFFER.mkdir(parents=True,exist_ok=True) rows=con.execute('SELECT name FROM shards WHERE worker=?',(gpu,)).fetchall() sequence=max([int(r['name'].removesuffix('.tar').rsplit('-',1)[1]) for r in rows]+[-1])+1 first=True;warm_modes=set();scorer=None from teen_generation_safety import in_scope,screen_frame,persist_actual_plan while True: person=claim(con,gpu) if person is None: if con.execute("SELECT COUNT(*) FROM people WHERE status='held'").fetchone()[0]:time.sleep(5);continue break kind=person['record_type'];limit=1 if first or person['personality_id'] in PILOT_IDS else (2 if kind=='human' else 20) name=f'{"humans" if kind=="human" else "specials"}-g{gpu}-{sequence:05d}.tar' partial=BUFFER/(name+'.partial');records=[];people=[] with tarfile.open(partial,'w',format=tarfile.USTAR_FORMAT) as tar: for ix in range(limit): if ix: person=claim(con,gpu,kind) if person is None:break wanted=float(person.get('lora_scale',1.0)) if in_scope(person): person['seed_strategy']='safety-per-emotion-attempt' if scorer is None: from laion_image_scorer import Scorer scorer=Scorer('cuda:0') if wanted!=scale: import gc del pipe;gc.collect();torch.cuda.empty_cache() pipe=create_native_pipeline('characters',device='cuda:0',compile_mode='default',cfg_mode='batched',adapter_scale=wanted) scale=wanted;warm_modes=set() cache={};encoding={} for e in person['expressions']: t=time.perf_counter();cache[e['id']]=encode_text(pipe,e['prompt']);torch.cuda.synchronize();encoding[e['id']]=time.perf_counter()-t if e['negative_prompt'] not in pipe._native_text_cache:pipe._native_text_cache[e['negative_prompt']]=encode_text(pipe,e['negative_prompt']) reference=None;reference_sha='' for e in person['expressions']: edit=e['emotion']!='neutral';torch.cuda.synchronize();t=time.perf_counter() im=generate_native_image(pipe,prompt_embeds=cache[e['id']],seed=e['seed'],steps=50,guidance=4., negative_prompt=e['negative_prompt'],image=reference if edit else None,width=832,height=1248)[0] torch.cuda.synchronize();seconds=time.perf_counter()-t safety=None if in_scope(person): im,actual,safety,extra=screen_frame(pipe,person,e,im,reference if edit else None,scorer) e.update(actual);seconds+=extra b=io.BytesIO();im.save(b,format='PNG',compress_level=4);png=b.getvalue() m=metadata(person,e,png,reference_sha,seconds,encoding[e['id']],name,'dedicated-GPU-preencoded-extension') if safety is not None: safety['image_sha256']=m['image_sha256'];m['safety_check']=safety m['runtime']['includes_compile_warmup']=edit not in warm_modes;warm_modes.add(edit) add_member(tar,e['id']+'.png',png);add_member(tar,e['id']+'.json',json.dumps(m,ensure_ascii=False,indent=2).encode());add_member(tar,e['id']+'.txt',e['prompt'].encode()) records.append(m);event(con,gpu,'image',dict(id=e['id'],person_id=person['personality_id'],seconds=seconds)) print(json.dumps(dict(id=e['id'],gpu=gpu,seconds=round(seconds,2))),flush=True) if not edit:reference=im.resize((416,624),Image.Resampling.BICUBIC);reference_sha=hashlib.sha256(png).hexdigest() if in_scope(person): persist_actual_plan(STATE,'person-plan.json','personality_id',person) con.execute('UPDATE people SET record=? WHERE id=?',(json.dumps(person,ensure_ascii=False,sort_keys=True),person['personality_id']));con.commit() people.append(person['personality_id']);first=False final=BUFFER/name;partial.replace(final) con.execute('BEGIN IMMEDIATE') con.execute('INSERT INTO shards VALUES(?,?,?,?,?,?,?,?,?)',(name,gpu,len(records),final.stat().st_size,sha(final),'ready',None,utc(),None)) for m in records:con.execute('INSERT INTO images VALUES(?,?,?,?,?)',(m['id'],m['personality_id'],m['emotion'],name,json.dumps(m,ensure_ascii=False))) for ident in people:con.execute("UPDATE people SET status='done',finished=? WHERE id=?",(utc(),ident)) con.commit();sequence+=1 if scorer is not None:scorer.close() event(con,gpu,'complete');print('Extension worker complete',gpu,flush=True) def upload(): from huggingface_hub import HfApi api=HfApi(token=os.environ['HF_TOKEN']);con=connect() while True: if not (STATE/'quality-gate-passed.json').exists():time.sleep(5);continue for r in con.execute("SELECT * FROM shards WHERE status='ready' ORDER BY created").fetchall(): try: from teen_generation_safety import approved_metadata assert all(approved_metadata(json.loads(m[0])) for m in con.execute('SELECT metadata FROM images WHERE shard=?',(r['name'],))),'Under-20 image lacks passing exact-checksum screening' path=BUFFER/r['name'];assert sha(path)==r['sha256'] commit=api.upload_file(path_or_fileobj=path,path_in_repo='extension-data/'+r['name'],repo_id=REPO,repo_type='dataset', commit_message=f"Add {r['count']} adult/special character images: {r['name']}") remote=next(f for f in api.dataset_info(REPO,revision=commit.oid,files_metadata=True).siblings if f.rfilename=='extension-data/'+r['name']) assert remote.size==r['bytes'] and remote.lfs.sha256==r['sha256'] con.execute("UPDATE shards SET status='uploaded',revision=?,uploaded=? WHERE name=?",(commit.oid,utc(),r['name']));con.commit() print(json.dumps(dict(uploaded=r['name'],images=r['count'],revision=commit.oid)),flush=True) except Exception as exc:print('Upload retry:',type(exc).__name__,str(exc),flush=True);time.sleep(10) progress=status(con);dump(STATE/'progress.json',progress) if progress['people'].get('done')==340 and progress['images_uploaded']==2500:return time.sleep(5) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('command',choices=['init','worker','status','upload','release-specials']);p.add_argument('--gpu',type=int);a=p.parse_args() if a.command=='init':init() elif a.command=='worker':worker(a.gpu) elif a.command=='upload':upload() elif a.command=='release-specials':release_specials() else:print(json.dumps(status(),indent=2))