Update app.py
Browse files
app.py
CHANGED
@@ -12,6 +12,8 @@ from PIL import Image
|
|
12 |
import glob
|
13 |
import re
|
14 |
from urllib.parse import quote
|
|
|
|
|
15 |
|
16 |
# App Configuration
|
17 |
Site_Name = '🤖🧠Chat & Quote Node📝🔬'
|
@@ -26,23 +28,36 @@ st.set_page_config(
|
|
26 |
initial_sidebar_state="auto"
|
27 |
)
|
28 |
|
29 |
-
# Fun usernames with emojis - the VIP list of quirky characters! 🎉😜
|
30 |
-
FUN_USERNAMES =
|
31 |
-
"CosmicJester 🌌"
|
32 |
-
"
|
33 |
-
"
|
34 |
-
"
|
35 |
-
"
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
-
# Directories for chat
|
39 |
CHAT_DIR = "chat_logs"
|
40 |
VOTE_DIR = "vote_logs"
|
41 |
-
MEDIA_DIR = "media"
|
42 |
STATE_FILE = "user_state.txt"
|
43 |
os.makedirs(CHAT_DIR, exist_ok=True)
|
44 |
os.makedirs(VOTE_DIR, exist_ok=True)
|
45 |
-
os.makedirs(MEDIA_DIR, exist_ok=True)
|
46 |
|
47 |
# Persistent files - the grand tomes of chatter and votes! 📖✨
|
48 |
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
@@ -122,6 +137,13 @@ def get_user_list(chat_content):
|
|
122 |
users.add(user)
|
123 |
return sorted(list(users))
|
124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
# Quote loader - the sage pulling wisdom from the ages! 📜🧙
|
126 |
def load_quotes(source="famous"):
|
127 |
"""📚 Grabs a stack of wise words from famous folks or custom quips! 🗣️"""
|
@@ -218,6 +240,23 @@ def load_username():
|
|
218 |
print(f"Failed to load username: {e}")
|
219 |
return None
|
220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
# Media HTML generators - IVA’s multimedia magic! 🎥🎶🖼️
|
222 |
def get_video_html(video_path, width="100%"):
|
223 |
"""🎬 Rolls out the red carpet for videos - autoplay and loop like a star! 🌟"""
|
@@ -249,8 +288,7 @@ async def websocket_handler(websocket, path):
|
|
249 |
room_id = "chat" # Single room "Sector 🌌"
|
250 |
active_connections.setdefault(room_id, {})[client_id] = websocket
|
251 |
print(f"Client {client_id} joined the Sector party!")
|
252 |
-
|
253 |
-
username = st.session_state.get('username', random.choice(FUN_USERNAMES))
|
254 |
save_chat_entry("System 🌟", f"{username} has joined {START_ROOM}!")
|
255 |
|
256 |
async for message in websocket:
|
@@ -298,7 +336,7 @@ async def run_websocket_server():
|
|
298 |
# Chat interface maker - the stage builder for our Sector extravaganza! 🎭🏟️
|
299 |
def create_streamlit_interface(initial_username):
|
300 |
"""🖌️ Sets up the Sector stage with pulsing timers, voting, and IVA media flair! 🌟"""
|
301 |
-
# Custom CSS
|
302 |
st.markdown("""
|
303 |
<style>
|
304 |
.chat-box {
|
@@ -322,11 +360,34 @@ def create_streamlit_interface(initial_username):
|
|
322 |
100% { transform: scale(1); }
|
323 |
}
|
324 |
</style>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
325 |
""", unsafe_allow_html=True)
|
326 |
|
327 |
# Title and intro
|
328 |
st.title(f"{Site_Name}")
|
329 |
-
st.markdown(f"Welcome to {START_ROOM} - chat, vote, and enjoy IVA’s media magic! 🎉")
|
330 |
|
331 |
# Load or set username
|
332 |
saved_username = load_username()
|
@@ -347,6 +408,8 @@ def create_streamlit_interface(initial_username):
|
|
347 |
st.session_state.quote_index = random.randint(0, max(0, len(quotes) - 1)) if quotes else 0
|
348 |
if 'quote_source' not in st.session_state:
|
349 |
st.session_state.quote_source = "famous"
|
|
|
|
|
350 |
|
351 |
# Chat section
|
352 |
st.subheader(f"{START_ROOM} Chat 💬")
|
@@ -366,22 +429,44 @@ def create_streamlit_interface(initial_username):
|
|
366 |
st.rerun()
|
367 |
|
368 |
user_list = get_user_list(chat_content)
|
369 |
-
new_username = st.selectbox("Switch
|
370 |
if new_username != st.session_state.username:
|
371 |
save_chat_entry("System 🌟", f"{st.session_state.username} switched to {new_username} in {START_ROOM}!")
|
372 |
st.session_state.username = new_username
|
373 |
st.session_state.timer_start = time.time()
|
374 |
save_username(st.session_state.username)
|
375 |
|
376 |
-
|
377 |
-
|
378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
379 |
st.session_state.timer_start = time.time()
|
380 |
save_username(st.session_state.username)
|
381 |
st.rerun()
|
382 |
|
383 |
# Quote section
|
384 |
-
st.subheader("Quote
|
385 |
quotes = load_quotes(st.session_state.quote_source)
|
386 |
if quotes:
|
387 |
st.session_state.quote_index = st.session_state.quote_index % len(quotes)
|
@@ -390,7 +475,7 @@ def create_streamlit_interface(initial_username):
|
|
390 |
with col1:
|
391 |
st.markdown(quote)
|
392 |
with col2:
|
393 |
-
if st.button("👍
|
394 |
user_hash = generate_user_hash()
|
395 |
save_vote(QUOTE_VOTES_FILE, quote, user_hash)
|
396 |
st.session_state.timer_start = time.time()
|
@@ -407,15 +492,15 @@ def create_streamlit_interface(initial_username):
|
|
407 |
else:
|
408 |
st.markdown("No quotes available - check back later! 📭")
|
409 |
|
410 |
-
# IVA Media Gallery
|
411 |
-
st.subheader("IVA
|
412 |
media_files = (
|
413 |
-
glob.glob(
|
414 |
-
glob.glob(
|
415 |
-
glob.glob(
|
416 |
)
|
417 |
if media_files:
|
418 |
-
media_cols = st.slider("Gallery
|
419 |
cols = st.columns(media_cols)
|
420 |
for idx, media_file in enumerate(media_files):
|
421 |
with cols[idx % media_cols]:
|
@@ -425,18 +510,18 @@ def create_streamlit_interface(initial_username):
|
|
425 |
st.markdown(get_audio_html(media_file, width="100%"), unsafe_allow_html=True)
|
426 |
elif media_file.endswith('.mp4'):
|
427 |
st.markdown(get_video_html(media_file, width="100%"), unsafe_allow_html=True)
|
428 |
-
if st.button(f"👍
|
429 |
user_hash = generate_user_hash()
|
430 |
save_vote(IMAGE_VOTES_FILE, media_file, user_hash)
|
431 |
st.session_state.timer_start = time.time()
|
432 |
save_username(st.session_state.username)
|
433 |
st.rerun()
|
434 |
else:
|
435 |
-
st.error("No media files (images, audio, video) found in
|
436 |
|
437 |
# Refresh rate controls with pulsing timer
|
438 |
-
st.subheader("
|
439 |
-
refresh_rate = st.slider("Refresh
|
440 |
if refresh_rate != st.session_state.refresh_rate:
|
441 |
st.session_state.refresh_rate = refresh_rate
|
442 |
st.session_state.timer_start = time.time()
|
@@ -444,17 +529,17 @@ def create_streamlit_interface(initial_username):
|
|
444 |
|
445 |
col1, col2, col3 = st.columns(3)
|
446 |
with col1:
|
447 |
-
if st.button("🐇 Small (1s)"):
|
448 |
st.session_state.refresh_rate = 1
|
449 |
st.session_state.timer_start = time.time()
|
450 |
save_username(st.session_state.username)
|
451 |
with col2:
|
452 |
-
if st.button("🐢 Medium (5s)"):
|
453 |
st.session_state.refresh_rate = 5
|
454 |
st.session_state.timer_start = time.time()
|
455 |
save_username(st.session_state.username)
|
456 |
with col3:
|
457 |
-
if st.button("🐘 Large (5m)"):
|
458 |
st.session_state.refresh_rate = 300
|
459 |
st.session_state.timer_start = time.time()
|
460 |
save_username(st.session_state.username)
|
@@ -474,7 +559,7 @@ def create_streamlit_interface(initial_username):
|
|
474 |
st.rerun()
|
475 |
|
476 |
# Sidebar vote stats
|
477 |
-
st.sidebar.subheader("Vote
|
478 |
chat_votes = load_votes(QUOTE_VOTES_FILE)
|
479 |
image_votes = load_votes(IMAGE_VOTES_FILE)
|
480 |
for item, count in chat_votes.items():
|
@@ -493,7 +578,7 @@ async def main():
|
|
493 |
server_task = asyncio.create_task(run_websocket_server())
|
494 |
|
495 |
query_params = st.query_params if hasattr(st, 'query_params') else {}
|
496 |
-
initial_username = query_params.get("username", random.choice(FUN_USERNAMES)) if query_params else random.choice(FUN_USERNAMES)
|
497 |
print(f"Welcoming {initial_username} to the Sector bash!")
|
498 |
|
499 |
create_streamlit_interface(initial_username)
|
|
|
12 |
import glob
|
13 |
import re
|
14 |
from urllib.parse import quote
|
15 |
+
import base64
|
16 |
+
import io
|
17 |
|
18 |
# App Configuration
|
19 |
Site_Name = '🤖🧠Chat & Quote Node📝🔬'
|
|
|
28 |
initial_sidebar_state="auto"
|
29 |
)
|
30 |
|
31 |
+
# Fun usernames with emojis and rhyming labels - the VIP list of quirky characters! 🎉😜
|
32 |
+
FUN_USERNAMES = {
|
33 |
+
"CosmicJester 🌌": "Jest Best",
|
34 |
+
"PixelPanda 🐼": "Panda Dandy",
|
35 |
+
"QuantumQuack 🦆": "Quack Pack",
|
36 |
+
"StellarSquirrel 🐿️": "Squirrel Whirl",
|
37 |
+
"GizmoGuru ⚙️": "Guru Brew",
|
38 |
+
"NebulaNinja 🌠": "Ninja Zinger",
|
39 |
+
"ByteBuster 💾": "Buster Cluster",
|
40 |
+
"GalacticGopher 🌍": "Gopher Loafer",
|
41 |
+
"RocketRaccoon 🚀": "Raccoon Zoom",
|
42 |
+
"EchoElf 🧝": "Elf Shelf",
|
43 |
+
"PhantomFox 🦊": "Fox Rocks",
|
44 |
+
"WittyWizard 🧙": "Wizard Blizzard",
|
45 |
+
"LunarLlama 🌙": "Llama Drama",
|
46 |
+
"SolarSloth ☀️": "Sloth Growth",
|
47 |
+
"AstroAlpaca 🦙": "Alpaca Plaque",
|
48 |
+
"CyberCoyote 🐺": "Coyote Byte",
|
49 |
+
"MysticMoose 🦌": "Moose Juice",
|
50 |
+
"GlitchGnome 🧚": "Gnome Roam",
|
51 |
+
"VortexViper 🐍": "Viper Hyper",
|
52 |
+
"ChronoChimp 🐒": "Chimp Whimp"
|
53 |
+
}
|
54 |
|
55 |
+
# Directories for chat and votes - the secret vaults where treasures are stashed! 🗄️🔒
|
56 |
CHAT_DIR = "chat_logs"
|
57 |
VOTE_DIR = "vote_logs"
|
|
|
58 |
STATE_FILE = "user_state.txt"
|
59 |
os.makedirs(CHAT_DIR, exist_ok=True)
|
60 |
os.makedirs(VOTE_DIR, exist_ok=True)
|
|
|
61 |
|
62 |
# Persistent files - the grand tomes of chatter and votes! 📖✨
|
63 |
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
|
|
137 |
users.add(user)
|
138 |
return sorted(list(users))
|
139 |
|
140 |
+
# Message suggestion loader - the oracle of past chats! 🔮💬
|
141 |
+
def get_message_suggestions(chat_content, prefix):
|
142 |
+
"""🔮 Pulls past messages from the cosmic archives for autocomplete magic! ✨"""
|
143 |
+
lines = chat_content.split('\n')
|
144 |
+
messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
|
145 |
+
return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5] # Top 5 matches
|
146 |
+
|
147 |
# Quote loader - the sage pulling wisdom from the ages! 📜🧙
|
148 |
def load_quotes(source="famous"):
|
149 |
"""📚 Grabs a stack of wise words from famous folks or custom quips! 🗣️"""
|
|
|
240 |
print(f"Failed to load username: {e}")
|
241 |
return None
|
242 |
|
243 |
+
# Image paste handler - the cosmic courier delivering pasted pics! 📸🚀
|
244 |
+
def save_pasted_image(image_data):
|
245 |
+
"""📸 Saves a pasted image to the root vault with a cosmic name! 🌠"""
|
246 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
247 |
+
filename = f"paste_{timestamp}.png"
|
248 |
+
filepath = os.path.join('./', filename) # Root directory
|
249 |
+
try:
|
250 |
+
if ',' in image_data:
|
251 |
+
image_data = image_data.split(',')[1]
|
252 |
+
img_bytes = base64.b64decode(image_data)
|
253 |
+
img = Image.open(io.BytesIO(img_bytes))
|
254 |
+
img.save(filepath, "PNG")
|
255 |
+
return filename
|
256 |
+
except Exception as e:
|
257 |
+
print(f"Failed to save pasted image: {e}")
|
258 |
+
return None
|
259 |
+
|
260 |
# Media HTML generators - IVA’s multimedia magic! 🎥🎶🖼️
|
261 |
def get_video_html(video_path, width="100%"):
|
262 |
"""🎬 Rolls out the red carpet for videos - autoplay and loop like a star! 🌟"""
|
|
|
288 |
room_id = "chat" # Single room "Sector 🌌"
|
289 |
active_connections.setdefault(room_id, {})[client_id] = websocket
|
290 |
print(f"Client {client_id} joined the Sector party!")
|
291 |
+
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
|
|
|
292 |
save_chat_entry("System 🌟", f"{username} has joined {START_ROOM}!")
|
293 |
|
294 |
async for message in websocket:
|
|
|
336 |
# Chat interface maker - the stage builder for our Sector extravaganza! 🎭🏟️
|
337 |
def create_streamlit_interface(initial_username):
|
338 |
"""🖌️ Sets up the Sector stage with pulsing timers, voting, and IVA media flair! 🌟"""
|
339 |
+
# Custom CSS and JS for chat box, timer, and paste detection
|
340 |
st.markdown("""
|
341 |
<style>
|
342 |
.chat-box {
|
|
|
360 |
100% { transform: scale(1); }
|
361 |
}
|
362 |
</style>
|
363 |
+
<script>
|
364 |
+
document.addEventListener('paste', function(e) {
|
365 |
+
const items = (e.clipboardData || window.clipboardData).items;
|
366 |
+
for (let i = 0; i < items.length; i++) {
|
367 |
+
if (items[i].type.indexOf('image') !== -1) {
|
368 |
+
const blob = items[i].getAsFile();
|
369 |
+
const reader = new FileReader();
|
370 |
+
reader.onload = function(event) {
|
371 |
+
const imageData = event.target.result;
|
372 |
+
sessionStorage.setItem('pastedImage', imageData);
|
373 |
+
document.getElementById('message_input').value = 'PastedImage:' + blob.name;
|
374 |
+
document.getElementById('send_button').click();
|
375 |
+
};
|
376 |
+
reader.readAsDataURL(blob);
|
377 |
+
}
|
378 |
+
}
|
379 |
+
});
|
380 |
+
document.getElementById('message_input')?.addEventListener('keypress', function(e) {
|
381 |
+
if (e.key === 'Enter') {
|
382 |
+
document.getElementById('send_button').click();
|
383 |
+
}
|
384 |
+
});
|
385 |
+
</script>
|
386 |
""", unsafe_allow_html=True)
|
387 |
|
388 |
# Title and intro
|
389 |
st.title(f"{Site_Name}")
|
390 |
+
st.markdown(f"Welcome to {START_ROOM} - chat, vote, paste images, and enjoy IVA’s media magic! 🎉")
|
391 |
|
392 |
# Load or set username
|
393 |
saved_username = load_username()
|
|
|
408 |
st.session_state.quote_index = random.randint(0, max(0, len(quotes) - 1)) if quotes else 0
|
409 |
if 'quote_source' not in st.session_state:
|
410 |
st.session_state.quote_source = "famous"
|
411 |
+
if 'pasted_image' not in st.session_state:
|
412 |
+
st.session_state.pasted_image = None
|
413 |
|
414 |
# Chat section
|
415 |
st.subheader(f"{START_ROOM} Chat 💬")
|
|
|
429 |
st.rerun()
|
430 |
|
431 |
user_list = get_user_list(chat_content)
|
432 |
+
new_username = st.selectbox("Switch Star", user_list + [st.session_state.username], index=len(user_list))
|
433 |
if new_username != st.session_state.username:
|
434 |
save_chat_entry("System 🌟", f"{st.session_state.username} switched to {new_username} in {START_ROOM}!")
|
435 |
st.session_state.username = new_username
|
436 |
st.session_state.timer_start = time.time()
|
437 |
save_username(st.session_state.username)
|
438 |
|
439 |
+
# Message input with search engine and paste handling
|
440 |
+
agent_icon = st.session_state.username.split()[-1] # Extract emoji
|
441 |
+
agent_label = FUN_USERNAMES.get(st.session_state.username, "Chatty Brat")
|
442 |
+
message = st.text_input(f"Message Mate {agent_icon} - {agent_label} 🔍📸", key="message_input", placeholder="Type or paste here...")
|
443 |
+
suggestions = get_message_suggestions(chat_content, message) if message else []
|
444 |
+
if suggestions:
|
445 |
+
suggestion = st.selectbox("Chat Snap", [""] + suggestions, index=0)
|
446 |
+
if suggestion:
|
447 |
+
message = suggestion
|
448 |
+
st.session_state.message_input = suggestion
|
449 |
+
|
450 |
+
col_send, _ = st.columns([1, 5])
|
451 |
+
with col_send:
|
452 |
+
send_button = st.button("Send Bend 🚀", key="send_button")
|
453 |
+
if send_button and message.strip():
|
454 |
+
if message.startswith("PastedImage:"):
|
455 |
+
# Handle pasted image
|
456 |
+
image_data = st.session_state.get('pasted_image')
|
457 |
+
if image_data:
|
458 |
+
filename = save_pasted_image(image_data)
|
459 |
+
if filename:
|
460 |
+
save_chat_entry(st.session_state.username, f"Pasted image: {filename}")
|
461 |
+
st.session_state.pasted_image = None
|
462 |
+
else:
|
463 |
+
save_chat_entry(st.session_state.username, message)
|
464 |
st.session_state.timer_start = time.time()
|
465 |
save_username(st.session_state.username)
|
466 |
st.rerun()
|
467 |
|
468 |
# Quote section
|
469 |
+
st.subheader("Quote Note 📝")
|
470 |
quotes = load_quotes(st.session_state.quote_source)
|
471 |
if quotes:
|
472 |
st.session_state.quote_index = st.session_state.quote_index % len(quotes)
|
|
|
475 |
with col1:
|
476 |
st.markdown(quote)
|
477 |
with col2:
|
478 |
+
if st.button("👍 Vote Float", key="quote_vote"):
|
479 |
user_hash = generate_user_hash()
|
480 |
save_vote(QUOTE_VOTES_FILE, quote, user_hash)
|
481 |
st.session_state.timer_start = time.time()
|
|
|
492 |
else:
|
493 |
st.markdown("No quotes available - check back later! 📭")
|
494 |
|
495 |
+
# IVA Media Gallery - Root Directory
|
496 |
+
st.subheader("IVA Gallery 🎨🎶🎥")
|
497 |
media_files = (
|
498 |
+
glob.glob("./*.png") + glob.glob("./*.jpg") + glob.glob("./*.jpeg") +
|
499 |
+
glob.glob("./*.mp3") + glob.glob("./*.wav") +
|
500 |
+
glob.glob("./*.mp4")
|
501 |
)
|
502 |
if media_files:
|
503 |
+
media_cols = st.slider("Gallery Rally", min_value=1, max_value=5, value=3)
|
504 |
cols = st.columns(media_cols)
|
505 |
for idx, media_file in enumerate(media_files):
|
506 |
with cols[idx % media_cols]:
|
|
|
510 |
st.markdown(get_audio_html(media_file, width="100%"), unsafe_allow_html=True)
|
511 |
elif media_file.endswith('.mp4'):
|
512 |
st.markdown(get_video_html(media_file, width="100%"), unsafe_allow_html=True)
|
513 |
+
if st.button(f"👍 Vote Tote {os.path.basename(media_file)}", key=f"media_vote_{idx}"):
|
514 |
user_hash = generate_user_hash()
|
515 |
save_vote(IMAGE_VOTES_FILE, media_file, user_hash)
|
516 |
st.session_state.timer_start = time.time()
|
517 |
save_username(st.session_state.username)
|
518 |
st.rerun()
|
519 |
else:
|
520 |
+
st.error("No media files (images, audio, video) found in root directory!")
|
521 |
|
522 |
# Refresh rate controls with pulsing timer
|
523 |
+
st.subheader("Refresh Dash ⏳")
|
524 |
+
refresh_rate = st.slider("Refresh Clash", min_value=1, max_value=300, value=st.session_state.refresh_rate, step=1)
|
525 |
if refresh_rate != st.session_state.refresh_rate:
|
526 |
st.session_state.refresh_rate = refresh_rate
|
527 |
st.session_state.timer_start = time.time()
|
|
|
529 |
|
530 |
col1, col2, col3 = st.columns(3)
|
531 |
with col1:
|
532 |
+
if st.button("🐇 Small Call (1s)"):
|
533 |
st.session_state.refresh_rate = 1
|
534 |
st.session_state.timer_start = time.time()
|
535 |
save_username(st.session_state.username)
|
536 |
with col2:
|
537 |
+
if st.button("🐢 Medium Fling (5s)"):
|
538 |
st.session_state.refresh_rate = 5
|
539 |
st.session_state.timer_start = time.time()
|
540 |
save_username(st.session_state.username)
|
541 |
with col3:
|
542 |
+
if st.button("🐘 Large Surge (5m)"):
|
543 |
st.session_state.refresh_rate = 300
|
544 |
st.session_state.timer_start = time.time()
|
545 |
save_username(st.session_state.username)
|
|
|
559 |
st.rerun()
|
560 |
|
561 |
# Sidebar vote stats
|
562 |
+
st.sidebar.subheader("Vote Loads")
|
563 |
chat_votes = load_votes(QUOTE_VOTES_FILE)
|
564 |
image_votes = load_votes(IMAGE_VOTES_FILE)
|
565 |
for item, count in chat_votes.items():
|
|
|
578 |
server_task = asyncio.create_task(run_websocket_server())
|
579 |
|
580 |
query_params = st.query_params if hasattr(st, 'query_params') else {}
|
581 |
+
initial_username = query_params.get("username", random.choice(list(FUN_USERNAMES.keys()))) if query_params else random.choice(list(FUN_USERNAMES.keys()))
|
582 |
print(f"Welcoming {initial_username} to the Sector bash!")
|
583 |
|
584 |
create_streamlit_interface(initial_username)
|