pranit144 commited on
Commit
4760f46
ยท
verified ยท
1 Parent(s): db536eb

Update app.py

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