forked from All-Hands-AI/OpenHands
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowsing.py
273 lines (220 loc) Β· 8.68 KB
/
browsing.py
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
##################################################################################################
# Adapted from https://github.com/TheAgentCompany/TheAgentCompany/blob/main/evaluation/browsing.py
##################################################################################################
import base64
import os
import re
from dataclasses import dataclass
from enum import Enum, auto
from typing import Dict, List, Optional, Union
from openhands.core.logger import openhands_logger as logger
from openhands.events.action import BrowseInteractiveAction
from openhands.events.observation import BrowserOutputObservation
from openhands.runtime.base import Runtime
class ActionType(Enum):
GOTO = auto()
FILL = auto()
CLICK = auto()
NOOP = auto()
@dataclass
class Selector:
"""
Represents either a direct anchor ID or a descriptive selector
"""
value: str
is_anchor: bool = False
def __str__(self) -> str:
return f'{self.value}'
@dataclass
class BrowserAction:
"""Base class for all browser actions"""
action_type: ActionType
def to_instruction(self) -> str:
"""Convert the action to a browser instruction string"""
raise NotImplementedError
@dataclass
class GotoAction(BrowserAction):
url: str
def __init__(self, url: str):
super().__init__(ActionType.GOTO)
self.url = url
def to_instruction(self) -> str:
return f'goto("{self.url}")'
@dataclass
class NoopAction(BrowserAction):
milliseconds: int
def __init__(self, milliseconds: int):
super().__init__(ActionType.NOOP)
self.milliseconds = milliseconds
def to_instruction(self) -> str:
return f'noop({self.milliseconds})'
@dataclass
class InputAction(BrowserAction):
selector: Selector
value: str
def __init__(self, selector: Union[str, Selector], value: str):
super().__init__(ActionType.FILL)
self.selector = (
selector if isinstance(selector, Selector) else Selector(selector)
)
self.value = value
def to_instruction(self) -> str:
return f'fill("{self.selector}", "{self.value}")'
@dataclass
class ClickAction(BrowserAction):
selector: Selector
def __init__(self, selector: Union[str, Selector]):
super().__init__(ActionType.CLICK)
self.selector = (
selector if isinstance(selector, Selector) else Selector(selector)
)
def to_instruction(self) -> str:
return f'click("{self.selector}")'
def parse_content_to_elements(content: str) -> Dict[str, str]:
"""Parse the observation content into a dictionary mapping anchors to their descriptions"""
elements = {}
current_anchor = None
description_lines = []
for line in content.split('\n'):
line = line.strip()
if not line:
continue
# Check for anchor line
anchor_match = re.match(r'\[(\d+)\](.*)', line)
if anchor_match:
# Save previous element if it exists
if current_anchor and description_lines:
elements[current_anchor] = ' '.join(description_lines)
# Start new element
current_anchor = anchor_match.group(1)
description_lines = [anchor_match.group(2).strip()]
else:
# Add to current description if we have an anchor
if current_anchor:
description_lines.append(line)
# Save last element
if current_anchor and description_lines:
elements[current_anchor] = ' '.join(description_lines)
return elements
def find_matching_anchor(content: str, selector: str) -> Optional[str]:
"""Find the anchor ID that matches the given selector description"""
elements = parse_content_to_elements(content)
# Clean up selector and create a pattern
selector = selector.lower().strip()
for anchor, description in elements.items():
description = description.lower().strip()
if selector in description:
return anchor
return None
def resolve_action(action: BrowserAction, content: str) -> BrowserAction:
"""
Resolve any descriptive selectors in the action to anchor IDs based on the content.
Returns a new action with resolved selectors.
"""
if isinstance(action, (InputAction, ClickAction)):
if not action.selector.is_anchor:
anchor = find_matching_anchor(content, action.selector.value)
if anchor:
new_selector = Selector(anchor, is_anchor=True)
if isinstance(action, InputAction):
return InputAction(new_selector, action.value)
else:
return ClickAction(new_selector)
else:
logger.error(f'NO MATCH FOUND FOR SELECTOR, {action.selector}')
return None
return action
def pre_login(
runtime: Runtime,
services: List[str],
save_screenshots=True,
screenshots_dir='screenshots',
):
"""
Logs in to all the websites that are needed for the evaluation.
Once logged in, the sessions would be cached in the browser, so OpenHands
agent doesn't need to log in to these websites again.
"""
owncloud_login_actions = [
GotoAction('http://the-agent-company.com:8092'),
NoopAction(1000),
InputAction("textbox '', clickable, focused, required", 'theagentcompany'),
NoopAction(1000),
InputAction("textbox '', clickable, required", 'theagentcompany'),
NoopAction(1000),
ClickAction("button '', clickable"),
NoopAction(1000),
]
rocketchat_login_actions = [
GotoAction('http://the-agent-company.com:3000'),
NoopAction(1000),
InputAction("textbox '', clickable, focused", 'theagentcompany'),
NoopAction(1000),
InputAction("textbox '', clickable", 'theagentcompany'),
NoopAction(1000),
ClickAction("button 'Login', clickable"),
]
gitlab_login_actions = [
GotoAction('http://the-agent-company.com:8929/users/sign_in'),
NoopAction(1000),
InputAction("textbox 'Username or primary email'", 'root'),
NoopAction(1000),
InputAction("textbox 'Password'", 'theagentcompany'),
NoopAction(1000),
ClickAction("button 'Sign in', clickable"),
]
# devnote: plane reset is not stable, and sometimes it fails to launch
# in which case the login action will fail, and then we would skip the task
plane_login_actions = [
GotoAction('http://the-agent-company.com:8091'),
NoopAction(1000),
InputAction(
"textbox 'Email', clickable, focused",
),
NoopAction(1000),
ClickAction("button 'Continue'"),
NoopAction(1000),
InputAction("textbox 'Enter password', clickable", 'theagentcompany'),
NoopAction(1000),
ClickAction("button 'Go to workspace'"),
]
all_login_actions = [
('owncloud', owncloud_login_actions),
('rocketchat', rocketchat_login_actions),
('gitlab', gitlab_login_actions),
('plane', plane_login_actions),
]
for website_name, login_actions in all_login_actions:
if website_name not in services:
logger.info(
f"Skipping login for {website_name} because it's not in the list of services to reset"
)
continue
if save_screenshots:
directory = os.path.join(screenshots_dir, website_name)
if not os.path.exists(directory):
os.makedirs(directory)
image_id = 0
obs: BrowserOutputObservation = None
for action in login_actions:
# Resolve any descriptive selectors to anchor IDs
if obs:
action = resolve_action(action, obs.get_agent_obs_text())
if not action:
logger.error(f'FAILED TO RESOLVE ACTION, {action}')
raise Exception(
'FAILED TO RESOLVE ACTION, maybe the service is not available'
)
# Convert the action to an instruction string
instruction = action.to_instruction()
browser_action = BrowseInteractiveAction(browser_actions=instruction)
browser_action.timeout = 10000
logger.info(browser_action, extra={'msg_type': 'ACTION'})
obs: BrowserOutputObservation = runtime.run_action(browser_action)
logger.debug(obs, extra={'msg_type': 'OBSERVATION'})
if save_screenshots:
image_data = base64.b64decode(obs.screenshot)
with open(os.path.join(directory, f'{image_id}.png'), 'wb') as file:
file.write(image_data)
image_id += 1