from flask import Flask, request, jsonify import joblib import pandas as pd import numpy as np app = Flask("Sales Prediction") # Load the serialized model model = joblib.load('best_sales_forecasting_model.joblib') @app.route('/', methods=['GET']) def home(): return jsonify({"status": "running", "message": "Sales Prediction API is live"}) @app.route('/predict_single', methods=['POST']) def predict_single(): """ API endpoint for single prediction. Expects a JSON object with the features for one product-store combination. """ try: data = request.get_json(force=True) # Convert the dictionary to a pandas DataFrame df = pd.DataFrame([data]) # Ensure columns are in the same order as during training df = df[model.feature_names_in_] prediction = model.predict(df) # Return the prediction as a JSON response return jsonify({'prediction': prediction[0].tolist()}) except Exception as e: return jsonify({'error': str(e)}) @app.route('/predict_batch', methods=['POST']) def predict_batch(): """ API endpoint for batch predictions. Expects a JSON array of JSON objects, where each object is a product-store combination. """ try: data = request.get_json(force=True) # Convert the list of dictionaries to a pandas DataFrame df = pd.DataFrame(data) # Ensure columns are in the same order as during training df = df[model.feature_names_in_] predictions = model.predict(df) # Return the predictions as a JSON response return jsonify({'predictions': predictions.tolist()}) except Exception as e: return jsonify({'error': str(e)}) # if __name__ == '__main__': # # Run the Flask app # # Setting debug=True allows for automatic reloading and provides a debugger # app.run(debug=True, host='0.0.0.0', port=7860)