HumanMachine74 commited on
Commit
802d8fe
·
verified ·
1 Parent(s): 19ec263

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import numpy as np
3
+ import joblib # For loading the serialized model
4
+ import pandas as pd # For data manipualation
5
+ from flask import Flask, jsonify, request # For creating Flask API
6
+
7
+ # Intialize the Flask application
8
+ # Correcting the inconsistent variable name to SuperKart_predictions_api
9
+ SuperKart_predictions_api = Flask("SuperKart K model")
10
+
11
+ # Load the serialized model
12
+ # Ensure the model file path is correct relative to where the app runs in the container
13
+ try:
14
+ model = joblib.load("best_superkart_sales_model.joblib")
15
+ print("Model loaded successfully.")
16
+ except FileNotFoundError:
17
+ print("Error: Model file 'best_superkart_sales_model.joblib' not found.")
18
+ model = None # Set model to None if loading fails
19
+ except Exception as e:
20
+ print(f"Error loading model: {e}")
21
+ model = None
22
+
23
+
24
+ # Define a route for home page(GET request)
25
+ @SuperKart_predictions_api.route('/') # Use the correct variable name here
26
+ def home():
27
+ """
28
+ This function handles GET requests to the root URL ('/') of the API.
29
+ It returns a simple welcome message.
30
+ """
31
+ return "Welcome to SuperKart!"
32
+
33
+ # Define an endpoint
34
+ @SuperKart_predictions_api.route('/v1/SuperKart', methods=['POST']) # Use the correct variable name and specify POST method
35
+ def predict():
36
+ """
37
+ This function handles POST requests to the '/v1/SuperKart' endpoint.
38
+ It expects a JSON payload containing the data for prediction,
39
+ uses the loaded model to make predictions, and returns the predictions.
40
+ """
41
+ # Check if the model was loaded successfully
42
+ if model is None:
43
+ return jsonify({"error": "Model is not available. Cannot make predictions."}), 500
44
+
45
+ try:
46
+ # Get the JSON data from the request
47
+ # The data is expected to be a list of dictionaries, where each dictionary
48
+ # represents a single data point with features.
49
+ data = request.get_json()
50
+
51
+ # Convert the JSON data to a pandas DataFrame
52
+ # Ensure the column names in the JSON match the feature names expected by the model's preprocessor
53
+ input_df = pd.DataFrame(data)
54
+
55
+ # Make predictions using the loaded model
56
+ # The loaded model object (which is a Pipeline) handles both preprocessing and prediction
57
+ predictions = model.predict(input_df)
58
+
59
+ # Convert the numpy array of predictions to a list for JSON serialization
60
+ predictions_list = predictions.tolist()
61
+
62
+ # Return the predictions as a JSON response
63
+ return jsonify({"predictions": predictions_list})
64
+
65
+ except Exception as e:
66
+ # Return an error response if an exception occurs during processing (e.g., invalid input data)
67
+ return jsonify({"error": f"An error occurred during prediction: {e}"}), 400 # Use 400 for client-side errors
68
+
69
+
70
+ # This block is for local development and testing only.
71
+ # When deployed with Gunicorn on Hugging Face Spaces, this code is not executed.
72
+ if __name__ == "__main__":
73
+ # Run the Flask app locally on port 7860 (common for Hugging Face Spaces)
74
+ # host="0.0.0.0" makes the server accessible externally (needed in Docker containers)
75
+ # debug=False for production deployment
76
+ SuperKart_predictions_api.run(host="0.0.0.0", port=7860, debug=False)