awacke1 commited on
Commit
1a03fd6
ยท
verified ยท
1 Parent(s): 9008baf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +471 -663
app.py CHANGED
@@ -14,23 +14,21 @@ import base64
14
  import io
15
  import streamlit.components.v1 as components
16
  import edge_tts
 
17
  import nest_asyncio
18
  import re
19
  from streamlit_paste_button import paste_image_button
20
  import pytz
21
  import shutil
22
- from urllib.parse import urlencode
23
- from PyPDF2 import PdfReader
24
- import json
25
 
26
- # Patch for nested async - sneaky fix, a loopโ€™s heroic mix, in Streamlitโ€™s nix! ๐Ÿโœจ
27
  nest_asyncio.apply()
28
 
29
- # Static config - constants rule, a cosmic tool, our sagaโ€™s jewel, in shared school! ๐Ÿ“๐Ÿ‘‘
30
  icons = '๐Ÿค–๐Ÿง ๐Ÿ”ฌ๐Ÿ“'
31
  START_ROOM = "Sector ๐ŸŒŒ"
32
 
33
- # Page setup - dressing up with flair, a UI so rare, in Streamlitโ€™s glare, in shared air! ๐Ÿ–ผ๏ธ๐ŸŽ€
34
  st.set_page_config(
35
  page_title="๐Ÿค–๐Ÿง MMO Chat Brain๐Ÿ“๐Ÿ”ฌ",
36
  page_icon=icons,
@@ -38,7 +36,7 @@ st.set_page_config(
38
  initial_sidebar_state="auto"
39
  )
40
 
41
- # Funky usernames with voices - a cosmic cast, shared memoryโ€™s blast, in shared past! ๐ŸŒŒ๐ŸŽญ
42
  FUN_USERNAMES = {
43
  "CosmicJester ๐ŸŒŒ": "en-US-AriaNeural",
44
  "PixelPanda ๐Ÿผ": "en-US-JennyNeural",
@@ -62,21 +60,28 @@ FUN_USERNAMES = {
62
  "ChronoChimp ๐Ÿ’": "en-GB-LibbyNeural"
63
  }
64
 
65
- # Top-level files and directories - the treasure trove, shared memoryโ€™s grove, in shared cove! ๐Ÿ—บ๏ธ๐Ÿ“œ
66
- CHAT_FILE = "global_chat.md"
67
- QUOTE_VOTES_FILE = "quote_votes.md"
68
- MEDIA_VOTES_FILE = "media_votes.md"
69
- HISTORY_FILE = "chat_history.md"
70
  STATE_FILE = "user_state.txt"
71
  AUDIO_DIR = "audio_logs"
 
72
  MEDIA_DIR = "media_files"
 
 
73
  os.makedirs(AUDIO_DIR, exist_ok=True)
 
74
  os.makedirs(MEDIA_DIR, exist_ok=True)
75
 
76
- # Fancy digits - numbers dance, in shared cache, a numeric trance, in shared glance! ๐Ÿ”ข๐Ÿ’ƒ
 
 
 
 
 
77
  UNICODE_DIGITS = {i: f"{i}\uFE0Fโƒฃ" for i in range(10)}
78
 
79
- # Massive font collection - typographyโ€™s spree, in shared cache, a scribeโ€™s decree, in shared sea! ๐Ÿ–‹๏ธ๐ŸŽจ
80
  UNICODE_FONTS = [
81
  ("Normal", lambda x: x),
82
  ("Bold", lambda x: "".join(chr(ord(c) + 0x1D400 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D41A - 0x61) if 'a' <= c <= 'z' else c for c in x)),
@@ -99,7 +104,7 @@ UNICODE_FONTS = [
99
  ("Regional Indicator", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F1E6) if 'A' <= c <= 'Z' else c for c in x)),
100
  ]
101
 
102
- # Global state - keeping tabs, a shared sagaโ€™s grab, in Streamlitโ€™s crab! ๐ŸŒ๐Ÿ“‹ โ€“ epic memoryโ€™s lab!
103
  if 'server_running' not in st.session_state:
104
  st.session_state.server_running = False
105
  if 'server_task' not in st.session_state:
@@ -112,6 +117,10 @@ if 'last_chat_update' not in st.session_state:
112
  st.session_state.last_chat_update = 0
113
  if 'displayed_chat_lines' not in st.session_state:
114
  st.session_state.displayed_chat_lines = []
 
 
 
 
115
  if 'message_text' not in st.session_state:
116
  st.session_state.message_text = ""
117
  if 'audio_cache' not in st.session_state:
@@ -124,22 +133,20 @@ if 'refresh_rate' not in st.session_state:
124
  st.session_state.refresh_rate = 5
125
  if 'base64_cache' not in st.session_state:
126
  st.session_state.base64_cache = {}
 
 
 
 
127
  if 'image_hashes' not in st.session_state:
128
  st.session_state.image_hashes = set()
129
- if 'gallery_columns' not in st.session_state:
130
- st.session_state.gallery_columns = 1
131
- if 'user_id' not in st.session_state:
132
- st.session_state.user_id = None
133
- if 'user_hash' not in st.session_state:
134
- st.session_state.user_hash = None
135
-
136
- # Timestamp wizardry - clock ticks with flair, a temporal affair, in shared air, in Streamlitโ€™s lair! โฐ๐ŸŽฉ
137
  def format_timestamp_prefix(username):
138
  central = pytz.timezone('US/Central')
139
  now = datetime.now(central)
140
- return f"{username}-{now.strftime('%I-%M-%p-%m-%d-%Y')}-{st.session_state.user_id}"
141
 
142
- # Compute image hash - a cryptographic clash, securing our flash, in shared dash, in Streamlitโ€™s sash! ๐Ÿ›ก๏ธ๐Ÿ”
143
  def compute_image_hash(image_data):
144
  if isinstance(image_data, Image.Image):
145
  img_byte_arr = io.BytesIO()
@@ -149,7 +156,7 @@ def compute_image_hash(image_data):
149
  img_bytes = image_data
150
  return hashlib.md5(img_bytes).hexdigest()[:8]
151
 
152
- # Node naming - christening the beast, a heroic feast, in shared yeast, in Streamlitโ€™s east! ๐ŸŒ๐Ÿผ
153
  def get_node_name():
154
  parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
155
  parser.add_argument('--node-name', type=str, default=None)
@@ -159,7 +166,7 @@ def get_node_name():
159
  log_action(username, "๐ŸŒ๐Ÿผ - Node naming - christening the beast!")
160
  return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
161
 
162
- # Action logger - spying on deeds, a stealthy steed, in shared need, in Streamlitโ€™s seed! ๐Ÿ•ต๏ธ๐Ÿ“œ
163
  def log_action(username, action):
164
  if 'action_log' not in st.session_state:
165
  st.session_state.action_log = {}
@@ -173,206 +180,34 @@ def log_action(username, action):
173
  f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n")
174
  user_log[action] = current_time
175
 
176
- # Clean text - strip the fancy fluff, a scribeโ€™s tough bluff, in shared puff, in Streamlitโ€™s cuff! ๐Ÿงน๐Ÿ“
177
  def clean_text_for_tts(text):
178
  cleaned = re.sub(r'[#*!\[\]]+', '', text)
179
  cleaned = ' '.join(cleaned.split())
180
- return cleaned if cleaned else "No text to speak" # Default if empty
181
-
182
- # Shared Memory Cache - the epic vault, a shared memory assault, in Streamlitโ€™s fault, in syncโ€™s assault! ๐Ÿ—ณ๏ธ๐Ÿ’พ
183
- @st.cache_resource
184
- def get_shared_memory():
185
- """
186
- Oh, the cache, a grand, shared hall, where data dances, never to fall!
187
- Thread-safe and global, it holds our lore, across users and sessions, forevermore, in Streamlitโ€™s core! ๐ŸŒ๐Ÿง™
188
- """
189
- class SharedMemory:
190
- def __init__(self):
191
- self.chat_history = [] # Condensed dialogs, epic tales condensed, in sync intense!
192
- self.media_files = [] # Media treasures, shared with flair and bends, in syncโ€™s blends!
193
- self.cache_time = datetime.now() # Timestamp of glory, a heroโ€™s blend, in syncโ€™s trend!
194
-
195
- def update_chat(self, entry):
196
- """Add a chat entry, a rhyme in the stream, keeping our saga supreme, in syncโ€™s dream, in Streamlitโ€™s beam! ๐Ÿ’ฌ๐ŸŽถ"""
197
- self.chat_history.append(entry)
198
- if len(self.chat_history) > 100: # Limit to keep it tight, a knightโ€™s fight, in syncโ€™s light!
199
- self.chat_history.pop(0)
200
-
201
- def update_media(self, media_path):
202
- """Store media files, a visual dream, in our shared cache, a radiant beam, in syncโ€™s gleam, in Streamlitโ€™s stream! ๐Ÿ–ผ๏ธ๐ŸŒŸ"""
203
- self.media_files.append(media_path)
204
- if len(self.media_files) > 50: # Cap the hoard, lest it grow too wide, in syncโ€™s tide!
205
- self.media_files.pop(0)
206
-
207
- def get_condensed_dialogs(self):
208
- """Condense the chatter, a poetic pact, short and sweet, our story intact, in syncโ€™s act, in Streamlitโ€™s tract! ๐Ÿ—ฃ๏ธโœจ"""
209
- return "\n".join(f"- {entry.split(': ')[1][:50]}" for entry in self.chat_history[-10:])
210
-
211
- def clear(self):
212
- """Clear the cache, a dramatic purge, resetting our tale, a new surge, in syncโ€™s urge, in Streamlitโ€™s surge! ๐ŸŒ€๐Ÿ”ฅ"""
213
- self.chat_history.clear()
214
- self.media_files.clear()
215
- self.cache_time = datetime.now()
216
-
217
- return SharedMemory()
218
-
219
- # Audio Processor Class - voices echo, a sonic hero, in shared zero, in Streamlitโ€™s hero! ๐ŸŽถ๐ŸŒŸ
220
- class AudioProcessor:
221
- def __init__(self):
222
- self.cache_dir = AUDIO_DIR
223
- os.makedirs(self.cache_dir, exist_ok=True)
224
- self.metadata = self._load_metadata()
225
-
226
- def _load_metadata(self):
227
- metadata_file = os.path.join(self.cache_dir, "metadata.json")
228
- return json.load(open(metadata_file)) if os.path.exists(metadata_file) else {}
229
-
230
- def _save_metadata(self):
231
- metadata_file = os.path.join(self.cache_dir, "metadata.json")
232
- with open(metadata_file, 'w') as f:
233
- json.dump(self.metadata, f)
234
-
235
- async def create_audio(self, text, voice='en-US-AriaNeural', filename=None):
236
- """
237
- Create audio, a voice that roars, in our shared cache, through cosmic doors, in syncโ€™s shores, in Streamlitโ€™s roars! ๐ŸŽค๐ŸŒŒ
238
- """
239
- cache_key = hashlib.md5(f"{text}:{voice}".encode()).hexdigest()
240
- timestamp = format_timestamp_prefix(st.session_state.username)
241
- filename = filename or os.path.join(self.cache_dir, f"audio_{timestamp}_{random.randint(1000, 9999)}.mp3")
242
-
243
- if cache_key in self.metadata and os.path.exists(filename):
244
- return filename
245
-
246
- # Clean text for speech, a bardโ€™s clean sweep, in syncโ€™s deep, in Streamlitโ€™s keep!
247
- text = text.replace("\n", " ").replace("</s>", " ").strip()
248
- if not text:
249
- return None
250
-
251
- # Generate audio, a sonic leap, with edge_tts, our voices deep, in syncโ€™s heap, in Streamlitโ€™s leap!
252
- try:
253
- communicate = edge_tts.Communicate(text, voice)
254
- await communicate.save(filename)
255
- if not os.path.exists(filename):
256
- raise edge_tts.exceptions.NoAudioReceived("No audio file created")
257
- except edge_tts.exceptions.NoAudioReceived as e:
258
- log_action("System ๐ŸŒŸ", f"TTS failed for text '{text}' with voice '{voice}': {str(e)}")
259
- return None
260
-
261
- # Update metadata, our epic creed, in shared memory, a heroic deed, in syncโ€™s need, in Streamlitโ€™s deed!
262
- self.metadata[cache_key] = {
263
- 'timestamp': datetime.now().isoformat(),
264
- 'text_length': len(text),
265
- 'voice': voice
266
- }
267
- self._save_metadata()
268
-
269
- return filename
270
 
271
- # Chat saver - words locked tight, in shared memoryโ€™s light, a shared fight, in Streamlitโ€™s sight! ๐Ÿ’ฌ๐Ÿ”’
272
- async def save_chat_entry(username, message, is_markdown=False, quote_line=None, media_file=None, skip_audio=False):
273
- """
274
- Save chats with flair, in shared cache we dare, a rhyming affair, in syncโ€™s air, in Streamlitโ€™s stare! โœจ๐ŸŽ‰
275
- """
276
  central = pytz.timezone('US/Central')
277
  timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
278
- user_history_file = f"{username}_history.md"
279
- voice = st.session_state.voice if username == st.session_state.username else FUN_USERNAMES.get(username, "en-US-AriaNeural")
280
- indent = " " if quote_line else "" # Nesting for replies, a poetic spree, in syncโ€™s tree!
281
-
282
- # Prepare entry, a verse so bright, in shared memoryโ€™s sight, a shared delight, in Streamlitโ€™s light!
283
  if is_markdown:
284
- entry = f"{indent}[{timestamp}] {username}:\n{indent}```markdown\n{indent}{message}\n{indent}```"
285
  else:
286
- entry = f"{indent}[{timestamp}] {username}: {message}"
287
- if quote_line:
288
- entry = f"{indent}> {quote_line}\n{entry}"
289
-
290
- # Save to global chat file, a shared epic tale, never frail, in syncโ€™s gale, in Streamlitโ€™s veil!
291
- with open(CHAT_FILE, 'a') as f:
292
- f.write(f"{entry}\n")
293
-
294
- # Save to user-specific history, a personal rhyme, in shared time, a shared chime, in Streamlitโ€™s chime!
295
- if not os.path.exists(user_history_file):
296
- with open(user_history_file, 'w') as f:
297
- f.write(f"# Chat History for {username} (Voice: {voice})\n\n")
298
- with open(user_history_file, 'a') as f:
299
- f.write(f"{entry}\n")
300
-
301
- # Generate audio, unless we skip, in shared cache, a sonic grip, in syncโ€™s rip, in Streamlitโ€™s slip!
302
- audio_filename = None # Initialize, lest our tale derail, in syncโ€™s veil, in Streamlitโ€™s trail!
303
- if not skip_audio and message.strip():
304
- cleaned_message = clean_text_for_tts(message)
305
- audio_processor = AudioProcessor()
306
- audio_filename = await audio_processor.create_audio(cleaned_message, voice)
307
- if audio_filename:
308
- with open(HISTORY_FILE, 'a') as f:
309
- f.write(f"[{timestamp}] {username} ({voice}): Audio generated - {audio_filename}\n")
310
- with open(user_history_file, 'a') as f:
311
- f.write(f"{indent}[{timestamp}] Audio: {audio_filename}\n")
312
- with open(CHAT_FILE, 'a') as f:
313
- f.write(f"{indent}[{timestamp}] Audio: {audio_filename}\n")
314
-
315
- # Handle media files, a visual quest, in shared memory, our treasure chest, in syncโ€™s zest, in Streamlitโ€™s nest!
316
- if media_file:
317
- if isinstance(media_file, Image.Image):
318
- timestamp_prefix = format_timestamp_prefix(username)
319
- media_filename = f"{username}-{timestamp_prefix.split('-')[-1]}.{media_file.format.lower()}"
320
- media_path = os.path.join(MEDIA_DIR, media_filename)
321
- img_byte_arr = io.BytesIO()
322
- media_file.save(img_byte_arr, format=media_file.format)
323
- await asyncio.to_thread(lambda: open(media_path, 'wb').write(img_byte_arr.getvalue()))
324
- media_file = media_filename
325
- elif media_file.name in ['png', 'jpg', 'mp4', 'mp3', 'wav']:
326
- timestamp_prefix = format_timestamp_prefix(username)
327
- media_filename = f"{username}-{timestamp_prefix.split('-')[-1]}.{media_file.name.split('.')[-1]}"
328
- media_path = os.path.join(MEDIA_DIR, media_filename)
329
- await asyncio.to_thread(lambda: open(media_path, 'wb').write(media_file.getbuffer()))
330
- media_file = media_filename
331
- elif media_file.name == 'pdf':
332
- timestamp_prefix = format_timestamp_prefix(username)
333
- file_hash = hashlib.md5(media_file.getbuffer()).hexdigest()[:8]
334
- media_filename = f"{username}-{timestamp_prefix.split('-')[-1]}-{file_hash}.pdf"
335
- media_path = os.path.join(MEDIA_DIR, media_filename)
336
- await asyncio.to_thread(lambda: open(media_path, 'wb').write(media_file.getbuffer()))
337
- media_file = media_filename
338
- with open(CHAT_FILE, 'a') as f:
339
- f.write(f"{indent}[{timestamp}] Media: ![Media]({media_file})\n")
340
- with open(user_history_file, 'a') as f:
341
- f.write(f"{indent}[{timestamp}] Media: ![Media]({media_file})\n")
342
-
343
- # Update shared memory, our epic lore, in cache forevermore, in syncโ€™s core, in Streamlitโ€™s lore!
344
- shared_memory = get_shared_memory()
345
- shared_memory.update_chat(entry)
346
- if media_file:
347
- shared_memory.update_media(os.path.join(MEDIA_DIR, media_file))
348
-
349
  await broadcast_message(f"{username}|{message}", "chat")
350
  st.session_state.last_chat_update = time.time()
351
- return audio_filename # Return, even if silent, our taleโ€™s delight, in syncโ€™s flight, in Streamlitโ€™s sight!
352
 
353
- # Save chat history with image or PDF - a scribeโ€™s historic flight, in shared night, in Streamlitโ€™s light! ๐Ÿ“œ๐Ÿš€
354
- async def save_chat_history_with_image(username, image_path):
355
- """
356
- Save history, a scribeโ€™s grand sight, in shared memory, pure and bright, in syncโ€™s light, in Streamlitโ€™s right! โœจ๐Ÿ“–
357
- """
358
- central = pytz.timezone('US/Central')
359
- timestamp = datetime.now(central).strftime("%Y-%m-%d_%H-%M-%S")
360
- user_history_file = f"{username}_history.md"
361
- chat_content = await load_chat()
362
- voice = st.session_state.voice if username == st.session_state.username else FUN_USERNAMES.get(username, "en-US-AriaNeural")
363
- if not os.path.exists(user_history_file):
364
- with open(user_history_file, 'w') as f:
365
- f.write(f"# Chat History for {username} (Voice: {voice})\n\n")
366
- with open(user_history_file, 'a') as f:
367
- f.write(f"[{timestamp}] {username} (Voice: {voice}) Shared Media: {os.path.basename(image_path)}\n")
368
- f.write(f"```markdown\n{chat_content}\n```\n")
369
-
370
- # Chat loader - history unleashed, a shared epic feast, in shared beast, in Streamlitโ€™s east! ๐Ÿ“œ๐Ÿš€
371
- @st.cache_resource
372
  async def load_chat():
373
- """
374
- Load chats, a shared memory spree, from cache with glee, our history free, in syncโ€™s sea, in Streamlitโ€™s tree! ๐ŸŒŸ๐Ÿ’ฌ
375
- """
376
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
377
  await asyncio.to_thread(log_action, username, "๐Ÿ“œ๐Ÿš€ - Chat loader - history unleashed!")
378
  if not os.path.exists(CHAT_FILE):
@@ -381,11 +216,8 @@ async def load_chat():
381
  content = await asyncio.to_thread(f.read)
382
  return content
383
 
384
- # User lister - whoโ€™s in the gang, a shared memory bang, in shared rang, in Streamlitโ€™s gang! ๐Ÿ‘ฅ๐ŸŽ‰
385
  async def get_user_list(chat_content):
386
- """
387
- List users, a shared rosterโ€™s rhyme, in cache divine, through space and time, in syncโ€™s chime, in Streamlitโ€™s time! ๐ŸŒ๐ŸŽญ
388
- """
389
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
390
  await asyncio.to_thread(log_action, username, "๐Ÿ‘ฅ๐ŸŽ‰ - User lister - whoโ€™s in the gang!")
391
  users = set()
@@ -395,32 +227,22 @@ async def get_user_list(chat_content):
395
  users.add(user)
396
  return sorted(list(users))
397
 
398
- # Join checker - been here before, in shared cache, a lore galore, in shared shore, in Streamlitโ€™s lore! ๐Ÿšช๐Ÿ”
399
  async def has_joined_before(client_id, chat_content):
400
- """
401
- Check joins, a shared memory chore, in cache secure, forevermore, in syncโ€™s lore, in Streamlitโ€™s core! ๐ŸŒ€๐Ÿ”
402
- """
403
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
404
  await asyncio.to_thread(log_action, username, "๐Ÿšช๐Ÿ” - Join checker - been here before?")
405
  return any(f"Client-{client_id}" in line for line in chat_content.split('\n'))
406
 
407
- # Suggestion maker - old quips resurface, in shared cache, a verse so fierce, in shared pierce, in Streamlitโ€™s fierce! ๐Ÿ’ก๐Ÿ“
408
  async def get_message_suggestions(chat_content, prefix):
409
- """
410
- Suggest quips, a shared memory jest, in cache we nest, our humor blessed, in syncโ€™s zest, in Streamlitโ€™s best! ๐Ÿ˜‚๐ŸŒŸ
411
- """
412
  username = st.session_state.get('username', 'System ๏ฟฝ๏ฟฝ')
413
  await asyncio.to_thread(log_action, username, "๐Ÿ’ก๐Ÿ“ - Suggestion maker - old quips resurface!")
414
  lines = chat_content.split('\n')
415
  messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
416
  return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5]
417
 
418
- # Vote saver - cheers recorded, in shared cache, our cheers restored, in shared chord, in Streamlitโ€™s cord! ๐Ÿ‘๐Ÿ“Š
419
- @st.cache_resource
420
  async def save_vote(file, item, user_hash, username, comment=""):
421
- """
422
- Save votes, a shared tallyโ€™s cheer, in cache so clear, our triumph near, in syncโ€™s spear, in Streamlitโ€™s near! ๐Ÿ†๐ŸŽ‰
423
- """
424
  await asyncio.to_thread(log_action, username, "๐Ÿ‘๐Ÿ“Š - Vote saver - cheers recorded!")
425
  central = pytz.timezone('US/Central')
426
  timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
@@ -431,14 +253,9 @@ async def save_vote(file, item, user_hash, username, comment=""):
431
  if comment:
432
  chat_message += f" - {comment}"
433
  await save_chat_entry(username, chat_message)
434
- return entry # Return for caching, our epic fling, in syncโ€™s ring, in Streamlitโ€™s sing!
435
 
436
- # Vote counter - tallying the love, in shared cache, a tale above, in shared glove, in Streamlitโ€™s love! ๐Ÿ†๐Ÿ“ˆ
437
- @st.cache_resource
438
  async def load_votes(file):
439
- """
440
- Count votes, a shared tallyโ€™s might, in cache so bright, our victoryโ€™s light, in syncโ€™s fight, in Streamlitโ€™s light! ๐ŸŒŸ๐Ÿ“Š
441
- """
442
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
443
  await asyncio.to_thread(log_action, username, "๐Ÿ†๐Ÿ“ˆ - Vote counter - tallying the love!")
444
  if not os.path.exists(file):
@@ -458,139 +275,74 @@ async def load_votes(file):
458
  user_votes.add(vote_key)
459
  return votes
460
 
461
- # Hash generator - secret codes ahoy, in shared cache, a cryptic joy, in shared toy, in Streamlitโ€™s joy! ๐Ÿ”‘๐Ÿ•ต๏ธ
462
  async def generate_user_hash():
463
- """
464
- Generate hashes, a shared codeโ€™s chime, in cache sublime, through space and time, in syncโ€™s rhyme, in Streamlitโ€™s chime! ๐ŸŒŒ๐Ÿ”
465
- """
466
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
467
  await asyncio.to_thread(log_action, username, "๐Ÿ”‘๐Ÿ•ต๏ธ - Hash generator - secret codes ahoy!")
468
  if 'user_hash' not in st.session_state:
469
  st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8]
470
  return st.session_state.user_hash
471
 
472
- # Audio maker - voices come alive, in shared cache, a sonic dive, in shared hive, in Streamlitโ€™s dive! ๐ŸŽถ๐ŸŒŸ
473
  async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
474
- """
475
- Make audio, a shared voiceโ€™s thrill, in cache we fill, with sonic will, in syncโ€™s hill, in Streamlitโ€™s will! ๐ŸŽค๐Ÿ”Š
476
- """
477
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
478
  await asyncio.to_thread(log_action, username, "๐ŸŽถ๐ŸŒŸ - Audio maker - voices come alive!")
479
  timestamp = format_timestamp_prefix(username)
480
- filename = os.path.join(AUDIO_DIR, f"audio_{timestamp}_{random.randint(1000, 9999)}.mp3")
 
481
  communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
482
  try:
483
- await communicate.save(filename)
484
- return filename if os.path.exists(filename) else None
485
  except edge_tts.exceptions.NoAudioReceived:
486
  with open(HISTORY_FILE, 'a') as f:
487
  central = pytz.timezone('US/Central')
488
  f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: Audio failed - No audio received for '{text}'\n")
489
  return None
490
 
491
- # Audio player - tunes blast off, in shared cache, a musical scoff, in shared toff, in Streamlitโ€™s scoff! ๐Ÿ”Š๐Ÿš€
492
  def play_and_download_audio(file_path):
493
- """
494
- Play tunes, a shared melodyโ€™s jest, in cache expressed, our audio quest, in syncโ€™s zest, in Streamlitโ€™s quest! ๐ŸŽต๐ŸŒŒ
495
- """
496
  if file_path and os.path.exists(file_path):
497
  st.audio(file_path)
498
- with open(file_path, "rb") as f:
499
- b64 = base64.b64encode(f.read()).decode()
 
 
 
500
  dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">๐ŸŽต Download {os.path.basename(file_path)}</a>'
501
  st.markdown(dl_link, unsafe_allow_html=True)
502
 
503
- # Image saver - pics preserved, in shared cache, a visual burst, in shared thirst, in Streamlitโ€™s burst! ๐Ÿ“ธ๐Ÿ’พ
504
  async def save_pasted_image(image, username):
505
- """
506
- Save images, a shared sightโ€™s cheer, in cache so clear, our vision near, in syncโ€™s spear, in Streamlitโ€™s near! ๐Ÿ–ผ๏ธ๐ŸŒŸ
507
- """
508
  await asyncio.to_thread(log_action, username, "๐Ÿ“ธ๐Ÿ’พ - Image saver - pics preserved!")
 
 
 
509
  timestamp = format_timestamp_prefix(username)
510
- media_filename = f"{username}-{timestamp.split('-')[-1]}.png"
511
- media_path = os.path.join(MEDIA_DIR, media_filename)
512
- img_byte_arr = io.BytesIO()
513
- image.save(img_byte_arr, format='PNG')
514
- await asyncio.to_thread(lambda: open(media_path, 'wb').write(img_byte_arr.getvalue()))
515
- return media_filename
516
-
517
- # Video and Audio savers - media magic, in shared cache, a heroic tragic, in shared magic, in Streamlitโ€™s magic! ๐ŸŽฅ๐ŸŽถ
518
- async def save_media(file, username, ext):
519
- """
520
- Save media, a shared epicโ€™s might, in cache so bright, our treasures ignite, in syncโ€™s kite, in Streamlitโ€™s kite! ๐Ÿง™๐Ÿ”ฅ
521
- """
522
- await asyncio.to_thread(log_action, username, f"๐Ÿ“ธ๐Ÿ’พ - Media saver - {ext} preserved!")
523
- timestamp = format_timestamp_prefix(username)
524
- media_filename = f"{username}-{timestamp.split('-')[-1]}.{ext}"
525
- media_path = os.path.join(MEDIA_DIR, media_filename)
526
- await asyncio.to_thread(lambda: open(media_path, 'wb').write(file.getbuffer()))
527
- return media_filename
528
-
529
- # PDF saver and audio generator - documents dance, in shared cache, a chance, in shared trance, in Streamlitโ€™s dance! ๐Ÿ“œ๐ŸŽถ
530
- async def save_pdf_and_generate_audio(pdf_file, username, max_pages=10):
531
- """
532
- Save PDFs, a shared documentโ€™s glee, in cache we see, our historyโ€™s key, in syncโ€™s sea, in Streamlitโ€™s key! ๐Ÿ“š๐ŸŒŸ
533
- """
534
- await asyncio.to_thread(log_action, username, "๐Ÿ“œ๐ŸŽถ - PDF saver and audio generator!")
535
- timestamp = format_timestamp_prefix(username)
536
- file_hash = hashlib.md5(pdf_file.getbuffer()).hexdigest()[:8]
537
- pdf_filename = f"{username}-{timestamp.split('-')[-1]}-{file_hash}.pdf"
538
- media_path = os.path.join(MEDIA_DIR, pdf_filename)
539
- with open(media_path, 'wb') as f:
540
- f.write(pdf_file.getbuffer())
541
-
542
- reader = PdfReader(media_path)
543
- total_pages = min(len(reader.pages), max_pages)
544
- texts = []
545
- audio_files = []
546
-
547
- audio_processor = AudioProcessor()
548
- voice = st.session_state.voice if username == st.session_state.username else FUN_USERNAMES.get(username, "en-US-AriaNeural")
549
-
550
- for i in range(total_pages):
551
- text = reader.pages[i].extract_text()
552
- texts.append(text)
553
- audio_filename = f"{username}-{timestamp.split('-')[-1]}-page{i+1}-{file_hash}-voice-{voice}.mp3"
554
- audio_path = os.path.join(AUDIO_DIR, audio_filename)
555
- audio_data = await audio_processor.create_audio(text, voice, audio_path)
556
- if audio_data:
557
- audio_files.append(audio_filename)
558
-
559
- return pdf_filename, texts, audio_files
560
-
561
- # Video renderer - movies roll, in shared cache, a visual toll, in shared roll, in Streamlitโ€™s roll! ๐ŸŽฅ๐ŸŽฌ
562
- def get_video_html(video_path, width="100px"):
563
- """
564
- Render videos, a shared screenโ€™s thrill, in cache we fill, with cinematic will, in syncโ€™s hill, in Streamlitโ€™s will! ๐Ÿ“บ๐ŸŒŒ
565
- """
566
- video_url = f"data:video/mp4;base64,{base64.b64encode(open(os.path.join(MEDIA_DIR, video_path), 'rb').read()).decode()}"
567
- return f'''
568
- <video width="{width}" controls autoplay muted loop>
569
- <source src="{video_url}" type="video/mp4">
570
- Your browser does not support the video tag.
571
- </video>
572
- '''
573
-
574
- # Audio renderer - sounds soar, in shared cache, a sonic roar, in shared roar, in Streamlitโ€™s roar! ๐ŸŽถโœˆ๏ธ
575
- async def get_audio_html(audio_path, width="100px"):
576
- """
577
- Render audio, a shared soundโ€™s cheer, in cache so clear, our music near, in syncโ€™s spear, in Streamlitโ€™s near! ๐ŸŽต๐ŸŒŸ
578
- """
579
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
580
  await asyncio.to_thread(log_action, username, "๐ŸŽถโœˆ๏ธ - Audio renderer - sounds soar!")
581
- audio_url = f"data:audio/mpeg;base64,{base64.b64encode(await asyncio.to_thread(open, os.path.join(AUDIO_DIR, audio_path), 'rb').read()).decode()}"
582
- return f'''
583
- <audio controls style="width: {width};">
584
- <source src="{audio_url}" type="audio/mpeg">
585
- Your browser does not support the audio element.
586
- </audio>
587
- '''
588
-
589
- # Websocket handler - chat links up, in shared cache, a connectionโ€™s cup, in shared cup, in Streamlitโ€™s cup! ๐ŸŒ๐Ÿ”—
590
  async def websocket_handler(websocket, path):
591
- """
592
- Handle chats, a shared linkโ€™s might, in cache so bright, our networkโ€™s light, in syncโ€™s night, in Streamlitโ€™s light! ๐ŸŒ๐Ÿ”Œ
593
- """
594
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
595
  await asyncio.to_thread(log_action, username, "๐ŸŒ๐Ÿ”— - Websocket handler - chat links up!")
596
  try:
@@ -612,11 +364,8 @@ async def websocket_handler(websocket, path):
612
  if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
613
  del st.session_state.active_connections[room_id][client_id]
614
 
615
- # Message broadcaster - words fly far, in shared cache, a starry czar, in shared star, in Streamlitโ€™s star! ๐Ÿ“ขโœˆ๏ธ
616
  async def broadcast_message(message, room_id):
617
- """
618
- Broadcast words, a shared echoโ€™s cheer, in cache so clear, our message near, in syncโ€™s spear, in Streamlitโ€™s near! ๐ŸŒ ๐Ÿ“ก
619
- """
620
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
621
  await asyncio.to_thread(log_action, username, "๐Ÿ“ขโœˆ๏ธ - Message broadcaster - words fly far!")
622
  if room_id in st.session_state.active_connections:
@@ -629,11 +378,8 @@ async def broadcast_message(message, room_id):
629
  for client_id in disconnected:
630
  del st.session_state.active_connections[room_id][client_id]
631
 
632
- # Server starter - web spins up, in shared cache, a digital pup, in shared pup, in Streamlitโ€™s pup! ๐Ÿ–ฅ๏ธ๐ŸŒ€
633
  async def run_websocket_server():
634
- """
635
- Start server, a shared spinโ€™s delight, in cache so right, our web takes flight, in syncโ€™s night, in Streamlitโ€™s flight! ๐Ÿš€๐ŸŒ
636
- """
637
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
638
  await asyncio.to_thread(log_action, username, "๐Ÿ–ฅ๏ธ๐ŸŒ€ - Server starter - web spins up!")
639
  if not st.session_state.server_running:
@@ -641,212 +387,327 @@ async def run_websocket_server():
641
  st.session_state.server_running = True
642
  await server.wait_closed()
643
 
644
- # Delete all user files - a purge so grand, in shared cache, a clearing band, in shared land, in Streamlitโ€™s band! ๐Ÿ—‘๏ธ๐Ÿ”ฅ
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
645
  def delete_user_files():
646
- """
647
- Delete files, a shared purgeโ€™s might, in cache so light, our slate wiped tight, in syncโ€™s night, in Streamlitโ€™s tight! ๐Ÿงน๐ŸŒŒ
648
- """
649
- protected_files = {'app.py', 'requirements.txt', 'README.md', CHAT_FILE, QUOTE_VOTES_FILE, MEDIA_VOTES_FILE, HISTORY_FILE, STATE_FILE, AUDIO_DIR, MEDIA_DIR}
650
  deleted_files = []
651
- for file in os.listdir('.'):
652
- if file not in protected_files and not file.endswith('_history.md'):
653
- try:
654
- os.remove(file)
655
- deleted_files.append(file)
656
- except Exception as e:
657
- st.error(f"Failed to delete {file}: {e}")
658
- for root, dirs, files in os.walk(AUDIO_DIR):
659
- for file in files:
660
- file_path = os.path.join(root, file)
 
 
 
 
 
 
661
  try:
662
- os.remove(file_path)
663
- deleted_files.append(file_path)
664
  except Exception as e:
665
- st.error(f"Failed to delete {file_path}: {e}")
666
- for root, dirs, files in os.walk(MEDIA_DIR):
667
- for file in files:
668
- file_path = os.path.join(root, file)
669
- try:
670
- os.remove(file_path)
671
- deleted_files.append(file_path)
672
- except Exception as e:
673
- st.error(f"Failed to delete {file_path}: {e}")
674
  st.session_state.image_hashes.clear()
675
  st.session_state.audio_cache.clear()
676
  st.session_state.base64_cache.clear()
677
  st.session_state.displayed_chat_lines.clear()
678
- shared_memory = get_shared_memory()
679
- shared_memory.clear() # Clear shared cache on purge, in syncโ€™s surge, in Streamlitโ€™s surge!
680
  return deleted_files
681
 
682
- # Query parameter checker - parse q with flair, in shared cache, a naming affair, in shared air, in Streamlitโ€™s air! ๐Ÿšช๐Ÿ”
683
- def check_query_params():
684
- """
685
- Check queries, a shared nameโ€™s quest, in cache so blessed, our path expressed, in syncโ€™s zest, in Streamlitโ€™s best! ๐ŸŒŸ๐Ÿ”
686
- """
687
- query_params = st.query_params if hasattr(st, 'query_params') else st.experimental_get_query_params()
688
- q_value = query_params.get("q", [None])[0]
689
- if q_value and q_value in FUN_USERNAMES:
690
- st.session_state.username = q_value
691
- st.session_state.voice = FUN_USERNAMES[q_value]
692
- return q_value
693
- elif q_value:
694
- st.session_state.user_id = q_value # Use as user_id if not a valid username
695
- return None
696
-
697
- # Mermaid graph generator - visualize our tale, in shared cache, a graphic gale, in shared vale, in Streamlitโ€™s gale! ๐ŸŒณ๐Ÿ“ˆ
698
- def generate_mermaid_graph(chat_lines):
699
- """
700
- Generate graphs, a shared visionโ€™s rhyme, in cache sublime, our storyโ€™s chime, in syncโ€™s time, in Streamlitโ€™s chime! ๐Ÿงฉ๐ŸŒŒ
701
- """
702
- mermaid_code = "graph TD\n"
703
- nodes = {}
704
- edges = []
705
- for i, line in enumerate(chat_lines):
706
- if line.strip() and not line.startswith(' '):
707
- timestamp = line.split('] ')[0][1:] if '] ' in line else "Unknown"
708
- content = line.split(': ', 1)[1] if ': ' in line else line
709
- user = content.split(' ')[0]
710
- message = content.split(' ', 1)[1] if ' ' in content else ''
711
- node_id = f"{user}_{i}"
712
- nodes[node_id] = f"{user}: {message[:20]}..." if len(message) > 20 else f"{user}: {message}"
713
- if i + 1 < len(chat_lines) and "Audio:" in chat_lines[i + 1]:
714
- audio_node = f"audio_{i}"
715
- nodes[audio_node] = "๐ŸŽต"
716
- edges.append(f"{node_id} --> {audio_node}")
717
- if i + 2 < len(chat_lines) and "Media:" in chat_lines[i + 2]:
718
- media_node = f"media_{i}"
719
- nodes[media_node] = "๐Ÿ–ผ"
720
- edges.append(f"{node_id} --> {media_node}")
721
- if i > 0 and "> " in line:
722
- parent_user = chat_lines[i-1].split(': ')[1].split(' ')[0]
723
- parent_id = f"{parent_user}_{i-1}"
724
- edges.append(f"{parent_id} --> {node_id}")
725
-
726
- for node_id, label in nodes.items():
727
- mermaid_code += f" {node_id}[\"{label}\"]\n"
728
- mermaid_code += "\n".join(f" {edge}" for edge in edges)
729
- return mermaid_code
730
-
731
- # Main execution - letโ€™s roll, in shared cache, a heroic toll, in shared soul, in Streamlitโ€™s roll! ๐ŸŽฒ๐Ÿš€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732
  def main():
733
- """
734
- Launch our saga, a shared memoryโ€™s cheer, in Streamlitโ€™s cache, our epic year, in syncโ€™s spear, in Streamlitโ€™s year! ๐Ÿš€โœจ
735
- """
736
  NODE_NAME, port = get_node_name()
737
 
738
- # Use Streamlitโ€™s event loop or create a new one safely, avoiding reuse errors! ๐ŸŒ€๐Ÿ”„
739
- try:
740
- loop = asyncio.get_event_loop()
741
- if loop.is_closed():
742
- loop = asyncio.new_event_loop()
743
- asyncio.set_event_loop(loop)
744
- except RuntimeError:
745
- loop = asyncio.new_event_loop()
746
- asyncio.set_event_loop(loop)
747
-
748
- # Run async interface within the loop, ensuring no reuse or nested awaits! ๐ŸŒŸ๐ŸŽญ
749
- loop.run_until_complete(async_interface())
750
- loop.close()
751
-
752
- # Async interface - our epic quest, in shared cache, a tale expressed, in syncโ€™s zest, in Streamlitโ€™s quest! ๐ŸŽญ๐ŸŒŸ
753
- async def async_interface():
754
- # Generate user ID and hash, a shared identityโ€™s clash, in syncโ€™s flash, in Streamlitโ€™s clash! ๐Ÿ†”๐Ÿ”ฎ
755
- if not st.session_state.user_id:
756
- st.session_state.user_id = str(uuid.uuid4())
757
- st.session_state.user_hash = await generate_user_hash()
758
-
759
- # Check query params, a shared nameโ€™s quest, in cache expressed, our path impressed, in syncโ€™s zest, in Streamlitโ€™s quest! ๐Ÿšช๐Ÿ”
760
- q_value = check_query_params()
761
- if not q_value and 'username' not in st.session_state:
762
- chat_content = await load_chat()
763
- available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
764
- st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
765
- st.session_state.voice = FUN_USERNAMES[st.session_state.username]
766
- st.markdown(f"**๐ŸŽ™๏ธ Voice Selected**: {st.session_state.voice} ๐Ÿ—ฃ๏ธ for {st.session_state.username}")
767
-
768
- # Check existing history, a shared memoryโ€™s cheer, in cache so clear, our lore near, in syncโ€™s spear, in Streamlitโ€™s near! ๐Ÿ“œ๐ŸŒŸ
769
- user_history_file = f"{st.session_state.username}_history.md"
770
- if os.path.exists(user_history_file):
771
- with open(user_history_file, 'r') as f:
772
- st.session_state.displayed_chat_lines = f.read().split('\n')
773
-
774
- user_url = f"/q={st.session_state.username}"
775
- with st.container():
776
- st.markdown(f"<small>Your unique URL path: [{user_url}]({user_url})</small>", unsafe_allow_html=True)
777
-
778
- with st.container():
779
- st.markdown(f"#### ๐Ÿค–๐Ÿง MMO {st.session_state.username}๐Ÿ“๐Ÿ”ฌ")
780
- st.markdown(f"<small>Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! ๐ŸŽ‰ User ID: {st.session_state.user_id}</small>", unsafe_allow_html=True)
781
-
782
- if not st.session_state.server_task:
783
- st.session_state.server_task = asyncio.create_task(run_websocket_server())
784
-
785
- # Unified Chat History at Top - a shared epicโ€™s roar, condensed and stored, in syncโ€™s cord, in Streamlitโ€™s cord! ๐Ÿ’ฌ๐ŸŒŒ
786
- with st.container():
787
- st.markdown(f"##### {START_ROOM} Chat History ๐Ÿ’ฌ")
788
- shared_memory = get_shared_memory()
789
  chat_content = await load_chat()
790
- chat_lines = [line for line in chat_content.split('\n') if line.strip() and not line.startswith('#')]
791
- if chat_lines:
792
- chat_by_minute = {}
793
- for line in reversed(chat_lines):
794
- timestamp = line.split('] ')[0][1:] if '] ' in line else "Unknown"
795
- minute_key = timestamp[:16] # Up to minute
796
- if minute_key not in chat_by_minute:
797
- chat_by_minute[minute_key] = []
798
- chat_by_minute[minute_key].append(line)
799
-
800
- markdown_output = ""
801
- for minute, lines in chat_by_minute.items():
802
- minute_output = f"###### {minute[-5:]}\n" # Show only HH:MM
803
- for line in lines:
804
- if ': ' in line and not line.startswith(' '):
805
- user_message = line.split(': ', 1)[1]
806
- user = user_message.split(' ')[0]
807
- msg = user_message.split(' ', 1)[1] if ' ' in user_message else ''
808
- audio_html = ""
809
- media_content = ""
810
- next_lines = chat_lines[chat_lines.index(line)+1:chat_lines.index(line)+3]
811
- for nl in next_lines:
812
- if "Audio:" in nl:
813
- audio_file = nl.split("Audio: ")[-1].strip()
814
- audio_html = play_and_download_audio(audio_file)
815
- elif "Media:" in nl:
816
- media_file = nl.split("Media: ")[-1].strip('![]()')
817
- media_path = os.path.join(MEDIA_DIR, media_file)
818
- if os.path.exists(media_path):
819
- if media_file.endswith(('.png', '.jpg')):
820
- media_content = f"<img src='file://{media_path}' width='100'>"
821
- elif media_file.endswith('.mp4'):
822
- media_content = get_video_html(media_file)
823
- elif media_file.endswith('.mp3'):
824
- media_content = await get_audio_html(media_file)
825
- elif media_file.endswith('.pdf'):
826
- media_content = f"๐Ÿ“œ {os.path.basename(media_file)}"
827
- minute_output += f"- ๐Ÿ’ฌ **{user}**: {msg[:50]}... {audio_html} {media_content}\n" # Condensed dialog
828
- markdown_output += minute_output
829
- st.markdown(markdown_output, unsafe_allow_html=True)
830
- shared_memory.update_chat(markdown_output) # Cache condensed dialogs, in syncโ€™s log, in Streamlitโ€™s fog!
831
-
832
- # Condensed Dialogs Display - a shared tale, concise and hale, in shared vale, in Streamlitโ€™s tale! ๐Ÿ—ฃ๏ธโœจ
833
- st.markdown("###### Condensed Dialogs ๐Ÿ—ฃ๏ธ")
834
- condensed_dialogs = shared_memory.get_condensed_dialogs()
835
- st.markdown(condensed_dialogs)
836
-
837
- # Mermaid Graph Visualization - a shared map, our chatโ€™s trap, in shared cap, in Streamlitโ€™s map! ๐ŸŒณ๐Ÿ“ˆ
838
- st.markdown("###### Chat Relationship Tree ๐ŸŒณ")
839
- mermaid_code = generate_mermaid_graph(chat_lines)
840
- mermaid_html = f"""
841
- <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
842
- <div class="mermaid" style="height: 200px; overflow: auto;">{mermaid_code}</div>
843
- <script>mermaid.initialize({{startOnLoad:true}});</script>
844
- """
845
- components.html(mermaid_html, height=250)
846
-
847
- with st.container():
 
 
 
 
 
848
  if st.session_state.quote_line:
849
- st.markdown(f"###### Quoting: {st.session_state.quote_line}")
850
  quote_response = st.text_area("Add your response", key="quote_response", value=st.session_state.message_text)
851
  paste_result_quote = paste_image_button("๐Ÿ“‹ Paste Image or Text with Quote", key="paste_button_quote")
852
  if paste_result_quote.image_data is not None:
@@ -858,14 +719,13 @@ async def async_interface():
858
  filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
859
  if filename:
860
  st.session_state.pasted_image_data = filename
861
- await save_chat_entry(st.session_state.username, f"Pasted image: {filename}", quote_line=st.session_state.quote_line, media_file=paste_result_quote.image_data)
862
  if st.button("Send Quote ๐Ÿš€", key="send_quote"):
863
  markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
864
  if st.session_state.pasted_image_data:
865
  markdown_response += f"\n- **Image**: ![Pasted Image]({st.session_state.pasted_image_data})"
866
- await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}", quote_line=st.session_state.quote_line, media_file=st.session_state.pasted_image_data)
867
  st.session_state.pasted_image_data = None
868
- await save_chat_entry(st.session_state.username, markdown_response, is_markdown=True, quote_line=st.session_state.quote_line)
869
  st.session_state.quote_line = None
870
  st.session_state.message_text = ''
871
  st.rerun()
@@ -879,157 +739,105 @@ async def async_interface():
879
  st.markdown(f"**๐ŸŽ™๏ธ Voice Changed**: {st.session_state.voice} ๐Ÿ—ฃ๏ธ for {st.session_state.username}")
880
  st.rerun()
881
 
882
- # Message input with Send button - a shared chatโ€™s might, in shared night, in Streamlitโ€™s might! ๐Ÿ’ฌ๐Ÿš€
883
- col_input, col_send = st.columns([5, 1])
884
- with col_input:
885
- message = st.text_input(f"Message as {st.session_state.username} (Voice: {st.session_state.voice})", key="message_input", value=st.session_state.message_text)
886
- with col_send:
887
- if st.button("Send ๐Ÿš€", key="send_button"):
888
- if message.strip() or st.session_state.pasted_image_data:
889
- await save_chat_entry(st.session_state.username, message if message.strip() else "Image shared", is_markdown=True, media_file=st.session_state.pasted_image_data if st.session_state.pasted_image_data else None, skip_audio=not message.strip())
890
- if st.session_state.pasted_image_data:
891
- st.session_state.pasted_image_data = None
892
- st.session_state.message_text = ''
893
- st.rerun()
894
-
895
  paste_result_msg = paste_image_button("๐Ÿ“‹ Paste Image or Text with Message", key="paste_button_msg")
896
  if paste_result_msg.image_data is not None:
897
  if isinstance(paste_result_msg.image_data, str):
898
  st.session_state.message_text = paste_result_msg.image_data
899
  st.text_input(f"Message as {st.session_state.username} (Voice: {st.session_state.voice})", key="message_input_paste", value=st.session_state.message_text)
900
  else:
901
- st.image(paste_result_msg.image_data, caption="Received Image for Quote")
902
  filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
903
  if filename:
904
- await save_chat_entry(st.session_state.username, "Image shared", is_markdown=True, media_file=paste_result_msg.image_data, skip_audio=True)
905
- st.session_state.pasted_image_data = None
906
- st.rerun()
 
 
 
 
 
 
 
 
907
 
908
- with st.container():
909
- st.markdown("###### Upload Media ๐ŸŽจ๐ŸŽถ๐Ÿ“œ๐ŸŽฅ")
910
- uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3', 'wav', 'pdf', 'txt', 'md', 'py'])
 
 
 
911
  if uploaded_file:
912
  timestamp = format_timestamp_prefix(st.session_state.username)
913
  username = st.session_state.username
914
- ext = uploaded_file.name.split('.')[-1].lower()
915
- if ext in ['png', 'jpg']:
916
- filename = await save_pasted_image(uploaded_file, username)
917
- elif ext in ['mp4', 'mp3', 'wav']:
918
- filename = await save_media(uploaded_file, username, ext)
919
- elif ext == 'pdf':
920
- pdf_filename, _, _ = await save_pdf_and_generate_audio(uploaded_file, username)
921
- filename = pdf_filename
922
- else:
923
- filename = f"{username}-{timestamp.split('-')[-1]}.{ext}"
924
- media_path = os.path.join(MEDIA_DIR, filename)
925
- await asyncio.to_thread(lambda: open(media_path, 'wb').write(uploaded_file.getbuffer()))
926
- await save_chat_entry(username, f"Uploaded {ext.upper()}: {os.path.basename(filename)}", media_file=uploaded_file, skip_audio=True)
927
- shared_memory = get_shared_memory()
928
- shared_memory.update_media(os.path.join(MEDIA_DIR, filename)) # Cache media, in syncโ€™s sea, in Streamlitโ€™s sea!
929
- st.success(f"Uploaded {filename}")
930
-
931
- # Big Red Delete Button - a purge so grand, clearing our shared land, in syncโ€™s sand, in Streamlitโ€™s sand! ๐Ÿ—‘๏ธ๐Ÿ”ฅ
932
- st.markdown("###### ๐Ÿ›‘ Danger Zone")
933
  if st.button("Try Not To Delete It All On Your First Day", key="delete_all", help="Deletes all user-added files!", type="primary", use_container_width=True):
934
  deleted_files = delete_user_files()
935
  if deleted_files:
936
  st.markdown("### ๐Ÿ—‘๏ธ Deleted Files:\n" + "\n".join([f"- `{file}`" for file in deleted_files]))
937
- shared_memory = get_shared_memory()
938
- shared_memory.clear() # Clear shared cache on purge, in syncโ€™s surge, in Streamlitโ€™s surge!
939
  else:
940
  st.markdown("### ๐Ÿ—‘๏ธ Nothing to Delete!")
 
 
 
 
941
  st.rerun()
942
 
943
- st.markdown("###### Refresh โณ")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
944
  refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
945
  st.session_state.refresh_rate = refresh_rate
946
  timer_placeholder = st.empty()
947
  for i in range(st.session_state.refresh_rate, -1, -1):
948
  font_name, font_func = random.choice(UNICODE_FONTS)
949
  countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
950
- timer_placeholder.markdown(f"<small>โณ {font_func('Refresh in:')} {countdown_str}</small>", unsafe_allow_html=True)
951
- await asyncio.sleep(1) # Use asyncio.sleep for async context, in syncโ€™s nest, in Streamlitโ€™s nest!
952
  st.rerun()
953
 
954
- # Separate Galleries for Own and Shared Files - a shared galleryโ€™s glare, in shared air, in Streamlitโ€™s air! ๐Ÿ–ผ๏ธ๐ŸŽฅ
955
- with st.container():
956
- all_files = glob.glob(os.path.join(MEDIA_DIR, "*.md")) + glob.glob(os.path.join(MEDIA_DIR, "*.pdf")) + glob.glob(os.path.join(MEDIA_DIR, "*.txt")) + glob.glob(os.path.join(MEDIA_DIR, "*.py")) + glob.glob(os.path.join(MEDIA_DIR, "*.png")) + glob.glob(os.path.join(MEDIA_DIR, "*.jpg")) + glob.glob(os.path.join(MEDIA_DIR, "*.mp3")) + glob.glob(os.path.join(MEDIA_DIR, "*.mp4")) + glob.glob(os.path.join(AUDIO_DIR, "*.mp3"))
957
- shared_memory = get_shared_memory()
958
- own_files = [f for f in all_files if st.session_state.user_id in os.path.basename(f) or st.session_state.username in os.path.basename(f)]
959
- shared_files = [f for f in all_files if f not in own_files and not f in [CHAT_FILE, QUOTE_VOTES_FILE, MEDIA_VOTES_FILE, HISTORY_FILE, STATE_FILE, os.path.join(AUDIO_DIR, "*"), os.path.join(MEDIA_DIR, "*")]]
960
-
961
- st.markdown("###### Your Files ๐Ÿ“‚")
962
- st.markdown("###### Image Gallery ๐Ÿ–ผ")
963
- own_image_files = [f for f in own_files if f.endswith(('.png', '.jpg'))]
964
- image_cols = st.slider("Image Gallery Columns ๐Ÿ–ผ (Own)", min_value=1, max_value=15, value=5)
965
- cols = st.columns(image_cols)
966
- for idx, image_file in enumerate(own_image_files):
967
- with cols[idx % image_cols]:
968
- st.image(image_file, use_container_width=True)
969
- shared_memory.update_media(image_file) # Cache media, in syncโ€™s sea, in Streamlitโ€™s sea!
970
-
971
- st.markdown("###### Video Gallery ๐ŸŽฅ")
972
- own_video_files = [f for f in own_files if f.endswith('.mp4')]
973
- video_cols = st.slider("Video Gallery Columns ๐ŸŽฌ (Own)", min_value=1, max_value=5, value=3)
974
- cols = st.columns(video_cols)
975
- for idx, video_file in enumerate(own_video_files):
976
- with cols[idx % video_cols]:
977
- st.markdown(get_video_html(video_file), unsafe_allow_html=True)
978
- shared_memory.update_media(video_file) # Cache media, in syncโ€™s lea, in Streamlitโ€™s lea!
979
-
980
- st.markdown("###### Audio Gallery ๐ŸŽง")
981
- own_audio_files = [f for f in own_files if f.endswith(('.mp3', '.wav')) or f.startswith(os.path.join(AUDIO_DIR, "audio_"))]
982
- audio_cols = st.slider("Audio Gallery Columns ๐ŸŽถ (Own)", min_value=1, max_value=15, value=5)
983
- cols = st.columns(audio_cols)
984
- for idx, audio_file in enumerate(own_audio_files):
985
- with cols[idx % audio_cols]:
986
- st.markdown(await get_audio_html(audio_file), unsafe_allow_html=True)
987
- shared_memory.update_media(audio_file) # Cache media, in syncโ€™s tea, in Streamlitโ€™s tea!
988
-
989
- st.markdown("###### Shared Files ๐Ÿ“ค")
990
- st.markdown("###### Image Gallery ๐Ÿ–ผ")
991
- shared_image_files = [f for f in shared_files if f.endswith(('.png', '.jpg'))]
992
- image_cols = st.slider("Image Gallery Columns ๐Ÿ–ผ (Shared)", min_value=1, max_value=15, value=5)
993
- cols = st.columns(image_cols)
994
- for idx, image_file in enumerate(shared_image_files):
995
- with cols[idx % image_cols]:
996
- st.image(image_file, use_container_width=True)
997
- shared_memory.update_media(image_file) # Cache media, in syncโ€™s bee, in Streamlitโ€™s bee!
998
-
999
- st.markdown("###### Video Gallery ๐ŸŽฅ")
1000
- shared_video_files = [f for f in shared_files if f.endswith('.mp4')]
1001
- video_cols = st.slider("Video Gallery Columns ๐ŸŽฌ (Shared)", min_value=1, max_value=5, value=3)
1002
- cols = st.columns(video_cols)
1003
- for idx, video_file in enumerate(shared_video_files):
1004
- with cols[idx % video_cols]:
1005
- st.markdown(get_video_html(video_file), unsafe_allow_html=True)
1006
- shared_memory.update_media(video_file) # Cache media, in syncโ€™s tree, in Streamlitโ€™s tree!
1007
-
1008
- st.markdown("###### Audio Gallery ๐ŸŽง")
1009
- shared_audio_files = [f for f in shared_files if f.endswith(('.mp3', '.wav')) or f.startswith(os.path.join(AUDIO_DIR, "audio_"))]
1010
- audio_cols = st.slider("Audio Gallery Columns ๐ŸŽถ (Shared)", min_value=1, max_value=15, value=5)
1011
- cols = st.columns(audio_cols)
1012
- for idx, audio_file in enumerate(shared_audio_files):
1013
- with cols[idx % audio_cols]:
1014
- st.markdown(await get_audio_html(audio_file), unsafe_allow_html=True)
1015
- shared_memory.update_media(audio_file) # Cache media, in syncโ€™s glee, in Streamlitโ€™s glee!
1016
-
1017
- # Full Log at End with Download - a shared epicโ€™s end, our tale to mend, in syncโ€™s bend, in Streamlitโ€™s end! ๐Ÿ“œ๐Ÿ“ฅ
1018
- with st.container():
1019
- st.markdown("###### Full Chat Log ๐Ÿ“œ")
1020
- with open(CHAT_FILE, 'r') as f:
1021
  history_content = f.read()
1022
- st.markdown(history_content)
1023
- st.download_button("Download Chat Log as .md", history_content, file_name=f"chat_{st.session_state.user_id}.md", mime="text/markdown")
1024
 
1025
- # Clear Cache Button - purge the cache, a shared epicโ€™s crash, in syncโ€™s flash, in Streamlitโ€™s crash! ๐Ÿ—‘๏ธ๐Ÿ”„
1026
- if st.button("Clear Shared Memory Cache", key="clear_cache"):
1027
- shared_memory = get_shared_memory()
1028
- shared_memory.clear()
1029
- st.success("Shared memory cache cleared, a fresh start with a bardโ€™s heart, in syncโ€™s art, in Streamlitโ€™s art! ๐ŸŒŸ๐ŸŽถ")
1030
 
1031
  if __name__ == "__main__":
1032
- """
1033
- Launch our saga, a shared memoryโ€™s cheer, in Streamlitโ€™s cache, our epic year, in syncโ€™s spear, in Streamlitโ€™s year! ๐Ÿš€โœจ
1034
- """
1035
  main()
 
14
  import io
15
  import streamlit.components.v1 as components
16
  import edge_tts
17
+ from audio_recorder_streamlit import audio_recorder
18
  import nest_asyncio
19
  import re
20
  from streamlit_paste_button import paste_image_button
21
  import pytz
22
  import shutil
 
 
 
23
 
24
+ # Patch for nested async - sneaky fix! ๐Ÿโœจ
25
  nest_asyncio.apply()
26
 
27
+ # Static config - constants rule! ๐Ÿ“๐Ÿ‘‘
28
  icons = '๐Ÿค–๐Ÿง ๐Ÿ”ฌ๐Ÿ“'
29
  START_ROOM = "Sector ๐ŸŒŒ"
30
 
31
+ # Page setup - dressing up the window! ๐Ÿ–ผ๏ธ๐ŸŽ€
32
  st.set_page_config(
33
  page_title="๐Ÿค–๐Ÿง MMO Chat Brain๐Ÿ“๐Ÿ”ฌ",
34
  page_icon=icons,
 
36
  initial_sidebar_state="auto"
37
  )
38
 
39
+ # Funky usernames - whoโ€™s who in the zoo with unique voices! ๐ŸŽญ๐Ÿพ๐ŸŽ™๏ธ
40
  FUN_USERNAMES = {
41
  "CosmicJester ๐ŸŒŒ": "en-US-AriaNeural",
42
  "PixelPanda ๐Ÿผ": "en-US-JennyNeural",
 
60
  "ChronoChimp ๐Ÿ’": "en-GB-LibbyNeural"
61
  }
62
 
63
+ # Folders galore - organizing chaos! ๐Ÿ“‚๐ŸŒ€
64
+ CHAT_DIR = "chat_logs"
65
+ VOTE_DIR = "vote_logs"
 
 
66
  STATE_FILE = "user_state.txt"
67
  AUDIO_DIR = "audio_logs"
68
+ HISTORY_DIR = "history_logs"
69
  MEDIA_DIR = "media_files"
70
+ os.makedirs(CHAT_DIR, exist_ok=True)
71
+ os.makedirs(VOTE_DIR, exist_ok=True)
72
  os.makedirs(AUDIO_DIR, exist_ok=True)
73
+ os.makedirs(HISTORY_DIR, exist_ok=True)
74
  os.makedirs(MEDIA_DIR, exist_ok=True)
75
 
76
+ CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
77
+ QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
78
+ MEDIA_VOTES_FILE = os.path.join(VOTE_DIR, "media_votes.md")
79
+ HISTORY_FILE = os.path.join(HISTORY_DIR, "chat_history.md")
80
+
81
+ # Fancy digits - numbers got style! ๐Ÿ”ข๐Ÿ’ƒ
82
  UNICODE_DIGITS = {i: f"{i}\uFE0Fโƒฃ" for i in range(10)}
83
 
84
+ # Massive font collection - typography bonanza! ๐Ÿ–‹๏ธ๐ŸŽจ
85
  UNICODE_FONTS = [
86
  ("Normal", lambda x: x),
87
  ("Bold", lambda x: "".join(chr(ord(c) + 0x1D400 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D41A - 0x61) if 'a' <= c <= 'z' else c for c in x)),
 
104
  ("Regional Indicator", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F1E6) if 'A' <= c <= 'Z' else c for c in x)),
105
  ]
106
 
107
+ # Global state - keeping tabs! ๐ŸŒ๐Ÿ“‹
108
  if 'server_running' not in st.session_state:
109
  st.session_state.server_running = False
110
  if 'server_task' not in st.session_state:
 
117
  st.session_state.last_chat_update = 0
118
  if 'displayed_chat_lines' not in st.session_state:
119
  st.session_state.displayed_chat_lines = []
120
+ if 'old_val' not in st.session_state:
121
+ st.session_state.old_val = ""
122
+ if 'last_query' not in st.session_state:
123
+ st.session_state.last_query = ""
124
  if 'message_text' not in st.session_state:
125
  st.session_state.message_text = ""
126
  if 'audio_cache' not in st.session_state:
 
133
  st.session_state.refresh_rate = 5
134
  if 'base64_cache' not in st.session_state:
135
  st.session_state.base64_cache = {}
136
+ if 'transcript_history' not in st.session_state:
137
+ st.session_state.transcript_history = []
138
+ if 'last_transcript' not in st.session_state:
139
+ st.session_state.last_transcript = ""
140
  if 'image_hashes' not in st.session_state:
141
  st.session_state.image_hashes = set()
142
+
143
+ # Timestamp wizardry - clock ticks with flair! โฐ๐ŸŽฉ
 
 
 
 
 
 
144
  def format_timestamp_prefix(username):
145
  central = pytz.timezone('US/Central')
146
  now = datetime.now(central)
147
+ return f"{now.strftime('%I-%M-%p-ct-%m-%d-%Y')}-by-{username}"
148
 
149
+ # Compute image hash from binary data
150
  def compute_image_hash(image_data):
151
  if isinstance(image_data, Image.Image):
152
  img_byte_arr = io.BytesIO()
 
156
  img_bytes = image_data
157
  return hashlib.md5(img_bytes).hexdigest()[:8]
158
 
159
+ # Node naming - christening the beast! ๐ŸŒ๐Ÿผ
160
  def get_node_name():
161
  parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
162
  parser.add_argument('--node-name', type=str, default=None)
 
166
  log_action(username, "๐ŸŒ๐Ÿผ - Node naming - christening the beast!")
167
  return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
168
 
169
+ # Action logger - spying on deeds! ๐Ÿ•ต๏ธ๐Ÿ“œ
170
  def log_action(username, action):
171
  if 'action_log' not in st.session_state:
172
  st.session_state.action_log = {}
 
180
  f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n")
181
  user_log[action] = current_time
182
 
183
+ # Clean text - strip the fancy stuff! ๐Ÿงน๐Ÿ“
184
  def clean_text_for_tts(text):
185
  cleaned = re.sub(r'[#*!\[\]]+', '', text)
186
  cleaned = ' '.join(cleaned.split())
187
+ return cleaned[:200] if cleaned else "No text to speak"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
+ # Chat saver - words locked tight! ๐Ÿ’ฌ๐Ÿ”’
190
+ async def save_chat_entry(username, message, is_markdown=False):
191
+ await asyncio.to_thread(log_action, username, "๐Ÿ’ฌ๐Ÿ”’ - Chat saver - words locked tight!")
 
 
192
  central = pytz.timezone('US/Central')
193
  timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 
194
  if is_markdown:
195
+ entry = f"[{timestamp}] {username}:\n```markdown\n{message}\n```"
196
  else:
197
+ entry = f"[{timestamp}] {username}: {message}"
198
+ await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"{entry}\n"))
199
+ voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
200
+ cleaned_message = clean_text_for_tts(message)
201
+ audio_file = await async_edge_tts_generate(cleaned_message, voice)
202
+ if audio_file:
203
+ with open(HISTORY_FILE, 'a') as f:
204
+ f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  await broadcast_message(f"{username}|{message}", "chat")
206
  st.session_state.last_chat_update = time.time()
207
+ return audio_file
208
 
209
+ # Chat loader - history unleashed! ๐Ÿ“œ๐Ÿš€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  async def load_chat():
 
 
 
211
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
212
  await asyncio.to_thread(log_action, username, "๐Ÿ“œ๐Ÿš€ - Chat loader - history unleashed!")
213
  if not os.path.exists(CHAT_FILE):
 
216
  content = await asyncio.to_thread(f.read)
217
  return content
218
 
219
+ # User lister - whoโ€™s in the gang! ๐Ÿ‘ฅ๐ŸŽ‰
220
  async def get_user_list(chat_content):
 
 
 
221
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
222
  await asyncio.to_thread(log_action, username, "๐Ÿ‘ฅ๐ŸŽ‰ - User lister - whoโ€™s in the gang!")
223
  users = set()
 
227
  users.add(user)
228
  return sorted(list(users))
229
 
230
+ # Join checker - been here before? ๐Ÿšช๐Ÿ”
231
  async def has_joined_before(client_id, chat_content):
 
 
 
232
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
233
  await asyncio.to_thread(log_action, username, "๐Ÿšช๐Ÿ” - Join checker - been here before?")
234
  return any(f"Client-{client_id}" in line for line in chat_content.split('\n'))
235
 
236
+ # Suggestion maker - old quips resurface! ๐Ÿ’ก๐Ÿ“
237
  async def get_message_suggestions(chat_content, prefix):
 
 
 
238
  username = st.session_state.get('username', 'System ๏ฟฝ๏ฟฝ')
239
  await asyncio.to_thread(log_action, username, "๐Ÿ’ก๐Ÿ“ - Suggestion maker - old quips resurface!")
240
  lines = chat_content.split('\n')
241
  messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
242
  return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5]
243
 
244
+ # Vote saver - cheers recorded! ๐Ÿ‘๐Ÿ“Š
 
245
  async def save_vote(file, item, user_hash, username, comment=""):
 
 
 
246
  await asyncio.to_thread(log_action, username, "๐Ÿ‘๐Ÿ“Š - Vote saver - cheers recorded!")
247
  central = pytz.timezone('US/Central')
248
  timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
 
253
  if comment:
254
  chat_message += f" - {comment}"
255
  await save_chat_entry(username, chat_message)
 
256
 
257
+ # Vote counter - tallying the love! ๐Ÿ†๐Ÿ“ˆ
 
258
  async def load_votes(file):
 
 
 
259
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
260
  await asyncio.to_thread(log_action, username, "๐Ÿ†๐Ÿ“ˆ - Vote counter - tallying the love!")
261
  if not os.path.exists(file):
 
275
  user_votes.add(vote_key)
276
  return votes
277
 
278
+ # Hash generator - secret codes ahoy! ๐Ÿ”‘๐Ÿ•ต๏ธ
279
  async def generate_user_hash():
 
 
 
280
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
281
  await asyncio.to_thread(log_action, username, "๐Ÿ”‘๐Ÿ•ต๏ธ - Hash generator - secret codes ahoy!")
282
  if 'user_hash' not in st.session_state:
283
  st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8]
284
  return st.session_state.user_hash
285
 
286
+ # Audio maker - voices come alive! ๐ŸŽถ๐ŸŒŸ
287
  async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
 
 
 
288
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
289
  await asyncio.to_thread(log_action, username, "๐ŸŽถ๐ŸŒŸ - Audio maker - voices come alive!")
290
  timestamp = format_timestamp_prefix(username)
291
+ filename = f"{timestamp}.{file_format}"
292
+ filepath = os.path.join(AUDIO_DIR, filename)
293
  communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
294
  try:
295
+ await communicate.save(filepath)
296
+ return filepath if os.path.exists(filepath) else None
297
  except edge_tts.exceptions.NoAudioReceived:
298
  with open(HISTORY_FILE, 'a') as f:
299
  central = pytz.timezone('US/Central')
300
  f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: Audio failed - No audio received for '{text}'\n")
301
  return None
302
 
303
+ # Audio player - tunes blast off! ๐Ÿ”Š๐Ÿš€
304
  def play_and_download_audio(file_path):
 
 
 
305
  if file_path and os.path.exists(file_path):
306
  st.audio(file_path)
307
+ if file_path not in st.session_state.base64_cache:
308
+ with open(file_path, "rb") as f:
309
+ b64 = base64.b64encode(f.read()).decode()
310
+ st.session_state.base64_cache[file_path] = b64
311
+ b64 = st.session_state.base64_cache[file_path]
312
  dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">๐ŸŽต Download {os.path.basename(file_path)}</a>'
313
  st.markdown(dl_link, unsafe_allow_html=True)
314
 
315
+ # Image saver - pics preserved with naming! ๐Ÿ“ธ๐Ÿ’พ
316
  async def save_pasted_image(image, username):
 
 
 
317
  await asyncio.to_thread(log_action, username, "๐Ÿ“ธ๐Ÿ’พ - Image saver - pics preserved!")
318
+ img_hash = compute_image_hash(image)
319
+ if img_hash in st.session_state.image_hashes:
320
+ return None
321
  timestamp = format_timestamp_prefix(username)
322
+ filename = f"{timestamp}-{img_hash}.png"
323
+ filepath = os.path.join(MEDIA_DIR, filename)
324
+ await asyncio.to_thread(image.save, filepath, "PNG")
325
+ st.session_state.image_hashes.add(img_hash)
326
+ return filepath
327
+
328
+ # Video renderer - movies roll with autoplay! ๐ŸŽฅ๐ŸŽฌ
329
+ async def get_video_html(video_path, width="100%"):
330
+ username = st.session_state.get('username', 'System ๐ŸŒŸ')
331
+ await asyncio.to_thread(log_action, username, "๐ŸŽฅ๐ŸŽฌ - Video renderer - movies roll!")
332
+ with open(video_path, 'rb') as f:
333
+ video_data = await asyncio.to_thread(f.read)
334
+ video_url = f"data:video/mp4;base64,{base64.b64encode(video_data).decode()}"
335
+ return f'<video width="{width}" controls autoplay><source src="{video_url}" type="video/mp4">Your browser does not support the video tag.</video>'
336
+
337
+ # Audio renderer - sounds soar! ๐ŸŽถโœˆ๏ธ
338
+ async def get_audio_html(audio_path, width="100%"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
340
  await asyncio.to_thread(log_action, username, "๐ŸŽถโœˆ๏ธ - Audio renderer - sounds soar!")
341
+ audio_url = f"data:audio/mpeg;base64,{base64.b64encode(await asyncio.to_thread(open, audio_path, 'rb').read()).decode()}"
342
+ return f'<audio controls style="width: {width};"><source src="{audio_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>'
343
+
344
+ # Websocket handler - chat links up! ๐ŸŒ๐Ÿ”—
 
 
 
 
 
345
  async def websocket_handler(websocket, path):
 
 
 
346
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
347
  await asyncio.to_thread(log_action, username, "๐ŸŒ๐Ÿ”— - Websocket handler - chat links up!")
348
  try:
 
364
  if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
365
  del st.session_state.active_connections[room_id][client_id]
366
 
367
+ # Message broadcaster - words fly far! ๐Ÿ“ขโœˆ๏ธ
368
  async def broadcast_message(message, room_id):
 
 
 
369
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
370
  await asyncio.to_thread(log_action, username, "๐Ÿ“ขโœˆ๏ธ - Message broadcaster - words fly far!")
371
  if room_id in st.session_state.active_connections:
 
378
  for client_id in disconnected:
379
  del st.session_state.active_connections[room_id][client_id]
380
 
381
+ # Server starter - web spins up! ๐Ÿ–ฅ๏ธ๐ŸŒ€
382
  async def run_websocket_server():
 
 
 
383
  username = st.session_state.get('username', 'System ๐ŸŒŸ')
384
  await asyncio.to_thread(log_action, username, "๐Ÿ–ฅ๏ธ๐ŸŒ€ - Server starter - web spins up!")
385
  if not st.session_state.server_running:
 
387
  st.session_state.server_running = True
388
  await server.wait_closed()
389
 
390
+ # Voice processor - speech to text! ๐ŸŽค๐Ÿ“
391
+ async def process_voice_input(audio_bytes):
392
+ username = st.session_state.get('username', 'System ๐ŸŒŸ')
393
+ await asyncio.to_thread(log_action, username, "๐ŸŽค๐Ÿ“ - Voice processor - speech to text!")
394
+ if audio_bytes:
395
+ text = "Voice input simulation"
396
+ await save_chat_entry(username, text)
397
+
398
+ # Dummy AI lookup function (replace with actual implementation)
399
+ async def perform_ai_lookup(query, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False, useArxiv=True, useArxivAudio=False):
400
+ username = st.session_state.get('username', 'System ๐ŸŒŸ')
401
+ result = f"AI Lookup Result for '{query}' (Arxiv: {useArxiv}, Audio: {useArxivAudio})"
402
+ await save_chat_entry(username, result)
403
+ if useArxivAudio:
404
+ audio_file = await async_edge_tts_generate(result, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
405
+ if audio_file:
406
+ st.audio(audio_file)
407
+
408
+ # Delete all user files function
409
  def delete_user_files():
410
+ protected_files = {'app.py', 'requirements.txt', 'README.md'}
 
 
 
411
  deleted_files = []
412
+
413
+ # Directories to clear
414
+ directories = [MEDIA_DIR, AUDIO_DIR, CHAT_DIR, VOTE_DIR, HISTORY_DIR]
415
+
416
+ for directory in directories:
417
+ if os.path.exists(directory):
418
+ for root, _, files in os.walk(directory):
419
+ for file in files:
420
+ file_path = os.path.join(root, file)
421
+ if os.path.basename(file_path) not in protected_files:
422
+ try:
423
+ os.remove(file_path)
424
+ deleted_files.append(file_path)
425
+ except Exception as e:
426
+ st.error(f"Failed to delete {file_path}: {e}")
427
+ # Remove empty directories
428
  try:
429
+ shutil.rmtree(directory, ignore_errors=True)
430
+ os.makedirs(directory, exist_ok=True) # Recreate empty directory
431
  except Exception as e:
432
+ st.error(f"Failed to remove directory {directory}: {e}")
433
+
434
+ # Clear session state caches
 
 
 
 
 
 
435
  st.session_state.image_hashes.clear()
436
  st.session_state.audio_cache.clear()
437
  st.session_state.base64_cache.clear()
438
  st.session_state.displayed_chat_lines.clear()
439
+
 
440
  return deleted_files
441
 
442
+ # ASR Component HTML
443
+ ASR_HTML = """
444
+ <html>
445
+ <head>
446
+ <title>Continuous Speech Demo</title>
447
+ <style>
448
+ body {
449
+ font-family: sans-serif;
450
+ padding: 20px;
451
+ max-width: 800px;
452
+ margin: 0 auto;
453
+ }
454
+ button {
455
+ padding: 10px 20px;
456
+ margin: 10px 5px;
457
+ font-size: 16px;
458
+ }
459
+ #status {
460
+ margin: 10px 0;
461
+ padding: 10px;
462
+ background: #e8f5e9;
463
+ border-radius: 4px;
464
+ }
465
+ #output {
466
+ white-space: pre-wrap;
467
+ padding: 15px;
468
+ background: #f5f5f5;
469
+ border-radius: 4px;
470
+ margin: 10px 0;
471
+ min-height: 100px;
472
+ max-height: 400px;
473
+ overflow-y: auto;
474
+ }
475
+ .controls {
476
+ margin: 10px 0;
477
+ }
478
+ </style>
479
+ </head>
480
+ <body>
481
+ <div class="controls">
482
+ <button id="start">Start Listening</button>
483
+ <button id="stop" disabled>Stop Listening</button>
484
+ <button id="clear">Clear Text</button>
485
+ </div>
486
+ <div id="status">Ready</div>
487
+ <div id="output"></div>
488
+
489
+ <script>
490
+ if (!('webkitSpeechRecognition' in window)) {
491
+ alert('Speech recognition not supported');
492
+ } else {
493
+ const recognition = new webkitSpeechRecognition();
494
+ const startButton = document.getElementById('start');
495
+ const stopButton = document.getElementById('stop');
496
+ const clearButton = document.getElementById('clear');
497
+ const status = document.getElementById('status');
498
+ const output = document.getElementById('output');
499
+ let fullTranscript = '';
500
+ let lastUpdateTime = Date.now();
501
+
502
+ recognition.continuous = true;
503
+ recognition.interimResults = true;
504
+
505
+ const startRecognition = () => {
506
+ try {
507
+ recognition.start();
508
+ status.textContent = 'Listening...';
509
+ startButton.disabled = true;
510
+ stopButton.disabled = false;
511
+ } catch (e) {
512
+ console.error(e);
513
+ status.textContent = 'Error: ' + e.message;
514
+ }
515
+ };
516
+
517
+ window.addEventListener('load', () => {
518
+ setTimeout(startRecognition, 1000);
519
+ });
520
+
521
+ startButton.onclick = startRecognition;
522
+
523
+ stopButton.onclick = () => {
524
+ recognition.stop();
525
+ status.textContent = 'Stopped';
526
+ startButton.disabled = false;
527
+ stopButton.disabled = true;
528
+ };
529
+
530
+ clearButton.onclick = () => {
531
+ fullTranscript = '';
532
+ output.textContent = '';
533
+ sendDataToPython({value: '', dataType: "json"});
534
+ };
535
+
536
+ recognition.onresult = (event) => {
537
+ let interimTranscript = '';
538
+ let finalTranscript = '';
539
+
540
+ for (let i = event.resultIndex; i < event.results.length; i++) {
541
+ const transcript = event.results[i][0].transcript;
542
+ if (event.results[i].isFinal) {
543
+ finalTranscript += transcript + '\\n';
544
+ } else {
545
+ interimTranscript += transcript;
546
+ }
547
+ }
548
+
549
+ if (finalTranscript || (Date.now() - lastUpdateTime > 5000)) {
550
+ if (finalTranscript) {
551
+ fullTranscript += finalTranscript;
552
+ }
553
+ lastUpdateTime = Date.now();
554
+ output.textContent = fullTranscript + (interimTranscript ? '... ' + interimTranscript : '');
555
+ output.scrollTop = output.scrollHeight;
556
+ sendDataToPython({value: fullTranscript, dataType: "json"});
557
+ }
558
+ };
559
+
560
+ recognition.onend = () => {
561
+ if (!stopButton.disabled) {
562
+ try {
563
+ recognition.start();
564
+ console.log('Restarted recognition');
565
+ } catch (e) {
566
+ console.error('Failed to restart recognition:', e);
567
+ status.textContent = 'Error restarting: ' + e.message;
568
+ startButton.disabled = false;
569
+ stopButton.disabled = true;
570
+ }
571
+ }
572
+ };
573
+
574
+ recognition.onerror = (event) => {
575
+ console.error('Recognition error:', event.error);
576
+ status.textContent = 'Error: ' + event.error;
577
+ if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
578
+ startButton.disabled = false;
579
+ stopButton.disabled = true;
580
+ }
581
+ };
582
+ }
583
+
584
+ function sendDataToPython(data) {
585
+ window.parent.postMessage({
586
+ isStreamlitMessage: true,
587
+ type: "streamlit:setComponentValue",
588
+ ...data
589
+ }, "*");
590
+ }
591
+
592
+ window.addEventListener('load', function() {
593
+ window.setTimeout(function() {
594
+ window.parent.postMessage({
595
+ isStreamlitMessage: true,
596
+ type: "streamlit:setFrameHeight",
597
+ height: document.documentElement.clientHeight
598
+ }, "*");
599
+ }, 0);
600
+ });
601
+ </script>
602
+ </body>
603
+ </html>
604
+ """
605
+
606
+ # Main execution - letโ€™s roll! ๐ŸŽฒ๐Ÿš€
607
  def main():
 
 
 
608
  NODE_NAME, port = get_node_name()
609
 
610
+ loop = asyncio.new_event_loop()
611
+ asyncio.set_event_loop(loop)
612
+
613
+ async def async_interface():
614
+ if 'username' not in st.session_state:
615
+ chat_content = await load_chat()
616
+ available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
617
+ st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
618
+ st.session_state.voice = FUN_USERNAMES[st.session_state.username]
619
+ st.markdown(f"**๐ŸŽ™๏ธ Voice Selected**: {st.session_state.voice} ๐Ÿ—ฃ๏ธ for {st.session_state.username}")
620
+
621
+ st.title(f"๐Ÿค–๐Ÿง MMO {st.session_state.username}๐Ÿ“๐Ÿ”ฌ")
622
+ st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! ๐ŸŽ‰")
623
+
624
+ if not st.session_state.server_task:
625
+ st.session_state.server_task = loop.create_task(run_websocket_server())
626
+
627
+ audio_bytes = audio_recorder()
628
+ if audio_bytes:
629
+ await process_voice_input(audio_bytes)
630
+ st.rerun()
631
+
632
+ # Continuous Speech Input (ASR)
633
+ st.subheader("๐ŸŽค Continuous Speech Input")
634
+ asr_component = components.html(ASR_HTML, height=400)
635
+ if asr_component and isinstance(asr_component, dict) and 'value' in asr_component:
636
+ transcript = asr_component['value'].strip()
637
+ if transcript and transcript != st.session_state.last_transcript:
638
+ st.session_state.transcript_history.append(transcript)
639
+ await save_chat_entry(st.session_state.username, transcript, is_markdown=True)
640
+ st.session_state.last_transcript = transcript
641
+ st.rerun()
642
+
643
+ # Load and display chat
644
+ st.subheader(f"{START_ROOM} Chat ๐Ÿ’ฌ")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
645
  chat_content = await load_chat()
646
+ chat_lines = chat_content.split('\n')
647
+ chat_votes = await load_votes(QUOTE_VOTES_FILE)
648
+
649
+ current_time = time.time()
650
+ if current_time - st.session_state.last_chat_update > 1 or not st.session_state.displayed_chat_lines:
651
+ new_lines = [line for line in chat_lines if line.strip() and ': ' in line and line not in st.session_state.displayed_chat_lines and not line.startswith('#')]
652
+ st.session_state.displayed_chat_lines.extend(new_lines)
653
+ st.session_state.last_chat_update = current_time
654
+
655
+ for i, line in enumerate(st.session_state.displayed_chat_lines):
656
+ col1, col2, col3, col4 = st.columns([3, 1, 1, 2])
657
+ with col1:
658
+ if "```markdown" in line:
659
+ markdown_content = re.search(r'```markdown\n(.*?)```', line, re.DOTALL)
660
+ if markdown_content:
661
+ st.markdown(markdown_content.group(1))
662
+ else:
663
+ st.markdown(line)
664
+ else:
665
+ st.markdown(line)
666
+ if "Pasted image:" in line or "Uploaded media:" in line:
667
+ file_path = line.split(': ')[-1].strip()
668
+ if os.path.exists(file_path):
669
+ if file_path not in st.session_state.base64_cache:
670
+ with open(file_path, "rb") as f:
671
+ b64 = base64.b64encode(f.read()).decode()
672
+ st.session_state.base64_cache[file_path] = b64
673
+ b64 = st.session_state.base64_cache[file_path]
674
+ mime_type = "image/png" if file_path.endswith(('.png', '.jpg')) else "video/mp4" if file_path.endswith('.mp4') else "audio/mpeg"
675
+ if file_path.endswith(('.png', '.jpg')):
676
+ st.image(file_path, use_container_width=True)
677
+ dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">๐Ÿ“ฅ Download {os.path.basename(file_path)}</a>'
678
+ st.markdown(dl_link, unsafe_allow_html=True)
679
+ elif file_path.endswith('.mp4'):
680
+ st.markdown(await get_video_html(file_path), unsafe_allow_html=True)
681
+ dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">๐Ÿ“ฅ Download {os.path.basename(file_path)}</a>'
682
+ st.markdown(dl_link, unsafe_allow_html=True)
683
+ elif file_path.endswith('.mp3'):
684
+ st.markdown(await get_audio_html(file_path), unsafe_allow_html=True)
685
+ dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">๐Ÿ“ฅ Download {os.path.basename(file_path)}</a>'
686
+ st.markdown(dl_link, unsafe_allow_html=True)
687
+ with col2:
688
+ vote_count = chat_votes.get(line.split('. ')[1] if '. ' in line else line, 0)
689
+ if st.button(f"๐Ÿ‘ {vote_count}", key=f"chat_vote_{i}"):
690
+ comment = st.session_state.message_text
691
+ await save_vote(QUOTE_VOTES_FILE, line.split('. ')[1] if '. ' in line else line, await generate_user_hash(), st.session_state.username, comment)
692
+ st.session_state.message_text = ''
693
+ st.rerun()
694
+ with col3:
695
+ if st.button("๐Ÿ“ข Quote", key=f"quote_{i}"):
696
+ st.session_state.quote_line = line
697
+ st.rerun()
698
+ with col4:
699
+ username = line.split(': ')[1].split(' ')[0]
700
+ cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
701
+ if cache_key not in st.session_state.audio_cache:
702
+ cleaned_text = clean_text_for_tts(line.split(': ', 1)[1])
703
+ audio_file = await async_edge_tts_generate(cleaned_text, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
704
+ st.session_state.audio_cache[cache_key] = audio_file
705
+ audio_file = st.session_state.audio_cache.get(cache_key)
706
+ if audio_file:
707
+ play_and_download_audio(audio_file)
708
+
709
  if st.session_state.quote_line:
710
+ st.markdown(f"### Quoting: {st.session_state.quote_line}")
711
  quote_response = st.text_area("Add your response", key="quote_response", value=st.session_state.message_text)
712
  paste_result_quote = paste_image_button("๐Ÿ“‹ Paste Image or Text with Quote", key="paste_button_quote")
713
  if paste_result_quote.image_data is not None:
 
719
  filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
720
  if filename:
721
  st.session_state.pasted_image_data = filename
 
722
  if st.button("Send Quote ๐Ÿš€", key="send_quote"):
723
  markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
724
  if st.session_state.pasted_image_data:
725
  markdown_response += f"\n- **Image**: ![Pasted Image]({st.session_state.pasted_image_data})"
726
+ await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
727
  st.session_state.pasted_image_data = None
728
+ await save_chat_entry(st.session_state.username, markdown_response, is_markdown=True)
729
  st.session_state.quote_line = None
730
  st.session_state.message_text = ''
731
  st.rerun()
 
739
  st.markdown(f"**๐ŸŽ™๏ธ Voice Changed**: {st.session_state.voice} ๐Ÿ—ฃ๏ธ for {st.session_state.username}")
740
  st.rerun()
741
 
742
+ message = st.text_input(f"Message as {st.session_state.username} (Voice: {st.session_state.voice})", key="message_input", value=st.session_state.message_text)
 
 
 
 
 
 
 
 
 
 
 
 
743
  paste_result_msg = paste_image_button("๐Ÿ“‹ Paste Image or Text with Message", key="paste_button_msg")
744
  if paste_result_msg.image_data is not None:
745
  if isinstance(paste_result_msg.image_data, str):
746
  st.session_state.message_text = paste_result_msg.image_data
747
  st.text_input(f"Message as {st.session_state.username} (Voice: {st.session_state.voice})", key="message_input_paste", value=st.session_state.message_text)
748
  else:
749
+ st.image(paste_result_msg.image_data, caption="Received Image for Message")
750
  filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
751
  if filename:
752
+ st.session_state.pasted_image_data = filename
753
+ if st.button("Send ๐Ÿš€", key="send_button") and (message.strip() or st.session_state.pasted_image_data):
754
+ if message.strip():
755
+ audio_file = await save_chat_entry(st.session_state.username, message, is_markdown=True)
756
+ if audio_file:
757
+ st.session_state.audio_cache[f"{message}_{FUN_USERNAMES[st.session_state.username]}"] = audio_file
758
+ if st.session_state.pasted_image_data:
759
+ await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
760
+ st.session_state.pasted_image_data = None
761
+ st.session_state.message_text = ''
762
+ st.rerun()
763
 
764
+ tab_main = st.radio("Action:", ["๐ŸŽค Voice", "๐Ÿ“ธ Media", "๐Ÿ” ArXiv", "๐Ÿ“ Editor"], horizontal=True)
765
+ useArxiv = st.checkbox("Search Arxiv for Research Paper Answers", value=True)
766
+ useArxivAudio = st.checkbox("Generate Audio File for Research Paper Answers", value=False)
767
+
768
+ st.subheader("Upload Media ๐ŸŽจ๐ŸŽถ๐ŸŽฅ")
769
+ uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3'])
770
  if uploaded_file:
771
  timestamp = format_timestamp_prefix(st.session_state.username)
772
  username = st.session_state.username
773
+ ext = uploaded_file.name.split('.')[-1]
774
+ file_hash = hashlib.md5(uploaded_file.getbuffer()).hexdigest()[:8]
775
+ if file_hash not in st.session_state.image_hashes:
776
+ filename = f"{timestamp}-{file_hash}.{ext}"
777
+ file_path = os.path.join(MEDIA_DIR, filename)
778
+ await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
779
+ st.success(f"Uploaded {filename}")
780
+ await save_chat_entry(username, f"Uploaded media: {file_path}")
781
+ st.session_state.image_hashes.add(file_hash)
782
+ if file_path.endswith('.mp4'):
783
+ st.session_state.media_notifications.append(file_path)
784
+
785
+ # Big Red Delete Button
786
+ st.subheader("๐Ÿ›‘ Danger Zone")
 
 
 
 
 
787
  if st.button("Try Not To Delete It All On Your First Day", key="delete_all", help="Deletes all user-added files!", type="primary", use_container_width=True):
788
  deleted_files = delete_user_files()
789
  if deleted_files:
790
  st.markdown("### ๐Ÿ—‘๏ธ Deleted Files:\n" + "\n".join([f"- `{file}`" for file in deleted_files]))
 
 
791
  else:
792
  st.markdown("### ๐Ÿ—‘๏ธ Nothing to Delete!")
793
+ st.session_state.image_hashes.clear()
794
+ st.session_state.audio_cache.clear()
795
+ st.session_state.base64_cache.clear()
796
+ st.session_state.displayed_chat_lines.clear()
797
  st.rerun()
798
 
799
+ st.subheader("Media Gallery ๐ŸŽจ๐ŸŽถ๐ŸŽฅ")
800
+ media_files = glob.glob(f"{MEDIA_DIR}/*.png") + glob.glob(f"{MEDIA_DIR}/*.jpg") + glob.glob(f"{MEDIA_DIR}/*.mp4") + glob.glob(f"{MEDIA_DIR}/*.mp3")
801
+ if media_files:
802
+ media_votes = await load_votes(MEDIA_VOTES_FILE)
803
+ st.write("### All Media Uploads")
804
+ seen_files = set()
805
+ for media_file in sorted(media_files, key=os.path.getmtime, reverse=True):
806
+ if media_file not in seen_files:
807
+ seen_files.add(media_file)
808
+ filename = os.path.basename(media_file)
809
+ vote_count = media_votes.get(media_file, 0)
810
+ col1, col2 = st.columns([3, 1])
811
+ with col1:
812
+ st.markdown(f"**{filename}**")
813
+ if media_file.endswith(('.png', '.jpg')):
814
+ st.image(media_file, use_container_width=True)
815
+ elif media_file.endswith('.mp4'):
816
+ st.markdown(await get_video_html(media_file), unsafe_allow_html=True)
817
+ elif media_file.endswith('.mp3'):
818
+ st.markdown(await get_audio_html(media_file), unsafe_allow_html=True)
819
+ with col2:
820
+ if st.button(f"๐Ÿ‘ {vote_count}", key=f"media_vote_{media_file}"):
821
+ await save_vote(MEDIA_VOTES_FILE, media_file, await generate_user_hash(), st.session_state.username)
822
+ st.rerun()
823
+
824
+ st.subheader("Refresh โณ")
825
  refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
826
  st.session_state.refresh_rate = refresh_rate
827
  timer_placeholder = st.empty()
828
  for i in range(st.session_state.refresh_rate, -1, -1):
829
  font_name, font_func = random.choice(UNICODE_FONTS)
830
  countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
831
+ timer_placeholder.markdown(f"<p class='timer'>โณ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
832
+ time.sleep(1)
833
  st.rerun()
834
 
835
+ st.sidebar.subheader("Chat History ๐Ÿ“œ")
836
+ with open(HISTORY_FILE, 'r') as f:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837
  history_content = f.read()
838
+ st.sidebar.markdown(history_content)
 
839
 
840
+ loop.run_until_complete(async_interface())
 
 
 
 
841
 
842
  if __name__ == "__main__":
 
 
 
843
  main()