File size: 8,450 Bytes
846748c 072cd2f | 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | import streamlit as st
import pandas as pd
import joblib
import plotly.express as px
import numpy as np
# Page configuration
st.set_page_config(
page_title="API Status Code Predictor",
page_icon="๐ก",
layout="wide"
)
# Custom CSS for better styling
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
color: #1E88E5;
margin-bottom: 0;
}
.sub-header {
font-size: 1.1rem;
color: #666;
margin-top: 0;
margin-bottom: 2rem;
}
.card {
padding: 1.5rem;
border-radius: 0.5rem;
background-color: #f8f9fa;
box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
margin-bottom: 1rem;
}
.highlight-number {
font-size: 3rem;
font-weight: bold;
}
.status-200 { color: #4CAF50; }
.status-400 { color: #FF9800; }
.status-500 { color: #F44336; }
</style>
""", unsafe_allow_html=True)
# Load model
@st.cache_resource
def load_model():
return joblib.load("status_code_classifier.pkl")
try:
model = load_model()
model_loaded = True
except:
st.error("โ ๏ธ Model file not found. Using a placeholder for demonstration purposes.")
model_loaded = False
# Create a dummy model for UI demonstration
class DummyModel:
def __init__(self):
self.classes_ = np.array([200, 400, 500])
def predict(self, X):
return np.array([200])
def predict_proba(self, X):
return np.array([[0.75, 0.15, 0.10]])
model = DummyModel()
# Header section
st.markdown("<h1 class='main-header'>๐ก API Status Code Predictor</h1>", unsafe_allow_html=True)
st.markdown(
"<p class='sub-header'>Analyze API behaviors and predict response status codes based on request parameters</p>",
unsafe_allow_html=True)
# Create two columns for layout
col1, col2 = st.columns([3, 5])
# Sidebar with inputs - now moved to a card in the left column
with col1:
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.subheader("๐ Request Parameters")
# API and Environment selection with more informative labels
api_options = {
"OrderProcessor": "Order Processing API",
"AuthService": "Authentication Service",
"ProductCatalog": "Product Catalog API",
"PaymentGateway": "Payment Gateway"
}
api_id = st.selectbox("API Service", list(api_options.keys()), format_func=lambda x: api_options[x])
env = st.selectbox(
"Environment",
["production-useast1", "staging"],
format_func=lambda x: f"{'Production (US East)' if x == 'production-useast1' else 'Staging'}"
)
# More organized parameter inputs with tooltips
st.subheader("โ๏ธ Performance Metrics")
latency_ms = st.slider(
"Latency (ms)",
min_value=0.0,
max_value=100.0,
value=10.0,
help="Response time in milliseconds"
)
bytes_transferred = st.slider(
"Bytes Transferred",
min_value=0,
max_value=15000,
value=500,
help="Size of data transferred in bytes"
)
st.subheader("๐ Request Context")
hour_of_day = st.select_slider(
"Hour of Day",
options=list(range(24)),
value=12,
format_func=lambda x: f"{x:02d}:00"
)
cpu_cost = st.slider(
"CPU Cost",
min_value=0.0,
max_value=50.0,
value=10.0,
help="Computational resources used"
)
memory_mb = st.slider(
"Memory Usage (MB)",
min_value=0.0,
max_value=100.0,
value=25.0,
help="Memory consumption in megabytes"
)
# Add a predict button to make prediction more intentional
predict_button = st.button("๐ฎ Predict Status Code", use_container_width=True)
st.markdown("</div>", unsafe_allow_html=True)
# Mapping to codes - moved after selection
api_id_code = {"OrderProcessor": 2, "AuthService": 0, "ProductCatalog": 1, "PaymentGateway": 3}[api_id]
env_code = {"production-useast1": 1, "staging": 0}[env]
# Input for prediction
input_data = pd.DataFrame([[api_id_code, env_code, latency_ms, bytes_transferred, hour_of_day, cpu_cost, memory_mb]],
columns=['api_id', 'env', 'latency_ms', 'bytes_transferred', 'hour_of_day',
'simulated_cpu_cost', 'simulated_memory_mb'])
# Results section on the right
with col2:
if predict_button or not model_loaded:
# Predict
prediction = model.predict(input_data)[0]
probabilities = model.predict_proba(input_data)
# Format prediction results
status_codes = {
200: "Success (200)",
400: "Client Error (400)",
500: "Server Error (500)"
}
status_class = {
200: "status-200",
400: "status-400",
500: "status-500"
}
# Display the prediction in a card
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.subheader("๐ฏ Prediction Result")
st.markdown(
f"<p>Most likely status code:</p><h1 class='highlight-number {status_class[prediction]}'>{prediction}</h1><p>{status_codes.get(prediction, 'Unknown')}</p>",
unsafe_allow_html=True)
# Show prediction confidence
prob_dict = {int(model.classes_[i]): float(probabilities[0][i]) for i in range(len(model.classes_))}
confidence = prob_dict[prediction] * 100
st.write(f"Confidence: {confidence:.1f}%")
st.markdown("</div>", unsafe_allow_html=True)
# Show probability distribution with a horizontal bar chart
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.subheader("๐ Probability Distribution")
# Create dataframe for visualization
prob_df = pd.DataFrame({
'Status Code': [f"{int(code)} - {status_codes.get(int(code), 'Unknown')}" for code in model.classes_],
'Probability': probabilities[0]
})
# Create a bar chart using Plotly
fig = px.bar(
prob_df,
x='Probability',
y='Status Code',
orientation='h',
color='Status Code',
color_discrete_map={
f"200 - {status_codes.get(200)}": '#4CAF50',
f"400 - {status_codes.get(400)}": '#FF9800',
f"500 - {status_codes.get(500)}": '#F44336'
}
)
fig.update_layout(
height=300,
margin=dict(l=20, r=20, t=30, b=20),
xaxis_title="Probability",
yaxis_title="",
xaxis=dict(tickformat=".0%")
)
st.plotly_chart(fig, use_container_width=True)
st.markdown("</div>", unsafe_allow_html=True)
# Parameters influence section
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.subheader("๐ Feature Importance")
st.write("How different parameters influence the prediction:")
# Mock feature importance for demonstration
# In a real app, you'd use model-specific methods to calculate this
feature_importance = {
'API Service': 0.25,
'Environment': 0.15,
'Latency': 0.20,
'Bytes Transferred': 0.10,
'Time of Day': 0.05,
'CPU Cost': 0.15,
'Memory Usage': 0.10
}
# Create a horizontal bar chart for feature importance
importance_df = pd.DataFrame({
'Feature': list(feature_importance.keys()),
'Importance': list(feature_importance.values())
}).sort_values('Importance', ascending=False)
fig_importance = px.bar(
importance_df,
x='Importance',
y='Feature',
orientation='h',
color='Importance',
color_continuous_scale='Blues'
)
fig_importance.update_layout(
height=350,
margin=dict(l=20, r=20, t=20, b=20),
yaxis_title="",
coloraxis_showscale=False
)
st.plotly_chart(fig_importance, use_container_width=True)
st.markdown("</div>", unsafe_allow_html=True)
# Footer with information
st.markdown("---")
st.markdown(
"๐ก **About**: This tool uses machine learning to predict API response status codes based on request parameters and system metrics.") |