VectorV17 commited on
Commit
d06543d
·
verified ·
1 Parent(s): 285922a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +246 -310
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. ELEGANT MODERN SAAS CSS (Glassmorphism & Mesh Background Glow)
12
  # =============================================================================
13
 
14
- MODERN_SAAS_CSS = """
15
- /* Vibrant Mesh Gradient Background */
16
  body, .gradio-container {
17
- background: radial-gradient(ellipse at 50% -20%, #2e1065 0%, #0f172a 50%, #020617 100%) !important;
18
- color: #f8fafc !important;
19
- font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
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.65);
47
- backdrop-filter: blur(12px);
48
- border: 1px solid rgba(255, 255, 255, 0.08);
49
- border-radius: 16px;
50
- padding: 20px 24px;
51
- transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
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.75rem;
72
  color: #94a3b8;
73
  text-transform: uppercase;
74
- letter-spacing: 0.08em;
75
- font-weight: 700;
76
  }
77
 
78
- /* Clean Modular Tabs Styling */
79
- .gr-tabs {
80
- background: transparent !important;
81
- border: none !important;
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
- .gr-tab-nav button {
92
- border-radius: 8px !important;
93
- font-weight: 600 !important;
94
- font-size: 0.9rem !important;
95
- color: #94a3b8 !important;
96
- border: none !important;
97
- padding: 8px 16px !important;
98
- transition: all 0.2s ease !important;
99
  }
100
 
101
- .gr-tab-nav button.selected {
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: #ffffff !important;
112
- border-radius: 12px !important;
113
- font-weight: 700 !important;
114
- font-size: 1rem !important;
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
- .glow-btn:hover {
123
- transform: translateY(-2px) scale(1.005);
124
- box-shadow: 0 10px 32px rgba(217, 70, 239, 0.5) !important;
125
  }
126
 
127
- /* Component Overrides */
128
- .gr-box, .gr-form {
129
- background: rgba(15, 23, 42, 0.5) !important;
130
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
131
- border-radius: 14px !important;
 
132
  }
133
 
134
- .gr-input, .gr-dropdown {
135
- background: rgba(30, 41, 59, 0.7) !important;
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. CORE BACKEND & ROUTING ENGINE
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 EnterpriseSentimentEngine:
158
  def __init__(self):
159
  self.model = None
160
  self.label_encoders = {}
161
  self.target_encoder = LabelEncoder()
162
  self.metrics = {}
163
- self.train_pipeline()
 
164
 
165
- def generate_synthetic_telemetry(self, n=2500):
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(18, 75, n)
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(200, 4000, n)
173
 
174
  ratings = {col: np.random.randint(1, 6, n) for col in FEATURE_COLUMNS[6:20]}
175
- dep_delays = np.random.exponential(10, n).astype(int)
176
- arr_delays = np.maximum(0, dep_delays + np.random.randint(-3, 8, n))
177
 
178
- score = (ratings['Inflight wifi service']*1.5 + ratings['Online boarding']*1.4 +
179
- ratings['Inflight entertainment']*1.2 + ratings['Seat comfort']*1.0 - (dep_delays / 20))
 
 
 
 
180
 
181
- satisfaction = ['satisfied' if s > 15.5 else 'neutral or dissatisfied' for s in score]
 
182
 
183
- return pd.DataFrame({
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 train_pipeline(self):
191
  train_path = next((f for f in ["train (1).csv", "train.csv", "test (1).csv"] if os.path.exists(f)), None)
192
- df = pd.read_csv(train_path) if train_path else self.generate_synthetic_telemetry()
 
 
 
 
 
 
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=100, max_depth=14, random_state=42, n_jobs=-1)
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
- 'precision': precision_score(y_encoded, preds, average='weighted', zero_division=0)
215
  }
216
 
217
- engine = EnterpriseSentimentEngine()
218
 
219
  # =============================================================================
220
- # 3. HIGH-VISUALIZATION GRAPHICS
221
  # =============================================================================
222
 
223
- def create_sleek_gauge(probability):
224
- fig = go.Figure(go.Indicator(
225
- mode="gauge+number",
226
- value=probability,
227
- number={'suffix': "%", 'font': {'size': 38, 'color': "#ffffff", 'family': "Plus Jakarta Sans"}},
228
- gauge={
229
- 'axis': {'range': [0, 100], 'tickwidth': 1, 'tickcolor': "#475569"},
230
- 'bar': {'color': "#818cf8"},
231
- 'bgcolor': "rgba(15, 23, 42, 0.8)",
232
- 'bordercolor': "rgba(255, 255, 255, 0.1)",
233
- 'steps': [
234
- {'range': [0, 50], 'color': 'rgba(239, 68, 68, 0.25)'},
235
- {'range': [50, 100], 'color': 'rgba(16, 185, 129, 0.25)'}
236
- ],
237
- 'threshold': {'line': {'color': "#c084fc", 'width': 3}, 'thickness': 0.8, 'value': probability}
238
- }
239
- ))
240
- fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', height=200, margin=dict(l=20, r=20, t=20, b=10))
241
- return fig
242
-
243
- def create_sleek_radar(ratings):
244
- categories = list(ratings.keys())
245
- values = list(ratings.values())
246
- fig = go.Figure(data=go.Scatterpolar(
247
- r=values + [values[0]],
248
- theta=categories + [categories[0]],
249
- fill='toself',
250
- fillcolor='rgba(168, 85, 247, 0.25)',
251
- line=dict(color='#c084fc', width=2)
252
- ))
253
- fig.update_layout(
254
- polar=dict(
255
- bgcolor='rgba(15, 23, 42, 0.6)',
256
- radialaxis=dict(visible=True, range=[0, 5], color="#94a3b8", gridcolor="rgba(255,255,255,0.08)"),
257
- angularaxis=dict(color="#f8fafc", gridcolor="rgba(255,255,255,0.08)")
258
- ),
259
- paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', showlegend=False, height=210, margin=dict(l=30, r=30, t=20, b=20)
260
- )
261
- return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
  # =============================================================================
264
- # 4. PRESET ROUTING & EXECUTION HANDLERS
265
  # =============================================================================
266
 
267
- PRESET_PROFILES = {
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
- data_dict = {
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
- df_input = pd.DataFrame([data_dict])
298
 
299
  for col in CATEGORICAL_COLS:
300
- val = str(df_input[col].iloc[0])
301
  le = engine.label_encoders[col]
302
- df_input[col] = le.transform([val]) if val in le.classes_ else 0
303
-
304
- probs = engine.model.predict_proba(df_input[FEATURE_COLUMNS])[0]
 
 
 
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
- is_sat = sat_score >= 50
310
- badge_bg = "rgba(16, 185, 129, 0.15)" if is_sat else "rgba(239, 68, 68, 0.15)"
311
- badge_border = "#10b981" if is_sat else "#ef4444"
312
- status_text = "SATISFIED" if is_sat else "NEUTRAL / DISSATISFIED"
 
 
 
 
 
 
313
 
314
- status_card = f"""
315
- <div style="background: {badge_bg}; border: 1px solid {badge_border}; border-radius: 14px; padding: 20px; text-align: center;">
316
- <span style="color: {badge_border}; font-size: 0.75rem; font-weight: 800; letter-spacing: 0.1em; text-transform: uppercase;">Switchboard Classification Output</span>
317
- <h2 style="color: #ffffff; font-size: 1.75rem; margin: 6px 0 0 0; font-weight: 800;">{status_text}</h2>
318
- <div style="color: #94a3b8; font-size: 0.85rem; margin-top: 4px;">Inference Probability: <b style="color: #fff;">{sat_score:.1f}%</b></div>
319
  </div>
320
  """
321
 
322
- gauge = create_sleek_gauge(sat_score)
323
- radar = create_sleek_radar({'Wifi': wifi, 'Boarding': online_board, 'Entertainment': entertainment, 'Comfort': seat_comfort, 'Cleanliness': cleanliness, 'Service': onboard_service})
 
324
 
325
- return status_card, gauge, radar
 
 
 
 
 
 
326
 
327
  # =============================================================================
328
- # 5. MODULAR ELEGANT INTERFACE BUILDER
329
  # =============================================================================
330
 
331
- with gr.Blocks(css=MODERN_SAAS_CSS, theme=gr.themes.Soft()) as demo:
332
 
333
- # Glassmorphism Top Navigation
334
- gr.HTML(
335
- """
336
- <div class="navbar-header">
337
- <div style="display: flex; align-items: center; gap: 12px;">
338
- <div style="background: linear-gradient(135deg, #a855f7, #6366f1); width: 12px; height: 12px; border-radius: 50%;"></div>
339
- <span style="font-size: 1.1rem; font-weight: 800; color: #ffffff; letter-spacing: -0.02em;">AERO-SWITCHBOARD AI</span>
340
- </div>
341
- <div style="font-size: 0.85rem; color: #94a3b8; font-weight: 500;">Enterprise Telemetry Classifier</div>
342
- </div>
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">&lt;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
- </div>
367
- """
368
- )
369
 
370
- with gr.Row():
371
- # Left Workspace: Modular Tabs Layout
372
- with gr.Column(scale=3):
373
- preset_selector = gr.Dropdown(
374
- choices=list(PRESET_PROFILES.keys()),
375
- value="Select Switching Profile...",
376
- label="⚡ Switchboard Fast-Route Preset",
377
- interactive=True
378
- )
379
 
380
- with gr.Tabs():
381
- with gr.Tab("👤 Passenger Profile"):
382
- with gr.Row():
383
- gender = gr.Dropdown(["Female", "Male"], value="Female", label="Gender")
384
- cust_type = gr.Dropdown(["Loyal Customer", "disloyal Customer"], value="Loyal Customer", label="Customer Loyalty")
385
- with gr.Row():
386
- travel_type = gr.Dropdown(["Business travel", "Personal Travel"], value="Business travel", label="Travel Purpose")
387
- flight_class = gr.Dropdown(["Business", "Eco", "Eco Plus"], value="Business", label="Cabin Class")
388
- with gr.Row():
389
- age = gr.Slider(18, 80, value=38, step=1, label="Age")
390
- distance = gr.Slider(100, 5000, value=1400, step=50, label="Flight Distance (Miles)")
391
-
392
- with gr.Tab("⭐ Flight Experience"):
393
- with gr.Row():
394
- wifi = gr.Slider(0, 5, value=4, step=1, label="Inflight Wifi")
395
- online_board = gr.Slider(0, 5, value=4, step=1, label="Online Boarding")
396
- with gr.Row():
397
- entertainment = gr.Slider(0, 5, value=5, step=1, label="Entertainment")
398
- seat_comfort = gr.Slider(0, 5, value=4, step=1, label="Seat Comfort")
399
- with gr.Row():
400
- cleanliness = gr.Slider(0, 5, value=4, step=1, label="Cleanliness")
401
- food = gr.Slider(0, 5, value=3, step=1, label="Food & Beverage")
402
-
403
- with gr.Tab("🛠️ Operations & Delays"):
404
- with gr.Row():
405
- onboard_service = gr.Slider(0, 5, value=4, step=1, label="On-board Service")
406
- leg_room = gr.Slider(0, 5, value=4, step=1, label="Leg Room Space")
407
- with gr.Row():
408
- baggage = gr.Slider(0, 5, value=4, step=1, label="Baggage Handling")
409
- checkin = gr.Slider(0, 5, value=4, step=1, label="Check-in Service")
410
- with gr.Row():
411
- inflight_service = gr.Slider(0, 5, value=4, step=1, label="Inflight Service")
412
- ease_booking = gr.Slider(0, 5, value=4, step=1, label="Booking Ease")
413
- with gr.Row():
414
- time_conv = gr.Slider(0, 5, value=3, step=1, label="Time Convenience")
415
- gate_loc = gr.Slider(0, 5, value=3, step=1, label="Gate Location")
416
- with gr.Row():
417
- dep_delay = gr.Number(value=0, label="Departure Delay (Mins)")
418
- arr_delay = gr.Number(value=0, label="Arrival Delay (Mins)")
419
-
420
- run_btn = gr.Button("🚀 Execute Switchboard Analysis", elem_classes=["glow-btn"])
421
-
422
- # Right Workspace: Real-Time Output Analytics Panel
423
- with gr.Column(scale=2):
424
- output_card = gr.HTML(
425
- """
426
- <div style="background: rgba(15, 23, 42, 0.5); border: 1px dashed rgba(255,255,255,0.15); border-radius: 14px; padding: 28px; text-align: center; color: #94a3b8;">
427
- Adjust telemetry tabs or choose a preset profile, then click <b>Execute Switchboard Analysis</b>.
428
- </div>
429
- """
430
- )
431
- gauge_plot = gr.Plot()
432
- radar_plot = gr.Plot()
433
-
434
- all_inputs = [
435
- gender, cust_type, age, travel_type, flight_class, distance,
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()