Spaces:
Running
Running
Delete 09052024-1.backup.app.py
Browse files- 09052024-1.backup.app.py +0 -224
09052024-1.backup.app.py
DELETED
@@ -1,224 +0,0 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
from azure.cosmos import CosmosClient, PartitionKey, exceptions
|
3 |
-
import os
|
4 |
-
import pandas as pd
|
5 |
-
import traceback # For detailed error stacks
|
6 |
-
|
7 |
-
st.set_page_config(layout="wide")
|
8 |
-
|
9 |
-
# Cosmos DB configuration
|
10 |
-
ENDPOINT = "https://acae-afd.documents.azure.com:443/"
|
11 |
-
SUBSCRIPTION_ID = "003fba60-5b3f-48f4-ab36-3ed11bc40816"
|
12 |
-
DATABASE_NAME = os.environ.get("COSMOS_DATABASE_NAME")
|
13 |
-
CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
|
14 |
-
Key = os.environ.get("Key")
|
15 |
-
|
16 |
-
def insert_record(record):
|
17 |
-
try:
|
18 |
-
response = container.create_item(body=record)
|
19 |
-
return True, response
|
20 |
-
except exceptions.CosmosHttpResponseError as e:
|
21 |
-
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
22 |
-
except Exception as e:
|
23 |
-
return False, f"An unexpected error occurred: {str(e)}"
|
24 |
-
|
25 |
-
def call_stored_procedure(record):
|
26 |
-
try:
|
27 |
-
response = container.scripts.execute_stored_procedure(
|
28 |
-
sproc="processPrompt",
|
29 |
-
params=[record],
|
30 |
-
partition_key=record['id']
|
31 |
-
)
|
32 |
-
return True, response
|
33 |
-
except exceptions.CosmosHttpResponseError as e:
|
34 |
-
error_message = f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
35 |
-
return False, error_message
|
36 |
-
except Exception as e:
|
37 |
-
error_message = f"An unexpected error occurred: {str(e)}"
|
38 |
-
return False, error_message
|
39 |
-
|
40 |
-
def fetch_all_records():
|
41 |
-
try:
|
42 |
-
query = "SELECT * FROM c"
|
43 |
-
items = list(container.query_items(query=query, enable_cross_partition_query=True))
|
44 |
-
return pd.DataFrame(items)
|
45 |
-
except exceptions.CosmosHttpResponseError as e:
|
46 |
-
st.error(f"HTTP error occurred while fetching records: {str(e)}. Status code: {e.status_code}")
|
47 |
-
return pd.DataFrame()
|
48 |
-
except Exception as e:
|
49 |
-
st.error(f"An unexpected error occurred while fetching records: {str(e)}")
|
50 |
-
return pd.DataFrame()
|
51 |
-
|
52 |
-
def update_record(updated_record):
|
53 |
-
try:
|
54 |
-
container.upsert_item(body=updated_record) # Upsert updates the item if it exists
|
55 |
-
return True, f"Record with id {updated_record['id']} successfully updated."
|
56 |
-
except exceptions.CosmosHttpResponseError as e:
|
57 |
-
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
58 |
-
except Exception as e:
|
59 |
-
return False, f"An unexpected error occurred: {traceback.format_exc()}"
|
60 |
-
|
61 |
-
def delete_record(name, id):
|
62 |
-
try:
|
63 |
-
container.delete_item(item=id, partition_key=id)
|
64 |
-
return True, f"Successfully deleted record with name: {name} and id: {id}"
|
65 |
-
except exceptions.CosmosResourceNotFoundError:
|
66 |
-
return False, f"Record with id {id} not found. It may have been already deleted."
|
67 |
-
except exceptions.CosmosHttpResponseError as e:
|
68 |
-
return False, f"HTTP error occurred: {str(e)}. Status code: {e.status_code}"
|
69 |
-
except Exception as e:
|
70 |
-
return False, f"An unexpected error occurred: {traceback.format_exc()}"
|
71 |
-
|
72 |
-
# Streamlit app
|
73 |
-
st.title("🌟 Cosmos DB Record Management")
|
74 |
-
|
75 |
-
# Initialize session state for selected records
|
76 |
-
if 'selected_records' not in st.session_state:
|
77 |
-
st.session_state.selected_records = []
|
78 |
-
|
79 |
-
# Login section
|
80 |
-
if 'logged_in' not in st.session_state:
|
81 |
-
st.session_state.logged_in = False
|
82 |
-
|
83 |
-
if not st.session_state.logged_in:
|
84 |
-
st.subheader("🔐 Login")
|
85 |
-
input_key = Key # Use the predefined Key instead of asking for user input
|
86 |
-
if st.button("🚀 Login"):
|
87 |
-
if input_key:
|
88 |
-
st.session_state.primary_key = input_key
|
89 |
-
st.session_state.logged_in = True
|
90 |
-
st.rerun()
|
91 |
-
else:
|
92 |
-
st.error("Invalid key. Please check your environment variables.")
|
93 |
-
else:
|
94 |
-
# Initialize Cosmos DB client
|
95 |
-
try:
|
96 |
-
client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
|
97 |
-
database = client.get_database_client(DATABASE_NAME)
|
98 |
-
container = database.get_container_client(CONTAINER_NAME)
|
99 |
-
except exceptions.CosmosHttpResponseError as e:
|
100 |
-
st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)}. Status code: {e.status_code}")
|
101 |
-
st.stop()
|
102 |
-
except Exception as e:
|
103 |
-
st.error(f"An unexpected error occurred while connecting to Cosmos DB: {str(e)}")
|
104 |
-
st.stop()
|
105 |
-
|
106 |
-
# Fetch and display all records
|
107 |
-
st.subheader("📊 All Records")
|
108 |
-
df = fetch_all_records()
|
109 |
-
|
110 |
-
if df.empty:
|
111 |
-
st.write("No records found in the database.")
|
112 |
-
else:
|
113 |
-
st.write("Records:")
|
114 |
-
for index, row in df.iterrows():
|
115 |
-
col1, col2, col3 = st.columns([5, 1, 1])
|
116 |
-
|
117 |
-
with col1:
|
118 |
-
# Display all fields in the listing
|
119 |
-
st.write(f"ID: {row['id']}, Name: {row['name']}, Document: {row['document']}, "
|
120 |
-
f"Evaluation Text: {row['evaluationText']}, Evaluation Score: {row['evaluationScore']}")
|
121 |
-
|
122 |
-
with col2:
|
123 |
-
key = f"select_{row['id']}"
|
124 |
-
if st.button(f"👉 Select", key=key):
|
125 |
-
st.session_state.selected_record = row.to_dict()
|
126 |
-
|
127 |
-
with col3:
|
128 |
-
if st.button(f"🗑️ Delete", key=f"delete_{row['id']}"):
|
129 |
-
success, message = delete_record(row['name'], row['id'])
|
130 |
-
if success:
|
131 |
-
st.success(message)
|
132 |
-
st.rerun() # Refresh after deletion
|
133 |
-
else:
|
134 |
-
st.error(message)
|
135 |
-
|
136 |
-
# Display selected record for editing
|
137 |
-
if 'selected_record' in st.session_state and st.session_state.selected_record:
|
138 |
-
selected_record = st.session_state.selected_record
|
139 |
-
|
140 |
-
st.subheader(f"Editing Record - ID: {selected_record['id']}")
|
141 |
-
|
142 |
-
# Editable fields prefilled with the selected record
|
143 |
-
updated_name = st.text_input("Name", value=selected_record['name'])
|
144 |
-
updated_document = st.text_area("Document", value=selected_record['document'])
|
145 |
-
updated_evaluation_text = st.text_area("Evaluation Text", value=selected_record['evaluationText'])
|
146 |
-
updated_evaluation_score = st.text_input("Evaluation Score", value=str(selected_record['evaluationScore']))
|
147 |
-
|
148 |
-
# Update button with emoji
|
149 |
-
if st.button("💾 Save Changes"):
|
150 |
-
updated_record = {
|
151 |
-
"id": selected_record['id'],
|
152 |
-
"name": updated_name,
|
153 |
-
"document": updated_document,
|
154 |
-
"evaluationText": updated_evaluation_text,
|
155 |
-
"evaluationScore": updated_evaluation_score # Now treated as a string
|
156 |
-
}
|
157 |
-
|
158 |
-
success, message = update_record(updated_record)
|
159 |
-
if success:
|
160 |
-
st.success(message)
|
161 |
-
st.session_state.selected_record = updated_record # Update the session state with new values
|
162 |
-
else:
|
163 |
-
st.error(message)
|
164 |
-
|
165 |
-
# Input fields for new record
|
166 |
-
st.subheader("📝 Enter New Record Details")
|
167 |
-
new_id = st.text_input("ID")
|
168 |
-
new_name = st.text_input("Name")
|
169 |
-
new_document = st.text_area("Document")
|
170 |
-
new_evaluation_text = st.text_area("Evaluation Text")
|
171 |
-
new_evaluation_score = st.text_input("Evaluation Score") # Now treated as a string
|
172 |
-
|
173 |
-
col1, col2 = st.columns(2)
|
174 |
-
|
175 |
-
# Insert Record button
|
176 |
-
with col1:
|
177 |
-
if st.button("💾 Insert Record"):
|
178 |
-
record = {
|
179 |
-
"id": new_id,
|
180 |
-
"name": new_name,
|
181 |
-
"document": new_document,
|
182 |
-
"evaluationText": new_evaluation_text,
|
183 |
-
"evaluationScore": new_evaluation_score # Insert as a string
|
184 |
-
}
|
185 |
-
|
186 |
-
success, response = insert_record(record)
|
187 |
-
if success:
|
188 |
-
st.success("✅ Record inserted successfully!")
|
189 |
-
st.json(response)
|
190 |
-
else:
|
191 |
-
st.error(f"❌ Failed to insert record: {response}")
|
192 |
-
st.rerun()
|
193 |
-
|
194 |
-
# Call Procedure button
|
195 |
-
with col2:
|
196 |
-
if st.button("🔧 Call Procedure"):
|
197 |
-
record = {
|
198 |
-
"id": new_id,
|
199 |
-
"name": new_name,
|
200 |
-
"document": new_document,
|
201 |
-
"evaluationText": new_evaluation_text,
|
202 |
-
"evaluationScore": new_evaluation_score
|
203 |
-
}
|
204 |
-
|
205 |
-
success, response = call_stored_procedure(record)
|
206 |
-
if success:
|
207 |
-
st.success("✅ Stored procedure executed successfully!")
|
208 |
-
st.json(response)
|
209 |
-
else:
|
210 |
-
st.error(f"❌ Failed to execute stored procedure: {response}")
|
211 |
-
|
212 |
-
# Logout button
|
213 |
-
if st.button("🚪 Logout"):
|
214 |
-
st.session_state.logged_in = False
|
215 |
-
st.session_state.selected_records.clear() # Clear selected records on logout
|
216 |
-
st.session_state.selected_record = None # Clear selected record
|
217 |
-
st.rerun()
|
218 |
-
|
219 |
-
# Display connection info
|
220 |
-
st.sidebar.subheader("🔗 Connection Information")
|
221 |
-
st.sidebar.text(f"Endpoint: {ENDPOINT}")
|
222 |
-
st.sidebar.text(f"Subscription ID: {SUBSCRIPTION_ID}")
|
223 |
-
st.sidebar.text(f"Database: {DATABASE_NAME}")
|
224 |
-
st.sidebar.text(f"Container: {CONTAINER_NAME}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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