Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,29 +12,34 @@ from datetime import datetime
|
|
| 12 |
import base64
|
| 13 |
import json
|
| 14 |
|
|
|
|
| 15 |
st.set_page_config(layout="wide")
|
| 16 |
|
| 17 |
-
# Cosmos DB configuration
|
| 18 |
ENDPOINT = "https://acae-afd.documents.azure.com:443/"
|
| 19 |
SUBSCRIPTION_ID = "003fba60-5b3f-48f4-ab36-3ed11bc40816"
|
| 20 |
DATABASE_NAME = os.environ.get("COSMOS_DATABASE_NAME")
|
| 21 |
CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
|
| 22 |
-
Key = os.environ.get("Key")
|
| 23 |
|
| 24 |
-
# GitHub configuration
|
| 25 |
def download_github_repo(url, local_path):
|
|
|
|
| 26 |
if os.path.exists(local_path):
|
| 27 |
shutil.rmtree(local_path)
|
| 28 |
Repo.clone_from(url, local_path)
|
| 29 |
|
| 30 |
def create_zip_file(source_dir, output_filename):
|
|
|
|
| 31 |
shutil.make_archive(output_filename, 'zip', source_dir)
|
| 32 |
|
| 33 |
def create_repo(g, repo_name):
|
|
|
|
| 34 |
user = g.get_user()
|
| 35 |
return user.create_repo(repo_name)
|
| 36 |
|
| 37 |
def push_to_github(local_path, repo, github_token):
|
|
|
|
| 38 |
repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
|
| 39 |
local_repo = Repo(local_path)
|
| 40 |
|
|
@@ -58,83 +63,60 @@ def push_to_github(local_path, repo, github_token):
|
|
| 58 |
origin.push(refspec=f'{current_branch}:{current_branch}')
|
| 59 |
|
| 60 |
def get_base64_download_link(file_path, file_name):
|
|
|
|
| 61 |
with open(file_path, "rb") as file:
|
| 62 |
contents = file.read()
|
| 63 |
base64_encoded = base64.b64encode(contents).decode()
|
| 64 |
-
return f'<a href="data:application/zip;base64,{base64_encoded}" download="{file_name}"
|
| 65 |
|
| 66 |
|
| 67 |
-
# New functions for dynamic sidebar
|
| 68 |
def get_databases(client):
|
|
|
|
| 69 |
return [db['id'] for db in client.list_databases()]
|
| 70 |
|
| 71 |
def get_containers(database):
|
|
|
|
| 72 |
return [container['id'] for container in database.list_containers()]
|
| 73 |
|
| 74 |
def get_documents(container, limit=1000):
|
|
|
|
| 75 |
query = "SELECT * FROM c"
|
| 76 |
items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
|
| 77 |
return items
|
| 78 |
|
| 79 |
|
| 80 |
-
# Cosmos DB functions
|
| 81 |
-
def insert_record(record):
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
return True,
|
| 85 |
except exceptions.CosmosHttpResponseError as e:
|
| 86 |
-
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
| 87 |
except Exception as e:
|
| 88 |
-
return False, f"An unexpected error occurred: {str(e)}"
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
try:
|
| 92 |
-
response = container.scripts.execute_stored_procedure(
|
| 93 |
-
sproc="processPrompt",
|
| 94 |
-
params=[record],
|
| 95 |
-
partition_key=record['id']
|
| 96 |
-
)
|
| 97 |
-
return True, response
|
| 98 |
-
except exceptions.CosmosHttpResponseError as e:
|
| 99 |
-
error_message = f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
| 100 |
-
return False, error_message
|
| 101 |
-
except Exception as e:
|
| 102 |
-
error_message = f"An unexpected error occurred: {str(e)}"
|
| 103 |
-
return False, error_message
|
| 104 |
-
|
| 105 |
-
def fetch_all_records():
|
| 106 |
-
try:
|
| 107 |
-
query = "SELECT * FROM c"
|
| 108 |
-
items = list(container.query_items(query=query, enable_cross_partition_query=True))
|
| 109 |
-
return pd.DataFrame(items)
|
| 110 |
-
except exceptions.CosmosHttpResponseError as e:
|
| 111 |
-
st.error(f"HTTP error occurred while fetching records: {str(e)}. Status code: {e.status_code}")
|
| 112 |
-
return pd.DataFrame()
|
| 113 |
-
except Exception as e:
|
| 114 |
-
st.error(f"An unexpected error occurred while fetching records: {str(e)}")
|
| 115 |
-
return pd.DataFrame()
|
| 116 |
-
|
| 117 |
-
def update_record(updated_record):
|
| 118 |
try:
|
| 119 |
container.upsert_item(body=updated_record)
|
| 120 |
-
return True, f"Record with id {updated_record['id']} successfully updated."
|
| 121 |
except exceptions.CosmosHttpResponseError as e:
|
| 122 |
-
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
| 123 |
except Exception as e:
|
| 124 |
-
return False, f"An unexpected error occurred: {traceback.format_exc()}"
|
| 125 |
|
| 126 |
-
def delete_record(name, id):
|
| 127 |
try:
|
| 128 |
container.delete_item(item=id, partition_key=id)
|
| 129 |
-
return True, f"Successfully deleted record with name: {name} and id: {id}"
|
| 130 |
except exceptions.CosmosResourceNotFoundError:
|
| 131 |
-
return False, f"Record with id {id} not found. It may have been already deleted."
|
| 132 |
except exceptions.CosmosHttpResponseError as e:
|
| 133 |
-
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
| 134 |
except Exception as e:
|
| 135 |
-
return False, f"An unexpected error occurred: {traceback.format_exc()}"
|
| 136 |
|
| 137 |
-
#
|
| 138 |
def archive_current_container(database_name, container_name, client):
|
| 139 |
try:
|
| 140 |
base_dir = "./cosmos_archive_current_container"
|
|
@@ -159,14 +141,14 @@ def archive_current_container(database_name, container_name, client):
|
|
| 159 |
|
| 160 |
return get_base64_download_link(f"{archive_name}.zip", f"{archive_name}.zip")
|
| 161 |
except Exception as e:
|
| 162 |
-
return f"An error occurred while archiving data: {str(e)}"
|
| 163 |
|
| 164 |
|
| 165 |
-
#
|
| 166 |
def main():
|
| 167 |
st.title("π Cosmos DB and GitHub Integration")
|
| 168 |
|
| 169 |
-
# Initialize session state
|
| 170 |
if 'logged_in' not in st.session_state:
|
| 171 |
st.session_state.logged_in = False
|
| 172 |
if 'selected_records' not in st.session_state:
|
|
@@ -178,27 +160,27 @@ def main():
|
|
| 178 |
if 'selected_container' not in st.session_state:
|
| 179 |
st.session_state.selected_container = None
|
| 180 |
|
| 181 |
-
# Login section
|
| 182 |
if not st.session_state.logged_in:
|
| 183 |
st.subheader("π Login")
|
| 184 |
-
#
|
| 185 |
-
input_key=Key
|
| 186 |
|
| 187 |
-
#
|
| 188 |
if st.button("π Login"):
|
| 189 |
if input_key:
|
| 190 |
st.session_state.primary_key = input_key
|
| 191 |
st.session_state.logged_in = True
|
| 192 |
-
st.
|
| 193 |
else:
|
| 194 |
-
st.error("Invalid key. Please check your input.")
|
| 195 |
else:
|
| 196 |
-
# Initialize Cosmos DB client
|
| 197 |
try:
|
| 198 |
if st.session_state.client is None:
|
| 199 |
st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
|
| 200 |
|
| 201 |
-
# Sidebar for database, container, and document selection
|
| 202 |
st.sidebar.title("ποΈ Cosmos DB Navigator")
|
| 203 |
|
| 204 |
databases = get_databases(st.session_state.client)
|
|
@@ -207,7 +189,7 @@ def main():
|
|
| 207 |
if selected_db != st.session_state.selected_database:
|
| 208 |
st.session_state.selected_database = selected_db
|
| 209 |
st.session_state.selected_container = None
|
| 210 |
-
st.
|
| 211 |
|
| 212 |
if st.session_state.selected_database:
|
| 213 |
database = st.session_state.client.get_database_client(st.session_state.selected_database)
|
|
@@ -216,12 +198,12 @@ def main():
|
|
| 216 |
|
| 217 |
if selected_container != st.session_state.selected_container:
|
| 218 |
st.session_state.selected_container = selected_container
|
| 219 |
-
st.
|
| 220 |
|
| 221 |
if st.session_state.selected_container:
|
| 222 |
container = database.get_container_client(st.session_state.selected_container)
|
| 223 |
|
| 224 |
-
# Add Export button
|
| 225 |
if st.button("π¦ Export Container Data"):
|
| 226 |
download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
|
| 227 |
if download_link.startswith('<a'):
|
|
@@ -240,78 +222,78 @@ def main():
|
|
| 240 |
st.subheader(f"π Document Details: {selected_document}")
|
| 241 |
selected_doc = next((doc for doc in documents if doc.get('id') == selected_document), None)
|
| 242 |
if selected_doc:
|
| 243 |
-
# Add Viewer/Editor selection
|
| 244 |
view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
|
| 245 |
selected_view = st.selectbox("Select Viewer/Editor", view_options)
|
| 246 |
-
|
| 247 |
if selected_view == 'Show as Markdown':
|
| 248 |
-
# Show as Markdown
|
| 249 |
items = get_documents(container)
|
| 250 |
for item in items:
|
| 251 |
-
st.markdown(f"### ID: {item.get('id', 'Unknown')}")
|
| 252 |
content = item.get('content', '')
|
| 253 |
if isinstance(content, dict) or isinstance(content, list):
|
| 254 |
content = json.dumps(content, indent=2)
|
| 255 |
st.markdown(content)
|
| 256 |
elif selected_view == 'Show as Code Editor':
|
| 257 |
-
# Show as Code Editor
|
| 258 |
items = get_documents(container)
|
| 259 |
for item in items:
|
| 260 |
st.code(json.dumps(item, indent=2), language='python')
|
| 261 |
elif selected_view == 'Show as Edit and Save':
|
| 262 |
-
# Show as Edit and Save
|
| 263 |
doc_str = st.text_area("Edit Document", value=json.dumps(selected_doc, indent=2), height=300)
|
| 264 |
if st.button("πΎ Save"):
|
| 265 |
try:
|
| 266 |
updated_doc = json.loads(doc_str)
|
| 267 |
-
success, message = update_record(updated_doc)
|
| 268 |
if success:
|
| 269 |
st.success(message)
|
| 270 |
else:
|
| 271 |
st.error(message)
|
| 272 |
except json.JSONDecodeError as e:
|
| 273 |
-
st.error(f"Invalid JSON: {str(e)}")
|
| 274 |
elif selected_view == 'Clone Document':
|
| 275 |
-
# Clone Document
|
| 276 |
if st.button("π Clone Document"):
|
| 277 |
cloned_doc = selected_doc.copy()
|
| 278 |
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
|
| 279 |
cloned_doc['id'] = f"{cloned_doc['id']}_clone_{timestamp}"
|
| 280 |
-
success, message = insert_record(cloned_doc)
|
| 281 |
if success:
|
| 282 |
-
st.success(f"Document cloned with new id: {cloned_doc['id']}")
|
| 283 |
else:
|
| 284 |
st.error(message)
|
| 285 |
elif selected_view == 'New Record':
|
| 286 |
-
# New Record
|
| 287 |
new_doc_str = st.text_area("New Document", value='{}', height=300)
|
| 288 |
if st.button("β Create New Document"):
|
| 289 |
try:
|
| 290 |
new_doc = json.loads(new_doc_str)
|
| 291 |
if 'id' not in new_doc:
|
| 292 |
new_doc['id'] = f"new_doc_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
| 293 |
-
success, message = insert_record(new_doc)
|
| 294 |
if success:
|
| 295 |
-
st.success(f"New document created with id: {new_doc['id']}")
|
| 296 |
else:
|
| 297 |
st.error(message)
|
| 298 |
except json.JSONDecodeError as e:
|
| 299 |
-
st.error(f"Invalid JSON: {str(e)}")
|
| 300 |
else:
|
| 301 |
-
st.sidebar.info("No documents found in this container.")
|
| 302 |
|
| 303 |
-
# Main content area
|
| 304 |
st.subheader(f"π Container: {st.session_state.selected_container}")
|
| 305 |
if st.session_state.selected_container:
|
| 306 |
df = pd.DataFrame(documents)
|
| 307 |
st.dataframe(df)
|
| 308 |
|
| 309 |
-
# GitHub section
|
| 310 |
st.subheader("π GitHub Operations")
|
| 311 |
github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
|
| 312 |
source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
|
| 313 |
new_repo_name = st.text_input("New Repository Name (for cloning)", value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
|
| 314 |
-
|
| 315 |
col1, col2 = st.columns(2)
|
| 316 |
with col1:
|
| 317 |
if st.button("π₯ Clone Repository"):
|
|
@@ -322,16 +304,16 @@ def main():
|
|
| 322 |
zip_filename = f"{new_repo_name}.zip"
|
| 323 |
create_zip_file(local_path, zip_filename[:-4])
|
| 324 |
st.markdown(get_base64_download_link(zip_filename, zip_filename), unsafe_allow_html=True)
|
| 325 |
-
st.success("Repository cloned successfully!")
|
| 326 |
except Exception as e:
|
| 327 |
-
st.error(f"An error occurred: {str(e)}")
|
| 328 |
finally:
|
| 329 |
if os.path.exists(local_path):
|
| 330 |
shutil.rmtree(local_path)
|
| 331 |
if os.path.exists(zip_filename):
|
| 332 |
os.remove(zip_filename)
|
| 333 |
else:
|
| 334 |
-
st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided.")
|
| 335 |
|
| 336 |
with col2:
|
| 337 |
if st.button("π€ Push to New Repository"):
|
|
@@ -342,28 +324,28 @@ def main():
|
|
| 342 |
local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
| 343 |
download_github_repo(source_repo, local_path)
|
| 344 |
push_to_github(local_path, new_repo, github_token)
|
| 345 |
-
st.success(f"Repository pushed successfully to {new_repo.html_url}")
|
| 346 |
except Exception as e:
|
| 347 |
-
st.error(f"An error occurred: {str(e)}")
|
| 348 |
finally:
|
| 349 |
if os.path.exists(local_path):
|
| 350 |
shutil.rmtree(local_path)
|
| 351 |
else:
|
| 352 |
-
st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided.")
|
| 353 |
-
|
| 354 |
except exceptions.CosmosHttpResponseError as e:
|
| 355 |
-
st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)}. Status code: {e.status_code}")
|
| 356 |
except Exception as e:
|
| 357 |
-
st.error(f"An unexpected error occurred: {str(e)}")
|
| 358 |
|
| 359 |
-
# Logout button
|
| 360 |
if st.session_state.logged_in and st.sidebar.button("πͺ Logout"):
|
| 361 |
st.session_state.logged_in = False
|
| 362 |
st.session_state.selected_records.clear()
|
| 363 |
st.session_state.client = None
|
| 364 |
st.session_state.selected_database = None
|
| 365 |
st.session_state.selected_container = None
|
| 366 |
-
st.
|
| 367 |
|
| 368 |
if __name__ == "__main__":
|
| 369 |
main()
|
|
|
|
| 12 |
import base64
|
| 13 |
import json
|
| 14 |
|
| 15 |
+
# π Welcome to our fun-filled Cosmos DB and GitHub Integration app!
|
| 16 |
st.set_page_config(layout="wide")
|
| 17 |
|
| 18 |
+
# π Cosmos DB configuration
|
| 19 |
ENDPOINT = "https://acae-afd.documents.azure.com:443/"
|
| 20 |
SUBSCRIPTION_ID = "003fba60-5b3f-48f4-ab36-3ed11bc40816"
|
| 21 |
DATABASE_NAME = os.environ.get("COSMOS_DATABASE_NAME")
|
| 22 |
CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
|
| 23 |
+
Key = os.environ.get("Key") # π Don't forget your key!
|
| 24 |
|
| 25 |
+
# π GitHub configuration
|
| 26 |
def download_github_repo(url, local_path):
|
| 27 |
+
# π Let's download that GitHub repo!
|
| 28 |
if os.path.exists(local_path):
|
| 29 |
shutil.rmtree(local_path)
|
| 30 |
Repo.clone_from(url, local_path)
|
| 31 |
|
| 32 |
def create_zip_file(source_dir, output_filename):
|
| 33 |
+
# π¦ Zipping up files like a pro!
|
| 34 |
shutil.make_archive(output_filename, 'zip', source_dir)
|
| 35 |
|
| 36 |
def create_repo(g, repo_name):
|
| 37 |
+
# π οΈ Creating a new GitHub repo. Magic!
|
| 38 |
user = g.get_user()
|
| 39 |
return user.create_repo(repo_name)
|
| 40 |
|
| 41 |
def push_to_github(local_path, repo, github_token):
|
| 42 |
+
# π Pushing code to GitHub. Hold on tight!
|
| 43 |
repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
|
| 44 |
local_repo = Repo(local_path)
|
| 45 |
|
|
|
|
| 63 |
origin.push(refspec=f'{current_branch}:{current_branch}')
|
| 64 |
|
| 65 |
def get_base64_download_link(file_path, file_name):
|
| 66 |
+
# π§ββοΈ Generating a magical download link!
|
| 67 |
with open(file_path, "rb") as file:
|
| 68 |
contents = file.read()
|
| 69 |
base64_encoded = base64.b64encode(contents).decode()
|
| 70 |
+
return f'<a href="data:application/zip;base64,{base64_encoded}" download="{file_name}">β¬οΈ Download {file_name}</a>'
|
| 71 |
|
| 72 |
|
| 73 |
+
# π§ New functions for dynamic sidebar navigation
|
| 74 |
def get_databases(client):
|
| 75 |
+
# π Fetching list of databases. So many options!
|
| 76 |
return [db['id'] for db in client.list_databases()]
|
| 77 |
|
| 78 |
def get_containers(database):
|
| 79 |
+
# π Getting containers. Containers within containers!
|
| 80 |
return [container['id'] for container in database.list_containers()]
|
| 81 |
|
| 82 |
def get_documents(container, limit=1000):
|
| 83 |
+
# π Retrieving documents. Shhh, don't tell anyone!
|
| 84 |
query = "SELECT * FROM c"
|
| 85 |
items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
|
| 86 |
return items
|
| 87 |
|
| 88 |
|
| 89 |
+
# π Cosmos DB functions
|
| 90 |
+
def insert_record(container, record):
|
| 91 |
try:
|
| 92 |
+
container.create_item(body=record)
|
| 93 |
+
return True, "Record inserted successfully! π"
|
| 94 |
except exceptions.CosmosHttpResponseError as e:
|
| 95 |
+
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code} π¨"
|
| 96 |
except Exception as e:
|
| 97 |
+
return False, f"An unexpected error occurred: {str(e)} π±"
|
| 98 |
|
| 99 |
+
def update_record(container, updated_record):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
try:
|
| 101 |
container.upsert_item(body=updated_record)
|
| 102 |
+
return True, f"Record with id {updated_record['id']} successfully updated. π οΈ"
|
| 103 |
except exceptions.CosmosHttpResponseError as e:
|
| 104 |
+
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code} π¨"
|
| 105 |
except Exception as e:
|
| 106 |
+
return False, f"An unexpected error occurred: {traceback.format_exc()} π±"
|
| 107 |
|
| 108 |
+
def delete_record(container, name, id):
|
| 109 |
try:
|
| 110 |
container.delete_item(item=id, partition_key=id)
|
| 111 |
+
return True, f"Successfully deleted record with name: {name} and id: {id} ποΈ"
|
| 112 |
except exceptions.CosmosResourceNotFoundError:
|
| 113 |
+
return False, f"Record with id {id} not found. It may have been already deleted. π΅οΈββοΈ"
|
| 114 |
except exceptions.CosmosHttpResponseError as e:
|
| 115 |
+
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code} π¨"
|
| 116 |
except Exception as e:
|
| 117 |
+
return False, f"An unexpected error occurred: {traceback.format_exc()} π±"
|
| 118 |
|
| 119 |
+
# π¦ Function to archive current container
|
| 120 |
def archive_current_container(database_name, container_name, client):
|
| 121 |
try:
|
| 122 |
base_dir = "./cosmos_archive_current_container"
|
|
|
|
| 141 |
|
| 142 |
return get_base64_download_link(f"{archive_name}.zip", f"{archive_name}.zip")
|
| 143 |
except Exception as e:
|
| 144 |
+
return f"An error occurred while archiving data: {str(e)} π’"
|
| 145 |
|
| 146 |
|
| 147 |
+
# π Let's modify the main app to be more fun!
|
| 148 |
def main():
|
| 149 |
st.title("π Cosmos DB and GitHub Integration")
|
| 150 |
|
| 151 |
+
# π¦ Initialize session state
|
| 152 |
if 'logged_in' not in st.session_state:
|
| 153 |
st.session_state.logged_in = False
|
| 154 |
if 'selected_records' not in st.session_state:
|
|
|
|
| 160 |
if 'selected_container' not in st.session_state:
|
| 161 |
st.session_state.selected_container = None
|
| 162 |
|
| 163 |
+
# π Login section
|
| 164 |
if not st.session_state.logged_in:
|
| 165 |
st.subheader("π Login")
|
| 166 |
+
# Let's be sneaky and use the Key from environment variables! π΅οΈββοΈ
|
| 167 |
+
input_key = Key
|
| 168 |
|
| 169 |
+
# π Time to blast off!
|
| 170 |
if st.button("π Login"):
|
| 171 |
if input_key:
|
| 172 |
st.session_state.primary_key = input_key
|
| 173 |
st.session_state.logged_in = True
|
| 174 |
+
st.experimental_rerun()
|
| 175 |
else:
|
| 176 |
+
st.error("Invalid key. Please check your input. πβ")
|
| 177 |
else:
|
| 178 |
+
# π Initialize Cosmos DB client
|
| 179 |
try:
|
| 180 |
if st.session_state.client is None:
|
| 181 |
st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
|
| 182 |
|
| 183 |
+
# ποΈ Sidebar for database, container, and document selection
|
| 184 |
st.sidebar.title("ποΈ Cosmos DB Navigator")
|
| 185 |
|
| 186 |
databases = get_databases(st.session_state.client)
|
|
|
|
| 189 |
if selected_db != st.session_state.selected_database:
|
| 190 |
st.session_state.selected_database = selected_db
|
| 191 |
st.session_state.selected_container = None
|
| 192 |
+
st.experimental_rerun()
|
| 193 |
|
| 194 |
if st.session_state.selected_database:
|
| 195 |
database = st.session_state.client.get_database_client(st.session_state.selected_database)
|
|
|
|
| 198 |
|
| 199 |
if selected_container != st.session_state.selected_container:
|
| 200 |
st.session_state.selected_container = selected_container
|
| 201 |
+
st.experimental_rerun()
|
| 202 |
|
| 203 |
if st.session_state.selected_container:
|
| 204 |
container = database.get_container_client(st.session_state.selected_container)
|
| 205 |
|
| 206 |
+
# π¦ Add Export button
|
| 207 |
if st.button("π¦ Export Container Data"):
|
| 208 |
download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
|
| 209 |
if download_link.startswith('<a'):
|
|
|
|
| 222 |
st.subheader(f"π Document Details: {selected_document}")
|
| 223 |
selected_doc = next((doc for doc in documents if doc.get('id') == selected_document), None)
|
| 224 |
if selected_doc:
|
| 225 |
+
# π¨ Add Viewer/Editor selection
|
| 226 |
view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
|
| 227 |
selected_view = st.selectbox("Select Viewer/Editor", view_options)
|
| 228 |
+
|
| 229 |
if selected_view == 'Show as Markdown':
|
| 230 |
+
# ποΈ Show as Markdown
|
| 231 |
items = get_documents(container)
|
| 232 |
for item in items:
|
| 233 |
+
st.markdown(f"### π ID: {item.get('id', 'Unknown')}")
|
| 234 |
content = item.get('content', '')
|
| 235 |
if isinstance(content, dict) or isinstance(content, list):
|
| 236 |
content = json.dumps(content, indent=2)
|
| 237 |
st.markdown(content)
|
| 238 |
elif selected_view == 'Show as Code Editor':
|
| 239 |
+
# π» Show as Code Editor
|
| 240 |
items = get_documents(container)
|
| 241 |
for item in items:
|
| 242 |
st.code(json.dumps(item, indent=2), language='python')
|
| 243 |
elif selected_view == 'Show as Edit and Save':
|
| 244 |
+
# βοΈ Show as Edit and Save
|
| 245 |
doc_str = st.text_area("Edit Document", value=json.dumps(selected_doc, indent=2), height=300)
|
| 246 |
if st.button("πΎ Save"):
|
| 247 |
try:
|
| 248 |
updated_doc = json.loads(doc_str)
|
| 249 |
+
success, message = update_record(container, updated_doc)
|
| 250 |
if success:
|
| 251 |
st.success(message)
|
| 252 |
else:
|
| 253 |
st.error(message)
|
| 254 |
except json.JSONDecodeError as e:
|
| 255 |
+
st.error(f"Invalid JSON: {str(e)} π«")
|
| 256 |
elif selected_view == 'Clone Document':
|
| 257 |
+
# 𧬠Clone Document
|
| 258 |
if st.button("π Clone Document"):
|
| 259 |
cloned_doc = selected_doc.copy()
|
| 260 |
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
|
| 261 |
cloned_doc['id'] = f"{cloned_doc['id']}_clone_{timestamp}"
|
| 262 |
+
success, message = insert_record(container, cloned_doc)
|
| 263 |
if success:
|
| 264 |
+
st.success(f"Document cloned with new id: {cloned_doc['id']} π")
|
| 265 |
else:
|
| 266 |
st.error(message)
|
| 267 |
elif selected_view == 'New Record':
|
| 268 |
+
# π New Record
|
| 269 |
new_doc_str = st.text_area("New Document", value='{}', height=300)
|
| 270 |
if st.button("β Create New Document"):
|
| 271 |
try:
|
| 272 |
new_doc = json.loads(new_doc_str)
|
| 273 |
if 'id' not in new_doc:
|
| 274 |
new_doc['id'] = f"new_doc_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
| 275 |
+
success, message = insert_record(container, new_doc)
|
| 276 |
if success:
|
| 277 |
+
st.success(f"New document created with id: {new_doc['id']} π")
|
| 278 |
else:
|
| 279 |
st.error(message)
|
| 280 |
except json.JSONDecodeError as e:
|
| 281 |
+
st.error(f"Invalid JSON: {str(e)} π«")
|
| 282 |
else:
|
| 283 |
+
st.sidebar.info("No documents found in this container. π")
|
| 284 |
|
| 285 |
+
# π Main content area
|
| 286 |
st.subheader(f"π Container: {st.session_state.selected_container}")
|
| 287 |
if st.session_state.selected_container:
|
| 288 |
df = pd.DataFrame(documents)
|
| 289 |
st.dataframe(df)
|
| 290 |
|
| 291 |
+
# π GitHub section
|
| 292 |
st.subheader("π GitHub Operations")
|
| 293 |
github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
|
| 294 |
source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
|
| 295 |
new_repo_name = st.text_input("New Repository Name (for cloning)", value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
|
| 296 |
+
|
| 297 |
col1, col2 = st.columns(2)
|
| 298 |
with col1:
|
| 299 |
if st.button("π₯ Clone Repository"):
|
|
|
|
| 304 |
zip_filename = f"{new_repo_name}.zip"
|
| 305 |
create_zip_file(local_path, zip_filename[:-4])
|
| 306 |
st.markdown(get_base64_download_link(zip_filename, zip_filename), unsafe_allow_html=True)
|
| 307 |
+
st.success("Repository cloned successfully! π")
|
| 308 |
except Exception as e:
|
| 309 |
+
st.error(f"An error occurred: {str(e)} π’")
|
| 310 |
finally:
|
| 311 |
if os.path.exists(local_path):
|
| 312 |
shutil.rmtree(local_path)
|
| 313 |
if os.path.exists(zip_filename):
|
| 314 |
os.remove(zip_filename)
|
| 315 |
else:
|
| 316 |
+
st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πβ")
|
| 317 |
|
| 318 |
with col2:
|
| 319 |
if st.button("π€ Push to New Repository"):
|
|
|
|
| 324 |
local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
| 325 |
download_github_repo(source_repo, local_path)
|
| 326 |
push_to_github(local_path, new_repo, github_token)
|
| 327 |
+
st.success(f"Repository pushed successfully to {new_repo.html_url} π")
|
| 328 |
except Exception as e:
|
| 329 |
+
st.error(f"An error occurred: {str(e)} π’")
|
| 330 |
finally:
|
| 331 |
if os.path.exists(local_path):
|
| 332 |
shutil.rmtree(local_path)
|
| 333 |
else:
|
| 334 |
+
st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πβ")
|
| 335 |
+
|
| 336 |
except exceptions.CosmosHttpResponseError as e:
|
| 337 |
+
st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)}. Status code: {e.status_code} π¨")
|
| 338 |
except Exception as e:
|
| 339 |
+
st.error(f"An unexpected error occurred: {str(e)} π±")
|
| 340 |
|
| 341 |
+
# πͺ Logout button
|
| 342 |
if st.session_state.logged_in and st.sidebar.button("πͺ Logout"):
|
| 343 |
st.session_state.logged_in = False
|
| 344 |
st.session_state.selected_records.clear()
|
| 345 |
st.session_state.client = None
|
| 346 |
st.session_state.selected_database = None
|
| 347 |
st.session_state.selected_container = None
|
| 348 |
+
st.experimental_rerun()
|
| 349 |
|
| 350 |
if __name__ == "__main__":
|
| 351 |
main()
|