awacke1 commited on
Commit
59e84c0
Β·
verified Β·
1 Parent(s): 6af69d9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +450 -0
app.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="🚲BikeAIπŸ† ArXiv Voice Research",
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': "🚲BikeAIπŸ† ArXiv Voice Research"
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
+ stop_words = set([
64
+ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with',
65
+ 'by', 'from', 'up', 'about', 'into', 'over', 'after', 'is', 'are', 'was', 'were',
66
+ 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
67
+ 'should', 'could', 'might', 'must', 'shall', 'can', 'may', 'this', 'that', 'these',
68
+ 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'what', 'which', 'who',
69
+ 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
70
+ 'other', 'some', 'such', 'than', 'too', 'very', 'just', 'there'
71
+ ])
72
+ key_phrases = [
73
+ 'artificial intelligence', 'machine learning', 'deep learning', 'neural network',
74
+ 'personal assistant', 'natural language', 'computer vision', 'data science',
75
+ 'reinforcement learning', 'knowledge graph', 'semantic search', 'time series',
76
+ 'large language model', 'transformer model', 'attention mechanism',
77
+ 'autonomous system', 'edge computing', 'quantum computing', 'blockchain technology',
78
+ 'cognitive science', 'human computer', 'decision making', 'arxiv search',
79
+ 'research paper', 'scientific study', 'empirical analysis'
80
+ ]
81
+
82
+ preserved_phrases = []
83
+ lower_text = text.lower()
84
+ for phrase in key_phrases:
85
+ if phrase in lower_text:
86
+ preserved_phrases.append(phrase)
87
+ text = text.replace(phrase, '')
88
+
89
+ words = re.findall(r'\b\w+(?:-\w+)*\b', text)
90
+ high_info_words = [
91
+ word.lower() for word in words
92
+ if len(word) > 3
93
+ and word.lower() not in stop_words
94
+ and not word.isdigit()
95
+ and any(c.isalpha() for c in word)
96
+ ]
97
+
98
+ all_terms = preserved_phrases + high_info_words
99
+ seen = set()
100
+ unique_terms = []
101
+ for term in all_terms:
102
+ if term not in seen:
103
+ seen.add(term)
104
+ unique_terms.append(term)
105
+
106
+ return unique_terms[:5]
107
+
108
+ def clean_text_for_filename(text: str) -> str:
109
+ text = text.lower()
110
+ text = re.sub(r'[^\w\s-]', '', text)
111
+ words = text.split()
112
+ stop_short = set(['the','and','for','with','this','that','from','just','very','then','been','only','also','about'])
113
+ filtered = [w for w in words if len(w)>3 and w not in stop_short]
114
+ return '_'.join(filtered)[:200]
115
+
116
+ def generate_filename(prompt, response, file_type="md"):
117
+ prefix = datetime.now().strftime("%y%m_%H%M") + "_"
118
+ combined = (prompt + " " + response).strip()
119
+ info_terms = get_high_info_terms(combined)
120
+
121
+ snippet = (prompt[:100] + " " + response[:100]).strip()
122
+ snippet_cleaned = clean_text_for_filename(snippet)
123
+ name_parts = info_terms + [snippet_cleaned]
124
+ full_name = '_'.join(name_parts)
125
+
126
+ if len(full_name) > 150:
127
+ full_name = full_name[:150]
128
+
129
+ filename = f"{prefix}{full_name}.{file_type}"
130
+ return filename
131
+
132
+ def create_file(prompt, response, file_type="md"):
133
+ filename = generate_filename(prompt.strip(), response.strip(), file_type)
134
+ with open(filename, 'w', encoding='utf-8') as f:
135
+ f.write(prompt + "\n\n" + response)
136
+ return filename
137
+
138
+ def get_download_link(file):
139
+ with open(file, "rb") as f:
140
+ b64 = base64.b64encode(f.read()).decode()
141
+ return f'<a href="data:file/zip;base64,{b64}" download="{os.path.basename(file)}">πŸ“‚ Download {os.path.basename(file)}</a>'
142
+
143
+ def clean_for_speech(text: str) -> str:
144
+ text = text.replace("\n", " ")
145
+ text = text.replace("</s>", " ")
146
+ text = text.replace("#", "")
147
+ text = re.sub(r"\(https?:\/\/[^\)]+\)", "", text)
148
+ text = re.sub(r"\s+", " ", text).strip()
149
+ return text
150
+
151
+ async def edge_tts_generate_audio(text, voice="en-US-AriaNeural", rate=0, pitch=0):
152
+ text = clean_for_speech(text)
153
+ if not text.strip():
154
+ return None
155
+ rate_str = f"{rate:+d}%"
156
+ pitch_str = f"{pitch:+d}Hz"
157
+ communicate = edge_tts.Communicate(text, voice, rate=rate_str, pitch=pitch_str)
158
+ out_fn = generate_filename(text, text, "mp3")
159
+ try:
160
+ await communicate.save(out_fn)
161
+ except edge_tts.exceptions.NoAudioReceived:
162
+ st.error("No audio was received from TTS service.")
163
+ return None
164
+ return out_fn
165
+
166
+ def speak_with_edge_tts(text, voice="en-US-AriaNeural", rate=0, pitch=0):
167
+ return asyncio.run(edge_tts_generate_audio(text, voice, rate, pitch))
168
+
169
+ def play_and_download_audio(file_path):
170
+ if file_path and os.path.exists(file_path):
171
+ st.audio(file_path)
172
+ 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>'
173
+ st.markdown(dl_link, unsafe_allow_html=True)
174
+
175
+ def load_files_for_sidebar():
176
+ md_files = glob.glob("*.md")
177
+ mp3_files = glob.glob("*.mp3")
178
+
179
+ md_files = [f for f in md_files if os.path.basename(f).lower() != 'readme.md']
180
+ all_files = md_files + mp3_files
181
+
182
+ groups = defaultdict(list)
183
+ for f in all_files:
184
+ fname = os.path.basename(f)
185
+ prefix = fname[:10]
186
+ groups[prefix].append(f)
187
+
188
+ for prefix in groups:
189
+ groups[prefix].sort(key=lambda x: os.path.getmtime(x), reverse=True)
190
+
191
+ sorted_prefixes = sorted(groups.keys(),
192
+ key=lambda pre: max(os.path.getmtime(x) for x in groups[pre]),
193
+ reverse=True)
194
+ return groups, sorted_prefixes
195
+
196
+ def extract_keywords_from_md(files):
197
+ text = ""
198
+ for f in files:
199
+ if f.endswith(".md"):
200
+ c = open(f,'r',encoding='utf-8').read()
201
+ text += " " + c
202
+ return get_high_info_terms(text)
203
+
204
+ def display_file_manager_sidebar(groups, sorted_prefixes):
205
+ st.sidebar.title("🎡 Audio & Docs Manager")
206
+
207
+ all_md = []
208
+ all_mp3 = []
209
+ for prefix in groups:
210
+ for f in groups[prefix]:
211
+ if f.endswith(".md"):
212
+ all_md.append(f)
213
+ elif f.endswith(".mp3"):
214
+ all_mp3.append(f)
215
+
216
+ top_bar = st.sidebar.columns(3)
217
+ with top_bar[0]:
218
+ if st.button("πŸ—‘ DelAllMD"):
219
+ for f in all_md:
220
+ os.remove(f)
221
+ st.session_state.should_rerun = True
222
+ with top_bar[1]:
223
+ if st.button("πŸ—‘ DelAllMP3"):
224
+ for f in all_mp3:
225
+ os.remove(f)
226
+ st.session_state.should_rerun = True
227
+ with top_bar[2]:
228
+ if st.button("⬇️ ZipAll"):
229
+ z = create_zip_of_files(all_md, all_mp3)
230
+ if z:
231
+ st.sidebar.markdown(get_download_link(z),unsafe_allow_html=True)
232
+
233
+ for prefix in sorted_prefixes:
234
+ files = groups[prefix]
235
+ kw = extract_keywords_from_md(files)
236
+ keywords_str = " ".join(kw) if kw else "No Keywords"
237
+ with st.sidebar.expander(f"{prefix} Files ({len(files)}) - KW: {keywords_str}", expanded=True):
238
+ c1,c2 = st.columns(2)
239
+ with c1:
240
+ if st.button("πŸ‘€ViewGrp", key="view_group_"+prefix):
241
+ st.session_state.viewing_prefix = prefix
242
+ with c2:
243
+ if st.button("πŸ—‘DelGrp", key="del_group_"+prefix):
244
+ for f in files:
245
+ os.remove(f)
246
+ st.success(f"Deleted group {prefix}!")
247
+ st.session_state.should_rerun = True
248
+
249
+ for f in files:
250
+ fname = os.path.basename(f)
251
+ ctime = datetime.fromtimestamp(os.path.getmtime(f)).strftime("%Y-%m-%d %H:%M:%S")
252
+ st.write(f"**{fname}** - {ctime}")
253
+
254
+ def create_zip_of_files(md_files, mp3_files):
255
+ md_files = [f for f in md_files if os.path.basename(f).lower() != 'readme.md']
256
+ all_files = md_files + mp3_files
257
+ if not all_files:
258
+ return None
259
+
260
+ all_content = []
261
+ for f in all_files:
262
+ if f.endswith('.md'):
263
+ with open(f,'r',encoding='utf-8') as file:
264
+ all_content.append(file.read())
265
+ elif f.endswith('.mp3'):
266
+ all_content.append(os.path.basename(f))
267
+
268
+ combined_content = " ".join(all_content)
269
+ info_terms = get_high_info_terms(combined_content)
270
+
271
+ timestamp = datetime.now().strftime("%y%m_%H%M")
272
+ name_text = '_'.join(term.replace(' ', '-') for term in info_terms[:3])
273
+ zip_name = f"{timestamp}_{name_text}.zip"
274
+
275
+ with zipfile.ZipFile(zip_name,'w') as z:
276
+ for f in all_files:
277
+ z.write(f)
278
+
279
+ return zip_name
280
+
281
+ def perform_ai_lookup(q, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False):
282
+ """Perform Arxiv search (via your RAG pattern) and generate audio summaries."""
283
+ start = time.time()
284
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
285
+ # The next lines call your RAG pipeline
286
+ refs = client.predict(q,20,"Semantic Search","mistralai/Mixtral-8x7B-Instruct-v0.1",api_name="/update_with_rag_md")[0]
287
+ r2 = client.predict(q,"mistralai/Mixtral-8x7B-Instruct-v0.1",True,api_name="/ask_llm")
288
+
289
+ result = f"### πŸ”Ž {q}\n\n{r2}\n\n{refs}"
290
+ st.markdown(result)
291
+
292
+ # Audio outputs
293
+ if full_audio:
294
+ complete_text = f"Complete response for query: {q}. {clean_for_speech(r2)} {clean_for_speech(refs)}"
295
+ audio_file_full = speak_with_edge_tts(complete_text)
296
+ if audio_file_full:
297
+ st.write("### πŸ“š Full Audio")
298
+ play_and_download_audio(audio_file_full)
299
+
300
+ if vocal_summary:
301
+ main_text = clean_for_speech(r2)
302
+ if main_text.strip():
303
+ audio_file_main = speak_with_edge_tts(main_text)
304
+ if audio_file_main:
305
+ st.write("### πŸŽ™ Short Audio")
306
+ play_and_download_audio(audio_file_main)
307
+
308
+ if extended_refs:
309
+ summaries_text = "Extended references: " + refs.replace('"','')
310
+ summaries_text = clean_for_speech(summaries_text)
311
+ if summaries_text.strip():
312
+ audio_file_refs = speak_with_edge_tts(summaries_text)
313
+ if audio_file_refs:
314
+ st.write("### πŸ“œ Long Refs")
315
+ play_and_download_audio(audio_file_refs)
316
+
317
+ if titles_summary:
318
+ titles = []
319
+ for line in refs.split('\n'):
320
+ m = re.search(r"\[([^\]]+)\]", line)
321
+ if m:
322
+ titles.append(m.group(1))
323
+ if titles:
324
+ titles_text = "Titles: " + ", ".join(titles)
325
+ titles_text = clean_for_speech(titles_text)
326
+ if titles_text.strip():
327
+ audio_file_titles = speak_with_edge_tts(titles_text)
328
+ if audio_file_titles:
329
+ st.write("### πŸ”– Titles")
330
+ play_and_download_audio(audio_file_titles)
331
+
332
+ elapsed = time.time()-start
333
+ st.write(f"**Total Elapsed:** {elapsed:.2f} s")
334
+
335
+ create_file(q, result, "md")
336
+
337
+ return result
338
+
339
+ def main():
340
+ st.sidebar.markdown("### 🚲BikeAIπŸ† ArXiv Voice Research")
341
+ st.session_state['user_name'] = st.selectbox("Current User:", USER_NAMES, index=0)
342
+
343
+ # Display saved files in sidebar
344
+ groups, sorted_prefixes = load_files_for_sidebar()
345
+ display_file_manager_sidebar(groups, sorted_prefixes)
346
+ if st.session_state.viewing_prefix and st.session_state.viewing_prefix in groups:
347
+ st.write("---")
348
+ st.write(f"**Viewing Group:** {st.session_state.viewing_prefix}")
349
+ for f in groups[st.session_state.viewing_prefix]:
350
+ fname = os.path.basename(f)
351
+ ext = os.path.splitext(fname)[1].lower().strip('.')
352
+ st.write(f"### {fname}")
353
+ if ext == "md":
354
+ content = open(f,'r',encoding='utf-8').read()
355
+ st.markdown(content)
356
+ elif ext == "mp3":
357
+ st.audio(f)
358
+ else:
359
+ st.markdown(get_download_link(f), unsafe_allow_html=True)
360
+ if st.button("❌ Close"):
361
+ st.session_state.viewing_prefix = None
362
+
363
+ if st.button("πŸ—‘οΈ Clear All History in Sidebar"):
364
+ md_files = glob.glob("*.md")
365
+ mp3_files = glob.glob("*.mp3")
366
+ for f in md_files+mp3_files:
367
+ os.remove(f)
368
+ st.success("All history cleared!")
369
+ st.rerun()
370
+
371
+ st.title("πŸŽ™οΈ ArXiv Voice Search")
372
+
373
+ # Voice component
374
+ mycomponent = components.declare_component("mycomponent", path="mycomponent")
375
+ voice_val = mycomponent(my_input_value="Start speaking...")
376
+
377
+ tabs = st.tabs(["🎀 Voice Chat", "πŸ’Ύ History", "βš™οΈ Settings"])
378
+
379
+ with tabs[0]:
380
+ st.subheader("🎀 Voice Chat")
381
+ if voice_val:
382
+ voice_text = voice_val.strip()
383
+ input_changed = (voice_text != st.session_state.get('old_val'))
384
+ if input_changed and voice_text:
385
+ # Save user input
386
+ create_file(st.session_state['user_name'], voice_text, "md")
387
+
388
+ # Perform ArXiv search automatically
389
+ with st.spinner("Searching ArXiv..."):
390
+ # Always do vocal_summary = True, extended_refs=False, titles_summary=True, full_audio=False
391
+ result = perform_ai_lookup(voice_text, vocal_summary=True, extended_refs=False, titles_summary=True, full_audio=False)
392
+
393
+ # Update old_val
394
+ st.session_state['old_val'] = voice_text
395
+ # Clear the text by rerunning
396
+ st.rerun()
397
+
398
+ st.write("Speak a query to run an ArXiv search and hear the results.")
399
+
400
+ with tabs[1]:
401
+ st.subheader("πŸ’Ύ History")
402
+ # Show all MD files and allow reading them aloud
403
+ md_files = sorted(glob.glob("*.md"), key=os.path.getmtime, reverse=True)
404
+ for i, fpath in enumerate(md_files, start=1):
405
+ fname = os.path.basename(fpath)
406
+ with open(fpath,'r',encoding='utf-8') as ff:
407
+ content = ff.read()
408
+ with st.expander(fname, expanded=False):
409
+ st.write(content)
410
+ if st.button(f"πŸ”Š Read Aloud {fname}", key=f"read_{i}_{fname}"):
411
+ voice = USER_VOICES.get(st.session_state['user_name'], "en-US-AriaNeural")
412
+ audio_file = speak_with_edge_tts(content, voice=voice)
413
+ if audio_file:
414
+ play_and_download_audio(audio_file)
415
+
416
+ if st.button("πŸ“œ Read Entire History"):
417
+ all_content = []
418
+ for fpath in sorted(md_files, key=os.path.getmtime):
419
+ with open(fpath,'r',encoding='utf-8') as ff:
420
+ c = ff.read().strip()
421
+ if c:
422
+ all_content.append((fpath, c))
423
+ mp3_files = []
424
+ for (fpath, text) in all_content:
425
+ voice = USER_VOICES.get(st.session_state['user_name'], "en-US-AriaNeural")
426
+ audio_file = speak_with_edge_tts(text, voice=voice)
427
+ if audio_file:
428
+ mp3_files.append(audio_file)
429
+ st.write(f"**{os.path.basename(fpath)}:**")
430
+ play_and_download_audio(audio_file)
431
+
432
+ if mp3_files:
433
+ combined_file = f"full_conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp3"
434
+ with open(combined_file, 'wb') as outfile:
435
+ for f in mp3_files:
436
+ with open(f, 'rb') as infile:
437
+ outfile.write(infile.read())
438
+ st.write("**Full Conversation Audio:**")
439
+ play_and_download_audio(combined_file)
440
+
441
+ with tabs[2]:
442
+ st.subheader("βš™οΈ Settings")
443
+ st.write("Currently no additional settings.")
444
+
445
+ if st.session_state.should_rerun:
446
+ st.session_state.should_rerun = False
447
+ st.rerun()
448
+
449
+ if __name__=="__main__":
450
+ main()