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("""
""", 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('
⚠️ API Error Prediction System
', unsafe_allow_html=True)
st.markdown("""
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.
""", 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('', 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('', 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"""
✅ No Error Predicted
The API call is likely to succeed
Confidence: {(1 - probability) * 100:.1f}%
""", unsafe_allow_html=True)
else:
st.markdown(f"""
🚫 Error Predicted
The API call is likely to fail
Confidence: {probability * 100:.1f}%
""", 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('', unsafe_allow_html=True)
# Create three columns for metrics
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
""".format(api_options[api_id], api_id), unsafe_allow_html=True)
with col2:
st.markdown("""
""".format(env_options[env]), unsafe_allow_html=True)
with col3:
st.markdown("""
""".format(hour_display), unsafe_allow_html=True)
# Performance metrics
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
""".format(latency_ms), unsafe_allow_html=True)
with col2:
st.markdown("""
""".format(simulated_cpu_cost), unsafe_allow_html=True)
with col3:
st.markdown("""
""".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)