Spaces:
Runtime error
Runtime error
File size: 7,083 Bytes
eece79b 173bfa1 eece79b 173bfa1 584b32f 173bfa1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | 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_Low',
'Store_Size_Medium',
'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():
print("App: Home endpoint accessed.")
return "Sales Prediction API. Use /predict endpoint to make predictions."
@predict_sales_api.route('/predict', methods=['POST'])
def predict():
print("App: /predict endpoint accessed.")
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)
print("App: Input data preprocessed.")
# Make prediction
prediction = model.predict(preprocessed_data)
print(f"App: Prediction made: {prediction}")
# 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
# --- 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. You will need to run this code and potentially expose it via a service like ngrok or deploy it to a platform like Hugging Face Spaces.")
|