awacke1 commited on
Commit
16461da
Β·
verified Β·
1 Parent(s): 2c1b72e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -0
app.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from azure.cosmos import CosmosClient
3
+ import os
4
+ import pandas as pd
5
+
6
+ # Cosmos DB configuration
7
+ ENDPOINT = "https://acae-afd.documents.azure.com:443/"
8
+ SUBSCRIPTION_ID = "003fba60-5b3f-48f4-ab36-3ed11bc40816"
9
+ # You'll need to set these environment variables or use Azure Key Vault
10
+ DATABASE_NAME = os.environ.get("COSMOS_DATABASE_NAME")
11
+ CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
12
+ Key = os.environ.get("Key")
13
+
14
+ def insert_record(record):
15
+ try:
16
+ response = container.create_item(body=record)
17
+ return True, response
18
+ except Exception as e:
19
+ return False, str(e)
20
+
21
+ def call_stored_procedure(record):
22
+ try:
23
+ response = container.scripts.execute_stored_procedure(
24
+ sproc="processPrompt",
25
+ params=[record],
26
+ partition_key=record['id']
27
+ )
28
+ return True, response
29
+ except Exception as e:
30
+ error_message = f"Error type: {type(e).__name__}\nError message: {str(e)}"
31
+ if hasattr(e, 'sub_status'):
32
+ error_message += f"\nSub-status: {e.sub_status}"
33
+ if hasattr(e, 'response'):
34
+ error_message += f"\nResponse: {e.response}"
35
+ return False, error_message
36
+
37
+ def fetch_all_records():
38
+ query = "SELECT * FROM c"
39
+ items = list(container.query_items(query=query, enable_cross_partition_query=True))
40
+ return pd.DataFrame(items)
41
+
42
+ def delete_record(id):
43
+ try:
44
+ container.delete_item(id, partition_key=id)
45
+ return True
46
+ except Exception as e:
47
+ return False
48
+
49
+ # Streamlit app
50
+ st.title("🌟 Cosmos DB Record Management")
51
+
52
+ # Login section
53
+ if 'logged_in' not in st.session_state:
54
+ st.session_state.logged_in = False
55
+
56
+ if not st.session_state.logged_in:
57
+ st.subheader("πŸ” Login")
58
+ input_key = st.text_input("Enter your key", type="password")
59
+ if st.button("πŸš€ Login"):
60
+ if input_key:
61
+ st.session_state.primary_key = input_key
62
+ st.session_state.logged_in = True
63
+ st.rerun()
64
+ else:
65
+ st.error("Please enter a valid key")
66
+ else:
67
+ # Initialize Cosmos DB client
68
+ client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
69
+ database = client.get_database_client(DATABASE_NAME)
70
+ container = database.get_container_client(CONTAINER_NAME)
71
+
72
+ # Fetch and display all records
73
+ st.subheader("πŸ“Š All Records")
74
+ df = fetch_all_records()
75
+
76
+ # Use Streamlit's data editor
77
+ edited_df = st.data_editor(df, num_rows="dynamic", key="data_editor")
78
+
79
+ # Add delete and download buttons
80
+ col1, col2 = st.columns(2)
81
+ with col1:
82
+ if st.button("πŸ—‘οΈ Delete Selected"):
83
+ for index, row in edited_df.iterrows():
84
+ if row.get('_selected', False):
85
+ if delete_record(row['id']):
86
+ st.success(f"Deleted record with ID: {row['id']}")
87
+ else:
88
+ st.error(f"Failed to delete record with ID: {row['id']}")
89
+ st.rerun()
90
+
91
+ with col2:
92
+ if st.download_button("πŸ“₯ Download Data", edited_df.to_csv(index=False), "cosmos_db_data.csv", "text/csv"):
93
+ st.success("Data downloaded successfully!")
94
+
95
+ # Input fields for new record
96
+ st.subheader("πŸ“ Enter New Record Details")
97
+ new_id = st.text_input("ID")
98
+ new_name = st.text_input("Name")
99
+ new_document = st.text_area("Document")
100
+ new_evaluation_text = st.text_area("Evaluation Text")
101
+ new_evaluation_score = st.number_input("Evaluation Score", min_value=0, max_value=100, step=1)
102
+
103
+ col1, col2 = st.columns(2)
104
+
105
+ # Insert Record button
106
+ with col1:
107
+ if st.button("πŸ’Ύ Insert Record"):
108
+ record = {
109
+ "id": new_id,
110
+ "name": new_name,
111
+ "document": new_document,
112
+ "evaluationText": new_evaluation_text,
113
+ "evaluationScore": new_evaluation_score
114
+ }
115
+
116
+ success, response = insert_record(record)
117
+ if success:
118
+ st.success("βœ… Record inserted successfully!")
119
+ st.json(response)
120
+ else:
121
+ st.error(f"❌ Failed to insert record: {response}")
122
+ st.rerun()
123
+
124
+ # Call Procedure button
125
+ with col2:
126
+ if st.button("πŸ”§ Call Procedure"):
127
+ record = {
128
+ "id": new_id,
129
+ "name": new_name,
130
+ "document": new_document,
131
+ "evaluationText": new_evaluation_text,
132
+ "evaluationScore": new_evaluation_score
133
+ }
134
+
135
+ success, response = call_stored_procedure(record)
136
+ if success:
137
+ st.success("βœ… Stored procedure executed successfully!")
138
+ st.json(response)
139
+ else:
140
+ st.error(f"❌ Failed to execute stored procedure: {response}")
141
+
142
+ # Logout button
143
+ if st.button("πŸšͺ Logout"):
144
+ st.session_state.logged_in = False
145
+ st.rerun()
146
+
147
+ # Display connection info
148
+ st.sidebar.subheader("πŸ”— Connection Information")
149
+ st.sidebar.text(f"Endpoint: {ENDPOINT}")
150
+ st.sidebar.text(f"Subscription ID: {SUBSCRIPTION_ID}")
151
+ st.sidebar.text(f"Database: {DATABASE_NAME}")
152
+ st.sidebar.text(f"Container: {CONTAINER_NAME}")