File size: 2,549 Bytes
55eed03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

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

# Initialize the Flask app with a custom name
super_kart_predictor_api = Flask("Super Kart Sales Predictor")

# Load the trained model from the specified path
# Make sure model_path variable is defined or replace with the actual path string
model_path = "super_kart_prediction_gbr_tuned_model_v1_0.joblib"
model = joblib.load(model_path)

# Define a route for the home page (GET request)
@super_kart_predictor_api.get('/')
def home():
  """
  This function handles GET requests to the root URL ('/') of the API.
  It returns a simple welcome message.
  """
  return "Welcome to the Super Kart Sales Predictor API!"

# Define a route for predictions (POST request)
@super_kart_predictor_api.post("/v1/sales")
def predict_sales():
  """
  This function handles POST requests to the /v1/sales endpoint.
  It expects a JSON payload containing commodity sales details and returns
  the predicted sales as a JSON response
  """
  # Get JSON data from the POST request
  superkart_data = request.get_json()
  print(f"\nIncoming request data: \n{superkart_data}\n")

  # Extract relevant features from the JSON payload into a dictionary
  sample = {
      'Product_Weight': superkart_data['Product_Weight'],
      'Product_Allocated_Area': superkart_data['Product_Allocated_Area'],
      'Product_MRP': superkart_data['Product_MRP'],
      'Product_Sugar_Content': superkart_data['Product_Sugar_Content'],
      'Product_Type': superkart_data['Product_Type'],
      'Product_Category': superkart_data['Product_Category'],      
      'Store_Id': superkart_data['Store_Id'],
      'Store_Establishment_Year': superkart_data['Store_Establishment_Year'],      
      'Store_Size': superkart_data['Store_Size'],
      'Store_Location_City_Type': superkart_data['Store_Location_City_Type'],
      'Store_Type': superkart_data['Store_Type'],
      'Store_Tenure': superkart_data['Store_Tenure'],
      'Perishability': superkart_data['Perishability'],
  }

  # Create a DataFrame from the input dictionary for model compatibility
  input_data = pd.DataFrame([sample])

  # Predict sales price using the loaded model
  predicted_sales_price = model.predict(input_data)[0]

  # Convert the prediction to a float type with rounding to 3 decimal places
  predicted_sales = round(predicted_sales_price, 3)

  print(f"\nPredicted Sales Price: {predicted_sales}\n")

  # Return the prediction as a JSON response
  return jsonify({"predicted_sales_price": predicted_sales})