awacke1 commited on
Commit
668494b
Β·
verified Β·
1 Parent(s): 76434fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -320
app.py CHANGED
@@ -588,326 +588,89 @@ def add_video_generation_ui(container):
588
  st.warning(f"Cleanup error: {str(e)}")
589
  except Exception as e:
590
  st.error(f"Upload error: {str(e)}")
591
-
592
- # %% ───────────── MAIN FUNCTION ─────────────
593
  def main():
594
- st.markdown("### πŸ™ GitCosmos - Cosmos & Git Hub")
595
- if "chat_history" not in st.session_state:
596
- st.session_state.chat_history = []
597
- # Auth & Cosmos client initialization
598
- if Key:
599
- st.session_state.primary_key = Key
600
- st.session_state.logged_in = True
601
- else:
602
- st.error("Missing Cosmos Key πŸ”‘βŒ")
603
- return
604
- if st.session_state.logged_in:
605
- try:
606
- if st.session_state.get("client") is None:
607
- st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
608
- st.sidebar.title("πŸ™ Navigator")
609
- databases = get_databases(st.session_state.client)
610
- selected_db = st.sidebar.selectbox("πŸ—ƒοΈ DB", databases)
611
- st.markdown(CosmosDBUrl)
612
- if selected_db != st.session_state.get("selected_database"):
613
- st.session_state.selected_database = selected_db
614
- st.session_state.selected_container = None
615
- st.session_state.selected_document_id = None
616
- st.session_state.current_index = 0
617
- st.rerun()
618
- if st.session_state.selected_database:
619
- database = st.session_state.client.get_database_client(st.session_state.selected_database)
620
- containers = get_containers(database)
621
- selected_container = st.sidebar.selectbox("πŸ“ Container", containers)
622
- if selected_container != st.session_state.get("selected_container"):
623
- st.session_state.selected_container = selected_container
624
- st.session_state.selected_document_id = None
625
- st.session_state.current_index = 0
626
- st.rerun()
627
- if st.session_state.selected_container:
628
- container = database.get_container_client(st.session_state.selected_container)
629
- if st.sidebar.button("πŸ“¦ Export"):
630
- download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
631
- if download_link.startswith('<a'):
632
- st.markdown(download_link, unsafe_allow_html=True)
633
- else:
634
- st.error(download_link)
635
- documents = get_documents(container)
636
- total_docs = len(documents)
637
- num_docs = st.slider("Docs", 1, 20, 1)
638
- documents_to_display = documents[:num_docs] if total_docs > num_docs else documents
639
- st.sidebar.info(f"Showing {len(documents_to_display)} docs")
640
- # --- Document Viewer / Editor ---
641
- view_options = ['Markdown', 'Code', 'Run AI', 'Clone', 'New']
642
- selected_view = st.sidebar.selectbox("View", view_options, index=1)
643
- if selected_view == 'Markdown':
644
- st.markdown("#### πŸ“„ Markdown")
645
- if documents:
646
- doc = documents[st.session_state.current_index]
647
- content = json.dumps(doc, indent=2)
648
- st.markdown(f"```json\n{content}\n```")
649
- col_prev, col_next = st.columns(2)
650
- with col_prev:
651
- if st.button("⬅️") and st.session_state.current_index > 0:
652
- st.session_state.current_index -= 1
653
- st.rerun()
654
- with col_next:
655
- if st.button("➑️") and st.session_state.current_index < total_docs - 1:
656
- st.session_state.current_index += 1
657
- st.rerun()
658
- elif selected_view == 'Code':
659
- st.markdown("#### πŸ’» Code Editor")
660
- if documents:
661
- doc = documents[st.session_state.current_index]
662
- doc_str = st.text_area("Edit JSON", value=json.dumps(doc, indent=2), height=300, key=f'code_{st.session_state.current_index}')
663
- col_prev, col_next = st.columns(2)
664
- with col_prev:
665
- if st.button("⬅️") and st.session_state.current_index > 0:
666
- st.session_state.current_index -= 1
667
- st.rerun()
668
- with col_next:
669
- if st.button("➑️") and st.session_state.current_index < total_docs - 1:
670
- st.session_state.current_index += 1
671
- st.rerun()
672
- col_save, col_delete = st.columns(2)
673
- with col_save:
674
- if st.button("πŸ’Ύ Save", key=f'save_{st.session_state.current_index}'):
675
- try:
676
- updated_doc = json.loads(doc_str)
677
- container.upsert_item(body=updated_doc)
678
- st.success(f"Saved {updated_doc['id']}")
679
- st.rerun()
680
- except Exception as e:
681
- st.error(f"Save err: {str(e)}")
682
- with col_delete:
683
- if st.button("πŸ—‘οΈ Delete", key=f'delete_{st.session_state.current_index}'):
684
- try:
685
- current_doc = json.loads(doc_str)
686
- success, message = delete_record(container, current_doc)
687
- if success:
688
- st.success(message)
689
- st.rerun()
690
- else:
691
- st.error(message)
692
- except Exception as e:
693
- st.error(f"Delete err: {str(e)}")
694
- if "delete_log" in st.session_state and st.session_state.delete_log:
695
- st.subheader("Delete Log")
696
- for log_entry in st.session_state.delete_log[-5:]:
697
- st.write(log_entry)
698
- elif selected_view == 'Run AI':
699
- st.markdown("#### πŸ€– Run AI (stub)")
700
- st.info("AI functionality not implemented.")
701
- elif selected_view == 'Clone':
702
- st.markdown("#### πŸ“„ Clone")
703
- if documents:
704
- doc = documents[st.session_state.current_index]
705
- st.markdown(f"Original ID: {doc.get('id', '')}")
706
- new_id = st.text_input("New ID", value=generate_unique_id(), key='new_clone_id')
707
- new_name = st.text_input("New Name", value=f"Clone_{new_id[:8]}", key='new_clone_name')
708
- new_doc = {'id': new_id, 'name': new_name, **{k: v for k, v in doc.items() if k not in ['id', 'name', '_rid', '_self', '_etag', '_attachments', '_ts']}}
709
- doc_str = st.text_area("Edit JSON", value=json.dumps(new_doc, indent=2), height=300, key='clone_preview')
710
- col1, col2 = st.columns(2)
711
- with col1:
712
- if st.button("πŸ”„ Regenerate"):
713
- new_id = generate_unique_id()
714
- st.session_state.new_clone_id = new_id
715
- st.rerun()
716
- with col2:
717
- if st.button("πŸ’Ύ Save Clone"):
718
- try:
719
- final_doc = json.loads(doc_str)
720
- for field in ['_rid', '_self', '_etag', '_attachments', '_ts']:
721
- final_doc.pop(field, None)
722
- container.create_item(body=final_doc)
723
- st.success(f"Cloned {final_doc['id']}")
724
- st.rerun()
725
- except Exception as e:
726
- st.error(f"Clone err: {str(e)}")
727
- col_prev, col_next = st.columns(2)
728
- with col_prev:
729
- if st.button("⬅️") and st.session_state.current_index > 0:
730
- st.session_state.current_index -= 1
731
- st.rerun()
732
- with col_next:
733
- if st.button("➑️") and st.session_state.current_index < total_docs - 1:
734
- st.session_state.current_index += 1
735
- st.rerun()
736
- elif selected_view == 'New':
737
- st.markdown("#### βž• New Doc")
738
- if st.button("πŸ€– Auto-Gen"):
739
- auto_doc = {
740
- "id": generate_unique_id(),
741
- "name": f"Auto {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
742
- "content": "Auto-generated record.",
743
- "timestamp": datetime.now().isoformat()
744
- }
745
- success, message = insert_record(container, auto_doc)
746
- if success:
747
- st.success(message)
748
- st.rerun()
749
- else:
750
- st.error(message)
751
- else:
752
- new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
753
- default_doc = {
754
- "id": new_id,
755
- "name": "New Doc",
756
- "content": "",
757
- "timestamp": datetime.now().isoformat()
758
- }
759
- new_doc_str = st.text_area("JSON", value=json.dumps(default_doc, indent=2), height=300)
760
- if st.button("βž• Create"):
761
- try:
762
- cleaned = preprocess_text(new_doc_str)
763
- new_doc = json.loads(cleaned)
764
- new_doc['id'] = new_id
765
- success, message = insert_record(container, new_doc)
766
- if success:
767
- st.success(f"Created {new_doc['id']}")
768
- st.rerun()
769
- else:
770
- st.error(message)
771
- except Exception as e:
772
- st.error(f"Create err: {str(e)}")
773
- st.subheader(f"πŸ“Š {st.session_state.selected_container}")
774
- if documents_to_display:
775
- df = pd.DataFrame(documents_to_display)
776
- st.dataframe(df)
777
- else:
778
- st.info("No docs.")
779
-
780
- # ───── Advanced Cosmos Ops ─────
781
- with st.sidebar.expander("Advanced Cosmos Ops"):
782
- st.markdown("### Advanced Cosmos Operations")
783
- # Create Container
784
- with st.form("create_container_form"):
785
- container_id = st.text_input("Container ID", value="newContainer")
786
- partition_key_path = st.text_input("Partition Key Path", value="/id")
787
- analytical = st.checkbox("Enable Analytical Store", value=False)
788
- submitted = st.form_submit_button("πŸ†• Create Container")
789
- if submitted:
790
- analytical_ttl = -1 if analytical else None
791
- new_container = create_new_container(database, container_id, partition_key_path,
792
- analytical_storage_ttl=analytical_ttl)
793
- if new_container:
794
- st.success(f"Container '{container_id}' created.")
795
- else:
796
- st.error("Container creation failed.")
797
-
798
- # Insert Item
799
- with st.form("insert_item_form"):
800
- item_json = st.text_area("Item JSON", value='{"id": "itemX", "productName": "Widget", "productModel": "Model X"}')
801
- submitted = st.form_submit_button("βž• Insert Item")
802
- if submitted:
803
- try:
804
- item = json.loads(item_json)
805
- success, msg = advanced_insert_item(container, item)
806
- if success:
807
- st.success(msg)
808
- else:
809
- st.error(msg)
810
- except Exception as e:
811
- st.error(str(e))
812
-
813
- # Update Item
814
- with st.form("update_item_form"):
815
- update_json = st.text_area("Update Item JSON", value='{"id": "itemX", "productName": "Widget", "productModel": "Updated Model"}')
816
- submitted = st.form_submit_button("✏️ Update Item")
817
- if submitted:
818
- try:
819
- item = json.loads(update_json)
820
- success, msg = advanced_update_item(container, item)
821
- if success:
822
- st.success(msg)
823
- else:
824
- st.error(msg)
825
- except Exception as e:
826
- st.error(str(e))
827
-
828
- # Delete Item
829
- with st.form("delete_item_form"):
830
- del_item_id = st.text_input("Item ID to delete", value="itemX")
831
- del_partition = st.text_input("Partition Key Value", value="Widget")
832
- submitted = st.form_submit_button("πŸ—‘οΈ Delete Item")
833
- if submitted:
834
- success, msg = advanced_delete_item(container, del_item_id, del_partition)
835
- if success:
836
- st.success(msg)
837
- else:
838
- st.error(msg)
839
-
840
- # Vector Search
841
- with st.form("vector_search_form"):
842
- vector_str = st.text_input("Query Vector (comma separated)", value="0.1, 0.2, 0.3, 0.4")
843
- top_n = st.number_input("Top N Results", min_value=1, max_value=100, value=10)
844
- vector_field = st.text_input("Vector Field", value="vector")
845
- submitted = st.form_submit_button("πŸ”Ž Vector Search")
846
- if submitted:
847
- try:
848
- query_vector = [float(x.strip()) for x in vector_str.split(",") if x.strip()]
849
- results = vector_search(container, query_vector, vector_field, top=top_n)
850
- st.write(results)
851
- except Exception as e:
852
- st.error(str(e))
853
-
854
- # ───── End Advanced Ops ─────
855
- st.subheader("πŸ™ GitHub Ops")
856
- github_token = os.environ.get("GITHUB")
857
- source_repo = st.text_input("Source Repo URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
858
- new_repo_name = st.text_input("New Repo Name", value=f"Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
859
- col_g1, col_g2 = st.columns(2)
860
- with col_g1:
861
- if st.button("πŸ“₯ Clone Repo"):
862
- if github_token and source_repo:
863
- try:
864
- local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
865
- download_github_repo(source_repo, local_path)
866
- zip_filename = f"{new_repo_name}.zip"
867
- create_zip_file(local_path, zip_filename[:-4])
868
- st.markdown(get_download_link(zip_filename), unsafe_allow_html=True)
869
- st.success("Cloned! πŸŽ‰")
870
- except Exception as e:
871
- st.error(f"Clone err: {str(e)}")
872
- finally:
873
- if os.path.exists(local_path):
874
- shutil.rmtree(local_path)
875
- if os.path.exists(zip_filename):
876
- os.remove(zip_filename)
877
- else:
878
- st.error("Missing token or URL πŸ”‘β“")
879
- with col_g2:
880
- if st.button("πŸ“€ Push Repo"):
881
- if github_token and source_repo:
882
- try:
883
- g = Github(github_token)
884
- new_repo = create_repo(g, new_repo_name)
885
- local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
886
- download_github_repo(source_repo, local_path)
887
- push_to_github(local_path, new_repo, github_token)
888
- st.success(f"Pushed to {new_repo.html_url} πŸš€")
889
- except Exception as e:
890
- st.error(f"Push err: {str(e)}")
891
- finally:
892
- if os.path.exists(local_path):
893
- shutil.rmtree(local_path)
894
- else:
895
- st.error("Missing token or URL πŸ”‘β“")
896
- update_file_management_section()
897
- except exceptions.CosmosHttpResponseError as e:
898
- st.error(f"Cosmos error: {str(e)} 🚨")
899
- except Exception as e:
900
- st.error(f"Error: {str(e)} 😱")
901
- if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
902
- st.markdown("#### πŸšͺ Logout")
903
- st.session_state.logged_in = False
904
- st.session_state.selected_records = []
905
- st.session_state.client = None
906
- st.session_state.selected_database = None
907
- st.session_state.selected_container = None
908
- st.session_state.selected_document_id = None
909
- st.session_state.current_index = 0
910
- st.rerun()
911
 
912
  if __name__ == "__main__":
913
- main()
 
 
588
  st.warning(f"Cleanup error: {str(e)}")
589
  except Exception as e:
590
  st.error(f"Upload error: {str(e)}")
 
 
591
  def main():
592
+ st.markdown("### πŸ™ GitCosmos - Cosmos & Git Hub")
593
+ if "chat_history" not in st.session_state:
594
+ st.session_state.chat_history = []
595
+ # Auth & Cosmos client initialization
596
+ if Key:
597
+ st.session_state.primary_key = Key
598
+ st.session_state.logged_in = True
599
+ else:
600
+ st.error("Missing Cosmos Key πŸ”‘βŒ")
601
+ return
602
+ if st.session_state.logged_in:
603
+ try:
604
+ if st.session_state.get("client") is None:
605
+ st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
606
+ st.sidebar.title("πŸ™ Navigator")
607
+ databases = get_databases(st.session_state.client)
608
+ selected_db = st.sidebar.selectbox("πŸ—ƒοΈ DB", databases)
609
+ st.markdown(CosmosDBUrl)
610
+ if selected_db != st.session_state.get("selected_database"):
611
+ st.session_state.selected_database = selected_db
612
+ st.session_state.selected_container = None
613
+ st.session_state.selected_document_id = None
614
+ st.session_state.current_index = 0
615
+ st.rerun()
616
+ if st.session_state.selected_database:
617
+ database = st.session_state.client.get_database_client(st.session_state.selected_database)
618
+
619
+ # ── New Container Button & Form Under DB Menu ──
620
+ if "show_new_container_form" not in st.session_state:
621
+ st.session_state.show_new_container_form = False
622
+ if st.sidebar.button("πŸ†• New Container"):
623
+ st.session_state.show_new_container_form = True
624
+ if st.session_state.show_new_container_form:
625
+ with st.sidebar.form("new_container_form"):
626
+ new_container_id = st.text_input("Container ID", value="newContainer")
627
+ new_partition_key = st.text_input("Partition Key", value="/id")
628
+ new_analytical = st.checkbox("Enable Analytical Store", value=False)
629
+ submitted = st.form_submit_button("Create Container")
630
+ if submitted:
631
+ analytical_ttl = -1 if new_analytical else None
632
+ new_container = create_new_container(
633
+ database,
634
+ new_container_id,
635
+ new_partition_key,
636
+ analytical_storage_ttl=analytical_ttl
637
+ )
638
+ if new_container:
639
+ st.success(f"Container '{new_container_id}' created.")
640
+ st.session_state.show_new_container_form = False
641
+ st.session_state.new_container_created = new_container_id
642
+ st.rerun()
643
+
644
+ # ── Get and Update Container List ──
645
+ containers = get_containers(database)
646
+ if "new_container_created" in st.session_state and st.session_state.new_container_created not in containers:
647
+ containers.append(st.session_state.new_container_created)
648
+ selected_container = st.sidebar.selectbox("πŸ“ Container", containers)
649
+ if selected_container != st.session_state.get("selected_container"):
650
+ st.session_state.selected_container = selected_container
651
+ st.session_state.selected_document_id = None
652
+ st.session_state.current_index = 0
653
+ st.rerun()
654
+
655
+ if st.session_state.selected_container:
656
+ container = database.get_container_client(st.session_state.selected_container)
657
+ # ... rest of your container operations code follows here ...
658
+
659
+ except exceptions.CosmosHttpResponseError as e:
660
+ st.error(f"Cosmos error: {str(e)} 🚨")
661
+ except Exception as e:
662
+ st.error(f"Error: {str(e)} 😱")
663
+ if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
664
+ st.markdown("#### πŸšͺ Logout")
665
+ st.session_state.logged_in = False
666
+ st.session_state.selected_records = []
667
+ st.session_state.client = None
668
+ st.session_state.selected_database = None
669
+ st.session_state.selected_container = None
670
+ st.session_state.selected_document_id = None
671
+ st.session_state.current_index = 0
672
+ st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
 
674
  if __name__ == "__main__":
675
+ main()
676
+