Spaces:
Sleeping
Sleeping
| import joblib | |
| import pandas as pd | |
| from flask import Flask, request, jsonify | |
| # Initialize Flask app | |
| sales_forecast_api = Flask("SuperKart Sales Forecast API") | |
| # Load trained model (includes preprocessing pipeline) | |
| model = joblib.load("best_random_forest.pkl") | |
| # Home route | |
| def home(): | |
| return "Welcome to the SuperKart Sales Forecast API!" | |
| # Predict for a single input | |
| def predict_sales(): | |
| data = request.get_json() | |
| # Convert JSON into DataFrame (1 row) | |
| input_df = pd.DataFrame([data]) | |
| # Model prediction | |
| prediction = model.predict(input_df).tolist()[0] | |
| return jsonify({"Predicted_Sales_Total": prediction}) | |
| # Predict for a batch (CSV upload) | |
| def predict_sales_batch(): | |
| # Read uploaded CSV file | |
| file = request.files['file'] | |
| input_data = pd.read_csv(file) | |
| # Check for optional Product_Id column | |
| if "Product_Id" in input_data.columns: | |
| ids = input_data["Product_Id"].astype(str) | |
| input_data = input_data.drop(columns=["Product_Id"]) | |
| else: | |
| ids = input_data.index.astype(str) # fallback to row indices | |
| # Make predictions | |
| preds = model.predict(input_data).tolist() | |
| # Map Product_Id (or row index) → prediction | |
| results = dict(zip(ids, preds)) | |
| return jsonify(results) | |
| # Run app | |
| if __name__ == "__main__": | |
| sales_forecast_api.run(debug=True) | |