VectorV17 commited on
Commit
59631e6
·
verified ·
1 Parent(s): 0db9f12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +422 -294
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
@@ -5,13 +6,76 @@ import plotly.express as px
5
  import plotly.graph_objects as go
6
  from sklearn.ensemble import RandomForestClassifier
7
  from sklearn.preprocessing import LabelEncoder
8
- from sklearn.model_selection import train_test_split
9
- from sklearn.metrics import classification_report, accuracy_score, confusion_matrix
10
- import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- # ==========================================
13
- # 1. DATA PREPROCESSING & MODEL TRAINING
14
- # ==========================================
15
 
16
  FEATURE_COLUMNS = [
17
  'Gender', 'Customer Type', 'Age', 'Type of Travel', 'Class', 'Flight Distance',
@@ -24,367 +88,431 @@ FEATURE_COLUMNS = [
24
 
25
  CATEGORICAL_COLS = ['Gender', 'Customer Type', 'Type of Travel', 'Class']
26
 
27
- label_encoders = {}
28
-
29
- def build_synthetic_dataset(n_samples=2000):
30
- """Generates synthetic dataset structured identically to Japan Airlines customer survey if no CSV exists."""
31
- np.random.seed(42)
32
- genders = np.random.choice(['Male', 'Female'], n_samples)
33
- cust_types = np.random.choice(['Loyal Customer', 'disloyal Customer'], n_samples, p=[0.8, 0.2])
34
- ages = np.random.randint(15, 80, n_samples)
35
- travel_types = np.random.choice(['Business travel', 'Personal Travel'], n_samples, p=[0.7, 0.3])
36
- classes = np.random.choice(['Business', 'Eco', 'Eco Plus'], n_samples, p=[0.5, 0.4, 0.1])
37
- distances = np.random.randint(100, 4000, n_samples)
38
-
39
- ratings = {col: np.random.randint(1, 6, n_samples) for col in FEATURE_COLUMNS[6:20]}
40
-
41
- dep_delays = np.random.exponential(scale=15, size=n_samples).astype(int)
42
- arr_delays = dep_delays + np.random.randint(-5, 10, n_samples)
43
- arr_delays = np.maximum(0, arr_delays)
44
-
45
- # Calculate synthetic satisfaction score logic
46
- score = (ratings['Inflight wifi service'] * 1.5 +
47
- ratings['Online boarding'] * 1.5 +
48
- ratings['Inflight entertainment'] * 1.2 +
49
- ratings['Seat comfort'] * 1.0 -
50
- (dep_delays / 20))
51
-
52
- satisfaction = ['satisfied' if s > 12 else 'neutral or dissatisfied' for s in score]
53
-
54
- data = {
55
- 'Gender': genders,
56
- 'Customer Type': cust_types,
57
- 'Age': ages,
58
- 'Type of Travel': travel_types,
59
- 'Class': classes,
60
- 'Flight Distance': distances,
61
- **ratings,
62
- 'Departure Delay in Minutes': dep_delays,
63
- 'Arrival Delay in Minutes': arr_delays,
64
- 'satisfaction': satisfaction
65
- }
66
- return pd.DataFrame(data)
67
 
68
- def load_and_train_model():
69
- """Loads dataset (or builds synthetic dataset) and trains the Random Forest model."""
70
- data_path = "train (1).csv" if os.path.exists("train (1).csv") else ("train.csv" if os.path.exists("train.csv") else None)
71
-
72
- if data_path:
73
- df = pd.read_csv(data_path)
74
- else:
75
- df = build_synthetic_dataset(3000)
76
-
77
- # Clean missing values
78
- if 'Arrival Delay in Minutes' in df.columns:
79
- df['Arrival Delay in Minutes'].fillna(df['Arrival Delay in Minutes'].median(), inplace=True)
80
-
81
- # Encode Categoricals
82
- df_encoded = df.copy()
83
- for col in CATEGORICAL_COLS:
84
- le = LabelEncoder()
85
- df_encoded[col] = le.fit_transform(df_encoded[col].astype(str))
86
- label_encoders[col] = le
 
 
 
 
 
 
 
 
 
87
 
88
- X = df_encoded[FEATURE_COLUMNS]
89
- y = df_encoded['satisfaction']
90
-
91
- # Target Encoding
92
- le_target = LabelEncoder()
93
- y_encoded = le_target.fit_transform(y)
94
- label_encoders['satisfaction'] = le_target
95
-
96
- # Model definition optimized for fast CPU performance
97
- clf = RandomForestClassifier(
98
- n_estimators=100,
99
- max_depth=15,
100
- random_state=42,
101
- n_jobs=-1
102
- )
103
- clf.fit(X, y_encoded)
104
-
105
- # Accuracy evaluation on dataset
106
- y_pred = clf.predict(X)
107
- acc = accuracy_score(y_encoded, y_pred)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- return clf, acc, df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
- # Initialize Model and Data
112
- model, model_acc, sample_df = load_and_train_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- # ==========================================
115
- # 2. INFERENCE & VISUALIZATION FUNCTIONS
116
- # ==========================================
117
 
118
- def predict_single_customer(
119
  gender, cust_type, age, travel_type, flight_class, distance,
120
  wifi, time_conv, ease_booking, gate_loc, food, online_board,
121
  seat_comfort, entertainment, onboard_service, leg_room,
122
  baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
123
  ):
124
- """Processes single passenger inputs and returns prediction probabilities + gauge chart."""
125
-
126
  input_dict = {
127
- 'Gender': gender,
128
- 'Customer Type': cust_type,
129
- 'Age': age,
130
- 'Type of Travel': travel_type,
131
- 'Class': flight_class,
132
- 'Flight Distance': distance,
133
- 'Inflight wifi service': wifi,
134
- 'Departure/Arrival time convenient': time_conv,
135
- 'Ease of Online booking': ease_booking,
136
- 'Gate location': gate_loc,
137
- 'Food and drink': food,
138
- 'Online boarding': online_board,
139
- 'Seat comfort': seat_comfort,
140
- 'Inflight entertainment': entertainment,
141
- 'On-board service': onboard_service,
142
- 'Leg room service': leg_room,
143
- 'Baggage handling': baggage,
144
- 'Checkin service': checkin,
145
- 'Inflight service': inflight_service,
146
- 'Cleanliness': cleanliness,
147
- 'Departure Delay in Minutes': dep_delay,
148
- 'Arrival Delay in Minutes': arr_delay
149
  }
150
 
151
  input_df = pd.DataFrame([input_dict])
152
 
153
- # Encode inputs
154
  for col in CATEGORICAL_COLS:
155
- input_df[col] = label_encoders[col].transform(input_df[col].astype(str))
156
 
157
- probs = model.predict_proba(input_df[FEATURE_COLUMNS])[0]
158
- classes = label_encoders['satisfaction'].classes_
159
 
160
- satisfaction_prob = probs[np.where(classes == 'satisfied')[0][0]] * 100
161
- dissatisfied_prob = probs[np.where(classes == 'neutral or dissatisfied')[0][0]] * 100
162
 
163
- pred_label = "Satisfied 😄" if satisfaction_prob >= 50 else "Neutral or Dissatisfied 🙁"
 
 
164
 
165
- # Create Speedometer/Gauge Plot for Probability
166
- fig = go.Figure(go.Indicator(
167
- mode="gauge+number",
168
- value=satisfaction_prob,
169
- domain={'x': [0, 1], 'y': [0, 1]},
170
- title={'text': "Satisfaction Probability (%)", 'font': {'size': 20}},
171
- number={'suffix': "%", 'font': {'size': 28}},
172
- gauge={
173
- 'axis': {'range': [0, 100], 'tickwidth': 1},
174
- 'bar': {'color': "#1e88e5"},
175
- 'steps': [
176
- {'range': [0, 50], 'color': "#ffcdd2"},
177
- {'range': [50, 100], 'color': "#c8e6c9"}
178
- ],
179
- 'threshold': {
180
- 'line': {'color': "red", 'width': 4},
181
- 'thickness': 0.75,
182
- 'value': 50
183
- }
184
- }
185
- ))
186
- fig.update_layout(height=280, margin=dict(l=20, r=20, t=40, b=20))
187
 
188
- # Ratings Radar Chart
189
- categories = ['Wifi', 'Entertainment', 'Seat Comfort', 'Cleanliness', 'On-board Service', 'Ease of Booking']
190
- values = [wifi, entertainment, seat_comfort, cleanliness, onboard_service, ease_booking]
191
 
192
- radar_fig = go.Figure(data=go.Scatterpolar(
193
- r=values,
194
- theta=categories,
195
- fill='toself',
196
- fillcolor='rgba(30, 136, 229, 0.3)',
197
- line_color='#1e88e5'
198
- ))
199
- radar_fig.update_layout(
200
- polar=dict(radialaxis=dict(visible=True, range=[0, 5])),
201
- showlegend=False,
202
- title="Passenger Service Profile Ratings",
203
- height=280,
204
- margin=dict(l=40, r=40, t=40, b=20)
205
- )
206
-
207
- result_text = f"### Predicted Outcome: **{pred_label}**\n\n" \
208
- f"* **Probability Satisfied:** {satisfaction_prob:.1f}%\n" \
209
- f"* **Probability Dissatisfied:** {dissatisfied_prob:.1f}%"
210
-
211
- return result_text, fig, radar_fig
212
-
213
 
214
- def batch_predict(file):
215
- """Processes batch CSV uploads and appends predicted satisfaction columns."""
216
- if file is None:
217
- return None, "Please upload a valid CSV file."
218
 
219
- df = pd.read_csv(file.name)
220
  df_encoded = df.copy()
221
 
222
- # Ensure missing columns are handled
223
  if 'Arrival Delay in Minutes' in df_encoded.columns:
224
- df_encoded['Arrival Delay in Minutes'].fillna(df_encoded['Arrival Delay in Minutes'].median(), inplace=True)
225
 
226
  for col in CATEGORICAL_COLS:
227
  if col in df_encoded.columns:
228
- le = label_encoders[col]
229
  df_encoded[col] = df_encoded[col].astype(str).map(lambda s: le.transform([s])[0] if s in le.classes_ else 0)
230
 
231
- preds = model.predict(df_encoded[FEATURE_COLUMNS])
232
- pred_labels = label_encoders['satisfaction'].inverse_transform(preds)
233
 
234
  df['Predicted_Satisfaction'] = pred_labels
235
 
236
- # Calculate batch summary plot
237
- summary_counts = df['Predicted_Satisfaction'].value_counts().reset_index()
238
- summary_counts.columns = ['Satisfaction', 'Count']
 
 
239
 
240
  fig = px.pie(
241
- summary_counts,
242
- names='Satisfaction',
243
- values='Count',
244
- title="Batch Flight Satisfaction Distribution",
245
  color='Satisfaction',
246
- color_discrete_map={'satisfied': '#66bb6a', 'neutral or dissatisfied': '#ef5350'}
247
  )
248
-
249
- # Save output CSV for user download
250
- output_path = "batch_predictions_output.csv"
251
- df.to_csv(output_path, index=False)
252
 
253
  return output_path, df.head(10), fig
254
 
 
 
 
255
 
256
- def generate_feature_importance_plot():
257
- """Generates feature importance chart for model explanations."""
258
- importances = model.feature_importances_
259
- indices = np.argsort(importances)[::-1]
260
 
261
- sorted_features = [FEATURE_COLUMNS[i] for i in indices]
262
- sorted_importances = importances[indices]
 
 
 
 
 
 
 
263
 
264
- fig = px.bar(
265
- x=sorted_importances[:10],
266
- y=sorted_features[:10],
267
- orientation='h',
268
- labels={'x': 'Importance Score', 'y': 'Feature'},
269
- title="Top 10 Key Drivers of Passenger Satisfaction",
270
- color=sorted_importances[:10],
271
- color_continuous_scale='Viridis'
272
- )
273
- fig.update_layout(yaxis=dict(autorange="reversed"), height=400)
274
- return fig
275
-
276
- # ==========================================
277
- # 3. GRADIO USER INTERFACE DESIGN
278
- # ==========================================
 
 
 
 
 
 
 
 
 
279
 
280
- theme = gr.themes.Soft(
281
- primary_hue="indigo",
282
- secondary_hue="blue",
283
- )
284
 
285
- with gr.Blocks(theme=theme, title="Airline Customer Satisfaction AI Dashboard") as demo:
286
-
287
- gr.Markdown(
288
- """
289
- # ✈️ Airline Customer Satisfaction AI Dashboard
290
- Predict passenger satisfaction levels, analyze key service drivers, and batch process survey responses using Machine Learning.
291
- """
292
- )
293
-
294
  with gr.Tabs():
295
 
296
- # TAB 1: Single Passenger Prediction
297
- with gr.TabItem("🎯 Real-Time Passenger Predictor"):
298
- gr.Markdown("### Input Passenger & Flight Details")
299
-
300
  with gr.Row():
301
- with gr.Column(scale=1):
302
- gr.Markdown("#### 👤 Passenger Profile")
303
- gender = gr.Dropdown(["Female", "Male"], label="Gender", value="Female")
304
- cust_type = gr.Dropdown(["Loyal Customer", "disloyal Customer"], label="Customer Type", value="Loyal Customer")
305
- age = gr.Slider(7, 80, value=35, step=1, label="Age")
306
- travel_type = gr.Dropdown(["Business travel", "Personal Travel"], label="Type of Travel", value="Business travel")
307
- flight_class = gr.Dropdown(["Business", "Eco", "Eco Plus"], label="Flight Class", value="Business")
308
- distance = gr.Slider(100, 5000, value=1200, step=50, label="Flight Distance (Miles)")
309
- dep_delay = gr.Number(label="Departure Delay (Minutes)", value=0)
310
- arr_delay = gr.Number(label="Arrival Delay (Minutes)", value=0)
311
 
312
- with gr.Column(scale=1):
313
- gr.Markdown("#### ⭐ Inflight & Airport Service Ratings (1-5 Scale)")
314
- wifi = gr.Slider(0, 5, value=4, step=1, label="Inflight Wifi Service")
315
- online_board = gr.Slider(0, 5, value=4, step=1, label="Online Boarding")
316
- seat_comfort = gr.Slider(0, 5, value=4, step=1, label="Seat Comfort")
317
- entertainment = gr.Slider(0, 5, value=5, step=1, label="Inflight Entertainment")
318
- cleanliness = gr.Slider(0, 5, value=4, step=1, label="Cleanliness")
319
- food = gr.Slider(0, 5, value=3, step=1, label="Food and Drink")
320
-
321
- with gr.Column(scale=1):
322
- gr.Markdown("#### 🛠️ Operation & Support Ratings")
323
- onboard_service = gr.Slider(0, 5, value=4, step=1, label="On-board Service")
324
- leg_room = gr.Slider(0, 5, value=4, step=1, label="Leg Room Service")
325
- baggage = gr.Slider(0, 5, value=4, step=1, label="Baggage Handling")
326
- checkin = gr.Slider(0, 5, value=3, step=1, label="Check-in Service")
327
- inflight_service = gr.Slider(0, 5, value=4, step=1, label="Inflight Service")
328
- ease_booking = gr.Slider(0, 5, value=3, step=1, label="Ease of Online Booking")
329
- time_conv = gr.Slider(0, 5, value=3, step=1, label="Departure/Arrival Time Convenient")
330
- gate_loc = gr.Slider(0, 5, value=3, step=1, label="Gate Location")
331
-
332
- predict_btn = gr.Button("🚀 Predict Satisfaction", variant="primary", size="lg")
333
-
334
- gr.Markdown("---")
335
- gr.Markdown("### Prediction Results & Diagnostics")
336
-
337
- with gr.Row():
338
- with gr.Column(scale=1):
339
- result_output = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  gauge_plot = gr.Plot()
341
- with gr.Column(scale=1):
342
  radar_plot = gr.Plot()
343
-
344
  predict_btn.click(
345
- fn=predict_single_customer,
346
  inputs=[
347
  gender, cust_type, age, travel_type, flight_class, distance,
348
  wifi, time_conv, ease_booking, gate_loc, food, online_board,
349
  seat_comfort, entertainment, onboard_service, leg_room,
350
  baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
351
  ],
352
- outputs=[result_output, gauge_plot, radar_plot]
353
  )
354
 
355
- # TAB 2: Batch Prediction via CSV Upload
356
- with gr.TabItem("📊 Batch Prediction & CSV Analytics"):
357
- gr.Markdown("### Upload Passenger CSV Dataset")
358
- gr.Markdown("Upload a structured CSV containing passenger feedback columns to run automated bulk predictions.")
359
-
360
  with gr.Row():
361
- file_input = gr.File(label="Upload CSV Dataset", file_types=[".csv"])
362
- batch_btn = gr.Button("⚡ Run Batch Predictions", variant="primary")
363
 
364
  with gr.Row():
365
- file_output = gr.File(label="Download Predicted Output CSV")
 
366
 
367
- with gr.Row():
368
- preview_table = gr.DataFrame(label="Preview Sample Batch Results")
369
- batch_chart = gr.Plot(label="Batch Distribution")
370
 
371
  batch_btn.click(
372
- fn=batch_predict,
373
  inputs=[file_input],
374
- outputs=[file_output, preview_table, batch_chart]
375
  )
376
 
377
- # TAB 3: Model Performance & Insights Dashboard
378
- with gr.TabItem("📈 Model Metrics & Key Drivers"):
379
- gr.Markdown("### Machine Learning Model Intelligence")
380
-
381
- with gr.Row():
382
- gr.Markdown(f"**Model Architecture:** Random Forest Classifier (100 Trees)")
383
- gr.Markdown(f"**Baseline Training Accuracy:** `{model_acc * 100:.2f}%`")
384
- gr.Markdown("**Target Operational Environment:** Hugging Face CPU Basic")
385
-
386
  with gr.Row():
387
- importance_chart = gr.Plot(value=generate_feature_importance_plot())
 
 
 
 
 
388
 
389
  if __name__ == "__main__":
390
  demo.launch()
 
1
+ import os
2
  import gradio as gr
3
  import pandas as pd
4
  import numpy as np
 
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 Styling */
17
+ body, .gradio-container {
18
+ background-color: #0f172a !important;
19
+ font-family: 'Inter', system-ui, -apple-system, sans-serif !important;
20
+ }
21
+
22
+ .kpi-card {
23
+ background: linear-gradient(135deg, rgba(30, 41, 59, 0.7), rgba(15, 23, 42, 0.8));
24
+ border: 1px solid rgba(255, 255, 255, 0.1);
25
+ border-radius: 12px;
26
+ padding: 18px;
27
+ text-align: center;
28
+ box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
29
+ backdrop-filter: blur(8px);
30
+ }
31
+
32
+ .kpi-title {
33
+ font-size: 0.85rem;
34
+ color: #94a3b8;
35
+ text-transform: uppercase;
36
+ letter-spacing: 0.05em;
37
+ font-weight: 600;
38
+ }
39
+
40
+ .kpi-value {
41
+ font-size: 1.8rem;
42
+ font-weight: 700;
43
+ color: #38bdf8;
44
+ margin-top: 4px;
45
+ }
46
+
47
+ .accent-header {
48
+ background: linear-gradient(90deg, #38bdf8, #818cf8);
49
+ -webkit-background-clip: text;
50
+ -webkit-text-fill-color: transparent;
51
+ font-weight: 800;
52
+ }
53
+
54
+ .custom-btn-primary {
55
+ background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%) !important;
56
+ border: none !important;
57
+ color: white !important;
58
+ border-radius: 8px !important;
59
+ font-weight: 600 !important;
60
+ transition: all 0.3s ease !important;
61
+ }
62
+
63
+ .custom-btn-primary:hover {
64
+ transform: translateY(-2px);
65
+ box-shadow: 0 4px 20px rgba(99, 102, 241, 0.4) !important;
66
+ }
67
+
68
+ /* Accordion Customization */
69
+ .gr-accordion {
70
+ border: 1px solid rgba(255, 255, 255, 0.08) !important;
71
+ border-radius: 10px !important;
72
+ background: rgba(30, 41, 59, 0.4) !important;
73
+ }
74
+ """
75
 
76
+ # =============================================================================
77
+ # 2. DATA & MODEL PIPELINE (MODULAR)
78
+ # =============================================================================
79
 
80
  FEATURE_COLUMNS = [
81
  'Gender', 'Customer Type', 'Age', 'Type of Travel', 'Class', 'Flight Distance',
 
88
 
89
  CATEGORICAL_COLS = ['Gender', 'Customer Type', 'Type of Travel', 'Class']
90
 
91
+ class AirlineSatisfactionEngine:
92
+ def __init__(self):
93
+ self.model = None
94
+ self.label_encoders = {}
95
+ self.target_encoder = LabelEncoder()
96
+ self.metrics = {}
97
+ self.df_sample = None
98
+ self.initialize_and_train()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ def generate_synthetic_data(self, n=3000):
101
+ np.random.seed(42)
102
+ genders = np.random.choice(['Male', 'Female'], n)
103
+ cust_types = np.random.choice(['Loyal Customer', 'disloyal Customer'], n, p=[0.8, 0.2])
104
+ ages = np.random.randint(15, 80, n)
105
+ travel_types = np.random.choice(['Business travel', 'Personal Travel'], n, p=[0.7, 0.3])
106
+ classes = np.random.choice(['Business', 'Eco', 'Eco Plus'], n, p=[0.5, 0.4, 0.1])
107
+ distances = np.random.randint(100, 4500, n)
108
+
109
+ ratings = {col: np.random.randint(1, 6, n) for col in FEATURE_COLUMNS[6:20]}
110
+ dep_delays = np.random.exponential(12, n).astype(int)
111
+ arr_delays = np.maximum(0, dep_delays + np.random.randint(-5, 10, n))
112
+
113
+ score = (ratings['Inflight wifi service']*1.6 +
114
+ ratings['Online boarding']*1.5 +
115
+ ratings['Inflight entertainment']*1.3 +
116
+ ratings['Seat comfort']*1.1 -
117
+ (dep_delays / 18))
118
+
119
+ satisfaction = ['satisfied' if s > 12.5 else 'neutral or dissatisfied' for s in score]
120
+
121
+ data = {
122
+ 'Gender': genders, 'Customer Type': cust_types, 'Age': ages,
123
+ 'Type of Travel': travel_types, 'Class': classes, 'Flight Distance': distances,
124
+ **ratings, 'Departure Delay in Minutes': dep_delays,
125
+ 'Arrival Delay in Minutes': arr_delays, 'satisfaction': satisfaction
126
+ }
127
+ return pd.DataFrame(data)
128
 
129
+ def initialize_and_train(self):
130
+ # Look for user uploaded datasets
131
+ train_path = next((f for f in ["train (1).csv", "train.csv", "test (1).csv"] if os.path.exists(f)), None)
132
+
133
+ if train_path:
134
+ df = pd.read_csv(train_path)
135
+ else:
136
+ df = self.generate_synthetic_data()
137
+
138
+ self.df_sample = df.copy()
139
+
140
+ # Handle missing values
141
+ if 'Arrival Delay in Minutes' in df.columns:
142
+ df['Arrival Delay in Minutes'] = df['Arrival Delay in Minutes'].fillna(df['Arrival Delay in Minutes'].median())
143
+
144
+ df_encoded = df.copy()
145
+ for col in CATEGORICAL_COLS:
146
+ le = LabelEncoder()
147
+ df_encoded[col] = le.fit_transform(df_encoded[col].astype(str))
148
+ self.label_encoders[col] = le
149
+
150
+ X = df_encoded[FEATURE_COLUMNS]
151
+ y_encoded = self.target_encoder.fit_transform(df_encoded['satisfaction'])
152
+
153
+ # Train Random Forest Classifier
154
+ self.model = RandomForestClassifier(n_estimators=120, max_depth=16, random_state=42, n_jobs=-1)
155
+ self.model.fit(X, y_encoded)
156
+
157
+ # Calculate metrics
158
+ preds = self.model.predict(X)
159
+ self.metrics = {
160
+ 'accuracy': accuracy_score(y_encoded, preds),
161
+ 'precision': precision_score(y_encoded, preds, average='weighted'),
162
+ 'recall': recall_score(y_encoded, preds, average='weighted'),
163
+ 'f1': f1_score(y_encoded, preds, average='weighted'),
164
+ 'cm': confusion_matrix(y_encoded, preds)
165
+ }
166
+
167
+ engine = AirlineSatisfactionEngine()
168
+
169
+ # =============================================================================
170
+ # 3. VISUALIZATION ENGINE (PLOTLY)
171
+ # =============================================================================
172
+
173
+ class DashboardVisualizer:
174
 
175
+ @staticmethod
176
+ def create_gauge(probability):
177
+ fig = go.Figure(go.Indicator(
178
+ mode="gauge+number",
179
+ value=probability,
180
+ domain={'x': [0, 1], 'y': [0, 1]},
181
+ title={'text': "Satisfaction Confidence", 'font': {'size': 18, 'color': "#94a3b8"}},
182
+ number={'suffix': "%", 'font': {'size': 32, 'color': "#38bdf8"}},
183
+ gauge={
184
+ 'axis': {'range': [0, 100], 'tickwidth': 1, 'tickcolor': "#475569"},
185
+ 'bar': {'color': "#6366f1"},
186
+ 'bgcolor': "rgba(30, 41, 59, 0.5)",
187
+ 'bordercolor': "rgba(255, 255, 255, 0.1)",
188
+ 'steps': [
189
+ {'range': [0, 50], 'color': 'rgba(239, 68, 68, 0.25)'},
190
+ {'range': [50, 100], 'color': 'rgba(16, 185, 129, 0.25)'}
191
+ ],
192
+ 'threshold': {
193
+ 'line': {'color': "#38bdf8", 'width': 3},
194
+ 'thickness': 0.8,
195
+ 'value': probability
196
+ }
197
+ }
198
+ ))
199
+ fig.update_layout(
200
+ paper_bgcolor='rgba(0,0,0,0)',
201
+ plot_bgcolor='rgba(0,0,0,0)',
202
+ height=250,
203
+ margin=dict(l=20, r=20, t=40, b=20)
204
+ )
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,
229
+ height=250,
230
+ margin=dict(l=30, r=30, t=30, b=30)
231
+ )
232
+ return fig
233
+
234
+ @staticmethod
235
+ def create_feature_importance():
236
+ importances = engine.model.feature_importances_
237
+ idx = np.argsort(importances)[::-1][:10]
238
+
239
+ top_features = [FEATURE_COLUMNS[i] for i in idx]
240
+ top_scores = importances[idx]
241
+
242
+ fig = px.bar(
243
+ x=top_scores,
244
+ y=top_features,
245
+ orientation='h',
246
+ labels={'x': 'Relative Score', 'y': 'Feature'},
247
+ color=top_scores,
248
+ color_continuous_scale='plasma'
249
+ )
250
+ fig.update_layout(
251
+ yaxis=dict(autorange="reversed", color="#e2e8f0"),
252
+ xaxis=dict(color="#94a3b8", gridcolor="rgba(255,255,255,0.05)"),
253
+ paper_bgcolor='rgba(0,0,0,0)',
254
+ plot_bgcolor='rgba(0,0,0,0)',
255
+ font=dict(color="#e2e8f0"),
256
+ coloraxis_showscale=False,
257
+ height=350,
258
+ margin=dict(l=20, r=20, t=30, b=20)
259
+ )
260
+ return fig
261
+
262
+ @staticmethod
263
+ def create_confusion_matrix_plot():
264
+ cm = engine.metrics['cm']
265
+ labels = engine.target_encoder.classes_
266
+
267
+ fig = px.imshow(
268
+ cm,
269
+ x=labels,
270
+ y=labels,
271
+ text_auto=True,
272
+ color_continuous_scale='Blues',
273
+ labels=dict(x="Predicted Label", y="Actual Label")
274
+ )
275
+ fig.update_layout(
276
+ paper_bgcolor='rgba(0,0,0,0)',
277
+ plot_bgcolor='rgba(0,0,0,0)',
278
+ font=dict(color="#e2e8f0"),
279
+ height=350,
280
+ margin=dict(l=20, r=20, t=30, b=20)
281
+ )
282
+ return fig
283
 
284
+ # =============================================================================
285
+ # 4. PREDICTION HANDLER FUNCTIONS
286
+ # =============================================================================
287
 
288
+ def predict_satisfaction(
289
  gender, cust_type, age, travel_type, flight_class, distance,
290
  wifi, time_conv, ease_booking, gate_loc, food, online_board,
291
  seat_comfort, entertainment, onboard_service, leg_room,
292
  baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
293
  ):
 
 
294
  input_dict = {
295
+ 'Gender': gender, 'Customer Type': cust_type, 'Age': age,
296
+ 'Type of Travel': travel_type, 'Class': flight_class, 'Flight Distance': distance,
297
+ 'Inflight wifi service': wifi, 'Departure/Arrival time convenient': time_conv,
298
+ 'Ease of Online booking': ease_booking, 'Gate location': gate_loc,
299
+ 'Food and drink': food, 'Online boarding': online_board,
300
+ 'Seat comfort': seat_comfort, 'Inflight entertainment': entertainment,
301
+ 'On-board service': onboard_service, 'Leg room service': leg_room,
302
+ 'Baggage handling': baggage, 'Checkin service': checkin,
303
+ 'Inflight service': inflight_service, 'Cleanliness': cleanliness,
304
+ 'Departure Delay in Minutes': dep_delay, 'Arrival Delay in Minutes': arr_delay
 
 
 
 
 
 
 
 
 
 
 
 
305
  }
306
 
307
  input_df = pd.DataFrame([input_dict])
308
 
309
+ # Encode categoricals
310
  for col in CATEGORICAL_COLS:
311
+ input_df[col] = engine.label_encoders[col].transform(input_df[col].astype(str))
312
 
313
+ probs = engine.model.predict_proba(input_df[FEATURE_COLUMNS])[0]
314
+ classes = engine.target_encoder.classes_
315
 
316
+ sat_idx = np.where(classes == 'satisfied')[0][0]
317
+ sat_prob = probs[sat_idx] * 100
318
 
319
+ status_symbol = "😄" if sat_prob >= 50 else "🙁"
320
+ status_label = "SATISFIED" if sat_prob >= 50 else "NEUTRAL / DISSATISFIED"
321
+ status_color = "#10b981" if sat_prob >= 50 else "#ef4444"
322
 
323
+ html_result = f"""
324
+ <div style="background: rgba(30, 41, 59, 0.7); border: 1px solid {status_color}; border-radius: 12px; padding: 20px; text-align: center;">
325
+ <span style="font-size: 2.5rem;">{status_symbol}</span>
326
+ <h2 style="color: {status_color}; margin: 8px 0; font-weight: 800;">{status_label}</h2>
327
+ <p style="color: #94a3b8; margin: 0;">Predicted Customer Sentiment Outcome</p>
328
+ </div>
329
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
 
331
+ gauge_fig = DashboardVisualizer.create_gauge(sat_prob)
 
 
332
 
333
+ radar_dict = {
334
+ 'Wifi': wifi, 'Boarding': online_board, 'Entertainment': entertainment,
335
+ 'Seat Comfort': seat_comfort, 'Cleanliness': cleanliness, 'Service': onboard_service
336
+ }
337
+ radar_fig = DashboardVisualizer.create_radar(radar_dict)
338
+
339
+ return html_result, gauge_fig, radar_fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
 
341
+ def process_batch_csv(file_obj):
342
+ if file_obj is None:
343
+ return None, "Please upload a CSV file.", None
 
344
 
345
+ df = pd.read_csv(file_obj.name)
346
  df_encoded = df.copy()
347
 
 
348
  if 'Arrival Delay in Minutes' in df_encoded.columns:
349
+ df_encoded['Arrival Delay in Minutes'] = df_encoded['Arrival Delay in Minutes'].fillna(df_encoded['Arrival Delay in Minutes'].median())
350
 
351
  for col in CATEGORICAL_COLS:
352
  if col in df_encoded.columns:
353
+ le = engine.label_encoders[col]
354
  df_encoded[col] = df_encoded[col].astype(str).map(lambda s: le.transform([s])[0] if s in le.classes_ else 0)
355
 
356
+ preds = engine.model.predict(df_encoded[FEATURE_COLUMNS])
357
+ pred_labels = engine.target_encoder.inverse_transform(preds)
358
 
359
  df['Predicted_Satisfaction'] = pred_labels
360
 
361
+ output_path = "batch_predictions_output.csv"
362
+ df.to_csv(output_path, index=False)
363
+
364
+ counts = df['Predicted_Satisfaction'].value_counts().reset_index()
365
+ counts.columns = ['Satisfaction', 'Count']
366
 
367
  fig = px.pie(
368
+ counts, names='Satisfaction', values='Count', hole=0.4,
 
 
 
369
  color='Satisfaction',
370
+ color_discrete_map={'satisfied': '#10b981', 'neutral or dissatisfied': '#ef4444'}
371
  )
372
+ fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', font=dict(color="#e2e8f0"), height=300)
 
 
 
373
 
374
  return output_path, df.head(10), fig
375
 
376
+ # =============================================================================
377
+ # 5. GRADIO UI LAYOUT BUILDER
378
+ # =============================================================================
379
 
380
+ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Dark()) as demo:
 
 
 
381
 
382
+ # Header & Title Block
383
+ with gr.Row():
384
+ with gr.Column(scale=4):
385
+ gr.Markdown(
386
+ """
387
+ # <span class="accent-header">✈️ Japan Airlines AI Satisfaction Intelligence</span>
388
+ #### *Modular Machine Learning & Analytics Dashboard for Passenger Survey Optimization*
389
+ """
390
+ )
391
 
392
+ # Top KPI Bar
393
+ with gr.Row():
394
+ gr.HTML(
395
+ f"""
396
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; width: 100%;">
397
+ <div class="kpi-card">
398
+ <div class="kpi-title">Model Accuracy</div>
399
+ <div class="kpi-value">{engine.metrics['accuracy']*100:.2f}%</div>
400
+ </div>
401
+ <div class="kpi-card">
402
+ <div class="kpi-title">F1-Score</div>
403
+ <div class="kpi-value">{engine.metrics['f1']:.2f}</div>
404
+ </div>
405
+ <div class="kpi-card">
406
+ <div class="kpi-title">Precision</div>
407
+ <div class="kpi-value">{engine.metrics['precision']:.2f}</div>
408
+ </div>
409
+ <div class="kpi-card">
410
+ <div class="kpi-title">Algorithm</div>
411
+ <div class="kpi-value" style="font-size:1.3rem; color:#818cf8;">Random Forest</div>
412
+ </div>
413
+ </div>
414
+ """
415
+ )
416
 
417
+ gr.Markdown("<br>")
 
 
 
418
 
 
 
 
 
 
 
 
 
 
419
  with gr.Tabs():
420
 
421
+ # TAB 1: REAL-TIME PREDICTOR
422
+ with gr.TabItem("🎯 Real-Time Predictor"):
 
 
423
  with gr.Row():
424
+ # Inputs Column
425
+ with gr.Column(scale=3):
 
 
 
 
 
 
 
 
426
 
427
+ with gr.Accordion("👤 1. Passenger & Flight Profile", open=True):
428
+ with gr.Row():
429
+ gender = gr.Dropdown(["Female", "Male"], value="Female", label="Gender")
430
+ cust_type = gr.Dropdown(["Loyal Customer", "disloyal Customer"], value="Loyal Customer", label="Customer Loyalty")
431
+ age = gr.Slider(10, 80, value=35, step=1, label="Age")
432
+ with gr.Row():
433
+ travel_type = gr.Dropdown(["Business travel", "Personal Travel"], value="Business travel", label="Travel Type")
434
+ flight_class = gr.Dropdown(["Business", "Eco", "Eco Plus"], value="Business", label="Class")
435
+ distance = gr.Slider(100, 5000, value=1250, step=50, label="Flight Distance (Miles)")
436
+
437
+ with gr.Accordion("⭐ 2. In-Flight Service Ratings", open=False):
438
+ with gr.Row():
439
+ wifi = gr.Slider(0, 5, value=4, step=1, label="Inflight Wifi")
440
+ online_board = gr.Slider(0, 5, value=4, step=1, label="Online Boarding")
441
+ seat_comfort = gr.Slider(0, 5, value=5, step=1, label="Seat Comfort")
442
+ with gr.Row():
443
+ entertainment = gr.Slider(0, 5, value=5, step=1, label="Inflight Entertainment")
444
+ cleanliness = gr.Slider(0, 5, value=4, step=1, label="Cleanliness")
445
+ food = gr.Slider(0, 5, value=3, step=1, label="Food & Drink")
446
+
447
+ with gr.Accordion("🛠️ 3. Logistics, Operations & Delays", open=False):
448
+ with gr.Row():
449
+ onboard_service = gr.Slider(0, 5, value=4, step=1, label="On-board Service")
450
+ leg_room = gr.Slider(0, 5, value=4, step=1, label="Leg Room")
451
+ baggage = gr.Slider(0, 5, value=4, step=1, label="Baggage Handling")
452
+ with gr.Row():
453
+ checkin = gr.Slider(0, 5, value=4, step=1, label="Check-in Service")
454
+ inflight_service = gr.Slider(0, 5, value=4, step=1, label="Inflight Service")
455
+ ease_booking = gr.Slider(0, 5, value=3, step=1, label="Ease of Booking")
456
+ with gr.Row():
457
+ time_conv = gr.Slider(0, 5, value=3, step=1, label="Time Convenience")
458
+ gate_loc = gr.Slider(0, 5, value=3, step=1, label="Gate Location")
459
+ dep_delay = gr.Number(value=0, label="Departure Delay (Min)")
460
+ arr_delay = gr.Number(value=0, label="Arrival Delay (Min)")
461
+
462
+ predict_btn = gr.Button("🚀 Run AI Sentiment Inference", elem_classes=["custom-btn-primary"], size="lg")
463
+
464
+ # Outputs Column
465
+ with gr.Column(scale=2):
466
+ result_card = gr.HTML(
467
+ """
468
+ <div style="background: rgba(30, 41, 59, 0.5); border: 1px dashed rgba(255,255,255,0.2); border-radius: 12px; padding: 25px; text-align: center; color: #94a3b8;">
469
+ Adjust parameters and click <b>Run AI Sentiment Inference</b> to see real-time output.
470
+ </div>
471
+ """
472
+ )
473
  gauge_plot = gr.Plot()
 
474
  radar_plot = gr.Plot()
475
+
476
  predict_btn.click(
477
+ fn=predict_satisfaction,
478
  inputs=[
479
  gender, cust_type, age, travel_type, flight_class, distance,
480
  wifi, time_conv, ease_booking, gate_loc, food, online_board,
481
  seat_comfort, entertainment, onboard_service, leg_room,
482
  baggage, checkin, inflight_service, cleanliness, dep_delay, arr_delay
483
  ],
484
+ outputs=[result_card, gauge_plot, radar_plot]
485
  )
486
 
487
+ # TAB 2: BATCH CSV ANALYTICS
488
+ with gr.TabItem("📊 Batch CSV Analytics"):
489
+ gr.Markdown("### Upload Bulk Survey Dataset")
 
 
490
  with gr.Row():
491
+ file_input = gr.File(label="Upload Passengers CSV", file_types=[".csv"])
492
+ batch_btn = gr.Button("⚡ Execute Batch Processing", elem_classes=["custom-btn-primary"])
493
 
494
  with gr.Row():
495
+ file_output = gr.File(label="Download Labeled CSV")
496
+ batch_pie = gr.Plot(label="Sentiment Distribution")
497
 
498
+ preview_df = gr.DataFrame(label="Sample Batch Predictions Preview")
 
 
499
 
500
  batch_btn.click(
501
+ fn=process_batch_csv,
502
  inputs=[file_input],
503
+ outputs=[file_output, preview_df, batch_pie]
504
  )
505
 
506
+ # TAB 3: MODEL INTELLIGENCE
507
+ with gr.TabItem("📈 Model Intelligence & Explanations"):
508
+ gr.Markdown("### Explainable AI & Performance Diagnostics")
 
 
 
 
 
 
509
  with gr.Row():
510
+ with gr.Column():
511
+ gr.Markdown("#### Key Drivers of Passenger Satisfaction")
512
+ imp_chart = gr.Plot(value=DashboardVisualizer.create_feature_importance())
513
+ with gr.Column():
514
+ gr.Markdown("#### Model Confusion Matrix")
515
+ cm_chart = gr.Plot(value=DashboardVisualizer.create_confusion_matrix_plot())
516
 
517
  if __name__ == "__main__":
518
  demo.launch()