Spaces:
Sleeping
Sleeping
| # 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) | |
| 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.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') | |
| 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) | |