awacke1 commited on
Commit
d5aeedf
β€’
1 Parent(s): 5b15408

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -22
app.py CHANGED
@@ -41,15 +41,24 @@ HF_KEY = os.getenv('HF_KEY')
41
  API_URL = os.getenv('API_URL')
42
 
43
  # Session states
44
- st.session_state.setdefault('transcript_history', [])
45
- st.session_state.setdefault('chat_history', [])
46
- st.session_state.setdefault('openai_model', "gpt-4o-2024-05-13")
47
- st.session_state.setdefault('messages', [])
48
- st.session_state.setdefault('last_voice_input', "")
49
- st.session_state.setdefault('editing_file', None)
50
- st.session_state.setdefault('edit_new_name', "")
51
- st.session_state.setdefault('edit_new_content', "")
52
- st.session_state.setdefault('should_rerun', False) # Flag to indicate we need to rerun after operations
 
 
 
 
 
 
 
 
 
53
 
54
  # 🎨 Minimal Custom CSS
55
  st.markdown("""
@@ -75,9 +84,9 @@ def generate_filename(prompt, file_type="md"):
75
  return f"{date_str}_{safe}.{file_type}"
76
 
77
  def create_file(filename, prompt, response):
 
78
  with open(filename, 'w', encoding='utf-8') as f:
79
  f.write(prompt + "\n\n" + response)
80
- st.session_state.should_rerun = True
81
 
82
  def get_download_link(file):
83
  with open(file, "rb") as f:
@@ -97,6 +106,7 @@ def speech_synthesis_html(result):
97
  components.html(html_code, height=0)
98
 
99
  async def edge_tts_generate_audio(text, voice="en-US-AriaNeural", rate=0, pitch=0):
 
100
  if not text.strip():
101
  return None
102
  rate_str = f"{rate:+d}%"
@@ -104,7 +114,6 @@ async def edge_tts_generate_audio(text, voice="en-US-AriaNeural", rate=0, pitch=
104
  communicate = edge_tts.Communicate(text, voice, rate=rate_str, pitch=pitch_str)
105
  out_fn = generate_filename(text,"mp3")
106
  await communicate.save(out_fn)
107
- st.session_state.should_rerun = True
108
  return out_fn
109
 
110
  def speak_with_edge_tts(text, voice="en-US-AriaNeural", rate=0, pitch=0):
@@ -133,10 +142,10 @@ def process_image(image_path, user_prompt):
133
  return resp.choices[0].message.content
134
 
135
  def process_audio(audio_path):
 
136
  with open(audio_path, "rb") as f:
137
  transcription = openai_client.audio.transcriptions.create(model="whisper-1", file=f)
138
  st.session_state.messages.append({"role": "user", "content": transcription.text})
139
- st.session_state.should_rerun = True
140
  return transcription.text
141
 
142
  def process_video(video_path, seconds_per_frame=1):
@@ -191,6 +200,7 @@ def perform_ai_lookup(q, vocal_summary=True, extended_refs=False, titles_summary
191
 
192
  if vocal_summary:
193
  audio_file_main = speak_with_edge_tts(r2, voice="en-US-AriaNeural", rate=0, pitch=0)
 
194
  st.write("### πŸŽ™οΈ Vocal Summary (Short Answer)")
195
  play_and_download_audio(audio_file_main)
196
 
@@ -259,6 +269,7 @@ def create_zip_of_files():
259
  with zipfile.ZipFile(zip_name,'w') as z:
260
  for f in all_files:
261
  z.write(f)
 
262
  st.session_state.should_rerun = True
263
  return zip_name
264
 
@@ -291,7 +302,6 @@ def display_file_manager_sidebar(files_by_ext):
291
  md_files = files_by_ext.get('md', [])
292
  mp3_files = files_by_ext.get('mp3', [])
293
 
294
- # Delete all buttons
295
  col_del = st.sidebar.columns(2)
296
  with col_del[0]:
297
  if st.button("πŸ—‘ Delete All MD"):
@@ -304,11 +314,9 @@ def display_file_manager_sidebar(files_by_ext):
304
  os.remove(f)
305
  st.session_state.should_rerun = True
306
 
307
- # Sort extensions by number of files descending
308
  ext_counts = {ext: len(files) for ext, files in files_by_ext.items()}
309
  sorted_ext = sorted(files_by_ext.keys(), key=lambda x: ext_counts[x], reverse=True)
310
 
311
- # Display groups
312
  for ext in sorted_ext:
313
  emoji = FILE_EMOJIS.get(ext, "πŸ“¦")
314
  count = len(files_by_ext[ext])
@@ -337,6 +345,7 @@ def display_file_manager_sidebar(files_by_ext):
337
  st.session_state.editing_file = f
338
  st.session_state.edit_new_name = fname.replace(".md","")
339
  st.session_state.edit_new_content = open(f,'r',encoding='utf-8').read()
 
340
  st.session_state.should_rerun = True
341
  else:
342
  pass
@@ -344,9 +353,9 @@ def display_file_manager_sidebar(files_by_ext):
344
  # Delete button
345
  if st.button("πŸ—‘", key="del_"+f):
346
  os.remove(f)
 
347
  st.session_state.should_rerun = True
348
 
349
- # Download all as zip
350
  if (len(md_files) > 0 or len(mp3_files) > 0) and st.sidebar.button("⬇️ Download All (.md and .mp3)"):
351
  z = create_zip_of_files()
352
  st.sidebar.markdown(get_download_link(z),unsafe_allow_html=True)
@@ -366,13 +375,14 @@ def display_file_manager_sidebar(files_by_ext):
366
  with open(new_path,'w',encoding='utf-8') as f:
367
  f.write(st.session_state.edit_new_content)
368
  st.session_state.editing_file = None
 
369
  st.session_state.should_rerun = True
370
  with c2:
371
  if st.button("Cancel"):
372
  st.session_state.editing_file = None
 
373
  st.session_state.should_rerun = True
374
 
375
-
376
  def main():
377
  st.sidebar.markdown("### 🚲BikeAIπŸ† Multi-Agent Research AI")
378
  tab_main = st.radio("Action:",["🎀 Voice Input","πŸ“Έ Media Gallery","πŸ” Search ArXiv","πŸ“ File Editor"],horizontal=True)
@@ -422,8 +432,7 @@ def main():
422
  if q:
423
  q = q.strip()
424
  if q and st.button("Run ArXiv Query"):
425
- r = perform_ai_lookup(q, vocal_summary=vocal_summary, extended_refs=extended_refs, titles_summary=titles_summary)
426
- st.markdown(r)
427
 
428
  elif tab_main == "🎀 Voice Input":
429
  st.subheader("🎀 Voice Recognition")
@@ -490,7 +499,6 @@ def main():
490
  st.write("No videos found.")
491
 
492
  elif tab_main == "πŸ“ File Editor":
493
- # Existing code for inline editing if needed
494
  if getattr(st.session_state,'current_file',None):
495
  st.subheader(f"Editing: {st.session_state.current_file}")
496
  new_text = st.text_area("Content:", st.session_state.file_content, height=300)
@@ -498,15 +506,16 @@ def main():
498
  with open(st.session_state.current_file,'w',encoding='utf-8') as f:
499
  f.write(new_text)
500
  st.success("Updated!")
 
501
  st.session_state.should_rerun = True
502
  else:
503
  st.write("Select a file from the sidebar to edit.")
504
 
505
- # After all main content is processed, load files and display in sidebar
506
  files_by_ext = load_files_for_sidebar()
507
  display_file_manager_sidebar(files_by_ext)
508
 
509
- # If we performed an operation, rerun now at the end
510
  if st.session_state.should_rerun:
511
  st.session_state.should_rerun = False
512
  st.rerun()
 
41
  API_URL = os.getenv('API_URL')
42
 
43
  # Session states
44
+ if 'transcript_history' not in st.session_state:
45
+ st.session_state['transcript_history'] = []
46
+ if 'chat_history' not in st.session_state:
47
+ st.session_state['chat_history'] = []
48
+ if 'openai_model' not in st.session_state:
49
+ st.session_state['openai_model'] = "gpt-4o-2024-05-13"
50
+ if 'messages' not in st.session_state:
51
+ st.session_state['messages'] = []
52
+ if 'last_voice_input' not in st.session_state:
53
+ st.session_state['last_voice_input'] = ""
54
+ if 'editing_file' not in st.session_state:
55
+ st.session_state['editing_file'] = None
56
+ if 'edit_new_name' not in st.session_state:
57
+ st.session_state['edit_new_name'] = ""
58
+ if 'edit_new_content' not in st.session_state:
59
+ st.session_state['edit_new_content'] = ""
60
+ if 'should_rerun' not in st.session_state:
61
+ st.session_state['should_rerun'] = False
62
 
63
  # 🎨 Minimal Custom CSS
64
  st.markdown("""
 
84
  return f"{date_str}_{safe}.{file_type}"
85
 
86
  def create_file(filename, prompt, response):
87
+ # Just create the file. Do not rerun automatically here.
88
  with open(filename, 'w', encoding='utf-8') as f:
89
  f.write(prompt + "\n\n" + response)
 
90
 
91
  def get_download_link(file):
92
  with open(file, "rb") as f:
 
106
  components.html(html_code, height=0)
107
 
108
  async def edge_tts_generate_audio(text, voice="en-US-AriaNeural", rate=0, pitch=0):
109
+ # Create mp3 file. Do not trigger rerun here.
110
  if not text.strip():
111
  return None
112
  rate_str = f"{rate:+d}%"
 
114
  communicate = edge_tts.Communicate(text, voice, rate=rate_str, pitch=pitch_str)
115
  out_fn = generate_filename(text,"mp3")
116
  await communicate.save(out_fn)
 
117
  return out_fn
118
 
119
  def speak_with_edge_tts(text, voice="en-US-AriaNeural", rate=0, pitch=0):
 
142
  return resp.choices[0].message.content
143
 
144
  def process_audio(audio_path):
145
+ # Creating transcription does not force rerun here.
146
  with open(audio_path, "rb") as f:
147
  transcription = openai_client.audio.transcriptions.create(model="whisper-1", file=f)
148
  st.session_state.messages.append({"role": "user", "content": transcription.text})
 
149
  return transcription.text
150
 
151
  def process_video(video_path, seconds_per_frame=1):
 
200
 
201
  if vocal_summary:
202
  audio_file_main = speak_with_edge_tts(r2, voice="en-US-AriaNeural", rate=0, pitch=0)
203
+ # audio_file_main is created but we do not rerun
204
  st.write("### πŸŽ™οΈ Vocal Summary (Short Answer)")
205
  play_and_download_audio(audio_file_main)
206
 
 
269
  with zipfile.ZipFile(zip_name,'w') as z:
270
  for f in all_files:
271
  z.write(f)
272
+ # user action triggered, set rerun
273
  st.session_state.should_rerun = True
274
  return zip_name
275
 
 
302
  md_files = files_by_ext.get('md', [])
303
  mp3_files = files_by_ext.get('mp3', [])
304
 
 
305
  col_del = st.sidebar.columns(2)
306
  with col_del[0]:
307
  if st.button("πŸ—‘ Delete All MD"):
 
314
  os.remove(f)
315
  st.session_state.should_rerun = True
316
 
 
317
  ext_counts = {ext: len(files) for ext, files in files_by_ext.items()}
318
  sorted_ext = sorted(files_by_ext.keys(), key=lambda x: ext_counts[x], reverse=True)
319
 
 
320
  for ext in sorted_ext:
321
  emoji = FILE_EMOJIS.get(ext, "πŸ“¦")
322
  count = len(files_by_ext[ext])
 
345
  st.session_state.editing_file = f
346
  st.session_state.edit_new_name = fname.replace(".md","")
347
  st.session_state.edit_new_content = open(f,'r',encoding='utf-8').read()
348
+ # user triggered, set rerun
349
  st.session_state.should_rerun = True
350
  else:
351
  pass
 
353
  # Delete button
354
  if st.button("πŸ—‘", key="del_"+f):
355
  os.remove(f)
356
+ # user triggered, set rerun
357
  st.session_state.should_rerun = True
358
 
 
359
  if (len(md_files) > 0 or len(mp3_files) > 0) and st.sidebar.button("⬇️ Download All (.md and .mp3)"):
360
  z = create_zip_of_files()
361
  st.sidebar.markdown(get_download_link(z),unsafe_allow_html=True)
 
375
  with open(new_path,'w',encoding='utf-8') as f:
376
  f.write(st.session_state.edit_new_content)
377
  st.session_state.editing_file = None
378
+ # user triggered, set rerun
379
  st.session_state.should_rerun = True
380
  with c2:
381
  if st.button("Cancel"):
382
  st.session_state.editing_file = None
383
+ # user triggered, set rerun
384
  st.session_state.should_rerun = True
385
 
 
386
  def main():
387
  st.sidebar.markdown("### 🚲BikeAIπŸ† Multi-Agent Research AI")
388
  tab_main = st.radio("Action:",["🎀 Voice Input","πŸ“Έ Media Gallery","πŸ” Search ArXiv","πŸ“ File Editor"],horizontal=True)
 
432
  if q:
433
  q = q.strip()
434
  if q and st.button("Run ArXiv Query"):
435
+ perform_ai_lookup(q, vocal_summary=vocal_summary, extended_refs=extended_refs, titles_summary=titles_summary)
 
436
 
437
  elif tab_main == "🎀 Voice Input":
438
  st.subheader("🎀 Voice Recognition")
 
499
  st.write("No videos found.")
500
 
501
  elif tab_main == "πŸ“ File Editor":
 
502
  if getattr(st.session_state,'current_file',None):
503
  st.subheader(f"Editing: {st.session_state.current_file}")
504
  new_text = st.text_area("Content:", st.session_state.file_content, height=300)
 
506
  with open(st.session_state.current_file,'w',encoding='utf-8') as f:
507
  f.write(new_text)
508
  st.success("Updated!")
509
+ # user action: rename or save
510
  st.session_state.should_rerun = True
511
  else:
512
  st.write("Select a file from the sidebar to edit.")
513
 
514
+ # After main content, load files and display in sidebar
515
  files_by_ext = load_files_for_sidebar()
516
  display_file_manager_sidebar(files_by_ext)
517
 
518
+ # If user triggered changes require a rerun, do it now
519
  if st.session_state.should_rerun:
520
  st.session_state.should_rerun = False
521
  st.rerun()