|
|
from flask import Flask, request, jsonify
|
|
|
import joblib
|
|
|
import pandas as pd
|
|
|
import numpy as np
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
try:
|
|
|
kmeans_model = joblib.load("kmeans_model.joblib")
|
|
|
scaler_model = joblib.load("scaler_model.joblib")
|
|
|
print("Models loaded successfully!")
|
|
|
except Exception as e:
|
|
|
print(f"Error loading models: {e}")
|
|
|
kmeans_model = None
|
|
|
scaler_model = None
|
|
|
|
|
|
@app.route("/predict", methods=["POST"])
|
|
|
def predict():
|
|
|
if kmeans_model is None or scaler_model is None:
|
|
|
return jsonify({"error": "Model not loaded. Please check deployment logs."}), 500
|
|
|
|
|
|
data = request.get_json(force=True)
|
|
|
|
|
|
try:
|
|
|
|
|
|
age = data.get("age")
|
|
|
annual_income = data.get("annual_income")
|
|
|
spending_score = data.get("spending_score")
|
|
|
|
|
|
if age is None or annual_income is None or spending_score is None:
|
|
|
return jsonify({"error": "Missing required input features (age, annual_income, spending_score)."}), 400
|
|
|
|
|
|
|
|
|
features_df = pd.DataFrame([[age, annual_income, spending_score]],
|
|
|
columns=['Age', 'Annual Income (k$)', 'Spending Score (1-100)'])
|
|
|
|
|
|
|
|
|
scaled_features = scaler_model.transform(features_df)
|
|
|
|
|
|
|
|
|
prediction = kmeans_model.predict(scaled_features)
|
|
|
cluster_id = int(prediction[0])
|
|
|
|
|
|
return jsonify({"cluster_id": cluster_id})
|
|
|
|
|
|
except Exception as e:
|
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
app.run(debug=True) |