From 9066673a5e148425afca71b6a107fd609cf75ce3 Mon Sep 17 00:00:00 2001 From: "Dolon (Agent)" Date: Tue, 24 Mar 2026 17:10:55 +0000 Subject: [PATCH] =?UTF-8?q?Add=20render=5Fcourtesans=5Ftriples=5Ffullynake?= =?UTF-8?q?d.py=20=E2=80=94=20triples=20baseline?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Companion to doublepairs script; handles triple-courtesan Undressed renders. Uses same FullyNaked recipe (pro model, V4→V1, narrative clauses). Completes the render script collection (pairs + triples; twins handled via doublepairs with is_twins flag). --- .../render_courtesans_triples_fullynaked.py | 403 ++++++++++++++++++ 1 file changed, 403 insertions(+) create mode 100644 scripts/render_courtesans_triples_fullynaked.py diff --git a/scripts/render_courtesans_triples_fullynaked.py b/scripts/render_courtesans_triples_fullynaked.py new file mode 100644 index 0000000..8223c50 --- /dev/null +++ b/scripts/render_courtesans_triples_fullynaked.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +import datetime as dt +import json +import os +import pathlib +import re +import subprocess +import time +import uuid + +API_URL = "https://api.x.ai/v1/images/generations" +MODEL = "grok-imagine-image" +ASPECT = "16:9" +MAX_ATTEMPTS = 4 # V4×2 -> V1×2 + +V4_CLAUSE = ( + "short, neatly trimmed pubic hair matching head-hair color, " + "tasteful classical nude figure-study framing" +) +V1_CLAUSE = ( + "short, neatly trimmed pubic hair matching head-hair color, " + "gentle, non-erotic life-drawing study framing" +) + +NEGATIVE_TEXT = ( + "no text, no labels, no captions, no logos, no watermark, no signage, no letters, " + "no symbols, no UI overlays" +) + +BASE_OUT = pathlib.Path("/home/rick/output/to-dnd-session/Grok-NPCs/Courtesans") +MANIFEST_DIR = pathlib.Path("/home/rick/.openclaw/workspace/memory/npc-run-manifests") +SOURCE_MANIFEST = MANIFEST_DIR / "courtesans-doublepairs-fullynaked-rerender-smile-resume-20260319-010351.json" +LOG_PATH = pathlib.Path("/home/rick/.openclaw/workspace/logs/courtesans_triples_gen.log") + +TIER_SETTINGS = { + "Wealthy": [ + {"slug": "marblebath", "desc": "polished bathhouse with tiled pool, brass fixtures, and soft steam"}, + {"slug": "plushfurs", "desc": "plush furs on a raised daybed with velvet pillows"}, + {"slug": "canopybed", "desc": "private bedchamber with a canopy bed, linen drapes, and warm light"}, + ], + "Elite": [ + {"slug": "marblebath", "desc": "marble bathhouse with mist, carved columns, and soft candlelight"}, + {"slug": "velvetdivan", "desc": "velvet-covered divan beside rich tapestries and carved wood"}, + {"slug": "opulentbed", "desc": "opulent bedchamber with a carved canopy bed and silk linens"}, + ], + "Elite XL": [ + {"slug": "mosaicspa", "desc": "grand spa suite with mosaic pool, carved stone, and drifting steam"}, + {"slug": "silkfurs", "desc": "silken furs on a raised dais with velvet pillows"}, + {"slug": "royalbed", "desc": "royal bedchamber with a tall canopy, silk curtains, and warm glow"}, + ], + "Elite XXL": [ + {"slug": "palatialbath", "desc": "palatial bath hall with marble pool, gold inlay, and drifting steam"}, + {"slug": "luxfurpavilion", "desc": "luxury fur pavilion with velvet canopies and rich textures"}, + {"slug": "imperialbed", "desc": "imperial bedchamber with a massive canopy bed and silk"}, + ], +} + +FAILED_ONLY = { + "Elite XL": ["royalbed"], +} + +TRIPLETS = { + "Wealthy": [ + "Solveig Goldleaf", + "Thyra Roseglen", + "Dagny Seabloom", + ], + "Elite": [ + "Brynhild Starweave", + "Gudrun Moonbraid", + "Idunn Stormlace", + ], + "Elite XL": [ + "Astrid Dawnspire", + "Linnea Frostgild", + "Katla Silkshore", + ], + "Elite XXL": [ + "Adalind Crownmere", + "Celina Jadeveil", + "Brenna Silverquill", + ], +} + + +def _log(msg: str) -> None: + ts = dt.datetime.utcnow().isoformat() + LOG_PATH.parent.mkdir(parents=True, exist_ok=True) + with LOG_PATH.open("a", encoding="utf-8") as f: + f.write(f"{ts} {msg}\n") + + +def run_cmd(cmd: list, timeout: int = 120) -> subprocess.CompletedProcess: + return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) + + +def get_api_key() -> str: + res = run_cmd(["pass", "show", "x.ai/apikey"], timeout=30) + if res.returncode != 0: + raise RuntimeError(f"Failed to read API key: {res.stderr.strip()}") + return res.stdout.strip().splitlines()[0] + + +def curl_json_with_code(api_key: str, payload: dict): + payload_str = json.dumps(payload) + cmd = [ + "curl", + "-sS", + "-w", + "\nHTTP_CODE:%{http_code}", + "-H", + "Content-Type: application/json", + "-H", + f"Authorization: Bearer {api_key}", + "--data", + payload_str, + API_URL, + ] + res = run_cmd(cmd, timeout=120) + raw = res.stdout + http_code = 0 + body = raw + if "HTTP_CODE:" in raw: + body, code = raw.rsplit("HTTP_CODE:", 1) + body = body.rstrip("\n") + try: + http_code = int(code.strip()) + except ValueError: + http_code = 0 + data = None + if body.strip(): + try: + data = json.loads(body) + except json.JSONDecodeError: + data = None + return http_code, data, body + + +def curl_download(url: str, out_path: pathlib.Path) -> pathlib.Path: + tmp_path = out_path.with_suffix(out_path.suffix + ".tmp") + cmd = [ + "curl", + "-sS", + "-L", + "-f", + "--max-time", + "60", + "-o", + str(tmp_path), + url, + ] + res = run_cmd(cmd, timeout=120) + if res.returncode != 0 or not tmp_path.exists() or tmp_path.stat().st_size == 0: + if tmp_path.exists(): + tmp_path.unlink(missing_ok=True) + raise RuntimeError("download failed") + tmp_path.replace(out_path) + return out_path + + +def is_moderation_reject(http_code: int, data, raw: str) -> bool: + text = "" + if isinstance(data, dict) and data.get("error"): + err = data.get("error") + if isinstance(err, dict): + text = (err.get("message") or err.get("error") or "").lower() + else: + text = str(err).lower() + if "moderation" in text or "content moderation" in text: + return True + if raw and "content moderation" in raw.lower(): + return True + if http_code == 400 and raw and "moderation" in raw.lower(): + return True + return False + + +def slugify(text: str) -> str: + text = re.sub(r"[^A-Za-z0-9]+", "_", text) + return text.strip("_") + + +def build_triple_prompt(triple, setting_desc: str, variant_clause: str) -> str: + n1, n2, n3 = triple + a1, a2, a3 = n1["age"], n2["age"], n3["age"] + id1, id2, id3 = n1["identity"], n2["identity"], n3["identity"] + prompt = f""" +Three clearly adult women (ages {a1}, {a2}, and {a3}) in a cozy, intimate medieval Norse setting: {setting_desc}. + +Woman A ({n1['name']}): {id1}. +Woman B ({n2['name']}): {id2}. +Woman C ({n3['name']}): {id3}. +They have distinct faces and clearly different facial features, hair colors, hairstyles, and skin tones. +Overall composition resembles a museum-quality, non-erotic life drawing study. + +All three women are completely unclothed, visible and unobstructed nipples, {variant_clause}. +Each woman's pubic hair matches her own head-hair color (no cross-matching), short and sparse, confined strictly to pubic area only; no hair on breasts/abdomen; no solid triangle. +They smile warmly with inviting, gentle eye contact toward the viewer (not daydreaming or angry). +They stand or sit together with respectful spacing; no sexual interaction. +No sexual acts or erotic posing. Classical, non-erotic figure-study portrait. +Full-body, head-to-toe composition showing all three women; no waist-cropping. +Photorealistic, cinematic lighting, 16:9. +{NEGATIVE_TEXT}. +""".strip() + return prompt + + +def render_with_workflow(api_key: str, prompt_builder, out_path: pathlib.Path): + attempts = [] + final_status = "failed" + final_error = "" + final_http_code = 0 + output_path = None + + for attempt in range(1, MAX_ATTEMPTS + 1): + variant = "V4" if attempt <= 2 else "V1" + clause = V4_CLAUSE if variant == "V4" else V1_CLAUSE + prompt = prompt_builder(clause) + + payload = { + "model": MODEL, + "prompt": prompt, + "aspect_ratio": ASPECT, + } + + http_code = 0 + status = "failed" + err_snip = "" + image_url = "" + try: + _log(f"RENDER_ATTEMPT out={out_path} attempt={attempt} variant={variant}") + http_code, data, raw = curl_json_with_code(api_key, payload) + final_http_code = http_code + + if isinstance(data, dict) and data.get("error"): + err_snip = json.dumps(data.get("error")) + if is_moderation_reject(http_code, data, raw): + status = "moderation_rejected" + else: + status = "failed" + raise RuntimeError(err_snip) + + data_list = data.get("data") if isinstance(data, dict) else None + if not data_list or not isinstance(data_list, list) or not data_list[0].get("url"): + err_snip = raw.strip()[:200] + status = "failed" + raise RuntimeError(f"missing image URL: {err_snip}") + + image_url = data_list[0]["url"] + actual_path = curl_download(image_url, out_path) + output_path = str(actual_path) + status = "success" + final_status = "success" + final_error = "" + _log(f"RENDER_SUCCESS out={output_path} http={http_code}") + attempts.append( + { + "attempt": attempt, + "variant": variant, + "http_code": http_code, + "status": status, + "image_url": image_url, + } + ) + break + except Exception as exc: + if not err_snip: + err_snip = str(exc) + final_error = err_snip + attempts.append( + { + "attempt": attempt, + "variant": variant, + "http_code": http_code, + "status": status, + "error": err_snip, + "image_url": image_url, + } + ) + _log(f"RENDER_FAIL out={out_path} attempt={attempt} variant={variant} error={err_snip}") + time.sleep(2 + attempt) + + return { + "status": final_status, + "final_error": final_error, + "final_http_code": final_http_code, + "output_path": output_path, + "attempts": attempts, + } + + +def main(): + LOG_PATH.parent.mkdir(parents=True, exist_ok=True) + _log("START courtesans triples FullyNaked") + + with SOURCE_MANIFEST.open("r", encoding="utf-8") as f: + source = json.load(f) + + npc_by_name = {} + for pair in source.get("pairs", []): + for npc in pair.get("npcs", []): + npc_by_name[npc["name"]] = npc + + runhex = uuid.uuid4().hex[:8] + created_at = dt.datetime.utcnow().isoformat() + + tiers_meta = {} + for tier, names in TRIPLETS.items(): + triplet = [] + for name in names: + if name not in npc_by_name: + raise RuntimeError(f"NPC not found in source manifest: {name}") + triplet.append(npc_by_name[name]) + tiers_meta[tier] = { + "triplet": triplet, + "settings": TIER_SETTINGS[tier], + } + + images = [] + total = 0 + for tier in TRIPLETS.keys(): + if FAILED_ONLY: + if tier not in FAILED_ONLY: + continue + total += len([s for s in TIER_SETTINGS[tier] if s["slug"] in FAILED_ONLY[tier]]) + else: + total += len(TIER_SETTINGS[tier]) + + api_key = get_api_key() + completed = 0 + failed = 0 + + for tier, meta in tiers_meta.items(): + if FAILED_ONLY and tier not in FAILED_ONLY: + continue + out_dir = BASE_OUT / tier / "FullyNaked" + out_dir.mkdir(parents=True, exist_ok=True) + triplet = meta["triplet"] + settings = meta["settings"] + if FAILED_ONLY: + settings = [s for s in settings if s["slug"] in FAILED_ONLY[tier]] + for setting in settings: + setting_slug = setting["slug"] + setting_desc = setting["desc"] + + name_slug = "_".join(slugify(npc["name"]) for npc in triplet) + file_name = f"Triple_{name_slug}_{setting_slug}__{runhex}.jpg" + out_path = out_dir / file_name + + def prompt_builder(clause: str, triplet=triplet, setting_desc=setting_desc): + return build_triple_prompt(triplet, setting_desc, clause) + + result = render_with_workflow(api_key, prompt_builder, out_path) + + images.append( + { + "tier": tier, + "setting": setting, + "triplet": triplet, + "output_path": result.get("output_path"), + "status": result.get("status"), + "attempts": result.get("attempts"), + "final_error": result.get("final_error"), + "final_http_code": result.get("final_http_code"), + } + ) + + if result.get("status") == "success": + completed += 1 + else: + failed += 1 + + _log( + f"PROGRESS completed={completed}/{total} failed={failed} tier={tier} setting={setting_slug}" + ) + + manifest = { + "run_label": "Courtesans Triples FullyNaked Rerun", + "created_at": created_at, + "source_manifest": str(SOURCE_MANIFEST), + "model": MODEL, + "endpoint": API_URL, + "aspect_ratio": ASPECT, + "runhex": runhex, + "output_root": str(BASE_OUT), + "total_images": total, + "tiers": tiers_meta, + "images": images, + "summary": {"success": completed, "failed": failed}, + } + + ts = dt.datetime.utcnow().strftime("%Y%m%d-%H%M%S") + out_manifest = MANIFEST_DIR / f"courtesans-triples-fullynaked-{ts}.json" + MANIFEST_DIR.mkdir(parents=True, exist_ok=True) + with out_manifest.open("w", encoding="utf-8") as f: + json.dump(manifest, f, indent=2) + + _log(f"DONE success={completed} failed={failed} manifest={out_manifest}") + print(str(out_manifest)) + + +if __name__ == "__main__": + main()