Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557import gradio as grimport pandas as pdimport numpy as npimport timeimport tempfilefrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import LabelEncoder, StandardScaler# --------------------------------------------------------------------# 1. MODEL ENGINE & DATASET INITIALIZATION# --------------------------------------------------------------------def build_pipeline():np.random.seed(42)n_samples = 2500genders = np.random.choice(['Female', 'Male'], n_samples)customer_types = np.random.choice(['Loyal Customer', 'disloyal Customer'], n_samples, p=[0.82, 0.18])travel_types = np.random.choice(['Business travel', 'Personal Travel'], n_samples, p=[0.69, 0.31])classes = np.random.choice(['Business', 'Eco', 'Eco Plus'], n_samples, p=[0.48, 0.44, 0.08])ages = np.random.randint(18, 75, n_samples)distances = np.random.randint(100, 4000, n_samples)wifi = np.random.randint(1, 6, n_samples)booking = np.random.randint(1, 6, n_samples)food = np.random.randint(1, 6, n_samples)boarding = np.random.randint(1, 6, n_samples)comfort = np.random.randint(1, 6, n_samples)entertainment = np.random.randint(1, 6, n_samples)onboard = np.random.randint(1, 6, n_samples)legroom = np.random.randint(1, 6, n_samples)baggage = np.random.randint(1, 6, n_samples)checkin = np.random.randint(1, 6, n_samples)inflight = np.random.randint(1, 6, n_samples)cleanliness = np.random.randint(1, 6, n_samples)dep_delay = np.random.exponential(scale=14, size=n_samples).astype(int)arr_delay = dep_delay + np.random.randint(-4, 8, size=n_samples)arr_delay = np.clip(arr_delay, 0, None)raw_score = (wifi * 0.22 + boarding * 0.25 + comfort * 0.18 +entertainment * 0.15 + legroom * 0.12 + (classes == 'Business') * 0.5 -(dep_delay / 25) * 0.4)satisfaction = np.where(raw_score > 2.8, 1, 0)df = pd.DataFrame({'Gender': genders,'Customer_Type': customer_types,'Age': ages,'Type_of_Travel': travel_types,'Class': classes,'Flight_Distance': distances,'Inflight_wifi_service': wifi,'Ease_of_Online_booking': booking,'Food_and_drink': food,'Online_boarding': boarding,'Seat_comfort': comfort,'Inflight_entertainment': entertainment,'Onboard_service': onboard,'Leg_room_service': legroom,'Baggage_handling': baggage,'Checkin_service': checkin,'Inflight_service': inflight,'Cleanliness': cleanliness,'Departure_Delay_in_Minutes': dep_delay,'Arrival_Delay_in_Minutes': arr_delay,'satisfaction': satisfaction})encoders = {}df_enc = df.copy()for col in ['Gender', 'Customer_Type', 'Type_of_Travel', 'Class']:le = LabelEncoder()df_enc[col] = le.fit_transform(df[col])encoders[col] = leX = df_enc.drop('satisfaction', axis=1)y = df_enc['satisfaction']scaler = StandardScaler()X_scaled = scaler.fit_transform(X)rf = RandomForestClassifier(n_estimators=80, max_depth=10, random_state=42)rf.fit(X, y)lr = LogisticRegression(max_iter=500)lr.fit(X_scaled, y)gb = GradientBoostingClassifier(n_estimators=80, random_state=42)gb.fit(X, y)return {'rf': rf, 'lr': lr, 'gb': gb,'encoders': encoders, 'scaler': scaler,'feature_names': list(X.columns),'df': df}pipeline = build_pipeline()# --------------------------------------------------------------------# 2. INTERACTIVE SIMULATION INFERENCE LOGIC# --------------------------------------------------------------------def run_single_inference(gender, cust_type, age, travel_type, flight_class, distance,wifi, booking, food, boarding, comfort, entertainment,onboard, legroom, baggage, checkin, inflight, cleanliness,dep_delay, arr_delay, model_choice="Random Forest"):data = pd.DataFrame([{'Gender': pipeline['encoders']['Gender'].transform([gender])[0],'Customer_Type': pipeline['encoders']['Customer_Type'].transform([cust_type])[0],'Age': age,'Type_of_Travel': pipeline['encoders']['Type_of_Travel'].transform([travel_type])[0],'Class': pipeline['encoders']['Class'].transform([flight_class])[0],'Flight_Distance': distance,'Inflight_wifi_service': wifi,'Ease_of_Online_booking': booking,'Food_and_drink': food,'Online_boarding': boarding,'Seat_comfort': comfort,'Inflight_entertainment': entertainment,'Onboard_service': onboard,'Leg_room_service': legroom,'Baggage_handling': baggage,'Checkin_service': checkin,'Inflight_service': inflight,'Cleanliness': cleanliness,'Departure_Delay_in_Minutes': dep_delay,'Arrival_Delay_in_Minutes': arr_delay}])start_t = time.time()if model_choice == "Logistic Regression":X_scaled = pipeline['scaler'].transform(data)prob = pipeline['lr'].predict_proba(X_scaled)[0][1]elif model_choice == "Gradient Boosting":prob = pipeline['gb'].predict_proba(data)[0][1]else:prob = pipeline['rf'].predict_proba(data)[0][1]latency = (time.time() - start_t) * 1000is_satisfied = prob >= 0.5status_str = "SATISFIED" if is_satisfied else "NEUTRAL / DISSATISFIED"emoji = "😊" if is_satisfied else "🙁"color = "#10B981" if is_satisfied else "#EF4444"bg_gradient = "linear-gradient(135deg, rgba(16,185,129,0.15) 0%, rgba(10,13,20,0.8) 100%)" if is_satisfied else "linear-gradient(135deg, rgba(239,68,68,0.15) 0%, rgba(10,13,20,0.8) 100%)"return f"""<div style="background: {bg_gradient}; border: 1px solid {color}; border-radius: 16px; padding: 24px; text-align: center; color: #FFFFFF;"><div style="font-size: 54px; margin-bottom: 8px;">{emoji}</div><div style="font-size: 13px; text-transform: uppercase; letter-spacing: 2px; color: {color}; font-weight: 700;">PREDICTED STATUS</div><div style="font-size: 28px; font-weight: 800; color: #FFFFFF; margin: 4px 0 16px 0;">{status_str}</div><div style="display: flex; justify-content: space-around; background: rgba(255,255,255,0.05); padding: 12px; border-radius: 12px; margin-top: 12px;"><div><div style="font-size: 11px; color: #94A3B8;">Confidence</div><div style="font-size: 20px; font-weight: 700; color: {color};">{prob*100:.1f}%</div></div><div style="border-left: 1px solid rgba(255,255,255,0.1); padding-left: 12px;"><div style="font-size: 11px; color: #94A3B8;">Latency</div><div style="font-size: 20px; font-weight: 700; color: #6366F1;">{latency:.2f} ms</div></div></div></div>"""# --------------------------------------------------------------------# 3. DYNAMIC EXECUTIVE ANALYTICS (Tied to Active Dataset State)# --------------------------------------------------------------------def execute_structured_analytics(analysis_mode, active_df):df = active_df if active_df is not None else pipeline['df']touchpoint_cols = [c for c in ['Inflight_wifi_service', 'Ease_of_Online_booking', 'Food_and_drink','Online_boarding', 'Seat_comfort', 'Inflight_entertainment','Onboard_service', 'Leg_room_service', 'Baggage_handling','Checkin_service', 'Inflight_service', 'Cleanliness'] if c in df.columns]sat_col = 'satisfaction' if 'satisfaction' in df.columns else 'Predicted_Satisfaction_Binary'formatted_names = {'Inflight_wifi_service': 'Inflight Wifi', 'Ease_of_Online_booking': 'Online Booking','Food_and_drink': 'Food & Drink', 'Online_boarding': 'Online Boarding','Seat_comfort': 'Seat Comfort', 'Inflight_entertainment': 'Inflight Entertainment','Onboard_service': 'Onboard Service', 'Leg_room_service': 'Leg Room Service','Baggage_handling': 'Baggage Handling', 'Checkin_service': 'Check-in Service','Inflight_service': 'Inflight Service', 'Cleanliness': 'Cleanliness'}# 1. OVERALL TOUCHPOINT RATING BREAKDOWNif "Overall Touchpoint" in analysis_mode:means = df[touchpoint_cols].mean().sort_values(ascending=False)top_3 = means.head(3)mid_6 = means.iloc[3:9]low_3 = means.tail(3)high_str = "".join([f"<li style='margin-bottom:4px;'><b>{formatted_names.get(k, k)}</b>: <span style='color:#10B981; font-weight:bold;'>{v:.2f} / 5.00</span></li>" for k, v in top_3.items()])avg_str = "".join([f"<li style='margin-bottom:4px;'><b>{formatted_names.get(k, k)}</b>: <span style='color:#38BDF8; font-weight:bold;'>{v:.2f} / 5.00</span></li>" for k, v in mid_6.items()])low_str = "".join([f"<li style='margin-bottom:4px;'><b>{formatted_names.get(k, k)}</b>: <span style='color:#EF4444; font-weight:bold;'>{v:.2f} / 5.00</span></li>" for k, v in low_3.items()])card_html = f"""<div style="background: #121824; border: 1px solid #10B981; border-radius: 14px; padding: 20px; color: #FFFFFF;"><div style="font-size: 11px; color: #10B981; font-weight: 700; letter-spacing: 1.5px;">ACTIVE DATASET ANALYSIS ({len(df):,} RECORDS)</div><h3 style="margin: 6px 0 16px 0; font-size: 20px;">Overall Touchpoint Rating Statistics</h3><div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px;"><div style="background: #1E293B; padding: 14px; border-radius: 10px; border-top: 3px solid #10B981;"><div style="font-size: 12px; color: #10B981; font-weight: 700; margin-bottom: 8px;">🟢 High Performing</div><ul style="padding-left: 18px; margin: 0; font-size: 12px; color: #CBD5E1;">{high_str}</ul></div><div style="background: #1E293B; padding: 14px; border-radius: 10px; border-top: 3px solid #38BDF8;"><div style="font-size: 12px; color: #38BDF8; font-weight: 700; margin-bottom: 8px;">🔵 Average Performing</div><ul style="padding-left: 18px; margin: 0; font-size: 12px; color: #CBD5E1;">{avg_str}</ul></div><div style="background: #1E293B; padding: 14px; border-radius: 10px; border-top: 3px solid #EF4444;"><div style="font-size: 12px; color: #EF4444; font-weight: 700; margin-bottom: 8px;">🔴 Priority Improvement</div><ul style="padding-left: 18px; margin: 0; font-size: 12px; color: #CBD5E1;">{low_str}</ul></div></div></div>"""return "🟢 **Analytics Computed on Active Dataset State**", card_html# 2. HIGH-YIELD & REVENUE SEGMENTSelif "High-Yield" in analysis_mode:biz_sat = (df[df['Class'] == 'Business'][sat_col].mean() * 100) if 'Class' in df.columns else 0eco_sat = (df[df['Class'] == 'Eco'][sat_col].mean() * 100) if 'Class' in df.columns else 0loyal_sat = (df[df['Customer_Type'] == 'Loyal Customer'][sat_col].mean() * 100) if 'Customer_Type' in df.columns else 0biz_travel_sat = (df[df['Type_of_Travel'] == 'Business travel'][sat_col].mean() * 100) if 'Type_of_Travel' in df.columns else 0card_html = f"""<div style="background: #121824; border: 1px solid #38BDF8; border-radius: 14px; padding: 20px; color: #FFFFFF;"><div style="font-size: 11px; color: #38BDF8; font-weight: 700; letter-spacing: 1.5px;">SEGMENT PERFORMANCE ({len(df):,} RECORDS)</div><h3 style="margin: 6px 0 16px 0; font-size: 20px;">Promising Revenue Avenues & High-Yield Segments</h3><div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 16px;"><div style="background: #1E293B; padding: 12px; border-radius: 10px; text-align: center;"><div style="font-size: 11px; color: #94A3B8;">Business Class Sat.</div><div style="font-size: 22px; font-weight: 800; color: #10B981;">{biz_sat:.1f}%</div></div><div style="background: #1E293B; padding: 12px; border-radius: 10px; text-align: center;"><div style="font-size: 11px; color: #94A3B8;">Economy Class Sat.</div><div style="font-size: 22px; font-weight: 800; color: #F59E0B;">{eco_sat:.1f}%</div></div><div style="background: #1E293B; padding: 12px; border-radius: 10px; text-align: center;"><div style="font-size: 11px; color: #94A3B8;">Business Travel Sat.</div><div style="font-size: 22px; font-weight: 800; color: #38BDF8;">{biz_travel_sat:.1f}%</div></div><div style="background: #1E293B; padding: 12px; border-radius: 10px; text-align: center;"><div style="font-size: 11px; color: #94A3B8;">Loyal Customer Sat.</div><div style="font-size: 22px; font-weight: 800; color: #6366F1;">{loyal_sat:.1f}%</div></div></div></div>"""return "🟢 **Revenue Segment Analysis Updated**", card_html# 3. CRITICAL IMPROVEMENT & CHURN DRIVERSelif "Critical Improvement" in analysis_mode:sat_means = df[df[sat_col] == 1][touchpoint_cols].mean()dissat_means = df[df[sat_col] == 0][touchpoint_cols].mean()gaps = (sat_means - dissat_means).sort_values(ascending=False)top_driver = gaps.index[0] if len(gaps) > 0 else touchpoint_cols[0]second_driver = gaps.index[1] if len(gaps) > 1 else touchpoint_cols[1]card_html = f"""<div style="background: #121824; border: 1px solid #EF4444; border-radius: 14px; padding: 20px; color: #FFFFFF;"><div style="font-size: 11px; color: #EF4444; font-weight: 700; letter-spacing: 1.5px;">CHURN DIAGNOSTICS ({len(df):,} RECORDS)</div><h3 style="margin: 6px 0 16px 0; font-size: 20px;">Primary Drivers of Passenger Dissatisfaction</h3><div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;"><div style="background: #1E293B; padding: 14px; border-radius: 10px;"><div style="font-size: 12px; color: #F59E0B; font-weight: 700; margin-bottom: 6px;">🎯 Primary Churn Driver</div><div style="font-size: 18px; font-weight: 800; color: #FFFFFF;">{formatted_names.get(top_driver, top_driver)}</div><div style="font-size: 12px; color: #94A3B8; margin-top: 4px;">Satisfaction gap: <b style="color:#EF4444;">{gaps.iloc[0]:.2f} points</b>.</div></div><div style="background: #1E293B; padding: 14px; border-radius: 10px;"><div style="font-size: 12px; color: #F59E0B; font-weight: 700; margin-bottom: 6px;">🎯 Secondary Churn Driver</div><div style="font-size: 18px; font-weight: 800; color: #FFFFFF;">{formatted_names.get(second_driver, second_driver)}</div><div style="font-size: 12px; color: #94A3B8; margin-top: 4px;">Satisfaction gap: <b style="color:#EF4444;">{gaps.iloc[1]:.2f} points</b>.</div></div></div></div>"""return "🟢 **Churn Drivers Updated**", card_html# 4. STRATEGIC CONCLUSIONS & ROADMAPelse:sat_pct = df[sat_col].mean() * 100card_html = f"""<div style="background: #121824; border: 1px solid #6366F1; border-radius: 14px; padding: 20px; color: #FFFFFF;"><div style="font-size: 11px; color: #6366F1; font-weight: 700; letter-spacing: 1.5px;">EXECUTIVE SUMMARY</div><h3 style="margin: 6px 0 16px 0; font-size: 20px;">Strategic Takeaways from Current Dataset</h3><div style="font-size: 13px; color: #CBD5E1; line-height: 1.6;"><p>Analyzed <b>{len(df):,} survey records</b>. Overall dataset satisfaction benchmark is <b style="color:#6366F1;">{sat_pct:.1f}%</b>.</p></div></div>"""return "🟢 **Strategic Blueprint Updated**", card_html# --------------------------------------------------------------------# 4. RECTIFIED BULK PASSENGER SURVEY CSV SCORING ENGINE# --------------------------------------------------------------------def process_batch_csv(file_obj, current_analytics_mode):if file_obj is None:return None, "<div style='color:#EF4444;'>Please upload a valid CSV file.</div>", None, None, "⚠️ Upload required.", ""try:df_raw = pd.read_csv(file_obj.name)df_proc = df_raw.copy()# Header standardization & mappingdf_proc.columns = df_proc.columns.str.strip().str.replace(' ', '_').str.replace('-', '_')col_mappings = {'Inflight_wifi': 'Inflight_wifi_service', 'Wifi': 'Inflight_wifi_service','Ease_of_online_booking': 'Ease_of_Online_booking', 'Online_booking': 'Ease_of_Online_booking','Food_and_Drink': 'Food_and_drink', 'Seat_Comfort': 'Seat_comfort','Departure_Delay': 'Departure_Delay_in_Minutes', 'Arrival_Delay': 'Arrival_Delay_in_Minutes'}df_proc.rename(columns=col_mappings, inplace=True)# Categorical encoding handlingfor col in ['Gender', 'Customer_Type', 'Type_of_Travel', 'Class']:if col in df_proc.columns:le = pipeline['encoders'][col]df_proc[col] = df_proc[col].astype(str).str.strip()df_proc[col] = df_proc[col].map(lambda s: s if s in le.classes_ else le.classes_[0])df_proc[col] = le.transform(df_proc[col])else:df_proc[col] = 0# Fill missing features dynamicallyfeatures = pipeline['feature_names']for f in features:if f not in df_proc.columns:df_proc[f] = 3 if any(k in f.lower() for k in ['service', 'wifi', 'comfort', 'boarding']) else 0else:df_proc[f] = pd.to_numeric(df_proc[f], errors='coerce').fillna(3)X_batch = df_proc[features]preds = pipeline['rf'].predict(X_batch)probs = pipeline['rf'].predict_proba(X_batch)[:, 1]# Output dataframe generationdf_out = df_raw.copy()df_out['Predicted_Satisfaction_Binary'] = predsdf_out['Predicted_Satisfaction'] = np.where(preds == 1, 'Satisfied', 'Neutral/Dissatisfied')df_out['Satisfaction_Probability'] = np.round(probs, 4)satisfied_cnt = int((preds == 1).sum())total_cnt = len(preds)sat_rate = (satisfied_cnt / total_cnt) * 100 if total_cnt > 0 else 0summary_html = f"""<div style="display: flex; gap: 16px; margin-bottom: 16px;"><div style="flex: 1; background: #121824; border: 1px solid #1F293D; padding: 16px; border-radius: 12px; text-align: center;"><div style="font-size: 12px; color: #94A3B8;">Processed CSV Records</div><div style="font-size: 28px; font-weight: 800; color: #FFFFFF;">{total_cnt:,}</div></div><div style="flex: 1; background: #121824; border: 1px solid #10B981; padding: 16px; border-radius: 12px; text-align: center;"><div style="font-size: 12px; color: #94A3B8;">Calculated Satisfaction Rate</div><div style="font-size: 28px; font-weight: 800; color: #10B981;">{sat_rate:.1f}%</div></div></div>"""# Save temporary output CSV for downloadtemp_out = tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", newline="", encoding="utf-8")df_out.to_csv(temp_out.name, index=False)temp_out.close()# Trigger recalculation of executive analytics on uploaded CSV dataexec_status, exec_card = execute_structured_analytics(current_analytics_mode, df_out)return df_out.head(20), summary_html, temp_out.name, df_out, exec_status, exec_cardexcept Exception as e:err_html = f"<div style='color:#EF4444; font-weight: bold;'>Error scoring CSV: {str(e)}</div>"return None, err_html, None, None, "❌ Execution Error", ""# --------------------------------------------------------------------# 5. GRADIO APPLICATION LAYOUT# --------------------------------------------------------------------custom_css = """body, .gradio-container {background-color: #0A0D14 !important;font-family: 'Inter', sans-serif !important;color: #F8FAFC !important;}.gr-box, .gr-card, .gr-panel {background: #121824 !important;border: 1px solid #1F293D !important;border-radius: 14px !important;}.gr-button-primary {background: linear-gradient(135deg, #6366F1 0%, #4F46E5 100%) !important;border: none !important;border-radius: 10px !important;font-weight: 600 !important;color: #FFFFFF !important;}"""with gr.Blocks(title="Unified Airline CX Platform", css=custom_css) as app:# GLOBAL STATE HOLDER FOR ACTIVE DATASETactive_dataset_state = gr.State(value=pipeline['df'])gr.HTML("""<div style="padding: 12px 0 24px 0; border-bottom: 1px solid #1F293D; margin-bottom: 24px;"><div style="font-size: 11px; text-transform: uppercase; letter-spacing: 2px; color: #6366F1; font-weight: 700;">CONNECTED DATA PLATFORM</div><h1 style="margin: 4px 0 0 0; font-size: 26px; font-weight: 800; color: #FFFFFF;">Passenger Survey & Executive Analytics System</h1></div>""")# ----------------------------------------------------------------# EXECUTIVE ANALYTICS SELECTOR (REACTIONARY TO DATASET STATE)# ----------------------------------------------------------------with gr.Group():gr.Markdown("### 📊 Structured Executive Analytics Selector")with gr.Row():analytics_mode_in = gr.Radio(choices=["📊 Overall Touchpoint Rating Breakdown (High, Average & Low Areas)","🚀 High-Yield & Revenue-Generating Segment Analysis","🛠️ Critical Improvement Areas & Churn Drivers","💡 Strategic Conclusions & Executive Blueprint"],value="📊 Overall Touchpoint Rating Breakdown (High, Average & Low Areas)",label="Select Analytics Focus area",scale=4)analytics_btn = gr.Button("Re-Run Analytics", variant="primary", scale=1)analytics_status = gr.Markdown("🟢 *Ready. Analytics are dynamically connected to the active survey dataset.*")analytics_output_card = gr.HTML()gr.Markdown("---")# ----------------------------------------------------------------# TABS: SIMULATOR & BATCH CSV ENGINE# ----------------------------------------------------------------with gr.Tabs():# TAB 1: PASSENGER EXPERIENCE SIMULATORwith gr.TabItem("🎯 Interactive Simulator"):with gr.Row():with gr.Column(scale=2):gr.Markdown("#### Passenger Profile & Survey Score Inputs")with gr.Row():gender_in = gr.Dropdown(['Female', 'Male'], value='Female', label="Gender")cust_type_in = gr.Dropdown(['Loyal Customer', 'disloyal Customer'], value='Loyal Customer', label="Customer Type")travel_in = gr.Dropdown(['Business travel', 'Personal Travel'], value='Business travel', label="Type of Travel")class_in = gr.Dropdown(['Business', 'Eco', 'Eco Plus'], value='Business', label="Class")with gr.Row():age_in = gr.Slider(18, 80, value=38, step=1, label="Age")dist_in = gr.Slider(100, 4000, value=1250, step=50, label="Flight Distance (mi)")dep_delay_in = gr.Slider(0, 180, value=15, step=5, label="Departure Delay (min)")arr_delay_in = gr.Slider(0, 180, value=10, step=5, label="Arrival Delay (min)")with gr.Row():wifi_in = gr.Slider(1, 5, value=4, step=1, label="Inflight Wifi")boarding_in = gr.Slider(1, 5, value=4, step=1, label="Online Boarding")comfort_in = gr.Slider(1, 5, value=4, step=1, label="Seat Comfort")entertainment_in = gr.Slider(1, 5, value=4, step=1, label="Inflight Entertainment")with gr.Row():legroom_in = gr.Slider(1, 5, value=4, step=1, label="Leg Room")onboard_in = gr.Slider(1, 5, value=4, step=1, label="On-board Service")cleanliness_in = gr.Slider(1, 5, value=4, step=1, label="Cleanliness")booking_in = gr.Slider(1, 5, value=3, step=1, label="Online Booking")with gr.Accordion("Additional Service Touchpoints", open=False):with gr.Row():food_in = gr.Slider(1, 5, value=3, step=1, label="Food & Drink")baggage_in = gr.Slider(1, 5, value=4, step=1, label="Baggage Handling")checkin_in = gr.Slider(1, 5, value=4, step=1, label="Check-in Service")inflight_in = gr.Slider(1, 5, value=4, step=1, label="Inflight Service")model_sel = gr.Radio(["Random Forest", "Gradient Boosting", "Logistic Regression"], value="Random Forest", label="Target ML Model")sim_btn = gr.Button("Run Real-Time Prediction", variant="primary")with gr.Column(scale=1):gr.Markdown("#### Prediction Output")sim_out_html = gr.HTML("<div style='color:#64748B;'>Configure inputs to run simulation.</div>")# TAB 2: BULK SURVEY CSV SCORING ENGINEwith gr.TabItem("📊 Bulk Passenger Survey CSV Scoring Engine"):gr.Markdown("#### Batch CSV Ingestion & Global Analytics Sync")with gr.Row():with gr.Column(scale=1):csv_file_in = gr.File(label="Upload Customer Survey CSV File", file_types=[".csv"])batch_proc_btn = gr.Button("Score CSV & Update Global Analytics", variant="primary")csv_file_out = gr.File(label="Download Scored Results CSV")with gr.Column(scale=2):batch_summary_html = gr.HTML("<div style='color:#64748B;'>Upload a CSV to process batch satisfaction scores.</div>")batch_dataframe_out = gr.Dataframe(label="Scored Passenger Preview (Top 20 Records)")# ----------------------------------------------------------------# EVENT HANDLERS# ----------------------------------------------------------------sim_inputs = [gender_in, cust_type_in, age_in, travel_in, class_in, dist_in,wifi_in, booking_in, food_in, boarding_in, comfort_in, entertainment_in,onboard_in, legroom_in, baggage_in, checkin_in, inflight_in, cleanliness_in,dep_delay_in, arr_delay_in, model_sel]sim_btn.click(fn=run_single_inference,inputs=sim_inputs,outputs=sim_out_html)# Executive Analytics Button & Selection Handlersanalytics_btn.click(fn=execute_structured_analytics,inputs=[analytics_mode_in, active_dataset_state],outputs=[analytics_status, analytics_output_card])analytics_mode_in.change(fn=execute_structured_analytics,inputs=[analytics_mode_in, active_dataset_state],outputs=[analytics_status, analytics_output_card])# CSV Scoring Event -> Automatically Updates Global Active Dataset State & Executive Analyticsbatch_proc_btn.click(fn=process_batch_csv,inputs=[csv_file_in, analytics_mode_in],outputs=[batch_dataframe_out,batch_summary_html,csv_file_out,active_dataset_state,analytics_status,analytics_output_card])# Initial Load Triggerapp.load(fn=execute_structured_analytics,inputs=[analytics_mode_in, active_dataset_state],outputs=[analytics_status, analytics_output_card])if __name__ == "__main__":app.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177import osimport pandas as pdimport numpy as npimport gradio as grfrom sklearn.ensemble import HistGradientBoostingClassifierfrom sklearn.preprocessing import OrdinalEncoder# Identify feature schemaCAT_COLS = ['Gender', 'Customer Type', 'Type of Travel', 'Class']NUM_COLS = ['Age', 'Flight Distance', 'Inflight wifi service','Departure/Arrival time convenient', 'Ease of Online booking','Gate location', 'Food and drink', 'Online boarding', 'Seat comfort','Inflight entertainment', 'On-board service', 'Leg room service','Baggage handling', 'Checkin service', 'Inflight service','Cleanliness', 'Departure Delay in Minutes', 'Arrival Delay in Minutes']FEATURES = CAT_COLS + NUM_COLS# Global Model & Encoder Initializationencoder = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)model = HistGradientBoostingClassifier(random_state=42)def train_baseline_model():"""Trains baseline model if train.csv is available locally."""if os.path.exists("train.csv"):train_df = pd.read_csv("train.csv")X = train_df[FEATURES].copy()y = (train_df["satisfaction"] == "satisfied").astype(int)X[CAT_COLS] = encoder.fit_transform(X[CAT_COLS])model.fit(X, y)return "Model trained successfully on train.csv."else:# Fallback dummy fitting if dataset is uploaded laterdummy_x = pd.DataFrame([{c: "Male" if c in CAT_COLS else 3 for c in FEATURES}])dummy_x[CAT_COLS] = encoder.fit_transform(dummy_x[CAT_COLS])model.fit(dummy_x, [1])return "Initialized with default schema. Upload batch files to score."status_msg = train_baseline_model()# --- Real-Time Simulation Engine ---def simulate_operational_change(gender, customer_type, type_of_travel, flight_class, age, flight_dist,wifi, dep_arr_time, ease_booking, gate, food_drink, online_boarding,seat_comfort, entertainment, onboard_service, leg_room, baggage,checkin, inflight_service, cleanliness, dep_delay, arr_delay):input_data = pd.DataFrame([{'Gender': gender,'Customer Type': customer_type,'Type of Travel': type_of_travel,'Class': flight_class,'Age': age,'Flight Distance': flight_dist,'Inflight wifi service': wifi,'Departure/Arrival time convenient': dep_arr_time,'Ease of Online booking': ease_booking,'Gate location': gate,'Food and drink': food_drink,'Online boarding': online_boarding,'Seat comfort': seat_comfort,'Inflight entertainment': entertainment,'On-board service': onboard_service,'Leg room service': leg_room,'Baggage handling': baggage,'Checkin service': checkin,'Inflight service': inflight_service,'Cleanliness': cleanliness,'Departure Delay in Minutes': dep_delay,'Arrival Delay in Minutes': arr_delay}])input_data[CAT_COLS] = encoder.transform(input_data[CAT_COLS])satisfaction_prob = model.predict_proba(input_data)[0][1]prob_pct = round(satisfaction_prob * 100, 2)status_label = "Satisfied" if satisfaction_prob >= 0.5 else "Neutral / Dissatisfied"return f"{prob_pct}% ({status_label})"# --- Batch Scoring Engine (ETL) ---def score_batch_csv(file_obj):if file_obj is None:return "Please upload a valid CSV file.", Nonedf = pd.read_csv(file_obj.name)# Preprocessing & schema validationdrop_cols = [c for c in ['Unnamed: 0', 'id'] if c in df.columns]X_batch = df.drop(columns=drop_cols)# Align missing columns if anyfor col in FEATURES:if col not in X_batch.columns:X_batch[col] = 0 if col in NUM_COLS else "Male"X_eval = X_batch[FEATURES].copy()X_eval[CAT_COLS] = encoder.transform(X_eval[CAT_COLS])probs = model.predict_proba(X_eval)[:, 1]df['satisfaction_probability'] = np.round(probs, 4)df['predicted_satisfaction'] = np.where(probs >= 0.5, 'satisfied', 'neutral or dissatisfied')output_path = "scored_passengers_batch.csv"df.to_csv(output_path, index=False)return df.head(10), output_path# --- Gradio Interface ---with gr.Blocks(title="Flexible Batch Scoring & Operational Simulator") as app:gr.Markdown("# Flexible Multi-Dataset Batch Scoring Engine & Operational Simulator")gr.Markdown(f"**System Status:** {status_msg}")with gr.Tab("Real-Time Operational Simulator"):gr.Markdown("### Simulate Operational Changes on Satisfaction Probability")with gr.Row():with gr.Column():gr.Markdown("**Passenger Profile & Flight Info**")gender = gr.Dropdown(['Male', 'Female'], value='Male', label='Gender')customer_type = gr.Dropdown(['Loyal Customer', 'disloyal Customer'], value='Loyal Customer', label='Customer Type')type_of_travel = gr.Dropdown(['Personal Travel', 'Business travel'], value='Business travel', label='Type of Travel')flight_class = gr.Dropdown(['Business', 'Eco', 'Eco Plus'], value='Business', label='Class')age = gr.Slider(7, 85, value=39, step=1, label='Age')flight_dist = gr.Slider(31, 5000, value=1200, step=10, label='Flight Distance')dep_delay = gr.Number(value=0, label='Departure Delay (Minutes)')arr_delay = gr.Number(value=0, label='Arrival Delay (Minutes)')with gr.Column():gr.Markdown("**Operational & Service Ratings (0-5)**")wifi = gr.Slider(0, 5, value=3, step=1, label='Inflight WiFi Service')seat_comfort = gr.Slider(0, 5, value=4, step=1, label='Seat Comfort')entertainment = gr.Slider(0, 5, value=4, step=1, label='Inflight Entertainment')onboard_service = gr.Slider(0, 5, value=3, step=1, label='On-board Service')leg_room = gr.Slider(0, 5, value=3, step=1, label='Leg Room Service')cleanliness = gr.Slider(0, 5, value=4, step=1, label='Cleanliness')online_boarding = gr.Slider(0, 5, value=3, step=1, label='Online Boarding')baggage = gr.Slider(1, 5, value=4, step=1, label='Baggage Handling')# Additional lower-impact operational fieldsdep_arr_time = gr.Slider(0, 5, value=3, step=1, visible=False)ease_booking = gr.Slider(0, 5, value=3, step=1, visible=False)gate = gr.Slider(0, 5, value=3, step=1, visible=False)food_drink = gr.Slider(0, 5, value=3, step=1, visible=False)checkin = gr.Slider(0, 5, value=3, step=1, visible=False)inflight_service = gr.Slider(0, 5, value=4, step=1, visible=False)sim_btn = gr.Button("Simulate Operational Change", variant="primary")sim_output = gr.Textbox(label="Predicted Passenger Satisfaction Probability")sim_btn.click(fn=simulate_operational_change,inputs=[gender, customer_type, type_of_travel, flight_class, age, flight_dist,wifi, dep_arr_time, ease_booking, gate, food_drink, online_boarding,seat_comfort, entertainment, onboard_service, leg_room, baggage,checkin, inflight_service, cleanliness, dep_delay, arr_delay],outputs=sim_output)with gr.Tab("Multi-Dataset Batch Scoring (ETL)"):gr.Markdown("### Upload CSV (train.csv / test.csv / custom batch) for Pipeline Scoring")file_input = gr.File(label="Upload CSV Dataset", file_types=[".csv"])score_btn = gr.Button("Process Batch & Generate Scores", variant="primary")preview_table = gr.Dataframe(label="Batch Results Preview (Top 10 Rows)")download_output = gr.File(label="Download Full Scored CSV")score_btn.click(fn=score_batch_csv,inputs=file_input,outputs=[preview_table, download_output])app.launch()
app.py+158-538