import joblib import pandas as pd from flask import Flask, request, jsonify # Initialize the Flask application superkart_sales_api = Flask("SuperKart Sales Forecast API") model = joblib.load("sales_forecast_model_v1_0.joblib") EXPECTED_FEATURES = [ "Product_Weight", "Product_Allocated_Area", "Product_MRP", "Store_Age", "Product_Sugar_Content", "Product_Type", "Store_Size", "Store_Location_City_Type", "Store_Type", ] # Define a route for the home page (GET request) @superkart_sales_api.get("/") def home(): """ Handles GET requests to the root URL ('/'). Returns a simple welcome message and the expected schema. """ return "Welcome to the SuperKart Sales Forecast API!" # Define an endpoint for single sales prediction (POST request) @superkart_sales_api.post("/v1/sales") def predict_sales(): """ Handles POST requests to the '/v1/sales' endpoint. Expects a JSON payload with SuperKart product & store features and returns the predicted Product_Store_Sales_Total as JSON. Example payload: { "Product_Weight": 12.5, "Product_Allocated_Area": 0.06, "Product_MRP": 150, "Store_Age": 16, "Product_Sugar_Content": "Regular", "Product_Type": "Snack Foods", "Store_Size": "Medium", "Store_Location_City_Type": "Tier 2", "Store_Type": "Supermarket Type 2" } """ try: payload = request.get_json() # Basic validation: ensure all required features are present missing = [f for f in EXPECTED_FEATURES if f not in payload] if missing: return jsonify({ "error": "Missing required feature(s).", "missing": missing, "expected_features": EXPECTED_FEATURES }), 400 # Build a single-row DataFrame in the expected feature order sample = {f: payload[f] for f in EXPECTED_FEATURES} input_df = pd.DataFrame([sample]) # Predict sales (model outputs actual sales; no log transform) pred = model.predict(input_df)[0] pred = round(float(pred), 2) return jsonify({"Predicted Product_Store_Sales_Total": pred}) except Exception as e: return jsonify({"error": str(e)}), 500 # Run the Flask application in debug mode if this script is executed directly if __name__ == "__main__": superkart_sales_api.run(debug=True)