YashsharmaPhD commited on
Commit
b8220d9
Β·
verified Β·
1 Parent(s): 6a83093

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -73
app.py CHANGED
@@ -15,76 +15,91 @@ obstacle_hits = []
15
  color_index = 0
16
  rgb_colors = ['red', 'green', 'blue']
17
  noise_enabled = True
18
- obstacles = []
19
  auto_mode = False
 
 
20
 
21
- # Generate obstacles
22
  def generate_obstacles(count=10):
23
- return [{"x": random.uniform(-8, 8), "z": random.uniform(-8, 8), "radius": random.uniform(0.5, 1.2)} for _ in range(count)]
24
-
25
- # Check collision
26
- def check_collision(x, z):
27
- for obs in obstacles:
28
- dist = np.sqrt((obs["x"] - x)**2 + (obs["z"] - z)**2)
29
- if dist <= obs["radius"] + 0.2:
30
- return True
31
- return False
32
 
33
- # Reset simulation
34
  def reset_sim(count):
35
  global pose, trajectory, obstacles, obstacle_hits, color_index
36
  pose = {"x": 0, "z": 0, "angle": 0}
37
- trajectory.clear()
38
- trajectory.append((0, 0))
39
- obstacle_hits.clear()
40
  color_index = 0
41
  obstacles.clear()
42
- obstacles.extend(generate_obstacles(int(count)))
43
- return render_env(), render_slam_map(), None, f"Simulation reset with {count} obstacles"
44
 
45
- # Toggle noise
46
  def toggle_noise():
47
  global noise_enabled
48
  noise_enabled = not noise_enabled
49
  return "Noise: ON" if noise_enabled else "Noise: OFF"
50
 
51
- # Move robot (manual or automatic)
 
 
 
 
 
 
52
  def move_robot(direction):
53
  global pose, trajectory
54
- step = 1; d = direction.upper()
55
- dx, dz = 0, 0
56
- if d=='W': dz=step; pose["angle"]=90
57
- elif d=='S': dz=-step; pose["angle"]=-90
58
- elif d=='A': dx=-step; pose["angle"]=180
59
- elif d=='D': dx=step; pose["angle"]=0
 
 
 
 
 
 
 
 
 
 
60
  else:
61
  return render_env(), render_slam_map(), None, "❌ Invalid Key"
62
- nx, nz = pose["x"]+dx, pose["z"]+dz
63
- if check_collision(nx, nz):
64
- return render_env(), render_slam_map(), "collision1.wav", "🚫 Collision!"
65
- pose["x"], pose["z"] = nx, nz
 
66
  if noise_enabled:
67
- trajectory.append((pose["x"]+random.uniform(-0.1,0.1),
68
- pose["z"]+random.uniform(-0.1,0.1)))
 
69
  else:
70
  trajectory.append((pose["x"], pose["z"]))
71
- return render_env(), render_slam_map(), None, f"Moved {d}"
72
 
73
- # Render environment
 
74
  def render_env():
75
- global obstacle_hits
76
  fig, ax = plt.subplots()
77
  ax.set_xlim(-10, 10)
78
  ax.set_ylim(-10, 10)
79
  ax.set_title("SLAM Environment")
 
80
  try:
81
  bg = mpimg.imread("map.png")
82
  ax.imshow(bg, extent=(-10, 10, -10, 10), alpha=0.2)
83
  except:
84
  pass
 
85
  for obs in obstacles:
86
- ax.add_patch(plt.Circle((obs["x"], obs["z"]), obs["radius"], color="gray", alpha=0.6))
 
 
87
  ax.plot(pose["x"], pose["z"], 'ro', markersize=8)
 
88
  angles = np.linspace(0, 2*np.pi, 24)
89
  for ang in angles:
90
  for r in np.linspace(0, 3, 30):
@@ -94,10 +109,10 @@ def render_env():
94
  ax.plot([pose["x"], scan_x], [pose["z"], scan_z], 'g-', linewidth=0.5)
95
  obstacle_hits.append((scan_x, scan_z))
96
  break
 
97
  plt.close(fig)
98
  return fig
99
 
100
- # Render SLAM map
101
  def render_slam_map():
102
  global color_index
103
  fig, ax = plt.subplots()
@@ -106,55 +121,61 @@ def render_slam_map():
106
  z_vals = [z for x, z in trajectory]
107
  ax.plot(x_vals, z_vals, 'bo-', markersize=3)
108
  ax.grid(True)
 
109
  if obstacle_hits:
110
  current_color = rgb_colors[color_index % 3]
111
  for hit in obstacle_hits[-20:]:
112
  ax.plot(hit[0], hit[1], 'o', color=current_color, markersize=6)
113
  color_index += 1
 
114
  plt.close(fig)
115
  return fig
116
 
117
- # Handle manual input
118
  def handle_text_input(direction):
119
  return move_robot(direction.strip().upper())
120
 
121
- # Auto move loop
122
- def auto_move_loop(update_outputs_fn):
123
  global auto_mode
124
  directions = ['W', 'A', 'S', 'D']
125
  while auto_mode:
126
- random.shuffle(directions)
127
- for dir in directions:
128
- env, slam, audio, msg = move_robot(dir)
129
- update_outputs_fn(env, slam, audio, f"[AUTO] {msg}")
130
- time.sleep(1)
131
- if not auto_mode:
132
- break
133
 
134
- # Toggle auto mode
135
- def toggle_auto(update_fn):
136
- global auto_mode
137
  auto_mode = not auto_mode
138
  if auto_mode:
139
- thread = threading.Thread(target=auto_move_loop, args=(update_fn,))
140
- thread.start()
141
- return "🟒 Auto Mode ON"
 
 
 
 
 
 
 
142
  else:
143
- return "πŸ”΄ Auto Mode OFF"
144
 
145
- # Gradio UI
146
  with gr.Blocks() as demo:
147
- gr.Markdown("## πŸ€– SLAM Simulation β€” Manual & Automatic Navigation")
148
- obstacle_slider = gr.Slider(1, 20, value=10, step=1, label="Obstacle Count")
 
149
  direction_input = gr.Textbox(label="Type W / A / S / D", placeholder="e.g., W")
150
- status = gr.Textbox(label="Status")
151
- audio = gr.Audio(label="Collision Sound", interactive=False)
152
 
153
  with gr.Row():
154
  with gr.Column():
155
- env_plot = gr.Plot(label="Robot + Environment View")
156
  with gr.Column():
157
- slam_plot = gr.Plot(label="SLAM Trajectory Map")
158
 
159
  with gr.Row():
160
  w = gr.Button("⬆️ W")
@@ -163,18 +184,15 @@ with gr.Blocks() as demo:
163
  d = gr.Button("➑️ D")
164
  reset = gr.Button("πŸ”„ Reset")
165
  toggle = gr.Button("πŸ”€ Toggle Noise")
166
- auto_btn = gr.Button("πŸ€– Toggle Auto Mode")
167
-
168
- w.click(fn=move_robot, inputs=gr.State("W"), outputs=[env_plot, slam_plot, audio, status])
169
- a.click(fn=move_robot, inputs=gr.State("A"), outputs=[env_plot, slam_plot, audio, status])
170
- s.click(fn=move_robot, inputs=gr.State("S"), outputs=[env_plot, slam_plot, audio, status])
171
- d.click(fn=move_robot, inputs=gr.State("D"), outputs=[env_plot, slam_plot, audio, status])
172
-
173
- direction_input.submit(fn=handle_text_input, inputs=direction_input, outputs=[env_plot, slam_plot, audio, status])
174
- reset.click(fn=reset_sim, inputs=[obstacle_slider], outputs=[env_plot, slam_plot, audio, status])
175
- toggle.click(fn=lambda: (None, None, None, toggle_noise()), outputs=[env_plot, slam_plot, audio, status])
176
-
177
- auto_btn.click(fn=lambda: toggle_auto(lambda e, s, a, t: [env_plot.update(e), slam_plot.update(s), audio.update(a), status.update(t)]),
178
- outputs=[auto_btn])
179
 
180
  demo.launch()
 
15
  color_index = 0
16
  rgb_colors = ['red', 'green', 'blue']
17
  noise_enabled = True
 
18
  auto_mode = False
19
+ auto_thread = None
20
+ obstacles = []
21
 
 
22
  def generate_obstacles(count=10):
23
+ return [{
24
+ "x": random.uniform(-8, 8),
25
+ "z": random.uniform(-8, 8),
26
+ "radius": random.uniform(0.5, 1.2)
27
+ } for _ in range(count)]
 
 
 
 
28
 
 
29
  def reset_sim(count):
30
  global pose, trajectory, obstacles, obstacle_hits, color_index
31
  pose = {"x": 0, "z": 0, "angle": 0}
32
+ trajectory = [(0, 0)]
33
+ obstacle_hits = []
 
34
  color_index = 0
35
  obstacles.clear()
36
+ obstacles.extend(generate_obstacles(count))
37
+ return render_env(), render_slam_map(), None, f"Simulation Reset with {count} obstacles"
38
 
 
39
  def toggle_noise():
40
  global noise_enabled
41
  noise_enabled = not noise_enabled
42
  return "Noise: ON" if noise_enabled else "Noise: OFF"
43
 
44
+ def check_collision(x, z):
45
+ for obs in obstacles:
46
+ dist = np.sqrt((obs["x"] - x) ** 2 + (obs["z"] - z) ** 2)
47
+ if dist <= obs["radius"] + 0.2:
48
+ return True
49
+ return False
50
+
51
  def move_robot(direction):
52
  global pose, trajectory
53
+ step = 1
54
+ direction = direction.upper()
55
+
56
+ new_x, new_z = pose["x"], pose["z"]
57
+ if direction == "W":
58
+ new_z += step
59
+ pose["angle"] = 90
60
+ elif direction == "S":
61
+ new_z -= step
62
+ pose["angle"] = -90
63
+ elif direction == "A":
64
+ new_x -= step
65
+ pose["angle"] = 180
66
+ elif direction == "D":
67
+ new_x += step
68
+ pose["angle"] = 0
69
  else:
70
  return render_env(), render_slam_map(), None, "❌ Invalid Key"
71
+
72
+ if check_collision(new_x, new_z):
73
+ return render_env(), render_slam_map(), "collision1.wav", "🚫 Collision Detected!"
74
+
75
+ pose["x"], pose["z"] = new_x, new_z
76
  if noise_enabled:
77
+ noisy_x = pose["x"] + random.uniform(-0.1, 0.1)
78
+ noisy_z = pose["z"] + random.uniform(-0.1, 0.1)
79
+ trajectory.append((noisy_x, noisy_z))
80
  else:
81
  trajectory.append((pose["x"], pose["z"]))
 
82
 
83
+ return render_env(), render_slam_map(), None, "Moved " + direction
84
+
85
  def render_env():
 
86
  fig, ax = plt.subplots()
87
  ax.set_xlim(-10, 10)
88
  ax.set_ylim(-10, 10)
89
  ax.set_title("SLAM Environment")
90
+
91
  try:
92
  bg = mpimg.imread("map.png")
93
  ax.imshow(bg, extent=(-10, 10, -10, 10), alpha=0.2)
94
  except:
95
  pass
96
+
97
  for obs in obstacles:
98
+ circ = plt.Circle((obs["x"], obs["z"]), obs["radius"], color="gray", alpha=0.6)
99
+ ax.add_patch(circ)
100
+
101
  ax.plot(pose["x"], pose["z"], 'ro', markersize=8)
102
+
103
  angles = np.linspace(0, 2*np.pi, 24)
104
  for ang in angles:
105
  for r in np.linspace(0, 3, 30):
 
109
  ax.plot([pose["x"], scan_x], [pose["z"], scan_z], 'g-', linewidth=0.5)
110
  obstacle_hits.append((scan_x, scan_z))
111
  break
112
+
113
  plt.close(fig)
114
  return fig
115
 
 
116
  def render_slam_map():
117
  global color_index
118
  fig, ax = plt.subplots()
 
121
  z_vals = [z for x, z in trajectory]
122
  ax.plot(x_vals, z_vals, 'bo-', markersize=3)
123
  ax.grid(True)
124
+
125
  if obstacle_hits:
126
  current_color = rgb_colors[color_index % 3]
127
  for hit in obstacle_hits[-20:]:
128
  ax.plot(hit[0], hit[1], 'o', color=current_color, markersize=6)
129
  color_index += 1
130
+
131
  plt.close(fig)
132
  return fig
133
 
 
134
  def handle_text_input(direction):
135
  return move_robot(direction.strip().upper())
136
 
137
+ # --------- Automatic Mode Logic ---------
138
+ def auto_move_loop(update_callback):
139
  global auto_mode
140
  directions = ['W', 'A', 'S', 'D']
141
  while auto_mode:
142
+ direction = random.choice(directions)
143
+ env, slam, audio, msg = move_robot(direction)
144
+ update_callback(env, slam, audio, f"[AUTO] {msg}")
145
+ time.sleep(1.0)
146
+
147
+ def toggle_auto_mode(env_plot, slam_plot, collision_audio, status_text):
148
+ global auto_mode, auto_thread
149
 
 
 
 
150
  auto_mode = not auto_mode
151
  if auto_mode:
152
+ def update_ui(e, s, a, t):
153
+ env_plot.update(value=e)
154
+ slam_plot.update(value=s)
155
+ collision_audio.update(value=a)
156
+ status_text.update(value=t)
157
+
158
+ auto_thread = threading.Thread(target=auto_move_loop, args=(update_ui,))
159
+ auto_thread.daemon = True
160
+ auto_thread.start()
161
+ return "🟒 Auto Mode: ON"
162
  else:
163
+ return "βšͺ Auto Mode: OFF"
164
 
165
+ # --------- Gradio UI ---------
166
  with gr.Blocks() as demo:
167
+ gr.Markdown("## πŸ€– SLAM Simulation: Manual + Auto Navigation")
168
+
169
+ obstacle_slider = gr.Slider(1, 20, value=10, step=1, label="Number of Obstacles")
170
  direction_input = gr.Textbox(label="Type W / A / S / D", placeholder="e.g., W")
171
+ status_text = gr.Textbox(label="Status")
172
+ collision_audio = gr.Audio(label="Collision Sound", interactive=False)
173
 
174
  with gr.Row():
175
  with gr.Column():
176
+ env_plot = gr.Plot(label="Environment")
177
  with gr.Column():
178
+ slam_plot = gr.Plot(label="SLAM Map")
179
 
180
  with gr.Row():
181
  w = gr.Button("⬆️ W")
 
184
  d = gr.Button("➑️ D")
185
  reset = gr.Button("πŸ”„ Reset")
186
  toggle = gr.Button("πŸ”€ Toggle Noise")
187
+ auto = gr.Button("πŸ€– Toggle Auto")
188
+
189
+ w.click(fn=move_robot, inputs=gr.State("W"), outputs=[env_plot, slam_plot, collision_audio, status_text])
190
+ a.click(fn=move_robot, inputs=gr.State("A"), outputs=[env_plot, slam_plot, collision_audio, status_text])
191
+ s.click(fn=move_robot, inputs=gr.State("S"), outputs=[env_plot, slam_plot, collision_audio, status_text])
192
+ d.click(fn=move_robot, inputs=gr.State("D"), outputs=[env_plot, slam_plot, collision_audio, status_text])
193
+ reset.click(fn=reset_sim, inputs=[obstacle_slider], outputs=[env_plot, slam_plot, collision_audio, status_text])
194
+ toggle.click(fn=lambda: (None, None, None, toggle_noise()), outputs=[env_plot, slam_plot, collision_audio, status_text])
195
+ direction_input.submit(fn=handle_text_input, inputs=direction_input, outputs=[env_plot, slam_plot, collision_audio, status_text])
196
+ auto.click(fn=toggle_auto_mode, inputs=[env_plot, slam_plot, collision_audio, status_text], outputs=auto)
 
 
 
197
 
198
  demo.launch()