import numpy as np import pandas as pd import joblib from flask import Flask, request, jsonify from datetime import datetime # Initialize Flask app Superkart_api = Flask("SuperKart Sales Prediction") # Load the trained SuperKart sales model from the correct path model = joblib.load("backend_files/Superkart_Sales_prediction_model_v1_0.joblib") # Feature Engineering current_year = datetime.now().year perishable = {'Meat','Dairy','Fruits and Vegetables','Frozen Foods','Seafood','Breads','Breakfast'} def apply_feature_engineering(dataset): if 'Product_Id' in dataset.columns: dataset['Product_Category'] = dataset['Product_Id'].str[:2].map({ 'DR':'Drinks','NC':'Non-Consumable','FD':'Food & Veg' }).fillna('Other') if 'Store_Establishment_Year' in dataset.columns: dataset['Store_Age'] = current_year - dataset['Store_Establishment_Year'] if 'Product_Type' in dataset.columns: dataset['Food_Type'] = dataset['Product_Type'].apply( lambda t: 'Perishable' if t in perishable else 'Non-Perishable' ) return dataset # Home route @Superkart_api.get('/') def home(): return "Welcome to the SuperKart Sales Prediction!" # Single prediction endpoint @Superkart_api.post('/v1/sales') def predict_sales(): data = request.get_json() sample = { 'Product_Id': data.get('Product_Id'), 'Product_Weight': data.get('Product_Weight'), 'Product_Sugar_Content': data.get('Product_Sugar_Content'), 'Product_Allocated_Area': data.get('Product_Allocated_Area'), 'Product_Type': data.get('Product_Type'), 'Product_MRP': data.get('Product_MRP'), 'Store_Id': data.get('Store_Id'), 'Store_Establishment_Year': data.get('Store_Establishment_Year'), 'Store_Size': data.get('Store_Size'), 'Store_Location_City_Type': data.get('Store_Location_City_Type'), 'Store_Type': data.get('Store_Type'), } input_df = pd.DataFrame([sample]) input_df = apply_feature_engineering(input_df) predicted_sales = model.predict(input_df)[0] return jsonify({'Predicted Sales': round(float(predicted_sales), 2)}) # Batch prediction endpoint @Superkart_api.post('/v1/salesbatch') def predict_sales_batch(): file = request.files['file'] input_df = pd.read_csv(file) input_df = apply_feature_engineering(input_df) predicted_sales = model.predict(input_df).tolist() if 'Product_Id' in input_df.columns: product_ids = input_df['Product_Id'].tolist() output_dict = dict(zip(product_ids, [round(float(x), 2) for x in predicted_sales])) else: output_dict = [round(float(x), 2) for x in predicted_sales] return jsonify(output_dict) # Run the app if __name__ == '__main__': Superkart_api.run(debug=True)