Files
2026-03-26 18:05:40 +00:00

594 lines
24 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Tier-independent Topless renderer.
Behavior:
- Single women: A-Z (24 letters, skip I/O) + ABERX expansion (A0/A1-A9, etc.)
- Single men: A-E only
- Doubles / DoubleTwins / Triples: A-Z + ABERX expansion
Naming:
- single: <Name>_ToplessA__<runhex>.jpg, <Name>_ToplessA1__<runhex>.jpg
- multi: <Base>_A__<runhex>.jpg, <Base>_A1__<runhex>.jpg
Useful scopes:
- --scope all -> everything missing for the tier
- --scope multiperson -> doubles/twins/triples only
- --scope singles -> singles only (women full set, men A-E)
"""
import argparse
import base64
import json
import os
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests
sys.path.append(str(Path(__file__).resolve().parent))
from prompt_guard import enforce
LETTERS = ["A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z"]
ABERX_LETTERS = ["A", "B", "E", "R", "X"]
MALE_LETTERS = ["A", "B", "C", "D", "E"]
POSE_LIST = [
'standing relaxed, hands at sides',
'seated on a cushioned bench, relaxed posture',
'leaning lightly against a carved post',
'walking slowly with a small step',
'adjusting the neckline with one hand',
'standing with one hand resting on hip',
'seated on a low stool, upright posture',
'leaning forward slightly with hands clasped',
'standing and brushing hair back with one hand',
'seated on the edge of a cushioned seat',
'standing with arms loosely crossed',
'seated on a bench, slight twist at waist',
'leaning against a wall, one knee bent',
'standing with a slight contrapposto',
'seated on a low step, hands resting on knees',
'standing with one arm raised to adjust hair',
'walking slowly, garment swaying',
'standing, hands clasped behind back',
'seated, one leg tucked slightly under',
'leaning on a beam with one shoulder',
'standing in profile three-quarter, head turned to camera',
'seated on a stool, one hand on thigh',
'standing, one hand lightly touching collarbone',
'leaning forward, hands on hips',
]
POSE_MAP = {LETTERS[i]: POSE_LIST[i] for i in range(len(LETTERS))}
METHOD_AB = set(LETTERS[:10]) # A-K
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."
)
def data_url(path: Path) -> str:
return "data:image/jpeg;base64," + base64.b64encode(path.read_bytes()).decode()
def load_identities(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
# Common shapes seen in Rick's manifests
candidate_npcs = []
if isinstance(data.get("individuals"), list):
candidate_npcs.extend(data["individuals"])
if isinstance(data.get("pairs"), list):
for pair in data["pairs"]:
candidate_npcs.extend(pair.get("npcs", []))
if isinstance(data.get("npc_profiles"), dict):
candidate_npcs.extend(data["npc_profiles"].values())
if data.get("courtesan"):
candidate_npcs.append({
"name": data.get("courtesan"),
"identity": _extract_identity_from_run_manifest(data),
})
for npc in candidate_npcs:
name = npc.get("name")
if not name:
continue
keys = {name, name.replace(" ", "_")}
for key in keys:
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", "")
marker = "Identity: "
if marker in prompt:
rest = prompt.split(marker, 1)[1]
return rest.split("\n", 1)[0].strip()
return ""
def extract_eye(identity: str):
for part in identity.split(';'):
if 'eye' in part.lower():
return part.strip()
return None
def normalize_single_base(base: str, tier: str) -> str:
base = 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_single_gender(original_base: str, normalized_base: str, identity_map: dict) -> str:
# Current working heuristic: the only single Dressed files with _Single_Courtesan_ are the men.
if "_Single_Courtesan_" in original_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 parse_record(ref_path: Path, tier: str, identity_map: dict):
raw_base = ref_path.stem.split("__", 1)[0]
if raw_base.startswith("DoubleTwin_"):
parts = raw_base.split("_")
return {
"kind": "twin",
"group": "double",
"raw_base": raw_base,
"output_base": raw_base,
"names": [f"{parts[1]} {parts[2]}", f"{parts[3]} {parts[4]}"],
"letters": LETTERS,
"aberx": True,
"ref": ref_path,
"undressed_prefix": raw_base,
}
if raw_base.startswith("Double_"):
parts = raw_base.split("_")
return {
"kind": "double",
"group": "double",
"raw_base": raw_base,
"output_base": raw_base,
"names": [f"{parts[1]} {parts[2]}", f"{parts[3]} {parts[4]}"],
"letters": LETTERS,
"aberx": True,
"ref": ref_path,
"undressed_prefix": raw_base,
}
if raw_base.startswith("Triple_"):
parts = raw_base.split("_")
return {
"kind": "triple",
"group": "triple",
"raw_base": raw_base,
"output_base": raw_base,
"names": [f"{parts[1]} {parts[2]}", f"{parts[3]} {parts[4]}", f"{parts[5]} {parts[6]}"],
"letters": LETTERS,
"aberx": True,
"ref": ref_path,
"undressed_prefix": raw_base,
}
normalized = normalize_single_base(raw_base, tier)
gender = infer_single_gender(raw_base, normalized, identity_map)
return {
"kind": "male_single" if gender == "male" else "single",
"group": "single",
"raw_base": raw_base,
"output_base": normalized,
"names": [normalized.replace("_", " ")],
"letters": MALE_LETTERS if gender == "male" else LETTERS,
"aberx": gender != "male",
"ref": ref_path,
"undressed_prefix": raw_base,
}
def discover_records(dressed_dir: Path, tier: str, identity_map: dict, scope: str):
records = []
for ref in sorted(dressed_dir.glob("*.jpg")):
rec = parse_record(ref, tier, identity_map)
if scope == "multiperson" and rec["kind"] in {"single", "male_single"}:
continue
if scope == "singles" and rec["kind"] not in {"single", "male_single"}:
continue
records.append(rec)
return records
def find_undressed_ref(undressed_dir: Path, prefix: str):
for p in sorted(undressed_dir.glob("*.jpg")):
if p.stem.split("__", 1)[0].startswith(prefix):
return p
return None
def blend_scene_clause(has_undressed_ref: bool):
if has_undressed_ref:
return (
"Scene must be a believable continuation of the same establishment and room logic, "
"using the extra reference to preserve architecture and lighting continuity rather than inventing a new place."
)
return "Scene should match the reference room and lighting."
def method_clause(letter: str):
if letter in METHOD_AB:
return "Topless stage (A-B method): garment dropped below shoulders; arms may still have fabric."
return "Topless stage (C-E method): no fabric above waist, shoulders, or arms."
def build_prompt_single_female(name: str, letter: str, identity_map: dict, has_undressed_ref: bool):
ident = (identity_map.get(name.replace(" ", "_")) or identity_map.get(name) or {}).get("identity", "")
eye = extract_eye(ident) or "Eye color must match the reference exactly."
eye_clause = f"Eye color: {eye}. Eye color must match exactly." if "match" not in eye.lower() else eye
return f"""
Single adult woman, character name reference: {name}.
Identity: {ident}.
{eye_clause}
Use ONLY the provided reference image as the exact outfit source.
Keep the same garment colors, fabrics, patterns, and accessory placement below the waist.
Garments remain intact with no tears, rips, holes, fraying, or cuts.
{method_clause(letter)}
Nipples visible and unobstructed with anatomically correct lateral placement (not pulled to midline).
Same skirt/lower garment as reference. No nudity below the waist.
Pose: {POSE_MAP[letter]}.
{blend_scene_clause(has_undressed_ref)}
Keep the same face/likeness as the reference; preserve facial marks exactly; no airbrushing.
Smiling warmly with inviting 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_single_male(name: str, letter: str, identity_map: dict, has_undressed_ref: bool):
ident = (identity_map.get(name.replace(" ", "_")) or identity_map.get(name) or {}).get("identity", "")
eye = extract_eye(ident) or "Eye color must match the reference exactly."
eye_clause = f"Eye color: {eye}. Eye color must match exactly." if "match" not in eye.lower() else eye
return f"""
Single adult man, character name reference: {name}.
Identity: {ident}.
{eye_clause}
Use ONLY the provided reference image as the exact outfit source.
Keep the same garment colors, fabrics, patterns, and accessory placement below the waist.
Garments remain intact with no tears, rips, holes, fraying, or cuts.
Topless stage: tunic or upper garment dropped below shoulders; chest fully bare; nipples visible and unobstructed.
Same lower garment or trousers as reference. No nudity below the waist.
Pose: {POSE_MAP[letter]}.
{blend_scene_clause(has_undressed_ref)}
Keep the same face/likeness as the reference; preserve facial marks exactly; no airbrushing.
Smiling warmly with inviting 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_double(names, letter: str, identity_map: dict, is_twin: bool, has_undressed_ref: bool):
name1, name2 = names
id1 = (identity_map.get(name1.replace(" ", "_")) or identity_map.get(name1) or {}).get("identity", "")
id2 = (identity_map.get(name2.replace(" ", "_")) or identity_map.get(name2) or {}).get("identity", "")
twin_clause = "They are identical twins with the same face, same marks, and same facial structure." if is_twin else "They have clearly distinct faces and clearly different facial features."
identity_clause = f"Identity for both: {id1}." if is_twin else f"Identity {name1}: {id1}. Identity {name2}: {id2}."
return f"""
Two adult women, character name references: {name1} and {name2}.
{twin_clause}
{identity_clause}
Use ONLY the provided reference image as the exact outfit source.
Keep the same garment colors, fabrics, patterns, and accessory placement below the waist for each woman.
Garments remain intact with no tears, rips, holes, fraying, or cuts.
{method_clause(letter)}
At least one nipple visible and unobstructed with anatomically correct lateral placement (1/4 visible is acceptable; 1 each is acceptable).
No nudity below the waist.
Pose: {POSE_MAP[letter]}.
{blend_scene_clause(has_undressed_ref)}
Keep the same face/likeness as the reference; preserve facial marks exactly; no airbrushing.
Smiling warmly with inviting 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_triple(names, letter: str, identity_map: dict, has_undressed_ref: bool):
name1, name2, name3 = names
id1 = (identity_map.get(name1.replace(" ", "_")) or identity_map.get(name1) or {}).get("identity", "")
id2 = (identity_map.get(name2.replace(" ", "_")) or identity_map.get(name2) or {}).get("identity", "")
id3 = (identity_map.get(name3.replace(" ", "_")) or identity_map.get(name3) or {}).get("identity", "")
return f"""
Three adult women, character name references: {name1}, {name2}, and {name3}.
They have clearly distinct faces and clearly different facial features.
Identity {name1}: {id1}. Identity {name2}: {id2}. Identity {name3}: {id3}.
Use ONLY the provided reference image as the exact outfit source.
Keep the same garment colors, fabrics, patterns, and accessory placement below the waist for each woman.
Garments remain intact with no tears, rips, holes, fraying, or cuts.
{method_clause(letter)}
At least two nipples visible and unobstructed with anatomically correct lateral placement.
No nudity below the waist.
Pose: {POSE_MAP[letter]}.
{blend_scene_clause(has_undressed_ref)}
Keep the same face/likeness as the reference; preserve facial marks exactly; no airbrushing.
Smiling warmly with inviting 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(record, letter: str, identity_map: dict, has_undressed_ref: bool):
if record["kind"] == "single":
prompt = build_prompt_single_female(record["names"][0], letter, identity_map, has_undressed_ref)
enforce("topless", "single", prompt)
return prompt
if record["kind"] == "male_single":
prompt = build_prompt_single_male(record["names"][0], letter, identity_map, has_undressed_ref)
enforce("topless", "single", prompt)
return prompt
if record["kind"] == "double":
prompt = build_prompt_double(record["names"], letter, identity_map, False, has_undressed_ref)
enforce("topless", "double", prompt)
return prompt
if record["kind"] == "twin":
prompt = build_prompt_double(record["names"], letter, identity_map, True, has_undressed_ref)
enforce("topless", "double", prompt)
return prompt
prompt = build_prompt_triple(record["names"], letter, identity_map, has_undressed_ref)
enforce("topless", "triple", prompt)
return prompt
def plain_pattern(record, letter: str) -> str:
if record["group"] == "single":
return f"{record['output_base']}_Topless{letter}__*.jpg"
return f"{record['output_base']}_{letter}__*.jpg"
def zero_pattern(record, letter: str) -> str:
if record["group"] == "single":
return f"{record['output_base']}_Topless{letter}0__*.jpg"
return f"{record['output_base']}_{letter}0__*.jpg"
def extra_pattern(record, letter: str, num: int) -> str:
if record["group"] == "single":
return f"{record['output_base']}_Topless{letter}{num}__*.jpg"
return f"{record['output_base']}_{letter}{num}__*.jpg"
def out_base(record, letter: str, variant_num: int) -> str:
if record["group"] == "single":
return f"{record['output_base']}_Topless{letter}{variant_num if variant_num else ''}"
return f"{record['output_base']}_{letter}{variant_num if variant_num else ''}"
def any_match(out_dir: Path, pattern: str) -> bool:
return any(out_dir.glob(pattern))
def base_variant_exists(out_dir: Path, record, letter: str) -> bool:
if any_match(out_dir, plain_pattern(record, letter)):
return True
if letter in ABERX_LETTERS and any_match(out_dir, zero_pattern(record, letter)):
return True
return False
def variant_exists(out_dir: Path, record, letter: str, num: int) -> bool:
return any_match(out_dir, extra_pattern(record, letter, num))
def render_job(record, letter: str, variant_num: int, runhex: str, identity_map: dict, undressed_dir: Path, out_dir: Path, api_url: str, headers: dict):
out_file = f"{out_base(record, letter, variant_num)}__{runhex}.jpg"
out_path = out_dir / out_file
if out_path.exists():
return {"status": "skip"}
uref = find_undressed_ref(undressed_dir, record["undressed_prefix"])
has_undressed_ref = uref is not None
prompt = build_prompt(record, letter, identity_map, has_undressed_ref)
payload = {
"model": "grok-imagine-image",
"prompt": prompt,
"image": {"url": data_url(record["ref"])},
"aspect_ratio": "16:9",
}
if has_undressed_ref:
payload["image_2"] = {"url": data_url(uref)}
fail_marker = out_dir / f"{out_base(record, letter, variant_num)}_FAIL.txt"
for attempt in range(1, 4):
try:
r = requests.post(api_url, headers=headers, data=json.dumps(payload), timeout=90)
if r.status_code in (429, 500, 502, 503, 504):
time.sleep(1.5 * attempt)
continue
if r.status_code != 200:
if attempt < 3:
time.sleep(1)
continue
fail_marker.touch()
return {"status": "failed", "error": f"HTTP {r.status_code}: {r.text[:180]}"}
url = r.json()["data"][0]["url"]
subprocess.run(["curl", "-sS", "-L", url, "-o", str(out_path)], check=True, timeout=60)
if fail_marker.exists():
fail_marker.unlink()
return {"status": "success", "file": out_file}
except Exception as e:
if attempt < 3:
time.sleep(1)
continue
fail_marker.touch()
return {"status": "exception", "error": str(e)}
def rename_aberx_zeroes(records, out_dir: Path):
renamed = 0
skipped = 0
for record in records:
if not record["aberx"]:
continue
for letter in ABERX_LETTERS:
plain_files = sorted(out_dir.glob(plain_pattern(record, letter)))
zero_files = sorted(out_dir.glob(zero_pattern(record, letter)))
if zero_files:
skipped += len(plain_files)
continue
for old_path in plain_files:
new_name = old_path.name.replace(
f"Topless{letter}__", f"Topless{letter}0__"
) if record["group"] == "single" else old_path.name.replace(
f"_{letter}__", f"_{letter}0__"
)
new_path = old_path.with_name(new_name)
old_path.rename(new_path)
renamed += 1
return renamed, skipped
def main():
parser = argparse.ArgumentParser(description="Render Topless A-Z + ABERX for a courtesan tier")
parser.add_argument("--tier", required=True)
parser.add_argument("--workers", type=int, default=25)
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("--scope", choices=["all", "multiperson", "singles"], default="all")
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"
undressed_dir = tier_dir / "Undressed"
out_dir = tier_dir / "Topless"
out_dir.mkdir(parents=True, exist_ok=True)
identity_map = load_identities(Path(args.manifest_dir))
records = discover_records(dressed_dir, args.tier, identity_map, args.scope)
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("=" * 68)
print(f"{args.tier} Topless A-Z + ABERX (scope={args.scope}, runhex={runhex})")
print("=" * 68)
print(f"Records discovered: {len(records)}")
print(f"Workers: {args.workers}\n")
sys.stdout.flush()
# Phase 1: missing base letters
phase1_jobs = []
for record in records:
for letter in record["letters"]:
if base_variant_exists(out_dir, record, letter):
continue
phase1_jobs.append((record, letter, 0, runhex, identity_map, undressed_dir, out_dir, api_url, headers))
print(f"Phase 1: missing base jobs = {len(phase1_jobs)}")
sys.stdout.flush()
success1 = failed1 = skip1 = 0
if phase1_jobs:
with ThreadPoolExecutor(max_workers=args.workers) as ex:
futures = {ex.submit(render_job, *job): job for job in phase1_jobs}
for i, future in enumerate(as_completed(futures), start=1):
result = future.result()
if result["status"] == "success":
success1 += 1
elif result["status"] == "skip":
skip1 += 1
else:
failed1 += 1
if failed1 <= 5:
print(f"FAIL phase1: {result.get('error', '?')[:160]}")
if i % 50 == 0:
print(f" Phase 1 progress: {i}/{len(phase1_jobs)}")
sys.stdout.flush()
print(f"Phase 1 done: ok={success1} fail={failed1} skip={skip1}\n")
sys.stdout.flush()
# Phase 2: rename plain ABERX to *0
renamed, rename_skipped = rename_aberx_zeroes(records, out_dir)
print(f"Phase 2: renamed {renamed} ABERX files to *0 format (skipped plain-with-existing-zero={rename_skipped})\n")
sys.stdout.flush()
# Phase 3: missing ABERX extras for ABERX-eligible records only
phase3_jobs = []
for record in records:
if not record["aberx"]:
continue
for letter in ABERX_LETTERS:
for num in range(1, 10):
if variant_exists(out_dir, record, letter, num):
continue
phase3_jobs.append((record, letter, num, runhex, identity_map, undressed_dir, out_dir, api_url, headers))
print(f"Phase 3: missing ABERX jobs = {len(phase3_jobs)}")
sys.stdout.flush()
success3 = failed3 = skip3 = 0
if phase3_jobs:
with ThreadPoolExecutor(max_workers=args.workers) as ex:
futures = {ex.submit(render_job, *job): job for job in phase3_jobs}
for i, future in enumerate(as_completed(futures), start=1):
result = future.result()
if result["status"] == "success":
success3 += 1
elif result["status"] == "skip":
skip3 += 1
else:
failed3 += 1
if failed3 <= 5:
print(f"FAIL phase3: {result.get('error', '?')[:160]}")
if i % 50 == 0:
print(f" Phase 3 progress: {i}/{len(phase3_jobs)}")
sys.stdout.flush()
print("\n" + "=" * 68)
print(
f"DONE: phase1 ok={success1} fail={failed1} skip={skip1} | "
f"phase3 ok={success3} fail={failed3} skip={skip3}"
)
print("=" * 68)
if __name__ == "__main__":
main()