BetterLeaks / scan (push) Successful in 55s
Use strict _ArrivalA/B/C matching (instead of broad _A*) and include legacy non-Arrival variants like _C1__ as supplemental candidates. This prevents Type-A labels from accidentally picking Type-C content in doubles/twins/triples. Also documented the rule in SKILL.md + workflow notes and applied arrival retrofix across finalized tiers (Poor/Modest/Comfortable/Wealthy).
768 lines
27 KiB
Python
Executable File
768 lines
27 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Finalize and package a courtesan tier (Poor/Modest/Wealthy/etc.) in a tier-agnostic way.
|
|
|
|
Usage:
|
|
python3 finalize_courtesan_tier.py --tier Modest
|
|
python3 finalize_courtesan_tier.py --tier Comfortable --final-stage "Underwear L"
|
|
|
|
Notes:
|
|
- Uses "Stages and Raw Files" as stage root if present.
|
|
- Enforces preflight: no stage-letter tokens in non-Arrival folders.
|
|
- Generates passport lineup thumbnails (Name.jpg) via OpenCV on upper-half crop.
|
|
"""
|
|
|
|
from pathlib import Path
|
|
import argparse
|
|
import re
|
|
import shutil
|
|
import sys
|
|
from collections import defaultdict
|
|
|
|
BRACKET_RE=re.compile(r'[\[\{\(\<]\s*(\d{1,2})\s*[\]\}\)\>]')
|
|
MARKER_SUFFIX_RE=re.compile(r'^(?P<base>.*?)(?P<sep>[ _-]*)[\[\{\(\<]\s*(?P<token>[^\]\}\)\>]+?)\s*[\]\}\)\>]$')
|
|
# Legacy filename support: one underscore before runhex, e.g. ..._(0b)_7857649.jpg
|
|
# Canonical form remains ...__7857649.jpg and this regex is only for ingest/normalization.
|
|
LEGACY_SINGLESEP_RUNHEX_RE=re.compile(r'^(?P<prefix>.+?)(?<!_)_(?P<runhex>[0-9a-fA-F]{6,16})\.jpg$')
|
|
NUM_TOKEN_RE=re.compile(r'^\d{1,3}$')
|
|
NUM_SUFFIX_TOKEN_RE=re.compile(r'^(\d{1,3})([a-z]+)$', re.IGNORECASE)
|
|
LAST_TOKEN_RE=re.compile(r'^last$', re.IGNORECASE)
|
|
LAST_NUM_TOKEN_RE=re.compile(r'^last-(\d+)$', re.IGNORECASE)
|
|
LAST_N_TOKEN_RE=re.compile(r'^last-n$', re.IGNORECASE)
|
|
|
|
|
|
def pick_latest(files):
|
|
if not files:
|
|
return None
|
|
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)[0]
|
|
|
|
|
|
def ensure_dir(p: Path):
|
|
p.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
def copy_to(src: Path, dst: Path, overwrite=True):
|
|
ensure_dir(dst.parent)
|
|
if dst.exists() and overwrite:
|
|
dst.unlink()
|
|
if not dst.exists():
|
|
shutil.copy2(src, dst)
|
|
return True
|
|
return False
|
|
|
|
|
|
def bracketed_variants(stage_dir: Path, base_pattern: str):
|
|
out={}
|
|
for f in stage_dir.glob(base_pattern+'__*.jpg'):
|
|
m=BRACKET_RE.search(f.name)
|
|
if not m:
|
|
continue
|
|
idx=int(m.group(1))
|
|
if idx in out:
|
|
raise RuntimeError(f"Conflict: duplicate variant index [{idx}] in {stage_dir.name} for pattern {base_pattern}")
|
|
out[idx]=f
|
|
return out
|
|
|
|
|
|
def has_unbracketed(stage_dir: Path, base_pattern: str):
|
|
for f in stage_dir.glob(base_pattern+'__*.jpg'):
|
|
if not BRACKET_RE.search(f.name):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _suffix_rank(s: str):
|
|
if not s:
|
|
return 0
|
|
v=0
|
|
for ch in s.lower():
|
|
if not ('a' <= ch <= 'z'):
|
|
return None
|
|
v=v*27 + (ord(ch)-96)
|
|
return v
|
|
|
|
|
|
def _parse_variant_token(token: str):
|
|
t=(token or '').strip().lower().replace(' ', '')
|
|
if NUM_TOKEN_RE.fullmatch(t):
|
|
return ('num', int(t), None)
|
|
m=NUM_SUFFIX_TOKEN_RE.fullmatch(t)
|
|
if m:
|
|
return ('numsuffix', int(m.group(1)), m.group(2).lower())
|
|
if LAST_TOKEN_RE.fullmatch(t):
|
|
return ('last', 0, None)
|
|
m=LAST_NUM_TOKEN_RE.fullmatch(t)
|
|
if m:
|
|
return ('last', int(m.group(1)), None)
|
|
if LAST_N_TOKEN_RE.fullmatch(t):
|
|
return ('lastn', None, None)
|
|
return ('unknown', t, None)
|
|
|
|
|
|
def _manual_order_prompt(stage_name: str, base: str, entries, reason: str):
|
|
if not sys.stdin.isatty():
|
|
sample='; '.join(e['path'].name for e in entries[:6])
|
|
raise RuntimeError(
|
|
f"Preflight ambiguous in {stage_name} for '{base}': {reason}. "
|
|
f"Run interactively and choose order, or rename manually. Files: {sample}"
|
|
)
|
|
|
|
print(f"\nAMBIGUOUS ORDER in {stage_name}: {base}")
|
|
print(f"Reason: {reason}")
|
|
for i, e in enumerate(entries, start=1):
|
|
tok=e.get('token') or 'unmarked'
|
|
print(f" {i}) {e['path'].name} marker={tok}")
|
|
print("Enter desired order as item numbers, earliest -> latest (e.g. 2,1,3).")
|
|
|
|
while True:
|
|
raw=input('order> ').strip()
|
|
if not raw:
|
|
raise RuntimeError(f"Aborted by user while resolving {stage_name}/{base}")
|
|
parts=[p.strip() for p in raw.split(',') if p.strip()]
|
|
try:
|
|
chosen=[int(p) for p in parts]
|
|
except ValueError:
|
|
print('Please enter only numbers separated by commas.')
|
|
continue
|
|
if len(chosen) != len(entries):
|
|
print(f"Need exactly {len(entries)} numbers.")
|
|
continue
|
|
if sorted(chosen) != list(range(1, len(entries)+1)):
|
|
print('Use each item number exactly once.')
|
|
continue
|
|
return [entries[i-1] for i in chosen]
|
|
|
|
|
|
def _compute_order(stage_name: str, base: str, entries):
|
|
parsed=[]
|
|
for e in entries:
|
|
kind,a,b=_parse_variant_token(e['token'])
|
|
parsed.append((e,kind,a,b))
|
|
|
|
unknown=[e for (e,kind,_,_) in parsed if kind=='unknown']
|
|
if unknown:
|
|
return _manual_order_prompt(stage_name, base, entries, f"unrecognized marker(s): {', '.join(sorted({u['token'] for u in unknown}))}")
|
|
|
|
non_last=[]
|
|
last=[]
|
|
lastn=[]
|
|
|
|
for e,kind,a,b in parsed:
|
|
if kind=='num':
|
|
non_last.append((a,0,e))
|
|
elif kind=='numsuffix':
|
|
sr=_suffix_rank(b or '')
|
|
if sr is None:
|
|
return _manual_order_prompt(stage_name, base, entries, f"invalid numeric suffix marker: {e['token']}")
|
|
non_last.append((a,sr,e))
|
|
elif kind=='last':
|
|
last.append((a,e))
|
|
elif kind=='lastn':
|
|
lastn.append(e)
|
|
|
|
# Detect duplicate numeric/provisional slots (ambiguous intent)
|
|
seen_slots=defaultdict(list)
|
|
for n,s,e in non_last:
|
|
seen_slots[(n,s)].append(e)
|
|
dup_slots=[k for k,v in seen_slots.items() if len(v)>1]
|
|
if dup_slots:
|
|
return _manual_order_prompt(stage_name, base, entries, f"duplicate provisional slots: {dup_slots}")
|
|
|
|
seen_last=defaultdict(list)
|
|
for d,e in last:
|
|
seen_last[d].append(e)
|
|
dup_last=[k for k,v in seen_last.items() if len(v)>1]
|
|
if dup_last:
|
|
return _manual_order_prompt(stage_name, base, entries, f"duplicate last-markers: {dup_last}")
|
|
|
|
if len(lastn) > 1:
|
|
return _manual_order_prompt(stage_name, base, entries, "multiple 'last-n' placeholders")
|
|
|
|
# Infer one 'last-n' as earliest among last-group.
|
|
if len(lastn) == 1:
|
|
inferred=(max([d for d,_ in last], default=0) + 1)
|
|
last.append((inferred, lastn[0]))
|
|
|
|
ordered=[]
|
|
if non_last:
|
|
ordered.extend([e for _,_,e in sorted(non_last, key=lambda t: (t[0], t[1]))])
|
|
if last:
|
|
# last-2, last-1, last (distance descending)
|
|
ordered.extend([e for _,e in sorted(last, key=lambda t: t[0], reverse=True)])
|
|
|
|
if not ordered:
|
|
return entries
|
|
|
|
if len(ordered) != len(entries):
|
|
return _manual_order_prompt(stage_name, base, entries, "could not establish full ordering")
|
|
|
|
return ordered
|
|
|
|
|
|
def normalize_provisional_markers(stage_dir: Path):
|
|
"""Normalize provisional markers like (3b)/(3c)/(last-2)/(last) to canonical [1]..[n]."""
|
|
if not stage_dir.exists():
|
|
return []
|
|
|
|
by_base=defaultdict(list)
|
|
|
|
for f in stage_dir.glob('*.jpg'):
|
|
name=f.name
|
|
if '__' in name:
|
|
prefix, suffix = name.split('__', 1)
|
|
else:
|
|
# Legacy fallback: single underscore before runhex, normalize to canonical __ on write.
|
|
m_legacy=LEGACY_SINGLESEP_RUNHEX_RE.match(name)
|
|
if not m_legacy:
|
|
continue
|
|
prefix=m_legacy.group('prefix')
|
|
suffix=f"{m_legacy.group('runhex')}.jpg"
|
|
|
|
m=MARKER_SUFFIX_RE.match(prefix)
|
|
if m:
|
|
base=m.group('base')
|
|
sep=m.group('sep') or ''
|
|
token=(m.group('token') or '').strip()
|
|
marked=True
|
|
else:
|
|
base=prefix
|
|
sep=''
|
|
token=None
|
|
marked=False
|
|
by_base[base].append({
|
|
'path': f,
|
|
'base': base,
|
|
'sep': sep,
|
|
'token': token,
|
|
'suffix': suffix,
|
|
'marked': marked,
|
|
})
|
|
|
|
renames=[]
|
|
|
|
for base, entries in sorted(by_base.items()):
|
|
marked=[e for e in entries if e['marked']]
|
|
if not marked:
|
|
continue
|
|
|
|
if len(marked) != len(entries):
|
|
raise RuntimeError(
|
|
f"Preflight failed in {stage_dir.name}: mixed marked/unmarked variants for '{base}'. "
|
|
"Either mark all variants or keep exactly one unmarked file."
|
|
)
|
|
|
|
ordered=_compute_order(stage_dir.name, base, marked)
|
|
|
|
for idx, e in enumerate(ordered, start=1):
|
|
new_prefix=f"{e['base']}{e['sep']}[{idx}]"
|
|
new_name=f"{new_prefix}__{e['suffix']}"
|
|
if new_name != e['path'].name:
|
|
renames.append((e['path'], e['path'].with_name(new_name)))
|
|
|
|
# two-phase rename to avoid collisions
|
|
if renames:
|
|
tmp_moves=[]
|
|
for i, (src, dst) in enumerate(renames, start=1):
|
|
tmp=src.with_name(src.name + f".tmpnorm{i}")
|
|
src.rename(tmp)
|
|
tmp_moves.append((tmp, dst))
|
|
for tmp, dst in tmp_moves:
|
|
if dst.exists():
|
|
raise RuntimeError(f"Cannot normalize markers; target already exists: {dst.name}")
|
|
tmp.rename(dst)
|
|
|
|
return renames
|
|
|
|
|
|
def copy_stage_with_variants(stage_dir: Path, base_pattern: str, dst_folder: Path, label: str):
|
|
variants=bracketed_variants(stage_dir, base_pattern)
|
|
unbracketed=has_unbracketed(stage_dir, base_pattern)
|
|
if variants and unbracketed:
|
|
raise RuntimeError(f"Conflict: both bracketed and unnumbered for {label} {base_pattern}")
|
|
if variants:
|
|
for idx in sorted(variants):
|
|
copy_to(variants[idx], dst_folder/f"{label} {idx}.jpg")
|
|
return True
|
|
f=pick_latest(list(stage_dir.glob(base_pattern+'__*.jpg')))
|
|
if f:
|
|
copy_to(f, dst_folder/f"{label}.jpg")
|
|
return True
|
|
return False
|
|
|
|
|
|
def parse_double_base(base: str):
|
|
parts=base.split('_')
|
|
if parts[0] != 'Double' or len(parts) < 6:
|
|
return None
|
|
name1=f"{parts[1]} {parts[2]}"
|
|
name2=f"{parts[3]} {parts[4]}"
|
|
scene=" ".join(parts[5:]) if len(parts) > 5 else ""
|
|
return name1, name2, scene
|
|
|
|
|
|
def parse_twin_base(base: str):
|
|
parts=base.split('_')
|
|
if parts[0] != 'DoubleTwin' or len(parts) < 6:
|
|
return None
|
|
first1, last1, first2, last2 = parts[1], parts[2], parts[3], parts[4]
|
|
scene=" ".join(parts[5:]) if len(parts) > 5 else ""
|
|
return first1, last1, first2, last2, scene
|
|
|
|
|
|
def parse_triple_base(base: str):
|
|
parts=base.split('_')
|
|
if parts[0] != 'Triple' or len(parts) < 8:
|
|
return None
|
|
n1=f"{parts[1]} {parts[2]}"
|
|
n2=f"{parts[3]} {parts[4]}"
|
|
n3=f"{parts[5]} {parts[6]}"
|
|
scene=" ".join(parts[7:]) if len(parts) > 7 else ""
|
|
return n1, n2, n3, scene
|
|
|
|
|
|
def scene_paren(scene: str):
|
|
scene=scene.replace('_',' ').strip()
|
|
return f" ({scene})" if scene else ""
|
|
|
|
|
|
def extract_single_name(base: str):
|
|
"""Extract name from single base (strip _Single_Courtesan_Tier suffixes)."""
|
|
# Pattern: Name_Name_Single_Courtesan_Tier or Name_Name_Courtesan_Tier
|
|
# We want just: Name_Name
|
|
parts = base.split('_')
|
|
|
|
# Find where the suffix starts (Single, Courtesan, or tier names)
|
|
suffix_markers = ['Single', 'Courtesan', 'Comfortable', 'Modest', 'Wealthy', 'Elite', 'Poor']
|
|
|
|
name_parts = []
|
|
for part in parts:
|
|
if part in suffix_markers:
|
|
break
|
|
name_parts.append(part)
|
|
|
|
return '_'.join(name_parts) if name_parts else base
|
|
|
|
|
|
def extract_single_base_from_dressed_filename(filename: str):
|
|
"""Return the single base from a dressed filename, tolerant of legacy suffixes.
|
|
|
|
Examples:
|
|
- Helga_Sunspire_Dressed__abcd.jpg -> Helga_Sunspire
|
|
- Magnus_Ironbrook_Single_Courtesan_Wealthy_Dressed_v2_E__abcd.jpg -> Magnus_Ironbrook_Single_Courtesan_Wealthy
|
|
"""
|
|
prefix = filename.split('__', 1)[0]
|
|
# Strip trailing _Dressed plus optional legacy tail segments (_v2_E, etc.).
|
|
return re.sub(r'_Dressed(?:_[^_]+)*$', '', prefix)
|
|
|
|
|
|
def copy_arrival(arrival_dir: Path, base_pattern: str, dst_folder: Path, is_single: bool):
|
|
copied=False
|
|
for L in ['A','B','C']:
|
|
# Canonical arrival naming for all groups is ..._<base>_Arrival{L}<variant>__...
|
|
files = list(arrival_dir.glob(f"{base_pattern}_Arrival{L}*__*.jpg"))
|
|
|
|
# Legacy fallback for some old double/triple outputs where Arrival token is missing,
|
|
# e.g. ..._<base>_C1__<runhex>.jpg. Include alongside canonical files so a non-stairs
|
|
# legacy variant can coexist with canonical stairs-only variants for the same lobby type.
|
|
if not is_single:
|
|
for cand in arrival_dir.glob(f"{base_pattern}_{L}*__*.jpg"):
|
|
tail = cand.name[len(base_pattern) + 1:]
|
|
if tail.lower().startswith('arrival'):
|
|
continue
|
|
files.append(cand)
|
|
|
|
if not files:
|
|
continue
|
|
|
|
# de-duplicate by full path
|
|
files = list({str(p): p for p in files}.values())
|
|
stairs=[f for f in files if 'stairs' in f.name.lower()]
|
|
nonstairs=[f for f in files if 'stairs' not in f.name.lower()]
|
|
if stairs:
|
|
f=pick_latest(stairs)
|
|
copy_to(f, dst_folder/f"Arrival (Lobby type {L}, with stairs).jpg")
|
|
copied=True
|
|
if nonstairs:
|
|
f=pick_latest(nonstairs)
|
|
copy_to(f, dst_folder/f"Arrival (Lobby type {L}).jpg")
|
|
copied=True
|
|
return copied
|
|
|
|
|
|
def _pick_latest_globs(stage_dir: Path, patterns):
|
|
files=[]
|
|
for pat in patterns:
|
|
files.extend(stage_dir.glob(pat))
|
|
if not files:
|
|
return None
|
|
uniq={str(p): p for p in files}
|
|
return pick_latest(list(uniq.values()))
|
|
|
|
|
|
def copy_stages_single(base: str, dirs, dst_folder: Path, final_stage: str):
|
|
dressed_dir, teasing_dir, teasing_more_dir, topless_dir, topless_plus_dir, underwear_l_dir, underwear_s_dir, undressed_dir, arrival_dir = dirs
|
|
|
|
name_only=extract_single_name(base)
|
|
|
|
# Allow suffixes after stage names (e.g., _Dressed_v2_E) so legacy keeper names still resolve.
|
|
f=_pick_latest_globs(dressed_dir, [
|
|
f"{base}_Dressed*__*.jpg",
|
|
f"{name_only}_Dressed*__*.jpg",
|
|
])
|
|
if f: copy_to(f, dst_folder/'Dressed.jpg')
|
|
|
|
# Some singles include scene tokens before stage names (e.g., _marblebath_Teasing__...)
|
|
f=_pick_latest_globs(teasing_dir, [
|
|
f"{base}_Teasing*__*.jpg",
|
|
f"{base}_*Teasing__*.jpg",
|
|
f"{name_only}_Teasing*__*.jpg",
|
|
f"{name_only}_*Teasing__*.jpg",
|
|
])
|
|
if f: copy_to(f, dst_folder/'Teasing.jpg')
|
|
|
|
f=_pick_latest_globs(teasing_more_dir, [
|
|
f"{base}_TeasingMore*__*.jpg",
|
|
f"{base}_*TeasingMore__*.jpg",
|
|
f"{name_only}_TeasingMore*__*.jpg",
|
|
f"{name_only}_*TeasingMore__*.jpg",
|
|
])
|
|
if f: copy_to(f, dst_folder/'Teasing More.jpg')
|
|
|
|
# Topless may be keyed by long single base or short name-only base.
|
|
has_topless=copy_stage_with_variants(topless_dir, f"{base}_Topless*", dst_folder, 'Topless')
|
|
if not has_topless and name_only != base:
|
|
copy_stage_with_variants(topless_dir, f"{name_only}_Topless*", dst_folder, 'Topless')
|
|
|
|
if final_stage == 'Underwear L':
|
|
f=_pick_latest_globs(underwear_l_dir, [
|
|
f"{base}_Underwear*__*.jpg",
|
|
f"{name_only}_Underwear*__*.jpg",
|
|
])
|
|
if f: copy_to(f, dst_folder/'Underwear L.jpg')
|
|
elif final_stage == 'Underwear S':
|
|
f=_pick_latest_globs(underwear_s_dir, [
|
|
f"{base}_Underwear*__*.jpg",
|
|
f"{name_only}_Underwear*__*.jpg",
|
|
])
|
|
if f: copy_to(f, dst_folder/'Underwear S.jpg')
|
|
else:
|
|
has_topless_plus=copy_stage_with_variants(topless_plus_dir, f"{base}_Topless*", dst_folder, 'Topless Plus')
|
|
if not has_topless_plus and name_only != base:
|
|
copy_stage_with_variants(topless_plus_dir, f"{name_only}_Topless*", dst_folder, 'Topless Plus')
|
|
|
|
has_undressed=copy_stage_with_variants(undressed_dir, f"{base}*Undressed*", dst_folder, 'Undressed')
|
|
if not has_undressed and name_only != base:
|
|
copy_stage_with_variants(undressed_dir, f"{name_only}*Undressed*", dst_folder, 'Undressed')
|
|
|
|
if not copy_arrival(arrival_dir, base, dst_folder, True) and name_only != base:
|
|
copy_arrival(arrival_dir, name_only, dst_folder, True)
|
|
|
|
|
|
def copy_stages_double(base: str, dirs, dst_folder: Path, final_stage: str):
|
|
dressed_dir, teasing_dir, teasing_more_dir, topless_dir, topless_plus_dir, underwear_l_dir, underwear_s_dir, undressed_dir, arrival_dir = dirs
|
|
|
|
f=pick_latest(list(dressed_dir.glob(f"{base}__*.jpg")))
|
|
if f: copy_to(f, dst_folder/'Dressed.jpg')
|
|
f=pick_latest(list(teasing_dir.glob(f"{base}__*.jpg")))
|
|
if f: copy_to(f, dst_folder/'Teasing.jpg')
|
|
f=pick_latest(list(teasing_more_dir.glob(f"{base}__*.jpg")))
|
|
if f: copy_to(f, dst_folder/'Teasing More.jpg')
|
|
|
|
copy_stage_with_variants(topless_dir, f"{base}*", dst_folder, 'Topless')
|
|
|
|
if final_stage == 'Underwear L':
|
|
f=pick_latest(list(underwear_l_dir.glob(f"{base}*__*.jpg")))
|
|
if f: copy_to(f, dst_folder/'Underwear L.jpg')
|
|
elif final_stage == 'Underwear S':
|
|
f=pick_latest(list(underwear_s_dir.glob(f"{base}*__*.jpg")))
|
|
if f: copy_to(f, dst_folder/'Underwear S.jpg')
|
|
else:
|
|
copy_stage_with_variants(topless_plus_dir, f"{base}*", dst_folder, 'Topless Plus')
|
|
copy_stage_with_variants(undressed_dir, f"{base}*", dst_folder, 'Undressed')
|
|
|
|
copy_arrival(arrival_dir, base, dst_folder, False)
|
|
|
|
|
|
def copy_arrival_overview(arrival_dir: Path, tier_dir: Path):
|
|
"""Copy ArrivalAll overview composites to tier root.
|
|
|
|
Supports ArrivalAllSingles, ArrivalAllMen, ArrivalAllLadies and maps them to:
|
|
- Arrival (All, Lobby type X).jpg
|
|
- Arrival (Men, Lobby type X).jpg
|
|
- Arrival (Ladies, Lobby type X).jpg
|
|
|
|
Stair variants are detected either by explicit `_stairs` token or by legacy
|
|
variant numbering (A4-C6 => with stairs).
|
|
"""
|
|
re_overview = re.compile(
|
|
r'ArrivalAll(?P<group>Singles|Men|Ladies)_(?P<letter>[ABC])(?P<variant>\d+)(?P<stairs>_stairs)?__',
|
|
re.IGNORECASE,
|
|
)
|
|
|
|
buckets = {}
|
|
seen_groups = set()
|
|
|
|
for f in arrival_dir.glob('ArrivalAll*__*.jpg'):
|
|
m = re_overview.search(f.name)
|
|
if not m:
|
|
continue
|
|
group = m.group('group').title()
|
|
letter = m.group('letter').upper()
|
|
variant = int(m.group('variant'))
|
|
stairs = bool(m.group('stairs')) or variant >= 4
|
|
key = (group, letter, stairs)
|
|
buckets.setdefault(key, []).append(f)
|
|
seen_groups.add(group)
|
|
|
|
if not buckets:
|
|
return
|
|
|
|
has_gender_sets = ('Men' in seen_groups) or ('Ladies' in seen_groups)
|
|
|
|
# If gendered sets exist, remove old generic Arrival (Lobby type X) files to avoid duplicate naming.
|
|
if has_gender_sets:
|
|
for old in tier_dir.glob('Arrival (Lobby type *.jpg'):
|
|
try:
|
|
old.unlink()
|
|
except Exception:
|
|
pass
|
|
|
|
for (group, letter, stairs), files in sorted(buckets.items()):
|
|
f = pick_latest(files)
|
|
|
|
if group == 'Singles':
|
|
if has_gender_sets:
|
|
base = f"Arrival (All, Lobby type {letter}"
|
|
else:
|
|
base = f"Arrival (Lobby type {letter}"
|
|
elif group == 'Men':
|
|
base = f"Arrival (Men, Lobby type {letter}"
|
|
else: # Ladies
|
|
base = f"Arrival (Ladies, Lobby type {letter}"
|
|
|
|
label = f"{base}, with stairs).jpg" if stairs else f"{base}).jpg"
|
|
copy_to(f, tier_dir / label)
|
|
|
|
|
|
def generate_passports(tier_dir: Path, per_dir: Path, singles_bases):
|
|
try:
|
|
import cv2
|
|
except Exception as e:
|
|
raise RuntimeError(f"OpenCV not available: {e}. Run with ~/.openclaw/workspace/.venv-opencv/bin/python")
|
|
try:
|
|
from PIL import Image
|
|
except Exception:
|
|
Image=None
|
|
|
|
# Cleanup legacy numbered passport names from older runs (01-Name.jpg)
|
|
for old in tier_dir.glob('[0-9][0-9]-*.jpg'):
|
|
try:
|
|
old.unlink()
|
|
except Exception:
|
|
pass
|
|
|
|
cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
|
fallback_used=[]
|
|
missing=[]
|
|
|
|
for base in sorted(singles_bases):
|
|
name_only = extract_single_name(base)
|
|
name = name_only.replace('_',' ')
|
|
dressed=per_dir/'Singles'/name/'Dressed.jpg'
|
|
if not dressed.exists():
|
|
missing.append(name)
|
|
continue
|
|
img=cv2.imread(str(dressed))
|
|
if img is None:
|
|
missing.append(name)
|
|
continue
|
|
h,w=img.shape[:2]
|
|
upper_h=h//2
|
|
upper=img[0:upper_h, 0:w]
|
|
gray=cv2.cvtColor(upper, cv2.COLOR_BGR2GRAY)
|
|
faces=cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(50,50))
|
|
if len(faces)>0:
|
|
x,y,fw,fh=max(faces, key=lambda r: r[2]*r[3])
|
|
cx=x+fw//2
|
|
cy=y+fh//2
|
|
size=int(max(fw,fh)*2.0)
|
|
x0=max(0, cx - size//2)
|
|
y0=max(0, cy - size//2)
|
|
x1=min(w, x0 + size)
|
|
y1=min(upper_h, y0 + size)
|
|
if x1 - x0 < size:
|
|
x0=max(0, x1 - size)
|
|
if y1 - y0 < size:
|
|
y0=max(0, y1 - size)
|
|
crop=upper[y0:y1, x0:x0+size]
|
|
else:
|
|
# fallback: upper-half center square
|
|
fallback_used.append(name)
|
|
size=min(w, upper_h)
|
|
x0=(w-size)//2
|
|
crop=upper[0:size, x0:x0+size]
|
|
if Image is not None:
|
|
# re-encode via Pillow to keep consistent quality
|
|
pil=Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB))
|
|
out=tier_dir/f"{name}.jpg"
|
|
pil.save(out, format="JPEG", quality=95)
|
|
continue
|
|
out=tier_dir/f"{name}.jpg"
|
|
cv2.imwrite(str(out), crop, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
|
|
|
|
return fallback_used, missing
|
|
|
|
|
|
def main():
|
|
ap=argparse.ArgumentParser()
|
|
ap.add_argument('--tier', required=True, help='Tier name (e.g., Modest, Poor, Comfortable)')
|
|
ap.add_argument('--base-dir', default='/home/rick/output/to-dnd-session/Grok-NPCs/Courtesans', help='Base directory for tiers')
|
|
ap.add_argument('--final-stage', default='Undressed', choices=['Undressed','Underwear L','Underwear S'])
|
|
ap.add_argument('--no-passports', action='store_true')
|
|
ap.add_argument('--no-arrival-overview', action='store_true')
|
|
ap.add_argument('--no-cleanup', action='store_true')
|
|
args=ap.parse_args()
|
|
|
|
tier_dir=Path(args.base_dir)/args.tier
|
|
if not tier_dir.exists():
|
|
raise SystemExit(f"Tier not found: {tier_dir}")
|
|
|
|
per_dir=tier_dir/'Per Courtesan'
|
|
stages_dir=tier_dir/'Stages and Raw Files'
|
|
stage_root=stages_dir if stages_dir.exists() else tier_dir
|
|
|
|
# stage folders
|
|
dressed_dir=stage_root/'Dressed'
|
|
teasing_dir=stage_root/'Teasing'
|
|
teasing_more_dir=stage_root/'Teasing More'
|
|
topless_dir=stage_root/'Topless'
|
|
topless_plus_dir=stage_root/'Topless Plus'
|
|
underwear_l_dir=stage_root/'Underwear L'
|
|
underwear_s_dir=stage_root/'Underwear S'
|
|
undressed_dir=stage_root/'Undressed'
|
|
arrival_dir=stage_root/'Arrival'
|
|
|
|
# preflight: normalize provisional variant markers to canonical [1..n]
|
|
for folder in (topless_dir, topless_plus_dir, undressed_dir):
|
|
changes=normalize_provisional_markers(folder)
|
|
if changes:
|
|
print(f"Normalized {len(changes)} provisional marker(s) in {folder.name}")
|
|
|
|
# preflight: no stage-letter tokens in finalized folders
|
|
stage_pat=re.compile(r'_(?:[A-E])(?:_[A-E])?__|(?:TeasingMore|Teasing|Topless|ToplessPlus|UnderwearL|UnderwearS)[A-E](?:_[A-E])?__')
|
|
check_folders=[teasing_dir, teasing_more_dir, topless_plus_dir, underwear_l_dir, underwear_s_dir]
|
|
for folder in check_folders:
|
|
if not folder.exists():
|
|
continue
|
|
bad=[x.name for x in folder.glob('*.jpg') if stage_pat.search(x.name)]
|
|
if bad:
|
|
raise RuntimeError(f"Preflight failed: stage-letter tokens still present in {folder.name}: {bad[:5]}")
|
|
|
|
# build base lists from Dressed
|
|
singles=[]
|
|
doubles=[]
|
|
triples=[]
|
|
twins=[]
|
|
for f in dressed_dir.glob('*.jpg'):
|
|
name=f.name
|
|
if name.startswith('DoubleTwin_'):
|
|
twins.append(name.split('__')[0])
|
|
elif name.startswith('Double_'):
|
|
doubles.append(name.split('__')[0])
|
|
elif name.startswith('Triple_'):
|
|
triples.append(name.split('__')[0])
|
|
else:
|
|
singles.append(extract_single_base_from_dressed_filename(name))
|
|
|
|
# Deduplicate singles by extracted name (prefer shorter bases)
|
|
seen_names = {}
|
|
for base in singles:
|
|
name_only = extract_single_name(base)
|
|
if name_only not in seen_names or len(base) < len(seen_names[name_only]):
|
|
seen_names[name_only] = base
|
|
singles = sorted(seen_names.values())
|
|
|
|
doubles=sorted(set(doubles))
|
|
triples=sorted(set(triples))
|
|
twins=sorted(set(twins))
|
|
|
|
# create folders
|
|
ensure_dir(per_dir)
|
|
if singles: ensure_dir(per_dir/'Singles')
|
|
if doubles: ensure_dir(per_dir/'Doubles')
|
|
if triples: ensure_dir(per_dir/'Triples')
|
|
if twins: ensure_dir(per_dir/'Twins')
|
|
|
|
dirs=(dressed_dir, teasing_dir, teasing_more_dir, topless_dir, topless_plus_dir, underwear_l_dir, underwear_s_dir, undressed_dir, arrival_dir)
|
|
|
|
for base in singles:
|
|
name_only = extract_single_name(base)
|
|
folder_name = name_only.replace('_',' ')
|
|
dst=per_dir/'Singles'/folder_name
|
|
ensure_dir(dst)
|
|
copy_stages_single(base, dirs, dst, args.final_stage)
|
|
|
|
for base in doubles:
|
|
parsed=parse_double_base(base)
|
|
if not parsed:
|
|
continue
|
|
n1,n2,scene=parsed
|
|
folder=f"{n1}, {n2}{scene_paren(scene)}"
|
|
dst=per_dir/'Doubles'/folder
|
|
ensure_dir(dst)
|
|
copy_stages_double(base, dirs, dst, args.final_stage)
|
|
|
|
for base in twins:
|
|
parsed=parse_twin_base(base)
|
|
if not parsed:
|
|
continue
|
|
f1,l1,f2,l2,scene=parsed
|
|
if l1==l2:
|
|
name=f"{f1} and {f2} {l1}"
|
|
else:
|
|
name=f"{f1} {l1} and {f2} {l2}"
|
|
folder=f"{name}{scene_paren(scene)}"
|
|
dst=per_dir/'Twins'/folder
|
|
ensure_dir(dst)
|
|
copy_stages_double(base, dirs, dst, args.final_stage)
|
|
|
|
for base in triples:
|
|
parsed=parse_triple_base(base)
|
|
if not parsed:
|
|
continue
|
|
n1,n2,n3,scene=parsed
|
|
folder=f"{n1}, {n2}, {n3}{scene_paren(scene)}"
|
|
dst=per_dir/'Triples'/folder
|
|
ensure_dir(dst)
|
|
copy_stages_double(base, dirs, dst, args.final_stage)
|
|
|
|
# ArrivalAllSingles overview
|
|
if not args.no_arrival_overview and arrival_dir.exists():
|
|
copy_arrival_overview(arrival_dir, tier_dir)
|
|
|
|
# passports
|
|
if not args.no_passports:
|
|
try:
|
|
fallback_used, missing = generate_passports(tier_dir, per_dir, singles)
|
|
if fallback_used:
|
|
print("Passport fallback used for:", ", ".join(fallback_used))
|
|
if missing:
|
|
print("Missing dressed for:", ", ".join(missing))
|
|
except Exception as e:
|
|
print(f"Passport generation failed: {e}")
|
|
|
|
# cleanup
|
|
if not args.no_cleanup and stage_root == tier_dir:
|
|
ensure_dir(stages_dir)
|
|
for d in tier_dir.iterdir():
|
|
if not d.is_dir():
|
|
continue
|
|
if d.name in ('Per Courtesan','Stages and Raw Files'):
|
|
continue
|
|
shutil.move(str(d), str(stages_dir/d.name))
|
|
|
|
print('DONE')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|