diff --git a/scripts/render_arrival_all_composites.py b/scripts/render_arrival_all_composites.py new file mode 100755 index 0000000..c814b3c --- /dev/null +++ b/scripts/render_arrival_all_composites.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +""" +Tier-independent ArrivalAll composite renderer. +Usage: python3 render_arrival_all_composites.py --tier Wealthy [--workers 20] [--output-base /path] + +Generates: +- ArrivalAllMen A1-C6 (18 images) +- ArrivalAllLadies A1-C6 (18 images) +- ArrivalAllSingles A1-C6 (18 images, includes one twin if present) +""" +import argparse, base64, json, subprocess, time, 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.', +} + +def load_identities_from_manifests(manifest_dir): + """Load NPC identities from manifest JSON files.""" + 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 + # Also check top-level npc_profiles + for n, npc in data.get('npc_profiles', {}).items(): + if n not in identity_map: + identity_map[n] = npc + except Exception: + continue + return identity_map + +def discover_singles(dressed_dir, identity_map): + """Discover singles from Dressed folder and separate by gender.""" + males = [] + females = [] + + for f in dressed_dir.glob('*_Dressed__*.jpg'): + # Skip doubles/triples + if f.name.startswith(('Double_', 'DoubleTwin_', 'Triple_')): + continue + + # Extract name from filename + name_part = f.stem.split('_Dressed__')[0].replace('_Single_Courtesan_Wealthy', '').replace('_Single_Courtesan_Comfortable', '').replace('_Single_Courtesan_Modest', '').replace('_Single_Courtesan_Poor', '') + # Handle versioned names (e.g., _v2_E) + name_part = name_part.split('_v')[0].split('_D')[0].split('_E')[0].split('_A')[0].split('_B')[0].split('_C')[0] + + name_display = name_part.replace('_', ' ') + name_key = name_part + + npc_data = identity_map.get(name_key, {}) + identity = npc_data.get('identity', '') + gender = npc_data.get('gender', 'Unknown') + + if not identity: + print(f"⚠ Warning: No identity found for {name_display}") + continue + + npc_entry = {"name": name_display, "identity": identity} + + if gender == "Man": + males.append(npc_entry) + else: + females.append(npc_entry) + + return males, females + +def build_prompt(group_type, subjects, tier, letter, variant): + """Build prompt for ArrivalAll composite.""" + count = len(subjects) + + if group_type == "men": + group_desc = f"{count} adult men" if count > 1 else "one adult man" + elif group_type == "ladies": + group_desc = f"{count} adult women" + else: # all singles + male_count = sum(1 for s in subjects if 'Man' in str(s)) + female_count = count - male_count + group_desc = f"{count} adults ({female_count} women and {male_count} men)" + + list_desc = ", ".join([f"{s['name']} ({s['identity']})" for s in subjects]) + lobby_clause = LOBBY_LEVELS[letter] + stairs_clause = "visible staircase ascending in background" if variant > 3 else "no staircase visible" + + tier_desc = { + 'Poor': 'simple rustic', + 'Modest': 'modest comfortable', + 'Comfortable': 'comfortable well-appointed', + 'Wealthy': 'wealthy luxurious', + 'Elite': 'elite opulent', + 'Elite XL': 'extremely elite palatial', + 'Elite XXL': 'legendary palatial', + }.get(tier, 'medieval Norse') + + return f""" +{tier_desc.capitalize()} medieval Norse brothel lobby (arrival scene), with carved timber beams, tapestries, seating, warm firelight. +{group_desc} standing or seated in the lobby, all fully dressed in {tier}-tier clothing, smiling warmly and charmingly toward the camera. +Characters: {list_desc}. +Each character should be clearly identifiable with their distinctive features visible. +{lobby_clause} +Background gender mix: 80% women, 20% men. {stairs_clause}. +Main subjects: standing centered or seated on central furniture (not leaning against beams). +Photorealistic, cinematic 16:9, warm welcoming atmosphere. +No facial scars or injuries on main subjects. +{ANTI_MODERN} +{NEGATIVE_TEXT} +""".strip() + +def render_job(args, group_type, subjects, letter, variant, runhex, api_url, headers, out_dir): + group_name = {"men": "Men", "ladies": "Ladies", "singles": "Singles"}[group_type] + out_file = f"ArrivalAll{group_name}_{letter}{variant}__{runhex}.jpg" + out_path = out_dir / out_file + + if out_path.exists(): + return {"status": "skip"} + + prompt = build_prompt(group_type, subjects, args.tier, letter, variant) + + payload = { + "model": "grok-imagine-image", + "prompt": prompt, + "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", "file": out_file} + 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 ArrivalAll composites for a courtesan tier') + parser.add_argument('--tier', required=True, help='Tier name (e.g., Wealthy, Comfortable)') + parser.add_argument('--workers', type=int, default=20, help='Concurrent workers (default: 20)') + parser.add_argument('--output-base', default='/home/rick/output/to-dnd-session-rclone/Grok-NPCs/Courtesans', + help='Base output directory') + parser.add_argument('--skip-tier-subfolder', action='store_true', + help='Output directly to base (skip tier subfolder)') + parser.add_argument('--manifest-dir', default='/home/rick/.openclaw/workspace/memory/npc-run-manifests', + help='Manifest directory for identity lookup') + 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_from_manifests(Path(args.manifest_dir)) + + # Discover singles from Dressed folder + males, females = discover_singles(dressed_dir, identity_map) + all_singles = females + males # Females first + + print(f"{'='*60}") + print(f"{args.tier} ArrivalAll Composites") + print(f"{'='*60}") + print(f"Discovered: {len(males)} men, {len(females)} ladies") + print(f"Total singles: {len(all_singles)}\n") + + if not males and not females: + print("ERROR: No singles found in Dressed folder!") + return + + # 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/generations" + + runhex = os.urandom(4).hex() + + # Build job list + jobs = [] + if males: + for letter in ['A', 'B', 'C']: + for variant in range(1, 7): + jobs.append(("men", males, letter, variant)) + + if females: + for letter in ['A', 'B', 'C']: + for variant in range(1, 7): + jobs.append(("ladies", females, letter, variant)) + + if all_singles: + for letter in ['A', 'B', 'C']: + for variant in range(1, 7): + jobs.append(("singles", all_singles, letter, variant)) + + 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, args, *j, runhex, api_url, headers, out_dir): j for j in jobs} + for future in as_completed(futures): + result = future.result() + if result["status"] == "success": + success += 1 + if success % 10 == 0: + print(f"Progress: {success}/{len(jobs)}") + elif result["status"] == "skip": + skip += 1 + else: + failed += 1 + if failed <= 5: + 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()