sahilsingla's picture
Upload folder using huggingface_hub
e846182 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
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/v1/*": {"origins": "*"}})
# Initialize the Flask application
sales_forecast_api = Flask("SuperKart Sales Forecast API")
# Load the trained machine learning model
model = joblib.load("superkart_sales_prediction_model_v1_0.joblib")
# Define a route for the home page (GET request)
@sales_forecast_api.get('/')
def home():
return "Welcome to the SuperKart Sales Forecast API!"
# Define an endpoint for single prediction (POST request)
@sales_forecast_api.post('/v1/sales')
def predict_sales():
"""
This function handles POST requests to the '/v1/sales' endpoint.
It expects a JSON payload with product and store attributes and returns
the predicted product-store sales revenue.
"""
# Get the JSON data
data = request.get_json()
# Extract features based on the data dictionary
sample = {
'Product_Weight': data['Product_Weight'],
'Product_Sugar_Content': data['Product_Sugar_Content'],
'Product_Allocated_Area': data['Product_Allocated_Area'],
'Product_Type': data['Product_Type'],
'Product_MRP': data['Product_MRP'],
'Store_Establishment_Year': data['Store_Establishment_Year'],
'Store_Size': data['Store_Size'],
'Store_Location_City_Type': data['Store_Location_City_Type'],
'Store_Type': data['Store_Type']
}
# Convert to DataFrame
input_df = pd.DataFrame([sample])
# Predict sales
predicted_sales = model.predict(input_df)[0]
predicted_sales = round(float(predicted_sales), 2)
return jsonify({'prediction': predicted_sales})
# Define an endpoint for batch prediction (POST request)
@sales_forecast_api.post('/v1/salesbatch')
def predict_sales_batch():
"""
Handles POST requests to '/v1/salesbatch'.
Accepts a CSV file and returns predicted sales totals for each product-store.
"""
# Read the uploaded file
file = request.files['file']
input_df = pd.read_csv(file)
# Predict sales for the batch
predictions = model.predict(input_df).tolist()
predictions = [round(float(pred), 2) for pred in predictions]
# Use Product_Id and Store_Id as combined key if available
if 'Product_Id' in input_df.columns and 'Store_Id' in input_df.columns:
keys = input_df['Product_Id'] + "_" + input_df['Store_Id']
else:
keys = list(range(len(predictions)))
results = dict(zip(keys, predictions))
return jsonify(results)
# Run the application
if __name__ == '__main__':
sales_forecast_api.run(debug=True)