File size: 10,003 Bytes
e29e711 | 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | import streamlit as st
import pandas as pd
import joblib
import matplotlib.pyplot as plt
import numpy as np
# Page configuration
st.set_page_config(
page_title="API Error Predictor",
page_icon="β οΈ",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: 700;
margin-bottom: 1rem;
}
.sub-header {
font-size: 1.5rem;
font-weight: 600;
margin-top: 1rem;
}
.info-box {
background-color: #f8f9fa;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
.prediction-box-success {
background-color: #d4edda;
color: #155724;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
text-align: center;
}
.prediction-box-error {
background-color: #f8d7da;
color: #721c24;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
text-align: center;
}
.sidebar-header {
font-size: 1.2rem;
font-weight: 600;
margin-bottom: 0.5rem;
}
.metric-container {
background-color: #e9ecef;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
</style>
""", unsafe_allow_html=True)
# Load trained model
@st.cache_resource
def load_model():
return joblib.load("error_classifier.pkl")
model = load_model()
# Header section
col1, col2 = st.columns([5, 1])
with col1:
st.markdown('<div class="main-header">β οΈ API Error Prediction System</div>', unsafe_allow_html=True)
st.markdown("""
<div class="info-box">
This tool predicts whether an API call will result in an error based on request metrics and parameters.
Use the sidebar to adjust input parameters and see real-time predictions.
</div>
""", unsafe_allow_html=True)
with col2:
st.image("https://via.placeholder.com/150", width=100) # Replace with your logo if available
# Sidebar for input parameters
st.sidebar.markdown('<div class="sidebar-header">π§ Input Parameters</div>', unsafe_allow_html=True)
# Group related parameters
with st.sidebar.expander("API Configuration", expanded=True):
# API ID dropdown with colored icons
api_options = {
"OrderProcessor": "π",
"AuthService": "π",
"ProductCatalog": "π",
"PaymentGateway": "π³"
}
api_id = st.selectbox(
"API Service",
options=list(api_options.keys()),
format_func=lambda x: f"{api_options[x]} {x}"
)
api_id_mapping = {"OrderProcessor": 2, "AuthService": 0, "ProductCatalog": 1, "PaymentGateway": 3}
api_id_encoded = api_id_mapping[api_id]
# Environment dropdown with descriptions
env_options = {
"production-useast1": "Production (US East)",
"staging": "Staging Environment"
}
env = st.selectbox(
"Environment",
options=list(env_options.keys()),
format_func=lambda x: env_options[x]
)
env_mapping = {"production-useast1": 1, "staging": 0}
env_encoded = env_mapping[env]
# Performance metrics with tooltips and better ranges
with st.sidebar.expander("Performance Metrics", expanded=True):
latency_ms = st.slider(
"Latency (ms)",
min_value=0.0,
max_value=100.0,
value=10.0,
step=0.1,
help="Response time in milliseconds"
)
bytes_transferred = st.slider(
"Bytes Transferred",
min_value=0,
max_value=15000,
value=300,
help="Amount of data transferred in the request/response"
)
hour_slider = st.slider(
"Hour of Day",
min_value=0,
max_value=23,
value=14,
help="The hour when the request is made (0-23)"
)
# Convert hour to more readable format
hour_of_day = hour_slider
hour_display = f"{hour_slider}:00" + (" AM" if hour_slider < 12 else " PM")
st.caption(f"Selected time: {hour_display}")
# Resource usage
with st.sidebar.expander("Resource Usage", expanded=True):
simulated_cpu_cost = st.slider(
"CPU Cost",
min_value=0.0,
max_value=50.0,
value=10.0,
step=0.1,
help="Simulated CPU utilization cost"
)
simulated_memory_mb = st.slider(
"Memory Usage (MB)",
min_value=0.0,
max_value=100.0,
value=25.0,
step=0.1,
help="Simulated memory usage in megabytes"
)
# Add a reset button
if st.sidebar.button("Reset Parameters"):
st.experimental_rerun()
# Prepare input DataFrame
input_df = pd.DataFrame([[
api_id_encoded, env_encoded, latency_ms, bytes_transferred, hour_of_day,
simulated_cpu_cost, simulated_memory_mb
]], columns=[
'api_id', 'env', 'latency_ms', 'bytes_transferred',
'hour_of_day', 'simulated_cpu_cost', 'simulated_memory_mb'
])
# Get prediction
prediction = model.predict(input_df)[0]
probability = model.predict_proba(input_df)[0][1]
# Main content area
st.markdown('<div class="sub-header">π§ Prediction Results</div>', unsafe_allow_html=True)
# Display prediction in two columns
col1, col2 = st.columns(2)
with col1:
# Show prediction with better styling
if prediction == 0:
st.markdown(f"""
<div class="prediction-box-success">
<h2>β
No Error Predicted</h2>
<p>The API call is likely to succeed</p>
<h3>Confidence: {(1 - probability) * 100:.1f}%</h3>
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div class="prediction-box-error">
<h2>π« Error Predicted</h2>
<p>The API call is likely to fail</p>
<h3>Confidence: {probability * 100:.1f}%</h3>
</div>
""", unsafe_allow_html=True)
with col2:
# Create a gauge chart for probability visualization
fig, ax = plt.subplots(figsize=(4, 3))
# Create gauge
gauge_colors = [(0.2, 0.8, 0.2), (0.8, 0.8, 0.2), (0.8, 0.2, 0.2)]
cmap = plt.cm.RdYlGn_r
norm = plt.Normalize(0, 1)
theta = np.linspace(0.75 * np.pi, 0.25 * np.pi, 100)
r = 0.5
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, 'k', linewidth=3)
# Needle
needle_theta = 0.75 * np.pi - probability * 0.5 * np.pi
needle_x = [0, r * 0.8 * np.cos(needle_theta)]
needle_y = [0, r * 0.8 * np.sin(needle_theta)]
ax.plot(needle_x, needle_y, 'r', linewidth=2)
ax.add_patch(plt.Circle((0, 0), radius=0.05, color='darkred'))
# Add labels
ax.text(-0.5, -0.1, "Low", fontsize=9)
ax.text(0, 0.35, "Medium", fontsize=9)
ax.text(0.5, -0.1, "High", fontsize=9)
ax.text(0, -0.3, f"Error Probability: {probability:.2f}", fontsize=10, ha='center', fontweight='bold')
# Format plot
ax.set_aspect('equal')
ax.axis('off')
st.pyplot(fig)
# Display feature importance
st.markdown('<div class="sub-header">π Feature Analysis</div>', unsafe_allow_html=True)
# Create three columns for metrics
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="metric-container">
<h4>API Service</h4>
<p>{} {}</p>
</div>
""".format(api_options[api_id], api_id), unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="metric-container">
<h4>Environment</h4>
<p>{}</p>
</div>
""".format(env_options[env]), unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="metric-container">
<h4>Time of Day</h4>
<p>{}</p>
</div>
""".format(hour_display), unsafe_allow_html=True)
# Performance metrics
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="metric-container">
<h4>Latency</h4>
<p>{} ms</p>
</div>
""".format(latency_ms), unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="metric-container">
<h4>CPU Cost</h4>
<p>{}</p>
</div>
""".format(simulated_cpu_cost), unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="metric-container">
<h4>Memory Usage</h4>
<p>{} MB</p>
</div>
""".format(simulated_memory_mb), unsafe_allow_html=True)
# Input data inspector
with st.expander("π View Raw Input Data"):
# Create a more readable table
display_df = pd.DataFrame({
'Feature': ['API Service', 'Environment', 'Latency (ms)', 'Bytes Transferred',
'Hour of Day', 'CPU Cost', 'Memory (MB)'],
'Value': [api_id, env, latency_ms, bytes_transferred,
hour_of_day, simulated_cpu_cost, simulated_memory_mb],
'Encoded Value': [api_id_encoded, env_encoded, latency_ms, bytes_transferred,
hour_of_day, simulated_cpu_cost, simulated_memory_mb]
})
st.dataframe(display_df, use_container_width=True)
# Help section
with st.expander("β How to Use This Tool"):
st.markdown("""
### Instructions
1. **Adjust Parameters**: Use the sidebar sliders and dropdowns to set your API parameters
2. **View Prediction**: The prediction updates automatically when you change any parameter
3. **Analyze Results**: Look at the gauge chart and feature metrics to understand factors affecting the prediction
### About the Model
This tool uses a machine learning model trained on historical API call data to predict whether a call with the given parameters will result in an error.
""")
# Footer
st.markdown("---")
st.markdown("API Error Prediction Tool | Developed for DevOps Team", unsafe_allow_html=True) |