from __future__ import annotations import gc import json import math import shutil import sys from pathlib import Path from typing import Any, Callable import numpy as np import torch import torch.nn.functional as F from PIL import Image import analysis_core DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") def atomic_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8") temporary.replace(path) def cache_metric(cache_dir: Path, name: str, run_ids: list[str], calculate: Callable[[str], Any]) -> dict[str, Any]: path = cache_dir / f"{name}.json" cache = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {} for index, run_id in enumerate(run_ids, start=1): if run_id not in cache: print(f" {name}: {index}/{len(run_ids)} {run_id}", flush=True) cache[run_id] = calculate(run_id) atomic_json(path, cache) return cache def image_tensor(results_dir: Path, run_id: str) -> torch.Tensor: array = np.load(results_dir / "captures" / run_id / "decoded_float32.npy", allow_pickle=False).astype(np.float32) return torch.from_numpy(array).permute(0, 3, 1, 2).to(DEVICE) def pil_image(results_dir: Path, run_id: str) -> Image.Image: return Image.open(results_dir / "captures" / run_id / "image.png").convert("RGB") def clear_model(model) -> None: del model gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() def paired_perceptual(config: dict[str, Any], results_dir: Path, run_ids: list[str], cache_dir: Path) -> dict[str, dict[str, float]]: import lpips import DISTS_pytorch from DISTS_pytorch import DISTS from pytorch_msssim import ms_ssim references = {run_id: run_id.rsplit("__", 1)[0] + "__bf16" for run_id in run_ids} output: dict[str, dict[str, float]] = {run_id: {} for run_id in run_ids} for network in ("alex", "vgg"): model = lpips.LPIPS(net=network).to(DEVICE).eval() def calculate(run_id: str): if run_id.endswith("__bf16"): return 0.0 reference = image_tensor(results_dir, references[run_id]) * 2.0 - 1.0 candidate = image_tensor(results_dir, run_id) * 2.0 - 1.0 with torch.inference_mode(): return float(model(reference, candidate).item()) values = cache_metric(cache_dir, f"lpips_{network}", run_ids, calculate) for run_id in run_ids: output[run_id][f"lpips_{network}"] = float(values[run_id]) clear_model(model) model = DISTS(load_weights=False) dists_weights = torch.load(Path(DISTS_pytorch.__file__).resolve().parent / "weights.pt", map_location="cpu", weights_only=True) model.alpha.data.copy_(dists_weights["alpha"]) model.beta.data.copy_(dists_weights["beta"]) model = model.to(DEVICE).eval() def calculate_dists(run_id: str): if run_id.endswith("__bf16"): return 0.0 with torch.inference_mode(): return float(model(image_tensor(results_dir, references[run_id]), image_tensor(results_dir, run_id)).item()) values = cache_metric(cache_dir, "dists", run_ids, calculate_dists) for run_id in run_ids: output[run_id]["dists"] = float(values[run_id]) clear_model(model) def calculate_msssim(run_id: str): if run_id.endswith("__bf16"): return 1.0 with torch.inference_mode(): return float(ms_ssim(image_tensor(results_dir, references[run_id]), image_tensor(results_dir, run_id), data_range=1.0).item()) values = cache_metric(cache_dir, "ms_ssim", run_ids, calculate_msssim) for run_id in run_ids: output[run_id]["ms_ssim"] = float(values[run_id]) return output def dino_embeddings(results_dir: Path, run_ids: list[str], cache_dir: Path) -> dict[str, list[float]]: from transformers import AutoImageProcessor, AutoModel processor = AutoImageProcessor.from_pretrained("facebook/dinov2-large") model = AutoModel.from_pretrained("facebook/dinov2-large").to(DEVICE).eval() def calculate(run_id: str): inputs = processor(images=pil_image(results_dir, run_id), return_tensors="pt") inputs = {key: value.to(DEVICE) for key, value in inputs.items()} with torch.inference_mode(): embedding = model(**inputs).last_hidden_state[:, 0] embedding = F.normalize(embedding.float(), dim=-1) return embedding[0].cpu().tolist() values = cache_metric(cache_dir, "dinov2_large_embeddings", run_ids, calculate) clear_model(model) return values def openclip_metrics(config: dict[str, Any], results_dir: Path, run_ids: list[str], prompt_by_run: dict[str, str], cache_dir: Path) -> tuple[dict[str, list[float]], dict[str, float]]: import open_clip model, _, preprocess = open_clip.create_model_and_transforms("ViT-H-14", pretrained="laion2b_s32b_b79k", device=DEVICE) tokenizer = open_clip.get_tokenizer("ViT-H-14") model.eval() def calculate_image(run_id: str): image = preprocess(pil_image(results_dir, run_id)).unsqueeze(0).to(DEVICE) with torch.inference_mode(): embedding = F.normalize(model.encode_image(image).float(), dim=-1) return embedding[0].cpu().tolist() image_values = cache_metric(cache_dir, "openclip_vith14_image_embeddings", run_ids, calculate_image) def calculate_score(run_id: str): image_embedding = torch.tensor(image_values[run_id], device=DEVICE).unsqueeze(0) text = tokenizer([prompt_by_run[run_id]]).to(DEVICE) with torch.inference_mode(): text_embedding = F.normalize(model.encode_text(text).float(), dim=-1) return float((100.0 * image_embedding @ text_embedding.T).item()) scores = cache_metric(cache_dir, "openclip_vith14_prompt_score", run_ids, calculate_score) clear_model(model) return image_values, scores def pickscore(config: dict[str, Any], results_dir: Path, run_ids: list[str], prompt_by_run: dict[str, str], cache_dir: Path) -> dict[str, float]: from transformers import AutoModel, AutoProcessor processor = AutoProcessor.from_pretrained("yuvalkirstain/PickScore_v1") model = AutoModel.from_pretrained("yuvalkirstain/PickScore_v1").to(DEVICE).eval() def calculate(run_id: str): image_inputs = processor(images=[pil_image(results_dir, run_id)], padding=True, truncation=True, max_length=77, return_tensors="pt").to(DEVICE) text_inputs = processor(text=[prompt_by_run[run_id]], padding=True, truncation=True, max_length=77, return_tensors="pt").to(DEVICE) with torch.inference_mode(): image_output = model.get_image_features(**image_inputs) text_output = model.get_text_features(**text_inputs) if hasattr(image_output, "pooler_output"): image_output = image_output.pooler_output if hasattr(text_output, "pooler_output"): text_output = text_output.pooler_output image_features = F.normalize(image_output.float(), dim=-1) text_features = F.normalize(text_output.float(), dim=-1) score = model.logit_scale.exp() * (text_features @ image_features.T) return float(score.item()) values = cache_metric(cache_dir, "pickscore_v1", run_ids, calculate) clear_model(model) return {key: float(value) for key, value in values.items()} def no_reference_iqa(results_dir: Path, run_ids: list[str], cache_dir: Path) -> dict[str, dict[str, float]]: import pyiqa output = {run_id: {} for run_id in run_ids} for name in ("musiq", "maniqa", "topiq_nr", "niqe", "brisque"): model = pyiqa.create_metric(name, device=DEVICE) def calculate(run_id: str): with torch.inference_mode(): return float(model(image_tensor(results_dir, run_id)).item()) values = cache_metric(cache_dir, f"pyiqa_{name}", run_ids, calculate) for run_id in run_ids: output[run_id][name] = float(values[run_id]) clear_model(model) return output def levenshtein(a: str, b: str) -> int: previous = list(range(len(b) + 1)) for index_a, char_a in enumerate(a, start=1): current = [index_a] for index_b, char_b in enumerate(b, start=1): current.append(min(current[-1] + 1, previous[index_b] + 1, previous[index_b - 1] + (char_a != char_b))) previous = current return previous[-1] def ocr_metrics(config: dict[str, Any], results_dir: Path, run_ids: list[str], prompt_by_id: dict[str, dict], cache_dir: Path) -> dict[str, dict[str, Any]]: from rapidocr_onnxruntime import RapidOCR engine = RapidOCR() output = {} target_runs = [run_id for run_id in run_ids if prompt_by_id[run_id.split("__r", 1)[0]].get("expected_text")] def calculate(run_id: str): result, _ = engine(str(results_dir / "captures" / run_id / "image.png")) lines = [] if result is None else [str(item[1]).upper().strip() for item in result] confidences = [] if result is None else [float(item[2]) for item in result] combined = " | ".join(lines) expected = prompt_by_id[run_id.split("__r", 1)[0]]["expected_text"] distances = [] exact = [] for phrase in expected: phrase = phrase.upper() candidates = lines + [combined] distance = min((levenshtein(phrase, value) / max(len(phrase), len(value), 1) for value in candidates), default=1.0) distances.append(distance) exact.append(phrase in combined) return { "recognized_text": combined, "recognized_line_count": len(lines), "mean_confidence": float(np.mean(confidences)) if confidences else 0.0, "expected_phrase_exact_fraction": float(np.mean(exact)), "expected_phrase_normalized_edit_distance": float(np.mean(distances)), } values = cache_metric(cache_dir, "rapidocr", target_runs, calculate) for run_id in run_ids: output[run_id] = values.get( run_id, { "recognized_text": "", "recognized_line_count": 0, "mean_confidence": float("nan"), "expected_phrase_exact_fraction": float("nan"), "expected_phrase_normalized_edit_distance": float("nan"), }, ) return output def hps_scores(results_dir: Path, run_ids: list[str], prompt_by_run: dict[str, str], cache_dir: Path) -> dict[str, float]: import types if "turtle" not in sys.modules: # hpsv2 imports an unused turtle.forward symbol; Windows embedded Python # does not ship Tk/turtle, so provide only that inert import target. turtle_stub = types.ModuleType("turtle") turtle_stub.forward = None sys.modules["turtle"] = turtle_stub import hpsv2 hps_bpe = Path(hpsv2.__file__).resolve().parent / "src" / "open_clip" / "bpe_simple_vocab_16e6.txt.gz" if not hps_bpe.is_file(): source_bpe = Path(__file__).resolve().parent / ".vendor" / "open_clip" / "bpe_simple_vocab_16e6.txt.gz" if not source_bpe.is_file(): raise FileNotFoundError("Neither hpsv2 nor open_clip contains the required BPE vocabulary") hps_bpe.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source_bpe, hps_bpe) def calculate(run_id: str): path = str(results_dir / "captures" / run_id / "image.png") score = hpsv2.score(path, prompt_by_run[run_id], hps_version="v2.1") return float(score[0] if isinstance(score, (list, tuple)) else score) values = cache_metric(cache_dir, "hpsv2_1", run_ids, calculate) return {key: float(value) for key, value in values.items()} def analyze(config: dict[str, Any], results_dir: Path) -> None: if not (results_dir / "metrics" / "analysis_core_complete.json").is_file(): raise RuntimeError("Core analysis must complete before advanced metrics") run_ids = [ f"{prompt['id']}__r{replicate}__{format_id}" for prompt in config["prompts"] for replicate in range(int(config["campaign"]["replicates"])) for format_id in config["formats"] ] prompt_by_id = {prompt["id"]: prompt for prompt in config["prompts"]} prompt_by_run = {run_id: prompt_by_id[run_id.split("__r", 1)[0]]["text"] for run_id in run_ids} cache_dir = results_dir / "advanced_metric_cache" cache_dir.mkdir(parents=True, exist_ok=True) perceptual = paired_perceptual(config, results_dir, run_ids, cache_dir) dino = dino_embeddings(results_dir, run_ids, cache_dir) openclip_images, clip_scores = openclip_metrics(config, results_dir, run_ids, prompt_by_run, cache_dir) pick_scores = pickscore(config, results_dir, run_ids, prompt_by_run, cache_dir) hps = hps_scores(results_dir, run_ids, prompt_by_run, cache_dir) iqa = no_reference_iqa(results_dir, run_ids, cache_dir) ocr = ocr_metrics(config, results_dir, run_ids, prompt_by_id, cache_dir) rows = [] for run_id in run_ids: prompt_id, replicate_token, format_id = run_id.split("__") replicate = int(replicate_token[1:]) reference_id = f"{prompt_id}__r{replicate}__bf16" dino_cosine = float(np.dot(dino[run_id], dino[reference_id])) clip_image_cosine = float(np.dot(openclip_images[run_id], openclip_images[reference_id])) row = { "run_id": run_id, "format_id": format_id, "prompt_id": prompt_id, "replicate": replicate, **perceptual[run_id], "dinov2_large_image_cosine_to_bf16": dino_cosine, "openclip_vith14_image_cosine_to_bf16": clip_image_cosine, "openclip_vith14_prompt_score": float(clip_scores[run_id]), "pickscore_v1": float(pick_scores[run_id]), "hpsv2_1": float(hps[run_id]), **{f"pyiqa_{key}": value for key, value in iqa[run_id].items()}, **{f"ocr_{key}": value for key, value in ocr[run_id].items()}, } rows.append(row) metrics_dir = results_dir / "metrics" analysis_core.write_csv(metrics_dir / "image_advanced.csv", rows) numeric_rows = [{key: value for key, value in row.items() if key != "ocr_recognized_text"} for row in rows] summary, pairwise = analysis_core.statistical_tables(numeric_rows, config) analysis_core.write_csv(metrics_dir / "image_advanced_summary.csv", summary) analysis_core.write_csv(metrics_dir / "image_advanced_pairwise_statistics.csv", pairwise) atomic_json(metrics_dir / "analysis_advanced_complete.json", {"complete": True, "rows": len(rows)})