Spaces:
Sleeping
Sleeping
Download app.py from HacksterT/GreatLearningProject: direct link, hf CLI and curl.
- Browser
- Download file 3.7 kB
-
https://huggingface.co/spaces/HacksterT/GreatLearningProject/resolve/main/app.py
- Command line
-
hf download hf://spaces/HacksterT/GreatLearningProject/app.py
-
curl -L -o app.py https://huggingface.co/spaces/HacksterT/GreatLearningProject/resolve/main/app.py
3.7 kB
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| import joblib | |
| import pandas as pd | |
| import numpy as np | |
| from datetime import datetime | |
| app = Flask(__name__) | |
| CORS(app) | |
| # Load model components using joblib (class requirement) | |
| print("Loading model components...") | |
| try: | |
| deployment_package = joblib.load('models/superkart_minimal.pkl') | |
| model = deployment_package['model'] | |
| scaler = deployment_package['scaler'] | |
| metadata = deployment_package['metadata'] | |
| print("Model loaded successfully with joblib!") | |
| except Exception as e: | |
| print(f"Error loading model: {e}") | |
| model = None | |
| scaler = None | |
| metadata = None | |
| def home(): | |
| return jsonify({ | |
| 'status': 'healthy', | |
| 'message': 'SuperKart Sales Forecasting API', | |
| 'model_loaded': True | |
| }) | |
| def predict_sales(): | |
| try: | |
| data = request.get_json() | |
| # Calculate Store_Age from Store_Establishment_Year (as done in training) | |
| current_year = 2025 # Use consistent year as in training | |
| if 'Store_Establishment_Year' in data: | |
| data['Store_Age'] = current_year - data['Store_Establishment_Year'] | |
| del data['Store_Establishment_Year'] # Remove original field | |
| input_df = pd.DataFrame([data]) | |
| # Apply same preprocessing as training: one-hot encoding for categorical features | |
| categorical_cols = ['Product_Sugar_Content', 'Product_Type', 'Store_Id', 'Store_Size', | |
| 'Store_Location_City_Type', 'Store_Type'] | |
| # One-hot encode categorical features (drop_first=True to match training) | |
| input_encoded = pd.get_dummies(input_df, columns=categorical_cols, drop_first=True) | |
| # Ensure we have all the same columns as training (30 features) | |
| # Define all expected columns from training | |
| training_columns = [ | |
| 'Product_Weight', 'Product_MRP', 'Store_Age', | |
| 'Product_Sugar_Content_No Sugar', 'Product_Sugar_Content_Regular', | |
| '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_Id_OUT002', 'Store_Id_OUT003', 'Store_Id_OUT004', | |
| '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' | |
| ] | |
| # Reindex to match training columns (missing columns filled with 0) | |
| input_final = input_encoded.reindex(columns=training_columns, fill_value=0) | |
| # CRITICAL: Apply scaler ONLY to numerical columns (as done in training) | |
| numerical_cols = ['Product_Weight', 'Product_MRP', 'Store_Age'] | |
| input_final[numerical_cols] = scaler.transform(input_final[numerical_cols]) | |
| prediction = model.predict(input_final) | |
| return jsonify({ | |
| 'prediction': float(prediction[0]), | |
| 'prediction_formatted': f"${prediction[0]:.2f}", | |
| 'status': 'success' | |
| }) | |
| except Exception as e: | |
| return jsonify({'error': str(e), 'status': 'failed'}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860, debug=False) | |