awacke1 commited on
Commit
c491bcc
โ€ข
1 Parent(s): 8010524

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -63
app.py CHANGED
@@ -67,6 +67,9 @@ if 'viewing_prefix' not in st.session_state:
67
  st.session_state['viewing_prefix'] = None
68
  if 'should_rerun' not in st.session_state:
69
  st.session_state['should_rerun'] = False
 
 
 
70
 
71
  # ๐ŸŽจ Minimal Custom CSS
72
  st.markdown("""
@@ -94,21 +97,14 @@ def clean_for_speech(text: str) -> str:
94
  return text
95
 
96
  def generate_filename(content, file_type="md"):
97
- # Prefix: YYMM_HHmm_ -> total 10 chars including underscore
98
- # Actually: %y%m_%H%M gives 9 chars, add trailing underscore for total 10 chars.
99
- # Example: 23 09 _12 45 _ => '2309_1245_'
100
  prefix = datetime.now().strftime("%y%m_%H%M") + "_"
101
- # Extract some words from content
102
  words = re.findall(r"\w+", content)
103
- # Take first 3 words for filename segment
104
  name_text = '_'.join(words[:3]) if words else 'file'
105
  filename = f"{prefix}{name_text}.{file_type}"
106
  return filename
107
 
108
  def create_file(prompt, response, file_type="md"):
109
- # Decide which content to base the filename on (prefer response)
110
- base_content = response.strip() if response.strip() else prompt.strip()
111
- filename = generate_filename(base_content, file_type)
112
  with open(filename, 'w', encoding='utf-8') as f:
113
  f.write(prompt + "\n\n" + response)
114
  return filename
@@ -252,7 +248,7 @@ def perform_ai_lookup(q, vocal_summary=True, extended_refs=False, titles_summary
252
 
253
  elapsed = time.time()-start
254
  st.write(f"**Total Elapsed:** {elapsed:.2f} s")
255
- # Create MD file from q and result
256
  create_file(q, result, "md")
257
  return result
258
 
@@ -269,6 +265,7 @@ def process_with_gpt(text):
269
  )
270
  ans = c.choices[0].message.content
271
  st.write("GPT-4o: " + ans)
 
272
  create_file(text, ans, "md")
273
  st.session_state.messages.append({"role":"assistant","content":ans})
274
  return ans
@@ -285,6 +282,7 @@ def process_with_claude(text):
285
  )
286
  ans = r.content[0].text
287
  st.write("Claude: " + ans)
 
288
  create_file(text, ans, "md")
289
  st.session_state.chat_history.append({"user":text,"claude":ans})
290
  return ans
@@ -295,7 +293,6 @@ def create_zip_of_files(md_files, mp3_files):
295
  all_files = md_files + mp3_files
296
  if not all_files:
297
  return None
298
- # Build a descriptive name
299
  stems = [os.path.splitext(os.path.basename(f))[0] for f in all_files]
300
  joined = "_".join(stems)
301
  if len(joined) > 50:
@@ -307,7 +304,6 @@ def create_zip_of_files(md_files, mp3_files):
307
  return zip_name
308
 
309
  def load_files_for_sidebar():
310
- # Gather files
311
  md_files = glob.glob("*.md")
312
  mp3_files = glob.glob("*.mp3")
313
 
@@ -316,30 +312,25 @@ def load_files_for_sidebar():
316
 
317
  all_files = md_files + mp3_files
318
 
319
- # Group by first 10 chars of filename
320
  groups = defaultdict(list)
321
  for f in all_files:
322
  fname = os.path.basename(f)
323
  prefix = fname[:10] # first 10 chars as group prefix
324
  groups[prefix].append(f)
325
 
326
- # Sort files in each group by mod time descending
327
  for prefix in groups:
328
  groups[prefix].sort(key=lambda x: os.path.getmtime(x), reverse=True)
329
 
330
- # Sort prefixes by newest file time
331
  sorted_prefixes = sorted(groups.keys(), key=lambda pre: max(os.path.getmtime(x) for x in groups[pre]), reverse=True)
332
 
333
  return groups, sorted_prefixes
334
 
335
  def extract_keywords_from_md(files):
336
- # Combine all MD content
337
  text = ""
338
  for f in files:
339
  if f.endswith(".md"):
340
  c = open(f,'r',encoding='utf-8').read()
341
  text += " " + c
342
- # Extract first 5 unique words
343
  words = re.findall(r"\w+", text.lower())
344
  unique_words = []
345
  for w in words:
@@ -352,7 +343,6 @@ def extract_keywords_from_md(files):
352
  def display_file_manager_sidebar(groups, sorted_prefixes):
353
  st.sidebar.title("๐ŸŽต Audio & Document Manager")
354
 
355
- # Collect all md and mp3 files for zip operations
356
  all_md = []
357
  all_mp3 = []
358
  for prefix in groups:
@@ -381,34 +371,25 @@ def display_file_manager_sidebar(groups, sorted_prefixes):
381
 
382
  for prefix in sorted_prefixes:
383
  files = groups[prefix]
384
- # Extract 5-word keywords from MD in this group
385
  kw = extract_keywords_from_md(files)
386
  keywords_str = " ".join(kw) if kw else "No Keywords"
387
  with st.sidebar.expander(f"{prefix} Files ({len(files)}) - Keywords: {keywords_str}", expanded=True):
388
- # Delete group / View group
389
  c1,c2 = st.columns(2)
390
  with c1:
391
  if st.button("๐Ÿ‘€View Group", key="view_group_"+prefix):
392
  st.session_state.viewing_prefix = prefix
393
- # No rerun needed, just state update
394
  with c2:
395
  if st.button("๐Ÿ—‘Del Group", key="del_group_"+prefix):
396
  for f in files:
397
  os.remove(f)
 
 
398
  st.session_state.should_rerun = True
399
 
400
  for f in files:
401
  fname = os.path.basename(f)
402
  ctime = datetime.fromtimestamp(os.path.getmtime(f)).strftime("%Y-%m-%d %H:%M:%S")
403
- ext = os.path.splitext(fname)[1].lower().strip('.')
404
  st.write(f"**{fname}** - {ctime}")
405
- # Individual file actions are less necessary if we have group actions
406
- # But we can still provide them if desired.
407
- # The user requested grouping primarily, but we can keep minimal file actions if needed.
408
- # In instructions now, main focus is group view/delete.
409
- # We'll omit individual file view/edit here since we have group view.
410
- # If needed, re-add them similarly as before.
411
- # For now, rely on "View Group" to see all files.
412
 
413
  def main():
414
  st.sidebar.markdown("### ๐ŸšฒBikeAI๐Ÿ† Multi-Agent Research AI")
@@ -418,36 +399,41 @@ def main():
418
 
419
  mycomponent = components.declare_component("mycomponent", path="mycomponent")
420
  val = mycomponent(my_input_value="Hello")
 
 
421
  if val:
422
- user_input = val.strip()
423
- if user_input:
424
- if model_choice == "GPT-4o":
425
- process_with_gpt(user_input)
426
- elif model_choice == "Claude-3":
427
- process_with_claude(user_input)
428
- elif model_choice == "Arxiv":
429
- st.subheader("Arxiv Only Results:")
430
- perform_ai_lookup(user_input, vocal_summary=True, extended_refs=False, titles_summary=True)
431
- else:
432
- col1,col2,col3=st.columns(3)
433
- with col1:
434
- st.subheader("GPT-4o Omni:")
435
- try:
436
- process_with_gpt(user_input)
437
- except:
438
- st.write('GPT 4o error')
439
- with col2:
440
- st.subheader("Claude-3 Sonnet:")
441
- try:
442
- process_with_claude(user_input)
443
- except:
444
- st.write('Claude error')
445
- with col3:
446
- st.subheader("Arxiv + Mistral:")
447
- try:
448
- perform_ai_lookup(user_input, vocal_summary=True, extended_refs=False, titles_summary=True)
449
- except:
450
- st.write("Arxiv error")
 
 
 
451
 
452
  if tab_main == "๐Ÿ” Search ArXiv":
453
  st.subheader("๐Ÿ” Search ArXiv")
@@ -518,7 +504,7 @@ def main():
518
  if vids:
519
  for v in vids:
520
  with st.expander(f"๐ŸŽฅ {os.path.basename(v)}"):
521
- st.markdown(get_media_html(v,"video"),unsafe_allow_html=True)
522
  if st.button(f"Analyze {os.path.basename(v)}", key=f"analyze_{v}"):
523
  a = process_video_with_gpt(v,"Describe video.")
524
  st.markdown(a)
@@ -537,16 +523,12 @@ def main():
537
  else:
538
  st.write("Select a file from the sidebar to edit.")
539
 
540
- # After main content, load and show file groups in sidebar
541
  groups, sorted_prefixes = load_files_for_sidebar()
542
  display_file_manager_sidebar(groups, sorted_prefixes)
543
 
544
- # If viewing a prefix group, show all files in main area
545
  if st.session_state.viewing_prefix and st.session_state.viewing_prefix in groups:
546
  st.write("---")
547
  st.write(f"**Viewing Group:** {st.session_state.viewing_prefix}")
548
- # Show all files in this prefix group in order (mp3 and md)
549
- # Sort by mod time descending (already sorted)
550
  for f in groups[st.session_state.viewing_prefix]:
551
  fname = os.path.basename(f)
552
  ext = os.path.splitext(fname)[1].lower().strip('.')
@@ -557,7 +539,6 @@ def main():
557
  elif ext == "mp3":
558
  st.audio(f)
559
  else:
560
- # just show a download link
561
  st.markdown(get_download_link(f), unsafe_allow_html=True)
562
  if st.button("Close Group View"):
563
  st.session_state.viewing_prefix = None
 
67
  st.session_state['viewing_prefix'] = None
68
  if 'should_rerun' not in st.session_state:
69
  st.session_state['should_rerun'] = False
70
+ # CHANGED LINE: Track old input from mycomponent to avoid recreating files on rerun
71
+ if 'old_val' not in st.session_state:
72
+ st.session_state['old_val'] = None
73
 
74
  # ๐ŸŽจ Minimal Custom CSS
75
  st.markdown("""
 
97
  return text
98
 
99
  def generate_filename(content, file_type="md"):
 
 
 
100
  prefix = datetime.now().strftime("%y%m_%H%M") + "_"
 
101
  words = re.findall(r"\w+", content)
 
102
  name_text = '_'.join(words[:3]) if words else 'file'
103
  filename = f"{prefix}{name_text}.{file_type}"
104
  return filename
105
 
106
  def create_file(prompt, response, file_type="md"):
107
+ filename = generate_filename(response.strip() if response.strip() else prompt.strip(), file_type)
 
 
108
  with open(filename, 'w', encoding='utf-8') as f:
109
  f.write(prompt + "\n\n" + response)
110
  return filename
 
248
 
249
  elapsed = time.time()-start
250
  st.write(f"**Total Elapsed:** {elapsed:.2f} s")
251
+ # CHANGED LINE: Only create a file after explicit user action is taken (already covered by button triggers)
252
  create_file(q, result, "md")
253
  return result
254
 
 
265
  )
266
  ans = c.choices[0].message.content
267
  st.write("GPT-4o: " + ans)
268
+ # CHANGED LINE: create_file is safe here since it's triggered by a user action button
269
  create_file(text, ans, "md")
270
  st.session_state.messages.append({"role":"assistant","content":ans})
271
  return ans
 
282
  )
283
  ans = r.content[0].text
284
  st.write("Claude: " + ans)
285
+ # CHANGED LINE: create_file only after button press/user action
286
  create_file(text, ans, "md")
287
  st.session_state.chat_history.append({"user":text,"claude":ans})
288
  return ans
 
293
  all_files = md_files + mp3_files
294
  if not all_files:
295
  return None
 
296
  stems = [os.path.splitext(os.path.basename(f))[0] for f in all_files]
297
  joined = "_".join(stems)
298
  if len(joined) > 50:
 
304
  return zip_name
305
 
306
  def load_files_for_sidebar():
 
307
  md_files = glob.glob("*.md")
308
  mp3_files = glob.glob("*.mp3")
309
 
 
312
 
313
  all_files = md_files + mp3_files
314
 
 
315
  groups = defaultdict(list)
316
  for f in all_files:
317
  fname = os.path.basename(f)
318
  prefix = fname[:10] # first 10 chars as group prefix
319
  groups[prefix].append(f)
320
 
 
321
  for prefix in groups:
322
  groups[prefix].sort(key=lambda x: os.path.getmtime(x), reverse=True)
323
 
 
324
  sorted_prefixes = sorted(groups.keys(), key=lambda pre: max(os.path.getmtime(x) for x in groups[pre]), reverse=True)
325
 
326
  return groups, sorted_prefixes
327
 
328
  def extract_keywords_from_md(files):
 
329
  text = ""
330
  for f in files:
331
  if f.endswith(".md"):
332
  c = open(f,'r',encoding='utf-8').read()
333
  text += " " + c
 
334
  words = re.findall(r"\w+", text.lower())
335
  unique_words = []
336
  for w in words:
 
343
  def display_file_manager_sidebar(groups, sorted_prefixes):
344
  st.sidebar.title("๐ŸŽต Audio & Document Manager")
345
 
 
346
  all_md = []
347
  all_mp3 = []
348
  for prefix in groups:
 
371
 
372
  for prefix in sorted_prefixes:
373
  files = groups[prefix]
 
374
  kw = extract_keywords_from_md(files)
375
  keywords_str = " ".join(kw) if kw else "No Keywords"
376
  with st.sidebar.expander(f"{prefix} Files ({len(files)}) - Keywords: {keywords_str}", expanded=True):
 
377
  c1,c2 = st.columns(2)
378
  with c1:
379
  if st.button("๐Ÿ‘€View Group", key="view_group_"+prefix):
380
  st.session_state.viewing_prefix = prefix
 
381
  with c2:
382
  if st.button("๐Ÿ—‘Del Group", key="del_group_"+prefix):
383
  for f in files:
384
  os.remove(f)
385
+ # CHANGED LINE: Show success message after deletion
386
+ st.success(f"Deleted all files in group {prefix} successfully!")
387
  st.session_state.should_rerun = True
388
 
389
  for f in files:
390
  fname = os.path.basename(f)
391
  ctime = datetime.fromtimestamp(os.path.getmtime(f)).strftime("%Y-%m-%d %H:%M:%S")
 
392
  st.write(f"**{fname}** - {ctime}")
 
 
 
 
 
 
 
393
 
394
  def main():
395
  st.sidebar.markdown("### ๐ŸšฒBikeAI๐Ÿ† Multi-Agent Research AI")
 
399
 
400
  mycomponent = components.declare_component("mycomponent", path="mycomponent")
401
  val = mycomponent(my_input_value="Hello")
402
+
403
+ # CHANGED BLOCK: Wrap processing val in a button to avoid re-creation on rerun
404
  if val:
405
+ st.write("**Input Detected:**", val)
406
+ if st.button("Process Input"):
407
+ # Only process if val is new
408
+ if val != st.session_state.old_val:
409
+ st.session_state.old_val = val
410
+ if model_choice == "GPT-4o":
411
+ process_with_gpt(val)
412
+ elif model_choice == "Claude-3":
413
+ process_with_claude(val)
414
+ elif model_choice == "Arxiv":
415
+ st.subheader("Arxiv Only Results:")
416
+ perform_ai_lookup(val, vocal_summary=True, extended_refs=False, titles_summary=True)
417
+ else:
418
+ col1,col2,col3=st.columns(3)
419
+ with col1:
420
+ st.subheader("GPT-4o Omni:")
421
+ try:
422
+ process_with_gpt(val)
423
+ except:
424
+ st.write('GPT 4o error')
425
+ with col2:
426
+ st.subheader("Claude-3 Sonnet:")
427
+ try:
428
+ process_with_claude(val)
429
+ except:
430
+ st.write('Claude error')
431
+ with col3:
432
+ st.subheader("Arxiv + Mistral:")
433
+ try:
434
+ perform_ai_lookup(val, vocal_summary=True, extended_refs=False, titles_summary=True)
435
+ except:
436
+ st.write("Arxiv error")
437
 
438
  if tab_main == "๐Ÿ” Search ArXiv":
439
  st.subheader("๐Ÿ” Search ArXiv")
 
504
  if vids:
505
  for v in vids:
506
  with st.expander(f"๐ŸŽฅ {os.path.basename(v)}"):
507
+ st.video(v)
508
  if st.button(f"Analyze {os.path.basename(v)}", key=f"analyze_{v}"):
509
  a = process_video_with_gpt(v,"Describe video.")
510
  st.markdown(a)
 
523
  else:
524
  st.write("Select a file from the sidebar to edit.")
525
 
 
526
  groups, sorted_prefixes = load_files_for_sidebar()
527
  display_file_manager_sidebar(groups, sorted_prefixes)
528
 
 
529
  if st.session_state.viewing_prefix and st.session_state.viewing_prefix in groups:
530
  st.write("---")
531
  st.write(f"**Viewing Group:** {st.session_state.viewing_prefix}")
 
 
532
  for f in groups[st.session_state.viewing_prefix]:
533
  fname = os.path.basename(f)
534
  ext = os.path.splitext(fname)[1].lower().strip('.')
 
539
  elif ext == "mp3":
540
  st.audio(f)
541
  else:
 
542
  st.markdown(get_download_link(f), unsafe_allow_html=True)
543
  if st.button("Close Group View"):
544
  st.session_state.viewing_prefix = None