File size: 4,739 Bytes
75ea5f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Compare action types, coordinates, numeric inputs, and control sequences."""

from decimal import Decimal, InvalidOperation
import json
import math
import re


TYPE_NUMBER_PATTERN = re.compile(
    r"[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)"
)


def numeric_type_signature(value):
    """Normalize numeric spelling while preserving all keyboard controls."""
    if not isinstance(value, str):
        return None
    normalized = value.replace("\r\n", "\n").replace("\r", "\n")
    matches = list(TYPE_NUMBER_PATTERN.finditer(normalized))
    if not matches:
        return None
    numbers = []
    separators = []
    cursor = 0
    try:
        for match in matches:
            separators.append(normalized[cursor:match.start()])
            number = Decimal(match.group(0))
            if not number.is_finite():
                return None
            numbers.append(number)
            cursor = match.end()
    except InvalidOperation:
        return None
    separators.append(normalized[cursor:])
    return tuple(numbers), tuple(separators)


def parameter_coordinates(value):
    """Decode a coordinate pair independently of the predicted action tag."""
    candidate = value
    if isinstance(candidate, str):
        try:
            candidate = json.loads(candidate.strip())
        except Exception:
            return None
    if not isinstance(candidate, (list, tuple)) or len(candidate) != 2:
        return None
    try:
        result = [float(candidate[0]), float(candidate[1])]
    except (TypeError, ValueError):
        return None
    if not all(math.isfinite(item) for item in result):
        return None
    return result


def compare_to_reference(generated, expected, record=None,
                         screen_size=(1920, 1080)):
    """Compare two parsed actions using the canonical CAD-Drawer protocol."""
    result = {
        "action_match": generated.action == expected.action,
        "parameter_match": False,
        "step_success": False,
        "full_match": False,
    }

    # Parameters use the reference action schema. Thus click and double_click
    # at the same target can have Parameter=1 while Action=0 and Step=0.
    if expected.action in ("click", "double_click"):
        generated_coordinates = parameter_coordinates(generated.parameters)
        if generated_coordinates is None:
            return result
        dx = generated_coordinates[0] - expected.parameters[0]
        dy = generated_coordinates[1] - expected.parameters[1]
        result["normalized_l2"] = round(math.hypot(dx, dy), 8)
        result["pixel_l2_at_1920x1080"] = round(math.hypot(
            dx * float(screen_size[0]), dy * float(screen_size[1])), 3)

        bounds = None
        if record is not None:
            values = [record.get(name) for name in (
                "x_min_norm", "x_max_norm", "y_min_norm", "y_max_norm")]
            if all(value is not None for value in values):
                bounds = [float(value) for value in values]
        if bounds is not None:
            x_min, x_max, y_min, y_max = bounds
            result["parameter_match"] = (
                x_min <= generated_coordinates[0] <= x_max and
                y_min <= generated_coordinates[1] <= y_max
            )
            result["target_bbox_norm"] = bounds
        else:
            result["parameter_match"] = math.hypot(
                dx * float(screen_size[0]),
                dy * float(screen_size[1]),
            ) <= 5.0
    elif expected.action == "type":
        generated_signature = numeric_type_signature(generated.parameters)
        expected_signature = numeric_type_signature(expected.parameters)
        if generated_signature is not None and expected_signature is not None:
            result["parameter_match"] = (
                generated_signature == expected_signature)
            result["parameter_match_mode"] = (
                "numeric_value_and_control_sequence")
        else:
            generated_text = (
                generated.parameters.replace("\r\n", "\n").replace("\r", "\n")
                if isinstance(generated.parameters, str) else None)
            expected_text = (
                expected.parameters.replace("\r\n", "\n").replace("\r", "\n")
                if isinstance(expected.parameters, str) else None)
            result["parameter_match"] = generated_text == expected_text
            result["parameter_match_mode"] = "exact_control_text"
    else:
        result["parameter_match"] = (
            generated.parameters == expected.parameters)

    result["step_success"] = (
        result["action_match"] and result["parameter_match"])
    result["full_match"] = result["step_success"]
    return result