Spaces:
Sleeping
Sleeping
File size: 4,265 Bytes
6b07176 508d0df 6b07176 5713a86 6b07176 f8ab404 6b07176 3e45f30 6b07176 3e45f30 |
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 103 104 105 106 107 108 109 |
# Import necessary libraries
from datetime import datetime
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
# Initialize the Flask application
SK_Sales_Forecast_api = Flask("SK_Sales_Backend")
# Load the trained machine learning model
model = joblib.load("SuperKart_Sales_Forecast_model_v1_0.joblib")
# Define a route for the home page (GET request)
@SK_Sales_Forecast_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 SuperKart Sales Forecast API!"
# Define an endpoint for single product sales prediction (POST request)
@SK_Sales_Forecast_api.post('/v1/salespredict')
#@SK_Sales_Forecast_api.route('/salespredict', methods=['GET', 'POST'])
def predict_product_sale():
"""
This function handles POST requests to the '/salespredict' endpoint.
It expects a JSON payload containing property details and returns
the predicted rental price as a JSON response.
"""
# Get the JSON data from the request body
product_data = request.get_json()
# Extract relevant features from the JSON data
sample = {
'Product_Id': product_data['Product_Id'],
'Product_Weight': product_data['Product_Weight'],
'Product_Sugar_Content': product_data['Product_Sugar_Content'],
'Product_Allocated_Area': product_data['Product_Allocated_Area'],
'Product_Type': product_data['Product_Type'],
'Product_MRP': product_data['Product_MRP'],
'Store_Establishment_Year': product_data['Store_Establishment_Year'],
'Store_Size': product_data['Store_Size'],
'Store_Location_City_Type': product_data['Store_Location_City_Type'],
'Store_Type': product_data['Store_Type']
}
# Convert the extracted data into a Pandas DataFrame
input_data = pd.DataFrame([sample])
# Extract the Product_Code and Store_Age before feeding to the model
input_data["Product_Code"] = input_data["Product_Id"].str[:2]
input_data.drop("Product_Id", axis=1, inplace=True)
current_year = datetime.now().year
input_data["Store_Age"] = current_year - input_data["Store_Establishment_Year"]
input_data.drop("Store_Establishment_Year", axis=1, inplace=True)
# Make prediction
predicted_sale = model.predict(input_data)[0]
# Return the actual price
return jsonify({'Predicted Sale': predicted_sale})
# Define an endpoint for batch prediction (POST request)
#@SK_Sales_Forecast_api.post('/salespredictbatch')
@SK_Sales_Forecast_api.route('/salespredictbatch', methods=['GET', 'POST'])
def predict_product_sale_batch():
"""
This function handles POST requests to the '/salespredictbatch' endpoint.
It expects a CSV file containing property details for multiple properties
and returns the predicted rental prices as a dictionary 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_data = pd.read_csv(file)
# Extract the Product_Code and Store_Age before feeding to the model
input_data["Product_Code"] = input_data["Product_Id"].str[:2]
product_ids = input_data['Product_Id'].tolist()
input_data.drop("Product_Id", axis=1, inplace=True)
current_year = datetime.now().year
input_data["Store_Age"] = current_year - input_data["Store_Establishment_Year"]
input_data.drop("Store_Establishment_Year", axis=1, inplace=True)
# Make predictions for all products in the DataFrame
predicted_sales = model.predict(input_data).tolist()
# Create a dictionary of predictions with product IDs as keys
#product_ids = input_data['Product_Id'].tolist()
output_dict = dict(zip(product_ids, predicted_sales)) # Use actual prices
# Return the predictions dictionary as a JSON response
return output_dict
# Run the Flask application in debug mode if this script is executed directly
if __name__ == '__main__':
#SK_Sales_Forecast_api.run(debug=True)
SK_Sales_Forecast_api.run(host="0.0.0.0", port=7860)
|