awacke1 commited on
Commit
5a9e2f4
·
verified ·
1 Parent(s): ee6f1dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -24
app.py CHANGED
@@ -17,7 +17,7 @@ import streamlit.components.v1 as components
17
  from gradio_client import Client
18
  from streamlit_marquee import streamlit_marquee
19
  import folium
20
- from streamlit_folium import st_folium # Use st_folium instead of folium_static
21
  import glob
22
  import pytz
23
  from collections import defaultdict
@@ -117,7 +117,89 @@ def load_username():
117
  return None
118
 
119
  # -----------------------------
120
- # Audio and Chat Processing Functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  # -----------------------------
122
  async def async_edge_tts_generate(text, voice, username):
123
  cache_key = f"{text[:100]}_{voice}"
@@ -149,24 +231,6 @@ async def generate_chat_audio(username, message, voice):
149
  audio_file = await async_edge_tts_generate(message, voice, username)
150
  return audio_file
151
 
152
- # -----------------------------
153
- # Broadcast Message (defined before usage)
154
- # -----------------------------
155
- async def broadcast_message(message, room_id):
156
- if room_id in st.session_state.active_connections:
157
- disconnected = []
158
- for client_id, ws in st.session_state.active_connections[room_id].items():
159
- try:
160
- await ws.send(message)
161
- except websockets.ConnectionClosed:
162
- disconnected.append(client_id)
163
- for client_id in disconnected:
164
- if client_id in st.session_state.active_connections[room_id]:
165
- del st.session_state.active_connections[room_id][client_id]
166
-
167
- # -----------------------------
168
- # Chat Entry Saving Function
169
- # -----------------------------
170
  async def save_chat_entry(username, message, voice, is_markdown=False):
171
  if not message.strip() or message == st.session_state.get('last_transcript', ''):
172
  return None, None
@@ -203,6 +267,21 @@ async def load_chat():
203
  content = f.read().strip()
204
  return content.split('\n')
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  # -----------------------------
207
  # Session State Initialization
208
  # -----------------------------
@@ -383,7 +462,7 @@ def display_file_history_in_sidebar():
383
 
384
  def log_performance_metrics():
385
  st.sidebar.markdown("### ⏱️ Performance Metrics")
386
- metrics = st.session_state['operation_timings']
387
  if metrics:
388
  total_time = sum(metrics.values())
389
  st.sidebar.write(f"**Total Processing Time:** {total_time:.2f}s")
@@ -394,7 +473,6 @@ def log_performance_metrics():
394
  # -----------------------------
395
  # Enhanced 3D World HTML
396
  # -----------------------------
397
- # Precompute player attributes for correct interpolation.
398
  player_color = next(c["color"] for c in EDGE_TTS_VOICES if c["name"] == st.session_state.username)
399
  player_shape = next(c["shape"] for c in EDGE_TTS_VOICES if c["name"] == st.session_state.username)
400
 
@@ -565,7 +643,6 @@ rocky_map_html = f"""
565
  }}
566
  const mesh = playerMeshes[player.username];
567
  mesh.position.set(player.x, 1, player.z);
568
- players[player.username] = {{ score: player.score, treasures: player.treasures }};
569
  if(player.username === playerName) {{
570
  xPos = player.x;
571
  zPos = player.z;
@@ -677,7 +754,7 @@ def main():
677
  st.session_state.last_activity = time.time()
678
  st.success(f"🌄 +10 points! New Score: ${st.session_state.score}")
679
 
680
- # Display Quest Log as a Code Block (with Python formatting)
681
  chat_content = asyncio.run(load_chat())
682
  st.code("\n".join(chat_content[-10:]), language="python")
683
 
 
17
  from gradio_client import Client
18
  from streamlit_marquee import streamlit_marquee
19
  import folium
20
+ from streamlit_folium import st_folium # Using st_folium instead of folium_static
21
  import glob
22
  import pytz
23
  from collections import defaultdict
 
117
  return None
118
 
119
  # -----------------------------
120
+ # Game State Functions
121
+ # -----------------------------
122
+ @st.cache_resource
123
+ def load_game_state(_timestamp):
124
+ if os.path.exists(GAME_STATE_FILE):
125
+ with open(GAME_STATE_FILE, 'r') as f:
126
+ state = json.load(f)
127
+ else:
128
+ state = {
129
+ "players": {},
130
+ "treasures": [
131
+ {"id": str(uuid.uuid4()), "x": random.uniform(-40, 40), "z": random.uniform(-40, 40)}
132
+ for _ in range(5)
133
+ ],
134
+ "world_objects": [],
135
+ "history": []
136
+ }
137
+ with open(GAME_STATE_FILE, 'w') as f:
138
+ json.dump(state, f)
139
+ return state
140
+
141
+ def update_game_state(state):
142
+ state["timestamp"] = os.path.getmtime(GAME_STATE_FILE) if os.path.exists(GAME_STATE_FILE) else time.time()
143
+ with open(GAME_STATE_FILE, 'w') as f:
144
+ json.dump(state, f)
145
+ load_game_state.clear()
146
+ return load_game_state(time.time())
147
+
148
+ def reset_game_state():
149
+ state = {
150
+ "players": {},
151
+ "treasures": [
152
+ {"id": str(uuid.uuid4()), "x": random.uniform(-40, 40), "z": random.uniform(-40, 40)}
153
+ for _ in range(5)
154
+ ],
155
+ "world_objects": [],
156
+ "history": []
157
+ }
158
+ return update_game_state(state)
159
+
160
+ # -----------------------------
161
+ # PlayerAgent Class
162
+ # -----------------------------
163
+ class PlayerAgent:
164
+ def __init__(self, username, char_data):
165
+ self.username = username
166
+ self.x = random.uniform(-20, 20)
167
+ self.z = random.uniform(-40, 40)
168
+ self.color = char_data["color"]
169
+ self.shape = char_data["shape"]
170
+ self.score = 0
171
+ self.treasures = 0
172
+ self.last_active = time.time()
173
+ self.voice = char_data["voice"]
174
+
175
+ def to_dict(self):
176
+ return {
177
+ "username": self.username,
178
+ "x": self.x,
179
+ "z": self.z,
180
+ "color": self.color,
181
+ "shape": self.shape,
182
+ "score": self.score,
183
+ "treasures": self.treasures,
184
+ "last_active": self.last_active
185
+ }
186
+
187
+ def update_from_message(self, message):
188
+ if '|' in message:
189
+ _, content = message.split('|', 1)
190
+ if content.startswith("MOVE:"):
191
+ _, x, z = content.split(":")
192
+ self.x, self.z = float(x), float(z)
193
+ self.last_active = time.time()
194
+ elif content.startswith("SCORE:"):
195
+ self.score = int(content.split(":")[1])
196
+ self.last_active = time.time()
197
+ elif content.startswith("TREASURE:"):
198
+ self.treasures = int(content.split(":")[1])
199
+ self.last_active = time.time()
200
+
201
+ # -----------------------------
202
+ # Audio and Chat Processing
203
  # -----------------------------
204
  async def async_edge_tts_generate(text, voice, username):
205
  cache_key = f"{text[:100]}_{voice}"
 
231
  audio_file = await async_edge_tts_generate(message, voice, username)
232
  return audio_file
233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  async def save_chat_entry(username, message, voice, is_markdown=False):
235
  if not message.strip() or message == st.session_state.get('last_transcript', ''):
236
  return None, None
 
267
  content = f.read().strip()
268
  return content.split('\n')
269
 
270
+ # -----------------------------
271
+ # Broadcast Message Function
272
+ # -----------------------------
273
+ async def broadcast_message(message, room_id):
274
+ if room_id in st.session_state.active_connections:
275
+ disconnected = []
276
+ for client_id, ws in st.session_state.active_connections[room_id].items():
277
+ try:
278
+ await ws.send(message)
279
+ except websockets.ConnectionClosed:
280
+ disconnected.append(client_id)
281
+ for client_id in disconnected:
282
+ if client_id in st.session_state.active_connections[room_id]:
283
+ del st.session_state.active_connections[room_id][client_id]
284
+
285
  # -----------------------------
286
  # Session State Initialization
287
  # -----------------------------
 
462
 
463
  def log_performance_metrics():
464
  st.sidebar.markdown("### ⏱️ Performance Metrics")
465
+ metrics = st.session_state.get('operation_timings', {})
466
  if metrics:
467
  total_time = sum(metrics.values())
468
  st.sidebar.write(f"**Total Processing Time:** {total_time:.2f}s")
 
473
  # -----------------------------
474
  # Enhanced 3D World HTML
475
  # -----------------------------
 
476
  player_color = next(c["color"] for c in EDGE_TTS_VOICES if c["name"] == st.session_state.username)
477
  player_shape = next(c["shape"] for c in EDGE_TTS_VOICES if c["name"] == st.session_state.username)
478
 
 
643
  }}
644
  const mesh = playerMeshes[player.username];
645
  mesh.position.set(player.x, 1, player.z);
 
646
  if(player.username === playerName) {{
647
  xPos = player.x;
648
  zPos = player.z;
 
754
  st.session_state.last_activity = time.time()
755
  st.success(f"🌄 +10 points! New Score: ${st.session_state.score}")
756
 
757
+ # Display Quest Log as a Python code block
758
  chat_content = asyncio.run(load_chat())
759
  st.code("\n".join(chat_content[-10:]), language="python")
760