LRU1 commited on
Commit
1a948ca
Β·
1 Parent(s): 772ca75

add test mode to huggingface UI

Browse files

add test mode

Update config.py

add test mode

add test mode

Files changed (5) hide show
  1. app.py +307 -207
  2. config.py +2 -2
  3. experiment_runner.py +0 -0
  4. geo_bot.py +165 -0
  5. mapcrunch_controller.py +10 -0
app.py CHANGED
@@ -2,6 +2,8 @@ import streamlit as st
2
  import json
3
  import os
4
  import time
 
 
5
  import re
6
  from pathlib import Path
7
 
@@ -67,7 +69,7 @@ with st.sidebar:
67
  st.header("Configuration")
68
 
69
  # Mode selection
70
- mode = st.radio("Mode", ["Dataset Mode", "Online Mode"], index=0)
71
 
72
  if mode == "Dataset Mode":
73
  # Get available datasets and ensure we have a valid default
@@ -114,6 +116,43 @@ with st.sidebar:
114
  num_samples = st.slider(
115
  "Samples to Test", 1, len(golden_labels), min(3, len(golden_labels))
116
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  else: # Online Mode
118
  st.info("Enter a URL to analyze a specific location")
119
 
@@ -211,221 +250,282 @@ with st.sidebar:
211
  help="Controls randomness in AI responses. 0.0 = deterministic, higher = more creative",
212
  )
213
 
 
214
  start_button = st.button("πŸš€ Start", type="primary")
215
 
216
  # Main Logic
217
  if start_button:
218
- test_samples = golden_labels[:num_samples]
219
- config = MODELS_CONFIG[model_choice]
220
- model_class = get_model_class(config["class"])
221
-
222
- benchmark_helper = MapGuesserBenchmark(
223
- dataset_name=dataset_choice if mode == "Dataset Mode" else "online"
224
- )
225
- all_results = []
226
-
227
- progress_bar = st.progress(0)
228
-
229
- with GeoBot(
230
- model=model_class,
231
- model_name=config["model_name"],
232
- headless=True,
233
- temperature=temperature,
234
- ) as bot:
235
- for i, sample in enumerate(test_samples):
236
- st.divider()
237
- st.header(f"Sample {i + 1}/{num_samples}")
238
-
239
- if mode == "Online Mode":
240
- # Load the MapCrunch URL directly
241
- bot.controller.load_url(sample["url"])
242
- else:
243
- # Load from dataset as before
244
- bot.controller.load_location_from_data(sample)
245
-
246
- bot.controller.setup_clean_environment()
247
-
248
- # Create containers for UI updates
249
- sample_container = st.container()
250
-
251
- # Initialize UI state for this sample
252
- step_containers = {}
253
- sample_steps_data = []
254
-
255
- def ui_step_callback(step_info):
256
- """Callback function to update UI after each step"""
257
- step_num = step_info["step_num"]
258
-
259
- # Store step data
260
- sample_steps_data.append(step_info)
261
 
262
- with sample_container:
263
- # Create step container if it doesn't exist
264
- if step_num not in step_containers:
265
- step_containers[step_num] = st.container()
266
-
267
- with step_containers[step_num]:
268
- st.subheader(f"Step {step_num}/{step_info['max_steps']}")
269
-
270
- col1, col2 = st.columns([1, 2])
271
-
272
- with col1:
273
- # Display screenshot
274
- st.image(
275
- step_info["screenshot_bytes"],
276
- caption=f"What AI sees - Step {step_num}",
277
- use_column_width=True,
278
- )
279
-
280
- with col2:
281
- # Show available actions
282
- st.write("**Available Actions:**")
283
- st.code(
284
- json.dumps(step_info["available_actions"], indent=2)
285
- )
286
-
287
- # Show history context - use the history from step_info
288
- current_history = step_info.get("history", [])
289
- history_text = bot.generate_history_text(current_history)
290
- st.write("**AI Context:**")
291
- st.text_area(
292
- "History",
293
- history_text,
294
- height=100,
295
- disabled=True,
296
- key=f"history_{i}_{step_num}",
297
- )
298
-
299
- # Show AI reasoning and action
300
- action = step_info.get("action_details", {}).get(
301
- "action", "N/A"
302
- )
303
-
304
- if step_info.get("is_final_step") and action != "GUESS":
305
- st.warning("Max steps reached. Forcing GUESS.")
306
-
307
- st.write("**AI Reasoning:**")
308
- st.info(step_info.get("reasoning", "N/A"))
309
- if step_info.get("debug_message") != "N/A":
310
- st.write("**AI Debug Message:**")
311
- st.code(step_info.get("debug_message"), language="json")
312
- st.write("**AI Action:**")
313
- if action == "GUESS":
314
- lat = step_info.get("action_details", {}).get("lat")
315
- lon = step_info.get("action_details", {}).get("lon")
316
- st.success(f"`{action}` - {lat:.4f}, {lon:.4f}")
317
- else:
318
- st.success(f"`{action}`")
319
-
320
- # Show decision details for debugging
321
- with st.expander("Decision Details"):
322
- decision_data = {
323
- "reasoning": step_info.get("reasoning"),
324
- "action_details": step_info.get("action_details"),
325
- "remaining_steps": step_info.get("remaining_steps"),
326
- }
327
- st.json(decision_data)
328
-
329
- # Force UI refresh
330
- time.sleep(0.5) # Small delay to ensure UI updates are visible
331
-
332
- # Run the agent loop with UI callback
333
- try:
334
- final_guess = bot.run_agent_loop(
335
- max_steps=steps_per_sample, step_callback=ui_step_callback
336
- )
337
- except Exception as e:
338
- st.error(f"Error during agent execution: {e}")
339
- final_guess = None
340
-
341
- # Sample Results
342
- with sample_container:
343
- st.subheader("Sample Result")
344
- true_coords = {"lat": sample.get("lat"), "lng": sample.get("lng")}
345
- distance_km = None
346
- is_success = False
347
-
348
- if final_guess:
349
- distance_km = benchmark_helper.calculate_distance(
350
- true_coords, final_guess
351
- )
352
- if distance_km is not None:
353
- is_success = distance_km <= SUCCESS_THRESHOLD_KM
354
 
355
- col1, col2, col3 = st.columns(3)
356
- col1.metric(
357
- "Final Guess", f"{final_guess[0]:.3f}, {final_guess[1]:.3f}"
358
- )
359
- col2.metric(
360
- "Ground Truth",
361
- f"{true_coords['lat']:.3f}, {true_coords['lng']:.3f}",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  )
363
- col3.metric(
364
- "Distance",
365
- f"{distance_km:.1f} km",
366
- delta="Success" if is_success else "Failed",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  )
368
- else:
369
- st.error("No final guess made")
370
-
371
- all_results.append(
372
- {
373
- "sample_id": sample.get("id"),
374
- "model": model_choice,
375
- "steps_taken": len(sample_steps_data),
376
- "max_steps": steps_per_sample,
377
- "temperature": temperature,
378
- "true_coordinates": true_coords,
379
- "predicted_coordinates": final_guess,
380
- "distance_km": distance_km,
381
- "success": is_success,
382
- }
383
- )
384
 
385
- progress_bar.progress((i + 1) / num_samples)
386
-
387
- # Final Summary
388
- st.divider()
389
- st.header("🏁 Final Results")
390
-
391
- # Calculate summary stats
392
- successes = [r for r in all_results if r["success"]]
393
- success_rate = len(successes) / len(all_results) if all_results else 0
394
-
395
- valid_distances = [
396
- r["distance_km"] for r in all_results if r["distance_km"] is not None
397
- ]
398
- avg_distance = sum(valid_distances) / len(valid_distances) if valid_distances else 0
399
-
400
- # Overall metrics
401
- col1, col2, col3 = st.columns(3)
402
- col1.metric("Success Rate", f"{success_rate * 100:.1f}%")
403
- col2.metric("Average Distance", f"{avg_distance:.1f} km")
404
- col3.metric("Total Samples", len(all_results))
405
-
406
- # Detailed results table
407
- st.subheader("Detailed Results")
408
- st.dataframe(all_results, use_container_width=True)
409
-
410
- # Success/failure breakdown
411
- if successes:
412
- st.subheader("βœ… Successful Samples")
413
- st.dataframe(successes, use_container_width=True)
414
-
415
- failures = [r for r in all_results if not r["success"]]
416
- if failures:
417
- st.subheader("❌ Failed Samples")
418
- st.dataframe(failures, use_container_width=True)
419
-
420
- # Export functionality
421
- if st.button("πŸ’Ύ Export Results"):
422
- results_json = json.dumps(all_results, indent=2)
423
- st.download_button(
424
- label="Download results.json",
425
- data=results_json,
426
- file_name=f"geo_results_{dataset_choice}_{model_choice}_{num_samples}samples.json",
427
- mime="application/json",
428
- )
429
 
430
 
431
  def handle_tab_completion():
 
2
  import json
3
  import os
4
  import time
5
+ import pandas as pd
6
+ import altair as alt
7
  import re
8
  from pathlib import Path
9
 
 
69
  st.header("Configuration")
70
 
71
  # Mode selection
72
+ mode = st.radio("Mode", ["Dataset Mode", "Online Mode", "Test Mode"], index=0)
73
 
74
  if mode == "Dataset Mode":
75
  # Get available datasets and ensure we have a valid default
 
116
  num_samples = st.slider(
117
  "Samples to Test", 1, len(golden_labels), min(3, len(golden_labels))
118
  )
119
+
120
+ elif mode == "Test Mode":
121
+ st.info("πŸ”¬ Multi-Model Benchmark Testing")
122
+ available_datasets = get_available_datasets()
123
+ dataset_choice = st.selectbox("Dataset", available_datasets, index=0)
124
+
125
+ selected_models = st.multiselect(
126
+ "Select Models to Compare",
127
+ list(MODELS_CONFIG.keys()),
128
+ default=[DEFAULT_MODEL],
129
+ )
130
+ if not selected_models:
131
+ st.warning("Please select at least one model to run the test.")
132
+ st.stop()
133
+
134
+ steps_per_sample = st.slider("Max Steps", 1, 50, 10)
135
+ temperature = st.slider(
136
+ "Temperature",
137
+ 0.0,
138
+ 2.0,
139
+ DEFAULT_TEMPERATURE,
140
+ 0.1,
141
+ help="Controls randomness in AI responses. 0.0 = deterministic, higher = more creative",
142
+ )
143
+
144
+ # load dataset
145
+ data_paths = get_data_paths(dataset_choice)
146
+ try:
147
+ with open(data_paths["golden_labels"], "r") as f:
148
+ golden_labels = json.load(f).get("samples", [])
149
+ st.success(f"Dataset '{dataset_choice}' loaded with {len(golden_labels)} samples")
150
+ except Exception as e:
151
+ st.error(f"Error loading dataset '{dataset_choice}': {str(e)}")
152
+ st.stop()
153
+ num_samples = st.slider("Samples per Run", 1, len(golden_labels), min(10, len(golden_labels)))
154
+ runs_per_model = st.slider("Runs per Model", 1, 10, 5)
155
+
156
  else: # Online Mode
157
  st.info("Enter a URL to analyze a specific location")
158
 
 
250
  help="Controls randomness in AI responses. 0.0 = deterministic, higher = more creative",
251
  )
252
 
253
+ # common start button
254
  start_button = st.button("πŸš€ Start", type="primary")
255
 
256
  # Main Logic
257
  if start_button:
258
+ if mode == "Test Mode":
259
+ benchmark_helper = MapGuesserBenchmark(dataset_name=dataset_choice)
260
+ summary_by_step = {}
261
+ progress_bar = st.progress(0)
262
+ for mi, model_name in enumerate(selected_models):
263
+ st.header(f"Model: {model_name}")
264
+ config = MODELS_CONFIG[model_name]
265
+ model_class = get_model_class(config["class"])
266
+
267
+ successes_per_step = [0]*steps_per_sample
268
+ total_iterations = runs_per_model * num_samples
269
+ model_bar = st.progress(0, text=f"Running {model_name}")
270
+ iteration_counter = 0
271
+ for run_idx in range(runs_per_model):
272
+ with GeoBot(model=model_class, model_name=config["model_name"], headless=True, temperature=temperature) as bot:
273
+ for si, sample in enumerate(golden_labels[:num_samples]):
274
+ if not bot.controller.load_location_from_data(sample):
275
+ iteration_counter += 1
276
+ model_bar.progress(iteration_counter/total_iterations)
277
+ continue
278
+ predictions = bot.test_run_agent_loop(max_steps=steps_per_sample)
279
+ true_coords = {"lat": sample["lat"], "lng": sample["lng"]}
280
+ for step_idx, pred in enumerate(predictions):
281
+ if isinstance(pred, dict) and "lat" in pred:
282
+ dist = benchmark_helper.calculate_distance(true_coords, (pred["lat"], pred["lon"]))
283
+ if dist is not None and dist <= SUCCESS_THRESHOLD_KM:
284
+ successes_per_step[step_idx] += 1
285
+ iteration_counter += 1
286
+ model_bar.progress(iteration_counter/total_iterations)
287
+ # calculate accuracy per step
288
+ acc_per_step = [s/(num_samples*runs_per_model) for s in successes_per_step]
289
+ summary_by_step[model_name] = acc_per_step
290
+ progress_bar.progress((mi+1)/len(selected_models))
291
+ # plot
292
+ st.subheader("Accuracy vs Steps")
293
+
294
+ # summary_by_step {model: [acc_step1, acc_step2, ...]}
295
+ df_wide = pd.DataFrame(summary_by_step)
296
+ df_long = (
297
+ df_wide
298
+ .reset_index(names="Step")
299
+ .melt(id_vars="Step", var_name="Model", value_name="Accuracy")
300
+ )
301
 
302
+ chart = (
303
+ alt.Chart(df_long)
304
+ .mark_line(point=True)
305
+ .encode(
306
+ x=alt.X("Step:O", title="Step #"),
307
+ y=alt.Y("Accuracy:Q", title="Accuracy", scale=alt.Scale(domain=[0, 1])),
308
+ color=alt.Color("Model:N", title="Model"),
309
+ tooltip=["Model:N", "Step:O", alt.Tooltip("Accuracy:Q", format=".2%")],
310
+ )
311
+ .properties(width=700, height=400)
312
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ st.altair_chart(chart, use_container_width=True)
315
+ st.stop()
316
+
317
+ else:
318
+ test_samples = golden_labels[:num_samples]
319
+ config = MODELS_CONFIG[model_choice]
320
+ model_class = get_model_class(config["class"])
321
+
322
+ benchmark_helper = MapGuesserBenchmark(
323
+ dataset_name=dataset_choice if mode == "Dataset Mode" else "online"
324
+ )
325
+ all_results = []
326
+
327
+ progress_bar = st.progress(0)
328
+
329
+ with GeoBot(
330
+ model=model_class,
331
+ model_name=config["model_name"],
332
+ headless=True,
333
+ temperature=temperature,
334
+ ) as bot:
335
+ for i, sample in enumerate(test_samples):
336
+ st.divider()
337
+ st.header(f"Sample {i + 1}/{num_samples}")
338
+
339
+ if mode == "Online Mode":
340
+ # Load the MapCrunch URL directly
341
+ bot.controller.load_url(sample["url"])
342
+ else:
343
+ # Load from dataset as before
344
+ bot.controller.load_location_from_data(sample)
345
+
346
+ bot.controller.setup_clean_environment()
347
+
348
+ # Create containers for UI updates
349
+ sample_container = st.container()
350
+
351
+ # Initialize UI state for this sample
352
+ step_containers = {}
353
+ sample_steps_data = []
354
+
355
+ def ui_step_callback(step_info):
356
+ """Callback function to update UI after each step"""
357
+ step_num = step_info["step_num"]
358
+
359
+ # Store step data
360
+ sample_steps_data.append(step_info)
361
+
362
+ with sample_container:
363
+ # Create step container if it doesn't exist
364
+ if step_num not in step_containers:
365
+ step_containers[step_num] = st.container()
366
+
367
+ with step_containers[step_num]:
368
+ st.subheader(f"Step {step_num}/{step_info['max_steps']}")
369
+
370
+ col1, col2 = st.columns([1, 2])
371
+
372
+ with col1:
373
+ # Display screenshot
374
+ st.image(
375
+ step_info["screenshot_bytes"],
376
+ caption=f"What AI sees - Step {step_num}",
377
+ use_column_width=True,
378
+ )
379
+
380
+ with col2:
381
+ # Show available actions
382
+ st.write("**Available Actions:**")
383
+ st.code(
384
+ json.dumps(step_info["available_actions"], indent=2)
385
+ )
386
+
387
+ # Show history context - use the history from step_info
388
+ current_history = step_info.get("history", [])
389
+ history_text = bot.generate_history_text(current_history)
390
+ st.write("**AI Context:**")
391
+ st.text_area(
392
+ "History",
393
+ history_text,
394
+ height=100,
395
+ disabled=True,
396
+ key=f"history_{i}_{step_num}",
397
+ )
398
+
399
+ # Show AI reasoning and action
400
+ action = step_info.get("action_details", {}).get(
401
+ "action", "N/A"
402
+ )
403
+
404
+ if step_info.get("is_final_step") and action != "GUESS":
405
+ st.warning("Max steps reached. Forcing GUESS.")
406
+
407
+ st.write("**AI Reasoning:**")
408
+ st.info(step_info.get("reasoning", "N/A"))
409
+ if step_info.get("debug_message") != "N/A":
410
+ st.write("**AI Debug Message:**")
411
+ st.code(step_info.get("debug_message"), language="json")
412
+ st.write("**AI Action:**")
413
+ if action == "GUESS":
414
+ lat = step_info.get("action_details", {}).get("lat")
415
+ lon = step_info.get("action_details", {}).get("lon")
416
+ st.success(f"`{action}` - {lat:.4f}, {lon:.4f}")
417
+ else:
418
+ st.success(f"`{action}`")
419
+
420
+ # Show decision details for debugging
421
+ with st.expander("Decision Details"):
422
+ decision_data = {
423
+ "reasoning": step_info.get("reasoning"),
424
+ "action_details": step_info.get("action_details"),
425
+ "remaining_steps": step_info.get("remaining_steps"),
426
+ }
427
+ st.json(decision_data)
428
+
429
+ # Force UI refresh
430
+ time.sleep(0.5) # Small delay to ensure UI updates are visible
431
+
432
+ # Run the agent loop with UI callback
433
+ try:
434
+ final_guess = bot.run_agent_loop(
435
+ max_steps=steps_per_sample, step_callback=ui_step_callback
436
  )
437
+ except Exception as e:
438
+ st.error(f"Error during agent execution: {e}")
439
+ final_guess = None
440
+
441
+ # Sample Results
442
+ with sample_container:
443
+ st.subheader("Sample Result")
444
+ true_coords = {"lat": sample.get("lat"), "lng": sample.get("lng")}
445
+ distance_km = None
446
+ is_success = False
447
+
448
+ if final_guess:
449
+ distance_km = benchmark_helper.calculate_distance(
450
+ true_coords, final_guess
451
+ )
452
+ if distance_km is not None:
453
+ is_success = distance_km <= SUCCESS_THRESHOLD_KM
454
+
455
+ col1, col2, col3 = st.columns(3)
456
+ col1.metric(
457
+ "Final Guess", f"{final_guess[0]:.3f}, {final_guess[1]:.3f}"
458
+ )
459
+ col2.metric(
460
+ "Ground Truth",
461
+ f"{true_coords['lat']:.3f}, {true_coords['lng']:.3f}",
462
+ )
463
+ col3.metric(
464
+ "Distance",
465
+ f"{distance_km:.1f} km",
466
+ delta="Success" if is_success else "Failed",
467
+ )
468
+ else:
469
+ st.error("No final guess made")
470
+
471
+ all_results.append(
472
+ {
473
+ "sample_id": sample.get("id"),
474
+ "model": model_choice,
475
+ "steps_taken": len(sample_steps_data),
476
+ "max_steps": steps_per_sample,
477
+ "temperature": temperature,
478
+ "true_coordinates": true_coords,
479
+ "predicted_coordinates": final_guess,
480
+ "distance_km": distance_km,
481
+ "success": is_success,
482
+ }
483
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484
 
485
+ progress_bar.progress((i + 1) / num_samples)
486
+
487
+ # Final Summary
488
+ st.divider()
489
+ st.header("🏁 Final Results")
490
+
491
+ # Calculate summary stats
492
+ successes = [r for r in all_results if r["success"]]
493
+ success_rate = len(successes) / len(all_results) if all_results else 0
494
+
495
+ valid_distances = [
496
+ r["distance_km"] for r in all_results if r["distance_km"] is not None
497
+ ]
498
+ avg_distance = sum(valid_distances) / len(valid_distances) if valid_distances else 0
499
+
500
+ # Overall metrics
501
+ col1, col2, col3 = st.columns(3)
502
+ col1.metric("Success Rate", f"{success_rate * 100:.1f}%")
503
+ col2.metric("Average Distance", f"{avg_distance:.1f} km")
504
+ col3.metric("Total Samples", len(all_results))
505
+
506
+ # Detailed results table
507
+ st.subheader("Detailed Results")
508
+ st.dataframe(all_results, use_container_width=True)
509
+
510
+ # Success/failure breakdown
511
+ if successes:
512
+ st.subheader("βœ… Successful Samples")
513
+ st.dataframe(successes, use_container_width=True)
514
+
515
+ failures = [r for r in all_results if not r["success"]]
516
+ if failures:
517
+ st.subheader("❌ Failed Samples")
518
+ st.dataframe(failures, use_container_width=True)
519
+
520
+ # Export functionality
521
+ if st.button("πŸ’Ύ Export Results"):
522
+ results_json = json.dumps(all_results, indent=2)
523
+ st.download_button(
524
+ label="Download results.json",
525
+ data=results_json,
526
+ file_name=f"geo_results_{dataset_choice}_{model_choice}_{num_samples}samples.json",
527
+ mime="application/json",
528
+ )
529
 
530
 
531
  def handle_tab_completion():
config.py CHANGED
@@ -38,12 +38,12 @@ DEFAULT_TEMPERATURE = 1.0
38
  # Model configurations
39
  MODELS_CONFIG = {
40
  "gpt-4o": {
41
- "class": "ChatOpenAI",
42
  "model_name": "gpt-4o",
43
  "description": "OpenAI GPT-4o",
44
  },
45
  "gpt-4o-mini": {
46
- "class": "ChatOpenAI",
47
  "model_name": "gpt-4o-mini",
48
  "description": "OpenAI GPT-4o Mini",
49
  },
 
38
  # Model configurations
39
  MODELS_CONFIG = {
40
  "gpt-4o": {
41
+ "class": "OpenRouter",
42
  "model_name": "gpt-4o",
43
  "description": "OpenAI GPT-4o",
44
  },
45
  "gpt-4o-mini": {
46
+ "class": "OpenRouter",
47
  "model_name": "gpt-4o-mini",
48
  "description": "OpenAI GPT-4o Mini",
49
  },
experiment_runner.py ADDED
File without changes
geo_bot.py CHANGED
@@ -69,6 +69,72 @@ Your response MUST be a valid JSON object wrapped in ```json ... ```.
69
  ```
70
  """
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  BENCHMARK_PROMPT = """
73
  Analyze the image and determine its geographic coordinates.
74
  1. Describe visual clues.
@@ -255,6 +321,49 @@ class GeoBot:
255
 
256
  return decision
257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  def execute_action(self, action: str) -> bool:
259
  """
260
  Execute the given action using the controller.
@@ -272,6 +381,62 @@ class GeoBot:
272
  self.controller.pan_view("right")
273
  return True
274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  def run_agent_loop(
276
  self, max_steps: int = 10, step_callback=None
277
  ) -> Optional[Tuple[float, float]]:
 
69
  ```
70
  """
71
 
72
+ TEST_AGENT_PROMPT_TEMPLATE = """
73
+ **Mission:** You are an expert geo-location agent. Your goal is to pinpoint our position based on the surroundings and your observation history.
74
+
75
+ **Current Status**
76
+ β€’ Actions You Can Take *this* turn: {available_actions}
77
+
78
+ ────────────────────────────────
79
+ **Core Principles**
80
+
81
+ 1. **Observe β†’ Orient β†’ Act**
82
+ Start each turn with a structured three-part reasoning block:
83
+ **(1) Visual Clues β€”** plainly describe what you see (signs, text language, road lines, vegetation, building styles, vehicles, terrain, weather, etc.).
84
+ **(2) Potential Regions β€”** list the most plausible regions/countries those clues suggest.
85
+ **(3) Most Probable + Plan β€”** pick the single likeliest region and explain the next action (move/pan or guess).
86
+
87
+ 2. **Navigate with Labels:**
88
+ - `MOVE_FORWARD` follows the green **UP** arrow.
89
+ - `MOVE_BACKWARD` follows the red **DOWN** arrow.
90
+ - No arrow β‡’ you cannot move that way.
91
+
92
+ 3. **Efficient Exploration:**
93
+ - **Pan Before You Move:** At fresh spots/intersections, use `PAN_LEFT` / `PAN_RIGHT` first.
94
+ - After ~2 or 3 fruitless moves in repetitive scenery, turn around.
95
+
96
+ 4. **Be Decisive:** A unique, definitive clue (full address, rare town name, etc.) β‡’ `GUESS` immediately.
97
+
98
+ 5. **Final-Step Rule:** If **Remaining Steps = 1**, you **MUST** `GUESS` and you should carefully check the image and the surroundings.
99
+
100
+ 6. **Always Predict:** On EVERY step, provide your current best estimate of the location, even if you're not ready to make a final guess.
101
+
102
+ ────────────────────────────────
103
+ **Context & Task:**
104
+ Analyze your full journey history and current view, apply the Core Principles, and decide your next action in the required JSON format.
105
+
106
+ **Action History**
107
+ {history_text}
108
+
109
+ ────────────────────────────────
110
+ **JSON Output Format:**
111
+ Your response MUST be a valid JSON object wrapped in ```json ... ```.
112
+ {{
113
+ "reasoning": "…",
114
+ "current_prediction": {{
115
+ "lat": <float>,
116
+ "lon": <float>,
117
+ "location_description": "Brief description of predicted location"
118
+ }},
119
+ "action_details": {{"action": action chosen from the available actions}}
120
+ }}
121
+ **Example **
122
+ ```json
123
+ {{
124
+ "reasoning": "(1) Visual Clues β€” I see left-side driving, eucalyptus trees, and a yellow speed-warning sign; the road markings are solid white. (2) Potential Regions β€” Southeastern Australia, Tasmania, or the North Island of New Zealand. (3) Most Probable + Plan β€” The scene most likely sits in a suburb of Hobart, Tasmania. I will PAN_LEFT to look for additional road signs that confirm this.",
125
+ "current_prediction": {{
126
+ "lat": -42.8806,
127
+ "lon": 147.3250,
128
+ "location_description": "Hobart suburb, Tasmania, Australia"
129
+ }},
130
+ "action_details": {{
131
+ "action": "PAN_LEFT"
132
+ }}
133
+ }}
134
+ ```
135
+
136
+ """
137
+
138
  BENCHMARK_PROMPT = """
139
  Analyze the image and determine its geographic coordinates.
140
  1. Describe visual clues.
 
321
 
322
  return decision
323
 
324
+ def execute_test_agent_step(
325
+ self,
326
+ history: List[Dict[str, Any]],
327
+ current_screenshot_b64: str,
328
+ available_actions: List[str],
329
+ ) -> Optional[Dict[str, Any]]:
330
+ """
331
+ Execute a single agent step: generate prompt, get AI decision, return decision.
332
+ This is the core step logic extracted for reuse.
333
+ """
334
+ history_text = self.generate_history_text(history)
335
+ image_b64_for_prompt = self.get_history_images(history) + [
336
+ current_screenshot_b64
337
+ ]
338
+
339
+ prompt = TEST_AGENT_PROMPT_TEMPLATE.format(
340
+ history_text=history_text,
341
+ available_actions=available_actions,
342
+ )
343
+
344
+ try:
345
+ message = self._create_message_with_history(
346
+ prompt, image_b64_for_prompt[-1:]
347
+ )
348
+ response = self.model.invoke(message)
349
+ decision = self._parse_agent_response(response)
350
+ except Exception as e:
351
+ print(f"Error during model invocation: {e}")
352
+ decision = None
353
+
354
+ if not decision:
355
+ print(
356
+ "Response parsing failed or model error. Using default recovery action: PAN_RIGHT."
357
+ )
358
+ decision = {
359
+ "reasoning": "Recovery due to parsing failure or model error.",
360
+ "action_details": {"action": "PAN_RIGHT"},
361
+ "current_prediction": "N/A",
362
+ "debug_message": f"{response.content.strip()}",
363
+ }
364
+
365
+ return decision
366
+
367
  def execute_action(self, action: str) -> bool:
368
  """
369
  Execute the given action using the controller.
 
381
  self.controller.pan_view("right")
382
  return True
383
 
384
+ def test_run_agent_loop(self, max_steps: int = 10, step_callback=None) -> Optional[list[Tuple[float, float]]]:
385
+ history = self.init_history()
386
+ predictions = []
387
+ for step in range(max_steps, 0, -1):
388
+ # Setup and screenshot
389
+ self.controller.setup_clean_environment()
390
+ self.controller.label_arrows_on_screen()
391
+
392
+ screenshot_bytes = self.controller.take_street_view_screenshot()
393
+ if not screenshot_bytes:
394
+ print("Failed to take screenshot. Ending agent loop.")
395
+ return None
396
+
397
+ current_screenshot_b64 = self.pil_to_base64(
398
+ image=Image.open(BytesIO(screenshot_bytes))
399
+ )
400
+ available_actions = self.controller.get_test_available_actions()
401
+ print(f"Available actions: {available_actions}")
402
+
403
+
404
+ # Normal step execution
405
+ decision = self.execute_test_agent_step(
406
+ history, current_screenshot_b64, available_actions
407
+ )
408
+
409
+ # Create step_info with current history BEFORE adding current step
410
+ # This shows the history up to (but not including) the current step
411
+ step_info = {
412
+ "max_steps": max_steps,
413
+ "remaining_steps": step,
414
+ "screenshot_bytes": screenshot_bytes,
415
+ "screenshot_b64": current_screenshot_b64,
416
+ "available_actions": available_actions,
417
+ "is_final_step": step == 1,
418
+ "reasoning": decision.get("reasoning", "N/A"),
419
+ "action_details": decision.get("action_details", {"action": "N/A"}),
420
+ "history": history.copy(), # History up to current step (excluding current)
421
+ "debug_message": decision.get("debug_message", "N/A"),
422
+ "current_prediction": decision.get("current_prediction", "N/A"),
423
+ }
424
+
425
+ action_details = decision.get("action_details", {})
426
+ action = action_details.get("action")
427
+ print(f"AI Reasoning: {decision.get('reasoning', 'N/A')}")
428
+ print(f"AI Current Prediction: {decision.get('current_prediction', 'N/A')}")
429
+ print(f"AI Action: {action}")
430
+
431
+
432
+ # Add step to history AFTER callback (so next iteration has this step in history)
433
+ self.add_step_to_history(history, current_screenshot_b64, decision)
434
+
435
+ predictions.append(decision.get("current_prediction", "N/A"))
436
+ self.execute_action(action)
437
+
438
+ return predictions
439
+
440
  def run_agent_loop(
441
  self, max_steps: int = 10, step_callback=None
442
  ) -> Optional[Tuple[float, float]]:
mapcrunch_controller.py CHANGED
@@ -214,6 +214,16 @@ class MapCrunchController:
214
  base_actions.extend(["MOVE_FORWARD", "MOVE_BACKWARD"])
215
  return base_actions
216
 
 
 
 
 
 
 
 
 
 
 
217
  def get_current_address(self) -> Optional[str]:
218
  try:
219
  address_element = self.wait.until(
 
214
  base_actions.extend(["MOVE_FORWARD", "MOVE_BACKWARD"])
215
  return base_actions
216
 
217
+ def get_test_available_actions(self) -> List[str]:
218
+ """
219
+ Checks for movement links via JavaScript.
220
+ """
221
+ base_actions = ["PAN_LEFT", "PAN_RIGHT"]
222
+ links = self.driver.execute_script("return window.panorama.getLinks();")
223
+ if links and len(links) > 0:
224
+ base_actions.extend(["MOVE_FORWARD", "MOVE_BACKWARD"])
225
+ return base_actions
226
+
227
  def get_current_address(self) -> Optional[str]:
228
  try:
229
  address_element = self.wait.until(