-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshow_grid_examples.py
More file actions
135 lines (116 loc) · 5.56 KB
/
show_grid_examples.py
File metadata and controls
135 lines (116 loc) · 5.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
"""
Example: Grid Overlay Visualization
Demonstrates how to use the grid overlay feature to visualize detected grids
on a webpage, including highlighting specific grids and identifying the dominant group.
"""
import os
import time
from sentience import SentienceBrowser, snapshot
from sentience.models import SnapshotOptions
def main():
# Get API key from environment variable (optional - uses free tier if not set)
api_key = os.environ.get("SENTIENCE_API_KEY")
# Use VPS IP directly if domain is not configured
# Replace with your actual domain once DNS is set up: api_url="https://api.sentienceapi.com"
api_url = os.environ.get("SENTIENCE_API_URL", "http://15.204.243.91:9000")
try:
with SentienceBrowser(api_key=api_key, api_url=api_url, headless=False) as browser:
# Navigate to a page with grid layouts (e.g., product listings, article feeds)
browser.page.goto("https://example.com", wait_until="domcontentloaded")
time.sleep(2) # Wait for page to fully load
print("=" * 60)
print("Example 1: Show all detected grids")
print("=" * 60)
# Show all grids (all in purple)
snap = snapshot(browser, SnapshotOptions(show_grid=True, use_api=True))
print(f"✅ Found {len(snap.elements)} elements")
print(" Purple borders appear around all detected grids for 5 seconds")
time.sleep(6) # Wait to see the overlay
print("\n" + "=" * 60)
print("Example 2: Highlight a specific grid in red")
print("=" * 60)
# Get grid information first
grids = snap.get_grid_bounds()
if grids:
print(f"✅ Found {len(grids)} grids:")
for grid in grids:
print(
f" Grid {grid.grid_id}: {grid.item_count} items, "
f"{grid.row_count}x{grid.col_count} rows/cols, "
f"label: {grid.label or 'none'}"
)
# Highlight the first grid in red
if len(grids) > 0:
target_grid_id = grids[0].grid_id
print(f"\n Highlighting Grid {target_grid_id} in red...")
snap = snapshot(
browser,
SnapshotOptions(
show_grid=True,
grid_id=target_grid_id, # This grid will be highlighted in red
),
)
time.sleep(6) # Wait to see the overlay
else:
print(" ⚠️ No grids detected on this page")
print("\n" + "=" * 60)
print("Example 3: Highlight the dominant group")
print("=" * 60)
# Find and highlight the dominant grid
grids = snap.get_grid_bounds()
dominant_grid = next((g for g in grids if g.is_dominant), None)
if dominant_grid:
print(f"✅ Dominant group detected: Grid {dominant_grid.grid_id}")
print(f" Label: {dominant_grid.label or 'none'}")
print(f" Items: {dominant_grid.item_count}")
print(f" Size: {dominant_grid.row_count}x{dominant_grid.col_count}")
print(f"\n Highlighting dominant grid in red...")
snap = snapshot(
browser,
SnapshotOptions(
show_grid=True,
grid_id=dominant_grid.grid_id, # Highlight dominant grid in red
),
)
time.sleep(6) # Wait to see the overlay
else:
print(" ⚠️ No dominant group detected")
print("\n" + "=" * 60)
print("Example 4: Combine element overlay and grid overlay")
print("=" * 60)
# Show both element borders and grid borders simultaneously
snap = snapshot(
browser,
SnapshotOptions(
show_overlay=True, # Show element borders (green/blue/red)
show_grid=True, # Show grid borders (purple/orange/red)
),
)
print("✅ Both overlays are now visible:")
print(" - Element borders: Green (regular), Blue (primary), Red (target)")
print(" - Grid borders: Purple (regular), Orange (dominant), Red (target)")
time.sleep(6) # Wait to see the overlay
print("\n" + "=" * 60)
print("Example 5: Grid information analysis")
print("=" * 60)
# Analyze grid structure
grids = snap.get_grid_bounds()
print(f"✅ Grid Analysis:")
for grid in grids:
dominant_indicator = "⭐ DOMINANT" if grid.is_dominant else ""
print(f"\n Grid {grid.grid_id} {dominant_indicator}:")
print(f" Label: {grid.label or 'none'}")
print(f" Items: {grid.item_count}")
print(f" Size: {grid.row_count} rows × {grid.col_count} cols")
print(
f" BBox: ({grid.bbox.x:.0f}, {grid.bbox.y:.0f}) "
f"{grid.bbox.width:.0f}×{grid.bbox.height:.0f}"
)
print(f" Confidence: {grid.confidence}")
print("\n✅ All examples completed!")
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()