awacke1 commited on
Commit
05d0c2b
β€’
1 Parent(s): 6c39974

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -0
app.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Streamlit app
62
+ st.title("🌟 Cosmos DB Record Management")
63
+
64
+ # Initialize session state for selected records
65
+ if 'selected_records' not in st.session_state:
66
+ st.session_state.selected_records = []
67
+
68
+ # Login section
69
+ if 'logged_in' not in st.session_state:
70
+ st.session_state.logged_in = False
71
+
72
+ if not st.session_state.logged_in:
73
+ st.subheader("πŸ” Login")
74
+ input_key = Key # Use the predefined Key instead of asking for user input
75
+ if st.button("πŸš€ Login"):
76
+ if input_key:
77
+ st.session_state.primary_key = input_key
78
+ st.session_state.logged_in = True
79
+ st.rerun()
80
+ else:
81
+ st.error("Invalid key. Please check your environment variables.")
82
+ else:
83
+ # Initialize Cosmos DB client
84
+ try:
85
+ client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
86
+ database = client.get_database_client(DATABASE_NAME)
87
+ container = database.get_container_client(CONTAINER_NAME)
88
+ except exceptions.CosmosHttpResponseError as e:
89
+ st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)}. Status code: {e.status_code}")
90
+ st.stop()
91
+ except Exception as e:
92
+ st.error(f"An unexpected error occurred while connecting to Cosmos DB: {str(e)}")
93
+ st.stop()
94
+
95
+ # Fetch and display all records
96
+ st.subheader("πŸ“Š All Records")
97
+ df = fetch_all_records()
98
+
99
+ if df.empty:
100
+ st.write("No records found in the database.")
101
+ else:
102
+ st.write("Records:")
103
+ for index, row in df.iterrows():
104
+ col1, col2 = st.columns([5, 1])
105
+
106
+ with col1:
107
+ # Display all fields in the listing
108
+ st.write(f"ID: {row['id']}, Name: {row['name']}, Document: {row['document']}, "
109
+ f"Evaluation Text: {row['evaluationText']}, Evaluation Score: {row['evaluationScore']}")
110
+
111
+ with col2:
112
+ key = f"select_{row['id']}"
113
+ if st.button("Select", key=key):
114
+ st.session_state.selected_record = row.to_dict()
115
+
116
+ # Display selected record for editing
117
+ if 'selected_record' in st.session_state and st.session_state.selected_record:
118
+ selected_record = st.session_state.selected_record
119
+
120
+ st.subheader(f"Editing Record - ID: {selected_record['id']}")
121
+
122
+ # Editable fields prefilled with the selected record
123
+ updated_name = st.text_input("Name", value=selected_record['name'])
124
+ updated_document = st.text_area("Document", value=selected_record['document'])
125
+ updated_evaluation_text = st.text_area("Evaluation Text", value=selected_record['evaluationText'])
126
+ updated_evaluation_score = st.number_input("Evaluation Score", value=selected_record['evaluationScore'], min_value=0, max_value=100)
127
+
128
+ # Update button
129
+ if st.button("πŸ”„ Update Record"):
130
+ updated_record = {
131
+ "id": selected_record['id'],
132
+ "name": updated_name,
133
+ "document": updated_document,
134
+ "evaluationText": updated_evaluation_text,
135
+ "evaluationScore": updated_evaluation_score
136
+ }
137
+
138
+ success, message = update_record(updated_record)
139
+ if success:
140
+ st.success(message)
141
+ st.session_state.selected_record = updated_record # Update the session state with new values
142
+ else:
143
+ st.error(message)
144
+
145
+ # Input fields for new record
146
+ st.subheader("πŸ“ Enter New Record Details")
147
+ new_id = st.text_input("ID")
148
+ new_name = st.text_input("Name")
149
+ new_document = st.text_area("Document")
150
+ new_evaluation_text = st.text_area("Evaluation Text")
151
+ new_evaluation_score = st.number_input("Evaluation Score", min_value=0, max_value=100, step=1)
152
+
153
+ col1, col2 = st.columns(2)
154
+
155
+ # Insert Record button
156
+ with col1:
157
+ if st.button("πŸ’Ύ Insert Record"):
158
+ record = {
159
+ "id": new_id,
160
+ "name": new_name,
161
+ "document": new_document,
162
+ "evaluationText": new_evaluation_text,
163
+ "evaluationScore": new_evaluation_score
164
+ }
165
+
166
+ success, response = insert_record(record)
167
+ if success:
168
+ st.success("βœ… Record inserted successfully!")
169
+ st.json(response)
170
+ else:
171
+ st.error(f"❌ Failed to insert record: {response}")
172
+ st.rerun()
173
+
174
+ # Call Procedure button
175
+ with col2:
176
+ if st.button("πŸ”§ Call Procedure"):
177
+ record = {
178
+ "id": new_id,
179
+ "name": new_name,
180
+ "document": new_document,
181
+ "evaluationText": new_evaluation_text,
182
+ "evaluationScore": new_evaluation_score
183
+ }
184
+
185
+ success, response = call_stored_procedure(record)
186
+ if success:
187
+ st.success("βœ… Stored procedure executed successfully!")
188
+ st.json(response)
189
+ else:
190
+ st.error(f"❌ Failed to execute stored procedure: {response}")
191
+
192
+ # Logout button
193
+ if st.button("πŸšͺ Logout"):
194
+ st.session_state.logged_in = False
195
+ st.session_state.selected_records.clear() # Clear selected records on logout
196
+ st.session_state.selected_record = None # Clear selected record
197
+ st.rerun()
198
+
199
+ # Display connection info
200
+ st.sidebar.subheader("πŸ”— Connection Information")
201
+ st.sidebar.text(f"Endpoint: {ENDPOINT}")
202
+ st.sidebar.text(f"Subscription ID: {SUBSCRIPTION_ID}")
203
+ st.sidebar.text(f"Database: {DATABASE_NAME}")
204
+ st.sidebar.text(f"Container: {CONTAINER_NAME}")