"""Screen future under-20 human sprites before they enter an uploadable TAR.""" import fcntl import hashlib import json from pathlib import Path import sqlite3 import time from background_production import dump, utc from minor_safety_policy import passes, accepted_signatures ROOT = Path(__file__).resolve().parents[1] STATE = ROOT / 'experiments/minor-safety' def in_scope(record): age = record.get('age_years') return isinstance(age, int) and age <= 19 def screen_frame(pipe, record, expression, image, reference, scorer): """Keep the first passing candidate; record actual seeds for any retry.""" from native_flux_inference import generate_native_image, encode_text import torch policy = json.loads((STATE / 'policy.json').read_text()) actual = dict(expression) extra_seconds = 0.0 original_seed = actual['seed'] for attempt in range(33): score = scorer.score([image])[0] score.update(id=actual['id'], attempt=attempt, utc=utc(), policy_sha256=policy['policy_sha256'], passed=passes(score, policy)) if score['passed']: return image, actual, score, extra_seconds with (STATE / 'future-teen-rejected-candidates.jsonl').open('a') as out: out.write(json.dumps(dict(production_phase=record.get('production_phase'), original_seed=original_seed, actual_seed=actual['seed'], **score)) + '\n') if attempt == 32: raise RuntimeError('No passing under-20 sprite after33 checked candidates: ' + actual['id']) actual['seed'] = int.from_bytes(hashlib.sha256( f'vivarium-under20-safe:{actual["id"]}:{original_seed}:{attempt+1}'.encode()).digest()[:4], 'big') actual['negative_prompt'] = expression['negative_prompt'] + ', nudity, underwear, revealing clothing, sexualized, suggestive pose' torch.cuda.synchronize() started = time.perf_counter() embeds = encode_text(pipe, actual['prompt']) image = generate_native_image(pipe, prompt_embeds=embeds, seed=actual['seed'], steps=50, guidance=4., negative_prompt=actual['negative_prompt'], image=reference, width=832, height=1248)[0] torch.cuda.synchronize() extra_seconds += time.perf_counter() - started def persist_actual_plan(state, filename, key, record): """Serialize worker updates without losing another identity's actual seeds.""" path = state / filename with (state / 'actual-plan.lock').open('a+') as lock: fcntl.flock(lock, fcntl.LOCK_EX) original = state / ('original-' + filename) if not original.exists(): original.write_bytes(path.read_bytes()) plan = json.loads(path.read_text()) indices = [i for i, item in enumerate(plan) if item[key] == record[key]] assert len(indices) == 1 plan[indices[0]] = record dump(path, plan) def approved_metadata(metadata): if not in_scope(metadata): return True policy = json.loads((STATE / 'policy.json').read_text()) score = metadata.get('safety_check', {}) if not score: with sqlite3.connect(STATE / 'scores.sqlite') as db: row = db.execute('SELECT record FROM scores WHERE id=? AND image_sha256=? AND policy_sha256=?', (metadata['id'], metadata['image_sha256'], policy['policy_sha256'])).fetchone() if row: score = json.loads(row[0]) score['passed'] = score.get('decision') == 'pass' return (score.get('passed') is True and score.get('policy_sha256') in accepted_signatures(policy) and score.get('image_sha256') == metadata['image_sha256'] and set(score.get('views', {})) == {'original', 'foreground'} and passes(score, policy))