File size: 17,175 Bytes
5f75059
b1fe0dd
 
 
 
 
e2ffbc8
962f379
5ede71e
6a6053b
b1fe0dd
f9e683f
962f379
 
 
 
 
 
 
 
6a6053b
5ede71e
6a6053b
5ede71e
6a6053b
5ede71e
6a6053b
5ede71e
6a6053b
 
 
6862189
f9e683f
b1fe0dd
f9e683f
b1fe0dd
 
d13d130
b1fe0dd
6862189
a58b36c
5ede71e
 
 
 
 
e2ffbc8
5ede71e
 
 
e2ffbc8
5ede71e
 
 
 
 
 
 
 
 
a58b36c
5ede71e
6862189
 
5ede71e
 
6862189
5ede71e
 
 
 
 
 
 
 
 
 
 
 
d597cda
6a6053b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6862189
d597cda
5ede71e
b1fe0dd
5ede71e
b1fe0dd
 
5ede71e
962f379
5ede71e
962f379
b1fe0dd
 
5ede71e
 
 
 
 
 
 
 
ca4200f
5ede71e
ca4200f
 
 
 
 
 
5ede71e
ca4200f
5ede71e
ca4200f
 
 
 
5ede71e
ca4200f
 
 
 
 
5ede71e
ca4200f
5ede71e
ca4200f
5ede71e
ca4200f
 
5ede71e
5f75059
6a6053b
d13d130
5f75059
 
 
 
 
 
 
 
6a6053b
5f75059
 
d13d130
 
 
 
 
5f75059
 
 
 
6a6053b
 
5f75059
6a6053b
5f75059
 
d13d130
6a6053b
d13d130
 
6a6053b
 
 
 
5f75059
6a6053b
 
5f75059
6a6053b
 
 
 
 
 
 
 
 
 
 
 
5f75059
 
 
 
 
 
 
 
 
6a6053b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d13d130
 
6a6053b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d13d130
 
6a6053b
d13d130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ede71e
6a6053b
 
 
 
 
 
 
 
 
5ede71e
ca4200f
5ede71e
6862189
ca4200f
 
6862189
d13d130
5f75059
5ede71e
 
5f75059
ca4200f
 
 
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
import streamlit as st
import asyncio
import websockets
import uuid
import argparse
from datetime import datetime
import os
import random
import time
import hashlib

# Fun usernames with emojis - the VIP list of quirky characters! πŸŽ‰πŸ˜œ
FUN_USERNAMES = [
    "CosmicJester 🌌", "PixelPanda 🐼", "QuantumQuack πŸ¦†", "StellarSquirrel 🐿️",
    "GizmoGuru βš™οΈ", "NebulaNinja 🌠", "ByteBuster πŸ’Ύ", "GalacticGopher 🌍",
    "RocketRaccoon πŸš€", "EchoElf 🧝", "PhantomFox 🦊", "WittyWizard πŸ§™",
    "LunarLlama πŸŒ™", "SolarSloth β˜€οΈ", "AstroAlpaca πŸ¦™", "CyberCoyote 🐺",
    "MysticMoose 🦌", "GlitchGnome 🧚", "VortexViper 🐍", "ChronoChimp πŸ’"
]

# Directories for chat and votes - the secret vaults where tales and tallies are stashed! πŸ—„οΈπŸ”’
CHAT_DIR = "chat_logs"
VOTE_DIR = "vote_logs"
os.makedirs(CHAT_DIR, exist_ok=True)
os.makedirs(VOTE_DIR, exist_ok=True)

# Persistent files - the grand tomes of chatter and votes! πŸ“–βœ¨
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
IMAGE_VOTES_FILE = os.path.join(VOTE_DIR, "image_votes.md")
HISTORY_FILE = os.path.join(VOTE_DIR, "vote_history.md")

# Node name - the app’s codename generator, sneaky and slick! πŸ•΅οΈβ€β™‚οΈπŸ’Ύ
def get_node_name():
    """🎲 Spins the wheel of fate to name our node - a random alias or user pick! 🏷️"""
    parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
    parser.add_argument('--node-name', type=str, default=None, help='Name for this chat node')
    parser.add_argument('--port', type=int, default=8501, help='Port to run the Streamlit interface on')
    args = parser.parse_args()
    return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port

# Chat saver - the scribe etching epic messages into the eternal scroll! πŸ–‹οΈπŸ“œ
def save_chat_entry(username, message):
    """πŸ–ŒοΈ Carves a chat line into the grand Markdown tome - history in the making! πŸ›οΈ"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entry = f"[{timestamp}] {username}: {message}"
    try:
        with open(CHAT_FILE, 'a') as f:
            f.write(f"{entry}\n")
        return True
    except Exception as e:
        print(f"Oops! Failed to save chat: {e}")
        return False

# Chat loader - the archaeologist unearthing the chat saga! β›οΈπŸ“š
def load_chat():
    """πŸ” Digs up the chat treasure from the filesystem - tales of old and new! πŸ’°"""
    if not os.path.exists(CHAT_FILE):
        with open(CHAT_FILE, 'w') as f:
            f.write("# Global Chat\n\nNo messages yet - start chatting! 🎀\n")
    try:
        with open(CHAT_FILE, 'r') as f:
            content = f.read()
        lines = content.strip().split('\n')
        numbered_content = "\n".join(f"{i+1}. {line}" for i, line in enumerate(lines) if line.strip())
        return numbered_content
    except Exception as e:
        print(f"Chat load hiccup: {e}")
        return "# Error loading chat\nSomething went wonky! 😡"

# User list grabber - the social butterfly spotting all the chatters! πŸ¦‹πŸ‘₯
def get_user_list(chat_content):
    """πŸ‘€ Peeks at the chat to spot all the cool cats talking - who’s in the club? 🎸"""
    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))

# Quote loader - the sage pulling wisdom from the ages! πŸ“œπŸ§™
def load_quotes(source="famous"):
    """πŸ“š Grabs a stack of wise words from famous folks or custom quips! πŸ—£οΈ"""
    famous_quotes = [
        "The true sign of intelligence is not knowledge but imagination. – Albert Einstein",
        "I have not failed. I've just found 10,000 ways that won't work. – Thomas Edison",
        "Innovation distinguishes between a leader and a follower. – Steve Jobs",
        "Research is what I'm doing when I don't know what I'm doing. – Wernher von Braun",
        "The only way to discover the limits of the possible is to go beyond them into the impossible. – Arthur C. Clarke",
        "Success is a science; if you have the conditions, you get the result. – Oscar Wilde",
        "An expert is a person who has made all the mistakes that can be made in a very narrow field. – Niels Bohr",
        "The important thing is to not stop questioning. Curiosity has its own reason for existing. – Albert Einstein",
        "The best way to predict the future is to invent it. – Alan Kay",
        "If I have seen further it is by standing on the shoulders of Giants. – Isaac Newton",
        "Logic will get you from A to B. Imagination will take you everywhere. – Albert Einstein",
        "Imagination is more important than knowledge. Knowledge is limited. Imagination encircles the world. – Albert Einstein",
        "Science is a way of thinking much more than it is a body of knowledge. – Carl Sagan",
        "We cannot solve our problems with the same thinking we used when we created them. – Albert Einstein",
        "The true method of knowledge is experiment. – William Blake",
        "The scientist is not a person who gives the right answers, he's one who asks the right questions. – Claude Levi-Strauss",
        "It's kind of fun to do the impossible. – Walt Disney",
        "Any sufficiently advanced technology is indistinguishable from magic. – Arthur C. Clarke",
        "Creativity is intelligence having fun. – Albert Einstein",
        "To invent, you need a good imagination and a pile of junk. – Thomas Edison"
    ]
    custom_quotes = [
        "Every age unfolds a new lesson. Life's chapters evolve, each teaching us anew.",
        "From infancy to twilight, our journey is painted in growth. Every stage shines with its own wisdom.",
        "Love is the universal language, transcending boundaries and touching souls.",
        "Through love, we find connection, unity, and the essence of existence."
    ]
    return famous_quotes if source == "famous" else custom_quotes

# Vote saver - the tally keeper counting thumbs up! πŸ‘πŸ“Š
def save_vote(file, item, user_hash):
    """✍️ Tallies a vote in the grand ledger - your opinion matters! πŸ—³οΈ"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entry = f"[{timestamp}] {user_hash} voted for {item}"
    try:
        with open(file, 'a') as f:
            f.write(f"{entry}\n")
        with open(HISTORY_FILE, 'a') as f:
            f.write(f"- {timestamp} - User {user_hash} voted for {item}\n")
        return True
    except Exception as e:
        print(f"Vote save flop: {e}")
        return False

# Vote loader - the scorekeeper tallying the crowd’s cheers! πŸŽ‰πŸ…
def load_votes(file):
    """πŸ“ˆ Counts the votes from the ledger - who’s winning the popularity contest? πŸ†"""
    if not os.path.exists(file):
        with open(file, 'w') as f:
            f.write("# Vote Tally\n\nNo votes yet - get clicking! πŸ–±οΈ\n")
    try:
        with open(file, 'r') as f:
            lines = f.read().strip().split('\n')
        votes = {}
        for line in lines[2:]:  # Skip header
            if line.strip() and 'voted for' in line:
                item = line.split('voted for ')[1]
                votes[item] = votes.get(item, 0) + 1
        return votes
    except Exception as e:
        print(f"Vote load oopsie: {e}")
        return {}

# User hash generator - the secret agent giving you a cool code! πŸ•΅οΈβ€β™‚οΈπŸ”‘
def generate_user_hash():
    """πŸ•΅οΈ Crafts a snazzy 8-digit ID badge - you’re in the club now! 🎟️"""
    if 'user_hash' not in st.session_state:
        session_id = str(random.getrandbits(128))
        hash_object = hashlib.md5(session_id.encode())
        st.session_state['user_hash'] = hash_object.hexdigest()[:8]
    return st.session_state['user_hash']

active_connections = {}

# WebSocket handler - the bouncer at the chat rave, keeping it hopping! πŸŽ‰πŸšͺ
async def websocket_handler(websocket, path):
    """🎧 Guards the chat gate, letting messages fly and booting crashers! 🚨"""
    try:
        client_id = str(uuid.uuid4())
        room_id = "chat"
        active_connections.setdefault(room_id, {})[client_id] = websocket
        print(f"Client {client_id} joined the chat party!")

        async for message in websocket:
            try:
                parts = message.split('|', 1)
                if len(parts) == 2:
                    username, content = parts
                    save_chat_entry(username, content)
                    await broadcast_message(f"{username}|{content}", room_id)
            except Exception as e:
                print(f"Message mishap: {e}")
                await websocket.send(f"ERROR|Oops, bad message format! 😬")
    except websockets.ConnectionClosed:
        print(f"Client {client_id} bailed from the chat!")
    finally:
        if room_id in active_connections and client_id in active_connections[room_id]:
            del active_connections[room_id][client_id]
            if not active_connections[room_id]:
                del active_connections[room_id]

# Broadcaster - the megaphone blasting chat vibes to all! πŸ“£πŸŽΆ
async def broadcast_message(message, room_id):
    """πŸ“’ Shouts the latest chat beat to every dancer in the room - hear it loud! 🎡"""
    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]

# WebSocket starter - the DJ spinning up the chat tunes! 🎧πŸ”₯
async def start_websocket_server(host='0.0.0.0', port=8765):
    """🌐 Cranks up the WebSocket jukebox, ready to rock the chat scene! 🎸"""
    server = await websockets.serve(websocket_handler, host, port)
    print(f"WebSocket server jamming on ws://{host}:{port}")
    return server

# Chat interface maker - the stage builder for our chat extravaganza! 🎭🏟️
def create_streamlit_interface(initial_username):
    """πŸ–ŒοΈ Sets up the chat stage with live updates, timers, voting, and refresh flair! 🌟"""
    # Custom CSS for a sleek chat box and timer
    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: 18px;
            color: #ffcc00;
            text-align: center;
        }
        </style>
    """, unsafe_allow_html=True)

    # Title and intro
    st.title(f"Chat & Quote Node: {NODE_NAME}")
    st.markdown("Chat, vote on messages, quotes, and images - keep the party rocking! πŸŽ‰")

    # Session state for username, refresh rate, and quote index
    if 'username' not in st.session_state:
        st.session_state.username = initial_username
    if 'refresh_rate' not in st.session_state:
        st.session_state.refresh_rate = 5
    if 'last_refresh' not in st.session_state:
        st.session_state.last_refresh = time.time()
    if 'quote_index' not in st.session_state:
        st.session_state.quote_index = random.randint(0, len(load_quotes("famous")) - 1)
    if 'quote_source' not in st.session_state:
        st.session_state.quote_source = "famous"

    # Chat section
    st.subheader("Chat Room πŸ’¬")
    chat_content = load_chat()
    chat_lines = chat_content.split('\n')
    for i, line in enumerate(chat_lines):
        if line.strip() and ': ' in line:
            col1, col2 = st.columns([5, 1])
            with col1:
                st.markdown(line)
            with col2:
                if st.button(f"πŸ‘", key=f"chat_vote_{i}"):
                    user_hash = generate_user_hash()
                    save_vote(QUOTE_VOTES_FILE, line, user_hash)
                    st.session_state.last_refresh = time.time()
                    st.rerun()

    user_list = get_user_list(chat_content)
    new_username = st.selectbox("Switch User", user_list + [st.session_state.username], index=len(user_list))
    if new_username != st.session_state.username:
        st.session_state.username = new_username

    message = st.text_input("Message", placeholder="Type your epic line here! ✍️")
    if st.button("Send πŸš€") and message.strip():
        save_chat_entry(st.session_state.username, message)
        st.session_state.last_refresh = time.time()
        st.rerun()

    # Quote section
    st.subheader("Quote of the Moment πŸ“")
    quotes = load_quotes(st.session_state.quote_source)
    quote = quotes[st.session_state.quote_index]
    col1, col2 = st.columns([5, 1])
    with col1:
        st.markdown(quote)
    with col2:
        if st.button("πŸ‘ Upvote", key="quote_vote"):
            user_hash = generate_user_hash()
            save_vote(QUOTE_VOTES_FILE, quote, user_hash)
            st.session_state.last_refresh = time.time()
            st.rerun()
    if time.time() - st.session_state.last_refresh > 10:  # 10s quote refresh
        st.session_state.quote_index = (st.session_state.quote_index + 1) % len(quotes)
        st.session_state.quote_source = "custom" if st.session_state.quote_source == "famous" else "famous"
        st.session_state.last_refresh = time.time()
        st.rerun()

    # Image voting section
    st.subheader("Image Voting πŸ–ΌοΈ")
    image_dir = '.'
    valid_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')
    images = [f for f in os.listdir(image_dir) if f.lower().endswith(valid_extensions)]
    if len(images) >= 2:
        image1, image2 = random.sample(images, 2)
        col1, col2 = st.columns(2)
        with col1:
            st.image(os.path.join(image_dir, image1))
            if st.button(f"πŸ‘ Upvote {image1}", key=f"img_vote_{image1}"):
                user_hash = generate_user_hash()
                save_vote(IMAGE_VOTES_FILE, image1, user_hash)
                st.session_state.last_refresh = time.time()
                st.rerun()
        with col2:
            st.image(os.path.join(image_dir, image2))
            if st.button(f"πŸ‘ Upvote {image2}", key=f"img_vote_{image2}"):
                user_hash = generate_user_hash()
                save_vote(IMAGE_VOTES_FILE, image2, user_hash)
                st.session_state.last_refresh = time.time()
                st.rerun()
    else:
        st.error("Need at least 2 images in the directory for voting!")

    # Refresh rate controls
    st.subheader("Set Refresh Rate ⏳")
    refresh_rate = st.slider("Refresh Rate (seconds)", min_value=1, max_value=300, value=st.session_state.refresh_rate, step=1)
    st.session_state.refresh_rate = refresh_rate

    col1, col2, col3 = st.columns(3)
    with col1:
        if st.button("πŸ‡ Small (1s)"):
            st.session_state.refresh_rate = 1
            st.session_state.last_refresh = time.time()
            st.rerun()
    with col2:
        if st.button("🐒 Medium (5s)"):
            st.session_state.refresh_rate = 5
            st.session_state.last_refresh = time.time()
            st.rerun()
    with col3:
        if st.button("🐘 Large (5m)"):
            st.session_state.refresh_rate = 300
            st.session_state.last_refresh = time.time()
            st.rerun()

    # Countdown timer
    elapsed = time.time() - st.session_state.last_refresh
    remaining = max(0, st.session_state.refresh_rate - int(elapsed))
    st.markdown(f"<p class='timer'>Next refresh in: {remaining} seconds</p>", unsafe_allow_html=True)

    # Auto-refresh logic
    if elapsed >= st.session_state.refresh_rate:
        st.session_state.last_refresh = time.time()
        st.rerun()
    else:
        st.markdown(f"<script>window.setTimeout(() => window.location.reload(), {int((st.session_state.refresh_rate - elapsed) * 1000)});</script>", unsafe_allow_html=True)

    # Sidebar vote stats
    st.sidebar.subheader("Vote Totals")
    chat_votes = load_votes(QUOTE_VOTES_FILE)
    image_votes = load_votes(IMAGE_VOTES_FILE)
    for item, count in chat_votes.items():
        st.sidebar.write(f"{item}: {count} votes")
    for image, count in image_votes.items():
        st.sidebar.write(f"{image}: {count} votes")

# Main event - the ringmaster kicking off the chat circus! πŸŽͺ🀑
async def main():
    """🎀 Drops the mic and starts the chat party - it’s showtime, folks! πŸŽ‰"""
    global NODE_NAME
    NODE_NAME, port = get_node_name()
    await start_websocket_server()

    query_params = st.query_params if hasattr(st, 'query_params') else {}
    initial_username = query_params.get("username", random.choice(FUN_USERNAMES)) if query_params else random.choice(FUN_USERNAMES)
    print(f"Welcoming {initial_username} to the chat bash!")

    create_streamlit_interface(initial_username)

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