from __future__ import annotations import json import math from pathlib import Path import numpy as np from PIL import Image, ImageDraw, ImageFont def font(size: int): candidates = [Path("C:/Windows/Fonts/segoeui.ttf"), Path("C:/Windows/Fonts/arial.ttf")] for candidate in candidates: if candidate.is_file(): return ImageFont.truetype(str(candidate), size=size) return ImageFont.load_default() def capture_image(results_dir: Path, run_id: str) -> Image.Image: return Image.open(results_dir / "captures" / run_id / "image.png").convert("RGB") def labeled_grid(images: list[Image.Image], labels: list[str], title: str, cell_size: int = 384, columns: int = 4) -> Image.Image: header = 64 title_height = 52 rows = math.ceil(len(images) / columns) canvas = Image.new("RGB", (cell_size * columns, title_height + rows * (header + cell_size)), "#111111") draw = ImageDraw.Draw(canvas) draw.text((16, 12), title, fill="white", font=font(24)) label_font = font(20) for index, (image, label) in enumerate(zip(images, labels)): row, column = divmod(index, columns) x = column * cell_size y = title_height + row * (header + cell_size) draw.rectangle((x, y, x + cell_size, y + header), fill="#202020") draw.text((x + 12, y + 18), label, fill="white", font=label_font) canvas.paste(image.resize((cell_size, cell_size), Image.Resampling.LANCZOS), (x, y + header)) return canvas def heatmap(values: np.ndarray, scale: float) -> Image.Image: normalized = np.clip(values / max(scale, 1e-12), 0.0, 1.0) red = np.clip(3.0 * normalized, 0.0, 1.0) green = np.clip(3.0 * normalized - 1.0, 0.0, 1.0) blue = np.clip(4.0 * normalized - 3.0, 0.0, 1.0) rgb = np.stack([red, green, blue], axis=-1) return Image.fromarray(np.round(rgb * 255.0).astype(np.uint8)) def detail_regions(reference: np.ndarray, crop_size: int = 256, count: int = 3) -> list[tuple[int, int, int, int]]: gray = reference[..., 0] * 0.2126 + reference[..., 1] * 0.7152 + reference[..., 2] * 0.0722 gradient = np.hypot(np.diff(gray, axis=1, append=gray[:, -1:]), np.diff(gray, axis=0, append=gray[-1:, :])) stride = crop_size // 2 candidates = [] for top in range(0, max(1, gray.shape[0] - crop_size + 1), stride): for left in range(0, max(1, gray.shape[1] - crop_size + 1), stride): bottom = min(gray.shape[0], top + crop_size) right = min(gray.shape[1], left + crop_size) candidates.append((float(gradient[top:bottom, left:right].mean()), left, top, right, bottom)) selected = [] for _, left, top, right, bottom in sorted(candidates, reverse=True): center = ((left + right) * 0.5, (top + bottom) * 0.5) if all((center[0] - existing[0]) ** 2 + (center[1] - existing[1]) ** 2 >= (crop_size * 0.75) ** 2 for existing in selected): selected.append(center) if len(selected) == count: break return [ ( int(max(0, min(gray.shape[1] - crop_size, cx - crop_size / 2))), int(max(0, min(gray.shape[0] - crop_size, cy - crop_size / 2))), int(max(0, min(gray.shape[1] - crop_size, cx - crop_size / 2))) + crop_size, int(max(0, min(gray.shape[0] - crop_size, cy - crop_size / 2))) + crop_size, ) for cx, cy in selected ] def detail_sheet(images: list[Image.Image], labels: list[str], regions: list[tuple[int, int, int, int]], title: str, cell: int = 320, columns: int = 4) -> Image.Image: title_height = 58 label_height = 42 format_rows = math.ceil(len(images) / columns) region_height = format_rows * (label_height + cell) canvas = Image.new("RGB", (cell * columns, title_height + region_height * len(regions)), "#111111") draw = ImageDraw.Draw(canvas) draw.text((16, 14), title, fill="white", font=font(24)) for region_index, region in enumerate(regions): base_y = title_height + region_index * region_height for index, (image, label) in enumerate(zip(images, labels)): row, column = divmod(index, columns) y = base_y + row * (label_height + cell) draw.text((column * cell + 10, y + 10), label, fill="white", font=font(18)) crop = image.crop(region).resize((cell, cell), Image.Resampling.NEAREST) canvas.paste(crop, (column * cell, y + label_height)) draw.text((8, base_y + label_height + 8), f"detail {region_index + 1}", fill="#ffdf80", font=font(16), stroke_width=2, stroke_fill="#111111") return canvas def generate(config: dict, results_dir: Path) -> None: if not (results_dir / "campaign_complete.json").is_file(): raise RuntimeError("The scored campaign is incomplete") sheets_dir = results_dir / "comparison_sheets" full_dir = sheets_dir / "full" diff_dir = sheets_dir / "differences" detail_dir = sheets_dir / "details" for directory in (full_dir, diff_dir, detail_dir): directory.mkdir(parents=True, exist_ok=True) format_order = list(config["formats"]) labels = [config["formats"][format_id]["label"] for format_id in format_order] index = [] contact_rows = [] for prompt in config["prompts"]: for replicate in range(int(config["campaign"]["replicates"])): run_ids = [f"{prompt['id']}__r{replicate}__{format_id}" for format_id in format_order] images = [capture_image(results_dir, run_id) for run_id in run_ids] title = f"{prompt['id']} · replicate {replicate} · seed {json.loads((results_dir / 'captures' / run_ids[0] / 'metadata.json').read_text(encoding='utf-8'))['output']['seed']}" full_path = full_dir / f"{prompt['id']}__r{replicate}.png" labeled_grid(images, labels, title).save(full_path, format="PNG", compress_level=4) arrays = [np.asarray(image, dtype=np.float32) / 255.0 for image in images] differences = [np.mean(np.abs(array - arrays[0]), axis=-1) for array in arrays[1:]] scale = float(np.quantile(np.concatenate([value.reshape(-1) for value in differences]), 0.99)) difference_images = [images[0]] + [heatmap(value, scale) for value in differences] difference_path = diff_dir / f"{prompt['id']}__r{replicate}.png" labeled_grid(difference_images, ["BF16 reference"] + [f"|{label} − BF16|" for label in labels[1:]], f"{title} · shared heatmap p99 scale={scale:.6f}").save(difference_path, format="PNG", compress_level=4) regions = detail_regions(arrays[0]) detail_path = detail_dir / f"{prompt['id']}__r{replicate}.png" detail_sheet(images, labels, regions, title).save(detail_path, format="PNG", compress_level=4) index.append( { "prompt_id": prompt["id"], "replicate": replicate, "full": str(full_path.relative_to(results_dir)), "differences": str(difference_path.relative_to(results_dir)), "details": str(detail_path.relative_to(results_dir)), "detail_regions": regions, } ) if replicate == 0: contact_rows.append((prompt["id"], images)) thumb = 192 row_header = 180 top = 62 contact_columns = 4 contact_format_rows = math.ceil(len(format_order) / contact_columns) prompt_block_height = thumb * contact_format_rows contact = Image.new("RGB", (row_header + thumb * contact_columns, top + prompt_block_height * len(contact_rows)), "#111111") draw = ImageDraw.Draw(contact) draw.text((12, 14), "Krea 2 Turbo format contact sheet · replicate 0", fill="white", font=font(24)) for row, (prompt_id, images) in enumerate(contact_rows): y = top + row * prompt_block_height draw.text((8, y + prompt_block_height // 2 - 10), prompt_id, fill="white", font=font(16)) for format_index, image in enumerate(images): format_row, column = divmod(format_index, contact_columns) contact.paste(image.resize((thumb, thumb), Image.Resampling.LANCZOS), (row_header + column * thumb, y + format_row * thumb)) draw.text((row_header + column * thumb + 5, y + format_row * thumb + 5), labels[format_index], fill="#ffdf80", font=font(13), stroke_width=2, stroke_fill="#111111") contact.save(sheets_dir / "contact_sheet_replicate0.png", format="PNG", compress_level=4) (sheets_dir / "index.json").write_text(json.dumps(index, indent=2), encoding="utf-8") (sheets_dir / "complete.json").write_text(json.dumps({"complete": True, "groups": len(index)}, indent=2), encoding="utf-8")