#!/usr/bin/env python3 """ Tile story screenshots into labelled contact sheets for quick visual review. python3 scripts/contact-sheet.py /tmp/tansy-story-check/light [--prefix forms-] [--per 12] Each screenshot is trimmed to its content (plus a margin) before tiling, so a small component isn't lost in an empty 1100x760 frame. """ from __future__ import annotations import argparse import sys from pathlib import Path from PIL import Image, ImageChops, ImageDraw def trim(img: Image.Image, margin: int = 16) -> Image.Image: rgb = img.convert("RGB") bg = Image.new("RGB", rgb.size, rgb.getpixel((2, 2))) box = ImageChops.difference(rgb, bg).getbbox() if not box: return rgb.crop((0, 0, 400, 120)) l, t, r, b = box return rgb.crop((max(l - margin, 0), max(t - margin, 0), min(r + margin, rgb.width), min(b + margin, rgb.height))) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("dir") ap.add_argument("--prefix", default="") ap.add_argument("--per", type=int, default=12) ap.add_argument("--cols", type=int, default=3) ap.add_argument("--cell", type=int, default=560, help="cell width in px") args = ap.parse_args() src = Path(args.dir) shots = sorted(p for p in src.glob("*.png") if p.name.startswith(args.prefix) and not p.name.startswith("sheet-")) if not shots: sys.exit("no screenshots matched") out = [] for n in range(0, len(shots), args.per): batch = shots[n : n + args.per] cells = [] for p in batch: img = trim(Image.open(p)) scale = min(1.0, (args.cell - 16) / img.width) img = img.resize((int(img.width * scale), int(img.height * scale))) cells.append((p.stem, img)) rows = [cells[i : i + args.cols] for i in range(0, len(cells), args.cols)] heights = [max(c[1].height for c in row) + 34 for row in rows] sheet = Image.new("RGB", (args.cell * args.cols, sum(heights)), "#8a8f99") draw = ImageDraw.Draw(sheet) y = 0 for row, h in zip(rows, heights): for i, (name, img) in enumerate(row): x = i * args.cell draw.rectangle([x + 2, y + 2, x + args.cell - 2, y + h - 2], fill="#ffffff") draw.text((x + 10, y + 8), name, fill="#b00020") sheet.paste(img, (x + 8, y + 26)) y += h path = src / f"sheet-{args.prefix or 'all'}-{n // args.per + 1:02d}.png" sheet.save(path) out.append(str(path)) print("\n".join(out)) if __name__ == "__main__": main()