Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from flask import Flask, request, jsonify
|
| 4 |
+
import joblib
|
| 5 |
+
|
| 6 |
+
# Initialize Flask app
|
| 7 |
+
sales_prediction_api = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# 👇 REQUIRED for Hugging Face Gunicorn
|
| 10 |
+
application = sales_prediction_api
|
| 11 |
+
|
| 12 |
+
# Load models
|
| 13 |
+
dt_model = joblib.load("decision_tree_model.pkl")
|
| 14 |
+
xgb_model = joblib.load("xgboost_model.pkl")
|
| 15 |
+
|
| 16 |
+
# Home route
|
| 17 |
+
@sales_prediction_api.route("/")
|
| 18 |
+
def home():
|
| 19 |
+
return "✅ SuperKart Sales Prediction API is running"
|
| 20 |
+
|
| 21 |
+
# Prediction route
|
| 22 |
+
@sales_prediction_api.route("/predict", methods=["POST"])
|
| 23 |
+
def predict():
|
| 24 |
+
try:
|
| 25 |
+
data = request.get_json()
|
| 26 |
+
|
| 27 |
+
# Model choice
|
| 28 |
+
model_choice = data.get("model", "dt")
|
| 29 |
+
|
| 30 |
+
# Extract features (MATCHES STREAMLIT KEYS)
|
| 31 |
+
sample = {
|
| 32 |
+
"Product_Weight": data["Product_Weight"],
|
| 33 |
+
"Product_Sugar_Content": data["Product_Sugar_Content"],
|
| 34 |
+
"Product_Allocated_Area": data["Product_Allocated_Area"],
|
| 35 |
+
"Product_Type": data["Product_Type"],
|
| 36 |
+
"Product_MRP": data["Product_MRP"],
|
| 37 |
+
"Store_Size": data["Store_Size"],
|
| 38 |
+
"Store_Location_City_Type": data["Store_Location_City_Type"],
|
| 39 |
+
"Store_Type": data["Store_Type"],
|
| 40 |
+
"Store_Age": data["Store_Age"]
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
sample_df = pd.DataFrame([sample])
|
| 44 |
+
|
| 45 |
+
# Select model
|
| 46 |
+
if model_choice == "dt":
|
| 47 |
+
prediction = dt_model.predict(sample_df)[0]
|
| 48 |
+
elif model_choice == "xgb":
|
| 49 |
+
prediction = xgb_model.predict(sample_df)[0]
|
| 50 |
+
else:
|
| 51 |
+
return jsonify({"error": "Invalid model choice"}), 400
|
| 52 |
+
|
| 53 |
+
return jsonify({
|
| 54 |
+
"Prediction": float(prediction),
|
| 55 |
+
"ModelUsed": model_choice
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
return jsonify({"error": str(e)}), 500
|