|
|
| |
| import numpy as np |
| import joblib |
| import pandas as pd |
| from flask import Flask, request, jsonify |
|
|
| from flask_cors import CORS |
| app = Flask(__name__) |
| CORS(app, resources={r"/v1/*": {"origins": "*"}}) |
|
|
| |
| sales_forecast_api = Flask("SuperKart Sales Forecast API") |
|
|
| |
| model = joblib.load("superkart_sales_prediction_model_v1_0.joblib") |
|
|
|
|
| |
| @sales_forecast_api.get('/') |
| def home(): |
| return "Welcome to the SuperKart Sales Forecast API!" |
|
|
| |
| @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. |
| """ |
| |
| data = request.get_json() |
|
|
| |
| 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'] |
| } |
|
|
| |
| input_df = pd.DataFrame([sample]) |
|
|
| |
| predicted_sales = model.predict(input_df)[0] |
| predicted_sales = round(float(predicted_sales), 2) |
|
|
| return jsonify({'prediction': predicted_sales}) |
|
|
| |
| @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. |
| """ |
| |
| file = request.files['file'] |
| input_df = pd.read_csv(file) |
|
|
| |
| predictions = model.predict(input_df).tolist() |
| predictions = [round(float(pred), 2) for pred in predictions] |
|
|
| |
| 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) |
|
|
| |
| if __name__ == '__main__': |
| sales_forecast_api.run(debug=True) |
|
|