Spaces:
Sleeping

MRM5 commited on
Commit
30b0ee6
·
verified ·
1 Parent(s): a970708

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import pickle
4
+ import matplotlib.pyplot as plt
5
+
6
+ # 1. LOAD THE BRAIN
7
+ with open('agent_q_table.pkl', 'rb') as f:
8
+ q_table = pickle.load(f)
9
+
10
+ # Hardcoded environment parameters matching your script
11
+ grid_size = (5, 5)
12
+ goal = (4, 4)
13
+ pits = [(1, 1), (2, 2), (3, 3)]
14
+ walls = [(0, 1), (1, 0)]
15
+ actions = ['up', 'down', 'left', 'right']
16
+
17
+ # 2. SIMULATION LOGIC
18
+ def simulate_agent(start_pos):
19
+ # Convert string input like "0,0" to tuple (0,0)
20
+ try:
21
+ current_state = tuple(map(int, start_pos.split(',')))
22
+ except:
23
+ return None, "Invalid format. Use 'row,col' (e.g., 0,0)"
24
+
25
+ path = [current_state]
26
+ steps = 0
27
+ done = False
28
+
29
+ while not done and steps < 20:
30
+ # Get best action from Q-table
31
+ action_idx = np.argmax(q_table[current_state[0], current_state[1]])
32
+ action = actions[action_idx]
33
+
34
+ # Calculate new state
35
+ r, c = current_state
36
+ if action == 'up': r = max(0, r - 1)
37
+ elif action == 'down': r = min(grid_size[0] - 1, r + 1)
38
+ elif action == 'left': c = max(0, c - 1)
39
+ elif action == 'right': c = min(grid_size[1] - 1, c + 1)
40
+
41
+ new_state = (r, c)
42
+ if new_state in walls: new_state = current_state # Stay put if wall
43
+
44
+ current_state = new_state
45
+ path.append(current_state)
46
+
47
+ if current_state == goal or current_state in pits:
48
+ done = True
49
+ steps += 1
50
+
51
+ # 3. DRAW THE GRID
52
+ fig, ax = plt.subplots(figsize=(5, 5))
53
+ grid = np.zeros(grid_size)
54
+ for p in pits: grid[p] = -1
55
+ grid[goal] = 1
56
+
57
+ ax.imshow(grid, cmap='RdYlGn', origin='upper')
58
+
59
+ # Draw the path
60
+ path_r, path_c = zip(*path)
61
+ ax.plot(path_c, path_r, marker='o', color='blue', linewidth=2, label='Agent Path')
62
+
63
+ ax.set_title(f"Agent Journey: {'Success!' if path[-1] == goal else 'Failed'}")
64
+ plt.legend()
65
+
66
+ return fig, f"Path taken: {path}"
67
+
68
+ # 4. GRADIO INTERFACE
69
+ demo = gr.Interface(
70
+ fn=simulate_agent,
71
+ inputs=gr.Textbox(label="Starting Position (row,col)", value="0,0"),
72
+ outputs=[gr.Plot(label="Grid Map"), gr.Text(label="Path Details")],
73
+ title="🤖 RL Gridworld Navigator",
74
+ description="Choose a starting point. The agent uses its learned Q-table to navigate to the green goal while avoiding red pits.",
75
+ theme=gr.themes.Soft(),
76
+ css=".share-button { display: none !important; }"
77
+ )
78
+
79
+ if __name__ == "__main__":
80
+ demo.launch()