Yashwanthsairam's picture
Upload folder using huggingface_hub
5918259 verified
# Import necessary libraries
import numpy as np
import joblib
import pandas as pd
from flask import Flask, request, jsonify
# Initialize the Flask application
superkart_sales_forecast_api = Flask("SuperKart Sales Forecast API")
# Load the trained machine learning model
model = joblib.load("product_store_sales_prediction.joblib")
# Define a route for the home page (GET request)
@superkart_sales_forecast_api.get('/')
def home():
"""
Handles GET requests to the root URL ('/').
Returns a welcome message.
"""
return "Welcome to the SuperKart Sales Forecast API!"
# Define an endpoint for single prediction (POST request)
@superkart_sales_forecast_api.post('/v1/forecast')
def predict_sales_forecast():
"""
Handles POST requests to '/v1/forecast'.
Expects a JSON payload of product-store details.
Returns the predicted sales total.
"""
forecast_data = request.get_json()
sample = {
'Product_Weight': float(forecast_data['Product_Weight']),
'Product_MRP': float(forecast_data['Product_MRP']),
'Product_Sugar_Content': forecast_data['Product_Sugar_Content'],
'Product_Allocated_Area': float(forecast_data['Product_Allocated_Area']),
'Product_Type': forecast_data['Product_Type'],
'Store_Id': forecast_data['Store_Id'],
'Store_Establishment_Year': int(forecast_data['Store_Establishment_Year']),
'Store_Size': forecast_data['Store_Size'],
'Store_Location_City_Type': forecast_data['Store_Location_City_Type'],
'Store_Type': forecast_data['Store_Type']
}
input_df = pd.DataFrame([sample])
prediction = model.predict(input_df)
predicted_sales = round(float(prediction[0]), 2)
return jsonify({'predicted_product_store_sales_total': predicted_sales})
# Define an endpoint for batch prediction (POST request)
@superkart_sales_forecast_api.post('/v1/forecastbatch')
def predict_sales_forecast_batch():
"""
Handles POST requests to '/v1/forecastbatch'.
Expects a CSV file with product-store rows.
Returns a dictionary of predicted sales totals.
"""
file = request.files['file']
input_df = pd.read_csv(file)
predictions = model.predict(input_df).tolist()
predictions = [round(float(x), 2) for x in predictions]
if 'id' in input_df.columns:
ids = input_df['id'].tolist()
else:
ids = list(range(1, len(predictions) + 1))
result = dict(zip(ids, predictions))
return jsonify(result)
# Run the Flask app
if __name__ == '__main__':
superkart_sales_forecast_api.run(debug=True)