abersbail's picture
Deploy Customer Churn ML Predictor & Demo Video to Hugging Face
d0bac84 verified
Raw
History Blame Contribute Delete
2.45 kB
import os
import json
from flask import Flask, render_template, request, jsonify, send_file
import pandas as pd
from src.model import ChurnClassifier
from src.predict import predict_single
from src.train import train_pipeline
app = Flask(__name__)
MODEL_PATH = "models/churn_model.pkl"
METRICS_PATH = "models/metrics.json"
@app.route("/")
def index():
# Load metrics if available
metrics = None
if os.path.exists(METRICS_PATH):
try:
with open(METRICS_PATH, "r") as f:
metrics = json.load(f)
except Exception:
pass
model_exists = os.path.exists(MODEL_PATH)
return render_template("index.html", metrics=metrics, model_exists=model_exists)
@app.route("/video")
def video():
possible_paths = ["download.webm", "src/static/download.webm", os.path.join(os.path.dirname(__file__), "..", "download.webm")]
for path in possible_paths:
if os.path.exists(path):
return send_file(path, mimetype="video/webm")
return "Video not found", 404
@app.route("/train", methods=["POST"])
def train():
try:
train_pipeline(
n_samples=1000,
test_size=0.2,
model_path=MODEL_PATH,
metrics_path=METRICS_PATH
)
with open(METRICS_PATH, "r") as f:
metrics = json.load(f)
return jsonify({"success": True, "metrics": metrics})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/predict", methods=["POST"])
def predict():
try:
age = int(request.form.get("age", 40))
monthly_charges = float(request.form.get("monthly_charges", 50.0))
contract_length = int(request.form.get("contract_length", 12))
support_calls = int(request.form.get("support_calls", 1))
tech_support = request.form.get("tech_support", "no")
result = predict_single(
age=age,
monthly_charges=monthly_charges,
contract_length=contract_length,
support_calls=support_calls,
tech_support=tech_support,
model_path=MODEL_PATH
)
return jsonify({"success": True, "result": result})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
app.run(host="0.0.0.0", port=port, debug=False)