File size: 5,633 Bytes
6b360d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""EvoCUA <-> GUI-LongDep action conversion. Standard library only.

EvoCUA writes each action as an ``Action:`` line followed by ``<tool_call>`` blocks of the
``computer_use`` function, with coordinates on a 0..999 grid of the screenshot.

  build_reply(step, width, height)       dataset step -> the EvoCUA reply stored as history
                                         (pixel -> grid: ``round(px / W * 999)``, clamped)
  to_actions(response, width, height)    raw EvoCUA reply -> pixel actions for ``score.py``
                                         (grid -> pixel: ``int(x * W / 999)``, the mapping the
                                         EvoCUA agent uses to execute its actions)

The reply parser and its key cleanup reproduce ``mm_agents/evocua/parsing.py`` of the
OSWorld-V2 EvoCUA agent (Apache-2.0), the code that executes EvoCUA's actions.

Use ``score.py --adapter evocua`` to score raw EvoCUA replies.
"""
from __future__ import annotations

import json

GRID_MAX = 999
THINK_END = "</think>"
_POINTER = frozenset({"left_click", "right_click", "middle_click", "double_click",
                      "triple_click", "mouse_move", "left_click_drag", "click"})
_EXECUTED = frozenset({"left_click", "click", "right_click", "middle_click", "double_click",
                       "triple_click", "type", "key", "key_down", "key_up", "scroll", "wait",
                       "terminate", "mouse_move", "left_click_drag"})


# --------------------------------------------------------------------------- #
# Dataset step -> EvoCUA history reply
# --------------------------------------------------------------------------- #
def to_grid(v: float, size: float) -> int:
    """Pixel -> EvoCUA 0..999 grid: ``round(v / size * 999)``, clamped."""
    return min(GRID_MAX, max(0, round(float(v) / float(size) * GRID_MAX)))


def build_reply(step: dict, width: int, height: int) -> str:
    """The EvoCUA-format reply of a recorded step (``Action:`` line + tool calls)."""
    blocks = []
    for a in step["actions"]:
        args = dict(a)
        if "coordinate" in args:
            x, y = args["coordinate"]
            args["coordinate"] = [to_grid(x, width), to_grid(y, height)]
        call = json.dumps({"name": "computer_use", "arguments": args}, ensure_ascii=False)
        blocks.append(f"<tool_call>\n{call}\n</tool_call>")
    return "\n".join([f"Action: {step['description']}"] + blocks)


# --------------------------------------------------------------------------- #
# Raw EvoCUA reply -> pixel actions
# --------------------------------------------------------------------------- #
def split_thinking(text):
    """(reasoning, answer); text up to the last ``</think>`` is reasoning."""
    text = text or ""
    if THINK_END in text:
        reasoning, _, answer = text.rpartition(THINK_END)
        return reasoning.replace("<think>", "").strip(), answer
    return "", text


def relative_to_pixels(x, y, width, height):
    """EvoCUA's relative mapping: 0..999 grid, ``int(x * W / 999)``, no clamping."""
    return int(x * (width / 999)), int(y * (height / 999))


def _point(v):
    try:
        return float(v[0]), float(v[1])
    except (TypeError, IndexError, ValueError, KeyError):
        return None


def extract_tool_calls(text):
    """Argument dicts of the tool calls the EvoCUA agent would process (None = malformed)."""
    _, answer = split_thinking(text or "")
    blocks, inside, cur = [], False, []
    for line in answer.split("\n"):
        line = line.strip()
        if not line or line.lower().startswith("action:"):
            continue
        if line.startswith("<tool_call>"):
            inside = True
            continue
        if line.startswith("</tool_call>"):
            if cur:
                blocks.append("\n".join(cur))
                cur = []
            inside = False
            continue
        if inside:
            cur.append(line)
            continue
        if line.startswith("{") and line.endswith("}"):
            try:
                obj = json.loads(line)
            except ValueError:
                continue
            if isinstance(obj, dict) and "name" in obj and "arguments" in obj:
                blocks.append(line)
    if cur:
        blocks.append("\n".join(cur))
    out = []
    for b in blocks:
        try:
            obj = json.loads(b)
            if obj.get("name") != "computer_use":
                raise ValueError("not computer_use")
            args = dict(obj["arguments"])
            str(args["action"])
        except (ValueError, KeyError, TypeError, AttributeError):
            out.append(None)
            continue
        out.append(args)
    return out


def parse_reply(text):
    """The executable tool calls of a raw EvoCUA reply (coordinates on the 0..999 grid)."""
    calls = []
    for a in extract_tool_calls(text):
        if a is None or str(a.get("action")) not in _EXECUTED:
            continue
        coord = a.get("coordinate")
        if "coordinate" in a and str(a["action"]) in _POINTER and _point(coord) is None:
            continue
        if "coordinate" in a and isinstance(coord, (list, tuple)) and len(coord) != 2:
            continue
        calls.append(a)
    return calls


def to_actions(response, width, height):
    """Pixel actions of a raw EvoCUA reply, in the dataset's action format."""
    out = []
    for a in parse_reply(response):
        a = dict(a)
        p = _point(a.get("coordinate")) if "coordinate" in a else None
        if p is not None:
            a["coordinate"] = list(relative_to_pixels(p[0], p[1], width, height))
        out.append(a)
    return out