|
|
import joblib |
|
|
import pandas as pd |
|
|
from flask import Flask, request, jsonify |
|
|
import numpy as np |
|
|
|
|
|
|
|
|
sales_forecast_api = Flask("SuperKart Sales Forecast API") |
|
|
|
|
|
|
|
|
model = joblib.load("superkart_sales_forecast_model.pkl") |
|
|
|
|
|
|
|
|
@sales_forecast_api.get('/') |
|
|
def home(): |
|
|
return "Welcome to the SuperKart Sales Forecasting API! ππ" |
|
|
|
|
|
|
|
|
@sales_forecast_api.post('/v1/predict_sales') |
|
|
def predict_sales(): |
|
|
try: |
|
|
|
|
|
input_data = request.get_json() |
|
|
|
|
|
|
|
|
sample = { |
|
|
'Product_Weight': input_data['Product_Weight'], |
|
|
'Product_Sugar_Content': input_data['Product_Sugar_Content'], |
|
|
'Product_Allocated_Area': input_data['Product_Allocated_Area'], |
|
|
'Product_Type': input_data['Product_Type'], |
|
|
'Product_MRP': input_data['Product_MRP'], |
|
|
'Store_Establishment_Year': input_data['Store_Establishment_Year'], |
|
|
'Store_Size': input_data['Store_Size'], |
|
|
'Store_Location_City_Type': input_data['Store_Location_City_Type'], |
|
|
'Store_Type': input_data['Store_Type'] |
|
|
} |
|
|
|
|
|
|
|
|
input_df = pd.DataFrame([sample]) |
|
|
|
|
|
|
|
|
prediction = model.predict(input_df)[0] |
|
|
|
|
|
|
|
|
prediction = float(prediction) |
|
|
|
|
|
|
|
|
return jsonify({ |
|
|
'Product_Id': input_data.get('Product_Id', 'N/A'), |
|
|
'Store_Id': input_data.get('Store_Id', 'N/A'), |
|
|
'Predicted_Sales': round(prediction, 2), |
|
|
'Currency': 'INR', |
|
|
'Status': 'Success' |
|
|
}) |
|
|
|
|
|
except Exception as e: |
|
|
return jsonify({ |
|
|
'Error': str(e), |
|
|
'Status': 'Failed' |
|
|
}), 400 |
|
|
|
|
|
|
|
|
@sales_forecast_api.post('/v1/predict_sales_batch') |
|
|
def predict_sales_batch(): |
|
|
try: |
|
|
|
|
|
file = request.files['file'] |
|
|
|
|
|
|
|
|
input_data = pd.read_csv(file) |
|
|
|
|
|
|
|
|
feature_columns = [ |
|
|
'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area', |
|
|
'Product_Type', 'Product_MRP', 'Store_Establishment_Year', |
|
|
'Store_Size', 'Store_Location_City_Type', 'Store_Type' |
|
|
] |
|
|
|
|
|
|
|
|
prediction_data = input_data[feature_columns] |
|
|
|
|
|
|
|
|
predictions = model.predict(prediction_data) |
|
|
|
|
|
|
|
|
output_list = [] |
|
|
for i, (_, row) in enumerate(input_data.iterrows()): |
|
|
prediction_entry = { |
|
|
'Product_Id': row.get('Product_Id', f'Product_{i}'), |
|
|
'Store_Id': row.get('Store_Id', f'Store_{i}'), |
|
|
'Predicted_Sales': float(predictions[i]) |
|
|
} |
|
|
output_list.append(prediction_entry) |
|
|
|
|
|
return jsonify({ |
|
|
'Predictions': output_list, |
|
|
'Total_Records': len(predictions), |
|
|
'Currency': 'INR', |
|
|
'Status': 'Success' |
|
|
}) |
|
|
|
|
|
except Exception as e: |
|
|
return jsonify({ |
|
|
'Error': str(e), |
|
|
'Status': 'Failed' |
|
|
}), 400 |
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
|
sales_forecast_api.run(debug=True, host='0.0.0.0', port=7860) |