Spaces:
Sleeping
Sleeping
File size: 2,914 Bytes
8e87cc8 |
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 |
# 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("superkart_sales_prediction.joblib", mmap_mode=None)
# ---------------- Home Route ----------------
@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!"
# ---------------- Online Forecast Route ----------------
@superkart_sales_forecast_api.post('/v1/sales')
def predict_sales_forecast():
"""
Handles POST requests to '/v1/sales'.
Expects a JSON payload of product-store details.
Returns the predicted sales total.
"""
try:
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})
except Exception as e:
return jsonify({'error': str(e)}), 500
# ---------------- Batch Forecast Route ----------------
@superkart_sales_forecast_api.post('/v1/salesbatch')
def predict_sales_forecast_batch():
"""
Handles POST requests to '/v1/salesbatch'.
Expects a CSV file with product-store rows.
Returns predicted sales totals per row.
"""
try:
file = request.files.get('file')
if file is None:
return jsonify({"error": "No file uploaded"}), 400
input_df = pd.read_csv(file)
# Predict using the trained model
predictions = model.predict(input_df)
input_df["predicted_product_store_sales_total"] = [round(float(x), 2) for x in predictions]
return jsonify(input_df.to_dict(orient="records"))
except Exception as e:
return jsonify({'error': str(e)}), 500
# ---------------- Run the Flask App ----------------
if __name__ == '__main__':
superkart_sales_forecast_api.run(host='0.0.0.0', port=7860, debug=True)
|