"""Generate 'Spot the Contour Diff' visual benchmark dataset. Two panels are shown side by side. Each panel contains the same set of closed contours (Fourier-descriptor blobs) at the same positions, with each contour pair tagged by an uppercase letter label that appears at the same position in both panels. Some contours in the right panel have a different shape from the corresponding contour in the left panel. The task is to list the letter labels of contour pairs whose shape differs between the two panels. Blob generation is reused from the sibling ``contour_silhouette_count`` task. """ from __future__ import annotations import argparse import json import math import random import sys from pathlib import Path from typing import Any, Dict, List, Tuple import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np from tqdm import tqdm # Reuse blob generation and stroke helpers from contour_silhouette_count. _SIBLING = Path(__file__).resolve().parent.parent / "contour_silhouette_count" sys.path.insert(0, str(_SIBLING)) from creation import ( # type: ignore # noqa: E402 STROKE_WIDTH, _draw_blob_outline, blob_bounding_radius, blob_hausdorff, fourier_blob, ) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- NUM_ITEMS = 15 MIN_DIFFS = 4 MAX_DIFFS = 7 PANEL_W = 900 PANEL_H = 900 PADDING = 18 # visible gap between blob outlines EDGE_PADDING = 18 # gap between blob bounding circle and panel edge HAUSDORFF_THRESH = 5.0 # changed blob must differ from original by at least this HAUSDORFF_MAX = 20.0 # …but not by more than this (keep diffs subtle) BG_COLOR = "#0a1020" BORDER_COLOR = "#7aa6ff" BORDER_WIDTH = 2.0 HIGHLIGHT_COLOR = "#dc1e1e" LABEL_BADGE_COLOR = "#f5d76e" LABEL_TEXT_COLOR = "#1a1a1a" LABEL_BADGE_PAD = 8.0 # gap between bounding circle and badge centre offset MARGIN_PX = 60 GAP_PX = 100 LABEL_HEIGHT = 44 QUESTION = ( "Two panels are shown side by side. Each panel contains the same set of " "closed contours at the same positions. Some contours in the right " "panel have a different shape from the corresponding contour in the " "left panel. Count the number of contour pairs whose shape differs " "between the two panels and report the integer count. " "Provide your final answer enclosed in ... tags." ) def _index_to_label(i: int) -> str: """Map 0->A, 1->B, ..., 25->Z, 26->AA, 27->AB, ...""" letters = [] n = i while True: letters.append(chr(ord("A") + (n % 26))) n = n // 26 - 1 if n < 0: break return "".join(reversed(letters)) # --------------------------------------------------------------------------- # Blob generation / swapping # --------------------------------------------------------------------------- def _generate_blob(rng: random.Random) -> np.ndarray: r0 = rng.uniform(38.0, 52.0) return fourier_blob(rng, r0=r0, K_range=(4, 6), amp_scale=0.22) def _polygon_area(poly: np.ndarray) -> float: x = poly[:, 0] y = poly[:, 1] return 0.5 * abs(float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1)))) # Minimum fractional difference in enclosed area between the original and the # swapped contour. Together with HAUSDORFF_THRESH this guarantees that the # swap differs both in OUTLINE shape and in ENCLOSED REGION. MIN_AREA_RATIO_DIFF = 0.18 def _sample_different_blob( rng: random.Random, old: np.ndarray, old_radius: float, max_tries: int = 800, ) -> np.ndarray: """Sample a new blob with Hausdorff distance >= HAUSDORFF_THRESH from ``old``, area differing by at least MIN_AREA_RATIO_DIFF, and bounding radius no larger than ``old_radius``.""" old_area = _polygon_area(old) for _ in range(max_tries): cand = _generate_blob(rng) if blob_bounding_radius(cand) > old_radius: continue d = blob_hausdorff(cand, old) if not (HAUSDORFF_THRESH <= d <= HAUSDORFF_MAX): continue cand_area = _polygon_area(cand) if old_area > 0 and abs(cand_area - old_area) / old_area < MIN_AREA_RATIO_DIFF: continue return cand raise RuntimeError("Could not sample a sufficiently different blob.") # --------------------------------------------------------------------------- # Layout # --------------------------------------------------------------------------- def _place_items( rng: random.Random, radii: List[float], max_tries_per_item: int = 5000, ) -> List[Tuple[float, float]]: order = sorted(range(len(radii)), key=lambda i: -radii[i]) centers: List[Tuple[float, float] | None] = [None] * len(radii) for i in order: r = radii[i] placed = False for _ in range(max_tries_per_item): x = rng.uniform(r + EDGE_PADDING, PANEL_W - r - EDGE_PADDING) y = rng.uniform(r + EDGE_PADDING, PANEL_H - r - EDGE_PADDING) ok = True for j, c in enumerate(centers): if c is None or j == i: continue min_dist = radii[i] + radii[j] + PADDING dx = x - c[0] dy = y - c[1] if dx * dx + dy * dy < min_dist * min_dist: ok = False break if ok: centers[i] = (x, y) placed = True break if not placed: raise RuntimeError(f"Could not place blob {i} (r={r:.1f}) without overlap.") return [c for c in centers] # type: ignore[return-value] # --------------------------------------------------------------------------- # Sample construction # --------------------------------------------------------------------------- def build_sample( rng: random.Random, num_items: int, num_diffs: int, ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: left_blobs = [_generate_blob(rng) for _ in range(num_items)] radii = [blob_bounding_radius(b) for b in left_blobs] right_blobs: List[np.ndarray] = [b.copy() for b in left_blobs] changed_idx = rng.sample(range(num_items), num_diffs) for i in changed_idx: right_blobs[i] = _sample_different_blob(rng, left_blobs[i], radii[i]) centers = _place_items(rng, radii) changed_set = set(changed_idx) items: List[Dict[str, Any]] = [] for i in range(num_items): x, y = centers[i] items.append({ "index": i, "label": _index_to_label(i), "x": x, "y": y, "bounding_radius": radii[i], "left_pts": left_blobs[i], "right_pts": right_blobs[i], "changed": i in changed_set, }) diffs: List[Dict[str, Any]] = [ { "index": i, "label": items[i]["label"], "x": items[i]["x"], "y": items[i]["y"], "bounding_radius": items[i]["bounding_radius"], } for i in sorted(changed_idx) ] return items, diffs # --------------------------------------------------------------------------- # Rendering # --------------------------------------------------------------------------- def _panel_origins() -> Tuple[Tuple[float, float], Tuple[float, float]]: oy = MARGIN_PX + LABEL_HEIGHT ox_left = MARGIN_PX ox_right = MARGIN_PX + PANEL_W + GAP_PX return (ox_left, oy), (ox_right, oy) def _canvas_size() -> Tuple[int, int]: w = MARGIN_PX + PANEL_W + GAP_PX + PANEL_W + MARGIN_PX h = MARGIN_PX + LABEL_HEIGHT + PANEL_H + MARGIN_PX return w, h def _badge_offset( x: float, y: float, radius: float, badge_r: float, ) -> Tuple[float, float]: """Legacy compass-based fallback (unused — kept for backward compatibility).""" margin = radius + badge_r + LABEL_BADGE_PAD candidates = [ (1.0, -1.0), (1.0, 1.0), (-1.0, -1.0), (-1.0, 1.0), (1.0, 0.0), (0.0, -1.0), (-1.0, 0.0), (0.0, 1.0), ] inset = badge_r + 2.0 for sx, sy in candidates: norm = math.hypot(sx, sy) or 1.0 dx = sx / norm * margin dy = sy / norm * margin bx = x + dx by = y + dy if (inset <= bx <= PANEL_W - inset and inset <= by <= PANEL_H - inset): return dx, dy return margin / math.sqrt(2), -margin / math.sqrt(2) def _plan_label_positions( items: List[Dict[str, Any]], other_clearance: float = 14.0, label_clearance: float = 24.0, n_angles: int = 16, radial_steps: Tuple[float, ...] = (0.0, 6.0, 14.0, 24.0), ) -> List[Tuple[float, float]]: """Choose label-badge centres (in LEFT-panel local coords) using a multi-candidate, best-score search. Returns one (px, py) per item. Identical coordinates are reused for the right panel (just translated by that panel's origin) since both panels have the same width/height and contour positions. """ n = len(items) # Pre-compute badge radii and translated point sets (panel-local). badge_rs: List[float] = [] other_pts_list: List[np.ndarray] = [] for it in items: label = it["label"] badge_rs.append(22.0 + 6.0 * (len(label) - 1)) # Translate the LEFT contour's points into panel-local coords. other_pts_list.append(it["left_pts"] + np.array([it["x"], it["y"]])) placements: List[Tuple[float, float]] = [] placed_centres: List[Tuple[float, float]] = [] for i, it in enumerate(items): x, y = it["x"], it["y"] radius = it["bounding_radius"] badge_r = badge_rs[i] inset = badge_r + 2.0 base_margin = radius + badge_r + LABEL_BADGE_PAD # Other contours' points (everything except self). if n > 1: other_pts = np.concatenate( [other_pts_list[j] for j in range(n) if j != i], axis=0 ) else: other_pts = np.zeros((0, 2)) def evaluate(oc: float, lc: float): best = None best_score = -1e18 for a_idx in range(n_angles): ang = 2.0 * math.pi * a_idx / n_angles cos_a = math.cos(ang) sin_a = math.sin(ang) for off in radial_steps: margin = base_margin + off px = x + cos_a * margin py = y + sin_a * margin # Panel-bounds gate. if not (inset <= px <= PANEL_W - inset and inset <= py <= PANEL_H - inset): continue # Other-contour clearance. if other_pts.shape[0] > 0: dx = other_pts[:, 0] - px dy = other_pts[:, 1] - py other_d = float(np.sqrt(np.min(dx * dx + dy * dy))) else: other_d = 1e6 if other_d < oc: continue # Label-clearance gate. if placed_centres: label_d = min( math.hypot(px - lx, py - ly) for lx, ly in placed_centres ) else: label_d = 1e6 if label_d < lc: continue score = other_d + 0.5 * label_d - 0.4 * off if score > best_score: best_score = score best = (px, py) return best chosen = evaluate(other_clearance, label_clearance) # Soft fallback: progressively relax other_clearance. relax = other_clearance while chosen is None and relax > 1.0: relax *= 0.6 chosen = evaluate(relax, max(4.0, label_clearance * 0.6)) if chosen is None: # Last-resort: legacy compass. dx, dy = _badge_offset(x, y, radius, badge_r) chosen = (x + dx, y + dy) placements.append(chosen) placed_centres.append(chosen) return placements def _draw_panel( ax: plt.Axes, items: List[Dict[str, Any]], side: str, ox: float, oy: float, label_positions: List[Tuple[float, float]], ) -> None: key = "left_pts" if side == "left" else "right_pts" for it in items: translated = it[key] + np.array([ox + it["x"], oy + it["y"]]) _draw_blob_outline(ax, translated, STROKE_WIDTH, color="white", zorder=3) # Letter-label badges removed: the task is now a count, not a label-list, # so explicit per-contour anchors are no longer needed (and would let a # model match in text space rather than visually). def _render( out_path: Path, items: List[Dict[str, Any]], diffs: List[Dict[str, Any]] | None = None, ) -> None: w, h = _canvas_size() dpi = 100 fig, ax = plt.subplots(1, 1, figsize=(w / dpi, h / dpi), dpi=dpi) ax.set_xlim(0, w) ax.set_ylim(h, 0) ax.set_aspect("equal") ax.axis("off") fig.patch.set_facecolor(BG_COLOR) ax.set_facecolor(BG_COLOR) (ox_left, oy), (ox_right, _) = _panel_origins() for ox in (ox_left, ox_right): border = mpatches.Rectangle( (ox, oy), PANEL_W, PANEL_H, facecolor="none", edgecolor=BORDER_COLOR, linewidth=BORDER_WIDTH, zorder=1, ) ax.add_patch(border) label_positions = _plan_label_positions(items) _draw_panel(ax, items, "left", ox_left, oy, label_positions) _draw_panel(ax, items, "right", ox_right, oy, label_positions) ax.text( ox_left + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5, "Left", ha="center", va="center", fontsize=16, fontweight="bold", color="#cfe0ff", ) ax.text( ox_right + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5, "Right", ha="center", va="center", fontsize=16, fontweight="bold", color="#cfe0ff", ) if diffs: for diff in diffs: hl_r = diff["bounding_radius"] + 12 for ox in (ox_left, ox_right): cx = ox + diff["x"] cy = oy + diff["y"] ring = mpatches.Circle( (cx, cy), hl_r, facecolor="none", edgecolor=HIGHLIGHT_COLOR, linewidth=2.5, zorder=10, ) ax.add_patch(ring) fig.savefig(out_path, facecolor=BG_COLOR) plt.close(fig) def render_pair(out_path: Path, items: List[Dict[str, Any]]) -> None: _render(out_path, items) def render_answer( out_path: Path, items: List[Dict[str, Any]], diffs: List[Dict[str, Any]], ) -> None: _render(out_path, items, diffs) # --------------------------------------------------------------------------- # Annotation # --------------------------------------------------------------------------- def _answer_string(diffs: List[Dict[str, Any]]) -> str: return str(len(diffs)) def build_annotation( image_name: str, items: List[Dict[str, Any]], diffs: List[Dict[str, Any]], ) -> Dict[str, Any]: return { "image": image_name, "num_items": len(items), "num_differences": len(diffs), "differences": [ { "index": d["index"], "label": d["label"], "x": d["x"], "y": d["y"], "bounding_radius": d["bounding_radius"], } for d in diffs ], "question": QUESTION, "answer": _answer_string(diffs), } # --------------------------------------------------------------------------- # Dataset generation # --------------------------------------------------------------------------- def generate_dataset( rng: random.Random, count: int, output_dir: Path, num_items: int = NUM_ITEMS, min_diffs: int = MIN_DIFFS, max_diffs: int = MAX_DIFFS, ) -> None: images_dir = output_dir / "images" answers_dir = output_dir / "answers" images_dir.mkdir(parents=True, exist_ok=True) answers_dir.mkdir(parents=True, exist_ok=True) annotations: List[Dict[str, Any]] = [] data_items: List[Dict[str, Any]] = [] # Force evenly-spaced num_diffs across [min_diffs, max_diffs]. if count > 1: forced = [int(round(min_diffs + i * (max_diffs - min_diffs) / (count - 1))) for i in range(count)] else: forced = [min_diffs] print(f"forced contour diff counts: {forced}") for idx in tqdm(range(count), desc="Generating contour diff pairs"): num_diffs = forced[idx] for attempt in range(200): try: items, diffs = build_sample(rng, num_items, num_diffs) break except RuntimeError: continue else: raise RuntimeError(f"Failed to build sample {idx} after many retries") image_name = f"contour_diff_{idx:05d}.png" img_path = images_dir / image_name ans_path = answers_dir / image_name render_pair(img_path, items) render_answer(ans_path, items, diffs) rel_image = f"images/{image_name}" annotations.append(build_annotation(rel_image, items, diffs)) data_items.append({ "image": rel_image, "question": QUESTION, "answer": _answer_string(diffs), }) with (output_dir / "annotations.jsonl").open("w", encoding="utf-8") as fh: for rec in annotations: fh.write(json.dumps(rec) + "\n") data_json = { "task": "spot_the_contour_diff", "category": "visual_attribute_transfer", "count": len(data_items), "items": data_items, } with (output_dir / "data.json").open("w", encoding="utf-8") as fh: json.dump(data_json, fh, indent=2) fh.write("\n") # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser( description="Generate 'Spot the Contour Diff' visual benchmark dataset." ) p.add_argument("--output-root", type=Path, default=".") p.add_argument("--count", type=int, default=20) p.add_argument("--seed", type=int, default=42) p.add_argument("--difficulty", type=int, default=5, help="Integer difficulty >=0; scales diff count and subtlety.") return p.parse_args() def main() -> None: args = parse_args() rng = random.Random(args.seed) d = max(0, int(args.difficulty)) N_d = 10 + 2 * d N_0 = 10 s = math.sqrt(max(1.0, N_d / N_0)) global PANEL_W, PANEL_H PANEL_W = int(round(PANEL_W * s)) PANEL_H = int(round(PANEL_H * s)) global HAUSDORFF_THRESH, HAUSDORFF_MAX HAUSDORFF_THRESH = max(18.0, 22.0 - 0.4 * d) HAUSDORFF_MAX = max(HAUSDORFF_THRESH + 12.0, 50.0 - 1.0 * d) total_contours = 10 + 2 * d min_diffs = 5 max_diffs = 5 + 2 * d generate_dataset(rng, args.count, args.output_root, num_items=total_contours, min_diffs=min_diffs, max_diffs=max_diffs) print(f"Saved {args.count} image pairs to {args.output_root}") if __name__ == "__main__": main()