Spaces:
Sleeping
Sleeping
Update backup9clonesavenameatlast.app.py
Browse files- backup9clonesavenameatlast.app.py +353 -215
backup9clonesavenameatlast.app.py
CHANGED
@@ -1,25 +1,28 @@
|
|
1 |
-
|
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 |
-
|
20 |
-
import
|
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 |
-
|
|
|
|
|
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
|
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 |
-
|
273 |
-
return None
|
274 |
else:
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
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:
|
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 |
-
|
301 |
-
|
302 |
-
return None
|
303 |
-
|
304 |
except Exception as e:
|
305 |
-
|
306 |
-
return None
|
307 |
-
|
308 |
-
st.error("Failed to save document after maximum retries.")
|
309 |
-
return None
|
310 |
-
|
311 |
-
|
312 |
|
313 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
456 |
def main():
|
457 |
st.title("πGitπCosmosπ« - Azure Cosmos DB and Github Agent")
|
458 |
|
459 |
-
|
|
|
|
|
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 |
-
|
|
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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()
|
497 |
except Exception as e:
|
498 |
st.markdown(' ')
|
499 |
|
500 |
-
|
|
|
|
|
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
|
|
|
507 |
|
|
|
508 |
if st.session_state.logged_in:
|
509 |
-
# π
|
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 |
-
#
|
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 |
-
# π¦
|
542 |
-
if st.button("π¦ Export Container Data"):
|
543 |
-
download_link = archive_current_container(st.session_state.selected_database,
|
|
|
|
|
544 |
if download_link.startswith('<a'):
|
545 |
st.markdown(download_link, unsafe_allow_html=True)
|
546 |
else:
|
547 |
st.error(download_link)
|
|
|
|
|
548 |
|
549 |
-
#
|
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 |
-
# π¨
|
562 |
-
view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit
|
563 |
-
selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
|
564 |
|
565 |
if selected_view == 'Show as Markdown':
|
566 |
-
#
|
|
|
567 |
total_docs = len(documents)
|
568 |
doc = documents[st.session_state.current_index]
|
569 |
st.markdown(f"#### Document ID: {doc.get('id', '')}")
|
570 |
|
571 |
-
#
|
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 |
-
|
|
|
|
|
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 |
-
# π»
|
|
|
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",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
639 |
-
# βοΈ
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
654 |
|
655 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
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
|
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
|
|
|
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("
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
742 |
if st.button("β Create New Document"):
|
743 |
try:
|
744 |
new_doc = json.loads(new_doc_str)
|
745 |
-
new_doc['id'] = new_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 |
-
|
758 |
-
|
759 |
-
|
760 |
-
|
761 |
-
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
|
768 |
|
769 |
-
# π GitHub
|
770 |
st.subheader("π GitHub Operations")
|
771 |
-
github_token = os.environ.get("GITHUB")
|
772 |
-
source_repo = st.text_input("Source GitHub Repository URL",
|
773 |
-
|
|
|
|
|
|
|
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 |
-
|
|
|
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 |
-
|
|
|
|
|
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 |
-
|
|
|
|
|
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 |
-
|
|
|
|
|
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 |
-
|
|
|
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
|