File size: 1,808 Bytes
636922f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
import numpy as np
from flask import Flask, request, jsonify
import joblib
import pandas as pd

# Inititialize Flask app with name
sales_prediction_api = Flask("Sales Predictor")

# Load the trained model predictor model
dt_model = joblib.load("decision_tree_model.pkl")
xgb_model = joblib.load("xgboost_model.pkl")

# Define a route for the home page
@sales_prediction_api.route('/')
def home():
    return "Sales Prediction API"

# Define an endpoint to predict sales
@sales_prediction_api.post('/predict')
def predict():
    # Get the data from the request
    data = request.get_json()

    # Extract relevant features from the input data
    sample = {
        'Product_Weight': data['Product_Weight'],
        'Product_Sugar_Content': data['Product_Sugar_Content'],
        'Product_Allocated_Area':  data['Product_Allocated_Area'],
        'Product_Type': data['Product_Type'],
        'Product_MRP': data['Product_MRP'],
        'Store_Size': data['Store_Size'],
        'Store_Location_City_Type': data['Store_Location_City_Type'],
        'Store_Type': data['Store_Type'],
        'Store_Age': data['Store_Age']
    }

    #convert the extracted data into a dataframe
    sample_df = pd.DataFrame(sample, index=[0])

    # --------------------------------
    # Model selection logic (FIXED)
    # --------------------------------
    model_choice = data.get("model", "dt")

    if model_choice == "dt":
        prediction = dt_model.predict(sample_df)[0]

    else :
        prediction = xgb_model.predict(sample_df)[0]


    # --------------------------------
    # Response
    # --------------------------------
    return jsonify({
        "model_used": model_choice,
        "prediction": float(prediction)
    })

if __name__ == '__main__':
    sales_prediction_api.run(debug=True)