Spaces:
Sleeping
Sleeping
File size: 2,960 Bytes
30b0ee6 8846343 30b0ee6 8846343 30b0ee6 8846343 30b0ee6 8846343 4cde84b 8846343 4cde84b 30b0ee6 8846343 30b0ee6 8846343 30b0ee6 8846343 30b0ee6 8846343 30b0ee6 227b2a7 30b0ee6 4cde84b 8846343 30b0ee6 227b2a7 30b0ee6 8846343 30b0ee6 8846343 227b2a7 4cde84b 8846343 30b0ee6 | 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 | import gradio as gr
import numpy as np
import pickle
import matplotlib.pyplot as plt
# 1. LOAD THE BRAIN
# This assumes 'agent_q_table.pkl' is in your root directory
with open('agent_q_table.pkl', 'rb') as f:
q_table = pickle.load(f)
# Environment parameters from the project script
grid_size = (5, 5)
goal = (4, 4)
pits = [(1, 1), (2, 2), (3, 3)]
walls = [(0, 1), (1, 0)]
actions = ['up', 'down', 'left', 'right']
# 2. SIMULATION LOGIC WITH VALIDATION
def simulate_agent(start_pos):
try:
# Parse and validate coordinates (Must be 0-4 for a 5x5 grid)
r, c = map(int, start_pos.split(','))
if not (0 <= r < 5 and 0 <= c < 5):
return None, " Error: Coordinates must be between 0 and 4 (e.g., '0,2')."
current_state = (r, c)
except Exception:
return None, " Invalid format. Please use 'row,col' (e.g., 0,0)."
path = [current_state]
steps = 0
done = False
# Run simulation using the learned Q-table
while not done and steps < 20:
action_idx = np.argmax(q_table[current_state[0], current_state[1]])
action = actions[action_idx]
r, c = current_state
if action == 'up': r = max(0, r - 1)
elif action == 'down': r = min(grid_size[0] - 1, r + 1)
elif action == 'left': c = max(0, c - 1)
elif action == 'right': c = min(grid_size[1] - 1, c + 1)
new_state = (r, c)
if new_state in walls: new_state = current_state # Stay put if hitting a wall
current_state = new_state
path.append(current_state)
if current_state == goal or current_state in pits:
done = True
steps += 1
# 3. VISUALIZATION
fig, ax = plt.subplots(figsize=(5, 5))
grid = np.zeros(grid_size)
for p in pits: grid[p] = -1 # Pits marked as negative
grid[goal] = 1 # Goal marked as positive
ax.imshow(grid, cmap='RdYlGn', origin='upper')
# Plot the agent's path
path_r, path_c = zip(*path)
ax.plot(path_c, path_r, marker='o', color='blue', linewidth=2, label='Agent Path')
status = "Success! " if path[-1] == goal else "Fell in a Pit "
ax.set_title(f"Simulation: {status}")
plt.legend()
return fig, f"Steps taken: {steps} | Full Path: {path}"
# 4. AESTHETIC INTERFACE
# Uses gr.themes.Soft() for a clean look and custom CSS to hide the share button
demo = gr.Interface(
fn=simulate_agent,
inputs=gr.Textbox(label="Starting Position (row,col)", value="0,0", placeholder="Enter 0-4 coordinates"),
outputs=[gr.Plot(label="Navigation Map"), gr.Text(label="Path Details")],
title=" Autonomous Grid Navigator",
description="The agent uses Reinforcement Learning (Q-Learning) to navigate to the green goal while avoiding pits.",
theme=gr.themes.Soft(),
css=".share-button { display: none !important; }"
)
if __name__ == "__main__":
demo.launch() |