Spaces:
Sleeping
Sleeping
Force upload app.py - 1754763926
Browse files
app.py
CHANGED
|
@@ -1,37 +1,85 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
import joblib
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
app = Flask(__name__)
|
| 9 |
+
CORS(app)
|
| 10 |
+
|
| 11 |
+
# Load model components using joblib (class requirement)
|
| 12 |
+
print("Loading model components...")
|
| 13 |
+
try:
|
| 14 |
+
deployment_package = joblib.load('models/superkart_minimal.pkl')
|
| 15 |
+
model = deployment_package['model']
|
| 16 |
+
scaler = deployment_package['scaler']
|
| 17 |
+
metadata = deployment_package['metadata']
|
| 18 |
+
print("Model loaded successfully with joblib!")
|
| 19 |
+
except Exception as e:
|
| 20 |
+
print(f"Error loading model: {e}")
|
| 21 |
+
model = None
|
| 22 |
+
scaler = None
|
| 23 |
+
metadata = None
|
| 24 |
+
|
| 25 |
+
@app.route('/', methods=['GET'])
|
| 26 |
+
def home():
|
| 27 |
+
return jsonify({
|
| 28 |
+
'status': 'healthy',
|
| 29 |
+
'message': 'SuperKart Sales Forecasting API',
|
| 30 |
+
'model_loaded': True
|
| 31 |
+
})
|
| 32 |
+
|
| 33 |
+
@app.route('/predict', methods=['POST'])
|
| 34 |
+
def predict_sales():
|
| 35 |
+
try:
|
| 36 |
+
data = request.get_json()
|
| 37 |
+
|
| 38 |
+
# Calculate Store_Age from Store_Establishment_Year (as done in training)
|
| 39 |
+
current_year = 2025 # Use consistent year as in training
|
| 40 |
+
if 'Store_Establishment_Year' in data:
|
| 41 |
+
data['Store_Age'] = current_year - data['Store_Establishment_Year']
|
| 42 |
+
del data['Store_Establishment_Year'] # Remove original field
|
| 43 |
+
|
| 44 |
+
input_df = pd.DataFrame([data])
|
| 45 |
+
|
| 46 |
+
# Apply same preprocessing as training: one-hot encoding for categorical features
|
| 47 |
+
categorical_cols = ['Product_Sugar_Content', 'Product_Type', 'Store_Id', 'Store_Size',
|
| 48 |
+
'Store_Location_City_Type', 'Store_Type']
|
| 49 |
+
|
| 50 |
+
# One-hot encode categorical features (drop_first=True to match training)
|
| 51 |
+
input_encoded = pd.get_dummies(input_df, columns=categorical_cols, drop_first=True)
|
| 52 |
+
|
| 53 |
+
# Ensure we have all the same columns as training (30 features)
|
| 54 |
+
# Define all expected columns from training
|
| 55 |
+
training_columns = [
|
| 56 |
+
'Product_Weight', 'Product_MRP', 'Store_Age',
|
| 57 |
+
'Product_Sugar_Content_No Sugar', 'Product_Sugar_Content_Regular',
|
| 58 |
+
'Product_Type_Breads', 'Product_Type_Breakfast', 'Product_Type_Canned',
|
| 59 |
+
'Product_Type_Dairy', 'Product_Type_Frozen Foods', 'Product_Type_Fruits and Vegetables',
|
| 60 |
+
'Product_Type_Hard Drinks', 'Product_Type_Health and Hygiene', 'Product_Type_Household',
|
| 61 |
+
'Product_Type_Meat', 'Product_Type_Others', 'Product_Type_Seafood',
|
| 62 |
+
'Product_Type_Snack Foods', 'Product_Type_Soft Drinks', 'Product_Type_Starchy Foods',
|
| 63 |
+
'Store_Id_OUT002', 'Store_Id_OUT003', 'Store_Id_OUT004',
|
| 64 |
+
'Store_Size_Medium', 'Store_Size_Small',
|
| 65 |
+
'Store_Location_City_Type_Tier 2', 'Store_Location_City_Type_Tier 3',
|
| 66 |
+
'Store_Type_Food Mart', 'Store_Type_Supermarket Type1', 'Store_Type_Supermarket Type2'
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
# Reindex to match training columns (missing columns filled with 0)
|
| 70 |
+
input_final = input_encoded.reindex(columns=training_columns, fill_value=0)
|
| 71 |
+
|
| 72 |
+
# Scale the input data (essential for correct predictions)
|
| 73 |
+
input_scaled = scaler.transform(input_final)
|
| 74 |
+
prediction = model.predict(input_scaled)
|
| 75 |
+
|
| 76 |
+
return jsonify({
|
| 77 |
+
'prediction': float(prediction[0]),
|
| 78 |
+
'prediction_formatted': f"${prediction[0]:.2f}",
|
| 79 |
+
'status': 'success'
|
| 80 |
+
})
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return jsonify({'error': str(e), 'status': 'failed'}), 500
|
| 83 |
+
|
| 84 |
+
if __name__ == '__main__':
|
| 85 |
+
app.run(host='0.0.0.0', port=7860, debug=False)
|