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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
EntryTrial.py
|
| 3 |
+
|
| 4 |
+
A fully self-contained, single-file reimplementation of ArtArena's
|
| 5 |
+
Entry-Trials pipeline:
|
| 6 |
+
|
| 7 |
+
prep_ET.py -> ET_infer.py -> ET_eval_fixed.py
|
| 8 |
+
S
|
| 9 |
+
No dependency on the ArtArena repo directory — everything the three
|
| 10 |
+
original scripts did is reproduced in-process below. Supports sweeping
|
| 11 |
+
over multiple datasets, multiple T2I models, and multiple proximity
|
| 12 |
+
metrics in one call.
|
| 13 |
+
|
| 14 |
+
Built-in models: sd15, sdxl, sana15 (as in the original ET_infer.py).
|
| 15 |
+
A clearly marked PLACEHOLDER section lets you register any additional
|
| 16 |
+
text-to-image model — see "ADD NEW MODELS HERE" below.
|
| 17 |
+
|
| 18 |
+
CSD metric: expects a local ./CSD folder next to this script, containing
|
| 19 |
+
model.py and utils.py (exactly as you've set it up). Override with
|
| 20 |
+
--csd_repo_dir if you keep it elsewhere.
|
| 21 |
+
|
| 22 |
+
-------------------------------------------------------------------------
|
| 23 |
+
Examples
|
| 24 |
+
-------------------------------------------------------------------------
|
| 25 |
+
|
| 26 |
+
Single dataset, single model, single metric:
|
| 27 |
+
|
| 28 |
+
python EntryTrial.py \
|
| 29 |
+
--datasets /content/dataset \
|
| 30 |
+
--models sd15 \
|
| 31 |
+
--metrics clip \
|
| 32 |
+
--output_root /content/saves \
|
| 33 |
+
--num_imgs 2
|
| 34 |
+
|
| 35 |
+
Sweep: two datasets x three models x two metrics, resumable:
|
| 36 |
+
|
| 37 |
+
python EntryTrial.py \
|
| 38 |
+
--datasets /content/dataset_a /content/dataset_b \
|
| 39 |
+
--models sd15 sdxl sana15 \
|
| 40 |
+
--metrics clip lpips \
|
| 41 |
+
--output_root /content/saves \
|
| 42 |
+
--num_imgs 2 \
|
| 43 |
+
--skip_existing
|
| 44 |
+
|
| 45 |
+
CSD metric (reads ./CSD/model.py + ./CSD/utils.py next to this script):
|
| 46 |
+
|
| 47 |
+
python EntryTrial.py \
|
| 48 |
+
--datasets /content/dataset \
|
| 49 |
+
--models sd15 \
|
| 50 |
+
--metrics csd \
|
| 51 |
+
--csd_model_path /content/CSD/checkpoint.pt \
|
| 52 |
+
--output_root /content/saves \
|
| 53 |
+
--num_imgs 2
|
| 54 |
+
|
| 55 |
+
List the models currently registered:
|
| 56 |
+
|
| 57 |
+
python EntryTrial.py --list_models
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
from __future__ import annotations
|
| 61 |
+
|
| 62 |
+
import argparse
|
| 63 |
+
import contextlib
|
| 64 |
+
import csv
|
| 65 |
+
import gc
|
| 66 |
+
import hashlib
|
| 67 |
+
import importlib
|
| 68 |
+
import json
|
| 69 |
+
import re
|
| 70 |
+
import shutil
|
| 71 |
+
import sys
|
| 72 |
+
import time
|
| 73 |
+
from dataclasses import dataclass, field
|
| 74 |
+
from pathlib import Path
|
| 75 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
| 76 |
+
|
| 77 |
+
import torch
|
| 78 |
+
from PIL import Image, ImageFile
|
| 79 |
+
|
| 80 |
+
import contextlib
|
| 81 |
+
|
| 82 |
+
@contextlib.contextmanager
|
| 83 |
+
def temporary_sys_path(path: str):
|
| 84 |
+
"""Temporarily prepend `path` to sys.path, then restore it exactly as it was."""
|
| 85 |
+
sys.path.insert(0, path)
|
| 86 |
+
try:
|
| 87 |
+
yield
|
| 88 |
+
finally:
|
| 89 |
+
sys.path.remove(path)
|
| 90 |
+
|
| 91 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True # don't error on truncated images
|
| 92 |
+
|
| 93 |
+
SCRIPT_DIR = Path(__file__).resolve().parent
|
| 94 |
+
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".webp"}
|
| 95 |
+
VALID_IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".tiff", ".webp")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# =============================================================================
|
| 99 |
+
# STAGE 1 — dataset scanning / prompt + mapping construction (was prep_ET.py)
|
| 100 |
+
# =============================================================================
|
| 101 |
+
|
| 102 |
+
@dataclass
|
| 103 |
+
class PromptRecord:
|
| 104 |
+
orig_path: str
|
| 105 |
+
artist: str
|
| 106 |
+
artwork: str
|
| 107 |
+
prompt: str
|
| 108 |
+
gen_paths: List[str]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def parse_artwork_artist(stem: str, split_on: str = "last") -> Tuple[str, str]:
|
| 112 |
+
"""
|
| 113 |
+
LEGACY positional parser, kept only as the final fallback for files the
|
| 114 |
+
frequency-based method below can't confidently resolve (e.g. a genuinely
|
| 115 |
+
rare artist with too few paintings to clear --min_artist_count). Prefer
|
| 116 |
+
build_artist_artwork_mapping() for the actual dataset scan.
|
| 117 |
+
"""
|
| 118 |
+
if "_" not in stem:
|
| 119 |
+
return stem.replace("_", " "), "unknown"
|
| 120 |
+
|
| 121 |
+
if split_on == "first":
|
| 122 |
+
idx = stem.index("_")
|
| 123 |
+
else: # "last"
|
| 124 |
+
idx = stem.rindex("_")
|
| 125 |
+
artwork_raw, artist_raw = stem[:idx], stem[idx + 1:]
|
| 126 |
+
|
| 127 |
+
return artwork_raw.replace("_", " ").strip(), artist_raw.replace("_", " ").strip()
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# =============================================================================
|
| 131 |
+
# Frequency-based artist/artwork parsing
|
| 132 |
+
# =============================================================================
|
| 133 |
+
# A real artist's name recurs as the EXACT SAME trailing underscore-token
|
| 134 |
+
# sequence across every one of their paintings (dozens to hundreds of files),
|
| 135 |
+
# while a one-off quirk in a title (a Bible-verse reference like
|
| 136 |
+
# "Genesis 22_2", a colon-substitute like "Composition_ The Guitar", a
|
| 137 |
+
# duplicate-title disambiguation suffix) is, by construction, unique to a
|
| 138 |
+
# single file. That frequency gap is detectable directly from the dataset's
|
| 139 |
+
# filenames, with no external artist list and no access to the original
|
| 140 |
+
# per-artist source folder structure required.
|
| 141 |
+
|
| 142 |
+
def _clean_artwork_text(s: str) -> str:
|
| 143 |
+
return re.sub(r"\s+", " ", s).strip()
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def build_suffix_counts(stems: List[str], max_tokens: int) -> Dict[Tuple[str, ...], int]:
|
| 147 |
+
counts: Dict[Tuple[str, ...], int] = {}
|
| 148 |
+
for stem in stems:
|
| 149 |
+
toks = stem.split("_")
|
| 150 |
+
for n in range(1, min(max_tokens, len(toks) - 1) + 1):
|
| 151 |
+
key = tuple(toks[-n:])
|
| 152 |
+
counts[key] = counts.get(key, 0) + 1
|
| 153 |
+
return counts
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _find_artist_token_count(stem: str, counts: Dict[Tuple[str, ...], int], max_tokens: int, min_count: int) -> Optional[int]:
|
| 157 |
+
toks = stem.split("_")
|
| 158 |
+
best_n = None
|
| 159 |
+
for n in range(1, min(max_tokens, len(toks) - 1) + 1):
|
| 160 |
+
if counts.get(tuple(toks[-n:]), 0) >= min_count:
|
| 161 |
+
best_n = n # counts are non-increasing in n; keep the largest that still clears
|
| 162 |
+
return best_n
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def build_artist_artwork_mapping(
|
| 166 |
+
stems: List[str], max_tokens: int = 4, min_count: int = 3
|
| 167 |
+
) -> Tuple[Dict[str, Dict[str, str]], List[str]]:
|
| 168 |
+
"""
|
| 169 |
+
Returns ({stem: {"artwork": ..., "artist": ...}}, unresolved_stems).
|
| 170 |
+
Two passes: raw stems first, then a retry with a trailing "_<digits>"
|
| 171 |
+
collision-suffix stripped for anything unresolved on the first pass
|
| 172 |
+
(recovers cases like "..._Claude_Monet_2" without disturbing genuine
|
| 173 |
+
title-content digits, which normally appear BEFORE the artist and are
|
| 174 |
+
unaffected by stripping only the trailing end of the string).
|
| 175 |
+
"""
|
| 176 |
+
counts = build_suffix_counts(stems, max_tokens)
|
| 177 |
+
results: Dict[str, Dict[str, str]] = {}
|
| 178 |
+
unresolved: List[str] = []
|
| 179 |
+
|
| 180 |
+
for stem in stems:
|
| 181 |
+
n = _find_artist_token_count(stem, counts, max_tokens, min_count)
|
| 182 |
+
if n is None:
|
| 183 |
+
unresolved.append(stem)
|
| 184 |
+
continue
|
| 185 |
+
toks = stem.split("_")
|
| 186 |
+
artist = " ".join(toks[-n:])
|
| 187 |
+
artwork = _clean_artwork_text(" ".join(toks[:-n]))
|
| 188 |
+
results[stem] = {"artwork": artwork, "artist": artist}
|
| 189 |
+
|
| 190 |
+
if not unresolved:
|
| 191 |
+
return results, []
|
| 192 |
+
|
| 193 |
+
def strip_trailing_digits(s: str) -> str:
|
| 194 |
+
return re.sub(r"_\d+$", "", s)
|
| 195 |
+
|
| 196 |
+
stripped_stems = [strip_trailing_digits(s) for s in stems]
|
| 197 |
+
stripped_counts = build_suffix_counts(stripped_stems, max_tokens)
|
| 198 |
+
|
| 199 |
+
still_unresolved: List[str] = []
|
| 200 |
+
for stem in unresolved:
|
| 201 |
+
stripped = strip_trailing_digits(stem)
|
| 202 |
+
if stripped == stem:
|
| 203 |
+
still_unresolved.append(stem)
|
| 204 |
+
continue
|
| 205 |
+
n = _find_artist_token_count(stripped, stripped_counts, max_tokens, min_count)
|
| 206 |
+
if n is None:
|
| 207 |
+
still_unresolved.append(stem)
|
| 208 |
+
continue
|
| 209 |
+
toks = stripped.split("_")
|
| 210 |
+
artist = " ".join(toks[-n:])
|
| 211 |
+
artwork = _clean_artwork_text(" ".join(toks[:-n]))
|
| 212 |
+
results[stem] = {"artwork": artwork, "artist": artist}
|
| 213 |
+
|
| 214 |
+
return results, still_unresolved
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def save_artist_artwork_mapping(mapping: Dict[str, Dict[str, str]], path: Path) -> None:
|
| 218 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 219 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 220 |
+
json.dump(mapping, f, indent=2, ensure_ascii=False)
|
| 221 |
+
print(f"[OK] Saved artist/artwork mapping ({len(mapping)} entries) -> {path}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def load_artist_artwork_mapping(path: Path) -> Dict[str, Dict[str, str]]:
|
| 225 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 226 |
+
return json.load(f)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def collect_images(dataset_dir: Path) -> List[Path]:
|
| 230 |
+
"""All image files directly inside dataset_dir (non-recursive, sorted)."""
|
| 231 |
+
return sorted(
|
| 232 |
+
p for p in dataset_dir.iterdir()
|
| 233 |
+
if p.is_file() and p.suffix.lower() in IMAGE_EXTENSIONS
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def build_prompt(artwork: str, artist: str) -> str:
|
| 238 |
+
return f"{artwork} in the style of {artist}"
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def sanitize_name(name: str) -> str:
|
| 242 |
+
"""Make a string safe for file/folder names (spaces -> underscores, strip unsafe chars)."""
|
| 243 |
+
name = name.strip()
|
| 244 |
+
name = re.sub(r"\s", "_", name)
|
| 245 |
+
name = re.sub(r"[^A-Za-z0-9_.-]", "", name)
|
| 246 |
+
return name
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def generated_paths_for(artist: str, artwork: str, root_output_dir: Path, num_imgs: int) -> List[str]:
|
| 250 |
+
"""
|
| 251 |
+
root_output_dir/<artist>_<artwork>_<idx>.png, 1-based, zero-padded to 2 digits.
|
| 252 |
+
|
| 253 |
+
NOTE: sanitize_name() is applied here — the SAME single place used both to
|
| 254 |
+
build the mapping.json entries and to save the actual generated files
|
| 255 |
+
later, so the two can never drift apart (the original two-script version
|
| 256 |
+
sanitized only in ET_infer.py, not in prep_ET.py's mapping — a latent
|
| 257 |
+
mismatch bug if artist/artwork ever contained characters like ' or : ).
|
| 258 |
+
"""
|
| 259 |
+
artist_slug = sanitize_name(artist)
|
| 260 |
+
artwork_slug = sanitize_name(artwork)
|
| 261 |
+
return [
|
| 262 |
+
str(root_output_dir / f"{artist_slug}_{artwork_slug}_{i + 1:02d}.png")
|
| 263 |
+
for i in range(num_imgs)
|
| 264 |
+
]
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def build_prompts_and_mapping(
|
| 268 |
+
dataset_dir: Path, root_output_dir: Path, num_imgs: int, name_split: str,
|
| 269 |
+
artist_artwork_mapping_path: Optional[Path] = None,
|
| 270 |
+
min_artist_count: int = 3, max_artist_tokens: int = 4,
|
| 271 |
+
) -> List[PromptRecord]:
|
| 272 |
+
"""
|
| 273 |
+
name_split is kept for backward compatibility (used only as the final
|
| 274 |
+
fallback for anything the frequency method can't resolve) but is no
|
| 275 |
+
longer the primary parsing method.
|
| 276 |
+
|
| 277 |
+
If artist_artwork_mapping_path already exists on disk, it's loaded and
|
| 278 |
+
reused as-is (so hand-corrections persist and don't get silently
|
| 279 |
+
overwritten by a recompute). Otherwise it's built fresh from THIS
|
| 280 |
+
dataset_dir's full file list — the frequency method needs the full
|
| 281 |
+
dataset in view to detect which trailing token sequences recur often
|
| 282 |
+
enough to be a real artist, so this mapping should be built once at the
|
| 283 |
+
dataset level and reused across every model that dataset is run with
|
| 284 |
+
(not recomputed per model).
|
| 285 |
+
"""
|
| 286 |
+
if not dataset_dir.exists() or not dataset_dir.is_dir():
|
| 287 |
+
sys.exit(f"[ERROR] dataset_dir does not exist or is not a directory: {dataset_dir}")
|
| 288 |
+
|
| 289 |
+
images = collect_images(dataset_dir)
|
| 290 |
+
if not images:
|
| 291 |
+
sys.exit(f"[ERROR] No supported image files found in: {dataset_dir}")
|
| 292 |
+
|
| 293 |
+
stems = [img.stem for img in images]
|
| 294 |
+
|
| 295 |
+
if artist_artwork_mapping_path is not None and artist_artwork_mapping_path.is_file():
|
| 296 |
+
artist_artwork_map = load_artist_artwork_mapping(artist_artwork_mapping_path)
|
| 297 |
+
print(f"[i] Reusing existing artist/artwork mapping -> {artist_artwork_mapping_path} "
|
| 298 |
+
f"({len(artist_artwork_map)} entries). Delete it to force a fresh frequency-based rebuild.")
|
| 299 |
+
unresolved_stems = [s for s in stems if s not in artist_artwork_map]
|
| 300 |
+
else:
|
| 301 |
+
artist_artwork_map, unresolved_stems = build_artist_artwork_mapping(
|
| 302 |
+
stems, max_tokens=max_artist_tokens, min_count=min_artist_count
|
| 303 |
+
)
|
| 304 |
+
artist_counts: Dict[str, int] = {}
|
| 305 |
+
for entry in artist_artwork_map.values():
|
| 306 |
+
artist_counts[entry["artist"]] = artist_counts.get(entry["artist"], 0) + 1
|
| 307 |
+
print(f"[i] Frequency-based parsing discovered {len(artist_counts)} distinct artist(s):")
|
| 308 |
+
for artist, count in sorted(artist_counts.items(), key=lambda kv: -kv[1]):
|
| 309 |
+
print(f" {artist!r:30s} {count} file(s)")
|
| 310 |
+
if artist_artwork_mapping_path is not None:
|
| 311 |
+
save_artist_artwork_mapping(artist_artwork_map, artist_artwork_mapping_path)
|
| 312 |
+
|
| 313 |
+
if unresolved_stems:
|
| 314 |
+
print(f"[!] {len(unresolved_stems)} file(s) didn't clear --min_artist_count via the frequency "
|
| 315 |
+
f"method (rare artist, or a naming quirk) — falling back to positional split for these:")
|
| 316 |
+
for stem in unresolved_stems[:20]:
|
| 317 |
+
print(f" {stem}")
|
| 318 |
+
if len(unresolved_stems) > 20:
|
| 319 |
+
print(f" ... and {len(unresolved_stems) - 20} more")
|
| 320 |
+
|
| 321 |
+
records: List[PromptRecord] = []
|
| 322 |
+
skipped = 0
|
| 323 |
+
for img_path in images:
|
| 324 |
+
entry = artist_artwork_map.get(img_path.stem)
|
| 325 |
+
if entry is not None:
|
| 326 |
+
artwork, artist = entry["artwork"], entry["artist"]
|
| 327 |
+
else:
|
| 328 |
+
artwork, artist = parse_artwork_artist(img_path.stem, split_on=name_split)
|
| 329 |
+
|
| 330 |
+
if not artwork or not artist or artist == "unknown":
|
| 331 |
+
print(f" [!] Skipping '{img_path.name}': could not parse artwork/artist.")
|
| 332 |
+
skipped += 1
|
| 333 |
+
continue
|
| 334 |
+
prompt = build_prompt(artwork, artist)
|
| 335 |
+
gen_paths = generated_paths_for(artist, artwork, root_output_dir, num_imgs)
|
| 336 |
+
records.append(PromptRecord(str(img_path), artist, artwork, prompt, gen_paths))
|
| 337 |
+
|
| 338 |
+
if not records:
|
| 339 |
+
sys.exit("[ERROR] No valid image/prompt pairs could be built.")
|
| 340 |
+
if skipped:
|
| 341 |
+
print(f"[!] Skipped {skipped} file(s) due to parse failures.")
|
| 342 |
+
print(f"[i] Built {len(records)} prompt record(s) from {dataset_dir}")
|
| 343 |
+
return records
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def save_prompts_pt(records: List[PromptRecord], pt_path: Path) -> None:
|
| 347 |
+
pt_path.parent.mkdir(parents=True, exist_ok=True)
|
| 348 |
+
torch.save([r.prompt for r in records], str(pt_path))
|
| 349 |
+
print(f"[OK] Saved {len(records)} prompt(s) -> {pt_path}")
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def save_mapping_json(records: List[PromptRecord], json_path: Path) -> None:
|
| 353 |
+
json_path.parent.mkdir(parents=True, exist_ok=True)
|
| 354 |
+
mapping = {r.orig_path: r.gen_paths for r in records}
|
| 355 |
+
with open(json_path, "w", encoding="utf-8") as f:
|
| 356 |
+
json.dump(mapping, f, indent=2, ensure_ascii=False)
|
| 357 |
+
print(f"[OK] Saved mapping ({len(mapping)} entries) -> {json_path}")
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def load_existing_records(
|
| 361 |
+
pt_path: Path, json_path: Path, name_split: str,
|
| 362 |
+
artist_artwork_mapping: Optional[Dict[str, Dict[str, str]]] = None,
|
| 363 |
+
) -> List[PromptRecord]:
|
| 364 |
+
"""
|
| 365 |
+
Reconstructs the exact PromptRecord list from an already-saved
|
| 366 |
+
prompts.pt + mapping.json pair, WITHOUT rescanning the dataset or
|
| 367 |
+
touching either file. This is what lets multiple parallel
|
| 368 |
+
--start_index/--end_index jobs share one canonical prompt/mapping set:
|
| 369 |
+
only the job that actually built them (via 'prep' in --stages) writes
|
| 370 |
+
to disk; every other job just reads.
|
| 371 |
+
|
| 372 |
+
prompts.pt is a plain list[str] of prompts, saved in the same order as
|
| 373 |
+
mapping.json's keys (both come from the same `records` list in one
|
| 374 |
+
save_prompts_pt/save_mapping_json call), so zipping them back together
|
| 375 |
+
by position is safe as long as neither file was hand-edited to reorder
|
| 376 |
+
entries.
|
| 377 |
+
|
| 378 |
+
artist/artwork aren't stored in either file (only orig_path, prompt,
|
| 379 |
+
gen_paths are), but generate_images() needs them for its dedup key and
|
| 380 |
+
logging -- so they're re-derived via a plain O(1) dict lookup into the
|
| 381 |
+
SAME artist_artwork_mapping already used to build this prompt set (no
|
| 382 |
+
frequency recomputation), falling back to the positional parser only
|
| 383 |
+
for a stem that mapping doesn't cover.
|
| 384 |
+
"""
|
| 385 |
+
if not pt_path.is_file() or not json_path.is_file():
|
| 386 |
+
raise FileNotFoundError(
|
| 387 |
+
f"'prep' excluded from --stages but prompts.pt/mapping.json not found "
|
| 388 |
+
f"({pt_path}, {json_path}). Run a job with 'prep' in --stages first."
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
prompts = torch.load(str(pt_path))
|
| 392 |
+
with open(json_path, "r", encoding="utf-8") as f:
|
| 393 |
+
mapping = json.load(f)
|
| 394 |
+
|
| 395 |
+
orig_paths = list(mapping.keys())
|
| 396 |
+
if len(orig_paths) != len(prompts):
|
| 397 |
+
raise ValueError(
|
| 398 |
+
f"prompts.pt ({len(prompts)} entries) and mapping.json ({len(orig_paths)} entries) "
|
| 399 |
+
f"are out of sync at {pt_path.parent} -- delete both and rerun with 'prep' in --stages."
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
records: List[PromptRecord] = []
|
| 403 |
+
for orig_path, prompt in zip(orig_paths, prompts):
|
| 404 |
+
stem = Path(orig_path).stem
|
| 405 |
+
entry = artist_artwork_mapping.get(stem) if artist_artwork_mapping else None
|
| 406 |
+
if entry is not None:
|
| 407 |
+
artwork, artist = entry["artwork"], entry["artist"]
|
| 408 |
+
else:
|
| 409 |
+
artwork, artist = parse_artwork_artist(stem, split_on=name_split)
|
| 410 |
+
records.append(PromptRecord(orig_path, artist, artwork, prompt, mapping[orig_path]))
|
| 411 |
+
|
| 412 |
+
print(f"[i] Loaded {len(records)} existing record(s) from {pt_path.name}/{json_path.name} (no rebuild).")
|
| 413 |
+
return records
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
# =============================================================================
|
| 417 |
+
# STAGE 2 — image generation (was ET_infer.py)
|
| 418 |
+
# =============================================================================
|
| 419 |
+
|
| 420 |
+
class DiffusersPipelineWrapper:
|
| 421 |
+
"""Adapts any standard diffusers pipeline to the uniform .generate(...) interface."""
|
| 422 |
+
|
| 423 |
+
def __init__(self, pipe, extra_call_kwargs: dict = None):
|
| 424 |
+
self.pipe = pipe
|
| 425 |
+
self.extra_call_kwargs = extra_call_kwargs or {} # e.g. {"height": 1024, "width": 1024}
|
| 426 |
+
|
| 427 |
+
def generate(self, prompt, num_inference_steps, guidance_scale, num_images_per_prompt, generator):
|
| 428 |
+
result = self.pipe(
|
| 429 |
+
prompt=prompt,
|
| 430 |
+
num_inference_steps=num_inference_steps,
|
| 431 |
+
guidance_scale=guidance_scale,
|
| 432 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 433 |
+
generator=generator,
|
| 434 |
+
**self.extra_call_kwargs,
|
| 435 |
+
)
|
| 436 |
+
return result.images # list[PIL.Image]
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load_sd15(device: torch.device):
|
| 440 |
+
from diffusers import StableDiffusionPipeline
|
| 441 |
+
# MODEL_ID = "stable-diffusion-v1-5/stable-diffusion-v1-5"
|
| 442 |
+
MODEL_ID = r"G:\T2I_models\SDv15"
|
| 443 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
| 444 |
+
MODEL_ID, torch_dtype=torch.float16, safety_checker=None
|
| 445 |
+
).to(device)
|
| 446 |
+
print("[model] Stable Diffusion v1.5 loaded successfully!")
|
| 447 |
+
return DiffusersPipelineWrapper(pipe)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def load_sdxl(device: torch.device):
|
| 451 |
+
from diffusers import StableDiffusionXLPipeline
|
| 452 |
+
# MODEL_ID = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 453 |
+
MODEL_ID = r"G:\T2I_models\SDXL"
|
| 454 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 455 |
+
MODEL_ID, torch_dtype=torch.float16
|
| 456 |
+
).to(device)
|
| 457 |
+
print("[model] Stable Diffusion XL loaded successfully!")
|
| 458 |
+
return DiffusersPipelineWrapper(pipe)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def load_sana15(device: torch.device):
|
| 462 |
+
from diffusers import SanaPipeline
|
| 463 |
+
pipe = SanaPipeline.from_pretrained( # NOTE: fixed the original repo's "frm_pretrained" typo
|
| 464 |
+
"Efficient-Large-Model/SANA1.5_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
|
| 465 |
+
).to(device)
|
| 466 |
+
pipe.text_encoder = pipe.text_encoder.to(torch.bfloat16)
|
| 467 |
+
pipe.vae = pipe.vae.to(torch.bfloat16)
|
| 468 |
+
print("[model] SANA 1.5 loaded successfully!")
|
| 469 |
+
return DiffusersPipelineWrapper(pipe)
|
| 470 |
+
|
| 471 |
+
def load_flux(device: torch.device):
|
| 472 |
+
from diffusers import DiffusionPipeline
|
| 473 |
+
# MODEL_ID = r"G:\T2I_models\FLUX2" # <-- change this to wherever you saved the Flux model
|
| 474 |
+
MODEL_ID = "diffusers/FLUX.2-dev-bnb-4bit"
|
| 475 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 476 |
+
MODEL_ID,
|
| 477 |
+
dtype=torch.bfloat16,
|
| 478 |
+
device_map="cuda",
|
| 479 |
+
)
|
| 480 |
+
print("[model] FLUX.2 loaded successfully!")
|
| 481 |
+
return DiffusersPipelineWrapper(pipe)
|
| 482 |
+
|
| 483 |
+
# def load_flux_dev(device: torch.device):
|
| 484 |
+
# from diffusers import FluxPipeline
|
| 485 |
+
# MODEL_ID = "black-forest-labs/FLUX.1-dev"
|
| 486 |
+
# pipe = FluxPipeline.from_pretrained(
|
| 487 |
+
# MODEL_ID, torch_dtype=torch.bfloat16
|
| 488 |
+
# ).to(device)
|
| 489 |
+
# print("[model] FLUX.1-dev loaded successfully!")
|
| 490 |
+
# return DiffusersPipelineWrapper(pipe)
|
| 491 |
+
def load_flux_dev(device: torch.device):
|
| 492 |
+
from diffusers import FluxPipeline
|
| 493 |
+
MODEL_ID = "black-forest-labs/FLUX.1-dev"
|
| 494 |
+
pipe = FluxPipeline.from_pretrained(
|
| 495 |
+
MODEL_ID,
|
| 496 |
+
dtype=torch.bfloat16, # updated from torch_dtype, see note below
|
| 497 |
+
token="...", # <-- your token as a string
|
| 498 |
+
).to(device)
|
| 499 |
+
print("[model] FLUX.1-dev loaded successfully!")
|
| 500 |
+
return DiffusersPipelineWrapper(pipe)
|
| 501 |
+
|
| 502 |
+
def load_sd35_medium(device: torch.device):
|
| 503 |
+
from diffusers import StableDiffusion3Pipeline
|
| 504 |
+
MODEL_ID = "stabilityai/stable-diffusion-3.5-medium"
|
| 505 |
+
pipe = StableDiffusion3Pipeline.from_pretrained(
|
| 506 |
+
MODEL_ID,
|
| 507 |
+
dtype=torch.bfloat16,
|
| 508 |
+
token="...", # <-- only needed if you're not using huggingface-cli login
|
| 509 |
+
).to(device)
|
| 510 |
+
print("[model] Stable Diffusion 3.5 Medium loaded successfully!")
|
| 511 |
+
return DiffusersPipelineWrapper(pipe)
|
| 512 |
+
|
| 513 |
+
def load_qwen_image(device: torch.device):
|
| 514 |
+
from diffusers import DiffusionPipeline
|
| 515 |
+
MODEL_ID = "Qwen/Qwen-Image"
|
| 516 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 517 |
+
MODEL_ID, torch_dtype=torch.bfloat16
|
| 518 |
+
).to(device)
|
| 519 |
+
print("[model] Qwen-Image loaded successfully!")
|
| 520 |
+
return DiffusersPipelineWrapper(pipe)
|
| 521 |
+
|
| 522 |
+
def load_sd35_large(device: torch.device):
|
| 523 |
+
from diffusers import StableDiffusion3Pipeline
|
| 524 |
+
MODEL_ID = "stabilityai/stable-diffusion-3.5-large"
|
| 525 |
+
pipe = StableDiffusion3Pipeline.from_pretrained(
|
| 526 |
+
MODEL_ID,
|
| 527 |
+
dtype=torch.bfloat16,
|
| 528 |
+
token="...", # only needed if not using huggingface-cli login
|
| 529 |
+
).to(device)
|
| 530 |
+
print("[model] Stable Diffusion 3.5 Large loaded successfully!")
|
| 531 |
+
return DiffusersPipelineWrapper(pipe)
|
| 532 |
+
|
| 533 |
+
def load_pixart_alpha(device: torch.device):
|
| 534 |
+
from diffusers import PixArtAlphaPipeline
|
| 535 |
+
MODEL_ID = "PixArt-alpha/PixArt-XL-2-1024-MS"
|
| 536 |
+
pipe = PixArtAlphaPipeline.from_pretrained(MODEL_ID, dtype=torch.bfloat16).to(device)
|
| 537 |
+
print("[model] PixArt-alpha loaded successfully!")
|
| 538 |
+
return DiffusersPipelineWrapper(pipe)
|
| 539 |
+
|
| 540 |
+
def load_pixart_sigma(device: torch.device):
|
| 541 |
+
from diffusers import PixArtAlphaPipeline
|
| 542 |
+
MODEL_ID = "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS"
|
| 543 |
+
pipe = PixArtAlphaPipeline.from_pretrained(MODEL_ID, dtype=torch.bfloat16).to(device)
|
| 544 |
+
print("[model] PixArt-Sigma loaded successfully!")
|
| 545 |
+
return DiffusersPipelineWrapper(pipe)
|
| 546 |
+
|
| 547 |
+
def load_auraflow(device: torch.device):
|
| 548 |
+
from diffusers import AuraFlowPipeline
|
| 549 |
+
MODEL_ID = "fal/AuraFlow-v0.3"
|
| 550 |
+
pipe = AuraFlowPipeline.from_pretrained(MODEL_ID, dtype=torch.bfloat16).to(device)
|
| 551 |
+
print("[model] AuraFlow v0.3 loaded successfully!")
|
| 552 |
+
return DiffusersPipelineWrapper(pipe)
|
| 553 |
+
|
| 554 |
+
def load_kandinsky22(device: torch.device):
|
| 555 |
+
from diffusers import KandinskyV22CombinedPipeline
|
| 556 |
+
MODEL_ID = "kandinsky-community/kandinsky-2-2-decoder"
|
| 557 |
+
pipe = KandinskyV22CombinedPipeline.from_pretrained(MODEL_ID, dtype=torch.bfloat16).to(device)
|
| 558 |
+
print("[model] Kandinsky 2.2 loaded successfully!")
|
| 559 |
+
return DiffusersPipelineWrapper(pipe)
|
| 560 |
+
|
| 561 |
+
class Kandinsky31Wrapper:
|
| 562 |
+
def __init__(self, t2i_pipe):
|
| 563 |
+
self.t2i_pipe = t2i_pipe
|
| 564 |
+
|
| 565 |
+
def generate(self, prompt, num_inference_steps, guidance_scale, num_images_per_prompt, generator):
|
| 566 |
+
return self.t2i_pipe(
|
| 567 |
+
prompt,
|
| 568 |
+
images_num=num_images_per_prompt,
|
| 569 |
+
steps=num_inference_steps,
|
| 570 |
+
guidance_scale=guidance_scale,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def load_kandinsky31(device: torch.device):
|
| 575 |
+
KANDINSKY3_REPO_PATH = r"G:\Kandinsky-3-main"
|
| 576 |
+
|
| 577 |
+
with temporary_sys_path(KANDINSKY3_REPO_PATH):
|
| 578 |
+
from kandinsky3 import get_T2I_pipeline
|
| 579 |
+
|
| 580 |
+
device_map = device
|
| 581 |
+
dtype_map = {
|
| 582 |
+
'unet': torch.float16,
|
| 583 |
+
'text_encoder': torch.float16,
|
| 584 |
+
'movq': torch.float16,
|
| 585 |
+
}
|
| 586 |
+
t2i_pipe = get_T2I_pipeline(device_map, dtype_map,cache_dir= r"D:\kandinsky3")
|
| 587 |
+
print("[model] Kandinsky 3.1 (Full) loaded successfully!")
|
| 588 |
+
return Kandinsky31Wrapper(t2i_pipe)
|
| 589 |
+
|
| 590 |
+
class Kandinsky5Wrapper:
|
| 591 |
+
"""
|
| 592 |
+
Kandinsky5T2IPipeline returns `.image` (singular) instead of `.images`
|
| 593 |
+
like most diffusers pipelines. Everything else matches the standard
|
| 594 |
+
.generate(...) interface DiffusersPipelineWrapper uses.
|
| 595 |
+
"""
|
| 596 |
+
def __init__(self, pipe):
|
| 597 |
+
self.pipe = pipe
|
| 598 |
+
|
| 599 |
+
def generate(self, prompt, num_inference_steps, guidance_scale, num_images_per_prompt, generator):
|
| 600 |
+
result = self.pipe(
|
| 601 |
+
prompt=prompt,
|
| 602 |
+
num_inference_steps=num_inference_steps,
|
| 603 |
+
guidance_scale=guidance_scale,
|
| 604 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 605 |
+
generator=generator,
|
| 606 |
+
)
|
| 607 |
+
return result.image # note: .image, not .images
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def load_kandinsky5(device: torch.device):
|
| 611 |
+
from diffusers import Kandinsky5T2IPipeline
|
| 612 |
+
MODEL_ID = "kandinskylab/Kandinsky-5.0-T2I-Lite-sft-Diffusers"
|
| 613 |
+
pipe = Kandinsky5T2IPipeline.from_pretrained(
|
| 614 |
+
MODEL_ID, dtype=torch.bfloat16
|
| 615 |
+
).to(device)
|
| 616 |
+
print("[model] Kandinsky 5.0 loaded successfully!")
|
| 617 |
+
return Kandinsky5Wrapper(pipe)
|
| 618 |
+
|
| 619 |
+
def load_z_image(device: torch.device):
|
| 620 |
+
from diffusers import ZImagePipeline
|
| 621 |
+
MODEL_ID = "Tongyi-MAI/Z-Image"
|
| 622 |
+
pipe = ZImagePipeline.from_pretrained(MODEL_ID, torch_dtype=torch.float16, low_cpu_mem_usage=False).to(device)
|
| 623 |
+
print("[model] Z-Image (standard/base) loaded successfully!")
|
| 624 |
+
return DiffusersPipelineWrapper(pipe, extra_call_kwargs={"height": 1024, "width": 1024})
|
| 625 |
+
|
| 626 |
+
class HunyuanImageWrapper:
|
| 627 |
+
"""
|
| 628 |
+
HunyuanImagePipeline doesn't accept `guidance_scale` as a __call__ kwarg —
|
| 629 |
+
it's configured via a separate `guider` object instead (pipe.guider.new(...)).
|
| 630 |
+
It's also natively a 2K model, so height/width are fixed here rather than
|
| 631 |
+
left to the pipeline's own defaults. Everything else matches the same
|
| 632 |
+
.generate(...) interface DiffusersPipelineWrapper uses.
|
| 633 |
+
"""
|
| 634 |
+
def __init__(self, pipe, height: int = 2048, width: int = 2048):
|
| 635 |
+
self.pipe = pipe
|
| 636 |
+
self.height = height
|
| 637 |
+
self.width = width
|
| 638 |
+
|
| 639 |
+
def generate(self, prompt, num_inference_steps, guidance_scale, num_images_per_prompt, generator):
|
| 640 |
+
# Route guidance_scale into the guider instead of passing it to __call__.
|
| 641 |
+
self.pipe.guider = self.pipe.guider.new(guidance_scale=guidance_scale)
|
| 642 |
+
result = self.pipe(
|
| 643 |
+
prompt=prompt,
|
| 644 |
+
num_inference_steps=num_inference_steps,
|
| 645 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 646 |
+
generator=generator,
|
| 647 |
+
height=self.height,
|
| 648 |
+
width=self.width,
|
| 649 |
+
)
|
| 650 |
+
return result.images # list[PIL.Image]
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def load_hunyuanimage21(device: torch.device):
|
| 654 |
+
from diffusers import HunyuanImagePipeline
|
| 655 |
+
MODEL_ID = "hunyuanvideo-community/HunyuanImage-2.1-Diffusers"
|
| 656 |
+
pipe = HunyuanImagePipeline.from_pretrained(MODEL_ID, dtype=torch.bfloat16).to(device)
|
| 657 |
+
print("[model] HunyuanImage-2.1 loaded successfully!")
|
| 658 |
+
return HunyuanImageWrapper(pipe)
|
| 659 |
+
|
| 660 |
+
# -----------------------------------------------------------------------------
|
| 661 |
+
# ============================ ADD NEW MODELS HERE ========================
|
| 662 |
+
# -----------------------------------------------------------------------------
|
| 663 |
+
# Template for registering a new text-to-image model:
|
| 664 |
+
#
|
| 665 |
+
# 1. Write a loader function `load_<your_model>(device) -> wrapper`.
|
| 666 |
+
# - If it's a standard diffusers pipeline, just load it and return
|
| 667 |
+
# DiffusersPipelineWrapper(pipe) — exactly like load_sd15 above.
|
| 668 |
+
# - If it's NOT a diffusers pipeline (custom repo, different API, etc.),
|
| 669 |
+
# write a small wrapper class with a matching method:
|
| 670 |
+
#
|
| 671 |
+
# def generate(self, prompt, num_inference_steps, guidance_scale,
|
| 672 |
+
# num_images_per_prompt, generator) -> list[PIL.Image]:
|
| 673 |
+
# ...
|
| 674 |
+
#
|
| 675 |
+
# `generator` will be a list of torch.Generator objects (one per
|
| 676 |
+
# image) or None — handle whichever your backend supports.
|
| 677 |
+
#
|
| 678 |
+
# 2. Register it in MODEL_LOADERS below with the --model_name string
|
| 679 |
+
# you want to use on the command line.
|
| 680 |
+
#
|
| 681 |
+
# Example skeleton:
|
| 682 |
+
#
|
| 683 |
+
# def load_my_new_model(device: torch.device):
|
| 684 |
+
# # from my_package import MyPipeline
|
| 685 |
+
# # pipe = MyPipeline.from_pretrained("org/my-model").to(device)
|
| 686 |
+
# # return DiffusersPipelineWrapper(pipe) # if diffusers-style
|
| 687 |
+
# raise NotImplementedError("Implement load_my_new_model() and register it below.")
|
| 688 |
+
#
|
| 689 |
+
# MODEL_LOADERS["my_new_model"] = load_my_new_model
|
| 690 |
+
# -----------------------------------------------------------------------------
|
| 691 |
+
|
| 692 |
+
# MODEL_LOADERS: Dict[str, Callable[[torch.device], Any]] = {
|
| 693 |
+
# "sd15": load_sd15,
|
| 694 |
+
# "sdxl": load_sdxl,
|
| 695 |
+
# "sana15": load_sana15,
|
| 696 |
+
# # "my_new_model": load_my_new_model, # <- uncomment once implemented above
|
| 697 |
+
# }
|
| 698 |
+
|
| 699 |
+
# MODEL_LOADERS: Dict[str, Callable[[torch.device], Any]] = {
|
| 700 |
+
# "sd15": load_sd15,
|
| 701 |
+
# "sdxl": load_sdxl,
|
| 702 |
+
# "sana15": load_sana15,
|
| 703 |
+
# "flux": load_flux,
|
| 704 |
+
# }
|
| 705 |
+
MODEL_LOADERS: Dict[str, Callable[[torch.device], Any]] = {
|
| 706 |
+
"sd15": load_sd15,
|
| 707 |
+
"sdxl": load_sdxl,
|
| 708 |
+
"sana15": load_sana15,
|
| 709 |
+
"flux": load_flux, # if you added FLUX.2-dev earlier
|
| 710 |
+
"flux_dev": load_flux_dev, # FLUX.1-dev
|
| 711 |
+
"qwen_image": load_qwen_image,
|
| 712 |
+
"sd35_medium": load_sd35_medium,
|
| 713 |
+
"sd35_large": load_sd35_large,
|
| 714 |
+
"pixart_alpha": load_pixart_alpha,
|
| 715 |
+
"auraflow": load_auraflow,
|
| 716 |
+
"kandinsky22": load_kandinsky22,
|
| 717 |
+
"pixart_sigma": load_pixart_sigma,
|
| 718 |
+
"z_image": load_z_image,
|
| 719 |
+
"hunyuanimage21": load_hunyuanimage21,
|
| 720 |
+
"kandinsky5": load_kandinsky5,
|
| 721 |
+
"kandinsky31": load_kandinsky31,
|
| 722 |
+
}
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def unload_model(wrapper) -> None:
|
| 726 |
+
"""Free GPU memory before loading the next model in a sweep."""
|
| 727 |
+
del wrapper
|
| 728 |
+
gc.collect()
|
| 729 |
+
if torch.cuda.is_available():
|
| 730 |
+
torch.cuda.empty_cache()
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
def generate_images(
|
| 734 |
+
records: List[PromptRecord],
|
| 735 |
+
wrapper,
|
| 736 |
+
root_output_dir: Path,
|
| 737 |
+
images_per_prompt: int,
|
| 738 |
+
num_inference_steps: int,
|
| 739 |
+
guidance_scale: float,
|
| 740 |
+
seed_base: Optional[int],
|
| 741 |
+
device: torch.device,
|
| 742 |
+
skip_existing: bool,
|
| 743 |
+
) -> None:
|
| 744 |
+
"""
|
| 745 |
+
Generates images for each unique (artist, artwork) pair in `records` and
|
| 746 |
+
saves them to the exact paths already computed in record.gen_paths — so
|
| 747 |
+
generation output and mapping.json can never disagree on filenames.
|
| 748 |
+
"""
|
| 749 |
+
root_output_dir.mkdir(parents=True, exist_ok=True)
|
| 750 |
+
|
| 751 |
+
# Dedup by (artist, artwork): identical pairs share identical gen_paths,
|
| 752 |
+
# so there's no reason to render them twice (mirrors ET_infer.py's
|
| 753 |
+
# prompt-level dedup, but keyed on the actual output-path identity).
|
| 754 |
+
seen = set()
|
| 755 |
+
unique_records: List[PromptRecord] = []
|
| 756 |
+
for r in records:
|
| 757 |
+
key = (r.artist, r.artwork)
|
| 758 |
+
if key in seen:
|
| 759 |
+
continue
|
| 760 |
+
seen.add(key)
|
| 761 |
+
unique_records.append(r)
|
| 762 |
+
|
| 763 |
+
total = len(unique_records)
|
| 764 |
+
for idx, rec in enumerate(unique_records, start=1):
|
| 765 |
+
if skip_existing and all(Path(p).exists() for p in rec.gen_paths):
|
| 766 |
+
print(f"[{idx}/{total}] [skip] already generated: '{rec.artwork}' x '{rec.artist}'")
|
| 767 |
+
continue
|
| 768 |
+
|
| 769 |
+
print(f"\n[{idx}/{total}] Generating: '{rec.artwork}' in the style of '{rec.artist}'")
|
| 770 |
+
print(f"Prompt: {rec.prompt}")
|
| 771 |
+
|
| 772 |
+
generator = None
|
| 773 |
+
if seed_base is not None:
|
| 774 |
+
generator = [
|
| 775 |
+
torch.Generator(device=device).manual_seed(seed_base + idx * 1000 + k)
|
| 776 |
+
for k in range(images_per_prompt)
|
| 777 |
+
]
|
| 778 |
+
|
| 779 |
+
images = wrapper.generate(
|
| 780 |
+
prompt=rec.prompt,
|
| 781 |
+
num_inference_steps=num_inference_steps,
|
| 782 |
+
guidance_scale=guidance_scale,
|
| 783 |
+
num_images_per_prompt=images_per_prompt,
|
| 784 |
+
generator=generator,
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
for k, (image, out_path) in enumerate(zip(images, rec.gen_paths), start=1):
|
| 788 |
+
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
|
| 789 |
+
image.save(out_path)
|
| 790 |
+
print(f" -> Saved: {out_path}")
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
# =============================================================================
|
| 794 |
+
# STAGE 3 — proximity scoring (clip / csd / lpips) (was ET_eval_fixed.py)
|
| 795 |
+
# =============================================================================
|
| 796 |
+
|
| 797 |
+
@dataclass
|
| 798 |
+
class MetricHandlers:
|
| 799 |
+
load_embedding: Callable[[str], torch.Tensor]
|
| 800 |
+
compute_score: Callable[[torch.Tensor, torch.Tensor], float]
|
| 801 |
+
score_column_name: str
|
| 802 |
+
sort_ascending: bool
|
| 803 |
+
cache_embeddings: bool
|
| 804 |
+
model: Any = field(default=None, repr=False) # kept alive for the closures' lifetime
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def amp_context(device: torch.device, use_amp: bool):
|
| 808 |
+
if use_amp and device.type == "cuda":
|
| 809 |
+
return torch.amp.autocast("cuda", dtype=torch.float16)
|
| 810 |
+
return contextlib.nullcontext()
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def build_clip_handlers(device: torch.device, use_amp: bool) -> MetricHandlers:
|
| 814 |
+
from transformers import CLIPModel, CLIPProcessor
|
| 815 |
+
CLIP_MODEL_ID = "openai/clip-vit-base-patch32"
|
| 816 |
+
model = CLIPModel.from_pretrained(CLIP_MODEL_ID).to(device)
|
| 817 |
+
processor = CLIPProcessor.from_pretrained(CLIP_MODEL_ID)
|
| 818 |
+
model.eval()
|
| 819 |
+
print(f"[metric] CLIP model '{CLIP_MODEL_ID}' loaded successfully!")
|
| 820 |
+
|
| 821 |
+
def load_embedding(image_path: str) -> torch.Tensor:
|
| 822 |
+
with Image.open(image_path) as im:
|
| 823 |
+
im = im.convert("RGB")
|
| 824 |
+
inputs = processor(images=im, return_tensors="pt")
|
| 825 |
+
pixel_values = inputs["pixel_values"].to(device)
|
| 826 |
+
with torch.no_grad(), amp_context(device, use_amp):
|
| 827 |
+
vision_outputs = model.vision_model(pixel_values=pixel_values)
|
| 828 |
+
pooled_output = vision_outputs.pooler_output
|
| 829 |
+
img_feat = model.visual_projection(pooled_output)
|
| 830 |
+
img_feat = img_feat / (img_feat.norm(p=2, dim=-1, keepdim=True) + 1e-8)
|
| 831 |
+
return img_feat
|
| 832 |
+
|
| 833 |
+
def compute_score(a: torch.Tensor, b: torch.Tensor) -> float:
|
| 834 |
+
a = a / (a.norm(p=2, dim=-1, keepdim=True) + 1e-8)
|
| 835 |
+
b = b / (b.norm(p=2, dim=-1, keepdim=True) + 1e-8)
|
| 836 |
+
return float((a @ b.T).item())
|
| 837 |
+
|
| 838 |
+
return MetricHandlers(load_embedding, compute_score, "clip_cosine_similarity",
|
| 839 |
+
sort_ascending=False, cache_embeddings=True, model=model)
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def build_csd_handlers(
|
| 843 |
+
device: torch.device, use_amp: bool, csd_repo_dir: Path, model_path: Path,
|
| 844 |
+
use_cosine_similarity: bool,
|
| 845 |
+
) -> MetricHandlers:
|
| 846 |
+
from torchvision import transforms
|
| 847 |
+
import torchvision.transforms.functional as TF
|
| 848 |
+
|
| 849 |
+
if not csd_repo_dir.is_dir():
|
| 850 |
+
sys.exit(f"[ERROR] --csd_repo_dir not found: {csd_repo_dir}")
|
| 851 |
+
if not model_path.is_file():
|
| 852 |
+
sys.exit(f"[ERROR] --csd_model_path not found: {model_path}")
|
| 853 |
+
|
| 854 |
+
csd_repo_abs = csd_repo_dir.resolve()
|
| 855 |
+
csd_parent = csd_repo_abs.parent
|
| 856 |
+
csd_pkg_name = csd_repo_abs.name
|
| 857 |
+
|
| 858 |
+
if str(csd_parent) not in sys.path:
|
| 859 |
+
sys.path.insert(0, str(csd_parent))
|
| 860 |
+
|
| 861 |
+
init_file = csd_repo_abs / "__init__.py"
|
| 862 |
+
if not init_file.exists():
|
| 863 |
+
init_file.touch()
|
| 864 |
+
print(f"[metric] Created missing {init_file} to enable package-relative imports.")
|
| 865 |
+
|
| 866 |
+
csd_model_mod = importlib.import_module(f"{csd_pkg_name}.model")
|
| 867 |
+
CSD_CLIP = csd_model_mod.CSD_CLIP
|
| 868 |
+
|
| 869 |
+
if hasattr(csd_model_mod, "convert_state_dict"):
|
| 870 |
+
convert_state_dict = csd_model_mod.convert_state_dict
|
| 871 |
+
else:
|
| 872 |
+
csd_utils_mod = importlib.import_module(f"{csd_pkg_name}.utils")
|
| 873 |
+
convert_state_dict = csd_utils_mod.convert_state_dict
|
| 874 |
+
|
| 875 |
+
model = CSD_CLIP("vit_large", "default")
|
| 876 |
+
checkpoint = torch.load(str(model_path), map_location="cpu", weights_only=False)
|
| 877 |
+
state_dict = convert_state_dict(checkpoint["model_state_dict"])
|
| 878 |
+
model.load_state_dict(state_dict, strict=False)
|
| 879 |
+
model = model.to(device)
|
| 880 |
+
model.eval()
|
| 881 |
+
|
| 882 |
+
normalize = transforms.Normalize(
|
| 883 |
+
(0.48145466, 0.4578275, 0.40821073),
|
| 884 |
+
(0.26862954, 0.26130258, 0.27577711),
|
| 885 |
+
)
|
| 886 |
+
preprocess = transforms.Compose([
|
| 887 |
+
transforms.Resize(size=224, interpolation=TF.InterpolationMode.BICUBIC),
|
| 888 |
+
transforms.CenterCrop(224),
|
| 889 |
+
transforms.ToTensor(),
|
| 890 |
+
normalize,
|
| 891 |
+
])
|
| 892 |
+
print(f"[metric] CSD model loaded from '{model_path}' | cosine_sim={use_cosine_similarity}")
|
| 893 |
+
|
| 894 |
+
def load_embedding(image_path: str) -> torch.Tensor:
|
| 895 |
+
with Image.open(image_path) as im:
|
| 896 |
+
im = im.convert("RGB")
|
| 897 |
+
img_tensor = preprocess(im).unsqueeze(0).to(device)
|
| 898 |
+
with amp_context(device, use_amp):
|
| 899 |
+
output = model(img_tensor)
|
| 900 |
+
style_output = output[1] if isinstance(output, (tuple, list)) else output
|
| 901 |
+
return style_output
|
| 902 |
+
|
| 903 |
+
def compute_score(a: torch.Tensor, b: torch.Tensor) -> float:
|
| 904 |
+
if use_cosine_similarity:
|
| 905 |
+
eps = 1e-8
|
| 906 |
+
a = a / (a.norm(dim=1, keepdim=True) + eps)
|
| 907 |
+
b = b / (b.norm(dim=1, keepdim=True) + eps)
|
| 908 |
+
return float((a @ b.T).item())
|
| 909 |
+
|
| 910 |
+
return MetricHandlers(load_embedding, compute_score, "csd_score",
|
| 911 |
+
sort_ascending=False, cache_embeddings=True, model=model)
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
def build_lpips_handlers(device: torch.device) -> MetricHandlers:
|
| 915 |
+
import torch.nn.functional as F
|
| 916 |
+
import torchvision.transforms as T
|
| 917 |
+
from PIL import ImageOps
|
| 918 |
+
|
| 919 |
+
try:
|
| 920 |
+
import lpips
|
| 921 |
+
except ImportError:
|
| 922 |
+
raise RuntimeError("lpips not installed. Run: pip install lpips")
|
| 923 |
+
|
| 924 |
+
LPIPS_NET = "alex"
|
| 925 |
+
INTERP_MODE = "bicubic"
|
| 926 |
+
to_tensor_01 = T.Compose([T.ToTensor()])
|
| 927 |
+
|
| 928 |
+
# -------------------------------------------------------------------
|
| 929 |
+
# Load AlexNet's ImageNet weights from a LOCAL FILE, bypassing the
|
| 930 |
+
# network download entirely.
|
| 931 |
+
#
|
| 932 |
+
# Same underlying mechanism as the working Welkin reference script
|
| 933 |
+
# (also applied to MotifDuels.py's build_lpips_tournament_metric):
|
| 934 |
+
# lpips.LPIPS(net="alex") calls torchvision.models.alexnet
|
| 935 |
+
# (pretrained=True), which always resolves its weights via
|
| 936 |
+
# torch.hub -- checking <TORCH_HOME>/hub/checkpoints/<filename>.pth
|
| 937 |
+
# BEFORE ever attempting a download. So instead of intercepting the
|
| 938 |
+
# download call, we seed that exact cache location with the local
|
| 939 |
+
# file first; torch.hub then just finds it there and never reaches
|
| 940 |
+
# the network.
|
| 941 |
+
#
|
| 942 |
+
# Set this to your local .pth file.
|
| 943 |
+
ALEXNET_WEIGHTS_LOCAL_PATH = "/workspace/data/Ninad/Style_Leakage/Large_Experiments/Imitation_on_all/Art_FID/alexnet-owt-7be5be79.pth"
|
| 944 |
+
|
| 945 |
+
def _prepare_torchvision_cache_for_alexnet(local_path: str) -> str:
|
| 946 |
+
"""Ensure torchvision finds alexnet-owt-7be5be79.pth offline by
|
| 947 |
+
placing it in the hub checkpoints cache. Returns the destination path."""
|
| 948 |
+
import os
|
| 949 |
+
import shutil
|
| 950 |
+
|
| 951 |
+
if not os.path.isfile(local_path):
|
| 952 |
+
raise FileNotFoundError(f"Local AlexNet weights not found at: {local_path}")
|
| 953 |
+
|
| 954 |
+
torch_home = os.environ.get("TORCH_HOME", os.path.join(Path.home(), ".cache", "torch"))
|
| 955 |
+
checkpoints_dir = os.path.join(torch_home, "hub", "checkpoints")
|
| 956 |
+
os.makedirs(checkpoints_dir, exist_ok=True)
|
| 957 |
+
|
| 958 |
+
dest = os.path.join(checkpoints_dir, "alexnet-owt-7be5be79.pth")
|
| 959 |
+
|
| 960 |
+
need_copy = True
|
| 961 |
+
if os.path.exists(dest):
|
| 962 |
+
try:
|
| 963 |
+
need_copy = os.path.getsize(local_path) != os.path.getsize(dest)
|
| 964 |
+
except Exception:
|
| 965 |
+
need_copy = True
|
| 966 |
+
|
| 967 |
+
if need_copy:
|
| 968 |
+
shutil.copy2(local_path, dest)
|
| 969 |
+
print(f"[CACHE] Seeded TorchVision cache: {dest}")
|
| 970 |
+
else:
|
| 971 |
+
print(f"[CACHE] TorchVision cache already contains AlexNet weights: {dest}")
|
| 972 |
+
|
| 973 |
+
return dest
|
| 974 |
+
|
| 975 |
+
if ALEXNET_WEIGHTS_LOCAL_PATH:
|
| 976 |
+
try:
|
| 977 |
+
_prepare_torchvision_cache_for_alexnet(ALEXNET_WEIGHTS_LOCAL_PATH)
|
| 978 |
+
except FileNotFoundError as e:
|
| 979 |
+
print(f"[WARN] {e} -- falling back to normal download.")
|
| 980 |
+
|
| 981 |
+
loss_fn = lpips.LPIPS(net=LPIPS_NET).to(device)
|
| 982 |
+
loss_fn.eval()
|
| 983 |
+
print(f"[metric] LPIPS model (net={LPIPS_NET}) loaded successfully!")
|
| 984 |
+
|
| 985 |
+
def load_embedding(image_path: str) -> torch.Tensor:
|
| 986 |
+
with Image.open(image_path) as im:
|
| 987 |
+
im = ImageOps.exif_transpose(im).convert("RGB")
|
| 988 |
+
x = to_tensor_01(im) * 2.0 - 1.0 # [-1, 1]
|
| 989 |
+
return x.unsqueeze(0).to(device)
|
| 990 |
+
|
| 991 |
+
def compute_score(a: torch.Tensor, b: torch.Tensor) -> float:
|
| 992 |
+
if a.shape[2:] != b.shape[2:]:
|
| 993 |
+
h_t, w_t = b.shape[2], b.shape[3]
|
| 994 |
+
try:
|
| 995 |
+
a = F.interpolate(a, size=(h_t, w_t), mode=INTERP_MODE, align_corners=False, antialias=True)
|
| 996 |
+
except TypeError:
|
| 997 |
+
a = F.interpolate(a, size=(h_t, w_t), mode=INTERP_MODE, align_corners=False)
|
| 998 |
+
return float(loss_fn(a, b).item())
|
| 999 |
+
|
| 1000 |
+
return MetricHandlers(load_embedding, compute_score, "lpips_distance",
|
| 1001 |
+
sort_ascending=True, cache_embeddings=False, model=loss_fn)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
METRIC_BUILDERS = {"clip": build_clip_handlers, "csd": build_csd_handlers, "lpips": build_lpips_handlers}
|
| 1005 |
+
|
| 1006 |
+
|
| 1007 |
+
def is_nonempty_str(s) -> bool:
|
| 1008 |
+
return isinstance(s, str) and len(s.strip()) > 0
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
def has_valid_image_extension(path: str) -> bool:
|
| 1012 |
+
return Path(path).suffix.lower() in VALID_IMAGE_EXTS
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def short_hash(text: str, length: int = 8) -> str:
|
| 1016 |
+
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:length]
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
def unique_target_path(dst_dir: Path, base_name: str) -> Path:
|
| 1020 |
+
target = dst_dir / base_name
|
| 1021 |
+
if not target.exists():
|
| 1022 |
+
return target
|
| 1023 |
+
stem, ext = Path(base_name).stem, Path(base_name).suffix
|
| 1024 |
+
i = 1
|
| 1025 |
+
while True:
|
| 1026 |
+
candidate = dst_dir / f"{stem}__{i}{ext}"
|
| 1027 |
+
if not candidate.exists():
|
| 1028 |
+
return candidate
|
| 1029 |
+
i += 1
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
def copy_with_rank_and_hash(src_path: str, dst_dir: Path, rank: int) -> Path:
|
| 1033 |
+
dst_dir.mkdir(parents=True, exist_ok=True)
|
| 1034 |
+
base = Path(src_path).name
|
| 1035 |
+
h = short_hash(src_path)
|
| 1036 |
+
# ranked_name = f"[rank:{rank:02d}]__{h}__{base}"
|
| 1037 |
+
ranked_name = f"[rank-{rank:02d}]__{h}__{base}"
|
| 1038 |
+
target_path = unique_target_path(dst_dir, ranked_name)
|
| 1039 |
+
shutil.copy2(src_path, target_path)
|
| 1040 |
+
return target_path
|
| 1041 |
+
|
| 1042 |
+
|
| 1043 |
+
def save_top_pairs(results: List[Tuple[str, List[str], float]], top_root: Path, top_n: int) -> None:
|
| 1044 |
+
gen_dir = top_root / f"top{top_n}_generated"
|
| 1045 |
+
orig_dir = top_root / f"top{top_n}_original"
|
| 1046 |
+
print(f"[metric] Saving top-{top_n} pairs -> generated: {gen_dir} | original: {orig_dir}")
|
| 1047 |
+
for rank, (orig_path, gen_paths, score) in enumerate(results[:top_n], start=1):
|
| 1048 |
+
try:
|
| 1049 |
+
orig_dst = copy_with_rank_and_hash(orig_path, orig_dir, rank)
|
| 1050 |
+
gen_dsts = [copy_with_rank_and_hash(gp, gen_dir, rank) for gp in gen_paths]
|
| 1051 |
+
print(f"[TOP {rank:02d}] avg_score={score:.6f} orig: {orig_dst} gen: {gen_dsts}")
|
| 1052 |
+
except Exception as e:
|
| 1053 |
+
print(f"[ERROR] Failed copying pair rank={rank} ({orig_path}): {e}")
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
def score_mapping(
|
| 1057 |
+
mapping: Dict[str, List[str]],
|
| 1058 |
+
handlers: MetricHandlers,
|
| 1059 |
+
output_csv: Path,
|
| 1060 |
+
top_save_root: Optional[Path],
|
| 1061 |
+
top_n: int,
|
| 1062 |
+
) -> None:
|
| 1063 |
+
t0 = time.time()
|
| 1064 |
+
orig_embeddings: Dict[str, torch.Tensor] = {}
|
| 1065 |
+
gen_embeddings: Dict[str, torch.Tensor] = {}
|
| 1066 |
+
results: List[Tuple[str, List[str], float]] = []
|
| 1067 |
+
errors: List[str] = []
|
| 1068 |
+
|
| 1069 |
+
total = len(mapping)
|
| 1070 |
+
print(f"[metric] Processing {total} originals...")
|
| 1071 |
+
|
| 1072 |
+
with torch.no_grad():
|
| 1073 |
+
for idx, (orig_path, gen_paths) in enumerate(mapping.items(), start=1):
|
| 1074 |
+
if not Path(orig_path).is_file():
|
| 1075 |
+
msg = f"Missing original file: {orig_path}"
|
| 1076 |
+
print(f"[WARN] {msg}"); errors.append(msg); continue
|
| 1077 |
+
|
| 1078 |
+
try:
|
| 1079 |
+
if handlers.cache_embeddings:
|
| 1080 |
+
if orig_path not in orig_embeddings:
|
| 1081 |
+
orig_embeddings[orig_path] = handlers.load_embedding(orig_path).detach().cpu()
|
| 1082 |
+
a = orig_embeddings[orig_path]
|
| 1083 |
+
else:
|
| 1084 |
+
a = handlers.load_embedding(orig_path)
|
| 1085 |
+
except Exception as e:
|
| 1086 |
+
msg = f"Error embedding original ({orig_path}): {e}"
|
| 1087 |
+
print(f"[ERROR] {msg}"); errors.append(msg); continue
|
| 1088 |
+
|
| 1089 |
+
per_gen_scores: List[float] = []
|
| 1090 |
+
for gen_path in gen_paths:
|
| 1091 |
+
if not Path(gen_path).is_file():
|
| 1092 |
+
msg = f"Missing generated file: {gen_path} (original={orig_path})"
|
| 1093 |
+
print(f"[WARN] {msg}"); errors.append(msg); continue
|
| 1094 |
+
try:
|
| 1095 |
+
if handlers.cache_embeddings:
|
| 1096 |
+
if gen_path not in gen_embeddings:
|
| 1097 |
+
gen_embeddings[gen_path] = handlers.load_embedding(gen_path).detach().cpu()
|
| 1098 |
+
b = gen_embeddings[gen_path]
|
| 1099 |
+
else:
|
| 1100 |
+
b = handlers.load_embedding(gen_path)
|
| 1101 |
+
per_gen_scores.append(handlers.compute_score(a, b))
|
| 1102 |
+
except Exception as e:
|
| 1103 |
+
msg = f"Error scoring pair ({orig_path}, {gen_path}): {e}"
|
| 1104 |
+
print(f"[ERROR] {msg}"); errors.append(msg)
|
| 1105 |
+
|
| 1106 |
+
if not per_gen_scores:
|
| 1107 |
+
msg = f"No valid generated scores for original={orig_path}; skipping."
|
| 1108 |
+
print(f"[WARN] {msg}"); errors.append(msg); continue
|
| 1109 |
+
|
| 1110 |
+
avg_score = sum(per_gen_scores) / len(per_gen_scores)
|
| 1111 |
+
results.append((orig_path, gen_paths, avg_score))
|
| 1112 |
+
|
| 1113 |
+
if idx % 50 == 0 or idx == total:
|
| 1114 |
+
print(f"[metric] {idx}/{total} processed | avg_score={avg_score:.6f}")
|
| 1115 |
+
|
| 1116 |
+
results.sort(key=lambda x: x[2], reverse=not handlers.sort_ascending)
|
| 1117 |
+
|
| 1118 |
+
output_csv.parent.mkdir(parents=True, exist_ok=True)
|
| 1119 |
+
with open(output_csv, "w", newline="", encoding="utf-8") as f:
|
| 1120 |
+
writer = csv.writer(f)
|
| 1121 |
+
writer.writerow(["rank", "original_path", "generated_paths", "num_generated", handlers.score_column_name])
|
| 1122 |
+
for rank, (orig_path, gen_paths, avg_score) in enumerate(results, start=1):
|
| 1123 |
+
writer.writerow([rank, orig_path, "|".join(gen_paths), len(gen_paths), f"{avg_score:.8f}"])
|
| 1124 |
+
|
| 1125 |
+
print(f"[DONE] {len(results)} rows -> {output_csv} | Elapsed: {time.time()-t0:.2f}s | Errors: {len(errors)}")
|
| 1126 |
+
if errors:
|
| 1127 |
+
err_log = output_csv.with_name(output_csv.stem + "_errors.log")
|
| 1128 |
+
err_log.write_text("\n".join(errors), encoding="utf-8")
|
| 1129 |
+
print(f"[metric] Error log: {err_log}")
|
| 1130 |
+
|
| 1131 |
+
if top_save_root is not None:
|
| 1132 |
+
save_top_pairs(results, top_save_root, top_n)
|
| 1133 |
+
|
| 1134 |
+
|
| 1135 |
+
def unload_metric(handlers: MetricHandlers) -> None:
|
| 1136 |
+
del handlers
|
| 1137 |
+
gc.collect()
|
| 1138 |
+
if torch.cuda.is_available():
|
| 1139 |
+
torch.cuda.empty_cache()
|
| 1140 |
+
|
| 1141 |
+
|
| 1142 |
+
# =============================================================================
|
| 1143 |
+
# Orchestration
|
| 1144 |
+
# =============================================================================
|
| 1145 |
+
|
| 1146 |
+
def parse_args() -> argparse.Namespace:
|
| 1147 |
+
p = argparse.ArgumentParser(
|
| 1148 |
+
description="Self-contained ArtArena Entry-Trials pipeline: prep + generate + score.",
|
| 1149 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
p.add_argument("--list_models", action="store_true",
|
| 1153 |
+
help="Print registered model names and exit.")
|
| 1154 |
+
|
| 1155 |
+
p.add_argument("--datasets", nargs="+",
|
| 1156 |
+
help="One or more dataset directories.")
|
| 1157 |
+
p.add_argument("--models", nargs="+", default=["sd15"],
|
| 1158 |
+
help=f"One or more model names. Registered: {list(MODEL_LOADERS.keys())}")
|
| 1159 |
+
p.add_argument("--metrics", nargs="+", default=["clip"], choices=list(METRIC_BUILDERS.keys()),
|
| 1160 |
+
help="One or more proximity metrics.")
|
| 1161 |
+
p.add_argument("--output_root",
|
| 1162 |
+
help="Root directory for all outputs.")
|
| 1163 |
+
|
| 1164 |
+
# prep
|
| 1165 |
+
p.add_argument("--num_imgs", type=int, default=1,
|
| 1166 |
+
help="Images per prompt (used for both dataset prep and generation).")
|
| 1167 |
+
p.add_argument("--name_split", choices=["first", "last"], default="last",
|
| 1168 |
+
help="Fallback-only: used just for files the frequency-based parser can't resolve.")
|
| 1169 |
+
p.add_argument("--min_artist_count", type=int, default=3,
|
| 1170 |
+
help="Min files an artist must recur in for the frequency-based parser to trust it. "
|
| 1171 |
+
"Lower this if you have artists with very few paintings.")
|
| 1172 |
+
p.add_argument("--max_artist_tokens", type=int, default=4,
|
| 1173 |
+
help="Max artist-name length in underscore-tokens to consider (e.g. 'Vincent_van_Gogh' = 3).")
|
| 1174 |
+
p.add_argument("--artist_artwork_mapping", default=None,
|
| 1175 |
+
help="Path to a pre-built artist_artwork_mapping.json to use for EVERY dataset in this "
|
| 1176 |
+
"run, instead of the per-dataset auto path "
|
| 1177 |
+
"(<output_root>/<dataset_name>/artist_artwork_mapping.json). Same format this "
|
| 1178 |
+
"script already writes/reuses automatically. Build it once with a single prep-only "
|
| 1179 |
+
"run, then pass it explicitly to every parallel --start_index/--end_index job so "
|
| 1180 |
+
"they all resolve identical artist/artwork pairs instead of racing to build/write "
|
| 1181 |
+
"it independently.")
|
| 1182 |
+
|
| 1183 |
+
# infer chunking (for running several instances of this script in parallel)
|
| 1184 |
+
p.add_argument("--start_index", type=int, default=0,
|
| 1185 |
+
help="Only generate records[start_index:end_index] for each dataset (0-based, inclusive). "
|
| 1186 |
+
"prompts.pt/mapping.json always cover the FULL dataset regardless of this range — "
|
| 1187 |
+
"only the image-generation loop is sliced. Use this to split one large dataset's "
|
| 1188 |
+
"generation across multiple parallel script instances.")
|
| 1189 |
+
p.add_argument("--end_index", type=int, default=None,
|
| 1190 |
+
help="Exclusive upper bound for the generation slice (see --start_index). "
|
| 1191 |
+
"Omit to generate through the end of the dataset's record list.")
|
| 1192 |
+
|
| 1193 |
+
# infer
|
| 1194 |
+
p.add_argument("--num_inference_steps", type=int, default=25)
|
| 1195 |
+
p.add_argument("--guidance_scale", type=float, default=7.5)
|
| 1196 |
+
p.add_argument("--seed_base", type=int, default=42,
|
| 1197 |
+
help="Pass -1 for fully random generation.")
|
| 1198 |
+
|
| 1199 |
+
# eval
|
| 1200 |
+
p.add_argument("--top_n", type=int, default=20)
|
| 1201 |
+
p.add_argument("--no_amp", action="store_true", help="Disable AMP during scoring.")
|
| 1202 |
+
p.add_argument("--use_cosine_similarity_csd", action="store_true",
|
| 1203 |
+
help="[CSD only] L2-normalise before dot product.")
|
| 1204 |
+
p.add_argument("--csd_repo_dir", default=str(SCRIPT_DIR / "CSD"),
|
| 1205 |
+
help="Folder containing CSD's model.py/utils.py.")
|
| 1206 |
+
p.add_argument("--csd_model_path", default=str(SCRIPT_DIR / "CSD" / "checkpoint.pth"),
|
| 1207 |
+
help="Path to the CSD checkpoint .pth file.")
|
| 1208 |
+
|
| 1209 |
+
# orchestration
|
| 1210 |
+
p.add_argument("--stages", nargs="+", default=["prep", "infer", "eval"],
|
| 1211 |
+
choices=["prep", "infer", "eval"],
|
| 1212 |
+
help="Which stages to run. 'prep' is cheap and always safe to include; "
|
| 1213 |
+
"excluding it requires prompts.pt/mapping.json to already exist.")
|
| 1214 |
+
p.add_argument("--skip_existing", action="store_true",
|
| 1215 |
+
help="Skip generation/scoring for outputs that already exist (resumable sweeps).")
|
| 1216 |
+
p.add_argument("--dry_run", action="store_true",
|
| 1217 |
+
help="Print the planned dataset x model x metric grid and exit, without loading anything.")
|
| 1218 |
+
|
| 1219 |
+
args = p.parse_args()
|
| 1220 |
+
|
| 1221 |
+
if args.list_models:
|
| 1222 |
+
return args
|
| 1223 |
+
if not args.datasets or not args.output_root:
|
| 1224 |
+
p.error("--datasets and --output_root are required (unless using --list_models)")
|
| 1225 |
+
for m in args.models:
|
| 1226 |
+
if m not in MODEL_LOADERS:
|
| 1227 |
+
p.error(f"Unknown model '{m}'. Registered: {list(MODEL_LOADERS.keys())}")
|
| 1228 |
+
if args.start_index < 0:
|
| 1229 |
+
p.error("--start_index must be >= 0")
|
| 1230 |
+
if args.end_index is not None and args.end_index <= args.start_index:
|
| 1231 |
+
p.error(f"--end_index ({args.end_index}) must be greater than --start_index ({args.start_index})")
|
| 1232 |
+
return args
|
| 1233 |
+
|
| 1234 |
+
|
| 1235 |
+
def main() -> None:
|
| 1236 |
+
args = parse_args()
|
| 1237 |
+
|
| 1238 |
+
if args.list_models:
|
| 1239 |
+
print("Registered models:")
|
| 1240 |
+
for name in MODEL_LOADERS:
|
| 1241 |
+
print(f" - {name}")
|
| 1242 |
+
return
|
| 1243 |
+
|
| 1244 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 1245 |
+
if device.type == "cpu":
|
| 1246 |
+
print("[WARN] CUDA not available - running on CPU. This will be very slow.")
|
| 1247 |
+
|
| 1248 |
+
output_root = Path(args.output_root).resolve()
|
| 1249 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 1250 |
+
dataset_dirs = [Path(d).resolve() for d in args.datasets]
|
| 1251 |
+
use_amp = not args.no_amp
|
| 1252 |
+
|
| 1253 |
+
print(
|
| 1254 |
+
f"[i] Sweep: {len(dataset_dirs)} dataset(s) x {len(args.models)} model(s) "
|
| 1255 |
+
f"x {len(args.metrics)} metric(s) | stages={args.stages}"
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
def combo_dir(dataset_dir: Path, model_name: str) -> Path:
|
| 1259 |
+
return output_root / dataset_dir.name / model_name
|
| 1260 |
+
|
| 1261 |
+
if args.dry_run:
|
| 1262 |
+
for dataset_dir in dataset_dirs:
|
| 1263 |
+
for model_name in args.models:
|
| 1264 |
+
cd = combo_dir(dataset_dir, model_name)
|
| 1265 |
+
print(f"[dry_run] {dataset_dir.name} x {model_name} -> {cd}")
|
| 1266 |
+
for metric in args.metrics:
|
| 1267 |
+
print(f"[dry_run] eval[{metric}] -> {cd / 'eval' / metric}")
|
| 1268 |
+
return
|
| 1269 |
+
|
| 1270 |
+
failures: List[str] = []
|
| 1271 |
+
t_start = time.time()
|
| 1272 |
+
|
| 1273 |
+
# ---------------- Phase 1: prep + generation (model-outer loop) -----------------
|
| 1274 |
+
for model_name in args.models:
|
| 1275 |
+
wrapper = None
|
| 1276 |
+
if "infer" in args.stages:
|
| 1277 |
+
print(f"\n{'='*80}\n[Loading model] {model_name}\n{'='*80}")
|
| 1278 |
+
try:
|
| 1279 |
+
wrapper = MODEL_LOADERS[model_name](device)
|
| 1280 |
+
except Exception as e:
|
| 1281 |
+
msg = f"Failed to load model '{model_name}': {e}"
|
| 1282 |
+
print(f"[ERROR] {msg}")
|
| 1283 |
+
failures.append(msg)
|
| 1284 |
+
# continue
|
| 1285 |
+
|
| 1286 |
+
for dataset_dir in dataset_dirs:
|
| 1287 |
+
cd = combo_dir(dataset_dir, model_name)
|
| 1288 |
+
gen_dir = cd / "generated"
|
| 1289 |
+
print(f"\n--- dataset={dataset_dir.name} | model={model_name} ---")
|
| 1290 |
+
|
| 1291 |
+
records: Optional[List[PromptRecord]] = None
|
| 1292 |
+
if "prep" in args.stages or "infer" in args.stages:
|
| 1293 |
+
try:
|
| 1294 |
+
mapping_path = (
|
| 1295 |
+
Path(args.artist_artwork_mapping) if args.artist_artwork_mapping
|
| 1296 |
+
else (output_root / dataset_dir.name / "artist_artwork_mapping.json")
|
| 1297 |
+
)
|
| 1298 |
+
if "prep" in args.stages:
|
| 1299 |
+
# This is the "producer" run: build fresh from the dataset scan
|
| 1300 |
+
# (reusing mapping_path's artist/artwork mapping if it already
|
| 1301 |
+
# exists, exactly as before) and ALWAYS (over)save the FULL
|
| 1302 |
+
# record set — prompts.pt/mapping.json must stay complete
|
| 1303 |
+
# regardless of --start_index/--end_index, since the eval
|
| 1304 |
+
# stage later scores against the whole dataset once all
|
| 1305 |
+
# parallel generation jobs have finished their chunks.
|
| 1306 |
+
records = build_prompts_and_mapping(
|
| 1307 |
+
dataset_dir, gen_dir, args.num_imgs, args.name_split,
|
| 1308 |
+
artist_artwork_mapping_path=mapping_path,
|
| 1309 |
+
min_artist_count=args.min_artist_count,
|
| 1310 |
+
max_artist_tokens=args.max_artist_tokens,
|
| 1311 |
+
)
|
| 1312 |
+
save_prompts_pt(records, cd / "prompts.pt")
|
| 1313 |
+
save_mapping_json(records, cd / "mapping.json")
|
| 1314 |
+
else:
|
| 1315 |
+
# 'prep' excluded: this is a "consumer" run (e.g. a parallel
|
| 1316 |
+
# --start_index/--end_index chunk job) -- reuse whatever the
|
| 1317 |
+
# producer run already saved. Never rebuilds, never rewrites,
|
| 1318 |
+
# so no race with sibling jobs running at the same time.
|
| 1319 |
+
artist_artwork_map = (
|
| 1320 |
+
load_artist_artwork_mapping(mapping_path) if mapping_path.is_file() else None
|
| 1321 |
+
)
|
| 1322 |
+
records = load_existing_records(
|
| 1323 |
+
cd / "prompts.pt", cd / "mapping.json", args.name_split,
|
| 1324 |
+
artist_artwork_mapping=artist_artwork_map,
|
| 1325 |
+
)
|
| 1326 |
+
except (SystemExit, FileNotFoundError, ValueError) as e:
|
| 1327 |
+
msg = f"prep FAILED for dataset={dataset_dir.name}: {e}"
|
| 1328 |
+
print(f"[ERROR] {msg}")
|
| 1329 |
+
failures.append(msg)
|
| 1330 |
+
continue
|
| 1331 |
+
|
| 1332 |
+
if "infer" in args.stages and wrapper is not None and records is not None:
|
| 1333 |
+
start = min(args.start_index, len(records))
|
| 1334 |
+
end = len(records) if args.end_index is None else min(args.end_index, len(records))
|
| 1335 |
+
chunk = records[start:end]
|
| 1336 |
+
print(f"[i] Generation slice: records[{start}:{end}] of {len(records)} total "
|
| 1337 |
+
f"({len(chunk)} record(s) in this run)")
|
| 1338 |
+
if not chunk:
|
| 1339 |
+
print(f"[WARN] Empty slice for dataset={dataset_dir.name} "
|
| 1340 |
+
f"(start_index={args.start_index} >= {len(records)} total records) — nothing to generate.")
|
| 1341 |
+
else:
|
| 1342 |
+
try:
|
| 1343 |
+
generate_images(
|
| 1344 |
+
chunk, wrapper, gen_dir,
|
| 1345 |
+
images_per_prompt=args.num_imgs,
|
| 1346 |
+
num_inference_steps=args.num_inference_steps,
|
| 1347 |
+
guidance_scale=args.guidance_scale,
|
| 1348 |
+
seed_base=(args.seed_base if args.seed_base >= 0 else None),
|
| 1349 |
+
device=device,
|
| 1350 |
+
skip_existing=args.skip_existing,
|
| 1351 |
+
)
|
| 1352 |
+
except Exception as e:
|
| 1353 |
+
msg = f"infer FAILED for dataset={dataset_dir.name} model={model_name}: {e}"
|
| 1354 |
+
print(f"[ERROR] {msg}")
|
| 1355 |
+
failures.append(msg)
|
| 1356 |
+
|
| 1357 |
+
if wrapper is not None:
|
| 1358 |
+
unload_model(wrapper)
|
| 1359 |
+
|
| 1360 |
+
# ---------------- Phase 2: evaluation (metric-outer loop) -----------------
|
| 1361 |
+
if "eval" in args.stages:
|
| 1362 |
+
for metric in args.metrics:
|
| 1363 |
+
print(f"\n{'='*80}\n[Loading metric] {metric}\n{'='*80}")
|
| 1364 |
+
try:
|
| 1365 |
+
if metric == "clip":
|
| 1366 |
+
handlers = build_clip_handlers(device, use_amp)
|
| 1367 |
+
elif metric == "lpips":
|
| 1368 |
+
handlers = build_lpips_handlers(device)
|
| 1369 |
+
elif metric == "csd":
|
| 1370 |
+
handlers = build_csd_handlers(
|
| 1371 |
+
device, use_amp,
|
| 1372 |
+
csd_repo_dir=Path(args.csd_repo_dir),
|
| 1373 |
+
model_path=Path(args.csd_model_path),
|
| 1374 |
+
use_cosine_similarity=args.use_cosine_similarity_csd,
|
| 1375 |
+
)
|
| 1376 |
+
else:
|
| 1377 |
+
raise ValueError(metric)
|
| 1378 |
+
except Exception as e:
|
| 1379 |
+
msg = f"Failed to load metric '{metric}': {e}"
|
| 1380 |
+
print(f"[ERROR] {msg}")
|
| 1381 |
+
failures.append(msg)
|
| 1382 |
+
continue
|
| 1383 |
+
|
| 1384 |
+
for model_name in args.models:
|
| 1385 |
+
for dataset_dir in dataset_dirs:
|
| 1386 |
+
cd = combo_dir(dataset_dir, model_name)
|
| 1387 |
+
mapping_json = cd / "mapping.json"
|
| 1388 |
+
if not mapping_json.exists():
|
| 1389 |
+
msg = f"eval SKIPPED (no mapping.json) for dataset={dataset_dir.name} model={model_name}"
|
| 1390 |
+
print(f"[WARN] {msg}")
|
| 1391 |
+
failures.append(msg)
|
| 1392 |
+
continue
|
| 1393 |
+
|
| 1394 |
+
eval_dir = cd / "eval" / metric
|
| 1395 |
+
scores_csv = eval_dir / f"{metric}_scores.csv"
|
| 1396 |
+
if args.skip_existing and scores_csv.exists():
|
| 1397 |
+
print(f"[skip] {scores_csv} already exists")
|
| 1398 |
+
continue
|
| 1399 |
+
|
| 1400 |
+
print(f"\n--- eval dataset={dataset_dir.name} | model={model_name} | metric={metric} ---")
|
| 1401 |
+
with open(mapping_json, "r", encoding="utf-8") as f:
|
| 1402 |
+
mapping = json.load(f)
|
| 1403 |
+
mapping = {
|
| 1404 |
+
o: (g if isinstance(g, list) else [g])
|
| 1405 |
+
for o, g in mapping.items()
|
| 1406 |
+
if is_nonempty_str(o) and has_valid_image_extension(o)
|
| 1407 |
+
}
|
| 1408 |
+
|
| 1409 |
+
try:
|
| 1410 |
+
score_mapping(mapping, handlers, scores_csv, eval_dir / "candidates", args.top_n)
|
| 1411 |
+
except Exception as e:
|
| 1412 |
+
msg = f"eval FAILED for dataset={dataset_dir.name} model={model_name} metric={metric}: {e}"
|
| 1413 |
+
print(f"[ERROR] {msg}")
|
| 1414 |
+
failures.append(msg)
|
| 1415 |
+
|
| 1416 |
+
unload_metric(handlers)
|
| 1417 |
+
|
| 1418 |
+
elapsed = time.time() - t_start
|
| 1419 |
+
print(f"\n{'='*80}\n[Done] Pipeline finished in {elapsed:.1f}s")
|
| 1420 |
+
if failures:
|
| 1421 |
+
print(f"[!] {len(failures)} issue(s):")
|
| 1422 |
+
for f in failures:
|
| 1423 |
+
print(f" - {f}")
|
| 1424 |
+
sys.exit(1)
|
| 1425 |
+
print("[OK] All stages completed successfully.")
|
| 1426 |
+
|
| 1427 |
+
|
| 1428 |
+
if __name__ == "__main__":
|
| 1429 |
+
main()
|