Spaces:
Sleeping
Sleeping
| 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') | |
| def home(): | |
| return jsonify({"status": "running", "message": "Sales Prediction API is live"}) | |
| 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)}) | |
| 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) | |