File size: 45,183 Bytes
0390c2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
"""
CAD-GUI Benchmark 统一评测引擎 (benchmark_evaluator.py)
========================================================
整合了项目中所有任务的评测逻辑,服务器上直接用这一个文件即可。

包含:
  1. 几何判定引擎(点/线[圆滑]/多边形/椭圆/避让区/拖拽起终点)
  2. 模型输出解析(point / bbox / action / 坐标 / 方向 / 输入内容)
  3. 坐标转换(0-1000 归一化 <-> 像素)
  4. 各任务评测:定位(Point/BBox) / 动作类型+参数 / 多步规划(Teacher Forcing)
  5. LLM-as-Judge 意图一致性判定

依赖: pip install shapely numpy scipy openai
"""
import json
import math
import re
import numpy as np
from shapely.geometry import Point, Polygon, LineString
from scipy.interpolate import splprep, splev

TOLERANCE = 5.0  # 像素容差(基于真实CAD鼠标点击物理容差)


# ============================================================
# 1. 几何判定引擎
# ============================================================
def smooth_trajectory(kps):
    """对 >=3 个点的轨迹做 B-spline 圆滑插值,返回 LineString。
    注意:标注点顺序必须沿曲线走向,否则会过冲/交叉。"""
    if len(kps) < 3:
        return LineString(kps)
    try:
        pts = np.array(kps)
        k = min(3, len(kps) - 1)
        tck, u = splprep([pts[:, 0], pts[:, 1]], s=0, k=k)
        u_new = np.linspace(0, 1, max(len(kps) * 10, 100))
        x_new, y_new = splev(u_new, tck)
        return LineString(list(zip(x_new.tolist(), y_new.tolist())))
    except Exception:
        return LineString(kps)


def is_point_in_ellipse(px, py, el):
    """判断点是否在旋转椭圆内"""
    cx, cy, rx, ry = el['cx'], el['cy'], el['rx'], el['ry']
    angle = math.radians(el.get('rotation', 0))
    cos_a, sin_a = math.cos(angle), math.sin(angle)
    dx, dy = px - cx, py - cy
    rx2 = cos_a * dx + sin_a * dy
    ry2 = -sin_a * dx + cos_a * dy
    if rx == 0 or ry == 0:
        return False
    return (rx2**2 / rx**2) + (ry2**2 / ry**2) <= 1


def hit_region(px, py, region, tol=TOLERANCE):
    """判断像素点 (px,py) 是否命中一个区域 (含 polygons/keypoints/ellipses/arc_trajectory)"""
    p = Point(px, py)
    for poly in region.get("polygons", []):
        if len(poly) >= 3 and Polygon(poly).buffer(tol).contains(p):
            return True
    for el in region.get("ellipses", []):
        if is_point_in_ellipse(px, py, el):
            return True
    kps = region.get("keypoints", [])
    if len(kps) == 1:
        if p.distance(Point(kps[0][0], kps[0][1])) <= tol:
            return True
    elif len(kps) >= 2:
        traj = smooth_trajectory(kps) if len(kps) >= 3 else LineString(kps)
        if traj.distance(p) <= tol:
            return True
    arc = region.get("arc_trajectory", [])
    if len(arc) >= 2:
        traj = smooth_trajectory(arc) if len(arc) >= 3 else LineString(arc)
        if traj.distance(p) <= tol:
            return True
    return False


def evaluate_prediction(px, py, ground_truth, tol=TOLERANCE):
    """核心判定:像素坐标是否命中目标且避开禁区。
    先判 exclude(命中即False),再判 include(命中即True)。"""
    exclude = ground_truth.get("exclude", {})
    if hit_region(px, py, exclude, tol):
        return False
    include = ground_truth.get("include", {})
    return hit_region(px, py, include, tol)


def compute_iou(box1, box2):
    """两个 bbox [xmin,ymin,xmax,ymax] 的 IoU"""
    x1, y1 = max(box1[0], box2[0]), max(box1[1], box2[1])
    x2, y2 = min(box1[2], box2[2]), min(box1[3], box2[3])
    inter = max(0, x2 - x1) * max(0, y2 - y1)
    a1 = (box1[2] - box1[0]) * (box1[3] - box1[1])
    a2 = (box2[2] - box2[0]) * (box2[3] - box2[1])
    union = a1 + a2 - inter
    return inter / union if union > 0 else 0


# ============================================================
# 2. 坐标转换
# ============================================================
def norm_to_pixel(nx, ny, w, h):
    """0-1000 归一化 -> 像素"""
    return nx / 1000.0 * w, ny / 1000.0 * h


def pixel_bbox_to_norm(bbox_pixels, resolution):
    """像素 bbox -> 0-1000 归一化(用于 IoU 评测时把 GT 转到归一化空间)"""
    w, h = resolution
    return [bbox_pixels[0]/w*1000, bbox_pixels[1]/h*1000,
            bbox_pixels[2]/w*1000, bbox_pixels[3]/h*1000]


def smart_resize(h, w, factor=28, min_pixels=3136, max_pixels=12845056):
    """Qwen2-VL/2.5-VL 的 smart_resize:返回 (resized_h, resized_w)。
    像素坐标模型(UI-Venus/Holo2/InfiGUI)输出的是 resize 后空间的像素,
    需按各模型的 min/max_pixels 反算回原图。"""
    import math
    h_bar = round(h / factor) * factor
    w_bar = round(w / factor) * factor
    if h_bar * w_bar > max_pixels:
        beta = math.sqrt((h * w) / max_pixels)
        h_bar = math.floor(h / beta / factor) * factor
        w_bar = math.floor(w / beta / factor) * factor
    elif h_bar * w_bar < min_pixels:
        beta = math.sqrt(min_pixels / (h * w))
        h_bar = math.ceil(h * beta / factor) * factor
        w_bar = math.ceil(w * beta / factor) * factor
    return h_bar, w_bar


# 各像素坐标模型的 smart_resize 参数(min_pixels, max_pixels)
SMART_RESIZE_PARAMS = {
    "ui-venus": (2000000, 4800000),   # 官方 README
    "holo2":    (3136, 12845056),     # Qwen2.5-VL 默认(Holo2 用默认 smart_resize)
    "infigui":  (3136, 12845056),     # 实测接近原图,用默认
    "ui-tars":  (3136, 12845056),     # UI-TARS-1.5: Qwen2.5-VL 默认 smart_resize,输出绝对像素
    "opencua":  (3136, 12845056),     # OpenCUA: Qwen2.5-VL 默认 smart_resize,输出绝对像素
}


# ============================================================
# 3. 模型输出解析
# ============================================================
def parse_point(text):
    """解析 'Point: [x, y]' 或任意 [x,y],返回 0-1000 范围的 [x,y] 或 None"""
    for m in re.findall(r'\[(\d+\.?\d*),\s*(\d+\.?\d*)\]', text):
        x, y = float(m[0]), float(m[1])
        if 0 <= x <= 1000 and 0 <= y <= 1000:
            return [x, y]
    return None


def parse_bbox(text):
    """解析 'Box: [xmin,ymin,xmax,ymax]',返回 0-1000 的 4 元组或 None"""
    for m in re.findall(r'\[(\d+\.?\d*),\s*(\d+\.?\d*),\s*(\d+\.?\d*),\s*(\d+\.?\d*)\]', text):
        v = [float(x) for x in m]
        if all(0 <= x <= 1000 for x in v):
            return v
    return None


def parse_action(text):
    """解析 'Action: xxx',返回小写动作名或 None"""
    m = re.search(r'Action:\s*([a-z_]+)', text, re.IGNORECASE)
    return m.group(1).strip().lower() if m else None


def parse_coords_list(text):
    """解析 Params 行里的所有 [x,y],返回列表(用于拖拽/框选的起终点)"""
    pm = re.search(r'Params:\s*(.*)', text, re.IGNORECASE | re.DOTALL)
    seg = pm.group(1) if pm else text
    return [[float(a), float(b)] for a, b in re.findall(r'\[(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\]', seg)]


def parse_direction(text):
    """解析方向,归一化为英文 (up/down/left/right/left_up/...)"""
    pm = re.search(r'Params:\s*(.*)', text, re.IGNORECASE)
    seg = (pm.group(1).lower() if pm else text.lower())
    for key in ['left_up', 'left_down', 'right_up', 'right_down',
                '向左上', '向右上', '向左下', '向右下',
                '上', '下', '左', '右', 'up', 'down', 'left', 'right']:
        if key in seg:
            return {'上': 'up', '下': 'down', '左': 'left', '右': 'right',
                    '向左上': 'left_up', '向右上': 'right_up',
                    '向左下': 'left_down', '向右下': 'right_down'}.get(key, key)
    return None


def parse_thought(text):
    """解析 'Thought: ...'(到 Action 之前)"""
    m = re.search(r'Thought:\s*(.*?)(?=Action:|$)', text, re.IGNORECASE | re.DOTALL)
    return m.group(1).strip() if m else ""


def parse_type_value(text):
    """解析 type_enter 的输入内容"""
    pm = re.search(r'Params:\s*(.*)', text, re.IGNORECASE)
    return pm.group(1).strip().strip('[]"\'') if pm else None


# ---- 专用模型坐标解析器(各模型原生输出格式不同)----
def parse_paren_point(text):
    """UGround: 输出 '(x, y)' 圆括号,0-1000。取最后一个括号对。"""
    ms = re.findall(r'\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\)', text)
    if ms:
        x, y = float(ms[-1][0]), float(ms[-1][1])
        return [x, y]
    return None


def parse_uitars_point(text):
    """UI-TARS: 'click(start_box='(x,y)')' 或 '(x,y)',0-1000。"""
    m = re.search(r"start_box\s*=\s*['\"]?\(?\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)", text)
    if m:
        return [float(m.group(1)), float(m.group(2))]
    return parse_paren_point(text)


def parse_osatlas_point(text):
    """OS-Atlas: 可能输出 '(x1,y1),(x2,y2)' 圆括号 或 '[[x1,y1,x2,y2]]' 方括号,0-1000。
    出框时取中心点;出点时直接用。会先复述指令文字,正则只抓坐标。"""
    # 先试方括号 bbox [[x1,y1,x2,y2]] 或 [x1,y1,x2,y2]
    m = re.search(r'\[+\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\]', text)
    if m:
        v = [float(m.group(i)) for i in range(1, 5)]
        return [(v[0]+v[2])/2, (v[1]+v[3])/2]
    # 再试圆括号点对
    pts = re.findall(r'\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\)', text)
    if len(pts) >= 2:
        return [(float(pts[0][0])+float(pts[1][0]))/2, (float(pts[0][1])+float(pts[1][1]))/2]
    if len(pts) == 1:
        return [float(pts[0][0]), float(pts[0][1])]
    # 最后试方括号点 [x,y]
    m2 = re.search(r'\[\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\]', text)
    if m2:
        return [float(m2.group(1)), float(m2.group(2))]
    return None


def parse_osatlas_bbox(text):
    """OS-Atlas 出框:支持 '[[x1,y1,x2,y2]]' 方括号 或 '(x1,y1),(x2,y2)' 圆括号,0-1000。"""
    m = re.search(r'\[+\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\]', text)
    if m:
        v = [float(m.group(i)) for i in range(1, 5)]
        return [min(v[0], v[2]), min(v[1], v[3]), max(v[0], v[2]), max(v[1], v[3])]
    pts = re.findall(r'\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\)', text)
    if len(pts) >= 2:
        x1, y1 = float(pts[0][0]), float(pts[0][1])
        x2, y2 = float(pts[1][0]), float(pts[1][1])
        return [min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)]
    return None


def parse_json_point(text):
    """InfiGUI-G1: 去掉<think>后 JSON [{"point_2d":[x,y]}];像素坐标。
    兼容 ```json 围栏与多候选(取第一个)。"""
    seg = text.split("</think>")[-1]
    seg = seg.replace("```json", "").replace("```", "")
    m = re.search(r'"point_2d"\s*:\s*\[\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\]', seg)
    if m:
        return [float(m.group(1)), float(m.group(2))]
    return None


def parse_click_absolute(text):
    """Holo2: JSON {"action":"click_absolute","x":..,"y":..};像素坐标。"""
    mx = re.search(r'"x"\s*:\s*(\d+\.?\d*)', text)
    my = re.search(r'"y"\s*:\s*(\d+\.?\d*)', text)
    if mx and my:
        return [float(mx.group(1)), float(my.group(1))]
    return None


def parse_uivenus_bbox(text):
    """UI-Venus: 输出 [x1,y1,x2,y2](smart_resize 像素),返回原始 4 元组。"""
    m = re.search(r'\[\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)\s*\]', text)
    if m:
        return [float(m.group(i)) for i in range(1, 5)]
    return None


def parse_uivenus_point(text):
    """UI-Venus: [x1,y1,x2,y2] -> 中心点(smart_resize 像素)。"""
    bb = parse_uivenus_bbox(text)
    if bb:
        return [(bb[0] + bb[2]) / 2, (bb[1] + bb[3]) / 2]
    return None


def parse_pyautogui_point(text):
    """OpenCUA: 'pyautogui.click(x=1443, y=343)',smart_resize 后绝对像素。
    兼容 click/moveTo/dragTo 等,取第一个 x=,y=。"""
    m = re.search(r'x\s*=\s*(\d+\.?\d*)\s*,\s*y\s*=\s*(\d+\.?\d*)', text)
    if m:
        return [float(m.group(1)), float(m.group(2))]
    return None


def parse_point_by_style(text, style):
    """按 parse_style 分发到对应解析器,统一返回原始数值对 [x,y] 或 None。
    范围/归一化由各模型 cfg 决定,这里只负责从文本里把数提出来。"""
    if style == "paren":
        return parse_paren_point(text)
    if style == "uitars":
        return parse_uitars_point(text)
    if style == "osatlas":
        return parse_osatlas_point(text)
    if style == "json_point":      # InfiGUI-G1
        return parse_json_point(text)
    if style == "click_absolute":  # Holo2
        return parse_click_absolute(text)
    if style == "uivenus":         # UI-Venus: bbox 中心点
        return parse_uivenus_point(text)
    if style == "pyautogui":       # OpenCUA: pyautogui.click(x=,y=)
        return parse_pyautogui_point(text)
    return parse_point(text)  # bracket 默认


def parse_bbox_by_style(text, style):
    """按 parse_style 分发 bbox 解析。"""
    if style == "osatlas":
        return parse_osatlas_bbox(text)
    if style == "uivenus":
        return parse_uivenus_bbox(text)
    return parse_bbox(text)  # bracket 默认


# ============================================================
# 4. 统一 Prompt 模板
# ============================================================
COORD_SYSTEM = """COORDINATE SYSTEM:
- (0, 0) = top-left corner of the image
- (1000, 1000) = bottom-right corner of the image
- Simply estimate the target's position as a percentage of image width/height, then multiply by 10.
- Do NOT assume any screen resolution (not 1920x1080, not 2560x1440)."""

PROMPT_POINT = """You are a GUI expert. Given a screenshot and an action intent about interacting with a specific UI element, you need to identify the click point (x, y) of the target element, normalized to 0-1000. Note that the X-axis runs horizontally from left (0) to right (999), and the Y-axis runs vertically from top (0) to bottom (999).
""" + COORD_SYSTEM + """
Action Intent: {instruction}
IMPORTANT: Output ONLY the result in the exact format below. Do NOT explain.
Output format:
Point: [x, y]"""

PROMPT_BBOX = """You are a GUI expert. Given a screenshot and an action intent, identify the bounding box [xmin, ymin, xmax, ymax] of the target element, normalized to 0-1000.
""" + COORD_SYSTEM + """
Action Intent: {instruction}
IMPORTANT: Output ONLY the result. Do NOT explain.
Output format:
Box: [xmin, ymin, xmax, ymax]"""

ACTION_SPACE = """Available actions:
- left_click [x,y]
- double_click [x,y]
- right_click [x,y]
- ctrl_click [x,y]
- drag [x1,y1] [x2,y2]
- box_select [x1,y1] [x2,y2]
- middle_drag [direction]        # rotate 3D view
- ctrl_middle_drag [direction]   # pan view
- shift_middle_drag [direction]  # zoom: up=zoom in, down=zoom out
- double_middle_click            # reset/fit view
- type_enter [text]
- press_esc
- press_delete"""

PROMPT_ACTION = """You are a SOLIDWORKS operation expert. Given a screenshot and a user's intent, decide the SINGLE next action.

""" + ACTION_SPACE + "\n\n" + COORD_SYSTEM + """

User intent: {instruction}

Output STRICTLY:
Action: <action_name>
Params: <[x,y] or [x1,y1] [x2,y2] or direction or text or NONE>"""

PROMPT_MULTISTEP = """You are a SOLIDWORKS expert doing a multi-step task.

High-level task: {high_level_instruction}

""" + ACTION_SPACE + "\n\n" + COORD_SYSTEM + """

History (already done correctly):
{history}

Based on the CURRENT screenshot, decide the NEXT step.
Output:
Thought: <what to do now and why>
Action: <action_name>
Params: <[x,y] or [x1,y1] [x2,y2] or text or NONE>"""


# ============================================================
# 5. 单步评测(支持 alternatives 多方案 / 各种动作类型)
# ============================================================
NEED_COORD = {"left_click", "double_click", "right_click", "ctrl_click"}
NEED_DRAG = {"drag", "box_select"}
NO_COORD = {"press_esc", "press_delete", "double_middle_click"}


def eval_one_alternative(pred_action, coords, type_text, gt, w, h):
    """判定模型输出是否匹配单个 GT 方案。返回 (action_ok, param_ok)"""
    gt_action = gt["action_type"]
    action_ok = (pred_action == gt_action)
    if not action_ok:
        return False, False

    if gt_action in NEED_COORD:
        if coords:
            px, py = norm_to_pixel(coords[0][0], coords[0][1], w, h)
            return True, evaluate_prediction(px, py, gt)
        return True, False
    elif gt_action in NEED_DRAG:
        if len(coords) >= 2:
            ps = norm_to_pixel(coords[0][0], coords[0][1], w, h)
            pe = norm_to_pixel(coords[1][0], coords[1][1], w, h)
            # 兼容4.4格式: drag_start/end 可能是 {"polygon":[[x,y],...]} 需转成 {"polygons":[[[x,y],...]]}
            ds = gt.get("drag_start") or {}
            de = gt.get("drag_end") or {}
            if "polygon" in ds and "polygons" not in ds:
                ds = {"polygons": [ds["polygon"]], "keypoints": [], "ellipses": []}
            if "polygon" in de and "polygons" not in de:
                de = {"polygons": [de["polygon"]], "keypoints": [], "ellipses": []}
            s_ok = hit_region(ps[0], ps[1], ds)
            e_ok = hit_region(pe[0], pe[1], de)
            return True, (s_ok and e_ok)
        return True, False
    elif gt_action == "type_enter":
        tv = gt.get("type_value", "")
        return True, (tv in (type_text or "")) if tv else True
    else:  # NO_COORD 或视图方向类
        if "direction" in gt:
            return True, True  # 方向需调用方单独判
        return True, True


def eval_step(reply, gt, w, h):
    """评测一步。支持 gt 带 alternatives(多等价方案,命中任一即对)。
    返回 dict: thought, action, action_ok, param_ok, step_ok"""
    thought = parse_thought(reply)
    action = parse_action(reply)
    coords = parse_coords_list(reply)
    type_text = parse_type_value(reply)
    direction = parse_direction(reply)

    alts = gt["alternatives"] if "alternatives" in gt else [gt]

    best = (False, False)
    for alt in alts:
        a_ok, p_ok = eval_one_alternative(action, coords, type_text, alt, w, h)
        # 方向类单独判
        if a_ok and "direction" in alt:
            p_ok = (direction == alt["direction"])
        if a_ok and p_ok:
            best = (True, True); break
        if a_ok and not best[0]:
            best = (True, False)
    action_ok, param_ok = best
    return {
        "thought": thought, "action": action,
        "action_ok": action_ok, "param_ok": param_ok,
        "step_ok": action_ok and param_ok,
    }


# ============================================================
# 6. LLM-as-Judge 意图一致性
# ============================================================
def judge_thought(client, gt_thought, pred_thought, high_instr, judge_model="qwen-plus"):
    """用 LLM 判断模型 thought 与 GT thought 语义是否一致。返回 True/False"""
    prompt = f"""你是评判员。在SolidWorks多步操作任务中,判断模型的"当前步骤意图"和标准答案意图是否在语义上一致(想做的事相同即可,措辞不同没关系)。

高层任务: {high_instr}
标准意图: {gt_thought}
模型意图: {pred_thought}

只回答一个词: 一致 或 不一致"""
    try:
        r = client.chat.completions.create(
            model=judge_model,
            messages=[{"role": "user", "content": prompt}],
            max_tokens=10, timeout=60)
        reply = (r.choices[0].message.content or "").strip().strip('"\'“”‘’。.!! \t\r\n')
        return reply == "一致"
    except Exception:
        return False


def attribute_verdict(action_ok, param_ok, intent_ok):
    """归因分类"""
    if action_ok and param_ok:
        return "完全正确"
    if action_ok and not param_ok and intent_ok:
        return "懂意图懂动作_点歪了"
    if action_ok and not param_ok and not intent_ok:
        return "动作蒙对_没真懂"
    if not action_ok and intent_ok:
        return "懂意图_动作选错"
    return "不懂该做什么"


# ============================================================
# 9. 分组统计与能力分级
# ============================================================
def grade(rate):
    """能力分级:掌握>70% / 部分30-70% / 缺失<30%"""
    if rate >= 70: return "掌握"
    if rate >= 30: return "部分"
    return "缺失"


def summarize_groups(results, groups):
    """按分组汇总定位结果。
    results: run_localization 返回的逐题列表(每条含 id/hits/tries,可选 avg_iou/acc50)
    groups: [(组名, set(id集合)), ...]
    返回每组的命中率、best-of-N、能力分级、(若有)平均IoU/Acc@0.5
    """
    by_id = {r["id"]: r for r in results}
    table = []
    for gname, ids in groups:
        grp = [by_id[i] for i in ids if i in by_id]
        if not grp:
            continue
        total_hits = sum(r["hits"] for r in grp)
        total_tries = sum(r["tries"] for r in grp)
        best_of_n = sum(1 for r in grp if r["hits"] > 0)
        hit_rate = total_hits / total_tries * 100 if total_tries else 0
        best_rate = best_of_n / len(grp) * 100 if grp else 0
        row = {
            "group": gname, "n_items": len(grp),
            "hit_rate": round(hit_rate, 1),
            "best_of_n_rate": round(best_rate, 1),
            "grade": grade(hit_rate),
        }
        ious = [r["avg_iou"] for r in grp if "avg_iou" in r]
        if ious:
            row["avg_iou"] = round(sum(ious)/len(ious), 4)
        acc50 = [r["acc50"] for r in grp if "acc50" in r]
        if acc50:
            row["acc50"] = round(sum(acc50)/len(acc50)*100, 1)
        table.append(row)
    return table


def make_groups_every_n(results, n=10):
    """便捷:每 n 个 id 一组,组名 Group1/Group2..."""
    ids = sorted(r["id"] for r in results)
    groups = []
    for g, start in enumerate(range(0, len(ids), n), 1):
        chunk = set(ids[start:start+n])
        groups.append((f"Group{g}", chunk))
    return groups


def make_groups_by_direction(results):
    """便捷:按 id 末位分'从左到右'(1-5)和'从右到左'(6-0)两组(任务3.1方位)"""
    l2r = {r["id"] for r in results if r["id"] % 10 in (1, 2, 3, 4, 5)}
    r2l = {r["id"] for r in results if r["id"] % 10 in (6, 7, 8, 9, 0)}
    return [("从左到右", l2r), ("从右到左", r2l)]


def print_group_table(table, title=""):
    """打印分组汇总表"""
    if title:
        print(f"\n{'='*70}\n=== {title} ===\n{'='*70}")
    header = f"{'组别':<18}{'题数':>5}{'命中率':>9}{'Best-of-N':>11}{'分级':>7}"
    has_iou = any("avg_iou" in r for r in table)
    if has_iou:
        header += f"{'Acc@0.5':>9}{'平均IoU':>9}"
    print(header)
    print("-" * len(header))
    for r in table:
        line = f"{r['group']:<18}{r['n_items']:>5}{r['hit_rate']:>8.1f}%{r['best_of_n_rate']:>10.1f}%{r['grade']:>7}"
        if has_iou and "avg_iou" in r:
            line += f"{r.get('acc50',0):>8.1f}%{r['avg_iou']:>9.4f}"
        print(line)


# ============================================================
# 10. 模型坐标格式适配(不同模型坐标约定不同)
# ============================================================
# 用法:根据模型名选择对应的解析+转换策略
MODEL_COORD_CONFIG = {
    # type: specialized=专用GUI模型(原生模板,不加CoT) / general=通用大模型(GUI expert prompt)
    # prompt: 用哪个模板  parse: 用哪个解析器  norm/order: 坐标转换
    # point_only: 只能出点(任务1/2的IoU列留空)
    "default":      {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy"},
    # ---- 专用 GUI 模型:各自原生模板 + 各自解析 ----
    # UI-TARS-1.5: 输出 smart_resize 后绝对像素坐标(不是0-1000!),需反算回原图
    "ui-tars":      {"type": "specialized", "prompt": "uitars",   "parse": "uitars",  "norm": "smart_resize", "resize": "ui-tars", "order": "xy", "point_only": True},
    # OS-Atlas: 输出 [[x1,y1,x2,y2]]方括号 或 (x1,y1),(x2,y2)圆括号 0-1000,会复述指令文字需大token
    "os-atlas":     {"type": "specialized", "prompt": "osatlas",  "parse": "osatlas", "norm": 1000, "order": "xy", "max_tokens": 640},
    "uground":      {"type": "specialized", "prompt": "uground",  "parse": "paren",   "norm": 1000, "order": "xy", "point_only": True},
    # OpenCUA: 官方system + pyautogui.click(x=,y=),smart_resize绝对像素(默认参数),point_only
    "opencua":      {"type": "specialized", "prompt": "opencua",  "parse": "pyautogui", "norm": "smart_resize", "resize": "opencua", "order": "xy", "system": "opencua", "point_only": True, "max_tokens": 512},
    # UI-Venus: 官方 prompt 出 [x1,y1,x2,y2],坐标在 smart_resize(min2M,max4.8M)像素空间,取中心点
    "ui-venus":     {"type": "specialized", "prompt": "uivenus",  "parse": "uivenus", "norm": "smart_resize", "resize": "ui-venus", "order": "xy"},
    "gui-owl":      {"type": "specialized", "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy"},
    # InfiGUI-G1: 像素坐标 + system prompt 告知分辨率 + <think> + JSON point_2d(实测≈原图像素)
    "infigui":      {"type": "specialized", "prompt": "infigui",  "parse": "json_point", "norm": "smart_resize", "resize": "infigui", "order": "xy", "system": "infigui", "point_only": True},
    # Holo2: 实测输出 0-1000 归一化(非smart_resize像素),JSON click_absolute,话痨需大max_tokens
    "holo2":        {"type": "specialized", "prompt": "holo2",    "parse": "click_absolute", "norm": 1000, "order": "xy", "point_only": True, "max_tokens": 640},
    # GELab-Zero(StepGUI): 0-999 归一化
    "gelab":        {"type": "specialized", "prompt": "point",    "parse": "bracket", "norm": 999, "order": "xy"},
    # ---- 通用大模型:统一 GUI expert prompt,thinking 模型自带 CoT ----
    "qwen3-vl":     {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy"},
    "glm-4.5v":     {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy"},
    "glm-4.6v":     {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy", "max_tokens": 1024},
    "glm-5v":       {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy", "max_tokens": 1024},
    "gpt-5":        {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy", "max_tokens": 2048},
    "claude":       {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy"},
    "o3":           {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy"},
    # Gemini: point 输出 xy(正常),但 bbox 是 [ymin,xmin,ymax,xmax] → bbox_order=yx
    "gemini-2.5":   {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy", "bbox_order": "yx", "max_tokens": 8192},
    "gemini":       {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": 1000, "order": "xy", "bbox_order": "yx", "max_tokens": 1024},
    # Qwen2.5-VL: 输出像素坐标,需告知真实分辨率,转换时 norm=None
    "qwen2.5-vl":   {"type": "general",     "prompt": "point",    "parse": "bracket", "norm": None, "order": "xy"},
}


def get_model_cfg(model_name):
    """按模型名(子串匹配)取配置,找不到用 default。"""
    key = model_name.lower()
    for name, cfg in MODEL_COORD_CONFIG.items():
        if name != "default" and name in key:
            return cfg
    return MODEL_COORD_CONFIG["default"]


def normalize_coord(coord, cfg, w, h):
    """根据模型配置把模型输出的坐标转成原图像素 [x,y]。
    coord: 模型输出的原始数值对; cfg: MODEL_COORD_CONFIG[xxx]
    norm 取值:
      - 数值(1000/999): 归一化基数, 坐标/norm*原图
      - "smart_resize": 输出是 resize 后像素, 按 cfg['resize'] 参数反算回原图
      - "pixel"/None: 已是原图像素, 直接用"""
    if cfg["order"] == "yx":
        coord = [coord[1], coord[0]]
    norm = cfg.get("norm")
    if isinstance(norm, (int, float)) and norm:
        return coord[0]/norm*w, coord[1]/norm*h
    if norm == "smart_resize":
        params = SMART_RESIZE_PARAMS.get(cfg.get("resize"), (3136, 12845056))
        rh, rw = smart_resize(h, w, min_pixels=params[0], max_pixels=params[1])
        return coord[0]/rw*w, coord[1]/rh*h
    return coord[0], coord[1]  # 已是原图像素(norm == "pixel" / None)


# ============================================================
# 12. 专用模型原生模板 + CoT 模板
# ============================================================
# UGround-V1:输出单个 "(x, y)" 0-1000(官方模板,末尾 Answer:)
PROMPT_UGROUND = """Your task is to help the user identify the precise coordinates (x, y) of a specific area/element/object on the screen based on a description.

- Your response should aim to point to the center or a representative point within the described area/element/object as accurately as possible.
- If the description is unclear or ambiguous, infer the most relevant area or element based on its likely context or purpose.
- Your answer should be a single string (x, y) corresponding to the point of the interest.

Description: {instruction}

Answer:"""

# OS-Atlas:输出 "<|box_start|>(x1,y1),(x2,y2)<|box_end|>" 0-1000,可出框/点
PROMPT_OSATLAS_POINT = """In the screenshot of this page, please give me the coordinates of the element I want to click on according to my instructions(with point).
"{instruction}\""""

# UI-TARS-1.5:grounding 模式,输出 click(start_box='(x,y)') 0-1000
PROMPT_UITARS = """Output only the coordinate of one point in your response. What element matches the following instruction: {instruction}"""

# InfiGUI-G1:像素坐标 + system prompt 告知分辨率 + <think> + JSON
# system prompt 与 user prompt 在 call 时分别传入
INFIGUI_SYSTEM = ('You FIRST think about the reasoning process as an internal monologue '
                  'and then provide the final answer.\n'
                  'The reasoning process MUST BE enclosed within <think> </think> tags.')
PROMPT_INFIGUI = ("The screen's resolution is {w}x{h}.\n"
                  'Locate the UI element(s) for "{instruction}", '
                  'output the coordinates using JSON format: [{{"point_2d": [x, y]}}, ...]')

# Holo2:像素坐标(smart_resize) + JSON click_absolute
PROMPT_HOLO2 = ('Localize an element on the GUI image according to the provided target '
                'and output a click position. You must output a valid JSON following the format: '
                '{{"action": "click_absolute", "x": <int px from left>, "y": <int px from top>}}\n'
                'Your target is: {instruction}')

# UI-Venus:官方 grounding prompt,输出 [x1,y1,x2,y2](smart_resize 像素空间)
PROMPT_UIVENUS = ('Outline the position corresponding to the instruction: {instruction}. '
                  'The output should be only [x1,y1,x2,y2].')

# OpenCUA:官方 system + 直接给 instruction,输出 pyautogui.click(x=,y=),smart_resize 绝对像素
OPENCUA_SYSTEM = ('You are a GUI agent. You are given a task and a screenshot of the screen. '
                  'You need to perform a series of pyautogui actions to complete the task.')
PROMPT_OPENCUA = "{instruction}"

# 任务1.3/2.3 CoT 对照(通用大模型)
PROMPT_POINT_COT = """You are a GUI expert. Analyze step by step.
""" + COORD_SYSTEM + """
Action Intent: {instruction}
Output:
Observation: <what you see relevant to the intent>
Reasoning: <which element to click and why>
Point: [x, y]"""


# ============================================================
# 11. 模型调用(OpenAI 兼容 API;本地部署模型用 vLLM/sglang 起 OpenAI server 即可)
# ============================================================
import base64
import os
import time


def encode_image(path):
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")


def call_vlm(client, model, image_path, prompt, max_tokens=300, retries=3, temperature=0.0, system=None):
    """调用多模态模型。client 为 openai.OpenAI 实例。
    temperature 默认 0.0:任务1/2 每题仅 1 次,必须确定性输出才可复现
    (UGround 等官方亦强调 temperature=0)。
    system: 可选 system prompt(InfiGUI-G1 等需要)。
    """
    b64 = encode_image(image_path)
    messages = []
    if system:
        messages.append({"role": "system", "content": system})
    messages.append({"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
        {"type": "text", "text": prompt}
    ]})
    # GPT-5 / o3 等推理模型:用 max_completion_tokens,且只支持默认 temperature
    is_reasoning = any(k in model.lower() for k in ("gpt-5", "o3", "o4"))
    for a in range(retries):
        try:
            kwargs = dict(model=model, messages=messages, timeout=120)
            if is_reasoning:
                kwargs["max_completion_tokens"] = max_tokens
            else:
                kwargs["max_tokens"] = max_tokens
                kwargs["temperature"] = temperature
            resp = client.chat.completions.create(**kwargs)
            return resp.choices[0].message.content or ""
        except Exception as e:
            if a < retries - 1:
                time.sleep(3)
            else:
                return f"API_ERROR: {e}"


SYSTEM_PROMPTS = {"infigui": INFIGUI_SYSTEM, "opencua": OPENCUA_SYSTEM}


# ============================================================
# 8. 任务级评测函数
# ============================================================
def build_localization_prompt(prompt_style, instruction, mode, cot=False, w=None, h=None):
    """按 prompt_style 选模板生成定位 prompt。
    prompt_style: point/uground/osatlas/uitars/infigui/holo2; mode: point/bbox; cot: 意图题用
    w/h: 像素模型(infigui)需要把分辨率写进 prompt"""
    if cot:
        return PROMPT_POINT_COT.format(instruction=instruction)
    if prompt_style == "uground":
        return PROMPT_UGROUND.format(instruction=instruction)
    if prompt_style == "osatlas":
        return PROMPT_OSATLAS_POINT.format(instruction=instruction)
    if prompt_style == "uitars":
        return PROMPT_UITARS.format(instruction=instruction)
    if prompt_style == "infigui":
        return PROMPT_INFIGUI.format(instruction=instruction, w=w, h=h)
    if prompt_style == "holo2":
        return PROMPT_HOLO2.format(instruction=instruction)
    if prompt_style == "uivenus":
        return PROMPT_UIVENUS.format(instruction=instruction)
    if prompt_style == "opencua":
        return PROMPT_OPENCUA.format(instruction=instruction)
    # 通用大模型 / 默认
    if mode == "bbox":
        return PROMPT_BBOX.format(instruction=instruction)
    return PROMPT_POINT.format(instruction=instruction)


def run_localization(client, model, benchmark_file, image_dir, tries=None,
                     mode="point", cfg=None, cot=False, max_tokens=None):
    """定位任务(任务1/2/3/4.1)。
    - cfg: MODEL_COORD_CONFIG 条目;None 时按 model 名自动取(含 prompt/parse/norm/order/point_only)
    - tries: 每题测试次数;None 时按数据规模自动(任务1/2 大数据集=1次,任务3/4=10次)
    - mode: 'point' 或 'bbox';point_only 模型强制 point
    - cot: 意图题(1.3/2.3) CoT 对照实验时置 True
    benchmark 既支持 bbox_pixels(任务1/2)也支持 ground_truth(任务3/4)格式。"""
    cfg = cfg or get_model_cfg(model)
    data = json.load(open(benchmark_file, "r", encoding="utf-8"))

    # point_only 模型不能出框:bbox 模式自动降级为 point(IoU 留空)
    if cfg.get("point_only") and mode == "bbox":
        mode = "point"
    # tries 默认:bbox_pixels 格式(任务1/2)每题1次,ground_truth 格式(任务3/4)每题10次
    if tries is None:
        tries = 1 if ("bbox_pixels" in data[0]) else 10
    # CoT 模式需要更长输出;专用话痨模型(如Holo2)可在cfg里指定 max_tokens
    if max_tokens is None:
        max_tokens = cfg.get("max_tokens", 512 if cot else 100)

    prompt_style = cfg.get("prompt", "point")
    parse_style = cfg.get("parse", "bracket")
    results = []
    consec_quota_err = 0  # 连续配额错误计数,达阈值则中止(避免余额耗尽后空跑)
    for item in data:
        img = os.path.join(image_dir, item["image_path"])
        w, h = item["image_resolution"]
        if "ground_truth" in item:
            gt = item["ground_truth"]
            gt_box_norm = None
        else:  # bbox_pixels 格式
            bp = item["bbox_pixels"]
            gt = {"include": {"polygons": [[[bp[0],bp[1]],[bp[2],bp[1]],[bp[2],bp[3]],[bp[0],bp[3]]]],
                              "keypoints": [], "ellipses": []},
                  "exclude": {"polygons": [], "keypoints": [], "ellipses": []}}
            gt_box_norm = pixel_bbox_to_norm(bp, item["image_resolution"])

        prompt = build_localization_prompt(prompt_style, item["instruction"], mode, cot, w, h)
        sys_prompt = SYSTEM_PROMPTS.get(cfg.get("system"))
        hits = 0
        ious = []
        parse_fail = 0
        trials = []
        for _ in range(tries):
            started_at = time.perf_counter()
            reply = call_vlm(client, model, img, prompt, max_tokens, system=sys_prompt)
            latency_s = round(time.perf_counter() - started_at, 4)
            # 配额耗尽保护:连续 20 次 429/quota 错误则中止整轮,避免空跑污染结果
            if isinstance(reply, str) and reply.startswith("API_ERROR") and \
               ("429" in reply or "quota" in reply.lower() or "insufficient" in reply.lower()):
                consec_quota_err += 1
                if consec_quota_err >= 20:
                    raise RuntimeError(
                        f"[配额耗尽中止] 连续{consec_quota_err}次429/quota错误,"
                        f"已完成的结果已落盘,请充值后重跑(断点续跑会跳过已完成)。")
            else:
                consec_quota_err = 0
            if mode == "point":
                pt = parse_point_by_style(reply, parse_style)
                if pt is None:
                    parse_fail += 1
                    trials.append({
                        "parse_ok": False,
                        "hit": False,
                        "latency_s": latency_s,
                    })
                    continue
                px, py = normalize_coord(pt, cfg, w, h)
                hit = evaluate_prediction(px, py, gt)
                if hit:
                    hits += 1
                trials.append({
                    "parse_ok": True,
                    "raw_point": [round(float(pt[0]), 4), round(float(pt[1]), 4)],
                    "point_px": [round(float(px), 4), round(float(py), 4)],
                    "hit": bool(hit),
                    "latency_s": latency_s,
                })
            else:  # bbox
                bb = parse_bbox_by_style(reply, parse_style)
                if bb is None:
                    parse_fail += 1
                    trials.append({
                        "parse_ok": False,
                        "latency_s": latency_s,
                    })
                    continue
                if gt_box_norm:
                    # 把模型 bbox 的两个角点经 normalize_coord 转成原图像素,
                    # 再转 0-1000 归一化(统一处理 yx 顺序 / smart_resize / 归一化基数)
                    # bbox 顺序可能与 point 不同(如 Gemini point=xy 但 bbox=yx),用 bbox_order 覆盖
                    bcfg = dict(cfg, order=cfg.get("bbox_order", cfg["order"]))
                    p1 = normalize_coord([bb[0], bb[1]], bcfg, w, h)
                    p2 = normalize_coord([bb[2], bb[3]], bcfg, w, h)
                    bb_norm = [p1[0]/w*1000, p1[1]/h*1000, p2[0]/w*1000, p2[1]/h*1000]
                    bb_norm = [min(bb_norm[0], bb_norm[2]), min(bb_norm[1], bb_norm[3]),
                               max(bb_norm[0], bb_norm[2]), max(bb_norm[1], bb_norm[3])]
                    iou = compute_iou(bb_norm, gt_box_norm)
                    ious.append(iou)
                    trials.append({
                        "parse_ok": True,
                        "raw_bbox": [round(float(value), 4) for value in bb],
                        "bbox_norm": [round(float(value), 4) for value in bb_norm],
                        "iou": round(float(iou), 6),
                        "latency_s": latency_s,
                    })
                else:
                    trials.append({
                        "parse_ok": True,
                        "raw_bbox": [round(float(value), 4) for value in bb],
                        "latency_s": latency_s,
                    })
        rec = {
            "id": item["id"],
            "hits": hits,
            "tries": tries,
            "parse_fail": parse_fail,
            "trials": trials,
        }
        if mode == "bbox" and ious:
            rec["avg_iou"] = sum(ious)/len(ious)
            rec["acc50"] = sum(1 for v in ious if v >= 0.5)/len(ious)
            rec["acc75"] = sum(1 for v in ious if v >= 0.75)/len(ious)
        results.append(rec)
    return results


def run_multistep(client, model, benchmark_file, image_base, judge_model="qwen-plus", judge_client=None):
    """多步规划评测(任务5),Teacher Forcing + 三层归因。
    image_base: 多步截图目录;支持数据中保存的相对路径或 record/raw_images 布局。"""
    judge_client = judge_client or client
    data = json.load(open(benchmark_file, "r", encoding="utf-8"))
    task_results = []
    for task in data:
        tid = task["task_id"]
        instr = task["high_level_instruction"]
        history = []
        step_results = []
        died_at = None
        for s in task["steps"]:
            rel_image = s["image_path"].replace("\\", "/")
            img = os.path.join(image_base, *rel_image.split("/"))
            if not os.path.exists(img):
                img = os.path.join(image_base, f"record_{tid:03d}", "raw_images", os.path.basename(rel_image))
            if not os.path.exists(img):
                img = os.path.join(image_base, *[part for part in rel_image.split("/") if part != "raw_images"])
            w, h = s["image_resolution"]
            gt = s["ground_truth"]
            hist_txt = "\n".join(history) if history else "(none, this is the first step)"
            prompt = PROMPT_MULTISTEP.format(high_level_instruction=instr, history=hist_txt)
            reply = call_vlm(client, model, img, prompt, 400)
            ev = eval_step(reply, gt, w, h)
            if ev["step_ok"]:
                verdict = "完全正确"; intent_ok = None
            elif "thought" in s:
                intent_ok = judge_thought(judge_client, s["thought"], ev["thought"], instr, judge_model)
                verdict = attribute_verdict(ev["action_ok"], ev["param_ok"], intent_ok)
            else:
                intent_ok = None
                verdict = "动作或参数错误"
            if not ev["step_ok"] and died_at is None:
                died_at = s["step"]
            step_results.append({"step": s["step"], "verdict": verdict, **ev, "intent_ok": intent_ok})
            history.append(f"Step {s['step']}: [action]{gt['action_type']}")
        correct = sum(1 for r in step_results if r["step_ok"])
        task_results.append({
            "task_id": tid, "total_steps": len(task["steps"]),
            "correct_steps": correct, "task_success": correct == len(task["steps"]),
            "died_at_step": died_at if died_at else "全对",
            "steps": step_results,
        })
    return task_results


# ============================================================
# 使用示例
# ============================================================
if __name__ == "__main__":
    from openai import OpenAI

    # 本地部署模型:用 vLLM / sglang 起一个 OpenAI 兼容 server
    # 例: python -m vllm.entrypoints.openai.api_server --model <path> --port 8000
    client = OpenAI(api_key="EMPTY", base_url="http://localhost:8000/v1")
    MODEL = "your-model-name"

    # 定位任务
    res = run_localization(client, MODEL,
                           "任务3.1基础任务.json", "任务3截图", tries=10, mode="point")
    total_hits = sum(r["hits"] for r in res)
    total_tries = sum(r["tries"] for r in res)
    print(f"命中率: {total_hits}/{total_tries} = {total_hits/total_tries*100:.1f}%")

    # 多步规划
    # task_res = run_multistep(client, MODEL, "任务5_多步规划.json", "dataset_records")
    # for t in task_res:
    #     print(f"Task{t['task_id']}: {'成功' if t['task_success'] else '失败'} "
    #           f"{t['correct_steps']}/{t['total_steps']} 死在第{t['died_at_step']}步")