BkEd / app.py
Lokiiparihar's picture
Update app.py
66778c3 verified
# 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_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})
# Run the Flask application in debug mode if this script is executed directly
# When deploying with Gunicorn, this block is usually commented out or removed
if __name__ == '__main__':
print("--- app.py: Running Flask app in debug mode ---")
superkart_sales_api.run(debug=True)