Update app.py
Browse files
app.py
CHANGED
@@ -14,23 +14,21 @@ 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 +36,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 +60,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 +104,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 +117,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:
|
@@ -124,22 +133,20 @@ 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 |
-
|
130 |
-
|
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"{
|
141 |
|
142 |
-
# Compute image hash
|
143 |
def compute_image_hash(image_data):
|
144 |
if isinstance(image_data, Image.Image):
|
145 |
img_byte_arr = io.BytesIO()
|
@@ -149,7 +156,7 @@ def compute_image_hash(image_data):
|
|
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 +166,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 = {}
|
@@ -173,206 +180,34 @@ def log_action(username, action):
|
|
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
|
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 |
-
# 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
|
272 |
-
async def save_chat_entry(username, message, is_markdown=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"
|
285 |
else:
|
286 |
-
entry = f"
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
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
|
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 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,11 +216,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 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,32 +227,22 @@ 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 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
|
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
|
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")
|
@@ -431,14 +253,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 syncโs ring, in Streamlitโs sing!
|
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 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,139 +275,74 @@ 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 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
|
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 =
|
|
|
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 |
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
|
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 |
-
|
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 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 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
""
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
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,
|
582 |
-
return f''
|
583 |
-
|
584 |
-
|
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,11 +364,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 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,11 +378,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 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,212 +387,327 @@ async def run_websocket_server():
|
|
641 |
st.session_state.server_running = True
|
642 |
await server.wait_closed()
|
643 |
|
644 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
661 |
try:
|
662 |
-
|
663 |
-
|
664 |
except Exception as e:
|
665 |
-
st.error(f"Failed to
|
666 |
-
|
667 |
-
|
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 |
-
|
679 |
-
shared_memory.clear() # Clear shared cache on purge, in syncโs surge, in Streamlitโs surge!
|
680 |
return deleted_files
|
681 |
|
682 |
-
#
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
|
730 |
-
|
731 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
-
|
753 |
-
|
754 |
-
|
755 |
-
|
756 |
-
|
757 |
-
|
758 |
-
|
759 |
-
|
760 |
-
|
761 |
-
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
|
768 |
-
|
769 |
-
|
770 |
-
|
771 |
-
|
772 |
-
|
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 =
|
791 |
-
|
792 |
-
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
-
|
797 |
-
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
|
802 |
-
|
803 |
-
|
804 |
-
if
|
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 |
-
|
835 |
-
|
836 |
-
|
837 |
-
|
838 |
-
|
839 |
-
|
840 |
-
|
841 |
-
|
842 |
-
|
843 |
-
|
844 |
-
|
845 |
-
|
846 |
-
|
847 |
-
|
|
|
|
|
|
|
|
|
|
|
848 |
if st.session_state.quote_line:
|
849 |
-
st.markdown(f"
|
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:
|
@@ -858,14 +719,13 @@ async def async_interface():
|
|
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}"
|
867 |
st.session_state.pasted_image_data = None
|
868 |
-
await save_chat_entry(st.session_state.username, markdown_response, is_markdown=True
|
869 |
st.session_state.quote_line = None
|
870 |
st.session_state.message_text = ''
|
871 |
st.rerun()
|
@@ -879,157 +739,105 @@ async def async_interface():
|
|
879 |
st.markdown(f"**๐๏ธ Voice Changed**: {st.session_state.voice} ๐ฃ๏ธ for {st.session_state.username}")
|
880 |
st.rerun()
|
881 |
|
882 |
-
|
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
|
902 |
filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
|
903 |
if filename:
|
904 |
-
|
905 |
-
|
906 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
907 |
|
908 |
-
|
909 |
-
st.
|
910 |
-
|
|
|
|
|
|
|
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]
|
915 |
-
|
916 |
-
|
917 |
-
|
918 |
-
|
919 |
-
|
920 |
-
|
921 |
-
|
922 |
-
|
923 |
-
|
924 |
-
|
925 |
-
|
926 |
-
|
927 |
-
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"<
|
951 |
-
|
952 |
st.rerun()
|
953 |
|
954 |
-
|
955 |
-
|
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 |
-
|
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()
|
|
|
14 |
import io
|
15 |
import streamlit.components.v1 as components
|
16 |
import edge_tts
|
17 |
+
from audio_recorder_streamlit import audio_recorder
|
18 |
import nest_asyncio
|
19 |
import re
|
20 |
from streamlit_paste_button import paste_image_button
|
21 |
import pytz
|
22 |
import shutil
|
|
|
|
|
|
|
23 |
|
24 |
+
# Patch for nested async - sneaky fix! ๐โจ
|
25 |
nest_asyncio.apply()
|
26 |
|
27 |
+
# Static config - constants rule! ๐๐
|
28 |
icons = '๐ค๐ง ๐ฌ๐'
|
29 |
START_ROOM = "Sector ๐"
|
30 |
|
31 |
+
# Page setup - dressing up the window! ๐ผ๏ธ๐
|
32 |
st.set_page_config(
|
33 |
page_title="๐ค๐ง MMO Chat Brain๐๐ฌ",
|
34 |
page_icon=icons,
|
|
|
36 |
initial_sidebar_state="auto"
|
37 |
)
|
38 |
|
39 |
+
# Funky usernames - whoโs who in the zoo with unique voices! ๐ญ๐พ๐๏ธ
|
40 |
FUN_USERNAMES = {
|
41 |
"CosmicJester ๐": "en-US-AriaNeural",
|
42 |
"PixelPanda ๐ผ": "en-US-JennyNeural",
|
|
|
60 |
"ChronoChimp ๐": "en-GB-LibbyNeural"
|
61 |
}
|
62 |
|
63 |
+
# Folders galore - organizing chaos! ๐๐
|
64 |
+
CHAT_DIR = "chat_logs"
|
65 |
+
VOTE_DIR = "vote_logs"
|
|
|
|
|
66 |
STATE_FILE = "user_state.txt"
|
67 |
AUDIO_DIR = "audio_logs"
|
68 |
+
HISTORY_DIR = "history_logs"
|
69 |
MEDIA_DIR = "media_files"
|
70 |
+
os.makedirs(CHAT_DIR, exist_ok=True)
|
71 |
+
os.makedirs(VOTE_DIR, exist_ok=True)
|
72 |
os.makedirs(AUDIO_DIR, exist_ok=True)
|
73 |
+
os.makedirs(HISTORY_DIR, exist_ok=True)
|
74 |
os.makedirs(MEDIA_DIR, exist_ok=True)
|
75 |
|
76 |
+
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
77 |
+
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
78 |
+
MEDIA_VOTES_FILE = os.path.join(VOTE_DIR, "media_votes.md")
|
79 |
+
HISTORY_FILE = os.path.join(HISTORY_DIR, "chat_history.md")
|
80 |
+
|
81 |
+
# Fancy digits - numbers got style! ๐ข๐
|
82 |
UNICODE_DIGITS = {i: f"{i}\uFE0Fโฃ" for i in range(10)}
|
83 |
|
84 |
+
# Massive font collection - typography bonanza! ๐๏ธ๐จ
|
85 |
UNICODE_FONTS = [
|
86 |
("Normal", lambda x: x),
|
87 |
("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)),
|
|
|
104 |
("Regional Indicator", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F1E6) if 'A' <= c <= 'Z' else c for c in x)),
|
105 |
]
|
106 |
|
107 |
+
# Global state - keeping tabs! ๐๐
|
108 |
if 'server_running' not in st.session_state:
|
109 |
st.session_state.server_running = False
|
110 |
if 'server_task' not in st.session_state:
|
|
|
117 |
st.session_state.last_chat_update = 0
|
118 |
if 'displayed_chat_lines' not in st.session_state:
|
119 |
st.session_state.displayed_chat_lines = []
|
120 |
+
if 'old_val' not in st.session_state:
|
121 |
+
st.session_state.old_val = ""
|
122 |
+
if 'last_query' not in st.session_state:
|
123 |
+
st.session_state.last_query = ""
|
124 |
if 'message_text' not in st.session_state:
|
125 |
st.session_state.message_text = ""
|
126 |
if 'audio_cache' not in st.session_state:
|
|
|
133 |
st.session_state.refresh_rate = 5
|
134 |
if 'base64_cache' not in st.session_state:
|
135 |
st.session_state.base64_cache = {}
|
136 |
+
if 'transcript_history' not in st.session_state:
|
137 |
+
st.session_state.transcript_history = []
|
138 |
+
if 'last_transcript' not in st.session_state:
|
139 |
+
st.session_state.last_transcript = ""
|
140 |
if 'image_hashes' not in st.session_state:
|
141 |
st.session_state.image_hashes = set()
|
142 |
+
|
143 |
+
# Timestamp wizardry - clock ticks with flair! โฐ๐ฉ
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
def format_timestamp_prefix(username):
|
145 |
central = pytz.timezone('US/Central')
|
146 |
now = datetime.now(central)
|
147 |
+
return f"{now.strftime('%I-%M-%p-ct-%m-%d-%Y')}-by-{username}"
|
148 |
|
149 |
+
# Compute image hash from binary data
|
150 |
def compute_image_hash(image_data):
|
151 |
if isinstance(image_data, Image.Image):
|
152 |
img_byte_arr = io.BytesIO()
|
|
|
156 |
img_bytes = image_data
|
157 |
return hashlib.md5(img_bytes).hexdigest()[:8]
|
158 |
|
159 |
+
# Node naming - christening the beast! ๐๐ผ
|
160 |
def get_node_name():
|
161 |
parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
|
162 |
parser.add_argument('--node-name', type=str, default=None)
|
|
|
166 |
log_action(username, "๐๐ผ - Node naming - christening the beast!")
|
167 |
return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
|
168 |
|
169 |
+
# Action logger - spying on deeds! ๐ต๏ธ๐
|
170 |
def log_action(username, action):
|
171 |
if 'action_log' not in st.session_state:
|
172 |
st.session_state.action_log = {}
|
|
|
180 |
f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n")
|
181 |
user_log[action] = current_time
|
182 |
|
183 |
+
# Clean text - strip the fancy stuff! ๐งน๐
|
184 |
def clean_text_for_tts(text):
|
185 |
cleaned = re.sub(r'[#*!\[\]]+', '', text)
|
186 |
cleaned = ' '.join(cleaned.split())
|
187 |
+
return cleaned[:200] if cleaned else "No text to speak"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
|
189 |
+
# Chat saver - words locked tight! ๐ฌ๐
|
190 |
+
async def save_chat_entry(username, message, is_markdown=False):
|
191 |
+
await asyncio.to_thread(log_action, username, "๐ฌ๐ - Chat saver - words locked tight!")
|
|
|
|
|
192 |
central = pytz.timezone('US/Central')
|
193 |
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
|
|
|
|
|
|
194 |
if is_markdown:
|
195 |
+
entry = f"[{timestamp}] {username}:\n```markdown\n{message}\n```"
|
196 |
else:
|
197 |
+
entry = f"[{timestamp}] {username}: {message}"
|
198 |
+
await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"{entry}\n"))
|
199 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
200 |
+
cleaned_message = clean_text_for_tts(message)
|
201 |
+
audio_file = await async_edge_tts_generate(cleaned_message, voice)
|
202 |
+
if audio_file:
|
203 |
+
with open(HISTORY_FILE, 'a') as f:
|
204 |
+
f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
await broadcast_message(f"{username}|{message}", "chat")
|
206 |
st.session_state.last_chat_update = time.time()
|
207 |
+
return audio_file
|
208 |
|
209 |
+
# Chat loader - history unleashed! ๐๐
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
async def load_chat():
|
|
|
|
|
|
|
211 |
username = st.session_state.get('username', 'System ๐')
|
212 |
await asyncio.to_thread(log_action, username, "๐๐ - Chat loader - history unleashed!")
|
213 |
if not os.path.exists(CHAT_FILE):
|
|
|
216 |
content = await asyncio.to_thread(f.read)
|
217 |
return content
|
218 |
|
219 |
+
# User lister - whoโs in the gang! ๐ฅ๐
|
220 |
async def get_user_list(chat_content):
|
|
|
|
|
|
|
221 |
username = st.session_state.get('username', 'System ๐')
|
222 |
await asyncio.to_thread(log_action, username, "๐ฅ๐ - User lister - whoโs in the gang!")
|
223 |
users = set()
|
|
|
227 |
users.add(user)
|
228 |
return sorted(list(users))
|
229 |
|
230 |
+
# Join checker - been here before? ๐ช๐
|
231 |
async def has_joined_before(client_id, chat_content):
|
|
|
|
|
|
|
232 |
username = st.session_state.get('username', 'System ๐')
|
233 |
await asyncio.to_thread(log_action, username, "๐ช๐ - Join checker - been here before?")
|
234 |
return any(f"Client-{client_id}" in line for line in chat_content.split('\n'))
|
235 |
|
236 |
+
# Suggestion maker - old quips resurface! ๐ก๐
|
237 |
async def get_message_suggestions(chat_content, prefix):
|
|
|
|
|
|
|
238 |
username = st.session_state.get('username', 'System ๏ฟฝ๏ฟฝ')
|
239 |
await asyncio.to_thread(log_action, username, "๐ก๐ - Suggestion maker - old quips resurface!")
|
240 |
lines = chat_content.split('\n')
|
241 |
messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
|
242 |
return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5]
|
243 |
|
244 |
+
# Vote saver - cheers recorded! ๐๐
|
|
|
245 |
async def save_vote(file, item, user_hash, username, comment=""):
|
|
|
|
|
|
|
246 |
await asyncio.to_thread(log_action, username, "๐๐ - Vote saver - cheers recorded!")
|
247 |
central = pytz.timezone('US/Central')
|
248 |
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
|
|
|
253 |
if comment:
|
254 |
chat_message += f" - {comment}"
|
255 |
await save_chat_entry(username, chat_message)
|
|
|
256 |
|
257 |
+
# Vote counter - tallying the love! ๐๐
|
|
|
258 |
async def load_votes(file):
|
|
|
|
|
|
|
259 |
username = st.session_state.get('username', 'System ๐')
|
260 |
await asyncio.to_thread(log_action, username, "๐๐ - Vote counter - tallying the love!")
|
261 |
if not os.path.exists(file):
|
|
|
275 |
user_votes.add(vote_key)
|
276 |
return votes
|
277 |
|
278 |
+
# Hash generator - secret codes ahoy! ๐๐ต๏ธ
|
279 |
async def generate_user_hash():
|
|
|
|
|
|
|
280 |
username = st.session_state.get('username', 'System ๐')
|
281 |
await asyncio.to_thread(log_action, username, "๐๐ต๏ธ - Hash generator - secret codes ahoy!")
|
282 |
if 'user_hash' not in st.session_state:
|
283 |
st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8]
|
284 |
return st.session_state.user_hash
|
285 |
|
286 |
+
# Audio maker - voices come alive! ๐ถ๐
|
287 |
async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
|
|
|
|
|
|
|
288 |
username = st.session_state.get('username', 'System ๐')
|
289 |
await asyncio.to_thread(log_action, username, "๐ถ๐ - Audio maker - voices come alive!")
|
290 |
timestamp = format_timestamp_prefix(username)
|
291 |
+
filename = f"{timestamp}.{file_format}"
|
292 |
+
filepath = os.path.join(AUDIO_DIR, filename)
|
293 |
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
294 |
try:
|
295 |
+
await communicate.save(filepath)
|
296 |
+
return filepath if os.path.exists(filepath) else None
|
297 |
except edge_tts.exceptions.NoAudioReceived:
|
298 |
with open(HISTORY_FILE, 'a') as f:
|
299 |
central = pytz.timezone('US/Central')
|
300 |
f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: Audio failed - No audio received for '{text}'\n")
|
301 |
return None
|
302 |
|
303 |
+
# Audio player - tunes blast off! ๐๐
|
304 |
def play_and_download_audio(file_path):
|
|
|
|
|
|
|
305 |
if file_path and os.path.exists(file_path):
|
306 |
st.audio(file_path)
|
307 |
+
if file_path not in st.session_state.base64_cache:
|
308 |
+
with open(file_path, "rb") as f:
|
309 |
+
b64 = base64.b64encode(f.read()).decode()
|
310 |
+
st.session_state.base64_cache[file_path] = b64
|
311 |
+
b64 = st.session_state.base64_cache[file_path]
|
312 |
dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">๐ต Download {os.path.basename(file_path)}</a>'
|
313 |
st.markdown(dl_link, unsafe_allow_html=True)
|
314 |
|
315 |
+
# Image saver - pics preserved with naming! ๐ธ๐พ
|
316 |
async def save_pasted_image(image, username):
|
|
|
|
|
|
|
317 |
await asyncio.to_thread(log_action, username, "๐ธ๐พ - Image saver - pics preserved!")
|
318 |
+
img_hash = compute_image_hash(image)
|
319 |
+
if img_hash in st.session_state.image_hashes:
|
320 |
+
return None
|
321 |
timestamp = format_timestamp_prefix(username)
|
322 |
+
filename = f"{timestamp}-{img_hash}.png"
|
323 |
+
filepath = os.path.join(MEDIA_DIR, filename)
|
324 |
+
await asyncio.to_thread(image.save, filepath, "PNG")
|
325 |
+
st.session_state.image_hashes.add(img_hash)
|
326 |
+
return filepath
|
327 |
+
|
328 |
+
# Video renderer - movies roll with autoplay! ๐ฅ๐ฌ
|
329 |
+
async def get_video_html(video_path, width="100%"):
|
330 |
+
username = st.session_state.get('username', 'System ๐')
|
331 |
+
await asyncio.to_thread(log_action, username, "๐ฅ๐ฌ - Video renderer - movies roll!")
|
332 |
+
with open(video_path, 'rb') as f:
|
333 |
+
video_data = await asyncio.to_thread(f.read)
|
334 |
+
video_url = f"data:video/mp4;base64,{base64.b64encode(video_data).decode()}"
|
335 |
+
return f'<video width="{width}" controls autoplay><source src="{video_url}" type="video/mp4">Your browser does not support the video tag.</video>'
|
336 |
+
|
337 |
+
# Audio renderer - sounds soar! ๐ถโ๏ธ
|
338 |
+
async def get_audio_html(audio_path, width="100%"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
339 |
username = st.session_state.get('username', 'System ๐')
|
340 |
await asyncio.to_thread(log_action, username, "๐ถโ๏ธ - Audio renderer - sounds soar!")
|
341 |
+
audio_url = f"data:audio/mpeg;base64,{base64.b64encode(await asyncio.to_thread(open, audio_path, 'rb').read()).decode()}"
|
342 |
+
return f'<audio controls style="width: {width};"><source src="{audio_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>'
|
343 |
+
|
344 |
+
# Websocket handler - chat links up! ๐๐
|
|
|
|
|
|
|
|
|
|
|
345 |
async def websocket_handler(websocket, path):
|
|
|
|
|
|
|
346 |
username = st.session_state.get('username', 'System ๐')
|
347 |
await asyncio.to_thread(log_action, username, "๐๐ - Websocket handler - chat links up!")
|
348 |
try:
|
|
|
364 |
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
|
365 |
del st.session_state.active_connections[room_id][client_id]
|
366 |
|
367 |
+
# Message broadcaster - words fly far! ๐ขโ๏ธ
|
368 |
async def broadcast_message(message, room_id):
|
|
|
|
|
|
|
369 |
username = st.session_state.get('username', 'System ๐')
|
370 |
await asyncio.to_thread(log_action, username, "๐ขโ๏ธ - Message broadcaster - words fly far!")
|
371 |
if room_id in st.session_state.active_connections:
|
|
|
378 |
for client_id in disconnected:
|
379 |
del st.session_state.active_connections[room_id][client_id]
|
380 |
|
381 |
+
# Server starter - web spins up! ๐ฅ๏ธ๐
|
382 |
async def run_websocket_server():
|
|
|
|
|
|
|
383 |
username = st.session_state.get('username', 'System ๐')
|
384 |
await asyncio.to_thread(log_action, username, "๐ฅ๏ธ๐ - Server starter - web spins up!")
|
385 |
if not st.session_state.server_running:
|
|
|
387 |
st.session_state.server_running = True
|
388 |
await server.wait_closed()
|
389 |
|
390 |
+
# Voice processor - speech to text! ๐ค๐
|
391 |
+
async def process_voice_input(audio_bytes):
|
392 |
+
username = st.session_state.get('username', 'System ๐')
|
393 |
+
await asyncio.to_thread(log_action, username, "๐ค๐ - Voice processor - speech to text!")
|
394 |
+
if audio_bytes:
|
395 |
+
text = "Voice input simulation"
|
396 |
+
await save_chat_entry(username, text)
|
397 |
+
|
398 |
+
# Dummy AI lookup function (replace with actual implementation)
|
399 |
+
async def perform_ai_lookup(query, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False, useArxiv=True, useArxivAudio=False):
|
400 |
+
username = st.session_state.get('username', 'System ๐')
|
401 |
+
result = f"AI Lookup Result for '{query}' (Arxiv: {useArxiv}, Audio: {useArxivAudio})"
|
402 |
+
await save_chat_entry(username, result)
|
403 |
+
if useArxivAudio:
|
404 |
+
audio_file = await async_edge_tts_generate(result, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
|
405 |
+
if audio_file:
|
406 |
+
st.audio(audio_file)
|
407 |
+
|
408 |
+
# Delete all user files function
|
409 |
def delete_user_files():
|
410 |
+
protected_files = {'app.py', 'requirements.txt', 'README.md'}
|
|
|
|
|
|
|
411 |
deleted_files = []
|
412 |
+
|
413 |
+
# Directories to clear
|
414 |
+
directories = [MEDIA_DIR, AUDIO_DIR, CHAT_DIR, VOTE_DIR, HISTORY_DIR]
|
415 |
+
|
416 |
+
for directory in directories:
|
417 |
+
if os.path.exists(directory):
|
418 |
+
for root, _, files in os.walk(directory):
|
419 |
+
for file in files:
|
420 |
+
file_path = os.path.join(root, file)
|
421 |
+
if os.path.basename(file_path) not in protected_files:
|
422 |
+
try:
|
423 |
+
os.remove(file_path)
|
424 |
+
deleted_files.append(file_path)
|
425 |
+
except Exception as e:
|
426 |
+
st.error(f"Failed to delete {file_path}: {e}")
|
427 |
+
# Remove empty directories
|
428 |
try:
|
429 |
+
shutil.rmtree(directory, ignore_errors=True)
|
430 |
+
os.makedirs(directory, exist_ok=True) # Recreate empty directory
|
431 |
except Exception as e:
|
432 |
+
st.error(f"Failed to remove directory {directory}: {e}")
|
433 |
+
|
434 |
+
# Clear session state caches
|
|
|
|
|
|
|
|
|
|
|
|
|
435 |
st.session_state.image_hashes.clear()
|
436 |
st.session_state.audio_cache.clear()
|
437 |
st.session_state.base64_cache.clear()
|
438 |
st.session_state.displayed_chat_lines.clear()
|
439 |
+
|
|
|
440 |
return deleted_files
|
441 |
|
442 |
+
# ASR Component HTML
|
443 |
+
ASR_HTML = """
|
444 |
+
<html>
|
445 |
+
<head>
|
446 |
+
<title>Continuous Speech Demo</title>
|
447 |
+
<style>
|
448 |
+
body {
|
449 |
+
font-family: sans-serif;
|
450 |
+
padding: 20px;
|
451 |
+
max-width: 800px;
|
452 |
+
margin: 0 auto;
|
453 |
+
}
|
454 |
+
button {
|
455 |
+
padding: 10px 20px;
|
456 |
+
margin: 10px 5px;
|
457 |
+
font-size: 16px;
|
458 |
+
}
|
459 |
+
#status {
|
460 |
+
margin: 10px 0;
|
461 |
+
padding: 10px;
|
462 |
+
background: #e8f5e9;
|
463 |
+
border-radius: 4px;
|
464 |
+
}
|
465 |
+
#output {
|
466 |
+
white-space: pre-wrap;
|
467 |
+
padding: 15px;
|
468 |
+
background: #f5f5f5;
|
469 |
+
border-radius: 4px;
|
470 |
+
margin: 10px 0;
|
471 |
+
min-height: 100px;
|
472 |
+
max-height: 400px;
|
473 |
+
overflow-y: auto;
|
474 |
+
}
|
475 |
+
.controls {
|
476 |
+
margin: 10px 0;
|
477 |
+
}
|
478 |
+
</style>
|
479 |
+
</head>
|
480 |
+
<body>
|
481 |
+
<div class="controls">
|
482 |
+
<button id="start">Start Listening</button>
|
483 |
+
<button id="stop" disabled>Stop Listening</button>
|
484 |
+
<button id="clear">Clear Text</button>
|
485 |
+
</div>
|
486 |
+
<div id="status">Ready</div>
|
487 |
+
<div id="output"></div>
|
488 |
+
|
489 |
+
<script>
|
490 |
+
if (!('webkitSpeechRecognition' in window)) {
|
491 |
+
alert('Speech recognition not supported');
|
492 |
+
} else {
|
493 |
+
const recognition = new webkitSpeechRecognition();
|
494 |
+
const startButton = document.getElementById('start');
|
495 |
+
const stopButton = document.getElementById('stop');
|
496 |
+
const clearButton = document.getElementById('clear');
|
497 |
+
const status = document.getElementById('status');
|
498 |
+
const output = document.getElementById('output');
|
499 |
+
let fullTranscript = '';
|
500 |
+
let lastUpdateTime = Date.now();
|
501 |
+
|
502 |
+
recognition.continuous = true;
|
503 |
+
recognition.interimResults = true;
|
504 |
+
|
505 |
+
const startRecognition = () => {
|
506 |
+
try {
|
507 |
+
recognition.start();
|
508 |
+
status.textContent = 'Listening...';
|
509 |
+
startButton.disabled = true;
|
510 |
+
stopButton.disabled = false;
|
511 |
+
} catch (e) {
|
512 |
+
console.error(e);
|
513 |
+
status.textContent = 'Error: ' + e.message;
|
514 |
+
}
|
515 |
+
};
|
516 |
+
|
517 |
+
window.addEventListener('load', () => {
|
518 |
+
setTimeout(startRecognition, 1000);
|
519 |
+
});
|
520 |
+
|
521 |
+
startButton.onclick = startRecognition;
|
522 |
+
|
523 |
+
stopButton.onclick = () => {
|
524 |
+
recognition.stop();
|
525 |
+
status.textContent = 'Stopped';
|
526 |
+
startButton.disabled = false;
|
527 |
+
stopButton.disabled = true;
|
528 |
+
};
|
529 |
+
|
530 |
+
clearButton.onclick = () => {
|
531 |
+
fullTranscript = '';
|
532 |
+
output.textContent = '';
|
533 |
+
sendDataToPython({value: '', dataType: "json"});
|
534 |
+
};
|
535 |
+
|
536 |
+
recognition.onresult = (event) => {
|
537 |
+
let interimTranscript = '';
|
538 |
+
let finalTranscript = '';
|
539 |
+
|
540 |
+
for (let i = event.resultIndex; i < event.results.length; i++) {
|
541 |
+
const transcript = event.results[i][0].transcript;
|
542 |
+
if (event.results[i].isFinal) {
|
543 |
+
finalTranscript += transcript + '\\n';
|
544 |
+
} else {
|
545 |
+
interimTranscript += transcript;
|
546 |
+
}
|
547 |
+
}
|
548 |
+
|
549 |
+
if (finalTranscript || (Date.now() - lastUpdateTime > 5000)) {
|
550 |
+
if (finalTranscript) {
|
551 |
+
fullTranscript += finalTranscript;
|
552 |
+
}
|
553 |
+
lastUpdateTime = Date.now();
|
554 |
+
output.textContent = fullTranscript + (interimTranscript ? '... ' + interimTranscript : '');
|
555 |
+
output.scrollTop = output.scrollHeight;
|
556 |
+
sendDataToPython({value: fullTranscript, dataType: "json"});
|
557 |
+
}
|
558 |
+
};
|
559 |
+
|
560 |
+
recognition.onend = () => {
|
561 |
+
if (!stopButton.disabled) {
|
562 |
+
try {
|
563 |
+
recognition.start();
|
564 |
+
console.log('Restarted recognition');
|
565 |
+
} catch (e) {
|
566 |
+
console.error('Failed to restart recognition:', e);
|
567 |
+
status.textContent = 'Error restarting: ' + e.message;
|
568 |
+
startButton.disabled = false;
|
569 |
+
stopButton.disabled = true;
|
570 |
+
}
|
571 |
+
}
|
572 |
+
};
|
573 |
+
|
574 |
+
recognition.onerror = (event) => {
|
575 |
+
console.error('Recognition error:', event.error);
|
576 |
+
status.textContent = 'Error: ' + event.error;
|
577 |
+
if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
|
578 |
+
startButton.disabled = false;
|
579 |
+
stopButton.disabled = true;
|
580 |
+
}
|
581 |
+
};
|
582 |
+
}
|
583 |
+
|
584 |
+
function sendDataToPython(data) {
|
585 |
+
window.parent.postMessage({
|
586 |
+
isStreamlitMessage: true,
|
587 |
+
type: "streamlit:setComponentValue",
|
588 |
+
...data
|
589 |
+
}, "*");
|
590 |
+
}
|
591 |
+
|
592 |
+
window.addEventListener('load', function() {
|
593 |
+
window.setTimeout(function() {
|
594 |
+
window.parent.postMessage({
|
595 |
+
isStreamlitMessage: true,
|
596 |
+
type: "streamlit:setFrameHeight",
|
597 |
+
height: document.documentElement.clientHeight
|
598 |
+
}, "*");
|
599 |
+
}, 0);
|
600 |
+
});
|
601 |
+
</script>
|
602 |
+
</body>
|
603 |
+
</html>
|
604 |
+
"""
|
605 |
+
|
606 |
+
# Main execution - letโs roll! ๐ฒ๐
|
607 |
def main():
|
|
|
|
|
|
|
608 |
NODE_NAME, port = get_node_name()
|
609 |
|
610 |
+
loop = asyncio.new_event_loop()
|
611 |
+
asyncio.set_event_loop(loop)
|
612 |
+
|
613 |
+
async def async_interface():
|
614 |
+
if 'username' not in st.session_state:
|
615 |
+
chat_content = await load_chat()
|
616 |
+
available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
|
617 |
+
st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
|
618 |
+
st.session_state.voice = FUN_USERNAMES[st.session_state.username]
|
619 |
+
st.markdown(f"**๐๏ธ Voice Selected**: {st.session_state.voice} ๐ฃ๏ธ for {st.session_state.username}")
|
620 |
+
|
621 |
+
st.title(f"๐ค๐ง MMO {st.session_state.username}๐๐ฌ")
|
622 |
+
st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! ๐")
|
623 |
+
|
624 |
+
if not st.session_state.server_task:
|
625 |
+
st.session_state.server_task = loop.create_task(run_websocket_server())
|
626 |
+
|
627 |
+
audio_bytes = audio_recorder()
|
628 |
+
if audio_bytes:
|
629 |
+
await process_voice_input(audio_bytes)
|
630 |
+
st.rerun()
|
631 |
+
|
632 |
+
# Continuous Speech Input (ASR)
|
633 |
+
st.subheader("๐ค Continuous Speech Input")
|
634 |
+
asr_component = components.html(ASR_HTML, height=400)
|
635 |
+
if asr_component and isinstance(asr_component, dict) and 'value' in asr_component:
|
636 |
+
transcript = asr_component['value'].strip()
|
637 |
+
if transcript and transcript != st.session_state.last_transcript:
|
638 |
+
st.session_state.transcript_history.append(transcript)
|
639 |
+
await save_chat_entry(st.session_state.username, transcript, is_markdown=True)
|
640 |
+
st.session_state.last_transcript = transcript
|
641 |
+
st.rerun()
|
642 |
+
|
643 |
+
# Load and display chat
|
644 |
+
st.subheader(f"{START_ROOM} Chat ๐ฌ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
645 |
chat_content = await load_chat()
|
646 |
+
chat_lines = chat_content.split('\n')
|
647 |
+
chat_votes = await load_votes(QUOTE_VOTES_FILE)
|
648 |
+
|
649 |
+
current_time = time.time()
|
650 |
+
if current_time - st.session_state.last_chat_update > 1 or not st.session_state.displayed_chat_lines:
|
651 |
+
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('#')]
|
652 |
+
st.session_state.displayed_chat_lines.extend(new_lines)
|
653 |
+
st.session_state.last_chat_update = current_time
|
654 |
+
|
655 |
+
for i, line in enumerate(st.session_state.displayed_chat_lines):
|
656 |
+
col1, col2, col3, col4 = st.columns([3, 1, 1, 2])
|
657 |
+
with col1:
|
658 |
+
if "```markdown" in line:
|
659 |
+
markdown_content = re.search(r'```markdown\n(.*?)```', line, re.DOTALL)
|
660 |
+
if markdown_content:
|
661 |
+
st.markdown(markdown_content.group(1))
|
662 |
+
else:
|
663 |
+
st.markdown(line)
|
664 |
+
else:
|
665 |
+
st.markdown(line)
|
666 |
+
if "Pasted image:" in line or "Uploaded media:" in line:
|
667 |
+
file_path = line.split(': ')[-1].strip()
|
668 |
+
if os.path.exists(file_path):
|
669 |
+
if file_path not in st.session_state.base64_cache:
|
670 |
+
with open(file_path, "rb") as f:
|
671 |
+
b64 = base64.b64encode(f.read()).decode()
|
672 |
+
st.session_state.base64_cache[file_path] = b64
|
673 |
+
b64 = st.session_state.base64_cache[file_path]
|
674 |
+
mime_type = "image/png" if file_path.endswith(('.png', '.jpg')) else "video/mp4" if file_path.endswith('.mp4') else "audio/mpeg"
|
675 |
+
if file_path.endswith(('.png', '.jpg')):
|
676 |
+
st.image(file_path, use_container_width=True)
|
677 |
+
dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">๐ฅ Download {os.path.basename(file_path)}</a>'
|
678 |
+
st.markdown(dl_link, unsafe_allow_html=True)
|
679 |
+
elif file_path.endswith('.mp4'):
|
680 |
+
st.markdown(await get_video_html(file_path), unsafe_allow_html=True)
|
681 |
+
dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">๐ฅ Download {os.path.basename(file_path)}</a>'
|
682 |
+
st.markdown(dl_link, unsafe_allow_html=True)
|
683 |
+
elif file_path.endswith('.mp3'):
|
684 |
+
st.markdown(await get_audio_html(file_path), unsafe_allow_html=True)
|
685 |
+
dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">๐ฅ Download {os.path.basename(file_path)}</a>'
|
686 |
+
st.markdown(dl_link, unsafe_allow_html=True)
|
687 |
+
with col2:
|
688 |
+
vote_count = chat_votes.get(line.split('. ')[1] if '. ' in line else line, 0)
|
689 |
+
if st.button(f"๐ {vote_count}", key=f"chat_vote_{i}"):
|
690 |
+
comment = st.session_state.message_text
|
691 |
+
await save_vote(QUOTE_VOTES_FILE, line.split('. ')[1] if '. ' in line else line, await generate_user_hash(), st.session_state.username, comment)
|
692 |
+
st.session_state.message_text = ''
|
693 |
+
st.rerun()
|
694 |
+
with col3:
|
695 |
+
if st.button("๐ข Quote", key=f"quote_{i}"):
|
696 |
+
st.session_state.quote_line = line
|
697 |
+
st.rerun()
|
698 |
+
with col4:
|
699 |
+
username = line.split(': ')[1].split(' ')[0]
|
700 |
+
cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
|
701 |
+
if cache_key not in st.session_state.audio_cache:
|
702 |
+
cleaned_text = clean_text_for_tts(line.split(': ', 1)[1])
|
703 |
+
audio_file = await async_edge_tts_generate(cleaned_text, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
|
704 |
+
st.session_state.audio_cache[cache_key] = audio_file
|
705 |
+
audio_file = st.session_state.audio_cache.get(cache_key)
|
706 |
+
if audio_file:
|
707 |
+
play_and_download_audio(audio_file)
|
708 |
+
|
709 |
if st.session_state.quote_line:
|
710 |
+
st.markdown(f"### Quoting: {st.session_state.quote_line}")
|
711 |
quote_response = st.text_area("Add your response", key="quote_response", value=st.session_state.message_text)
|
712 |
paste_result_quote = paste_image_button("๐ Paste Image or Text with Quote", key="paste_button_quote")
|
713 |
if paste_result_quote.image_data is not None:
|
|
|
719 |
filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
|
720 |
if filename:
|
721 |
st.session_state.pasted_image_data = filename
|
|
|
722 |
if st.button("Send Quote ๐", key="send_quote"):
|
723 |
markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
|
724 |
if st.session_state.pasted_image_data:
|
725 |
markdown_response += f"\n- **Image**: "
|
726 |
+
await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
|
727 |
st.session_state.pasted_image_data = None
|
728 |
+
await save_chat_entry(st.session_state.username, markdown_response, is_markdown=True)
|
729 |
st.session_state.quote_line = None
|
730 |
st.session_state.message_text = ''
|
731 |
st.rerun()
|
|
|
739 |
st.markdown(f"**๐๏ธ Voice Changed**: {st.session_state.voice} ๐ฃ๏ธ for {st.session_state.username}")
|
740 |
st.rerun()
|
741 |
|
742 |
+
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
743 |
paste_result_msg = paste_image_button("๐ Paste Image or Text with Message", key="paste_button_msg")
|
744 |
if paste_result_msg.image_data is not None:
|
745 |
if isinstance(paste_result_msg.image_data, str):
|
746 |
st.session_state.message_text = paste_result_msg.image_data
|
747 |
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)
|
748 |
else:
|
749 |
+
st.image(paste_result_msg.image_data, caption="Received Image for Message")
|
750 |
filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
|
751 |
if filename:
|
752 |
+
st.session_state.pasted_image_data = filename
|
753 |
+
if st.button("Send ๐", key="send_button") and (message.strip() or st.session_state.pasted_image_data):
|
754 |
+
if message.strip():
|
755 |
+
audio_file = await save_chat_entry(st.session_state.username, message, is_markdown=True)
|
756 |
+
if audio_file:
|
757 |
+
st.session_state.audio_cache[f"{message}_{FUN_USERNAMES[st.session_state.username]}"] = audio_file
|
758 |
+
if st.session_state.pasted_image_data:
|
759 |
+
await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
|
760 |
+
st.session_state.pasted_image_data = None
|
761 |
+
st.session_state.message_text = ''
|
762 |
+
st.rerun()
|
763 |
|
764 |
+
tab_main = st.radio("Action:", ["๐ค Voice", "๐ธ Media", "๐ ArXiv", "๐ Editor"], horizontal=True)
|
765 |
+
useArxiv = st.checkbox("Search Arxiv for Research Paper Answers", value=True)
|
766 |
+
useArxivAudio = st.checkbox("Generate Audio File for Research Paper Answers", value=False)
|
767 |
+
|
768 |
+
st.subheader("Upload Media ๐จ๐ถ๐ฅ")
|
769 |
+
uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3'])
|
770 |
if uploaded_file:
|
771 |
timestamp = format_timestamp_prefix(st.session_state.username)
|
772 |
username = st.session_state.username
|
773 |
+
ext = uploaded_file.name.split('.')[-1]
|
774 |
+
file_hash = hashlib.md5(uploaded_file.getbuffer()).hexdigest()[:8]
|
775 |
+
if file_hash not in st.session_state.image_hashes:
|
776 |
+
filename = f"{timestamp}-{file_hash}.{ext}"
|
777 |
+
file_path = os.path.join(MEDIA_DIR, filename)
|
778 |
+
await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
|
779 |
+
st.success(f"Uploaded {filename}")
|
780 |
+
await save_chat_entry(username, f"Uploaded media: {file_path}")
|
781 |
+
st.session_state.image_hashes.add(file_hash)
|
782 |
+
if file_path.endswith('.mp4'):
|
783 |
+
st.session_state.media_notifications.append(file_path)
|
784 |
+
|
785 |
+
# Big Red Delete Button
|
786 |
+
st.subheader("๐ Danger Zone")
|
|
|
|
|
|
|
|
|
|
|
787 |
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):
|
788 |
deleted_files = delete_user_files()
|
789 |
if deleted_files:
|
790 |
st.markdown("### ๐๏ธ Deleted Files:\n" + "\n".join([f"- `{file}`" for file in deleted_files]))
|
|
|
|
|
791 |
else:
|
792 |
st.markdown("### ๐๏ธ Nothing to Delete!")
|
793 |
+
st.session_state.image_hashes.clear()
|
794 |
+
st.session_state.audio_cache.clear()
|
795 |
+
st.session_state.base64_cache.clear()
|
796 |
+
st.session_state.displayed_chat_lines.clear()
|
797 |
st.rerun()
|
798 |
|
799 |
+
st.subheader("Media Gallery ๐จ๐ถ๐ฅ")
|
800 |
+
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")
|
801 |
+
if media_files:
|
802 |
+
media_votes = await load_votes(MEDIA_VOTES_FILE)
|
803 |
+
st.write("### All Media Uploads")
|
804 |
+
seen_files = set()
|
805 |
+
for media_file in sorted(media_files, key=os.path.getmtime, reverse=True):
|
806 |
+
if media_file not in seen_files:
|
807 |
+
seen_files.add(media_file)
|
808 |
+
filename = os.path.basename(media_file)
|
809 |
+
vote_count = media_votes.get(media_file, 0)
|
810 |
+
col1, col2 = st.columns([3, 1])
|
811 |
+
with col1:
|
812 |
+
st.markdown(f"**{filename}**")
|
813 |
+
if media_file.endswith(('.png', '.jpg')):
|
814 |
+
st.image(media_file, use_container_width=True)
|
815 |
+
elif media_file.endswith('.mp4'):
|
816 |
+
st.markdown(await get_video_html(media_file), unsafe_allow_html=True)
|
817 |
+
elif media_file.endswith('.mp3'):
|
818 |
+
st.markdown(await get_audio_html(media_file), unsafe_allow_html=True)
|
819 |
+
with col2:
|
820 |
+
if st.button(f"๐ {vote_count}", key=f"media_vote_{media_file}"):
|
821 |
+
await save_vote(MEDIA_VOTES_FILE, media_file, await generate_user_hash(), st.session_state.username)
|
822 |
+
st.rerun()
|
823 |
+
|
824 |
+
st.subheader("Refresh โณ")
|
825 |
refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
|
826 |
st.session_state.refresh_rate = refresh_rate
|
827 |
timer_placeholder = st.empty()
|
828 |
for i in range(st.session_state.refresh_rate, -1, -1):
|
829 |
font_name, font_func = random.choice(UNICODE_FONTS)
|
830 |
countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
|
831 |
+
timer_placeholder.markdown(f"<p class='timer'>โณ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
|
832 |
+
time.sleep(1)
|
833 |
st.rerun()
|
834 |
|
835 |
+
st.sidebar.subheader("Chat History ๐")
|
836 |
+
with open(HISTORY_FILE, 'r') as f:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
837 |
history_content = f.read()
|
838 |
+
st.sidebar.markdown(history_content)
|
|
|
839 |
|
840 |
+
loop.run_until_complete(async_interface())
|
|
|
|
|
|
|
|
|
841 |
|
842 |
if __name__ == "__main__":
|
|
|
|
|
|
|
843 |
main()
|