forked from avinashchandan12/Misty-AI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
228 lines (197 loc) · 9.28 KB
/
app.py
File metadata and controls
228 lines (197 loc) · 9.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import json
import uuid
from datetime import datetime, timedelta
import os
import streamlit as st
import time
import threading
import streamlit as st
import os
import shutil
import time
import json
import uuid
from datetime import datetime, timedelta
from llm_inference import LLMInference
from config import read_openai_config
from streamlit.components.v1 import html
# Function to load example data
def load_example_data():
with open("example.json", "r") as file:
return json.load(file)
openai_config = read_openai_config()
# Load access codes
def load_access_codes():
with open("access_codes.json", "r") as file:
return json.load(file)
access_codes = load_access_codes()
# Load sessions
def load_sessions():
with open("sessions.json", "r") as file:
return json.load(file)
# Save sessions
def save_sessions(sessions):
with open("sessions.json", "w") as file:
json.dump(sessions, file)
# Create a session
def create_session(email):
sessions = load_sessions()
session_id = uuid.uuid4().hex
sessions[email] = {"session_id": session_id, "timestamp": datetime.now().isoformat()}
save_sessions(sessions)
return session_id
# Validate a session
def validate_session(email, session_id):
sessions = load_sessions()
if email in sessions:
session = sessions[email]
if session["session_id"] == session_id:
session_time = datetime.fromisoformat(session["timestamp"])
if datetime.now() - session_time < timedelta(minutes=30):
return True
return False
# Terminate a session
def terminate_session(email):
sessions = load_sessions()
if email in sessions:
del sessions[email]
save_sessions(sessions)
# Authentication
def authenticate(email, code):
return access_codes.get(email) == code
# Function to clean up generated files
def cleanup_files(files):
for file in files:
if os.path.exists(file):
os.remove(file)
# Endpoint to handle cleanup requests
def handle_cleanup_request():
if "output" in st.session_state and st.session_state["output"]:
cleanup_files([st.session_state["output"]["png_path"], st.session_state["output"]["drawio_path"]])
st.session_state["submitted"] = False
st.session_state["output"] = None
st.session_state["input_data"] = None
# App state initialization
if "authenticated" not in st.session_state:
st.session_state["authenticated"] = True
if "email" not in st.session_state:
st.session_state["email"] = None
if "session_id" not in st.session_state:
st.session_state["session_id"] = None
if "submitted" not in st.session_state:
st.session_state["submitted"] = False
if "output" not in st.session_state:
st.session_state["output"] = None
if "last_interaction" not in st.session_state:
st.session_state["last_interaction"] = time.time()
if "input_data" not in st.session_state:
st.session_state["input_data"] = None
# Function to check idle time and cleanup
def check_idle_time():
if time.time() - st.session_state["last_interaction"] > 30: # 30 seconds
handle_cleanup_request()
terminate_session(st.session_state["email"])
st.session_state["authenticated"] = False
st.stop()
# Update last interaction time
def update_interaction():
st.session_state["last_interaction"] = time.time()
# Inject JavaScript to handle page unload
st.markdown("""
<script>
window.addEventListener('beforeunload', function (event) {
// Send a request to the cleanup endpoint
fetch('/clean-up', { method: 'POST' });
});
</script>
""", unsafe_allow_html=True)
# Title
st.title("MistyAI CloudArch Designer")
update_interaction()
#LOGO
logo_image = "logo.jpg"
st.logo(logo_image)
# Supported cloud providers
cloud_providers = ["AWS", "Azure", "Google Cloud", "IBM Cloud", "Oracle Cloud"]
# Adding a button to load example data
if st.button("Load Example Data"):
example_data = load_example_data()
# Extracting data from the example JSON
example_title = example_data["questions_and_answers"][0]["answer"]
example_resources = example_data["questions_and_answers"][1]["answer"]
example_clustering = example_data["questions_and_answers"][2]["answer"]
example_relationships = example_data["questions_and_answers"][3]["answer"]
# Pre-filling the form fields with example data
st.session_state["title"] = example_title
st.session_state["resources"] = example_resources
st.session_state["clustering"] = example_clustering
st.session_state["relationships"] = example_relationships
st.session_state["file_name"] = "example"
st.session_state["selected_providers"] = ["AWS"]
# User inputs
with st.form("architecture_form"):
file_name = st.text_input("Provide a file name for the project. Warning: File name will be used as provided", st.session_state.get("file_name", ""))
title = st.text_input("Provide a title of your cloud system architecture and a brief description", st.session_state.get("title", ""))
selected_providers = st.multiselect("Select cloud providers", cloud_providers, st.session_state.get("selected_providers", []))
resources = st.text_area("What are the resources used in this cloud system architecture?", st.session_state.get("resources", ""), height=150)
clustering = st.text_area("How are these cloud provider resources clustered or grouped? Describe in detail.", st.session_state.get("clustering", ""), height=150)
relationships = st.text_area("Describe the relationships between these resources and clusters/groups", st.session_state.get("relationships", ""), height=150)
submitted = st.form_submit_button("Submit", on_click=update_interaction)
# Handle form submission
user_id = st.session_state["session_id"]
if submitted:
input_data = {
"title": title,
"resources": resources,
"clustering": clustering,
"relationships": relationships,
"cloud_providers": selected_providers,
"file_name": file_name + "_" + uuid.uuid4().hex
}
st.session_state["input_data"] = input_data
st.session_state["output"] = LLMInference().run_inference_google(input_data) # Google inference
st.session_state["submitted"] = True
# Display generated PNG and provide options if submitted
if st.session_state["submitted"]:
st.image(st.session_state["output"]["png_path"])
update_interaction()
if st.button("Regenerate", on_click=update_interaction):
# st.session_state["output"] = LLMInference().run_inference_openai(st.session_state["input_data"]) # OpenAI inference
st.session_state["output"] = LLMInference().run_inference_google(st.session_state["input_data"]) # Google Inference
st.image(st.session_state["output"]["png_path"])
st.experimental_rerun()
if st.button("Import to DrawIO", on_click=update_interaction):
with open(st.session_state["output"]["drawio_path"], "rb") as f:
st.download_button(
label="Download DrawIO File",
data=f,
file_name=f"{st.session_state['input_data']['file_name']}.drawio",
mime="application/octet-stream"
)
if st.button("Restart", on_click=update_interaction):
files_to_remove = [
f"{st.session_state['input_data']['file_name']}.drawio",
f"{st.session_state['input_data']['file_name']}.png",
f"{st.session_state['input_data']['file_name']}.dot",
f"{st.session_state['input_data']['file_name']}"
]
cleanup_files(files_to_remove)
st.session_state["submitted"] = False
st.session_state["output"] = None
st.session_state["input_data"] = None
st.experimental_rerun()
# Function to clean up files with .dot, .png extensions and no extension
def periodic_cleanup():
while True:
now = time.time()
for file in os.listdir('.'):
if file.endswith('.dot') or file.endswith('.png') or file.endswith('.drawio') or not os.path.splitext(file)[1]:
if os.path.isfile(file) and now - os.path.getmtime(file) > 30*60:
os.remove(file)
time.sleep(30*60) # Sleep for 30 minutes
# Start the daemon thread for periodic cleanup
cleanup_thread = threading.Thread(target=periodic_cleanup, daemon=True)
cleanup_thread.start()
# Check idle time
check_idle_time()
st.link_button("Join our Discord Server", "https://discord.gg/6Jz79xKdPE", help=None, type="secondary", disabled=False, use_container_width=False)