File size: 29,620 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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
"""Generate stroke_gesture_count samples.

Each sample produces a SINGLE side-by-side image: Template on the left,
Field on the right, separated by a thin divider.

The Template panel shows a single white brush stroke with a specific
curvature profile, and the Field (900x900 dark canvas) shows 25-35
scattered brush strokes, some matching the template's shape exactly
(translated only) and the rest being distractors.

The task: count how many strokes in the field match the template's shape.
"""

from __future__ import annotations

import argparse
import io
import json
import random
from pathlib import Path
from typing import List, Tuple, Optional

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import Rectangle
import numpy as np
from PIL import Image
from scipy.interpolate import splprep, splev
from scipy.spatial.distance import directed_hausdorff
from tqdm import tqdm


QUESTION = (
    "This image has two panels separated by a thin vertical divider. "
    "The left panel shows the Template: a single white brush stroke with a "
    "specific curvature profile. The right panel shows the Field: many white "
    "brush strokes scattered across the canvas, all at the same thickness. "
    "Both panels use the SAME pixel scale and stroke width. Count the number "
    "of strokes in the Field that have the exact same shape as the Template "
    "(translation only — same curvature, same orientation, no rotation or "
    "mirroring) and report the integer count. "
    "Provide your final answer enclosed in <answer>...</answer> tags."
)

STROKE_WIDTH = 4.0
BG_COLOR = "#0a1020"
HEADER_BG = "#11182a"
BORDER_COLOR = "#7aa6ff"
LABEL_COLOR = "#cfe0ff"
STROKE_COLOR = "white"
LABEL_TEXT_COLOR = "#ffd24a"  # bright yellow/gold, distinct from white strokes
LABEL_FONT_SIZE = 13


# ---------------------------------------------------------------------------
# Stroke generation via B-splines
# ---------------------------------------------------------------------------

def _random_control_points(rng: random.Random, n_pts: int = 5,
                           target_length: float = 120.0) -> np.ndarray:
    """Generate n_pts control points that create an interesting curve.

    Returns control points centered around the origin.
    The resulting curve will have arc length approximately target_length.
    """
    # Spread control points in a roughly sequential manner along x
    # with random y offsets to create interesting curvature
    scale = target_length / (n_pts - 1)
    pts = []
    for i in range(n_pts):
        x = i * scale * rng.uniform(0.6, 1.4)
        y = rng.uniform(-scale * 1.2, scale * 1.2)
        pts.append([x, y])
    pts = np.array(pts, dtype=np.float64)
    # Center around origin
    centroid = pts.mean(axis=0)
    pts -= centroid
    return pts


def _sample_bspline(control_points: np.ndarray,
                    n_samples: int = 300) -> np.ndarray:
    """Dense-sample a B-spline through the given control points.

    Returns (n_samples, 2) array of points along the curve.
    """
    k = min(3, len(control_points) - 1)
    tck, u = splprep([control_points[:, 0], control_points[:, 1]],
                     s=0, k=k)
    u_fine = np.linspace(0, 1, n_samples)
    x, y = splev(u_fine, tck)
    return np.column_stack([x, y])


def _arc_length(curve: np.ndarray) -> float:
    """Compute arc length of a polyline."""
    diffs = np.diff(curve, axis=0)
    return float(np.sum(np.sqrt(np.sum(diffs**2, axis=1))))


def _curve_bbox(curve: np.ndarray) -> Tuple[float, float, float, float]:
    """Return (xmin, ymin, xmax, ymax) of a curve."""
    return (curve[:, 0].min(), curve[:, 1].min(),
            curve[:, 0].max(), curve[:, 1].max())


def _hausdorff_distance(c1: np.ndarray, c2: np.ndarray) -> float:
    """Symmetric Hausdorff distance between two point sets."""
    d1 = directed_hausdorff(c1, c2)[0]
    d2 = directed_hausdorff(c2, c1)[0]
    return max(d1, d2)


def generate_template_stroke(rng: random.Random) -> Tuple[np.ndarray, np.ndarray]:
    """Generate a template stroke.

    Returns (control_points, sampled_curve) where the curve is centered
    around origin.
    """
    for _ in range(100):
        n_pts = rng.randint(4, 5)
        lo = max(40.0, 120.0 - TEMPLATE_LENGTH_STD)
        hi = 120.0 + TEMPLATE_LENGTH_STD
        target_len = rng.uniform(lo, hi)
        cp = _random_control_points(rng, n_pts, target_len)
        curve = _sample_bspline(cp, 300)

        length = _arc_length(curve)
        if length < max(40.0, lo - 10.0) or length > hi + 30.0:
            continue

        # Check bounding box isn't too degenerate
        bbox = _curve_bbox(curve)
        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]
        if w < 20 or h < 15:
            continue
        if w > 250 or h > 250:
            continue

        # Center the curve
        centroid = curve.mean(axis=0)
        curve -= centroid
        cp -= centroid
        return cp, curve

    raise RuntimeError("Could not generate template stroke")


DISTRACTOR_HAUSDORFF_MIN = 15.0  # module-level override target (difficulty-tunable)
TEMPLATE_LENGTH_STD = 35.0       # range for uniform target_length around 120


def generate_distractor_stroke(rng: random.Random,
                               template_curve: np.ndarray,
                               min_hausdorff: float = 15.0,
                               max_hausdorff: float | None = None) -> Tuple[np.ndarray, np.ndarray]:
    """Generate a distractor stroke that is similar in size but different shape.

    Returns (control_points, sampled_curve) centered around origin.
    """
    template_length = _arc_length(template_curve)

    for _ in range(200):
        n_pts = rng.randint(4, 5)
        # Match approximate length
        target_len = template_length * rng.uniform(0.8, 1.2)
        cp = _random_control_points(rng, n_pts, target_len)
        curve = _sample_bspline(cp, 300)

        length = _arc_length(curve)
        if length < 60 or length > 200:
            continue

        bbox = _curve_bbox(curve)
        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]
        if w < 15 or h < 10:
            continue
        if w > 280 or h > 280:
            continue

        # Center
        centroid = curve.mean(axis=0)
        curve -= centroid
        cp -= centroid

        # Verify sufficiently different from template
        hd = _hausdorff_distance(curve, template_curve)
        if hd < min_hausdorff:
            continue
        if max_hausdorff is not None and hd > max_hausdorff:
            continue

        return cp, curve

    raise RuntimeError("Could not generate distractor stroke")


# ---------------------------------------------------------------------------
# Placement
# ---------------------------------------------------------------------------

def _curves_overlap(centers: List[np.ndarray], curves: List[np.ndarray],
                    new_center: np.ndarray, new_curve: np.ndarray,
                    min_dist: float) -> bool:
    """Check if a new stroke (at new_center) overlaps any existing strokes.

    Uses bounding-box pre-filter then checks minimum point-to-point distance
    between the actual curve samples for any pair whose bboxes are close.
    """
    min_pixel_gap = 14.0  # minimum pixel gap between any two strokes
    new_shifted = new_curve + new_center
    new_bbox = _curve_bbox(new_shifted)

    for i, (c, crv) in enumerate(zip(centers, curves)):
        existing_shifted = crv + c
        existing_bbox = _curve_bbox(existing_shifted)

        # Quick bbox rejection with generous margin
        margin = min_pixel_gap + 5.0
        if (new_bbox[2] + margin < existing_bbox[0] or
            new_bbox[0] - margin > existing_bbox[2] or
            new_bbox[3] + margin < existing_bbox[1] or
            new_bbox[1] - margin > existing_bbox[3]):
            continue  # bboxes far apart, no overlap

        # Bboxes are close -- subsample curves and check min distance
        # Use every 10th point for speed (still ~30 points per curve)
        ns = new_shifted[::10]
        es = existing_shifted[::10]
        # Compute pairwise distances
        diffs = ns[:, None, :] - es[None, :, :]
        dists_sq = np.sum(diffs**2, axis=-1)
        min_d = float(np.sqrt(dists_sq.min()))
        if min_d < min_pixel_gap:
            return True
    return False


def build_sample(rng: random.Random, width: int, height: int,
                 target_matches: int, total_strokes: int
                 ) -> Tuple[np.ndarray, np.ndarray, List[np.ndarray], List[np.ndarray], int]:
    """Build a sample.

    Returns:
        template_cp: control points for template
        template_curve: sampled template curve (centered at origin)
        centers: list of (x, y) center positions for each placed stroke
        curves: list of sampled curves (each centered at origin) for each stroke
        realised_matches: verified match count
    """
    for attempt in range(40):
        try:
            template_cp, template_curve = generate_template_stroke(rng)
        except RuntimeError:
            continue

        t_bbox = _curve_bbox(template_curve)
        max_stroke_extent = max(abs(t_bbox[0]), abs(t_bbox[1]),
                                abs(t_bbox[2]), abs(t_bbox[3]))
        pad = max_stroke_extent + 30.0
        min_center_dist = max_stroke_extent * 1.8 + 10.0

        centers: List[np.ndarray] = []
        curves: List[np.ndarray] = []
        is_match: List[bool] = []

        # 1. Place template matches
        placed_matches = 0
        for _ in range(target_matches):
            placed = False
            for _try in range(500):
                cx = rng.uniform(pad, width - pad)
                cy = rng.uniform(pad, height - pad)
                center = np.array([cx, cy])

                if _curves_overlap(centers, curves, center, template_curve,
                                   min_center_dist):
                    continue

                # Check the stroke stays in bounds
                shifted = template_curve + center
                if (shifted[:, 0].min() < 5 or shifted[:, 0].max() > width - 5 or
                    shifted[:, 1].min() < 5 or shifted[:, 1].max() > height - 5):
                    continue

                centers.append(center)
                curves.append(template_curve.copy())
                is_match.append(True)
                placed_matches += 1
                placed = True
                break
            if not placed:
                break

        if placed_matches != target_matches:
            continue

        # 2. Place distractors
        distractors_needed = total_strokes - placed_matches
        fail = False
        for _ in range(distractors_needed):
            placed = False
            for _try in range(300):
                try:
                    d_cp, d_curve = generate_distractor_stroke(
                        random.Random(rng.randint(0, 2**31 - 1)),
                        template_curve,
                        min_hausdorff=DISTRACTOR_HAUSDORFF_MIN)
                except RuntimeError:
                    continue

                d_bbox = _curve_bbox(d_curve)
                d_extent = max(abs(d_bbox[0]), abs(d_bbox[1]),
                               abs(d_bbox[2]), abs(d_bbox[3]))
                d_pad = d_extent + 20.0

                cx = rng.uniform(d_pad, width - d_pad)
                cy = rng.uniform(d_pad, height - d_pad)
                center = np.array([cx, cy])

                if _curves_overlap(centers, curves, center, d_curve,
                                   min_center_dist * 0.7):
                    continue

                shifted = d_curve + center
                if (shifted[:, 0].min() < 5 or shifted[:, 0].max() > width - 5 or
                    shifted[:, 1].min() < 5 or shifted[:, 1].max() > height - 5):
                    continue

                centers.append(center)
                curves.append(d_curve)
                is_match.append(False)
                placed = True
                break
            if not placed:
                fail = True
                break

        if fail:
            continue

        # 3. Verify match count by checking Hausdorff distance
        verified_matches = 0
        for i, crv in enumerate(curves):
            hd = _hausdorff_distance(crv, template_curve)
            if hd < 2.0:  # essentially identical shape
                verified_matches += 1

        if verified_matches == target_matches:
            return template_cp, template_curve, centers, curves, verified_matches

    raise RuntimeError("Failed to build sample after many attempts")


# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------

def _render_curve_on_ax(ax, curve: np.ndarray, center: np.ndarray,
                        color: str = "white", linewidth: float = STROKE_WIDTH):
    """Render a single stroke on a matplotlib axes."""
    shifted = curve + center
    ax.plot(shifted[:, 0], shifted[:, 1],
            color=color, linewidth=linewidth,
            solid_capstyle="round", solid_joinstyle="round",
            antialiased=True, zorder=3)


def _label_index_to_text(idx: int) -> str:
    """Map 0->A, 1->B, ..., 25->Z, 26->AA, 27->AB, ..."""
    s = ""
    n = idx
    while True:
        s = chr(ord("A") + (n % 26)) + s
        n = n // 26 - 1
        if n < 0:
            break
    return s


def _compute_label_positions(width: int, height: int,
                             centers: List[np.ndarray],
                             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.
    """
    own_max = 22.0          # label must be within own_max of its own stroke
    other_clearance = 16.0  # must clear all OTHER strokes by ≥ this
    label_clearance = 22.0  # must clear other labels by ≥ this (centre-centre)
    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 + 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 indices: ~n_anchors uniformly along the curve, plus the
        # two endpoints explicitly.
        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]] = []  # (score, px, py)
        for idx in anchor_idxs:
            anchor = sh[idx]
            # Tangent at anchor (use neighbours if available).
            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]
            # At endpoints, also try extending outward along the tangent.
            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

                    # Distance to own stroke and to every other stroke.
                    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

                    # Hard gates.
                    if own_d > own_max:
                        continue
                    if other_d < other_clearance:
                        continue

                    # Label-label clearance.
                    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

                    # Maximise (other_d, label_d) and minimise offset.
                    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:
            # Soft fallback: relax other_clearance progressively.
            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


def render_field(width: int, height: int,
                 centers: List[np.ndarray], curves: List[np.ndarray],
                 labels: Optional[List[str]] = None,
                 label_positions: Optional[List[Tuple[float, float]]] = None) -> Image.Image:
    """Render the field image. Returns PIL Image."""
    fig = plt.figure(figsize=(width / 100, height / 100), dpi=100,
                     facecolor=BG_COLOR)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)
    ax.axis("off")
    ax.set_facecolor(BG_COLOR)

    for center, curve in zip(centers, curves):
        _render_curve_on_ax(ax, curve, center)

    # Letter labels removed — task is now a count, no per-stroke labels needed.

    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=100, bbox_inches="tight", pad_inches=0,
                facecolor=fig.get_facecolor())
    plt.close(fig)
    buf.seek(0)
    return Image.open(buf).convert("RGB")


def render_template(template_curve: np.ndarray) -> Image.Image:
    """Render the template panel at the SAME pixel scale as the field. Returns PIL Image."""
    t_bbox = _curve_bbox(template_curve)
    span_x = t_bbox[2] - t_bbox[0]
    span_y = t_bbox[3] - t_bbox[1]

    margin = 40.0
    header_h = 34.0
    min_width = 200.0

    content_w = span_x + 2 * margin
    content_h = span_y + 2 * margin
    canvas_w = max(content_w, min_width)
    canvas_h = header_h + content_h

    # Offset to center the stroke in the content area
    margin_x = (canvas_w - span_x) / 2.0
    ox = margin_x - t_bbox[0]
    oy = (header_h + margin) - t_bbox[1]
    center = np.array([ox, oy])

    fig = plt.figure(figsize=(canvas_w / 100, canvas_h / 100), dpi=100,
                     facecolor="#070b14")
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, canvas_w)
    ax.set_ylim(canvas_h, 0)
    ax.axis("off")
    ax.set_facecolor("#070b14")

    # Header strip
    ax.add_patch(Rectangle((0, 0), canvas_w, header_h,
                           facecolor=HEADER_BG, edgecolor="none", zorder=4))
    ax.plot([0, canvas_w], [header_h, header_h],
            color="#2d3a5a", linewidth=1.0, zorder=5)
    ax.text(canvas_w / 2, header_h / 2, "TEMPLATE",
            color=LABEL_COLOR, fontsize=14, fontweight="bold",
            ha="center", va="center", zorder=6,
            family="DejaVu Sans")

    # Border
    ax.add_patch(Rectangle((1.5, 1.5), canvas_w - 3, canvas_h - 3,
                           facecolor="none", edgecolor=BORDER_COLOR,
                           linewidth=2.0, zorder=6))

    # Draw the template stroke
    _render_curve_on_ax(ax, template_curve, center, linewidth=STROKE_WIDTH)

    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=100, bbox_inches=None, pad_inches=0,
                facecolor=fig.get_facecolor())
    plt.close(fig)
    buf.seek(0)
    return Image.open(buf).convert("RGB")


DIVIDER_WIDTH = 3
DIVIDER_COLOR = (51, 51, 85)  # #333355


def render_combined(out_path: Path, template_img: Image.Image,
                    field_img: Image.Image) -> None:
    """Concatenate template (left) and field (right) with a thin divider,
    then pad to a square canvas (BG colour) so downstream image-edit
    models receive a 1:1 input."""
    bg = tuple(int(BG_COLOR.lstrip("#")[i:i+2], 16) for i in (0, 2, 4))
    tw, th = template_img.size
    fw, fh = field_img.size
    inner_h = max(th, fh)
    inner_w = tw + DIVIDER_WIDTH + fw
    side = max(inner_w, inner_h)
    combined = Image.new("RGB", (side, side), bg)
    x0 = (side - inner_w) // 2
    y0 = (side - inner_h) // 2
    combined.paste(template_img, (x0, y0 + (inner_h - th) // 2))
    for x in range(x0 + tw, x0 + tw + DIVIDER_WIDTH):
        for y in range(y0, y0 + inner_h):
            combined.putpixel((x, y), DIVIDER_COLOR)
    combined.paste(field_img, (x0 + tw + DIVIDER_WIDTH, y0 + (inner_h - fh) // 2))
    combined.save(out_path)


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main() -> None:
    parser = argparse.ArgumentParser(
        description="Generate stroke_gesture_count samples")
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument("--count", type=int, default=30)
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--width", type=int, default=900)
    parser.add_argument("--height", type=int, default=900)
    parser.add_argument("--difficulty", type=int, default=5,
                        help="Integer difficulty >=0; scales matches, total strokes, and distractor similarity.")
    args = parser.parse_args()

    import math
    d = max(0, int(args.difficulty))
    _min_matches = 5
    _max_matches = 5 + 2 * d
    _total_strokes_lo = 25 + 3 * d
    global DISTRACTOR_HAUSDORFF_MIN, TEMPLATE_LENGTH_STD
    DISTRACTOR_HAUSDORFF_MIN = max(8.0, 18.0 - 1.0 * d)
    TEMPLATE_LENGTH_STD = 30.0 + 5.0 * d

    # Canvas scaling: N_d = 25 + 3d, N_0 = 25. Scale both axes by sqrt(N_d/N_0)
    # to preserve stroke density.
    n_d = 25 + 3 * d
    n_0 = 25
    s = math.sqrt(max(1.0, n_d / n_0))
    args.width = int(round(args.width * s))
    args.height = int(round(args.height * s))

    out_root: Path = args.output_root
    img_dir = out_root / "images"
    img_dir.mkdir(parents=True, exist_ok=True)

    ann_path = out_root / "annotations.jsonl"
    master_rng = random.Random(args.seed)

    # Force evenly-spaced answers across [_min_matches, _max_matches].
    if args.count > 1:
        plan = [int(round(_min_matches + i * (_max_matches - _min_matches) / (args.count - 1))) for i in range(args.count)]
    else:
        plan = [_min_matches]
    print(f"forced stroke_gesture match counts: {plan}")

    records = []
    with ann_path.open("w") as f:
        for i in tqdm(range(args.count), desc="stroke_gesture_count"):
            target = plan[i]
            total_strokes = master_rng.randint(_total_strokes_lo,
                                               _total_strokes_lo + 10)
            total_strokes = max(total_strokes, target + 20)

            built = False
            for retry in range(20):
                sub_seed = master_rng.randint(0, 2**31 - 1)
                sub_rng = random.Random(sub_seed)
                try:
                    template_cp, template_curve, centers, curves, realised = \
                        build_sample(sub_rng, args.width, args.height,
                                     target_matches=target,
                                     total_strokes=total_strokes)
                except RuntimeError:
                    continue
                built = True
                break
            if not built:
                raise RuntimeError(f"sample {i} could not be generated")

            # Shuffle the stroke order so match labels are not always first.
            order = list(range(len(centers)))
            master_rng.shuffle(order)
            centers = [centers[k] for k in order]
            curves = [curves[k] for k in order]

            # Recompute match flags after shuffling.
            is_match = []
            for crv in curves:
                hd = _hausdorff_distance(crv, template_curve)
                is_match.append(hd < 2.0)

            labels = [_label_index_to_text(k) for k in range(len(centers))]
            label_positions = _compute_label_positions(
                args.width, args.height, centers, curves)

            matching_labels = sorted(
                [labels[k] for k, m in enumerate(is_match) if m],
                key=lambda s: (len(s), s))
            answer_str = str(realised)

            img_name = f"stroke_gesture_count_{i:05d}.png"
            tpl_img = render_template(template_curve)
            fld_img = render_field(args.width, args.height, centers, curves,
                                   labels=None, label_positions=None)
            render_combined(img_dir / img_name, tpl_img, fld_img)

            rec = {
                "image": f"images/{img_name}",
                "question": QUESTION,
                "answer": answer_str,
                "num_matches": realised,
                "matching_labels": matching_labels,
                "total_strokes": len(centers),
                "metadata": {
                    "seed": sub_seed,
                    "template_control_points": template_cp.tolist(),
                    "template_arc_length": float(_arc_length(template_curve)),
                },
            }
            f.write(json.dumps(rec) + "\n")
            f.flush()
            records.append(rec)

    data_json = {
        "task": "stroke_gesture_count",
        "category": "visual_attribute_transfer",
        "count": len(records),
        "items": records,
    }
    (out_root / "data.json").write_text(json.dumps(data_json, indent=2))

    # Print summary
    from collections import Counter
    answers = [r["answer"] for r in records]
    dist = Counter(answers)
    print(f"\nSaved {len(records)} samples to {out_root}")
    print(f"Images: {len(records)} (single combined per sample)")
    print(f"Answer distribution: {dict(sorted(dist.items()))}")


if __name__ == "__main__":
    main()