Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,145 +2,84 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
|
|
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
from sklearn.ensemble import RandomForestClassifier
|
| 7 |
from sklearn.preprocessing import LabelEncoder
|
| 8 |
-
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
| 9 |
|
| 10 |
# =============================================================================
|
| 11 |
-
# 1.
|
| 12 |
# =============================================================================
|
| 13 |
|
| 14 |
-
|
| 15 |
-
/*
|
| 16 |
body, .gradio-container {
|
| 17 |
-
background:
|
| 18 |
-
color: #
|
| 19 |
-
font-family: '
|
| 20 |
-
}
|
| 21 |
-
|
| 22 |
-
/* Glassmorphism Navigation Bar */
|
| 23 |
-
.navbar-header {
|
| 24 |
-
display: flex;
|
| 25 |
-
justify-content: space-between;
|
| 26 |
-
align-items: center;
|
| 27 |
-
padding: 18px 28px;
|
| 28 |
-
background: rgba(15, 23, 42, 0.6);
|
| 29 |
-
backdrop-filter: blur(16px);
|
| 30 |
-
-webkit-backdrop-filter: blur(16px);
|
| 31 |
-
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 32 |
-
border-radius: 16px;
|
| 33 |
-
margin-bottom: 24px;
|
| 34 |
-
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
/* KPI Metric Cards with Subtle Glow */
|
| 38 |
-
.kpi-grid {
|
| 39 |
-
display: grid;
|
| 40 |
-
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
|
| 41 |
-
gap: 16px;
|
| 42 |
-
margin-bottom: 24px;
|
| 43 |
}
|
| 44 |
|
| 45 |
.kpi-card {
|
| 46 |
-
background: rgba(15, 23, 42, 0.
|
| 47 |
-
|
| 48 |
-
border:
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
.kpi-card:hover {
|
| 55 |
-
border-color: rgba(99, 102, 241, 0.5);
|
| 56 |
-
transform: translateY(-3px);
|
| 57 |
-
box-shadow: 0 12px 24px rgba(99, 102, 241, 0.15);
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
.kpi-value {
|
| 61 |
-
font-size: 2.1rem;
|
| 62 |
-
font-weight: 800;
|
| 63 |
-
letter-spacing: -0.03em;
|
| 64 |
-
background: linear-gradient(135deg, #a855f7 0%, #6366f1 50%, #38bdf8 100%);
|
| 65 |
-
-webkit-background-clip: text;
|
| 66 |
-
-webkit-text-fill-color: transparent;
|
| 67 |
-
margin-bottom: 2px;
|
| 68 |
}
|
| 69 |
|
| 70 |
.kpi-title {
|
| 71 |
-
font-size: 0.
|
| 72 |
color: #94a3b8;
|
| 73 |
text-transform: uppercase;
|
| 74 |
-
letter-spacing: 0.
|
| 75 |
-
font-weight:
|
| 76 |
}
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
.gr-tab-nav {
|
| 85 |
-
background: rgba(15, 23, 42, 0.5) !important;
|
| 86 |
-
border-radius: 12px !important;
|
| 87 |
-
padding: 4px !important;
|
| 88 |
-
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
| 89 |
}
|
| 90 |
|
| 91 |
-
.
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
border: none !important;
|
| 97 |
-
padding: 8px 16px !important;
|
| 98 |
-
transition: all 0.2s ease !important;
|
| 99 |
}
|
| 100 |
|
| 101 |
-
.
|
| 102 |
background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%) !important;
|
| 103 |
-
color: #ffffff !important;
|
| 104 |
-
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3) !important;
|
| 105 |
-
}
|
| 106 |
-
|
| 107 |
-
/* Sleek Primary Glowing CTA Button */
|
| 108 |
-
.glow-btn {
|
| 109 |
-
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #d946ef 100%) !important;
|
| 110 |
border: none !important;
|
| 111 |
-
color:
|
| 112 |
-
border-radius:
|
| 113 |
-
font-weight:
|
| 114 |
-
|
| 115 |
-
padding: 16px 28px !important;
|
| 116 |
-
box-shadow: 0 6px 24px rgba(139, 92, 246, 0.4) !important;
|
| 117 |
-
transition: all 0.25s ease !important;
|
| 118 |
-
width: 100% !important;
|
| 119 |
-
margin-top: 16px !important;
|
| 120 |
}
|
| 121 |
|
| 122 |
-
.
|
| 123 |
-
transform: translateY(-2px)
|
| 124 |
-
box-shadow: 0
|
| 125 |
}
|
| 126 |
|
| 127 |
-
/*
|
| 128 |
-
.gr-
|
| 129 |
-
background: rgba(15, 23, 42, 0.5) !important;
|
| 130 |
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
| 131 |
-
border-radius:
|
|
|
|
| 132 |
}
|
| 133 |
|
| 134 |
-
.
|
| 135 |
-
|
| 136 |
-
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 137 |
-
color: #ffffff !important;
|
| 138 |
-
border-radius: 8px !important;
|
| 139 |
}
|
| 140 |
"""
|
| 141 |
|
| 142 |
# =============================================================================
|
| 143 |
-
# 2.
|
| 144 |
# =============================================================================
|
| 145 |
|
| 146 |
FEATURE_COLUMNS = [
|
|
@@ -154,47 +93,61 @@ FEATURE_COLUMNS = [
|
|
| 154 |
|
| 155 |
CATEGORICAL_COLS = ['Gender', 'Customer Type', 'Type of Travel', 'Class']
|
| 156 |
|
| 157 |
-
class
|
| 158 |
def __init__(self):
|
| 159 |
self.model = None
|
| 160 |
self.label_encoders = {}
|
| 161 |
self.target_encoder = LabelEncoder()
|
| 162 |
self.metrics = {}
|
| 163 |
-
self.
|
|
|
|
| 164 |
|
| 165 |
-
def
|
| 166 |
np.random.seed(42)
|
| 167 |
genders = np.random.choice(['Male', 'Female'], n)
|
| 168 |
cust_types = np.random.choice(['Loyal Customer', 'disloyal Customer'], n, p=[0.8, 0.2])
|
| 169 |
-
ages = np.random.randint(
|
| 170 |
travel_types = np.random.choice(['Business travel', 'Personal Travel'], n, p=[0.7, 0.3])
|
| 171 |
classes = np.random.choice(['Business', 'Eco', 'Eco Plus'], n, p=[0.5, 0.4, 0.1])
|
| 172 |
-
distances = np.random.randint(
|
| 173 |
|
| 174 |
ratings = {col: np.random.randint(1, 6, n) for col in FEATURE_COLUMNS[6:20]}
|
| 175 |
-
dep_delays = np.random.exponential(
|
| 176 |
-
arr_delays = np.maximum(0, dep_delays + np.random.randint(-
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
-
|
|
|
|
| 182 |
|
| 183 |
-
|
| 184 |
'Gender': genders, 'Customer Type': cust_types, 'Age': ages,
|
| 185 |
'Type of Travel': travel_types, 'Class': classes, 'Flight Distance': distances,
|
| 186 |
**ratings, 'Departure Delay in Minutes': dep_delays,
|
| 187 |
'Arrival Delay in Minutes': arr_delays, 'satisfaction': satisfaction
|
| 188 |
-
}
|
|
|
|
| 189 |
|
| 190 |
-
def
|
| 191 |
train_path = next((f for f in ["train (1).csv", "train.csv", "test (1).csv"] if os.path.exists(f)), None)
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
if 'Arrival Delay in Minutes' in df.columns:
|
| 195 |
df['Arrival Delay in Minutes'] = df['Arrival Delay in Minutes'].fillna(df['Arrival Delay in Minutes'].median())
|
| 196 |
|
| 197 |
df_encoded = df.copy()
|
|
|
|
| 198 |
for col in CATEGORICAL_COLS:
|
| 199 |
if col in df_encoded.columns:
|
| 200 |
le = LabelEncoder()
|
|
@@ -204,84 +157,89 @@ class EnterpriseSentimentEngine:
|
|
| 204 |
X = df_encoded[FEATURE_COLUMNS]
|
| 205 |
y_encoded = self.target_encoder.fit_transform(df_encoded['satisfaction'])
|
| 206 |
|
| 207 |
-
self.model = RandomForestClassifier(n_estimators=
|
| 208 |
self.model.fit(X, y_encoded)
|
| 209 |
|
| 210 |
preds = self.model.predict(X)
|
| 211 |
self.metrics = {
|
| 212 |
'accuracy': accuracy_score(y_encoded, preds),
|
|
|
|
|
|
|
| 213 |
'f1': f1_score(y_encoded, preds, average='weighted', zero_division=0),
|
| 214 |
-
'
|
| 215 |
}
|
| 216 |
|
| 217 |
-
engine =
|
| 218 |
|
| 219 |
# =============================================================================
|
| 220 |
-
# 3.
|
| 221 |
# =============================================================================
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
'
|
| 231 |
-
'
|
| 232 |
-
'
|
| 233 |
-
|
| 234 |
-
{'range': [0,
|
| 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 |
-
# 4.
|
| 265 |
# =============================================================================
|
| 266 |
|
| 267 |
-
|
| 268 |
-
"Select Switching Profile...": None,
|
| 269 |
-
"High-Value Business Traveler (Satisfied)": ("Female", "Loyal Customer", 42, "Business travel", "Business", 2800, 5, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 4, 5, 5, 0, 0),
|
| 270 |
-
"Low-Cost Economy Traveler (Dissatisfied)": ("Male", "disloyal Customer", 24, "Personal Travel", "Eco", 400, 1, 2, 1, 3, 1, 1, 1, 2, 2, 1, 2, 2, 2, 1, 45, 50)
|
| 271 |
-
}
|
| 272 |
-
|
| 273 |
-
def load_preset_values(preset_name):
|
| 274 |
-
if preset_name in PRESET_PROFILES and PRESET_PROFILES[preset_name] is not None:
|
| 275 |
-
return PRESET_PROFILES[preset_name]
|
| 276 |
-
return gr.skip()
|
| 277 |
-
|
| 278 |
-
def execute_routing_analysis(
|
| 279 |
gender, cust_type, age, travel_type, flight_class, distance,
|
| 280 |
wifi, time_conv, ease_booking, gate_loc, food, online_board,
|
| 281 |
seat_comfort, entertainment, onboard_service, leg_room,
|
| 282 |
baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
|
| 283 |
):
|
| 284 |
-
|
| 285 |
'Gender': gender, 'Customer Type': cust_type, 'Age': age,
|
| 286 |
'Type of Travel': travel_type, 'Class': flight_class, 'Flight Distance': distance,
|
| 287 |
'Inflight wifi service': wifi, 'Departure/Arrival time convenient': time_conv,
|
|
@@ -294,159 +252,137 @@ def execute_routing_analysis(
|
|
| 294 |
'Departure Delay in Minutes': dep_delay, 'Arrival Delay in Minutes': arr_delay
|
| 295 |
}
|
| 296 |
|
| 297 |
-
|
| 298 |
|
| 299 |
for col in CATEGORICAL_COLS:
|
| 300 |
-
val = str(
|
| 301 |
le = engine.label_encoders[col]
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
|
|
|
| 305 |
classes = engine.target_encoder.classes_
|
| 306 |
-
sat_idx = np.where(classes == 'satisfied')[0][0] if 'satisfied' in classes else 0
|
| 307 |
-
sat_score = probs[sat_idx] * 100
|
| 308 |
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
-
|
| 315 |
-
<div style="background:
|
| 316 |
-
<span style="
|
| 317 |
-
<h2 style="color:
|
| 318 |
-
<
|
| 319 |
</div>
|
| 320 |
"""
|
| 321 |
|
| 322 |
-
|
| 323 |
-
|
|
|
|
| 324 |
|
| 325 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
|
| 327 |
# =============================================================================
|
| 328 |
-
# 5.
|
| 329 |
# =============================================================================
|
| 330 |
|
| 331 |
-
with gr.Blocks(css=
|
| 332 |
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
<
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
)
|
| 345 |
-
|
| 346 |
-
# Executive KPI Cards
|
| 347 |
-
gr.HTML(
|
| 348 |
-
f"""
|
| 349 |
-
<div class="kpi-grid">
|
| 350 |
-
<div class="kpi-card">
|
| 351 |
-
<div class="kpi-value">{engine.metrics['accuracy']*100:.2f}%</div>
|
| 352 |
-
<div class="kpi-title">Model Accuracy Score</div>
|
| 353 |
-
</div>
|
| 354 |
-
<div class="kpi-card">
|
| 355 |
-
<div class="kpi-value">0.97</div>
|
| 356 |
-
<div class="kpi-title">F1-Score Reliability</div>
|
| 357 |
-
</div>
|
| 358 |
-
<div class="kpi-card">
|
| 359 |
-
<div class="kpi-value"><8ms</div>
|
| 360 |
-
<div class="kpi-title">Switchboard Latency</div>
|
| 361 |
-
</div>
|
| 362 |
-
<div class="kpi-card">
|
| 363 |
-
<div class="kpi-value">22</div>
|
| 364 |
-
<div class="kpi-title">Active Telemetry Channels</div>
|
| 365 |
</div>
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
)
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
|
| 380 |
-
with gr.
|
| 381 |
-
with gr.
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
with gr.
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
wifi, time_conv, ease_booking, gate_loc, food, online_board,
|
| 437 |
-
seat_comfort, entertainment, onboard_service, leg_room,
|
| 438 |
-
baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
|
| 439 |
-
]
|
| 440 |
-
|
| 441 |
-
# Pre-fill input tabs smoothly upon preset dropdown selection
|
| 442 |
-
preset_selector.change(fn=load_preset_values, inputs=[preset_selector], outputs=all_inputs)
|
| 443 |
-
|
| 444 |
-
# Execute prediction routing
|
| 445 |
-
run_btn.click(
|
| 446 |
-
fn=execute_routing_analysis,
|
| 447 |
-
inputs=all_inputs,
|
| 448 |
-
outputs=[output_card, gauge_plot, radar_plot]
|
| 449 |
-
)
|
| 450 |
|
| 451 |
if __name__ == "__main__":
|
| 452 |
demo.launch()
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
+
import plotly.express as px
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
from sklearn.ensemble import RandomForestClassifier
|
| 8 |
from sklearn.preprocessing import LabelEncoder
|
| 9 |
+
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
|
| 10 |
|
| 11 |
# =============================================================================
|
| 12 |
+
# 1. THEME & CUSTOM CSS ENGINE
|
| 13 |
# =============================================================================
|
| 14 |
|
| 15 |
+
CUSTOM_CSS = """
|
| 16 |
+
/* Sleek Glassmorphic Dark Styling */
|
| 17 |
body, .gradio-container {
|
| 18 |
+
background-color: #0f172a !important;
|
| 19 |
+
color: #e2e8f0 !important;
|
| 20 |
+
font-family: 'Inter', system-ui, -apple-system, sans-serif !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
}
|
| 22 |
|
| 23 |
.kpi-card {
|
| 24 |
+
background: linear-gradient(135deg, rgba(30, 41, 59, 0.7), rgba(15, 23, 42, 0.8));
|
| 25 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 26 |
+
border-radius: 12px;
|
| 27 |
+
padding: 18px;
|
| 28 |
+
text-align: center;
|
| 29 |
+
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
|
| 30 |
+
backdrop-filter: blur(8px);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
}
|
| 32 |
|
| 33 |
.kpi-title {
|
| 34 |
+
font-size: 0.85rem;
|
| 35 |
color: #94a3b8;
|
| 36 |
text-transform: uppercase;
|
| 37 |
+
letter-spacing: 0.05em;
|
| 38 |
+
font-weight: 600;
|
| 39 |
}
|
| 40 |
|
| 41 |
+
.kpi-value {
|
| 42 |
+
font-size: 1.8rem;
|
| 43 |
+
font-weight: 700;
|
| 44 |
+
color: #38bdf8;
|
| 45 |
+
margin-top: 4px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
}
|
| 47 |
|
| 48 |
+
.accent-header {
|
| 49 |
+
background: linear-gradient(90deg, #38bdf8, #818cf8);
|
| 50 |
+
-webkit-background-clip: text;
|
| 51 |
+
-webkit-text-fill-color: transparent;
|
| 52 |
+
font-weight: 800;
|
|
|
|
|
|
|
|
|
|
| 53 |
}
|
| 54 |
|
| 55 |
+
.custom-btn-primary {
|
| 56 |
background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%) !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
border: none !important;
|
| 58 |
+
color: white !important;
|
| 59 |
+
border-radius: 8px !important;
|
| 60 |
+
font-weight: 600 !important;
|
| 61 |
+
transition: all 0.3s ease !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
}
|
| 63 |
|
| 64 |
+
.custom-btn-primary:hover {
|
| 65 |
+
transform: translateY(-2px);
|
| 66 |
+
box-shadow: 0 4px 20px rgba(99, 102, 241, 0.4) !important;
|
| 67 |
}
|
| 68 |
|
| 69 |
+
/* Accordion Customization */
|
| 70 |
+
.gr-accordion {
|
|
|
|
| 71 |
border: 1px solid rgba(255, 255, 255, 0.08) !important;
|
| 72 |
+
border-radius: 10px !important;
|
| 73 |
+
background: rgba(30, 41, 59, 0.4) !important;
|
| 74 |
}
|
| 75 |
|
| 76 |
+
span.svelte-1gfkn6j {
|
| 77 |
+
color: #94a3b8 !important;
|
|
|
|
|
|
|
|
|
|
| 78 |
}
|
| 79 |
"""
|
| 80 |
|
| 81 |
# =============================================================================
|
| 82 |
+
# 2. DATA & MODEL PIPELINE (MODULAR)
|
| 83 |
# =============================================================================
|
| 84 |
|
| 85 |
FEATURE_COLUMNS = [
|
|
|
|
| 93 |
|
| 94 |
CATEGORICAL_COLS = ['Gender', 'Customer Type', 'Type of Travel', 'Class']
|
| 95 |
|
| 96 |
+
class AirlineSatisfactionEngine:
|
| 97 |
def __init__(self):
|
| 98 |
self.model = None
|
| 99 |
self.label_encoders = {}
|
| 100 |
self.target_encoder = LabelEncoder()
|
| 101 |
self.metrics = {}
|
| 102 |
+
self.df_sample = None
|
| 103 |
+
self.initialize_and_train()
|
| 104 |
|
| 105 |
+
def generate_synthetic_data(self, n=3000):
|
| 106 |
np.random.seed(42)
|
| 107 |
genders = np.random.choice(['Male', 'Female'], n)
|
| 108 |
cust_types = np.random.choice(['Loyal Customer', 'disloyal Customer'], n, p=[0.8, 0.2])
|
| 109 |
+
ages = np.random.randint(15, 80, n)
|
| 110 |
travel_types = np.random.choice(['Business travel', 'Personal Travel'], n, p=[0.7, 0.3])
|
| 111 |
classes = np.random.choice(['Business', 'Eco', 'Eco Plus'], n, p=[0.5, 0.4, 0.1])
|
| 112 |
+
distances = np.random.randint(100, 4500, n)
|
| 113 |
|
| 114 |
ratings = {col: np.random.randint(1, 6, n) for col in FEATURE_COLUMNS[6:20]}
|
| 115 |
+
dep_delays = np.random.exponential(12, n).astype(int)
|
| 116 |
+
arr_delays = np.maximum(0, dep_delays + np.random.randint(-5, 10, n))
|
| 117 |
|
| 118 |
+
# FIXED LOGIC: Higher threshold to ensure the dataset isn't biased towards "Satisfied"
|
| 119 |
+
score = (ratings['Inflight wifi service']*1.6 +
|
| 120 |
+
ratings['Online boarding']*1.5 +
|
| 121 |
+
ratings['Inflight entertainment']*1.3 +
|
| 122 |
+
ratings['Seat comfort']*1.1 -
|
| 123 |
+
(dep_delays / 18))
|
| 124 |
|
| 125 |
+
# Increased from 12.5 to 16.5 for a proper 50/50 class balance distribution
|
| 126 |
+
satisfaction = ['satisfied' if s > 16.5 else 'neutral or dissatisfied' for s in score]
|
| 127 |
|
| 128 |
+
data = {
|
| 129 |
'Gender': genders, 'Customer Type': cust_types, 'Age': ages,
|
| 130 |
'Type of Travel': travel_types, 'Class': classes, 'Flight Distance': distances,
|
| 131 |
**ratings, 'Departure Delay in Minutes': dep_delays,
|
| 132 |
'Arrival Delay in Minutes': arr_delays, 'satisfaction': satisfaction
|
| 133 |
+
}
|
| 134 |
+
return pd.DataFrame(data)
|
| 135 |
|
| 136 |
+
def initialize_and_train(self):
|
| 137 |
train_path = next((f for f in ["train (1).csv", "train.csv", "test (1).csv"] if os.path.exists(f)), None)
|
| 138 |
+
|
| 139 |
+
if train_path:
|
| 140 |
+
df = pd.read_csv(train_path)
|
| 141 |
+
else:
|
| 142 |
+
df = self.generate_synthetic_data()
|
| 143 |
+
|
| 144 |
+
self.df_sample = df.copy()
|
| 145 |
|
| 146 |
if 'Arrival Delay in Minutes' in df.columns:
|
| 147 |
df['Arrival Delay in Minutes'] = df['Arrival Delay in Minutes'].fillna(df['Arrival Delay in Minutes'].median())
|
| 148 |
|
| 149 |
df_encoded = df.copy()
|
| 150 |
+
|
| 151 |
for col in CATEGORICAL_COLS:
|
| 152 |
if col in df_encoded.columns:
|
| 153 |
le = LabelEncoder()
|
|
|
|
| 157 |
X = df_encoded[FEATURE_COLUMNS]
|
| 158 |
y_encoded = self.target_encoder.fit_transform(df_encoded['satisfaction'])
|
| 159 |
|
| 160 |
+
self.model = RandomForestClassifier(n_estimators=120, max_depth=16, random_state=42, n_jobs=-1)
|
| 161 |
self.model.fit(X, y_encoded)
|
| 162 |
|
| 163 |
preds = self.model.predict(X)
|
| 164 |
self.metrics = {
|
| 165 |
'accuracy': accuracy_score(y_encoded, preds),
|
| 166 |
+
'precision': precision_score(y_encoded, preds, average='weighted', zero_division=0),
|
| 167 |
+
'recall': recall_score(y_encoded, preds, average='weighted', zero_division=0),
|
| 168 |
'f1': f1_score(y_encoded, preds, average='weighted', zero_division=0),
|
| 169 |
+
'cm': confusion_matrix(y_encoded, preds)
|
| 170 |
}
|
| 171 |
|
| 172 |
+
engine = AirlineSatisfactionEngine()
|
| 173 |
|
| 174 |
# =============================================================================
|
| 175 |
+
# 3. VISUALIZATION ENGINE (PLOTLY)
|
| 176 |
# =============================================================================
|
| 177 |
|
| 178 |
+
class DashboardVisualizer:
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def create_gauge(probability):
|
| 182 |
+
fig = go.Figure(go.Indicator(
|
| 183 |
+
mode="gauge+number",
|
| 184 |
+
value=probability,
|
| 185 |
+
domain={'x': [0, 1], 'y': [0, 1]},
|
| 186 |
+
title={'text': "Satisfaction Confidence", 'font': {'size': 18, 'color': "#94a3b8"}},
|
| 187 |
+
number={'suffix': "%", 'font': {'size': 32, 'color': "#38bdf8"}},
|
| 188 |
+
gauge={
|
| 189 |
+
'axis': {'range': [0, 100], 'tickwidth': 1, 'tickcolor': "#475569"},
|
| 190 |
+
'bar': {'color': "#6366f1"},
|
| 191 |
+
'bgcolor': "rgba(30, 41, 59, 0.5)",
|
| 192 |
+
'bordercolor': "rgba(255, 255, 255, 0.1)",
|
| 193 |
+
'steps': [
|
| 194 |
+
{'range': [0, 50], 'color': 'rgba(239, 68, 68, 0.25)'},
|
| 195 |
+
{'range': [50, 100], 'color': 'rgba(16, 185, 129, 0.25)'}
|
| 196 |
+
],
|
| 197 |
+
'threshold': {
|
| 198 |
+
'line': {'color': "#38bdf8", 'width': 3},
|
| 199 |
+
'thickness': 0.8,
|
| 200 |
+
'value': probability
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
))
|
| 204 |
+
fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', height=250, margin=dict(l=20, r=20, t=40, b=20))
|
| 205 |
+
return fig
|
| 206 |
+
|
| 207 |
+
@staticmethod
|
| 208 |
+
def create_radar(ratings_dict):
|
| 209 |
+
categories = list(ratings_dict.keys())
|
| 210 |
+
values = list(ratings_dict.values())
|
| 211 |
+
|
| 212 |
+
fig = go.Figure(data=go.Scatterpolar(
|
| 213 |
+
r=values + [values[0]],
|
| 214 |
+
theta=categories + [categories[0]],
|
| 215 |
+
fill='toself',
|
| 216 |
+
fillcolor='rgba(56, 189, 248, 0.25)',
|
| 217 |
+
line=dict(color='#38bdf8', width=2)
|
| 218 |
+
))
|
| 219 |
+
|
| 220 |
+
fig.update_layout(
|
| 221 |
+
polar=dict(
|
| 222 |
+
bgcolor='rgba(30, 41, 59, 0.5)',
|
| 223 |
+
radialaxis=dict(visible=True, range=[0, 5], color="#94a3b8", gridcolor="rgba(255,255,255,0.1)"),
|
| 224 |
+
angularaxis=dict(color="#e2e8f0", gridcolor="rgba(255,255,255,0.1)")
|
| 225 |
+
),
|
| 226 |
+
paper_bgcolor='rgba(0,0,0,0)',
|
| 227 |
+
plot_bgcolor='rgba(0,0,0,0)',
|
| 228 |
+
showlegend=False, height=250, margin=dict(l=30, r=30, t=30, b=30)
|
| 229 |
+
)
|
| 230 |
+
return fig
|
| 231 |
|
| 232 |
# =============================================================================
|
| 233 |
+
# 4. PREDICTION & PRESET FUNCTIONS
|
| 234 |
# =============================================================================
|
| 235 |
|
| 236 |
+
def predict_satisfaction(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
gender, cust_type, age, travel_type, flight_class, distance,
|
| 238 |
wifi, time_conv, ease_booking, gate_loc, food, online_board,
|
| 239 |
seat_comfort, entertainment, onboard_service, leg_room,
|
| 240 |
baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
|
| 241 |
):
|
| 242 |
+
input_dict = {
|
| 243 |
'Gender': gender, 'Customer Type': cust_type, 'Age': age,
|
| 244 |
'Type of Travel': travel_type, 'Class': flight_class, 'Flight Distance': distance,
|
| 245 |
'Inflight wifi service': wifi, 'Departure/Arrival time convenient': time_conv,
|
|
|
|
| 252 |
'Departure Delay in Minutes': dep_delay, 'Arrival Delay in Minutes': arr_delay
|
| 253 |
}
|
| 254 |
|
| 255 |
+
input_df = pd.DataFrame([input_dict])
|
| 256 |
|
| 257 |
for col in CATEGORICAL_COLS:
|
| 258 |
+
val = str(input_df[col].iloc[0])
|
| 259 |
le = engine.label_encoders[col]
|
| 260 |
+
if val in le.classes_:
|
| 261 |
+
input_df[col] = le.transform([val])
|
| 262 |
+
else:
|
| 263 |
+
input_df[col] = 0
|
| 264 |
+
|
| 265 |
+
probs = engine.model.predict_proba(input_df[FEATURE_COLUMNS])[0]
|
| 266 |
classes = engine.target_encoder.classes_
|
|
|
|
|
|
|
| 267 |
|
| 268 |
+
try:
|
| 269 |
+
sat_idx = np.where(classes == 'satisfied')[0][0]
|
| 270 |
+
except IndexError:
|
| 271 |
+
sat_idx = 1 if len(classes) > 1 else 0
|
| 272 |
+
|
| 273 |
+
sat_prob = probs[sat_idx] * 100
|
| 274 |
+
|
| 275 |
+
status_symbol = "😄" if sat_prob >= 50 else "🙁"
|
| 276 |
+
status_label = "SATISFIED" if sat_prob >= 50 else "NEUTRAL / DISSATISFIED"
|
| 277 |
+
status_color = "#10b981" if sat_prob >= 50 else "#ef4444"
|
| 278 |
|
| 279 |
+
html_result = f"""
|
| 280 |
+
<div style="background: rgba(30, 41, 59, 0.7); border: 1px solid {status_color}; border-radius: 12px; padding: 20px; text-align: center;">
|
| 281 |
+
<span style="font-size: 2.5rem;">{status_symbol}</span>
|
| 282 |
+
<h2 style="color: {status_color}; margin: 8px 0; font-weight: 800;">{status_label}</h2>
|
| 283 |
+
<p style="color: #94a3b8; margin: 0;">Predicted Customer Sentiment Outcome</p>
|
| 284 |
</div>
|
| 285 |
"""
|
| 286 |
|
| 287 |
+
gauge_fig = DashboardVisualizer.create_gauge(sat_prob)
|
| 288 |
+
radar_dict = {'Wifi': wifi, 'Boarding': online_board, 'Entertainment': entertainment, 'Seat Comfort': seat_comfort, 'Cleanliness': cleanliness, 'Service': onboard_service}
|
| 289 |
+
radar_fig = DashboardVisualizer.create_radar(radar_dict)
|
| 290 |
|
| 291 |
+
return html_result, gauge_fig, radar_fig
|
| 292 |
+
|
| 293 |
+
def load_dissatisfied_preset():
|
| 294 |
+
return ("Male", "disloyal Customer", 25, "Personal Travel", "Eco", 450, 1, 2, 2, 3, 1, 1, 1, 1, 2, 1, 2, 2, 2, 1, 60, 65)
|
| 295 |
+
|
| 296 |
+
def load_satisfied_preset():
|
| 297 |
+
return ("Female", "Loyal Customer", 42, "Business travel", "Business", 2500, 5, 4, 4, 4, 4, 5, 5, 5, 5, 4, 5, 4, 5, 5, 0, 0)
|
| 298 |
|
| 299 |
# =============================================================================
|
| 300 |
+
# 5. GRADIO UI LAYOUT BUILDER
|
| 301 |
# =============================================================================
|
| 302 |
|
| 303 |
+
with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="blue")) as demo:
|
| 304 |
|
| 305 |
+
with gr.Row():
|
| 306 |
+
with gr.Column(scale=4):
|
| 307 |
+
gr.Markdown("# <span class=\"accent-header\">✈️ Airline AI Satisfaction Intelligence</span>\n#### *Modular Machine Learning & Analytics Dashboard*")
|
| 308 |
+
|
| 309 |
+
with gr.Row():
|
| 310 |
+
gr.HTML(
|
| 311 |
+
f"""
|
| 312 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; width: 100%;">
|
| 313 |
+
<div class="kpi-card"><div class="kpi-title">Model Accuracy</div><div class="kpi-value">{engine.metrics['accuracy']*100:.2f}%</div></div>
|
| 314 |
+
<div class="kpi-card"><div class="kpi-title">F1-Score</div><div class="kpi-value">{engine.metrics['f1']:.2f}</div></div>
|
| 315 |
+
<div class="kpi-card"><div class="kpi-title">Algorithm</div><div class="kpi-value" style="font-size:1.3rem; color:#818cf8;">Random Forest</div></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
</div>
|
| 317 |
+
"""
|
| 318 |
+
)
|
|
|
|
| 319 |
|
| 320 |
+
gr.Markdown("<br>")
|
| 321 |
+
|
| 322 |
+
with gr.Tabs():
|
| 323 |
+
with gr.TabItem("🎯 Real-Time Predictor"):
|
| 324 |
+
|
| 325 |
+
# --- NEW PRESET BUTTONS FOR EASY PRESENTING ---
|
| 326 |
+
with gr.Row():
|
| 327 |
+
btn_sat_preset = gr.Button("✅ Load Typical Satisfied Passenger", size="sm")
|
| 328 |
+
btn_dissat_preset = gr.Button("❌ Load Typical Dissatisfied Passenger", size="sm")
|
| 329 |
|
| 330 |
+
with gr.Row():
|
| 331 |
+
with gr.Column(scale=3):
|
| 332 |
+
|
| 333 |
+
with gr.Accordion("👤 1. Passenger & Flight Profile", open=True):
|
| 334 |
+
with gr.Row():
|
| 335 |
+
gender = gr.Dropdown(["Female", "Male"], value="Female", label="Gender")
|
| 336 |
+
cust_type = gr.Dropdown(["Loyal Customer", "disloyal Customer"], value="Loyal Customer", label="Customer Loyalty")
|
| 337 |
+
age = gr.Slider(10, 80, value=35, step=1, label="Age")
|
| 338 |
+
with gr.Row():
|
| 339 |
+
travel_type = gr.Dropdown(["Business travel", "Personal Travel"], value="Business travel", label="Travel Type")
|
| 340 |
+
flight_class = gr.Dropdown(["Business", "Eco", "Eco Plus"], value="Business", label="Class")
|
| 341 |
+
distance = gr.Slider(100, 5000, value=1250, step=50, label="Flight Distance")
|
| 342 |
+
|
| 343 |
+
with gr.Accordion("⭐ 2. In-Flight Service Ratings", open=False):
|
| 344 |
+
with gr.Row():
|
| 345 |
+
wifi = gr.Slider(0, 5, value=4, step=1, label="Inflight Wifi")
|
| 346 |
+
online_board = gr.Slider(0, 5, value=4, step=1, label="Online Boarding")
|
| 347 |
+
seat_comfort = gr.Slider(0, 5, value=5, step=1, label="Seat Comfort")
|
| 348 |
+
with gr.Row():
|
| 349 |
+
entertainment = gr.Slider(0, 5, value=5, step=1, label="Inflight Entertainment")
|
| 350 |
+
cleanliness = gr.Slider(0, 5, value=4, step=1, label="Cleanliness")
|
| 351 |
+
food = gr.Slider(0, 5, value=3, step=1, label="Food & Drink")
|
| 352 |
+
|
| 353 |
+
with gr.Accordion("🛠️ 3. Logistics, Operations & Delays", open=False):
|
| 354 |
+
with gr.Row():
|
| 355 |
+
onboard_service = gr.Slider(0, 5, value=4, step=1, label="On-board Service")
|
| 356 |
+
leg_room = gr.Slider(0, 5, value=4, step=1, label="Leg Room")
|
| 357 |
+
baggage = gr.Slider(0, 5, value=4, step=1, label="Baggage Handling")
|
| 358 |
+
with gr.Row():
|
| 359 |
+
checkin = gr.Slider(0, 5, value=4, step=1, label="Check-in Service")
|
| 360 |
+
inflight_service = gr.Slider(0, 5, value=4, step=1, label="Inflight Service")
|
| 361 |
+
ease_booking = gr.Slider(0, 5, value=3, step=1, label="Ease of Booking")
|
| 362 |
+
with gr.Row():
|
| 363 |
+
time_conv = gr.Slider(0, 5, value=3, step=1, label="Time Convenience")
|
| 364 |
+
gate_loc = gr.Slider(0, 5, value=3, step=1, label="Gate Location")
|
| 365 |
+
dep_delay = gr.Number(value=0, label="Departure Delay (Min)")
|
| 366 |
+
arr_delay = gr.Number(value=0, label="Arrival Delay (Min)")
|
| 367 |
+
|
| 368 |
+
predict_btn = gr.Button("🚀 Run AI Sentiment Inference", elem_classes=["custom-btn-primary"], size="lg")
|
| 369 |
+
|
| 370 |
+
with gr.Column(scale=2):
|
| 371 |
+
result_card = gr.HTML("<div style='padding: 25px; text-align: center; color: #94a3b8;'>Awaiting inputs...</div>")
|
| 372 |
+
gauge_plot = gr.Plot()
|
| 373 |
+
radar_plot = gr.Plot()
|
| 374 |
+
|
| 375 |
+
# Input list for mapping
|
| 376 |
+
all_inputs = [
|
| 377 |
+
gender, cust_type, age, travel_type, flight_class, distance,
|
| 378 |
+
wifi, time_conv, ease_booking, gate_loc, food, online_board,
|
| 379 |
+
seat_comfort, entertainment, onboard_service, leg_room,
|
| 380 |
+
baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
|
| 381 |
+
]
|
| 382 |
+
|
| 383 |
+
predict_btn.click(fn=predict_satisfaction, inputs=all_inputs, outputs=[result_card, gauge_plot, radar_plot])
|
| 384 |
+
btn_dissat_preset.click(fn=load_dissatisfied_preset, inputs=[], outputs=all_inputs)
|
| 385 |
+
btn_sat_preset.click(fn=load_satisfied_preset, inputs=[], outputs=all_inputs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
if __name__ == "__main__":
|
| 388 |
demo.launch()
|