Spaces:
Runtime error
Runtime error
| # Import necessary libraries | |
| import numpy as np | |
| import joblib # For loading the serialized model | |
| import pandas as pd # For data manipualation | |
| from flask import Flask, jsonify, request # For creating Flask API | |
| # Intialize the Flask application | |
| # Correcting the inconsistent variable name to SuperKart_predictions_api | |
| SuperKart_predictions_api = Flask("SuperKart K model") | |
| # Load the serialized model | |
| # Ensure the model file path is correct relative to where the app runs in the container | |
| try: | |
| model = joblib.load("best_superkart_sales_model.joblib") | |
| print("Model loaded successfully.") | |
| except FileNotFoundError: | |
| print("Error: Model file 'best_superkart_sales_model.joblib' not found.") | |
| model = None # Set model to None if loading fails | |
| except Exception as e: | |
| print(f"Error loading model: {e}") | |
| model = None | |
| # Define a route for home page(GET request) | |
| # Use the correct variable name here | |
| def home(): | |
| """ | |
| This function handles GET requests to the root URL ('/') of the API. | |
| It returns a simple welcome message. | |
| """ | |
| return "Welcome to SuperKart!" | |
| # Define an endpoint | |
| # Use the correct variable name and specify POST method | |
| def predict(): | |
| """ | |
| This function handles POST requests to the '/v1/SuperKart' endpoint. | |
| It expects a JSON payload containing the data for prediction, | |
| uses the loaded model to make predictions, and returns the predictions. | |
| """ | |
| # Check if the model was loaded successfully | |
| if model is None: | |
| return jsonify({"error": "Model is not available. Cannot make predictions."}), 500 | |
| try: | |
| # Get the JSON data from the request | |
| # The data is expected to be a list of dictionaries, where each dictionary | |
| # represents a single data point with features. | |
| data = request.get_json() | |
| # Convert the JSON data to a pandas DataFrame | |
| # Ensure the column names in the JSON match the feature names expected by the model's preprocessor | |
| input_df = pd.DataFrame(data) | |
| # Make predictions using the loaded model | |
| # The loaded model object (which is a Pipeline) handles both preprocessing and prediction | |
| predictions = model.predict(input_df) | |
| # Convert the numpy array of predictions to a list for JSON serialization | |
| predictions_list = predictions.tolist() | |
| # Return the predictions as a JSON response | |
| return jsonify({"predictions": predictions_list}) | |
| except Exception as e: | |
| # Return an error response if an exception occurs during processing (e.g., invalid input data) | |
| return jsonify({"error": f"An error occurred during prediction: {e}"}), 400 # Use 400 for client-side errors | |
| # This block is for local development and testing only. | |
| # When deployed with Gunicorn on Hugging Face Spaces, this code is not executed. | |
| if __name__ == "__main__": | |
| # Run the Flask app locally on port 7860 (common for Hugging Face Spaces) | |
| # host="0.0.0.0" makes the server accessible externally (needed in Docker containers) | |
| # debug=False for production deployment | |
| SuperKart_predictions_api.run(host="0.0.0.0", port=7860, debug=False) | |