File size: 1,984 Bytes
2d85bfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Flask backend that serves the trained SuperKart sales-forecasting model pipeline

from flask import Flask, request, jsonify
import pandas as pd
import joblib

# Initialize the Flask application
superkart_api = Flask(__name__)

# Load the trained pipeline (preprocessing + model) once at startup
model = joblib.load("superkart_model.joblib")

# The exact feature columns (and order) the model pipeline expects
FEATURE_COLUMNS = [
    "Product_Weight", "Product_Sugar_Content", "Product_Allocated_Area",
    "Product_MRP", "Store_Size", "Store_Location_City_Type", "Store_Type",
    "Product_Id_char", "Store_Age_Years", "Product_Type_Category",
]


@superkart_api.get("/")
def home():
    """Simple health-check route."""
    return {"message": "SuperKart Sales Forecasting API is up and running."}


@superkart_api.post("/v1/predict")
def predict():
    """Online inference: predicts sales for a single record sent as JSON."""
    data = request.get_json()

    # Build a single-row DataFrame from the incoming JSON payload, in the
    # exact column order the pipeline was trained on
    input_df = pd.DataFrame([data], columns=FEATURE_COLUMNS)

    prediction = model.predict(input_df)[0]

    return jsonify({"predicted_Product_Store_Sales_Total": round(float(prediction), 2)})


@superkart_api.post("/v1/predictbatch")
def predict_batch():
    """Batch inference: predicts sales for every row in an uploaded CSV file."""
    file = request.files["file"]

    # Read the uploaded CSV into a DataFrame and align its columns
    input_df = pd.read_csv(file)
    input_df = input_df[FEATURE_COLUMNS]

    predictions = model.predict(input_df)

    # Return predictions keyed by row index, as a JSON object
    result = {str(idx): round(float(pred), 2) for idx, pred in enumerate(predictions)}
    return jsonify(result)


if __name__ == "__main__":
    # Run the Flask app on all interfaces, port 7860 (matches Codespace forwarding)
    superkart_api.run(host="0.0.0.0", port=7860)