Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
|
|
| 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,301 +17,225 @@ import edge_tts
|
|
| 18 |
from audio_recorder_streamlit import audio_recorder
|
| 19 |
import nest_asyncio
|
| 20 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
# Patch for
|
| 23 |
nest_asyncio.apply()
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
icons = '🤖🧠🔬📝'
|
| 27 |
-
START_ROOM = "Sector 🌌"
|
| 28 |
-
|
| 29 |
-
# Page setup - dressing up the window! 🖼️🎀
|
| 30 |
st.set_page_config(
|
| 31 |
-
page_title="
|
| 32 |
-
page_icon=
|
| 33 |
layout="wide",
|
| 34 |
initial_sidebar_state="auto"
|
| 35 |
)
|
| 36 |
|
| 37 |
-
#
|
|
|
|
|
|
|
| 38 |
FUN_USERNAMES = {
|
| 39 |
-
"CosmicJester 🌌": "en-US-AriaNeural",
|
| 40 |
-
"PixelPanda 🐼": "en-US-JennyNeural",
|
| 41 |
-
"QuantumQuack 🦆": "en-GB-SoniaNeural",
|
| 42 |
-
"StellarSquirrel 🐿️": "en-AU-NatashaNeural",
|
| 43 |
-
"GizmoGuru ⚙️": "en-CA-ClaraNeural",
|
| 44 |
-
"NebulaNinja 🌠": "en-US-GuyNeural",
|
| 45 |
-
"ByteBuster 💾": "en-GB-RyanNeural",
|
| 46 |
-
"GalacticGopher 🌍": "en-AU-WilliamNeural",
|
| 47 |
-
"RocketRaccoon 🚀": "en-CA-LiamNeural",
|
| 48 |
-
"EchoElf 🧝": "en-US-AnaNeural",
|
| 49 |
-
"PhantomFox 🦊": "en-US-BrandonNeural", # 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 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
os.
|
| 68 |
-
|
| 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 |
-
#
|
| 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 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
| 242 |
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 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 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
await asyncio.to_thread(img.save, filepath, "PNG")
|
| 272 |
-
return filename
|
| 273 |
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 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 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 302 |
-
|
| 303 |
-
username, content = parts
|
| 304 |
await save_chat_entry(username, content)
|
| 305 |
-
|
|
|
|
| 306 |
except websockets.ConnectionClosed:
|
| 307 |
-
|
| 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 |
-
|
| 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():
|
|
@@ -321,238 +244,253 @@ async def broadcast_message(message, room_id):
|
|
| 321 |
except websockets.ConnectionClosed:
|
| 322 |
disconnected.append(client_id)
|
| 323 |
for client_id in disconnected:
|
| 324 |
-
|
|
|
|
| 325 |
|
| 326 |
-
# Server starter - web spins up! 🖥️🌀
|
| 327 |
async def run_websocket_server():
|
| 328 |
-
|
| 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 |
-
#
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
if
|
| 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 |
st.subheader(f"{START_ROOM} Chat 💬")
|
| 390 |
chat_content = await load_chat()
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 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 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
st.
|
| 465 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
st.rerun()
|
| 467 |
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
for
|
| 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 |
-
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 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
st.sidebar.
|
| 549 |
-
|
| 550 |
-
|
|
|
|
| 551 |
|
| 552 |
-
# Main execution - let’s roll! 🎲🚀
|
| 553 |
def main():
|
| 554 |
-
|
| 555 |
-
|
| 556 |
|
| 557 |
if __name__ == "__main__":
|
| 558 |
main()
|
|
|
|
| 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 |
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 |
+
# 🛠️ Patch asyncio for nesting glory
|
| 36 |
nest_asyncio.apply()
|
| 37 |
|
| 38 |
+
# 🎨 Page Config
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
st.set_page_config(
|
| 40 |
+
page_title="🚲TalkingAIResearcher🏆",
|
| 41 |
+
page_icon="🚲🏆",
|
| 42 |
layout="wide",
|
| 43 |
initial_sidebar_state="auto"
|
| 44 |
)
|
| 45 |
|
| 46 |
+
# 🌟 Static Config
|
| 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):
|
| 89 |
+
self.start = time.time()
|
| 90 |
+
return self
|
| 91 |
+
def __exit__(self, *args):
|
| 92 |
+
duration = time.time() - self.start
|
| 93 |
+
st.session_state['operation_timings'][self.name] = duration
|
| 94 |
+
st.session_state['performance_metrics'][self.name].append(duration)
|
| 95 |
+
|
| 96 |
+
# 🎛️ Session State Init
|
| 97 |
+
def init_session_state():
|
| 98 |
+
defaults = {
|
| 99 |
+
'server_running': False, 'server_task': None, 'active_connections': {},
|
| 100 |
+
'media_notifications': [], 'last_chat_update': 0, 'displayed_chat_lines': [],
|
| 101 |
+
'message_text': "", 'audio_cache': {}, 'pasted_image_data': None,
|
| 102 |
+
'quote_line': None, 'refresh_rate': 5, 'base64_cache': {},
|
| 103 |
+
'transcript_history': [], 'last_transcript': "", 'image_hashes': set(),
|
| 104 |
+
'tts_voice': "en-US-AriaNeural", 'chat_history': [], 'marquee_settings': {
|
| 105 |
+
"background": "#1E1E1E", "color": "#FFFFFF", "font-size": "14px",
|
| 106 |
+
"animationDuration": "20s", "width": "100%", "lineHeight": "35px"
|
| 107 |
+
}, 'operation_timings': {}, 'performance_metrics': defaultdict(list),
|
| 108 |
+
'enable_audio': True, 'download_link_cache': {}, 'username': None,
|
| 109 |
+
'autosend': True, 'autosearch': True, 'last_message': "", 'last_query': ""
|
| 110 |
+
}
|
| 111 |
+
for k, v in defaults.items():
|
| 112 |
+
if k not in st.session_state: st.session_state[k] = v
|
| 113 |
+
|
| 114 |
+
# 🖌️ Marquee Helpers
|
| 115 |
+
def update_marquee_settings_ui():
|
| 116 |
+
# 🎨 Sidebar marquee controls
|
| 117 |
+
st.sidebar.markdown("### 🎯 Marquee Settings")
|
| 118 |
+
cols = st.sidebar.columns(2)
|
| 119 |
+
with cols[0]:
|
| 120 |
+
st.session_state['marquee_settings']['background'] = st.color_picker("🎨 Background", "#1E1E1E")
|
| 121 |
+
st.session_state['marquee_settings']['color'] = st.color_picker("✍️ Text", "#FFFFFF")
|
| 122 |
+
with cols[1]:
|
| 123 |
+
st.session_state['marquee_settings']['font-size'] = f"{st.slider('📏 Size', 10, 24, 14)}px"
|
| 124 |
+
st.session_state['marquee_settings']['animationDuration'] = f"{st.slider('⏱️ Speed', 1, 20, 20)}s"
|
| 125 |
+
|
| 126 |
+
def display_marquee(text, settings, key_suffix=""):
|
| 127 |
+
# 🌈 Show marquee with truncation
|
| 128 |
+
truncated = text[:280] + "..." if len(text) > 280 else text
|
| 129 |
+
streamlit_marquee(content=truncated, **settings, key=f"marquee_{key_suffix}")
|
| 130 |
+
st.write("")
|
| 131 |
+
|
| 132 |
+
# 📝 Text & File Helpers
|
| 133 |
+
def clean_text_for_tts(text): return re.sub(r'[#*!\[\]]+', '', ' '.join(text.split()))[:200] or "No text"
|
| 134 |
+
def clean_text_for_filename(text): return '_'.join(re.sub(r'[^\w\s-]', '', text.lower()).split())[:200]
|
| 135 |
+
def get_high_info_terms(text, top_n=10):
|
| 136 |
+
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with'}
|
| 137 |
+
words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
|
| 138 |
+
bi_grams = [' '.join(pair) for pair in zip(words, words[1:])]
|
| 139 |
+
filtered = [t for t in words + bi_grams if t not in stop_words and len(t.split()) <= 2]
|
| 140 |
+
return [t for t, _ in Counter(filtered).most_common(top_n)]
|
| 141 |
+
|
| 142 |
+
def generate_filename(prompt, response, file_type="md"):
|
| 143 |
+
# 📁 Smart filename with info terms
|
| 144 |
+
prefix = format_timestamp_prefix()
|
| 145 |
+
terms = get_high_info_terms(prompt + " " + response, 5)
|
| 146 |
+
snippet = clean_text_for_filename(prompt[:40] + " " + response[:40])
|
| 147 |
+
wct, sw = len(prompt.split()), len(response.split())
|
| 148 |
+
dur = round((wct + sw) / 2.5)
|
| 149 |
+
base = '_'.join(list(dict.fromkeys(terms + [snippet])))[:200 - len(prefix) - len(f"_wct{wct}_sw{sw}_dur{dur}.{file_type}")]
|
| 150 |
+
return f"{prefix}{base}_wct{wct}_sw{sw}_dur{dur}.{file_type}"
|
| 151 |
+
|
| 152 |
+
def create_file(prompt, response, file_type="md"):
|
| 153 |
+
# 📝 Save file with Q&A
|
| 154 |
+
filename = generate_filename(prompt, response, file_type)
|
| 155 |
+
with open(filename, 'w', encoding='utf-8') as f: f.write(prompt + "\n\n" + response)
|
| 156 |
+
return filename
|
| 157 |
|
| 158 |
+
def get_download_link(file, file_type="mp3"):
|
| 159 |
+
# ⬇️ Cached download link
|
| 160 |
+
cache_key = f"dl_{file}"
|
| 161 |
+
if cache_key not in st.session_state['download_link_cache']:
|
| 162 |
+
with open(file, "rb") as f:
|
| 163 |
+
b64 = base64.b64encode(f.read()).decode()
|
| 164 |
+
st.session_state['download_link_cache'][cache_key] = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file)}">{FILE_EMOJIS.get(file_type, "Download")} Download {os.path.basename(file)}</a>'
|
| 165 |
+
return st.session_state['download_link_cache'][cache_key]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
+
# 🎶 Audio Processing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
|
| 169 |
+
# 🎵 Async TTS with caching - Fixed KeyError!
|
| 170 |
+
cache_key = f"{text[:100]}_{voice}_{rate}_{pitch}_{file_format}"
|
| 171 |
+
if cache_key in st.session_state['audio_cache']: return st.session_state['audio_cache'][cache_key], 0
|
| 172 |
+
start_time = time.time()
|
| 173 |
+
text = clean_text_for_tts(text)
|
| 174 |
+
if not text: return None, 0
|
| 175 |
+
filename = f"audio_{format_timestamp_prefix()}_{random.randint(1000, 9999)}.{file_format}"
|
| 176 |
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
| 177 |
+
await communicate.save(filename)
|
| 178 |
+
st.session_state['audio_cache'][cache_key] = filename
|
| 179 |
+
return filename, time.time() - start_time # No reliance on operation_timings
|
| 180 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
def play_and_download_audio(file_path):
|
| 182 |
+
# 🔊 Play + download
|
| 183 |
if file_path and os.path.exists(file_path):
|
| 184 |
st.audio(file_path)
|
| 185 |
+
st.markdown(get_download_link(file_path), unsafe_allow_html=True)
|
| 186 |
+
|
| 187 |
+
async def save_chat_entry(username, message, is_markdown=False):
|
| 188 |
+
# 💬 Save chat with multicast broadcast
|
| 189 |
+
central = pytz.timezone('US/Central')
|
| 190 |
+
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
|
| 191 |
+
entry = f"[{timestamp}] {username}: {message}" if not is_markdown else f"[{timestamp}] {username}:\n```markdown\n{message}\n```"
|
| 192 |
+
with open(CHAT_FILE, 'a') as f: f.write(f"{entry}\n")
|
| 193 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
| 194 |
+
audio_file, _ = await async_edge_tts_generate(clean_text_for_tts(message), voice)
|
| 195 |
+
if audio_file:
|
| 196 |
+
with open(HISTORY_FILE, 'a') as f: f.write(f"[{timestamp}] {username}: Audio - {audio_file}\n")
|
| 197 |
+
await broadcast_message(f"{username}|{message}", "chat")
|
| 198 |
+
st.session_state.last_chat_update = time.time()
|
| 199 |
+
st.session_state.chat_history.append(entry) # Append to history
|
| 200 |
+
return audio_file
|
|
|
|
|
|
|
| 201 |
|
| 202 |
+
async def load_chat():
|
| 203 |
+
# 📜 Load chat history - Numbered like old version
|
| 204 |
+
if not os.path.exists(CHAT_FILE):
|
| 205 |
+
with open(CHAT_FILE, 'a') as f: f.write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub! 🎤\n")
|
| 206 |
+
with open(CHAT_FILE, 'r') as f:
|
| 207 |
+
content = f.read().strip()
|
| 208 |
+
lines = content.split('\n')
|
| 209 |
+
numbered_content = "\n".join(f"{i+1}. {line}" for i, line in enumerate(lines) if line.strip())
|
| 210 |
+
return numbered_content
|
| 211 |
+
|
| 212 |
+
# 🌐 WebSocket Handling
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
async def websocket_handler(websocket, path):
|
| 214 |
+
# 🤝 Handle WebSocket clients - Fixed multicast
|
| 215 |
+
client_id = str(uuid.uuid4())
|
| 216 |
+
room_id = "chat"
|
| 217 |
+
if room_id not in st.session_state.active_connections:
|
| 218 |
+
st.session_state.active_connections[room_id] = {}
|
| 219 |
+
st.session_state.active_connections[room_id][client_id] = websocket
|
| 220 |
+
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
|
| 221 |
+
chat_content = await load_chat()
|
| 222 |
+
if not any(f"Client-{client_id}" in line for line in chat_content.split('\n')):
|
| 223 |
+
await save_chat_entry("System 🌟", f"{username} has joined {START_ROOM}!")
|
| 224 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
async for message in websocket:
|
| 226 |
+
if '|' in message:
|
| 227 |
+
username, content = message.split('|', 1)
|
|
|
|
| 228 |
await save_chat_entry(username, content)
|
| 229 |
+
else:
|
| 230 |
+
await websocket.send("ERROR|Message format: username|content")
|
| 231 |
except websockets.ConnectionClosed:
|
| 232 |
+
await save_chat_entry("System 🌟", f"{username} has left {START_ROOM}!")
|
| 233 |
finally:
|
| 234 |
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
|
| 235 |
del st.session_state.active_connections[room_id][client_id]
|
| 236 |
|
|
|
|
| 237 |
async def broadcast_message(message, room_id):
|
| 238 |
+
# 📢 Broadcast to all clients - Fixed!
|
|
|
|
| 239 |
if room_id in st.session_state.active_connections:
|
| 240 |
disconnected = []
|
| 241 |
for client_id, ws in st.session_state.active_connections[room_id].items():
|
|
|
|
| 244 |
except websockets.ConnectionClosed:
|
| 245 |
disconnected.append(client_id)
|
| 246 |
for client_id in disconnected:
|
| 247 |
+
if client_id in st.session_state.active_connections[room_id]:
|
| 248 |
+
del st.session_state.active_connections[room_id][client_id]
|
| 249 |
|
|
|
|
| 250 |
async def run_websocket_server():
|
| 251 |
+
# 🖥️ Start WebSocket server
|
|
|
|
| 252 |
if not st.session_state.server_running:
|
| 253 |
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
|
| 254 |
st.session_state.server_running = True
|
| 255 |
await server.wait_closed()
|
| 256 |
|
| 257 |
+
# 📚 PDF to Audio
|
| 258 |
+
class AudioProcessor:
|
| 259 |
+
def __init__(self):
|
| 260 |
+
self.cache_dir = AUDIO_CACHE_DIR
|
| 261 |
+
os.makedirs(self.cache_dir, exist_ok=True)
|
| 262 |
+
self.metadata = json.load(open(f"{self.cache_dir}/metadata.json")) if os.path.exists(f"{self.cache_dir}/metadata.json") else {}
|
| 263 |
+
|
| 264 |
+
def _save_metadata(self):
|
| 265 |
+
with open(f"{self.cache_dir}/metadata.json", 'w') as f: json.dump(self.metadata, f)
|
| 266 |
+
|
| 267 |
+
async def create_audio(self, text, voice='en-US-AriaNeural'):
|
| 268 |
+
# 🎶 Generate cached audio
|
| 269 |
+
cache_key = hashlib.md5(f"{text}:{voice}".encode()).hexdigest()
|
| 270 |
+
cache_path = f"{self.cache_dir}/{cache_key}.mp3"
|
| 271 |
+
if cache_key in self.metadata and os.path.exists(cache_path):
|
| 272 |
+
return open(cache_path, 'rb').read()
|
| 273 |
+
text = clean_text_for_tts(text)
|
| 274 |
+
if not text: return None
|
| 275 |
+
communicate = edge_tts.Communicate(text, voice)
|
| 276 |
+
await communicate.save(cache_path)
|
| 277 |
+
self.metadata[cache_key] = {'timestamp': datetime.now().isoformat(), 'text_length': len(text), 'voice': voice}
|
| 278 |
+
self._save_metadata()
|
| 279 |
+
return open(cache_path, 'rb').read()
|
| 280 |
+
|
| 281 |
+
def process_pdf(pdf_file, max_pages, voice, audio_processor):
|
| 282 |
+
# 📄 Convert PDF to audio
|
| 283 |
+
reader = PdfReader(pdf_file)
|
| 284 |
+
total_pages = min(len(reader.pages), max_pages)
|
| 285 |
+
texts, audios = [], {}
|
| 286 |
+
async def process_page(i, text): audios[i] = await audio_processor.create_audio(text, voice)
|
| 287 |
+
for i in range(total_pages):
|
| 288 |
+
text = reader.pages[i].extract_text()
|
| 289 |
+
texts.append(text)
|
| 290 |
+
threading.Thread(target=lambda: asyncio.run(process_page(i, text))).start()
|
| 291 |
+
return texts, audios, total_pages
|
| 292 |
+
|
| 293 |
+
# 🔍 ArXiv & AI Lookup
|
| 294 |
+
def parse_arxiv_refs(ref_text):
|
| 295 |
+
# 📜 Parse ArXiv refs into dicts
|
| 296 |
+
if not ref_text: return []
|
| 297 |
+
papers = []
|
| 298 |
+
current = {}
|
| 299 |
+
for line in ref_text.split('\n'):
|
| 300 |
+
if line.count('|') == 2:
|
| 301 |
+
if current: papers.append(current)
|
| 302 |
+
date, title, *_ = line.strip('* ').split('|')
|
| 303 |
+
url = re.search(r'(https://arxiv.org/\S+)', line).group(1) if re.search(r'(https://arxiv.org/\S+)', line) else f"paper_{len(papers)}"
|
| 304 |
+
current = {'date': date, 'title': title, 'url': url, 'authors': '', 'summary': '', 'full_audio': None, 'download_base64': ''}
|
| 305 |
+
elif current:
|
| 306 |
+
if not current['authors']: current['authors'] = line.strip('* ')
|
| 307 |
+
else: current['summary'] += ' ' + line.strip() if current['summary'] else line.strip()
|
| 308 |
+
if current: papers.append(current)
|
| 309 |
+
return papers[:20]
|
| 310 |
+
|
| 311 |
+
def generate_5min_feature_markdown(paper):
|
| 312 |
+
# ✨ 5-min research paper feature
|
| 313 |
+
title, summary, authors, date, url = paper['title'], paper['summary'], paper['authors'], paper['date'], paper['url']
|
| 314 |
+
pdf_url = url.replace("abs", "pdf") + (".pdf" if not url.endswith(".pdf") else "")
|
| 315 |
+
wct, sw = len(title.split()), len(summary.split())
|
| 316 |
+
terms = get_high_info_terms(summary, 15)
|
| 317 |
+
rouge = round((len(terms) / max(sw, 1)) * 100, 2)
|
| 318 |
+
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```"
|
| 319 |
+
return f"""
|
| 320 |
+
## 📄 {title}
|
| 321 |
+
**Authors:** {authors} | **Date:** {date} | **Words:** Title: {wct}, Summary: {sw}
|
| 322 |
+
**Links:** [Abstract]({url}) | [PDF]({pdf_url})
|
| 323 |
+
**Terms:** {', '.join(terms)} | **ROUGE:** {rouge}%
|
| 324 |
+
### 🎤 TTF Read Aloud
|
| 325 |
+
- **Title:** {title} | **Terms:** {', '.join(terms)} | **ROUGE:** {rouge}%
|
| 326 |
+
#### Concepts Graph
|
| 327 |
+
{mermaid}
|
| 328 |
+
---
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
def create_detailed_paper_md(papers): return "# Detailed Summary\n" + "\n".join(generate_5min_feature_markdown(p) for p in papers)
|
| 332 |
+
|
| 333 |
+
async def create_paper_audio_files(papers, query):
|
| 334 |
+
# 🎧 Generate paper audio
|
| 335 |
+
for p in papers:
|
| 336 |
+
audio_text = clean_text_for_tts(f"{p['title']} by {p['authors']}. {p['summary']}")
|
| 337 |
+
p['full_audio'], _ = await async_edge_tts_generate(audio_text, st.session_state['tts_voice'])
|
| 338 |
+
if p['full_audio']: p['download_base64'] = get_download_link(p['full_audio'])
|
| 339 |
+
|
| 340 |
+
async def perform_ai_lookup(q, useArxiv=True, useArxivAudio=False):
|
| 341 |
+
# 🔮 AI-powered research
|
| 342 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
| 343 |
+
response = client.messages.create(model="claude-3-sonnet-20240229", max_tokens=1000, messages=[{"role": "user", "content": q}])
|
| 344 |
+
result = response.content[0].text
|
| 345 |
+
st.markdown("### Claude's Reply 🧠\n" + result)
|
| 346 |
+
md_file = create_file(q, result)
|
| 347 |
+
audio_file, _ = await async_edge_tts_generate(result, st.session_state['tts_voice'])
|
| 348 |
+
play_and_download_audio(audio_file)
|
| 349 |
+
|
| 350 |
+
if useArxiv:
|
| 351 |
+
q += result
|
| 352 |
+
gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
| 353 |
+
refs = gradio_client.predict(q, 10, "Semantic Search", "mistralai/Mixtral-8x7B-Instruct-v0.1", api_name="/update_with_rag_md")[0]
|
| 354 |
+
result = f"🔎 {q}\n\n{refs}"
|
| 355 |
+
md_file, audio_file = create_file(q, result), (await async_edge_tts_generate(result, st.session_state['tts_voice']))[0]
|
| 356 |
+
play_and_download_audio(audio_file)
|
| 357 |
+
papers = parse_arxiv_refs(refs)
|
| 358 |
+
if papers and useArxivAudio: await create_paper_audio_files(papers, q)
|
| 359 |
+
return result, papers
|
| 360 |
+
return result, []
|
| 361 |
+
|
| 362 |
+
# 📦 Zip Files
|
| 363 |
+
def create_zip_of_files(md_files, mp3_files, query):
|
| 364 |
+
# 📦 Zip it up
|
| 365 |
+
all_files = md_files + mp3_files
|
| 366 |
+
if not all_files: return None
|
| 367 |
+
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)
|
| 368 |
+
zip_name = f"{format_timestamp_prefix()}_{'-'.join(terms)[:20]}.zip"
|
| 369 |
+
with zipfile.ZipFile(zip_name, 'w') as z: [z.write(f) for f in all_files]
|
| 370 |
+
return zip_name
|
| 371 |
+
|
| 372 |
+
# 🎮 Main Interface
|
| 373 |
+
async def async_interface():
|
| 374 |
+
init_session_state()
|
| 375 |
+
if not st.session_state.username:
|
| 376 |
+
available = [n for n in FUN_USERNAMES if not any(f"{n} has joined" in l for l in (await load_chat()).split('\n'))]
|
| 377 |
+
st.session_state.username = random.choice(available or list(FUN_USERNAMES.keys()))
|
| 378 |
+
st.session_state.tts_voice = FUN_USERNAMES[st.session_state.username]
|
| 379 |
+
await save_chat_entry("System 🌟", f"{st.session_state.username} has joined {START_ROOM}!")
|
| 380 |
+
|
| 381 |
+
st.title(f"🤖🧠MMO Chat & Research for {st.session_state.username}📝🔬")
|
| 382 |
+
update_marquee_settings_ui()
|
| 383 |
+
display_marquee(f"🚀 Welcome to {START_ROOM} | 🤖 {st.session_state.username}", st.session_state['marquee_settings'], "welcome")
|
| 384 |
+
|
| 385 |
+
if not st.session_state.server_task:
|
| 386 |
+
st.session_state.server_task = asyncio.create_task(run_websocket_server())
|
| 387 |
+
|
| 388 |
+
tab_main = st.radio("Action:", ["🎤 Chat & Voice", "📸 Media", "🔍 ArXiv", "📚 PDF to Audio"], horizontal=True)
|
| 389 |
+
useArxiv, useArxivAudio = st.checkbox("Search ArXiv", True), st.checkbox("ArXiv Audio", False)
|
| 390 |
+
st.session_state.autosend = st.checkbox("Autosend Chat", value=True)
|
| 391 |
+
st.session_state.autosearch = st.checkbox("Autosearch ArXiv", value=True)
|
| 392 |
+
|
| 393 |
+
# 🎤 Chat & Voice
|
| 394 |
+
if tab_main == "🎤 Chat & Voice":
|
| 395 |
st.subheader(f"{START_ROOM} Chat 💬")
|
| 396 |
chat_content = await load_chat()
|
| 397 |
+
chat_container = st.container()
|
| 398 |
+
with chat_container:
|
| 399 |
+
st.markdown(chat_content) # Display numbered chat history
|
| 400 |
+
|
| 401 |
+
message = st.text_input(f"Message as {st.session_state.username}", key="message_input")
|
| 402 |
+
if message and message != st.session_state.last_message:
|
| 403 |
+
st.session_state.last_message = message
|
| 404 |
+
if st.session_state.autosend or st.button("Send 🚀"):
|
| 405 |
+
await save_chat_entry(st.session_state.username, message, True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
st.rerun()
|
| 407 |
|
| 408 |
+
st.subheader("🎤 Speech-to-Chat")
|
| 409 |
+
speech_component = components.declare_component("speech_component", path="mycomponent")
|
| 410 |
+
transcript_data = speech_component(default_value=st.session_state.get('last_transcript', ''))
|
| 411 |
+
if transcript_data and 'value' in transcript_data:
|
| 412 |
+
transcript = transcript_data['value'].strip()
|
| 413 |
+
st.write(f"🎙️ You said: {transcript}")
|
| 414 |
+
if transcript and transcript != st.session_state.last_transcript:
|
| 415 |
+
st.session_state.last_transcript = transcript
|
| 416 |
+
if st.session_state.autosend:
|
| 417 |
+
await save_chat_entry(st.session_state.username, transcript, True)
|
| 418 |
+
st.rerun()
|
| 419 |
+
elif st.button("Send to Chat"):
|
| 420 |
+
await save_chat_entry(st.session_state.username, transcript, True)
|
| 421 |
+
st.rerun()
|
| 422 |
+
|
| 423 |
+
# 📸 Media
|
| 424 |
+
elif tab_main == "📸 Media":
|
| 425 |
+
st.header("📸 Media Gallery")
|
| 426 |
+
tabs = st.tabs(["🎵 Audio", "🖼 Images", "🎥 Video"])
|
| 427 |
+
with tabs[0]:
|
| 428 |
+
for a in glob.glob(f"{MEDIA_DIR}/*.mp3"):
|
| 429 |
+
with st.expander(os.path.basename(a)): play_and_download_audio(a)
|
| 430 |
+
with tabs[1]:
|
| 431 |
+
imgs = glob.glob(f"{MEDIA_DIR}/*.png") + glob.glob(f"{MEDIA_DIR}/*.jpg")
|
| 432 |
+
if imgs:
|
| 433 |
+
cols = st.columns(3)
|
| 434 |
+
for i, f in enumerate(imgs): cols[i % 3].image(f, use_container_width=True)
|
| 435 |
+
with tabs[2]:
|
| 436 |
+
for v in glob.glob(f"{MEDIA_DIR}/*.mp4"):
|
| 437 |
+
with st.expander(os.path.basename(v)): st.video(v)
|
| 438 |
+
|
| 439 |
+
uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3'])
|
| 440 |
+
if uploaded_file:
|
| 441 |
+
filename = f"{format_timestamp_prefix(st.session_state.username)}-{hashlib.md5(uploaded_file.getbuffer()).hexdigest()[:8]}.{uploaded_file.name.split('.')[-1]}"
|
| 442 |
+
with open(f"{MEDIA_DIR}/{filename}", 'wb') as f: f.write(uploaded_file.getbuffer())
|
| 443 |
+
await save_chat_entry(st.session_state.username, f"Uploaded: {filename}")
|
| 444 |
st.rerun()
|
| 445 |
|
| 446 |
+
# 🔍 ArXiv
|
| 447 |
+
elif tab_main == "🔍 ArXiv":
|
| 448 |
+
q = st.text_input("🔍 Query:", key="arxiv_query")
|
| 449 |
+
if q and q != st.session_state.last_query:
|
| 450 |
+
st.session_state.last_query = q
|
| 451 |
+
if st.session_state.autosearch or st.button("🔍 Run"):
|
| 452 |
+
result, papers = await perform_ai_lookup(q, useArxiv, useArxivAudio)
|
| 453 |
+
for i, p in enumerate(papers, 1):
|
| 454 |
+
with st.expander(f"{i}. 📄 {p['title']}"):
|
| 455 |
+
st.markdown(f"**{p['date']} | {p['title']}** — [Link]({p['url']})")
|
| 456 |
+
st.markdown(generate_5min_feature_markdown(p))
|
| 457 |
+
if p.get('full_audio'): play_and_download_audio(p['full_audio'])
|
| 458 |
+
|
| 459 |
+
# 📚 PDF to Audio
|
| 460 |
+
elif tab_main == "📚 PDF to Audio":
|
| 461 |
+
audio_processor = AudioProcessor()
|
| 462 |
+
pdf_file = st.file_uploader("Choose PDF", "pdf")
|
| 463 |
+
max_pages = st.slider('Pages', 1, 100, 10)
|
| 464 |
+
if pdf_file:
|
| 465 |
+
with st.spinner('Processing...'):
|
| 466 |
+
texts, audios, total = process_pdf(pdf_file, max_pages, st.session_state['tts_voice'], audio_processor)
|
| 467 |
+
for i, text in enumerate(texts):
|
| 468 |
+
with st.expander(f"Page {i+1}"):
|
| 469 |
+
st.markdown(text)
|
| 470 |
+
while i not in audios: time.sleep(0.1)
|
| 471 |
+
if audios[i]:
|
| 472 |
+
st.audio(audios[i], format='audio/mp3')
|
| 473 |
+
st.markdown(get_download_link(io.BytesIO(audios[i]), "mp3"), unsafe_allow_html=True)
|
| 474 |
+
|
| 475 |
+
# 🗂️ Sidebar
|
| 476 |
+
st.sidebar.subheader("Voice Settings")
|
| 477 |
+
new_username = st.sidebar.selectbox("Change Name/Voice", list(FUN_USERNAMES.keys()), index=list(FUN_USERNAMES.keys()).index(st.session_state.username))
|
| 478 |
+
if new_username != st.session_state.username:
|
| 479 |
+
await save_chat_entry("System 🌟", f"{st.session_state.username} changed to {new_username}")
|
| 480 |
+
st.session_state.username, st.session_state.tts_voice = new_username, FUN_USERNAMES[new_username]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
st.rerun()
|
| 482 |
|
| 483 |
+
md_files, mp3_files = glob.glob("*.md"), glob.glob("*.mp3")
|
| 484 |
+
st.sidebar.markdown("### 📂 File History")
|
| 485 |
+
for f in sorted(md_files + mp3_files, key=os.path.getmtime, reverse=True)[:10]:
|
| 486 |
+
st.sidebar.write(f"{FILE_EMOJIS.get(f.split('.')[-1], '📄')} {os.path.basename(f)}")
|
| 487 |
+
if st.sidebar.button("⬇️ Zip All"):
|
| 488 |
+
zip_name = create_zip_of_files(md_files, mp3_files, "latest_query")
|
| 489 |
+
if zip_name: st.sidebar.markdown(get_download_link(zip_name, "zip"), unsafe_allow_html=True)
|
| 490 |
|
|
|
|
| 491 |
def main():
|
| 492 |
+
# 🎉 Kick it off
|
| 493 |
+
asyncio.run(async_interface())
|
| 494 |
|
| 495 |
if __name__ == "__main__":
|
| 496 |
main()
|