Update app.py
Browse files
app.py
CHANGED
|
@@ -18,6 +18,7 @@ import edge_tts
|
|
| 18 |
from audio_recorder_streamlit import audio_recorder
|
| 19 |
import nest_asyncio
|
| 20 |
import re
|
|
|
|
| 21 |
|
| 22 |
# Patch for nested async - sneaky fix! πβ¨
|
| 23 |
nest_asyncio.apply()
|
|
@@ -36,26 +37,26 @@ st.set_page_config(
|
|
| 36 |
|
| 37 |
# Funky usernames - whoβs who in the zoo with unique voices! ππΎποΈ
|
| 38 |
FUN_USERNAMES = {
|
| 39 |
-
"CosmicJester π": "en-US-AriaNeural",
|
| 40 |
-
"PixelPanda πΌ": "en-US-JennyNeural",
|
| 41 |
-
"QuantumQuack π¦": "en-GB-SoniaNeural",
|
| 42 |
-
"StellarSquirrel πΏοΈ": "en-AU-NatashaNeural",
|
| 43 |
-
"GizmoGuru βοΈ": "en-CA-ClaraNeural",
|
| 44 |
-
"NebulaNinja π ": "en-US-GuyNeural",
|
| 45 |
-
"ByteBuster πΎ": "en-GB-RyanNeural",
|
| 46 |
-
"GalacticGopher π": "en-AU-WilliamNeural",
|
| 47 |
-
"RocketRaccoon π": "en-CA-LiamNeural",
|
| 48 |
-
"EchoElf π§": "en-US-AnaNeural",
|
| 49 |
-
"PhantomFox π¦": "en-US-BrandonNeural",
|
| 50 |
-
"WittyWizard π§": "en-GB-ThomasNeural",
|
| 51 |
-
"LunarLlama π": "en-AU-FreyaNeural",
|
| 52 |
-
"SolarSloth βοΈ": "en-CA-LindaNeural",
|
| 53 |
-
"AstroAlpaca π¦": "en-US-ChristopherNeural"
|
| 54 |
-
"CyberCoyote πΊ": "en-GB-ElliotNeural",
|
| 55 |
-
"MysticMoose π¦": "en-AU-JamesNeural",
|
| 56 |
-
"GlitchGnome π§": "en-CA-EthanNeural",
|
| 57 |
-
"VortexViper π": "en-US-AmberNeural",
|
| 58 |
-
"ChronoChimp π": "en-GB-LibbyNeural"
|
| 59 |
}
|
| 60 |
|
| 61 |
# Folders galore - organizing chaos! ππ
|
|
@@ -64,10 +65,12 @@ VOTE_DIR = "vote_logs"
|
|
| 64 |
STATE_FILE = "user_state.txt"
|
| 65 |
AUDIO_DIR = "audio_logs"
|
| 66 |
HISTORY_DIR = "history_logs"
|
|
|
|
| 67 |
os.makedirs(CHAT_DIR, exist_ok=True)
|
| 68 |
os.makedirs(VOTE_DIR, exist_ok=True)
|
| 69 |
os.makedirs(AUDIO_DIR, exist_ok=True)
|
| 70 |
os.makedirs(HISTORY_DIR, exist_ok=True)
|
|
|
|
| 71 |
|
| 72 |
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
| 73 |
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
|
@@ -107,6 +110,26 @@ if 'server_task' not in st.session_state:
|
|
| 107 |
st.session_state.server_task = None
|
| 108 |
if 'active_connections' not in st.session_state:
|
| 109 |
st.session_state.active_connections = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
# Timestamp wizardry - clock ticks with flair! β°π©
|
| 112 |
def format_timestamp_prefix():
|
|
@@ -137,11 +160,8 @@ def log_action(username, action):
|
|
| 137 |
|
| 138 |
# Clean text - strip the fancy stuff! π§Ήπ
|
| 139 |
def clean_text_for_tts(text):
|
| 140 |
-
# Remove Markdown formatting (e.g., #, *, [], ![])
|
| 141 |
cleaned = re.sub(r'[#*!\[\]]+', '', text)
|
| 142 |
-
# Replace newlines with spaces and strip extra whitespace
|
| 143 |
cleaned = ' '.join(cleaned.split())
|
| 144 |
-
# Ensure some text exists, max 200 chars to avoid edgeTTS limits
|
| 145 |
return cleaned[:200] if cleaned else "No text to speak"
|
| 146 |
|
| 147 |
# Chat saver - words locked tight! π¬π
|
|
@@ -156,6 +176,8 @@ async def save_chat_entry(username, message):
|
|
| 156 |
if audio_file:
|
| 157 |
with open(HISTORY_FILE, 'a') as f:
|
| 158 |
f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
|
|
|
|
|
|
|
| 159 |
|
| 160 |
# Chat loader - history unleashed! ππ
|
| 161 |
async def load_chat():
|
|
@@ -182,7 +204,7 @@ async def get_user_list(chat_content):
|
|
| 182 |
async def has_joined_before(client_id, chat_content):
|
| 183 |
username = st.session_state.get('username', 'System π')
|
| 184 |
await asyncio.to_thread(log_action, username, "πͺπ - Join checker - been here before?")
|
| 185 |
-
return any(f"Client-{client_id}
|
| 186 |
|
| 187 |
# Suggestion maker - old quips resurface! π‘π
|
| 188 |
async def get_message_suggestions(chat_content, prefix):
|
|
@@ -257,26 +279,24 @@ def play_and_download_audio(file_path):
|
|
| 257 |
dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">π΅ Download {os.path.basename(file_path)}</a>'
|
| 258 |
st.markdown(dl_link, unsafe_allow_html=True)
|
| 259 |
|
| 260 |
-
# Image saver - pics preserved! πΈπΎ
|
| 261 |
-
async def save_pasted_image(
|
| 262 |
-
username = st.session_state.get('username', 'System π')
|
| 263 |
await asyncio.to_thread(log_action, username, "πΈπΎ - Image saver - pics preserved!")
|
| 264 |
timestamp = format_timestamp_prefix()
|
| 265 |
-
filename = f"paste_{timestamp}.png"
|
| 266 |
-
filepath = os.path.join(
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
return filename
|
| 273 |
-
|
| 274 |
-
# Video renderer - movies roll! π₯π¬
|
| 275 |
async def get_video_html(video_path, width="100%"):
|
| 276 |
username = st.session_state.get('username', 'System π')
|
| 277 |
await asyncio.to_thread(log_action, username, "π₯π¬ - Video renderer - movies roll!")
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
| 280 |
|
| 281 |
# Audio renderer - sounds soar! πΆβοΈ
|
| 282 |
async def get_audio_html(audio_path, width="100%"):
|
|
@@ -302,7 +322,6 @@ async def websocket_handler(websocket, path):
|
|
| 302 |
if len(parts) == 2:
|
| 303 |
username, content = parts
|
| 304 |
await save_chat_entry(username, content)
|
| 305 |
-
await broadcast_message(f"{username}|{content}", room_id)
|
| 306 |
except websockets.ConnectionClosed:
|
| 307 |
pass
|
| 308 |
finally:
|
|
@@ -337,11 +356,23 @@ async def process_voice_input(audio_bytes):
|
|
| 337 |
username = st.session_state.get('username', 'System π')
|
| 338 |
await asyncio.to_thread(log_action, username, "π€π - Voice processor - speech to text!")
|
| 339 |
if audio_bytes:
|
| 340 |
-
text = "Voice input simulation"
|
| 341 |
await save_chat_entry(username, text)
|
| 342 |
|
| 343 |
-
#
|
| 344 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
loop = asyncio.new_event_loop()
|
| 346 |
asyncio.set_event_loop(loop)
|
| 347 |
|
|
@@ -351,30 +382,6 @@ def create_streamlit_interface():
|
|
| 351 |
available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
|
| 352 |
st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
|
| 353 |
|
| 354 |
-
if 'refresh_rate' not in st.session_state:
|
| 355 |
-
st.session_state.refresh_rate = 5
|
| 356 |
-
if 'timer_start' not in st.session_state:
|
| 357 |
-
st.session_state.timer_start = time.time()
|
| 358 |
-
if 'quote_line' not in st.session_state:
|
| 359 |
-
st.session_state.quote_line = None
|
| 360 |
-
if 'pasted_image_data' not in st.session_state:
|
| 361 |
-
st.session_state.pasted_image_data = None
|
| 362 |
-
if 'message_text' not in st.session_state:
|
| 363 |
-
st.session_state.message_text = ""
|
| 364 |
-
if 'audio_cache' not in st.session_state:
|
| 365 |
-
st.session_state.audio_cache = {}
|
| 366 |
-
if 'chat_history' not in st.session_state:
|
| 367 |
-
st.session_state.chat_history = []
|
| 368 |
-
|
| 369 |
-
st.markdown("""
|
| 370 |
-
<style>
|
| 371 |
-
.chat-box {font-family: monospace; background: #1e1e1e; color: #d4d4d4; padding: 10px; border-radius: 5px; height: 300px; overflow-y: auto;}
|
| 372 |
-
.timer {font-size: 24px; color: #ffcc00; text-align: center; animation: pulse 1s infinite;}
|
| 373 |
-
@keyframes pulse {0% {transform: scale(1);} 50% {transform: scale(1.1);} 100% {transform: scale(1);}}
|
| 374 |
-
#paste-target {border: 2px dashed #ccc; padding: 20px; text-align: center; cursor: pointer;}
|
| 375 |
-
</style>
|
| 376 |
-
""", unsafe_allow_html=True)
|
| 377 |
-
|
| 378 |
st.title(f"π€π§ MMO {st.session_state.username}ππ¬")
|
| 379 |
st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! π")
|
| 380 |
|
|
@@ -386,150 +393,139 @@ def create_streamlit_interface():
|
|
| 386 |
await process_voice_input(audio_bytes)
|
| 387 |
st.rerun()
|
| 388 |
|
|
|
|
| 389 |
st.subheader(f"{START_ROOM} Chat π¬")
|
| 390 |
chat_content = await load_chat()
|
| 391 |
chat_lines = chat_content.split('\n')
|
| 392 |
chat_votes = await load_votes(QUOTE_VOTES_FILE)
|
| 393 |
-
for i, line in enumerate(chat_lines):
|
| 394 |
-
if line.strip() and ': ' in line:
|
| 395 |
-
col1, col2, col3 = st.columns([4, 1, 1])
|
| 396 |
-
with col1:
|
| 397 |
-
st.markdown(line)
|
| 398 |
-
username = line.split(': ')[1].split(' ')[0]
|
| 399 |
-
audio_file = None
|
| 400 |
-
cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
|
| 401 |
-
if cache_key in st.session_state.audio_cache:
|
| 402 |
-
audio_file = st.session_state.audio_cache[cache_key]
|
| 403 |
-
else:
|
| 404 |
-
cleaned_text = clean_text_for_tts(line.split(': ', 1)[1])
|
| 405 |
-
audio_file = await async_edge_tts_generate(cleaned_text, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
|
| 406 |
-
st.session_state.audio_cache[cache_key] = audio_file
|
| 407 |
-
if audio_file:
|
| 408 |
-
play_and_download_audio(audio_file)
|
| 409 |
-
with col2:
|
| 410 |
-
vote_count = chat_votes.get(line.split('. ')[1] if '. ' in line else line, 0)
|
| 411 |
-
if st.button(f"π {vote_count}", key=f"chat_vote_{i}"):
|
| 412 |
-
comment = st.session_state.message_text
|
| 413 |
-
await save_vote(QUOTE_VOTES_FILE, line.split('. ')[1] if '. ' in line else line, await generate_user_hash(), st.session_state.username, comment)
|
| 414 |
-
if st.session_state.pasted_image_data:
|
| 415 |
-
filename = await save_pasted_image(st.session_state.pasted_image_data)
|
| 416 |
-
if filename:
|
| 417 |
-
await save_chat_entry(st.session_state.username, f"Pasted image: {filename}")
|
| 418 |
-
st.session_state.pasted_image_data = None
|
| 419 |
-
st.session_state.message_text = ''
|
| 420 |
-
st.rerun()
|
| 421 |
-
with col3:
|
| 422 |
-
if st.button("π’ Quote", key=f"quote_{i}"):
|
| 423 |
-
st.session_state.quote_line = line
|
| 424 |
-
st.rerun()
|
| 425 |
|
| 426 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
st.markdown(f"### Quoting: {st.session_state.quote_line}")
|
| 428 |
quote_response = st.text_area("Add your response", key="quote_response")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
if st.button("Send Quote π", key="send_quote"):
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
markdown_response
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
st.session_state.pasted_image_data = None
|
| 438 |
-
try:
|
| 439 |
-
await save_chat_entry(st.session_state.username, markdown_response)
|
| 440 |
-
except edge_tts.exceptions.NoAudioReceived:
|
| 441 |
-
# Log failure but continue without audio
|
| 442 |
-
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 443 |
-
with open(HISTORY_FILE, 'a') as f:
|
| 444 |
-
f.write(f"[{timestamp}] {st.session_state.username}: Quote saved without audio - No audio received\n")
|
| 445 |
-
await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"[{timestamp}] {st.session_state.username}: {markdown_response}\n"))
|
| 446 |
-
loop.run_until_complete(process_quote())
|
| 447 |
-
del st.session_state.quote_line
|
| 448 |
st.session_state.message_text = ''
|
| 449 |
st.rerun()
|
| 450 |
|
| 451 |
new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
|
| 452 |
if new_username and new_username != st.session_state.username:
|
| 453 |
-
|
| 454 |
st.session_state.username = new_username
|
| 455 |
st.rerun()
|
| 456 |
|
| 457 |
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))
|
| 458 |
-
|
| 459 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
if st.session_state.pasted_image_data:
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
loop.run_until_complete(save_chat_entry(st.session_state.username, f"Pasted image: {filename}"))
|
| 464 |
-
st.session_state.pasted_image_data = None
|
| 465 |
st.session_state.message_text = ''
|
| 466 |
st.rerun()
|
| 467 |
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
const pasteTarget = document.getElementById('paste-target');
|
| 473 |
-
pasteTarget.addEventListener('paste', (event) => {
|
| 474 |
-
const items = (event.clipboardData || window.clipboardData).items;
|
| 475 |
-
for (let i = 0; i < items.length; i++) {
|
| 476 |
-
if (items[i].type.indexOf('image') !== -1) {
|
| 477 |
-
const blob = items[i].getAsFile();
|
| 478 |
-
const reader = new FileReader();
|
| 479 |
-
reader.onload = (e) => {
|
| 480 |
-
window.parent.postMessage({
|
| 481 |
-
type: 'streamlit:setComponentValue',
|
| 482 |
-
value: e.target.result
|
| 483 |
-
}, '*');
|
| 484 |
-
pasteTarget.innerHTML = '<p>Image pasted! Processing...</p>';
|
| 485 |
-
};
|
| 486 |
-
reader.readAsDataURL(blob);
|
| 487 |
-
}
|
| 488 |
-
}
|
| 489 |
-
event.preventDefault();
|
| 490 |
-
});
|
| 491 |
-
</script>
|
| 492 |
-
""",
|
| 493 |
-
height=100
|
| 494 |
-
)
|
| 495 |
|
| 496 |
-
|
| 497 |
-
|
|
|
|
| 498 |
if uploaded_file:
|
| 499 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
|
| 501 |
-
st.success(f"Uploaded {
|
|
|
|
|
|
|
|
|
|
| 502 |
|
| 503 |
-
|
|
|
|
| 504 |
if media_files:
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
for
|
|
|
|
| 508 |
vote_count = media_votes.get(media_file, 0)
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
filename = loop.run_until_complete(save_pasted_image(st.session_state.pasted_image_data))
|
| 524 |
-
if filename:
|
| 525 |
-
loop.run_until_complete(save_chat_entry(st.session_state.username, f"Pasted image: {filename}"))
|
| 526 |
-
st.session_state.pasted_image_data = None
|
| 527 |
-
st.session_state.message_text = ''
|
| 528 |
-
st.rerun()
|
| 529 |
-
with col2:
|
| 530 |
-
if st.button("ποΈ", key=f"media_delete_{idx}"):
|
| 531 |
-
await asyncio.to_thread(os.remove, media_file)
|
| 532 |
-
st.rerun()
|
| 533 |
|
| 534 |
st.subheader("Refresh β³")
|
| 535 |
refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
|
|
@@ -539,7 +535,7 @@ def create_streamlit_interface():
|
|
| 539 |
font_name, font_func = random.choice(UNICODE_FONTS)
|
| 540 |
countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
|
| 541 |
timer_placeholder.markdown(f"<p class='timer'>β³ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
|
| 542 |
-
|
| 543 |
st.rerun()
|
| 544 |
|
| 545 |
st.sidebar.subheader("Chat History π")
|
|
@@ -549,10 +545,5 @@ def create_streamlit_interface():
|
|
| 549 |
|
| 550 |
loop.run_until_complete(async_interface())
|
| 551 |
|
| 552 |
-
# Main execution - letβs roll! π²π
|
| 553 |
-
def main():
|
| 554 |
-
NODE_NAME, port = get_node_name()
|
| 555 |
-
create_streamlit_interface()
|
| 556 |
-
|
| 557 |
if __name__ == "__main__":
|
| 558 |
main()
|
|
|
|
| 18 |
from audio_recorder_streamlit import audio_recorder
|
| 19 |
import nest_asyncio
|
| 20 |
import re
|
| 21 |
+
from streamlit_paste_button import paste_image_button # Using this for image pasting
|
| 22 |
|
| 23 |
# Patch for nested async - sneaky fix! πβ¨
|
| 24 |
nest_asyncio.apply()
|
|
|
|
| 37 |
|
| 38 |
# Funky usernames - whoβs who in the zoo with unique voices! ππΎποΈ
|
| 39 |
FUN_USERNAMES = {
|
| 40 |
+
"CosmicJester π": "en-US-AriaNeural",
|
| 41 |
+
"PixelPanda πΌ": "en-US-JennyNeural",
|
| 42 |
+
"QuantumQuack π¦": "en-GB-SoniaNeural",
|
| 43 |
+
"StellarSquirrel πΏοΈ": "en-AU-NatashaNeural",
|
| 44 |
+
"GizmoGuru βοΈ": "en-CA-ClaraNeural",
|
| 45 |
+
"NebulaNinja π ": "en-US-GuyNeural",
|
| 46 |
+
"ByteBuster πΎ": "en-GB-RyanNeural",
|
| 47 |
+
"GalacticGopher π": "en-AU-WilliamNeural",
|
| 48 |
+
"RocketRaccoon π": "en-CA-LiamNeural",
|
| 49 |
+
"EchoElf π§": "en-US-AnaNeural",
|
| 50 |
+
"PhantomFox π¦": "en-US-BrandonNeural",
|
| 51 |
+
"WittyWizard π§": "en-GB-ThomasNeural",
|
| 52 |
+
"LunarLlama π": "en-AU-FreyaNeural",
|
| 53 |
+
"SolarSloth βοΈ": "en-CA-LindaNeural",
|
| 54 |
+
"AstroAlpaca π¦": "en-US-ChristopherNeural",
|
| 55 |
+
"CyberCoyote πΊ": "en-GB-ElliotNeural",
|
| 56 |
+
"MysticMoose π¦": "en-AU-JamesNeural",
|
| 57 |
+
"GlitchGnome π§": "en-CA-EthanNeural",
|
| 58 |
+
"VortexViper π": "en-US-AmberNeural",
|
| 59 |
+
"ChronoChimp π": "en-GB-LibbyNeural"
|
| 60 |
}
|
| 61 |
|
| 62 |
# Folders galore - organizing chaos! ππ
|
|
|
|
| 65 |
STATE_FILE = "user_state.txt"
|
| 66 |
AUDIO_DIR = "audio_logs"
|
| 67 |
HISTORY_DIR = "history_logs"
|
| 68 |
+
MEDIA_DIR = "media_files"
|
| 69 |
os.makedirs(CHAT_DIR, exist_ok=True)
|
| 70 |
os.makedirs(VOTE_DIR, exist_ok=True)
|
| 71 |
os.makedirs(AUDIO_DIR, exist_ok=True)
|
| 72 |
os.makedirs(HISTORY_DIR, exist_ok=True)
|
| 73 |
+
os.makedirs(MEDIA_DIR, exist_ok=True)
|
| 74 |
|
| 75 |
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
| 76 |
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
|
|
|
| 110 |
st.session_state.server_task = None
|
| 111 |
if 'active_connections' not in st.session_state:
|
| 112 |
st.session_state.active_connections = {}
|
| 113 |
+
if 'media_notifications' not in st.session_state:
|
| 114 |
+
st.session_state.media_notifications = []
|
| 115 |
+
if 'last_chat_update' not in st.session_state:
|
| 116 |
+
st.session_state.last_chat_update = 0
|
| 117 |
+
if 'displayed_chat_lines' not in st.session_state:
|
| 118 |
+
st.session_state.displayed_chat_lines = []
|
| 119 |
+
if 'old_val' not in st.session_state:
|
| 120 |
+
st.session_state.old_val = ""
|
| 121 |
+
if 'last_query' not in st.session_state:
|
| 122 |
+
st.session_state.last_query = ""
|
| 123 |
+
if 'message_text' not in st.session_state:
|
| 124 |
+
st.session_state.message_text = ""
|
| 125 |
+
if 'audio_cache' not in st.session_state:
|
| 126 |
+
st.session_state.audio_cache = {}
|
| 127 |
+
if 'pasted_image_data' not in st.session_state:
|
| 128 |
+
st.session_state.pasted_image_data = None
|
| 129 |
+
if 'quote_line' not in st.session_state:
|
| 130 |
+
st.session_state.quote_line = None
|
| 131 |
+
if 'refresh_rate' not in st.session_state:
|
| 132 |
+
st.session_state.refresh_rate = 5 # Default refresh rate
|
| 133 |
|
| 134 |
# Timestamp wizardry - clock ticks with flair! β°π©
|
| 135 |
def format_timestamp_prefix():
|
|
|
|
| 160 |
|
| 161 |
# Clean text - strip the fancy stuff! π§Ήπ
|
| 162 |
def clean_text_for_tts(text):
|
|
|
|
| 163 |
cleaned = re.sub(r'[#*!\[\]]+', '', text)
|
|
|
|
| 164 |
cleaned = ' '.join(cleaned.split())
|
|
|
|
| 165 |
return cleaned[:200] if cleaned else "No text to speak"
|
| 166 |
|
| 167 |
# Chat saver - words locked tight! π¬π
|
|
|
|
| 176 |
if audio_file:
|
| 177 |
with open(HISTORY_FILE, 'a') as f:
|
| 178 |
f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
|
| 179 |
+
await broadcast_message(f"{username}|{message}", "chat")
|
| 180 |
+
st.session_state.last_chat_update = time.time()
|
| 181 |
|
| 182 |
# Chat loader - history unleashed! ππ
|
| 183 |
async def load_chat():
|
|
|
|
| 204 |
async def has_joined_before(client_id, chat_content):
|
| 205 |
username = st.session_state.get('username', 'System π')
|
| 206 |
await asyncio.to_thread(log_action, username, "πͺπ - Join checker - been here before?")
|
| 207 |
+
return any(f"Client-{client_id}" in line for line in chat_content.split('\n'))
|
| 208 |
|
| 209 |
# Suggestion maker - old quips resurface! π‘π
|
| 210 |
async def get_message_suggestions(chat_content, prefix):
|
|
|
|
| 279 |
dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">π΅ Download {os.path.basename(file_path)}</a>'
|
| 280 |
st.markdown(dl_link, unsafe_allow_html=True)
|
| 281 |
|
| 282 |
+
# Image saver - pics preserved with naming! πΈπΎ
|
| 283 |
+
async def save_pasted_image(image, username):
|
|
|
|
| 284 |
await asyncio.to_thread(log_action, username, "πΈπΎ - Image saver - pics preserved!")
|
| 285 |
timestamp = format_timestamp_prefix()
|
| 286 |
+
filename = f"paste_{timestamp}_{username}.png"
|
| 287 |
+
filepath = os.path.join(MEDIA_DIR, filename)
|
| 288 |
+
# Directly save the PIL Image object without base64 conversion
|
| 289 |
+
await asyncio.to_thread(image.save, filepath, "PNG")
|
| 290 |
+
return filepath
|
| 291 |
+
|
| 292 |
+
# Video renderer - movies roll with autoplay! π₯π¬
|
|
|
|
|
|
|
|
|
|
| 293 |
async def get_video_html(video_path, width="100%"):
|
| 294 |
username = st.session_state.get('username', 'System π')
|
| 295 |
await asyncio.to_thread(log_action, username, "π₯π¬ - Video renderer - movies roll!")
|
| 296 |
+
with open(video_path, 'rb') as f:
|
| 297 |
+
video_data = await asyncio.to_thread(f.read)
|
| 298 |
+
video_url = f"data:video/mp4;base64,{base64.b64encode(video_data).decode()}"
|
| 299 |
+
return f'<video width="{width}" controls autoplay><source src="{video_url}" type="video/mp4">Your browser does not support the video tag.</video>'
|
| 300 |
|
| 301 |
# Audio renderer - sounds soar! πΆβοΈ
|
| 302 |
async def get_audio_html(audio_path, width="100%"):
|
|
|
|
| 322 |
if len(parts) == 2:
|
| 323 |
username, content = parts
|
| 324 |
await save_chat_entry(username, content)
|
|
|
|
| 325 |
except websockets.ConnectionClosed:
|
| 326 |
pass
|
| 327 |
finally:
|
|
|
|
| 356 |
username = st.session_state.get('username', 'System π')
|
| 357 |
await asyncio.to_thread(log_action, username, "π€π - Voice processor - speech to text!")
|
| 358 |
if audio_bytes:
|
| 359 |
+
text = "Voice input simulation"
|
| 360 |
await save_chat_entry(username, text)
|
| 361 |
|
| 362 |
+
# Dummy AI lookup function (replace with actual implementation)
|
| 363 |
+
async def perform_ai_lookup(query, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False, useArxiv=True, useArxivAudio=False):
|
| 364 |
+
username = st.session_state.get('username', 'System π')
|
| 365 |
+
result = f"AI Lookup Result for '{query}' (Arxiv: {useArxiv}, Audio: {useArxivAudio})"
|
| 366 |
+
await save_chat_entry(username, result)
|
| 367 |
+
if useArxivAudio:
|
| 368 |
+
audio_file = await async_edge_tts_generate(result, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
|
| 369 |
+
if audio_file:
|
| 370 |
+
st.audio(audio_file)
|
| 371 |
+
|
| 372 |
+
# Main execution - letβs roll! π²π
|
| 373 |
+
def main():
|
| 374 |
+
NODE_NAME, port = get_node_name()
|
| 375 |
+
|
| 376 |
loop = asyncio.new_event_loop()
|
| 377 |
asyncio.set_event_loop(loop)
|
| 378 |
|
|
|
|
| 382 |
available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
|
| 383 |
st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
|
| 384 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
st.title(f"π€π§ MMO {st.session_state.username}ππ¬")
|
| 386 |
st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! π")
|
| 387 |
|
|
|
|
| 393 |
await process_voice_input(audio_bytes)
|
| 394 |
st.rerun()
|
| 395 |
|
| 396 |
+
# Load and display chat
|
| 397 |
st.subheader(f"{START_ROOM} Chat π¬")
|
| 398 |
chat_content = await load_chat()
|
| 399 |
chat_lines = chat_content.split('\n')
|
| 400 |
chat_votes = await load_votes(QUOTE_VOTES_FILE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
|
| 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 and not line.startswith('#')]
|
| 405 |
+
st.session_state.displayed_chat_lines.extend(new_lines)
|
| 406 |
+
st.session_state.last_chat_update = current_time
|
| 407 |
+
|
| 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:
|
| 411 |
+
st.markdown(line)
|
| 412 |
+
if "Pasted image:" in line or "Uploaded media:" in line:
|
| 413 |
+
file_path = line.split(': ')[-1].strip()
|
| 414 |
+
if os.path.exists(file_path):
|
| 415 |
+
if file_path.endswith(('.png', '.jpg')):
|
| 416 |
+
st.image(file_path, use_container_width=True)
|
| 417 |
+
elif file_path.endswith('.mp4'):
|
| 418 |
+
st.markdown(await get_video_html(file_path), unsafe_allow_html=True)
|
| 419 |
+
elif file_path.endswith('.mp3'):
|
| 420 |
+
st.markdown(await get_audio_html(file_path), unsafe_allow_html=True)
|
| 421 |
+
with col2:
|
| 422 |
+
vote_count = chat_votes.get(line.split('. ')[1] if '. ' in line else line, 0)
|
| 423 |
+
if st.button(f"π {vote_count}", key=f"chat_vote_{i}"):
|
| 424 |
+
comment = st.session_state.message_text
|
| 425 |
+
await save_vote(QUOTE_VOTES_FILE, line.split('. ')[1] if '. ' in line else line, await generate_user_hash(), st.session_state.username, comment)
|
| 426 |
+
st.session_state.message_text = ''
|
| 427 |
+
st.rerun()
|
| 428 |
+
with col3:
|
| 429 |
+
if st.button("π’ Quote", key=f"quote_{i}"):
|
| 430 |
+
st.session_state.quote_line = line
|
| 431 |
+
st.rerun()
|
| 432 |
+
with col4:
|
| 433 |
+
username = line.split(': ')[1].split(' ')[0]
|
| 434 |
+
cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
|
| 435 |
+
if cache_key not in st.session_state.audio_cache:
|
| 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 |
+
audio_file = st.session_state.audio_cache.get(cache_key)
|
| 440 |
+
if audio_file:
|
| 441 |
+
play_and_download_audio(audio_file)
|
| 442 |
+
|
| 443 |
+
if st.session_state.quote_line:
|
| 444 |
st.markdown(f"### Quoting: {st.session_state.quote_line}")
|
| 445 |
quote_response = st.text_area("Add your response", key="quote_response")
|
| 446 |
+
# Add paste button within quote response
|
| 447 |
+
paste_result_quote = paste_image_button("π Paste Image with Quote", key="paste_button_quote")
|
| 448 |
+
if paste_result_quote.image_data is not None:
|
| 449 |
+
st.image(paste_result_quote.image_data, caption="Received Image for Quote")
|
| 450 |
+
filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
|
| 451 |
+
if filename:
|
| 452 |
+
st.session_state.pasted_image_data = filename # Store for use in quote submission
|
| 453 |
if st.button("Send Quote π", key="send_quote"):
|
| 454 |
+
markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
|
| 455 |
+
if st.session_state.pasted_image_data:
|
| 456 |
+
markdown_response += f"\n- **Image**: "
|
| 457 |
+
await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
|
| 458 |
+
st.session_state.pasted_image_data = None
|
| 459 |
+
await save_chat_entry(st.session_state.username, markdown_response)
|
| 460 |
+
st.session_state.quote_line = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
st.session_state.message_text = ''
|
| 462 |
st.rerun()
|
| 463 |
|
| 464 |
new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
|
| 465 |
if new_username and new_username != st.session_state.username:
|
| 466 |
+
await save_chat_entry("System π", f"{st.session_state.username} changed name to {new_username}")
|
| 467 |
st.session_state.username = new_username
|
| 468 |
st.rerun()
|
| 469 |
|
| 470 |
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))
|
| 471 |
+
# Add paste button next to message input
|
| 472 |
+
paste_result_msg = paste_image_button("π Paste Image with Message", key="paste_button_msg")
|
| 473 |
+
if paste_result_msg.image_data is not None:
|
| 474 |
+
st.image(paste_result_msg.image_data, caption="Received Image for Message")
|
| 475 |
+
filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
|
| 476 |
+
if filename:
|
| 477 |
+
st.session_state.pasted_image_data = filename # Store for use in message submission
|
| 478 |
+
if st.button("Send π", key="send_button") and (message.strip() or st.session_state.pasted_image_data):
|
| 479 |
+
if message.strip():
|
| 480 |
+
await save_chat_entry(st.session_state.username, message)
|
| 481 |
if st.session_state.pasted_image_data:
|
| 482 |
+
await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
|
| 483 |
+
st.session_state.pasted_image_data = None
|
|
|
|
|
|
|
| 484 |
st.session_state.message_text = ''
|
| 485 |
st.rerun()
|
| 486 |
|
| 487 |
+
# Main action tabs and model use choices
|
| 488 |
+
tab_main = st.radio("Action:", ["π€ Voice", "πΈ Media", "π ArXiv", "π Editor"], horizontal=True)
|
| 489 |
+
useArxiv = st.checkbox("Search Arxiv for Research Paper Answers", value=True)
|
| 490 |
+
useArxivAudio = st.checkbox("Generate Audio File for Research Paper Answers", value=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
|
| 492 |
+
# Enhanced Media Gallery with Image, Audio, Video
|
| 493 |
+
st.subheader("Upload Media π¨πΆπ₯")
|
| 494 |
+
uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3'])
|
| 495 |
if uploaded_file:
|
| 496 |
+
timestamp = format_timestamp_prefix()
|
| 497 |
+
username = st.session_state.username
|
| 498 |
+
ext = uploaded_file.name.split('.')[-1]
|
| 499 |
+
filename = f"{timestamp}_{username}.{ext}"
|
| 500 |
+
file_path = os.path.join(MEDIA_DIR, filename)
|
| 501 |
await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
|
| 502 |
+
st.success(f"Uploaded {filename}")
|
| 503 |
+
await save_chat_entry(username, f"Uploaded media: {file_path}")
|
| 504 |
+
if file_path.endswith('.mp4'):
|
| 505 |
+
st.session_state.media_notifications.append(file_path)
|
| 506 |
|
| 507 |
+
st.subheader("Media Gallery π¨πΆπ₯")
|
| 508 |
+
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")
|
| 509 |
if media_files:
|
| 510 |
+
media_votes = await load_votes(MEDIA_VOTES_FILE)
|
| 511 |
+
st.write("### All Media Uploads")
|
| 512 |
+
for media_file in sorted(media_files, key=os.path.getmtime, reverse=True): # Sort by modification time, newest first
|
| 513 |
+
filename = os.path.basename(media_file)
|
| 514 |
vote_count = media_votes.get(media_file, 0)
|
| 515 |
+
|
| 516 |
+
col1, col2 = st.columns([3, 1])
|
| 517 |
+
with col1:
|
| 518 |
+
st.markdown(f"**{filename}**")
|
| 519 |
+
if media_file.endswith(('.png', '.jpg')):
|
| 520 |
+
st.image(media_file, use_container_width=True)
|
| 521 |
+
elif media_file.endswith('.mp4'):
|
| 522 |
+
st.markdown(await get_video_html(media_file), unsafe_allow_html=True)
|
| 523 |
+
elif media_file.endswith('.mp3'):
|
| 524 |
+
st.markdown(await get_audio_html(media_file), unsafe_allow_html=True)
|
| 525 |
+
with col2:
|
| 526 |
+
if st.button(f"π {vote_count}", key=f"media_vote_{media_file}"):
|
| 527 |
+
await save_vote(MEDIA_VOTES_FILE, media_file, await generate_user_hash(), st.session_state.username)
|
| 528 |
+
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 529 |
|
| 530 |
st.subheader("Refresh β³")
|
| 531 |
refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
|
|
|
|
| 535 |
font_name, font_func = random.choice(UNICODE_FONTS)
|
| 536 |
countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
|
| 537 |
timer_placeholder.markdown(f"<p class='timer'>β³ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
|
| 538 |
+
time.sleep(1) # Use synchronous sleep
|
| 539 |
st.rerun()
|
| 540 |
|
| 541 |
st.sidebar.subheader("Chat History π")
|
|
|
|
| 545 |
|
| 546 |
loop.run_until_complete(async_interface())
|
| 547 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
if __name__ == "__main__":
|
| 549 |
main()
|