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