File size: 3,697 Bytes
7f13127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c422e69
 
 
 
7f13127
 
 
 
 
 
 
 
 
 
 
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
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

@app.route('/', methods=['GET'])
def home():
    return jsonify({
        'status': 'healthy',
        'message': 'SuperKart Sales Forecasting API',
        'model_loaded': True
    })

@app.route('/predict', methods=['POST'])
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)