File size: 2,433 Bytes
1edd06f
 
 
7acc16a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1edd06f
7acc16a
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import joblib  
import pandas as pd  
from flask import Flask, request, jsonify  

# Initialize the Flask application
superkart_sales_api = Flask("SuperKart Sales Forecast API")

model = joblib.load("sales_forecast_model_v1_0.joblib")

EXPECTED_FEATURES = [
    "Product_Weight",
    "Product_Allocated_Area",
    "Product_MRP",
    "Store_Age",
    "Product_Sugar_Content",
    "Product_Type",
    "Store_Size",
    "Store_Location_City_Type",
    "Store_Type",
]

# Define a route for the home page (GET request)
@superkart_sales_api.get("/")
def home():
    """
    Handles GET requests to the root URL ('/').
    Returns a simple welcome message and the expected schema.
    """
    return "Welcome to the SuperKart Sales Forecast API!"

# Define an endpoint for single sales prediction (POST request)
@superkart_sales_api.post("/v1/sales")
def predict_sales():
    """
    Handles POST requests to the '/v1/sales' endpoint.
    Expects a JSON payload with SuperKart product & store features and
    returns the predicted Product_Store_Sales_Total as JSON.

    Example payload:
    {
      "Product_Weight": 12.5,
      "Product_Allocated_Area": 0.06,
      "Product_MRP": 150,
      "Store_Age": 16,
      "Product_Sugar_Content": "Regular",
      "Product_Type": "Snack Foods",
      "Store_Size": "Medium",
      "Store_Location_City_Type": "Tier 2",
      "Store_Type": "Supermarket Type 2"
    }
    """
    try:
        payload = request.get_json()

        # Basic validation: ensure all required features are present
        missing = [f for f in EXPECTED_FEATURES if f not in payload]
        if missing:
            return jsonify({
                "error": "Missing required feature(s).",
                "missing": missing,
                "expected_features": EXPECTED_FEATURES
            }), 400

        # Build a single-row DataFrame in the expected feature order
        sample = {f: payload[f] for f in EXPECTED_FEATURES}
        input_df = pd.DataFrame([sample])

        # Predict sales (model outputs actual sales; no log transform)
        pred = model.predict(input_df)[0]
        pred = round(float(pred), 2)  

        return jsonify({"Predicted Product_Store_Sales_Total": pred})

    except Exception as e:
        return jsonify({"error": str(e)}), 500

# Run the Flask application in debug mode if this script is executed directly
if __name__ == "__main__":
    superkart_sales_api.run(debug=True)