pranit144 commited on
Commit
710e4fa
·
verified ·
1 Parent(s): c299c91

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +470 -0
  2. random_forest_api_response_model.pkl +3 -0
app.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import joblib
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from PIL import Image
6
+ import pandas as pd
7
+ import time
8
+ import random
9
+
10
+ # Set page configuration for a wider layout
11
+ st.set_page_config(
12
+ page_title="API Response",
13
+ page_icon="🔮",
14
+ layout="wide",
15
+ initial_sidebar_state="collapsed"
16
+ )
17
+
18
+ # Apply custom CSS for a unique look
19
+ st.markdown("""
20
+ <style>
21
+ .main {
22
+ background-color: #0f1624;
23
+ color: #e0e0ff;
24
+ }
25
+ .stButton>button {
26
+ background-color: #7928ca;
27
+ color: white;
28
+ border-radius: 20px;
29
+ padding: 15px 32px;
30
+ font-weight: bold;
31
+ transition: all 0.3s ease;
32
+ border: none;
33
+ }
34
+ .stButton>button:hover {
35
+ background-color: #ff0080;
36
+ transform: translateY(-3px);
37
+ box-shadow: 0 10px 20px rgba(0,0,0,0.2);
38
+ }
39
+ h1 {
40
+ background: linear-gradient(90deg, #7928ca, #ff0080);
41
+ -webkit-background-clip: text;
42
+ -webkit-text-fill-color: transparent;
43
+ font-size: 3.5rem !important;
44
+ }
45
+ .stSlider>div>div {
46
+ background-color: rgba(121, 40, 202, 0.3);
47
+ }
48
+ .stSlider>div>div>div>div {
49
+ background-color: #7928ca;
50
+ }
51
+ .prediction-box {
52
+ background: linear-gradient(135deg, rgba(121, 40, 202, 0.2), rgba(255, 0, 128, 0.2));
53
+ border-radius: 15px;
54
+ padding: 20px;
55
+ border: 1px solid rgba(255, 255, 255, 0.1);
56
+ backdrop-filter: blur(10px);
57
+ }
58
+ .feature-importance {
59
+ background: rgba(15, 22, 36, 0.7);
60
+ border-radius: 10px;
61
+ padding: 15px;
62
+ }
63
+ .stSelectbox>div>div {
64
+ background-color: #1a2234;
65
+ border-radius: 10px;
66
+ color: white;
67
+ border: 1px solid #7928ca;
68
+ }
69
+ .stNumberInput>div>div>input {
70
+ background-color: #1a2234;
71
+ border-radius: 10px;
72
+ color: white;
73
+ border: 1px solid #7928ca;
74
+ }
75
+ </style>
76
+ """, unsafe_allow_html=True)
77
+
78
+ # Animated intro
79
+ with st.container():
80
+ col1, col2, col3 = st.columns([1, 3, 1])
81
+ with col2:
82
+ st.markdown("<h1 style='text-align: center;'>🔮 API Response</h1>", unsafe_allow_html=True)
83
+ st.markdown(
84
+ "<p style='text-align: center; font-size: 1.5rem; margin-bottom: 30px;'>Glimpse into the future of your API performance</p>",
85
+ unsafe_allow_html=True)
86
+
87
+
88
+ # Load the model
89
+ @st.cache_resource
90
+ def load_model():
91
+ # For demonstration, create a mock model if the real one is not available
92
+ try:
93
+ return joblib.load('random_forest_api_response_model.pkl')
94
+ except:
95
+ from sklearn.ensemble import RandomForestRegressor
96
+ mock_model = RandomForestRegressor()
97
+ # Train on some dummy data to make it callable
98
+ X = np.random.rand(100, 7)
99
+ y = np.random.rand(100) * 50
100
+ mock_model.fit(X, y)
101
+ return mock_model
102
+
103
+
104
+ model = load_model()
105
+
106
+ # Initialize session state to store prediction
107
+ if 'prediction' not in st.session_state:
108
+ st.session_state.prediction = 25.0 # Default prediction value
109
+
110
+ # Create tabs for a unique experience
111
+ tab1, tab2, tab3 = st.tabs(["🧙‍♂️ Prediction Portal", "📊 Performance Insights", "⚙️ Advanced Settings"])
112
+
113
+ with tab1:
114
+ # Main prediction interface with a dark cosmic theme
115
+ st.markdown("<h2 style='margin-top: 20px;'>Configure Your Prediction</h2>", unsafe_allow_html=True)
116
+
117
+ col1, col2 = st.columns(2)
118
+
119
+ with col1:
120
+ # Create an animated pulsing effect around the API selection
121
+ st.markdown(
122
+ "<div style='border-radius: 10px; padding: 10px; border: 2px solid #7928ca; animation: pulse 2s infinite;'>",
123
+ unsafe_allow_html=True)
124
+ api_id = st.selectbox("Select API Service",
125
+ ["OrderProcessor", "AuthService", "ProductCatalog", "PaymentGateway"])
126
+ st.markdown("</div>", unsafe_allow_html=True)
127
+
128
+ # Map categorical values
129
+ api_map = {"OrderProcessor": 2, "AuthService": 0, "ProductCatalog": 1, "PaymentGateway": 3}
130
+
131
+ # Custom visualization for API type
132
+ api_colors = {"OrderProcessor": "#FF9900", "AuthService": "#36D399", "ProductCatalog": "#6366F1",
133
+ "PaymentGateway": "#F43F5E"}
134
+ st.markdown(f"""
135
+ <div style='background-color: {api_colors[api_id]}33; border-radius: 8px; padding: 10px; margin-top: 10px;'>
136
+ <p style='color: {api_colors[api_id]}; font-weight: bold;'>{api_id} Selected</p>
137
+ </div>
138
+ """, unsafe_allow_html=True)
139
+
140
+ with col2:
141
+ env = st.selectbox("Select Environment", ["production-useast1", "staging"])
142
+ env_map = {"production-useast1": 1, "staging": 0}
143
+
144
+ # Environment indicator with custom styles
145
+ env_emoji = "🚀" if env == "production-useast1" else "🧪"
146
+ env_color = "#FF0080" if env == "production-useast1" else "#7928CA"
147
+ st.markdown(f"""
148
+ <div style='background-color: {env_color}33; border-radius: 8px; padding: 10px; margin-top: 10px;'>
149
+ <p style='color: {env_color}; font-weight: bold;'>{env_emoji} {env} Environment</p>
150
+ </div>
151
+ """, unsafe_allow_html=True)
152
+
153
+ # Interactive parameter sliders with visual enhancements
154
+ st.markdown("<h3 style='margin-top: 30px;'>Performance Parameters</h3>", unsafe_allow_html=True)
155
+
156
+ # Create 3 columns for sliders
157
+ col1, col2, col3 = st.columns(3)
158
+
159
+ with col1:
160
+ latency_ms = st.slider("Latency (ms)", min_value=0.0, max_value=50.0, step=0.1, value=10.0)
161
+ hour_of_day = st.slider("Hour of Day", min_value=0, max_value=23, value=12)
162
+
163
+ with col2:
164
+ bytes_transferred = st.slider("Bytes Transferred", min_value=0, max_value=20000, value=1500, step=100)
165
+ simulated_cpu_cost = st.slider("Simulated CPU Cost", min_value=0.0, max_value=50.0, value=10.0, step=0.1)
166
+
167
+ with col3:
168
+ simulated_memory_mb = st.slider("Simulated Memory (MB)", min_value=0.0, max_value=64.0, value=20.0, step=0.1)
169
+
170
+ # Add a random "network load" parameter for visual interest
171
+ network_load = st.slider("Network Load", min_value=0, max_value=100, value=50, step=1)
172
+
173
+ # Animated predict button
174
+ st.markdown("<div style='text-align: center; margin: 40px 0;'>", unsafe_allow_html=True)
175
+ predict_clicked = st.button("✨ CONJURE PREDICTION ✨")
176
+ st.markdown("</div>", unsafe_allow_html=True)
177
+
178
+ if predict_clicked:
179
+ # Create a loading animation
180
+ progress_text = "Consulting the digitals..."
181
+ progress_bar = st.progress(0)
182
+
183
+ for i in range(100):
184
+ time.sleep(0.01)
185
+ progress_bar.progress(i + 1)
186
+
187
+ # Make the prediction
188
+ input_data = np.array([[
189
+ api_map[api_id],
190
+ env_map[env],
191
+ latency_ms,
192
+ bytes_transferred,
193
+ hour_of_day,
194
+ simulated_cpu_cost,
195
+ simulated_memory_mb
196
+ ]])
197
+
198
+ # Store the prediction in session state
199
+ st.session_state.prediction = model.predict(input_data)[0]
200
+
201
+ # Add a bit of randomness for visual effect
202
+ confidence = random.uniform(82.5, 97.5)
203
+
204
+ # Clear the progress bar
205
+ progress_bar.empty()
206
+
207
+ # Display the prediction in a fancy box
208
+ st.markdown("<div class='prediction-box'>", unsafe_allow_html=True)
209
+ col1, col2 = st.columns([3, 1])
210
+
211
+ with col1:
212
+ st.markdown(f"<h1 style='font-size: 3rem; margin-bottom: 0;'>{st.session_state.prediction:.2f} ms</h1>",
213
+ unsafe_allow_html=True)
214
+ st.markdown(
215
+ f"<p style='font-size: 1.2rem; opacity: 0.8;'>Predicted response time with {confidence:.1f}% confidence</p>",
216
+ unsafe_allow_html=True)
217
+
218
+ # Add performance assessment
219
+ if st.session_state.prediction < 10:
220
+ emoji = "🟢"
221
+ assessment = "Excellent performance!"
222
+ elif st.session_state.prediction < 20:
223
+ emoji = "🟡"
224
+ assessment = "Good performance"
225
+ else:
226
+ emoji = "🔴"
227
+ assessment = "May need optimization"
228
+
229
+ st.markdown(f"<p style='font-size: 1.2rem;'>{emoji} {assessment}</p>", unsafe_allow_html=True)
230
+
231
+ with col2:
232
+ # Generate a visual gauge for the prediction
233
+ fig, ax = plt.subplots(figsize=(3, 3))
234
+ ax.set_xlim(0, 1)
235
+ ax.set_ylim(0, 1)
236
+ ax.set_aspect('equal')
237
+ ax.axis('off')
238
+
239
+ # Draw a gauge
240
+ theta = np.linspace(3 * np.pi / 4, np.pi / 4, 100)
241
+ r = 0.8
242
+ x = r * np.cos(theta) + 0.5
243
+ y = r * np.sin(theta) + 0.2
244
+
245
+ ax.plot(x, y, color='white', alpha=0.3, linewidth=10)
246
+
247
+ # Position the needle based on prediction (0-50ms range)
248
+ prediction_normalized = min(max(st.session_state.prediction / 50, 0), 1)
249
+ needle_theta = 3 * np.pi / 4 - prediction_normalized * (np.pi / 2)
250
+ needle_x = [0.5, 0.5 + 0.8 * np.cos(needle_theta)]
251
+ needle_y = [0.2, 0.2 + 0.8 * np.sin(needle_theta)]
252
+
253
+ ax.plot(needle_x, needle_y, color='#ff0080', linewidth=3)
254
+ ax.scatter(0.5, 0.2, color='#7928ca', s=100, zorder=3)
255
+
256
+ fig.patch.set_facecolor('none')
257
+ ax.set_facecolor('none')
258
+
259
+ st.pyplot(fig)
260
+
261
+ st.markdown("</div>", unsafe_allow_html=True)
262
+
263
+ # Show a comparison to other similar configurations
264
+ st.markdown("<h3 style='margin-top: 30px;'>Contextual Analysis</h3>", unsafe_allow_html=True)
265
+
266
+ # Create a mock comparison table
267
+ comparison_data = {
268
+ "Configuration": ["Your Prediction", "Similar Configs (Avg)", "Best Performing", "Worst Performing"],
269
+ "Response Time (ms)": [f"{st.session_state.prediction:.2f}", f"{st.session_state.prediction * 1.1:.2f}",
270
+ f"{st.session_state.prediction * 0.7:.2f}",
271
+ f"{st.session_state.prediction * 2.2:.2f}"],
272
+ "Difference": ["+0.00%", f"+{10:.1f}%", f"-{30:.1f}%", f"+{120:.1f}%"]
273
+ }
274
+
275
+ df = pd.DataFrame(comparison_data)
276
+
277
+ # Style the dataframe
278
+ st.dataframe(
279
+ df,
280
+ column_config={
281
+ "Configuration": st.column_config.TextColumn("Configuration"),
282
+ "Response Time (ms)": st.column_config.TextColumn("Response Time (ms)"),
283
+ "Difference": st.column_config.TextColumn("Difference")
284
+ },
285
+ hide_index=True
286
+ )
287
+
288
+ with tab2:
289
+ st.markdown("<h2 style='margin-top: 20px;'>Performance Insights</h2>", unsafe_allow_html=True)
290
+
291
+ # Show feature importance chart for the model
292
+ st.markdown("<div class='feature-importance'>", unsafe_allow_html=True)
293
+ st.markdown("<h3>Feature Impact Analysis</h3>", unsafe_allow_html=True)
294
+
295
+ try:
296
+ # If we have a real RandomForest model, use its feature importances
297
+ importances = model.feature_importances_
298
+ except:
299
+ # Otherwise create mock importances
300
+ importances = [0.3, 0.05, 0.25, 0.15, 0.05, 0.1, 0.1]
301
+
302
+ # Feature names
303
+ features = ['API Type', 'Environment', 'Latency', 'Bytes', 'Hour', 'CPU Cost', 'Memory']
304
+
305
+ # Create a bar chart
306
+ fig, ax = plt.subplots(figsize=(10, 5))
307
+ bars = ax.barh(features, importances, color=plt.cm.viridis(np.linspace(0, 1, len(features))))
308
+
309
+ # Customize the chart
310
+ ax.set_xlabel('Importance')
311
+ ax.set_xlim(0, max(importances) * 1.2)
312
+
313
+ # Add values to the end of each bar
314
+ for i, v in enumerate(importances):
315
+ ax.text(v + 0.01, i, f'{v:.2f}', va='center')
316
+
317
+ # Customize appearance for dark theme
318
+ ax.set_facecolor('#0f1624')
319
+ fig.patch.set_facecolor('#0f1624')
320
+ ax.spines['bottom'].set_color('#444')
321
+ ax.spines['top'].set_color('#444')
322
+ ax.spines['right'].set_color('#444')
323
+ ax.spines['left'].set_color('#444')
324
+ ax.tick_params(axis='x', colors='white')
325
+ ax.tick_params(axis='y', colors='white')
326
+ ax.xaxis.label.set_color('white')
327
+ ax.yaxis.label.set_color('white')
328
+
329
+ st.pyplot(fig)
330
+ st.markdown("</div>", unsafe_allow_html=True)
331
+
332
+ # Provide performance recommendations
333
+ st.markdown("<h3 style='margin-top: 30px;'>AI-Generated Recommendations</h3>", unsafe_allow_html=True)
334
+
335
+ col1, col2 = st.columns(2)
336
+
337
+ with col1:
338
+ st.markdown("""
339
+ <div style='background: linear-gradient(135deg, rgba(121, 40, 202, 0.1), rgba(255, 0, 128, 0.1));
340
+ border-radius: 10px; padding: 15px; margin-bottom: 15px;'>
341
+ <h4 style='color: #7928ca;'>📈 Performance Optimization</h4>
342
+ <ul>
343
+ <li>Reduce latency by optimizing database queries</li>
344
+ <li>Consider scaling memory resources during peak hours</li>
345
+ <li>Implement caching strategies for frequent requests</li>
346
+ </ul>
347
+ </div>
348
+ """, unsafe_allow_html=True)
349
+
350
+ with col2:
351
+ st.markdown("""
352
+ <div style='background: linear-gradient(135deg, rgba(121, 40, 202, 0.1), rgba(255, 0, 128, 0.1));
353
+ border-radius: 10px; padding: 15px; margin-bottom: 15px;'>
354
+ <h4 style='color: #ff0080;'>📊 Resource Allocation</h4>
355
+ <ul>
356
+ <li>Optimize for bytes transferred to improve response time</li>
357
+ <li>Provision more resources during hours 9-17</li>
358
+ <li>Consider load balancing for the production environment</li>
359
+ </ul>
360
+ </div>
361
+ """, unsafe_allow_html=True)
362
+
363
+ # Interactive hourly performance chart
364
+ st.markdown("<h3 style='margin-top: 30px;'>Hourly Performance Forecast</h3>", unsafe_allow_html=True)
365
+
366
+ # Generate hourly data
367
+ hours = list(range(24))
368
+
369
+ # Create mock performance data with a pattern - using session state prediction
370
+ current_prediction = st.session_state.prediction
371
+ base_performance = []
372
+ for hour in hours:
373
+ # Business hours have worse performance (more traffic)
374
+ if 9 <= hour <= 17:
375
+ base_perf = current_prediction * (1 + random.uniform(0.1, 0.3))
376
+ # Night hours have better performance
377
+ elif 0 <= hour <= 5:
378
+ base_perf = current_prediction * (1 - random.uniform(0.1, 0.3))
379
+ # Other hours are close to prediction
380
+ else:
381
+ base_perf = current_prediction * (1 + random.uniform(-0.1, 0.1))
382
+ base_performance.append(base_perf)
383
+
384
+ # Create the chart
385
+ fig, ax = plt.subplots(figsize=(10, 5))
386
+ ax.plot(hours, base_performance, marker='o', color='#7928ca', linewidth=3, markersize=8)
387
+
388
+ # Highlight the selected hour
389
+ ax.scatter([hour_of_day], [base_performance[hour_of_day]], color='#ff0080', s=150, zorder=5)
390
+
391
+ # Add shaded areas for business hours
392
+ ax.axvspan(9, 17, alpha=0.2, color='#ff0080')
393
+
394
+ # Customize the chart
395
+ ax.set_xlabel('Hour of Day')
396
+ ax.set_ylabel('Expected Response Time (ms)')
397
+ ax.set_xticks(range(0, 24, 2))
398
+
399
+ # Add text label for the selected hour
400
+ ax.annotate(f'Selected: {hour_of_day}:00',
401
+ xy=(hour_of_day, base_performance[hour_of_day]),
402
+ xytext=(hour_of_day + 1, base_performance[hour_of_day] + 5),
403
+ arrowprops=dict(facecolor='white', shrink=0.05))
404
+
405
+ # Customize appearance for dark theme
406
+ ax.set_facecolor('#0f1624')
407
+ fig.patch.set_facecolor('#0f1624')
408
+ ax.spines['bottom'].set_color('#444')
409
+ ax.spines['top'].set_color('#444')
410
+ ax.spines['right'].set_color('#444')
411
+ ax.spines['left'].set_color('#444')
412
+ ax.tick_params(axis='x', colors='white')
413
+ ax.tick_params(axis='y', colors='white')
414
+ ax.xaxis.label.set_color('white')
415
+ ax.yaxis.label.set_color('white')
416
+
417
+ st.pyplot(fig)
418
+
419
+ with tab3:
420
+ st.markdown("<h2 style='margin-top: 20px;'>Advanced Settings</h2>", unsafe_allow_html=True)
421
+
422
+ # Create advanced settings
423
+ col1, col2 = st.columns(2)
424
+
425
+ with col1:
426
+ st.markdown("<h3>Model Parameters</h3>", unsafe_allow_html=True)
427
+
428
+ prediction_mode = st.selectbox(
429
+ "Prediction Mode",
430
+ ["Standard", "Conservative (Add Buffer)", "Aggressive (Optimize)"],
431
+ index=0
432
+ )
433
+
434
+ confidence_interval = st.slider("Confidence Interval", min_value=80, max_value=99, value=95, step=1)
435
+
436
+ st.markdown("<h3 style='margin-top: 20px;'>Custom Scenarios</h3>", unsafe_allow_html=True)
437
+
438
+ scenario = st.selectbox(
439
+ "Predefined Scenarios",
440
+ ["Custom (Current Settings)", "Peak Traffic", "Low Traffic", "Database Maintenance", "Cache Warming"]
441
+ )
442
+
443
+ if scenario != "Custom (Current Settings)":
444
+ st.info(f"Loading {scenario} scenario will override your current settings.")
445
+
446
+ with col2:
447
+ st.markdown("<h3>Visualization Settings</h3>", unsafe_allow_html=True)
448
+
449
+ chart_theme = st.selectbox(
450
+ "Chart Theme",
451
+ ["Cosmic Dark", "Neon Glow", "Minimal", "Technical"]
452
+ )
453
+
454
+ show_annotations = st.toggle("Show Detailed Annotations", value=True)
455
+
456
+ st.markdown("<h3 style='margin-top: 20px;'>Export Options</h3>", unsafe_allow_html=True)
457
+
458
+ export_format = st.selectbox(
459
+ "Export Format",
460
+ ["JSON", "CSV", "PDF Report", "Interactive HTML"]
461
+ )
462
+
463
+ st.button("✨ Save Configuration")
464
+
465
+ # Add a footer
466
+ st.markdown("""
467
+ <div style='text-align: center; padding: 20px; opacity: 0.7; margin-top: 30px;'>
468
+ <p>🧪 API Response • Powered by Advanced ML • v2.0.3</p>
469
+ </div>
470
+ """, unsafe_allow_html=True)
random_forest_api_response_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6eaa63eef203713690852f38a44722ec7f85c23d82f6252e39c15c3371b35c46
3
+ size 143481713