awacke1 commited on
Commit
151d32d
Β·
verified Β·
1 Parent(s): 88e04a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -93
app.py CHANGED
@@ -499,15 +499,16 @@ def display_saved_files_in_sidebar():
499
  st.rerun()
500
 
501
 
502
-
503
-
504
 
505
 
506
- # 🎭 Main function - Where the magic happens (and occasionally breaks)
 
507
  def main():
508
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
509
 
510
- # 🚦 Initialize session state
 
 
511
  if 'logged_in' not in st.session_state:
512
  st.session_state.logged_in = False
513
  if 'selected_records' not in st.session_state:
@@ -525,19 +526,18 @@ def main():
525
  if 'cloned_doc' not in st.session_state:
526
  st.session_state.cloned_doc = None
527
 
528
- # βš™οΈ q= Run ArXiv search from query parameters
 
 
529
  try:
530
  query_params = st.query_params
531
  query = query_params.get('q') or query_params.get('query') or ''
532
  if query:
533
- # πŸ•΅οΈβ€β™‚οΈ We have a query! Let's process it!
534
  result, result2, result3, response2 = search_glossary(query)
535
- # When saving results, pass the container
 
536
  try:
537
- # πŸ“ Automatically save the AI-generated content
538
  if st.button("Save AI Output"):
539
-
540
- # πŸ•΅οΈβ€β™‚οΈ Save our nice research summaries for later sleuthing
541
  filename = create_file_from_content(result)
542
  st.success(f"File saved: {filename}")
543
  filename = create_file_from_content(result2)
@@ -547,14 +547,11 @@ def main():
547
  filename = create_file_from_content(response2)
548
  st.success(f"File saved: {filename}")
549
 
550
- #st.rerun() # Rerun the app to update the sidebar
551
-
552
- # πŸ“ Display saved markdown files in the sidebar
553
  display_saved_files_in_sidebar()
554
  except Exception as e:
555
  st.error(f"An unexpected error occurred: {str(e)} 😱")
556
 
557
-
558
  try:
559
  save_to_cosmos_db(st.session_state.cosmos_container, query, result, result)
560
  save_to_cosmos_db(st.session_state.cosmos_container, query, result2, result2)
@@ -566,42 +563,52 @@ def main():
566
  except Exception as e:
567
  st.error(f"An unexpected error occurred: {str(e)} 😱")
568
 
569
- st.stop() # Stop further execution
570
  except Exception as e:
571
  st.markdown(' ')
572
 
573
- # πŸ” Automatic Login
 
 
574
  if Key:
575
  st.session_state.primary_key = Key
576
  st.session_state.logged_in = True
577
  else:
578
  st.error("Cosmos DB Key is not set in environment variables. πŸ”‘βŒ")
579
- return # Can't proceed without a key
 
580
 
 
581
  if st.session_state.logged_in:
582
- # 🌌 Initialize Cosmos DB client
583
  try:
584
  if st.session_state.client is None:
585
  st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
586
 
587
- # πŸ—„οΈ Sidebar for database, container, and document selection
588
  st.sidebar.title("πŸ™Git🌌CosmosπŸ’«πŸ—„οΈNavigator")
589
 
590
  databases = get_databases(st.session_state.client)
591
  selected_db = st.sidebar.selectbox("πŸ—ƒοΈ Select Database", databases)
 
 
592
 
 
593
  if selected_db != st.session_state.selected_database:
594
  st.session_state.selected_database = selected_db
595
  st.session_state.selected_container = None
596
  st.session_state.selected_document_id = None
597
  st.session_state.current_index = 0
598
  st.rerun()
599
-
 
 
600
  if st.session_state.selected_database:
601
  database = st.session_state.client.get_database_client(st.session_state.selected_database)
602
  containers = get_containers(database)
603
  selected_container = st.sidebar.selectbox("πŸ“ Select Container", containers)
604
 
 
605
  if selected_container != st.session_state.selected_container:
606
  st.session_state.selected_container = selected_container
607
  st.session_state.selected_document_id = None
@@ -611,15 +618,19 @@ def main():
611
  if st.session_state.selected_container:
612
  container = database.get_container_client(st.session_state.selected_container)
613
 
614
- # πŸ“¦ Add Export button
615
  if st.button("πŸ“¦ Export Container Data"):
616
- download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
 
 
617
  if download_link.startswith('<a'):
618
  st.markdown(download_link, unsafe_allow_html=True)
619
  else:
620
  st.error(download_link)
 
 
621
 
622
- # Fetch documents
623
  documents = get_documents(container)
624
  total_docs = len(documents)
625
 
@@ -631,17 +642,18 @@ def main():
631
  st.info(f"Showing all {len(documents_to_display)} documents.")
632
 
633
  if documents_to_display:
634
- # 🎨 Add Viewer/Editor selection
635
- view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
 
636
  selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
637
 
 
638
  if selected_view == 'Show as Markdown':
639
- # πŸ–ŒοΈ Show each record as Markdown with navigation
640
  total_docs = len(documents)
641
  doc = documents[st.session_state.current_index]
642
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
643
 
644
- # πŸ•΅οΈβ€β™‚οΈ Let's extract values from the JSON that have at least one space
645
  values_with_space = []
646
  def extract_values(obj):
647
  if isinstance(obj, dict):
@@ -655,17 +667,16 @@ def main():
655
  values_with_space.append(obj)
656
 
657
  extract_values(doc)
658
-
659
- # πŸ”— Let's create a list of links for these values
660
  st.markdown("#### πŸ”— Links for Extracted Texts")
661
  for term in values_with_space:
662
  display_glossary_entity(term)
663
 
664
- # Show the document content as markdown
665
  content = json.dumps(doc, indent=2)
666
  st.markdown(f"```json\n{content}\n```")
667
 
668
- # Navigation buttons
 
 
669
  col_prev, col_next = st.columns([1, 1])
670
  with col_prev:
671
  if st.button("⬅️ Previous", key='prev_markdown'):
@@ -678,12 +689,21 @@ def main():
678
  st.session_state.current_index += 1
679
  st.rerun()
680
 
 
 
 
681
  elif selected_view == 'Show as Code Editor':
682
- # πŸ’» Show each record in a code editor with navigation
683
  total_docs = len(documents)
684
  doc = documents[st.session_state.current_index]
685
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
686
- doc_str = st.text_area("Edit Document", value=json.dumps(doc, indent=2), height=300, key=f'code_editor_{st.session_state.current_index}')
 
 
 
 
 
 
 
687
  col_prev, col_next = st.columns([1, 1])
688
  with col_prev:
689
  if st.button("⬅️ Previous", key='prev_code'):
@@ -695,6 +715,10 @@ def main():
695
  if st.session_state.current_index < total_docs - 1:
696
  st.session_state.current_index += 1
697
  st.rerun()
 
 
 
 
698
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{st.session_state.current_index}'):
699
  try:
700
  updated_doc = json.loads(doc_str)
@@ -707,31 +731,39 @@ def main():
707
  st.error(message)
708
  except json.JSONDecodeError as e:
709
  st.error(f"Invalid JSON: {str(e)} 🚫")
 
 
710
 
 
711
  elif selected_view == 'Show as Edit and Save':
712
- # ✏️ Show as Edit and Save in columns
713
  st.markdown("#### Edit the document fields below:")
714
 
715
- # Create columns for each document
716
  num_cols = len(documents_to_display)
717
  cols = st.columns(num_cols)
718
 
 
 
719
  for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
720
  with col:
721
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
722
- editable_id = st.text_input("ID", value=doc.get('id', ''), key=f'edit_id_{idx}')
723
- # Remove 'id' from the document for editing other fields
724
  editable_doc = doc.copy()
725
  editable_doc.pop('id', None)
726
- doc_str = st.text_area("Document Content (in JSON format)", value=json.dumps(editable_doc, indent=2), height=300, key=f'doc_str_{idx}')
 
 
 
 
 
727
 
728
- # Add the "Run With AI" button next to "Save Changes"
729
  col_save, col_ai = st.columns(2)
730
  with col_save:
731
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{idx}'):
732
  try:
733
  updated_doc = json.loads(doc_str)
734
- updated_doc['id'] = editable_id # Include the possibly edited ID
735
  success, message = update_record(container, updated_doc)
736
  if success:
737
  st.success(f"Document {updated_doc['id']} saved successfully.")
@@ -741,28 +773,30 @@ def main():
741
  st.error(message)
742
  except json.JSONDecodeError as e:
743
  st.error(f"Invalid JSON: {str(e)} 🚫")
 
 
744
  with col_ai:
745
  if st.button("πŸ€– Run With AI", key=f'run_with_ai_button_{idx}'):
746
- # Use the entire document as input
747
  search_glossary(json.dumps(editable_doc, indent=2))
748
- # Usage in your Streamlit app
749
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
750
  with st.spinner("Cloning document..."):
751
- cloned_id = save_or_clone_to_cosmos_db(container, clone_id=doc['id'])
 
752
  if cloned_id:
753
  st.success(f"Document cloned successfully with new ID: {cloned_id}")
754
  st.rerun()
755
  else:
756
  st.error("Failed to clone document. Please try again.")
757
 
 
 
 
758
  elif selected_view == 'Clone Document':
759
- # 🧬 Clone Document per record
760
  st.markdown("#### Clone a document:")
761
  for idx, doc in enumerate(documents_to_display):
762
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
763
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
764
  cloned_doc = doc.copy()
765
- # Generate a unique ID
766
  cloned_doc['id'] = generate_unique_id()
767
  st.session_state.cloned_doc = cloned_doc
768
  st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
@@ -770,7 +804,11 @@ def main():
770
  st.rerun()
771
  if st.session_state.get('clone_mode', False):
772
  st.markdown("#### Edit Cloned Document and Name Your Clone:")
773
- cloned_doc_str = st.text_area("Cloned Document Content (in JSON format) - Update name please to make it unique before saving!", value=st.session_state.cloned_doc_str, height=300)
 
 
 
 
774
  if st.button("πŸ’Ύ Save Cloned Document"):
775
  try:
776
  new_doc = json.loads(cloned_doc_str)
@@ -778,47 +816,53 @@ def main():
778
  if success:
779
  st.success(f"Cloned document saved with id: {new_doc['id']} πŸŽ‰")
780
  st.session_state.selected_document_id = new_doc['id']
781
- st.session_state.clone_mode = False
782
- st.session_state.cloned_doc = None
783
- st.session_state.cloned_doc_str = ''
784
- st.rerun()
785
- else:
786
- st.error(message)
787
- except json.JSONDecodeError as e:
788
- st.error(f"Invalid JSON: {str(e)} 🚫")
789
-
790
- elif selected_view == 'New Record':
791
- # πŸ†• New Record
792
- st.markdown("#### Create a new document:")
793
- if st.button("πŸ€– Insert Auto-Generated Record"):
794
- success, message = save_or_clone_to_cosmos_db(container, query="Auto-generated", response="This is an auto-generated record.")
795
- if success:
796
- st.success(message)
797
- st.rerun()
 
 
 
 
 
 
798
  else:
799
- st.error(message)
800
- else:
801
- new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
802
- new_doc_str = st.text_area("Document Content (in JSON format)", value='{}', height=300)
803
- if st.button("βž• Create New Document"):
804
- try:
805
- new_doc = json.loads(new_doc_str)
806
- new_doc['id'] = new_id # Use the provided ID
807
- success, message = insert_record(container, new_doc)
808
- if success:
809
- st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
810
- st.session_state.selected_document_id = new_doc['id']
811
- # Switch to 'Show as Edit and Save' mode
812
- st.rerun()
813
- else:
814
- st.error(message)
815
- except json.JSONDecodeError as e:
816
- st.error(f"Invalid JSON: {str(e)} 🚫")
817
 
818
  else:
819
  st.sidebar.info("No documents found in this container. πŸ“­")
820
-
821
- # πŸŽ‰ Main content area
 
 
822
  st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
823
  if st.session_state.selected_container:
824
  if documents_to_display:
@@ -826,13 +870,19 @@ def main():
826
  st.dataframe(df)
827
  else:
828
  st.info("No documents to display. 🧐")
 
 
829
 
830
- # πŸ™ GitHub section
831
  st.subheader("πŸ™ GitHub Operations")
832
- github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
833
- source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
834
- new_repo_name = st.text_input("New Repository Name (for cloning)", value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
 
 
 
835
 
 
836
  col1, col2 = st.columns(2)
837
  with col1:
838
  if st.button("πŸ“₯ Clone Repository"):
@@ -853,7 +903,9 @@ def main():
853
  os.remove(zip_filename)
854
  else:
855
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
856
-
 
 
857
  with col2:
858
  if st.button("πŸ“€ Push to New Repository"):
859
  if github_token and source_repo:
@@ -872,7 +924,9 @@ def main():
872
  else:
873
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
874
 
875
- # πŸ’¬ Chat with Claude
 
 
876
  st.subheader("πŸ’¬ Chat with Claude")
877
  user_input = st.text_area("Message πŸ“¨:", height=100)
878
 
@@ -896,14 +950,18 @@ def main():
896
  # Save to Cosmos DB
897
  save_to_cosmos_db(container, user_input, response.content[0].text, "")
898
 
899
- # Display Chat History
 
 
900
  st.subheader("Past Conversations πŸ“œ")
901
  for chat in st.session_state.chat_history:
902
  st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
903
  st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
904
  st.markdown("---")
905
 
906
- # File Editor
 
 
907
  if hasattr(st.session_state, 'current_file'):
908
  st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
909
  new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
@@ -912,7 +970,9 @@ def main():
912
  file.write(new_content)
913
  st.success("File updated successfully! πŸŽ‰")
914
 
915
- # File Management
 
 
916
  st.sidebar.title("πŸ“ File Management")
917
 
918
  all_files = glob.glob("*.md")
@@ -944,12 +1004,16 @@ def main():
944
  os.remove(file)
945
  st.rerun()
946
 
 
 
947
  except exceptions.CosmosHttpResponseError as e:
948
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
949
  except Exception as e:
950
  st.error(f"An unexpected error occurred: {str(e)} 😱")
951
 
952
- # πŸšͺ Logout button
 
 
953
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
954
  st.session_state.logged_in = False
955
  st.session_state.selected_records.clear()
 
499
  st.rerun()
500
 
501
 
 
 
502
 
503
 
504
+
505
+ # 🎭 Main function - "All the world's a stage, and all the code merely players" -Shakespeare, probably
506
  def main():
507
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
508
 
509
+
510
+
511
+ # 🎲 Session state vars - "Life is like a session state, you never know what you're gonna get"
512
  if 'logged_in' not in st.session_state:
513
  st.session_state.logged_in = False
514
  if 'selected_records' not in st.session_state:
 
526
  if 'cloned_doc' not in st.session_state:
527
  st.session_state.cloned_doc = None
528
 
529
+
530
+
531
+ # πŸ” Query processing - "To search or not to search, that is the query"
532
  try:
533
  query_params = st.query_params
534
  query = query_params.get('q') or query_params.get('query') or ''
535
  if query:
 
536
  result, result2, result3, response2 = search_glossary(query)
537
+
538
+ # πŸ’Ύ Save results - "Every file you save is a future you pave"
539
  try:
 
540
  if st.button("Save AI Output"):
 
 
541
  filename = create_file_from_content(result)
542
  st.success(f"File saved: {filename}")
543
  filename = create_file_from_content(result2)
 
547
  filename = create_file_from_content(response2)
548
  st.success(f"File saved: {filename}")
549
 
 
 
 
550
  display_saved_files_in_sidebar()
551
  except Exception as e:
552
  st.error(f"An unexpected error occurred: {str(e)} 😱")
553
 
554
+ # 🌟 Cosmos DB operations - "In Cosmos DB we trust, but we still handle errors we must"
555
  try:
556
  save_to_cosmos_db(st.session_state.cosmos_container, query, result, result)
557
  save_to_cosmos_db(st.session_state.cosmos_container, query, result2, result2)
 
563
  except Exception as e:
564
  st.error(f"An unexpected error occurred: {str(e)} 😱")
565
 
566
+ st.stop()
567
  except Exception as e:
568
  st.markdown(' ')
569
 
570
+
571
+
572
+ # πŸ” Auth check - "With great keys come great connectivity"
573
  if Key:
574
  st.session_state.primary_key = Key
575
  st.session_state.logged_in = True
576
  else:
577
  st.error("Cosmos DB Key is not set in environment variables. πŸ”‘βŒ")
578
+ return
579
+
580
 
581
+
582
  if st.session_state.logged_in:
583
+ # 🌌 DB initialization - "In the beginning, there was connection string..."
584
  try:
585
  if st.session_state.client is None:
586
  st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
587
 
588
+ # πŸ“š Navigation setup - "Navigation is not about where you are, but where you're going"
589
  st.sidebar.title("πŸ™Git🌌CosmosπŸ’«πŸ—„οΈNavigator")
590
 
591
  databases = get_databases(st.session_state.client)
592
  selected_db = st.sidebar.selectbox("πŸ—ƒοΈ Select Database", databases)
593
+
594
+
595
 
596
+ # πŸ”„ State management - "Change is the only constant in state management"
597
  if selected_db != st.session_state.selected_database:
598
  st.session_state.selected_database = selected_db
599
  st.session_state.selected_container = None
600
  st.session_state.selected_document_id = None
601
  st.session_state.current_index = 0
602
  st.rerun()
603
+
604
+
605
+
606
  if st.session_state.selected_database:
607
  database = st.session_state.client.get_database_client(st.session_state.selected_database)
608
  containers = get_containers(database)
609
  selected_container = st.sidebar.selectbox("πŸ“ Select Container", containers)
610
 
611
+ # πŸ”„ Container state handling - "Container changes, state arranges"
612
  if selected_container != st.session_state.selected_container:
613
  st.session_state.selected_container = selected_container
614
  st.session_state.selected_document_id = None
 
618
  if st.session_state.selected_container:
619
  container = database.get_container_client(st.session_state.selected_container)
620
 
621
+ # πŸ“¦ Export functionality - "Pack it, zip it, ship it"
622
  if st.button("πŸ“¦ Export Container Data"):
623
+ download_link = archive_current_container(st.session_state.selected_database,
624
+ st.session_state.selected_container,
625
+ st.session_state.client)
626
  if download_link.startswith('<a'):
627
  st.markdown(download_link, unsafe_allow_html=True)
628
  else:
629
  st.error(download_link)
630
+
631
+
632
 
633
+ # πŸ“ Document handling - "Document, document, on the wall, who's the most recent of them all?"
634
  documents = get_documents(container)
635
  total_docs = len(documents)
636
 
 
642
  st.info(f"Showing all {len(documents_to_display)} documents.")
643
 
644
  if documents_to_display:
645
+ # 🎨 View options - "Different strokes for different folks"
646
+ view_options = ['Show as Markdown', 'Show as Code Editor',
647
+ 'Show as Edit and Save', 'Clone Document', 'New Record']
648
  selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
649
 
650
+ # πŸ“„ Markdown view - "Mark it down, mark it up"
651
  if selected_view == 'Show as Markdown':
 
652
  total_docs = len(documents)
653
  doc = documents[st.session_state.current_index]
654
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
655
 
656
+ # πŸ•΅οΈ Value extraction - "Finding spaces in all the right places"
657
  values_with_space = []
658
  def extract_values(obj):
659
  if isinstance(obj, dict):
 
667
  values_with_space.append(obj)
668
 
669
  extract_values(doc)
 
 
670
  st.markdown("#### πŸ”— Links for Extracted Texts")
671
  for term in values_with_space:
672
  display_glossary_entity(term)
673
 
 
674
  content = json.dumps(doc, indent=2)
675
  st.markdown(f"```json\n{content}\n```")
676
 
677
+
678
+
679
+ # β¬…οΈβž‘οΈ Navigation - "Left and right, day and night"
680
  col_prev, col_next = st.columns([1, 1])
681
  with col_prev:
682
  if st.button("⬅️ Previous", key='prev_markdown'):
 
689
  st.session_state.current_index += 1
690
  st.rerun()
691
 
692
+
693
+
694
+ # πŸ’» Code editor view - "Code is poetry, bugs are typos"
695
  elif selected_view == 'Show as Code Editor':
 
696
  total_docs = len(documents)
697
  doc = documents[st.session_state.current_index]
698
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
699
+ doc_str = st.text_area("Edit Document",
700
+ value=json.dumps(doc, indent=2),
701
+ height=300,
702
+ key=f'code_editor_{st.session_state.current_index}')
703
+
704
+
705
+
706
+ # β¬…οΈβž‘οΈ Navigation and save controls
707
  col_prev, col_next = st.columns([1, 1])
708
  with col_prev:
709
  if st.button("⬅️ Previous", key='prev_code'):
 
715
  if st.session_state.current_index < total_docs - 1:
716
  st.session_state.current_index += 1
717
  st.rerun()
718
+
719
+
720
+
721
+ # πŸ’Ύ Save functionality - "Save early, save often"
722
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{st.session_state.current_index}'):
723
  try:
724
  updated_doc = json.loads(doc_str)
 
731
  st.error(message)
732
  except json.JSONDecodeError as e:
733
  st.error(f"Invalid JSON: {str(e)} 🚫")
734
+
735
+
736
 
737
+ # ✏️ Edit and save view - "Edit with wisdom, save with precision"
738
  elif selected_view == 'Show as Edit and Save':
 
739
  st.markdown("#### Edit the document fields below:")
740
 
 
741
  num_cols = len(documents_to_display)
742
  cols = st.columns(num_cols)
743
 
744
+
745
+
746
  for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
747
  with col:
748
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
749
+ editable_id = st.text_input("ID", value=doc.get('id', ''),
750
+ key=f'edit_id_{idx}')
751
  editable_doc = doc.copy()
752
  editable_doc.pop('id', None)
753
+ doc_str = st.text_area("Document Content (in JSON format)",
754
+ value=json.dumps(editable_doc, indent=2),
755
+ height=300,
756
+ key=f'doc_str_{idx}')
757
+
758
+
759
 
760
+ # πŸ’ΎπŸ€– Save and AI operations
761
  col_save, col_ai = st.columns(2)
762
  with col_save:
763
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{idx}'):
764
  try:
765
  updated_doc = json.loads(doc_str)
766
+ updated_doc['id'] = editable_id
767
  success, message = update_record(container, updated_doc)
768
  if success:
769
  st.success(f"Document {updated_doc['id']} saved successfully.")
 
773
  st.error(message)
774
  except json.JSONDecodeError as e:
775
  st.error(f"Invalid JSON: {str(e)} 🚫")
776
+
777
+
778
  with col_ai:
779
  if st.button("πŸ€– Run With AI", key=f'run_with_ai_button_{idx}'):
 
780
  search_glossary(json.dumps(editable_doc, indent=2))
 
781
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
782
  with st.spinner("Cloning document..."):
783
+ cloned_id = save_or_clone_to_cosmos_db(container,
784
+ clone_id=doc['id'])
785
  if cloned_id:
786
  st.success(f"Document cloned successfully with new ID: {cloned_id}")
787
  st.rerun()
788
  else:
789
  st.error("Failed to clone document. Please try again.")
790
 
791
+
792
+
793
+ # 🧬 Clone functionality - "Copy wisely, paste precisely"
794
  elif selected_view == 'Clone Document':
 
795
  st.markdown("#### Clone a document:")
796
  for idx, doc in enumerate(documents_to_display):
797
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
798
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
799
  cloned_doc = doc.copy()
 
800
  cloned_doc['id'] = generate_unique_id()
801
  st.session_state.cloned_doc = cloned_doc
802
  st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
 
804
  st.rerun()
805
  if st.session_state.get('clone_mode', False):
806
  st.markdown("#### Edit Cloned Document and Name Your Clone:")
807
+ cloned_doc_str = st.text_area("Cloned Document Content (in JSON format) - Update name please to make it unique before saving!",
808
+ value=st.session_state.cloned_doc_str,
809
+ height=300)
810
+
811
+
812
  if st.button("πŸ’Ύ Save Cloned Document"):
813
  try:
814
  new_doc = json.loads(cloned_doc_str)
 
816
  if success:
817
  st.success(f"Cloned document saved with id: {new_doc['id']} πŸŽ‰")
818
  st.session_state.selected_document_id = new_doc['id']
819
+ st.session_state.clone_mode = False
820
+ st.session_state.cloned_doc = None
821
+ st.session_state.cloned_doc_str = ''
822
+ st.rerun()
823
+ else:
824
+ st.error(message)
825
+ except json.JSONDecodeError as e:
826
+ st.error(f"Invalid JSON: {str(e)} 🚫")
827
+
828
+
829
+
830
+ # πŸ†• New Record view - "Every new record is a new beginning"
831
+ elif selected_view == 'New Record':
832
+ st.markdown("#### Create a new document:")
833
+ if st.button("πŸ€– Insert Auto-Generated Record"):
834
+ success, message = save_or_clone_to_cosmos_db(container,
835
+ query="Auto-generated",
836
+ response="This is an auto-generated record.")
837
+ if success:
838
+ st.success(message)
839
+ st.rerun()
840
+ else:
841
+ st.error(message)
842
  else:
843
+ new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
844
+ new_doc_str = st.text_area("Document Content (in JSON format)",
845
+ value='{}', height=300)
846
+ if st.button("βž• Create New Document"):
847
+ try:
848
+ new_doc = json.loads(new_doc_str)
849
+ new_doc['id'] = new_id
850
+ success, message = insert_record(container, new_doc)
851
+ if success:
852
+ st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
853
+ st.session_state.selected_document_id = new_doc['id']
854
+ st.rerun()
855
+ else:
856
+ st.error(message)
857
+ except json.JSONDecodeError as e:
858
+ st.error(f"Invalid JSON: {str(e)} 🚫")
 
 
859
 
860
  else:
861
  st.sidebar.info("No documents found in this container. πŸ“­")
862
+
863
+
864
+
865
+ # πŸ“Š Data display - "Data tells tales that words cannot"
866
  st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
867
  if st.session_state.selected_container:
868
  if documents_to_display:
 
870
  st.dataframe(df)
871
  else:
872
  st.info("No documents to display. 🧐")
873
+
874
+
875
 
876
+ # πŸ™ GitHub integration - "Git happens"
877
  st.subheader("πŸ™ GitHub Operations")
878
+ github_token = os.environ.get("GITHUB")
879
+ source_repo = st.text_input("Source GitHub Repository URL",
880
+ value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
881
+ new_repo_name = st.text_input("New Repository Name (for cloning)",
882
+ value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
883
+
884
 
885
+
886
  col1, col2 = st.columns(2)
887
  with col1:
888
  if st.button("πŸ“₯ Clone Repository"):
 
903
  os.remove(zip_filename)
904
  else:
905
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
906
+
907
+
908
+
909
  with col2:
910
  if st.button("πŸ“€ Push to New Repository"):
911
  if github_token and source_repo:
 
924
  else:
925
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
926
 
927
+
928
+
929
+ # πŸ’¬ Chat functionality - "Every chat is a chance to learn"
930
  st.subheader("πŸ’¬ Chat with Claude")
931
  user_input = st.text_area("Message πŸ“¨:", height=100)
932
 
 
950
  # Save to Cosmos DB
951
  save_to_cosmos_db(container, user_input, response.content[0].text, "")
952
 
953
+
954
+
955
+ # πŸ“œ Chat history display - "History repeats itself, first as chat, then as wisdom"
956
  st.subheader("Past Conversations πŸ“œ")
957
  for chat in st.session_state.chat_history:
958
  st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
959
  st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
960
  st.markdown("---")
961
 
962
+
963
+
964
+ # πŸ“ File editor - "Edit with care, save with flair"
965
  if hasattr(st.session_state, 'current_file'):
966
  st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
967
  new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
 
970
  file.write(new_content)
971
  st.success("File updated successfully! πŸŽ‰")
972
 
973
+
974
+
975
+ # πŸ“‚ File management - "Manage many, maintain order"
976
  st.sidebar.title("πŸ“ File Management")
977
 
978
  all_files = glob.glob("*.md")
 
1004
  os.remove(file)
1005
  st.rerun()
1006
 
1007
+
1008
+
1009
  except exceptions.CosmosHttpResponseError as e:
1010
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
1011
  except Exception as e:
1012
  st.error(f"An unexpected error occurred: {str(e)} 😱")
1013
 
1014
+
1015
+
1016
+ # πŸšͺ Logout - "All good things must come to an end"
1017
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
1018
  st.session_state.logged_in = False
1019
  st.session_state.selected_records.clear()