-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoverlay.py
More file actions
222 lines (184 loc) · 7.56 KB
/
Copy pathoverlay.py
File metadata and controls
222 lines (184 loc) · 7.56 KB
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
"""
Visual overlay utilities - show/clear element highlights in browser
"""
from typing import Any, Optional
from .browser import AsyncSentienceBrowser, SentienceBrowser
from .models import Element, Snapshot
def show_overlay(
browser: SentienceBrowser,
elements: list[Element] | list[dict[str, Any]] | Snapshot,
target_element_id: int | None = None,
) -> None:
"""
Display visual overlay highlighting elements in the browser
This function shows a Shadow DOM overlay with color-coded borders around
detected elements. Useful for debugging, learning, and validating element detection.
Args:
browser: SentienceBrowser instance
elements: Can be:
- List of Element objects (from snapshot.elements)
- List of raw element dicts (from snapshot result or API response)
- Snapshot object (will use snapshot.elements)
target_element_id: Optional ID of element to highlight in red (default: None)
Color Coding:
- Red: Target element (when target_element_id is specified)
- Blue: Primary elements (is_primary=true)
- Green: Regular interactive elements
Visual Indicators:
- Border thickness and opacity scale with importance score
- Semi-transparent fill for better visibility
- Importance badges showing scores
- Star icon for primary elements
- Target emoji for the target element
Auto-clear: Overlay automatically disappears after 5 seconds
Example:
# Show overlay from snapshot
snap = snapshot(browser)
show_overlay(browser, snap)
# Show overlay with custom elements
elements = [{"id": 1, "bbox": {"x": 100, "y": 100, "width": 200, "height": 50}, ...}]
show_overlay(browser, elements)
# Show overlay with target element highlighted in red
show_overlay(browser, snap, target_element_id=42)
# Clear overlay manually before 5 seconds
clear_overlay(browser)
"""
if not browser.page:
raise RuntimeError("Browser not started. Call browser.start() first.")
# Handle different input types
if isinstance(elements, Snapshot):
# Extract elements from Snapshot object
elements_list = [el.model_dump() for el in elements.elements]
elif isinstance(elements, list) and len(elements) > 0:
# Check if it's a list of Element objects or dicts
if hasattr(elements[0], "model_dump"):
# List of Element objects
elements_list = [el.model_dump() for el in elements]
else:
# Already a list of dicts
elements_list = elements
else:
raise ValueError("elements must be a Snapshot, list of Element objects, or list of dicts")
# Call extension API
browser.page.evaluate(
"""
(args) => {
if (window.sentience && window.sentience.showOverlay) {
window.sentience.showOverlay(args.elements, args.targetId);
} else {
console.warn('[Sentience SDK] showOverlay not available - is extension loaded?');
}
}
""",
{"elements": elements_list, "targetId": target_element_id},
)
def clear_overlay(browser: SentienceBrowser) -> None:
"""
Clear the visual overlay manually (before 5-second auto-clear)
Args:
browser: SentienceBrowser instance
Example:
show_overlay(browser, snap)
# ... inspect overlay ...
clear_overlay(browser) # Remove immediately
"""
if not browser.page:
raise RuntimeError("Browser not started. Call browser.start() first.")
browser.page.evaluate(
"""
() => {
if (window.sentience && window.sentience.clearOverlay) {
window.sentience.clearOverlay();
}
}
"""
)
async def show_overlay_async(
browser: AsyncSentienceBrowser,
elements: list[Element] | list[dict[str, Any]] | Snapshot,
target_element_id: int | None = None,
) -> None:
"""
Display visual overlay highlighting elements in the browser (async)
This function shows a Shadow DOM overlay with color-coded borders around
detected elements. Useful for debugging, learning, and validating element detection.
Args:
browser: AsyncSentienceBrowser instance
elements: Can be:
- List of Element objects (from snapshot.elements)
- List of raw element dicts (from snapshot result or API response)
- Snapshot object (will use snapshot.elements)
target_element_id: Optional ID of element to highlight in red (default: None)
Color Coding:
- Red: Target element (when target_element_id is specified)
- Blue: Primary elements (is_primary=true)
- Green: Regular interactive elements
Visual Indicators:
- Border thickness and opacity scale with importance score
- Semi-transparent fill for better visibility
- Importance badges showing scores
- Star icon for primary elements
- Target emoji for the target element
Auto-clear: Overlay automatically disappears after 5 seconds
Example:
# Show overlay from snapshot
snap = await snapshot_async(browser)
await show_overlay_async(browser, snap)
# Show overlay with custom elements
elements = [{"id": 1, "bbox": {"x": 100, "y": 100, "width": 200, "height": 50}, ...}]
await show_overlay_async(browser, elements)
# Show overlay with target element highlighted in red
await show_overlay_async(browser, snap, target_element_id=42)
# Clear overlay manually before 5 seconds
await clear_overlay_async(browser)
"""
if not browser.page:
raise RuntimeError("Browser not started. Call await browser.start() first.")
# Handle different input types
if isinstance(elements, Snapshot):
# Extract elements from Snapshot object
elements_list = [el.model_dump() for el in elements.elements]
elif isinstance(elements, list) and len(elements) > 0:
# Check if it's a list of Element objects or dicts
if hasattr(elements[0], "model_dump"):
# List of Element objects
elements_list = [el.model_dump() for el in elements]
else:
# Already a list of dicts
elements_list = elements
else:
raise ValueError("elements must be a Snapshot, list of Element objects, or list of dicts")
# Call extension API
await browser.page.evaluate(
"""
(args) => {
if (window.sentience && window.sentience.showOverlay) {
window.sentience.showOverlay(args.elements, args.targetId);
} else {
console.warn('[Sentience SDK] showOverlay not available - is extension loaded?');
}
}
""",
{"elements": elements_list, "targetId": target_element_id},
)
async def clear_overlay_async(browser: AsyncSentienceBrowser) -> None:
"""
Clear the visual overlay manually (before 5-second auto-clear) (async)
Args:
browser: AsyncSentienceBrowser instance
Example:
await show_overlay_async(browser, snap)
# ... inspect overlay ...
await clear_overlay_async(browser) # Remove immediately
"""
if not browser.page:
raise RuntimeError("Browser not started. Call await browser.start() first.")
await browser.page.evaluate(
"""
() => {
if (window.sentience && window.sentience.clearOverlay) {
window.sentience.clearOverlay();
}
}
"""
)