awacke1 commited on
Commit
3b1760c
·
verified ·
1 Parent(s): c3c1014

Delete backup.0611.app.py

Browse files
Files changed (1) hide show
  1. backup.0611.app.py +0 -178
backup.0611.app.py DELETED
@@ -1,178 +0,0 @@
1
- import streamlit as st
2
- from azure.cosmos import CosmosClient, PartitionKey
3
- import os
4
- import pandas as pd
5
-
6
- st.set_page_config(layout="wide")
7
-
8
- # Cosmos DB configuration
9
- ENDPOINT = "https://acae-afd.documents.azure.com:443/"
10
- SUBSCRIPTION_ID = "003fba60-5b3f-48f4-ab36-3ed11bc40816"
11
- # You'll need to set these environment variables or use Azure Key Vault
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 Exception as e:
21
- return False, str(e)
22
-
23
- def call_stored_procedure(record):
24
- try:
25
- response = container.scripts.execute_stored_procedure(
26
- sproc="processPrompt",
27
- params=[record],
28
- partition_key=record['id']
29
- )
30
- return True, response
31
- except Exception as e:
32
- error_message = f"Error type: {type(e).__name__}\nError message: {str(e)}"
33
- if hasattr(e, 'sub_status'):
34
- error_message += f"\nSub-status: {e.sub_status}"
35
- if hasattr(e, 'response'):
36
- error_message += f"\nResponse: {e.response}"
37
- return False, error_message
38
-
39
- def fetch_all_records():
40
- query = "SELECT * FROM c"
41
- items = list(container.query_items(query=query, enable_cross_partition_query=True))
42
- return pd.DataFrame(items)
43
-
44
- def delete_records(ids):
45
- try:
46
- for id in ids:
47
- container.delete_item(item=id, partition_key=id)
48
- return True, f"Successfully deleted {len(ids)} records"
49
- except Exception as e:
50
- return False, f"Error deleting records: {str(e)}"
51
-
52
- # Streamlit app
53
- st.title("🌟 Cosmos DB Record Management")
54
-
55
- # Initialize session state for selected IDs
56
- if 'selected_ids' not in st.session_state:
57
- st.session_state.selected_ids = set()
58
-
59
- # Login section
60
- if 'logged_in' not in st.session_state:
61
- st.session_state.logged_in = False
62
-
63
- if not st.session_state.logged_in:
64
- st.subheader("🔐 Login")
65
- input_key = Key # Use the predefined Key instead of asking for user input
66
- if st.button("🚀 Login"):
67
- if input_key:
68
- st.session_state.primary_key = input_key
69
- st.session_state.logged_in = True
70
- st.rerun()
71
- else:
72
- st.error("Invalid key. Please check your environment variables.")
73
- else:
74
- # Initialize Cosmos DB client
75
- client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
76
- database = client.get_database_client(DATABASE_NAME)
77
- container = database.get_container_client(CONTAINER_NAME)
78
-
79
- # Fetch and display all records
80
- st.subheader("📊 All Records")
81
- df = fetch_all_records()
82
-
83
- # Add a checkbox column to the dataframe
84
- df['select'] = df['id'].isin(st.session_state.selected_ids)
85
-
86
- # Use Streamlit's data editor
87
- edited_df = st.data_editor(df, key="data_editor", disabled=["id", "name", "document", "evaluationText", "evaluationScore"])
88
-
89
- # Update selected_ids based on the edited dataframe
90
- selected_rows = edited_df[edited_df['select']]
91
- st.session_state.selected_ids = set(selected_rows['id'])
92
-
93
- # Display selected IDs with emoji checkboxes
94
- if st.session_state.selected_ids:
95
- st.markdown("### Selected Records:")
96
- for id in st.session_state.selected_ids:
97
- st.markdown(f"✅ {id}")
98
- else:
99
- st.markdown("### No Records Selected")
100
-
101
- # Add delete and download buttons
102
- col1, col2 = st.columns(2)
103
- with col1:
104
- if st.button("🗑️ Delete Selected"):
105
- if st.session_state.selected_ids:
106
- success, message = delete_records(list(st.session_state.selected_ids))
107
- if success:
108
- st.success(message)
109
- st.session_state.selected_ids.clear() # Clear the selection after successful deletion
110
- else:
111
- st.error(message)
112
- st.rerun()
113
- else:
114
- st.warning("No records selected for deletion.")
115
-
116
- with col2:
117
- if st.download_button("📥 Download Data", df.to_csv(index=False), "cosmos_db_data.csv", "text/csv"):
118
- st.success("Data downloaded successfully!")
119
-
120
- # Input fields for new record
121
- st.subheader("📝 Enter New Record Details")
122
- new_id = st.text_input("ID")
123
- new_name = st.text_input("Name")
124
- new_document = st.text_area("Document")
125
- new_evaluation_text = st.text_area("Evaluation Text")
126
- new_evaluation_score = st.number_input("Evaluation Score", min_value=0, max_value=100, step=1)
127
-
128
- col1, col2 = st.columns(2)
129
-
130
- # Insert Record button
131
- with col1:
132
- if st.button("💾 Insert Record"):
133
- record = {
134
- "id": new_id,
135
- "name": new_name,
136
- "document": new_document,
137
- "evaluationText": new_evaluation_text,
138
- "evaluationScore": new_evaluation_score
139
- }
140
-
141
- success, response = insert_record(record)
142
- if success:
143
- st.success("✅ Record inserted successfully!")
144
- st.json(response)
145
- else:
146
- st.error(f"❌ Failed to insert record: {response}")
147
- st.rerun()
148
-
149
- # Call Procedure button
150
- with col2:
151
- if st.button("🔧 Call Procedure"):
152
- record = {
153
- "id": new_id,
154
- "name": new_name,
155
- "document": new_document,
156
- "evaluationText": new_evaluation_text,
157
- "evaluationScore": new_evaluation_score
158
- }
159
-
160
- success, response = call_stored_procedure(record)
161
- if success:
162
- st.success("✅ Stored procedure executed successfully!")
163
- st.json(response)
164
- else:
165
- st.error(f"❌ Failed to execute stored procedure: {response}")
166
-
167
- # Logout button
168
- if st.button("🚪 Logout"):
169
- st.session_state.logged_in = False
170
- st.session_state.selected_ids.clear() # Clear selected IDs on logout
171
- st.rerun()
172
-
173
- # Display connection info
174
- st.sidebar.subheader("🔗 Connection Information")
175
- st.sidebar.text(f"Endpoint: {ENDPOINT}")
176
- st.sidebar.text(f"Subscription ID: {SUBSCRIPTION_ID}")
177
- st.sidebar.text(f"Database: {DATABASE_NAME}")
178
- st.sidebar.text(f"Container: {CONTAINER_NAME}")