awacke1 commited on
Commit
905f9cb
β€’
1 Parent(s): d79f8d4

Update backup9clonesavenameatlast.app.py

Browse files
Files changed (1) hide show
  1. backup9clonesavenameatlast.app.py +353 -215
backup9clonesavenameatlast.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'
@@ -70,7 +73,9 @@ def get_download_link(file_path):
70
  def generate_unique_id():
71
  timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
72
  unique_uuid = str(uuid.uuid4())
73
- return f"{timestamp}-{unique_uuid}"
 
 
74
 
75
  # πŸ“ Generate a filename - Naming files like a pro (or a very confused librarian)
76
  def generate_filename(prompt, file_type):
@@ -244,20 +249,19 @@ def push_to_github(local_path, repo, github_token):
244
  origin.push(refspec=f'{current_branch}:{current_branch}')
245
 
246
 
247
-
248
- def save_or_clone_to_cosmos_db(container, query=None, response=None, clone_id=None):
249
  def generate_complex_unique_id():
250
  timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
251
  random_component = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))
252
  return f"{timestamp}-{random_component}-{str(uuid.uuid4())}"
253
 
254
  max_retries = 10
255
- base_delay = 0.1 # 100 ms
256
 
257
  for attempt in range(max_retries):
258
  try:
259
  new_id = generate_complex_unique_id()
260
-
261
  if clone_id:
262
  try:
263
  existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
@@ -269,96 +273,30 @@ def save_or_clone_to_cosmos_db(container, query=None, response=None, clone_id=No
269
  'cloned_at': datetime.utcnow().isoformat()
270
  }
271
  except exceptions.CosmosResourceNotFoundError:
272
- st.error(f"Document with ID {clone_id} not found for cloning.")
273
- return None
274
  else:
275
- new_doc = {
276
- 'id': new_id,
277
- 'query': query,
278
- 'response': response,
279
- 'created_at': datetime.utcnow().isoformat()
280
- }
281
-
282
- # Attempt to create the item
283
  response = container.create_item(body=new_doc)
284
-
285
- st.success(f"{'Cloned' if clone_id else 'New'} document saved successfully with ID: {response['id']}")
286
-
287
- # Refresh the documents in the session state
288
- st.session_state.documents = list(container.query_items(
289
- query="SELECT * FROM c ORDER BY c._ts DESC",
290
- enable_cross_partition_query=True
291
- ))
292
-
293
- return response['id']
294
 
295
  except exceptions.CosmosHttpResponseError as e:
296
- if e.status_code == 409: # Conflict error
297
  delay = base_delay * (2 ** attempt) + random.uniform(0, 0.1)
298
- st.warning(f"ID conflict occurred. Retrying in {delay:.2f} seconds... (Attempt {attempt + 1})")
299
  time.sleep(delay)
300
- else:
301
- st.error(f"Error saving to Cosmos DB: {e}")
302
- return None
303
-
304
  except Exception as e:
305
- st.error(f"An unexpected error occurred: {str(e)}")
306
- return None
307
-
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 +390,125 @@ 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 +526,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 +563,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 +618,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 +667,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 +689,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 +716,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 +732,47 @@ 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,69 +782,60 @@ 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
- st.markdown("#### Clone Document:")
 
687
  for idx, doc in enumerate(documents_to_display):
688
- st.markdown(f"##### Document ID: {doc.get('id', '')}")
689
- if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
690
- cloned_doc = doc.copy()
691
- # Generate new unique IDs
692
- new_id = str(uuid.uuid4())
693
- cloned_doc['id'] = new_id
694
- if 'name' in cloned_doc:
695
- cloned_doc['name'] = f"{cloned_doc['name']}_clone_{new_id[:8]}"
696
- st.session_state.cloned_doc = cloned_doc
697
- st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
698
- st.session_state.clone_mode = True
699
- st.rerun()
700
-
701
- if st.session_state.get('clone_mode', False):
702
- st.markdown("#### Edit Cloned Document:")
703
- cloned_doc_str = st.text_area(
704
- "Edit JSON content below:",
705
- value=st.session_state.cloned_doc_str,
706
- height=300
707
- )
708
 
709
- if st.button("πŸ’Ύ Save Cloned Document"):
710
- try:
711
- new_doc = json.loads(cloned_doc_str)
712
- success, message = insert_record(container, new_doc)
713
- if success:
714
- st.success(f"Cloned document saved successfully! πŸŽ‰")
715
- st.session_state.selected_document_id = new_doc['id']
716
- st.session_state.clone_mode = False
717
- st.session_state.cloned_doc = None
718
- st.session_state.cloned_doc_str = ''
719
- st.rerun()
720
- else:
721
- st.error(message)
722
- except json.JSONDecodeError as e:
723
- st.error(f"Invalid JSON: {str(e)} 🚫")
724
-
725
-
726
-
727
-
728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
729
  elif selected_view == 'New Record':
730
- # πŸ†• New Record
731
  st.markdown("#### Create a new document:")
 
732
  if st.button("πŸ€– Insert Auto-Generated Record"):
733
- success, message = save_or_clone_to_cosmos_db(container, query="Auto-generated", response="This is an auto-generated record.")
 
 
 
 
 
 
734
  if success:
735
  st.success(message)
736
  st.rerun()
@@ -738,44 +843,59 @@ def main():
738
  st.error(message)
739
  else:
740
  new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
741
- new_doc_str = st.text_area("Document Content (in JSON format)", value='{}', height=300)
 
 
 
 
 
 
 
 
 
742
  if st.button("βž• Create New Document"):
743
  try:
744
  new_doc = json.loads(new_doc_str)
745
- new_doc['id'] = new_id # Use the provided ID
746
  success, message = insert_record(container, new_doc)
747
  if success:
748
  st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
749
  st.session_state.selected_document_id = new_doc['id']
750
- # Switch to 'Show as Edit and Save' mode
751
  st.rerun()
752
  else:
753
  st.error(message)
754
  except json.JSONDecodeError as e:
755
  st.error(f"Invalid JSON: {str(e)} 🚫")
 
756
 
757
- else:
758
- st.sidebar.info("No documents found in this container. πŸ“­")
759
-
760
- # πŸŽ‰ Main content area
761
- st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
762
- if st.session_state.selected_container:
763
- if documents_to_display:
764
- df = pd.DataFrame(documents_to_display)
765
- st.dataframe(df)
766
- else:
767
- st.info("No documents to display. 🧐")
768
 
769
- # πŸ™ GitHub section
770
  st.subheader("πŸ™ GitHub Operations")
771
- github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
772
- source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
773
- new_repo_name = st.text_input("New Repository Name (for cloning)", value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
 
 
 
774
 
 
775
  col1, col2 = st.columns(2)
776
  with col1:
777
  if st.button("πŸ“₯ Clone Repository"):
778
  if github_token and source_repo:
 
 
779
  try:
780
  local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
781
  download_github_repo(source_repo, local_path)
@@ -792,10 +912,14 @@ def main():
792
  os.remove(zip_filename)
793
  else:
794
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
795
-
 
 
796
  with col2:
797
  if st.button("πŸ“€ Push to New Repository"):
798
  if github_token and source_repo:
 
 
799
  try:
800
  g = Github(github_token)
801
  new_repo = create_repo(g, new_repo_name)
@@ -811,11 +935,14 @@ def main():
811
  else:
812
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
813
 
814
- # πŸ’¬ Chat with Claude
 
815
  st.subheader("πŸ’¬ Chat with Claude")
816
  user_input = st.text_area("Message πŸ“¨:", height=100)
817
 
818
  if st.button("Send πŸ“¨"):
 
 
819
  if user_input:
820
  response = client.messages.create(
821
  model="claude-3-sonnet-20240229",
@@ -835,14 +962,18 @@ def main():
835
  # Save to Cosmos DB
836
  save_to_cosmos_db(container, user_input, response.content[0].text, "")
837
 
838
- # Display Chat History
 
 
839
  st.subheader("Past Conversations πŸ“œ")
840
  for chat in st.session_state.chat_history:
841
  st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
842
  st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
843
  st.markdown("---")
844
 
845
- # File Editor
 
 
846
  if hasattr(st.session_state, 'current_file'):
847
  st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
848
  new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
@@ -851,7 +982,9 @@ def main():
851
  file.write(new_content)
852
  st.success("File updated successfully! πŸŽ‰")
853
 
854
- # File Management
 
 
855
  st.sidebar.title("πŸ“ File Management")
856
 
857
  all_files = glob.glob("*.md")
@@ -883,13 +1016,18 @@ def main():
883
  os.remove(file)
884
  st.rerun()
885
 
 
 
886
  except exceptions.CosmosHttpResponseError as e:
887
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
888
  except Exception as e:
889
  st.error(f"An unexpected error occurred: {str(e)} 😱")
890
 
891
- # πŸšͺ Logout button
 
892
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
 
 
893
  st.session_state.logged_in = False
894
  st.session_state.selected_records.clear()
895
  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'
 
73
  def generate_unique_id():
74
  timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
75
  unique_uuid = str(uuid.uuid4())
76
+ returnValue = f"{timestamp}-{unique_uuid}"
77
+ st.write('New Unique ID:' + returnValue)
78
+ return
79
 
80
  # πŸ“ Generate a filename - Naming files like a pro (or a very confused librarian)
81
  def generate_filename(prompt, file_type):
 
249
  origin.push(refspec=f'{current_branch}:{current_branch}')
250
 
251
 
252
+ def save_or_clone_to_cosmos_db(container, document=None, clone_id=None):
 
253
  def generate_complex_unique_id():
254
  timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
255
  random_component = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))
256
  return f"{timestamp}-{random_component}-{str(uuid.uuid4())}"
257
 
258
  max_retries = 10
259
+ base_delay = 0.1
260
 
261
  for attempt in range(max_retries):
262
  try:
263
  new_id = generate_complex_unique_id()
264
+
265
  if clone_id:
266
  try:
267
  existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
 
273
  'cloned_at': datetime.utcnow().isoformat()
274
  }
275
  except exceptions.CosmosResourceNotFoundError:
276
+ return False, f"Document with ID {clone_id} not found for cloning."
 
277
  else:
278
+ if document is None:
279
+ return False, "No document provided for saving"
280
+
281
+ document['id'] = new_id
282
+ document['created_at'] = datetime.utcnow().isoformat()
283
+ new_doc = document
284
+
 
285
  response = container.create_item(body=new_doc)
286
+ return True, f"{'Cloned' if clone_id else 'New'} document saved successfully with ID: {response['id']}"
 
 
 
 
 
 
 
 
 
287
 
288
  except exceptions.CosmosHttpResponseError as e:
289
+ if e.status_code == 409:
290
  delay = base_delay * (2 ** attempt) + random.uniform(0, 0.1)
 
291
  time.sleep(delay)
292
+ continue
293
+ return False, f"Error saving to Cosmos DB: {str(e)}"
 
 
294
  except Exception as e:
295
+ return False, f"An unexpected error occurred: {str(e)}"
 
 
 
 
 
 
296
 
297
+ return False, "Failed to save document after maximum retries."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
+
300
  # πŸ“¦ Archive current container - Packing up data like you're moving to a new digital house
301
  def archive_current_container(database_name, container_name, client):
302
  try:
 
390
 
391
  return result, result2, result3, response2
392
 
393
+
394
+
395
+
396
+
397
+ # πŸ“ Generate a safe filename from the first few lines of content
398
+ def generate_filename_from_content(content, file_type="md"):
399
+ # Extract the first few lines or sentences
400
+ first_sentence = content.split('\n', 1)[0][:90] # Limit the length to 90 characters
401
+ # Remove special characters to make it a valid filename
402
+ safe_name = re.sub(r'[^\w\s-]', '', first_sentence)
403
+ # Limit length to be compatible with Windows and Linux
404
+ safe_name = safe_name[:50].strip() # Adjust length limit
405
+ return f"{safe_name}.{file_type}"
406
+
407
+ # πŸ’Ύ Create and save a file
408
+ def create_file_from_content(content, should_save=True):
409
+ if not should_save:
410
+ return
411
+ filename = generate_filename_from_content(content)
412
+ with open(filename, 'w', encoding='utf-8') as file:
413
+ file.write(content)
414
+ return filename
415
+
416
+ # πŸ“‚ Display list of saved .md files in the sidebar
417
+ def display_saved_files_in_sidebar():
418
+ all_files = glob.glob("*.md")
419
+ all_files.sort(reverse=True)
420
+ all_files = [file for file in all_files if not file.lower().startswith('readme')] # Exclude README.md
421
+
422
+ st.sidebar.markdown("## πŸ“ Saved Markdown Files")
423
+ for file in all_files:
424
+ col1, col2, col3 = st.sidebar.columns([6, 2, 1])
425
+ with col1:
426
+ st.markdown(f"πŸ“„ {file}")
427
+ with col2:
428
+ st.sidebar.download_button(
429
+ label="⬇️ Download",
430
+ data=open(file, 'rb').read(),
431
+ file_name=file
432
+ )
433
+ with col3:
434
+ if st.sidebar.button("πŸ—‘", key=f"delete_{file}"):
435
+ os.remove(file)
436
+ st.rerun()
437
+
438
+
439
+ def clone_record(container, clone_id):
440
+ try:
441
+ existing_doc = container.read_item(item=clone_id, partition_key=clone_id)
442
+ new_doc = existing_doc.copy()
443
+ new_doc['id'] = generate_unique_id() # Generate new unique ID with timestamp
444
+ new_doc['name'] = new_doc['id'] # Generate new unique ID with timestamp
445
+ new_doc['createdAt'] = datetime.utcnow().isoformat() # Update the creation time
446
+ new_doc['_rid'] = None # Reset _rid or any system-managed fields
447
+ new_doc['_self'] = None
448
+ new_doc['_etag'] = None
449
+ new_doc['_attachments'] = None
450
+ new_doc['_ts'] = None # Reset timestamp to be updated by Cosmos DB automatically
451
+
452
+ # Insert the cloned document
453
+ response = container.create_item(body=new_doc)
454
+ st.success(f"Cloned document saved successfully with ID: {new_doc['id']} πŸŽ‰")
455
+
456
+ # Refresh the documents in session state
457
+ st.session_state.documents = list(container.query_items(
458
+ query="SELECT * FROM c ORDER BY c._ts DESC",
459
+ enable_cross_partition_query=True
460
+ ))
461
+
462
+ except exceptions.CosmosResourceNotFoundError:
463
+ st.error(f"Document with ID {clone_id} not found for cloning.")
464
+ except exceptions.CosmosHttpResponseError as e:
465
+ st.error(f"HTTP error occurred: {str(e)} 🚨")
466
+ except Exception as e:
467
+ st.error(f"An unexpected error occurred: {str(e)} 😱")
468
+
469
+
470
+
471
+
472
+ def create_new_blank_record(container):
473
+ try:
474
+ # Get the structure of the latest document (to preserve schema)
475
+ latest_doc = container.query_items(query="SELECT * FROM c ORDER BY c._ts DESC", enable_cross_partition_query=True, max_item_count=1)
476
+ if latest_doc:
477
+ new_doc_structure = latest_doc[0].copy()
478
+ else:
479
+ new_doc_structure = {}
480
+
481
+ new_doc = {key: "" for key in new_doc_structure.keys()} # Set all fields to blank
482
+ new_doc['id'] = generate_unique_id() # Generate new unique ID
483
+ new_doc['createdAt'] = datetime.utcnow().isoformat() # Set creation time
484
+
485
+ # Insert the new blank document
486
+ response = container.create_item(body=new_doc)
487
+ st.success(f"New blank document saved successfully with ID: {new_doc['id']} πŸŽ‰")
488
+
489
+ # Refresh the documents in session state
490
+ st.session_state.documents = list(container.query_items(
491
+ query="SELECT * FROM c ORDER BY c._ts DESC",
492
+ enable_cross_partition_query=True
493
+ ))
494
+
495
+ except exceptions.CosmosHttpResponseError as e:
496
+ st.error(f"HTTP error occurred: {str(e)} 🚨")
497
+ except Exception as e:
498
+ st.error(f"An unexpected error occurred: {str(e)} 😱")
499
+
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)
544
+ st.success(f"File saved: {filename}")
545
+ filename = create_file_from_content(result3)
546
+ st.success(f"File saved: {filename}")
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.sidebar.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
 
637
  if total_docs > 5:
638
  documents_to_display = documents[:5]
639
+ st.sidebar.info("Showing top 5 most recent documents.")
640
  else:
641
  documents_to_display = documents
642
+ st.sidebar.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', 'Show as Edit, Save, Run AI', 'Clone Document', 'New Record']
647
+ selected_view = st.sidebar.selectbox("Select Viewer/Editor", view_options, index=2)
648
 
649
  if selected_view == 'Show as Markdown':
650
+ Label = '# πŸ“„ Markdown view - Mark it down, mark it up'
651
+ st.markdown(Label)
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
  elif selected_view == 'Show as Code Editor':
695
+ Label = '# πŸ’» Code editor view - Code is poetry, bugs are typos'
696
+ st.markdown(Label)
697
  total_docs = len(documents)
698
  doc = documents[st.session_state.current_index]
699
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
700
+ doc_str = st.text_area("Edit Document",
701
+ value=json.dumps(doc, indent=2),
702
+ height=300,
703
+ key=f'code_editor_{st.session_state.current_index}')
704
+
705
+
706
+
707
+ # β¬…οΈβž‘οΈ Navigation and save controls
708
  col_prev, col_next = st.columns([1, 1])
709
  with col_prev:
710
  if st.button("⬅️ Previous", key='prev_code'):
 
716
  if st.session_state.current_index < total_docs - 1:
717
  st.session_state.current_index += 1
718
  st.rerun()
719
+
720
+
721
+
722
+ # πŸ’Ύ Save functionality - "Save early, save often"
723
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{st.session_state.current_index}'):
724
  try:
725
  updated_doc = json.loads(doc_str)
 
732
  st.error(message)
733
  except json.JSONDecodeError as e:
734
  st.error(f"Invalid JSON: {str(e)} 🚫")
735
+
736
+
737
 
738
+ elif selected_view == 'Show as Edit, Save, Run AI':
739
+ Label = '# ✏️ Edit and save view - Edit with wisdom, save with precision'
740
+ st.markdown(Label)
741
  st.markdown("#### Edit the document fields below:")
742
 
 
743
  num_cols = len(documents_to_display)
744
  cols = st.columns(num_cols)
745
 
746
+
747
+
748
  for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
749
  with col:
750
+
751
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
752
  editable_id = st.text_input("ID", value=doc.get('id', ''), key=f'edit_id_{idx}')
 
753
  editable_doc = doc.copy()
754
  editable_doc.pop('id', None)
755
+
756
+ st.markdown(f"##### Document Name: {doc.get('name', '')}")
757
+ editable_id = st.text_input("Name", value=doc.get('name', ''), key=f'edit_name_{idx}')
758
+ editable_doc = doc.copy()
759
+ editable_doc.pop('name', None)
760
+
761
 
762
+ doc_str = st.text_area("Document Content (in JSON format)",
763
+ value=json.dumps(editable_doc, indent=2),
764
+ height=300,
765
+ key=f'doc_str_{idx}')
766
+
767
+
768
+
769
+ # πŸ’ΎπŸ€– Save and AI operations
770
  col_save, col_ai = st.columns(2)
771
  with col_save:
772
  if st.button("πŸ’Ύ Save Changes", key=f'save_button_{idx}'):
773
  try:
774
  updated_doc = json.loads(doc_str)
775
+ updated_doc['id'] = editable_id
776
  success, message = update_record(container, updated_doc)
777
  if success:
778
  st.success(f"Document {updated_doc['id']} saved successfully.")
 
782
  st.error(message)
783
  except json.JSONDecodeError as e:
784
  st.error(f"Invalid JSON: {str(e)} 🚫")
785
+
786
+
787
  with col_ai:
788
+ if st.button("πŸ€– Run AI", key=f'run_with_ai_button_{idx}'):
 
789
  search_glossary(json.dumps(editable_doc, indent=2))
 
 
 
 
 
 
 
 
 
790
 
791
+
792
  elif selected_view == 'Clone Document':
793
+ st.markdown("#### Clone a document:")
794
+
795
  for idx, doc in enumerate(documents_to_display):
796
+ st.markdown(f"##### Original Document ID: {doc.get('id', '')}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
797
 
798
+ if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
799
+ # Create new document with unique ID and name
800
+ new_doc = {
801
+ 'id': str(uuid.uuid4()),
802
+ 'name': f"Clone_{str(uuid.uuid4())[:8]}",
803
+ **{k: v for k, v in doc.items() if k not in ['id', 'name', '_rid', '_self', '_etag', '_attachments', '_ts']}
804
+ }
805
+
806
+ # Show editable preview
807
+ edited_doc = st.text_area(
808
+ "Edit cloned document:",
809
+ value=json.dumps(new_doc, indent=2),
810
+ height=300,
811
+ key=f'edit_clone_{idx}'
812
+ )
 
 
 
 
813
 
814
+ if st.button("πŸ’Ύ Save Clone", key=f'save_clone_{idx}'):
815
+ try:
816
+ final_doc = json.loads(edited_doc)
817
+ # Use container.create_item() instead of update_record()
818
+ response = container.create_item(body=final_doc)
819
+ if response:
820
+ st.success(f"New cloned document created with ID: {final_doc['id']}")
821
+ st.rerun()
822
+ else:
823
+ st.error("Failed to create new document")
824
+ except Exception as e:
825
+ st.error(f"Error creating document: {str(e)}")
826
+
827
+ #elif selected_view == 'New Record':
828
  elif selected_view == 'New Record':
 
829
  st.markdown("#### Create a new document:")
830
+
831
  if st.button("πŸ€– Insert Auto-Generated Record"):
832
+ auto_doc = {
833
+ "id": generate_unique_id(),
834
+ "name": f"Auto-generated Record {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
835
+ "content": "This is an auto-generated record.",
836
+ "timestamp": datetime.now().isoformat()
837
+ }
838
+ success, message = save_or_clone_to_cosmos_db(container, document=auto_doc)
839
  if success:
840
  st.success(message)
841
  st.rerun()
 
843
  st.error(message)
844
  else:
845
  new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
846
+ default_doc = {
847
+ "id": new_id,
848
+ "name": "New Document",
849
+ "content": "",
850
+ "timestamp": datetime.now().isoformat()
851
+ }
852
+ new_doc_str = st.text_area("Document Content (in JSON format)",
853
+ value=json.dumps(default_doc, indent=2),
854
+ height=300)
855
+
856
  if st.button("βž• Create New Document"):
857
  try:
858
  new_doc = json.loads(new_doc_str)
859
+ new_doc['id'] = new_id # Ensure ID matches input field
860
  success, message = insert_record(container, new_doc)
861
  if success:
862
  st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
863
  st.session_state.selected_document_id = new_doc['id']
 
864
  st.rerun()
865
  else:
866
  st.error(message)
867
  except json.JSONDecodeError as e:
868
  st.error(f"Invalid JSON: {str(e)} 🚫")
869
+
870
 
871
+ st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
872
+ if st.session_state.selected_container:
873
+ if documents_to_display:
874
+ Label = '# πŸ“Š Data display - Data tells tales that words cannot'
875
+ st.markdown(Label)
876
+ df = pd.DataFrame(documents_to_display)
877
+ st.dataframe(df)
878
+ else:
879
+ st.info("No documents to display. 🧐")
880
+
881
+
882
 
883
+ Label = '# πŸ™ GitHub integration - Git happens'
884
  st.subheader("πŸ™ GitHub Operations")
885
+ github_token = os.environ.get("GITHUB")
886
+ source_repo = st.text_input("Source GitHub Repository URL",
887
+ value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
888
+ new_repo_name = st.text_input("New Repository Name (for cloning)",
889
+ value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
890
+
891
 
892
+
893
  col1, col2 = st.columns(2)
894
  with col1:
895
  if st.button("πŸ“₯ Clone Repository"):
896
  if github_token and source_repo:
897
+
898
+ st.markdown(Label)
899
  try:
900
  local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
901
  download_github_repo(source_repo, local_path)
 
912
  os.remove(zip_filename)
913
  else:
914
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
915
+
916
+
917
+
918
  with col2:
919
  if st.button("πŸ“€ Push to New Repository"):
920
  if github_token and source_repo:
921
+
922
+ st.markdown(Label)
923
  try:
924
  g = Github(github_token)
925
  new_repo = create_repo(g, new_repo_name)
 
935
  else:
936
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
937
 
938
+
939
+
940
  st.subheader("πŸ’¬ Chat with Claude")
941
  user_input = st.text_area("Message πŸ“¨:", height=100)
942
 
943
  if st.button("Send πŸ“¨"):
944
+ Label = '# πŸ’¬ Chat functionality - Every chat is a chance to learn'
945
+ st.markdown(Label)
946
  if user_input:
947
  response = client.messages.create(
948
  model="claude-3-sonnet-20240229",
 
962
  # Save to Cosmos DB
963
  save_to_cosmos_db(container, user_input, response.content[0].text, "")
964
 
965
+
966
+
967
+ # πŸ“œ Chat history display - "History repeats itself, first as chat, then as wisdom"
968
  st.subheader("Past Conversations πŸ“œ")
969
  for chat in st.session_state.chat_history:
970
  st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
971
  st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
972
  st.markdown("---")
973
 
974
+
975
+
976
+ # πŸ“ File editor - "Edit with care, save with flair"
977
  if hasattr(st.session_state, 'current_file'):
978
  st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
979
  new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
 
982
  file.write(new_content)
983
  st.success("File updated successfully! πŸŽ‰")
984
 
985
+
986
+
987
+ # πŸ“‚ File management - "Manage many, maintain order"
988
  st.sidebar.title("πŸ“ File Management")
989
 
990
  all_files = glob.glob("*.md")
 
1016
  os.remove(file)
1017
  st.rerun()
1018
 
1019
+
1020
+
1021
  except exceptions.CosmosHttpResponseError as e:
1022
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
1023
  except Exception as e:
1024
  st.error(f"An unexpected error occurred: {str(e)} 😱")
1025
 
1026
+
1027
+
1028
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
1029
+ Label = '# πŸšͺ Logout - All good things must come to an end'
1030
+ st.markdown(Label)
1031
  st.session_state.logged_in = False
1032
  st.session_state.selected_records.clear()
1033
  st.session_state.client = None