import joblib import pandas as pd from flask import Flask, request, jsonify import numpy as np # Initialize Flask app sales_forecast_api = Flask("SuperKart Sales Forecast API") # Load the trained sales forecasting model model = joblib.load("superkart_sales_forecast_model.pkl") # Define a route for the home page @sales_forecast_api.get('/') def home(): return "Welcome to the SuperKart Sales Forecasting API! 🛒📊" # Define an endpoint to predict sales for a single product-store combination @sales_forecast_api.post('/v1/predict_sales') def predict_sales(): try: # Get JSON data from the request input_data = request.get_json() # Extract relevant features from the input data 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'] } # Convert the extracted data into a DataFrame input_df = pd.DataFrame([sample]) # Make sales prediction using the trained model prediction = model.predict(input_df)[0] # Convert NumPy float32 to Python float prediction = float(prediction) # Return the prediction as a JSON response 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 # Define an endpoint to predict sales for a batch of product-store combinations @sales_forecast_api.post('/v1/predict_sales_batch') def predict_sales_batch(): try: # Get the uploaded CSV file from the request file = request.files['file'] # Read the file into a DataFrame input_data = pd.read_csv(file) # Select only the required features for prediction 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' ] # Prepare data for prediction prediction_data = input_data[feature_columns] # Make predictions for the batch data predictions = model.predict(prediction_data) # Create output with Product_Id and Store_Id mapping 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 # Run the Flask app if __name__ == '__main__': sales_forecast_api.run(debug=True, host='0.0.0.0', port=7860) # Port 7860 for Hugging Face