awacke1 commited on
Commit
3c873ff
โ€ข
1 Parent(s): 0b505f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -153
app.py CHANGED
@@ -1,159 +1,112 @@
1
  import streamlit as st
2
- from azure.cosmos import CosmosClient, PartitionKey
3
  import os
4
- import pandas as pd
 
 
 
 
5
 
6
- # Streamlit page configuration for wide mode
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 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
- # Login section
56
- if 'logged_in' not in st.session_state:
57
- st.session_state.logged_in = False
58
-
59
- if not st.session_state.logged_in:
60
- st.subheader("๐Ÿ” Login")
61
- input_key = Key
62
- if st.button("๐Ÿš€ Login"):
63
- if input_key:
64
- st.session_state.primary_key = input_key
65
- st.session_state.logged_in = True
66
- st.rerun()
67
- else:
68
- st.error("Invalid key. Please check your environment variables.")
69
- else:
70
- # Initialize Cosmos DB client
71
- client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
72
- database = client.get_database_client(DATABASE_NAME)
73
- container = database.get_container_client(CONTAINER_NAME)
74
-
75
- # Fetch all records
76
- records_df = fetch_all_records()
77
-
78
- # Sidebar for data editing
79
- st.sidebar.title("Edit Records")
80
- edited_df = st.sidebar.data_editor(records_df, num_rows="dynamic", key="sidebar_editor")
81
-
82
- # Main Content Area
83
- col1, col2 = st.columns(2)
84
-
85
- with col1:
86
- st.subheader("๐Ÿ“ Enter Record Details")
87
- id = st.text_input("ID")
88
- name = st.text_input("Name")
89
- document = st.text_area("Document")
90
- evaluation_text = st.text_area("Evaluation Text")
91
- evaluation_score = st.number_input("Evaluation Score", min_value=0, max_value=100, step=1)
92
-
93
- if st.button("๐Ÿ’พ Insert Record"):
94
- record = {
95
- "id": id,
96
- "name": name,
97
- "document": document,
98
- "evaluationText": evaluation_text,
99
- "evaluationScore": evaluation_score
100
- }
101
-
102
- success, response = insert_record(record)
103
- if success:
104
- st.success("โœ… Record inserted successfully!")
105
- st.json(response)
106
- else:
107
- st.error(f"โŒ Failed to insert record: {response}")
108
-
109
- with col2:
110
- st.subheader("๐Ÿ”ง Call Stored Procedure")
111
- if st.button("Call Procedure"):
112
- record = {
113
- "id": id,
114
- "name": name,
115
- "document": document,
116
- "evaluationText": evaluation_text,
117
- "evaluationScore": evaluation_score
118
- }
119
-
120
- success, response = call_stored_procedure(record)
121
- if success:
122
- st.success("โœ… Stored procedure executed successfully!")
123
- st.json(response)
124
- else:
125
- st.error(f"โŒ Failed to execute stored procedure: {response}")
126
-
127
- st.subheader("๐Ÿ“Š All Records")
128
- st.dataframe(edited_df)
129
-
130
- col3, col4 = st.columns(2)
131
- with col3:
132
- if st.button("๐Ÿ—‘๏ธ Delete Selected"):
133
- selected_ids = edited_df[edited_df['select']]['id'].tolist() if 'select' in edited_df.columns else []
134
- if selected_ids:
135
- success, message = delete_records(selected_ids)
136
- if success:
137
- st.success(message)
138
- else:
139
- st.error(message)
140
- st.rerun()
141
- else:
142
- st.warning("No records selected for deletion.")
143
-
144
- with col4:
145
- if st.download_button("๐Ÿ“ฅ Download Data", edited_df.to_csv(index=False), "cosmos_db_data.csv", "text/csv"):
146
- st.success("Data downloaded successfully!")
147
-
148
- # Logout button
149
- if st.button("๐Ÿšช Logout"):
150
- st.session_state.logged_in = False
151
- st.rerun()
152
-
153
- # Display connection info
154
- st.sidebar.markdown("---")
155
- st.sidebar.subheader("๐Ÿ”— Connection Information")
156
- st.sidebar.text(f"Endpoint: {ENDPOINT}")
157
- st.sidebar.text(f"Subscription ID: {SUBSCRIPTION_ID}")
158
- st.sidebar.text(f"Database: {DATABASE_NAME}")
159
- st.sidebar.text(f"Container: {CONTAINER_NAME}")
 
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()