#!/usr/bin/env python3 """ Tier-independent Dressed A-E regeneration from Undressed keepers. Usage: python3 render_dressed_ae.py --tier Wealthy --clothing-manifest /path/to/clothing.json [--workers 4] Requires a clothing manifest JSON with structure: { "tier": "Wealthy", "entries": [ {"name": "Name Surname", "clothing": "detailed clothing description", "scene": "optional"} ] } """ 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." ) POSE_VARIANTS = { 'A': 'standing relaxed, hands at sides', 'B': 'seated on a cushioned bench, relaxed posture', 'C': 'leaning lightly against a timber post, one hand on the belt', 'D': 'walking slowly with a small step, garment swaying', 'E': 'adjusting the collar or belt with one hand', } 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, clothing, tag): eye = extract_eye(identity) or 'eyes' pose = POSE_VARIANTS[tag] return f""" Single adult, character name reference: {name}. Identity: {identity}. Eye color: {eye}. Eye color must match the reference exactly. Dressed stage: fully clothed in {clothing}. Same setting/scene as reference image; consistent architecture and lighting. Pose: {pose}. Keep the same face/likeness as the reference; preserve facial marks exactly; no airbrushing. Smiling warmly with calm, welcoming expression and direct eye contact. Cinematic 16:9, photorealistic, warm intimate lighting. No facial scars or injuries. {ANTI_MODERN} {NEGATIVE_TEXT} """.strip() def build_prompt_pair(names, identities, clothing, tag, twin): name1, name2 = names id1, id2 = identities pose = POSE_VARIANTS[tag] if twin: twin_clause = "identical twins with same face, features, and marks" id_clause = f"Identity for both: {id1}." else: twin_clause = "distinct faces with clearly different features" id_clause = f"Identity {name1}: {id1}. Identity {name2}: {id2}." return f""" Two adult women ({twin_clause}), character name references: {name1} and {name2}. {id_clause} Dressed stage: both fully clothed in {clothing}. Same setting/scene as reference image; consistent architecture and lighting. Pose: {pose}. Keep the same face/likeness as the reference; preserve facial marks exactly; no airbrushing. Smiling warmly with calm, welcoming expressions and direct eye contact. Cinematic 16:9, photorealistic, warm intimate lighting. No facial scars or injuries. {ANTI_MODERN} {NEGATIVE_TEXT} """.strip() def render_job(ref_path, npc_info, tag, runhex, api_url, headers, out_dir): npc_type, base_name, is_twin, name_display, identity, clothing = npc_info out_file = f"{base_name}_Dressed_{tag}__{runhex}.jpg" out_path = out_dir / out_file if out_path.exists(): return {"status": "skip"} if npc_type == "single": prompt = build_prompt_single(name_display, identity, clothing, tag) else: # pair parts = base_name.replace('DoubleTwin_', '').replace('Double_', '').split('_') name1 = f"{parts[0]} {parts[1]}" name2 = f"{parts[2]} {parts[3]}" # For pairs, identities is a tuple (id1, id2) prompt = build_prompt_pair((name1, name2), identity, clothing, tag, is_twin) payload = { "model": "grok-imagine-image-pro", "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 Dressed A-E from Undressed keepers') parser.add_argument('--tier', required=True) parser.add_argument('--clothing-manifest', required=True, help='Path to clothing JSON manifest') parser.add_argument('--workers', type=int, default=4, help='Concurrent workers (default: 4 for Pro model)') 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 undressed_dir = tier_dir / 'Undressed' out_dir = tier_dir / 'Dressed' out_dir.mkdir(parents=True, exist_ok=True) # Load clothing manifest clothing_data = json.load(Path(args.clothing_manifest).open()) clothing_by_name = {e['name']: e for e in clothing_data['entries']} # 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} Dressed A-E from Undressed keepers (runhex={runhex})") print(f"{'='*60}\n") # Build jobs from Undressed keepers jobs = [] # Singles for p in undressed_dir.glob('*_Undressed__*.jpg'): if p.name.startswith(('Double_', 'DoubleTwin_', 'Triple_')): continue base = p.stem.split('_Undressed__')[0] name_display = base.replace('_', ' ') name_key = base.replace(f'_Single_Courtesan_{args.tier}', '').replace('_Courtesan_' + args.tier, '') clothing_entry = clothing_by_name.get(name_display) if not clothing_entry: print(f"⚠ Skip {name_display}: no clothing definition") continue clothing_desc = clothing_entry['clothing'] npc_data = identity_map.get(name_key, {}) identity = npc_data.get('identity', '') for tag in ['A', 'B', 'C', 'D', 'E']: if list(out_dir.glob(f"{base}_Dressed_{tag}__*.jpg")): continue jobs.append((p, ("single", base, False, name_display, identity, clothing_desc), tag, runhex, api_url, headers, out_dir)) # Doubles and Twins - similar pattern for pattern in ['Double_*_Undressed__*.jpg', 'DoubleTwin_*_Undressed__*.jpg']: is_twin = 'Twin' in pattern for p in undressed_dir.glob(pattern): base = p.stem.split('_Undressed__')[0] parts = base.replace('DoubleTwin_', '').replace('Double_', '').split('_') # Extract scene from filename (last part before runhex) scene_part = parts[-1] if len(parts) > 4 else '' pair_key = f"{parts[0]} {parts[1]}, {parts[2]} {parts[3]}" clothing_entry = clothing_by_name.get(pair_key) if not clothing_entry: continue clothing_desc = clothing_entry['clothing'] id1 = identity_map.get(f"{parts[0]}_{parts[1]}", {}).get('identity', '') id2 = identity_map.get(f"{parts[2]}_{parts[3]}", {}).get('identity', '') for tag in ['A', 'B', 'C', 'D', 'E']: if list(out_dir.glob(f"{base}_Dressed_{tag}__*.jpg")): continue jobs.append((p, ("pair", base, is_twin, pair_key, (id1, id2), clothing_desc), tag, 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 % 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()