Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,6 @@ import streamlit as st
|
|
2 |
import asyncio
|
3 |
import websockets
|
4 |
import uuid
|
5 |
-
import argparse
|
6 |
from datetime import datetime
|
7 |
import os
|
8 |
import random
|
@@ -10,155 +9,491 @@ import time
|
|
10 |
import hashlib
|
11 |
from PIL import Image
|
12 |
import glob
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
import re
|
14 |
-
from
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
st.set_page_config(
|
23 |
-
page_title=
|
24 |
-
page_icon=
|
25 |
layout="wide",
|
26 |
initial_sidebar_state="auto"
|
27 |
)
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
"
|
35 |
-
"
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
-
# Directories for chat, votes, and media - the secret vaults where treasures are stashed! 🗄️🔒
|
39 |
CHAT_DIR = "chat_logs"
|
40 |
VOTE_DIR = "vote_logs"
|
41 |
-
MEDIA_DIR = "
|
|
|
|
|
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")
|
49 |
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
50 |
IMAGE_VOTES_FILE = os.path.join(VOTE_DIR, "image_votes.md")
|
51 |
HISTORY_FILE = os.path.join(VOTE_DIR, "vote_history.md")
|
52 |
|
53 |
-
#
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
-
|
60 |
-
UNICODE_FONTS = [
|
61 |
-
("Normal", lambda x: x),
|
62 |
-
("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)),
|
63 |
-
("Italic", lambda x: "".join(chr(ord(c) + 0x1D434 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D44E - 0x61) if 'a' <= c <= 'z' else c for c in x)),
|
64 |
-
("Script", lambda x: "".join(chr(ord(c) + 0x1D49C - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D4B6 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
|
65 |
-
("Fraktur", lambda x: "".join(chr(ord(c) + 0x1D504 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D51E - 0x61) if 'a' <= c <= 'z' else c for c in x)),
|
66 |
-
("Double Struck", lambda x: "".join(chr(ord(c) + 0x1D538 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D552 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
|
67 |
-
("Sans Serif", lambda x: "".join(chr(ord(c) + 0x1D5A0 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D5BA - 0x61) if 'a' <= c <= 'z' else c for c in x)),
|
68 |
-
("Sans Bold", lambda x: "".join(chr(ord(c) + 0x1D5D4 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D5EE - 0x61) if 'a' <= c <= 'z' else c for c in x)),
|
69 |
-
("Mono", lambda x: "".join(chr(ord(c) + 0x1D670 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D68A - 0x61) if 'a' <= c <= 'z' else c for c in x)),
|
70 |
-
("Circle", lambda x: "".join(chr(ord(c) + 0x24B6 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x24D0 - 0x61) if 'a' <= c <= 'z' else c for c in x))
|
71 |
-
]
|
72 |
-
|
73 |
-
# Global WebSocket server flag
|
74 |
-
server_running = False
|
75 |
-
server_task = None
|
76 |
-
|
77 |
-
# Node name - the app’s codename generator, sneaky and slick! 🕵️♂️💾
|
78 |
-
def get_node_name():
|
79 |
-
"""🎲 Spins the wheel of fate to name our node - a random alias or user pick! 🏷️"""
|
80 |
-
parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
|
81 |
-
parser.add_argument('--node-name', type=str, default=None, help='Name for this chat node')
|
82 |
-
parser.add_argument('--port', type=int, default=8501, help='Port to run the Streamlit interface on')
|
83 |
-
args = parser.parse_args()
|
84 |
-
return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
|
85 |
-
|
86 |
-
# Chat saver - the scribe etching epic messages into the eternal scroll! 🖋️📜
|
87 |
-
def save_chat_entry(username, message):
|
88 |
-
"""🖌️ Carves a chat line into the grand Markdown tome - history in the making! 🏛️"""
|
89 |
-
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
90 |
-
entry = f"[{timestamp}] {username}: {message}"
|
91 |
try:
|
92 |
-
with open(
|
93 |
-
f.write(
|
94 |
-
return True
|
95 |
except Exception as e:
|
96 |
-
print(f"
|
97 |
-
return False
|
98 |
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
try:
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
|
|
|
|
111 |
except Exception as e:
|
112 |
-
print(f"
|
113 |
-
return
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
return
|
158 |
-
|
159 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
def save_vote(file, item, user_hash):
|
161 |
-
"""✍️ Tallies a vote in the grand ledger - your opinion matters! 🗳️"""
|
162 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
163 |
entry = f"[{timestamp}] {user_hash} voted for {item}"
|
164 |
try:
|
@@ -171,9 +506,7 @@ def save_vote(file, item, user_hash):
|
|
171 |
print(f"Vote save flop: {e}")
|
172 |
return False
|
173 |
|
174 |
-
# Vote loader - the scorekeeper tallying the crowd’s cheers! 🎉🏅
|
175 |
def load_votes(file):
|
176 |
-
"""📈 Counts the votes from the ledger - who’s winning the popularity contest? 🏆"""
|
177 |
if not os.path.exists(file):
|
178 |
with open(file, 'w') as f:
|
179 |
f.write("# Vote Tally\n\nNo votes yet - get clicking! 🖱️\n")
|
@@ -190,290 +523,209 @@ def load_votes(file):
|
|
190 |
print(f"Vote load oopsie: {e}")
|
191 |
return {}
|
192 |
|
193 |
-
# User hash generator - the secret agent giving you a cool code! 🕵️♂️����
|
194 |
def generate_user_hash():
|
195 |
-
"""🕵️ Crafts a snazzy 8-digit ID badge - you’re in the club now! 🎟️"""
|
196 |
if 'user_hash' not in st.session_state:
|
197 |
session_id = str(random.getrandbits(128))
|
198 |
hash_object = hashlib.md5(session_id.encode())
|
199 |
st.session_state['user_hash'] = hash_object.hexdigest()[:8]
|
200 |
return st.session_state['user_hash']
|
201 |
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
Your browser does not support the video tag.
|
229 |
-
</video>
|
230 |
-
'''
|
231 |
-
|
232 |
-
def get_audio_html(audio_path, width="100%"):
|
233 |
-
"""🎶 Drops a beat with audio - your personal DJ in action! 🎧"""
|
234 |
-
audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
|
235 |
-
return f'''
|
236 |
-
<audio controls style="width: {width};">
|
237 |
-
<source src="{audio_url}" type="audio/mpeg">
|
238 |
-
Your browser does not support the audio element.
|
239 |
-
</audio>
|
240 |
-
'''
|
241 |
-
|
242 |
-
active_connections = {}
|
243 |
-
|
244 |
-
# WebSocket handler - the bouncer at the Sector rave, keeping it hopping! 🎉🚪
|
245 |
-
async def websocket_handler(websocket, path):
|
246 |
-
"""🎧 Guards the cosmic gate, welcoming all to Sector and booting crashers! 🚨"""
|
247 |
-
try:
|
248 |
-
client_id = str(uuid.uuid4())
|
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 |
-
# Auto-join message for every connection
|
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:
|
257 |
-
try:
|
258 |
-
parts = message.split('|', 1)
|
259 |
-
if len(parts) == 2:
|
260 |
-
username, content = parts
|
261 |
-
save_chat_entry(username, content)
|
262 |
-
await broadcast_message(f"{username}|{content}", room_id)
|
263 |
-
except Exception as e:
|
264 |
-
print(f"Message mishap: {e}")
|
265 |
-
await websocket.send(f"ERROR|Oops, bad message format! 😬")
|
266 |
-
except websockets.ConnectionClosed:
|
267 |
-
print(f"Client {client_id} bailed from Sector!")
|
268 |
-
save_chat_entry("System 🌟", f"{username} has left {START_ROOM}!")
|
269 |
-
finally:
|
270 |
-
if room_id in active_connections and client_id in active_connections[room_id]:
|
271 |
-
del active_connections[room_id][client_id]
|
272 |
-
if not active_connections[room_id]:
|
273 |
-
del active_connections[room_id]
|
274 |
-
|
275 |
-
# Broadcaster - the megaphone blasting Sector vibes to all! 📣🎶
|
276 |
-
async def broadcast_message(message, room_id):
|
277 |
-
"""📢 Shouts the latest Sector beat to every cosmic dancer - hear it loud! 🎵"""
|
278 |
-
if room_id in active_connections:
|
279 |
-
disconnected = []
|
280 |
-
for client_id, ws in active_connections[room_id].items():
|
281 |
-
try:
|
282 |
-
await ws.send(message)
|
283 |
-
except websockets.ConnectionClosed:
|
284 |
-
disconnected.append(client_id)
|
285 |
-
for client_id in disconnected:
|
286 |
-
del active_connections[room_id][client_id]
|
287 |
-
|
288 |
-
# WebSocket server runner - the DJ spinning up the Sector tunes once! 🎧🔥
|
289 |
-
async def run_websocket_server():
|
290 |
-
"""🌐 Cranks up the WebSocket jukebox once, keeping Sector rocking! 🎸"""
|
291 |
-
global server_running, server_task
|
292 |
-
if not server_running:
|
293 |
-
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
|
294 |
-
print(f"WebSocket server jamming on ws://0.0.0.0:8765")
|
295 |
-
server_running = True
|
296 |
-
await server.wait_closed()
|
297 |
-
|
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 for a sleek chat box and timer
|
302 |
-
st.markdown("""
|
303 |
-
<style>
|
304 |
-
.chat-box {
|
305 |
-
font-family: monospace;
|
306 |
-
background: #1e1e1e;
|
307 |
-
color: #d4d4d4;
|
308 |
-
padding: 10px;
|
309 |
-
border-radius: 5px;
|
310 |
-
height: 300px;
|
311 |
-
overflow-y: auto;
|
312 |
-
}
|
313 |
-
.timer {
|
314 |
-
font-size: 24px;
|
315 |
-
color: #ffcc00;
|
316 |
-
text-align: center;
|
317 |
-
animation: pulse 1s infinite;
|
318 |
-
}
|
319 |
-
@keyframes pulse {
|
320 |
-
0% { transform: scale(1); }
|
321 |
-
50% { transform: scale(1.1); }
|
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()
|
333 |
if saved_username and saved_username in FUN_USERNAMES:
|
334 |
-
|
335 |
-
if
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
364 |
st.session_state.timer_start = time.time()
|
365 |
save_username(st.session_state.username)
|
366 |
st.rerun()
|
367 |
|
368 |
-
|
369 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
370 |
if new_username != st.session_state.username:
|
371 |
-
save_chat_entry("System 🌟", f"{st.session_state.username}
|
372 |
-
st.session_state.username = new_username
|
373 |
-
st.session_state.timer_start = time.time()
|
374 |
-
save_username(st.session_state.username)
|
375 |
-
|
376 |
-
message = st.text_input("Message", placeholder="Type your epic line here! ✍️")
|
377 |
-
if st.button("Send 🚀") and message.strip():
|
378 |
-
save_chat_entry(st.session_state.username, message)
|
379 |
st.session_state.timer_start = time.time()
|
380 |
save_username(st.session_state.username)
|
381 |
st.rerun()
|
382 |
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
if quotes:
|
387 |
-
st.session_state.quote_index = st.session_state.quote_index % len(quotes)
|
388 |
-
quote = quotes[st.session_state.quote_index]
|
389 |
-
col1, col2 = st.columns([5, 1])
|
390 |
-
with col1:
|
391 |
-
st.markdown(quote)
|
392 |
-
with col2:
|
393 |
-
if st.button("👍 Upvote", key="quote_vote"):
|
394 |
-
user_hash = generate_user_hash()
|
395 |
-
save_vote(QUOTE_VOTES_FILE, quote, user_hash)
|
396 |
-
st.session_state.timer_start = time.time()
|
397 |
-
save_username(st.session_state.username)
|
398 |
-
st.rerun()
|
399 |
-
if time.time() - st.session_state.timer_start > 10: # 10s quote refresh
|
400 |
-
st.session_state.quote_index = (st.session_state.quote_index + 1) % len(quotes)
|
401 |
-
st.session_state.quote_source = "custom" if st.session_state.quote_source == "famous" else "famous"
|
402 |
-
quotes = load_quotes(st.session_state.quote_source)
|
403 |
-
st.session_state.quote_index = st.session_state.quote_index % len(quotes) if quotes else 0
|
404 |
-
st.session_state.timer_start = time.time()
|
405 |
-
save_username(st.session_state.username)
|
406 |
-
st.rerun()
|
407 |
-
else:
|
408 |
-
st.markdown("No quotes available - check back later! 📭")
|
409 |
-
|
410 |
-
# IVA Media Gallery
|
411 |
-
st.subheader("IVA Media Gallery 🎨🎶🎥")
|
412 |
-
media_files = (
|
413 |
-
glob.glob(f"{MEDIA_DIR}/*.png") + glob.glob(f"{MEDIA_DIR}/*.jpg") + glob.glob(f"{MEDIA_DIR}/*.jpeg") +
|
414 |
-
glob.glob(f"{MEDIA_DIR}/*.mp3") + glob.glob(f"{MEDIA_DIR}/*.wav") +
|
415 |
-
glob.glob(f"{MEDIA_DIR}/*.mp4")
|
416 |
-
)
|
417 |
-
if media_files:
|
418 |
-
media_cols = st.slider("Gallery Columns", min_value=1, max_value=5, value=3)
|
419 |
-
cols = st.columns(media_cols)
|
420 |
-
for idx, media_file in enumerate(media_files):
|
421 |
-
with cols[idx % media_cols]:
|
422 |
-
if media_file.endswith(('.png', '.jpg', '.jpeg')):
|
423 |
-
st.image(media_file, use_container_width=True)
|
424 |
-
elif media_file.endswith(('.mp3', '.wav')):
|
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"👍 Upvote {os.path.basename(media_file)}", key=f"media_vote_{idx}"):
|
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 'media' directory!")
|
436 |
-
|
437 |
-
# Refresh rate controls with pulsing timer
|
438 |
-
st.subheader("Set Refresh Rate ⏳")
|
439 |
-
refresh_rate = st.slider("Refresh Rate (seconds)", min_value=1, max_value=300, value=st.session_state.refresh_rate, step=1)
|
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()
|
443 |
-
save_username(st.session_state.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)
|
461 |
-
|
462 |
-
# Pulsing countdown timer with emoji digits and random Unicode font
|
463 |
-
timer_placeholder = st.empty()
|
464 |
-
start_time = st.session_state.timer_start
|
465 |
-
for i in range(st.session_state.refresh_rate, -1, -1):
|
466 |
-
font_name, font_func = random.choice(UNICODE_FONTS)
|
467 |
-
countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
|
468 |
-
timer_emoji = "⏳" if i % 2 == 0 else "💓" # Pulse effect
|
469 |
-
timer_placeholder.markdown(f"<p class='timer'>{timer_emoji} {font_func('Next refresh in:')} {countdown_str} {font_func('seconds')}</p>", unsafe_allow_html=True)
|
470 |
-
time.sleep(1) # Pulse every second
|
471 |
-
st.session_state.timer_start = time.time()
|
472 |
-
st.session_state.last_refresh = time.time()
|
473 |
-
save_username(st.session_state.username)
|
474 |
-
st.rerun()
|
475 |
|
476 |
-
# Sidebar vote stats
|
477 |
st.sidebar.subheader("Vote Totals")
|
478 |
chat_votes = load_votes(QUOTE_VOTES_FILE)
|
479 |
image_votes = load_votes(IMAGE_VOTES_FILE)
|
@@ -482,21 +734,18 @@ def create_streamlit_interface(initial_username):
|
|
482 |
for image, count in image_votes.items():
|
483 |
st.sidebar.write(f"{image}: {count} votes")
|
484 |
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
if server_task is None:
|
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 |
-
|
|
|
|
|
|
|
500 |
|
501 |
if __name__ == "__main__":
|
502 |
-
|
|
|
2 |
import asyncio
|
3 |
import websockets
|
4 |
import uuid
|
|
|
5 |
from datetime import datetime
|
6 |
import os
|
7 |
import random
|
|
|
9 |
import hashlib
|
10 |
from PIL import Image
|
11 |
import glob
|
12 |
+
import base64
|
13 |
+
import io
|
14 |
+
import streamlit.components.v1 as components
|
15 |
+
import edge_tts
|
16 |
+
from audio_recorder_streamlit import audio_recorder
|
17 |
+
import nest_asyncio
|
18 |
import re
|
19 |
+
from streamlit_paste_button import paste_image_button
|
20 |
+
import pytz
|
21 |
+
import shutil
|
22 |
+
import anthropic
|
23 |
+
import openai
|
24 |
+
from PyPDF2 import PdfReader
|
25 |
+
import threading
|
26 |
+
import json
|
27 |
+
import zipfile
|
28 |
+
from gradio_client import Client
|
29 |
+
from dotenv import load_dotenv
|
30 |
+
from streamlit_marquee import streamlit_marquee
|
31 |
+
from collections import defaultdict, Counter
|
32 |
+
import pandas as pd
|
33 |
+
|
34 |
+
# 🛠️ Patch asyncio for nesting
|
35 |
+
nest_asyncio.apply()
|
36 |
+
|
37 |
+
# 🎨 Page Config
|
38 |
st.set_page_config(
|
39 |
+
page_title="🚲TalkingAIResearcher🏆",
|
40 |
+
page_icon="🚲🏆",
|
41 |
layout="wide",
|
42 |
initial_sidebar_state="auto"
|
43 |
)
|
44 |
|
45 |
+
# 🌟 Static Config
|
46 |
+
icons = '🤖🧠🔬📝'
|
47 |
+
Site_Name = '🤖🧠Chat & Quote Node📝🔬'
|
48 |
+
START_ROOM = "Sector 🌌"
|
49 |
+
FUN_USERNAMES = {
|
50 |
+
"CosmicJester 🌌": "en-US-AriaNeural",
|
51 |
+
"PixelPanda 🐼": "en-US-JennyNeural",
|
52 |
+
"QuantumQuack 🦆": "en-GB-SoniaNeural",
|
53 |
+
"StellarSquirrel 🐿️": "en-AU-NatashaNeural",
|
54 |
+
"GizmoGuru ⚙️": "en-CA-ClaraNeural",
|
55 |
+
"NebulaNinja 🌠": "en-US-GuyNeural",
|
56 |
+
"ByteBuster 💾": "en-GB-RyanNeural",
|
57 |
+
"GalacticGopher 🌍": "en-AU-WilliamNeural",
|
58 |
+
"RocketRaccoon 🚀": "en-CA-LiamNeural",
|
59 |
+
"EchoElf 🧝": "en-US-AnaNeural",
|
60 |
+
"PhantomFox 🦊": "en-US-BrandonNeural",
|
61 |
+
"WittyWizard 🧙": "en-GB-ThomasNeural",
|
62 |
+
"LunarLlama 🌙": "en-AU-FreyaNeural",
|
63 |
+
"SolarSloth ☀️": "en-CA-LindaNeural",
|
64 |
+
"AstroAlpaca 🦙": "en-US-ChristopherNeural",
|
65 |
+
"CyberCoyote 🐺": "en-GB-ElliotNeural",
|
66 |
+
"MysticMoose 🦌": "en-AU-JamesNeural",
|
67 |
+
"GlitchGnome 🧚": "en-CA-EthanNeural",
|
68 |
+
"VortexViper 🐍": "en-US-AmberNeural",
|
69 |
+
"ChronoChimp 🐒": "en-GB-LibbyNeural"
|
70 |
+
}
|
71 |
+
EDGE_TTS_VOICES = list(set(FUN_USERNAMES.values()))
|
72 |
+
FILE_EMOJIS = {"md": "📝", "mp3": "🎵", "png": "🖼️", "mp4": "🎥"}
|
73 |
+
|
74 |
+
# 📁 Directories (Media at Root)
|
75 |
+
for d in ["chat_logs", "vote_logs", "audio_logs", "history_logs", "audio_cache"]:
|
76 |
+
os.makedirs(d, exist_ok=True)
|
77 |
|
|
|
78 |
CHAT_DIR = "chat_logs"
|
79 |
VOTE_DIR = "vote_logs"
|
80 |
+
MEDIA_DIR = "."
|
81 |
+
AUDIO_CACHE_DIR = "audio_cache"
|
82 |
+
AUDIO_DIR = "audio_logs"
|
83 |
STATE_FILE = "user_state.txt"
|
|
|
|
|
|
|
84 |
|
|
|
85 |
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
86 |
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
87 |
IMAGE_VOTES_FILE = os.path.join(VOTE_DIR, "image_votes.md")
|
88 |
HISTORY_FILE = os.path.join(VOTE_DIR, "vote_history.md")
|
89 |
|
90 |
+
# 🔑 API Keys
|
91 |
+
load_dotenv()
|
92 |
+
anthropic_key = os.getenv('ANTHROPIC_API_KEY', st.secrets.get('ANTHROPIC_API_KEY', ""))
|
93 |
+
openai_api_key = os.getenv('OPENAI_API_KEY', st.secrets.get('OPENAI_API_KEY', ""))
|
94 |
+
openai_client = openai.OpenAI(api_key=openai_api_key)
|
95 |
+
|
96 |
+
# 🕒 Timestamp Helper
|
97 |
+
def format_timestamp_prefix(username=""):
|
98 |
+
central = pytz.timezone('US/Central')
|
99 |
+
now = datetime.now(central)
|
100 |
+
return f"{now.strftime('%Y%m%d_%H%M%S')}-by-{username}"
|
101 |
+
|
102 |
+
# 📈 Performance Timer
|
103 |
+
class PerformanceTimer:
|
104 |
+
def __init__(self, name):
|
105 |
+
self.name, self.start = name, None
|
106 |
+
def __enter__(self):
|
107 |
+
self.start = time.time()
|
108 |
+
return self
|
109 |
+
def __exit__(self, *args):
|
110 |
+
duration = time.time() - self.start
|
111 |
+
st.session_state['operation_timings'][self.name] = duration
|
112 |
+
st.session_state['performance_metrics'][self.name].append(duration)
|
113 |
+
|
114 |
+
# 🎛️ Session State Init
|
115 |
+
def init_session_state():
|
116 |
+
defaults = {
|
117 |
+
'server_running': False, 'server_task': None, 'active_connections': {},
|
118 |
+
'media_notifications': [], 'last_chat_update': 0, 'displayed_chat_lines': [],
|
119 |
+
'message_text': "", 'audio_cache': {}, 'pasted_image_data': None,
|
120 |
+
'quote_line': None, 'refresh_rate': 5, 'base64_cache': {},
|
121 |
+
'transcript_history': [], 'last_transcript': "", 'image_hashes': set(),
|
122 |
+
'tts_voice': "en-US-AriaNeural", 'chat_history': [], 'marquee_settings': {
|
123 |
+
"background": "#1E1E1E", "color": "#FFFFFF", "font-size": "14px",
|
124 |
+
"animationDuration": "20s", "width": "100%", "lineHeight": "35px"
|
125 |
+
}, 'operation_timings': {}, 'performance_metrics': defaultdict(list),
|
126 |
+
'enable_audio': True, 'download_link_cache': {}, 'username': None,
|
127 |
+
'autosend': True, 'autosearch': True, 'last_message': "", 'last_query': "",
|
128 |
+
'mp3_files': {}, 'timer_start': time.time(), 'quote_index': 0,
|
129 |
+
'quote_source': "famous", 'last_sent_transcript': "", 'old_val': None
|
130 |
+
}
|
131 |
+
for k, v in defaults.items():
|
132 |
+
if k not in st.session_state:
|
133 |
+
st.session_state[k] = v
|
134 |
+
|
135 |
+
# 🖌️ Marquee Helpers
|
136 |
+
def update_marquee_settings_ui():
|
137 |
+
st.sidebar.markdown("### 🎯 Marquee Settings")
|
138 |
+
cols = st.sidebar.columns(2)
|
139 |
+
with cols[0]:
|
140 |
+
st.session_state['marquee_settings']['background'] = st.color_picker("🎨 Background", "#1E1E1E")
|
141 |
+
st.session_state['marquee_settings']['color'] = st.color_picker("✍️ Text", "#FFFFFF")
|
142 |
+
with cols[1]:
|
143 |
+
st.session_state['marquee_settings']['font-size'] = f"{st.slider('📏 Size', 10, 24, 14)}px"
|
144 |
+
st.session_state['marquee_settings']['animationDuration'] = f"{st.slider('⏱️ Speed', 1, 20, 20)}s"
|
145 |
+
|
146 |
+
def display_marquee(text, settings, key_suffix=""):
|
147 |
+
truncated = text[:280] + "..." if len(text) > 280 else text
|
148 |
+
streamlit_marquee(content=truncated, **settings, key=f"marquee_{key_suffix}")
|
149 |
+
st.write("")
|
150 |
+
|
151 |
+
# 📝 Text & File Helpers
|
152 |
+
def clean_text_for_tts(text):
|
153 |
+
return re.sub(r'[#*!\[\]]+', '', ' '.join(text.split()))[:200] or "No text"
|
154 |
+
|
155 |
+
def clean_text_for_filename(text):
|
156 |
+
return '_'.join(re.sub(r'[^\w\s-]', '', text.lower()).split())[:200]
|
157 |
+
|
158 |
+
def get_high_info_terms(text, top_n=10):
|
159 |
+
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with'}
|
160 |
+
words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
|
161 |
+
bi_grams = [' '.join(pair) for pair in zip(words, words[1:])]
|
162 |
+
filtered = [t for t in words + bi_grams if t not in stop_words and len(t.split()) <= 2]
|
163 |
+
return [t for t, _ in Counter(filtered).most_common(top_n)]
|
164 |
+
|
165 |
+
def generate_filename(prompt, username, file_type="md"):
|
166 |
+
timestamp = format_timestamp_prefix(username)
|
167 |
+
hash_val = hashlib.md5(prompt.encode()).hexdigest()[:8]
|
168 |
+
return f"{timestamp}-{hash_val}.{file_type}"
|
169 |
+
|
170 |
+
def create_file(prompt, username, file_type="md"):
|
171 |
+
filename = generate_filename(prompt, username, file_type)
|
172 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
173 |
+
f.write(prompt)
|
174 |
+
return filename
|
175 |
+
|
176 |
+
def get_download_link(file, file_type="mp3"):
|
177 |
+
cache_key = f"dl_{file}"
|
178 |
+
if cache_key not in st.session_state['download_link_cache']:
|
179 |
+
with open(file, "rb") as f:
|
180 |
+
b64 = base64.b64encode(f.read()).decode()
|
181 |
+
mime_types = {"mp3": "audio/mpeg", "png": "image/png", "mp4": "video/mp4", "md": "text/markdown"}
|
182 |
+
st.session_state['download_link_cache'][cache_key] = f'<a href="data:{mime_types.get(file_type, "application/octet-stream")};base64,{b64}" download="{os.path.basename(file)}">{FILE_EMOJIS.get(file_type, "Download")} Download {os.path.basename(file)}</a>'
|
183 |
+
return st.session_state['download_link_cache'][cache_key]
|
184 |
|
185 |
+
def save_username(username):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
try:
|
187 |
+
with open(STATE_FILE, 'w') as f:
|
188 |
+
f.write(username)
|
|
|
189 |
except Exception as e:
|
190 |
+
print(f"Failed to save username: {e}")
|
|
|
191 |
|
192 |
+
def load_username():
|
193 |
+
if os.path.exists(STATE_FILE):
|
194 |
+
try:
|
195 |
+
with open(STATE_FILE, 'r') as f:
|
196 |
+
return f.read().strip()
|
197 |
+
except Exception as e:
|
198 |
+
print(f"Failed to load username: {e}")
|
199 |
+
return None
|
200 |
+
|
201 |
+
def concatenate_markdown_files():
|
202 |
+
md_files = sorted(glob.glob("*.md"), key=os.path.getmtime, reverse=True)
|
203 |
+
all_md_content = ""
|
204 |
+
for md_file in md_files:
|
205 |
+
with open(md_file, 'r', encoding='utf-8') as f:
|
206 |
+
all_md_content += f.read() + "\n\n---\n\n"
|
207 |
+
return all_md_content.strip()
|
208 |
+
|
209 |
+
# 🎶 Audio Processing
|
210 |
+
async def async_edge_tts_generate(text, voice, username, rate=0, pitch=0, file_format="mp3"):
|
211 |
+
cache_key = f"{text[:100]}_{voice}_{rate}_{pitch}_{file_format}"
|
212 |
+
if cache_key in st.session_state['audio_cache']:
|
213 |
+
return st.session_state['audio_cache'][cache_key], 0
|
214 |
+
start_time = time.time()
|
215 |
+
text = clean_text_for_tts(text)
|
216 |
+
if not text or text == "No text":
|
217 |
+
print(f"Skipping audio generation for empty/invalid text: '{text}'")
|
218 |
+
return None, 0
|
219 |
+
filename = f"{format_timestamp_prefix(username)}-{hashlib.md5(text.encode()).hexdigest()[:8]}.{file_format}"
|
220 |
try:
|
221 |
+
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
222 |
+
await communicate.save(filename)
|
223 |
+
st.session_state['audio_cache'][cache_key] = filename
|
224 |
+
return filename, time.time() - start_time
|
225 |
+
except edge_tts.exceptions.NoAudioReceived as e:
|
226 |
+
print(f"No audio received for text: '{text}' with voice: {voice}. Error: {e}")
|
227 |
+
return None, 0
|
228 |
except Exception as e:
|
229 |
+
print(f"Error generating audio for text: '{text}' with voice: {voice}. Error: {e}")
|
230 |
+
return None, 0
|
231 |
+
|
232 |
+
def play_and_download_audio(file_path):
|
233 |
+
if file_path and os.path.exists(file_path):
|
234 |
+
st.audio(file_path)
|
235 |
+
st.markdown(get_download_link(file_path), unsafe_allow_html=True)
|
236 |
+
|
237 |
+
def load_mp3_viewer():
|
238 |
+
mp3_files = sorted(glob.glob(f"*.mp3"), key=os.path.getmtime, reverse=True)
|
239 |
+
for mp3 in mp3_files:
|
240 |
+
filename = os.path.basename(mp3)
|
241 |
+
if filename not in st.session_state['mp3_files']:
|
242 |
+
st.session_state['mp3_files'][filename] = mp3
|
243 |
+
|
244 |
+
async def save_chat_entry(username, message, voice, is_markdown=False):
|
245 |
+
if not message.strip() or message == st.session_state.last_transcript:
|
246 |
+
return None, None
|
247 |
+
central = pytz.timezone('US/Central')
|
248 |
+
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
|
249 |
+
entry = f"[{timestamp}] {username} ({voice}): {message}" if not is_markdown else f"[{timestamp}] {username} ({voice}):\n```markdown\n{message}\n```"
|
250 |
+
md_file = create_file(entry, username, "md")
|
251 |
+
with open(CHAT_FILE, 'a') as f:
|
252 |
+
f.write(f"{entry}\n")
|
253 |
+
audio_file, _ = await async_edge_tts_generate(message, voice, username)
|
254 |
+
if audio_file:
|
255 |
+
with open(HISTORY_FILE, 'a') as f:
|
256 |
+
f.write(f"[{timestamp}] {username}: Audio - {audio_file}\n")
|
257 |
+
st.session_state['mp3_files'][os.path.basename(audio_file)] = audio_file
|
258 |
+
await broadcast_message(f"{username}|{message}", "chat")
|
259 |
+
st.session_state.last_chat_update = time.time()
|
260 |
+
st.session_state.chat_history.append(entry)
|
261 |
+
st.session_state.last_transcript = message # Update last processed transcript
|
262 |
+
return md_file, audio_file
|
263 |
+
|
264 |
+
async def load_chat():
|
265 |
+
if not os.path.exists(CHAT_FILE):
|
266 |
+
with open(CHAT_FILE, 'a') as f:
|
267 |
+
f.write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub! 🎤\n")
|
268 |
+
with open(CHAT_FILE, 'r') as f:
|
269 |
+
content = f.read().strip()
|
270 |
+
lines = content.split('\n')
|
271 |
+
# Remove duplicates and empty lines
|
272 |
+
unique_lines = list(dict.fromkeys(line for line in lines if line.strip()))
|
273 |
+
numbered_content = "\n".join(f"{i+1}. {line}" for i, line in enumerate(unique_lines))
|
274 |
+
return numbered_content
|
275 |
+
|
276 |
+
# Claude Search Function
|
277 |
+
async def perform_claude_search(query, username):
|
278 |
+
if not query.strip() or query == st.session_state.last_transcript:
|
279 |
+
return None, None
|
280 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
281 |
+
response = client.messages.create(
|
282 |
+
model="claude-3-sonnet-20240229",
|
283 |
+
max_tokens=1000,
|
284 |
+
messages=[{"role": "user", "content": query}]
|
285 |
+
)
|
286 |
+
result = response.content[0].text
|
287 |
+
st.markdown(f"### Claude's Reply 🧠\n{result}")
|
288 |
+
|
289 |
+
# Save to chat history with audio
|
290 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
291 |
+
md_file, audio_file = await save_chat_entry(username, f"Claude Search: {query}\nResponse: {result}", voice, True)
|
292 |
+
return md_file, audio_file
|
293 |
+
|
294 |
+
# ArXiv Search Function
|
295 |
+
async def perform_arxiv_search(query, username):
|
296 |
+
if not query.strip() or query == st.session_state.last_transcript:
|
297 |
+
return None, None
|
298 |
+
# Step 1: Claude Search
|
299 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
300 |
+
claude_response = client.messages.create(
|
301 |
+
model="claude-3-sonnet-20240229",
|
302 |
+
max_tokens=1000,
|
303 |
+
messages=[{"role": "user", "content": query}]
|
304 |
+
)
|
305 |
+
claude_result = claude_response.content[0].text
|
306 |
+
st.markdown(f"### Claude's Reply 🧠\n{claude_result}")
|
307 |
+
|
308 |
+
# Step 2: Feed Claude result into ArXiv
|
309 |
+
enhanced_query = f"{query}\n\n{claude_result}"
|
310 |
+
gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
311 |
+
refs = gradio_client.predict(
|
312 |
+
enhanced_query, 10, "Semantic Search", "mistralai/Mixtral-8x7B-Instruct-v0.1", api_name="/update_with_rag_md"
|
313 |
+
)[0]
|
314 |
+
result = f"🔎 {enhanced_query}\n\n{refs}"
|
315 |
+
st.markdown(f"### ArXiv Results 🔍\n{result}")
|
316 |
+
|
317 |
+
# Save to chat history with audio
|
318 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
319 |
+
md_file, audio_file = await save_chat_entry(username, f"ArXiv Search: {query}\nClaude Response: {claude_result}\nArXiv Results: {refs}", voice, True)
|
320 |
+
return md_file, audio_file
|
321 |
+
|
322 |
+
async def perform_ai_lookup(q, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False, useArxiv=True, useArxivAudio=False):
|
323 |
+
start = time.time()
|
324 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
325 |
+
response = client.messages.create(
|
326 |
+
model="claude-3-sonnet-20240229",
|
327 |
+
max_tokens=1000,
|
328 |
+
messages=[{"role": "user", "content": q}]
|
329 |
+
)
|
330 |
+
st.write("Claude's reply 🧠:")
|
331 |
+
st.markdown(response.content[0].text)
|
332 |
+
|
333 |
+
result = response.content[0].text
|
334 |
+
md_file = create_file(result, "System", "md")
|
335 |
+
audio_file, _ = await async_edge_tts_generate(result, st.session_state['tts_voice'], "System")
|
336 |
+
st.subheader("📝 Main Response Audio")
|
337 |
+
play_and_download_audio(audio_file)
|
338 |
+
|
339 |
+
if useArxiv:
|
340 |
+
q = q + result
|
341 |
+
st.write('Running Arxiv RAG with Claude inputs.')
|
342 |
+
gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
343 |
+
refs = gradio_client.predict(
|
344 |
+
q, 10, "Semantic Search", "mistralai/Mixtral-8x7B-Instruct-v0.1", api_name="/update_with_rag_md"
|
345 |
+
)[0]
|
346 |
+
result = f"🔎 {q}\n\n{refs}"
|
347 |
+
md_file = create_file(result, "System", "md")
|
348 |
+
audio_file, _ = await async_edge_tts_generate(result, st.session_state['tts_voice'], "System")
|
349 |
+
st.subheader("📝 ArXiv Response Audio")
|
350 |
+
play_and_download_audio(audio_file)
|
351 |
+
|
352 |
+
papers = parse_arxiv_refs(refs)
|
353 |
+
if papers and useArxivAudio:
|
354 |
+
await create_paper_audio_files(papers, q)
|
355 |
+
return result, papers
|
356 |
+
elapsed = time.time() - start
|
357 |
+
st.write(f"**Total Elapsed:** {elapsed:.2f} s")
|
358 |
+
return result, []
|
359 |
+
|
360 |
+
# 🌐 WebSocket Handling
|
361 |
+
async def websocket_handler(websocket, path):
|
362 |
+
client_id = str(uuid.uuid4())
|
363 |
+
room_id = "chat"
|
364 |
+
if room_id not in st.session_state.active_connections:
|
365 |
+
st.session_state.active_connections[room_id] = {}
|
366 |
+
st.session_state.active_connections[room_id][client_id] = websocket
|
367 |
+
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
|
368 |
+
chat_content = await load_chat()
|
369 |
+
if not any(f"Client-{client_id}" in line for line in chat_content.split('\n')):
|
370 |
+
await save_chat_entry("System 🌟", f"{username} has joined {START_ROOM}!", "en-US-AriaNeural")
|
371 |
+
try:
|
372 |
+
async for message in websocket:
|
373 |
+
if '|' in message:
|
374 |
+
username, content = message.split('|', 1)
|
375 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
376 |
+
await save_chat_entry(username, content, voice)
|
377 |
+
else:
|
378 |
+
await websocket.send("ERROR|Message format: username|content")
|
379 |
+
except websockets.ConnectionClosed:
|
380 |
+
await save_chat_entry("System 🌟", f"{username} has left {START_ROOM}!", "en-US-AriaNeural")
|
381 |
+
finally:
|
382 |
+
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
|
383 |
+
del st.session_state.active_connections[room_id][client_id]
|
384 |
+
|
385 |
+
async def broadcast_message(message, room_id):
|
386 |
+
if room_id in st.session_state.active_connections:
|
387 |
+
disconnected = []
|
388 |
+
for client_id, ws in st.session_state.active_connections[room_id].items():
|
389 |
+
try:
|
390 |
+
await ws.send(message)
|
391 |
+
except websockets.ConnectionClosed:
|
392 |
+
disconnected.append(client_id)
|
393 |
+
for client_id in disconnected:
|
394 |
+
if client_id in st.session_state.active_connections[room_id]:
|
395 |
+
del st.session_state.active_connections[room_id][client_id]
|
396 |
+
|
397 |
+
async def run_websocket_server():
|
398 |
+
if not st.session_state.server_running:
|
399 |
+
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
|
400 |
+
st.session_state.server_running = True
|
401 |
+
await server.wait_closed()
|
402 |
+
|
403 |
+
def start_websocket_server():
|
404 |
+
asyncio.run(run_websocket_server())
|
405 |
+
|
406 |
+
# 📚 PDF to Audio
|
407 |
+
class AudioProcessor:
|
408 |
+
def __init__(self):
|
409 |
+
self.cache_dir = AUDIO_CACHE_DIR
|
410 |
+
os.makedirs(self.cache_dir, exist_ok=True)
|
411 |
+
self.metadata = json.load(open(f"{self.cache_dir}/metadata.json")) if os.path.exists(f"{self.cache_dir}/metadata.json") else {}
|
412 |
+
|
413 |
+
def _save_metadata(self):
|
414 |
+
with open(f"{self.cache_dir}/metadata.json", 'w') as f:
|
415 |
+
json.dump(self.metadata, f)
|
416 |
+
|
417 |
+
async def create_audio(self, text, voice='en-US-AriaNeural'):
|
418 |
+
cache_key = hashlib.md5(f"{text}:{voice}".encode()).hexdigest()
|
419 |
+
cache_path = f"{self.cache_dir}/{cache_key}.mp3"
|
420 |
+
if cache_key in self.metadata and os.path.exists(cache_path):
|
421 |
+
return cache_path
|
422 |
+
text = clean_text_for_tts(text)
|
423 |
+
if not text:
|
424 |
+
return None
|
425 |
+
communicate = edge_tts.Communicate(text, voice)
|
426 |
+
await communicate.save(cache_path)
|
427 |
+
self.metadata[cache_key] = {'timestamp': datetime.now().isoformat(), 'text_length': len(text), 'voice': voice}
|
428 |
+
self._save_metadata()
|
429 |
+
return cache_path
|
430 |
+
|
431 |
+
def process_pdf(pdf_file, max_pages, voice, audio_processor):
|
432 |
+
reader = PdfReader(pdf_file)
|
433 |
+
total_pages = min(len(reader.pages), max_pages)
|
434 |
+
texts, audios = [], {}
|
435 |
+
async def process_page(i, text):
|
436 |
+
audio_path = await audio_processor.create_audio(text, voice)
|
437 |
+
if audio_path:
|
438 |
+
audios[i] = audio_path
|
439 |
+
for i in range(total_pages):
|
440 |
+
text = reader.pages[i].extract_text()
|
441 |
+
texts.append(text)
|
442 |
+
threading.Thread(target=lambda: asyncio.run(process_page(i, text))).start()
|
443 |
+
return texts, audios, total_pages
|
444 |
+
|
445 |
+
# 🔍 ArXiv & AI Lookup
|
446 |
+
def parse_arxiv_refs(ref_text):
|
447 |
+
if not ref_text:
|
448 |
+
return []
|
449 |
+
papers = []
|
450 |
+
current = {}
|
451 |
+
for line in ref_text.split('\n'):
|
452 |
+
if line.count('|') == 2:
|
453 |
+
if current:
|
454 |
+
papers.append(current)
|
455 |
+
date, title, *_ = line.strip('* ').split('|')
|
456 |
+
url = re.search(r'(https://arxiv.org/\S+)', line).group(1) if re.search(r'(https://arxiv.org/\S+)', line) else f"paper_{len(papers)}"
|
457 |
+
current = {'date': date, 'title': title, 'url': url, 'authors': '', 'summary': '', 'full_audio': None, 'download_base64': ''}
|
458 |
+
elif current:
|
459 |
+
if not current['authors']:
|
460 |
+
current['authors'] = line.strip('* ')
|
461 |
+
else:
|
462 |
+
current['summary'] += ' ' + line.strip() if current['summary'] else line.strip()
|
463 |
+
if current:
|
464 |
+
papers.append(current)
|
465 |
+
return papers[:20]
|
466 |
+
|
467 |
+
def generate_5min_feature_markdown(paper):
|
468 |
+
title, summary, authors, date, url = paper['title'], paper['summary'], paper['authors'], paper['date'], paper['url']
|
469 |
+
pdf_url = url.replace("abs", "pdf") + (".pdf" if not url.endswith(".pdf") else "")
|
470 |
+
wct, sw = len(title.split()), len(summary.split())
|
471 |
+
terms = get_high_info_terms(summary, 15)
|
472 |
+
rouge = round((len(terms) / max(sw, 1)) * 100, 2)
|
473 |
+
mermaid = "```mermaid\nflowchart TD\n" + "\n".join(f' T{i+1}["{t}"] --> T{i+2}["{terms[i+1]}"]' for i in range(len(terms)-1)) + "\n```"
|
474 |
+
return f"""
|
475 |
+
## 📄 {title}
|
476 |
+
**Authors:** {authors} | **Date:** {date} | **Words:** Title: {wct}, Summary: {sw}
|
477 |
+
**Links:** [Abstract]({url}) | [PDF]({pdf_url})
|
478 |
+
**Terms:** {', '.join(terms)} | **ROUGE:** {rouge}%
|
479 |
+
### 🎤 TTF Read Aloud
|
480 |
+
- **Title:** {title} | **Terms:** {', '.join(terms)} | **ROUGE:** {rouge}%
|
481 |
+
#### Concepts Graph
|
482 |
+
{mermaid}
|
483 |
+
---
|
484 |
+
"""
|
485 |
+
|
486 |
+
def create_detailed_paper_md(papers):
|
487 |
+
return "# Detailed Summary\n" + "\n".join(generate_5min_feature_markdown(p) for p in papers)
|
488 |
+
|
489 |
+
async def create_paper_audio_files(papers, query):
|
490 |
+
for p in papers:
|
491 |
+
audio_text = clean_text_for_tts(f"{p['title']} by {p['authors']}. {p['summary']}")
|
492 |
+
p['full_audio'], _ = await async_edge_tts_generate(audio_text, st.session_state['tts_voice'], p['authors'])
|
493 |
+
if p['full_audio']:
|
494 |
+
p['download_base64'] = get_download_link(p['full_audio'])
|
495 |
+
|
496 |
def save_vote(file, item, user_hash):
|
|
|
497 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
498 |
entry = f"[{timestamp}] {user_hash} voted for {item}"
|
499 |
try:
|
|
|
506 |
print(f"Vote save flop: {e}")
|
507 |
return False
|
508 |
|
|
|
509 |
def load_votes(file):
|
|
|
510 |
if not os.path.exists(file):
|
511 |
with open(file, 'w') as f:
|
512 |
f.write("# Vote Tally\n\nNo votes yet - get clicking! 🖱️\n")
|
|
|
523 |
print(f"Vote load oopsie: {e}")
|
524 |
return {}
|
525 |
|
|
|
526 |
def generate_user_hash():
|
|
|
527 |
if 'user_hash' not in st.session_state:
|
528 |
session_id = str(random.getrandbits(128))
|
529 |
hash_object = hashlib.md5(session_id.encode())
|
530 |
st.session_state['user_hash'] = hash_object.hexdigest()[:8]
|
531 |
return st.session_state['user_hash']
|
532 |
|
533 |
+
async def save_pasted_image(image, username):
|
534 |
+
img_hash = hashlib.md5(image.tobytes()).hexdigest()[:8]
|
535 |
+
if img_hash in st.session_state.image_hashes:
|
536 |
+
return None
|
537 |
+
timestamp = format_timestamp_prefix(username)
|
538 |
+
filename = f"{timestamp}-{img_hash}.png"
|
539 |
+
filepath = filename
|
540 |
+
image.save(filepath, "PNG")
|
541 |
+
st.session_state.image_hashes.add(img_hash)
|
542 |
+
return filepath
|
543 |
+
|
544 |
+
# 📦 Zip Files
|
545 |
+
def create_zip_of_files(md_files, mp3_files, png_files, mp4_files, query):
|
546 |
+
all_files = md_files + mp3_files + png_files + mp4_files
|
547 |
+
if not all_files:
|
548 |
+
return None
|
549 |
+
terms = get_high_info_terms(" ".join([open(f, 'r', encoding='utf-8').read() if f.endswith('.md') else os.path.splitext(os.path.basename(f))[0].replace('_', ' ') for f in all_files] + [query]), 5)
|
550 |
+
zip_name = f"{format_timestamp_prefix()}_{'-'.join(terms)[:20]}.zip"
|
551 |
+
with zipfile.ZipFile(zip_name, 'w') as z:
|
552 |
+
[z.write(f) for f in all_files]
|
553 |
+
return zip_name
|
554 |
+
|
555 |
+
# 🎮 Main Interface
|
556 |
+
def main():
|
557 |
+
init_session_state()
|
558 |
+
load_mp3_viewer()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
559 |
saved_username = load_username()
|
560 |
if saved_username and saved_username in FUN_USERNAMES:
|
561 |
+
st.session_state.username = saved_username
|
562 |
+
if not st.session_state.username:
|
563 |
+
available = [n for n in FUN_USERNAMES if not any(f"{n} has joined" in l for l in asyncio.run(load_chat()).split('\n'))]
|
564 |
+
st.session_state.username = random.choice(available or list(FUN_USERNAMES.keys()))
|
565 |
+
st.session_state.tts_voice = FUN_USERNAMES[st.session_state.username]
|
566 |
+
asyncio.run(save_chat_entry("System 🌟", f"{st.session_state.username} has joined {START_ROOM}!", "en-US-AriaNeural"))
|
567 |
+
save_username(st.session_state.username)
|
568 |
+
|
569 |
+
st.title(f"{Site_Name} for {st.session_state.username}")
|
570 |
+
update_marquee_settings_ui()
|
571 |
+
display_marquee(f"🚀 Welcome to {START_ROOM} | 🤖 {st.session_state.username}", st.session_state['marquee_settings'], "welcome")
|
572 |
+
|
573 |
+
# Speech Component at Top Level
|
574 |
+
mycomponent = components.declare_component("mycomponent", path="mycomponent")
|
575 |
+
val = mycomponent(my_input_value="")
|
576 |
+
if val and val != st.session_state.last_transcript:
|
577 |
+
val_stripped = val.strip().replace('\n', ' ')
|
578 |
+
if val_stripped:
|
579 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
580 |
+
md_file, audio_file = asyncio.run(save_chat_entry(st.session_state.username, val_stripped, voice))
|
581 |
+
if audio_file:
|
582 |
+
play_and_download_audio(audio_file)
|
583 |
+
st.rerun()
|
584 |
+
|
585 |
+
tab_main = st.radio("Action:", ["🎤 Chat & Voice", "🔍 ArXiv", "📚 PDF to Audio"], horizontal=True, key="tab_main")
|
586 |
+
useArxiv = st.checkbox("Search ArXiv", True, key="use_arxiv")
|
587 |
+
useArxivAudio = st.checkbox("ArXiv Audio", False, key="use_arxiv_audio")
|
588 |
+
st.checkbox("Autosend Chat", value=True, key="autosend")
|
589 |
+
st.checkbox("Autosearch ArXiv", value=True, key="autosearch")
|
590 |
+
|
591 |
+
# 🎤 Chat & Voice
|
592 |
+
if tab_main == "🎤 Chat & Voice":
|
593 |
+
st.subheader(f"{START_ROOM} Chat 💬")
|
594 |
+
chat_content = asyncio.run(load_chat())
|
595 |
+
chat_container = st.container()
|
596 |
+
with chat_container:
|
597 |
+
st.markdown(chat_content)
|
598 |
+
|
599 |
+
message = st.text_input(f"Message as {st.session_state.username}", key="message_input")
|
600 |
+
paste_result = paste_image_button("📋 Paste Image or Text", key="paste_button_msg")
|
601 |
+
if paste_result.image_data is not None:
|
602 |
+
if isinstance(paste_result.image_data, str):
|
603 |
+
st.session_state.message_text = paste_result.image_data
|
604 |
+
message = st.text_input(f"Message as {st.session_state.username}", key="message_input_paste", value=st.session_state.message_text)
|
605 |
+
else:
|
606 |
+
st.image(paste_result.image_data, caption="Pasted Image")
|
607 |
+
filename = asyncio.run(save_pasted_image(paste_result.image_data, st.session_state.username))
|
608 |
+
if filename:
|
609 |
+
st.session_state.pasted_image_data = filename
|
610 |
+
|
611 |
+
if (message and message != st.session_state.last_message) or st.session_state.pasted_image_data:
|
612 |
+
st.session_state.last_message = message
|
613 |
+
col_send, col_claude, col_arxiv = st.columns([1, 1, 1])
|
614 |
+
|
615 |
+
with col_send:
|
616 |
+
if st.session_state.autosend or st.button("Send 🚀", key="send_button"):
|
617 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
618 |
+
if message.strip():
|
619 |
+
md_file, audio_file = asyncio.run(save_chat_entry(st.session_state.username, message, voice, True))
|
620 |
+
if audio_file:
|
621 |
+
play_and_download_audio(audio_file)
|
622 |
+
if st.session_state.pasted_image_data:
|
623 |
+
asyncio.run(save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}", voice))
|
624 |
+
st.session_state.pasted_image_data = None
|
625 |
st.session_state.timer_start = time.time()
|
626 |
save_username(st.session_state.username)
|
627 |
st.rerun()
|
628 |
|
629 |
+
with col_claude:
|
630 |
+
if st.button("🧠 Claude", key="claude_button"):
|
631 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
632 |
+
if message.strip():
|
633 |
+
md_file, audio_file = asyncio.run(perform_claude_search(message, st.session_state.username))
|
634 |
+
if audio_file:
|
635 |
+
play_and_download_audio(audio_file)
|
636 |
+
st.session_state.timer_start = time.time()
|
637 |
+
save_username(st.session_state.username)
|
638 |
+
st.rerun()
|
639 |
+
|
640 |
+
with col_arxiv:
|
641 |
+
if st.button("🔍 ArXiv", key="arxiv_button"):
|
642 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
643 |
+
if message.strip():
|
644 |
+
md_file, audio_file = asyncio.run(perform_arxiv_search(message, st.session_state.username))
|
645 |
+
if audio_file:
|
646 |
+
play_and_download_audio(audio_file)
|
647 |
+
st.session_state.timer_start = time.time()
|
648 |
+
save_username(st.session_state.username)
|
649 |
+
st.rerun()
|
650 |
+
|
651 |
+
# 🔍 ArXiv
|
652 |
+
elif tab_main == "🔍 ArXiv":
|
653 |
+
st.subheader("🔍 Query ArXiv")
|
654 |
+
q = st.text_input("🔍 Query:", key="arxiv_query")
|
655 |
+
if q and q != st.session_state.last_query:
|
656 |
+
st.session_state.last_query = q
|
657 |
+
if st.session_state.autosearch or st.button("🔍 Run", key="arxiv_run"):
|
658 |
+
result, papers = asyncio.run(perform_ai_lookup(q, useArxiv=useArxiv, useArxivAudio=useArxivAudio))
|
659 |
+
for i, p in enumerate(papers, 1):
|
660 |
+
with st.expander(f"{i}. 📄 {p['title']}"):
|
661 |
+
st.markdown(f"**{p['date']} | {p['title']}** — [Link]({p['url']})")
|
662 |
+
st.markdown(generate_5min_feature_markdown(p))
|
663 |
+
if p.get('full_audio'):
|
664 |
+
play_and_download_audio(p['full_audio'])
|
665 |
+
|
666 |
+
# 📚 PDF to Audio
|
667 |
+
elif tab_main == "📚 PDF to Audio":
|
668 |
+
audio_processor = AudioProcessor()
|
669 |
+
pdf_file = st.file_uploader("Choose PDF", "pdf", key="pdf_upload")
|
670 |
+
max_pages = st.slider('Pages', 1, 100, 10, key="pdf_pages")
|
671 |
+
if pdf_file:
|
672 |
+
with st.spinner('Processing...'):
|
673 |
+
texts, audios, total = process_pdf(pdf_file, max_pages, st.session_state['tts_voice'], audio_processor)
|
674 |
+
for i, text in enumerate(texts):
|
675 |
+
with st.expander(f"Page {i+1}"):
|
676 |
+
st.markdown(text)
|
677 |
+
while i not in audios:
|
678 |
+
time.sleep(0.1)
|
679 |
+
if audios.get(i):
|
680 |
+
st.audio(audios[i])
|
681 |
+
st.markdown(get_download_link(audios[i], "mp3"), unsafe_allow_html=True)
|
682 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
683 |
+
asyncio.run(save_chat_entry(st.session_state.username, f"PDF Page {i+1} converted to audio: {audios[i]}", voice))
|
684 |
+
|
685 |
+
# Always Visible Media Gallery
|
686 |
+
st.header("📸 Media Gallery")
|
687 |
+
all_files = sorted(glob.glob("*.md") + glob.glob("*.mp3") + glob.glob("*.png") + glob.glob("*.mp4"), key=os.path.getmtime, reverse=True)
|
688 |
+
md_files = [f for f in all_files if f.endswith('.md')]
|
689 |
+
mp3_files = [f for f in all_files if f.endswith('.mp3')]
|
690 |
+
png_files = [f for f in all_files if f.endswith('.png')]
|
691 |
+
mp4_files = [f for f in all_files if f.endswith('.mp4')]
|
692 |
+
|
693 |
+
st.subheader("All Submitted Text")
|
694 |
+
all_md_content = concatenate_markdown_files()
|
695 |
+
st.markdown(all_md_content)
|
696 |
+
|
697 |
+
st.subheader("🎵 Audio (MP3)")
|
698 |
+
for mp3 in mp3_files:
|
699 |
+
with st.expander(os.path.basename(mp3)):
|
700 |
+
st.audio(mp3)
|
701 |
+
st.markdown(get_download_link(mp3, "mp3"), unsafe_allow_html=True)
|
702 |
+
|
703 |
+
st.subheader("🖼️ Images (PNG)")
|
704 |
+
for png in png_files:
|
705 |
+
with st.expander(os.path.basename(png)):
|
706 |
+
st.image(png, use_container_width=True)
|
707 |
+
st.markdown(get_download_link(png, "png"), unsafe_allow_html=True)
|
708 |
+
|
709 |
+
st.subheader("🎥 Videos (MP4)")
|
710 |
+
for mp4 in mp4_files:
|
711 |
+
with st.expander(os.path.basename(mp4)):
|
712 |
+
st.video(mp4)
|
713 |
+
st.markdown(get_download_link(mp4, "mp4"), unsafe_allow_html=True)
|
714 |
+
|
715 |
+
# 🗂️ Sidebar with Dialog and Audio
|
716 |
+
st.sidebar.subheader("Voice Settings")
|
717 |
+
new_username = st.sidebar.selectbox("Change Name/Voice", list(FUN_USERNAMES.keys()), index=list(FUN_USERNAMES.keys()).index(st.session_state.username), key="username_select")
|
718 |
if new_username != st.session_state.username:
|
719 |
+
asyncio.run(save_chat_entry("System 🌟", f"{st.session_state.username} changed to {new_username}", "en-US-AriaNeural"))
|
720 |
+
st.session_state.username, st.session_state.tts_voice = new_username, FUN_USERNAMES[new_username]
|
|
|
|
|
|
|
|
|
|
|
|
|
721 |
st.session_state.timer_start = time.time()
|
722 |
save_username(st.session_state.username)
|
723 |
st.rerun()
|
724 |
|
725 |
+
st.sidebar.markdown("### 💬 Chat Dialog & Media")
|
726 |
+
chat_content = asyncio.run(load_chat())
|
727 |
+
st.sidebar.markdown(chat_content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
728 |
|
|
|
729 |
st.sidebar.subheader("Vote Totals")
|
730 |
chat_votes = load_votes(QUOTE_VOTES_FILE)
|
731 |
image_votes = load_votes(IMAGE_VOTES_FILE)
|
|
|
734 |
for image, count in image_votes.items():
|
735 |
st.sidebar.write(f"{image}: {count} votes")
|
736 |
|
737 |
+
st.sidebar.markdown("### 📂 File History")
|
738 |
+
for f in all_files[:10]:
|
739 |
+
st.sidebar.write(f"{FILE_EMOJIS.get(f.split('.')[-1], '📄')} {os.path.basename(f)}")
|
740 |
+
if st.sidebar.button("⬇️ Zip All", key="zip_all"):
|
741 |
+
zip_name = create_zip_of_files(md_files, mp3_files, png_files, mp4_files, "latest_query")
|
742 |
+
if zip_name:
|
743 |
+
st.sidebar.markdown(get_download_link(zip_name, "zip"), unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
744 |
|
745 |
+
# Start WebSocket server in a separate thread
|
746 |
+
if not st.session_state.server_running and not st.session_state.server_task:
|
747 |
+
st.session_state.server_task = threading.Thread(target=start_websocket_server, daemon=True)
|
748 |
+
st.session_state.server_task.start()
|
749 |
|
750 |
if __name__ == "__main__":
|
751 |
+
main()
|