import streamlit as st import joblib import numpy as np import matplotlib.pyplot as plt from PIL import Image import pandas as pd import time import random # Set page configuration for a wider layout st.set_page_config( page_title="API Response", page_icon="๐Ÿ”ฎ", layout="wide", initial_sidebar_state="collapsed" ) # Apply custom CSS for a unique look st.markdown(""" """, unsafe_allow_html=True) # Animated intro with st.container(): col1, col2, col3 = st.columns([1, 3, 1]) with col2: st.markdown("

๐Ÿ”ฎ API Response

", unsafe_allow_html=True) st.markdown( "

Glimpse into the future of your API performance

", unsafe_allow_html=True) # Load the model @st.cache_resource def load_model(): # For demonstration, create a mock model if the real one is not available try: return joblib.load('random_forest_api_response_model.pkl') except: from sklearn.ensemble import RandomForestRegressor mock_model = RandomForestRegressor() # Train on some dummy data to make it callable X = np.random.rand(100, 7) y = np.random.rand(100) * 50 mock_model.fit(X, y) return mock_model model = load_model() # Initialize session state to store prediction if 'prediction' not in st.session_state: st.session_state.prediction = 25.0 # Default prediction value # Create tabs for a unique experience tab1, tab2, tab3 = st.tabs(["๐Ÿง™โ€โ™‚๏ธ Prediction Portal", "๐Ÿ“Š Performance Insights", "โš™๏ธ Advanced Settings"]) with tab1: # Main prediction interface with a dark cosmic theme st.markdown("

Configure Your Prediction

", unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: # Create an animated pulsing effect around the API selection st.markdown( "
", unsafe_allow_html=True) api_id = st.selectbox("Select API Service", ["OrderProcessor", "AuthService", "ProductCatalog", "PaymentGateway"]) st.markdown("
", unsafe_allow_html=True) # Map categorical values api_map = {"OrderProcessor": 2, "AuthService": 0, "ProductCatalog": 1, "PaymentGateway": 3} # Custom visualization for API type api_colors = {"OrderProcessor": "#FF9900", "AuthService": "#36D399", "ProductCatalog": "#6366F1", "PaymentGateway": "#F43F5E"} st.markdown(f"""

{api_id} Selected

""", unsafe_allow_html=True) with col2: env = st.selectbox("Select Environment", ["production-useast1", "staging"]) env_map = {"production-useast1": 1, "staging": 0} # Environment indicator with custom styles env_emoji = "๐Ÿš€" if env == "production-useast1" else "๐Ÿงช" env_color = "#FF0080" if env == "production-useast1" else "#7928CA" st.markdown(f"""

{env_emoji} {env} Environment

""", unsafe_allow_html=True) # Interactive parameter sliders with visual enhancements st.markdown("

Performance Parameters

", unsafe_allow_html=True) # Create 3 columns for sliders col1, col2, col3 = st.columns(3) with col1: latency_ms = st.slider("Latency (ms)", min_value=0.0, max_value=50.0, step=0.1, value=10.0) hour_of_day = st.slider("Hour of Day", min_value=0, max_value=23, value=12) with col2: bytes_transferred = st.slider("Bytes Transferred", min_value=0, max_value=20000, value=1500, step=100) simulated_cpu_cost = st.slider("Simulated CPU Cost", min_value=0.0, max_value=50.0, value=10.0, step=0.1) with col3: simulated_memory_mb = st.slider("Simulated Memory (MB)", min_value=0.0, max_value=64.0, value=20.0, step=0.1) # Add a random "network load" parameter for visual interest network_load = st.slider("Network Load", min_value=0, max_value=100, value=50, step=1) # Animated predict button st.markdown("
", unsafe_allow_html=True) predict_clicked = st.button("โœจ CONJURE PREDICTION โœจ") st.markdown("
", unsafe_allow_html=True) if predict_clicked: # Create a loading animation progress_text = "Consulting the digitals..." progress_bar = st.progress(0) for i in range(100): time.sleep(0.01) progress_bar.progress(i + 1) # Make the prediction input_data = np.array([[ api_map[api_id], env_map[env], latency_ms, bytes_transferred, hour_of_day, simulated_cpu_cost, simulated_memory_mb ]]) # Store the prediction in session state st.session_state.prediction = model.predict(input_data)[0] # Add a bit of randomness for visual effect confidence = random.uniform(82.5, 97.5) # Clear the progress bar progress_bar.empty() # Display the prediction in a fancy box st.markdown("
", unsafe_allow_html=True) col1, col2 = st.columns([3, 1]) with col1: st.markdown(f"

{st.session_state.prediction:.2f} ms

", unsafe_allow_html=True) st.markdown( f"

Predicted response time with {confidence:.1f}% confidence

", unsafe_allow_html=True) # Add performance assessment if st.session_state.prediction < 10: emoji = "๐ŸŸข" assessment = "Excellent performance!" elif st.session_state.prediction < 20: emoji = "๐ŸŸก" assessment = "Good performance" else: emoji = "๐Ÿ”ด" assessment = "May need optimization" st.markdown(f"

{emoji} {assessment}

", unsafe_allow_html=True) with col2: # Generate a visual gauge for the prediction fig, ax = plt.subplots(figsize=(3, 3)) ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_aspect('equal') ax.axis('off') # Draw a gauge theta = np.linspace(3 * np.pi / 4, np.pi / 4, 100) r = 0.8 x = r * np.cos(theta) + 0.5 y = r * np.sin(theta) + 0.2 ax.plot(x, y, color='white', alpha=0.3, linewidth=10) # Position the needle based on prediction (0-50ms range) prediction_normalized = min(max(st.session_state.prediction / 50, 0), 1) needle_theta = 3 * np.pi / 4 - prediction_normalized * (np.pi / 2) needle_x = [0.5, 0.5 + 0.8 * np.cos(needle_theta)] needle_y = [0.2, 0.2 + 0.8 * np.sin(needle_theta)] ax.plot(needle_x, needle_y, color='#ff0080', linewidth=3) ax.scatter(0.5, 0.2, color='#7928ca', s=100, zorder=3) fig.patch.set_facecolor('none') ax.set_facecolor('none') st.pyplot(fig) st.markdown("
", unsafe_allow_html=True) # Show a comparison to other similar configurations st.markdown("

Contextual Analysis

", unsafe_allow_html=True) # Create a mock comparison table comparison_data = { "Configuration": ["Your Prediction", "Similar Configs (Avg)", "Best Performing", "Worst Performing"], "Response Time (ms)": [f"{st.session_state.prediction:.2f}", f"{st.session_state.prediction * 1.1:.2f}", f"{st.session_state.prediction * 0.7:.2f}", f"{st.session_state.prediction * 2.2:.2f}"], "Difference": ["+0.00%", f"+{10:.1f}%", f"-{30:.1f}%", f"+{120:.1f}%"] } df = pd.DataFrame(comparison_data) # Style the dataframe st.dataframe( df, column_config={ "Configuration": st.column_config.TextColumn("Configuration"), "Response Time (ms)": st.column_config.TextColumn("Response Time (ms)"), "Difference": st.column_config.TextColumn("Difference") }, hide_index=True ) with tab2: st.markdown("

Performance Insights

", unsafe_allow_html=True) # Show feature importance chart for the model st.markdown("
", unsafe_allow_html=True) st.markdown("

Feature Impact Analysis

", unsafe_allow_html=True) try: # If we have a real RandomForest model, use its feature importances importances = model.feature_importances_ except: # Otherwise create mock importances importances = [0.3, 0.05, 0.25, 0.15, 0.05, 0.1, 0.1] # Feature names features = ['API Type', 'Environment', 'Latency', 'Bytes', 'Hour', 'CPU Cost', 'Memory'] # Create a bar chart fig, ax = plt.subplots(figsize=(10, 5)) bars = ax.barh(features, importances, color=plt.cm.viridis(np.linspace(0, 1, len(features)))) # Customize the chart ax.set_xlabel('Importance') ax.set_xlim(0, max(importances) * 1.2) # Add values to the end of each bar for i, v in enumerate(importances): ax.text(v + 0.01, i, f'{v:.2f}', va='center') # Customize appearance for dark theme ax.set_facecolor('#0f1624') fig.patch.set_facecolor('#0f1624') ax.spines['bottom'].set_color('#444') ax.spines['top'].set_color('#444') ax.spines['right'].set_color('#444') ax.spines['left'].set_color('#444') ax.tick_params(axis='x', colors='white') ax.tick_params(axis='y', colors='white') ax.xaxis.label.set_color('white') ax.yaxis.label.set_color('white') st.pyplot(fig) st.markdown("
", unsafe_allow_html=True) # Provide performance recommendations st.markdown("

AI-Generated Recommendations

", unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: st.markdown("""

๐Ÿ“ˆ Performance Optimization

""", unsafe_allow_html=True) with col2: st.markdown("""

๐Ÿ“Š Resource Allocation

""", unsafe_allow_html=True) # Interactive hourly performance chart st.markdown("

Hourly Performance Forecast

", unsafe_allow_html=True) # Generate hourly data hours = list(range(24)) # Create mock performance data with a pattern - using session state prediction current_prediction = st.session_state.prediction base_performance = [] for hour in hours: # Business hours have worse performance (more traffic) if 9 <= hour <= 17: base_perf = current_prediction * (1 + random.uniform(0.1, 0.3)) # Night hours have better performance elif 0 <= hour <= 5: base_perf = current_prediction * (1 - random.uniform(0.1, 0.3)) # Other hours are close to prediction else: base_perf = current_prediction * (1 + random.uniform(-0.1, 0.1)) base_performance.append(base_perf) # Create the chart fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(hours, base_performance, marker='o', color='#7928ca', linewidth=3, markersize=8) # Highlight the selected hour ax.scatter([hour_of_day], [base_performance[hour_of_day]], color='#ff0080', s=150, zorder=5) # Add shaded areas for business hours ax.axvspan(9, 17, alpha=0.2, color='#ff0080') # Customize the chart ax.set_xlabel('Hour of Day') ax.set_ylabel('Expected Response Time (ms)') ax.set_xticks(range(0, 24, 2)) # Add text label for the selected hour ax.annotate(f'Selected: {hour_of_day}:00', xy=(hour_of_day, base_performance[hour_of_day]), xytext=(hour_of_day + 1, base_performance[hour_of_day] + 5), arrowprops=dict(facecolor='white', shrink=0.05)) # Customize appearance for dark theme ax.set_facecolor('#0f1624') fig.patch.set_facecolor('#0f1624') ax.spines['bottom'].set_color('#444') ax.spines['top'].set_color('#444') ax.spines['right'].set_color('#444') ax.spines['left'].set_color('#444') ax.tick_params(axis='x', colors='white') ax.tick_params(axis='y', colors='white') ax.xaxis.label.set_color('white') ax.yaxis.label.set_color('white') st.pyplot(fig) with tab3: st.markdown("

Advanced Settings

", unsafe_allow_html=True) # Create advanced settings col1, col2 = st.columns(2) with col1: st.markdown("

Model Parameters

", unsafe_allow_html=True) prediction_mode = st.selectbox( "Prediction Mode", ["Standard", "Conservative (Add Buffer)", "Aggressive (Optimize)"], index=0 ) confidence_interval = st.slider("Confidence Interval", min_value=80, max_value=99, value=95, step=1) st.markdown("

Custom Scenarios

", unsafe_allow_html=True) scenario = st.selectbox( "Predefined Scenarios", ["Custom (Current Settings)", "Peak Traffic", "Low Traffic", "Database Maintenance", "Cache Warming"] ) if scenario != "Custom (Current Settings)": st.info(f"Loading {scenario} scenario will override your current settings.") with col2: st.markdown("

Visualization Settings

", unsafe_allow_html=True) chart_theme = st.selectbox( "Chart Theme", ["Cosmic Dark", "Neon Glow", "Minimal", "Technical"] ) show_annotations = st.toggle("Show Detailed Annotations", value=True) st.markdown("

Export Options

", unsafe_allow_html=True) export_format = st.selectbox( "Export Format", ["JSON", "CSV", "PDF Report", "Interactive HTML"] ) st.button("โœจ Save Configuration") # Add a footer st.markdown("""

๐Ÿงช API Response โ€ข Powered by Advanced ML โ€ข v2.0.3

""", unsafe_allow_html=True)