print('App: app.py is being imported.') import joblib import pandas as pd from flask import Flask, request, jsonify # Initialize Flask app predict_sales_api = Flask("Super Sales Prediction") print("App: Starting Flask application...") # --- Load the trained model --- try: # Ensure the model file path is correct model = joblib.load('tuned_random_forest_model.joblib') print("App: Model loaded successfully!") except Exception as e: print(f"App: Error loading model: {e}") model = None # Set model to None if loading fails # --- Define the exact columns that the model was trained on --- # This list MUST exactly match the columns and their order used during model training (i.e., X_train columns). # You can get this list by running `X.columns.tolist()` in your notebook. # This is a placeholder; please replace it with the actual list from your X DataFrame. # Example: expected_model_columns = X.columns.tolist() expected_model_columns = [ 'Product_Weight', 'Product_Allocated_Area', 'Product_MRP', 'Store_Age', 'Product_Sugar_Content_Low Sugar', 'Product_Sugar_Content_No Sugar', 'Product_Sugar_Content_Regular', 'Product_Type_Baking Goods', 'Product_Type_Breads', 'Product_Type_Breakfast', 'Product_Type_Canned', 'Product_Type_Dairy', 'Product_Type_Frozen Foods', 'Product_Type_Fruits and Vegetables', 'Product_Type_Hard Drinks', 'Product_Type_Health and Hygiene', 'Product_Type_Household', 'Product_Type_Meat', 'Product_Type_Others', 'Product_Type_Seafood', 'Product_Type_Snack Foods', 'Product_Type_Soft Drinks', 'Product_Type_Starchy Foods', 'Store_Size_High', 'Store_Size_Medium', 'Store_Size_Small', 'Store_Location_City_Type_Tier 1', 'Store_Location_City_Type_Tier 2', 'Store_Location_City_Type_Tier 3', 'Store_Type_Departmental Store', 'Store_Type_Food Mart', 'Store_Type_Supermarket Type1', 'Store_Type_Supermarket Type2' ] # Based on the kernel state, X has 31 columns. You must update the above list to match your actual X.columns.tolist() # Identify original categorical features for one-hot encoding original_categorical_features = [ 'Product_Sugar_Content', 'Product_Type', 'Store_Size', 'Store_Location_City_Type', 'Store_Type' ] def preprocess_input(data): """ Preprocesses raw input data to match the format expected by the model. """ print(f"App: Preprocessing input data: {data}") if not data: raise ValueError("Input data cannot be empty.") # Convert input dict to DataFrame input_df = pd.DataFrame([data]) # Ensure all required raw columns are present required_raw_columns = [ 'Product_Id', 'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area', 'Product_Type', 'Product_MRP', 'Store_Id', 'Store_Establishment_Year', 'Store_Size', 'Store_Location_City_Type', 'Store_Type' ] if not all(col in input_df.columns for col in required_raw_columns): raise ValueError(f"Missing one or more required raw input columns. Expected: {required_raw_columns}") # Step 1: Handle typo in Product_Sugar_Content input_df['Product_Sugar_Content'] = input_df['Product_Sugar_Content'].replace('reg', 'Regular') print("App: Handled Product_Sugar_Content typo.") # Step 2: Engineer 'Store_Age' # Assuming the current year for 'Store_Age' calculation is 2024 as in the notebook input_df['Store_Age'] = 2024 - input_df['Store_Establishment_Year'] print("App: Engineered Store_Age.") # Step 3: Drop unnecessary columns (Product_Id, Store_Id, Store_Establishment_Year) input_df = input_df.drop(columns=['Product_Id', 'Store_Id', 'Store_Establishment_Year'], errors='ignore') print("App: Dropped unnecessary columns.") # Step 4: One-hot encode categorical features # Using pd.get_dummies and drop_first=False to get all categories and then reindex to match expected_model_columns processed_df = pd.get_dummies(input_df, columns=original_categorical_features, drop_first=False) print("App: Applied one-hot encoding.") # Step 5: Reindex to ensure all expected columns are present and in the correct order # Fill missing columns (e.g., categories not present in current input) with 0 # Drop extra columns that might arise from new unseen categories during inference final_input = processed_df.reindex(columns=expected_model_columns, fill_value=0) print("App: Reindexed columns to match model's expected features.") # Ensure the number of columns matches the model's expectation if final_input.shape[1] != len(expected_model_columns): raise ValueError(f"""Column mismatch after preprocessing. Expected {len(expected_model_columns)} columns but got {final_input.shape[1]}. Missing columns: {set(expected_model_columns) - set(final_input.columns)}. Extra columns: {set(final_input.columns) - set(expected_model_columns)}. Please verify `expected_model_columns` list.""") print(f"App: Final preprocessed data shape: {final_input.shape}") return final_input # --- Define API Endpoints --- @predict_sales_api.route('/') def home(): return "Sales Prediction API. Use /predict endpoint to make predictions." @predict_sales_api.route('/predict', methods=['POST']) def predict(): if model is None: print("App: Model is None, returning 500.") return jsonify({'error': 'Model not loaded. Please check server logs.'}), 500 try: # Get JSON data from request body data = request.get_json(force=True) print(f"App: Received data for prediction: {data}") if not data: print("App: No input data provided.") return jsonify({'error': 'No input data provided.'}), 400 # Preprocess the input data preprocessed_data = preprocess_input(data) # Make prediction prediction = model.predict(preprocessed_data) # Return prediction as JSON return jsonify({'predicted_sales': prediction.tolist()[0]}) except ValueError as ve: print(f"App: ValueError during prediction: {ve}") return jsonify({'error': str(ve)}), 400 except Exception as e: print(f"App: An unexpected error occurred during prediction: {e}") return jsonify({'error': f'An error occurred during prediction: {e}'}), 500 @predict_sales_api.route('/predict_batch', methods=['POST']) def predict_batch(): if model is None: print("App: Model is None, returning 500.") return jsonify({'error': 'Model not loaded. Please check server logs.'}), 500 try: batch_data = request.get_json(force=True) print(f"App: Received batch data for prediction: {batch_data}") if not isinstance(batch_data, list) or not batch_data: print("App: Invalid batch input. Expected a non-empty list of dictionaries.") return jsonify({'error': 'Invalid batch input. Expected a non-empty list of dictionaries.'}), 400 preprocessed_batch_data = [] for item in batch_data: preprocessed_batch_data.append(preprocess_input(item)) # Concatenate all preprocessed dataframes into a single dataframe for batch prediction final_batch_input = pd.concat(preprocessed_batch_data, ignore_index=True) # Make batch prediction batch_predictions = model.predict(final_batch_input) # Return predictions as JSON list return jsonify({'predicted_sales': batch_predictions.tolist()}) except ValueError as ve: print(f"App: ValueError during batch prediction: {ve}") return jsonify({'error': str(ve)}), 400 except Exception as e: print(f"App: An unexpected error occurred during batch prediction: {e}") return jsonify({'error': f'An error occurred during batch prediction: {e}'}), 500 # --- To run the Flask app (for local testing) --- # For Colab, you typically run it using ngrok or similar, or deploy directly. # This block is commented out because it would block the Colab environment. #if __name__ == '__main__': # predict_sales_api.run(debug=True) print("Flask app code for backend created.")