smartC / app.py
Drrevcade's picture
Upload folder using huggingface_hub
6d82fdf verified
Raw History Blame Contribute Delete
8.92 kB
from flask import Flask, request, jsonify
import joblib
import pandas as pd
import numpy as np
# Load the saved best model
# The path needs to be correct relative to where the app runs in the Docker container
model = joblib.load('best_model.joblib')
# Create a Flask application instance
app = Flask(__name__)
# Define the columns the model was trained on to ensure correct input format
# This is crucial for consistent input to the loaded model
# Need to refer to the columns of X or X_train
# Based on the notebook state, X_train has the correct columns after one-hot encoding
# Since we cannot directly access X_train here, we need to save the model columns
# or infer them from a small sample of processed data.
# For now, let's assume model_columns are saved separately or can be loaded.
# A safer approach would be to save the list of columns during model training/saving.
# For this example, let's hardcode a placeholder or load from a dummy file if available.
# **NOTE:** In a real-world scenario, ensure model_columns is correctly loaded or defined.
# Let's use a placeholder for now and assume it will be handled correctly during deployment setup.
# A better way is to include the column names in the saved model object or a separate file.
# Assuming model_columns are available in the environment or loaded:
# model_columns = loaded_model_columns
# A robust way is to save the columns along with the model.
# Since that wasn't done in the previous step, and we can't execute arbitrary code
# to regenerate or save the columns, we will proceed assuming model_columns
# will be handled externally during deployment setup or is embedded in the model
# if joblib handles that (it doesn't by default).
# A practical workaround for deployment without re-running previous steps
# is to manually inspect the X_train columns from the notebook state
# and include them in the deployment package or hardcode if they are stable.
# For demonstration, let's use a placeholder and a comment for the actual deployment step.
# For this subtask, we will define the expected structure based on the X_train variable from the notebook state.
# This is a workaround due to the constraints of the current environment.
model_columns = ['Product_Weight', 'Product_Allocated_Area', 'Product_MRP', 'Store_Age',
'Product_Sugar_Content_No Sugar', 'Product_Sugar_Content_Regular', 'Product_Sugar_Content_reg',
'Store_Size_Medium', 'Store_Size_Small', 'Store_Location_City_Type_Tier 2', 'Store_Location_City_Type_Tier 3',
'Store_Type_Food Mart', 'Store_Type_Supermarket Type1', 'Store_Type_Supermarket Type2',
'Product_Identifier_Type_FD', 'Product_Identifier_Type_NC', 'Product_Category_Perishable',
'Store_Id_OUT002', 'Store_Id_OUT003', 'Store_Id_OUT004'] # Manually retrieved from notebook state X_train.columns
@app.route('/predict', methods=['POST'])
def predict():
# Get the JSON data from the incoming request
data = request.get_json(force=True)
# Convert the received JSON data into a pandas DataFrame
# Ensure the column order matches the training data (model_columns)
try:
# Assuming the incoming JSON is a list of dictionaries, where each dictionary is a sample
input_df = pd.DataFrame(data)
# Reindex the DataFrame to ensure the columns are in the same order as the training data
# Handle potential missing columns by adding them with a default value (0 for numerical, False for booleans)
# Handle potential extra columns by dropping them
# Identify boolean columns from model_columns (these are the one-hot encoded ones)
bool_cols = [col for col in model_columns if any(sub in col for sub in ['Sugar_Content', 'Store_Size', 'Location_City_Type', 'Store_Type', 'Identifier_Type', 'Category', 'Store_Id'])]
# Create a new DataFrame with the correct columns and default values
processed_input = pd.DataFrame(columns=model_columns)
# Populate the new DataFrame with data from input_df
for col in model_columns:
if col in input_df.columns:
# For boolean columns, map the original categorical value to the correct one-hot encoded column
if col in bool_cols:
# Assuming input_df has the original categorical column (e.g., 'Product_Sugar_Content')
# We need to map the input category to the correct one-hot encoded column.
# This requires knowing the mapping from original category to dummy column name.
# A simpler approach for the backend is to expect already encoded data from the frontend,
# or to have the mapping logic here.
# Given the frontend sends original categories, the backend must perform encoding.
# Let's adjust the backend logic to handle original categories and then encode.
# This backend logic needs to be revised to perform the same encoding as done during training.
# The current approach of reindexing expects the frontend to send the dummy columns,
# which is not what the frontend code does (it sends original categories).
# REVISING BACKEND LOGIC:
# The backend should receive the original categorical values and then perform one-hot encoding
# using the same logic and expected columns as during training.
# To do this robustly, the backend needs access to the list of original categorical columns
# and the mapping of categories to dummy column names.
# Since we can't re-run the feature engineering step here, we will again use a workaround
# based on the known steps and columns from the notebook state.
# Expected original categorical columns based on notebook state:
original_categorical_cols = ['Product_Sugar_Content', 'Store_Size', 'Store_Location_City_Type',
'Store_Type', 'Product_Identifier_Type', 'Product_Category', 'Store_Id']
# Create a DataFrame from the input data (expecting original columns)
temp_df = pd.DataFrame(data)
# Perform one-hot encoding on the received original categorical columns
temp_df = pd.get_dummies(temp_df, columns=original_categorical_cols, drop_first=True)
# Now, reindex this *encoded* temporary DataFrame to match the model_columns
# Fill missing dummy columns (those not present in the input sample) with False or 0
# The model was trained with booleans, so False is appropriate.
input_df_encoded = temp_df.reindex(columns=model_columns, fill_value=False)
else:
# For numerical or other non-encoded columns, just copy the value
processed_input[col] = input_df[col]
else:
# Handle columns that were in model_columns but not in the input (shouldn't happen with the revised logic)
processed_input[col] = False # Default for dummy variables
# Ensure numerical columns are correct dtype (e.g., float) if necessary
for col in ['Product_Weight', 'Product_Allocated_Area', 'Product_MRP', 'Store_Age']:
if col in input_df_encoded.columns:
input_df_encoded[col] = pd.to_numeric(input_df_encoded[col], errors='coerce')
# Handle potential NaNs from coercion if input was not numeric
input_df_encoded[col] = input_df_encoded[col].fillna(input_df_encoded[col].mean()) # Or another imputation strategy
except Exception as e:
return jsonify({'error': f'Error processing input data for encoding: {e}'}), 400
# Use the loaded model to make a prediction on the processed input data
try:
# Ensure the processed input DataFrame has the correct column order before prediction
input_df_for_prediction = input_df_encoded[model_columns]
predictions = model.predict(input_df_for_prediction)
# Convert predictions to a list for JSON serialization
predictions_list = predictions.tolist()
except Exception as e:
return jsonify({'error': f'Error making prediction: {e}'}), 500
# Return the prediction result as a JSON response
return jsonify(predictions=predictions_list)
# Add a simple root route for health check or info
@app.route('/')
def index():
return "SuperKart Sales Forecasting Backend is running!"
if __name__ == '__main__':
# For local testing
# app.run(debug=True)
pass # Will be run by Gunicorn or similar in deployment