Files
openclaw-npc-nudity-workflo…/scripts/render_arrival_all_composites.py
2026-03-26 18:05:40 +00:00

347 lines
13 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Tier-independent ArrivalAll composite renderer.
Uses native-resolution Dressed-image grids as the reference input to /images/edits,
so the final lobby overviews preserve exact faces and outfits without the clothing
hallucinations from text-only generation and without blur/distortion from resizing.
Outputs:
- ArrivalAllMen_A1-C6
- ArrivalAllLadies_A1-C6
- ArrivalAllSingles_A1-C6
"""
import argparse
import base64
import json
import os
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests
try:
from PIL import Image
except ImportError as e:
raise SystemExit(
"Pillow is required for render_arrival_all_composites.py. "
"Run with ~/.openclaw/workspace/.venv-pillow/bin/python3 or install pillow."
) from e
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 and appropriate to spacious room size.",
"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_DESCRIPTIONS = {
"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",
}
def data_url(path: Path) -> str:
return "data:image/jpeg;base64," + base64.b64encode(path.read_bytes()).decode()
def load_identities_from_manifests(manifest_dir: Path):
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())
except Exception:
continue
candidates = []
if isinstance(data.get("individuals"), list):
candidates.extend(data["individuals"])
if isinstance(data.get("pairs"), list):
for pair in data["pairs"]:
candidates.extend(pair.get("npcs", []))
if isinstance(data.get("npc_profiles"), dict):
candidates.extend(data["npc_profiles"].values())
if data.get("courtesan"):
candidates.append({
"name": data.get("courtesan"),
"identity": _extract_identity_from_run_manifest(data),
})
for npc in candidates:
name = npc.get("name")
if not name:
continue
for key in {name, name.replace(" ", "_")}:
if key not in identity_map:
identity_map[key] = npc
return identity_map
def _extract_identity_from_run_manifest(data):
for img in data.get("images", []):
for attempt in img.get("attempts", []):
prompt = attempt.get("prompt", "")
if "Identity: " in prompt:
return prompt.split("Identity: ", 1)[1].split("\n", 1)[0].strip()
return ""
def normalize_single_base(raw_base: str, tier: str) -> str:
base = raw_base.split("_Dressed", 1)[0]
tier_token = tier.replace(" ", "_")
for marker in [
f"_Single_Courtesan_{tier_token}",
f"_Courtesan_{tier_token}",
]:
if marker in base:
base = base.replace(marker, "")
return base
def infer_gender(raw_base: str, normalized_base: str, identity_map: dict) -> str:
# In Rick's current Dressed naming, _Single_Courtesan_ singles are the men.
if "_Single_Courtesan_" in raw_base:
return "male"
npc = identity_map.get(normalized_base) or identity_map.get(normalized_base.replace("_", " ")) or {}
gender = str(npc.get("gender", "")).lower()
if gender in {"man", "male"}:
return "male"
return "female"
def discover_singles(dressed_dir: Path, identity_map: dict, tier: str):
males = []
females = []
for f in sorted(dressed_dir.glob("*.jpg")):
if f.name.startswith(("Double_", "DoubleTwin_", "Triple_")):
continue
raw_base = f.stem.split("__", 1)[0]
normalized = normalize_single_base(raw_base, tier)
display_name = normalized.replace("_", " ")
npc = identity_map.get(normalized) or identity_map.get(display_name) or {}
identity = npc.get("identity", "")
entry = {
"name": display_name,
"identity": identity,
"path": f,
"gender": infer_gender(raw_base, normalized, identity_map),
}
if entry["gender"] == "male":
males.append(entry)
else:
females.append(entry)
return males, females
def layout_for_count(count: int):
if count <= 2:
return count, 1
if count <= 4:
return 2, 2
if count <= 6:
return 3, 2
if count <= 9:
return 3, 3
return 4, 3
def create_native_grid(subjects, output_path: Path):
images = []
widths = []
heights = []
for subject in subjects:
img = Image.open(subject["path"]).convert("RGB")
images.append((subject, img))
widths.append(img.width)
heights.append(img.height)
if not images:
raise ValueError(f"No images available for grid {output_path}")
cols, rows = layout_for_count(len(images))
cell_w = max(widths)
cell_h = max(heights)
used_w = cols * cell_w
used_h = rows * cell_h
target_ratio = 16 / 9
actual_ratio = used_w / used_h
if actual_ratio < target_ratio:
canvas_w = int(round(used_h * target_ratio))
canvas_h = used_h
else:
canvas_w = used_w
canvas_h = int(round(used_w / target_ratio))
canvas = Image.new("RGB", (canvas_w, canvas_h), (20, 20, 20))
origin_x = (canvas_w - used_w) // 2
origin_y = (canvas_h - used_h) // 2
for idx, (_, img) in enumerate(images):
row = idx // cols
col = idx % cols
x = origin_x + col * cell_w + (cell_w - img.width) // 2
y = origin_y + row * cell_h + (cell_h - img.height) // 2
canvas.paste(img, (x, y))
output_path.parent.mkdir(parents=True, exist_ok=True)
canvas.save(output_path, quality=98, subsampling=0)
return output_path
def build_prompt(group_type: str, subjects, tier: str, letter: str, variant: int):
if group_type == "men":
group_desc = f"{len(subjects)} adult men"
elif group_type == "ladies":
group_desc = f"{len(subjects)} adult women"
else:
male_count = sum(1 for s in subjects if s["gender"] == "male")
female_count = len(subjects) - male_count
group_desc = f"{len(subjects)} adults ({female_count} women and {male_count} men)"
list_desc = ", ".join(
f"{s['name']} ({s['identity']})" if s.get('identity') else s['name']
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 = TIER_DESCRIPTIONS.get(tier, "medieval Norse")
return f"""
{tier_desc.capitalize()} medieval Norse brothel lobby (arrival scene), spacious with carved timber beams, tapestries, seating, and warm firelight.
{group_desc}, character name references: {list_desc}.
Use the provided reference image to preserve each main subject's exact face, outfit, colors, and overall styling.
All main subjects fully dressed in their exact same outfits as shown in the reference; no nudity on main subjects.
Main subjects standing centered or seated on central furniture; not leaning against beams.
{lobby_clause}
Background gender mix: 80% women, 20% men. {stairs_clause}.
Smiling warmly and charmingly with welcoming expressions toward camera.
Photorealistic, cinematic 16:9, warm inviting atmosphere.
No facial scars or injuries on main subjects.
{ANTI_MODERN}
{NEGATIVE_TEXT}
""".strip()
def render_job(group_type: str, subjects, ref_path: Path, tier: str, letter: str, variant: int, runhex: str, out_dir: Path, api_url: str, headers: dict):
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, 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", "file": out_file}
return {"status": "failed", "error": f"HTTP {r.status_code}: {r.text[:200]}"}
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)
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")
parser.add_argument("--manifest-dir", default="/home/rick/.openclaw/workspace/memory/npc-run-manifests")
parser.add_argument("--tmp-dir", default="/home/rick/.openclaw/workspace/tmp")
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)
tmp_dir = Path(args.tmp_dir)
tmp_dir.mkdir(parents=True, exist_ok=True)
identity_map = load_identities_from_manifests(Path(args.manifest_dir))
males, females = discover_singles(dressed_dir, identity_map, args.tier)
singles = females + males
print("=" * 68)
print(f"{args.tier} ArrivalAll native-res composites")
print("=" * 68)
print(f"Discovered singles: {len(females)} ladies, {len(males)} men")
if not singles:
raise SystemExit("No singles discovered in Dressed folder.")
tier_slug = args.tier.lower().replace(" ", "_")
groups = []
if males:
groups.append(("men", males, tmp_dir / f"{tier_slug}_men_dressed_grid_16x9_native.jpg"))
if females:
groups.append(("ladies", females, tmp_dir / f"{tier_slug}_ladies_dressed_grid_16x9_native.jpg"))
groups.append(("singles", singles, tmp_dir / f"{tier_slug}_all_singles_dressed_grid_16x9_native.jpg"))
for group_type, subjects, grid_path in groups:
create_native_grid(subjects, grid_path)
print(f"Grid ready: {grid_path.name} ({len(subjects)} subjects)")
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()
jobs = []
for group_type, subjects, grid_path in groups:
for letter in ["A", "B", "C"]:
for variant in range(1, 7):
jobs.append((group_type, subjects, grid_path, args.tier, letter, variant, runhex, out_dir, api_url, headers))
print(f"Total jobs: {len(jobs)}\n")
sys.stdout.flush()
success = failed = skip = 0
with ThreadPoolExecutor(max_workers=args.workers) as ex:
futures = {ex.submit(render_job, *job): job for job in jobs}
for i, future in enumerate(as_completed(futures), start=1):
result = future.result()
if result["status"] == "success":
success += 1
elif result["status"] == "skip":
skip += 1
else:
failed += 1
if failed <= 5:
print(f"FAIL: {result.get('error', '?')[:140]}")
if i % 10 == 0:
print(f"Progress: {i}/{len(jobs)}")
sys.stdout.flush()
print("\n" + "=" * 68)
print(f"DONE: ok={success} fail={failed} skip={skip} runhex={runhex}")
print("=" * 68)
if __name__ == "__main__":
main()