# Flask backend that serves the trained SuperKart sales-forecasting model pipeline from flask import Flask, request, jsonify import pandas as pd import joblib # Initialize the Flask application superkart_api = Flask(__name__) # Load the trained pipeline (preprocessing + model) once at startup model = joblib.load("superkart_model.joblib") # The exact feature columns (and order) the model pipeline expects FEATURE_COLUMNS = [ "Product_Weight", "Product_Sugar_Content", "Product_Allocated_Area", "Product_MRP", "Store_Size", "Store_Location_City_Type", "Store_Type", "Product_Id_char", "Store_Age_Years", "Product_Type_Category", ] @superkart_api.get("/") def home(): """Simple health-check route.""" return {"message": "SuperKart Sales Forecasting API is up and running."} @superkart_api.post("/v1/predict") def predict(): """Online inference: predicts sales for a single record sent as JSON.""" data = request.get_json() # Build a single-row DataFrame from the incoming JSON payload, in the # exact column order the pipeline was trained on input_df = pd.DataFrame([data], columns=FEATURE_COLUMNS) prediction = model.predict(input_df)[0] return jsonify({"predicted_Product_Store_Sales_Total": round(float(prediction), 2)}) @superkart_api.post("/v1/predictbatch") def predict_batch(): """Batch inference: predicts sales for every row in an uploaded CSV file.""" file = request.files["file"] # Read the uploaded CSV into a DataFrame and align its columns input_df = pd.read_csv(file) input_df = input_df[FEATURE_COLUMNS] predictions = model.predict(input_df) # Return predictions keyed by row index, as a JSON object result = {str(idx): round(float(pred), 2) for idx, pred in enumerate(predictions)} return jsonify(result) if __name__ == "__main__": # Run the Flask app on all interfaces, port 7860 (matches Codespace forwarding) superkart_api.run(host="0.0.0.0", port=7860)