""" Preprocessing for Customer Churn Predictor. Converts a raw customer record (matching Telco-style schema) into the one-hot encoded feature vector the trained model expects. """ import json import pandas as pd with open("schema.json") as f: SCHEMA = json.load(f) MODEL_COLUMNS = SCHEMA["model_columns"] BINARY_MAP = {"Yes": 1, "No": 0} BINARY_COLS = ["Partner", "Dependents", "PhoneService", "PaperlessBilling"] MULTI_CAT_COLS = [ "gender", "MultipleLines", "InternetService", "OnlineSecurity", "OnlineBackup", "DeviceProtection", "TechSupport", "StreamingTV", "StreamingMovies", "Contract", "PaymentMethod", ] def preprocess(record: dict) -> pd.DataFrame: """ record: dict of raw customer fields (see schema.json -> raw_input_schema) returns: single-row DataFrame aligned to MODEL_COLUMNS, ready for model.predict_proba """ df = pd.DataFrame([record]) # TotalCharges: treat blank/missing as 0 (new customer, tenure 0 case) df["TotalCharges"] = pd.to_numeric(df.get("TotalCharges", 0), errors="coerce").fillna(0.0) for col in BINARY_COLS: df[col] = df[col].map(BINARY_MAP) df_encoded = pd.get_dummies(df, columns=MULTI_CAT_COLS) # Align to the exact training-time columns (missing dummy cols -> 0, drop extras) df_aligned = df_encoded.reindex(columns=MODEL_COLUMNS, fill_value=0) return df_aligned