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
|
5 |
+
from datetime import datetime
|
6 |
+
import os
|
7 |
+
import random
|
8 |
+
import time
|
9 |
+
import hashlib
|
10 |
+
from PIL import Image
|
11 |
+
import glob
|
12 |
+
import base64
|
13 |
+
import io
|
14 |
+
import streamlit.components.v1 as components
|
15 |
+
import edge_tts
|
16 |
+
from audio_recorder_streamlit import audio_recorder
|
17 |
+
import nest_asyncio
|
18 |
+
import re
|
19 |
+
import pytz
|
20 |
+
import shutil
|
21 |
+
import anthropic
|
22 |
+
import openai
|
23 |
+
from PyPDF2 import PdfReader
|
24 |
+
import threading
|
25 |
+
import json
|
26 |
+
import zipfile
|
27 |
+
from gradio_client import Client
|
28 |
+
from dotenv import load_dotenv
|
29 |
+
from streamlit_marquee import streamlit_marquee
|
30 |
+
from collections import defaultdict, Counter
|
31 |
+
import pandas as pd
|
32 |
+
|
33 |
+
# 🛠️ Patch asyncio for nesting
|
34 |
+
nest_asyncio.apply()
|
35 |
+
|
36 |
+
# 🎨 Page Config
|
37 |
+
st.set_page_config(
|
38 |
+
page_title="🚲TalkingAIResearcher🏆",
|
39 |
+
page_icon="🚲🏆",
|
40 |
+
layout="wide",
|
41 |
+
initial_sidebar_state="auto"
|
42 |
+
)
|
43 |
+
|
44 |
+
# 🌟 Static Config
|
45 |
+
icons = '🤖🧠🔬📝'
|
46 |
+
Site_Name = '🤖🧠Chat & Quote Node📝🔬'
|
47 |
+
START_ROOM = "Sector 🌌"
|
48 |
+
FUN_USERNAMES = {
|
49 |
+
"CosmicJester 🌌": "en-US-AriaNeural",
|
50 |
+
"PixelPanda 🐼": "en-US-JennyNeural",
|
51 |
+
"QuantumQuack 🦆": "en-GB-SoniaNeural",
|
52 |
+
"StellarSquirrel 🐿️": "en-AU-NatashaNeural",
|
53 |
+
"GizmoGuru ⚙️": "en-CA-ClaraNeural",
|
54 |
+
"NebulaNinja 🌠": "en-US-GuyNeural",
|
55 |
+
"ByteBuster 💾": "en-GB-RyanNeural",
|
56 |
+
"GalacticGopher 🌍": "en-AU-WilliamNeural",
|
57 |
+
"RocketRaccoon 🚀": "en-CA-LiamNeural",
|
58 |
+
"EchoElf 🧝": "en-US-AnaNeural",
|
59 |
+
"PhantomFox 🦊": "en-US-BrandonNeural",
|
60 |
+
"WittyWizard 🧙": "en-GB-ThomasNeural",
|
61 |
+
"LunarLlama 🌙": "en-AU-FreyaNeural",
|
62 |
+
"SolarSloth ☀️": "en-CA-LindaNeural",
|
63 |
+
"AstroAlpaca 🦙": "en-US-ChristopherNeural",
|
64 |
+
"CyberCoyote 🐺": "en-GB-ElliotNeural",
|
65 |
+
"MysticMoose 🦌": "en-AU-JamesNeural",
|
66 |
+
"GlitchGnome 🧚": "en-CA-EthanNeural",
|
67 |
+
"VortexViper 🐍": "en-US-AmberNeural",
|
68 |
+
"ChronoChimp 🐒": "en-GB-LibbyNeural"
|
69 |
+
}
|
70 |
+
EDGE_TTS_VOICES = list(set(FUN_USERNAMES.values()))
|
71 |
+
FILE_EMOJIS = {"md": "📝", "mp3": "🎵", "png": "🖼️", "mp4": "🎥", "zip": "📦"}
|
72 |
+
|
73 |
+
# 📁 Directories
|
74 |
+
for d in ["chat_logs", "vote_logs", "audio_logs", "history_logs", "audio_cache", "paper_metadata"]:
|
75 |
+
os.makedirs(d, exist_ok=True)
|
76 |
+
|
77 |
+
CHAT_DIR = "chat_logs"
|
78 |
+
VOTE_DIR = "vote_logs"
|
79 |
+
MEDIA_DIR = "."
|
80 |
+
AUDIO_CACHE_DIR = "audio_cache"
|
81 |
+
AUDIO_DIR = "audio_logs"
|
82 |
+
PAPER_DIR = "paper_metadata"
|
83 |
+
STATE_FILE = "user_state.txt"
|
84 |
+
|
85 |
+
CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md")
|
86 |
+
QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md")
|
87 |
+
IMAGE_VOTES_FILE = os.path.join(VOTE_DIR, "image_votes.md")
|
88 |
+
HISTORY_FILE = os.path.join(VOTE_DIR, "vote_history.md")
|
89 |
+
|
90 |
+
# 🔑 API Keys
|
91 |
+
load_dotenv()
|
92 |
+
anthropic_key = os.getenv('ANTHROPIC_API_KEY', st.secrets.get('ANTHROPIC_API_KEY', ""))
|
93 |
+
openai_api_key = os.getenv('OPENAI_API_KEY', st.secrets.get('OPENAI_API_KEY', ""))
|
94 |
+
openai_client = openai.OpenAI(api_key=openai_api_key)
|
95 |
+
|
96 |
+
# 🕒 Timestamp Helper
|
97 |
+
def format_timestamp_prefix(username=""):
|
98 |
+
central = pytz.timezone('US/Central')
|
99 |
+
now = datetime.now(central)
|
100 |
+
return f"{now.strftime('%Y%m%d_%H%M%S')}-by-{username}"
|
101 |
+
|
102 |
+
# 📈 Performance Timer
|
103 |
+
class PerformanceTimer:
|
104 |
+
def __init__(self, name):
|
105 |
+
self.name, self.start = name, None
|
106 |
+
def __enter__(self):
|
107 |
+
self.start = time.time()
|
108 |
+
return self
|
109 |
+
def __exit__(self, *args):
|
110 |
+
duration = time.time() - self.start
|
111 |
+
st.session_state['operation_timings'][self.name] = duration
|
112 |
+
st.session_state['performance_metrics'][self.name].append(duration)
|
113 |
+
|
114 |
+
# 🎛️ Session State Init
|
115 |
+
def init_session_state():
|
116 |
+
defaults = {
|
117 |
+
'server_running': False, 'server_task': None, 'active_connections': {},
|
118 |
+
'media_notifications': [], 'last_chat_update': 0, 'displayed_chat_lines': [],
|
119 |
+
'message_text': "", 'audio_cache': {}, 'pasted_image_data': None,
|
120 |
+
'quote_line': None, 'refresh_rate': 10, 'base64_cache': {},
|
121 |
+
'transcript_history': [], 'last_transcript': "", 'image_hashes': set(),
|
122 |
+
'tts_voice': "en-US-AriaNeural", 'chat_history': [], 'marquee_settings': {
|
123 |
+
"background": "#1E1E1E", "color": "#FFFFFF", "font-size": "14px",
|
124 |
+
"animationDuration": "20s", "width": "100%", "lineHeight": "35px"
|
125 |
+
}, 'operation_timings': {}, 'performance_metrics': defaultdict(list),
|
126 |
+
'enable_audio': True, 'download_link_cache': {}, 'username': None,
|
127 |
+
'autosend': True, 'autosearch': True, 'last_message': "", 'last_query': "",
|
128 |
+
'mp3_files': {}, 'timer_start': time.time(), 'quote_index': 0,
|
129 |
+
'quote_source': "famous", 'last_sent_transcript': "", 'old_val': None,
|
130 |
+
'last_refresh': time.time(), 'paper_metadata': {}, 'paste_image_base64': "",
|
131 |
+
'use_arxiv': True, 'use_arxiv_audio': False, 'speech_processed': False,
|
132 |
+
'auto_refresh': True
|
133 |
+
}
|
134 |
+
for k, v in defaults.items():
|
135 |
+
if k not in st.session_state:
|
136 |
+
st.session_state[k] = v
|
137 |
+
|
138 |
+
# 🖌️ Marquee Helpers
|
139 |
+
def update_marquee_settings_ui():
|
140 |
+
st.sidebar.markdown("### 🎯 Marquee Settings")
|
141 |
+
cols = st.sidebar.columns(2)
|
142 |
+
with cols[0]:
|
143 |
+
st.session_state['marquee_settings']['background'] = st.color_picker("🎨 Background", "#1E1E1E")
|
144 |
+
st.session_state['marquee_settings']['color'] = st.color_picker("✍️ Text", "#FFFFFF")
|
145 |
+
with cols[1]:
|
146 |
+
st.session_state['marquee_settings']['font-size'] = f"{st.slider('📏 Size', 10, 24, 14)}px"
|
147 |
+
st.session_state['marquee_settings']['animationDuration'] = f"{st.slider('⏱️ Speed', 1, 20, 20)}s"
|
148 |
+
|
149 |
+
def display_marquee(text, settings, key_suffix=""):
|
150 |
+
truncated = text[:280] + "..." if len(text) > 280 else text
|
151 |
+
streamlit_marquee(content=truncated, **settings, key=f"marquee_{key_suffix}")
|
152 |
+
st.write("")
|
153 |
+
|
154 |
+
# 📝 Text & File Helpers
|
155 |
+
def clean_text_for_tts(text):
|
156 |
+
return re.sub(r'[#*!\[\]]+', '', ' '.join(text.split()))[:200] or "No text"
|
157 |
+
|
158 |
+
def clean_text_for_filename(text):
|
159 |
+
return '_'.join(re.sub(r'[^\w\s-]', '', text.lower()).split())[:50]
|
160 |
+
|
161 |
+
def get_high_info_terms(text, top_n=10):
|
162 |
+
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with'}
|
163 |
+
words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
|
164 |
+
bi_grams = [' '.join(pair) for pair in zip(words, words[1:])]
|
165 |
+
filtered = [t for t in words + bi_grams if t not in stop_words and len(t.split()) <= 2]
|
166 |
+
return [t for t, _ in Counter(filtered).most_common(top_n)]
|
167 |
+
|
168 |
+
def generate_filename(prompt, username, file_type="md", title=None):
|
169 |
+
timestamp = format_timestamp_prefix(username)
|
170 |
+
if title:
|
171 |
+
high_info = '-'.join(get_high_info_terms(title, 5))
|
172 |
+
return f"{timestamp}-{clean_text_for_filename(prompt[:20])}-{high_info}.{file_type}"
|
173 |
+
hash_val = hashlib.md5(prompt.encode()).hexdigest()[:8]
|
174 |
+
return f"{timestamp}-{hash_val}.{file_type}"
|
175 |
+
|
176 |
+
def create_file(prompt, username, file_type="md", title=None):
|
177 |
+
filename = generate_filename(prompt, username, file_type, title)
|
178 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
179 |
+
f.write(prompt)
|
180 |
+
return filename
|
181 |
+
|
182 |
+
def get_download_link(file, file_type="mp3"):
|
183 |
+
cache_key = f"dl_{file}"
|
184 |
+
if cache_key not in st.session_state['download_link_cache']:
|
185 |
+
with open(file, "rb") as f:
|
186 |
+
b64 = base64.b64encode(f.read()).decode()
|
187 |
+
mime_types = {"mp3": "audio/mpeg", "png": "image/png", "mp4": "video/mp4", "md": "text/markdown", "zip": "application/zip"}
|
188 |
+
st.session_state['download_link_cache'][cache_key] = f'<a href="data:{mime_types.get(file_type, "application/octet-stream")};base64,{b64}" download="{os.path.basename(file)}">{FILE_EMOJIS.get(file_type, "Download")} Download {os.path.basename(file)}</a>'
|
189 |
+
return st.session_state['download_link_cache'][cache_key]
|
190 |
+
|
191 |
+
def save_username(username):
|
192 |
+
try:
|
193 |
+
with open(STATE_FILE, 'w') as f:
|
194 |
+
f.write(username)
|
195 |
+
except Exception as e:
|
196 |
+
print(f"Failed to save username: {e}")
|
197 |
+
|
198 |
+
def load_username():
|
199 |
+
if os.path.exists(STATE_FILE):
|
200 |
+
try:
|
201 |
+
with open(STATE_FILE, 'r') as f:
|
202 |
+
return f.read().strip()
|
203 |
+
except Exception as e:
|
204 |
+
print(f"Failed to load username: {e}")
|
205 |
+
return None
|
206 |
+
|
207 |
+
def concatenate_markdown_files(exclude_files=["README.md"]):
|
208 |
+
md_files = sorted([f for f in glob.glob("*.md") if os.path.basename(f) not in exclude_files], key=os.path.getmtime)
|
209 |
+
all_md_content = ""
|
210 |
+
for i, md_file in enumerate(md_files, 1):
|
211 |
+
with open(md_file, 'r', encoding='utf-8') as f:
|
212 |
+
content = f.read().strip()
|
213 |
+
all_md_content += f"{i}. {content}\n"
|
214 |
+
return all_md_content.rstrip()
|
215 |
+
|
216 |
+
def get_chat_text_only(exclude_files=["README.md"]):
|
217 |
+
md_files = sorted([f for f in glob.glob("*.md") if os.path.basename(f) not in exclude_files], key=os.path.getmtime)
|
218 |
+
chat_text = ""
|
219 |
+
for i, md_file in enumerate(md_files, 1):
|
220 |
+
with open(md_file, 'r', encoding='utf-8') as f:
|
221 |
+
content = f.read().strip()
|
222 |
+
lines = content.split('\n')
|
223 |
+
for line in lines:
|
224 |
+
if line.strip() and not line.startswith('#'):
|
225 |
+
# Match timestamp, username, voice, and message
|
226 |
+
match = re.match(r'\[(.*?)\]\s(.*?)\s\((.*?)\):\s*(.*)', line)
|
227 |
+
if match:
|
228 |
+
message = match.group(4).strip()
|
229 |
+
if message.startswith('```markdown'):
|
230 |
+
message = message.replace('```markdown', '').replace('```', '').strip()
|
231 |
+
chat_text += f"{message}\n"
|
232 |
+
return chat_text.rstrip()
|
233 |
+
|
234 |
+
# 🎶 Audio Processing
|
235 |
+
async def async_edge_tts_generate(text, voice, username, rate=0, pitch=0, file_format="mp3"):
|
236 |
+
cache_key = f"{text[:100]}_{voice}_{rate}_{pitch}_{file_format}"
|
237 |
+
if cache_key in st.session_state['audio_cache']:
|
238 |
+
return st.session_state['audio_cache'][cache_key], 0
|
239 |
+
start_time = time.time()
|
240 |
+
text = clean_text_for_tts(text)
|
241 |
+
if not text or text == "No text":
|
242 |
+
print(f"Skipping audio generation for empty/invalid text: '{text}'")
|
243 |
+
return None, 0
|
244 |
+
filename = f"{format_timestamp_prefix(username)}-{hashlib.md5(text.encode()).hexdigest()[:8]}.{file_format}"
|
245 |
+
try:
|
246 |
+
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
|
247 |
+
await communicate.save(filename)
|
248 |
+
if os.path.exists(filename) and os.path.getsize(filename) > 0:
|
249 |
+
st.session_state['audio_cache'][cache_key] = filename
|
250 |
+
return filename, time.time() - start_time
|
251 |
+
else:
|
252 |
+
print(f"Audio file {filename} was not created or is empty.")
|
253 |
+
return None, 0
|
254 |
+
except edge_tts.exceptions.NoAudioReceived as e:
|
255 |
+
print(f"No audio received for text: '{text}' with voice: {voice}. Error: {e}")
|
256 |
+
return None, 0
|
257 |
+
except Exception as e:
|
258 |
+
print(f"Error generating audio for text: '{text}' with voice: {voice}. Error: {e}")
|
259 |
+
return None, 0
|
260 |
+
|
261 |
+
def play_and_download_audio(file_path):
|
262 |
+
if file_path and os.path.exists(file_path):
|
263 |
+
st.audio(file_path)
|
264 |
+
st.markdown(get_download_link(file_path), unsafe_allow_html=True)
|
265 |
+
else:
|
266 |
+
st.warning(f"Audio file not found: {file_path}")
|
267 |
+
|
268 |
+
def load_mp3_viewer():
|
269 |
+
mp3_files = sorted(glob.glob("*.mp3"), key=os.path.getmtime)
|
270 |
+
for i, mp3 in enumerate(mp3_files, 1):
|
271 |
+
filename = os.path.basename(mp3)
|
272 |
+
if filename not in st.session_state['mp3_files']:
|
273 |
+
st.session_state['mp3_files'][filename] = (i, mp3)
|
274 |
+
|
275 |
+
async def save_chat_entry(username, message, voice, is_markdown=False):
|
276 |
+
if not message.strip() or message == st.session_state.last_transcript:
|
277 |
+
return None, None
|
278 |
+
central = pytz.timezone('US/Central')
|
279 |
+
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
|
280 |
+
entry = f"[{timestamp}] {username} ({voice}): {message}" if not is_markdown else f"[{timestamp}] {username} ({voice}):\n```markdown\n{message}\n```"
|
281 |
+
md_file = create_file(entry, username, "md")
|
282 |
+
with open(CHAT_FILE, 'a') as f:
|
283 |
+
f.write(f"{entry}\n")
|
284 |
+
audio_file, _ = await async_edge_tts_generate(message, voice, username)
|
285 |
+
if audio_file:
|
286 |
+
with open(HISTORY_FILE, 'a') as f:
|
287 |
+
f.write(f"[{timestamp}] {username}: Audio - {audio_file}\n")
|
288 |
+
st.session_state['mp3_files'][os.path.basename(audio_file)] = (len(st.session_state['chat_history']) + 1, audio_file)
|
289 |
+
if st.session_state.get('speech_processed', False) and st.session_state.get('message_input', '') == message:
|
290 |
+
st.session_state['message_input'] = ""
|
291 |
+
st.session_state['speech_processed'] = False
|
292 |
+
else:
|
293 |
+
st.warning(f"Failed to generate audio for: {message}")
|
294 |
+
await broadcast_message(f"{username}|{message}", "chat")
|
295 |
+
st.session_state.last_chat_update = time.time()
|
296 |
+
st.session_state.chat_history.append(entry)
|
297 |
+
st.session_state.last_transcript = message
|
298 |
+
return md_file, audio_file
|
299 |
+
|
300 |
+
async def load_chat():
|
301 |
+
if not os.path.exists(CHAT_FILE):
|
302 |
+
with open(CHAT_FILE, 'a') as f:
|
303 |
+
f.write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub! 🎤\n")
|
304 |
+
with open(CHAT_FILE, 'r') as f:
|
305 |
+
content = f.read().strip()
|
306 |
+
lines = content.split('\n')
|
307 |
+
unique_lines = list(dict.fromkeys(line for line in lines if line.strip()))
|
308 |
+
return unique_lines
|
309 |
+
|
310 |
+
# Claude Search Function with Image Support
|
311 |
+
async def perform_claude_search(query, username, image=None):
|
312 |
+
if not query.strip() or query == st.session_state.last_transcript:
|
313 |
+
return None, None, None
|
314 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
315 |
+
message_content = [{"type": "text", "text": query}]
|
316 |
+
if image:
|
317 |
+
buffered = io.BytesIO()
|
318 |
+
image.save(buffered, format="PNG")
|
319 |
+
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
320 |
+
message_content.append({
|
321 |
+
"type": "image",
|
322 |
+
"source": {
|
323 |
+
"type": "base64",
|
324 |
+
"media_type": "image/png",
|
325 |
+
"data": img_base64
|
326 |
+
}
|
327 |
+
})
|
328 |
+
try:
|
329 |
+
response = client.messages.create(
|
330 |
+
model="claude-3-sonnet-20240229",
|
331 |
+
max_tokens=1000,
|
332 |
+
messages=[{"role": "user", "content": message_content}]
|
333 |
+
)
|
334 |
+
result = response.content[0].text
|
335 |
+
st.markdown(f"### Claude's Reply 🧠\n{result}")
|
336 |
+
except Exception as e:
|
337 |
+
st.error(f"Claude processing failed: {e}")
|
338 |
+
return None, None, None
|
339 |
+
|
340 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
341 |
+
full_text = f"Prompt: {query}\nResponse: {result}"
|
342 |
+
md_file, audio_file = await save_chat_entry(username, full_text, voice, True)
|
343 |
+
return md_file, audio_file, result
|
344 |
+
|
345 |
+
# ArXiv Search Function
|
346 |
+
async def perform_arxiv_search(query, username, claude_result=None):
|
347 |
+
if not query.strip() or query == st.session_state.last_transcript:
|
348 |
+
return None, None
|
349 |
+
if claude_result is None:
|
350 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
351 |
+
claude_response = client.messages.create(
|
352 |
+
model="claude-3-sonnet-20240229",
|
353 |
+
max_tokens=1000,
|
354 |
+
messages=[{"role": "user", "content": query}]
|
355 |
+
)
|
356 |
+
claude_result = claude_response.content[0].text
|
357 |
+
st.markdown(f"### Claude's Reply 🧠\n{claude_result}")
|
358 |
+
|
359 |
+
enhanced_query = f"{query}\n\n{claude_result}"
|
360 |
+
gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
361 |
+
refs = gradio_client.predict(
|
362 |
+
enhanced_query, 10, "Semantic Search", "mistralai/Mixtral-8x7B-Instruct-v0.1", api_name="/update_with_rag_md"
|
363 |
+
)[0]
|
364 |
+
result = f"🔎 {enhanced_query}\n\n{refs}"
|
365 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
366 |
+
md_file, audio_file = await save_chat_entry(username, result, voice, True)
|
367 |
+
return md_file, audio_file
|
368 |
+
|
369 |
+
async def perform_ai_lookup(q, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False, useArxiv=True, useArxivAudio=False):
|
370 |
+
start = time.time()
|
371 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
372 |
+
response = client.messages.create(
|
373 |
+
model="claude-3-sonnet-20240229",
|
374 |
+
max_tokens=1000,
|
375 |
+
messages=[{"role": "user", "content": q}]
|
376 |
+
)
|
377 |
+
st.write("Claude's reply 🧠:")
|
378 |
+
st.markdown(response.content[0].text)
|
379 |
+
|
380 |
+
result = response.content[0].text
|
381 |
+
md_file = create_file(result, "System", "md")
|
382 |
+
audio_file, _ = await async_edge_tts_generate(result, st.session_state['tts_voice'], "System")
|
383 |
+
st.subheader("📝 Main Response Audio")
|
384 |
+
play_and_download_audio(audio_file)
|
385 |
+
|
386 |
+
papers = []
|
387 |
+
if useArxiv:
|
388 |
+
q = q + result
|
389 |
+
st.write('Running Arxiv RAG with Claude inputs.')
|
390 |
+
gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
391 |
+
refs = gradio_client.predict(
|
392 |
+
q, 20, "Semantic Search", "mistralai/Mixtral-8x7B-Instruct-v0.1", api_name="/update_with_rag_md"
|
393 |
+
)[0]
|
394 |
+
papers = parse_arxiv_refs(refs, q)
|
395 |
+
for paper in papers:
|
396 |
+
filename = create_file(generate_5min_feature_markdown(paper), "System", "md", paper['title'])
|
397 |
+
paper['md_file'] = filename
|
398 |
+
st.session_state['paper_metadata'][paper['title']] = filename
|
399 |
+
if papers and useArxivAudio:
|
400 |
+
await create_paper_audio_files(papers, q)
|
401 |
+
elapsed = time.time() - start
|
402 |
+
st.write(f"**Total Elapsed:** {elapsed:.2f} s")
|
403 |
+
return result, papers
|
404 |
+
|
405 |
+
# 🌐 WebSocket Handling
|
406 |
+
async def websocket_handler(websocket, path):
|
407 |
+
client_id = str(uuid.uuid4())
|
408 |
+
room_id = "chat"
|
409 |
+
if room_id not in st.session_state.active_connections:
|
410 |
+
st.session_state.active_connections[room_id] = {}
|
411 |
+
st.session_state.active_connections[room_id][client_id] = websocket
|
412 |
+
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
|
413 |
+
chat_content = await load_chat()
|
414 |
+
if not any(f"Client-{client_id}" in line for line in chat_content):
|
415 |
+
await save_chat_entry("System 🌟", f"{username} has joined {START_ROOM}!", "en-US-AriaNeural")
|
416 |
+
try:
|
417 |
+
async for message in websocket:
|
418 |
+
if '|' in message:
|
419 |
+
username, content = message.split('|', 1)
|
420 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
421 |
+
await save_chat_entry(username, content, voice)
|
422 |
+
else:
|
423 |
+
await websocket.send("ERROR|Message format: username|content")
|
424 |
+
except websockets.ConnectionClosed:
|
425 |
+
await save_chat_entry("System 🌟", f"{username} has left {START_ROOM}!", "en-US-AriaNeural")
|
426 |
+
finally:
|
427 |
+
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
|
428 |
+
del st.session_state.active_connections[room_id][client_id]
|
429 |
+
|
430 |
+
async def broadcast_message(message, room_id):
|
431 |
+
if room_id in st.session_state.active_connections:
|
432 |
+
disconnected = []
|
433 |
+
for client_id, ws in st.session_state.active_connections[room_id].items():
|
434 |
+
try:
|
435 |
+
await ws.send(message)
|
436 |
+
except websockets.ConnectionClosed:
|
437 |
+
disconnected.append(client_id)
|
438 |
+
for client_id in disconnected:
|
439 |
+
if client_id in st.session_state.active_connections[room_id]:
|
440 |
+
del st.session_state.active_connections[room_id][client_id]
|
441 |
+
|
442 |
+
async def run_websocket_server():
|
443 |
+
if not st.session_state.get('server_running', False):
|
444 |
+
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
|
445 |
+
st.session_state['server_running'] = True
|
446 |
+
await server.wait_closed()
|
447 |
+
|
448 |
+
def start_websocket_server():
|
449 |
+
loop = asyncio.new_event_loop()
|
450 |
+
asyncio.set_event_loop(loop)
|
451 |
+
loop.run_until_complete(run_websocket_server())
|
452 |
+
|
453 |
+
# 📚 PDF to Audio
|
454 |
+
class AudioProcessor:
|
455 |
+
def __init__(self):
|
456 |
+
self.cache_dir = AUDIO_CACHE_DIR
|
457 |
+
os.makedirs(self.cache_dir, exist_ok=True)
|
458 |
+
self.metadata = json.load(open(f"{self.cache_dir}/metadata.json")) if os.path.exists(f"{self.cache_dir}/metadata.json") else {}
|
459 |
+
|
460 |
+
def _save_metadata(self):
|
461 |
+
with open(f"{self.cache_dir}/metadata.json", 'w') as f:
|
462 |
+
json.dump(self.metadata, f)
|
463 |
+
|
464 |
+
async def create_audio(self, text, voice='en-US-AriaNeural'):
|
465 |
+
cache_key = hashlib.md5(f"{text}:{voice}".encode()).hexdigest()
|
466 |
+
cache_path = f"{self.cache_dir}/{cache_key}.mp3"
|
467 |
+
if cache_key in self.metadata and os.path.exists(cache_path):
|
468 |
+
return cache_path
|
469 |
+
text = clean_text_for_tts(text)
|
470 |
+
if not text:
|
471 |
+
return None
|
472 |
+
communicate = edge_tts.Communicate(text, voice)
|
473 |
+
await communicate.save(cache_path)
|
474 |
+
self.metadata[cache_key] = {'timestamp': datetime.now().isoformat(), 'text_length': len(text), 'voice': voice}
|
475 |
+
self._save_metadata()
|
476 |
+
return cache_path
|
477 |
+
|
478 |
+
def process_pdf(pdf_file, max_pages, voice, audio_processor):
|
479 |
+
reader = PdfReader(pdf_file)
|
480 |
+
total_pages = min(len(reader.pages), max_pages)
|
481 |
+
texts, audios = [], {}
|
482 |
+
async def process_page(i, text):
|
483 |
+
audio_path = await audio_processor.create_audio(text, voice)
|
484 |
+
if audio_path:
|
485 |
+
audios[i] = audio_path
|
486 |
+
for i in range(total_pages):
|
487 |
+
text = reader.pages[i].extract_text()
|
488 |
+
texts.append(text)
|
489 |
+
threading.Thread(target=lambda: asyncio.run(process_page(i, text))).start()
|
490 |
+
return texts, audios, total_pages
|
491 |
+
|
492 |
+
# 🔍 ArXiv & AI Lookup
|
493 |
+
def parse_arxiv_refs(ref_text, query):
|
494 |
+
if not ref_text:
|
495 |
+
return []
|
496 |
+
papers = []
|
497 |
+
current = {}
|
498 |
+
for line in ref_text.split('\n'):
|
499 |
+
if line.count('|') == 2:
|
500 |
+
if current:
|
501 |
+
papers.append(current)
|
502 |
+
date, title, *_ = line.strip('* ').split('|')
|
503 |
+
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)}"
|
504 |
+
current = {'date': date, 'title': title, 'url': url, 'authors': '', 'summary': '', 'full_audio': None, 'download_base64': '', 'query': query}
|
505 |
+
elif current:
|
506 |
+
if not current['authors']:
|
507 |
+
current['authors'] = line.strip('* ')
|
508 |
+
else:
|
509 |
+
current['summary'] += ' ' + line.strip() if current['summary'] else line.strip()
|
510 |
+
if current:
|
511 |
+
papers.append(current)
|
512 |
+
return papers[:20]
|
513 |
+
|
514 |
+
def generate_5min_feature_markdown(paper):
|
515 |
+
title, summary, authors, date, url = paper['title'], paper['summary'], paper['authors'], paper['date'], paper['url']
|
516 |
+
pdf_url = url.replace("abs", "pdf") + (".pdf" if not url.endswith(".pdf") else "")
|
517 |
+
wct, sw = len(title.split()), len(summary.split())
|
518 |
+
terms = get_high_info_terms(summary, 15)
|
519 |
+
rouge = round((len(terms) / max(sw, 1)) * 100, 2)
|
520 |
+
# Fixed Mermaid syntax error: use terms[i] instead of undefined 't'
|
521 |
+
mermaid = "```mermaid\nflowchart TD\n" + "\n".join(f' T{i+1}["{terms[i]}"] --> T{i+2}["{terms[i+1]}"]' for i in range(len(terms)-1)) + "\n```"
|
522 |
+
return f"""
|
523 |
+
## 📄 {title}
|
524 |
+
**Authors:** {authors}
|
525 |
+
**Date:** {date}
|
526 |
+
**Words:** Title: {wct}, Summary: {sw}
|
527 |
+
**Links:** [Abstract]({url}) | [PDF]({pdf_url})
|
528 |
+
**Terms:** {', '.join(terms)}
|
529 |
+
**ROUGE:** {rouge}%
|
530 |
+
### 🎤 TTF Read Aloud
|
531 |
+
- **Title:** {title}
|
532 |
+
- **Terms:** {', '.join(terms)}
|
533 |
+
- **ROUGE:** {rouge}%
|
534 |
+
#### Concepts Graph
|
535 |
+
{mermaid}
|
536 |
+
---
|
537 |
+
"""
|
538 |
+
|
539 |
+
async def create_paper_audio_files(papers, query):
|
540 |
+
for p in papers:
|
541 |
+
audio_text = clean_text_for_tts(f"{p['title']} by {p['authors']}. {p['summary']}")
|
542 |
+
p['full_audio'], _ = await async_edge_tts_generate(audio_text, st.session_state['tts_voice'], p['authors'])
|
543 |
+
if p['full_audio']:
|
544 |
+
p['download_base64'] = get_download_link(p['full_audio'])
|
545 |
+
|
546 |
+
def save_vote(file, item, user_hash):
|
547 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
548 |
+
entry = f"[{timestamp}] {user_hash} voted for {item}"
|
549 |
+
try:
|
550 |
+
with open(file, 'a') as f:
|
551 |
+
f.write(f"{entry}\n")
|
552 |
+
with open(HISTORY_FILE, 'a') as f:
|
553 |
+
f.write(f"- {timestamp} - User {user_hash} voted for {item}\n")
|
554 |
+
return True
|
555 |
+
except Exception as e:
|
556 |
+
print(f"Vote save flop: {e}")
|
557 |
+
return False
|
558 |
+
|
559 |
+
def load_votes(file):
|
560 |
+
if not os.path.exists(file):
|
561 |
+
with open(file, 'w') as f:
|
562 |
+
f.write("# Vote Tally\n\nNo votes yet - get clicking! 🖱️\n")
|
563 |
+
try:
|
564 |
+
with open(file, 'r') as f:
|
565 |
+
lines = f.read().strip().split('\n')
|
566 |
+
votes = {}
|
567 |
+
for line in lines[2:]:
|
568 |
+
if line.strip() and 'voted for' in line:
|
569 |
+
item = line.split('voted for ')[1]
|
570 |
+
votes[item] = votes.get(item, 0) + 1
|
571 |
+
return votes
|
572 |
+
except Exception as e:
|
573 |
+
print(f"Vote load oopsie: {e}")
|
574 |
+
return {}
|
575 |
+
|
576 |
+
def generate_user_hash():
|
577 |
+
if 'user_hash' not in st.session_state:
|
578 |
+
session_id = str(random.getrandbits(128))
|
579 |
+
hash_object = hashlib.md5(session_id.encode())
|
580 |
+
st.session_state['user_hash'] = hash_object.hexdigest()[:8]
|
581 |
+
return st.session_state['user_hash']
|
582 |
+
|
583 |
+
async def save_pasted_image(image, username, prompt=""):
|
584 |
+
img_hash = hashlib.md5(image.tobytes()).hexdigest()[:8]
|
585 |
+
if img_hash in st.session_state.image_hashes:
|
586 |
+
return None
|
587 |
+
context = prompt if prompt else st.session_state.get('last_message', "pasted_image")
|
588 |
+
timestamp = format_timestamp_prefix(username)
|
589 |
+
filename = f"{timestamp}-{clean_text_for_filename(context)}-{img_hash}.png"
|
590 |
+
filepath = filename
|
591 |
+
try:
|
592 |
+
image.save(filepath, "PNG")
|
593 |
+
st.session_state.image_hashes.add(img_hash)
|
594 |
+
await save_chat_entry(username, f"Pasted image saved: {filepath}", FUN_USERNAMES.get(username, "en-US-AriaNeural"))
|
595 |
+
return filepath
|
596 |
+
except Exception as e:
|
597 |
+
st.error(f"Failed to save image: {e}")
|
598 |
+
return None
|
599 |
+
|
600 |
+
# 📦 Zip and Delete Files
|
601 |
+
def create_zip_of_files(files, prefix="All", query="latest"):
|
602 |
+
if not files:
|
603 |
+
return None
|
604 |
+
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 files] + [query]), 5)
|
605 |
+
zip_name = f"{prefix}_{format_timestamp_prefix()}_{'-'.join(terms)[:20]}.zip"
|
606 |
+
with zipfile.ZipFile(zip_name, 'w') as z:
|
607 |
+
[z.write(f) for f in files]
|
608 |
+
return zip_name
|
609 |
+
|
610 |
+
def delete_files(file_type, exclude_files=["README.md"]):
|
611 |
+
files = glob.glob(f"*.{file_type}")
|
612 |
+
if file_type == "md":
|
613 |
+
files = [f for f in files if os.path.basename(f) not in exclude_files]
|
614 |
+
for f in files:
|
615 |
+
try:
|
616 |
+
os.remove(f)
|
617 |
+
st.session_state['mp3_files'] = {k: v for k, v in st.session_state['mp3_files'].items() if not k.endswith(f".{file_type}")}
|
618 |
+
except Exception as e:
|
619 |
+
st.error(f"Failed to delete {f}: {e}")
|
620 |
+
if file_type in ["md", "mp3", "png", "mp4"]:
|
621 |
+
st.session_state['download_link_cache'] = {}
|
622 |
+
|
623 |
+
# Custom Paste and Upload Component
|
624 |
+
def paste_image_component():
|
625 |
+
with st.form(key="paste_form"):
|
626 |
+
paste_input = st.text_area("Paste Image Data Here", key="paste_input", height=100)
|
627 |
+
submit_button = st.form_submit_button("Paste Image 📋")
|
628 |
+
|
629 |
+
if submit_button and paste_input:
|
630 |
+
try:
|
631 |
+
if paste_input.startswith('data:image'):
|
632 |
+
mime_type = paste_input.split(';')[0].split(':')[1]
|
633 |
+
base64_str = paste_input.split(',')[1]
|
634 |
+
img_bytes = base64.b64decode(base64_str)
|
635 |
+
img = Image.open(io.BytesIO(img_bytes))
|
636 |
+
st.image(img, caption=f"Pasted Image ({mime_type.split('/')[1].upper()})", use_column_width=True)
|
637 |
+
return img, mime_type.split('/')[1]
|
638 |
+
else:
|
639 |
+
st.warning("Pasted data is not a recognized image format.")
|
640 |
+
return None, None
|
641 |
+
except Exception as e:
|
642 |
+
st.error(f"Error decoding pasted image: {e}")
|
643 |
+
return None, None
|
644 |
+
return None, None
|
645 |
+
|
646 |
+
# 🎮 Main Interface
|
647 |
+
def main():
|
648 |
+
init_session_state()
|
649 |
+
load_mp3_viewer()
|
650 |
+
saved_username = load_username()
|
651 |
+
if saved_username and saved_username in FUN_USERNAMES:
|
652 |
+
st.session_state.username = saved_username
|
653 |
+
if not st.session_state.username:
|
654 |
+
available = [n for n in FUN_USERNAMES if not any(f"{n} has joined" in l for l in asyncio.run(load_chat()))]
|
655 |
+
st.session_state.username = random.choice(available or list(FUN_USERNAMES.keys()))
|
656 |
+
st.session_state.tts_voice = FUN_USERNAMES[st.session_state.username]
|
657 |
+
asyncio.run(save_chat_entry("System 🌟", f"{st.session_state.username} has joined {START_ROOM}!", "en-US-AriaNeural"))
|
658 |
+
save_username(st.session_state.username)
|
659 |
+
|
660 |
+
st.title(f"{Site_Name} for {st.session_state.username}")
|
661 |
+
update_marquee_settings_ui()
|
662 |
+
chat_text = get_chat_text_only()
|
663 |
+
display_marquee(f"🚀 Welcome to {START_ROOM} | 🤖 {st.session_state.username} | Chat: {chat_text}", st.session_state['marquee_settings'], "welcome")
|
664 |
+
|
665 |
+
mycomponent = components.declare_component("mycomponent", path="mycomponent")
|
666 |
+
val = mycomponent(my_input_value="", key=f"speech_{st.session_state.get('speech_processed', False)}")
|
667 |
+
if val and val != st.session_state.last_transcript:
|
668 |
+
val_stripped = val.strip().replace('\n', ' ')
|
669 |
+
if val_stripped:
|
670 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
671 |
+
st.session_state['speech_processed'] = True
|
672 |
+
md_file, audio_file = asyncio.run(save_chat_entry(st.session_state.username, val_stripped, voice))
|
673 |
+
if audio_file:
|
674 |
+
play_and_download_audio(audio_file)
|
675 |
+
st.rerun()
|
676 |
+
|
677 |
+
tab_main = st.radio("Action:", ["🎤 Chat & Voice", "🔍 ArXiv", "📚 PDF to Audio"], horizontal=True, key="tab_main")
|
678 |
+
st.checkbox("Search ArXiv", key="use_arxiv")
|
679 |
+
st.checkbox("ArXiv Audio", key="use_arxiv_audio")
|
680 |
+
st.checkbox("Autosend Chat", key="autosend")
|
681 |
+
st.checkbox("Autosearch ArXiv", key="autosearch")
|
682 |
+
|
683 |
+
if tab_main == "🎤 Chat & Voice":
|
684 |
+
st.subheader(f"{START_ROOM} Chat 💬")
|
685 |
+
chat_content = asyncio.run(load_chat())
|
686 |
+
chat_container = st.container()
|
687 |
+
with chat_container:
|
688 |
+
numbered_content = "\n".join(f"{i+1}. {line}" for i, line in enumerate(chat_content))
|
689 |
+
st.code(numbered_content, language="python")
|
690 |
+
|
691 |
+
message = st.text_input(f"Message as {st.session_state.username}", key="message_input")
|
692 |
+
|
693 |
+
col_paste, col_upload = st.columns(2)
|
694 |
+
with col_paste:
|
695 |
+
pasted_image, img_type = paste_image_component()
|
696 |
+
with col_upload:
|
697 |
+
uploaded_files = st.file_uploader("Upload Files", accept_multiple_files=True, type=["mp3", "png", "mp4", "md"], key="file_upload")
|
698 |
+
|
699 |
+
if pasted_image is not None:
|
700 |
+
if st.session_state['paste_image_base64'] != base64.b64encode(pasted_image.tobytes()).decode('utf-8'):
|
701 |
+
st.session_state['paste_image_base64'] = base64.b64encode(pasted_image.tobytes()).decode('utf-8')
|
702 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
703 |
+
image_prompt = st.text_input("Add a prompt for Claude (e.g., 'OCR this image')", key="image_prompt", value="")
|
704 |
+
with st.spinner("Saving image..."):
|
705 |
+
filename = asyncio.run(save_pasted_image(pasted_image, st.session_state.username, image_prompt))
|
706 |
+
if filename:
|
707 |
+
st.success(f"Image saved as: {filename}")
|
708 |
+
if image_prompt:
|
709 |
+
with st.spinner("Processing with Claude..."):
|
710 |
+
md_file_claude, audio_file_claude, claude_result = asyncio.run(
|
711 |
+
perform_claude_search(image_prompt, st.session_state.username, pasted_image)
|
712 |
+
)
|
713 |
+
if audio_file_claude:
|
714 |
+
play_and_download_audio(audio_file_claude)
|
715 |
+
if claude_result:
|
716 |
+
with st.spinner("Searching ArXiv..."):
|
717 |
+
md_file_arxiv, audio_file_arxiv = asyncio.run(
|
718 |
+
perform_arxiv_search(image_prompt, st.session_state.username, claude_result)
|
719 |
+
)
|
720 |
+
if audio_file_arxiv:
|
721 |
+
play_and_download_audio(audio_file_arxiv)
|
722 |
+
st.session_state.pasted_image_data = None
|
723 |
+
st.session_state['paste_image_base64'] = ""
|
724 |
+
st.session_state.timer_start = time.time()
|
725 |
+
save_username(st.session_state.username)
|
726 |
+
st.rerun()
|
727 |
+
|
728 |
+
if uploaded_files:
|
729 |
+
for uploaded_file in uploaded_files:
|
730 |
+
file_type = uploaded_file.name.split('.')[-1].lower()
|
731 |
+
if file_type in ["mp3", "png", "mp4", "md"]:
|
732 |
+
timestamp = format_timestamp_prefix(st.session_state.username)
|
733 |
+
filename = f"{timestamp}-{clean_text_for_filename(uploaded_file.name)}"
|
734 |
+
with open(filename, "wb") as f:
|
735 |
+
f.write(uploaded_file.getbuffer())
|
736 |
+
st.success(f"Uploaded {file_type.upper()} as: {filename}")
|
737 |
+
if file_type == "png":
|
738 |
+
img = Image.open(filename)
|
739 |
+
st.image(img, caption=f"Uploaded Image: {filename}", use_column_width=True)
|
740 |
+
elif file_type == "mp3":
|
741 |
+
st.audio(filename)
|
742 |
+
elif file_type == "mp4":
|
743 |
+
st.video(filename)
|
744 |
+
elif file_type == "md":
|
745 |
+
with open(filename, 'r', encoding='utf-8') as f:
|
746 |
+
st.markdown(f.read())
|
747 |
+
asyncio.run(save_chat_entry(st.session_state.username, f"Uploaded {file_type.upper()}: {filename}", FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")))
|
748 |
+
st.session_state.timer_start = time.time()
|
749 |
+
save_username(st.session_state.username)
|
750 |
+
st.rerun()
|
751 |
+
|
752 |
+
if (message and message != st.session_state.last_message) or (st.session_state.pasted_image_data and not st.session_state['paste_image_base64']):
|
753 |
+
st.session_state.last_message = message
|
754 |
+
col_send, col_claude, col_arxiv = st.columns([1, 1, 1])
|
755 |
+
|
756 |
+
with col_send:
|
757 |
+
if st.session_state.autosend or st.button("Send 🚀", key="send_button"):
|
758 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
759 |
+
if message.strip():
|
760 |
+
md_file, audio_file = asyncio.run(save_chat_entry(st.session_state.username, message, voice, True))
|
761 |
+
if audio_file:
|
762 |
+
play_and_download_audio(audio_file)
|
763 |
+
if st.session_state.pasted_image_data:
|
764 |
+
asyncio.run(save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}", voice))
|
765 |
+
st.session_state.pasted_image_data = None
|
766 |
+
st.session_state.timer_start = time.time()
|
767 |
+
save_username(st.session_state.username)
|
768 |
+
st.rerun()
|
769 |
+
|
770 |
+
with col_claude:
|
771 |
+
if st.button("🧠 Claude", key="claude_button"):
|
772 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
773 |
+
if message.strip():
|
774 |
+
md_file, audio_file, _ = asyncio.run(perform_claude_search(message, st.session_state.username))
|
775 |
+
if audio_file:
|
776 |
+
play_and_download_audio(audio_file)
|
777 |
+
st.session_state.timer_start = time.time()
|
778 |
+
save_username(st.session_state.username)
|
779 |
+
st.rerun()
|
780 |
+
|
781 |
+
with col_arxiv:
|
782 |
+
if st.button("🔍 ArXiv", key="arxiv_button"):
|
783 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
784 |
+
if message.strip():
|
785 |
+
md_file, audio_file = asyncio.run(perform_arxiv_search(message, st.session_state.username))
|
786 |
+
if audio_file:
|
787 |
+
play_and_download_audio(audio_file)
|
788 |
+
st.session_state.timer_start = time.time()
|
789 |
+
save_username(st.session_state.username)
|
790 |
+
st.rerun()
|
791 |
+
|
792 |
+
elif tab_main == "🔍 ArXiv":
|
793 |
+
st.subheader("🔍 Query ArXiv")
|
794 |
+
q = st.text_input("🔍 Query:", key="arxiv_query")
|
795 |
+
if q and q != st.session_state.last_query:
|
796 |
+
st.session_state.last_query = q
|
797 |
+
if st.session_state.autosearch or st.button("🔍 Run", key="arxiv_run"):
|
798 |
+
result, papers = asyncio.run(perform_ai_lookup(q, useArxiv=st.session_state['use_arxiv'], useArxivAudio=st.session_state['use_arxiv_audio']))
|
799 |
+
st.markdown(f"### Query: {q}")
|
800 |
+
for i, p in enumerate(papers, 1):
|
801 |
+
expander_label = f"{p['title']} | [arXiv Link]({p['url']})"
|
802 |
+
with st.expander(expander_label):
|
803 |
+
with open(p['md_file'], 'r', encoding='utf-8') as f:
|
804 |
+
content = f.read()
|
805 |
+
numbered_content = "\n".join(f"{j+1}. {line}" for j, line in enumerate(content.split('\n')))
|
806 |
+
st.code(numbered_content, language="python")
|
807 |
+
|
808 |
+
elif tab_main == "📚 PDF to Audio":
|
809 |
+
audio_processor = AudioProcessor()
|
810 |
+
pdf_file = st.file_uploader("Choose PDF", "pdf", key="pdf_upload")
|
811 |
+
max_pages = st.slider('Pages', 1, 100, 10, key="pdf_pages")
|
812 |
+
if pdf_file:
|
813 |
+
with st.spinner('Processing...'):
|
814 |
+
texts, audios, total = process_pdf(pdf_file, max_pages, st.session_state['tts_voice'], audio_processor)
|
815 |
+
for i, text in enumerate(texts):
|
816 |
+
with st.expander(f"Page {i+1}"):
|
817 |
+
st.markdown(text)
|
818 |
+
while i not in audios:
|
819 |
+
time.sleep(0.1)
|
820 |
+
if audios.get(i):
|
821 |
+
st.audio(audios[i])
|
822 |
+
st.markdown(get_download_link(audios[i], "mp3"), unsafe_allow_html=True)
|
823 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
824 |
+
asyncio.run(save_chat_entry(st.session_state.username, f"PDF Page {i+1} converted to audio: {audios[i]}", voice))
|
825 |
+
|
826 |
+
# Always Visible Media Gallery
|
827 |
+
st.header("📸 Media Gallery")
|
828 |
+
all_files = sorted(glob.glob("*.md") + glob.glob("*.mp3") + glob.glob("*.png") + glob.glob("*.mp4"), key=os.path.getmtime)
|
829 |
+
md_files = [f for f in all_files if f.endswith('.md') and os.path.basename(f) != "README.md"]
|
830 |
+
mp3_files = [f for f in all_files if f.endswith('.mp3')]
|
831 |
+
png_files = [f for f in all_files if f.endswith('.png')]
|
832 |
+
mp4_files = [f for f in all_files if f.endswith('.mp4')]
|
833 |
+
|
834 |
+
st.subheader("All Submitted Text")
|
835 |
+
all_md_content = concatenate_markdown_files()
|
836 |
+
with st.expander("View All Markdown Content"):
|
837 |
+
st.markdown(all_md_content)
|
838 |
+
|
839 |
+
st.subheader("🎵 Audio (MP3)")
|
840 |
+
for filename, (num, mp3) in sorted(st.session_state['mp3_files'].items(), key=lambda x: x[1][0]):
|
841 |
+
with st.expander(f"{num}. {os.path.basename(mp3)}"):
|
842 |
+
st.audio(mp3)
|
843 |
+
st.markdown(get_download_link(mp3, "mp3"), unsafe_allow_html=True)
|
844 |
+
|
845 |
+
st.subheader("🖼️ Images (PNG)")
|
846 |
+
for png in sorted(png_files, key=os.path.getmtime):
|
847 |
+
with st.expander(os.path.basename(png)):
|
848 |
+
st.image(png, use_container_width=True)
|
849 |
+
st.markdown(get_download_link(png, "png"), unsafe_allow_html=True)
|
850 |
+
|
851 |
+
st.subheader("🎥 Videos (MP4)")
|
852 |
+
for mp4 in sorted(mp4_files, key=os.path.getmtime):
|
853 |
+
with st.expander(os.path.basename(mp4)):
|
854 |
+
st.video(mp4)
|
855 |
+
st.markdown(get_download_link(mp4, "mp4"), unsafe_allow_html=True)
|
856 |
+
|
857 |
+
# 🗂️ Sidebar with Dialog and Audio
|
858 |
+
st.sidebar.subheader("Voice Settings")
|
859 |
+
new_username = st.sidebar.selectbox("Change Name/Voice", list(FUN_USERNAMES.keys()), index=list(FUN_USERNAMES.keys()).index(st.session_state.username), key="username_select")
|
860 |
+
if new_username != st.session_state.username:
|
861 |
+
asyncio.run(save_chat_entry("System 🌟", f"{st.session_state.username} changed to {new_username}", "en-US-AriaNeural"))
|
862 |
+
st.session_state.username, st.session_state.tts_voice = new_username, FUN_USERNAMES[new_username]
|
863 |
+
st.session_state.timer_start = time.time()
|
864 |
+
save_username(st.session_state.username)
|
865 |
+
st.rerun()
|
866 |
+
|
867 |
+
st.sidebar.markdown("### 💬 Chat Dialog")
|
868 |
+
chat_content = asyncio.run(load_chat())
|
869 |
+
with st.sidebar.expander("Chat History"):
|
870 |
+
numbered_content = "\n".join(f"{i+1}. {line}" for i, line in enumerate(chat_content))
|
871 |
+
st.code(numbered_content, language="python")
|
872 |
+
|
873 |
+
st.sidebar.markdown("### 💬 Chat Text Only")
|
874 |
+
chat_text_only = get_chat_text_only()
|
875 |
+
with st.sidebar.expander("Text Only History"):
|
876 |
+
numbered_text = "\n".join(f"{i+1}. {line}" for i, line in enumerate(chat_text_only.split('\n')))
|
877 |
+
st.code(numbered_text, language="python")
|
878 |
+
|
879 |
+
st.sidebar.subheader("Vote Totals")
|
880 |
+
chat_votes = load_votes(QUOTE_VOTES_FILE)
|
881 |
+
image_votes = load_votes(IMAGE_VOTES_FILE)
|
882 |
+
for item, count in chat_votes.items():
|
883 |
+
st.sidebar.write(f"{item}: {count} votes")
|
884 |
+
for image, count in image_votes.items():
|
885 |
+
st.sidebar.write(f"{image}: {count} votes")
|
886 |
+
|
887 |
+
st.sidebar.markdown("### 📂 File History")
|
888 |
+
for f in all_files[:10]:
|
889 |
+
st.sidebar.write(f"{FILE_EMOJIS.get(f.split('.')[-1], '📄')} {os.path.basename(f)}")
|
890 |
+
|
891 |
+
st.sidebar.subheader("📦 Zip & Delete")
|
892 |
+
col_zip, col_del = st.sidebar.columns(2)
|
893 |
+
with col_zip:
|
894 |
+
if st.button("⬇️ Zip All", key="zip_all"):
|
895 |
+
zip_name = create_zip_of_files(all_files, "All")
|
896 |
+
if zip_name:
|
897 |
+
st.session_state['download_link_cache'] = {}
|
898 |
+
if st.button("⬇️ Zip All MD", key="zip_md"):
|
899 |
+
zip_name = create_zip_of_files(md_files, "MD")
|
900 |
+
if zip_name:
|
901 |
+
st.session_state['download_link_cache'] = {}
|
902 |
+
if st.button("⬇️ Zip All MP3", key="zip_mp3"):
|
903 |
+
zip_name = create_zip_of_files(mp3_files, "MP3")
|
904 |
+
if zip_name:
|
905 |
+
st.session_state['download_link_cache'] = {}
|
906 |
+
if st.button("⬇️ Zip All PNG", key="zip_png"):
|
907 |
+
zip_name = create_zip_of_files(png_files, "PNG")
|
908 |
+
if zip_name:
|
909 |
+
st.session_state['download_link_cache'] = {}
|
910 |
+
if st.button("⬇️ Zip All MP4", key="zip_mp4"):
|
911 |
+
zip_name = create_zip_of_files(mp4_files, "MP4")
|
912 |
+
if zip_name:
|
913 |
+
st.session_state['download_link_cache'] = {}
|
914 |
+
with col_del:
|
915 |
+
if st.button("🗑️ Del All", key="del_all"):
|
916 |
+
for ft in ["md", "mp3", "png", "mp4"]:
|
917 |
+
delete_files(ft)
|
918 |
+
st.rerun()
|
919 |
+
if st.button("🗑️ Del All MD", key="del_md"):
|
920 |
+
delete_files("md")
|
921 |
+
st.rerun()
|
922 |
+
if st.button("🗑️ Del All MP3", key="del_mp3"):
|
923 |
+
delete_files("mp3")
|
924 |
+
st.rerun()
|
925 |
+
if st.button("🗑️ Del All PNG", key="del_png"):
|
926 |
+
delete_files("png")
|
927 |
+
st.rerun()
|
928 |
+
if st.button("🗑️ Del All MP4", key="del_mp4"):
|
929 |
+
delete_files("mp4")
|
930 |
+
st.rerun()
|
931 |
+
if st.button("🗑️ Del All Zip", key="del_zip"):
|
932 |
+
delete_files("zip", exclude_files=[])
|
933 |
+
st.rerun()
|
934 |
+
|
935 |
+
zip_files = sorted(glob.glob("*.zip"), key=os.path.getmtime, reverse=True)
|
936 |
+
for zip_file in zip_files:
|
937 |
+
st.sidebar.markdown(get_download_link(zip_file, "zip"), unsafe_allow_html=True)
|
938 |
+
|
939 |
+
# Refresh Timer in Sidebar
|
940 |
+
st.sidebar.subheader("Set Refresh Rate ⏳")
|
941 |
+
st.session_state['auto_refresh'] = st.sidebar.radio("Auto Refresh", ["On", "Off"], index=0 if st.session_state['auto_refresh'] else 1) == "On"
|
942 |
+
st.markdown("""
|
943 |
+
<style>
|
944 |
+
.timer {
|
945 |
+
font-size: 24px;
|
946 |
+
color: #ffcc00;
|
947 |
+
text-align: center;
|
948 |
+
animation: pulse 1s infinite;
|
949 |
+
}
|
950 |
+
@keyframes pulse {
|
951 |
+
0% { transform: scale(1); }
|
952 |
+
50% { transform: scale(1.1); }
|
953 |
+
100% { transform: scale(1); }
|
954 |
+
}
|
955 |
+
</style>
|
956 |
+
""", unsafe_allow_html=True)
|
957 |
+
|
958 |
+
refresh_rate = st.sidebar.slider("Refresh Rate (seconds)", min_value=1, max_value=300, value=st.session_state.refresh_rate, step=1)
|
959 |
+
if refresh_rate != st.session_state.refresh_rate:
|
960 |
+
st.session_state.refresh_rate = refresh_rate
|
961 |
+
st.session_state.timer_start = time.time()
|
962 |
+
save_username(st.session_state.username)
|
963 |
+
|
964 |
+
col1, col2, col3 = st.sidebar.columns(3)
|
965 |
+
with col1:
|
966 |
+
if st.button("🐇 Small (1s)"):
|
967 |
+
st.session_state.refresh_rate = 1
|
968 |
+
st.session_state.timer_start = time.time()
|
969 |
+
save_username(st.session_state.username)
|
970 |
+
with col2:
|
971 |
+
if st.button("🐢 Medium (10s)"):
|
972 |
+
st.session_state.refresh_rate = 10
|
973 |
+
st.session_state.timer_start = time.time()
|
974 |
+
save_username(st.session_state.username)
|
975 |
+
with col3:
|
976 |
+
if st.button("🐘 Large (5m)"):
|
977 |
+
st.session_state.refresh_rate = 300
|
978 |
+
st.session_state.timer_start = time.time()
|
979 |
+
save_username(st.session_state.username)
|
980 |
+
|
981 |
+
timer_placeholder = st.sidebar.empty()
|
982 |
+
def update_timer():
|
983 |
+
start_time = st.session_state.timer_start
|
984 |
+
remaining_time = max(0, int(st.session_state.refresh_rate - (time.time() - start_time)))
|
985 |
+
timer_placeholder.markdown(f"<p class='timer'>⏳ Next refresh in: {remaining_time} seconds</p>", unsafe_allow_html=True)
|
986 |
+
if st.session_state['auto_refresh'] and remaining_time <= 0:
|
987 |
+
st.session_state.timer_start = time.time()
|
988 |
+
st.session_state.last_refresh = time.time()
|
989 |
+
st.rerun()
|
990 |
+
|
991 |
+
# Force timer update every second
|
992 |
+
threading.Thread(target=lambda: [time.sleep(1) or update_timer() for _ in range(int(st.session_state.refresh_rate)+1)], daemon=True).start()
|
993 |
+
update_timer()
|
994 |
+
|
995 |
+
if not st.session_state.get('server_running', False) and not st.session_state.get('server_task', None):
|
996 |
+
st.session_state.server_task = threading.Thread(target=start_websocket_server, daemon=True)
|
997 |
+
st.session_state.server_task.start()
|
998 |
+
|
999 |
+
if __name__ == "__main__":
|
1000 |
+
main()
|