Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,57 +1,402 @@
|
|
1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
#
|
4 |
-
|
5 |
-
|
6 |
-
#
|
7 |
-
st.
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
#
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
"""
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
st.write("Powered by Grok 3 @ xAI π₯βColorado madness, tech roasts, and your unhinged brain. Stay wild, fam! π")
|
|
|
1 |
import streamlit as st
|
2 |
+
import asyncio
|
3 |
+
import websockets
|
4 |
+
import uuid
|
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 anthropic
|
21 |
+
import openai
|
22 |
+
from PyPDF2 import PdfReader
|
23 |
+
import threading
|
24 |
+
import json
|
25 |
+
import zipfile
|
26 |
+
from gradio_client import Client
|
27 |
+
from dotenv import load_dotenv
|
28 |
+
from streamlit_marquee import streamlit_marquee
|
29 |
+
from collections import defaultdict, Counter
|
30 |
+
import pandas as pd
|
31 |
|
32 |
+
# Patch asyncio for nesting
|
33 |
+
nest_asyncio.apply()
|
34 |
+
|
35 |
+
# Page Config
|
36 |
+
st.set_page_config(
|
37 |
+
layout="wide",
|
38 |
+
page_title="Colorado Sim: Mountains, Memes, & Mayhem πποΈ",
|
39 |
+
page_icon="π¦"
|
40 |
+
)
|
41 |
+
|
42 |
+
# Static Config with Character-Driven Sim
|
43 |
+
Site_Name = "Colorado Sim Chat ποΈβ¨"
|
44 |
+
START_ROOM = "Rocky Mountain Hub π²"
|
45 |
+
FUN_USERNAMES = {
|
46 |
+
"Trailblazer Tim π": "en-US-GuyNeural", # Adventurous hiker
|
47 |
+
"Meme Queen Mia π": "en-US-JennyNeural", # Meme enthusiast
|
48 |
+
"Elk Whisperer Eve π¦": "en-GB-SoniaNeural", # Wildlife lover
|
49 |
+
"Tech Titan Tara πΎ": "en-AU-NatashaNeural", # Tech-savvy coder
|
50 |
+
"Ski Guru Sam β·οΈ": "en-CA-ClaraNeural", # Skiing pro
|
51 |
+
"Cosmic Camper Cal π ": "en-US-AriaNeural", # Stargazing storyteller
|
52 |
+
"Rasta Ranger Rick π": "en-GB-RyanNeural", # Chill outdoorsman
|
53 |
+
"Boulder Bro Ben πͺ¨": "en-AU-WilliamNeural" # Rock-climbing dude
|
54 |
+
}
|
55 |
+
EDGE_TTS_VOICES = list(set(FUN_USERNAMES.values()))
|
56 |
+
FILE_EMOJIS = {"md": "π", "mp3": "π΅", "png": "πΌοΈ", "mp4": "π₯", "zip": "π¦"}
|
57 |
+
|
58 |
+
# Directories
|
59 |
+
for d in ["chat_logs", "audio_logs", "audio_cache"]:
|
60 |
+
os.makedirs(d, exist_ok=True)
|
61 |
+
|
62 |
+
CHAT_DIR = "chat_logs"
|
63 |
+
AUDIO_CACHE_DIR = "audio_cache"
|
64 |
+
AUDIO_DIR = "audio_logs"
|
65 |
+
STATE_FILE = "user_state.txt"
|
66 |
+
CHAT_FILE = os.path.join(CHAT_DIR, "sim_chat.md")
|
67 |
+
|
68 |
+
# API Keys
|
69 |
+
load_dotenv()
|
70 |
+
anthropic_key = os.getenv('ANTHROPIC_API_KEY', st.secrets.get('ANTHROPIC_API_KEY', ""))
|
71 |
+
openai_api_key = os.getenv('OPENAI_API_KEY', st.secrets.get('OPENAI_API_KEY', ""))
|
72 |
+
openai_client = openai.OpenAI(api_key=openai_api_key)
|
73 |
+
|
74 |
+
# Timestamp Helper
|
75 |
+
def format_timestamp_prefix(username=""):
|
76 |
+
central = pytz.timezone('US/Central')
|
77 |
+
now = datetime.now(central)
|
78 |
+
return f"{now.strftime('%Y%m%d_%H%M%S')}-by-{username}"
|
79 |
+
|
80 |
+
# Session State Init
|
81 |
+
def init_session_state():
|
82 |
+
defaults = {
|
83 |
+
'server_running': False, 'server_task': None, 'active_connections': {},
|
84 |
+
'last_chat_update': 0, 'message_text': "", 'audio_cache': {},
|
85 |
+
'transcript_history': [], 'last_transcript': "", 'tts_voice': "en-US-AriaNeural",
|
86 |
+
'chat_history': [], 'marquee_settings': {
|
87 |
+
"background": "#1E1E1E", "color": "#FFFFFF", "font-size": "14px",
|
88 |
+
"animationDuration": "20s", "width": "100%", "lineHeight": "35px"
|
89 |
+
}, 'username': None, 'autosend': True, 'autosearch': True, 'last_message': "",
|
90 |
+
'mp3_files': {}, 'timer_start': time.time(), 'auto_refresh': True, 'refresh_rate': 10
|
91 |
+
}
|
92 |
+
for k, v in defaults.items():
|
93 |
+
if k not in st.session_state:
|
94 |
+
st.session_state[k] = v
|
95 |
+
|
96 |
+
# Marquee Helpers
|
97 |
+
def update_marquee_settings_ui():
|
98 |
+
st.sidebar.markdown("### π― Marquee Settings")
|
99 |
+
cols = st.sidebar.columns(2)
|
100 |
+
with cols[0]:
|
101 |
+
st.session_state['marquee_settings']['background'] = st.color_picker("π¨ Background", "#1E1E1E")
|
102 |
+
st.session_state['marquee_settings']['color'] = st.color_picker("βοΈ Text", "#FFFFFF")
|
103 |
+
with cols[1]:
|
104 |
+
st.session_state['marquee_settings']['font-size'] = f"{st.slider('π Size', 10, 24, 14)}px"
|
105 |
+
st.session_state['marquee_settings']['animationDuration'] = f"{st.slider('β±οΈ Speed', 1, 20, 20)}s"
|
106 |
+
|
107 |
+
def display_marquee(text, settings, key_suffix=""):
|
108 |
+
truncated = text[:280] + "..." if len(text) > 280 else text
|
109 |
+
streamlit_marquee(content=truncated, **settings, key=f"marquee_{key_suffix}")
|
110 |
+
st.write("")
|
111 |
+
|
112 |
+
# Text & File Helpers
|
113 |
+
def clean_text_for_tts(text):
|
114 |
+
return re.sub(r'[#*!\[\]]+', '', ' '.join(text.split()))[:200] or "No text"
|
115 |
+
|
116 |
+
def clean_text_for_filename(text):
|
117 |
+
return '_'.join(re.sub(r'[^\w\s-]', '', text.lower()).split())[:50]
|
118 |
+
|
119 |
+
def generate_filename(prompt, username, file_type="md"):
|
120 |
+
timestamp = format_timestamp_prefix(username)
|
121 |
+
hash_val = hashlib.md5(prompt.encode()).hexdigest()[:8]
|
122 |
+
return f"{timestamp}-{hash_val}.{file_type}"
|
123 |
+
|
124 |
+
def create_file(prompt, username, file_type="md"):
|
125 |
+
filename = generate_filename(prompt, username, file_type)
|
126 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
127 |
+
f.write(prompt)
|
128 |
+
return filename
|
129 |
+
|
130 |
+
def get_download_link(file, file_type="mp3"):
|
131 |
+
with open(file, "rb") as f:
|
132 |
+
b64 = base64.b64encode(f.read()).decode()
|
133 |
+
mime_types = {"mp3": "audio/mpeg", "png": "image/png", "md": "text/markdown"}
|
134 |
+
return 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>'
|
135 |
+
|
136 |
+
def save_username(username):
|
137 |
+
with open(STATE_FILE, 'w') as f:
|
138 |
+
f.write(username)
|
139 |
+
|
140 |
+
def load_username():
|
141 |
+
if os.path.exists(STATE_FILE):
|
142 |
+
with open(STATE_FILE, 'r') as f:
|
143 |
+
return f.read().strip()
|
144 |
+
return None
|
145 |
+
|
146 |
+
# Audio Processing
|
147 |
+
async def async_edge_tts_generate(text, voice, username):
|
148 |
+
cache_key = f"{text[:100]}_{voice}"
|
149 |
+
if cache_key in st.session_state['audio_cache']:
|
150 |
+
return st.session_state['audio_cache'][cache_key]
|
151 |
+
text = clean_text_for_tts(text)
|
152 |
+
filename = f"{format_timestamp_prefix(username)}-{hashlib.md5(text.encode()).hexdigest()[:8]}.mp3"
|
153 |
+
communicate = edge_tts.Communicate(text, voice)
|
154 |
+
await communicate.save(filename)
|
155 |
+
if os.path.exists(filename) and os.path.getsize(filename) > 0:
|
156 |
+
st.session_state['audio_cache'][cache_key] = filename
|
157 |
+
return filename
|
158 |
+
return None
|
159 |
+
|
160 |
+
def play_and_download_audio(file_path):
|
161 |
+
if file_path and os.path.exists(file_path):
|
162 |
+
st.audio(file_path)
|
163 |
+
st.markdown(get_download_link(file_path), unsafe_allow_html=True)
|
164 |
|
165 |
+
async def save_chat_entry(username, message, voice, is_markdown=False):
|
166 |
+
if not message.strip() or message == st.session_state.last_transcript:
|
167 |
+
return None, None
|
168 |
+
central = pytz.timezone('US/Central')
|
169 |
+
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
|
170 |
+
entry = f"[{timestamp}] {username} ({voice}): {message}" if not is_markdown else f"[{timestamp}] {username} ({voice}):\n```markdown\n{message}\n```"
|
171 |
+
md_file = create_file(entry, username, "md")
|
172 |
+
with open(CHAT_FILE, 'a') as f:
|
173 |
+
f.write(f"{entry}\n")
|
174 |
+
audio_file = await async_edge_tts_generate(message, voice, username)
|
175 |
+
await broadcast_message(f"{username}|{message}", "chat")
|
176 |
+
st.session_state.last_chat_update = time.time()
|
177 |
+
st.session_state.chat_history.append(entry)
|
178 |
+
st.session_state.last_transcript = message
|
179 |
+
return md_file, audio_file
|
180 |
|
181 |
+
async def load_chat():
|
182 |
+
if not os.path.exists(CHAT_FILE):
|
183 |
+
with open(CHAT_FILE, 'a') as f:
|
184 |
+
f.write(f"# {START_ROOM} Chat\n\nWelcome to the Colorado Sim! ποΈ\n")
|
185 |
+
with open(CHAT_FILE, 'r') as f:
|
186 |
+
content = f.read().strip()
|
187 |
+
lines = content.split('\n')
|
188 |
+
return list(dict.fromkeys(line for line in lines if line.strip()))
|
189 |
+
|
190 |
+
# Claude and ArXiv Search
|
191 |
+
async def perform_claude_search(query, username):
|
192 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
193 |
+
response = client.messages.create(
|
194 |
+
model="claude-3-sonnet-20240229",
|
195 |
+
max_tokens=1000,
|
196 |
+
messages=[{"role": "user", "content": query}]
|
197 |
+
)
|
198 |
+
result = response.content[0].text
|
199 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
200 |
+
full_text = f"Claude says: {result}"
|
201 |
+
md_file, audio_file = await save_chat_entry(username, full_text, voice, True)
|
202 |
+
return md_file, audio_file, result
|
203 |
+
|
204 |
+
async def perform_arxiv_search(query, username, claude_result=None):
|
205 |
+
if claude_result is None:
|
206 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
207 |
+
claude_response = client.messages.create(
|
208 |
+
model="claude-3-sonnet-20240229",
|
209 |
+
max_tokens=1000,
|
210 |
+
messages=[{"role": "user", "content": query}]
|
211 |
+
)
|
212 |
+
claude_result = claude_response.content[0].text
|
213 |
+
enhanced_query = f"{query}\n\n{claude_result}"
|
214 |
+
gradio_client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
215 |
+
refs = gradio_client.predict(
|
216 |
+
enhanced_query, 10, "Semantic Search", "mistralai/Mixtral-8x7B-Instruct-v0.1", api_name="/update_with_rag_md"
|
217 |
+
)[0]
|
218 |
+
result = f"π ArXiv Results:\n\n{refs}"
|
219 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
220 |
+
md_file, audio_file = await save_chat_entry(username, result, voice, True)
|
221 |
+
return md_file, audio_file
|
222 |
+
|
223 |
+
# WebSocket Handling
|
224 |
+
async def websocket_handler(websocket, path):
|
225 |
+
client_id = str(uuid.uuid4())
|
226 |
+
room_id = "chat"
|
227 |
+
if room_id not in st.session_state.active_connections:
|
228 |
+
st.session_state.active_connections[room_id] = {}
|
229 |
+
st.session_state.active_connections[room_id][client_id] = websocket
|
230 |
+
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
|
231 |
+
await save_chat_entry("System π", f"{username} has joined {START_ROOM}!", "en-US-AriaNeural")
|
232 |
+
try:
|
233 |
+
async for message in websocket:
|
234 |
+
if '|' in message:
|
235 |
+
username, content = message.split('|', 1)
|
236 |
+
voice = FUN_USERNAMES.get(username, "en-US-AriaNeural")
|
237 |
+
await save_chat_entry(username, content, voice)
|
238 |
+
except websockets.ConnectionClosed:
|
239 |
+
await save_chat_entry("System π", f"{username} has left {START_ROOM}!", "en-US-AriaNeural")
|
240 |
+
finally:
|
241 |
+
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
|
242 |
+
del st.session_state.active_connections[room_id][client_id]
|
243 |
+
|
244 |
+
async def broadcast_message(message, room_id):
|
245 |
+
if room_id in st.session_state.active_connections:
|
246 |
+
disconnected = []
|
247 |
+
for client_id, ws in st.session_state.active_connections[room_id].items():
|
248 |
+
try:
|
249 |
+
await ws.send(message)
|
250 |
+
except websockets.ConnectionClosed:
|
251 |
+
disconnected.append(client_id)
|
252 |
+
for client_id in disconnected:
|
253 |
+
if client_id in st.session_state.active_connections[room_id]:
|
254 |
+
del st.session_state.active_connections[room_id][client_id]
|
255 |
+
|
256 |
+
async def run_websocket_server():
|
257 |
+
if not st.session_state.get('server_running', False):
|
258 |
+
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
|
259 |
+
st.session_state['server_running'] = True
|
260 |
+
await server.wait_closed()
|
261 |
+
|
262 |
+
def start_websocket_server():
|
263 |
+
loop = asyncio.new_event_loop()
|
264 |
+
asyncio.set_event_loop(loop)
|
265 |
+
loop.run_until_complete(run_websocket_server())
|
266 |
+
|
267 |
+
# Sim-Oriented Mad Libs
|
268 |
+
def generate_mad_libs_story(username, inputs):
|
269 |
+
story = f"""
|
270 |
+
In the wilds of Colorado, {username} stumbled upon {inputs['plural_noun']}.
|
271 |
+
These {inputs['adjective1']} critters were {inputs['verb_ing']} all over the Rockies,
|
272 |
+
freaking out climbers like {inputs['celebrity']}.
|
273 |
+
Holding a {inputs['object']}, {username} felt {inputs['emotion']} as a {inputs['animal']}
|
274 |
+
{inputs['verb_past']} past, yelling {inputs['exclamation']} near {inputs['place']}.
|
275 |
+
Later, munching {inputs['food']} with a {inputs['adjective2']} {inputs['body_part']},
|
276 |
+
{username} looped β{inputs['song']}β {inputs['number']} times,
|
277 |
+
deciding to {inputs['verb_present']} as a {inputs['occupation']}
|
278 |
+
in a {inputs['color']} {inputs['noun']}βall ending with a {inputs['sound']}!
|
279 |
"""
|
280 |
+
return story.strip()
|
281 |
+
|
282 |
+
# Main Interface
|
283 |
+
def main():
|
284 |
+
init_session_state()
|
285 |
+
saved_username = load_username()
|
286 |
+
if saved_username and saved_username in FUN_USERNAMES:
|
287 |
+
st.session_state.username = saved_username
|
288 |
+
if not st.session_state.username:
|
289 |
+
st.session_state.username = random.choice(list(FUN_USERNAMES.keys()))
|
290 |
+
st.session_state.tts_voice = FUN_USERNAMES[st.session_state.username]
|
291 |
+
asyncio.run(save_chat_entry("System π", f"{st.session_state.username} has joined {START_ROOM}!", "en-US-AriaNeural"))
|
292 |
+
save_username(st.session_state.username)
|
293 |
+
|
294 |
+
st.title(f"{Site_Name} - {st.session_state.username}")
|
295 |
+
st.subheader("Chat, Search, or Create a Colorado Sim Story! ππ²")
|
296 |
+
update_marquee_settings_ui()
|
297 |
+
chat_text = " ".join([line.split(": ")[-1] for line in asyncio.run(load_chat()) if ": " in line])
|
298 |
+
display_marquee(f"ποΈ {START_ROOM} | {st.session_state.username} | {chat_text}", st.session_state['marquee_settings'], "welcome")
|
299 |
+
|
300 |
+
tab_main = st.radio("Action:", ["π€ Chat & Voice", "π Research", "β¨ Mad Libs Sim"], horizontal=True)
|
301 |
+
st.checkbox("Autosend Chat", key="autosend")
|
302 |
+
st.checkbox("Autosearch Research", key="autosearch")
|
303 |
+
|
304 |
+
if tab_main == "π€ Chat & Voice":
|
305 |
+
st.subheader(f"{START_ROOM} Chat π¬")
|
306 |
+
chat_content = asyncio.run(load_chat())
|
307 |
+
with st.container():
|
308 |
+
st.code("\n".join(f"{i+1}. {line}" for i, line in enumerate(chat_content)), language="python")
|
309 |
+
|
310 |
+
message = st.text_input(f"Message as {st.session_state.username}", key="message_input")
|
311 |
+
if message and message != st.session_state.last_message:
|
312 |
+
st.session_state.last_message = message
|
313 |
+
col_send, col_claude, col_arxiv = st.columns([1, 1, 1])
|
314 |
+
with col_send:
|
315 |
+
if st.session_state.autosend or st.button("Send π"):
|
316 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
317 |
+
md_file, audio_file = asyncio.run(save_chat_entry(st.session_state.username, message, voice, True))
|
318 |
+
if audio_file:
|
319 |
+
play_and_download_audio(audio_file)
|
320 |
+
st.rerun()
|
321 |
+
with col_claude:
|
322 |
+
if st.button("π§ Claude"):
|
323 |
+
md_file, audio_file, _ = asyncio.run(perform_claude_search(message, st.session_state.username))
|
324 |
+
if audio_file:
|
325 |
+
play_and_download_audio(audio_file)
|
326 |
+
st.rerun()
|
327 |
+
with col_arxiv:
|
328 |
+
if st.button("π ArXiv"):
|
329 |
+
md_file, audio_file = asyncio.run(perform_arxiv_search(message, st.session_state.username))
|
330 |
+
if audio_file:
|
331 |
+
play_and_download_audio(audio_file)
|
332 |
+
st.rerun()
|
333 |
+
|
334 |
+
elif tab_main == "π Research":
|
335 |
+
st.subheader("π Research with Claude & ArXiv")
|
336 |
+
q = st.text_input("Query:", key="research_query")
|
337 |
+
if q and (st.session_state.autosearch or st.button("π Run")):
|
338 |
+
st.session_state.last_message = q
|
339 |
+
md_file_claude, audio_file_claude, claude_result = asyncio.run(perform_claude_search(q, st.session_state.username))
|
340 |
+
if audio_file_claude:
|
341 |
+
play_and_download_audio(audio_file_claude)
|
342 |
+
md_file_arxiv, audio_file_arxiv = asyncio.run(perform_arxiv_search(q, st.session_state.username, claude_result))
|
343 |
+
if audio_file_arxiv:
|
344 |
+
play_and_download_audio(audio_file_arxiv)
|
345 |
+
|
346 |
+
elif tab_main == "β¨ Mad Libs Sim":
|
347 |
+
st.subheader("Create Your Colorado Sim Story!")
|
348 |
+
col1, col2 = st.columns(2)
|
349 |
+
inputs = {}
|
350 |
+
with col1:
|
351 |
+
inputs['plural_noun'] = st.text_input("1. Plural Noun", placeholder="e.g., 'tacos'")
|
352 |
+
inputs['adjective1'] = st.text_input("2. Adjective", placeholder="e.g., 'spicy'")
|
353 |
+
inputs['verb_ing'] = st.text_input("3. Verb ending in -ing", placeholder="e.g., 'yeeting'")
|
354 |
+
inputs['celebrity'] = st.text_input("4. Celebrity Name", placeholder="e.g., 'Elon Musk'")
|
355 |
+
inputs['object'] = st.text_input("5. Random Object", placeholder="e.g., 'toaster'")
|
356 |
+
inputs['emotion'] = st.text_input("6. Emotion", placeholder="e.g., 'salty'")
|
357 |
+
inputs['animal'] = st.text_input("7. Animal", placeholder="e.g., 'elk'")
|
358 |
+
inputs['verb_past'] = st.text_input("8. Verb (past tense)", placeholder="e.g., 'yeeted'")
|
359 |
+
inputs['place'] = st.text_input("9. Place", placeholder="e.g., 'Rockies'")
|
360 |
+
inputs['exclamation'] = st.text_input("10. Exclamation", placeholder="e.g., 'Bruh!'")
|
361 |
+
with col2:
|
362 |
+
inputs['food'] = st.text_input("11. Food Item", placeholder="e.g., 'pizza'")
|
363 |
+
inputs['adjective2'] = st.text_input("12. Adjective", placeholder="e.g., 'cringe'")
|
364 |
+
inputs['body_part'] = st.text_input("13. Body Part", placeholder="e.g., 'elbow'")
|
365 |
+
inputs['number'] = st.text_input("14. Number", placeholder="e.g., '69'")
|
366 |
+
inputs['song'] = st.text_input("15. Song Title", placeholder="e.g., 'Sweet Caroline'")
|
367 |
+
inputs['verb_present'] = st.text_input("16. Verb (present tense)", placeholder="e.g., 'slay'")
|
368 |
+
inputs['occupation'] = st.text_input("17. Occupation", placeholder="e.g., 'influencer'")
|
369 |
+
inputs['color'] = st.text_input("18. Color", placeholder="e.g., 'teal'")
|
370 |
+
inputs['noun'] = st.text_input("19. Noun", placeholder="e.g., 'chaos'")
|
371 |
+
inputs['sound'] = st.text_input("20. Silly Sound Effect", placeholder="e.g., 'Boop!'")
|
372 |
+
|
373 |
+
if st.button("Generate Sim Story! π"):
|
374 |
+
story = generate_mad_libs_story(st.session_state.username, inputs)
|
375 |
+
st.markdown("### Your Colorado Sim Adventure ποΈ")
|
376 |
+
st.write(story)
|
377 |
+
voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
|
378 |
+
md_file, audio_file = asyncio.run(save_chat_entry(st.session_state.username, story, voice, True))
|
379 |
+
if audio_file:
|
380 |
+
play_and_download_audio(audio_file)
|
381 |
+
|
382 |
+
# Sidebar
|
383 |
+
st.sidebar.subheader("Character Settings")
|
384 |
+
new_username = st.sidebar.selectbox("Switch Character", list(FUN_USERNAMES.keys()), index=list(FUN_USERNAMES.keys()).index(st.session_state.username))
|
385 |
+
if new_username != st.session_state.username:
|
386 |
+
asyncio.run(save_chat_entry("System π", f"{st.session_state.username} switched to {new_username}", "en-US-AriaNeural"))
|
387 |
+
st.session_state.username = new_username
|
388 |
+
st.session_state.tts_voice = FUN_USERNAMES[new_username]
|
389 |
+
save_username(st.session_state.username)
|
390 |
+
st.rerun()
|
391 |
+
|
392 |
+
st.sidebar.subheader("Chat History")
|
393 |
+
chat_content = asyncio.run(load_chat())
|
394 |
+
with st.sidebar.expander("Recent Logs"):
|
395 |
+
st.code("\n".join(f"{i+1}. {line}" for i, line in enumerate(chat_content[-10:])), language="python")
|
396 |
+
|
397 |
+
if not st.session_state.get('server_running', False):
|
398 |
+
st.session_state.server_task = threading.Thread(target=start_websocket_server, daemon=True)
|
399 |
+
st.session_state.server_task.start()
|
400 |
|
401 |
+
if __name__ == "__main__":
|
402 |
+
main()
|
|