awacke1 commited on
Commit
17aa09a
Β·
verified Β·
1 Parent(s): 33f1e6c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -32
app.py CHANGED
@@ -161,8 +161,8 @@ async def save_chat_entry(username, message):
161
  if audio_file:
162
  with open(HISTORY_FILE, 'a') as f:
163
  f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
164
- await broadcast_message(f"{username}|{message}", "chat") # Notify all clients
165
- st.session_state.last_chat_update = time.time() # Update timestamp for new chat
166
 
167
  # Chat loader - history unleashed! πŸ“œπŸš€
168
  async def load_chat():
@@ -189,7 +189,7 @@ async def get_user_list(chat_content):
189
  async def has_joined_before(client_id, chat_content):
190
  username = st.session_state.get('username', 'System 🌟')
191
  await asyncio.to_thread(log_action, username, "πŸšͺπŸ” - Join checker - been here before?")
192
- return any(f"Client-{client_id} has joined" in line for line in chat_content.split('\n'))
193
 
194
  # Suggestion maker - old quips resurface! πŸ’‘πŸ“
195
  async def get_message_suggestions(chat_content, prefix):
@@ -310,7 +310,6 @@ async def websocket_handler(websocket, path):
310
  if len(parts) == 2:
311
  username, content = parts
312
  await save_chat_entry(username, content)
313
- await broadcast_message(f"{username}|{content}", room_id)
314
  except websockets.ConnectionClosed:
315
  pass
316
  finally:
@@ -392,20 +391,20 @@ def create_streamlit_interface():
392
  await process_voice_input(audio_bytes)
393
  st.rerun()
394
 
395
- # Load chat only if there’s an update
396
  st.subheader(f"{START_ROOM} Chat πŸ’¬")
397
  chat_content = await load_chat()
398
  chat_lines = chat_content.split('\n')
399
  chat_votes = await load_votes(QUOTE_VOTES_FILE)
400
 
401
- # Only add new lines that haven’t been displayed yet
402
  current_time = time.time()
403
  if current_time - st.session_state.last_chat_update > 1 or not st.session_state.displayed_chat_lines:
404
- new_lines = [line for line in chat_lines if line.strip() and ': ' in line and line not in st.session_state.displayed_chat_lines]
405
  st.session_state.displayed_chat_lines.extend(new_lines)
406
  st.session_state.last_chat_update = current_time
407
 
408
- # Display chat lines from session state
409
  for i, line in enumerate(st.session_state.displayed_chat_lines):
410
  col1, col2, col3, col4 = st.columns([3, 1, 1, 2])
411
  with col1:
@@ -428,47 +427,39 @@ def create_streamlit_interface():
428
  st.rerun()
429
  with col4:
430
  username = line.split(': ')[1].split(' ')[0]
431
- audio_file = None
432
  cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
433
- if cache_key in st.session_state.audio_cache:
434
- audio_file = st.session_state.audio_cache[cache_key]
435
- else:
436
  cleaned_text = clean_text_for_tts(line.split(': ', 1)[1])
437
  audio_file = await async_edge_tts_generate(cleaned_text, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
438
  st.session_state.audio_cache[cache_key] = audio_file
 
439
  if audio_file:
440
  play_and_download_audio(audio_file)
441
 
442
- if 'quote_line' in st.session_state:
 
443
  st.markdown(f"### Quoting: {st.session_state.quote_line}")
444
  quote_response = st.text_area("Add your response", key="quote_response")
445
  if st.button("Send Quote πŸš€", key="send_quote"):
446
- async def process_quote():
447
- await asyncio.to_thread(log_action, st.session_state.username, "πŸ“’πŸ’¬ - Quote processor - echoes resound!")
448
- markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
449
- if st.session_state.pasted_image_data:
450
- filename = await save_pasted_image(st.session_state.pasted_image_data, st.session_state.username)
451
- if filename:
452
- markdown_response += f"\n- **Image**: ![Pasted Image]({filename})"
453
- st.session_state.pasted_image_data = None
454
- try:
455
- await save_chat_entry(st.session_state.username, markdown_response)
456
- except edge_tts.exceptions.NoAudioReceived:
457
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
458
- with open(HISTORY_FILE, 'a') as f:
459
- f.write(f"[{timestamp}] {st.session_state.username}: Quote saved without audio - No audio received\n")
460
- await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"[{timestamp}] {st.session_state.username}: {markdown_response}\n"))
461
- loop.run_until_complete(process_quote())
462
  del st.session_state.quote_line
463
  st.session_state.message_text = ''
464
  st.rerun()
465
 
 
466
  new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
467
  if new_username and new_username != st.session_state.username:
468
  loop.run_until_complete(save_chat_entry("System 🌟", f"{st.session_state.username} changed name to {new_username}"))
469
  st.session_state.username = new_username
470
  st.rerun()
471
 
 
472
  message = st.text_input(f"Message as {st.session_state.username}", key="message_input", value=st.session_state.message_text, on_change=lambda: st.session_state.update(message_text=st.session_state.message_input))
473
  if st.button("Send πŸš€", key="send_button") and message.strip():
474
  loop.run_until_complete(save_chat_entry(st.session_state.username, message))
@@ -520,13 +511,13 @@ def create_streamlit_interface():
520
  st.success(f"Uploaded {filename}")
521
  await save_chat_entry(username, f"Uploaded media: {file_path}")
522
  if file_path.endswith('.mp4'):
523
- st.session_state.media_notifications.append(file_path) # Trigger autoplay for all clients
524
 
525
  # Organize gallery by user
526
  media_files = glob.glob(f"{MEDIA_DIR}/*.png") + glob.glob(f"{MEDIA_DIR}/*.jpg") + glob.glob(f"{MEDIA_DIR}/*.mp3") + glob.glob(f"{MEDIA_DIR}/*.mp4")
527
  if media_files:
528
  media_votes = loop.run_until_complete(load_votes(MEDIA_VOTES_FILE))
529
- users = sorted(set(f.split('_')[-1].split('.')[0] for f in media_files)) # Extract usernames
530
  for user in users:
531
  with st.expander(f"{user}'s Media"):
532
  user_files = [f for f in media_files if user in f]
@@ -544,7 +535,7 @@ def create_streamlit_interface():
544
  st.markdown(await get_video_html(media_file), unsafe_allow_html=True)
545
  st.caption(os.path.basename(media_file))
546
  if media_file in st.session_state.media_notifications:
547
- st.session_state.media_notifications.remove(media_file) # Autoplay once
548
  with col2:
549
  if st.button(f"πŸ‘ {vote_count}", key=f"media_vote_{media_file}"):
550
  comment = st.session_state.message_text
 
161
  if audio_file:
162
  with open(HISTORY_FILE, 'a') as f:
163
  f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
164
+ await broadcast_message(f"{username}|{message}", "chat")
165
+ st.session_state.last_chat_update = time.time()
166
 
167
  # Chat loader - history unleashed! πŸ“œπŸš€
168
  async def load_chat():
 
189
  async def has_joined_before(client_id, chat_content):
190
  username = st.session_state.get('username', 'System 🌟')
191
  await asyncio.to_thread(log_action, username, "πŸšͺπŸ” - Join checker - been here before?")
192
+ return any(f"Client-{client_id}" in line for line in chat_content.split('\n'))
193
 
194
  # Suggestion maker - old quips resurface! πŸ’‘πŸ“
195
  async def get_message_suggestions(chat_content, prefix):
 
310
  if len(parts) == 2:
311
  username, content = parts
312
  await save_chat_entry(username, content)
 
313
  except websockets.ConnectionClosed:
314
  pass
315
  finally:
 
391
  await process_voice_input(audio_bytes)
392
  st.rerun()
393
 
394
+ # Load and display chat
395
  st.subheader(f"{START_ROOM} Chat πŸ’¬")
396
  chat_content = await load_chat()
397
  chat_lines = chat_content.split('\n')
398
  chat_votes = await load_votes(QUOTE_VOTES_FILE)
399
 
400
+ # Update displayed lines only with new, valid chat entries
401
  current_time = time.time()
402
  if current_time - st.session_state.last_chat_update > 1 or not st.session_state.displayed_chat_lines:
403
+ 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('#')]
404
  st.session_state.displayed_chat_lines.extend(new_lines)
405
  st.session_state.last_chat_update = current_time
406
 
407
+ # Display chat lines
408
  for i, line in enumerate(st.session_state.displayed_chat_lines):
409
  col1, col2, col3, col4 = st.columns([3, 1, 1, 2])
410
  with col1:
 
427
  st.rerun()
428
  with col4:
429
  username = line.split(': ')[1].split(' ')[0]
 
430
  cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
431
+ if cache_key not in st.session_state.audio_cache:
 
 
432
  cleaned_text = clean_text_for_tts(line.split(': ', 1)[1])
433
  audio_file = await async_edge_tts_generate(cleaned_text, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
434
  st.session_state.audio_cache[cache_key] = audio_file
435
+ audio_file = st.session_state.audio_cache.get(cache_key)
436
  if audio_file:
437
  play_and_download_audio(audio_file)
438
 
439
+ # Quoting interface
440
+ if 'quote_line' in st.session_state and st.session_state.quote_line:
441
  st.markdown(f"### Quoting: {st.session_state.quote_line}")
442
  quote_response = st.text_area("Add your response", key="quote_response")
443
  if st.button("Send Quote πŸš€", key="send_quote"):
444
+ markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
445
+ if st.session_state.pasted_image_data:
446
+ filename = await save_pasted_image(st.session_state.pasted_image_data, st.session_state.username)
447
+ if filename:
448
+ markdown_response += f"\n- **Image**: ![Pasted Image]({filename})"
449
+ st.session_state.pasted_image_data = None
450
+ await save_chat_entry(st.session_state.username, markdown_response)
 
 
 
 
 
 
 
 
 
451
  del st.session_state.quote_line
452
  st.session_state.message_text = ''
453
  st.rerun()
454
 
455
+ # Username change
456
  new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
457
  if new_username and new_username != st.session_state.username:
458
  loop.run_until_complete(save_chat_entry("System 🌟", f"{st.session_state.username} changed name to {new_username}"))
459
  st.session_state.username = new_username
460
  st.rerun()
461
 
462
+ # Message input
463
  message = st.text_input(f"Message as {st.session_state.username}", key="message_input", value=st.session_state.message_text, on_change=lambda: st.session_state.update(message_text=st.session_state.message_input))
464
  if st.button("Send πŸš€", key="send_button") and message.strip():
465
  loop.run_until_complete(save_chat_entry(st.session_state.username, message))
 
511
  st.success(f"Uploaded {filename}")
512
  await save_chat_entry(username, f"Uploaded media: {file_path}")
513
  if file_path.endswith('.mp4'):
514
+ st.session_state.media_notifications.append(file_path)
515
 
516
  # Organize gallery by user
517
  media_files = glob.glob(f"{MEDIA_DIR}/*.png") + glob.glob(f"{MEDIA_DIR}/*.jpg") + glob.glob(f"{MEDIA_DIR}/*.mp3") + glob.glob(f"{MEDIA_DIR}/*.mp4")
518
  if media_files:
519
  media_votes = loop.run_until_complete(load_votes(MEDIA_VOTES_FILE))
520
+ users = sorted(set(f.split('_')[-1].split('.')[0] for f in media_files))
521
  for user in users:
522
  with st.expander(f"{user}'s Media"):
523
  user_files = [f for f in media_files if user in f]
 
535
  st.markdown(await get_video_html(media_file), unsafe_allow_html=True)
536
  st.caption(os.path.basename(media_file))
537
  if media_file in st.session_state.media_notifications:
538
+ st.session_state.media_notifications.remove(media_file)
539
  with col2:
540
  if st.button(f"πŸ‘ {vote_count}", key=f"media_vote_{media_file}"):
541
  comment = st.session_state.message_text