awacke1 commited on
Commit
df6ddee
Β·
verified Β·
1 Parent(s): d790577

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +325 -148
app.py CHANGED
@@ -1,25 +1,28 @@
1
- import streamlit as st
2
- from azure.cosmos import CosmosClient, exceptions
3
- import os
4
- import pandas as pd
5
- import traceback
6
- import shutil
7
- from github import Github
8
- from git import Repo
9
- from datetime import datetime
10
- import base64
11
- import json
12
- import uuid
13
- from urllib.parse import quote
14
- from gradio_client import Client
15
  import anthropic
 
16
  import glob
 
 
 
 
17
  import pytz
 
18
  import re
19
- from PIL import Image
20
- import zipfile
21
- import hashlib
22
  import time
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  # 🎭 App Configuration - Because every app needs a good costume!
25
  Site_Name = 'πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent'
@@ -260,6 +263,7 @@ def save_or_clone_to_cosmos_db(container, query=None, response=None, clone_id=No
260
 
261
  if clone_id:
262
  try:
 
263
  existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
264
  new_doc = {
265
  'id': new_id,
@@ -308,57 +312,7 @@ def save_or_clone_to_cosmos_db(container, query=None, response=None, clone_id=No
308
  st.error("Failed to save document after maximum retries.")
309
  return None
310
 
311
-
312
 
313
- # πŸ’Ύ Save or clone to Cosmos DB - Because every document deserves a twin
314
- def save_or_clone_to_cosmos_db2(container, query=None, response=None, clone_id=None):
315
- try:
316
- if not container:
317
- st.error("Cosmos DB container is not initialized.")
318
- return
319
-
320
- # Generate a new unique ID
321
- new_id = str(uuid.uuid4())
322
-
323
- # Create a new document
324
- if clone_id:
325
- # If clone_id is provided, we're cloning an existing document
326
- try:
327
- existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
328
- new_doc = existing_doc.copy()
329
- new_doc['id'] = new_id
330
- new_doc['cloned_from'] = clone_id
331
- new_doc['cloned_at'] = datetime.utcnow().isoformat()
332
- except exceptions.CosmosResourceNotFoundError:
333
- st.error(f"Document with ID {clone_id} not found for cloning.")
334
- return
335
- else:
336
- # If no clone_id, we're creating a new document
337
- new_doc = {
338
- 'id': new_id,
339
- 'query': query,
340
- 'response': response,
341
- 'created_at': datetime.utcnow().isoformat()
342
- }
343
-
344
- # Insert the new document
345
- container.create_item(body=new_doc)
346
-
347
- st.success(f"{'Cloned' if clone_id else 'New'} document saved successfully with ID: {new_id}")
348
-
349
- # Refresh the documents in the session state
350
- st.session_state.documents = list(container.query_items(
351
- query="SELECT * FROM c ORDER BY c._ts DESC",
352
- enable_cross_partition_query=True
353
- ))
354
-
355
- return new_id
356
-
357
- except exceptions.CosmosHttpResponseError as e:
358
- st.error(f"Error saving to Cosmos DB: {e}")
359
- except Exception as e:
360
- st.error(f"An unexpected error occurred: {str(e)}")
361
-
362
  # πŸ“¦ Archive current container - Packing up data like you're moving to a new digital house
363
  def archive_current_container(database_name, container_name, client):
364
  try:
@@ -452,11 +406,124 @@ def search_glossary(query):
452
 
453
  return result, result2, result3, response2
454
 
455
- # 🎭 Main function - Where the magic happens (and occasionally breaks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
  def main():
457
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
458
 
459
- # 🚦 Initialize session state
 
 
460
  if 'logged_in' not in st.session_state:
461
  st.session_state.logged_in = False
462
  if 'selected_records' not in st.session_state:
@@ -474,14 +541,32 @@ def main():
474
  if 'cloned_doc' not in st.session_state:
475
  st.session_state.cloned_doc = None
476
 
477
- # βš™οΈ q= Run ArXiv search from query parameters
 
 
478
  try:
479
  query_params = st.query_params
480
  query = query_params.get('q') or query_params.get('query') or ''
481
  if query:
482
- # πŸ•΅οΈβ€β™‚οΈ We have a query! Let's process it!
483
  result, result2, result3, response2 = search_glossary(query)
484
- # When saving results, pass the container
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
  try:
486
  save_to_cosmos_db(st.session_state.cosmos_container, query, result, result)
487
  save_to_cosmos_db(st.session_state.cosmos_container, query, result2, result2)
@@ -493,42 +578,52 @@ def main():
493
  except Exception as e:
494
  st.error(f"An unexpected error occurred: {str(e)} 😱")
495
 
496
- st.stop() # Stop further execution
497
  except Exception as e:
498
  st.markdown(' ')
499
 
500
- # πŸ” Automatic Login
 
 
501
  if Key:
502
  st.session_state.primary_key = Key
503
  st.session_state.logged_in = True
504
  else:
505
  st.error("Cosmos DB Key is not set in environment variables. πŸ”‘βŒ")
506
- return # Can't proceed without a key
507
 
 
 
508
  if st.session_state.logged_in:
509
- # 🌌 Initialize Cosmos DB client
510
  try:
511
  if st.session_state.client is None:
512
  st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
513
 
514
- # πŸ—„οΈ Sidebar for database, container, and document selection
515
  st.sidebar.title("πŸ™Git🌌CosmosπŸ’«πŸ—„οΈNavigator")
516
 
517
  databases = get_databases(st.session_state.client)
518
  selected_db = st.sidebar.selectbox("πŸ—ƒοΈ Select Database", databases)
 
 
519
 
 
520
  if selected_db != st.session_state.selected_database:
521
  st.session_state.selected_database = selected_db
522
  st.session_state.selected_container = None
523
  st.session_state.selected_document_id = None
524
  st.session_state.current_index = 0
525
  st.rerun()
526
-
 
 
527
  if st.session_state.selected_database:
528
  database = st.session_state.client.get_database_client(st.session_state.selected_database)
529
  containers = get_containers(database)
530
  selected_container = st.sidebar.selectbox("πŸ“ Select Container", containers)
531
 
 
532
  if selected_container != st.session_state.selected_container:
533
  st.session_state.selected_container = selected_container
534
  st.session_state.selected_document_id = None
@@ -538,37 +633,42 @@ def main():
538
  if st.session_state.selected_container:
539
  container = database.get_container_client(st.session_state.selected_container)
540
 
541
- # πŸ“¦ Add Export button
542
- if st.button("πŸ“¦ Export Container Data"):
543
- download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
 
 
544
  if download_link.startswith('<a'):
545
  st.markdown(download_link, unsafe_allow_html=True)
546
  else:
547
  st.error(download_link)
 
 
548
 
549
- # Fetch documents
550
  documents = get_documents(container)
551
  total_docs = len(documents)
552
 
553
  if total_docs > 5:
554
  documents_to_display = documents[:5]
555
- st.info("Showing top 5 most recent documents.")
556
  else:
557
  documents_to_display = documents
558
- st.info(f"Showing all {len(documents_to_display)} documents.")
559
 
560
  if documents_to_display:
561
- # 🎨 Add Viewer/Editor selection
562
- view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
563
- selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
564
 
565
  if selected_view == 'Show as Markdown':
566
- # πŸ–ŒοΈ Show each record as Markdown with navigation
 
567
  total_docs = len(documents)
568
  doc = documents[st.session_state.current_index]
569
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
570
 
571
- # πŸ•΅οΈβ€β™‚οΈ Let's extract values from the JSON that have at least one space
572
  values_with_space = []
573
  def extract_values(obj):
574
  if isinstance(obj, dict):
@@ -582,17 +682,16 @@ def main():
582
  values_with_space.append(obj)
583
 
584
  extract_values(doc)
585
-
586
- # πŸ”— Let's create a list of links for these values
587
  st.markdown("#### πŸ”— Links for Extracted Texts")
588
  for term in values_with_space:
589
  display_glossary_entity(term)
590
 
591
- # Show the document content as markdown
592
  content = json.dumps(doc, indent=2)
593
  st.markdown(f"```json\n{content}\n```")
594
 
595
- # Navigation buttons
 
 
596
  col_prev, col_next = st.columns([1, 1])
597
  with col_prev:
598
  if st.button("⬅️ Previous", key='prev_markdown'):
@@ -605,12 +704,22 @@ def main():
605
  st.session_state.current_index += 1
606
  st.rerun()
607
 
 
 
608
  elif selected_view == 'Show as Code Editor':
609
- # πŸ’» Show each record in a code editor with navigation
 
610
  total_docs = len(documents)
611
  doc = documents[st.session_state.current_index]
612
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
613
- doc_str = st.text_area("Edit Document", value=json.dumps(doc, indent=2), height=300, key=f'code_editor_{st.session_state.current_index}')
 
 
 
 
 
 
 
614
  col_prev, col_next = st.columns([1, 1])
615
  with col_prev:
616
  if st.button("⬅️ Previous", key='prev_code'):
@@ -622,6 +731,10 @@ def main():
622
  if st.session_state.current_index < total_docs - 1:
623
  st.session_state.current_index += 1
624
  st.rerun()
 
 
 
 
625
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{st.session_state.current_index}'):
626
  try:
627
  updated_doc = json.loads(doc_str)
@@ -634,31 +747,40 @@ def main():
634
  st.error(message)
635
  except json.JSONDecodeError as e:
636
  st.error(f"Invalid JSON: {str(e)} 🚫")
 
 
637
 
638
- elif selected_view == 'Show as Edit and Save':
639
- # ✏️ Show as Edit and Save in columns
 
640
  st.markdown("#### Edit the document fields below:")
641
 
642
- # Create columns for each document
643
  num_cols = len(documents_to_display)
644
  cols = st.columns(num_cols)
645
 
 
 
646
  for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
647
  with col:
648
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
649
- editable_id = st.text_input("ID", value=doc.get('id', ''), key=f'edit_id_{idx}')
650
- # Remove 'id' from the document for editing other fields
651
  editable_doc = doc.copy()
652
  editable_doc.pop('id', None)
653
- doc_str = st.text_area("Document Content (in JSON format)", value=json.dumps(editable_doc, indent=2), height=300, key=f'doc_str_{idx}')
 
 
 
 
 
654
 
655
- # Add the "Run With AI" button next to "Save Changes"
656
  col_save, col_ai = st.columns(2)
657
  with col_save:
658
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{idx}'):
659
  try:
660
  updated_doc = json.loads(doc_str)
661
- updated_doc['id'] = editable_id # Include the possibly edited ID
662
  success, message = update_record(container, updated_doc)
663
  if success:
664
  st.success(f"Document {updated_doc['id']} saved successfully.")
@@ -668,28 +790,39 @@ def main():
668
  st.error(message)
669
  except json.JSONDecodeError as e:
670
  st.error(f"Invalid JSON: {str(e)} 🚫")
 
 
671
  with col_ai:
672
- if st.button("πŸ€– Run With AI", key=f'run_with_ai_button_{idx}'):
673
- # Use the entire document as input
674
  search_glossary(json.dumps(editable_doc, indent=2))
675
- # Usage in your Streamlit app
676
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
 
 
 
 
677
  with st.spinner("Cloning document..."):
678
- cloned_id = save_or_clone_to_cosmos_db(container, clone_id=doc['id'])
 
679
  if cloned_id:
680
  st.success(f"Document cloned successfully with new ID: {cloned_id}")
681
  st.rerun()
682
  else:
683
  st.error("Failed to clone document. Please try again.")
684
 
 
 
685
  elif selected_view == 'Clone Document':
686
- # 🧬 Clone Document per record
 
 
 
 
 
687
  st.markdown("#### Clone a document:")
688
  for idx, doc in enumerate(documents_to_display):
689
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
690
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
691
  cloned_doc = doc.copy()
692
- # Generate a unique ID
693
  cloned_doc['id'] = generate_unique_id()
694
  st.session_state.cloned_doc = cloned_doc
695
  st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
@@ -697,7 +830,11 @@ def main():
697
  st.rerun()
698
  if st.session_state.get('clone_mode', False):
699
  st.markdown("#### Edit Cloned Document and Name Your Clone:")
700
- 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)
 
 
 
 
701
  if st.button("πŸ’Ύ Save Cloned Document"):
702
  try:
703
  new_doc = json.loads(cloned_doc_str)
@@ -713,57 +850,79 @@ def main():
713
  st.error(message)
714
  except json.JSONDecodeError as e:
715
  st.error(f"Invalid JSON: {str(e)} 🚫")
716
-
 
 
717
  elif selected_view == 'New Record':
718
- # πŸ†• New Record
 
 
 
 
 
 
719
  st.markdown("#### Create a new document:")
720
- if st.button("πŸ€– Insert Auto-Generated Record"):
721
- success, message = save_or_clone_to_cosmos_db(container, query="Auto-generated", response="This is an auto-generated record.")
722
- if success:
723
- st.success(message)
724
- st.rerun()
725
- else:
726
- st.error(message)
727
  else:
728
- new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
729
- new_doc_str = st.text_area("Document Content (in JSON format)", value='{}', height=300)
730
- if st.button("βž• Create New Document"):
731
- try:
732
- new_doc = json.loads(new_doc_str)
733
- new_doc['id'] = new_id # Use the provided ID
734
- success, message = insert_record(container, new_doc)
735
- if success:
736
- st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
737
- st.session_state.selected_document_id = new_doc['id']
738
- # Switch to 'Show as Edit and Save' mode
739
- st.rerun()
740
- else:
741
- st.error(message)
742
- except json.JSONDecodeError as e:
743
- st.error(f"Invalid JSON: {str(e)} 🚫")
744
-
 
 
 
745
  else:
746
  st.sidebar.info("No documents found in this container. πŸ“­")
747
-
748
- # πŸŽ‰ Main content area
 
749
  st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
750
  if st.session_state.selected_container:
751
  if documents_to_display:
 
 
752
  df = pd.DataFrame(documents_to_display)
753
  st.dataframe(df)
754
  else:
755
  st.info("No documents to display. 🧐")
 
 
756
 
757
- # πŸ™ GitHub section
758
  st.subheader("πŸ™ GitHub Operations")
759
- github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
760
- source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
761
- new_repo_name = st.text_input("New Repository Name (for cloning)", value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
 
 
 
762
 
 
763
  col1, col2 = st.columns(2)
764
  with col1:
765
  if st.button("πŸ“₯ Clone Repository"):
766
  if github_token and source_repo:
 
 
767
  try:
768
  local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
769
  download_github_repo(source_repo, local_path)
@@ -780,10 +939,14 @@ def main():
780
  os.remove(zip_filename)
781
  else:
782
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
783
-
 
 
784
  with col2:
785
  if st.button("πŸ“€ Push to New Repository"):
786
  if github_token and source_repo:
 
 
787
  try:
788
  g = Github(github_token)
789
  new_repo = create_repo(g, new_repo_name)
@@ -799,11 +962,14 @@ def main():
799
  else:
800
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
801
 
802
- # πŸ’¬ Chat with Claude
 
803
  st.subheader("πŸ’¬ Chat with Claude")
804
  user_input = st.text_area("Message πŸ“¨:", height=100)
805
 
806
  if st.button("Send πŸ“¨"):
 
 
807
  if user_input:
808
  response = client.messages.create(
809
  model="claude-3-sonnet-20240229",
@@ -823,14 +989,18 @@ def main():
823
  # Save to Cosmos DB
824
  save_to_cosmos_db(container, user_input, response.content[0].text, "")
825
 
826
- # Display Chat History
 
 
827
  st.subheader("Past Conversations πŸ“œ")
828
  for chat in st.session_state.chat_history:
829
  st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
830
  st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
831
  st.markdown("---")
832
 
833
- # File Editor
 
 
834
  if hasattr(st.session_state, 'current_file'):
835
  st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
836
  new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
@@ -839,7 +1009,9 @@ def main():
839
  file.write(new_content)
840
  st.success("File updated successfully! πŸŽ‰")
841
 
842
- # File Management
 
 
843
  st.sidebar.title("πŸ“ File Management")
844
 
845
  all_files = glob.glob("*.md")
@@ -871,13 +1043,18 @@ def main():
871
  os.remove(file)
872
  st.rerun()
873
 
 
 
874
  except exceptions.CosmosHttpResponseError as e:
875
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
876
  except Exception as e:
877
  st.error(f"An unexpected error occurred: {str(e)} 😱")
878
 
879
- # πŸšͺ Logout button
 
880
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
 
 
881
  st.session_state.logged_in = False
882
  st.session_state.selected_records.clear()
883
  st.session_state.client = None
 
1
+
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import anthropic
3
+ import base64
4
  import glob
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import pandas as pd
9
  import pytz
10
+ import random
11
  import re
12
+ import shutil
13
+ import streamlit as st
 
14
  import time
15
+ import traceback
16
+ import uuid
17
+ import zipfile
18
+
19
+ from PIL import Image
20
+ from azure.cosmos import CosmosClient, exceptions
21
+ from datetime import datetime
22
+ from git import Repo
23
+ from github import Github
24
+ from gradio_client import Client
25
+ from urllib.parse import quote
26
 
27
  # 🎭 App Configuration - Because every app needs a good costume!
28
  Site_Name = 'πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent'
 
263
 
264
  if clone_id:
265
  try:
266
+
267
  existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
268
  new_doc = {
269
  'id': new_id,
 
312
  st.error("Failed to save document after maximum retries.")
313
  return None
314
 
 
315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  # πŸ“¦ Archive current container - Packing up data like you're moving to a new digital house
317
  def archive_current_container(database_name, container_name, client):
318
  try:
 
406
 
407
  return result, result2, result3, response2
408
 
409
+
410
+
411
+
412
+
413
+ # πŸ“ Generate a safe filename from the first few lines of content
414
+ def generate_filename_from_content(content, file_type="md"):
415
+ # Extract the first few lines or sentences
416
+ first_sentence = content.split('\n', 1)[0][:90] # Limit the length to 90 characters
417
+ # Remove special characters to make it a valid filename
418
+ safe_name = re.sub(r'[^\w\s-]', '', first_sentence)
419
+ # Limit length to be compatible with Windows and Linux
420
+ safe_name = safe_name[:50].strip() # Adjust length limit
421
+ return f"{safe_name}.{file_type}"
422
+
423
+ # πŸ’Ύ Create and save a file
424
+ def create_file_from_content(content, should_save=True):
425
+ if not should_save:
426
+ return
427
+ filename = generate_filename_from_content(content)
428
+ with open(filename, 'w', encoding='utf-8') as file:
429
+ file.write(content)
430
+ return filename
431
+
432
+ # πŸ“‚ Display list of saved .md files in the sidebar
433
+ def display_saved_files_in_sidebar():
434
+ all_files = glob.glob("*.md")
435
+ all_files.sort(reverse=True)
436
+ all_files = [file for file in all_files if not file.lower().startswith('readme')] # Exclude README.md
437
+
438
+ st.sidebar.markdown("## πŸ“ Saved Markdown Files")
439
+ for file in all_files:
440
+ col1, col2, col3 = st.sidebar.columns([6, 2, 1])
441
+ with col1:
442
+ st.markdown(f"οΏ½οΏ½ {file}")
443
+ with col2:
444
+ st.sidebar.download_button(
445
+ label="⬇️ Download",
446
+ data=open(file, 'rb').read(),
447
+ file_name=file
448
+ )
449
+ with col3:
450
+ if st.sidebar.button("πŸ—‘", key=f"delete_{file}"):
451
+ os.remove(file)
452
+ st.rerun()
453
+
454
+
455
+ def clone_record(container, clone_id):
456
+ try:
457
+ existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
458
+ new_doc = existing_doc.copy()
459
+ new_doc['id'] = generate_unique_id() # Generate new unique ID with timestamp
460
+ new_doc['createdAt'] = datetime.utcnow().isoformat() # Update the creation time
461
+ new_doc['_rid'] = None # Reset _rid or any system-managed fields
462
+ new_doc['_self'] = None
463
+ new_doc['_etag'] = None
464
+ new_doc['_attachments'] = None
465
+ new_doc['_ts'] = None # Reset timestamp to be updated by Cosmos DB automatically
466
+
467
+ # Insert the cloned document
468
+ response = container.create_item(body=new_doc)
469
+ st.success(f"Cloned document saved successfully with ID: {new_doc['id']} πŸŽ‰")
470
+
471
+ # Refresh the documents in session state
472
+ st.session_state.documents = list(container.query_items(
473
+ query="SELECT * FROM c ORDER BY c._ts DESC",
474
+ enable_cross_partition_query=True
475
+ ))
476
+
477
+ except exceptions.CosmosResourceNotFoundError:
478
+ st.error(f"Document with ID {clone_id} not found for cloning.")
479
+ except exceptions.CosmosHttpResponseError as e:
480
+ st.error(f"HTTP error occurred: {str(e)} 🚨")
481
+ except Exception as e:
482
+ st.error(f"An unexpected error occurred: {str(e)} 😱")
483
+
484
+
485
+
486
+
487
+ def create_new_blank_record(container):
488
+ try:
489
+ # Get the structure of the latest document (to preserve schema)
490
+ latest_doc = container.query_items(query="SELECT * FROM c ORDER BY c._ts DESC", enable_cross_partition_query=True, max_item_count=1)
491
+ if latest_doc:
492
+ new_doc_structure = latest_doc[0].copy()
493
+ else:
494
+ new_doc_structure = {}
495
+
496
+ new_doc = {key: "" for key in new_doc_structure.keys()} # Set all fields to blank
497
+ new_doc['id'] = generate_unique_id() # Generate new unique ID
498
+ new_doc['createdAt'] = datetime.utcnow().isoformat() # Set creation time
499
+
500
+ # Insert the new blank document
501
+ response = container.create_item(body=new_doc)
502
+ st.success(f"New blank document saved successfully with ID: {new_doc['id']} πŸŽ‰")
503
+
504
+ # Refresh the documents in session state
505
+ st.session_state.documents = list(container.query_items(
506
+ query="SELECT * FROM c ORDER BY c._ts DESC",
507
+ enable_cross_partition_query=True
508
+ ))
509
+
510
+ except exceptions.CosmosHttpResponseError as e:
511
+ st.error(f"HTTP error occurred: {str(e)} 🚨")
512
+ except Exception as e:
513
+ st.error(f"An unexpected error occurred: {str(e)} 😱")
514
+
515
+
516
+
517
+
518
+
519
+
520
+ # 🎭 Main function - "All the world's a stage, and all the code merely players" -Shakespeare, probably
521
  def main():
522
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
523
 
524
+
525
+
526
+ # 🎲 Session state vars - "Life is like a session state, you never know what you're gonna get"
527
  if 'logged_in' not in st.session_state:
528
  st.session_state.logged_in = False
529
  if 'selected_records' not in st.session_state:
 
541
  if 'cloned_doc' not in st.session_state:
542
  st.session_state.cloned_doc = None
543
 
544
+
545
+
546
+ # πŸ” Query processing - "To search or not to search, that is the query"
547
  try:
548
  query_params = st.query_params
549
  query = query_params.get('q') or query_params.get('query') or ''
550
  if query:
 
551
  result, result2, result3, response2 = search_glossary(query)
552
+
553
+ # πŸ’Ύ Save results - "Every file you save is a future you pave"
554
+ try:
555
+ if st.button("Save AI Output"):
556
+ filename = create_file_from_content(result)
557
+ st.success(f"File saved: {filename}")
558
+ filename = create_file_from_content(result2)
559
+ st.success(f"File saved: {filename}")
560
+ filename = create_file_from_content(result3)
561
+ st.success(f"File saved: {filename}")
562
+ filename = create_file_from_content(response2)
563
+ st.success(f"File saved: {filename}")
564
+
565
+ display_saved_files_in_sidebar()
566
+ except Exception as e:
567
+ st.error(f"An unexpected error occurred: {str(e)} 😱")
568
+
569
+ # 🌟 Cosmos DB operations - "In Cosmos DB we trust, but we still handle errors we must"
570
  try:
571
  save_to_cosmos_db(st.session_state.cosmos_container, query, result, result)
572
  save_to_cosmos_db(st.session_state.cosmos_container, query, result2, result2)
 
578
  except Exception as e:
579
  st.error(f"An unexpected error occurred: {str(e)} 😱")
580
 
581
+ st.stop()
582
  except Exception as e:
583
  st.markdown(' ')
584
 
585
+
586
+
587
+ # πŸ” Auth check - "With great keys come great connectivity"
588
  if Key:
589
  st.session_state.primary_key = Key
590
  st.session_state.logged_in = True
591
  else:
592
  st.error("Cosmos DB Key is not set in environment variables. πŸ”‘βŒ")
593
+ return
594
 
595
+
596
+
597
  if st.session_state.logged_in:
598
+ # 🌌 DB initialization - "In the beginning, there was connection string..."
599
  try:
600
  if st.session_state.client is None:
601
  st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
602
 
603
+ # πŸ“š Navigation setup - "Navigation is not about where you are, but where you're going"
604
  st.sidebar.title("πŸ™Git🌌CosmosπŸ’«πŸ—„οΈNavigator")
605
 
606
  databases = get_databases(st.session_state.client)
607
  selected_db = st.sidebar.selectbox("πŸ—ƒοΈ Select Database", databases)
608
+
609
+
610
 
611
+ # πŸ”„ State management - "Change is the only constant in state management"
612
  if selected_db != st.session_state.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
+
619
+
620
+
621
  if st.session_state.selected_database:
622
  database = st.session_state.client.get_database_client(st.session_state.selected_database)
623
  containers = get_containers(database)
624
  selected_container = st.sidebar.selectbox("πŸ“ Select Container", containers)
625
 
626
+ # πŸ”„ Container state handling - "Container changes, state arranges"
627
  if selected_container != st.session_state.selected_container:
628
  st.session_state.selected_container = selected_container
629
  st.session_state.selected_document_id = None
 
633
  if st.session_state.selected_container:
634
  container = database.get_container_client(st.session_state.selected_container)
635
 
636
+ # πŸ“¦ Export functionality - "Pack it, zip it, ship it"
637
+ if st.sidebar.button("πŸ“¦ Export Container Data"):
638
+ download_link = archive_current_container(st.session_state.selected_database,
639
+ st.session_state.selected_container,
640
+ st.session_state.client)
641
  if download_link.startswith('<a'):
642
  st.markdown(download_link, unsafe_allow_html=True)
643
  else:
644
  st.error(download_link)
645
+
646
+
647
 
648
+ # πŸ“ Document handling - "Document, document, on the wall, who's the most recent of them all?"
649
  documents = get_documents(container)
650
  total_docs = len(documents)
651
 
652
  if total_docs > 5:
653
  documents_to_display = documents[:5]
654
+ st.sidebar.info("Showing top 5 most recent documents.")
655
  else:
656
  documents_to_display = documents
657
+ st.sidebar.info(f"Showing all {len(documents_to_display)} documents.")
658
 
659
  if documents_to_display:
660
+ # 🎨 View options - "Different strokes for different folks"
661
+ view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit, Save, Run AI', 'Clone Document', 'New Record']
662
+ selected_view = st.sidebar.selectbox("Select Viewer/Editor", view_options, index=2)
663
 
664
  if selected_view == 'Show as Markdown':
665
+ Label = '# πŸ“„ Markdown view - Mark it down, mark it up'
666
+ st.markdown(Label)
667
  total_docs = len(documents)
668
  doc = documents[st.session_state.current_index]
669
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
670
 
671
+ # πŸ•΅οΈ Value extraction - "Finding spaces in all the right places"
672
  values_with_space = []
673
  def extract_values(obj):
674
  if isinstance(obj, dict):
 
682
  values_with_space.append(obj)
683
 
684
  extract_values(doc)
 
 
685
  st.markdown("#### πŸ”— Links for Extracted Texts")
686
  for term in values_with_space:
687
  display_glossary_entity(term)
688
 
 
689
  content = json.dumps(doc, indent=2)
690
  st.markdown(f"```json\n{content}\n```")
691
 
692
+
693
+
694
+ # β¬…οΈβž‘οΈ Navigation - "Left and right, day and night"
695
  col_prev, col_next = st.columns([1, 1])
696
  with col_prev:
697
  if st.button("⬅️ Previous", key='prev_markdown'):
 
704
  st.session_state.current_index += 1
705
  st.rerun()
706
 
707
+
708
+
709
  elif selected_view == 'Show as Code Editor':
710
+ Label = '# πŸ’» Code editor view - Code is poetry, bugs are typos'
711
+ st.markdown(Label)
712
  total_docs = len(documents)
713
  doc = documents[st.session_state.current_index]
714
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
715
+ doc_str = st.text_area("Edit Document",
716
+ value=json.dumps(doc, indent=2),
717
+ height=300,
718
+ key=f'code_editor_{st.session_state.current_index}')
719
+
720
+
721
+
722
+ # β¬…οΈβž‘οΈ Navigation and save controls
723
  col_prev, col_next = st.columns([1, 1])
724
  with col_prev:
725
  if st.button("⬅️ Previous", key='prev_code'):
 
731
  if st.session_state.current_index < total_docs - 1:
732
  st.session_state.current_index += 1
733
  st.rerun()
734
+
735
+
736
+
737
+ # πŸ’Ύ Save functionality - "Save early, save often"
738
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{st.session_state.current_index}'):
739
  try:
740
  updated_doc = json.loads(doc_str)
 
747
  st.error(message)
748
  except json.JSONDecodeError as e:
749
  st.error(f"Invalid JSON: {str(e)} 🚫")
750
+
751
+
752
 
753
+ elif selected_view == 'Show as Edit, Save, Run AI':
754
+ Label = '# ✏️ Edit and save view - Edit with wisdom, save with precision'
755
+ st.markdown(Label)
756
  st.markdown("#### Edit the document fields below:")
757
 
 
758
  num_cols = len(documents_to_display)
759
  cols = st.columns(num_cols)
760
 
761
+
762
+
763
  for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
764
  with col:
765
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
766
+ editable_id = st.text_input("ID", value=doc.get('id', ''),
767
+ key=f'edit_id_{idx}')
768
  editable_doc = doc.copy()
769
  editable_doc.pop('id', None)
770
+ doc_str = st.text_area("Document Content (in JSON format)",
771
+ value=json.dumps(editable_doc, indent=2),
772
+ height=300,
773
+ key=f'doc_str_{idx}')
774
+
775
+
776
 
777
+ # πŸ’ΎπŸ€– Save and AI operations
778
  col_save, col_ai = st.columns(2)
779
  with col_save:
780
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{idx}'):
781
  try:
782
  updated_doc = json.loads(doc_str)
783
+ updated_doc['id'] = editable_id
784
  success, message = update_record(container, updated_doc)
785
  if success:
786
  st.success(f"Document {updated_doc['id']} saved successfully.")
 
790
  st.error(message)
791
  except json.JSONDecodeError as e:
792
  st.error(f"Invalid JSON: {str(e)} 🚫")
793
+
794
+
795
  with col_ai:
796
+ if st.button("πŸ€– Run AI", key=f'run_with_ai_button_{idx}'):
 
797
  search_glossary(json.dumps(editable_doc, indent=2))
 
798
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
799
+
800
+
801
+
802
+
803
  with st.spinner("Cloning document..."):
804
+ cloned_id = save_or_clone_to_cosmos_db(container,
805
+ clone_id=doc['id'])
806
  if cloned_id:
807
  st.success(f"Document cloned successfully with new ID: {cloned_id}")
808
  st.rerun()
809
  else:
810
  st.error("Failed to clone document. Please try again.")
811
 
812
+
813
+
814
  elif selected_view == 'Clone Document':
815
+ if st.button("πŸ“„ Clone Document"):
816
+ clone_id = st.text_input("Enter Document ID to Clone")
817
+ if clone_id:
818
+ clone_record(container, clone_id)
819
+ Label = '# 🧬 Clone functionality - Copy wisely, paste precisely'
820
+ st.markdown(Label)
821
  st.markdown("#### Clone a document:")
822
  for idx, doc in enumerate(documents_to_display):
823
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
824
  if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
825
  cloned_doc = doc.copy()
 
826
  cloned_doc['id'] = generate_unique_id()
827
  st.session_state.cloned_doc = cloned_doc
828
  st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
 
830
  st.rerun()
831
  if st.session_state.get('clone_mode', False):
832
  st.markdown("#### Edit Cloned Document and Name Your Clone:")
833
+ cloned_doc_str = st.text_area("Cloned Document Content (in JSON format) - Update name please to make it unique before saving!",
834
+ value=st.session_state.cloned_doc_str,
835
+ height=300)
836
+
837
+
838
  if st.button("πŸ’Ύ Save Cloned Document"):
839
  try:
840
  new_doc = json.loads(cloned_doc_str)
 
850
  st.error(message)
851
  except json.JSONDecodeError as e:
852
  st.error(f"Invalid JSON: {str(e)} 🚫")
853
+
854
+
855
+
856
  elif selected_view == 'New Record':
857
+ Label = '# πŸ†• New Record view - Every new record is a new beginning'
858
+ st.markdown(Label)
859
+
860
+ if st.button("βž• Create New Blank Document"):
861
+ (container)
862
+
863
+
864
  st.markdown("#### Create a new document:")
865
+ #if st.button("πŸ€– Insert Auto-Generated Record"):
866
+ success, message = save_or_clone_to_cosmos_db(container,
867
+ query="Auto-generated",
868
+ response="This is an auto-generated record.")
869
+ if success:
870
+ st.success(message)
871
+ #st.rerun()
872
  else:
873
+ st.error(message)
874
+ #else:
875
+
876
+ new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
877
+ new_doc_str = st.text_area("Document Content (in JSON format)",
878
+ value='{}', height=300)
879
+ if st.button("βž• Create New Document"):
880
+ try:
881
+ new_doc = json.loads(new_doc_str)
882
+ new_doc['id'] = new_id
883
+ success, message = insert_record(container, new_doc)
884
+ if success:
885
+ st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
886
+ st.session_state.selected_document_id = new_doc['id']
887
+ #st.rerun()
888
+ else:
889
+ st.error(message)
890
+ except json.JSONDecodeError as e:
891
+ st.error(f"Invalid JSON: {str(e)} 🚫")
892
+
893
  else:
894
  st.sidebar.info("No documents found in this container. πŸ“­")
895
+
896
+
897
+
898
  st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
899
  if st.session_state.selected_container:
900
  if documents_to_display:
901
+ Label = '# πŸ“Š Data display - Data tells tales that words cannot'
902
+ st.markdown(Label)
903
  df = pd.DataFrame(documents_to_display)
904
  st.dataframe(df)
905
  else:
906
  st.info("No documents to display. 🧐")
907
+
908
+
909
 
910
+ Label = '# πŸ™ GitHub integration - Git happens'
911
  st.subheader("πŸ™ GitHub Operations")
912
+ github_token = os.environ.get("GITHUB")
913
+ source_repo = st.text_input("Source GitHub Repository URL",
914
+ value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
915
+ new_repo_name = st.text_input("New Repository Name (for cloning)",
916
+ value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
917
+
918
 
919
+
920
  col1, col2 = st.columns(2)
921
  with col1:
922
  if st.button("πŸ“₯ Clone Repository"):
923
  if github_token and source_repo:
924
+
925
+ st.markdown(Label)
926
  try:
927
  local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
928
  download_github_repo(source_repo, local_path)
 
939
  os.remove(zip_filename)
940
  else:
941
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
942
+
943
+
944
+
945
  with col2:
946
  if st.button("πŸ“€ Push to New Repository"):
947
  if github_token and source_repo:
948
+
949
+ st.markdown(Label)
950
  try:
951
  g = Github(github_token)
952
  new_repo = create_repo(g, new_repo_name)
 
962
  else:
963
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
964
 
965
+
966
+
967
  st.subheader("πŸ’¬ Chat with Claude")
968
  user_input = st.text_area("Message πŸ“¨:", height=100)
969
 
970
  if st.button("Send πŸ“¨"):
971
+ Label = '# πŸ’¬ Chat functionality - Every chat is a chance to learn'
972
+ st.markdown(Label)
973
  if user_input:
974
  response = client.messages.create(
975
  model="claude-3-sonnet-20240229",
 
989
  # Save to Cosmos DB
990
  save_to_cosmos_db(container, user_input, response.content[0].text, "")
991
 
992
+
993
+
994
+ # πŸ“œ Chat history display - "History repeats itself, first as chat, then as wisdom"
995
  st.subheader("Past Conversations πŸ“œ")
996
  for chat in st.session_state.chat_history:
997
  st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
998
  st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
999
  st.markdown("---")
1000
 
1001
+
1002
+
1003
+ # πŸ“ File editor - "Edit with care, save with flair"
1004
  if hasattr(st.session_state, 'current_file'):
1005
  st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
1006
  new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
 
1009
  file.write(new_content)
1010
  st.success("File updated successfully! πŸŽ‰")
1011
 
1012
+
1013
+
1014
+ # πŸ“‚ File management - "Manage many, maintain order"
1015
  st.sidebar.title("πŸ“ File Management")
1016
 
1017
  all_files = glob.glob("*.md")
 
1043
  os.remove(file)
1044
  st.rerun()
1045
 
1046
+
1047
+
1048
  except exceptions.CosmosHttpResponseError as e:
1049
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
1050
  except Exception as e:
1051
  st.error(f"An unexpected error occurred: {str(e)} 😱")
1052
 
1053
+
1054
+
1055
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
1056
+ Label = '# πŸšͺ Logout - All good things must come to an end'
1057
+ st.markdown(Label)
1058
  st.session_state.logged_in = False
1059
  st.session_state.selected_records.clear()
1060
  st.session_state.client = None