awacke1 commited on
Commit
1a27f11
Β·
verified Β·
1 Parent(s): 28e044b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +567 -0
app.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import asyncio
3
+ import websockets
4
+ import uuid
5
+ import argparse
6
+ from datetime import datetime
7
+ import os
8
+ import random
9
+ import time
10
+ import hashlib
11
+ from PIL import Image
12
+ import glob
13
+ from urllib.parse import quote
14
+ import base64
15
+ import io
16
+ import streamlit.components.v1 as components
17
+ import edge_tts
18
+ from audio_recorder_streamlit import audio_recorder
19
+ import nest_asyncio
20
+ from streamlit_paste_button import paste_image_button
21
+
22
+ # Patch for nested async - sneaky fix! 🐍✨
23
+ nest_asyncio.apply()
24
+
25
+ # Static config - constants rule! πŸ“πŸ‘‘
26
+ icons = 'πŸ€–πŸ§ πŸ”¬πŸ“'
27
+ START_ROOM = "Sector 🌌"
28
+
29
+ # Page setup - dressing up the window! πŸ–ΌοΈπŸŽ€
30
+ st.set_page_config(
31
+ page_title="πŸ€–πŸ§ MMO Chat BrainπŸ“πŸ”¬",
32
+ page_icon=icons,
33
+ layout="wide",
34
+ initial_sidebar_state="auto"
35
+ )
36
+
37
+ # Funky usernames - who’s who in the zoo with unique voices! πŸŽ­πŸΎπŸŽ™οΈ
38
+ FUN_USERNAMES = {
39
+ "CosmicJester 🌌": "en-US-AriaNeural",
40
+ "PixelPanda 🐼": "en-US-JennyNeural",
41
+ "QuantumQuack πŸ¦†": "en-GB-SoniaNeural",
42
+ "StellarSquirrel 🐿️": "en-AU-NatashaNeural",
43
+ "GizmoGuru βš™οΈ": "en-CA-ClaraNeural",
44
+ "NebulaNinja 🌠": "en-US-GuyNeural",
45
+ "ByteBuster πŸ’Ύ": "en-GB-RyanNeural",
46
+ "GalacticGopher 🌍": "en-AU-WilliamNeural",
47
+ "RocketRaccoon πŸš€": "en-CA-LiamNeural",
48
+ "EchoElf 🧝": "en-US-AnaNeural",
49
+ "PhantomFox 🦊": "en-US-BrandonNeural",
50
+ "WittyWizard πŸ§™": "en-GB-ThomasNeural",
51
+ "LunarLlama πŸŒ™": "en-AU-FreyaNeural",
52
+ "SolarSloth β˜€οΈ": "en-CA-LindaNeural",
53
+ "AstroAlpaca πŸ¦™": "en-US-ChristopherNeural",
54
+ "CyberCoyote 🐺": "en-GB-ElliotNeural",
55
+ "MysticMoose 🦌": "en-AU-JamesNeural",
56
+ "GlitchGnome 🧚": "en-CA-EthanNeural",
57
+ "VortexViper 🐍": "en-US-AmberNeural",
58
+ "ChronoChimp πŸ’": "en-GB-LibbyNeural"
59
+ }
60
+
61
+ # Folders galore - organizing chaos! πŸ“‚πŸŒ€
62
+ CHAT_DIR = "chat_logs"
63
+ VOTE_DIR = "vote_logs"
64
+ STATE_FILE = "user_state.txt"
65
+ AUDIO_DIR = "audio_logs"
66
+ HISTORY_DIR = "history_logs"
67
+ MEDIA_DIR = "media_files"
68
+ os.makedirs(CHAT_DIR, exist_ok=True)
69
+ os.makedirs(VOTE_DIR, exist_ok=True)
70
+ os.makedirs(AUDIO_DIR, exist_ok=True)
71
+ os.makedirs(HISTORY_DIR, exist_ok=True)
72
+ os.makedirs(MEDIA_DIR, exist_ok=True)
73
+
74
+ CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
75
+ QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
76
+ MEDIA_VOTES_FILE = os.path.join(VOTE_DIR, "media_votes.md")
77
+ HISTORY_FILE = os.path.join(HISTORY_DIR, "chat_history.md")
78
+
79
+ # Fancy digits - numbers got style! πŸ”’πŸ’ƒ
80
+ UNICODE_DIGITS = {i: f"{i}\uFE0F⃣" for i in range(10)}
81
+
82
+ # Massive font collection - typography bonanza! πŸ–‹οΈπŸŽ¨
83
+ UNICODE_FONTS = [
84
+ ("Normal", lambda x: x),
85
+ ("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)),
86
+ ("Italic", lambda x: "".join(chr(ord(c) + 0x1D434 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D44E - 0x61) if 'a' <= c <= 'z' else c for c in x)),
87
+ ("Bold Italic", lambda x: "".join(chr(ord(c) + 0x1D468 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D482 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
88
+ ("Script", lambda x: "".join(chr(ord(c) + 0x1D49C - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D4B6 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
89
+ ("Bold Script", lambda x: "".join(chr(ord(c) + 0x1D4D0 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D4EA - 0x61) if 'a' <= c <= 'z' else c for c in x)),
90
+ ("Fraktur", lambda x: "".join(chr(ord(c) + 0x1D504 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D51E - 0x61) if 'a' <= c <= 'z' else c for c in x)),
91
+ ("Bold Fraktur", lambda x: "".join(chr(ord(c) + 0x1D56C - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D586 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
92
+ ("Double Struck", lambda x: "".join(chr(ord(c) + 0x1D538 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D552 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
93
+ ("Sans Serif", lambda x: "".join(chr(ord(c) + 0x1D5A0 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D5BA - 0x61) if 'a' <= c <= 'z' else c for c in x)),
94
+ ("Sans Serif Bold", lambda x: "".join(chr(ord(c) + 0x1D5D4 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D5EE - 0x61) if 'a' <= c <= 'z' else c for c in x)),
95
+ ("Sans Serif Italic", lambda x: "".join(chr(ord(c) + 0x1D608 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D622 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
96
+ ("Sans Serif Bold Italic", lambda x: "".join(chr(ord(c) + 0x1D63C - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D656 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
97
+ ("Monospace", lambda x: "".join(chr(ord(c) + 0x1D670 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D68A - 0x61) if 'a' <= c <= 'z' else c for c in x)),
98
+ ("Circled", lambda x: "".join(chr(ord(c) - 0x41 + 0x24B6) if 'A' <= c <= 'Z' else chr(ord(c) - 0x61 + 0x24D0) if 'a' <= c <= 'z' else c for c in x)),
99
+ ("Squared", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F130) if 'A' <= c <= 'Z' else c for c in x)),
100
+ ("Negative Circled", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F150) if 'A' <= c <= 'Z' else c for c in x)),
101
+ ("Negative Squared", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F170) if 'A' <= c <= 'Z' else c for c in x)),
102
+ ("Regional Indicator", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F1E6) if 'A' <= c <= 'Z' else c for c in x)),
103
+ ]
104
+
105
+ # Global state - keeping tabs! πŸŒπŸ“‹
106
+ if 'server_running' not in st.session_state:
107
+ st.session_state.server_running = False
108
+ if 'server_task' not in st.session_state:
109
+ st.session_state.server_task = None
110
+ if 'active_connections' not in st.session_state:
111
+ st.session_state.active_connections = {}
112
+ if 'media_notifications' not in st.session_state:
113
+ st.session_state.media_notifications = []
114
+ if 'last_chat_update' not in st.session_state:
115
+ st.session_state.last_chat_update = 0
116
+ if 'displayed_chat_lines' not in st.session_state:
117
+ st.session_state.displayed_chat_lines = []
118
+ if 'old_val' not in st.session_state:
119
+ st.session_state.old_val = ""
120
+ if 'last_query' not in st.session_state:
121
+ st.session_state.last_query = ""
122
+ if 'message_text' not in st.session_state:
123
+ st.session_state.message_text = ""
124
+ if 'audio_cache' not in st.session_state:
125
+ st.session_state.audio_cache = {}
126
+ if 'pasted_image_data' not in st.session_state:
127
+ st.session_state.pasted_image_data = None
128
+ if 'quote_line' not in st.session_state:
129
+ st.session_state.quote_line = None
130
+ if 'refresh_rate' not in st.session_state:
131
+ st.session_state.refresh_rate = 5 # Default refresh rate
132
+ if 'base64_cache' not in st.session_state:
133
+ st.session_state.base64_cache = {} # Cache for base64 strings
134
+
135
+ # Timestamp wizardry - clock ticks with flair! ⏰🎩
136
+ def format_timestamp_prefix(username):
137
+ now = datetime.now()
138
+ return f"{now.strftime('%I-%M-%p-ct-%m-%d-%Y')}-by-{username}"
139
+
140
+ # Node naming - christening the beast! 🌐🍼
141
+ def get_node_name():
142
+ parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
143
+ parser.add_argument('--node-name', type=str, default=None)
144
+ parser.add_argument('--port', type=int, default=8501)
145
+ args = parser.parse_args()
146
+ username = st.session_state.get('username', 'System 🌟')
147
+ log_action(username, "🌐🍼 - Node naming - christening the beast!")
148
+ return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
149
+
150
+ # Action logger - spying on deeds! πŸ•΅οΈπŸ“œ
151
+ def log_action(username, action):
152
+ if 'action_log' not in st.session_state:
153
+ st.session_state.action_log = {}
154
+ user_log = st.session_state.action_log.setdefault(username, {})
155
+ current_time = time.time()
156
+ user_log = {k: v for k, v in user_log.items() if current_time - v < 10}
157
+ st.session_state.action_log[username] = user_log
158
+ if action not in user_log:
159
+ with open(HISTORY_FILE, 'a') as f:
160
+ f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n")
161
+ user_log[action] = current_time
162
+
163
+ # Clean text - strip the fancy stuff! πŸ§ΉπŸ“
164
+ def clean_text_for_tts(text):
165
+ cleaned = re.sub(r'[#*!\[\]]+', '', text)
166
+ cleaned = ' '.join(cleaned.split())
167
+ return cleaned[:200] if cleaned else "No text to speak"
168
+
169
+ # Chat saver - words locked tight! πŸ’¬πŸ”’
170
+ async def save_chat_entry(username, message):
171
+ await asyncio.to_thread(log_action, username, "πŸ’¬πŸ”’ - Chat saver - words locked tight!")
172
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Keep this for log consistency
173
+ entry = f"[{timestamp}] {username}: {message}"
174
+ await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"{entry}\n"))
175
+ voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
176
+ cleaned_message = clean_text_for_tts(message)
177
+ audio_file = await async_edge_tts_generate(cleaned_message, voice)
178
+ if audio_file:
179
+ with open(HISTORY_FILE, 'a') as f:
180
+ f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
181
+ await broadcast_message(f"{username}|{message}", "chat")
182
+ st.session_state.last_chat_update = time.time()
183
+
184
+ # Chat loader - history unleashed! πŸ“œπŸš€
185
+ async def load_chat():
186
+ username = st.session_state.get('username', 'System 🌟')
187
+ await asyncio.to_thread(log_action, username, "πŸ“œπŸš€ - Chat loader - history unleashed!")
188
+ if not os.path.exists(CHAT_FILE):
189
+ await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub - start chatting! 🎀\n"))
190
+ with open(CHAT_FILE, 'r') as f:
191
+ content = await asyncio.to_thread(f.read)
192
+ return content
193
+
194
+ # User lister - who’s in the gang! πŸ‘₯πŸŽ‰
195
+ async def get_user_list(chat_content):
196
+ username = st.session_state.get('username', 'System 🌟')
197
+ await asyncio.to_thread(log_action, username, "πŸ‘₯πŸŽ‰ - User lister - who’s in the gang!")
198
+ users = set()
199
+ for line in chat_content.split('\n'):
200
+ if line.strip() and ': ' in line:
201
+ user = line.split(': ')[1].split(' ')[0]
202
+ users.add(user)
203
+ return sorted(list(users))
204
+
205
+ # Join checker - been here before? πŸšͺπŸ”
206
+ async def has_joined_before(client_id, chat_content):
207
+ username = st.session_state.get('username', 'System 🌟')
208
+ await asyncio.to_thread(log_action, username, "πŸšͺπŸ” - Join checker - been here before?")
209
+ return any(f"Client-{client_id}" in line for line in chat_content.split('\n'))
210
+
211
+ # Suggestion maker - old quips resurface! πŸ’‘πŸ“
212
+ async def get_message_suggestions(chat_content, prefix):
213
+ username = st.session_state.get('username', 'System 🌟')
214
+ await asyncio.to_thread(log_action, username, "πŸ’‘πŸ“ - Suggestion maker - old quips resurface!")
215
+ lines = chat_content.split('\n')
216
+ messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
217
+ return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5]
218
+
219
+ # Vote saver - cheers recorded! πŸ‘πŸ“Š
220
+ async def save_vote(file, item, user_hash, username, comment=""):
221
+ await asyncio.to_thread(log_action, username, "πŸ‘πŸ“Š - Vote saver - cheers recorded!")
222
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
223
+ entry = f"[{timestamp}] {user_hash} voted for {item}"
224
+ await asyncio.to_thread(lambda: open(file, 'a').write(f"{entry}\n"))
225
+ await asyncio.to_thread(lambda: open(HISTORY_FILE, "a").write(f"- {timestamp} - User {user_hash} voted for {item}\n"))
226
+ chat_message = f"{username} upvoted: \"{item}\""
227
+ if comment:
228
+ chat_message += f" - {comment}"
229
+ await save_chat_entry(username, chat_message)
230
+
231
+ # Vote counter - tallying the love! πŸ†πŸ“ˆ
232
+ async def load_votes(file):
233
+ username = st.session_state.get('username', 'System 🌟')
234
+ await asyncio.to_thread(log_action, username, "πŸ†πŸ“ˆ - Vote counter - tallying the love!")
235
+ if not os.path.exists(file):
236
+ await asyncio.to_thread(lambda: open(file, 'w').write("# Vote Tally\n\nNo votes yet - get clicking! πŸ–±οΈ\n"))
237
+ with open(file, 'r') as f:
238
+ content = await asyncio.to_thread(f.read)
239
+ lines = content.strip().split('\n')[2:]
240
+ votes = {}
241
+ user_votes = set()
242
+ for line in lines:
243
+ if line.strip() and 'voted for' in line:
244
+ user_hash = line.split('] ')[1].split(' voted for ')[0]
245
+ item = line.split('voted for ')[1]
246
+ vote_key = f"{user_hash}-{item}"
247
+ if vote_key not in user_votes:
248
+ votes[item] = votes.get(item, 0) + 1
249
+ user_votes.add(vote_key)
250
+ return votes
251
+
252
+ # Hash generator - secret codes ahoy! πŸ”‘πŸ•΅οΈ
253
+ async def generate_user_hash():
254
+ username = st.session_state.get('username', 'System 🌟')
255
+ await asyncio.to_thread(log_action, username, "πŸ”‘πŸ•΅οΈ - Hash generator - secret codes ahoy!")
256
+ if 'user_hash' not in st.session_state:
257
+ st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8]
258
+ return st.session_state.user_hash
259
+
260
+ # Audio maker - voices come alive! 🎢🌟
261
+ async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
262
+ username = st.session_state.get('username', 'System 🌟')
263
+ await asyncio.to_thread(log_action, username, "🎢🌟 - Audio maker - voices come alive!")
264
+ timestamp = format_timestamp_prefix(username)
265
+ filename = f"{timestamp}.{file_format}"
266
+ filepath = os.path.join(AUDIO_DIR, filename)
267
+ communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
268
+ try:
269
+ await communicate.save(filepath)
270
+ return filepath if os.path.exists(filepath) else None
271
+ except edge_tts.exceptions.NoAudioReceived:
272
+ with open(HISTORY_FILE, 'a') as f:
273
+ f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {username}: Audio failed - No audio received for '{text}'\n")
274
+ return None
275
+
276
+ # Audio player - tunes blast off! πŸ”ŠπŸš€
277
+ def play_and_download_audio(file_path):
278
+ if file_path and os.path.exists(file_path):
279
+ st.audio(file_path)
280
+ if file_path not in st.session_state.base64_cache:
281
+ with open(file_path, "rb") as f:
282
+ b64 = base64.b64encode(f.read()).decode()
283
+ st.session_state.base64_cache[file_path] = b64
284
+ b64 = st.session_state.base64_cache[file_path]
285
+ dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">🎡 Download {os.path.basename(file_path)}</a>'
286
+ st.markdown(dl_link, unsafe_allow_html=True)
287
+
288
+ # Image saver - pics preserved with naming! πŸ“ΈπŸ’Ύ
289
+ async def save_pasted_image(image, username):
290
+ await asyncio.to_thread(log_action, username, "πŸ“ΈπŸ’Ύ - Image saver - pics preserved!")
291
+ timestamp = format_timestamp_prefix(username)
292
+ filename = f"{timestamp}.png"
293
+ filepath = os.path.join(MEDIA_DIR, filename)
294
+ await asyncio.to_thread(image.save, filepath, "PNG")
295
+ return filepath
296
+
297
+ # Video renderer - movies roll with autoplay! πŸŽ₯🎬
298
+ async def get_video_html(video_path, width="100%"):
299
+ username = st.session_state.get('username', 'System 🌟')
300
+ await asyncio.to_thread(log_action, username, "πŸŽ₯🎬 - Video renderer - movies roll!")
301
+ with open(video_path, 'rb') as f:
302
+ video_data = await asyncio.to_thread(f.read)
303
+ video_url = f"data:video/mp4;base64,{base64.b64encode(video_data).decode()}"
304
+ return f'<video width="{width}" controls autoplay><source src="{video_url}" type="video/mp4">Your browser does not support the video tag.</video>'
305
+
306
+ # Audio renderer - sounds soar! 🎢✈️
307
+ async def get_audio_html(audio_path, width="100%"):
308
+ username = st.session_state.get('username', 'System 🌟')
309
+ await asyncio.to_thread(log_action, username, "🎢✈️ - Audio renderer - sounds soar!")
310
+ audio_url = f"data:audio/mpeg;base64,{base64.b64encode(await asyncio.to_thread(open, audio_path, 'rb').read()).decode()}"
311
+ return f'<audio controls style="width: {width};"><source src="{audio_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>'
312
+
313
+ # Websocket handler - chat links up! πŸŒπŸ”—
314
+ async def websocket_handler(websocket, path):
315
+ username = st.session_state.get('username', 'System 🌟')
316
+ await asyncio.to_thread(log_action, username, "πŸŒπŸ”— - Websocket handler - chat links up!")
317
+ try:
318
+ client_id = str(uuid.uuid4())
319
+ room_id = "chat"
320
+ st.session_state.active_connections.setdefault(room_id, {})[client_id] = websocket
321
+ chat_content = await load_chat()
322
+ username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
323
+ if not await has_joined_before(client_id, chat_content):
324
+ await save_chat_entry(f"Client-{client_id}", f"{username} has joined {START_ROOM}!")
325
+ async for message in websocket:
326
+ parts = message.split('|', 1)
327
+ if len(parts) == 2:
328
+ username, content = parts
329
+ await save_chat_entry(username, content)
330
+ except websockets.ConnectionClosed:
331
+ pass
332
+ finally:
333
+ if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
334
+ del st.session_state.active_connections[room_id][client_id]
335
+
336
+ # Message broadcaster - words fly far! πŸ“’βœˆοΈ
337
+ async def broadcast_message(message, room_id):
338
+ username = st.session_state.get('username', 'System 🌟')
339
+ await asyncio.to_thread(log_action, username, "πŸ“’βœˆοΈ - Message broadcaster - words fly far!")
340
+ if room_id in st.session_state.active_connections:
341
+ disconnected = []
342
+ for client_id, ws in st.session_state.active_connections[room_id].items():
343
+ try:
344
+ await ws.send(message)
345
+ except websockets.ConnectionClosed:
346
+ disconnected.append(client_id)
347
+ for client_id in disconnected:
348
+ del st.session_state.active_connections[room_id][client_id]
349
+
350
+ # Server starter - web spins up! πŸ–₯οΈπŸŒ€
351
+ async def run_websocket_server():
352
+ username = st.session_state.get('username', 'System 🌟')
353
+ await asyncio.to_thread(log_action, username, "πŸ–₯οΈπŸŒ€ - Server starter - web spins up!")
354
+ if not st.session_state.server_running:
355
+ server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
356
+ st.session_state.server_running = True
357
+ await server.wait_closed()
358
+
359
+ # Voice processor - speech to text! πŸŽ€πŸ“
360
+ async def process_voice_input(audio_bytes):
361
+ username = st.session_state.get('username', 'System 🌟')
362
+ await asyncio.to_thread(log_action, username, "πŸŽ€πŸ“ - Voice processor - speech to text!")
363
+ if audio_bytes:
364
+ text = "Voice input simulation"
365
+ await save_chat_entry(username, text)
366
+
367
+ # Dummy AI lookup function (replace with actual implementation)
368
+ async def perform_ai_lookup(query, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False, useArxiv=True, useArxivAudio=False):
369
+ username = st.session_state.get('username', 'System 🌟')
370
+ result = f"AI Lookup Result for '{query}' (Arxiv: {useArxiv}, Audio: {useArxivAudio})"
371
+ await save_chat_entry(username, result)
372
+ if useArxivAudio:
373
+ audio_file = await async_edge_tts_generate(result, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
374
+ if audio_file:
375
+ st.audio(audio_file)
376
+
377
+ # Main execution - let’s roll! πŸŽ²πŸš€
378
+ def main():
379
+ NODE_NAME, port = get_node_name()
380
+
381
+ loop = asyncio.new_event_loop()
382
+ asyncio.set_event_loop(loop)
383
+
384
+ async def async_interface():
385
+ if 'username' not in st.session_state:
386
+ chat_content = await load_chat()
387
+ available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
388
+ st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
389
+
390
+ st.title(f"πŸ€–πŸ§ MMO {st.session_state.username}πŸ“πŸ”¬")
391
+ st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! πŸŽ‰")
392
+
393
+ if not st.session_state.server_task:
394
+ st.session_state.server_task = loop.create_task(run_websocket_server())
395
+
396
+ audio_bytes = audio_recorder()
397
+ if audio_bytes:
398
+ await process_voice_input(audio_bytes)
399
+ st.rerun()
400
+
401
+ # Load and display chat
402
+ st.subheader(f"{START_ROOM} Chat πŸ’¬")
403
+ chat_content = await load_chat()
404
+ chat_lines = chat_content.split('\n')
405
+ chat_votes = await load_votes(QUOTE_VOTES_FILE)
406
+
407
+ current_time = time.time()
408
+ if current_time - st.session_state.last_chat_update > 1 or not st.session_state.displayed_chat_lines:
409
+ 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('#')]
410
+ st.session_state.displayed_chat_lines.extend(new_lines)
411
+ st.session_state.last_chat_update = current_time
412
+
413
+ for i, line in enumerate(st.session_state.displayed_chat_lines):
414
+ col1, col2, col3, col4 = st.columns([3, 1, 1, 2])
415
+ with col1:
416
+ st.markdown(line)
417
+ if "Pasted image:" in line or "Uploaded media:" in line:
418
+ file_path = line.split(': ')[-1].strip()
419
+ if os.path.exists(file_path):
420
+ if file_path not in st.session_state.base64_cache:
421
+ with open(file_path, "rb") as f:
422
+ b64 = base64.b64encode(f.read()).decode()
423
+ st.session_state.base64_cache[file_path] = b64
424
+ b64 = st.session_state.base64_cache[file_path]
425
+ mime_type = "image/png" if file_path.endswith(('.png', '.jpg')) else "video/mp4" if file_path.endswith('.mp4') else "audio/mpeg"
426
+ if file_path.endswith(('.png', '.jpg')):
427
+ st.image(file_path, use_container_width=True)
428
+ dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">πŸ“₯ Download {os.path.basename(file_path)}</a>'
429
+ st.markdown(dl_link, unsafe_allow_html=True)
430
+ elif file_path.endswith('.mp4'):
431
+ st.markdown(await get_video_html(file_path), unsafe_allow_html=True)
432
+ dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">πŸ“₯ Download {os.path.basename(file_path)}</a>'
433
+ st.markdown(dl_link, unsafe_allow_html=True)
434
+ elif file_path.endswith('.mp3'):
435
+ st.markdown(await get_audio_html(file_path), unsafe_allow_html=True)
436
+ dl_link = f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">πŸ“₯ Download {os.path.basename(file_path)}</a>'
437
+ st.markdown(dl_link, unsafe_allow_html=True)
438
+ with col2:
439
+ vote_count = chat_votes.get(line.split('. ')[1] if '. ' in line else line, 0)
440
+ if st.button(f"πŸ‘ {vote_count}", key=f"chat_vote_{i}"):
441
+ comment = st.session_state.message_text
442
+ await save_vote(QUOTE_VOTES_FILE, line.split('. ')[1] if '. ' in line else line, await generate_user_hash(), st.session_state.username, comment)
443
+ st.session_state.message_text = ''
444
+ st.rerun()
445
+ with col3:
446
+ if st.button("πŸ“’ Quote", key=f"quote_{i}"):
447
+ st.session_state.quote_line = line
448
+ st.rerun()
449
+ with col4:
450
+ username = line.split(': ')[1].split(' ')[0]
451
+ cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
452
+ if cache_key not in st.session_state.audio_cache:
453
+ cleaned_text = clean_text_for_tts(line.split(': ', 1)[1])
454
+ audio_file = await async_edge_tts_generate(cleaned_text, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
455
+ st.session_state.audio_cache[cache_key] = audio_file
456
+ audio_file = st.session_state.audio_cache.get(cache_key)
457
+ if audio_file:
458
+ play_and_download_audio(audio_file)
459
+
460
+ if st.session_state.quote_line:
461
+ st.markdown(f"### Quoting: {st.session_state.quote_line}")
462
+ quote_response = st.text_area("Add your response", key="quote_response")
463
+ paste_result_quote = paste_image_button("πŸ“‹ Paste Image with Quote", key="paste_button_quote")
464
+ if paste_result_quote.image_data is not None:
465
+ st.image(paste_result_quote.image_data, caption="Received Image for Quote")
466
+ filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
467
+ if filename:
468
+ st.session_state.pasted_image_data = filename # Store for use in quote submission
469
+ if st.button("Send Quote πŸš€", key="send_quote"):
470
+ markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
471
+ if st.session_state.pasted_image_data:
472
+ markdown_response += f"\n- **Image**: ![Pasted Image]({st.session_state.pasted_image_data})"
473
+ await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
474
+ st.session_state.pasted_image_data = None
475
+ await save_chat_entry(st.session_state.username, markdown_response)
476
+ st.session_state.quote_line = None
477
+ st.session_state.message_text = ''
478
+ st.rerun()
479
+
480
+ new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
481
+ if new_username and new_username != st.session_state.username:
482
+ await save_chat_entry("System 🌟", f"{st.session_state.username} changed name to {new_username}")
483
+ st.session_state.username = new_username
484
+ st.rerun()
485
+
486
+ 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))
487
+ paste_result_msg = paste_image_button("πŸ“‹ Paste Image with Message", key="paste_button_msg")
488
+ if paste_result_msg.image_data is not None:
489
+ st.image(paste_result_msg.image_data, caption="Received Image for Message")
490
+ filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
491
+ if filename:
492
+ st.session_state.pasted_image_data = filename # Store for use in message submission
493
+ if st.button("Send πŸš€", key="send_button") and (message.strip() or st.session_state.pasted_image_data):
494
+ if message.strip():
495
+ await save_chat_entry(st.session_state.username, message)
496
+ if st.session_state.pasted_image_data:
497
+ await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}")
498
+ st.session_state.pasted_image_data = None
499
+ st.session_state.message_text = ''
500
+ st.rerun()
501
+
502
+ # Main action tabs and model use choices
503
+ tab_main = st.radio("Action:", ["🎀 Voice", "πŸ“Έ Media", "πŸ” ArXiv", "πŸ“ Editor"], horizontal=True)
504
+ useArxiv = st.checkbox("Search Arxiv for Research Paper Answers", value=True)
505
+ useArxivAudio = st.checkbox("Generate Audio File for Research Paper Answers", value=False)
506
+
507
+ # Enhanced Media Gallery with Image, Audio, Video
508
+ st.subheader("Upload Media 🎨🎢πŸŽ₯")
509
+ uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3'])
510
+ if uploaded_file:
511
+ timestamp = format_timestamp_prefix(st.session_state.username)
512
+ username = st.session_state.username
513
+ ext = uploaded_file.name.split('.')[-1]
514
+ filename = f"{timestamp}.{ext}"
515
+ file_path = os.path.join(MEDIA_DIR, filename)
516
+ await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
517
+ st.success(f"Uploaded {filename}")
518
+ await save_chat_entry(username, f"Uploaded media: {file_path}")
519
+ if file_path.endswith('.mp4'):
520
+ st.session_state.media_notifications.append(file_path)
521
+
522
+ st.subheader("Media Gallery 🎨🎢πŸŽ₯")
523
+ 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")
524
+ if media_files:
525
+ media_votes = await load_votes(MEDIA_VOTES_FILE)
526
+ st.write("### All Media Uploads")
527
+ seen_files = set() # Track unique file paths to prevent duplicates
528
+ for media_file in sorted(media_files, key=os.path.getmtime, reverse=True):
529
+ if media_file not in seen_files: # Only add if not already seen
530
+ seen_files.add(media_file)
531
+ filename = os.path.basename(media_file)
532
+ vote_count = media_votes.get(media_file, 0)
533
+
534
+ col1, col2 = st.columns([3, 1])
535
+ with col1:
536
+ st.markdown(f"**{filename}**")
537
+ if media_file.endswith(('.png', '.jpg')):
538
+ st.image(media_file, use_container_width=True)
539
+ elif media_file.endswith('.mp4'):
540
+ st.markdown(await get_video_html(media_file), unsafe_allow_html=True)
541
+ elif media_file.endswith('.mp3'):
542
+ st.markdown(await get_audio_html(media_file), unsafe_allow_html=True)
543
+ with col2:
544
+ if st.button(f"πŸ‘ {vote_count}", key=f"media_vote_{media_file}"):
545
+ await save_vote(MEDIA_VOTES_FILE, media_file, await generate_user_hash(), st.session_state.username)
546
+ st.rerun()
547
+
548
+ st.subheader("Refresh ⏳")
549
+ refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
550
+ st.session_state.refresh_rate = refresh_rate
551
+ timer_placeholder = st.empty()
552
+ for i in range(st.session_state.refresh_rate, -1, -1):
553
+ font_name, font_func = random.choice(UNICODE_FONTS)
554
+ countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
555
+ timer_placeholder.markdown(f"<p class='timer'>⏳ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
556
+ time.sleep(1) # Use synchronous sleep
557
+ st.rerun()
558
+
559
+ st.sidebar.subheader("Chat History πŸ“œ")
560
+ with open(HISTORY_FILE, 'r') as f:
561
+ history_content = f.read()
562
+ st.sidebar.markdown(history_content)
563
+
564
+ loop.run_until_complete(async_interface())
565
+
566
+ if __name__ == "__main__":
567
+ main()