#!/usr/bin/env python3 """ Tier-independent Arrival A1-C6 renderer (per individual NPC). Usage: python3 render_arrival_per_npc.py --tier Wealthy [--workers 20] Generates 18 Arrival images per NPC (A1-C6, B1-C6, C1-C6): - Variants 1-3: no staircase - Variants 4-6: visible staircase """ import argparse, base64, json, subprocess, os from pathlib import Path from concurrent.futures import ThreadPoolExecutor, as_completed import requests NEGATIVE_TEXT = "no text, no labels, no captions, no logos, no watermark, no signage, no letters, no symbols, no UI overlays" ANTI_MODERN = ( "Strict medieval Norse look: no bathrobes, no knit sweaters/cardigans, no modern trousers/pants, " "no lace-up modern boots, no tufted upholstery, no modern cushions/pillows, no folded towels, " "no modern plumbing/fixtures, no contemporary fabrics or cuts." ) LOBBY_LEVELS = { 'A': 'Background lobby patrons: adults only, fully dressed with full chest coverage (no bare chests, no exposed breasts, no bikini tops, no exposed midriff); out-of-focus with soft bokeh; some gently smiling toward camera, others chatting; crowd sparse.', 'B': 'Background lobby patrons: adults only, small sparse group; only 2-3 topless patrons; no fully naked patrons; rest fully dressed; out-of-focus with soft bokeh; some gently smiling toward camera, others chatting.', 'C': 'Background lobby patrons: adults only, small sparse group (same density as A/B); approximately 20% fully naked, 30% topless, rest fully dressed; out-of-focus with soft bokeh; some gently smiling toward camera, others chatting.', } TIER_DESCRIPTORS = { 'Poor': 'sparse rustic', 'Modest': 'modest comfortable', 'Comfortable': 'comfortable well-appointed', 'Wealthy': 'wealthy luxurious', 'Elite': 'elite opulent', 'Elite XL': 'extremely elite palatial', 'Elite XXL': 'legendary palatial', } def load_identities(manifest_dir): identity_map = {} for p in sorted([p for p in manifest_dir.glob('*.json') if 'payloads' not in p.name], key=lambda p: p.stat().st_mtime, reverse=True): try: data = json.load(p.open()) for npc in data.get('individuals', []): n = npc.get('name') if n and n not in identity_map: identity_map[n] = npc for pair in data.get('pairs', []): for npc in pair.get('npcs', []): n = npc.get('name') if n and n not in identity_map: identity_map[n] = npc except Exception: continue return identity_map def data_url(path: Path): return "data:image/jpeg;base64," + base64.b64encode(path.read_bytes()).decode() def extract_eye(identity: str): for part in identity.split(';'): if 'eye' in part.lower(): return part.strip() return None def build_prompt_single(name, identity, tier, letter, variant): eye = extract_eye(identity) or 'eyes' lobby_desc = LOBBY_LEVELS[letter] tier_desc = TIER_DESCRIPTORS.get(tier, 'medieval Norse') stairs = "visible staircase ascending in background" if variant > 3 else "no staircase visible" return f""" {tier_desc.capitalize()} medieval Norse brothel lobby (arrival scene), with carved timber beams, tapestries, warm firelight, appropriate spaciousness for the tier. Single adult, character name reference: {name}. Identity: {identity}. Eye color: {eye}. Eye color must match the reference exactly. Main subject fully dressed in exact same outfit as reference; no nudity on main subject. Pose: standing centered or seated on central furniture piece (not leaning against beam). {lobby_desc} Background gender mix: 80% women, 20% men. {stairs}. Eyes match reference exactly; preserve facial marks; no airbrushing. Smiling warmly and charmingly with welcoming expression toward camera. Cinematic 16:9, photorealistic, warm inviting atmosphere. No facial scars or injuries on main subject. {ANTI_MODERN} {NEGATIVE_TEXT} """.strip() def build_prompt_pair(names, identities, twin, tier, letter, variant): name1, name2 = names id1, id2 = identities lobby_desc = LOBBY_LEVELS[letter] tier_desc = TIER_DESCRIPTORS.get(tier, 'medieval Norse') stairs = "visible staircase ascending in background" if variant > 3 else "no staircase visible" if twin: twin_clause = "identical twins with same face, features, and marks" id_clause = f"Identity for both: {id1}." eye1 = extract_eye(id1) eye_clause = f"Eye color for both: {eye1}." if eye1 else "" else: twin_clause = "distinct faces with clearly different features" id_clause = f"Identity {name1}: {id1}. Identity {name2}: {id2}." eye1 = extract_eye(id1) eye2 = extract_eye(id2) eye_clause = f"Eye colors: {name1} {eye1 or 'match ref'}, {name2} {eye2 or 'match ref'}." if eye1 or eye2 else "" return f""" {tier_desc.capitalize()} medieval Norse brothel lobby (arrival scene), with carved timber beams, tapestries, warm firelight, appropriate spaciousness for the tier. Two adult women ({twin_clause}), character name references: {name1} and {name2}. {id_clause} {eye_clause} Both main subjects fully dressed in exact same outfits as reference; no nudity on main subjects. Pose: standing centered or seated on central furniture pieces (not leaning against beam). {lobby_desc} Background gender mix: 80% women, 20% men. {stairs}. Eyes match reference exactly; preserve facial marks; no airbrushing. Smiling warmly and charmingly with welcoming expressions toward camera. Cinematic 16:9, photorealistic, warm inviting atmosphere. No facial scars or injuries on main subjects. {ANTI_MODERN} {NEGATIVE_TEXT} """.strip() def render_job(ref_path, npc_info, tier, letter, variant, runhex, api_url, headers, out_dir): npc_type, base_name, is_twin, identity_map = npc_info out_file = f"{base_name}_Arrival_{letter}{variant}__{runhex}.jpg" out_path = out_dir / out_file if out_path.exists(): return {"status": "skip"} if npc_type == "single": name_display = base_name.replace('_', ' ') npc_data = identity_map.get(base_name, {}) identity = npc_data.get('identity', '') prompt = build_prompt_single(name_display, identity, tier, letter, variant) else: # pair parts = base_name.replace('DoubleTwin_', '').replace('Double_', '').split('_') name1 = f"{parts[0]} {parts[1]}" name2 = f"{parts[2]} {parts[3]}" id1 = identity_map.get(f"{parts[0]}_{parts[1]}", {}).get('identity', '') id2 = identity_map.get(f"{parts[2]}_{parts[3]}", {}).get('identity', '') prompt = build_prompt_pair((name1, name2), (id1, id2), is_twin, tier, letter, variant) payload = { "model": "grok-imagine-image", "prompt": prompt, "image": {"url": data_url(ref_path)}, "aspect_ratio": "16:9", } try: r = requests.post(api_url, headers=headers, data=json.dumps(payload), timeout=90) if r.status_code == 200: url = r.json()["data"][0]["url"] subprocess.run(["curl", "-sS", "-L", url, "-o", str(out_path)], check=True, timeout=60) return {"status": "success"} else: return {"status": "failed", "error": f"HTTP {r.status_code}"} except Exception as e: return {"status": "exception", "error": str(e)} def main(): parser = argparse.ArgumentParser(description='Render Arrival A1-C6 per NPC for a courtesan tier') parser.add_argument('--tier', required=True) parser.add_argument('--workers', type=int, default=20) parser.add_argument('--output-base', default='/home/rick/output/to-dnd-session-rclone/Grok-NPCs/Courtesans') parser.add_argument('--skip-tier-subfolder', action='store_true') args = parser.parse_args() tier_dir = Path(args.output_base) if args.skip_tier_subfolder else Path(args.output_base) / args.tier dressed_dir = tier_dir / 'Dressed' out_dir = tier_dir / 'Arrival' out_dir.mkdir(parents=True, exist_ok=True) # Load identities identity_map = load_identities(Path('/home/rick/.openclaw/workspace/memory/npc-run-manifests')) # Get API key key = subprocess.check_output(['bash', '-lc', 'pass show x.ai/apikey | head -n1']).decode().strip() headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"} api_url = "https://api.x.ai/v1/images/edits" runhex = os.urandom(4).hex() print(f"{'='*60}") print(f"{args.tier} Arrival A1-C6 per NPC (runhex={runhex})") print(f"{'='*60}\n") # Build jobs from Dressed keepers jobs = [] # Singles for p in dressed_dir.glob('*_Dressed__*.jpg'): if p.name.startswith(('Double_', 'DoubleTwin_', 'Triple_')): continue base = p.stem.split('_Dressed__')[0] for letter in ['A', 'B', 'C']: for variant in range(1, 7): # Check if already exists if list(out_dir.glob(f"{base}_Arrival_{letter}{variant}__*.jpg")): continue jobs.append((p, ("single", base, False, identity_map), args.tier, letter, variant, runhex, api_url, headers, out_dir)) # Doubles for p in dressed_dir.glob('Double_*__*.jpg'): base = p.stem.split('__')[0] for letter in ['A', 'B', 'C']: for variant in range(1, 7): if list(out_dir.glob(f"{base}_Arrival_{letter}{variant}__*.jpg")): continue jobs.append((p, ("pair", base, False, identity_map), args.tier, letter, variant, runhex, api_url, headers, out_dir)) # DoubleTwins for p in dressed_dir.glob('DoubleTwin_*__*.jpg'): base = p.stem.split('__')[0] for letter in ['A', 'B', 'C']: for variant in range(1, 7): if list(out_dir.glob(f"{base}_Arrival_{letter}{variant}__*.jpg")): continue jobs.append((p, ("pair", base, True, identity_map), args.tier, letter, variant, runhex, api_url, headers, out_dir)) print(f"Total jobs: {len(jobs)}\n") success, failed, skip = 0, 0, 0 with ThreadPoolExecutor(max_workers=args.workers) as ex: futures = {ex.submit(render_job, *j): j for j in jobs} for future in as_completed(futures): result = future.result() if result["status"] == "success": success += 1 if success % 50 == 0: print(f"Progress: {success}/{len(jobs)}") elif result["status"] == "skip": skip += 1 else: failed += 1 if failed <= 10: print(f"FAIL: {result.get('error', '?')[:100]}") print(f"\n{'='*60}") print(f"DONE: ok={success} fail={failed} skip={skip}") print(f"{'='*60}") if __name__ == "__main__": main()