Chrisyichuan commited on
Commit
0445e4c
Β·
1 Parent(s): 1300289

fix app.py and run agent loop

Browse files
Files changed (1) hide show
  1. app.py +82 -80
app.py CHANGED
@@ -127,22 +127,22 @@ with st.sidebar:
127
  # Add example URL and link
128
  example_url = "https://www.google.com/maps/@37.8728123,-122.2445339,3a,75y,3.36h,90t/data=!3m7!1e1!3m5!1s4DTABKOpCL6hdNRgnAHTgw!2e0!6shttps:%2F%2Fstreetviewpixels-pa.googleapis.com%2Fv1%2Fthumbnail%3Fcb_client%3Dmaps_sv.tactile%26w%3D900%26h%3D600%26pitch%3D0%26panoid%3D4DTABKOpCL6hdNRgnAHTgw%26yaw%3D3.3576431!7i13312!8i6656?entry=ttu"
129
 
130
- # Create columns for the example URL display
131
- example_col1, example_col2 = st.columns([4, 1])
132
 
133
- with example_col1:
134
- st.markdown(f"πŸ’‘ **Example Location:** [View in Google Maps]({example_url})")
 
 
 
135
 
136
- with example_col2:
137
- if st.button("πŸ“‹ Copy", key="copy_example", use_container_width=True):
138
- st.write(f'<script>navigator.clipboard.writeText("{example_url}")</script>', unsafe_allow_html=True)
139
- st.success("Copied!")
140
 
141
- # URL input
142
- google_url = st.text_input(
143
- "Google Maps URL",
144
- placeholder="https://www.google.com/maps/@37.5851338,-122.1519467,9z?entry=ttu"
145
- )
146
 
147
  if google_url:
148
  mapcrunch_url = convert_google_to_mapcrunch_url(google_url)
@@ -160,7 +160,7 @@ with st.sidebar:
160
  st.error("Invalid Google Maps URL format")
161
  st.stop()
162
  else:
163
- st.warning("Please enter a Google Maps URL")
164
  st.stop()
165
 
166
  model_choice = st.selectbox("Model", list(MODELS_CONFIG.keys()), index=list(MODELS_CONFIG.keys()).index(DEFAULT_MODEL))
@@ -188,7 +188,10 @@ if start_button:
188
  progress_bar = st.progress(0)
189
 
190
  with GeoBot(
191
- model=model_class, model_name=config["model_name"], headless=True, temperature=temperature
 
 
 
192
  ) as bot:
193
  for i, sample in enumerate(test_samples):
194
  st.divider()
@@ -203,103 +206,99 @@ if start_button:
203
 
204
  bot.controller.setup_clean_environment()
205
 
206
- # Create scrollable container for this sample
207
  sample_container = st.container()
208
 
209
- with sample_container:
210
- # Initialize step tracking
211
- history = bot.init_history()
212
- final_guess = None
213
 
214
- for step in range(steps_per_sample):
215
- step_num = step + 1
 
216
 
217
- # Create step container
218
- with st.container():
219
- st.subheader(f"Step {step_num}/{steps_per_sample}")
220
 
221
- # Take screenshot and show
222
- bot.controller.label_arrows_on_screen()
223
- screenshot_bytes = bot.controller.take_street_view_screenshot()
 
 
 
 
224
 
225
  col1, col2 = st.columns([1, 2])
226
 
227
  with col1:
 
228
  st.image(
229
- screenshot_bytes,
230
  caption=f"What AI sees - Step {step_num}",
231
  use_column_width=True,
232
  )
233
 
234
  with col2:
235
- # Get current screenshot as base64
236
- current_screenshot_b64 = bot.pil_to_base64(
237
- Image.open(BytesIO(screenshot_bytes))
238
- )
239
-
240
- available_actions = bot.controller.get_available_actions()
241
-
242
- # Show AI context
243
  st.write("**Available Actions:**")
244
- st.code(json.dumps(available_actions, indent=2))
 
 
245
 
246
- # Generate and display history
247
- history_text = bot.generate_history_text(history)
 
248
  st.write("**AI Context:**")
249
  st.text_area(
250
  "History",
251
  history_text,
252
  height=100,
253
  disabled=True,
254
- key=f"history_{i}_{step}",
255
  )
256
 
257
- # Force guess on last step or get AI decision
258
- if action != "GUESS":
259
- # Use the bot's agent step execution
260
- remaining_steps = steps_per_sample - step
261
- decision = bot.execute_agent_step(
262
- history, remaining_steps, current_screenshot_b64, available_actions
263
- )
264
-
265
- if decision is None:
266
- raise ValueError("Failed to get AI decision")
267
 
268
- action = decision["action_details"]["action"]
 
269
 
270
- # Show AI decision
271
  st.write("**AI Reasoning:**")
272
- st.info(decision.get("reasoning", "N/A"))
273
 
274
  st.write("**AI Action:**")
275
- st.success(f"`{action}`")
276
-
277
- # Show raw response for debugging
 
 
 
 
 
278
  with st.expander("Decision Details"):
279
- st.json(decision)
280
-
281
- # Add step to history using the bot's method
282
- bot.add_step_to_history(history, current_screenshot_b64, decision)
283
-
284
- # Execute action
285
- if action == "GUESS":
286
-
287
- lat = decision.get("action_details", {}).get("lat")
288
- lon = decision.get("action_details", {}).get("lon")
289
-
290
- if lat is not None and lon is not None:
291
- final_guess = (lat, lon)
292
- st.success(f"Final Guess: {lat:.4f}, {lon:.4f}")
293
- break
294
- else:
295
- # Use bot's execute_action method
296
- bot.execute_action(action)
297
-
298
- # Auto scroll to bottom
299
- st.empty() # Force refresh to show latest content
300
- time.sleep(1)
301
 
302
- # Sample Results
 
303
  st.subheader("Sample Result")
304
  true_coords = {"lat": sample.get("lat"), "lng": sample.get("lng")}
305
  distance_km = None
@@ -332,6 +331,9 @@ if start_button:
332
  {
333
  "sample_id": sample.get("id"),
334
  "model": model_choice,
 
 
 
335
  "true_coordinates": true_coords,
336
  "predicted_coordinates": final_guess,
337
  "distance_km": distance_km,
 
127
  # Add example URL and link
128
  example_url = "https://www.google.com/maps/@37.8728123,-122.2445339,3a,75y,3.36h,90t/data=!3m7!1e1!3m5!1s4DTABKOpCL6hdNRgnAHTgw!2e0!6shttps:%2F%2Fstreetviewpixels-pa.googleapis.com%2Fv1%2Fthumbnail%3Fcb_client%3Dmaps_sv.tactile%26w%3D900%26h%3D600%26pitch%3D0%26panoid%3D4DTABKOpCL6hdNRgnAHTgw%26yaw%3D3.3576431!7i13312!8i6656?entry=ttu"
129
 
130
+ # Create two columns for the URL input and paste button
131
+ url_col1, url_col2 = st.columns([3, 1])
132
 
133
+ with url_col1:
134
+ google_url = st.text_input(
135
+ "Google Maps URL",
136
+ placeholder="https://www.google.com/maps/@37.5851338,-122.1519467,9z?entry=ttu"
137
+ )
138
 
139
+ with url_col2:
140
+ if st.button("πŸ“‹ Paste Example", use_container_width=True):
141
+ google_url = example_url
142
+ st.experimental_rerun()
143
 
144
+ # Show the example link
145
+ st.markdown(f"πŸ’‘ **Example Location:** [View in Google Maps]({example_url})")
 
 
 
146
 
147
  if google_url:
148
  mapcrunch_url = convert_google_to_mapcrunch_url(google_url)
 
160
  st.error("Invalid Google Maps URL format")
161
  st.stop()
162
  else:
163
+ st.warning("Please enter a Google Maps URL or click 'Paste Example'")
164
  st.stop()
165
 
166
  model_choice = st.selectbox("Model", list(MODELS_CONFIG.keys()), index=list(MODELS_CONFIG.keys()).index(DEFAULT_MODEL))
 
188
  progress_bar = st.progress(0)
189
 
190
  with GeoBot(
191
+ model=model_class,
192
+ model_name=config["model_name"],
193
+ headless=True,
194
+ temperature=temperature,
195
  ) as bot:
196
  for i, sample in enumerate(test_samples):
197
  st.divider()
 
206
 
207
  bot.controller.setup_clean_environment()
208
 
209
+ # Create containers for UI updates
210
  sample_container = st.container()
211
 
212
+ # Initialize UI state for this sample
213
+ step_containers = {}
214
+ sample_steps_data = []
 
215
 
216
+ def ui_step_callback(step_info):
217
+ """Callback function to update UI after each step"""
218
+ step_num = step_info["step_num"]
219
 
220
+ # Store step data
221
+ sample_steps_data.append(step_info)
 
222
 
223
+ with sample_container:
224
+ # Create step container if it doesn't exist
225
+ if step_num not in step_containers:
226
+ step_containers[step_num] = st.container()
227
+
228
+ with step_containers[step_num]:
229
+ st.subheader(f"Step {step_num}/{step_info['max_steps']}")
230
 
231
  col1, col2 = st.columns([1, 2])
232
 
233
  with col1:
234
+ # Display screenshot
235
  st.image(
236
+ step_info["screenshot_bytes"],
237
  caption=f"What AI sees - Step {step_num}",
238
  use_column_width=True,
239
  )
240
 
241
  with col2:
242
+ # Show available actions
 
 
 
 
 
 
 
243
  st.write("**Available Actions:**")
244
+ st.code(
245
+ json.dumps(step_info["available_actions"], indent=2)
246
+ )
247
 
248
+ # Show history context - use the history from step_info
249
+ current_history = step_info.get("history", [])
250
+ history_text = bot.generate_history_text(current_history)
251
  st.write("**AI Context:**")
252
  st.text_area(
253
  "History",
254
  history_text,
255
  height=100,
256
  disabled=True,
257
+ key=f"history_{i}_{step_num}",
258
  )
259
 
260
+ # Show AI reasoning and action
261
+ action = step_info.get("action_details", {}).get(
262
+ "action", "N/A"
263
+ )
 
 
 
 
 
 
264
 
265
+ if step_info.get("is_final_step") and action != "GUESS":
266
+ st.warning("Max steps reached. Forcing GUESS.")
267
 
 
268
  st.write("**AI Reasoning:**")
269
+ st.info(step_info.get("reasoning", "N/A"))
270
 
271
  st.write("**AI Action:**")
272
+ if action == "GUESS":
273
+ lat = step_info.get("action_details", {}).get("lat")
274
+ lon = step_info.get("action_details", {}).get("lon")
275
+ st.success(f"`{action}` - {lat:.4f}, {lon:.4f}")
276
+ else:
277
+ st.success(f"`{action}`")
278
+
279
+ # Show decision details for debugging
280
  with st.expander("Decision Details"):
281
+ decision_data = {
282
+ "reasoning": step_info.get("reasoning"),
283
+ "action_details": step_info.get("action_details"),
284
+ "remaining_steps": step_info.get("remaining_steps"),
285
+ }
286
+ st.json(decision_data)
287
+
288
+ # Force UI refresh
289
+ time.sleep(0.5) # Small delay to ensure UI updates are visible
290
+
291
+ # Run the agent loop with UI callback
292
+ try:
293
+ final_guess = bot.run_agent_loop(
294
+ max_steps=steps_per_sample, step_callback=ui_step_callback
295
+ )
296
+ except Exception as e:
297
+ st.error(f"Error during agent execution: {e}")
298
+ final_guess = None
 
 
 
 
299
 
300
+ # Sample Results
301
+ with sample_container:
302
  st.subheader("Sample Result")
303
  true_coords = {"lat": sample.get("lat"), "lng": sample.get("lng")}
304
  distance_km = None
 
331
  {
332
  "sample_id": sample.get("id"),
333
  "model": model_choice,
334
+ "steps_taken": len(sample_steps_data),
335
+ "max_steps": steps_per_sample,
336
+ "temperature": temperature,
337
  "true_coordinates": true_coords,
338
  "predicted_coordinates": final_guess,
339
  "distance_km": distance_km,