Create backup12.app.py
Browse files- backup12.app.py +463 -0
backup12.app.py
ADDED
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import base64, cv2, glob, json, math, os, pytz, random, re, requests, textract, time, zipfile
|
3 |
+
import plotly.graph_objects as go
|
4 |
+
import streamlit.components.v1 as components
|
5 |
+
from datetime import datetime
|
6 |
+
from audio_recorder_streamlit import audio_recorder
|
7 |
+
from bs4 import BeautifulSoup
|
8 |
+
from collections import defaultdict
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
from gradio_client import Client
|
11 |
+
from huggingface_hub import InferenceClient
|
12 |
+
from io import BytesIO
|
13 |
+
from PIL import Image
|
14 |
+
from PyPDF2 import PdfReader
|
15 |
+
from urllib.parse import quote
|
16 |
+
from xml.etree import ElementTree as ET
|
17 |
+
import extra_streamlit_components as stx
|
18 |
+
from streamlit.runtime.scriptrunner import get_script_run_ctx
|
19 |
+
import asyncio
|
20 |
+
import edge_tts
|
21 |
+
|
22 |
+
# -------------------- Configuration --------------------
|
23 |
+
st.set_page_config(
|
24 |
+
page_title="π²CCCGπ Code Competition Claude vs GPT",
|
25 |
+
page_icon="π²π",
|
26 |
+
layout="wide",
|
27 |
+
initial_sidebar_state="auto",
|
28 |
+
menu_items={
|
29 |
+
'Get Help': 'https://huggingface.co/awacke1',
|
30 |
+
'Report a bug': 'https://huggingface.co/spaces/awacke1',
|
31 |
+
'About': "π²CCCGπ Code Competition Claude vs GPT"
|
32 |
+
}
|
33 |
+
)
|
34 |
+
load_dotenv()
|
35 |
+
|
36 |
+
USER_NAMES = [
|
37 |
+
"Aria", "Guy", "Sonia", "Tony", "Jenny", "Davis", "Libby", "Clara", "Liam", "Natasha", "William"
|
38 |
+
]
|
39 |
+
|
40 |
+
ENGLISH_VOICES = [
|
41 |
+
"en-US-AriaNeural", "en-US-GuyNeural", "en-GB-SoniaNeural", "en-GB-TonyNeural",
|
42 |
+
"en-US-JennyNeural", "en-US-DavisNeural", "en-GB-LibbyNeural", "en-CA-ClaraNeural",
|
43 |
+
"en-CA-LiamNeural", "en-AU-NatashaNeural", "en-AU-WilliamNeural"
|
44 |
+
]
|
45 |
+
|
46 |
+
USER_VOICES = dict(zip(USER_NAMES, ENGLISH_VOICES))
|
47 |
+
|
48 |
+
if 'user_name' not in st.session_state:
|
49 |
+
st.session_state['user_name'] = USER_NAMES[0]
|
50 |
+
if 'old_val' not in st.session_state:
|
51 |
+
st.session_state['old_val'] = None
|
52 |
+
if 'viewing_prefix' not in st.session_state:
|
53 |
+
st.session_state['viewing_prefix'] = None
|
54 |
+
if 'should_rerun' not in st.session_state:
|
55 |
+
st.session_state['should_rerun'] = False
|
56 |
+
|
57 |
+
FILE_EMOJIS = {
|
58 |
+
"md": "π",
|
59 |
+
"mp3": "π΅",
|
60 |
+
}
|
61 |
+
|
62 |
+
def get_high_info_terms(text: str) -> list:
|
63 |
+
# Expanded stop words
|
64 |
+
stop_words = set([
|
65 |
+
'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with',
|
66 |
+
'by', 'from', 'up', 'about', 'into', 'over', 'after', 'is', 'are', 'was', 'were',
|
67 |
+
'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
|
68 |
+
'should', 'could', 'might', 'must', 'shall', 'can', 'may', 'this', 'that', 'these',
|
69 |
+
'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'what', 'which', 'who',
|
70 |
+
'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
|
71 |
+
'other', 'some', 'such', 'than', 'too', 'very', 'just', 'there', 'as', 'if', 'while'
|
72 |
+
])
|
73 |
+
|
74 |
+
# Key phrases tailored to your interests
|
75 |
+
key_phrases = [
|
76 |
+
'artificial intelligence', 'machine learning', 'deep learning', 'neural networks',
|
77 |
+
'natural language processing', 'healthcare systems', 'clinical medicine',
|
78 |
+
'genomics', 'biological systems', 'cognitive science', 'data visualization',
|
79 |
+
'wellness technology', 'robotics', 'medical imaging', 'semantic understanding',
|
80 |
+
'transformers', 'large language models', 'empirical studies', 'scientific research',
|
81 |
+
'quantum mechanics', 'biomedical engineering', 'computational biology'
|
82 |
+
]
|
83 |
+
|
84 |
+
# Preserve key phrases and remove them from the text
|
85 |
+
preserved_phrases = []
|
86 |
+
lower_text = text.lower()
|
87 |
+
for phrase in key_phrases:
|
88 |
+
if phrase in lower_text:
|
89 |
+
preserved_phrases.append(phrase)
|
90 |
+
text = text.replace(phrase, '')
|
91 |
+
break # Stop after the first matching key phrase
|
92 |
+
|
93 |
+
# Extract words and filter high-info terms
|
94 |
+
words = re.findall(r'\b\w+(?:-\w+)*\b', text)
|
95 |
+
high_info_words = [
|
96 |
+
word.lower() for word in words
|
97 |
+
if len(word) > 3
|
98 |
+
and word.lower() not in stop_words
|
99 |
+
and not word.isdigit()
|
100 |
+
and any(c.isalpha() for c in word)
|
101 |
+
]
|
102 |
+
|
103 |
+
# Combine preserved phrases and filtered words, ensuring uniqueness
|
104 |
+
unique_terms = []
|
105 |
+
seen = set()
|
106 |
+
for term in preserved_phrases + high_info_words:
|
107 |
+
if term not in seen:
|
108 |
+
seen.add(term)
|
109 |
+
unique_terms.append(term)
|
110 |
+
|
111 |
+
# Return only the top 5 terms
|
112 |
+
return unique_terms[:5]
|
113 |
+
|
114 |
+
def clean_text_for_filename(text: str) -> str:
|
115 |
+
text = text.lower()
|
116 |
+
text = re.sub(r'[^\w\s-]', '', text)
|
117 |
+
words = text.split()
|
118 |
+
stop_short = set(['the','and','for','with','this','that','from','just','very','then','been','only','also','about'])
|
119 |
+
filtered = [w for w in words if len(w)>3 and w not in stop_short]
|
120 |
+
return '_'.join(filtered)[:200]
|
121 |
+
|
122 |
+
def generate_filename(prompt, response, file_type="md"):
|
123 |
+
# Adjust timezone to Central Time
|
124 |
+
central_tz = pytz.timezone('America/Chicago')
|
125 |
+
central_time = datetime.now(central_tz)
|
126 |
+
|
127 |
+
# Format the prefix to include the required format
|
128 |
+
prefix = central_time.strftime("%m-%d-%y_%I-%M-%p_") # e.g., 12-20-24_11-34-AM_
|
129 |
+
|
130 |
+
combined = (prompt + " " + response).strip()
|
131 |
+
info_terms = get_high_info_terms(combined)
|
132 |
+
|
133 |
+
snippet = (prompt[:100] + " " + response[:100]).strip()
|
134 |
+
snippet_cleaned = clean_text_for_filename(snippet)
|
135 |
+
name_parts = info_terms + [snippet_cleaned]
|
136 |
+
full_name = '_'.join(name_parts)
|
137 |
+
|
138 |
+
if len(full_name) > 150:
|
139 |
+
full_name = full_name[:150]
|
140 |
+
|
141 |
+
filename = f"{prefix}{full_name}.{file_type}"
|
142 |
+
return filename
|
143 |
+
|
144 |
+
def create_file(prompt, response, file_type="md"):
|
145 |
+
filename = generate_filename(prompt.strip(), response.strip(), file_type)
|
146 |
+
with open(filename, 'w', encoding='utf-8') as f:
|
147 |
+
f.write(prompt + "\n\n" + response)
|
148 |
+
return filename
|
149 |
+
|
150 |
+
def get_download_link(file):
|
151 |
+
with open(file, "rb") as f:
|
152 |
+
b64 = base64.b64encode(f.read()).decode()
|
153 |
+
return f'<a href="data:file/zip;base64,{b64}" download="{os.path.basename(file)}">π Download {os.path.basename(file)}</a>'
|
154 |
+
|
155 |
+
def clean_for_speech(text: str) -> str:
|
156 |
+
text = text.replace("\n", " ")
|
157 |
+
text = text.replace("</s>", " ")
|
158 |
+
text = text.replace("#", "")
|
159 |
+
text = re.sub(r"\(https?:\/\/[^\)]+\)", "", text)
|
160 |
+
text = re.sub(r"\s+", " ", text).strip()
|
161 |
+
return text
|
162 |
+
|
163 |
+
async def edge_tts_generate_audio(text, voice="en-US-AriaNeural", rate=0, pitch=0):
|
164 |
+
text = clean_for_speech(text)
|
165 |
+
if not text.strip():
|
166 |
+
return None
|
167 |
+
rate_str = f"{rate:+d}%"
|
168 |
+
pitch_str = f"{pitch:+d}Hz"
|
169 |
+
communicate = edge_tts.Communicate(text, voice, rate=rate_str, pitch=pitch_str)
|
170 |
+
out_fn = generate_filename(text, text, "mp3")
|
171 |
+
try:
|
172 |
+
await communicate.save(out_fn)
|
173 |
+
except edge_tts.exceptions.NoAudioReceived:
|
174 |
+
st.error("No audio was received from TTS service.")
|
175 |
+
return None
|
176 |
+
return out_fn
|
177 |
+
|
178 |
+
def speak_with_edge_tts(text, voice="en-US-AriaNeural", rate=0, pitch=0):
|
179 |
+
return asyncio.run(edge_tts_generate_audio(text, voice, rate, pitch))
|
180 |
+
|
181 |
+
def play_and_download_audio(file_path):
|
182 |
+
if file_path and os.path.exists(file_path):
|
183 |
+
st.audio(file_path)
|
184 |
+
dl_link = f'<a href="data:audio/mpeg;base64,{base64.b64encode(open(file_path,"rb").read()).decode()}" download="{os.path.basename(file_path)}">Download {os.path.basename(file_path)}</a>'
|
185 |
+
st.markdown(dl_link, unsafe_allow_html=True)
|
186 |
+
|
187 |
+
def load_files_for_sidebar():
|
188 |
+
md_files = glob.glob("*.md")
|
189 |
+
mp3_files = glob.glob("*.mp3")
|
190 |
+
|
191 |
+
md_files = [f for f in md_files if os.path.basename(f).lower() != 'readme.md']
|
192 |
+
all_files = md_files + mp3_files
|
193 |
+
|
194 |
+
groups = defaultdict(list)
|
195 |
+
for f in all_files:
|
196 |
+
fname = os.path.basename(f)
|
197 |
+
prefix = fname[:17]
|
198 |
+
groups[prefix].append(f)
|
199 |
+
|
200 |
+
for prefix in groups:
|
201 |
+
groups[prefix].sort(key=lambda x: os.path.getmtime(x), reverse=True)
|
202 |
+
|
203 |
+
sorted_prefixes = sorted(groups.keys(),
|
204 |
+
key=lambda pre: max(os.path.getmtime(x) for x in groups[pre]),
|
205 |
+
reverse=True)
|
206 |
+
return groups, sorted_prefixes
|
207 |
+
|
208 |
+
def extract_keywords_from_md(files):
|
209 |
+
text = ""
|
210 |
+
for f in files:
|
211 |
+
if f.endswith(".md"):
|
212 |
+
c = open(f,'r',encoding='utf-8').read()
|
213 |
+
text += " " + c
|
214 |
+
return get_high_info_terms(text)
|
215 |
+
|
216 |
+
def display_file_manager_sidebar(groups, sorted_prefixes):
|
217 |
+
st.sidebar.title("π΅ Audio & Docs Manager")
|
218 |
+
|
219 |
+
all_md = []
|
220 |
+
all_mp3 = []
|
221 |
+
for prefix in groups:
|
222 |
+
for f in groups[prefix]:
|
223 |
+
if f.endswith(".md"):
|
224 |
+
all_md.append(f)
|
225 |
+
elif f.endswith(".mp3"):
|
226 |
+
all_mp3.append(f)
|
227 |
+
|
228 |
+
top_bar = st.sidebar.columns(3)
|
229 |
+
with top_bar[0]:
|
230 |
+
if st.button("π DelAllMD"):
|
231 |
+
for f in all_md:
|
232 |
+
os.remove(f)
|
233 |
+
st.session_state.should_rerun = True
|
234 |
+
with top_bar[1]:
|
235 |
+
if st.button("π DelAllMP3"):
|
236 |
+
for f in all_mp3:
|
237 |
+
os.remove(f)
|
238 |
+
st.session_state.should_rerun = True
|
239 |
+
with top_bar[2]:
|
240 |
+
if st.button("β¬οΈ ZipAll"):
|
241 |
+
z = create_zip_of_files(all_md, all_mp3)
|
242 |
+
if z:
|
243 |
+
st.sidebar.markdown(get_download_link(z),unsafe_allow_html=True)
|
244 |
+
|
245 |
+
for prefix in sorted_prefixes:
|
246 |
+
files = groups[prefix]
|
247 |
+
kw = extract_keywords_from_md(files)
|
248 |
+
keywords_str = " ".join(kw) if kw else "No Keywords"
|
249 |
+
with st.sidebar.expander(f"{prefix} Files ({len(files)}) - KW: {keywords_str}", expanded=True):
|
250 |
+
c1,c2 = st.columns(2)
|
251 |
+
with c1:
|
252 |
+
if st.button("πViewGrp", key="view_group_"+prefix):
|
253 |
+
st.session_state.viewing_prefix = prefix
|
254 |
+
with c2:
|
255 |
+
if st.button("πDelGrp", key="del_group_"+prefix):
|
256 |
+
for f in files:
|
257 |
+
os.remove(f)
|
258 |
+
st.success(f"Deleted group {prefix}!")
|
259 |
+
st.session_state.should_rerun = True
|
260 |
+
|
261 |
+
for f in files:
|
262 |
+
fname = os.path.basename(f)
|
263 |
+
ctime = datetime.fromtimestamp(os.path.getmtime(f)).strftime("%Y-%m-%d %H:%M:%S")
|
264 |
+
st.write(f"**{fname}** - {ctime}")
|
265 |
+
|
266 |
+
def create_zip_of_files(md_files, mp3_files):
|
267 |
+
md_files = [f for f in md_files if os.path.basename(f).lower() != 'readme.md']
|
268 |
+
all_files = md_files + mp3_files
|
269 |
+
if not all_files:
|
270 |
+
return None
|
271 |
+
|
272 |
+
all_content = []
|
273 |
+
for f in all_files:
|
274 |
+
if f.endswith('.md'):
|
275 |
+
with open(f,'r',encoding='utf-8') as file:
|
276 |
+
all_content.append(file.read())
|
277 |
+
elif f.endswith('.mp3'):
|
278 |
+
all_content.append(os.path.basename(f))
|
279 |
+
|
280 |
+
combined_content = " ".join(all_content)
|
281 |
+
info_terms = get_high_info_terms(combined_content)
|
282 |
+
|
283 |
+
timestamp = datetime.now().strftime("%y%m_%H%M")
|
284 |
+
name_text = '_'.join(term.replace(' ', '-') for term in info_terms[:3])
|
285 |
+
zip_name = f"{timestamp}_{name_text}.zip"
|
286 |
+
|
287 |
+
with zipfile.ZipFile(zip_name,'w') as z:
|
288 |
+
for f in all_files:
|
289 |
+
z.write(f)
|
290 |
+
|
291 |
+
return zip_name
|
292 |
+
|
293 |
+
def perform_ai_lookup(q, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False):
|
294 |
+
"""Perform Arxiv search (via your RAG pattern) and generate audio summaries."""
|
295 |
+
start = time.time()
|
296 |
+
client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
297 |
+
# The next lines call your RAG pipeline
|
298 |
+
refs = client.predict(q,20,"Semantic Search","mistralai/Mixtral-8x7B-Instruct-v0.1",api_name="/update_with_rag_md")[0]
|
299 |
+
r2 = client.predict(q,"mistralai/Mixtral-8x7B-Instruct-v0.1",True,api_name="/ask_llm")
|
300 |
+
|
301 |
+
result = f"### π {q}\n\n{r2}\n\n{refs}"
|
302 |
+
|
303 |
+
# Audio outputs
|
304 |
+
if full_audio:
|
305 |
+
complete_text = f"Complete response for query: {q}. {clean_for_speech(r2)} {clean_for_speech(refs)}"
|
306 |
+
audio_file_full = speak_with_edge_tts(complete_text)
|
307 |
+
if audio_file_full:
|
308 |
+
st.write("### π Full Audio")
|
309 |
+
play_and_download_audio(audio_file_full)
|
310 |
+
|
311 |
+
if vocal_summary:
|
312 |
+
main_text = clean_for_speech(r2)
|
313 |
+
if main_text.strip():
|
314 |
+
audio_file_main = speak_with_edge_tts(main_text)
|
315 |
+
if audio_file_main:
|
316 |
+
st.write("### π Short Audio")
|
317 |
+
play_and_download_audio(audio_file_main)
|
318 |
+
|
319 |
+
if extended_refs:
|
320 |
+
summaries_text = "Extended references: " + refs.replace('"','')
|
321 |
+
summaries_text = clean_for_speech(summaries_text)
|
322 |
+
if summaries_text.strip():
|
323 |
+
audio_file_refs = speak_with_edge_tts(summaries_text)
|
324 |
+
if audio_file_refs:
|
325 |
+
st.write("### π Long Refs")
|
326 |
+
play_and_download_audio(audio_file_refs)
|
327 |
+
|
328 |
+
if titles_summary:
|
329 |
+
titles = []
|
330 |
+
for line in refs.split('\n'):
|
331 |
+
m = re.search(r"\[([^\]]+)\]", line)
|
332 |
+
if m:
|
333 |
+
titles.append(m.group(1))
|
334 |
+
if titles:
|
335 |
+
titles_text = "Titles: " + ", ".join(titles)
|
336 |
+
titles_text = clean_for_speech(titles_text)
|
337 |
+
if titles_text.strip():
|
338 |
+
audio_file_titles = speak_with_edge_tts(titles_text)
|
339 |
+
if audio_file_titles:
|
340 |
+
st.write("### π Titles")
|
341 |
+
play_and_download_audio(audio_file_titles)
|
342 |
+
|
343 |
+
# show text last after playback interfaces. For the big one lets add a feature later that breaks into their own.
|
344 |
+
st.markdown(result)
|
345 |
+
|
346 |
+
elapsed = time.time()-start
|
347 |
+
st.write(f"**Total Elapsed:** {elapsed:.2f} s")
|
348 |
+
|
349 |
+
create_file(q, result, "md")
|
350 |
+
|
351 |
+
return result
|
352 |
+
|
353 |
+
def main():
|
354 |
+
st.session_state['user_name'] = st.selectbox("Current User:", USER_NAMES, index=0)
|
355 |
+
|
356 |
+
# Display saved files in sidebar
|
357 |
+
groups, sorted_prefixes = load_files_for_sidebar()
|
358 |
+
display_file_manager_sidebar(groups, sorted_prefixes)
|
359 |
+
if st.session_state.viewing_prefix and st.session_state.viewing_prefix in groups:
|
360 |
+
st.write("---")
|
361 |
+
st.write(f"**Viewing Group:** {st.session_state.viewing_prefix}")
|
362 |
+
for f in groups[st.session_state.viewing_prefix]:
|
363 |
+
fname = os.path.basename(f)
|
364 |
+
ext = os.path.splitext(fname)[1].lower().strip('.')
|
365 |
+
st.write(f"### {fname}")
|
366 |
+
if ext == "md":
|
367 |
+
content = open(f,'r',encoding='utf-8').read()
|
368 |
+
st.markdown(content)
|
369 |
+
elif ext == "mp3":
|
370 |
+
st.audio(f)
|
371 |
+
else:
|
372 |
+
st.markdown(get_download_link(f), unsafe_allow_html=True)
|
373 |
+
if st.button("β Close"):
|
374 |
+
st.session_state.viewing_prefix = None
|
375 |
+
|
376 |
+
if st.button("ποΈ Clear All History in Sidebar"):
|
377 |
+
md_files = glob.glob("*.md")
|
378 |
+
mp3_files = glob.glob("*.mp3")
|
379 |
+
for f in md_files+mp3_files:
|
380 |
+
os.remove(f)
|
381 |
+
st.success("All history cleared!")
|
382 |
+
st.rerun()
|
383 |
+
|
384 |
+
st.title("ποΈ ArXiv Voice Search")
|
385 |
+
|
386 |
+
# Voice component
|
387 |
+
mycomponent = components.declare_component("mycomponent", path="mycomponent")
|
388 |
+
voice_val = mycomponent(my_input_value="Start speaking...")
|
389 |
+
|
390 |
+
tabs = st.tabs(["π€ Voice Chat", "πΎ History", "βοΈ Settings"])
|
391 |
+
|
392 |
+
with tabs[0]:
|
393 |
+
st.subheader("π€ Voice Chat")
|
394 |
+
if voice_val:
|
395 |
+
voice_text = voice_val.strip()
|
396 |
+
input_changed = (voice_text != st.session_state.get('old_val'))
|
397 |
+
if input_changed and voice_text:
|
398 |
+
# Save user input
|
399 |
+
create_file(st.session_state['user_name'], voice_text, "md")
|
400 |
+
|
401 |
+
# Perform ArXiv search automatically
|
402 |
+
with st.spinner("Searching ArXiv..."):
|
403 |
+
# Always do vocal_summary = True, extended_refs=False, titles_summary=True, full_audio=False
|
404 |
+
result = perform_ai_lookup(voice_text, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False)
|
405 |
+
|
406 |
+
# Update old_val
|
407 |
+
st.session_state['old_val'] = voice_text
|
408 |
+
# Clear the text by rerunning
|
409 |
+
#st.rerun()
|
410 |
+
|
411 |
+
st.write("Speak a query to run an ArXiv search and hear the results.")
|
412 |
+
|
413 |
+
with tabs[1]:
|
414 |
+
st.subheader("πΎ History")
|
415 |
+
# Show all MD files and allow reading them aloud
|
416 |
+
md_files = sorted(glob.glob("*.md"), key=os.path.getmtime, reverse=True)
|
417 |
+
for i, fpath in enumerate(md_files, start=1):
|
418 |
+
fname = os.path.basename(fpath)
|
419 |
+
with open(fpath,'r',encoding='utf-8') as ff:
|
420 |
+
content = ff.read()
|
421 |
+
with st.expander(fname, expanded=False):
|
422 |
+
st.write(content)
|
423 |
+
if st.button(f"π Read Aloud {fname}", key=f"read_{i}_{fname}"):
|
424 |
+
voice = USER_VOICES.get(st.session_state['user_name'], "en-US-AriaNeural")
|
425 |
+
audio_file = speak_with_edge_tts(content, voice=voice)
|
426 |
+
if audio_file:
|
427 |
+
play_and_download_audio(audio_file)
|
428 |
+
|
429 |
+
if st.button("π Read Entire History"):
|
430 |
+
all_content = []
|
431 |
+
for fpath in sorted(md_files, key=os.path.getmtime):
|
432 |
+
with open(fpath,'r',encoding='utf-8') as ff:
|
433 |
+
c = ff.read().strip()
|
434 |
+
if c:
|
435 |
+
all_content.append((fpath, c))
|
436 |
+
mp3_files = []
|
437 |
+
for (fpath, text) in all_content:
|
438 |
+
voice = USER_VOICES.get(st.session_state['user_name'], "en-US-AriaNeural")
|
439 |
+
audio_file = speak_with_edge_tts(text, voice=voice)
|
440 |
+
if audio_file:
|
441 |
+
mp3_files.append(audio_file)
|
442 |
+
st.write(f"**{os.path.basename(fpath)}:**")
|
443 |
+
play_and_download_audio(audio_file)
|
444 |
+
|
445 |
+
if mp3_files:
|
446 |
+
combined_file = f"full_conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp3"
|
447 |
+
with open(combined_file, 'wb') as outfile:
|
448 |
+
for f in mp3_files:
|
449 |
+
with open(f, 'rb') as infile:
|
450 |
+
outfile.write(infile.read())
|
451 |
+
st.write("**Full Conversation Audio:**")
|
452 |
+
play_and_download_audio(combined_file)
|
453 |
+
|
454 |
+
with tabs[2]:
|
455 |
+
st.subheader("βοΈ Settings")
|
456 |
+
st.write("Currently no additional settings.")
|
457 |
+
|
458 |
+
if st.session_state.should_rerun:
|
459 |
+
st.session_state.should_rerun = False
|
460 |
+
st.rerun()
|
461 |
+
|
462 |
+
if __name__=="__main__":
|
463 |
+
main()
|