"""Generate 'Spot the Stroke Diff' visual benchmark dataset. Two panels are shown side by side. Each panel contains the same set of brush strokes (B-spline curves) at the same positions, but some strokes in the right panel have a different shape from the corresponding stroke in the left panel. Each stroke pair is labelled with an uppercase letter (A, B, C, ...) placed identically in both panels. The task is to list the letters of the strokes that differ. Stroke generation is reused from the sibling ``stroke_gesture_count`` task. """ from __future__ import annotations import argparse import json import math import os 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 stroke generation helpers from stroke_gesture_count. _SIBLING = Path(__file__).resolve().parent.parent / "stroke_gesture_count" sys.path.insert(0, str(_SIBLING)) from creation import ( # type: ignore # noqa: E402 STROKE_WIDTH, _curve_bbox, _hausdorff_distance, _render_curve_on_ax, generate_distractor_stroke, generate_template_stroke, ) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- NUM_ITEMS = 14 MIN_DIFFS = 4 MAX_DIFFS = 7 PANEL_W = 900 PANEL_H = 900 PADDING = 20 EDGE_PADDING = 20 HAUSDORFF_THRESH = 8.0 HAUSDORFF_MAX = 18.0 BG_COLOR = "#0a1020" BORDER_COLOR = "#7aa6ff" BORDER_WIDTH = 2.0 HIGHLIGHT_COLOR = "#dc1e1e" LABEL_COLOR = "#cfe0ff" STROKE_LABEL_COLOR = "#ffd24a" STROKE_LABEL_OFFSET = 14.0 STROKE_LABEL_FONTSIZE = 14 MARGIN_PX = 60 GAP_PX = 100 LABEL_HEIGHT = 44 QUESTION = ( "Two panels are shown side by side. Each panel contains the same number " "of brush strokes at the same positions. Some strokes in the right panel " "have a different shape from the corresponding stroke in the left panel. " "Count the number of stroke pairs whose shape differs between the two " "panels and report the integer count. " "Provide your final answer enclosed in ... tags." ) # --------------------------------------------------------------------------- # Geometry helpers # --------------------------------------------------------------------------- def _curve_radius(curve: np.ndarray) -> float: """Max distance from origin to any point on a centred curve.""" return float(np.max(np.sqrt((curve * curve).sum(axis=1)))) def _index_to_letters(idx: int) -> str: """Convert 0-based index to uppercase spreadsheet-style label. 0 -> A, 25 -> Z, 26 -> AA, 27 -> AB, ... """ n = idx chars: List[str] = [] while True: chars.append(chr(ord("A") + (n % 26))) n = n // 26 - 1 if n < 0: break return "".join(reversed(chars)) def _compute_label_positions( width: int, height: int, centers: List[Tuple[float, float]], curves: List[np.ndarray], ) -> List[Tuple[float, float]]: """For each stroke, generate many candidate label positions and pick the one that (a) hugs its own stroke, (b) maximally clears every other stroke, and (c) doesn't collide with previously-placed labels. Strategy: for ~12 anchor points sampled along each stroke, try both perpendicular normals at offsets {12, 18, 24, 30}; plus the two endpoint-tangent extensions. Filter by hard clearance gates, then score by other-stroke clearance and label-label clearance. All inputs/outputs are in panel-local pixel coordinates (the panel being treated as a (width x height) box). """ own_max = 22.0 other_clearance = 16.0 label_clearance = 22.0 label_half_w = 9.0 label_half_h = 9.0 offsets = [12.0, 18.0, 24.0, 30.0] n_anchors = 12 shifted_all = [crv + np.array(ctr) for crv, ctr in zip(curves, centers)] positions: List[Tuple[float, float]] = [] placed_label_pts: List[np.ndarray] = [] for i, sh in enumerate(shifted_all): L = len(sh) if L < 4: positions.append((float(sh[0, 0]), float(sh[0, 1]))) placed_label_pts.append(np.array(positions[-1])) continue anchor_idxs = sorted(set( [0, L - 1] + [int(round(t * (L - 1))) for t in np.linspace(0.0, 1.0, n_anchors)] )) candidates: List[Tuple[float, float, float]] = [] for idx in anchor_idxs: anchor = sh[idx] if idx == 0: tan = sh[min(L - 1, 5)] - sh[0] elif idx == L - 1: tan = sh[L - 1] - sh[max(0, L - 6)] else: lo = max(0, idx - 3) hi = min(L - 1, idx + 3) tan = sh[hi] - sh[lo] n = float(np.linalg.norm(tan)) if n < 1e-6: continue t_unit = tan / n normal_l = np.array([-t_unit[1], t_unit[0]]) normal_r = -normal_l directions = [normal_l, normal_r] if idx == 0: directions.append(-t_unit) if idx == L - 1: directions.append(t_unit) for direction in directions: for offset in offsets: pos = anchor + direction * offset px, py = float(pos[0]), float(pos[1]) if (px - label_half_w < 4 or px + label_half_w > width - 4 or py - label_half_h < 4 or py + label_half_h > height - 4): continue own_d = float("inf") other_d = float("inf") for j, sh_j in enumerate(shifted_all): diffs = sh_j - np.array([px, py]) d = float(np.sqrt((diffs * diffs).sum(axis=1)).min()) if j == i: if d < own_d: own_d = d else: if d < other_d: other_d = d if own_d > own_max: continue if other_d < other_clearance: continue label_d = float("inf") for lp in placed_label_pts: d = float(np.hypot(px - lp[0], py - lp[1])) if d < label_d: label_d = d if label_d < label_clearance: continue score = other_d + 0.5 * label_d - 0.4 * offset candidates.append((score, px, py)) if candidates: candidates.sort(reverse=True) _, px, py = candidates[0] best_pos = (px, py) else: best_pos = None for relax in (0.7, 0.5, 0.3): clr = other_clearance * relax for idx in anchor_idxs: anchor = sh[idx] for direction_sign in (1, -1): if idx == 0: tan = sh[min(L - 1, 5)] - sh[0] elif idx == L - 1: tan = sh[L - 1] - sh[max(0, L - 6)] else: tan = sh[min(L - 1, idx + 3)] - sh[max(0, idx - 3)] n = float(np.linalg.norm(tan)) or 1.0 t_unit = tan / n normal = np.array([-t_unit[1] * direction_sign, t_unit[0] * direction_sign]) for offset in offsets: pos = anchor + normal * offset px, py = float(pos[0]), float(pos[1]) if (px - label_half_w < 4 or px + label_half_w > width - 4 or py - label_half_h < 4 or py + label_half_h > height - 4): continue other_d = min( float(np.sqrt(((sh_j - np.array([px, py])) ** 2).sum(axis=1)).min()) for j, sh_j in enumerate(shifted_all) if j != i ) if other_d >= clr: best_pos = (px, py) break if best_pos: break if best_pos: break if best_pos: break if best_pos is None: ep = sh[-1] best_pos = ( float(np.clip(ep[0] + 16, 4 + label_half_w, width - 4 - label_half_w)), float(np.clip(ep[1], 4 + label_half_h, height - 4 - label_half_h)), ) positions.append(best_pos) placed_label_pts.append(np.array(best_pos)) return positions # --------------------------------------------------------------------------- # Stroke sampling / swapping # --------------------------------------------------------------------------- def _generate_stroke(rng: random.Random) -> np.ndarray: _cp, curve = generate_template_stroke(rng) return curve def _sample_different_stroke( rng: random.Random, old: np.ndarray, old_radius: float, max_tries: int = 200, ) -> np.ndarray: """Sample a new stroke with Hausdorff distance >= HAUSDORFF_THRESH from ``old`` and bounding radius not larger than ``old_radius``.""" for _ in range(max_tries): try: _cp, cand = generate_distractor_stroke( rng, old, min_hausdorff=HAUSDORFF_THRESH, max_hausdorff=HAUSDORFF_MAX, ) except RuntimeError: continue if _curve_radius(cand) <= old_radius: return cand raise RuntimeError("Could not sample a sufficiently different stroke.") # --------------------------------------------------------------------------- # 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 stroke {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_strokes = [_generate_stroke(rng) for _ in range(num_items)] radii = [_curve_radius(s) for s in left_strokes] right_strokes: List[np.ndarray] = [s.copy() for s in left_strokes] changed_idx = rng.sample(range(num_items), num_diffs) for i in changed_idx: right_strokes[i] = _sample_different_stroke(rng, left_strokes[i], radii[i]) centers = _place_items(rng, radii) changed_set = set(changed_idx) # Compute label positions in panel-local coords using the LEFT stroke set # as geometry reference. The same (px, py) is used in both panels. label_positions = _compute_label_positions( PANEL_W, PANEL_H, centers, left_strokes ) items: List[Dict[str, Any]] = [] for i in range(num_items): x, y = centers[i] lx, ly = label_positions[i] items.append({ "index": i, "label": _index_to_letters(i), "x": x, "y": y, "bounding_radius": radii[i], "left_curve": left_strokes[i], "right_curve": right_strokes[i], "changed": i in changed_set, "label_pos": (lx, ly), }) 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 _draw_panel( ax: plt.Axes, items: List[Dict[str, Any]], side: str, ox: float, oy: float, ) -> None: key = "left_curve" if side == "left" else "right_curve" for it in items: center = np.array([ox + it["x"], oy + it["y"]]) _render_curve_on_ax(ax, it[key], center, color="white", linewidth=STROKE_WIDTH) # Letter labels removed: task is now a count, not a label list. 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) _draw_panel(ax, items, "left", ox_left, oy) _draw_panel(ax, items, "right", ox_right, oy) ax.text( ox_left + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5, "Left", ha="center", va="center", fontsize=16, fontweight="bold", color=LABEL_COLOR, ) ax.text( ox_right + PANEL_W / 2, MARGIN_PX + LABEL_HEIGHT * 0.5, "Right", ha="center", va="center", fontsize=16, fontweight="bold", color=LABEL_COLOR, ) if diffs: for diff in diffs: hl_r = diff["bounding_radius"] + 14 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": 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]] = [] 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 stroke diff counts: {forced}") for idx in tqdm(range(count), desc="Generating stroke diff pairs"): num_diffs = forced[idx] for _ in range(30): 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"stroke_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_stroke_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 Stroke 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 stroke subtlety.") p.add_argument("--workers", type=int, default=8) 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(8.0, 12.0 - 0.4 * d) HAUSDORFF_MAX = max(HAUSDORFF_THRESH + 10.0, 40.0 - 1.0 * d) stroke_count = 10 + 2 * d min_diffs = 5 max_diffs = 5 + 2 * d sys.path.insert(0, str(Path(__file__).resolve().parents[3])) from _sample_pool import parallel_sample_records # noqa: E402 # Force evenly-spaced num_diffs across [min_diffs, max_diffs]. if args.count > 1: forced_targets = [ int(round(min_diffs + i * (max_diffs - min_diffs) / (args.count - 1))) for i in range(args.count) ] else: forced_targets = [min_diffs] print(f"forced stroke_diff num_diffs: {forced_targets}") output_dir = args.output_root 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) raw = [] for ti, tgt in enumerate(forced_targets): def _attempt(rng, _tgt=tgt): try: items, diffs = build_sample(rng, stroke_count, _tgt) if len(diffs) != _tgt: return None return (items, diffs) except RuntimeError: return None sub = parallel_sample_records( _attempt, count=1, workers=args.workers, seed_base=args.seed + ti * 977, ) raw.extend(sub) annotations = [] data_items = [] for idx, (items, diffs) in enumerate(raw): image_name = f"stroke_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") (output_dir / "data.json").write_text(json.dumps({ "task": "spot_the_stroke_diff", "category": "visual_attribute_transfer", "count": len(data_items), "items": data_items, }, indent=2)) print(f"Saved {len(data_items)} image pairs to {output_dir} (workers={args.workers})") if __name__ == "__main__": main()