pranit144 commited on
Commit
846748c
ยท
verified ยท
1 Parent(s): 072cd2f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +273 -273
app.py CHANGED
@@ -1,274 +1,274 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import joblib
4
- import plotly.express as px
5
- import numpy as np
6
-
7
- # Page configuration
8
- st.set_page_config(
9
- page_title="API Status Code Predictor",
10
- page_icon="๐Ÿ“ก",
11
- layout="wide"
12
- )
13
-
14
- # Custom CSS for better styling
15
- st.markdown("""
16
- <style>
17
- .main-header {
18
- font-size: 2.5rem;
19
- color: #1E88E5;
20
- margin-bottom: 0;
21
- }
22
- .sub-header {
23
- font-size: 1.1rem;
24
- color: #666;
25
- margin-top: 0;
26
- margin-bottom: 2rem;
27
- }
28
- .card {
29
- padding: 1.5rem;
30
- border-radius: 0.5rem;
31
- background-color: #f8f9fa;
32
- box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
33
- margin-bottom: 1rem;
34
- }
35
- .highlight-number {
36
- font-size: 3rem;
37
- font-weight: bold;
38
- }
39
- .status-200 { color: #4CAF50; }
40
- .status-400 { color: #FF9800; }
41
- .status-500 { color: #F44336; }
42
- </style>
43
- """, unsafe_allow_html=True)
44
-
45
-
46
- # Load model
47
- @st.cache_resource
48
- def load_model():
49
- return joblib.load("C:\Users\prani\PycharmProjects\PythonProject15\status_code_classifier.pkl")
50
-
51
-
52
- try:
53
- model = load_model()
54
- model_loaded = True
55
- except:
56
- st.error("โš ๏ธ Model file not found. Using a placeholder for demonstration purposes.")
57
- model_loaded = False
58
-
59
-
60
- # Create a dummy model for UI demonstration
61
- class DummyModel:
62
- def __init__(self):
63
- self.classes_ = np.array([200, 400, 500])
64
-
65
- def predict(self, X):
66
- return np.array([200])
67
-
68
- def predict_proba(self, X):
69
- return np.array([[0.75, 0.15, 0.10]])
70
-
71
-
72
- model = DummyModel()
73
-
74
- # Header section
75
- st.markdown("<h1 class='main-header'>๐Ÿ“ก API Status Code Predictor</h1>", unsafe_allow_html=True)
76
- st.markdown(
77
- "<p class='sub-header'>Analyze API behaviors and predict response status codes based on request parameters</p>",
78
- unsafe_allow_html=True)
79
-
80
- # Create two columns for layout
81
- col1, col2 = st.columns([3, 5])
82
-
83
- # Sidebar with inputs - now moved to a card in the left column
84
- with col1:
85
- st.markdown("<div class='card'>", unsafe_allow_html=True)
86
- st.subheader("๐Ÿ“ Request Parameters")
87
-
88
- # API and Environment selection with more informative labels
89
- api_options = {
90
- "OrderProcessor": "Order Processing API",
91
- "AuthService": "Authentication Service",
92
- "ProductCatalog": "Product Catalog API",
93
- "PaymentGateway": "Payment Gateway"
94
- }
95
- api_id = st.selectbox("API Service", list(api_options.keys()), format_func=lambda x: api_options[x])
96
-
97
- env = st.selectbox(
98
- "Environment",
99
- ["production-useast1", "staging"],
100
- format_func=lambda x: f"{'Production (US East)' if x == 'production-useast1' else 'Staging'}"
101
- )
102
-
103
- # More organized parameter inputs with tooltips
104
- st.subheader("โš™๏ธ Performance Metrics")
105
-
106
- latency_ms = st.slider(
107
- "Latency (ms)",
108
- min_value=0.0,
109
- max_value=100.0,
110
- value=10.0,
111
- help="Response time in milliseconds"
112
- )
113
-
114
- bytes_transferred = st.slider(
115
- "Bytes Transferred",
116
- min_value=0,
117
- max_value=15000,
118
- value=500,
119
- help="Size of data transferred in bytes"
120
- )
121
-
122
- st.subheader("๐Ÿ”„ Request Context")
123
-
124
- hour_of_day = st.select_slider(
125
- "Hour of Day",
126
- options=list(range(24)),
127
- value=12,
128
- format_func=lambda x: f"{x:02d}:00"
129
- )
130
-
131
- cpu_cost = st.slider(
132
- "CPU Cost",
133
- min_value=0.0,
134
- max_value=50.0,
135
- value=10.0,
136
- help="Computational resources used"
137
- )
138
-
139
- memory_mb = st.slider(
140
- "Memory Usage (MB)",
141
- min_value=0.0,
142
- max_value=100.0,
143
- value=25.0,
144
- help="Memory consumption in megabytes"
145
- )
146
-
147
- # Add a predict button to make prediction more intentional
148
- predict_button = st.button("๐Ÿ”ฎ Predict Status Code", use_container_width=True)
149
- st.markdown("</div>", unsafe_allow_html=True)
150
-
151
- # Mapping to codes - moved after selection
152
- api_id_code = {"OrderProcessor": 2, "AuthService": 0, "ProductCatalog": 1, "PaymentGateway": 3}[api_id]
153
- env_code = {"production-useast1": 1, "staging": 0}[env]
154
-
155
- # Input for prediction
156
- input_data = pd.DataFrame([[api_id_code, env_code, latency_ms, bytes_transferred, hour_of_day, cpu_cost, memory_mb]],
157
- columns=['api_id', 'env', 'latency_ms', 'bytes_transferred', 'hour_of_day',
158
- 'simulated_cpu_cost', 'simulated_memory_mb'])
159
-
160
- # Results section on the right
161
- with col2:
162
- if predict_button or not model_loaded:
163
- # Predict
164
- prediction = model.predict(input_data)[0]
165
- probabilities = model.predict_proba(input_data)
166
-
167
- # Format prediction results
168
- status_codes = {
169
- 200: "Success (200)",
170
- 400: "Client Error (400)",
171
- 500: "Server Error (500)"
172
- }
173
-
174
- status_class = {
175
- 200: "status-200",
176
- 400: "status-400",
177
- 500: "status-500"
178
- }
179
-
180
- # Display the prediction in a card
181
- st.markdown("<div class='card'>", unsafe_allow_html=True)
182
- st.subheader("๐ŸŽฏ Prediction Result")
183
-
184
- st.markdown(
185
- f"<p>Most likely status code:</p><h1 class='highlight-number {status_class[prediction]}'>{prediction}</h1><p>{status_codes.get(prediction, 'Unknown')}</p>",
186
- unsafe_allow_html=True)
187
-
188
- # Show prediction confidence
189
- prob_dict = {int(model.classes_[i]): float(probabilities[0][i]) for i in range(len(model.classes_))}
190
- confidence = prob_dict[prediction] * 100
191
- st.write(f"Confidence: {confidence:.1f}%")
192
- st.markdown("</div>", unsafe_allow_html=True)
193
-
194
- # Show probability distribution with a horizontal bar chart
195
- st.markdown("<div class='card'>", unsafe_allow_html=True)
196
- st.subheader("๐Ÿ“Š Probability Distribution")
197
-
198
- # Create dataframe for visualization
199
- prob_df = pd.DataFrame({
200
- 'Status Code': [f"{int(code)} - {status_codes.get(int(code), 'Unknown')}" for code in model.classes_],
201
- 'Probability': probabilities[0]
202
- })
203
-
204
- # Create a bar chart using Plotly
205
- fig = px.bar(
206
- prob_df,
207
- x='Probability',
208
- y='Status Code',
209
- orientation='h',
210
- color='Status Code',
211
- color_discrete_map={
212
- f"200 - {status_codes.get(200)}": '#4CAF50',
213
- f"400 - {status_codes.get(400)}": '#FF9800',
214
- f"500 - {status_codes.get(500)}": '#F44336'
215
- }
216
- )
217
-
218
- fig.update_layout(
219
- height=300,
220
- margin=dict(l=20, r=20, t=30, b=20),
221
- xaxis_title="Probability",
222
- yaxis_title="",
223
- xaxis=dict(tickformat=".0%")
224
- )
225
-
226
- st.plotly_chart(fig, use_container_width=True)
227
- st.markdown("</div>", unsafe_allow_html=True)
228
-
229
- # Parameters influence section
230
- st.markdown("<div class='card'>", unsafe_allow_html=True)
231
- st.subheader("๐Ÿ” Feature Importance")
232
- st.write("How different parameters influence the prediction:")
233
-
234
- # Mock feature importance for demonstration
235
- # In a real app, you'd use model-specific methods to calculate this
236
- feature_importance = {
237
- 'API Service': 0.25,
238
- 'Environment': 0.15,
239
- 'Latency': 0.20,
240
- 'Bytes Transferred': 0.10,
241
- 'Time of Day': 0.05,
242
- 'CPU Cost': 0.15,
243
- 'Memory Usage': 0.10
244
- }
245
-
246
- # Create a horizontal bar chart for feature importance
247
- importance_df = pd.DataFrame({
248
- 'Feature': list(feature_importance.keys()),
249
- 'Importance': list(feature_importance.values())
250
- }).sort_values('Importance', ascending=False)
251
-
252
- fig_importance = px.bar(
253
- importance_df,
254
- x='Importance',
255
- y='Feature',
256
- orientation='h',
257
- color='Importance',
258
- color_continuous_scale='Blues'
259
- )
260
-
261
- fig_importance.update_layout(
262
- height=350,
263
- margin=dict(l=20, r=20, t=20, b=20),
264
- yaxis_title="",
265
- coloraxis_showscale=False
266
- )
267
-
268
- st.plotly_chart(fig_importance, use_container_width=True)
269
- st.markdown("</div>", unsafe_allow_html=True)
270
-
271
- # Footer with information
272
- st.markdown("---")
273
- st.markdown(
274
  "๐Ÿ’ก **About**: This tool uses machine learning to predict API response status codes based on request parameters and system metrics.")
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import joblib
4
+ import plotly.express as px
5
+ import numpy as np
6
+
7
+ # Page configuration
8
+ st.set_page_config(
9
+ page_title="API Status Code Predictor",
10
+ page_icon="๐Ÿ“ก",
11
+ layout="wide"
12
+ )
13
+
14
+ # Custom CSS for better styling
15
+ st.markdown("""
16
+ <style>
17
+ .main-header {
18
+ font-size: 2.5rem;
19
+ color: #1E88E5;
20
+ margin-bottom: 0;
21
+ }
22
+ .sub-header {
23
+ font-size: 1.1rem;
24
+ color: #666;
25
+ margin-top: 0;
26
+ margin-bottom: 2rem;
27
+ }
28
+ .card {
29
+ padding: 1.5rem;
30
+ border-radius: 0.5rem;
31
+ background-color: #f8f9fa;
32
+ box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
33
+ margin-bottom: 1rem;
34
+ }
35
+ .highlight-number {
36
+ font-size: 3rem;
37
+ font-weight: bold;
38
+ }
39
+ .status-200 { color: #4CAF50; }
40
+ .status-400 { color: #FF9800; }
41
+ .status-500 { color: #F44336; }
42
+ </style>
43
+ """, unsafe_allow_html=True)
44
+
45
+
46
+ # Load model
47
+ @st.cache_resource
48
+ def load_model():
49
+ return joblib.load("status_code_classifier.pkl")
50
+
51
+
52
+ try:
53
+ model = load_model()
54
+ model_loaded = True
55
+ except:
56
+ st.error("โš ๏ธ Model file not found. Using a placeholder for demonstration purposes.")
57
+ model_loaded = False
58
+
59
+
60
+ # Create a dummy model for UI demonstration
61
+ class DummyModel:
62
+ def __init__(self):
63
+ self.classes_ = np.array([200, 400, 500])
64
+
65
+ def predict(self, X):
66
+ return np.array([200])
67
+
68
+ def predict_proba(self, X):
69
+ return np.array([[0.75, 0.15, 0.10]])
70
+
71
+
72
+ model = DummyModel()
73
+
74
+ # Header section
75
+ st.markdown("<h1 class='main-header'>๐Ÿ“ก API Status Code Predictor</h1>", unsafe_allow_html=True)
76
+ st.markdown(
77
+ "<p class='sub-header'>Analyze API behaviors and predict response status codes based on request parameters</p>",
78
+ unsafe_allow_html=True)
79
+
80
+ # Create two columns for layout
81
+ col1, col2 = st.columns([3, 5])
82
+
83
+ # Sidebar with inputs - now moved to a card in the left column
84
+ with col1:
85
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
86
+ st.subheader("๐Ÿ“ Request Parameters")
87
+
88
+ # API and Environment selection with more informative labels
89
+ api_options = {
90
+ "OrderProcessor": "Order Processing API",
91
+ "AuthService": "Authentication Service",
92
+ "ProductCatalog": "Product Catalog API",
93
+ "PaymentGateway": "Payment Gateway"
94
+ }
95
+ api_id = st.selectbox("API Service", list(api_options.keys()), format_func=lambda x: api_options[x])
96
+
97
+ env = st.selectbox(
98
+ "Environment",
99
+ ["production-useast1", "staging"],
100
+ format_func=lambda x: f"{'Production (US East)' if x == 'production-useast1' else 'Staging'}"
101
+ )
102
+
103
+ # More organized parameter inputs with tooltips
104
+ st.subheader("โš™๏ธ Performance Metrics")
105
+
106
+ latency_ms = st.slider(
107
+ "Latency (ms)",
108
+ min_value=0.0,
109
+ max_value=100.0,
110
+ value=10.0,
111
+ help="Response time in milliseconds"
112
+ )
113
+
114
+ bytes_transferred = st.slider(
115
+ "Bytes Transferred",
116
+ min_value=0,
117
+ max_value=15000,
118
+ value=500,
119
+ help="Size of data transferred in bytes"
120
+ )
121
+
122
+ st.subheader("๐Ÿ”„ Request Context")
123
+
124
+ hour_of_day = st.select_slider(
125
+ "Hour of Day",
126
+ options=list(range(24)),
127
+ value=12,
128
+ format_func=lambda x: f"{x:02d}:00"
129
+ )
130
+
131
+ cpu_cost = st.slider(
132
+ "CPU Cost",
133
+ min_value=0.0,
134
+ max_value=50.0,
135
+ value=10.0,
136
+ help="Computational resources used"
137
+ )
138
+
139
+ memory_mb = st.slider(
140
+ "Memory Usage (MB)",
141
+ min_value=0.0,
142
+ max_value=100.0,
143
+ value=25.0,
144
+ help="Memory consumption in megabytes"
145
+ )
146
+
147
+ # Add a predict button to make prediction more intentional
148
+ predict_button = st.button("๐Ÿ”ฎ Predict Status Code", use_container_width=True)
149
+ st.markdown("</div>", unsafe_allow_html=True)
150
+
151
+ # Mapping to codes - moved after selection
152
+ api_id_code = {"OrderProcessor": 2, "AuthService": 0, "ProductCatalog": 1, "PaymentGateway": 3}[api_id]
153
+ env_code = {"production-useast1": 1, "staging": 0}[env]
154
+
155
+ # Input for prediction
156
+ input_data = pd.DataFrame([[api_id_code, env_code, latency_ms, bytes_transferred, hour_of_day, cpu_cost, memory_mb]],
157
+ columns=['api_id', 'env', 'latency_ms', 'bytes_transferred', 'hour_of_day',
158
+ 'simulated_cpu_cost', 'simulated_memory_mb'])
159
+
160
+ # Results section on the right
161
+ with col2:
162
+ if predict_button or not model_loaded:
163
+ # Predict
164
+ prediction = model.predict(input_data)[0]
165
+ probabilities = model.predict_proba(input_data)
166
+
167
+ # Format prediction results
168
+ status_codes = {
169
+ 200: "Success (200)",
170
+ 400: "Client Error (400)",
171
+ 500: "Server Error (500)"
172
+ }
173
+
174
+ status_class = {
175
+ 200: "status-200",
176
+ 400: "status-400",
177
+ 500: "status-500"
178
+ }
179
+
180
+ # Display the prediction in a card
181
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
182
+ st.subheader("๐ŸŽฏ Prediction Result")
183
+
184
+ st.markdown(
185
+ f"<p>Most likely status code:</p><h1 class='highlight-number {status_class[prediction]}'>{prediction}</h1><p>{status_codes.get(prediction, 'Unknown')}</p>",
186
+ unsafe_allow_html=True)
187
+
188
+ # Show prediction confidence
189
+ prob_dict = {int(model.classes_[i]): float(probabilities[0][i]) for i in range(len(model.classes_))}
190
+ confidence = prob_dict[prediction] * 100
191
+ st.write(f"Confidence: {confidence:.1f}%")
192
+ st.markdown("</div>", unsafe_allow_html=True)
193
+
194
+ # Show probability distribution with a horizontal bar chart
195
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
196
+ st.subheader("๐Ÿ“Š Probability Distribution")
197
+
198
+ # Create dataframe for visualization
199
+ prob_df = pd.DataFrame({
200
+ 'Status Code': [f"{int(code)} - {status_codes.get(int(code), 'Unknown')}" for code in model.classes_],
201
+ 'Probability': probabilities[0]
202
+ })
203
+
204
+ # Create a bar chart using Plotly
205
+ fig = px.bar(
206
+ prob_df,
207
+ x='Probability',
208
+ y='Status Code',
209
+ orientation='h',
210
+ color='Status Code',
211
+ color_discrete_map={
212
+ f"200 - {status_codes.get(200)}": '#4CAF50',
213
+ f"400 - {status_codes.get(400)}": '#FF9800',
214
+ f"500 - {status_codes.get(500)}": '#F44336'
215
+ }
216
+ )
217
+
218
+ fig.update_layout(
219
+ height=300,
220
+ margin=dict(l=20, r=20, t=30, b=20),
221
+ xaxis_title="Probability",
222
+ yaxis_title="",
223
+ xaxis=dict(tickformat=".0%")
224
+ )
225
+
226
+ st.plotly_chart(fig, use_container_width=True)
227
+ st.markdown("</div>", unsafe_allow_html=True)
228
+
229
+ # Parameters influence section
230
+ st.markdown("<div class='card'>", unsafe_allow_html=True)
231
+ st.subheader("๐Ÿ” Feature Importance")
232
+ st.write("How different parameters influence the prediction:")
233
+
234
+ # Mock feature importance for demonstration
235
+ # In a real app, you'd use model-specific methods to calculate this
236
+ feature_importance = {
237
+ 'API Service': 0.25,
238
+ 'Environment': 0.15,
239
+ 'Latency': 0.20,
240
+ 'Bytes Transferred': 0.10,
241
+ 'Time of Day': 0.05,
242
+ 'CPU Cost': 0.15,
243
+ 'Memory Usage': 0.10
244
+ }
245
+
246
+ # Create a horizontal bar chart for feature importance
247
+ importance_df = pd.DataFrame({
248
+ 'Feature': list(feature_importance.keys()),
249
+ 'Importance': list(feature_importance.values())
250
+ }).sort_values('Importance', ascending=False)
251
+
252
+ fig_importance = px.bar(
253
+ importance_df,
254
+ x='Importance',
255
+ y='Feature',
256
+ orientation='h',
257
+ color='Importance',
258
+ color_continuous_scale='Blues'
259
+ )
260
+
261
+ fig_importance.update_layout(
262
+ height=350,
263
+ margin=dict(l=20, r=20, t=20, b=20),
264
+ yaxis_title="",
265
+ coloraxis_showscale=False
266
+ )
267
+
268
+ st.plotly_chart(fig_importance, use_container_width=True)
269
+ st.markdown("</div>", unsafe_allow_html=True)
270
+
271
+ # Footer with information
272
+ st.markdown("---")
273
+ st.markdown(
274
  "๐Ÿ’ก **About**: This tool uses machine learning to predict API response status codes based on request parameters and system metrics.")