import gradio as gr import pandas as pd import pickle import xgboost as xgb # 1. LOAD THE PICKLE FILE # Ensure 'model.pkl' is uploaded to your Hugging Face Space files with open("model.pkl", "rb") as f: model = pickle.load(f) # 2. FULL FEATURE LIST (Ordered exactly as per your screenshot) ALL_FEATURES = [ 'InternetService_1', 'Contract_0', 'tenure', 'InternetService_0', 'Contract_1', 'MultipleLines_1', 'PaperlessBilling_0', 'StreamingMovies_1', 'SeniorCitizen', 'PaymentMethod_0', 'TotalCharges', 'StreamingTV_1', 'MonthlyCharges', 'PaymentMethod_1', 'OnlineSecurity_1', 'TechSupport_1', 'MultipleLines_0', 'PhoneService_0', 'OnlineBackup_0', 'OnlineSecurity_0', 'StreamingMovies_0', 'StreamingTV_0', 'DeviceProtection_0', 'OnlineBackup_1', 'DeviceProtection_1', 'TechSupport_0' ] def predict_churn(tenure, internet_service_fiber, contract_month_to_month): # Initialize all 26 features to 0 input_dict = {feature: [0.0] for feature in ALL_FEATURES} # Update the 3 features the user interacts with input_dict['tenure'] = [float(tenure)] input_dict['InternetService_1'] = [1.0 if internet_service_fiber else 0.0] input_dict['Contract_0'] = [1.0 if contract_month_to_month else 0.0] # IMPORTANT: Set sensible defaults for key continuous variables # if they aren't provided by the user (prevents skewed results) input_dict['MonthlyCharges'] = [65.0] input_dict['TotalCharges'] = [2000.0] # Create DataFrame and ensure column order matches ALL_FEATURES exactly input_data = pd.DataFrame(input_dict)[ALL_FEATURES] # 3. RUN PREDICTION # We use predict_proba to get the confidence level prediction_proba = model.predict_proba(input_data)[0][1] prediction = "Churn Risk" if prediction_proba > 0.5 else "Stay" return f"Result: {prediction} (Confidence: {prediction_proba:.2%})" # 4. DEFINE THE UI demo = gr.Interface( fn=predict_churn, inputs=[ gr.Slider(0, 72, label="Tenure (Months)", value=12), gr.Checkbox(label="Internet Service: Fiber Optic?"), gr.Checkbox(label="Contract: Month-to-Month?") ], outputs="text", title="Telco Churn Prediction Agent", description="Using the model's top drivers to assess customer loyalty." ) if __name__ == "__main__": demo.launch()