Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import joblibimport pandas as pdfrom flask import Flask, request, jsonify
# Initialize Flask appapp = Flask(__name__)
# --- Load the trained model ---try: # Ensure the model file path is correct model = joblib.load('/content/tuned_random_forest_model.joblib') print("Model loaded successfully!")except Exception as e: print(f"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' # This list has 33 elements, check against your actual X.columns.tolist()]# 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 encodingoriginal_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. """ 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')
# 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']
# 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')
# 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)
# 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)
# 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.""")
return final_input
# --- Define API Endpoints ---
@app.route('/')def home(): return "Sales Prediction API. Use /predict endpoint to make predictions."
@app.route('/predict', methods=['POST'])def predict(): if model is None: return jsonify({'error': 'Model not loaded. Please check server logs.'}), 500
try: # Get JSON data from request body data = request.get_json(force=True) if not data: 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: return jsonify({'error': str(ve)}), 400 except Exception as 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__': app.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.")app.pyAdded+132