Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,51 +1,51 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import joblib
|
| 3 |
-
from flask import Flask, request, jsonify
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import logging
|
| 6 |
|
| 7 |
# Initialize flask app with a name
|
| 8 |
-
sales_prediction = Flask(__name__)
|
| 9 |
|
| 10 |
# Configure logging
|
| 11 |
-
logging.basicConfig(level=logging.DEBUG)
|
| 12 |
|
| 13 |
# Load the trained model pipeline
|
| 14 |
-
try:
|
| 15 |
-
model = joblib.load("SuperKart_best_Model.joblib")
|
| 16 |
-
logging.info("Model loaded successfully.")
|
| 17 |
-
except Exception as e:
|
| 18 |
-
logging.error(f"Error loading model: {e}")
|
| 19 |
-
raise
|
| 20 |
|
| 21 |
# Define an endpoint for making predictions
|
| 22 |
-
@sales_prediction.get('/')
|
| 23 |
-
def home():
|
| 24 |
"""
|
| 25 |
This function handles GET requests to the root URL ('/') of the API.
|
| 26 |
It returns a simple welcome message.
|
| 27 |
"""
|
| 28 |
-
return "Welcome to the SuperKart Sales Prediction App!"
|
| 29 |
|
| 30 |
# Define an endpoint for single property prediction (POST request)
|
| 31 |
-
@sales_prediction.post('/v1/predict')
|
| 32 |
-
def predict_sales():
|
| 33 |
"""
|
| 34 |
This function handles POST requests to the '/v1/predict' endpoint.
|
| 35 |
It expects a JSON payload containing property details and returns
|
| 36 |
the predicted rental price as a JSON response.
|
| 37 |
"""
|
| 38 |
# Get the JSON data from the request body
|
| 39 |
-
try:
|
| 40 |
-
business_data = request.get_json()
|
| 41 |
-
logging.debug(f"Received data: {business_data}")
|
| 42 |
-
except Exception as e:
|
| 43 |
-
logging.error(f"Error decoding JSON: {e}")
|
| 44 |
-
return jsonify({'error': f'Invalid JSON: {e}'}), 400
|
| 45 |
|
| 46 |
# Extract relevant features from the JSON data
|
| 47 |
-
try:
|
| 48 |
-
business_data_sample = {
|
| 49 |
'Product_Weight': business_data['Product_Weight'],
|
| 50 |
'Product_Sugar_Content': business_data['Product_Sugar_Content'],
|
| 51 |
'Product_Type': business_data['Product_Type'],
|
|
@@ -55,37 +55,37 @@ def predict_sales():
|
|
| 55 |
'Store_Id': business_data['Store_Id'],
|
| 56 |
'Store_Location_City_Type': business_data['Store_Location_City_Type'],
|
| 57 |
'Store_Type': business_data['Store_Type'],
|
| 58 |
-
'Store_Current_Age': business_data['Store_Current_Age']
|
| 59 |
}
|
| 60 |
-
except KeyError as e:
|
| 61 |
-
logging.error(f"Missing key in JSON data: {e}")
|
| 62 |
-
return jsonify({'error': f'Missing key: {e}'}), 400
|
| 63 |
-
except TypeError as e:
|
| 64 |
-
logging.error(f"Error with data types: {e}")
|
| 65 |
-
return jsonify({'error': f'Incorrect data type: {e}'}), 400
|
| 66 |
|
| 67 |
# Convert the extracted data into a Pandas DataFrame
|
| 68 |
-
try:
|
| 69 |
-
business_df = pd.DataFrame(business_data_sample, index=[0])
|
| 70 |
-
logging.debug(f"DataFrame: {business_df.head().to_string()}")
|
| 71 |
-
except Exception as e:
|
| 72 |
-
logging.error(f"Error creating DataFrame: {e}")
|
| 73 |
-
return jsonify({'error': f'Error creating DataFrame: {e}'}), 500
|
| 74 |
|
| 75 |
# Make predictions using the loaded model
|
| 76 |
-
try:
|
| 77 |
-
prediction = model.predict(business_df)
|
| 78 |
-
logging.debug(f"Prediction: {prediction}")
|
| 79 |
-
except Exception as e:
|
| 80 |
-
logging.error(f"Error during prediction: {e}")
|
| 81 |
-
return jsonify({'error': f'Prediction error: {e}'}), 500
|
| 82 |
|
| 83 |
# Return the prediction as a JSON response
|
| 84 |
-
return jsonify({'prediction': list(prediction)})
|
| 85 |
|
| 86 |
# Define an endpoint for batch prediction (POST request)
|
| 87 |
-
@sales_prediction.post('/v1/batch_predict')
|
| 88 |
-
def batch_predict():
|
| 89 |
"""
|
| 90 |
This function handles POST requests to the '/v1/batch_predict' endpoint.
|
| 91 |
It expects a JSON payload containing a list of property details and returns
|
|
@@ -93,31 +93,31 @@ def batch_predict():
|
|
| 93 |
"""
|
| 94 |
# Get the uploaded CSV file from the request
|
| 95 |
try:
|
| 96 |
-
file = request.files['file']
|
| 97 |
-
logging.debug(f"Received file: {file.filename}")
|
| 98 |
-
except Exception as e:
|
| 99 |
-
logging.error(f"Error getting file: {e}")
|
| 100 |
-
return jsonify({'error': f'Error getting file: {e}'}), 400
|
| 101 |
|
| 102 |
# Read the CSV file into a Pandas DataFrame
|
| 103 |
-
try:
|
| 104 |
-
df = pd.read_csv(file)
|
| 105 |
-
logging.debug(f"DataFrame shape: {df.shape}")
|
| 106 |
-
except Exception as e:
|
| 107 |
-
logging.error(f"Error reading CSV: {e}")
|
| 108 |
-
return jsonify({'error': f'Error reading CSV file: {e}'}), 400
|
| 109 |
|
| 110 |
# Make preductions using the loaded model
|
| 111 |
-
try:
|
| 112 |
-
prediction = model.predict(df)
|
| 113 |
-
logging.debug(f"Prediction: {prediction}")
|
| 114 |
-
except Exception as e:
|
| 115 |
-
logging.error(f"Error during prediction: {e}")
|
| 116 |
-
return jsonify({'error': f'Prediction error: {e}'}), 500
|
| 117 |
|
| 118 |
# Return the prediction as a JSON response
|
| 119 |
-
return jsonify({'prediction': list(prediction)})
|
| 120 |
|
| 121 |
# Run the Flask app if this script is executed
|
| 122 |
-
if __name__ == '__main__':
|
| 123 |
-
sales_prediction.run(debug=True)
|
|
|
|
| 1 |
+
import os # Imports the 'os' module, which provides a way of using operating system dependent functionality
|
| 2 |
+
import joblib # Imports the 'joblib' library, used for efficient serialization and deserialization of Python objects
|
| 3 |
+
from flask import Flask, request, jsonify # Imports specific classes from the 'flask' framework
|
| 4 |
+
import pandas as pd # Imports the 'pandas' library, providing data structures and data analysis tools
|
| 5 |
+
import logging # Imports the 'logging' module, used for logging events that occur during the execution of the program
|
| 6 |
|
| 7 |
# Initialize flask app with a name
|
| 8 |
+
sales_prediction = Flask(__name__) # Creates an instance of the Flask class
|
| 9 |
|
| 10 |
# Configure logging
|
| 11 |
+
logging.basicConfig(level=logging.DEBUG) # Configures the logging system to record all events at DEBUG level and above
|
| 12 |
|
| 13 |
# Load the trained model pipeline
|
| 14 |
+
try: # Tries to load the model from a file
|
| 15 |
+
model = joblib.load("SuperKart_best_Model.joblib") # # Attempts to load the pre-trained machine learning model pipeline
|
| 16 |
+
logging.info("Model loaded successfully.") # Logs an informational message indicating that the model was loaded without errors
|
| 17 |
+
except Exception as e: # If an error occurs during the loading process
|
| 18 |
+
logging.error(f"Error loading model: {e}") # Logs an error message containing the specific error that occurred
|
| 19 |
+
raise # Raises the exception to propagate it to the caller
|
| 20 |
|
| 21 |
# Define an endpoint for making predictions
|
| 22 |
+
@sales_prediction.get('/') # Decorator that registers the home() function to handle GET requests
|
| 23 |
+
def home(): # Function that handles GET requests to the root URL ('/') of the API
|
| 24 |
"""
|
| 25 |
This function handles GET requests to the root URL ('/') of the API.
|
| 26 |
It returns a simple welcome message.
|
| 27 |
"""
|
| 28 |
+
return "Welcome to the SuperKart Sales Prediction App!"
|
| 29 |
|
| 30 |
# Define an endpoint for single property prediction (POST request)
|
| 31 |
+
@sales_prediction.post('/v1/predict') # Decorator that registers the predict_sales() function to handle POST requests to the '/v1/predict' endpoint
|
| 32 |
+
def predict_sales(): # Function that handles POST requests to the '/v1/predict' endpoint
|
| 33 |
"""
|
| 34 |
This function handles POST requests to the '/v1/predict' endpoint.
|
| 35 |
It expects a JSON payload containing property details and returns
|
| 36 |
the predicted rental price as a JSON response.
|
| 37 |
"""
|
| 38 |
# Get the JSON data from the request body
|
| 39 |
+
try: # Tries to decode the JSON data from the request body
|
| 40 |
+
business_data = request.get_json() # Attempts to retrieve the JSON data sent in the body of the POST request
|
| 41 |
+
logging.debug(f"Received data: {business_data}") # Logs the received data at the DEBUG level
|
| 42 |
+
except Exception as e: # Catches any exception that occurs during JSON decoding
|
| 43 |
+
logging.error(f"Error decoding JSON: {e}") # Logs an error message containing the specific JSON decoding error
|
| 44 |
+
return jsonify({'error': f'Invalid JSON: {e}'}), 400 # Returns a JSON response with an error message and a 400 Bad Request status code
|
| 45 |
|
| 46 |
# Extract relevant features from the JSON data
|
| 47 |
+
try: # Tries to decode the JSON data from the request body
|
| 48 |
+
business_data_sample = { # Creates a dictionary containing the features required for prediction, extracted from the received JSON data
|
| 49 |
'Product_Weight': business_data['Product_Weight'],
|
| 50 |
'Product_Sugar_Content': business_data['Product_Sugar_Content'],
|
| 51 |
'Product_Type': business_data['Product_Type'],
|
|
|
|
| 55 |
'Store_Id': business_data['Store_Id'],
|
| 56 |
'Store_Location_City_Type': business_data['Store_Location_City_Type'],
|
| 57 |
'Store_Type': business_data['Store_Type'],
|
| 58 |
+
'Store_Current_Age': business_data['Store_Current_Age']
|
| 59 |
}
|
| 60 |
+
except KeyError as e: # Catches a KeyError if a required key is missing from the input JSON data
|
| 61 |
+
logging.error(f"Missing key in JSON data: {e}") # Logs an error message containing the specific JSON decoding error
|
| 62 |
+
return jsonify({'error': f'Missing key: {e}'}), 400 # Returns a JSON response with an error message and a 400 Bad Request status code
|
| 63 |
+
except TypeError as e: # Catches a TypeError if the data type of a value in the JSON data is incorrect
|
| 64 |
+
logging.error(f"Error with data types: {e}") # Logs an error message containing the specific JSON decoding error
|
| 65 |
+
return jsonify({'error': f'Incorrect data type: {e}'}), 400 # Returns a JSON response with an error message and a 400 Bad Request status code
|
| 66 |
|
| 67 |
# Convert the extracted data into a Pandas DataFrame
|
| 68 |
+
try: # Tries to decode the JSON data from the request body
|
| 69 |
+
business_df = pd.DataFrame(business_data_sample, index=[0]) # Creates a Pandas DataFrame from the extracted feature dictionary, with a single row
|
| 70 |
+
logging.debug(f"DataFrame: {business_df.head().to_string()}") # Logs the first few rows of the DataFrame as a string
|
| 71 |
+
except Exception as e: # Catches any exception that occurs during DataFrame creation
|
| 72 |
+
logging.error(f"Error creating DataFrame: {e}") # Logs an error message containing the DataFrame creation error
|
| 73 |
+
return jsonify({'error': f'Error creating DataFrame: {e}'}), 500 # Returns a JSON response with an error message and a 500 Internal Server Error status code
|
| 74 |
|
| 75 |
# Make predictions using the loaded model
|
| 76 |
+
try: # Tries to make predictions using the loaded model
|
| 77 |
+
prediction = model.predict(business_df) # Uses the loaded machine learning model to predict the sales for the input data in the DataFrame
|
| 78 |
+
logging.debug(f"Prediction: {prediction}") # Logs the prediction result
|
| 79 |
+
except Exception as e: # Catches any exception that occurs during the prediction process
|
| 80 |
+
logging.error(f"Error during prediction: {e}") # Logs an error message containing the specific prediction error
|
| 81 |
+
return jsonify({'error': f'Prediction error: {e}'}), 500 # Returns a JSON response with an error message and a 500 Internal Server Error status code
|
| 82 |
|
| 83 |
# Return the prediction as a JSON response
|
| 84 |
+
return jsonify({'prediction': list(prediction)}) # Returns the prediction as a JSON object
|
| 85 |
|
| 86 |
# Define an endpoint for batch prediction (POST request)
|
| 87 |
+
@sales_prediction.post('/v1/batch_predict') # Decorator that registers the batch_predict() function to handle POST requests to the '/v1/batch_predict' endpoint
|
| 88 |
+
def batch_predict():
|
| 89 |
"""
|
| 90 |
This function handles POST requests to the '/v1/batch_predict' endpoint.
|
| 91 |
It expects a JSON payload containing a list of property details and returns
|
|
|
|
| 93 |
"""
|
| 94 |
# Get the uploaded CSV file from the request
|
| 95 |
try:
|
| 96 |
+
file = request.files['file'] # Attempts to retrieve the uploaded file from the request
|
| 97 |
+
logging.debug(f"Received file: {file.filename}") # Logs the filename of the uploaded file
|
| 98 |
+
except Exception as e: # Catches any exception that occurs while getting the file
|
| 99 |
+
logging.error(f"Error getting file: {e}") # Logs an error message containing the file retrieval error
|
| 100 |
+
return jsonify({'error': f'Error getting file: {e}'}), 400 # Returns a JSON response with an error message and a 400 Bad Request status code
|
| 101 |
|
| 102 |
# Read the CSV file into a Pandas DataFrame
|
| 103 |
+
try: # Tries to read the CSV file into a Pandas DataFrame
|
| 104 |
+
df = pd.read_csv(file) # Reads the uploaded CSV file into a Pandas DataFrame
|
| 105 |
+
logging.debug(f"DataFrame shape: {df.shape}") # Logs the shape of the DataFrame
|
| 106 |
+
except Exception as e: # Catches any exception that occurs during CSV reading
|
| 107 |
+
logging.error(f"Error reading CSV: {e}") # Logs an error message containing the CSV reading error
|
| 108 |
+
return jsonify({'error': f'Error reading CSV file: {e}'}), 400 # Returns a JSON response with an error message and a 400 Bad Request status code
|
| 109 |
|
| 110 |
# Make preductions using the loaded model
|
| 111 |
+
try: # Tries to make predictions using the loaded model
|
| 112 |
+
prediction = model.predict(df) # Uses the loaded machine learning model to predict sales for the data in the DataFrame
|
| 113 |
+
logging.debug(f"Prediction: {prediction}") # Logs the prediction result
|
| 114 |
+
except Exception as e: # Catches any exception that occurs during the prediction process
|
| 115 |
+
logging.error(f"Error during prediction: {e}") # Logs an error message containing the prediction error
|
| 116 |
+
return jsonify({'error': f'Prediction error: {e}'}), 500 # Returns a JSON response with an error message and a 500 Internal Server Error status code
|
| 117 |
|
| 118 |
# Return the prediction as a JSON response
|
| 119 |
+
return jsonify({'prediction': list(prediction)}) # Returns the prediction as a JSON object
|
| 120 |
|
| 121 |
# Run the Flask app if this script is executed
|
| 122 |
+
if __name__ == '__main__':
|
| 123 |
+
sales_prediction.run(debug=True) # Starts the Flask development server if the script is run directly with debug mode enabled
|