All materials
app.py
pyapp.py
"""
Churn Prediction API -- Baseline from P2
Basic serving endpoint without infrastructure.
"""
import json
import joblib
import numpy as np
from fastapi import FastAPI
app = FastAPI()
# Load model at startup
model = joblib.load("model.pkl")
# Load data profile for reference
with open("data_profile.json", "r") as f:
data_profile = json.load(f)
FEATURE_ORDER = [
"tenure_months",
"monthly_charges",
"total_charges",
"num_complaints",
"data_usage_gb",
"contract_type",
"payment_method",
"segment",
]
@app.post("/predict")
def predict(data: dict):
"""Accept a JSON body and return churn prediction."""
try:
features = []
for col in FEATURE_ORDER:
features.append(data[col])
# Convert categorical features to numeric (simple encoding)
contract_map = {"month-to-month": 0, "one-year": 1, "two-year": 2}
payment_map = {"bank_transfer": 0, "credit_card": 1, "mobile_money": 2, "cash": 3}
segment_map = {"prepaid": 0, "postpaid": 1}
processed = [
features[0], # tenure_months
features[1], # monthly_charges
features[2], # total_charges
features[3], # num_complaints
features[4], # data_usage_gb
contract_map.get(features[5], 0),
payment_map.get(features[6], 0),
segment_map.get(features[7], 0),
]
input_array = np.array([processed])
prediction = int(model.predict(input_array)[0])
probability = float(model.predict_proba(input_array)[0][1])
return {
"prediction": prediction,
"probability": round(probability, 4),
}
except Exception as e:
return {"error": str(e)}