awacke1 commited on
Commit
3993960
β€’
1 Parent(s): 3c873ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -103
app.py CHANGED
@@ -1,112 +1,178 @@
1
  import streamlit as st
2
- import requests
3
  import os
4
- import shutil
5
- import zipfile
6
- from github import Github
7
- from git import Repo
8
- from datetime import datetime
9
 
10
- def download_github_repo(url, local_path):
11
- if os.path.exists(local_path):
12
- shutil.rmtree(local_path)
13
- Repo.clone_from(url, local_path)
14
 
15
- def create_zip_file(source_dir, output_filename):
16
- shutil.make_archive(output_filename, 'zip', source_dir)
 
 
 
 
 
17
 
18
- def check_repo_exists(g, repo_name):
19
  try:
20
- g.get_repo(repo_name)
21
- return True
22
- except:
23
- return False
24
-
25
- def create_repo(g, repo_name):
26
- user = g.get_user()
27
- return user.create_repo(repo_name)
28
-
29
- def push_to_github(local_path, repo, github_token):
30
- repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
31
- repo = Repo(local_path)
32
- if 'origin' in [remote.name for remote in repo.remotes]:
33
- origin = repo.remote('origin')
34
- origin.set_url(repo_url)
35
- else:
36
- origin = repo.create_remote('origin', repo_url)
37
- origin.push(refspec='{}:{}'.format('master', 'master'))
38
 
39
- def main():
40
- st.title("GitHub Repository Cloner and Uploader")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Sidebar instructions (unchanged)
43
- st.sidebar.title("How to Get Your GitHub Token")
44
- st.sidebar.markdown("""
45
- 1. Go to your GitHub account settings
46
- 2. Click on 'Developer settings' in the left sidebar
47
- 3. Click on 'Personal access tokens' and then 'Tokens (classic)'
48
- 4. Click 'Generate new token' and select 'Generate new token (classic)'
49
- 5. Give your token a descriptive name
50
- 6. Select the following scopes:
51
- - repo (all)
52
- - delete_repo
53
- 7. Click 'Generate token' at the bottom of the page
54
- 8. Copy your new token immediately (you won't be able to see it again!)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- **Important:** Keep your token secret and secure. Treat it like a password!
57
- """)
58
-
59
- # Input for source repository
60
- source_repo = st.text_input("Source GitHub Repository URL",
61
- value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit/")
62
-
63
- # GitHub token input
64
- github_token = os.environ.get("GITHUB")
65
- if not github_token:
66
- github_token = st.text_input("GitHub Personal Access Token", type="password",
67
- help="Paste your GitHub token here. See sidebar for instructions on how to get it.")
68
-
69
- if st.button("Clone and Upload"):
70
- if not github_token:
71
- st.error("Please enter a GitHub token. See the sidebar for instructions.")
72
- return
73
-
74
- with st.spinner("Processing..."):
75
- try:
76
- # Generate a date-stamped name
77
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
78
- new_repo_name = f"AIExample-Clone-{timestamp}"
79
- local_path = f"./temp_repo_{timestamp}"
80
-
81
- # Download the source repository
82
- download_github_repo(source_repo, local_path)
83
-
84
- # Create a zip file
85
- zip_filename = f"repo_contents_{timestamp}"
86
- create_zip_file(local_path, zip_filename)
87
-
88
- # Create the new repository
89
- g = Github(github_token)
90
- user = g.get_user()
91
- new_repo = create_repo(g, new_repo_name)
92
-
93
- # Push the contents to the new repository
94
- push_to_github(local_path, new_repo, github_token)
95
-
96
- # Clean up
97
- shutil.rmtree(local_path)
98
- os.remove(zip_filename + ".zip")
99
-
100
- st.success(f"Repository cloned and uploaded successfully to {new_repo.html_url}!")
101
-
102
- except Exception as e:
103
- st.error(f"An error occurred: {str(e)}")
104
- finally:
105
- # Ensure cleanup even if an error occurs
106
- if os.path.exists(local_path):
107
- shutil.rmtree(local_path)
108
- if os.path.exists(zip_filename + ".zip"):
109
- os.remove(zip_filename + ".zip")
110
-
111
- if __name__ == "__main__":
112
- main()
 
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}")