File size: 3,834 Bytes
20c8664
 
1ddb84a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5e087e
 
 
 
1ddb84a
 
 
 
c5e087e
 
1ddb84a
 
c5e087e
 
1ddb84a
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from datetime import datetime

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

REQUIRED_FIELDS = [
        "Product_Weight",
        "Product_Sugar_Content",
        "Product_Allocated_Area",
        "Product_MRP",
        "Store_Size",
        "Store_Id",
        "Store_Location_City_Type",
        "Store_Type",
        "Store_Age",
        "Product_Type_Categories",
]

# Initialize Flask app with a name
sales_prediction = Flask("Superkart Sales Prediction")

# Load the trained sales prediction model
model = joblib.load("super_kart_prediction_model_v1_0.joblib")


# Define a route for the home page
@sales_prediction.get('/')
def home():
    """Home API endpoint"""
    return "Welcome to the Product Sales Prediction API!"


# Define an endpoint to predict sales for a single product
@sales_prediction.post('/v1/predict')
def predict_product_sales():
    """API endpoint to predict sales of a single product"""
    try:
        product_data = request.get_json()

        # Validate required inputs
        missing_fields = [f for f in REQUIRED_FIELDS if f not in product_data]
        if missing_fields:
            return jsonify({"error": f"Missing required fields: {missing_fields}"}), 400

        # Extract relevant product features from the input data
        data = pd.DataFrame([
                {
                        'Product_Weight': float(product_data['Product_Weight']),
                        'Product_Sugar_Content': product_data['Product_Sugar_Content'],
                        'Product_Allocated_Area': float(product_data['Product_Allocated_Area']),
                        'Product_MRP': float(product_data['Product_MRP']),
                        'Store_Size': product_data['Store_Size'],
                        'Store_Id': product_data['Store_Id'],
                        'Store_Location_City_Type': product_data['Store_Location_City_Type'],
                        'Store_Type': product_data['Store_Type'],
                        'Store_Age': int(product_data['Store_Age']),
                        'Product_Type_Categories': product_data['Product_Type_Categories']
                }
        ])

        # Make a churn prediction using the trained model
        sales_predicted = model.predict(data).tolist()[0]

        # Return the prediction as a JSON response
        return jsonify({'Sales': sales_predicted})
    except Exception as error:
        return jsonify({"error": f"Prediction failed: {str(error)}"}), 500


# Define an endpoint to predict sales for a batch of products
@sales_prediction.post('/v1/bulk/predict')
def predict_multiple_products_sales():
    """API endpoint to predict sales of multiple products"""
    # Get the uploaded CSV file from the request
    try:
        def add_store_age(est_year):
            """Function that adds store age"""
            return datetime.now().year - int(est_year)

        file = request.files['file']

        # Read the file into a DataFrame
        input_data = pd.read_csv(file)
        input_data["Store_Age"] = input_data["Store_Establishment_Year"].apply(add_store_age)
        input_data.drop("Store_Establishment_Year", axis=1, inplace=True)

        # Make predictions for the batch data and convert raw predictions into a readable format
        predictions = [x for x in model.predict(input_data.drop("Product_ID", axis=1)).tolist()]
        product_id_list = input_data.Product_ID.values.tolist()
        output_dict = dict(zip(product_id_list, predictions))
        return output_dict
    except Exception as error:
        return jsonify({"error": f"Prediction failed: {str(error)}"}), 500


# Run the Flask app in debug mode
if __name__ == '__main__':
    sales_prediction.run(debug=True)