Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,119 +1,101 @@
|
|
| 1 |
-
#
|
| 2 |
-
|
| 3 |
-
#
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
import pandas as pd
|
| 7 |
-
from flask import Flask, request, jsonify
|
| 8 |
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
app = Flask("APP")
|
| 13 |
-
|
| 14 |
-
# Load trained model
|
| 15 |
try:
|
| 16 |
model = joblib.load("superkart_sales_model.pkl")
|
| 17 |
-
print("Model loaded successfully")
|
| 18 |
except Exception as e:
|
| 19 |
-
print("ERROR loading model:
|
| 20 |
-
raise
|
| 21 |
-
|
| 22 |
-
# Required columns expected by the trained pipeline
|
| 23 |
-
REQUIRED_COLUMNS = [
|
| 24 |
-
"Product_Weight",
|
| 25 |
-
"Product_Allocated_Area",
|
| 26 |
-
"Product_MRP",
|
| 27 |
-
"Store_Current_Age",
|
| 28 |
-
"Product_Sugar_Content",
|
| 29 |
-
"Store_Id",
|
| 30 |
-
"Store_Size",
|
| 31 |
-
"Store_Location_City_Type",
|
| 32 |
-
"Store_Type",
|
| 33 |
-
"Product_Id",
|
| 34 |
-
"Product_Type"
|
| 35 |
-
]
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
# -------------------------------
|
| 40 |
-
@app.get("/")
|
| 41 |
def home():
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
#
|
| 50 |
-
@
|
| 51 |
def predict_sales():
|
| 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 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
def predict_sales_batch():
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
if col not in df.columns:
|
| 98 |
-
df[col] = None
|
| 99 |
|
| 100 |
-
|
|
|
|
| 101 |
|
| 102 |
-
|
|
|
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
})
|
| 107 |
|
| 108 |
-
except Exception as e:
|
| 109 |
-
print("Batch prediction error:", str(e))
|
| 110 |
-
return jsonify({
|
| 111 |
-
"error": "Batch prediction failed",
|
| 112 |
-
"details": str(e)
|
| 113 |
-
}), 500
|
| 114 |
|
| 115 |
# -------------------------------
|
| 116 |
# Local Run (Not used on HF)
|
| 117 |
# -------------------------------
|
| 118 |
if __name__ == "__main__":
|
| 119 |
-
app.
|
|
|
|
| 1 |
+
# Import necessary libraries
|
| 2 |
+
import numpy as np
|
| 3 |
+
import joblib # For loading the serialized model
|
| 4 |
+
import pandas as pd # For data manipulation
|
| 5 |
+
from flask import Flask, request, jsonify # For creating the Flask API
|
| 6 |
|
| 7 |
+
print("--- app.py: Starting Flask application setup ---")
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Initialize the Flask application
|
| 10 |
+
superkart_sales_api = Flask("SuperKart Sales Predictor")
|
| 11 |
+
print("--- app.py: Flask app initialized ---")
|
| 12 |
|
| 13 |
+
# Load the trained machine learning model
|
|
|
|
|
|
|
|
|
|
| 14 |
try:
|
| 15 |
model = joblib.load("superkart_sales_model.pkl")
|
| 16 |
+
print("--- app.py: Model loaded successfully ---")
|
| 17 |
except Exception as e:
|
| 18 |
+
print(f"--- app.py: ERROR loading model: {e} ---")
|
| 19 |
+
raise # Re-raise to ensure the error is visible
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# Define a route for the home page (GET request)
|
| 22 |
+
@superkart_sales_api.get('/')
|
|
|
|
|
|
|
| 23 |
def home():
|
| 24 |
+
print("--- API: Home route accessed ---")
|
| 25 |
+
"""
|
| 26 |
+
This function handles GET requests to the root URL ('/') of the API.
|
| 27 |
+
It returns a simple welcome message.
|
| 28 |
+
"""
|
| 29 |
+
return "Welcome to the SuperKart Sales Prediction API!"
|
| 30 |
+
|
| 31 |
+
# Define an endpoint for single sales prediction (POST request)
|
| 32 |
+
@superkart_sales_api.post('/v1/sales')
|
| 33 |
def predict_sales():
|
| 34 |
+
print("--- API: Single sales prediction route accessed ---")
|
| 35 |
+
"""
|
| 36 |
+
This function handles POST requests to the '/v1/sales' endpoint.
|
| 37 |
+
It expects a JSON payload containing product and store details and returns
|
| 38 |
+
the predicted sales as a JSON response.
|
| 39 |
+
"""
|
| 40 |
+
# Get the JSON data from the request body
|
| 41 |
+
input_data_json = request.get_json()
|
| 42 |
+
|
| 43 |
+
# Extract relevant features from the JSON data, matching x_train columns
|
| 44 |
+
# The model expects original feature names before one-hot encoding
|
| 45 |
+
sample = {
|
| 46 |
+
'Product_Id': input_data_json['Product_Id'],
|
| 47 |
+
'Product_Weight': input_data_json['Product_Weight'],
|
| 48 |
+
'Product_Sugar_Content': input_data_json['Product_Sugar_Content'],
|
| 49 |
+
'Product_Allocated_Area': input_data_json['Product_Allocated_Area'],
|
| 50 |
+
'Product_Type': input_data_json['Product_Type'],
|
| 51 |
+
'Product_MRP': input_data_json['Product_MRP'],
|
| 52 |
+
'Store_Id': input_data_json['Store_Id'],
|
| 53 |
+
'Store_Type': input_data_json['Store_type'],
|
| 54 |
+
'Store_Size': input_data_json['Store_Size'],
|
| 55 |
+
'Store_Location_City_Type': input_data_json['Store_Location_City_Type'],
|
| 56 |
+
'Store_Current_Age': input_data_json['Store_Current_Age']
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
# Convert the extracted data into a Pandas DataFrame
|
| 60 |
+
input_df = pd.DataFrame([sample])
|
| 61 |
+
|
| 62 |
+
# Make prediction
|
| 63 |
+
predicted_sales = model.predict(input_df)[0]
|
| 64 |
+
|
| 65 |
+
# Convert predicted_sales to Python float and round
|
| 66 |
+
predicted_sales = round(float(predicted_sales), 2)
|
| 67 |
+
|
| 68 |
+
# Return the predicted sales
|
| 69 |
+
return jsonify({'Predicted Sales': predicted_sales})
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Define an endpoint for batch prediction (POST request)
|
| 73 |
+
@superkart_sales_api.post('/v1/salesbatch')
|
| 74 |
def predict_sales_batch():
|
| 75 |
+
print("--- API: Batch sales prediction route accessed ---")
|
| 76 |
+
"""
|
| 77 |
+
This function handles POST requests to the '/v1/salesbatch' endpoint.
|
| 78 |
+
It expects a CSV file containing product and store details for multiple entries
|
| 79 |
+
and returns the predicted sales as a list in the JSON response.
|
| 80 |
+
"""
|
| 81 |
+
# Get the uploaded CSV file from the request
|
| 82 |
+
file = request.files['file']
|
| 83 |
|
| 84 |
+
# Read the CSV file into a Pandas DataFrame
|
| 85 |
+
input_df_batch = pd.read_csv(file)
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
# Make predictions for all entries in the DataFrame
|
| 88 |
+
predicted_sales_batch = model.predict(input_df_batch).tolist()
|
| 89 |
|
| 90 |
+
# Round each prediction and convert to float
|
| 91 |
+
predicted_sales_batch = [round(float(s), 2) for s in predicted_sales_batch]
|
| 92 |
|
| 93 |
+
# Return the predictions list as a JSON response
|
| 94 |
+
return jsonify({'Predicted Sales': predicted_sales_batch})
|
|
|
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
# -------------------------------
|
| 98 |
# Local Run (Not used on HF)
|
| 99 |
# -------------------------------
|
| 100 |
if __name__ == "__main__":
|
| 101 |
+
app.superkart_sales_api(dedug=True)
|