Spaces:
Sleeping
Sleeping
| import os | |
| import joblib | |
| import pandas as pd | |
| from flask import Flask, request, jsonify | |
| # Initialize Flask app | |
| app = Flask("SuperKart Sales Predictor") | |
| # Load the trained model pipeline from the file | |
| # This is loaded only once when the application starts | |
| try: | |
| model = joblib.load("superkart_sales_pipeline.joblib") | |
| print("Model loaded successfully.") | |
| except FileNotFoundError: | |
| print("Model file not found. Make sure 'superkart_sales_pipeline.joblib' is in the same directory.") | |
| model = None | |
| except Exception as e: | |
| print(f"An error occurred while loading the model: {e}") | |
| model = None | |
| # Define a root endpoint for a health check | |
| def home(): | |
| """A simple endpoint to confirm the API is running.""" | |
| return "Welcome to the SuperKart Sales Prediction API!" | |
| # Define the main endpoint for making sales predictions | |
| def predict_sales(): | |
| """ | |
| Receives a JSON object with features and returns a sales prediction. | |
| """ | |
| if model is None: | |
| return jsonify({'error': 'Model is not loaded or failed to load.'}), 500 | |
| # Get the JSON data from the request body | |
| input_data = request.get_json() | |
| if not input_data: | |
| return jsonify({'error': 'No input data provided.'}), 400 | |
| try: | |
| # Convert the JSON data into a pandas DataFrame | |
| # The `index=[0]` is crucial for creating a single-row DataFrame | |
| features_df = pd.DataFrame(input_data, index=[0]) | |
| # Make a prediction using the full pipeline | |
| # The pipeline handles all preprocessing steps (scaling, encoding, etc.) | |
| prediction = model.predict(features_df) | |
| # The prediction is a numpy array, so we extract the single value | |
| predicted_value = prediction[0] | |
| # Return the prediction in a JSON response, rounded to 2 decimal places | |
| return jsonify({'predicted_sales': round(predicted_value, 2)}) | |
| except (KeyError, TypeError) as e: | |
| # This catches errors if the input JSON is missing keys or malformed | |
| return jsonify({'error': f'Invalid input data format: {str(e)}'}), 400 | |
| except Exception as e: | |
| # A general catch-all for any other unexpected errors | |
| return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500 | |
| # This block is for deployment environments like Hugging Face Spaces | |
| if __name__ == '__main__': | |
| # The port is determined by the environment variable, defaulting to 7860 | |
| port = int(os.environ.get("PORT", 7860)) | |
| # Running on 0.0.0.0 makes the app accessible from outside the container | |
| app.run(host='0.0.0.0', port=port) | |