# Import necessary libraries import numpy as np import joblib # For loading the serialized model import pandas as pd # For data manipulation from flask import Flask, request, jsonify # For creating the Flask API # Initialize the Flask application superkart_api = Flask("SuperKart Sales Predictor") # Load the trained machine learning model model = joblib.load("superkart_sales_prediction_model_v1_0.joblib") # Define a route for the home page (GET request) @superkart_api.get('/') def home(): """ This function handles GET requests to the root URL ('/') of the API. It returns a simple welcome message. """ return "Welcome to the SuperKart Sales Prediction API!" # Define an endpoint for single property prediction (POST request) @superkart_api.post('/v1/sales') def predict_sales(): """ POST endpoint to predict sales for a single product-store combination. Expects JSON input with product and store attributes. """ try: # Get the JSON data from the request body data = request.get_json() print("Raw incoming data:", data) # Validate expected fields required_fields = [ "Product_Weight", "Product_Allocated_Area", "Product_MRP", "Store_Age", "Product_Sugar_Content", "Product_Type", "Store_Size", "Store_Location_City_Type", "Store_Type", "Store_Id" ] missing_fields = [f for f in required_fields if f not in data] if missing_fields: return jsonify({ "error": f"Missing required fields: {missing_fields}" }), 400 # Extract relevant features from the JSON data sample = { "Product_Weight": data["Product_Weight"], "Product_Allocated_Area": data["Product_Allocated_Area"], "Product_MRP": data["Product_MRP"], "Store_Age": data["Store_Age"], "Product_Sugar_Content": data["Product_Sugar_Content"], "Product_Type": data["Product_Type"], "Store_Size": data["Store_Size"], "Store_Location_City_Type": data["Store_Location_City_Type"], "Store_Type": data["Store_Type"], "Store_Id": data["Store_Id"] } # Prepare data for prediction sample = {f: data[f] for f in required_fields} # Convert the extracted data into a Pandas DataFrame input_df = pd.DataFrame([sample]) # Make prediction prediction = model.predict(input_df)[0] # Convert predicted_price to Python float predicted_sales = round(float(prediction), 2) # Return the predicted sales return jsonify({"Predicted_Sales_Total": predicted_sales}) except Exception as e: # Catch all errors and return them as JSON return jsonify({"error": str(e)}), 500 # Run the Flask application in debug mode if this script is executed directly if __name__ == '__main__': superkart_api.run(debug=True)