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 list of 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. # 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) # REVISING BACKEND LOGIC to handle original categories and then encode. # 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 # Use the model_columns to ensure consistency and handle potential missing dummy 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 with 0 or False (model was trained with booleans from get_dummies) input_df_encoded = temp_df.reindex(columns=model_columns, fill_value=False) # 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 # Consider a more robust imputation strategy than mean if needed input_df_encoded[col] = input_df_encoded[col].fillna(0) # Fill NaNs with 0 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