Update app.py
Browse files
app.py
CHANGED
@@ -10,27 +10,24 @@ import time
|
|
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
|
27 |
nest_asyncio.apply()
|
28 |
|
29 |
-
# Static config - constants rule
|
30 |
icons = '🤖🧠🔬📝'
|
31 |
START_ROOM = "Sector 🌌"
|
32 |
|
33 |
-
# Page setup - dressing up
|
34 |
st.set_page_config(
|
35 |
page_title="🤖🧠MMO Chat Brain📝🔬",
|
36 |
page_icon=icons,
|
@@ -38,7 +35,7 @@ st.set_page_config(
|
|
38 |
initial_sidebar_state="auto"
|
39 |
)
|
40 |
|
41 |
-
# Funky usernames
|
42 |
FUN_USERNAMES = {
|
43 |
"CosmicJester 🌌": "en-US-AriaNeural",
|
44 |
"PixelPanda 🐼": "en-US-JennyNeural",
|
@@ -62,21 +59,28 @@ FUN_USERNAMES = {
|
|
62 |
"ChronoChimp 🐒": "en-GB-LibbyNeural"
|
63 |
}
|
64 |
|
65 |
-
#
|
66 |
-
|
67 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
77 |
UNICODE_DIGITS = {i: f"{i}\uFE0F⃣" for i in range(10)}
|
78 |
|
79 |
-
# Massive font collection - typography
|
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,7 +103,7 @@ UNICODE_FONTS = [
|
|
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
|
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,6 +116,10 @@ if 'last_chat_update' 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,35 +129,16 @@ if 'pasted_image_data' 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
|
137 |
def format_timestamp_prefix(username):
|
138 |
-
|
139 |
-
now
|
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! 🛡️🔍
|
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
|
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,7 +148,7 @@ def get_node_name():
|
|
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
|
163 |
def log_action(username, action):
|
164 |
if 'action_log' not in st.session_state:
|
165 |
st.session_state.action_log = {}
|
@@ -168,211 +157,33 @@ def log_action(username, action):
|
|
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(
|
174 |
user_log[action] = current_time
|
175 |
|
176 |
-
# Clean text - strip the fancy
|
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"
|
181 |
-
|
182 |
-
#
|
183 |
-
|
184 |
-
|
185 |
-
""
|
186 |
-
|
187 |
-
|
188 |
-
""
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
def update_chat(self, entry):
|
196 |
-
"""Add a chat entry, a rhyme in the stream, keeping our saga supreme, in shared dream! 💬🎶"""
|
197 |
-
self.chat_history.append(entry)
|
198 |
-
if len(self.chat_history) > 100: # Limit to keep it tight, a knight’s fight!
|
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 shared gleam! 🖼️🌟"""
|
203 |
-
self.media_files.append(media_path)
|
204 |
-
if len(self.media_files) > 50: # Cap the hoard, lest it grow too wide!
|
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 shared act! 🗣️✨"""
|
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 shared urge! 🌀🔥"""
|
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! 🎶🌟
|
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 shared shores! 🎤🌌
|
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 shared deep!
|
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 shared keep!
|
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 shared need!
|
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! 💬🔒
|
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 shared air! ✨🎉
|
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!
|
281 |
-
|
282 |
-
# Prepare entry, a verse so bright, in shared memory’s sight, a shared delight!
|
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 shared gale!
|
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!
|
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 shared rip!
|
302 |
-
audio_filename = None # Initialize, lest our tale derail, in shared veil!
|
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 shared zest!
|
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 shared core!
|
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 shared flight!
|
352 |
|
353 |
-
#
|
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 shared light! ✨📖
|
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! 📜🚀
|
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 shared sea! 🌟💬
|
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,11 +192,8 @@ async def load_chat():
|
|
381 |
content = await asyncio.to_thread(f.read)
|
382 |
return content
|
383 |
|
384 |
-
# User lister - who’s in the 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 shared chime! 🌍🎭
|
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,35 +203,24 @@ async def get_user_list(chat_content):
|
|
395 |
users.add(user)
|
396 |
return sorted(list(users))
|
397 |
|
398 |
-
# Join checker - been here before
|
399 |
async def has_joined_before(client_id, chat_content):
|
400 |
-
"""
|
401 |
-
Check joins, a shared memory chore, in cache secure, forevermore, in shared lore! 🌀🔐
|
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
|
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 shared zest! 😂🌟
|
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
|
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 shared spear! 🏆🎉
|
423 |
-
"""
|
424 |
await asyncio.to_thread(log_action, username, "👍📊 - Vote saver - cheers recorded!")
|
425 |
-
|
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,14 +228,9 @@ async def save_vote(file, item, user_hash, username, comment=""):
|
|
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 shared ring!
|
435 |
|
436 |
-
# Vote counter - tallying the 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 shared fight! 🌟📊
|
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,139 +250,69 @@ async def load_votes(file):
|
|
458 |
user_votes.add(vote_key)
|
459 |
return votes
|
460 |
|
461 |
-
# Hash generator - secret codes ahoy
|
462 |
async def generate_user_hash():
|
463 |
-
"""
|
464 |
-
Generate hashes, a shared code’s chime, in cache sublime, through space and time, in shared rhyme! 🌌🔐
|
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
|
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 shared hill! 🎤🔊
|
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 =
|
|
|
481 |
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
482 |
try:
|
483 |
-
await communicate.save(
|
484 |
-
return
|
485 |
except edge_tts.exceptions.NoAudioReceived:
|
486 |
with open(HISTORY_FILE, 'a') as f:
|
487 |
-
|
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
|
492 |
def play_and_download_audio(file_path):
|
493 |
-
"""
|
494 |
-
Play tunes, a shared melody’s jest, in cache expressed, our audio quest, in shared zest! 🎵🌌
|
495 |
-
"""
|
496 |
if file_path and os.path.exists(file_path):
|
497 |
st.audio(file_path)
|
498 |
-
|
499 |
-
|
|
|
|
|
|
|
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
|
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 shared spear! 🖼️🌟
|
507 |
-
"""
|
508 |
await asyncio.to_thread(log_action, username, "📸💾 - Image saver - pics preserved!")
|
509 |
timestamp = format_timestamp_prefix(username)
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
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! 🎥🎶
|
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 shared 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! 📜🎶
|
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 shared sea! 📚🌟
|
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 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
# Video renderer - movies roll, in shared cache, a visual toll, in shared 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 shared hill! 📺🌌
|
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! 🎶✈️
|
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 shared spear! 🎵🌟
|
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,
|
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
|
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 shared night! 🌍🔌
|
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,11 +334,8 @@ async def websocket_handler(websocket, path):
|
|
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
|
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 shared spear! 🌠📡
|
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,11 +348,8 @@ async def broadcast_message(message, room_id):
|
|
629 |
for client_id in disconnected:
|
630 |
del st.session_state.active_connections[room_id][client_id]
|
631 |
|
632 |
-
# Server starter - web spins up
|
633 |
async def run_websocket_server():
|
634 |
-
"""
|
635 |
-
Start server, a shared spin’s delight, in cache so right, our web takes flight, in shared night! 🚀🌐
|
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,384 +357,212 @@ async def run_websocket_server():
|
|
641 |
st.session_state.server_running = True
|
642 |
await server.wait_closed()
|
643 |
|
644 |
-
#
|
645 |
-
def
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
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 shared surge!
|
680 |
-
return deleted_files
|
681 |
-
|
682 |
-
# Query parameter checker - parse q with flair, in shared cache, a naming affair, in shared air! 🚪🔍
|
683 |
-
def check_query_params():
|
684 |
-
"""
|
685 |
-
Check queries, a shared name’s quest, in cache so blessed, our path expressed, in shared zest! 🌟🔍
|
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! 🌳📈
|
698 |
-
def generate_mermaid_graph(chat_lines):
|
699 |
-
"""
|
700 |
-
Generate graphs, a shared vision’s rhyme, in cache sublime, our story’s chime, in shared time! 🧩🌌
|
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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
732 |
def main():
|
733 |
-
"""
|
734 |
-
Launch our saga, a shared memory’s cheer, in Streamlit’s cache, our epic year, in shared spear! 🚀✨
|
735 |
-
"""
|
736 |
NODE_NAME, port = get_node_name()
|
737 |
|
738 |
-
|
739 |
-
asyncio.
|
740 |
-
|
741 |
-
# Async interface - our epic quest, in shared cache, a tale expressed, in shared zest! 🎭🌟
|
742 |
-
async def async_interface():
|
743 |
-
# Generate user ID and hash, a shared identity’s clash, in shared flash! 🆔🔮
|
744 |
-
if not st.session_state.user_id:
|
745 |
-
st.session_state.user_id = str(uuid.uuid4())
|
746 |
-
st.session_state.user_hash = await generate_user_hash()
|
747 |
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
-
|
753 |
-
st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
|
754 |
-
st.session_state.voice = FUN_USERNAMES[st.session_state.username]
|
755 |
-
st.markdown(f"**🎙️ Voice Selected**: {st.session_state.voice} 🗣️ for {st.session_state.username}")
|
756 |
-
|
757 |
-
# Check existing history, a shared memory’s cheer, in cache so clear, our lore near, in shared spear! 📜🌟
|
758 |
-
user_history_file = f"{st.session_state.username}_history.md"
|
759 |
-
if os.path.exists(user_history_file):
|
760 |
-
with open(user_history_file, 'r') as f:
|
761 |
-
st.session_state.displayed_chat_lines = f.read().split('\n')
|
762 |
|
763 |
-
|
764 |
-
|
765 |
-
st.markdown(f"<small>Your unique URL path: [{user_url}]({user_url})</small>", unsafe_allow_html=True)
|
766 |
|
767 |
-
|
768 |
-
|
769 |
-
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)
|
770 |
|
771 |
-
|
772 |
-
|
|
|
|
|
773 |
|
774 |
-
|
775 |
-
|
776 |
-
st.markdown(f"##### {START_ROOM} Chat History 💬")
|
777 |
-
shared_memory = get_shared_memory()
|
778 |
chat_content = await load_chat()
|
779 |
-
chat_lines =
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
|
787 |
-
|
788 |
-
|
789 |
-
|
790 |
-
|
791 |
-
|
792 |
-
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
-
|
797 |
-
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
-
|
806 |
-
|
807 |
-
|
808 |
-
|
809 |
-
|
810 |
-
|
811 |
-
|
812 |
-
|
813 |
-
|
814 |
-
|
815 |
-
|
816 |
-
|
817 |
-
|
818 |
-
|
819 |
-
|
820 |
-
|
821 |
-
|
822 |
-
|
823 |
-
|
824 |
-
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
830 |
-
|
831 |
-
|
832 |
-
|
833 |
-
|
834 |
-
components.html(mermaid_html, height=250)
|
835 |
|
836 |
-
with st.container():
|
837 |
if st.session_state.quote_line:
|
838 |
-
st.markdown(f"
|
839 |
-
quote_response = st.text_area("Add your response", key="quote_response"
|
840 |
-
paste_result_quote = paste_image_button("📋 Paste Image
|
841 |
if paste_result_quote.image_data is not None:
|
842 |
-
|
843 |
-
|
844 |
-
|
845 |
-
|
846 |
-
st.image(paste_result_quote.image_data, caption="Received Image for Quote")
|
847 |
-
filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
|
848 |
-
if filename:
|
849 |
-
st.session_state.pasted_image_data = filename
|
850 |
-
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)
|
851 |
if st.button("Send Quote 🚀", key="send_quote"):
|
852 |
markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
|
853 |
if st.session_state.pasted_image_data:
|
854 |
markdown_response += f"\n- **Image**: "
|
855 |
-
await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}"
|
856 |
st.session_state.pasted_image_data = None
|
857 |
-
await save_chat_entry(st.session_state.username, markdown_response
|
858 |
st.session_state.quote_line = None
|
859 |
st.session_state.message_text = ''
|
860 |
st.rerun()
|
861 |
|
862 |
-
|
863 |
-
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")
|
864 |
if new_username and new_username != st.session_state.username:
|
865 |
await save_chat_entry("System 🌟", f"{st.session_state.username} changed name to {new_username}")
|
866 |
st.session_state.username = new_username
|
867 |
-
st.session_state.voice = FUN_USERNAMES[new_username]
|
868 |
-
st.markdown(f"**🎙️ Voice Changed**: {st.session_state.voice} 🗣️ for {st.session_state.username}")
|
869 |
st.rerun()
|
870 |
|
871 |
-
|
872 |
-
|
873 |
-
with col_input:
|
874 |
-
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)
|
875 |
-
with col_send:
|
876 |
-
if st.button("Send 🚀", key="send_button"):
|
877 |
-
if message.strip() or st.session_state.pasted_image_data:
|
878 |
-
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())
|
879 |
-
if st.session_state.pasted_image_data:
|
880 |
-
st.session_state.pasted_image_data = None
|
881 |
-
st.session_state.message_text = ''
|
882 |
-
st.rerun()
|
883 |
-
|
884 |
-
paste_result_msg = paste_image_button("📋 Paste Image or Text with Message", key="paste_button_msg")
|
885 |
if paste_result_msg.image_data is not None:
|
886 |
-
|
887 |
-
|
888 |
-
|
889 |
-
|
890 |
-
|
891 |
-
|
892 |
-
|
893 |
-
|
894 |
-
|
895 |
-
|
|
|
|
|
896 |
|
897 |
-
|
898 |
-
st.
|
899 |
-
|
|
|
|
|
|
|
|
|
|
|
900 |
if uploaded_file:
|
901 |
timestamp = format_timestamp_prefix(st.session_state.username)
|
902 |
username = st.session_state.username
|
903 |
-
ext = uploaded_file.name.split('.')[-1]
|
904 |
-
|
905 |
-
|
906 |
-
|
907 |
-
filename = await save_media(uploaded_file, username, ext)
|
908 |
-
elif ext == 'pdf':
|
909 |
-
pdf_filename, _, _ = await save_pdf_and_generate_audio(uploaded_file, username)
|
910 |
-
filename = pdf_filename
|
911 |
-
else:
|
912 |
-
filename = f"{username}-{timestamp.split('-')[-1]}.{ext}"
|
913 |
-
media_path = os.path.join(MEDIA_DIR, filename)
|
914 |
-
await asyncio.to_thread(lambda: open(media_path, 'wb').write(uploaded_file.getbuffer()))
|
915 |
-
await save_chat_entry(username, f"Uploaded {ext.upper()}: {os.path.basename(filename)}", media_file=uploaded_file, skip_audio=True)
|
916 |
-
shared_memory = get_shared_memory()
|
917 |
-
shared_memory.update_media(os.path.join(MEDIA_DIR, filename)) # Cache media
|
918 |
st.success(f"Uploaded {filename}")
|
919 |
-
|
920 |
-
|
921 |
-
|
922 |
-
|
923 |
-
|
924 |
-
|
925 |
-
|
926 |
-
|
927 |
-
|
928 |
-
|
929 |
-
|
930 |
-
|
931 |
-
|
932 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
933 |
refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
|
934 |
st.session_state.refresh_rate = refresh_rate
|
935 |
timer_placeholder = st.empty()
|
936 |
for i in range(st.session_state.refresh_rate, -1, -1):
|
937 |
font_name, font_func = random.choice(UNICODE_FONTS)
|
938 |
countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
|
939 |
-
timer_placeholder.markdown(f"<
|
940 |
-
|
941 |
st.rerun()
|
942 |
|
943 |
-
|
944 |
-
|
945 |
-
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"))
|
946 |
-
shared_memory = get_shared_memory()
|
947 |
-
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)]
|
948 |
-
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, "*")]]
|
949 |
-
|
950 |
-
st.markdown("###### Your Files 📂")
|
951 |
-
st.markdown("###### Image Gallery 🖼")
|
952 |
-
own_image_files = [f for f in own_files if f.endswith(('.png', '.jpg'))]
|
953 |
-
image_cols = st.slider("Image Gallery Columns 🖼 (Own)", min_value=1, max_value=15, value=5)
|
954 |
-
cols = st.columns(image_cols)
|
955 |
-
for idx, image_file in enumerate(own_image_files):
|
956 |
-
with cols[idx % image_cols]:
|
957 |
-
st.image(image_file, use_container_width=True)
|
958 |
-
shared_memory.update_media(image_file) # Cache media, in shared sea!
|
959 |
-
|
960 |
-
st.markdown("###### Video Gallery 🎥")
|
961 |
-
own_video_files = [f for f in own_files if f.endswith('.mp4')]
|
962 |
-
video_cols = st.slider("Video Gallery Columns 🎬 (Own)", min_value=1, max_value=5, value=3)
|
963 |
-
cols = st.columns(video_cols)
|
964 |
-
for idx, video_file in enumerate(own_video_files):
|
965 |
-
with cols[idx % video_cols]:
|
966 |
-
st.markdown(get_video_html(video_file), unsafe_allow_html=True)
|
967 |
-
shared_memory.update_media(video_file) # Cache media, in shared lea!
|
968 |
-
|
969 |
-
st.markdown("###### Audio Gallery 🎧")
|
970 |
-
own_audio_files = [f for f in own_files if f.endswith(('.mp3', '.wav')) or f.startswith(os.path.join(AUDIO_DIR, "audio_"))]
|
971 |
-
audio_cols = st.slider("Audio Gallery Columns 🎶 (Own)", min_value=1, max_value=15, value=5)
|
972 |
-
cols = st.columns(audio_cols)
|
973 |
-
for idx, audio_file in enumerate(own_audio_files):
|
974 |
-
with cols[idx % audio_cols]:
|
975 |
-
st.markdown(await get_audio_html(audio_file), unsafe_allow_html=True)
|
976 |
-
shared_memory.update_media(audio_file) # Cache media, in shared tea!
|
977 |
-
|
978 |
-
st.markdown("###### Shared Files 📤")
|
979 |
-
st.markdown("###### Image Gallery 🖼")
|
980 |
-
shared_image_files = [f for f in shared_files if f.endswith(('.png', '.jpg'))]
|
981 |
-
image_cols = st.slider("Image Gallery Columns 🖼 (Shared)", min_value=1, max_value=15, value=5)
|
982 |
-
cols = st.columns(image_cols)
|
983 |
-
for idx, image_file in enumerate(shared_image_files):
|
984 |
-
with cols[idx % image_cols]:
|
985 |
-
st.image(image_file, use_container_width=True)
|
986 |
-
shared_memory.update_media(image_file) # Cache media, in shared bee!
|
987 |
-
|
988 |
-
st.markdown("###### Video Gallery 🎥")
|
989 |
-
shared_video_files = [f for f in shared_files if f.endswith('.mp4')]
|
990 |
-
video_cols = st.slider("Video Gallery Columns 🎬 (Shared)", min_value=1, max_value=5, value=3)
|
991 |
-
cols = st.columns(video_cols)
|
992 |
-
for idx, video_file in enumerate(shared_video_files):
|
993 |
-
with cols[idx % video_cols]:
|
994 |
-
st.markdown(get_video_html(video_file), unsafe_allow_html=True)
|
995 |
-
shared_memory.update_media(video_file) # Cache media, in shared tree!
|
996 |
-
|
997 |
-
st.markdown("###### Audio Gallery 🎧")
|
998 |
-
shared_audio_files = [f for f in shared_files if f.endswith(('.mp3', '.wav')) or f.startswith(os.path.join(AUDIO_DIR, "audio_"))]
|
999 |
-
audio_cols = st.slider("Audio Gallery Columns 🎶 (Shared)", min_value=1, max_value=15, value=5)
|
1000 |
-
cols = st.columns(audio_cols)
|
1001 |
-
for idx, audio_file in enumerate(shared_audio_files):
|
1002 |
-
with cols[idx % audio_cols]:
|
1003 |
-
st.markdown(await get_audio_html(audio_file), unsafe_allow_html=True)
|
1004 |
-
shared_memory.update_media(audio_file) # Cache media, in shared glee!
|
1005 |
-
|
1006 |
-
# Full Log at End with Download - a shared epic’s end, our tale to mend, in shared bend! 📜📥
|
1007 |
-
with st.container():
|
1008 |
-
st.markdown("###### Full Chat Log 📜")
|
1009 |
-
with open(CHAT_FILE, 'r') as f:
|
1010 |
history_content = f.read()
|
1011 |
-
st.markdown(history_content)
|
1012 |
-
st.download_button("Download Chat Log as .md", history_content, file_name=f"chat_{st.session_state.user_id}.md", mime="text/markdown")
|
1013 |
|
1014 |
-
|
1015 |
-
if st.button("Clear Shared Memory Cache", key="clear_cache"):
|
1016 |
-
shared_memory = get_shared_memory()
|
1017 |
-
shared_memory.clear()
|
1018 |
-
st.success("Shared memory cache cleared, a fresh start with a bard’s heart, in shared art! 🌟🎶")
|
1019 |
|
1020 |
if __name__ == "__main__":
|
1021 |
-
"""
|
1022 |
-
Launch our saga, a shared memory’s cheer, in Streamlit’s cache, our epic year, in shared spear! 🚀✨
|
1023 |
-
"""
|
1024 |
main()
|
|
|
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 # Added back the re import for regular expressions
|
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 the window! 🖼️🎀
|
31 |
st.set_page_config(
|
32 |
page_title="🤖🧠MMO Chat Brain📝🔬",
|
33 |
page_icon=icons,
|
|
|
35 |
initial_sidebar_state="auto"
|
36 |
)
|
37 |
|
38 |
+
# Funky usernames - who’s who in the zoo with unique voices! 🎭🐾🎙️
|
39 |
FUN_USERNAMES = {
|
40 |
"CosmicJester 🌌": "en-US-AriaNeural",
|
41 |
"PixelPanda 🐼": "en-US-JennyNeural",
|
|
|
59 |
"ChronoChimp 🐒": "en-GB-LibbyNeural"
|
60 |
}
|
61 |
|
62 |
+
# Folders galore - organizing chaos! 📂🌀
|
63 |
+
CHAT_DIR = "chat_logs"
|
64 |
+
VOTE_DIR = "vote_logs"
|
|
|
|
|
65 |
STATE_FILE = "user_state.txt"
|
66 |
AUDIO_DIR = "audio_logs"
|
67 |
+
HISTORY_DIR = "history_logs"
|
68 |
MEDIA_DIR = "media_files"
|
69 |
+
os.makedirs(CHAT_DIR, exist_ok=True)
|
70 |
+
os.makedirs(VOTE_DIR, exist_ok=True)
|
71 |
os.makedirs(AUDIO_DIR, exist_ok=True)
|
72 |
+
os.makedirs(HISTORY_DIR, exist_ok=True)
|
73 |
os.makedirs(MEDIA_DIR, exist_ok=True)
|
74 |
|
75 |
+
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
76 |
+
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
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 bonanza! 🖋️🎨
|
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 |
("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 |
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 |
if 'quote_line' not in st.session_state:
|
130 |
st.session_state.quote_line = None
|
131 |
if 'refresh_rate' not in st.session_state:
|
132 |
+
st.session_state.refresh_rate = 5 # Default refresh rate
|
133 |
if 'base64_cache' not in st.session_state:
|
134 |
+
st.session_state.base64_cache = {} # Cache for base64 strings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
136 |
+
# Timestamp wizardry - clock ticks with flair! ⏰🎩
|
137 |
def format_timestamp_prefix(username):
|
138 |
+
now = datetime.now()
|
139 |
+
return f"{now.strftime('%I-%M-%p-ct-%m-%d-%Y')}-by-{username}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
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 |
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 stuff! 🧹📝
|
165 |
def clean_text_for_tts(text):
|
166 |
cleaned = re.sub(r'[#*!\[\]]+', '', text)
|
167 |
cleaned = ' '.join(cleaned.split())
|
168 |
+
return cleaned[:200] if cleaned else "No text to speak"
|
169 |
+
|
170 |
+
# Chat saver - words locked tight! 💬🔒
|
171 |
+
async def save_chat_entry(username, message):
|
172 |
+
await asyncio.to_thread(log_action, username, "💬🔒 - Chat saver - words locked tight!")
|
173 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Keep this for log consistency
|
174 |
+
entry = f"[{timestamp}] {username}: {message}"
|
175 |
+
await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"{entry}\n"))
|
176 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
177 |
+
cleaned_message = clean_text_for_tts(message)
|
178 |
+
audio_file = await async_edge_tts_generate(cleaned_message, voice)
|
179 |
+
if audio_file:
|
180 |
+
with open(HISTORY_FILE, 'a') as f:
|
181 |
+
f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
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 |
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 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
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 |
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 |
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}.{file_format}"
|
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(filepath)
|
271 |
+
return filepath if os.path.exists(filepath) else None
|
272 |
except edge_tts.exceptions.NoAudioReceived:
|
273 |
with open(HISTORY_FILE, 'a') as f:
|
274 |
+
f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {username}: Audio failed - No audio received for '{text}'\n")
|
|
|
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 |
+
if file_path not in st.session_state.base64_cache:
|
282 |
+
with open(file_path, "rb") as f:
|
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 with naming! 📸💾
|
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 |
+
filename = f"{timestamp}.png"
|
294 |
+
filepath = os.path.join(MEDIA_DIR, filename)
|
295 |
+
await asyncio.to_thread(image.save, filepath, "PNG")
|
296 |
+
return filepath
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
297 |
|
298 |
+
# Video renderer - movies roll with autoplay! 🎥🎬
|
299 |
+
async def get_video_html(video_path, width="100%"):
|
300 |
+
username = st.session_state.get('username', 'System 🌟')
|
301 |
+
await asyncio.to_thread(log_action, username, "🎥🎬 - Video renderer - movies roll!")
|
302 |
+
with open(video_path, 'rb') as f:
|
303 |
+
video_data = await asyncio.to_thread(f.read)
|
304 |
+
video_url = f"data:video/mp4;base64,{base64.b64encode(video_data).decode()}"
|
305 |
+
return f'<video width="{width}" controls autoplay><source src="{video_url}" type="video/mp4">Your browser does not support the video tag.</video>'
|
306 |
+
|
307 |
+
# Audio renderer - sounds soar! 🎶✈️
|
308 |
+
async def get_audio_html(audio_path, width="100%"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'<audio controls style="width: {width};"><source src="{audio_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>'
|
|
|
|
|
|
|
|
|
|
|
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 |
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 |
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 |
st.session_state.server_running = True
|
358 |
await server.wait_closed()
|
359 |
|
360 |
+
# Voice processor - speech to text! 🎤📝
|
361 |
+
async def process_voice_input(audio_bytes):
|
362 |
+
username = st.session_state.get('username', 'System 🌟')
|
363 |
+
await asyncio.to_thread(log_action, username, "🎤📝 - Voice processor - speech to text!")
|
364 |
+
if audio_bytes:
|
365 |
+
text = "Voice input simulation"
|
366 |
+
await save_chat_entry(username, text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
367 |
|
368 |
+
# Dummy AI lookup function (replace with actual implementation)
|
369 |
+
async def perform_ai_lookup(query, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False, useArxiv=True, useArxivAudio=False):
|
370 |
+
username = st.session_state.get('username', 'System 🌟')
|
371 |
+
result = f"AI Lookup Result for '{query}' (Arxiv: {useArxiv}, Audio: {useArxivAudio})"
|
372 |
+
await save_chat_entry(username, result)
|
373 |
+
if useArxivAudio:
|
374 |
+
audio_file = await async_edge_tts_generate(result, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
|
375 |
+
if audio_file:
|
376 |
+
st.audio(audio_file)
|
377 |
+
|
378 |
+
# Main execution - let’s roll! 🎲🚀
|
379 |
def main():
|
|
|
|
|
|
|
380 |
NODE_NAME, port = get_node_name()
|
381 |
|
382 |
+
loop = asyncio.new_event_loop()
|
383 |
+
asyncio.set_event_loop(loop)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
384 |
|
385 |
+
async def async_interface():
|
386 |
+
if 'username' not in st.session_state:
|
387 |
+
chat_content = await load_chat()
|
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 |
+
st.title(f"🤖🧠MMO {st.session_state.username}📝🔬")
|
392 |
+
st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! 🎉")
|
|
|
393 |
|
394 |
+
if not st.session_state.server_task:
|
395 |
+
st.session_state.server_task = loop.create_task(run_websocket_server())
|
|
|
396 |
|
397 |
+
audio_bytes = audio_recorder()
|
398 |
+
if audio_bytes:
|
399 |
+
await process_voice_input(audio_bytes)
|
400 |
+
st.rerun()
|
401 |
|
402 |
+
# Load and display chat
|
403 |
+
st.subheader(f"{START_ROOM} Chat 💬")
|
|
|
|
|
404 |
chat_content = await load_chat()
|
405 |
+
chat_lines = chat_content.split('\n')
|
406 |
+
chat_votes = await load_votes(QUOTE_VOTES_FILE)
|
407 |
+
|
408 |
+
current_time = time.time()
|
409 |
+
if current_time - st.session_state.last_chat_update > 1 or not st.session_state.displayed_chat_lines:
|
410 |
+
new_lines = [line for line in chat_lines if line.strip() and ': ' in line and line not in st.session_state.displayed_chat_lines and not line.startswith('#')]
|
411 |
+
st.session_state.displayed_chat_lines.extend(new_lines)
|
412 |
+
st.session_state.last_chat_update = current_time
|
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"### Quoting: {st.session_state.quote_line}")
|
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 |
+
st.image(paste_result_quote.image_data, caption="Received Image for Quote")
|
467 |
+
filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
|
468 |
+
if filename:
|
469 |
+
st.session_state.pasted_image_data = filename # Store for use in quote submission
|
|
|
|
|
|
|
|
|
|
|
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 |
+
new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
|
|
|
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 |
+
message = st.text_input(f"Message as {st.session_state.username}", key="message_input", value=st.session_state.message_text, on_change=lambda: st.session_state.update(message_text=st.session_state.message_input))
|
488 |
+
paste_result_msg = paste_image_button("📋 Paste Image with Message", key="paste_button_msg")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
489 |
if paste_result_msg.image_data is not None:
|
490 |
+
st.image(paste_result_msg.image_data, caption="Received Image for Message")
|
491 |
+
filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
|
492 |
+
if filename:
|
493 |
+
st.session_state.pasted_image_data = filename # Store for use in message submission
|
494 |
+
if st.button("Send 🚀", key="send_button") and (message.strip() or st.session_state.pasted_image_data):
|
495 |
+
if message.strip():
|
496 |
+
await save_chat_entry(st.session_state.username, message)
|
497 |
+
if st.session_state.pasted_image_data:
|
498 |
+
await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
|
499 |
+
st.session_state.pasted_image_data = None
|
500 |
+
st.session_state.message_text = ''
|
501 |
+
st.rerun()
|
502 |
|
503 |
+
# Main action tabs and model use choices
|
504 |
+
tab_main = st.radio("Action:", ["🎤 Voice", "📸 Media", "🔍 ArXiv", "📝 Editor"], horizontal=True)
|
505 |
+
useArxiv = st.checkbox("Search Arxiv for Research Paper Answers", value=True)
|
506 |
+
useArxivAudio = st.checkbox("Generate Audio File for Research Paper Answers", value=False)
|
507 |
+
|
508 |
+
# Enhanced Media Gallery with Image, Audio, Video
|
509 |
+
st.subheader("Upload Media 🎨🎶🎥")
|
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 |
+
filename = f"{timestamp}.{ext}"
|
516 |
+
file_path = os.path.join(MEDIA_DIR, filename)
|
517 |
+
await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
518 |
st.success(f"Uploaded {filename}")
|
519 |
+
await save_chat_entry(username, f"Uploaded media: {file_path}")
|
520 |
+
if file_path.endswith('.mp4'):
|
521 |
+
st.session_state.media_notifications.append(file_path)
|
522 |
+
|
523 |
+
st.subheader("Media Gallery 🎨🎶🎥")
|
524 |
+
media_files = glob.glob(f"{MEDIA_DIR}/*.png") + glob.glob(f"{MEDIA_DIR}/*.jpg") + glob.glob(f"{MEDIA_DIR}/*.mp4") + glob.glob(f"{MEDIA_DIR}/*.mp3")
|
525 |
+
if media_files:
|
526 |
+
media_votes = await load_votes(MEDIA_VOTES_FILE)
|
527 |
+
st.write("### All Media Uploads")
|
528 |
+
seen_files = set() # Track unique file paths to prevent duplicates
|
529 |
+
for media_file in sorted(media_files, key=os.path.getmtime, reverse=True):
|
530 |
+
if media_file not in seen_files: # Only add if not already seen
|
531 |
+
seen_files.add(media_file)
|
532 |
+
filename = os.path.basename(media_file)
|
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"<p class='timer'>⏳ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
|
557 |
+
time.sleep(1) # Use synchronous sleep
|
558 |
st.rerun()
|
559 |
|
560 |
+
st.sidebar.subheader("Chat History 📜")
|
561 |
+
with open(HISTORY_FILE, 'r') as f:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
562 |
history_content = f.read()
|
563 |
+
st.sidebar.markdown(history_content)
|
|
|
564 |
|
565 |
+
loop.run_until_complete(async_interface())
|
|
|
|
|
|
|
|
|
566 |
|
567 |
if __name__ == "__main__":
|
|
|
|
|
|
|
568 |
main()
|