File size: 22,555 Bytes
f69e256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
"""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 <answer>...</answer> 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()