Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,16 @@
|
|
1 |
-
# 🚀 Main App - TalkingAIResearcher with Chat, Voice, Media, ArXiv, and More
|
2 |
import streamlit as st
|
3 |
import asyncio
|
4 |
import websockets
|
5 |
import uuid
|
6 |
import argparse
|
|
|
7 |
import os
|
8 |
import random
|
9 |
import time
|
10 |
import hashlib
|
11 |
from PIL import Image
|
12 |
import glob
|
|
|
13 |
import base64
|
14 |
import io
|
15 |
import streamlit.components.v1 as components
|
@@ -17,453 +18,541 @@ import edge_tts
|
|
17 |
from audio_recorder_streamlit import audio_recorder
|
18 |
import nest_asyncio
|
19 |
import re
|
20 |
-
import pytz
|
21 |
-
import shutil
|
22 |
-
import anthropic
|
23 |
-
import openai
|
24 |
-
from PyPDF2 import PdfReader
|
25 |
-
import threading
|
26 |
-
import json
|
27 |
-
import zipfile
|
28 |
-
from gradio_client import Client
|
29 |
-
from dotenv import load_dotenv
|
30 |
-
from streamlit_marquee import streamlit_marquee
|
31 |
-
from datetime import datetime
|
32 |
-
from collections import defaultdict, Counter
|
33 |
-
import pandas as pd
|
34 |
|
35 |
-
#
|
36 |
nest_asyncio.apply()
|
37 |
|
38 |
-
#
|
|
|
|
|
|
|
|
|
39 |
st.set_page_config(
|
40 |
-
page_title="
|
41 |
-
page_icon=
|
42 |
layout="wide",
|
43 |
initial_sidebar_state="auto"
|
44 |
)
|
45 |
|
46 |
-
#
|
47 |
-
icons = '🤖🧠🔬📝'
|
48 |
-
START_ROOM = "Sector 🌌"
|
49 |
FUN_USERNAMES = {
|
50 |
-
"CosmicJester 🌌": "en-US-AriaNeural",
|
51 |
-
"PixelPanda 🐼": "en-US-JennyNeural",
|
52 |
-
"QuantumQuack 🦆": "en-GB-SoniaNeural",
|
53 |
-
"StellarSquirrel 🐿️": "en-AU-NatashaNeural",
|
54 |
-
"GizmoGuru ⚙️": "en-CA-ClaraNeural",
|
55 |
-
"NebulaNinja 🌠": "en-US-GuyNeural",
|
56 |
-
"ByteBuster 💾": "en-GB-RyanNeural",
|
57 |
-
"GalacticGopher 🌍": "en-AU-WilliamNeural",
|
58 |
-
"RocketRaccoon 🚀": "en-CA-LiamNeural",
|
59 |
-
"EchoElf 🧝": "en-US-AnaNeural",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
}
|
61 |
-
EDGE_TTS_VOICES = list(set(FUN_USERNAMES.values())) # 🎙️ Voice options
|
62 |
-
FILE_EMOJIS = {"md": "📝", "mp3": "🎵", "wav": "🔊"}
|
63 |
-
|
64 |
-
# 📁 Directories
|
65 |
-
for d in ["chat_logs", "vote_logs", "audio_logs", "history_logs", "media_files", "audio_cache"]:
|
66 |
-
os.makedirs(d, exist_ok=True)
|
67 |
-
|
68 |
-
CHAT_FILE = "chat_logs/global_chat.md"
|
69 |
-
HISTORY_FILE = "history_logs/chat_history.md"
|
70 |
-
MEDIA_DIR = "media_files"
|
71 |
-
AUDIO_CACHE_DIR = "audio_cache"
|
72 |
-
|
73 |
-
# 🔑 API Keys
|
74 |
-
load_dotenv()
|
75 |
-
anthropic_key = os.getenv('ANTHROPIC_API_KEY', st.secrets.get('ANTHROPIC_API_KEY', ""))
|
76 |
-
openai_api_key = os.getenv('OPENAI_API_KEY', st.secrets.get('OPENAI_API_KEY', ""))
|
77 |
-
openai_client = openai.OpenAI(api_key=openai_api_key)
|
78 |
-
|
79 |
-
# 🕒 Timestamp Helper
|
80 |
-
def format_timestamp_prefix(username=""):
|
81 |
-
central = pytz.timezone('US/Central')
|
82 |
-
now = datetime.now(central)
|
83 |
-
return f"{now.strftime('%Y%m%d_%H%M%S')}-by-{username}"
|
84 |
-
|
85 |
-
# 📈 Performance Timer
|
86 |
-
class PerformanceTimer:
|
87 |
-
def __init__(self, name): self.name, self.start = name, None
|
88 |
-
def __enter__(self): self.start = time.time(); return self
|
89 |
-
def __exit__(self, *args):
|
90 |
-
duration = time.time() - self.start
|
91 |
-
st.session_state['operation_timings'][self.name] = duration
|
92 |
-
st.session_state['performance_metrics'][self.name].append(duration)
|
93 |
-
|
94 |
-
# 🎛️ Session State Init
|
95 |
-
def init_session_state():
|
96 |
-
defaults = {
|
97 |
-
'server_running': False, 'server_task': None, 'active_connections': {},
|
98 |
-
'media_notifications': [], 'last_chat_update': 0, 'displayed_chat_lines': [],
|
99 |
-
'message_text': "", 'audio_cache': {}, 'pasted_image_data': None,
|
100 |
-
'quote_line': None, 'refresh_rate': 5, 'base64_cache': {},
|
101 |
-
'transcript_history': [], 'last_transcript': "", 'image_hashes': set(),
|
102 |
-
'tts_voice': "en-US-AriaNeural", 'chat_history': [], 'marquee_settings': {
|
103 |
-
"background": "#1E1E1E", "color": "#FFFFFF", "font-size": "14px",
|
104 |
-
"animationDuration": "20s", "width": "100%", "lineHeight": "35px"
|
105 |
-
}, 'operation_timings': {}, 'performance_metrics': defaultdict(list),
|
106 |
-
'enable_audio': True, 'download_link_cache': {}, 'username': None
|
107 |
-
}
|
108 |
-
for k, v in defaults.items():
|
109 |
-
if k not in st.session_state: st.session_state[k] = v
|
110 |
-
|
111 |
-
# 🖌️ Marquee Helpers
|
112 |
-
def update_marquee_settings_ui():
|
113 |
-
# 🎨 Sidebar marquee controls
|
114 |
-
st.sidebar.markdown("### 🎯 Marquee Settings")
|
115 |
-
cols = st.sidebar.columns(2)
|
116 |
-
with cols[0]:
|
117 |
-
st.session_state['marquee_settings']['background'] = st.color_picker("🎨 Background", "#1E1E1E")
|
118 |
-
st.session_state['marquee_settings']['color'] = st.color_picker("✍️ Text", "#FFFFFF")
|
119 |
-
with cols[1]:
|
120 |
-
st.session_state['marquee_settings']['font-size'] = f"{st.slider('📏 Size', 10, 24, 14)}px"
|
121 |
-
st.session_state['marquee_settings']['animationDuration'] = f"{st.slider('⏱️ Speed', 1, 20, 20)}s"
|
122 |
-
|
123 |
-
def display_marquee(text, settings, key_suffix=""):
|
124 |
-
# 🌈 Show marquee with truncation
|
125 |
-
truncated = text[:280] + "..." if len(text) > 280 else text
|
126 |
-
streamlit_marquee(content=truncated, **settings, key=f"marquee_{key_suffix}")
|
127 |
-
st.write("")
|
128 |
-
|
129 |
-
# 📝 Text & File Helpers
|
130 |
-
def clean_text_for_tts(text): return re.sub(r'[#*!\[\]]+', '', ' '.join(text.split()))[:200] or "No text"
|
131 |
-
def clean_text_for_filename(text): return '_'.join(re.sub(r'[^\w\s-]', '', text.lower()).split())[:200]
|
132 |
-
def get_high_info_terms(text, top_n=10):
|
133 |
-
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with'}
|
134 |
-
words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
|
135 |
-
bi_grams = [' '.join(pair) for pair in zip(words, words[1:])]
|
136 |
-
filtered = [t for t in words + bi_grams if t not in stop_words and len(t.split()) <= 2]
|
137 |
-
return [t for t, _ in Counter(filtered).most_common(top_n)]
|
138 |
-
|
139 |
-
def generate_filename(prompt, response, file_type="md"):
|
140 |
-
# 📁 Smart filename with info terms
|
141 |
-
prefix = format_timestamp_prefix()
|
142 |
-
terms = get_high_info_terms(prompt + " " + response, 5)
|
143 |
-
snippet = clean_text_for_filename(prompt[:40] + " " + response[:40])
|
144 |
-
wct, sw = len(prompt.split()), len(response.split())
|
145 |
-
dur = round((wct + sw) / 2.5)
|
146 |
-
base = '_'.join(list(dict.fromkeys(terms + [snippet])))[:200 - len(prefix) - len(f"_wct{wct}_sw{sw}_dur{dur}.{file_type}")]
|
147 |
-
return f"{prefix}{base}_wct{wct}_sw{sw}_dur{dur}.{file_type}"
|
148 |
-
|
149 |
-
def create_file(prompt, response, file_type="md"):
|
150 |
-
# 📝 Save file with Q&A
|
151 |
-
filename = generate_filename(prompt, response, file_type)
|
152 |
-
with open(filename, 'w', encoding='utf-8') as f: f.write(prompt + "\n\n" + response)
|
153 |
-
return filename
|
154 |
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
|
164 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
filename = f"audio_{format_timestamp_prefix()}_{random.randint(1000, 9999)}.{file_format}"
|
173 |
-
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
174 |
await communicate.save(filename)
|
175 |
-
|
176 |
-
|
|
|
|
|
|
|
177 |
|
|
|
178 |
def play_and_download_audio(file_path):
|
179 |
-
# 🔊 Play + download
|
180 |
if file_path and os.path.exists(file_path):
|
181 |
st.audio(file_path)
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
if not os.path.exists(CHAT_FILE):
|
201 |
-
with open(CHAT_FILE, 'a') as f: f.write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub! 🎤\n")
|
202 |
-
with open(CHAT_FILE, 'r') as f: return f.read()
|
203 |
|
204 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
async def websocket_handler(websocket, path):
|
206 |
-
|
207 |
-
|
208 |
-
room_id = "chat"
|
209 |
-
st.session_state.active_connections.setdefault(room_id, {})[client_id] = websocket
|
210 |
-
chat_content = await load_chat()
|
211 |
-
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
|
212 |
-
if not any(f"Client-{client_id}" in line for line in chat_content.split('\n')):
|
213 |
-
await save_chat_entry(f"Client-{client_id}", f"{username} has joined {START_ROOM}!")
|
214 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
async for message in websocket:
|
216 |
-
|
217 |
-
|
|
|
|
|
|
|
|
|
|
|
218 |
finally:
|
219 |
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
|
220 |
del st.session_state.active_connections[room_id][client_id]
|
221 |
|
|
|
222 |
async def broadcast_message(message, room_id):
|
223 |
-
|
|
|
224 |
if room_id in st.session_state.active_connections:
|
225 |
disconnected = []
|
226 |
for client_id, ws in st.session_state.active_connections[room_id].items():
|
227 |
-
try:
|
228 |
-
|
229 |
-
|
|
|
|
|
|
|
230 |
|
|
|
231 |
async def run_websocket_server():
|
232 |
-
|
|
|
233 |
if not st.session_state.server_running:
|
234 |
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
|
235 |
st.session_state.server_running = True
|
236 |
await server.wait_closed()
|
237 |
|
238 |
-
#
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
if
|
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 |
-
def generate_5min_feature_markdown(paper):
|
293 |
-
# ✨ 5-min research paper feature
|
294 |
-
title, summary, authors, date, url = paper['title'], paper['summary'], paper['authors'], paper['date'], paper['url']
|
295 |
-
pdf_url = url.replace("abs", "pdf") + (".pdf" if not url.endswith(".pdf") else "")
|
296 |
-
wct, sw = len(title.split()), len(summary.split())
|
297 |
-
terms = get_high_info_terms(summary, 15)
|
298 |
-
rouge = round((len(terms) / max(sw, 1)) * 100, 2)
|
299 |
-
mermaid = "```mermaid\nflowchart TD\n" + "\n".join(f' T{i+1}["{t}"] --> T{i+2}["{terms[i+1]}"]' for i in range(len(terms)-1)) + "\n```"
|
300 |
-
return f"""
|
301 |
-
## 📄 {title}
|
302 |
-
**Authors:** {authors} | **Date:** {date} | **Words:** Title: {wct}, Summary: {sw}
|
303 |
-
**Links:** [Abstract]({url}) | [PDF]({pdf_url})
|
304 |
-
**Terms:** {', '.join(terms)} | **ROUGE:** {rouge}%
|
305 |
-
### 🎤 TTF Read Aloud
|
306 |
-
- **Title:** {title} | **Terms:** {', '.join(terms)} | **ROUGE:** {rouge}%
|
307 |
-
#### Concepts Graph
|
308 |
-
{mermaid}
|
309 |
-
---
|
310 |
-
"""
|
311 |
-
|
312 |
-
def create_detailed_paper_md(papers): return "# Detailed Summary\n" + "\n".join(generate_5min_feature_markdown(p) for p in papers)
|
313 |
-
|
314 |
-
async def create_paper_audio_files(papers, query):
|
315 |
-
# 🎧 Generate paper audio
|
316 |
-
for p in papers:
|
317 |
-
audio_text = clean_text_for_tts(f"{p['title']} by {p['authors']}. {p['summary']}")
|
318 |
-
p['full_audio'], _ = await async_edge_tts_generate(audio_text, st.session_state['tts_voice'])
|
319 |
-
if p['full_audio']: p['download_base64'] = get_download_link(p['full_audio'])
|
320 |
-
|
321 |
-
async def perform_ai_lookup(q, useArxiv=True, useArxivAudio=False):
|
322 |
-
# 🔮 AI-powered research (now async!)
|
323 |
-
client = anthropic.Anthropic(api_key=anthropic_key)
|
324 |
-
response = client.messages.create(model="claude-3-sonnet-20240229", max_tokens=1000, messages=[{"role": "user", "content": q}])
|
325 |
-
result = response.content[0].text
|
326 |
-
st.markdown("### Claude's Reply 🧠\n" + result)
|
327 |
-
md_file = create_file(q, result)
|
328 |
-
audio_file, _ = await async_edge_tts_generate(result, st.session_state['tts_voice'])
|
329 |
-
play_and_download_audio(audio_file)
|
330 |
-
|
331 |
-
if useArxiv:
|
332 |
-
q += result
|
333 |
-
gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
334 |
-
refs = gradio_client.predict(q, 10, "Semantic Search", "mistralai/Mixtral-8x7B-Instruct-v0.1", api_name="/update_with_rag_md")[0]
|
335 |
-
result = f"🔎 {q}\n\n{refs}"
|
336 |
-
md_file, audio_file = create_file(q, result), (await async_edge_tts_generate(result, st.session_state['tts_voice']))[0]
|
337 |
-
play_and_download_audio(audio_file)
|
338 |
-
papers = parse_arxiv_refs(refs)
|
339 |
-
if papers and useArxivAudio: await create_paper_audio_files(papers, q)
|
340 |
-
return result, papers
|
341 |
-
return result, []
|
342 |
-
|
343 |
-
# 📦 Zip Files
|
344 |
-
def create_zip_of_files(md_files, mp3_files, query):
|
345 |
-
# 📦 Zip it up
|
346 |
-
all_files = md_files + mp3_files
|
347 |
-
if not all_files: return None
|
348 |
-
terms = get_high_info_terms(" ".join([open(f, 'r', encoding='utf-8').read() if f.endswith('.md') else os.path.splitext(os.path.basename(f))[0].replace('_', ' ') for f in all_files] + [query]), 5)
|
349 |
-
zip_name = f"{format_timestamp_prefix()}_{'-'.join(terms)[:20]}.zip"
|
350 |
-
with zipfile.ZipFile(zip_name, 'w') as z: [z.write(f) for f in all_files]
|
351 |
-
return zip_name
|
352 |
-
|
353 |
-
# 🎮 Main Interface
|
354 |
-
async def async_interface():
|
355 |
-
init_session_state()
|
356 |
-
if not st.session_state.username:
|
357 |
-
available = [n for n in FUN_USERNAMES if not any(f"{n} has joined" in l for l in (await load_chat()).split('\n'))]
|
358 |
-
st.session_state.username = random.choice(available or list(FUN_USERNAMES.keys()))
|
359 |
-
st.session_state.tts_voice = FUN_USERNAMES[st.session_state.username]
|
360 |
-
|
361 |
-
st.title(f"🤖🧠MMO Chat & Research for {st.session_state.username}📝🔬")
|
362 |
-
update_marquee_settings_ui()
|
363 |
-
display_marquee(f"🚀 Welcome to {START_ROOM} | 🤖 {st.session_state.username}", st.session_state['marquee_settings'], "welcome")
|
364 |
-
|
365 |
-
if not st.session_state.server_task:
|
366 |
-
st.session_state.server_task = asyncio.create_task(run_websocket_server())
|
367 |
-
|
368 |
-
tab_main = st.radio("Action:", ["🎤 Chat & Voice", "📸 Media", "🔍 ArXiv", "📚 PDF to Audio"], horizontal=True)
|
369 |
-
useArxiv, useArxivAudio = st.checkbox("Search ArXiv", True), st.checkbox("ArXiv Audio", False)
|
370 |
-
|
371 |
-
# 🎤 Chat & Voice
|
372 |
-
if tab_main == "🎤 Chat & Voice":
|
373 |
st.subheader(f"{START_ROOM} Chat 💬")
|
374 |
chat_content = await load_chat()
|
375 |
-
|
|
|
|
|
376 |
if line.strip() and ': ' in line:
|
377 |
-
st.
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
396 |
st.rerun()
|
397 |
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
with tabs[0]:
|
403 |
-
for a in glob.glob(f"{MEDIA_DIR}/*.mp3"):
|
404 |
-
with st.expander(os.path.basename(a)): play_and_download_audio(a)
|
405 |
-
with tabs[1]:
|
406 |
-
imgs = glob.glob(f"{MEDIA_DIR}/*.png") + glob.glob(f"{MEDIA_DIR}/*.jpg")
|
407 |
-
if imgs:
|
408 |
-
cols = st.columns(3)
|
409 |
-
for i, f in enumerate(imgs): cols[i % 3].image(f, use_container_width=True)
|
410 |
-
with tabs[2]:
|
411 |
-
for v in glob.glob(f"{MEDIA_DIR}/*.mp4"):
|
412 |
-
with st.expander(os.path.basename(v)): st.video(v)
|
413 |
-
|
414 |
-
uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3'])
|
415 |
-
if uploaded_file:
|
416 |
-
filename = f"{format_timestamp_prefix(st.session_state.username)}-{hashlib.md5(uploaded_file.getbuffer()).hexdigest()[:8]}.{uploaded_file.name.split('.')[-1]}"
|
417 |
-
with open(f"{MEDIA_DIR}/{filename}", 'wb') as f: f.write(uploaded_file.getbuffer())
|
418 |
-
await save_chat_entry(st.session_state.username, f"Uploaded: {filename}")
|
419 |
st.rerun()
|
420 |
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
st.
|
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 |
st.rerun()
|
455 |
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
st.sidebar.
|
460 |
-
|
461 |
-
|
462 |
-
if zip_name: st.sidebar.markdown(get_download_link(zip_name, "zip"), unsafe_allow_html=True)
|
463 |
|
|
|
464 |
def main():
|
465 |
-
|
466 |
-
|
467 |
|
468 |
if __name__ == "__main__":
|
469 |
main()
|
|
|
|
|
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
|
|
|
18 |
from audio_recorder_streamlit import audio_recorder
|
19 |
import nest_asyncio
|
20 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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", # US Female, bright & clear
|
40 |
+
"PixelPanda 🐼": "en-US-JennyNeural", # US Female, warm & friendly
|
41 |
+
"QuantumQuack 🦆": "en-GB-SoniaNeural", # UK Female, posh & crisp
|
42 |
+
"StellarSquirrel 🐿️": "en-AU-NatashaNeural", # AU Female, lively & upbeat
|
43 |
+
"GizmoGuru ⚙️": "en-CA-ClaraNeural", # CA Female, calm & soothing
|
44 |
+
"NebulaNinja 🌠": "en-US-GuyNeural", # US Male, deep & cool
|
45 |
+
"ByteBuster 💾": "en-GB-RyanNeural", # UK Male, smooth & refined
|
46 |
+
"GalacticGopher 🌍": "en-AU-WilliamNeural", # AU Male, bold & rugged
|
47 |
+
"RocketRaccoon 🚀": "en-CA-LiamNeural", # CA Male, steady & warm
|
48 |
+
"EchoElf 🧝": "en-US-AnaNeural", # US Female, soft & gentle (child-like)
|
49 |
+
"PhantomFox 🦊": "en-US-BrandonNeural", # US Male, confident & rich
|
50 |
+
"WittyWizard 🧙": "en-GB-ThomasNeural", # UK Male, authoritative & clear
|
51 |
+
"LunarLlama 🌙": "en-AU-FreyaNeural", # AU Female, sweet & melodic
|
52 |
+
"SolarSloth ☀️": "en-CA-LindaNeural", # CA Female, neutral & pleasant
|
53 |
+
"AstroAlpaca 🦙": "en-US-ChristopherNeural",# US Male, strong & resonant
|
54 |
+
"CyberCoyote 🐺": "en-GB-ElliotNeural", # UK Male, youthful & energetic
|
55 |
+
"MysticMoose 🦌": "en-AU-JamesNeural", # AU Male, deep & grounded
|
56 |
+
"GlitchGnome 🧚": "en-CA-EthanNeural", # CA Male, bright & lively
|
57 |
+
"VortexViper 🐍": "en-US-AmberNeural", # US Female, expressive & vibrant
|
58 |
+
"ChronoChimp 🐒": "en-GB-LibbyNeural" # UK Female, cheerful & distinct
|
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 |
+
os.makedirs(CHAT_DIR, exist_ok=True)
|
68 |
+
os.makedirs(VOTE_DIR, exist_ok=True)
|
69 |
+
os.makedirs(AUDIO_DIR, exist_ok=True)
|
70 |
+
os.makedirs(HISTORY_DIR, exist_ok=True)
|
71 |
+
|
72 |
+
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
73 |
+
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
74 |
+
MEDIA_VOTES_FILE = os.path.join(VOTE_DIR, "media_votes.md")
|
75 |
+
HISTORY_FILE = os.path.join(HISTORY_DIR, "chat_history.md")
|
76 |
+
|
77 |
+
# Fancy digits - numbers got style! 🔢💃
|
78 |
+
UNICODE_DIGITS = {i: f"{i}\uFE0F⃣" for i in range(10)}
|
79 |
+
|
80 |
+
# Massive font collection - typography bonanza! 🖋️🎨
|
81 |
+
UNICODE_FONTS = [
|
82 |
+
("Normal", lambda x: x),
|
83 |
+
("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)),
|
84 |
+
("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)),
|
85 |
+
("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)),
|
86 |
+
("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)),
|
87 |
+
("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)),
|
88 |
+
("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)),
|
89 |
+
("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)),
|
90 |
+
("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)),
|
91 |
+
("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)),
|
92 |
+
("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)),
|
93 |
+
("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)),
|
94 |
+
("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)),
|
95 |
+
("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)),
|
96 |
+
("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)),
|
97 |
+
("Squared", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F130) if 'A' <= c <= 'Z' else c for c in x)),
|
98 |
+
("Negative Circled", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F150) if 'A' <= c <= 'Z' else c for c in x)),
|
99 |
+
("Negative Squared", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F170) if 'A' <= c <= 'Z' else c for c in x)),
|
100 |
+
("Regional Indicator", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F1E6) if 'A' <= c <= 'Z' else c for c in x)),
|
101 |
+
]
|
102 |
+
|
103 |
+
# Global state - keeping tabs! 🌍📋
|
104 |
+
if 'server_running' not in st.session_state:
|
105 |
+
st.session_state.server_running = False
|
106 |
+
if 'server_task' not in st.session_state:
|
107 |
+
st.session_state.server_task = None
|
108 |
+
if 'active_connections' not in st.session_state:
|
109 |
+
st.session_state.active_connections = {}
|
110 |
+
|
111 |
+
# Timestamp wizardry - clock ticks with flair! ⏰🎩
|
112 |
+
def format_timestamp_prefix():
|
113 |
+
return datetime.now().strftime("%Y%m%d_%H%M%S")
|
114 |
+
|
115 |
+
# Node naming - christening the beast! 🌐🍼
|
116 |
+
def get_node_name():
|
117 |
+
parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
|
118 |
+
parser.add_argument('--node-name', type=str, default=None)
|
119 |
+
parser.add_argument('--port', type=int, default=8501)
|
120 |
+
args = parser.parse_args()
|
121 |
+
username = st.session_state.get('username', 'System 🌟')
|
122 |
+
log_action(username, "🌐🍼 - Node naming - christening the beast!")
|
123 |
+
return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
|
124 |
+
|
125 |
+
# Action logger - spying on deeds! 🕵️📜
|
126 |
+
def log_action(username, action):
|
127 |
+
if 'action_log' not in st.session_state:
|
128 |
+
st.session_state.action_log = {}
|
129 |
+
user_log = st.session_state.action_log.setdefault(username, {})
|
130 |
+
current_time = time.time()
|
131 |
+
user_log = {k: v for k, v in user_log.items() if current_time - v < 10}
|
132 |
+
st.session_state.action_log[username] = user_log
|
133 |
+
if action not in user_log:
|
134 |
+
with open(HISTORY_FILE, 'a') as f:
|
135 |
+
f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n")
|
136 |
+
user_log[action] = current_time
|
137 |
+
|
138 |
+
# Clean text - strip the fancy stuff! 🧹📝
|
139 |
+
def clean_text_for_tts(text):
|
140 |
+
# Remove Markdown formatting (e.g., #, *, [], ![])
|
141 |
+
cleaned = re.sub(r'[#*!\[\]]+', '', text)
|
142 |
+
# Replace newlines with spaces and strip extra whitespace
|
143 |
+
cleaned = ' '.join(cleaned.split())
|
144 |
+
# Ensure some text exists, max 200 chars to avoid edgeTTS limits
|
145 |
+
return cleaned[:200] if cleaned else "No text to speak"
|
146 |
+
|
147 |
+
# Chat saver - words locked tight! 💬🔒
|
148 |
+
async def save_chat_entry(username, message):
|
149 |
+
await asyncio.to_thread(log_action, username, "💬🔒 - Chat saver - words locked tight!")
|
150 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
151 |
+
entry = f"[{timestamp}] {username}: {message}"
|
152 |
+
await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"{entry}\n"))
|
153 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
154 |
+
cleaned_message = clean_text_for_tts(message)
|
155 |
+
audio_file = await async_edge_tts_generate(cleaned_message, voice)
|
156 |
+
if audio_file:
|
157 |
+
with open(HISTORY_FILE, 'a') as f:
|
158 |
+
f.write(f"[{timestamp}] {username}: Audio generated - {audio_file}\n")
|
159 |
|
160 |
+
# Chat loader - history unleashed! 📜🚀
|
161 |
+
async def load_chat():
|
162 |
+
username = st.session_state.get('username', 'System 🌟')
|
163 |
+
await asyncio.to_thread(log_action, username, "📜🚀 - Chat loader - history unleashed!")
|
164 |
+
if not os.path.exists(CHAT_FILE):
|
165 |
+
await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub - start chatting! 🎤\n"))
|
166 |
+
with open(CHAT_FILE, 'r') as f:
|
167 |
+
content = await asyncio.to_thread(f.read)
|
168 |
+
return content
|
169 |
+
|
170 |
+
# User lister - who’s in the gang! 👥🎉
|
171 |
+
async def get_user_list(chat_content):
|
172 |
+
username = st.session_state.get('username', 'System 🌟')
|
173 |
+
await asyncio.to_thread(log_action, username, "👥🎉 - User lister - who’s in the gang!")
|
174 |
+
users = set()
|
175 |
+
for line in chat_content.split('\n'):
|
176 |
+
if line.strip() and ': ' in line:
|
177 |
+
user = line.split(': ')[1].split(' ')[0]
|
178 |
+
users.add(user)
|
179 |
+
return sorted(list(users))
|
180 |
+
|
181 |
+
# Join checker - been here before? 🚪🔍
|
182 |
+
async def has_joined_before(client_id, chat_content):
|
183 |
+
username = st.session_state.get('username', 'System 🌟')
|
184 |
+
await asyncio.to_thread(log_action, username, "🚪🔍 - Join checker - been here before?")
|
185 |
+
return any(f"Client-{client_id} has joined" in line for line in chat_content.split('\n'))
|
186 |
+
|
187 |
+
# Suggestion maker - old quips resurface! 💡📝
|
188 |
+
async def get_message_suggestions(chat_content, prefix):
|
189 |
+
username = st.session_state.get('username', 'System 🌟')
|
190 |
+
await asyncio.to_thread(log_action, username, "💡📝 - Suggestion maker - old quips resurface!")
|
191 |
+
lines = chat_content.split('\n')
|
192 |
+
messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
|
193 |
+
return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5]
|
194 |
+
|
195 |
+
# Vote saver - cheers recorded! 👍📊
|
196 |
+
async def save_vote(file, item, user_hash, username, comment=""):
|
197 |
+
await asyncio.to_thread(log_action, username, "👍📊 - Vote saver - cheers recorded!")
|
198 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
199 |
+
entry = f"[{timestamp}] {user_hash} voted for {item}"
|
200 |
+
await asyncio.to_thread(lambda: open(file, 'a').write(f"{entry}\n"))
|
201 |
+
await asyncio.to_thread(lambda: open(HISTORY_FILE, "a").write(f"- {timestamp} - User {user_hash} voted for {item}\n"))
|
202 |
+
chat_message = f"{username} upvoted: \"{item}\""
|
203 |
+
if comment:
|
204 |
+
chat_message += f" - {comment}"
|
205 |
+
await save_chat_entry(username, chat_message)
|
206 |
+
|
207 |
+
# Vote counter - tallying the love! 🏆📈
|
208 |
+
async def load_votes(file):
|
209 |
+
username = st.session_state.get('username', 'System 🌟')
|
210 |
+
await asyncio.to_thread(log_action, username, "🏆📈 - Vote counter - tallying the love!")
|
211 |
+
if not os.path.exists(file):
|
212 |
+
await asyncio.to_thread(lambda: open(file, 'w').write("# Vote Tally\n\nNo votes yet - get clicking! 🖱️\n"))
|
213 |
+
with open(file, 'r') as f:
|
214 |
+
content = await asyncio.to_thread(f.read)
|
215 |
+
lines = content.strip().split('\n')[2:]
|
216 |
+
votes = {}
|
217 |
+
user_votes = set()
|
218 |
+
for line in lines:
|
219 |
+
if line.strip() and 'voted for' in line:
|
220 |
+
user_hash = line.split('] ')[1].split(' voted for ')[0]
|
221 |
+
item = line.split('voted for ')[1]
|
222 |
+
vote_key = f"{user_hash}-{item}"
|
223 |
+
if vote_key not in user_votes:
|
224 |
+
votes[item] = votes.get(item, 0) + 1
|
225 |
+
user_votes.add(vote_key)
|
226 |
+
return votes
|
227 |
+
|
228 |
+
# Hash generator - secret codes ahoy! 🔑🕵️
|
229 |
+
async def generate_user_hash():
|
230 |
+
username = st.session_state.get('username', 'System 🌟')
|
231 |
+
await asyncio.to_thread(log_action, username, "🔑🕵️ - Hash generator - secret codes ahoy!")
|
232 |
+
if 'user_hash' not in st.session_state:
|
233 |
+
st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8]
|
234 |
+
return st.session_state.user_hash
|
235 |
+
|
236 |
+
# Audio maker - voices come alive! 🎶🌟
|
237 |
async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
|
238 |
+
username = st.session_state.get('username', 'System 🌟')
|
239 |
+
await asyncio.to_thread(log_action, username, "🎶🌟 - Audio maker - voices come alive!")
|
240 |
+
timestamp = format_timestamp_prefix()
|
241 |
+
filename = os.path.join(AUDIO_DIR, f"audio_{timestamp}_{random.randint(1000, 9999)}.mp3")
|
242 |
+
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
243 |
+
try:
|
|
|
|
|
244 |
await communicate.save(filename)
|
245 |
+
return filename if os.path.exists(filename) else None
|
246 |
+
except edge_tts.exceptions.NoAudioReceived:
|
247 |
+
with open(HISTORY_FILE, 'a') as f:
|
248 |
+
f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {username}: Audio failed - No audio received for '{text}'\n")
|
249 |
+
return None
|
250 |
|
251 |
+
# Audio player - tunes blast off! 🔊🚀
|
252 |
def play_and_download_audio(file_path):
|
|
|
253 |
if file_path and os.path.exists(file_path):
|
254 |
st.audio(file_path)
|
255 |
+
with open(file_path, "rb") as f:
|
256 |
+
b64 = base64.b64encode(f.read()).decode()
|
257 |
+
dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">🎵 Download {os.path.basename(file_path)}</a>'
|
258 |
+
st.markdown(dl_link, unsafe_allow_html=True)
|
259 |
+
|
260 |
+
# Image saver - pics preserved! 📸💾
|
261 |
+
async def save_pasted_image(image_data):
|
262 |
+
username = st.session_state.get('username', 'System 🌟')
|
263 |
+
await asyncio.to_thread(log_action, username, "📸💾 - Image saver - pics preserved!")
|
264 |
+
timestamp = format_timestamp_prefix()
|
265 |
+
filename = f"paste_{timestamp}.png"
|
266 |
+
filepath = os.path.join('./', filename)
|
267 |
+
if ',' in image_data:
|
268 |
+
image_data = image_data.split(',')[1]
|
269 |
+
img_bytes = base64.b64decode(image_data)
|
270 |
+
img = Image.open(io.BytesIO(img_bytes))
|
271 |
+
await asyncio.to_thread(img.save, filepath, "PNG")
|
272 |
+
return filename
|
|
|
|
|
|
|
273 |
|
274 |
+
# Video renderer - movies roll! 🎥🎬
|
275 |
+
async def get_video_html(video_path, width="100%"):
|
276 |
+
username = st.session_state.get('username', 'System 🌟')
|
277 |
+
await asyncio.to_thread(log_action, username, "🎥🎬 - Video renderer - movies roll!")
|
278 |
+
video_url = f"data:video/mp4;base64,{base64.b64encode(await asyncio.to_thread(open, video_path, 'rb').read()).decode()}"
|
279 |
+
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>'
|
280 |
+
|
281 |
+
# Audio renderer - sounds soar! 🎶✈️
|
282 |
+
async def get_audio_html(audio_path, width="100%"):
|
283 |
+
username = st.session_state.get('username', 'System 🌟')
|
284 |
+
await asyncio.to_thread(log_action, username, "🎶✈️ - Audio renderer - sounds soar!")
|
285 |
+
audio_url = f"data:audio/mpeg;base64,{base64.b64encode(await asyncio.to_thread(open, audio_path, 'rb').read()).decode()}"
|
286 |
+
return f'<audio controls style="width: {width};"><source src="{audio_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>'
|
287 |
+
|
288 |
+
# Websocket handler - chat links up! 🌐🔗
|
289 |
async def websocket_handler(websocket, path):
|
290 |
+
username = st.session_state.get('username', 'System 🌟')
|
291 |
+
await asyncio.to_thread(log_action, username, "🌐🔗 - Websocket handler - chat links up!")
|
|
|
|
|
|
|
|
|
|
|
|
|
292 |
try:
|
293 |
+
client_id = str(uuid.uuid4())
|
294 |
+
room_id = "chat"
|
295 |
+
st.session_state.active_connections.setdefault(room_id, {})[client_id] = websocket
|
296 |
+
chat_content = await load_chat()
|
297 |
+
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
|
298 |
+
if not await has_joined_before(client_id, chat_content):
|
299 |
+
await save_chat_entry(f"Client-{client_id}", f"{username} has joined {START_ROOM}!")
|
300 |
async for message in websocket:
|
301 |
+
parts = message.split('|', 1)
|
302 |
+
if len(parts) == 2:
|
303 |
+
username, content = parts
|
304 |
+
await save_chat_entry(username, content)
|
305 |
+
await broadcast_message(f"{username}|{content}", room_id)
|
306 |
+
except websockets.ConnectionClosed:
|
307 |
+
pass
|
308 |
finally:
|
309 |
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
|
310 |
del st.session_state.active_connections[room_id][client_id]
|
311 |
|
312 |
+
# Message broadcaster - words fly far! 📢✈️
|
313 |
async def broadcast_message(message, room_id):
|
314 |
+
username = st.session_state.get('username', 'System 🌟')
|
315 |
+
await asyncio.to_thread(log_action, username, "📢✈️ - Message broadcaster - words fly far!")
|
316 |
if room_id in st.session_state.active_connections:
|
317 |
disconnected = []
|
318 |
for client_id, ws in st.session_state.active_connections[room_id].items():
|
319 |
+
try:
|
320 |
+
await ws.send(message)
|
321 |
+
except websockets.ConnectionClosed:
|
322 |
+
disconnected.append(client_id)
|
323 |
+
for client_id in disconnected:
|
324 |
+
del st.session_state.active_connections[room_id][client_id]
|
325 |
|
326 |
+
# Server starter - web spins up! 🖥️🌀
|
327 |
async def run_websocket_server():
|
328 |
+
username = st.session_state.get('username', 'System 🌟')
|
329 |
+
await asyncio.to_thread(log_action, username, "🖥️🌀 - Server starter - web spins up!")
|
330 |
if not st.session_state.server_running:
|
331 |
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
|
332 |
st.session_state.server_running = True
|
333 |
await server.wait_closed()
|
334 |
|
335 |
+
# Voice processor - speech to text! 🎤📝
|
336 |
+
async def process_voice_input(audio_bytes):
|
337 |
+
username = st.session_state.get('username', 'System 🌟')
|
338 |
+
await asyncio.to_thread(log_action, username, "🎤📝 - Voice processor - speech to text!")
|
339 |
+
if audio_bytes:
|
340 |
+
text = "Voice input simulation" # Replace with actual speech-to-text logic
|
341 |
+
await save_chat_entry(username, text)
|
342 |
+
|
343 |
+
# Interface builder - UI takes shape! 🎨🖌️
|
344 |
+
def create_streamlit_interface():
|
345 |
+
loop = asyncio.new_event_loop()
|
346 |
+
asyncio.set_event_loop(loop)
|
347 |
+
|
348 |
+
async def async_interface():
|
349 |
+
if 'username' not in st.session_state:
|
350 |
+
chat_content = await load_chat()
|
351 |
+
available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
|
352 |
+
st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
|
353 |
+
|
354 |
+
if 'refresh_rate' not in st.session_state:
|
355 |
+
st.session_state.refresh_rate = 5
|
356 |
+
if 'timer_start' not in st.session_state:
|
357 |
+
st.session_state.timer_start = time.time()
|
358 |
+
if 'quote_line' not in st.session_state:
|
359 |
+
st.session_state.quote_line = None
|
360 |
+
if 'pasted_image_data' not in st.session_state:
|
361 |
+
st.session_state.pasted_image_data = None
|
362 |
+
if 'message_text' not in st.session_state:
|
363 |
+
st.session_state.message_text = ""
|
364 |
+
if 'audio_cache' not in st.session_state:
|
365 |
+
st.session_state.audio_cache = {}
|
366 |
+
if 'chat_history' not in st.session_state:
|
367 |
+
st.session_state.chat_history = []
|
368 |
+
|
369 |
+
st.markdown("""
|
370 |
+
<style>
|
371 |
+
.chat-box {font-family: monospace; background: #1e1e1e; color: #d4d4d4; padding: 10px; border-radius: 5px; height: 300px; overflow-y: auto;}
|
372 |
+
.timer {font-size: 24px; color: #ffcc00; text-align: center; animation: pulse 1s infinite;}
|
373 |
+
@keyframes pulse {0% {transform: scale(1);} 50% {transform: scale(1.1);} 100% {transform: scale(1);}}
|
374 |
+
#paste-target {border: 2px dashed #ccc; padding: 20px; text-align: center; cursor: pointer;}
|
375 |
+
</style>
|
376 |
+
""", unsafe_allow_html=True)
|
377 |
+
|
378 |
+
st.title(f"🤖🧠MMO {st.session_state.username}📝🔬")
|
379 |
+
st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! 🎉")
|
380 |
+
|
381 |
+
if not st.session_state.server_task:
|
382 |
+
st.session_state.server_task = loop.create_task(run_websocket_server())
|
383 |
+
|
384 |
+
audio_bytes = audio_recorder()
|
385 |
+
if audio_bytes:
|
386 |
+
await process_voice_input(audio_bytes)
|
387 |
+
st.rerun()
|
388 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
389 |
st.subheader(f"{START_ROOM} Chat 💬")
|
390 |
chat_content = await load_chat()
|
391 |
+
chat_lines = chat_content.split('\n')
|
392 |
+
chat_votes = await load_votes(QUOTE_VOTES_FILE)
|
393 |
+
for i, line in enumerate(chat_lines):
|
394 |
if line.strip() and ': ' in line:
|
395 |
+
col1, col2, col3 = st.columns([4, 1, 1])
|
396 |
+
with col1:
|
397 |
+
st.markdown(line)
|
398 |
+
username = line.split(': ')[1].split(' ')[0]
|
399 |
+
audio_file = None
|
400 |
+
cache_key = f"{line}_{FUN_USERNAMES.get(username, 'en-US-AriaNeural')}"
|
401 |
+
if cache_key in st.session_state.audio_cache:
|
402 |
+
audio_file = st.session_state.audio_cache[cache_key]
|
403 |
+
else:
|
404 |
+
cleaned_text = clean_text_for_tts(line.split(': ', 1)[1])
|
405 |
+
audio_file = await async_edge_tts_generate(cleaned_text, FUN_USERNAMES.get(username, "en-US-AriaNeural"))
|
406 |
+
st.session_state.audio_cache[cache_key] = audio_file
|
407 |
+
if audio_file:
|
408 |
+
play_and_download_audio(audio_file)
|
409 |
+
with col2:
|
410 |
+
vote_count = chat_votes.get(line.split('. ')[1] if '. ' in line else line, 0)
|
411 |
+
if st.button(f"👍 {vote_count}", key=f"chat_vote_{i}"):
|
412 |
+
comment = st.session_state.message_text
|
413 |
+
await save_vote(QUOTE_VOTES_FILE, line.split('. ')[1] if '. ' in line else line, await generate_user_hash(), st.session_state.username, comment)
|
414 |
+
if st.session_state.pasted_image_data:
|
415 |
+
filename = await save_pasted_image(st.session_state.pasted_image_data)
|
416 |
+
if filename:
|
417 |
+
await save_chat_entry(st.session_state.username, f"Pasted image: {filename}")
|
418 |
+
st.session_state.pasted_image_data = None
|
419 |
+
st.session_state.message_text = ''
|
420 |
+
st.rerun()
|
421 |
+
with col3:
|
422 |
+
if st.button("📢 Quote", key=f"quote_{i}"):
|
423 |
+
st.session_state.quote_line = line
|
424 |
+
st.rerun()
|
425 |
+
|
426 |
+
if 'quote_line' in st.session_state:
|
427 |
+
st.markdown(f"### Quoting: {st.session_state.quote_line}")
|
428 |
+
quote_response = st.text_area("Add your response", key="quote_response")
|
429 |
+
if st.button("Send Quote 🚀", key="send_quote"):
|
430 |
+
async def process_quote():
|
431 |
+
await asyncio.to_thread(log_action, st.session_state.username, "📢💬 - Quote processor - echoes resound!")
|
432 |
+
markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
|
433 |
+
if st.session_state.pasted_image_data:
|
434 |
+
filename = await save_pasted_image(st.session_state.pasted_image_data)
|
435 |
+
if filename:
|
436 |
+
markdown_response += f"\n- **Image**: "
|
437 |
+
st.session_state.pasted_image_data = None
|
438 |
+
try:
|
439 |
+
await save_chat_entry(st.session_state.username, markdown_response)
|
440 |
+
except edge_tts.exceptions.NoAudioReceived:
|
441 |
+
# Log failure but continue without audio
|
442 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
443 |
+
with open(HISTORY_FILE, 'a') as f:
|
444 |
+
f.write(f"[{timestamp}] {st.session_state.username}: Quote saved without audio - No audio received\n")
|
445 |
+
await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"[{timestamp}] {st.session_state.username}: {markdown_response}\n"))
|
446 |
+
loop.run_until_complete(process_quote())
|
447 |
+
del st.session_state.quote_line
|
448 |
+
st.session_state.message_text = ''
|
449 |
st.rerun()
|
450 |
|
451 |
+
new_username = st.selectbox("Change Name", [""] + list(FUN_USERNAMES.keys()), index=0)
|
452 |
+
if new_username and new_username != st.session_state.username:
|
453 |
+
loop.run_until_complete(save_chat_entry("System 🌟", f"{st.session_state.username} changed name to {new_username}"))
|
454 |
+
st.session_state.username = new_username
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
455 |
st.rerun()
|
456 |
|
457 |
+
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))
|
458 |
+
if st.button("Send 🚀", key="send_button") and message.strip():
|
459 |
+
loop.run_until_complete(save_chat_entry(st.session_state.username, message))
|
460 |
+
if st.session_state.pasted_image_data:
|
461 |
+
filename = loop.run_until_complete(save_pasted_image(st.session_state.pasted_image_data))
|
462 |
+
if filename:
|
463 |
+
loop.run_until_complete(save_chat_entry(st.session_state.username, f"Pasted image: {filename}"))
|
464 |
+
st.session_state.pasted_image_data = None
|
465 |
+
st.session_state.message_text = ''
|
466 |
+
st.rerun()
|
467 |
+
|
468 |
+
components.html(
|
469 |
+
"""
|
470 |
+
<div id="paste-target">Paste an image here (Ctrl+V)</div>
|
471 |
+
<script>
|
472 |
+
const pasteTarget = document.getElementById('paste-target');
|
473 |
+
pasteTarget.addEventListener('paste', (event) => {
|
474 |
+
const items = (event.clipboardData || window.clipboardData).items;
|
475 |
+
for (let i = 0; i < items.length; i++) {
|
476 |
+
if (items[i].type.indexOf('image') !== -1) {
|
477 |
+
const blob = items[i].getAsFile();
|
478 |
+
const reader = new FileReader();
|
479 |
+
reader.onload = (e) => {
|
480 |
+
window.parent.postMessage({
|
481 |
+
type: 'streamlit:setComponentValue',
|
482 |
+
value: e.target.result
|
483 |
+
}, '*');
|
484 |
+
pasteTarget.innerHTML = '<p>Image pasted! Processing...</p>';
|
485 |
+
};
|
486 |
+
reader.readAsDataURL(blob);
|
487 |
+
}
|
488 |
+
}
|
489 |
+
event.preventDefault();
|
490 |
+
});
|
491 |
+
</script>
|
492 |
+
""",
|
493 |
+
height=100
|
494 |
+
)
|
495 |
+
|
496 |
+
st.subheader("Media Gallery 🎨🎶🎥")
|
497 |
+
uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp3', 'mp4'])
|
498 |
+
if uploaded_file:
|
499 |
+
file_path = os.path.join('./', uploaded_file.name)
|
500 |
+
await asyncio.to_thread(lambda: open(file_path, 'wb').write(uploaded_file.getbuffer()))
|
501 |
+
st.success(f"Uploaded {uploaded_file.name}")
|
502 |
+
|
503 |
+
media_files = glob.glob("./*.png") + glob.glob("./*.jpg") + glob.glob("./*.mp3") + glob.glob("./*.mp4")
|
504 |
+
if media_files:
|
505 |
+
cols = st.columns(3)
|
506 |
+
media_votes = loop.run_until_complete(load_votes(MEDIA_VOTES_FILE))
|
507 |
+
for idx, media_file in enumerate(media_files):
|
508 |
+
vote_count = media_votes.get(media_file, 0)
|
509 |
+
if vote_count > 0:
|
510 |
+
with cols[idx % 3]:
|
511 |
+
if media_file.endswith(('.png', '.jpg')):
|
512 |
+
st.image(media_file, use_container_width=True)
|
513 |
+
elif media_file.endswith('.mp3'):
|
514 |
+
st.markdown(loop.run_until_complete(get_audio_html(media_file)), unsafe_allow_html=True)
|
515 |
+
elif media_file.endswith('.mp4'):
|
516 |
+
st.markdown(loop.run_until_complete(get_video_html(media_file)), unsafe_allow_html=True)
|
517 |
+
col1, col2 = st.columns(2)
|
518 |
+
with col1:
|
519 |
+
if st.button(f"👍 {vote_count}", key=f"media_vote_{idx}"):
|
520 |
+
comment = st.session_state.message_text
|
521 |
+
loop.run_until_complete(save_vote(MEDIA_VOTES_FILE, media_file, await generate_user_hash(), st.session_state.username, comment))
|
522 |
+
if st.session_state.pasted_image_data:
|
523 |
+
filename = loop.run_until_complete(save_pasted_image(st.session_state.pasted_image_data))
|
524 |
+
if filename:
|
525 |
+
loop.run_until_complete(save_chat_entry(st.session_state.username, f"Pasted image: {filename}"))
|
526 |
+
st.session_state.pasted_image_data = None
|
527 |
+
st.session_state.message_text = ''
|
528 |
+
st.rerun()
|
529 |
+
with col2:
|
530 |
+
if st.button("🗑️", key=f"media_delete_{idx}"):
|
531 |
+
await asyncio.to_thread(os.remove, media_file)
|
532 |
+
st.rerun()
|
533 |
+
|
534 |
+
st.subheader("Refresh ⏳")
|
535 |
+
refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
|
536 |
+
st.session_state.refresh_rate = refresh_rate
|
537 |
+
timer_placeholder = st.empty()
|
538 |
+
for i in range(st.session_state.refresh_rate, -1, -1):
|
539 |
+
font_name, font_func = random.choice(UNICODE_FONTS)
|
540 |
+
countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
|
541 |
+
timer_placeholder.markdown(f"<p class='timer'>⏳ {font_func('Refresh in:')} {countdown_str}</p>", unsafe_allow_html=True)
|
542 |
+
loop.run_until_complete(asyncio.sleep(1))
|
543 |
st.rerun()
|
544 |
|
545 |
+
st.sidebar.subheader("Chat History 📜")
|
546 |
+
with open(HISTORY_FILE, 'r') as f:
|
547 |
+
history_content = f.read()
|
548 |
+
st.sidebar.markdown(history_content)
|
549 |
+
|
550 |
+
loop.run_until_complete(async_interface())
|
|
|
551 |
|
552 |
+
# Main execution - let’s roll! 🎲🚀
|
553 |
def main():
|
554 |
+
NODE_NAME, port = get_node_name()
|
555 |
+
create_streamlit_interface()
|
556 |
|
557 |
if __name__ == "__main__":
|
558 |
main()
|