File size: 2,659 Bytes
316c80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import joblib
import pandas as pd
from flask import Flask, request, jsonify

sales_predictor_api = Flask("Sales Predictor")

# Load the trained model pipeline
MODEL_PATH = os.path.join("deployment_files", "sales_predictor.joblib")
model = joblib.load(MODEL_PATH)

@sales_predictor_api.get("/")
def home():
    return "Welcome to the Sales Prediction API!"

def validate_and_make_dataframe(sales_data: dict) -> pd.DataFrame:
    """

    Validate required fields and convert a single JSON payload to a DataFrame.

    """
    required_fields = [
        "Product_Weight",
        "Product_Sugar_Content",
        "Product_Allocated_Area",
        "Product_Type",
        "Product_MRP",
        "Store_Establishment_Year_Before_2005",
        "Store_Size",
        "Store_Location_City_Type",
        "Store_Type",
    ]
    missing = [f for f in required_fields if f not in sales_data]
    if missing:
        raise KeyError(f"Missing required fields: {', '.join(missing)}")

    sample = {
        "Product_Weight": sales_data["Product_Weight"],
        "Product_Sugar_Content": sales_data["Product_Sugar_Content"],
        "Product_Allocated_Area": sales_data["Product_Allocated_Area"],
        "Product_Type": sales_data["Product_Type"],
        "Product_MRP": sales_data["Product_MRP"],
        "Store_Establishment_Year_Before_2005": sales_data["Store_Establishment_Year_Before_2005"],
        "Store_Size": sales_data["Store_Size"],
        "Store_Location_City_Type": sales_data["Store_Location_City_Type"],
        "Store_Type": sales_data["Store_Type"],
    }
    return pd.DataFrame([sample])

@sales_predictor_api.post("/v1/sales")
def predict_sale():
    try:
        sales_data = request.get_json(force=True, silent=False)
        input_df = validate_and_make_dataframe(sales_data)
        prediction = model.predict(input_df).tolist()[0]
        return jsonify({"Predicted_Sales": prediction})
    except Exception as e:
        return jsonify({"error": str(e)}), 400

@sales_predictor_api.post("/v1/salesbatch")
def predict_sale_batch():
    try:
        file = request.files.get("file")
        if file is None:
            return jsonify({"error": "No file provided with form field 'file'"}), 400
        input_df = pd.read_csv(file)
        predictions = model.predict(input_df).tolist()
        return jsonify({"Predicted_Sales": predictions})
    except Exception as e:
        return jsonify({"error": str(e)}), 400

if __name__ == "__main__":
    port = int(os.environ.get("PORT", "7860"))
    sales_predictor_api.run(host="0.0.0.0", port=port, debug=False)