-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.py
More file actions
280 lines (222 loc) Β· 9.46 KB
/
main.py
File metadata and controls
280 lines (222 loc) Β· 9.46 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
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
274
275
276
277
278
279
280
# VibeCheck - Stagehand-Powered Vibe Search on Google Maps
import sys
import os
import json
import asyncio
from dotenv import load_dotenv
from stagehand import Stagehand, StagehandConfig
from pydantic import BaseModel, Field
# Load environment variables
load_dotenv()
# ============= CLI PARSING =============
vibe = sys.argv[1] if len(sys.argv) > 1 else None
location = sys.argv[2] if len(sys.argv) > 2 else "San Francisco"
venue_type = sys.argv[3] if len(sys.argv) > 3 else None
if not vibe:
print('Usage: python main.py "<vibe>" "[location]" "[venue type]"')
print('Example: python main.py "sunset vibes" "San Francisco" "rooftop bar"')
print("\nLocation defaults to San Francisco if not provided.")
print("Venue type is fully optional (e.g., bar, restaurant, cafe, club, etc.)")
sys.exit(1)
# ============= PYDANTIC MODELS =============
class Venue(BaseModel):
name: str = Field(description="venue name")
address: str = Field(description="full address")
description: str = Field(description="venue description")
star_rating: str = Field(description="Google Maps star rating (e.g., '4.5')")
reviews: str = Field(description="Available individual reviews for the venue")
class VenuesData(BaseModel):
venues: list[Venue] = Field(description="list of venues from search results")
class VibeScore(BaseModel):
vibe_score: int
name: str
address: str
star_rating: str
review_summary: str
# ============= MAIN =============
async def main() -> None:
# ============= ASCII ART =============
print("\n")
print("\x1b[33mββββββββββββββββββββββββββββ")
print("ββββββββββββββββββββββββββββ")
print("βββββββββββββββββββ¦βββββββββ")
print("ββββββββββββββββββββββββββββ")
print("βββββββββββββββββββ¦βββββββββ")
print("ββββββββββββββββββββββββββββ\x1b[0m")
print("\n > Vibe........: " + vibe)
print(" > Location....: " + location)
if venue_type:
print(" > Venue Type..: " + venue_type)
print()
# ============= INITIALIZE STAGEHAND =============
print("\nπ
±οΈ Initializing Stagehand...\n")
config = StagehandConfig(
env="BROWSERBASE",
api_key=os.environ["BROWSERBASE_API_KEY"],
project_id=os.environ["BROWSERBASE_PROJECT_ID"],
model_name="openai/gpt-4.1",
model_api_key=os.environ["OPENAI_API_KEY"],
disable_api=True,
browserbase_session_create_params={
"project_id": os.environ["BROWSERBASE_PROJECT_ID"],
"browser_settings": {
# Viewport optimized for AI models
"viewport": {
"width": 1288,
"height": 711,
},
},
},
)
stagehand = Stagehand(config)
await stagehand.init()
print("\nπ
±οΈ Browser initialized...\n")
# Get session URL for debugging
session_id = stagehand.session_id
if session_id:
live_view_url = f"https://www.browserbase.com/sessions/{session_id}"
print(f"\nπ
±οΈ Live View: {live_view_url}\n")
# ============= STAGEHAND: OBSERVE - ACT - EXTRACT =============
# Get a page
page = stagehand.page
# Navigate to Google Maps
print("\nπ
±οΈ Navigating to Google Maps...\n")
await page.goto("https://www.google.com/maps")
# Build search query
search_query = (
f"{vibe} {venue_type + 's' if venue_type else 'venues'} in {location}"
)
print(f"\nπ
±οΈ Searching for: {search_query}\n")
# Search for venues - be very explicit and break down actions atomically
await page.act("click on the search box")
await page.act(f'type "{search_query}" into the search box')
await page.act("press Enter or click the search button")
await page.observe("make sure we can see the map search results")
print("\nπ
±οΈ Extracting venue data...\n")
# Extract venues with vibe scoring (note: extraction uses a11y tree, text only - no images)
venues_data = await page.extract(
"Extract all the venues you can from the search results.", schema=VenuesData
)
print("\nπ
±οΈ Venue data extracted:\n")
print(json.dumps(venues_data.model_dump(), indent=2))
# ============= STAGEHAND AGENT =============
print("\nπ
±οΈ Using agent to score venues...\n")
agent = stagehand.agent(
provider="google",
model="gemini-2.5-computer-use-preview-10-2025",
options={
"api_key": os.getenv("GEMINI_API_KEY"),
},
)
venue_type_filter = (
f"- Category/venue type (should be a {venue_type})" if venue_type else ""
)
scoring_instruction = f"""
For each venue, determine a vibe score of how well it matches the vibe "{vibe}" of either 1, 2, 3, 4, or 5.
Take into account:
- Venue name (does the name suggest this vibe?)
{venue_type_filter}
- Description text (does it mention relevant atmosphere or theme?)
- Review snippets (any keywords about ambiance/mood that fit the vibe?)
- Star rating (higher rated venues are better)
- Keywords (look for vibe-related words in any visible text)
Be generous with scoring. Do not search again. Use the data provided.
Data:
{json.dumps(venues_data.model_dump(), indent=2)}
Output as a JSON array, where each item has:
- vibe_score (number)
- name (string)
- address (string)
- star_rating (string)
- review_summary (string)
// Example:
[
{{
"vibe_score": 5,
"name": "Awesome Venue",
"address": "123 Sunset Blvd, San Francisco, CA",
"star_rating": "4.6",
"review_summary": "Beautiful views and great music."
}},
...
]
"""
result = await agent.execute(instruction=scoring_instruction, max_steps=30)
print("\nπ
±οΈ Closing browser...\n")
await stagehand.close()
# ============= PROCESS OUTPUT =============
# Extract JSON from the agent's response
output = result.message.strip()
# Find JSON between ```json and ``` markers
if "```json" in output:
start = output.find("```json") + 7
end = output.find("```", start)
output = output[start:end].strip()
# Or just find the JSON array
elif "[" in output and "]" in output:
start = output.find("[")
end = output.rfind("]") + 1
output = output[start:end]
vibe_scores_data = json.loads(output)
# Convert to VibeScore objects
vibe_scores = [VibeScore(**item) for item in vibe_scores_data]
print("\nπ
±οΈ Vibe scores:\n")
print(json.dumps([v.model_dump() for v in vibe_scores], indent=2))
# Sort by vibe score and take top 3
top_venues = sorted(vibe_scores, key=lambda x: x.vibe_score, reverse=True)[:3]
# ============= DISPLAY RESULTS =============
if top_venues and len(top_venues) > 0:
print("\n")
print(" β¦ β¦β¦ββ βββ")
print(" ββββββ β©βββ£")
print(" ββ β©ββββββ")
print(" ββββββββββββββββββββββ")
print(f" >> {len(venues_data.venues)} VIBES ANALYZED")
print(f" >> TOP 3 VIBES FOUND")
print(f" >> FOR VIBE: {vibe} in {location}")
print()
rank_labels = ["βββ PRIME VIBE", "ββ GOOD VIBE", "β VIBES"]
for index, venue in enumerate(top_venues):
rank = index + 1
print(f"\n ββ [{rank}] {rank_labels[index]}")
print(f" β")
print(f" β \x1b[1m\x1b[36m{venue.name}\x1b[0m")
print(f" β {venue.address}")
print(f" β")
# Visual bars
vibe_blocks = "β" * round(venue.vibe_score * 2) + "β" * (
10 - round(venue.vibe_score * 2)
)
rating_num = (
float(venue.star_rating)
if venue.star_rating and venue.star_rating.strip() not in ["", "null"]
else 0
)
rating_blocks = "β" * round(rating_num * 2) + "β" * (
10 - round(rating_num * 2)
)
display_rating = "n/a" if rating_num == 0 else rating_num
print(f" β VIBEΒ·Β·Β·Β· [{vibe_blocks}] {venue.vibe_score}")
print(f" β RATINGΒ·Β· [{rating_blocks}] {display_rating}")
print(f" β")
print(f' β "{venue.review_summary}"')
print(f" ββ")
print("\n β» Quick vibe check only - please vibe responsibly β»\n")
print(" β THANKS FOR VIBING! β")
else:
print("\n")
print(" β¦ β¦β¦ββ βββ")
print(" ββββββ β©βββ£")
print(" ββ β©ββββββ")
print(" ββββββββββββββββββββββ")
print("\n βββββββββββββββββββββββ")
print(" β NO VIBES FOUND β")
print(" β TRY DIFFERENT VIBE β")
print(" βββββββββββββββββββββββ\n")
# ============= ERROR HANDLING =============
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as err:
print(f"\nπ
±οΈ Error: {err}")
sys.exit(1)