File size: 3,877 Bytes
ae32f03
 
 
 
 
636922f
ae32f03
636922f
ae32f03
 
 
636922f
ae32f03
8deeab2
 
ae32f03
8deeab2
ae32f03
 
1cf3f01
ae32f03
 
636922f
ae32f03
 
 
 
 
 
 
 
 
8deeab2
ae32f03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e69a448
ae32f03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8deeab2
ae32f03
 
 
 
 
 
 
 
1cf3f01
ae32f03
 
1cf3f01
ae32f03
 
1cf3f01
ae32f03
 
1cf3f01
ae32f03
 
1cf3f01
 
 
 
 
 
ae32f03
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
102
# Import necessary libraries
import numpy as np
import joblib  # For loading the serialized model
import pandas as pd  # For data manipulation
from flask import Flask, request, jsonify  # For creating the Flask API

print("--- app.py: Starting Flask application setup ---")

# Initialize the Flask application
superkart_sales_api = Flask("SuperKart Sales Predictor")
print("--- app.py: Flask app initialized ---")

# Load the trained machine learning model
try:
    model = joblib.load("superkart_sales_model.pkl")
    print("--- app.py: Model loaded successfully ---")
except Exception as e:
    print(f"--- app.py: ERROR loading model: {e} ---")
    raise # Re-raise to ensure the error is visible

# Define a route for the home page (GET request)
@superkart_sales_api.get('/')
def home():
    print("--- API: Home route accessed ---")
    """
    This function handles GET requests to the root URL ('/') of the API.
    It returns a simple welcome message.
    """
    return "Welcome to the SuperKart Sales Prediction API!"

# Define an endpoint for single sales prediction (POST request)
@superkart_sales_api.post('/v1/sales')
def predict_sales():
    print("--- API: Single sales prediction route accessed ---")
    """
    This function handles POST requests to the '/v1/sales' endpoint.
    It expects a JSON payload containing product and store details and returns
    the predicted sales as a JSON response.
    """
    # Get the JSON data from the request body
    input_data_json = request.get_json()

    # Extract relevant features from the JSON data, matching x_train columns
    # The model expects original feature names before one-hot encoding
    sample = {
        'Product_Id': input_data_json['Product_Id'],
        'Product_Weight': input_data_json['Product_Weight'],
        'Product_Sugar_Content': input_data_json['Product_Sugar_Content'],
        'Product_Allocated_Area': input_data_json['Product_Allocated_Area'],
        'Product_Type': input_data_json['Product_Type'],
        'Product_MRP': input_data_json['Product_MRP'],
        'Store_Id': input_data_json['Store_Id'],
        'Store_Type': input_data_json['Store_Type'],
        'Store_Size': input_data_json['Store_Size'],
        'Store_Location_City_Type': input_data_json['Store_Location_City_Type'],
        'Store_Current_Age': input_data_json['Store_Current_Age']
    }

    # Convert the extracted data into a Pandas DataFrame
    input_df = pd.DataFrame([sample])

    # Make prediction
    predicted_sales = model.predict(input_df)[0]

    # Convert predicted_sales to Python float and round
    predicted_sales = round(float(predicted_sales), 2)

    # Return the predicted sales
    return jsonify({'Predicted Sales': predicted_sales})


# Define an endpoint for batch prediction (POST request)
@superkart_sales_api.post('/v1/salesbatch')
def predict_sales_batch():
    print("--- API: Batch sales prediction route accessed ---")
    """
    This function handles POST requests to the '/v1/salesbatch' endpoint.
    It expects a CSV file containing product and store details for multiple entries
    and returns the predicted sales as a list in the JSON response.
    """
    # Get the uploaded CSV file from the request
    file = request.files['file']

    # Read the CSV file into a Pandas DataFrame
    input_df_batch = pd.read_csv(file)

    # Make predictions for all entries in the DataFrame
    predicted_sales_batch = model.predict(input_df_batch).tolist()

    # Round each prediction and convert to float
    predicted_sales_batch = [round(float(s), 2) for s in predicted_sales_batch]

    # Return the predictions list as a JSON response
    return jsonify({'Predicted Sales': predicted_sales_batch})


# -------------------------------
# Local Run (Not used on HF)
# -------------------------------
if __name__ == "__main__":
    app.superkart_sales_api(dedug=True)