File size: 3,249 Bytes
802d8fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# 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)
@SuperKart_predictions_api.route('/') # 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
@SuperKart_predictions_api.route('/v1/SuperKart', methods=['POST']) # 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)