awacke1 commited on
Commit
8092a9c
·
verified ·
1 Parent(s): 40ec6ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +905 -328
app.py CHANGED
@@ -1,18 +1,30 @@
1
  import streamlit as st
2
- import anthropic, openai, base64, cv2, glob, json, math, os, pytz, random, re, requests, time, zipfile
 
 
3
  from datetime import datetime
4
  from audio_recorder_streamlit import audio_recorder
 
5
  from collections import defaultdict, deque, Counter
6
  from dotenv import load_dotenv
7
  from gradio_client import Client
8
  from huggingface_hub import InferenceClient
 
9
  from PIL import Image
 
 
 
10
  from openai import OpenAI
11
- from streamlit_marquee import streamlit_marquee
 
12
  import asyncio
13
  import edge_tts
14
 
15
- # Core Configuration
 
 
 
 
16
  st.set_page_config(
17
  page_title="🚲TalkingAIResearcher🏆",
18
  page_icon="🚲🏆",
@@ -24,17 +36,9 @@ st.set_page_config(
24
  'About': "🚲TalkingAIResearcher🏆"
25
  }
26
  )
 
27
 
28
- # Custom CSS
29
- st.markdown("""
30
- <style>
31
- .main { background: linear-gradient(to right, #1a1a1a, #2d2d2d); color: #fff; }
32
- .stMarkdown { font-family: 'Helvetica Neue', sans-serif; }
33
- .stButton>button { margin-right: 0.5rem; }
34
- </style>
35
- """, unsafe_allow_html=True)
36
-
37
- # Constants
38
  EDGE_TTS_VOICES = [
39
  "en-US-AriaNeural", # Default voice
40
  "en-US-GuyNeural",
@@ -47,403 +51,976 @@ EDGE_TTS_VOICES = [
47
  "en-CA-LiamNeural"
48
  ]
49
 
50
- FILE_EMOJIS = {
51
- "md": "📝",
52
- "mp3": "🎵",
53
- "wav": "🔊",
54
- "txt": "📄",
55
- "pdf": "📑",
56
- "html": "🌐"
57
- }
58
 
59
- # Load environment variables
60
- load_dotenv()
61
-
62
- # API Setup
63
  openai_api_key = os.getenv('OPENAI_API_KEY', "")
64
- anthropic_key = os.getenv('ANTHROPIC_API_KEY', "")
 
65
  if 'OPENAI_API_KEY' in st.secrets:
66
  openai_api_key = st.secrets['OPENAI_API_KEY']
67
  if 'ANTHROPIC_API_KEY' in st.secrets:
68
  anthropic_key = st.secrets["ANTHROPIC_API_KEY"]
69
 
70
- openai_client = OpenAI(api_key=openai_api_key)
71
  claude_client = anthropic.Anthropic(api_key=anthropic_key)
 
 
 
72
 
73
- # Initialize Session State
74
- state_vars = {
75
- 'tts_voice': EDGE_TTS_VOICES[0],
76
- 'audio_format': 'mp3',
77
- 'messages': [],
78
- 'chat_history': [],
79
- 'transcript_history': [],
80
- 'viewing_prefix': None,
81
- 'should_rerun': False,
82
- 'editing_mode': False,
83
- 'current_file': None,
84
- 'file_content': None,
85
- 'old_val': None,
86
- 'last_query': ''
87
- }
 
 
 
 
 
 
 
 
 
 
88
 
89
- for key, default in state_vars.items():
90
- if key not in st.session_state:
91
- st.session_state[key] = default
 
 
 
 
 
 
 
92
 
93
- # Core Functions
94
- @st.cache_resource
95
- def get_cached_audio_b64(file_path):
96
- with open(file_path, "rb") as f:
97
- return base64.b64encode(f.read()).decode()
98
 
99
- def beautify_filename(filename):
100
- name = os.path.splitext(filename)[0]
101
- return name.replace('_', ' ').replace('.', ' ')
 
 
 
 
 
 
 
 
 
102
 
103
- def display_marquee_controls():
104
- st.sidebar.markdown("### 🎯 Marquee Settings")
105
- cols = st.sidebar.columns(2)
106
- with cols[0]:
107
- bg_color = st.color_picker("🎨 Background", "#1E1E1E")
108
- text_color = st.color_picker("✍️ Text", "#FFFFFF")
109
- with cols[1]:
110
- font_size = st.slider("📏 Size", 10, 24, 14)
111
- duration = st.slider("⏱️ Speed", 1, 20, 10)
112
-
113
- return {
114
- "background": bg_color,
115
- "color": text_color,
116
- "font-size": f"{font_size}px",
117
- "animationDuration": f"{duration}s",
118
- "width": "100%",
119
- "lineHeight": "35px"
120
- }
121
 
122
- def get_high_info_terms(text: str, top_n=10) -> list:
123
- stop_words = set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for'])
124
  words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
125
  bi_grams = [' '.join(pair) for pair in zip(words, words[1:])]
126
  combined = words + bi_grams
127
- filtered = [term for term in combined if term not in stop_words and len(term) > 3]
128
- return Counter(filtered).most_common(top_n)
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def generate_filename(prompt, response, file_type="md"):
 
 
 
 
131
  prefix = datetime.now().strftime("%y%m_%H%M") + "_"
132
  combined = (prompt + " " + response).strip()
133
- name_parts = [term for term, _ in get_high_info_terms(combined, top_n=5)]
134
- filename = prefix + "_".join(name_parts)[:150] + "." + file_type
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  return filename
136
 
137
  def create_file(prompt, response, file_type="md"):
 
138
  filename = generate_filename(prompt.strip(), response.strip(), file_type)
139
  with open(filename, 'w', encoding='utf-8') as f:
140
- f.write(f"{prompt}\n\n{response}")
141
  return filename
142
 
143
- def get_download_link(file_path, file_type="zip"):
144
- with open(file_path, "rb") as f:
 
145
  b64 = base64.b64encode(f.read()).decode()
146
- ext_map = {'zip': '📦', 'mp3': '🎵', 'wav': '🔊', 'md': '📝'}
147
- emoji = ext_map.get(file_type, '')
148
- return f'<a href="data:application/{file_type};base64,{b64}" download="{os.path.basename(file_path)}">{emoji} Download {os.path.basename(file_path)}</a>'
149
-
150
- # Audio Processing
151
- def clean_speech_text(text):
152
- text = re.sub(r'\s+', ' ', text.strip())
153
- text = text.replace("</s>", "").replace("#", "")
 
 
 
 
 
 
 
 
 
154
  text = re.sub(r"\(https?:\/\/[^\)]+\)", "", text)
 
155
  return text
156
 
157
- async def edge_tts_generate(text, voice="en-US-AriaNeural", rate=0, pitch=0, file_format="mp3"):
158
- text = clean_speech_text(text)
159
- if not text: return None
160
- communicate = edge_tts.Communicate(text, voice, rate=f"{rate}%", pitch=f"{pitch}Hz")
161
- filename = f"{datetime.now().strftime('%y%m_%H%M')}_{voice}.{file_format}"
162
- await communicate.save(filename)
163
- return filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
- def speak_text(text, voice=None, file_format=None):
166
- if not text: return None
167
- voice = voice or st.session_state['tts_voice']
168
- fmt = file_format or st.session_state['audio_format']
169
- return asyncio.run(edge_tts_generate(text, voice, file_format=fmt))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  def process_audio_file(audio_path):
 
172
  with open(audio_path, "rb") as f:
173
- transcript = openai_client.audio.transcriptions.create(model="whisper-1", file=f)
174
- text = transcript.text
175
- st.session_state.messages.append({"role": "user", "content": text})
176
- return text
177
 
178
- # File Management
179
- def load_files_for_sidebar():
180
- files = []
181
- for f in glob.glob("*.*"):
182
- basename = os.path.basename(f)
183
- if f.endswith('.md'):
184
- if len(basename) >= 9 and re.match(r'\d{4}_\d{4}', basename[:9]):
185
- files.append(f)
186
- else:
187
- files.append(f)
188
-
189
- groups = defaultdict(list)
190
- for f in files:
191
- basename = os.path.basename(f)
192
- group_name = basename[:9] if len(basename) >= 9 else 'Other'
193
- groups[group_name].append(f)
194
-
195
- return sorted(groups.items(),
196
- key=lambda x: max(os.path.getmtime(f) for f in x[1]),
197
- reverse=True)
198
 
199
- def display_file_manager_sidebar(groups_sorted):
200
- st.sidebar.title("📚 File Manager")
201
- all_files = {'md': [], 'mp3': [], 'wav': []}
202
-
203
- for _, files in groups_sorted:
204
- for f in files:
205
- ext = os.path.splitext(f)[1].lower().strip('.')
206
- if ext in all_files:
207
- all_files[ext].append(f)
208
-
209
- cols = st.sidebar.columns(4)
210
- for i, (ext, files) in enumerate(all_files.items()):
211
- with cols[i]:
212
- if st.button(f"🗑️ {ext.upper()}"):
213
- [os.remove(f) for f in files]
214
- st.session_state.should_rerun = True
215
 
216
- if st.sidebar.button("📦 Zip All"):
217
- zip_name = create_zip_of_files(all_files['md'], all_files['mp3'], all_files['wav'])
218
- if zip_name:
219
- st.sidebar.markdown(get_download_link(zip_name), unsafe_allow_html=True)
220
 
221
- for group_name, files in groups_sorted:
222
- try:
223
- timestamp = datetime.strptime(group_name, "%y%m_%H%M").strftime("%Y-%m-%d %H:%M") if len(group_name) == 9 and group_name != 'Other' else group_name
224
- except ValueError:
225
- timestamp = group_name
226
 
227
- with st.sidebar.expander(f"📁 {timestamp} ({len(files)})", expanded=True):
228
- c1, c2 = st.columns(2)
229
- with c1:
230
- if st.button("👀", key=f"view_{group_name}"):
231
- st.session_state.viewing_prefix = group_name
232
- with c2:
233
- if st.button("🗑️", key=f"del_{group_name}"):
234
- [os.remove(f) for f in files]
235
- st.session_state.should_rerun = True
236
 
237
- for f in files:
238
- ext = os.path.splitext(f)[1].lower().strip('.')
239
- emoji = FILE_EMOJIS.get(ext, '📄')
240
- pretty_name = beautify_filename(os.path.basename(f))
241
- st.write(f"{emoji} **{pretty_name}**")
242
-
243
- if ext in ['mp3', 'wav']:
244
- st.audio(f)
245
- if st.button("🔄", key=f"loop_{f}"):
246
- audio_b64 = get_cached_audio_b64(f)
247
- st.components.v1.html(
248
- f'''<audio id="player_{f}" loop>
249
- <source src="data:audio/{ext};base64,{audio_b64}">
250
- </audio>
251
- <script>
252
- document.getElementById("player_{f}").play();
253
- </script>''',
254
- height=0
255
- )
256
-
257
- # ArXiv Integration
258
- def perform_arxiv_search(query):
259
- client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
260
- papers = client.predict(
261
- query, 20, "Semantic Search",
262
- "mistralai/Mixtral-8x7B-Instruct-v0.1",
263
- api_name="/update_with_rag_md"
264
- )[0]
265
 
266
- summary = client.predict(
267
- query,
268
- "mistralai/Mixtral-8x7B-Instruct-v0.1",
269
- True,
270
- api_name="/ask_llm"
271
- )
272
-
273
- result = f"### 🔎 {query}\n\n{summary}\n\n{papers}"
274
- st.markdown(result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
 
276
- papers_data = parse_arxiv_refs(papers)
277
- if papers_data:
278
- create_paper_audio(papers_data, query)
279
- display_papers(papers_data)
280
 
281
- create_file(query, result, "md")
282
- return result
283
 
284
- def parse_arxiv_refs(text):
285
- papers = []
286
- current = None
287
-
288
- for line in text.split('\n'):
289
- if '|' in line:
290
- if current: papers.append(current)
291
- parts = line.strip('* ').split('|')
292
- current = {
293
- 'date': parts[0].strip(),
294
- 'title': parts[1].strip(),
295
- 'authors': '',
296
- 'summary': '',
297
- 'id': re.search(r'(\d{4}\.\d{5})', line).group(1) if re.search(r'(\d{4}\.\d{5})', line) else ''
298
- }
299
- elif current:
300
- if not current['authors']:
301
- current['authors'] = line.strip('* ')
302
- else:
303
- current['summary'] += ' ' + line.strip()
304
-
305
- if current: papers.append(current)
306
- return papers[:20]
307
 
308
- def create_paper_audio(papers, query):
309
- combined = []
310
  for paper in papers:
311
  try:
312
- text = f"{paper['title']} by {paper['authors']}. {paper['summary']}"
 
 
 
313
  file_format = st.session_state['audio_format']
314
- audio_file = speak_text(text, file_format=file_format)
315
- paper['audio'] = audio_file
316
- st.write(f"### {FILE_EMOJIS.get(file_format, '')} {os.path.basename(audio_file)}")
317
- st.audio(audio_file)
318
- combined.append(paper['title'])
 
 
 
 
319
  except Exception as e:
320
- st.warning(f"Error generating audio for {paper['title']}: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
 
322
- if combined:
323
- summary = f"Found papers about: {'; '.join(combined)}. Query was: {query}"
324
- summary_audio = speak_text(summary)
325
- if summary_audio:
326
- st.write("### 📢 Summary")
327
- st.audio(summary_audio)
328
 
329
  def display_papers(papers):
 
330
  st.write("## Research Papers")
331
- for i, paper in enumerate(papers[:20], 1):
332
- with st.expander(f"{i}. 📄 {paper['title']}", expanded=True):
333
- st.markdown(f"**{paper['date']} | {paper['title']} | ⬇️**")
334
- st.markdown(f"*{paper['authors']}*")
335
- st.markdown(paper[previous code] ... st.markdown(paper['summary'])
336
- if paper.get('audio'):
337
- st.write("📚 Paper Audio")
338
- st.audio(paper['audio'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
  def process_with_gpt(text):
341
- if not text: return
342
- st.session_state.messages.append({"role": "user", "content": text})
343
- with st.chat_message("user"):
 
 
344
  st.markdown(text)
345
  with st.chat_message("assistant"):
346
- response = openai_client.chat.completions.create(
347
- model="gpt-4-turbo-preview",
348
  messages=st.session_state.messages,
349
  stream=False
350
  )
351
- answer = response.choices[0].message.content
352
- st.write(f"GPT-4: {answer}")
353
- create_file(text, answer, "md")
354
- st.session_state.messages.append({"role": "assistant", "content": answer})
355
- return answer
356
 
357
  def process_with_claude(text):
358
- if not text: return
 
 
359
  with st.chat_message("user"):
360
  st.markdown(text)
361
  with st.chat_message("assistant"):
362
- response = claude_client.messages.create(
363
  model="claude-3-sonnet-20240229",
364
- max_tokens=4000,
365
- messages=[{"role": "user", "content": text}]
366
  )
367
- answer = response.content[0].text
368
- st.write(f"Claude-3: {answer}")
369
- create_file(text, answer, "md")
370
- st.session_state.chat_history.append({"user": text, "claude": answer})
371
- return answer
372
 
373
- # Main App
374
- def main():
375
- st.sidebar.title("🚲 Research Assistant")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
 
377
- # Voice settings
378
- st.sidebar.markdown("### 🎤 Voice Config")
379
- voice = st.sidebar.selectbox("Voice:", EDGE_TTS_VOICES,
380
- index=EDGE_TTS_VOICES.index(st.session_state['tts_voice']))
381
- fmt = st.sidebar.radio("Format:", ["MP3", "WAV"], index=0)
382
 
383
- if voice != st.session_state['tts_voice']:
384
- st.session_state['tts_voice'] = voice
385
- st.rerun()
386
- if fmt.lower() != st.session_state['audio_format']:
387
- st.session_state['audio_format'] = fmt.lower()
388
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
 
390
- mode = st.radio("Mode:", ["🎤 Voice", "🔍 ArXiv", "📝 Editor"], horizontal=True)
 
 
 
 
 
 
391
 
392
- if mode == "🔍 ArXiv":
393
- query = st.text_input("🔍 Search:")
394
- if query:
395
- perform_arxiv_search(query)
396
 
397
- elif mode == "🎤 Voice":
398
- text = st.text_area("Message:", height=100).strip()
399
- if st.button("Send"):
400
- process_with_gpt(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
 
402
- st.subheader("History")
403
- tab1, tab2 = st.tabs(["Claude", "GPT-4"])
404
- with tab1:
405
- for msg in st.session_state.chat_history:
406
- st.write("You:", msg["user"])
407
- st.write("Claude:", msg["claude"])
408
- with tab2:
409
- for msg in st.session_state.messages:
410
- with st.chat_message(msg["role"]):
411
- st.markdown(msg["content"])
412
 
413
- elif mode == "📝 Editor":
414
- if st.session_state.current_file:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
  st.subheader(f"Editing: {st.session_state.current_file}")
416
- new_content = st.text_area("Content:", st.session_state.file_content, height=300)
417
- if st.button("Save"):
418
- with open(st.session_state.current_file, 'w') as f:
419
- f.write(new_content)
420
- st.success("Saved!")
421
  st.session_state.should_rerun = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
 
423
- # File management
424
- groups = load_files_for_sidebar()
425
- display_file_manager_sidebar(groups)
426
 
427
  if st.session_state.should_rerun:
428
  st.session_state.should_rerun = False
429
  st.rerun()
430
 
431
- sidebar_md = """# 📚 Research
432
- ## AGI Levels
433
- L0 ❌ No AI
434
- L1 🌱 ChatGPT [2303.08774](https://arxiv.org/abs/2303.08774) | [PDF](https://arxiv.org/pdf/2303.08774.pdf)
435
- L2 💪 Watson [2201.11903](https://arxiv.org/abs/2201.11903) | [PDF](https://arxiv.org/pdf/2201.11903.pdf)
436
- L3 🎯 DALL·E [2204.06125](https://arxiv.org/abs/2204.06125) | [PDF](https://arxiv.org/pdf/2204.06125.pdf)
437
- L4 🏆 AlphaGo [1712.01815](https://arxiv.org/abs/1712.01815) | [PDF](https://arxiv.org/pdf/1712.01815.pdf)
438
- L5 🚀 AlphaFold [2203.15556](https://arxiv.org/abs/2203.15556) | [PDF](https://arxiv.org/pdf/2203.15556.pdf)
439
-
440
- ## 🧬 AlphaFold2
441
- [2203.15556](https://arxiv.org/abs/2203.15556) | [PDF](https://arxiv.org/pdf/2203.15556.pdf)
442
- 1. 🧬 Input → 2. 🔍 Search → 3. 🧩 MSA
443
- 4. 📑 Templates → 5. 🔄 Evoformer → 6. 🧱 Structure
444
- 7. 🎯 3D Predict → 8. ♻️ Recycle"""
445
-
446
- st.sidebar.markdown(sidebar_md)
447
-
448
- if __name__ == "__main__":
449
- main()
 
1
  import streamlit as st
2
+ import anthropic, openai, 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, deque, Counter
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
  from openai import OpenAI
18
+ import extra_streamlit_components as stx
19
+ from streamlit.runtime.scriptrunner import get_script_run_ctx
20
  import asyncio
21
  import edge_tts
22
 
23
+ # Imports section (add streamlit-marquee)
24
+ from streamlit_marquee import streamlit_marquee
25
+
26
+
27
+ # 🎯 1. Core Configuration & Setup
28
  st.set_page_config(
29
  page_title="🚲TalkingAIResearcher🏆",
30
  page_icon="🚲🏆",
 
36
  'About': "🚲TalkingAIResearcher🏆"
37
  }
38
  )
39
+ load_dotenv()
40
 
41
+ # Add available English voices for Edge TTS
 
 
 
 
 
 
 
 
 
42
  EDGE_TTS_VOICES = [
43
  "en-US-AriaNeural", # Default voice
44
  "en-US-GuyNeural",
 
51
  "en-CA-LiamNeural"
52
  ]
53
 
54
+ # Initialize session state variables
55
+ if 'tts_voice' not in st.session_state:
56
+ st.session_state['tts_voice'] = EDGE_TTS_VOICES[0] # Default voice
57
+ if 'audio_format' not in st.session_state:
58
+ st.session_state['audio_format'] = 'mp3' # 🆕 Default audio format
 
 
 
59
 
60
+ # 🔑 2. API Setup & Clients
 
 
 
61
  openai_api_key = os.getenv('OPENAI_API_KEY', "")
62
+ anthropic_key = os.getenv('ANTHROPIC_API_KEY_3', "")
63
+ xai_key = os.getenv('xai',"")
64
  if 'OPENAI_API_KEY' in st.secrets:
65
  openai_api_key = st.secrets['OPENAI_API_KEY']
66
  if 'ANTHROPIC_API_KEY' in st.secrets:
67
  anthropic_key = st.secrets["ANTHROPIC_API_KEY"]
68
 
69
+ openai.api_key = openai_api_key
70
  claude_client = anthropic.Anthropic(api_key=anthropic_key)
71
+ openai_client = OpenAI(api_key=openai.api_key, organization=os.getenv('OPENAI_ORG_ID'))
72
+ HF_KEY = os.getenv('HF_KEY')
73
+ API_URL = os.getenv('API_URL')
74
 
75
+ # 📝 3. Session State Management
76
+ if 'transcript_history' not in st.session_state:
77
+ st.session_state['transcript_history'] = []
78
+ if 'chat_history' not in st.session_state:
79
+ st.session_state['chat_history'] = []
80
+ if 'openai_model' not in st.session_state:
81
+ st.session_state['openai_model'] = "gpt-4o-2024-05-13"
82
+ if 'messages' not in st.session_state:
83
+ st.session_state['messages'] = []
84
+ if 'last_voice_input' not in st.session_state:
85
+ st.session_state['last_voice_input'] = ""
86
+ if 'editing_file' not in st.session_state:
87
+ st.session_state['editing_file'] = None
88
+ if 'edit_new_name' not in st.session_state:
89
+ st.session_state['edit_new_name'] = ""
90
+ if 'edit_new_content' not in st.session_state:
91
+ st.session_state['edit_new_content'] = ""
92
+ if 'viewing_prefix' not in st.session_state:
93
+ st.session_state['viewing_prefix'] = None
94
+ if 'should_rerun' not in st.session_state:
95
+ st.session_state['should_rerun'] = False
96
+ if 'old_val' not in st.session_state:
97
+ st.session_state['old_val'] = None
98
+ if 'last_query' not in st.session_state:
99
+ st.session_state['last_query'] = "" # 🆕 Store the last query for zip naming
100
 
101
+ # 🎨 4. Custom CSS
102
+ st.markdown("""
103
+ <style>
104
+ .main { background: linear-gradient(to right, #1a1a1a, #2d2d2d); color: #fff; }
105
+ .stMarkdown { font-family: 'Helvetica Neue', sans-serif; }
106
+ .stButton>button {
107
+ margin-right: 0.5rem;
108
+ }
109
+ </style>
110
+ """, unsafe_allow_html=True)
111
 
112
+ FILE_EMOJIS = {
113
+ "md": "📝",
114
+ "mp3": "🎵",
115
+ "wav": "🔊" # 🆕 Add emoji for WAV
116
+ }
117
 
118
+ # 🧠 5. High-Information Content Extraction
119
+ def get_high_info_terms(text: str, top_n=10) -> list:
120
+ """Extract high-information terms from text, including key phrases."""
121
+ stop_words = set([
122
+ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with',
123
+ 'by', 'from', 'up', 'about', 'into', 'over', 'after', 'is', 'are', 'was', 'were',
124
+ 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
125
+ 'should', 'could', 'might', 'must', 'shall', 'can', 'may', 'this', 'that', 'these',
126
+ 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'what', 'which', 'who',
127
+ 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
128
+ 'other', 'some', 'such', 'than', 'too', 'very', 'just', 'there'
129
+ ])
130
 
131
+ key_phrases = [
132
+ 'artificial intelligence', 'machine learning', 'deep learning', 'neural network',
133
+ 'personal assistant', 'natural language', 'computer vision', 'data science',
134
+ 'reinforcement learning', 'knowledge graph', 'semantic search', 'time series',
135
+ 'large language model', 'transformer model', 'attention mechanism',
136
+ 'autonomous system', 'edge computing', 'quantum computing', 'blockchain technology',
137
+ 'cognitive science', 'human computer', 'decision making', 'arxiv search',
138
+ 'research paper', 'scientific study', 'empirical analysis'
139
+ ]
 
 
 
 
 
 
 
 
 
140
 
141
+ # Extract bi-grams and uni-grams
 
142
  words = re.findall(r'\b\w+(?:-\w+)*\b', text.lower())
143
  bi_grams = [' '.join(pair) for pair in zip(words, words[1:])]
144
  combined = words + bi_grams
 
 
145
 
146
+ # Filter out stop words and short words
147
+ filtered = [
148
+ term for term in combined
149
+ if term not in stop_words
150
+ and len(term.split()) <= 2 # Limit to uni-grams and bi-grams
151
+ and any(c.isalpha() for c in term)
152
+ ]
153
+
154
+ # Count frequencies
155
+ counter = Counter(filtered)
156
+ most_common = [term for term, freq in counter.most_common(top_n)]
157
+ return most_common
158
+
159
+ def clean_text_for_filename(text: str) -> str:
160
+ """Remove punctuation and short filler words, return a compact string."""
161
+ text = text.lower()
162
+ text = re.sub(r'[^\w\s-]', '', text)
163
+ words = text.split()
164
+ stop_short = set(['the','and','for','with','this','that','from','just','very','then','been','only','also','about'])
165
+ filtered = [w for w in words if len(w)>3 and w not in stop_short]
166
+ return '_'.join(filtered)[:200]
167
+
168
+ # 📁 6. File Operations
169
  def generate_filename(prompt, response, file_type="md"):
170
+ """
171
+ Generate filename with meaningful terms and short dense clips from prompt & response.
172
+ The filename should be about 150 chars total, include high-info terms, and a clipped snippet.
173
+ """
174
  prefix = datetime.now().strftime("%y%m_%H%M") + "_"
175
  combined = (prompt + " " + response).strip()
176
+ info_terms = get_high_info_terms(combined, top_n=10)
177
+
178
+ # Include a short snippet from prompt and response
179
+ snippet = (prompt[:100] + " " + response[:100]).strip()
180
+ snippet_cleaned = clean_text_for_filename(snippet)
181
+
182
+ # Combine info terms and snippet
183
+ name_parts = info_terms + [snippet_cleaned]
184
+ full_name = '_'.join(name_parts)
185
+
186
+ # Trim to ~150 chars
187
+ if len(full_name) > 150:
188
+ full_name = full_name[:150]
189
+
190
+ filename = f"{prefix}{full_name}.{file_type}"
191
  return filename
192
 
193
  def create_file(prompt, response, file_type="md"):
194
+ """Create file with intelligent naming"""
195
  filename = generate_filename(prompt.strip(), response.strip(), file_type)
196
  with open(filename, 'w', encoding='utf-8') as f:
197
+ f.write(prompt + "\n\n" + response)
198
  return filename
199
 
200
+ def get_download_link(file, file_type="zip"):
201
+ """Generate download link for file"""
202
+ with open(file, "rb") as f:
203
  b64 = base64.b64encode(f.read()).decode()
204
+ if file_type == "zip":
205
+ return f'<a href="data:application/zip;base64,{b64}" download="{os.path.basename(file)}">📂 Download {os.path.basename(file)}</a>'
206
+ elif file_type == "mp3":
207
+ return f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file)}">🎵 Download {os.path.basename(file)}</a>'
208
+ elif file_type == "wav":
209
+ return f'<a href="data:audio/wav;base64,{b64}" download="{os.path.basename(file)}">🔊 Download {os.path.basename(file)}</a>' # 🆕 WAV download link
210
+ elif file_type == "md":
211
+ return f'<a href="data:text/markdown;base64,{b64}" download="{os.path.basename(file)}">📝 Download {os.path.basename(file)}</a>'
212
+ else:
213
+ return f'<a href="data:application/octet-stream;base64,{b64}" download="{os.path.basename(file)}">Download {os.path.basename(file)}</a>'
214
+
215
+ # 🔊 7. Audio Processing
216
+ def clean_for_speech(text: str) -> str:
217
+ """Clean text for speech synthesis"""
218
+ text = text.replace("\n", " ")
219
+ text = text.replace("</s>", " ")
220
+ text = text.replace("#", "")
221
  text = re.sub(r"\(https?:\/\/[^\)]+\)", "", text)
222
+ text = re.sub(r"\s+", " ", text).strip()
223
  return text
224
 
225
+ @st.cache_resource
226
+ def speech_synthesis_html(result):
227
+ """Create HTML for speech synthesis"""
228
+ html_code = f"""
229
+ <html><body>
230
+ <script>
231
+ var msg = new SpeechSynthesisUtterance("{result.replace('"', '')}");
232
+ window.speechSynthesis.speak(msg);
233
+ </script>
234
+ </body></html>
235
+ """
236
+ components.html(html_code, height=0)
237
+
238
+ async def edge_tts_generate_audio(text, voice="en-US-AriaNeural", rate=0, pitch=0, file_format="mp3"):
239
+ """Generate audio using Edge TTS"""
240
+ text = clean_for_speech(text)
241
+ if not text.strip():
242
+ return None
243
+ rate_str = f"{rate:+d}%"
244
+ pitch_str = f"{pitch:+d}Hz"
245
+ communicate = edge_tts.Communicate(text, voice, rate=rate_str, pitch=pitch_str)
246
+ out_fn = generate_filename(text, text, file_type=file_format)
247
+ await communicate.save(out_fn)
248
+ return out_fn
249
+
250
+ def speak_with_edge_tts(text, voice="en-US-AriaNeural", rate=0, pitch=0, file_format="mp3"):
251
+ """Wrapper for edge TTS generation"""
252
+ return asyncio.run(edge_tts_generate_audio(text, voice, rate, pitch, file_format))
253
 
254
+ def play_and_download_audio(file_path, file_type="mp3"):
255
+ """Play and provide download link for audio"""
256
+ if file_path and os.path.exists(file_path):
257
+ if file_type == "mp3":
258
+ st.audio(file_path)
259
+ elif file_type == "wav":
260
+ st.audio(file_path)
261
+ dl_link = get_download_link(file_path, file_type=file_type)
262
+ st.markdown(dl_link, unsafe_allow_html=True)
263
+
264
+ # 🎬 8. Media Processing
265
+ def process_image(image_path, user_prompt):
266
+ """Process image with GPT-4V"""
267
+ with open(image_path, "rb") as imgf:
268
+ image_data = imgf.read()
269
+ b64img = base64.b64encode(image_data).decode("utf-8")
270
+ resp = openai_client.chat.completions.create(
271
+ model=st.session_state["openai_model"],
272
+ messages=[
273
+ {"role": "system", "content": "You are a helpful assistant."},
274
+ {"role": "user", "content": [
275
+ {"type": "text", "text": user_prompt},
276
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64img}"}}
277
+ ]}
278
+ ],
279
+ temperature=0.0,
280
+ )
281
+ return resp.choices[0].message.content
282
 
283
  def process_audio_file(audio_path):
284
+ """Process audio with Whisper"""
285
  with open(audio_path, "rb") as f:
286
+ transcription = openai_client.audio.transcriptions.create(model="whisper-1", file=f)
287
+ st.session_state.messages.append({"role": "user", "content": transcription.text})
288
+ return transcription.text
 
289
 
290
+ def process_video(video_path, seconds_per_frame=1):
291
+ """Extract frames from video"""
292
+ vid = cv2.VideoCapture(video_path)
293
+ total = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))
294
+ fps = vid.get(cv2.CAP_PROP_FPS)
295
+ skip = int(fps*seconds_per_frame)
296
+ frames_b64 = []
297
+ for i in range(0, total, skip):
298
+ vid.set(cv2.CAP_PROP_POS_FRAMES, i)
299
+ ret, frame = vid.read()
300
+ if not ret:
301
+ break
302
+ _, buf = cv2.imencode(".jpg", frame)
303
+ frames_b64.append(base64.b64encode(buf).decode("utf-8"))
304
+ vid.release()
305
+ return frames_b64
 
 
 
 
306
 
307
+ def process_video_with_gpt(video_path, prompt):
308
+ """Analyze video frames with GPT-4V"""
309
+ frames = process_video(video_path)
310
+ resp = openai_client.chat.completions.create(
311
+ model=st.session_state["openai_model"],
312
+ messages=[
313
+ {"role":"system","content":"Analyze video frames."},
314
+ {"role":"user","content":[
315
+ {"type":"text","text":prompt},
316
+ *[{"type":"image_url","image_url":{"url":f"data:image/jpeg;base64,{fr}"}} for fr in frames]
317
+ ]}
318
+ ]
319
+ )
320
+ return resp.choices[0].message.content
 
 
321
 
322
+ # 🤖 9. AI Model Integration
 
 
 
323
 
324
+ def save_full_transcript(query, text):
325
+ """Save full transcript of Arxiv results as a file."""
326
+ create_file(query, text, "md")
 
 
327
 
328
+ def parse_arxiv_refs(ref_text: str):
329
+ """
330
+ Parse papers by finding lines with two pipe characters as title lines.
331
+ Returns list of paper dictionaries with audio files.
332
+ """
333
+ if not ref_text:
334
+ return []
 
 
335
 
336
+ results = []
337
+ current_paper = {}
338
+ lines = ref_text.split('\n')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
+ for i, line in enumerate(lines):
341
+ # Check if this is a title line (contains exactly 2 pipe characters)
342
+ if line.count('|') == 2:
343
+ # If we have a previous paper, add it to results
344
+ if current_paper:
345
+ results.append(current_paper)
346
+ if len(results) >= 20: # Limit to 20 papers
347
+ break
348
+
349
+ # Parse new paper header
350
+ try:
351
+ # Remove ** and split by |
352
+ header_parts = line.strip('* ').split('|')
353
+ date = header_parts[0].strip()
354
+ title = header_parts[1].strip()
355
+ # Extract arXiv URL if present
356
+ url_match = re.search(r'(https://arxiv.org/\S+)', line)
357
+ url = url_match.group(1) if url_match else f"paper_{len(results)}"
358
+
359
+ current_paper = {
360
+ 'date': date,
361
+ 'title': title,
362
+ 'url': url,
363
+ 'authors': '',
364
+ 'summary': '',
365
+ 'content_start': i + 1 # Track where content begins
366
+ }
367
+ except Exception as e:
368
+ st.warning(f"Error parsing paper header: {str(e)}")
369
+ current_paper = {}
370
+ continue
371
+
372
+ # If we have a current paper and this isn't a title line, add to content
373
+ elif current_paper:
374
+ if not current_paper['authors']: # First line after title is authors
375
+ current_paper['authors'] = line.strip('* ')
376
+ else: # Rest is summary
377
+ if current_paper['summary']:
378
+ current_paper['summary'] += ' ' + line.strip()
379
+ else:
380
+ current_paper['summary'] = line.strip()
381
 
382
+ # Don't forget the last paper
383
+ if current_paper:
384
+ results.append(current_paper)
 
385
 
386
+ return results[:20] # Ensure we return maximum 20 papers
 
387
 
388
+ def create_paper_audio_files(papers, input_question):
389
+ """
390
+ Create audio files for each paper's content and add file paths to paper dict.
391
+ Also, display each audio as it's generated.
392
+ """
393
+ # Collect all content for combined summary
394
+ combined_titles = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
 
 
 
396
  for paper in papers:
397
  try:
398
+ # Generate audio for full content only
399
+ full_text = f"{paper['title']} by {paper['authors']}. {paper['summary']}"
400
+ full_text = clean_for_speech(full_text)
401
+ # Determine file format based on user selection
402
  file_format = st.session_state['audio_format']
403
+ full_file = speak_with_edge_tts(full_text, voice=st.session_state['tts_voice'], file_format=file_format)
404
+ paper['full_audio'] = full_file
405
+
406
+ # Display the audio immediately after generation
407
+ st.write(f"### {FILE_EMOJIS.get(file_format, '')} {os.path.basename(full_file)}")
408
+ play_and_download_audio(full_file, file_type=file_format)
409
+
410
+ combined_titles.append(paper['title'])
411
+
412
  except Exception as e:
413
+ st.warning(f"Error generating audio for paper {paper['title']}: {str(e)}")
414
+ paper['full_audio'] = None
415
+
416
+ # After all individual audios, create a combined summary audio
417
+ if combined_titles:
418
+ combined_text = f"Here are the titles of the papers related to your query: {'; '.join(combined_titles)}. Your original question was: {input_question}"
419
+ file_format = st.session_state['audio_format']
420
+ combined_file = speak_with_edge_tts(combined_text, voice=st.session_state['tts_voice'], file_format=file_format)
421
+ st.write(f"### {FILE_EMOJIS.get(file_format, '')} Combined Summary Audio")
422
+ play_and_download_audio(combined_file, file_type=file_format)
423
+ papers.append({'title': 'Combined Summary', 'full_audio': combined_file})
424
+
425
+
426
+
427
+ def display_marquee_controls():
428
+ st.sidebar.markdown("### 🎯 Marquee Settings")
429
+ cols = st.sidebar.columns(2)
430
+ with cols[0]:
431
+ bg_color = st.color_picker("🎨 Background", "#1E1E1E")
432
+ text_color = st.color_picker("✍️ Text", "#FFFFFF")
433
+ with cols[1]:
434
+ font_size = st.slider("📏 Size", 10, 24, 14)
435
+ duration = st.slider("⏱️ Speed", 1, 20, 10)
436
+
437
+ return {
438
+ "background": bg_color,
439
+ "color": text_color,
440
+ "font-size": f"{font_size}px",
441
+ "animationDuration": f"{duration}s",
442
+ "width": "100%",
443
+ "lineHeight": "35px"
444
+ }
445
+
446
 
 
 
 
 
 
 
447
 
448
  def display_papers(papers):
449
+ """Display papers with their audio controls and marquee summaries."""
450
  st.write("## Research Papers")
451
+ marquee_settings = display_marquee_controls()
452
+
453
+ papercount = 0
454
+ for paper in papers:
455
+ papercount = papercount + 1
456
+ if papercount <= 20:
457
+ # Add marquee display
458
+ content = f"📄 {paper['title']} | 👤 {paper['authors']} | 📝 {paper['summary']}"
459
+ streamlit_marquee(
460
+ content=content,
461
+ **marquee_settings,
462
+ key=f"paper_{paper.get('id', random.randint(1000,9999))}"
463
+ )
464
+ st.write("")
465
+
466
+ with st.expander(f"{papercount}. 📄 {paper['title']}", expanded=True):
467
+ st.markdown(f"**{paper['date']} | {paper['title']} | ⬇️**")
468
+ st.markdown(f"*{paper['authors']}*")
469
+ st.markdown(paper['summary'])
470
+
471
+ if paper.get('full_audio'):
472
+ st.write("📚 Paper Audio")
473
+ file_ext = os.path.splitext(paper['full_audio'])[1].lower().strip('.')
474
+ if file_ext in ['mp3', 'wav']:
475
+ st.audio(paper['full_audio'])
476
+
477
+
478
+ def perform_ai_lookup(q, vocal_summary=True, extended_refs=False,
479
+ titles_summary=True, full_audio=False):
480
+ """Perform Arxiv search with audio generation per paper."""
481
+ start = time.time()
482
+
483
+ # Query the HF RAG pipeline
484
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
485
+ refs = client.predict(q, 20, "Semantic Search",
486
+ "mistralai/Mixtral-8x7B-Instruct-v0.1",
487
+ api_name="/update_with_rag_md")[0]
488
+ r2 = client.predict(q, "mistralai/Mixtral-8x7B-Instruct-v0.1",
489
+ True, api_name="/ask_llm")
490
+
491
+ # Combine for final text output
492
+ result = f"### 🔎 {q}\n\n{r2}\n\n{refs}"
493
+ st.markdown(result)
494
+
495
+ # Parse and process papers
496
+ papers = parse_arxiv_refs(refs)
497
+ if papers:
498
+ create_paper_audio_files(papers, input_question=q)
499
+ display_papers(papers)
500
+ else:
501
+ st.warning("No papers found in the response.")
502
+
503
+ elapsed = time.time()-start
504
+ st.write(f"**Total Elapsed:** {elapsed:.2f} s")
505
+
506
+ # Save full transcript
507
+ create_file(q, result, "md")
508
+ return result
509
 
510
  def process_with_gpt(text):
511
+ """Process text with GPT-4"""
512
+ if not text:
513
+ return
514
+ st.session_state.messages.append({"role":"user","content":text})
515
+ with st.chat_message("user"):
516
  st.markdown(text)
517
  with st.chat_message("assistant"):
518
+ c = openai_client.chat.completions.create(
519
+ model=st.session_state["openai_model"],
520
  messages=st.session_state.messages,
521
  stream=False
522
  )
523
+ ans = c.choices[0].message.content
524
+ st.write("GPT-4o: " + ans)
525
+ create_file(text, ans, "md")
526
+ st.session_state.messages.append({"role":"assistant","content":ans})
527
+ return ans
528
 
529
  def process_with_claude(text):
530
+ """Process text with Claude"""
531
+ if not text:
532
+ return
533
  with st.chat_message("user"):
534
  st.markdown(text)
535
  with st.chat_message("assistant"):
536
+ r = claude_client.messages.create(
537
  model="claude-3-sonnet-20240229",
538
+ max_tokens=1000,
539
+ messages=[{"role":"user","content":text}]
540
  )
541
+ ans = r.content[0].text
542
+ st.write("Claude-3.5: " + ans)
543
+ create_file(text, ans, "md")
544
+ st.session_state.chat_history.append({"user":text,"claude":ans})
545
+ return ans
546
 
547
+ # 📂 10. File Management
548
+ def create_zip_of_files(md_files, mp3_files, wav_files, input_question):
549
+ """Create zip with intelligent naming based on top 10 common words."""
550
+ # Exclude 'readme.md'
551
+ md_files = [f for f in md_files if os.path.basename(f).lower() != 'readme.md']
552
+ all_files = md_files + mp3_files + wav_files
553
+ if not all_files:
554
+ return None
555
+
556
+ # Collect content for high-info term extraction
557
+ all_content = []
558
+ for f in all_files:
559
+ if f.endswith('.md'):
560
+ with open(f, 'r', encoding='utf-8') as file:
561
+ all_content.append(file.read())
562
+ elif f.endswith('.mp3') or f.endswith('.wav'):
563
+ # Replace underscores with spaces and extract basename without extension
564
+ basename = os.path.splitext(os.path.basename(f))[0]
565
+ words = basename.replace('_', ' ')
566
+ all_content.append(words)
567
 
568
+ # Include the input question
569
+ all_content.append(input_question)
 
 
 
570
 
571
+ combined_content = " ".join(all_content)
572
+ info_terms = get_high_info_terms(combined_content, top_n=10)
573
+
574
+ timestamp = datetime.now().strftime("%y%m_%H%M")
575
+ name_text = '_'.join(term.replace(' ', '-') for term in info_terms[:10])
576
+ zip_name = f"{timestamp}_{name_text}.zip"
577
+
578
+ with zipfile.ZipFile(zip_name,'w') as z:
579
+ for f in all_files:
580
+ z.write(f)
581
+
582
+ return zip_name
583
+
584
+ def load_files_for_sidebar():
585
+ """Load and group files for sidebar display based on first 9 characters of filename"""
586
+ md_files = glob.glob("*.md")
587
+ mp3_files = glob.glob("*.mp3")
588
+ wav_files = glob.glob("*.wav")
589
+
590
+ md_files = [f for f in md_files if os.path.basename(f).lower() != 'readme.md']
591
+ all_files = md_files + mp3_files + wav_files
592
+
593
+ groups = defaultdict(list)
594
+ for f in all_files:
595
+ # Get first 9 characters of filename (timestamp) as group name
596
+ basename = os.path.basename(f)
597
+ group_name = basename[:9] if len(basename) >= 9 else 'Other'
598
+ groups[group_name].append(f)
599
+
600
+ # Sort groups based on latest file modification time
601
+ sorted_groups = sorted(groups.items(), key=lambda x: max(os.path.getmtime(f) for f in x[1]), reverse=True)
602
+ return sorted_groups
603
+
604
+ def extract_keywords_from_md(files):
605
+ """Extract keywords from markdown files"""
606
+ text = ""
607
+ for f in files:
608
+ if f.endswith(".md"):
609
+ c = open(f,'r',encoding='utf-8').read()
610
+ text += " " + c
611
+ return get_high_info_terms(text, top_n=5)
612
+
613
+ def display_file_manager_sidebar(groups_sorted):
614
+ """Display file manager in sidebar with timestamp-based groups"""
615
+ st.sidebar.title("🎵 Audio & Docs Manager")
616
+
617
+ all_md = []
618
+ all_mp3 = []
619
+ all_wav = []
620
+ for group_name, files in groups_sorted:
621
+ for f in files:
622
+ if f.endswith(".md"):
623
+ all_md.append(f)
624
+ elif f.endswith(".mp3"):
625
+ all_mp3.append(f)
626
+ elif f.endswith(".wav"):
627
+ all_wav.append(f)
628
+
629
+ top_bar = st.sidebar.columns(4)
630
+ with top_bar[0]:
631
+ if st.button("🗑 DelAllMD"):
632
+ for f in all_md:
633
+ os.remove(f)
634
+ st.session_state.should_rerun = True
635
+ with top_bar[1]:
636
+ if st.button("🗑 DelAllMP3"):
637
+ for f in all_mp3:
638
+ os.remove(f)
639
+ st.session_state.should_rerun = True
640
+ with top_bar[2]:
641
+ if st.button("🗑 DelAllWAV"):
642
+ for f in all_wav:
643
+ os.remove(f)
644
+ st.session_state.should_rerun = True
645
+ with top_bar[3]:
646
+ if st.button("⬇️ ZipAll"):
647
+ zip_name = create_zip_of_files(all_md, all_mp3, all_wav, input_question=st.session_state.get('last_query', ''))
648
+ if zip_name:
649
+ st.sidebar.markdown(get_download_link(zip_name, file_type="zip"), unsafe_allow_html=True)
650
+
651
+ for group_name, files in groups_sorted:
652
+ timestamp_dt = datetime.strptime(group_name, "%y%m_%H%M") if len(group_name) == 9 else None
653
+ group_label = timestamp_dt.strftime("%Y-%m-%d %H:%M") if timestamp_dt else group_name
654
+
655
+ with st.sidebar.expander(f"📁 {group_label} ({len(files)})", expanded=True):
656
+ c1,c2 = st.columns(2)
657
+ with c1:
658
+ if st.button("👀ViewGrp", key="view_group_"+group_name):
659
+ st.session_state.viewing_prefix = group_name
660
+ with c2:
661
+ if st.button("🗑DelGrp", key="del_group_"+group_name):
662
+ for f in files:
663
+ os.remove(f)
664
+ st.success(f"Deleted group {group_name}!")
665
+ st.session_state.should_rerun = True
666
+
667
+ for f in files:
668
+ fname = os.path.basename(f)
669
+ ext = os.path.splitext(fname)[1].lower()
670
+ emoji = FILE_EMOJIS.get(ext.strip('.'), '')
671
+ ctime = datetime.fromtimestamp(os.path.getmtime(f)).strftime("%H:%M:%S")
672
+ st.write(f"{emoji} **{fname}** - {ctime}")
673
 
674
+ # 🎯 11. Main Application
675
+ def main():
676
+ st.sidebar.markdown("### 🚲BikeAI🏆 Multi-Agent Research")
677
+
678
+
679
+ # Add global marquee settings near top of main
680
+ marquee_settings = display_marquee_controls()
681
 
682
+ # Initialize content holder in session state if not present
683
+ if 'marquee_content' not in st.session_state:
684
+ st.session_state['marquee_content'] = "🚀 Welcome to TalkingAIResearcher | 🤖 Your Research Assistant"
 
685
 
686
+ # Marquee display with larger text and dynamic content
687
+ streamlit_marquee(
688
+ content=st.session_state['marquee_content'],
689
+ **{
690
+ **marquee_settings,
691
+ "font-size": "28px", # Larger default text
692
+ "lineHeight": "50px" # Increased line height for larger text
693
+ },
694
+ key="dynamic_marquee"
695
+ )
696
+
697
+ # Update marquee content when viewing files
698
+ if st.session_state.viewing_prefix:
699
+ for group_name, files in groups_sorted:
700
+ if group_name == st.session_state.viewing_prefix:
701
+ for f in files:
702
+ if f.endswith('.md'):
703
+ with open(f, 'r', encoding='utf-8') as file:
704
+ st.session_state['marquee_content'] = file.read()[:500] # First 500 chars
705
+
706
+ # Update marquee when displaying papers
707
+ if tab_main == "🔍 ArXiv":
708
+ papers = parse_arxiv_refs(refs)
709
+ if papers:
710
+ paper_texts = [f"📄 {p['title']} | {p['authors']}" for p in papers]
711
+ st.session_state['marquee_content'] = " ⭐ ".join(paper_texts)
712
+
713
 
 
 
 
 
 
 
 
 
 
 
714
 
715
+ # Add voice selector to sidebar
716
+ st.sidebar.markdown("### 🎤 Voice Settings")
717
+ selected_voice = st.sidebar.selectbox(
718
+ "Select TTS Voice:",
719
+ options=EDGE_TTS_VOICES,
720
+ index=EDGE_TTS_VOICES.index(st.session_state['tts_voice'])
721
+ )
722
+
723
+ # Add audio format selector to sidebar
724
+ st.sidebar.markdown("### 🔊 Audio Format")
725
+ selected_format = st.sidebar.radio(
726
+ "Choose Audio Format:",
727
+ options=["MP3", "WAV"],
728
+ index=0 # Default to MP3
729
+ )
730
+
731
+ # Update session state if voice or format changes
732
+ if selected_voice != st.session_state['tts_voice']:
733
+ st.session_state['tts_voice'] = selected_voice
734
+ st.rerun()
735
+ if selected_format.lower() != st.session_state['audio_format']:
736
+ st.session_state['audio_format'] = selected_format.lower()
737
+ st.rerun()
738
+
739
+ tab_main = st.radio("Action:",["🎤 Voice","📸 Media","🔍 ArXiv","📝 Editor"],horizontal=True)
740
+
741
+ mycomponent = components.declare_component("mycomponent", path="mycomponent")
742
+ val = mycomponent(my_input_value="Hello")
743
+
744
+ # Show input in a text box for editing if detected
745
+ if val:
746
+ val_stripped = val.replace('\\n', ' ')
747
+ edited_input = st.text_area("✏️ Edit Input:", value=val_stripped, height=100)
748
+ #edited_input = edited_input.replace('\n', ' ')
749
+
750
+ run_option = st.selectbox("Model:", ["Arxiv", "GPT-4o", "Claude-3.5"])
751
+ col1, col2 = st.columns(2)
752
+ with col1:
753
+ autorun = st.checkbox("⚙ AutoRun", value=True)
754
+ with col2:
755
+ full_audio = st.checkbox("📚FullAudio", value=False,
756
+ help="Generate full audio response")
757
+
758
+ input_changed = (val != st.session_state.old_val)
759
+
760
+ if autorun and input_changed:
761
+ st.session_state.old_val = val
762
+ st.session_state.last_query = edited_input # Store the last query for zip naming
763
+ if run_option == "Arxiv":
764
+ perform_ai_lookup(edited_input, vocal_summary=True, extended_refs=False,
765
+ titles_summary=True, full_audio=full_audio)
766
+ else:
767
+ if run_option == "GPT-4o":
768
+ process_with_gpt(edited_input)
769
+ elif run_option == "Claude-3.5":
770
+ process_with_claude(edited_input)
771
+ else:
772
+ if st.button("▶ Run"):
773
+ st.session_state.old_val = val
774
+ st.session_state.last_query = edited_input # Store the last query for zip naming
775
+ if run_option == "Arxiv":
776
+ perform_ai_lookup(edited_input, vocal_summary=True, extended_refs=False,
777
+ titles_summary=True, full_audio=full_audio)
778
+ else:
779
+ if run_option == "GPT-4o":
780
+ process_with_gpt(edited_input)
781
+ elif run_option == "Claude-3.5":
782
+ process_with_claude(edited_input)
783
+
784
+ if tab_main == "🔍 ArXiv":
785
+ st.subheader("🔍 Query ArXiv")
786
+ q = st.text_input("🔍 Query:")
787
+
788
+ st.markdown("### 🎛 Options")
789
+ vocal_summary = st.checkbox("🎙ShortAudio", value=True)
790
+ extended_refs = st.checkbox("📜LongRefs", value=False)
791
+ titles_summary = st.checkbox("🔖TitlesOnly", value=True)
792
+ full_audio = st.checkbox("📚FullAudio", value=False,
793
+ help="Full audio of results")
794
+ full_transcript = st.checkbox("🧾FullTranscript", value=False,
795
+ help="Generate a full transcript file")
796
+
797
+ if q and st.button("🔍Run"):
798
+ st.session_state.last_query = q # Store the last query for zip naming
799
+ result = perform_ai_lookup(q, vocal_summary=vocal_summary, extended_refs=extended_refs,
800
+ titles_summary=titles_summary, full_audio=full_audio)
801
+ if full_transcript:
802
+ save_full_transcript(q, result)
803
+
804
+ st.markdown("### Change Prompt & Re-Run")
805
+ q_new = st.text_input("🔄 Modify Query:")
806
+ if q_new and st.button("🔄 Re-Run with Modified Query"):
807
+ st.session_state.last_query = q_new # Update last query
808
+ result = perform_ai_lookup(q_new, vocal_summary=vocal_summary, extended_refs=extended_refs,
809
+ titles_summary=titles_summary, full_audio=full_audio)
810
+ if full_transcript:
811
+ save_full_transcript(q_new, result)
812
+
813
+ elif tab_main == "🎤 Voice":
814
+ st.subheader("🎤 Voice Input")
815
+ user_text = st.text_area("💬 Message:", height=100)
816
+ user_text = user_text.strip().replace('\n', ' ')
817
+ if st.button("📨 Send"):
818
+ process_with_gpt(user_text)
819
+ st.subheader("📜 Chat History")
820
+ t1,t2=st.tabs(["Claude History","GPT-4o History"])
821
+ with t1:
822
+ for c in st.session_state.chat_history:
823
+ st.write("**You:**", c["user"])
824
+ st.write("**Claude:**", c["claude"])
825
+ with t2:
826
+ for m in st.session_state.messages:
827
+ with st.chat_message(m["role"]):
828
+ st.markdown(m["content"])
829
+
830
+ elif tab_main == "📸 Media":
831
+ st.header("📸 Images & 🎥 Videos")
832
+ tabs = st.tabs(["🖼 Images", "🎥 Video"])
833
+ with tabs[0]:
834
+ imgs = glob.glob("*.png")+glob.glob("*.jpg")
835
+ if imgs:
836
+ c = st.slider("Cols",1,5,3)
837
+ cols = st.columns(c)
838
+ for i,f in enumerate(imgs):
839
+ with cols[i%c]:
840
+ st.image(Image.open(f),use_container_width=True)
841
+ if st.button(f"👀 Analyze {os.path.basename(f)}", key=f"analyze_{f}"):
842
+ a = process_image(f,"Describe this image.")
843
+ st.markdown(a)
844
+ else:
845
+ st.write("No images found.")
846
+ with tabs[1]:
847
+ vids = glob.glob("*.mp4")
848
+ if vids:
849
+ for v in vids:
850
+ with st.expander(f"🎥 {os.path.basename(v)}"):
851
+ st.video(v)
852
+ if st.button(f"Analyze {os.path.basename(v)}", key=f"analyze_{v}"):
853
+ a = process_video_with_gpt(v,"Describe video.")
854
+ st.markdown(a)
855
+ else:
856
+ st.write("No videos found.")
857
+
858
+ elif tab_main == "📝 Editor":
859
+ if getattr(st.session_state,'current_file',None):
860
  st.subheader(f"Editing: {st.session_state.current_file}")
861
+ new_text = st.text_area("✏️ Content:", st.session_state.file_content, height=300)
862
+ if st.button("💾 Save"):
863
+ with open(st.session_state.current_file,'w',encoding='utf-8') as f:
864
+ f.write(new_text)
865
+ st.success("Updated!")
866
  st.session_state.should_rerun = True
867
+ else:
868
+ st.write("Select a file from the sidebar to edit.")
869
+
870
+ # Load and display files in the sidebar
871
+ groups_sorted = load_files_for_sidebar()
872
+ display_file_manager_sidebar(groups_sorted)
873
+
874
+ if st.session_state.viewing_prefix and any(st.session_state.viewing_prefix == group for group, _ in groups_sorted):
875
+ st.write("---")
876
+ st.write(f"**Viewing Group:** {st.session_state.viewing_prefix}")
877
+ for group_name, files in groups_sorted:
878
+ if group_name == st.session_state.viewing_prefix:
879
+ for f in files:
880
+ fname = os.path.basename(f)
881
+ ext = os.path.splitext(fname)[1].lower().strip('.')
882
+ st.write(f"### {fname}")
883
+ if ext == "md":
884
+ content = open(f,'r',encoding='utf-8').read()
885
+ st.markdown(content)
886
+ elif ext == "mp3":
887
+ st.audio(f)
888
+ elif ext == "wav":
889
+ st.audio(f) # 🆕 Handle WAV files
890
+ else:
891
+ st.markdown(get_download_link(f), unsafe_allow_html=True)
892
+ break
893
+ if st.button("❌ Close"):
894
+ st.session_state.viewing_prefix = None
895
+
896
+ markdownPapers = """
897
+
898
+ # Levels of AGI
899
+
900
+ ## 1. Performance (rows) x Generality (columns)
901
+ - **Narrow**
902
+ - *clearly scoped or set of tasks*
903
+ - **General**
904
+ - *wide range of non-physical tasks, including metacognitive abilities like learning new skills*
905
+
906
+ ## 2. Levels of AGI
907
+
908
+ ### 2.1 Level 0: No AI
909
+ - **Narrow Non-AI**
910
+ - Calculator software; compiler
911
+ - **General Non-AI**
912
+ - Human-in-the-loop computing, e.g., Amazon Mechanical Turk
913
+
914
+ ### 2.2 Level 1: Emerging
915
+ *equal to or somewhat better than an unskilled human*
916
+ - **Emerging Narrow AI**
917
+ - GOFAI; simple rule-based systems
918
+ - Example: SHRDLU
919
+ - *Reference:* Winograd, T. (1971). **Procedures as a Representation for Data in a Computer Program for Understanding Natural Language**. MIT AI Technical Report. [Link](https://dspace.mit.edu/handle/1721.1/7095)
920
+ - **Emerging AGI**
921
+ - ChatGPT (OpenAI, 2023)
922
+ - Bard (Anil et al., 2023)
923
+ - *Reference:* Anil, R., et al. (2023). **Bard: Google’s AI Chatbot**. [arXiv](https://arxiv.org/abs/2303.12712)
924
+ - LLaMA 2 (Touvron et al., 2023)
925
+ - *Reference:* Touvron, H., et al. (2023). **LLaMA 2: Open and Efficient Foundation Language Models**. [arXiv](https://arxiv.org/abs/2307.09288)
926
+
927
+ ### 2.3 Level 2: Competent
928
+ *at least 50th percentile of skilled adults*
929
+ - **Competent Narrow AI**
930
+ - Toxicity detectors such as Jigsaw
931
+ - *Reference:* Das, S., et al. (2022). **Toxicity Detection at Scale with Jigsaw**. [arXiv](https://arxiv.org/abs/2204.06905)
932
+ - Smart Speakers (Apple, Amazon, Google)
933
+ - VQA systems (PaLI)
934
+ - *Reference:* Chen, T., et al. (2023). **PaLI: Pathways Language and Image model**. [arXiv](https://arxiv.org/abs/2301.01298)
935
+ - Watson (IBM)
936
+ - SOTA LLMs for subsets of tasks
937
+ - **Competent AGI**
938
+ - Not yet achieved
939
+
940
+ ### 2.4 Level 3: Expert
941
+ *at least 90th percentile of skilled adults*
942
+ - **Expert Narrow AI**
943
+ - Spelling & grammar checkers (Grammarly, 2023)
944
+ - Generative image models
945
+ - Example: Imagen
946
+ - *Reference:* Saharia, C., et al. (2022). **Imagen: Photorealistic Text-to-Image Diffusion Models**. [arXiv](https://arxiv.org/abs/2205.11487)
947
+ - Example: DALL·E 2
948
+ - *Reference:* Ramesh, A., et al. (2022). **Hierarchical Text-Conditional Image Generation with CLIP Latents**. [arXiv](https://arxiv.org/abs/2204.06125)
949
+ - **Expert AGI**
950
+ - Not yet achieved
951
+
952
+ ### 2.5 Level 4: Virtuoso
953
+ *at least 99th percentile of skilled adults*
954
+ - **Virtuoso Narrow AI**
955
+ - Deep Blue
956
+ - *Reference:* Campbell, M., et al. (2002). **Deep Blue**. IBM Journal of Research and Development. [Link](https://research.ibm.com/publications/deep-blue)
957
+ - AlphaGo
958
+ - *Reference:* Silver, D., et al. (2016, 2017). **Mastering the Game of Go with Deep Neural Networks and Tree Search**. [Nature](https://www.nature.com/articles/nature16961)
959
+ - **Virtuoso AGI**
960
+ - Not yet achieved
961
+
962
+ ### 2.6 Level 5: Superhuman
963
+ *outperforms 100% of humans*
964
+ - **Superhuman Narrow AI**
965
+ - AlphaFold
966
+ - *Reference:* Jumper, J., et al. (2021). **Highly Accurate Protein Structure Prediction with AlphaFold**. [Nature](https://www.nature.com/articles/s41586-021-03819-2)
967
+ - AlphaZero
968
+ - *Reference:* Silver, D., et al. (2018). **A General Reinforcement Learning Algorithm that Masters Chess, Shogi, and Go through Self-Play**. [Science](https://www.science.org/doi/10.1126/science.aar6404)
969
+ - StockFish
970
+ - *Reference:* Stockfish (2023). **Stockfish Chess Engine**. [Website](https://stockfishchess.org)
971
+ - **Artificial Superintelligence (ASI)**
972
+ - Not yet achieved
973
+
974
+
975
+ # 🧬 Innovative Architecture of AlphaFold2: A Hybrid System
976
+
977
+ ## 1. 🔢 Input Sequence
978
+ - The process starts with an **input sequence** (protein sequence).
979
+
980
+ ## 2. 🗄️ Database Searches
981
+ - **Genetic database search** 🔍
982
+ - Searches genetic databases to retrieve related sequences.
983
+ - **Structure database search** 🔍
984
+ - Searches structural databases for template structures.
985
+ - **Pairing** 🤝
986
+ - Aligns sequences and structures for further analysis.
987
+
988
+ ## 3. 🧩 MSA (Multiple Sequence Alignment)
989
+ - **MSA representation** 📊 (r,c)
990
+ - Representation of multiple aligned sequences used as input.
991
+
992
+ ## 4. 📑 Templates
993
+ - Template structures are paired to assist the model.
994
+
995
+ ## 5. 🔄 Evoformer (48 blocks)
996
+ - A **deep learning module** that refines representations:
997
+ - **MSA representation** 🧱
998
+ - **Pair representation** 🧱 (r,c)
999
+
1000
+ ## 6. 🧱 Structure Module (8 blocks)
1001
+ - Converts the representations into:
1002
+ - **Single representation** (r,c)
1003
+ - **Pair representation** (r,c)
1004
+
1005
+ ## 7. 🧬 3D Structure Prediction
1006
+ - The structure module predicts the **3D protein structure**.
1007
+ - **Confidence levels**:
1008
+ - 🔵 *High confidence*
1009
+ - 🟠 *Low confidence*
1010
+
1011
+ ## 8. ♻️ Recycling (Three Times)
1012
+ - The model **recycles** its output up to three times to refine the prediction.
1013
+
1014
+ ## 9. 📚 Reference
1015
+ **Jumper, J., et al. (2021).** Highly Accurate Protein Structure Prediction with AlphaFold. *Nature.*
1016
+ 🔗 [Nature Publication Link](https://www.nature.com/articles/s41586-021-03819-2)
1017
 
1018
+ """
1019
+ st.sidebar.markdown(markdownPapers)
 
1020
 
1021
  if st.session_state.should_rerun:
1022
  st.session_state.should_rerun = False
1023
  st.rerun()
1024
 
1025
+ if __name__=="__main__":
1026
+ main()