awacke1 commited on
Commit
67fe658
·
verified ·
1 Parent(s): ecd8001

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -63
app.py CHANGED
@@ -154,9 +154,50 @@ def load_username():
154
  return f.read().strip()
155
  return None
156
 
157
- # ---------------------
158
- # New Pair of Helper Functions
159
- # ---------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  def log_chat_history(username, message, is_markdown=False):
161
  """Log the chat entry to a markdown file."""
162
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@@ -174,7 +215,9 @@ async def generate_chat_audio(username, message, voice):
174
  audio_file = await async_edge_tts_generate(message, voice, username)
175
  return audio_file
176
 
177
- # Audio Processing
 
 
178
  async def async_edge_tts_generate(text, voice, username):
179
  cache_key = f"{text[:100]}_{voice}"
180
  if cache_key in st.session_state['audio_cache']:
@@ -193,9 +236,24 @@ def play_and_download_audio(file_path):
193
  st.audio(file_path, start_time=0)
194
  st.markdown(get_download_link(file_path), unsafe_allow_html=True)
195
 
196
- # ---------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  # Wrapper Function to Save Chat Entry (Using the Two Helpers Above)
198
- # ---------------------
199
  async def save_chat_entry(username, message, voice, is_markdown=False):
200
  if not message.strip() or message == st.session_state.get('last_transcript', ''):
201
  return None, None
@@ -232,7 +290,9 @@ async def load_chat():
232
  content = f.read().strip()
233
  return content.split('\n')
234
 
235
- # Session State Init
 
 
236
  def init_session_state():
237
  defaults = {
238
  'server_running': False, 'server_task': None, 'active_connections': {},
@@ -263,63 +323,12 @@ def init_session_state():
263
 
264
  init_session_state()
265
 
266
- # Agent Class for Players
267
- class PlayerAgent:
268
- def __init__(self, username, char_data):
269
- self.username = username
270
- self.x = random.uniform(-20, 20)
271
- self.z = random.uniform(-40, 40)
272
- self.color = char_data["color"]
273
- self.shape = char_data["shape"]
274
- self.score = 0
275
- self.treasures = 0
276
- self.last_active = time.time()
277
- self.voice = char_data["voice"]
278
-
279
- def to_dict(self):
280
- return {
281
- "username": self.username,
282
- "x": self.x,
283
- "z": self.z,
284
- "color": self.color,
285
- "shape": self.shape,
286
- "score": self.score,
287
- "treasures": self.treasures,
288
- "last_active": self.last_active
289
- }
290
-
291
- def update_from_message(self, message):
292
- if '|' in message:
293
- _, content = message.split('|', 1)
294
- if content.startswith("MOVE:"):
295
- _, x, z = content.split(":")
296
- self.x, self.z = float(x), float(z)
297
- self.last_active = time.time()
298
- elif content.startswith("SCORE:"):
299
- self.score = int(content.split(":")[1])
300
- self.last_active = time.time()
301
- elif content.startswith("TREASURE:"):
302
- self.treasures = int(content.split(":")[1])
303
- self.last_active = time.time()
304
-
305
- # WebSocket Broadcast
306
- async def broadcast_message(message, room_id):
307
- if room_id in st.session_state.active_connections:
308
- disconnected = []
309
- for client_id, ws in st.session_state.active_connections[room_id].items():
310
- try:
311
- await ws.send(message)
312
- except websockets.ConnectionClosed:
313
- disconnected.append(client_id)
314
- for client_id in disconnected:
315
- if client_id in st.session_state.active_connections[room_id]:
316
- del st.session_state.active_connections[room_id][client_id]
317
-
318
- # Chat and Quest Log (uses the new helper functions)
319
  async def save_chat_entry_wrapper(username, message, voice, is_markdown=False):
320
  return await save_chat_entry(username, message, voice, is_markdown)
321
 
322
- # WebSocket Handler
323
  async def websocket_handler(websocket, path):
324
  client_id = str(uuid.uuid4())
325
  room_id = "quest"
@@ -420,7 +429,9 @@ def start_websocket_server():
420
  asyncio.set_event_loop(loop)
421
  loop.run_until_complete(run_websocket_server())
422
 
423
- # ArXiv Integration remains unchanged
 
 
424
  async def perform_arxiv_search(query, username):
425
  gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
426
  refs = gradio_client.predict(
@@ -431,7 +442,9 @@ async def perform_arxiv_search(query, username):
431
  md_file, audio_file = await save_chat_entry_wrapper(username, result, voice, True)
432
  return md_file, audio_file
433
 
 
434
  # Sidebar Functions
 
435
  def update_marquee_settings_ui():
436
  st.sidebar.markdown("### 🎯 Marquee Settings")
437
  cols = st.sidebar.columns(2)
@@ -470,7 +483,9 @@ def log_performance_metrics():
470
  percentage = (duration / total_time) * 100
471
  st.sidebar.write(f"**{operation}:** {duration:.2f}s ({percentage:.1f}%)")
472
 
473
- # Enhanced 3D Game HTML remains largely unchanged, with dynamic insertion of the username and avatar details
 
 
474
  rocky_map_html = f"""
475
  <!DOCTYPE html>
476
  <html lang="en">
@@ -736,7 +751,9 @@ rocky_map_html = f"""
736
  </html>
737
  """
738
 
 
739
  # Main Game Loop
 
740
  def main():
741
  st.markdown(f"<h2 style='text-align: center;'>Welcome, {st.session_state.username}!</h2>", unsafe_allow_html=True)
742
  message = st.text_input(f"🗨️ Chat as {st.session_state.username}:", placeholder="Type to chat or add world features! 🌲", key="chat_input")
 
154
  return f.read().strip()
155
  return None
156
 
157
+ # -----------------------------------------------------------
158
+ # Define PlayerAgent class (used in session state initialization)
159
+ # -----------------------------------------------------------
160
+ class PlayerAgent:
161
+ def __init__(self, username, char_data):
162
+ self.username = username
163
+ self.x = random.uniform(-20, 20)
164
+ self.z = random.uniform(-40, 40)
165
+ self.color = char_data["color"]
166
+ self.shape = char_data["shape"]
167
+ self.score = 0
168
+ self.treasures = 0
169
+ self.last_active = time.time()
170
+ self.voice = char_data["voice"]
171
+
172
+ def to_dict(self):
173
+ return {
174
+ "username": self.username,
175
+ "x": self.x,
176
+ "z": self.z,
177
+ "color": self.color,
178
+ "shape": self.shape,
179
+ "score": self.score,
180
+ "treasures": self.treasures,
181
+ "last_active": self.last_active
182
+ }
183
+
184
+ def update_from_message(self, message):
185
+ if '|' in message:
186
+ _, content = message.split('|', 1)
187
+ if content.startswith("MOVE:"):
188
+ _, x, z = content.split(":")
189
+ self.x, self.z = float(x), float(z)
190
+ self.last_active = time.time()
191
+ elif content.startswith("SCORE:"):
192
+ self.score = int(content.split(":")[1])
193
+ self.last_active = time.time()
194
+ elif content.startswith("TREASURE:"):
195
+ self.treasures = int(content.split(":")[1])
196
+ self.last_active = time.time()
197
+
198
+ # -----------------------------------------------------------
199
+ # New Helper Functions: Chat Logging & TTS Generation
200
+ # -----------------------------------------------------------
201
  def log_chat_history(username, message, is_markdown=False):
202
  """Log the chat entry to a markdown file."""
203
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
215
  audio_file = await async_edge_tts_generate(message, voice, username)
216
  return audio_file
217
 
218
+ # -----------------------------------------------------------
219
+ # Audio Processing Function
220
+ # -----------------------------------------------------------
221
  async def async_edge_tts_generate(text, voice, username):
222
  cache_key = f"{text[:100]}_{voice}"
223
  if cache_key in st.session_state['audio_cache']:
 
236
  st.audio(file_path, start_time=0)
237
  st.markdown(get_download_link(file_path), unsafe_allow_html=True)
238
 
239
+ # -----------------------------------------------------------
240
+ # WebSocket Broadcast Function
241
+ # -----------------------------------------------------------
242
+ async def broadcast_message(message, room_id):
243
+ if room_id in st.session_state.active_connections:
244
+ disconnected = []
245
+ for client_id, ws in st.session_state.active_connections[room_id].items():
246
+ try:
247
+ await ws.send(message)
248
+ except websockets.ConnectionClosed:
249
+ disconnected.append(client_id)
250
+ for client_id in disconnected:
251
+ if client_id in st.session_state.active_connections[room_id]:
252
+ del st.session_state.active_connections[room_id][client_id]
253
+
254
+ # -----------------------------------------------------------
255
  # Wrapper Function to Save Chat Entry (Using the Two Helpers Above)
256
+ # -----------------------------------------------------------
257
  async def save_chat_entry(username, message, voice, is_markdown=False):
258
  if not message.strip() or message == st.session_state.get('last_transcript', ''):
259
  return None, None
 
290
  content = f.read().strip()
291
  return content.split('\n')
292
 
293
+ # -----------------------------------------------------------
294
+ # Session State Initialization
295
+ # -----------------------------------------------------------
296
  def init_session_state():
297
  defaults = {
298
  'server_running': False, 'server_task': None, 'active_connections': {},
 
323
 
324
  init_session_state()
325
 
326
+ # -----------------------------------------------------------
327
+ # WebSocket Handler and Related Functions
328
+ # -----------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  async def save_chat_entry_wrapper(username, message, voice, is_markdown=False):
330
  return await save_chat_entry(username, message, voice, is_markdown)
331
 
 
332
  async def websocket_handler(websocket, path):
333
  client_id = str(uuid.uuid4())
334
  room_id = "quest"
 
429
  asyncio.set_event_loop(loop)
430
  loop.run_until_complete(run_websocket_server())
431
 
432
+ # -----------------------------------------------------------
433
+ # ArXiv Integration (Unchanged)
434
+ # -----------------------------------------------------------
435
  async def perform_arxiv_search(query, username):
436
  gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
437
  refs = gradio_client.predict(
 
442
  md_file, audio_file = await save_chat_entry_wrapper(username, result, voice, True)
443
  return md_file, audio_file
444
 
445
+ # -----------------------------------------------------------
446
  # Sidebar Functions
447
+ # -----------------------------------------------------------
448
  def update_marquee_settings_ui():
449
  st.sidebar.markdown("### 🎯 Marquee Settings")
450
  cols = st.sidebar.columns(2)
 
483
  percentage = (duration / total_time) * 100
484
  st.sidebar.write(f"**{operation}:** {duration:.2f}s ({percentage:.1f}%)")
485
 
486
+ # -----------------------------------------------------------
487
+ # Enhanced 3D Game HTML (With dynamic insertion of username and avatar)
488
+ # -----------------------------------------------------------
489
  rocky_map_html = f"""
490
  <!DOCTYPE html>
491
  <html lang="en">
 
751
  </html>
752
  """
753
 
754
+ # -----------------------------------------------------------
755
  # Main Game Loop
756
+ # -----------------------------------------------------------
757
  def main():
758
  st.markdown(f"<h2 style='text-align: center;'>Welcome, {st.session_state.username}!</h2>", unsafe_allow_html=True)
759
  message = st.text_input(f"🗨️ Chat as {st.session_state.username}:", placeholder="Type to chat or add world features! 🌲", key="chat_input")