File size: 26,194 Bytes
34fcd26
00dbb5f
 
 
 
 
 
34fcd26
00dbb5f
34fcd26
 
 
 
 
 
 
 
 
 
0331b3d
34fcd26
 
 
 
 
 
 
 
 
 
 
 
 
00dbb5f
 
34fcd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0331b3d
00dbb5f
34fcd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0331b3d
25c5d30
34fcd26
 
 
 
00dbb5f
34fcd26
 
25c5d30
34fcd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb41de1
34fcd26
 
 
 
 
 
 
 
 
 
 
 
 
 
00dbb5f
34fcd26
 
 
00dbb5f
 
34fcd26
 
 
 
00dbb5f
34fcd26
 
00dbb5f
34fcd26
 
 
 
00dbb5f
 
34fcd26
 
 
 
 
 
 
 
 
 
00dbb5f
34fcd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0331b3d
 
34fcd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00dbb5f
 
34fcd26
 
 
 
 
 
 
 
 
00dbb5f
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import streamlit as st
import asyncio
import websockets
import uuid
import argparse
from datetime import datetime
import os
import random
import time
import hashlib
from PIL import Image
import glob
from urllib.parse import quote
import base64
import io
import streamlit.components.v1 as components
import edge_tts
from audio_recorder_streamlit import audio_recorder
import nest_asyncio

# Apply patch to allow nested asyncio.run() calls
nest_asyncio.apply()

# Initial App Configuration (static)
icons = '๐Ÿค–๐Ÿง ๐Ÿ”ฌ๐Ÿ“'
START_ROOM = "Sector ๐ŸŒŒ"

# Set page config once at the top
st.set_page_config(
    page_title="๐Ÿค–๐Ÿง MMO Chat Brain๐Ÿ“๐Ÿ”ฌ",  # Initial static title
    page_icon=icons,
    layout="wide",
    initial_sidebar_state="auto"
)

# Fun usernames with emojis and their paired voices
FUN_USERNAMES = {
    "CosmicJester ๐ŸŒŒ": "en-US-AriaNeural",
    "PixelPanda ๐Ÿผ": "en-US-JennyNeural",
    "QuantumQuack ๐Ÿฆ†": "en-GB-SoniaNeural",
    "StellarSquirrel ๐Ÿฟ๏ธ": "en-AU-NatashaNeural",
    "GizmoGuru โš™๏ธ": "en-CA-ClaraNeural",
    "NebulaNinja ๐ŸŒ ": "en-US-GuyNeural",
    "ByteBuster ๐Ÿ’พ": "en-GB-RyanNeural",
    "GalacticGopher ๐ŸŒ": "en-AU-WilliamNeural",
    "RocketRaccoon ๐Ÿš€": "en-CA-LiamNeural",
    "EchoElf ๐Ÿง": "en-US-AriaNeural",
    "PhantomFox ๐ŸฆŠ": "en-US-JennyNeural",
    "WittyWizard ๐Ÿง™": "en-GB-SoniaNeural",
    "LunarLlama ๐ŸŒ™": "en-AU-NatashaNeural",
    "SolarSloth โ˜€๏ธ": "en-CA-ClaraNeural",
    "AstroAlpaca ๐Ÿฆ™": "en-US-GuyNeural",
    "CyberCoyote ๐Ÿบ": "en-GB-RyanNeural",
    "MysticMoose ๐ŸฆŒ": "en-AU-WilliamNeural",
    "GlitchGnome ๐Ÿงš": "en-CA-LiamNeural",
    "VortexViper ๐Ÿ": "en-US-AriaNeural",
    "ChronoChimp ๐Ÿ’": "en-US-JennyNeural"
}

# Directories and files
CHAT_DIR = "chat_logs"
VOTE_DIR = "vote_logs"
STATE_FILE = "user_state.txt"
AUDIO_DIR = "audio_logs"
HISTORY_DIR = "history_logs"
os.makedirs(CHAT_DIR, exist_ok=True)
os.makedirs(VOTE_DIR, exist_ok=True)
os.makedirs(AUDIO_DIR, exist_ok=True)
os.makedirs(HISTORY_DIR, exist_ok=True)

CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
MEDIA_VOTES_FILE = os.path.join(VOTE_DIR, "media_votes.md")
HISTORY_FILE = os.path.join(HISTORY_DIR, "chat_history.md")

# Unicode digits and fonts
UNICODE_DIGITS = {i: f"{i}\uFE0Fโƒฃ" for i in range(10)}
UNICODE_FONTS = [
    ("Normal", lambda x: x),
    ("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)),
]

server_running = False
server_task = None

# Helper Functions
def format_timestamp_prefix():
    """๐Ÿ“… - Time Stamp Champ - Marks the clock, no flop!"""
    return datetime.now().strftime("%Y%m%d_%H%M%S")

def get_node_name():
    """๐ŸŒ - Naming Node with Code - Spins a name, oh so bold!"""
    action = "๐ŸŒ - Naming Node with Code - Spins a name, oh so bold!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    log_action(username, action)
    parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
    parser.add_argument('--node-name', type=str, default=None)
    parser.add_argument('--port', type=int, default=8501)
    args = parser.parse_args()
    return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port

def log_action(username, action):
    """๐Ÿ“œ - Log Jog Blog - Tracks the deed, no greed!"""
    if 'action_log' not in st.session_state:
        st.session_state.action_log = {}
    user_log = st.session_state.action_log.setdefault(username, {})
    current_time = time.time()
    user_log = {k: v for k, v in user_log.items() if current_time - v < 10}
    st.session_state.action_log[username] = user_log
    if action not in user_log:
        with open(HISTORY_FILE, 'a') as f:
            f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n")
        user_log[action] = current_time

async def save_chat_entry(username, message):
    """๐Ÿ“ - Chat Snap Trap - Logs your yap, no cap! โœ๏ธ๐Ÿง """
    action = "๐Ÿ“ - Chat Snap Trap - Logs your yap, no cap! โœ๏ธ๐Ÿง "
    await asyncio.to_thread(log_action, username, action)
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entry = f"[{timestamp}] {username}: {message}"
    await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"{entry}\n"))
    # Generate and save audio for the message
    voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
    audio_file = await async_edge_tts_generate(message, voice)
    if audio_file:
        with open(HISTORY_FILE, 'a') as f:
            f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")

async def load_chat():
    """๐Ÿ“– - Chat Fetch Quest - Grabs the log, no jest!"""
    action = "๐Ÿ“– - Chat Fetch Quest - Grabs the log, no jest!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    if not os.path.exists(CHAT_FILE):
        await asyncio.to_thread(lambda: open(CHAT_FILE, 'w').write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub - start chatting! ๐ŸŽค\n"))
    with open(CHAT_FILE, 'r') as f:
        content = await asyncio.to_thread(f.read)
    return content

async def get_user_list(chat_content):
    """๐Ÿ‘ฅ - Crew Clue Brew - Spots whoโ€™s who in the crew!"""
    action = "๐Ÿ‘ฅ - Crew Clue Brew - Spots whoโ€™s who in the crew!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    users = set()
    for line in chat_content.split('\n'):
        if line.strip() and ': ' in line:
            user = line.split(': ')[1].split(' ')[0]
            users.add(user)
    return sorted(list(users))

async def has_joined_before(client_id, chat_content):
    """๐Ÿšช - Join Check Trek - Sees whoโ€™s back, no wreck!"""
    action = "๐Ÿšช - Join Check Trek - Sees whoโ€™s back, no wreck!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    return any(f"Client-{client_id} has joined" in line for line in chat_content.split('\n'))

async def get_message_suggestions(chat_content, prefix):
    """๐Ÿ” - Suggest Jest Chest - Finds old quips, the best!"""
    action = "๐Ÿ” - Suggest Jest Chest - Finds old quips, the best!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    lines = chat_content.split('\n')
    messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
    return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5]

async def save_vote(file, item, user_hash, username, comment=""):
    """๐Ÿ‘ - Vote Note Float - Cheers rise, we gloat!"""
    action = "๐Ÿ‘ - Vote Note Float - Cheers rise, we gloat!"
    await asyncio.to_thread(log_action, username, action)
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entry = f"[{timestamp}] {user_hash} voted for {item}"
    await asyncio.to_thread(lambda: open(file, 'a').write(f"{entry}\n"))
    await asyncio.to_thread(lambda: open(HISTORY_FILE, "a").write(f"- {timestamp} - User {user_hash} voted for {item}\n"))
    chat_message = f"{username} upvoted: \"{item}\""
    if comment:
        chat_message += f" - {comment}"
    await save_chat_entry(username, chat_message)

async def load_votes(file):
    """๐Ÿ† - Tally Rally Call - Counts the cheers, no stall!"""
    action = "๐Ÿ† - Tally Rally Call - Counts the cheers, no stall!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    if not os.path.exists(file):
        await asyncio.to_thread(lambda: open(file, 'w').write("# Vote Tally\n\nNo votes yet - get clicking! ๐Ÿ–ฑ๏ธ\n"))
    with open(file, 'r') as f:
        lines = await asyncio.to_thread(f.read.strip().split, '\n')[2:]
    votes = {}
    user_votes = set()
    for line in lines:
        if line.strip() and 'voted for' in line:
            user_hash = line.split('] ')[1].split(' voted for ')[0]
            item = line.split('voted for ')[1]
            vote_key = f"{user_hash}-{item}"
            if vote_key not in user_votes:
                votes[item] = votes.get(item, 0) + 1
                user_votes.add(vote_key)
    return votes

async def generate_user_hash():
    """๐Ÿ”‘ - Hash Dash Bash - Crafts a code, so brash!"""
    action = "๐Ÿ”‘ - Hash Dash Bash - Crafts a code, so brash!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    if 'user_hash' not in st.session_state:
        st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8]
    return st.session_state.user_hash

async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
    """๐ŸŽถ - Tune Moon Boom - Drops a beat, so groom!"""
    action = "๐ŸŽถ - Tune Moon Boom - Drops a beat, so groom!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    timestamp = format_timestamp_prefix()
    filename = os.path.join(AUDIO_DIR, f"audio_{timestamp}_{random.randint(1000, 9999)}.mp3")
    communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
    await communicate.save(filename)
    return filename if os.path.exists(filename) else None

def play_and_download_audio(file_path):
    """๐Ÿ”Š - Sound Pound Ground - Plays it loud, all around!"""
    if file_path and os.path.exists(file_path):
        st.audio(file_path)
        with open(file_path, "rb") as f:
            b64 = base64.b64encode(f.read()).decode()
        dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">๐ŸŽต Download {os.path.basename(file_path)}</a>'
        st.markdown(dl_link, unsafe_allow_html=True)

async def save_pasted_image(image_data):
    """๐Ÿ“ธ - Snap Cap Trap - Saves your pic, no flap!"""
    action = "๐Ÿ“ธ - Snap Cap Trap - Saves your pic, no flap!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    timestamp = format_timestamp_prefix()
    filename = f"paste_{timestamp}.png"
    filepath = os.path.join('./', filename)
    if ',' in image_data:
        image_data = image_data.split(',')[1]
    img_bytes = base64.b64decode(image_data)
    img = Image.open(io.BytesIO(img_bytes))
    await asyncio.to_thread(img.save, filepath, "PNG")
    return filename

async def get_video_html(video_path, width="100%"):
    """๐ŸŽฅ - Reel Deal Steal - Plays your flick, so real!"""
    action = "๐ŸŽฅ - Reel Deal Steal - Plays your flick, so real!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    video_url = f"data:video/mp4;base64,{base64.b64encode(await asyncio.to_thread(open, video_path, 'rb').read()).decode()}"
    return f'<video width="{width}" controls autoplay muted loop><source src="{video_url}" type="video/mp4">Your browser does not support the video tag.</video>'

async def get_audio_html(audio_path, width="100%"):
    """๐ŸŽถ - Tune Moon Boom - Drops a beat, so groom!"""
    action = "๐ŸŽถ - Tune Moon Boom - Drops a beat, so groom!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    audio_url = f"data:audio/mpeg;base64,{base64.b64encode(await asyncio.to_thread(open, audio_path, 'rb').read()).decode()}"
    return f'<audio controls style="width: {width};"><source src="{audio_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>'

active_connections = {}

async def websocket_handler(websocket, path):
    """๐ŸŒ - Web Sock Jock - Links the chat, no block!"""
    action = "๐ŸŒ - Web Sock Jock - Links the chat, no block!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    try:
        client_id = str(uuid.uuid4())
        room_id = "chat"
        active_connections.setdefault(room_id, {})[client_id] = websocket
        chat_content = await load_chat()
        username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
        if not await has_joined_before(client_id, chat_content):
            await save_chat_entry(f"Client-{client_id}", f"{username} has joined {START_ROOM}!")
        async for message in websocket:
            parts = message.split('|', 1)
            if len(parts) == 2:
                username, content = parts
                await save_chat_entry(username, content)
                await broadcast_message(f"{username}|{content}", room_id)
    except websockets.ConnectionClosed:
        pass
    finally:
        if room_id in active_connections and client_id in active_connections[room_id]:
            del active_connections[room_id][client_id]

async def broadcast_message(message, room_id):
    """๐Ÿ“ข - Shout Out Bout - Blasts the word, no doubt!"""
    action = "๐Ÿ“ข - Shout Out Bout - Blasts the word, no doubt!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    if room_id in active_connections:
        disconnected = []
        for client_id, ws in active_connections[room_id].items():
            try:
                await ws.send(message)
            except websockets.ConnectionClosed:
                disconnected.append(client_id)
        for client_id in disconnected:
            del active_connections[room_id][client_id]

async def run_websocket_server():
    """๐Ÿ–ฅ๏ธ - Server Ferver Verve - Spins the web, with nerve!"""
    action = "๐Ÿ–ฅ๏ธ - Server Ferver Verve - Spins the web, with nerve!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    global server_running, server_task
    if not server_running:
        server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
        server_running = True
        await server.wait_closed()

async def process_voice_input(audio_bytes):
    """๐ŸŽค - Voice Choice Rejoice - Speaks your mind, oh boy!"""
    action = "๐ŸŽค - Voice Choice Rejoice - Speaks your mind, oh boy!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    if audio_bytes:
        # Simple placeholder for speech-to-text (requires additional library like `speech_recognition`)
        # For now, we'll simulate text input from audio
        text = "Voice input simulation"  # Replace with actual speech-to-text logic
        await save_chat_entry(username, text)

async def create_streamlit_interface():
    """๐ŸŽจ - UI Brew Crew - Builds the view, so new!"""
    action = "๐ŸŽจ - UI Brew Crew - Builds the view, so new!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)

    if 'username' not in st.session_state:
        chat_content = await load_chat()
        available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
        st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))

    if 'refresh_rate' not in st.session_state:
        st.session_state.refresh_rate = 5
    if 'timer_start' not in st.session_state:
        st.session_state.timer_start = time.time()
    if 'quote_line' not in st.session_state:
        st.session_state.quote_line = None
    if 'pasted_image_data' not in st.session_state:
        st.session_state.pasted_image_data = None
    if 'message_text' not in st.session_state:
        st.session_state.message_text = ""
    if 'audio_cache' not in st.session_state:
        st.session_state.audio_cache = {}
    if 'chat_history' not in st.session_state:
        st.session_state.chat_history = []

    st.markdown("""
        <style>
        .chat-box {font-family: monospace; background: #1e1e1e; color: #d4d4d4; padding: 10px; border-radius: 5px; height: 300px; overflow-y: auto;}
        .timer {font-size: 24px; color: #ffcc00; text-align: center; animation: pulse 1s infinite;}
        @keyframes pulse {0% {transform: scale(1);} 50% {transform: scale(1.1);} 100% {transform: scale(1);}}
        #paste-target {border: 2px dashed #ccc; padding: 20px; text-align: center; cursor: pointer;}
        </style>
    """, unsafe_allow_html=True)

    st.title(f"๐Ÿค–๐Ÿง MMO {st.session_state.username}๐Ÿ“๐Ÿ”ฌ")
    st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! ๐ŸŽ‰")

    # Voice Input
    audio_bytes = audio_recorder()
    if audio_bytes:
        await process_voice_input(audio_bytes)
        st.rerun()

    # Chat Section
    st.subheader(f"{START_ROOM} Chat ๐Ÿ’ฌ")
    chat_content = await load_chat()
    chat_lines = chat_content.split('\n')
    chat_votes = await load_votes(QUOTE_VOTES_FILE)
    for i, line in enumerate(chat_lines):
        if line.strip() and ': ' in line:
            col1, col2, col3 = st.columns([4, 1, 1])
            with col1:
                st.markdown(line)
                username = line.split(': ')[1].split(' ')[0]
                audio_file = None
                cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
                if cache_key in st.session_state.audio_cache:
                    audio_file = st.session_state.audio_cache[cache_key]
                else:
                    audio_file = await async_edge_tts_generate(line.split(': ', 1)[1], FUN_USERNAMES.get(username, "en-US-AriaNeural"))
                    st.session_state.audio_cache[cache_key] = audio_file
                if audio_file:
                    play_and_download_audio(audio_file)
            with col2:
                vote_count = chat_votes.get(line.split('. ')[1] if '. ' in line else line, 0)
                if st.button(f"๐Ÿ‘ {vote_count}", key=f"chat_vote_{i}"):
                    comment = st.session_state.message_text
                    await save_vote(QUOTE_VOTES_FILE, line.split('. ')[1] if '. ' in line else line, await generate_user_hash(), st.session_state.username, comment)
                    if st.session_state.pasted_image_data:
                        filename = await save_pasted_image(st.session_state.pasted_image_data)
                        if filename:
                            await save_chat_entry(st.session_state.username, f"Pasted image: {filename}")
                            st.session_state.pasted_image_data = None
                    st.session_state.message_text = ''
                    st.rerun()
            with col3:
                if st.button("๐Ÿ“ข Quote", key=f"quote_{i}"):
                    st.session_state.quote_line = line
                    st.rerun()

    # Quoting Section
    if 'quote_line' in st.session_state:
        st.markdown(f"### Quoting: {st.session_state.quote_line}")
        quote_response = st.text_area("Add your response", key="quote_response")
        if st.button("Send Quote ๐Ÿš€", key="send_quote"):
            async def process_quote():
                """๐Ÿ“ข - Quote Float Boat - Echoes chat, we gloat!"""
                action = "๐Ÿ“ข - Quote Float Boat - Echoes chat, we gloat!"
                await asyncio.to_thread(log_action, st.session_state.username, action)
                markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
                if st.session_state.pasted_image_data:
                    filename = await save_pasted_image(st.session_state.pasted_image_data)
                    if filename:
                        markdown_response += f"\n- **Image**: ![Pasted Image]({filename})"
                        st.session_state.pasted_image_data = None
                await save_chat_entry(st.session_state.username, markdown_response)
            await process_quote()
            del st.session_state.quote_line
            st.session_state.message_text = ''
            st.rerun()

    # Username Change Dropdown
    new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
    if new_username and new_username != st.session_state.username:
        await save_chat_entry("System ๐ŸŒŸ", f"{st.session_state.username} changed name to {new_username}")
        st.session_state.username = new_username
        st.rerun()

    # Message Input
    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))
    if st.button("Send ๐Ÿš€", key="send_button") and message.strip():
        await save_chat_entry(st.session_state.username, message)
        if st.session_state.pasted_image_data:
            filename = await save_pasted_image(st.session_state.pasted_image_data)
            if filename:
                await save_chat_entry(st.session_state.username, f"Pasted image: {filename}")
                st.session_state.pasted_image_data = None
        st.session_state.message_text = ''
        st.rerun()

    # Paste Target
    paste_component = components.html(
        """
        <div id="paste-target">Paste an image here (Ctrl+V)</div>
        <script>
        const pasteTarget = document.getElementById('paste-target');
        pasteTarget.addEventListener('paste', (event) => {
            const items = (event.clipboardData || window.clipboardData).items;
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf('image') !== -1) {
                    const blob = items[i].getAsFile();
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        window.parent.postMessage({
                            type: 'streamlit:setComponentValue',
                            value: e.target.result
                        }, '*');
                        pasteTarget.innerHTML = '<p>Image pasted! Processing...</p>';
                    };
                    reader.readAsDataURL(blob);
                }
            }
            event.preventDefault();
        });
        </script>
        """,
        height=100
    )

    # Media Section
    st.subheader("Media Gallery ๐ŸŽจ๐ŸŽถ๐ŸŽฅ")
    uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp3', 'mp4'])
    if uploaded_file:
        file_path = os.path.join('./', uploaded_file.name)
        await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
        st.success(f"Uploaded {uploaded_file.name}")

    media_files = glob.glob("./*.png") + glob.glob("./*.jpg") + glob.glob("./*.mp3") + glob.glob("./*.mp4")
    if media_files:
        cols = st.columns(3)
        media_votes = await load_votes(MEDIA_VOTES_FILE)
        for idx, media_file in enumerate(media_files):
            vote_count = media_votes.get(media_file, 0)
            if vote_count > 0:
                with cols[idx % 3]:
                    if media_file.endswith(('.png', '.jpg')):
                        st.image(media_file, use_container_width=True)
                    elif media_file.endswith('.mp3'):
                        st.markdown(await get_audio_html(media_file), unsafe_allow_html=True)
                    elif media_file.endswith('.mp4'):
                        st.markdown(await get_video_html(media_file), unsafe_allow_html=True)
                    col1, col2 = st.columns(2)
                    with col1:
                        if st.button(f"๐Ÿ‘ {vote_count}", key=f"media_vote_{idx}"):
                            comment = st.session_state.message_text
                            await save_vote(MEDIA_VOTES_FILE, media_file, await generate_user_hash(), st.session_state.username, comment)
                            if st.session_state.pasted_image_data:
                                filename = await save_pasted_image(st.session_state.pasted_image_data)
                                if filename:
                                    await save_chat_entry(st.session_state.username, f"Pasted image: {filename}")
                                    st.session_state.pasted_image_data = None
                            st.session_state.message_text = ''
                            st.rerun()
                    with col2:
                        if st.button("๐Ÿ—‘๏ธ", key=f"media_delete_{idx}"):
                            await asyncio.to_thread(os.remove, media_file)
                            st.rerun()

    # Refresh Timer
    st.subheader("Refresh โณ")
    refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
    st.session_state.refresh_rate = refresh_rate
    timer_placeholder = st.empty()
    for i in range(st.session_state.refresh_rate, -1, -1):
        font_name, font_func = random.choice(UNICODE_FONTS)
        countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
        timer_placeholder.markdown(f"<p class='timer'>โณ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
        await asyncio.sleep(1)
    st.rerun()

    # Sidebar History
    st.sidebar.subheader("Chat History ๐Ÿ“œ")
    with open(HISTORY_FILE, 'r') as f:
        history_content = f.read()
    st.sidebar.markdown(history_content)

async def main():
    """๐ŸŽฎ - Game Fame Claim - Starts the fun, no shame!"""
    action = "๐ŸŽฎ - Game Fame Claim - Starts the fun, no shame!"
    username = st.session_state.get('username', 'System ๐ŸŒŸ')
    await asyncio.to_thread(log_action, username, action)
    global NODE_NAME, server_task
    NODE_NAME, port = await get_node_name()
    if server_task is None:
        server_task = asyncio.create_task(run_websocket_server())
    await create_streamlit_interface()

if __name__ == "__main__":
    asyncio.run(main())