File size: 41,786 Bytes
15d1f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
eval_geometric02.py  --  v2 evaluation for the EDP "image -> ezdxf code" task.

WHY v2 (vs eval_geometric.py):
  The old metric named its levels L0/L1/L2/L3, which COLLIDES with the dataset
  difficulty tiers (labels.csv `tier` = L1/L2/L3). v2 reorganises the metric
  strictly around the THREE conceptual axes the task actually cares about, with
  names that can never be confused with dataset difficulty:

    U  Usability   (生成可用性) : can the prediction be turned into a drawing at all?
                                  format -> compile -> run -> dxf_readable -> non-degenerate
    G  Geometry    (几何正确性) : are the shapes right?
                                  HIT-RATIO side : lines / hidden (F1@tau) + circles / arcs (matched F1)
                                  ACCURACY side  : nearest-neighbour dist (mm) for lines/hidden,
                                                   center dist (mm) + radius MAPE for circles/arcs
    A  Annotation  (标注正确性) : are the dimensions right?
                                  value match (unit-normalised + tolerance, radius<->diameter
                                  equivalence) + placement

KEY FIXES over v1 (carried in from the metric review):
  * ONE shared Procrustes alignment (translate+scale, no rotation) reused by every
    geometry / annotation sub-metric -> cross-metric comparability.
  * Line geometry headline is F1@tau (tau normalised by part size), NOT raw Chamfer
    with exp(-d/1mm) which saturated to ~0 and killed all signal.
  * Dimension text is unit-normalised (strip %%c / %%C / Ø / R / spaces) and matched
    by RELATIVE tolerance, not exact string equality; radius<->diameter equivalence.
  * Usability adds a non-degenerate check (entities>0 & sane bbox) so an "empty but
    runnable" drawing cannot score as usable.  (matters a lot for RL reward hacking)
  * Every prediction gets ONE end-to-end scalar `overall` in [0,1] via a gated
    formula (usable -> then geometry & annotation), suitable to reuse as an RL reward.

Usage:
  python eval_geometric02.py \
    --pred /root/autodl-tmp/EDP_code/eval/sft_pred_test_full.jsonl \
    --gt-dir /root/autodl-tmp/EDP_code/code_datasets/gt_dxf_test \
    --pred-dxf-dir /root/autodl-tmp/EDP_code/eval/pred_dxf_full \
    --out /root/autodl-tmp/EDP_code/eval/scores_v2_full.jsonl \
    --summary /root/autodl-tmp/EDP_code/eval/summary_v2_full.json
"""
import os, re, sys, json, argparse, subprocess, tempfile
from collections import Counter, defaultdict
import numpy as np
import ezdxf
from scipy.spatial.distance import cdist
from scipy.optimize import linear_sum_assignment

CODE_PAT = re.compile(r"```python\s*\n(.*?)```", re.DOTALL)

# tau ladder (mm) for line F1@tau BEFORE size-normalisation reference.
# We normalise tau by the GT drawing diagonal so it is scale-robust across parts.
TAU_FRACS = (0.005, 0.01, 0.02)   # 0.5% / 1% / 2% of the GT bbox diagonal
TAU_HEADLINE_IDX = 1              # headline uses the 1% tau

# dimension value tolerance: matched if |v_pred - v_gt| <= max(ABS, REL*|v_gt|)
DIM_ABS_TOL = 0.5    # mm
DIM_REL_TOL = 0.01   # 1%

# circle/arc center-distance threshold, normalised by the GT drawing diagonal
# (same size-robust idea as the line F1@tau). A circle counts as located if its
# aligned center is within EPS_CENTER_FRAC * gt_diag of the GT center. This fixes
# the old absolute 0.5mm threshold that rejected correctly-drawn circles whenever
# the overall view layout was slightly translated/scaled.
EPS_CENTER_FRAC = 0.03   # 3% of GT bbox diagonal
CIRCLE_RTOL = 0.02       # radius relative tolerance (circles)
ARC_RTOL = 0.03          # radius relative tolerance (arcs, a bit looser)
ARC_ANGLE_IOU_MIN = 0.50
ARC_DEGENERATE_ANGLE_TOL_DEG = 0.01

# overall-score weights (within the "usable" branch); usable base is added on top.
W_GEOM = 0.5
W_ANNO = 0.5
USABLE_BASE = 0.3    # a usable, non-degenerate drawing floors at 0.3 before quality

# SOFT GATE (progressive U -> G -> A): annotation quality is only credited to the
# extent geometry is correct. We multiply the annotation term by a soft gate
# derived from the geometry score, so "geometry wrong but numbers right" cannot
# earn much overall, WITHOUT hard-zeroing A (the raw A is still reported for
# diagnosis). gate = GATE_FLOOR + (1-GATE_FLOOR) * G, clipped to [0,1].
#   GATE_FLOOR>0 keeps a small annotation credit alive even when G is low, so the
#   reward gradient does not fully vanish (helps RL / avoids dead zones).
GATE_FLOOR = 0.25


# ============================================================
# SECTION 1 — code execution + DXF entity extraction (helpers)
# ============================================================

def extract_code(text):
    m = CODE_PAT.search(text or "")
    return m.group(1) if m else (text or "").strip()


def compile_ok(code):
    try:
        compile(code, "<pred>", "exec"); return True
    except SyntaxError:
        return False


def run_code_to_dxf(code, out_path, timeout=30):
    """Run prediction code as subprocess -> DXF. Returns (ok, err_msg)."""
    fd, py = tempfile.mkstemp(suffix=".py", prefix="pred02_")
    os.close(fd)
    try:
        with open(py, "w", encoding="utf-8") as f:
            f.write(code)
        p = subprocess.run([sys.executable, py, out_path],
                           capture_output=True, text=True, timeout=timeout)
        if p.returncode != 0:
            err = (p.stderr or p.stdout or "").strip().splitlines()
            return False, err[-1] if err else "non-zero exit"
        if not os.path.exists(out_path):
            return False, "ran but no DXF produced"
        return True, None
    except subprocess.TimeoutExpired:
        return False, f"timeout >{timeout}s"
    except Exception as e:
        return False, f"{type(e).__name__}: {e}"
    finally:
        if os.path.exists(py):
            os.remove(py)


def extract_entities(dxf_path):
    """Read a DXF -> structured entity lists (or None if unreadable).
    lines:   (x1,y1,x2,y2, layer)
    circles: (cx,cy,r, layer)
    arcs:    (cx,cy,r,a1,a2, layer)
    dims:    (dimtype_int, text, layer, defpoint_x, defpoint_y, bind_x, bind_y)
    """
    try:
        doc = ezdxf.readfile(dxf_path)
    except Exception:
        return None
    msp = doc.modelspace()
    lines, circles, arcs, dims = [], [], [], []
    for e in msp:
        et = e.dxftype()
        layer = e.dxf.layer if e.dxf.hasattr("layer") else "0"
        if et == "LINE":
            lines.append((e.dxf.start.x, e.dxf.start.y,
                          e.dxf.end.x, e.dxf.end.y, layer))
        elif et == "CIRCLE":
            circles.append((e.dxf.center.x, e.dxf.center.y, e.dxf.radius, layer))
        elif et == "ARC":
            arcs.append((e.dxf.center.x, e.dxf.center.y, e.dxf.radius,
                         e.dxf.start_angle, e.dxf.end_angle, layer))
        elif et == "DIMENSION":
            dt = e.dxf.dimtype if e.dxf.hasattr("dimtype") else 0
            txt = e.dxf.text if e.dxf.hasattr("text") else ""
            dpx = e.dxf.defpoint.x if e.dxf.hasattr("defpoint") else 0.0
            dpy = e.dxf.defpoint.y if e.dxf.hasattr("defpoint") else 0.0
            dt_base = dt & 0x0F
            if dt_base in (0, 1) and e.dxf.hasattr("defpoint2") and e.dxf.hasattr("defpoint3"):
                bpx = (e.dxf.defpoint2.x + e.dxf.defpoint3.x) / 2
                bpy = (e.dxf.defpoint2.y + e.dxf.defpoint3.y) / 2
            elif dt_base in (3, 4) and e.dxf.hasattr("defpoint4"):
                bpx, bpy = e.dxf.defpoint4.x, e.dxf.defpoint4.y
            else:
                bpx, bpy = dpx, dpy
            dims.append((dt, txt, layer, dpx, dpy, bpx, bpy))
    return {"lines": lines, "circles": circles, "arcs": arcs, "dims": dims}


def dim_type_name(dt):
    base = dt & 0x0F
    return {0: "linear", 1: "aligned", 2: "angular", 3: "diameter",
            4: "radius", 5: "angular3", 6: "ordinate"}.get(base, f"type{base}")


def parse_dim_value(text):
    """Unit-normalise a dimension label -> (family, float_value|None, raw).
    Strips AutoCAD control tokens (%%c, %%C, %%d), Ø, R, diameter/radius glyphs,
    whitespace; returns family in {'diameter','radius','linear'} inferred from
    the prefix, and the numeric value if parseable."""
    raw = text or ""
    s = raw.strip().replace(" ", "")
    family = "linear"
    low = s.lower()
    if low.startswith("%%c") or s.startswith("\u00d8") or s.startswith("\u2205"):
        family = "diameter"
    elif low.startswith("r") and not low.startswith("r0e"):
        family = "radius"
    # strip known prefixes / control tokens anywhere
    cleaned = re.sub(r"%%[a-zA-Z]", "", s)
    cleaned = cleaned.replace("\u00d8", "").replace("\u2205", "")
    cleaned = re.sub(r"^[Rr]", "", cleaned)
    m = re.search(r"[-+]?\d*\.?\d+", cleaned)
    val = float(m.group(0)) if m else None
    return family, val, raw


def _ccw_span(start_deg, end_deg):
    """Counter-clockwise DXF arc span in degrees, normalised to [0, 360)."""
    return float((end_deg - start_deg) % 360.0)


def _angle_distance(first_deg, second_deg):
    """Smallest absolute distance between two directions in degrees."""
    return abs(float((first_deg - second_deg + 180.0) % 360.0 - 180.0))


def _arc_angle_quality(a1p, a2p, a1g, a2g):
    """Circular interval IoU, with tolerance for quantised near-zero arcs."""
    span_p = _ccw_span(a1p, a2p)
    span_g = _ccw_span(a1g, a2g)
    if max(span_p, span_g) <= ARC_DEGENERATE_ANGLE_TOL_DEG:
        return float(
            _angle_distance(a1p, a1g) <= ARC_DEGENERATE_ANGLE_TOL_DEG
        )
    if min(span_p, span_g) <= ARC_DEGENERATE_ANGLE_TOL_DEG:
        return 0.0

    start_p = float(a1p % 360.0)
    end_p = start_p + span_p
    start_g = float(a1g % 360.0)
    overlap = 0.0
    for shift in (-360.0, 0.0, 360.0):
        shifted_start = start_g + shift
        shifted_end = shifted_start + span_g
        overlap = max(
            overlap,
            max(0.0, min(end_p, shifted_end) - max(start_p, shifted_start)),
        )
    union = span_p + span_g - overlap
    return float(overlap / union) if union > 1e-12 else 0.0


def _arc_geometry_points(cx, cy, radius, start_deg, end_deg, *, midpoint=False):
    """Points that bound the visible DXF arc rather than its full support circle."""
    start = float(start_deg % 360.0)
    span = _ccw_span(start_deg, end_deg)
    angles = [start, start + span]
    for cardinal in (0.0, 90.0, 180.0, 270.0):
        relative = (cardinal - start) % 360.0
        if relative <= span + 1e-9:
            angles.append(start + relative)
    if midpoint and span > 1e-12:
        angles.append(start + span / 2.0)
    return [
        (
            cx + radius * np.cos(np.deg2rad(angle)),
            cy + radius * np.sin(np.deg2rad(angle)),
        )
        for angle in angles
    ]


def bbox_diagonal(ent):
    """Diagonal length of the visible-geometry bounding box (mm). 0 if empty."""
    xs, ys = [], []
    for x1, y1, x2, y2, layer in ent["lines"]:
        xs += [x1, x2]; ys += [y1, y2]
    for cx, cy, r, layer in ent["circles"]:
        xs += [cx - r, cx + r]; ys += [cy - r, cy + r]
    for cx, cy, r, a1, a2, layer in ent["arcs"]:
        for x, y in _arc_geometry_points(cx, cy, r, a1, a2):
            xs.append(x); ys.append(y)
    if not xs:
        return 0.0
    return float(np.hypot(max(xs) - min(xs), max(ys) - min(ys)))


# ============================================================
# SECTION 2 — U: Usability
# ============================================================

def n_entities(ent):
    if ent is None:
        return 0
    return len(ent["lines"]) + len(ent["circles"]) + len(ent["arcs"]) + len(ent["dims"])


def score_usability(pred_code, pred_dxf_path, ent_pred):
    """生成可用性. Gated ladder + non-degenerate check.
    Returns dict with binary sub-flags AND a continuous `score` in [0,1] so RL
    gets a smooth ramp instead of a 0/1 cliff.
    """
    has_code = bool(pred_code and pred_code.strip())
    compiles = compile_ok(pred_code) if has_code else False
    runs = os.path.isfile(pred_dxf_path) and ent_pred is not None
    readable = ent_pred is not None
    # non-degenerate: produced real geometry with a sane bounding box
    ne = n_entities(ent_pred)
    diag = bbox_diagonal(ent_pred) if ent_pred is not None else 0.0
    non_degenerate = readable and ne >= 3 and 1.0 <= diag <= 1e5

    if not has_code:
        score = 0.0
    elif not compiles:
        score = 0.1
    elif not runs or not readable:
        score = 0.2
    elif not non_degenerate:
        score = 0.25
    else:
        score = 1.0
    return {
        "format_ok": has_code,
        "compile_ok": compiles,
        "run_ok": runs,
        "dxf_readable": readable,
        "non_degenerate": non_degenerate,
        "n_entities": ne,
        "bbox_diag": round(diag, 3),
        "all_ok": bool(has_code and compiles and runs and readable and non_degenerate),
        "score": score,
    }


# ============================================================
# SECTION 3 — shared alignment (Procrustes translate+scale)
# ============================================================

def _procrustes_ts(src, dst):
    """Align src to dst with translation + isotropic scale (NO rotation) via
    2-iteration nearest-neighbour ICP. Returns (src_centroid, dst_centroid, scale)
    so the SAME transform can be reapplied to any other point set:
        aligned = scale * (pts - src_centroid) + dst_centroid
    """
    if len(src) == 0 or len(dst) == 0:
        return np.zeros(2), np.zeros(2), 1.0
    cur = src.copy()
    s_total, src_c0 = 1.0, src.mean(axis=0)
    dst_c_final = src.mean(axis=0)
    for _ in range(2):
        D = cdist(cur, dst)
        matched = dst[D.argmin(axis=1)]
        c_src = cur.mean(axis=0)
        c_dst = matched.mean(axis=0)
        sc = cur - c_src
        dc = matched - c_dst
        sn = np.sqrt((sc ** 2).sum())
        dn = np.sqrt((dc ** 2).sum())
        s = dn / sn if sn > 1e-9 else 1.0
        cur = s * sc + c_dst
        s_total *= s
        dst_c_final = c_dst
    # Fold the 2 iterations into one transform relative to the ORIGINAL src.
    # aligned = s_total * (src - src_c0) + dst_c_final
    return src_c0, dst_c_final, float(s_total)


def transform_points(pts, src_c, dst_c, scale):
    if len(pts) == 0:
        return pts
    return scale * (pts - src_c) + dst_c


def collect_alignment_points(ent):
    """Visible reference points, using drawn arc points instead of remote centres."""
    pts = set()
    for x1, y1, x2, y2, layer in ent["lines"]:
        if "hidden" not in layer.lower():
            pts.add((round(x1, 2), round(y1, 2)))
            pts.add((round(x2, 2), round(y2, 2)))
    for cx, cy, r, layer in ent["circles"]:
        if "hidden" not in layer.lower():
            pts.add((round(cx, 2), round(cy, 2)))
    for cx, cy, r, a1, a2, layer in ent["arcs"]:
        if "hidden" not in layer.lower():
            for x, y in _arc_geometry_points(cx, cy, r, a1, a2, midpoint=True):
                pts.add((round(x, 2), round(y, 2)))
    return np.array(sorted(pts)) if pts else np.empty((0, 2))


def shared_alignment(ent_pred, ent_gt):
    """ONE Procrustes transform (translate+scale) from ALL visible pred geometry
    to ALL visible GT geometry. Reused by every G/A sub-metric for comparability.
    Returns (src_c, dst_c, scale)."""
    src = collect_alignment_points(ent_pred)
    dst = collect_alignment_points(ent_gt)
    return _procrustes_ts(src, dst)


# ============================================================
# SECTION 4 — G: Geometry (lines / hidden lines / circles / arcs)
# ============================================================

def line_vertices(lines):
    pts = set()
    for x1, y1, x2, y2, layer in lines:
        pts.add((round(x1, 2), round(y1, 2)))
        pts.add((round(x2, 2), round(y2, 2)))
    return np.array(sorted(pts)) if pts else np.empty((0, 2))


def f1_at_tau(src_pts, dst_pts, tau):
    """Bidirectional point F1 at radius tau (mm).
    precision = frac of pred pts with a GT pt within tau
    recall    = frac of GT pts with a pred pt within tau
    Both empty -> 1.0 ; one empty -> 0.0."""
    if len(src_pts) == 0 and len(dst_pts) == 0:
        return 1.0, 1.0, 1.0
    if len(src_pts) == 0 or len(dst_pts) == 0:
        return 0.0, 0.0, 0.0
    D = cdist(src_pts, dst_pts)
    prec = float((D.min(axis=1) <= tau).mean())   # pred -> gt
    rec = float((D.min(axis=0) <= tau).mean())     # gt -> pred
    f1 = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0
    return prec, rec, f1


def chamfer_stats(src_pts, dst_pts):
    """Symmetric nearest-neighbour distance stats (mm) between two point sets.
    Reports the PRECISION side of the metric (mm accuracy) that F1@tau cannot:
    how far off the matched geometry actually is, not just the hit ratio.
    Returns (mean, median, p90) of the symmetric nearest-neighbour distances."""
    if len(src_pts) == 0 or len(dst_pts) == 0:
        return None, None, None
    D = cdist(src_pts, dst_pts)
    d = np.concatenate([D.min(axis=1), D.min(axis=0)])  # symmetric: both directions
    return (round(float(d.mean()), 4), round(float(np.median(d)), 4),
            round(float(np.percentile(d, 90)), 4))


def _line_f1_block(pred_lines, gt_lines, src_c, dst_c, scale, gt_diag):
    """Align pred line vertices with the SHARED transform, then F1@tau ladder."""
    pv = line_vertices(pred_lines)
    gv = line_vertices(gt_lines)
    if len(pv) == 0 and len(gv) == 0:
        return {"present": False, "f1": 1.0, "n_pred": 0, "n_gt": 0,
                "f1_at": {}, "headline_tau_mm": None,
                "nn_dist_mean_mm": None, "nn_dist_median_mm": None,
                "nn_dist_p90_mm": None}
    pva = transform_points(pv, src_c, dst_c, scale) if len(pv) else pv
    diag = gt_diag if gt_diag > 1e-6 else 1.0
    f1_at = {}
    for frac in TAU_FRACS:
        tau = frac * diag
        _, _, f1 = f1_at_tau(pva, gv, tau)
        f1_at[f"{frac:.3f}"] = round(f1, 4)
    headline_frac = TAU_FRACS[TAU_HEADLINE_IDX]
    nn_mean, nn_median, nn_p90 = chamfer_stats(pva, gv)
    return {
        "present": True,
        "f1": f1_at[f"{headline_frac:.3f}"],
        "f1_at": f1_at,
        "headline_tau_mm": round(headline_frac * diag, 4),
        # mm-accuracy (precision side): how far off matched vertices are
        "nn_dist_mean_mm": nn_mean,
        "nn_dist_median_mm": nn_median,
        "nn_dist_p90_mm": nn_p90,
        "n_pred": int(len(pv)), "n_gt": int(len(gv)),
    }


def score_geometry(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag):
    """几何正确性: visible lines + hidden lines (F1@tau) and circles + arcs (matched F1).
    Returns per-family dicts + a single `score` in [0,1] (mean of present families)."""
    vis_p = [l for l in ent_pred["lines"] if "hidden" not in l[-1].lower()]
    vis_g = [l for l in ent_gt["lines"] if "hidden" not in l[-1].lower()]
    hid_p = [l for l in ent_pred["lines"] if "hidden" in l[-1].lower()]
    hid_g = [l for l in ent_gt["lines"] if "hidden" in l[-1].lower()]

    lines = _line_f1_block(vis_p, vis_g, src_c, dst_c, scale, gt_diag)
    hidden = _line_f1_block(hid_p, hid_g, src_c, dst_c, scale, gt_diag)
    circles = _match_circles(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag)
    arcs = _match_arcs(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag)

    # weighted mean over families that are "present" in either pred or GT
    parts = []
    parts.append(("lines", lines["f1"], 1.0))
    if hidden["present"] or hid_g or hid_p:
        parts.append(("hidden", hidden["f1"], 0.5))
    if circles["n_gt"] or circles["n_pred"]:
        parts.append(("circles", circles["match_f1"], 1.0))
    if arcs["n_gt"] or arcs["n_pred"]:
        parts.append(("arcs", arcs["match_f1"], 1.0))
    wsum = sum(w for _, _, w in parts)
    score = sum(v * w for _, v, w in parts) / wsum if wsum > 0 else 0.0
    return {"lines": lines, "hidden": hidden, "circles": circles, "arcs": arcs,
            "score": round(score, 4)}


def _match_circles(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag):
    """Hungarian match on aligned centers; matched if center<=eps AND radius rel err<=rtol.
    eps is size-normalised: EPS_CENTER_FRAC * gt_diag (min 0.5mm floor)."""
    eps = max(0.5, EPS_CENTER_FRAC * gt_diag)
    rtol = CIRCLE_RTOL
    pc = [(cx, cy, r) for cx, cy, r, layer in ent_pred["circles"] if "hidden" not in layer.lower()]
    gc = [(cx, cy, r) for cx, cy, r, layer in ent_gt["circles"] if "hidden" not in layer.lower()]
    n_p, n_g = len(pc), len(gc)
    if n_p == 0 and n_g == 0:
        return {"match_f1": 1.0, "matched": 0, "n_pred": 0, "n_gt": 0,
                "radius_mape": 0.0, "center_dist_mean_mm": None}
    if n_p == 0 or n_g == 0:
        return {"match_f1": 0.0, "matched": 0, "n_pred": n_p, "n_gt": n_g,
                "radius_mape": 0.0, "center_dist_mean_mm": None}
    pcen = transform_points(np.array([(x, y) for x, y, r in pc]), src_c, dst_c, scale)
    pradii = [abs(scale) * radius for _, _, radius in pc]
    cost = np.full((n_p, n_g), 1e6)
    cd = np.zeros((n_p, n_g))
    for i in range(n_p):
        for j in range(n_g):
            d = np.hypot(pcen[i][0] - gc[j][0], pcen[i][1] - gc[j][1])
            cd[i][j] = d
            rr = abs(pradii[i] - gc[j][2]) / gc[j][2] if gc[j][2] > 1e-9 else 1e6
            cost[i][j] = d + 100.0 * rr
    ri, ci = linear_sum_assignment(cost)
    matched, rerrs, cdists = 0, [], []
    for a, b in zip(ri, ci):
        if cd[a][b] <= eps:
            gr = gc[b][2]
            if gr > 1e-9 and abs(pradii[a] - gr) / gr <= rtol:
                matched += 1
                rerrs.append(abs(pradii[a] - gr) / gr)
                cdists.append(cd[a][b])
    prec, rec = matched / max(n_p, 1), matched / max(n_g, 1)
    f1 = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0
    return {"match_f1": round(f1, 4), "matched": matched, "n_pred": n_p, "n_gt": n_g,
            "radius_mape": round(float(np.mean(rerrs)), 6) if rerrs else 0.0,
            "center_dist_mean_mm": round(float(np.mean(cdists)), 4) if cdists else None}


def _match_arcs(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag):
    eps = max(0.5, EPS_CENTER_FRAC * gt_diag)
    rtol = ARC_RTOL
    pa = [(cx, cy, r, a1, a2) for cx, cy, r, a1, a2, layer in ent_pred["arcs"] if "hidden" not in layer.lower()]
    ga = [(cx, cy, r, a1, a2) for cx, cy, r, a1, a2, layer in ent_gt["arcs"] if "hidden" not in layer.lower()]
    n_p, n_g = len(pa), len(ga)
    if n_p == 0 and n_g == 0:
        return {"match_f1": 1.0, "matched": 0, "n_pred": 0, "n_gt": 0,
                "radius_mape": 0.0, "center_dist_mean_mm": None}
    if n_p == 0 or n_g == 0:
        return {"match_f1": 0.0, "matched": 0, "n_pred": n_p, "n_gt": n_g,
                "radius_mape": 0.0, "center_dist_mean_mm": None}
    pcen = transform_points(np.array([(x, y) for x, y, r, a1, a2 in pa]), src_c, dst_c, scale)
    pradii = [abs(scale) * radius for _, _, radius, _, _ in pa]
    cost = np.full((n_p, n_g), 1e6)
    cd = np.zeros((n_p, n_g))
    for i in range(n_p):
        for j in range(n_g):
            d = np.hypot(pcen[i][0] - ga[j][0], pcen[i][1] - ga[j][1])
            cd[i][j] = d
            rr = abs(pradii[i] - ga[j][2]) / ga[j][2] if ga[j][2] > 1e-9 else 1e6
            angle_quality = _arc_angle_quality(
                pa[i][3], pa[i][4], ga[j][3], ga[j][4]
            )
            cost[i][j] = d + 100.0 * rr + 100.0 * (1.0 - angle_quality)
    ri, ci = linear_sum_assignment(cost)
    matched, rerrs, cdists = 0, [], []
    for a, b in zip(ri, ci):
        if cd[a][b] <= eps:
            gr = ga[b][2]
            angle_quality = _arc_angle_quality(
                pa[a][3], pa[a][4], ga[b][3], ga[b][4]
            )
            if (
                gr > 1e-9
                and abs(pradii[a] - gr) / gr <= rtol
                and angle_quality >= ARC_ANGLE_IOU_MIN
            ):
                matched += 1
                rerrs.append(abs(pradii[a] - gr) / gr)
                cdists.append(cd[a][b])
    prec, rec = matched / max(n_p, 1), matched / max(n_g, 1)
    f1 = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0
    return {"match_f1": round(f1, 4), "matched": matched, "n_pred": n_p, "n_gt": n_g,
            "radius_mape": round(float(np.mean(rerrs)), 6) if rerrs else 0.0,
            "center_dist_mean_mm": round(float(np.mean(cdists)), 4) if cdists else None}


# ============================================================
# SECTION 4b — G (DENSE): continuous geometry reward for RL only
# ============================================================
# The metric above uses F1@tau / matched-F1 (threshold HITS). That is correct
# for REPORTING but gives a FLAT reward surface for RL: a vertex at 1.1% error
# and one at 5% error both score 0 until they cross tau, so the policy gets no
# gradient while "getting closer". Here we reward CONTINUOUS proximity so every
# mm of improvement is credited. The reported F1 metric is left unchanged; these
# functions are used ONLY by the RL reward plugin.
DENSE_SIGMA_FRAC = 0.02   # distance decay length = 2% of GT diagonal.
                          # Chosen so the reward gradient is strongest around the
                          # model's current line error (~2-9mm), giving signal both
                          # for fine (near tau) and coarse (several-mm) improvements.
DENSE_RADIUS_RHO = 0.05   # radius rel-err decay length for circles/arcs


def _dense_pr_f1(prec, rec):
    return float(2 * prec * rec / (prec + rec)) if (prec + rec) > 0 else 0.0


def _dense_lines(pred_lines, gt_lines, src_c, dst_c, scale, gt_diag):
    """Soft line score: instead of counting hits within tau, each point earns
    exp(-d/sigma) for its nearest neighbour. Soft precision/recall -> soft F1.
    Full credit at d=0, smoothly decaying, so improving d always raises reward."""
    pv = line_vertices(pred_lines)
    gv = line_vertices(gt_lines)
    if len(pv) == 0 and len(gv) == 0:
        return 1.0
    if len(pv) == 0 or len(gv) == 0:
        return 0.0
    pva = transform_points(pv, src_c, dst_c, scale)
    sigma = max(1e-6, DENSE_SIGMA_FRAC * (gt_diag if gt_diag > 1e-6 else 1.0))
    D = cdist(pva, gv)
    soft_prec = float(np.exp(-D.min(axis=1) / sigma).mean())  # pred -> gt
    soft_rec = float(np.exp(-D.min(axis=0) / sigma).mean())   # gt -> pred
    return _dense_pr_f1(soft_prec, soft_rec)


def _dense_circles(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag, key="circles"):
    """Soft matched-F1 for circles/arcs, including aligned radius and arc angle."""
    pred_raw = [e for e in ent_pred[key] if "hidden" not in e[-1].lower()]
    gt_raw = [e for e in ent_gt[key] if "hidden" not in e[-1].lower()]
    pc = [(e[0], e[1], e[2]) for e in pred_raw]
    gc = [(e[0], e[1], e[2]) for e in gt_raw]
    n_p, n_g = len(pc), len(gc)
    if n_p == 0 and n_g == 0:
        return 1.0
    if n_p == 0 or n_g == 0:
        return 0.0
    pcen = transform_points(np.array([(x, y) for x, y, r in pc]), src_c, dst_c, scale)
    pradii = [abs(scale) * radius for _, _, radius in pc]
    sigma = max(1e-6, DENSE_SIGMA_FRAC * (gt_diag if gt_diag > 1e-6 else 1.0))
    cost = np.zeros((n_p, n_g))
    qual = np.zeros((n_p, n_g))
    for i in range(n_p):
        for j in range(n_g):
            d = np.hypot(pcen[i][0] - gc[j][0], pcen[i][1] - gc[j][1])
            rr = abs(pradii[i] - gc[j][2]) / gc[j][2] if gc[j][2] > 1e-9 else 9.9
            q = np.exp(-d / sigma) * np.exp(-rr / DENSE_RADIUS_RHO)
            if key == "arcs":
                q *= _arc_angle_quality(
                    pred_raw[i][3], pred_raw[i][4], gt_raw[j][3], gt_raw[j][4]
                )
            qual[i][j] = q
            cost[i][j] = -q
    ri, ci = linear_sum_assignment(cost)
    got = float(sum(qual[a][b] for a, b in zip(ri, ci)))
    return _dense_pr_f1(got / n_p, got / n_g)


def dense_geometry_score(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag):
    """Continuous geometry score in [0,1] for RL reward (NOT the eval metric).
    Same family decomposition/weights as score_geometry, but every family uses
    a smooth distance-decay so the reward surface has a usable gradient."""
    vis_p = [l for l in ent_pred["lines"] if "hidden" not in l[-1].lower()]
    vis_g = [l for l in ent_gt["lines"] if "hidden" not in l[-1].lower()]
    hid_p = [l for l in ent_pred["lines"] if "hidden" in l[-1].lower()]
    hid_g = [l for l in ent_gt["lines"] if "hidden" in l[-1].lower()]

    parts = [("lines", _dense_lines(vis_p, vis_g, src_c, dst_c, scale, gt_diag), 1.0)]
    if hid_g or hid_p:
        parts.append(("hidden", _dense_lines(hid_p, hid_g, src_c, dst_c, scale, gt_diag), 0.5))
    if _has_family(ent_pred, ent_gt, "circles"):
        parts.append(("circles", _dense_circles(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag, "circles"), 1.0))
    if _has_family(ent_pred, ent_gt, "arcs"):
        parts.append(("arcs", _dense_circles(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag, "arcs"), 1.0))
    wsum = sum(w for _, _, w in parts)
    return float(sum(v * w for _, v, w in parts) / wsum) if wsum > 0 else 0.0


def _has_family(ent_pred, ent_gt, key):
    def vis(ents):
        return [e for e in ents if "hidden" not in e[-1].lower()]
    return bool(vis(ent_pred[key]) or vis(ent_gt[key]))


# ============================================================
# SECTION 5 — A: Annotation (dimension value + placement)
# ============================================================

def _dim_family_value(dim_tuple):
    """(family, value) for a parsed dim, preferring the TYPE flag over text glyphs.
    A radius label 'R21' and a diameter label '%%c42' on the same feature are made
    comparable by normalising both to the same 'measured length': radius*2 == diameter.
    We keep the raw value but expose a `normed` diameter-equivalent for equivalence."""
    dt, txt = dim_tuple[0], dim_tuple[1]
    tname = dim_type_name(dt)
    fam_txt, val, _ = parse_dim_value(txt)
    # trust the DXF dimtype family first; fall back to text-derived family
    family = tname if tname in ("linear", "aligned", "diameter", "radius") else fam_txt
    return family, val


def _values_equivalent(fam_p, val_p, fam_g, val_g):
    """True if two dims denote the same measurement within tolerance, treating
    radius<->diameter as equivalent (compare on diameter-equivalent length)."""
    if val_p is None or val_g is None:
        return False

    def dia_equiv(fam, v):
        return v * 2.0 if fam == "radius" else v

    # linear/aligned only compare to linear/aligned; circular compare to circular
    lin = {"linear", "aligned"}
    cir = {"diameter", "radius"}
    if fam_p in lin and fam_g in lin:
        a, b = val_p, val_g
    elif fam_p in cir and fam_g in cir:
        a, b = dia_equiv(fam_p, val_p), dia_equiv(fam_g, val_g)
    else:
        return False
    return abs(a - b) <= max(DIM_ABS_TOL, DIM_REL_TOL * abs(b))


def _match_dims_by_binding(ent_pred, ent_gt, src_c, dst_c, scale):
    """Hungarian 1-1 pairing of dims by aligned binding-point proximity."""
    pd, gd = ent_pred["dims"], ent_gt["dims"]
    if not pd or not gd:
        return []
    pb = transform_points(np.array([(d[5], d[6]) for d in pd]), src_c, dst_c, scale)
    gb = np.array([(d[5], d[6]) for d in gd])
    cost = cdist(pb, gb)
    ri, ci = linear_sum_assignment(cost)
    return [(int(a), int(b), float(cost[a][b])) for a, b in zip(ri, ci)]


def score_annotation(ent_pred, ent_gt, src_c, dst_c, scale):
    """标注正确性: value correctness (unit-normalised + tolerance + R/Ø equivalence)
    matched by binding geometry, plus placement distance for value-matched dims.
    Returns per-type recall + a single `score` in [0,1] (value F1)."""
    pd, gd = ent_pred["dims"], ent_gt["dims"]
    n_p, n_g = len(pd), len(gd)
    if n_p == 0 and n_g == 0:
        return {"score": 1.0, "value_f1": 1.0, "value_recall": 1.0, "value_precision": 1.0,
                "matched": 0, "n_pred": 0, "n_gt": 0, "by_type": {},
                "placement_mean_mm": 0.0, "n_placement": 0}
    pairs = _match_dims_by_binding(ent_pred, ent_gt, src_c, dst_c, scale)

    by_type = defaultdict(lambda: {"matched": 0, "gt": 0, "pred": 0})
    for d in gd:
        by_type[_dim_family_value(d)[0]]["gt"] += 1
    for d in pd:
        by_type[_dim_family_value(d)[0]]["pred"] += 1

    matched = 0
    place_dists = []
    for pi, gi, _bind in pairs:
        fam_p, val_p = _dim_family_value(pd[pi])
        fam_g, val_g = _dim_family_value(gd[gi])
        if _values_equivalent(fam_p, val_p, fam_g, val_g):
            matched += 1
            by_type[fam_g]["matched"] += 1
            # placement: defpoint distance after alignment (only for value-matched)
            pa = transform_points(np.array([[pd[pi][3], pd[pi][4]]]), src_c, dst_c, scale)[0]
            place_dists.append(float(np.hypot(pa[0] - gd[gi][3], pa[1] - gd[gi][4])))

    recall = matched / max(n_g, 1)
    precision = matched / max(n_p, 1)
    f1 = 2 * recall * precision / (recall + precision) if (recall + precision) > 0 else 0.0
    by_type_out = {t: {"recall": round(v["matched"] / v["gt"], 4) if v["gt"] else 1.0,
                       "matched": v["matched"], "gt": v["gt"], "pred": v["pred"]}
                   for t, v in by_type.items()}
    return {"score": round(f1, 4), "value_f1": round(f1, 4),
            "value_recall": round(recall, 4), "value_precision": round(precision, 4),
            "matched": matched, "n_pred": n_p, "n_gt": n_g, "by_type": by_type_out,
            "placement_mean_mm": round(float(np.mean(place_dists)), 4) if place_dists else 0.0,
            "n_placement": len(place_dists)}


# ============================================================
# SECTION 6 — per-sample overall + main
# ============================================================

def geometry_soft_gate(gs):
    """Soft gate in [GATE_FLOOR, 1] as a function of the geometry score.
    Used to make annotation credit conditional on geometry being correct,
    realising the progressive U -> G -> A relationship without hard-zeroing A."""
    return GATE_FLOOR + (1.0 - GATE_FLOOR) * max(0.0, min(1.0, gs))


def compute_overall(u, g, a):
    """Single end-to-end scalar in [0,1], progressively gated: U -> G -> A.
    Not usable            -> the usability ramp (<=0.25).
    Usable non-degenerate -> USABLE_BASE + (1-USABLE_BASE) * quality, where
        quality = (W_GEOM*G + W_ANNO * gate(G) * A) / (W_GEOM + W_ANNO)
    i.e. annotation is only credited to the extent geometry is correct.
    This is the value we recommend reusing directly as an RL reward."""
    if not u["all_ok"]:
        return round(u["score"], 4)
    gs = g["score"] if g is not None else 0.0
    a_s = a["score"] if a is not None else 0.0
    gated_a = geometry_soft_gate(gs) * a_s
    quality = (W_GEOM * gs + W_ANNO * gated_a) / (W_GEOM + W_ANNO)
    return round(USABLE_BASE + (1.0 - USABLE_BASE) * quality, 4)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--pred", required=True, help="predictions JSONL (infer_testset output)")
    ap.add_argument("--gt-dir", required=True, help="GT DXF directory (gt_dxf_test)")
    ap.add_argument("--pred-dxf-dir", default=None, help="where to write prediction DXFs")
    ap.add_argument("--out", required=True, help="per-sample scores JSONL")
    ap.add_argument("--summary", default=None, help="aggregate summary JSON")
    ap.add_argument("--timeout", type=int, default=30, help="code run timeout (s)")
    ap.add_argument("--limit", type=int, default=0)
    args = ap.parse_args()

    if args.pred_dxf_dir is None:
        args.pred_dxf_dir = args.pred.replace(".jsonl", "_dxf")
    os.makedirs(args.pred_dxf_dir, exist_ok=True)
    gt_dir = os.path.abspath(args.gt_dir)
    fout = open(args.out, "w", encoding="utf-8")

    # accumulators
    u_flags = Counter()
    u_scores, g_scores, a_scores, overalls = [], [], [], []
    g_lines, g_hidden, g_circ, g_arc = [], [], [], []
    # mm-accuracy accumulators (precision side of geometry)
    g_lines_nn, g_hidden_nn = [], []
    g_circ_cdist, g_circ_rmape = [], []
    g_arc_cdist, g_arc_rmape = [], []
    a_recalls, a_f1s = [], []
    a_by_type = defaultdict(lambda: {"recall_sum": 0.0, "count": 0})
    place_dists = []
    n_total = n_scored = 0

    for line in open(args.pred, encoding="utf-8"):
        line = line.strip()
        if not line:
            continue
        d = json.loads(line)
        pid = d.get("id", "unknown")
        n_total += 1
        if args.limit and n_total > args.limit:
            n_total -= 1
            break

        pred_code = d.get("prediction_code") or extract_code(d.get("prediction", ""))
        pred_dxf = os.path.join(args.pred_dxf_dir, f"{pid}_pred.dxf")
        if not os.path.isfile(pred_dxf):
            run_code_to_dxf(pred_code, pred_dxf, timeout=args.timeout)

        ent_pred = extract_entities(pred_dxf) if os.path.isfile(pred_dxf) else None
        gt_dxf = os.path.join(gt_dir, f"{pid}.dxf")
        ent_gt = extract_entities(gt_dxf) if os.path.isfile(gt_dxf) else None

        u = score_usability(pred_code, pred_dxf, ent_pred)
        for k in ("format_ok", "compile_ok", "run_ok", "dxf_readable", "non_degenerate", "all_ok"):
            if u[k]:
                u_flags[k] += 1
        u_scores.append(u["score"])

        sample = {"id": pid, "usability": u}
        g = a = None
        if ent_pred is not None and ent_gt is not None:
            n_scored += 1
            src_c, dst_c, scale = shared_alignment(ent_pred, ent_gt)
            gt_diag = bbox_diagonal(ent_gt)
            g = score_geometry(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag)
            a = score_annotation(ent_pred, ent_gt, src_c, dst_c, scale)
            sample["geometry"] = g
            sample["annotation"] = a
            g_scores.append(g["score"]); a_scores.append(a["score"])
            g_lines.append(g["lines"]["f1"])
            if g["lines"].get("nn_dist_mean_mm") is not None:
                g_lines_nn.append(g["lines"]["nn_dist_mean_mm"])
            if g["hidden"]["present"]:
                g_hidden.append(g["hidden"]["f1"])
                if g["hidden"].get("nn_dist_mean_mm") is not None:
                    g_hidden_nn.append(g["hidden"]["nn_dist_mean_mm"])
            if g["circles"]["n_gt"] or g["circles"]["n_pred"]:
                g_circ.append(g["circles"]["match_f1"])
                if g["circles"].get("center_dist_mean_mm") is not None:
                    g_circ_cdist.append(g["circles"]["center_dist_mean_mm"])
                if g["circles"]["matched"]:
                    g_circ_rmape.append(g["circles"]["radius_mape"])
            if g["arcs"]["n_gt"] or g["arcs"]["n_pred"]:
                g_arc.append(g["arcs"]["match_f1"])
                if g["arcs"].get("center_dist_mean_mm") is not None:
                    g_arc_cdist.append(g["arcs"]["center_dist_mean_mm"])
                if g["arcs"]["matched"]:
                    g_arc_rmape.append(g["arcs"]["radius_mape"])
            a_recalls.append(a["value_recall"]); a_f1s.append(a["value_f1"])
            for t, v in a["by_type"].items():
                a_by_type[t]["recall_sum"] += v["recall"]; a_by_type[t]["count"] += 1
            if a["n_placement"] > 0:
                place_dists.append(a["placement_mean_mm"])

        overall = compute_overall(u, g, a)
        sample["overall"] = overall
        overalls.append(overall)
        fout.write(json.dumps(sample, ensure_ascii=False) + "\n")

        status = "OK" if u["all_ok"] else "--"
        print(f"  [{n_total}] {pid} {status} | overall={overall:.3f} | "
              f"G={g['score'] if g else 'NA'} A={a['score'] if a else 'NA'}")

    fout.close()

    def mean(x):
        return round(float(np.mean(x)), 4) if x else None

    summary = {
        "n_total": n_total,
        "n_scored": n_scored,
        "overall_mean": mean(overalls),
        "Usability": {
            "pass_rates": {k: round(v / max(1, n_total), 4) for k, v in u_flags.items()},
            "score_mean": mean(u_scores),
        },
        "Geometry": {
            "score_mean": mean(g_scores),
            # hit-ratio side (F1@tau / matched-F1)
            "lines_f1_mean": mean(g_lines),
            "hidden_f1_mean": mean(g_hidden),
            "hidden_n_samples": len(g_hidden),
            "circle_match_f1_mean": mean(g_circ),
            "arc_match_f1_mean": mean(g_arc),
            # mm-accuracy side (precision): how far off matched geometry is
            "lines_nn_dist_mean_mm": mean(g_lines_nn),
            "hidden_nn_dist_mean_mm": mean(g_hidden_nn),
            "circle_center_dist_mean_mm": mean(g_circ_cdist),
            "circle_radius_mape_mean": mean(g_circ_rmape),
            "arc_center_dist_mean_mm": mean(g_arc_cdist),
            "arc_radius_mape_mean": mean(g_arc_rmape),
        },
        "Annotation": {
            "score_mean": mean(a_scores),
            "value_f1_mean": mean(a_f1s),
            "value_recall_mean": mean(a_recalls),
            "by_type": {t: {"recall_mean": round(v["recall_sum"] / max(1, v["count"]), 4),
                            "count": v["count"]} for t, v in a_by_type.items()},
            "placement_mean_mm": mean(place_dists),
            "placement_n_samples": len(place_dists),
        },
    }
    print("\n" + "=" * 60)
    print(json.dumps(summary, indent=2, ensure_ascii=False))
    if args.summary:
        with open(args.summary, "w", encoding="utf-8") as f:
            json.dump(summary, f, indent=2, ensure_ascii=False)
        print(f"\nsummary written to: {args.summary}")
    print(f"per-sample scores: {args.out}")


if __name__ == "__main__":
    main()