File size: 3,087 Bytes
cb3df2e
 
011848c
 
 
cb3df2e
 
 
 
 
 
 
011848c
cb3df2e
 
 
7e8684a
cb3df2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e8684a
cb3df2e
 
 
 
 
 
011848c
 
 
 
 
 
cb3df2e
 
011848c
cb3df2e
 
 
011848c
 
cb3df2e
 
 
7e8684a
011848c
 
 
 
cb3df2e
 
011848c
 
cb3df2e
 
 
 
 
 
011848c
cb3df2e
7e8684a
011848c
cb3df2e
 
 
7e8684a
cb3df2e
 
 
 
 
011848c
 
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

import numpy as np
import joblib
import pandas as pd
from flask import Flask, request, jsonify
import os

APP_DIR = os.path.dirname(os.path.abspath(__file__))

# Initialize Flask app
superkart_api = Flask("superkart_predictor")

# Load preprocessor and model
try:
    preprocessor_path = os.path.join(APP_DIR, "preprocessor.joblib")
    model_path = os.path.join(APP_DIR, "model.joblib")

    preprocessor = joblib.load(preprocessor_path)
    model = joblib.load(model_path)
    print("✅ Preprocessor and model loaded successfully.")
except Exception as e:
    print(f"❌ Error loading artifacts: {e}")
    preprocessor = None
    model = None

# Define a route for the home page
@superkart_api.get('/')
def home():
    return "Welcome to the SuperKart Sales Prediction API!"

# Define an endpoint to predict sales
@superkart_api.post('/v1/predict')
def predict_sales():

    if preprocessor is None or model is None:
        return jsonify({"error": "Model or preprocessor not loaded"}), 500

    data = request.get_json()

    try:
        # Define the mappings exactly as in the notebook
        sugar_map = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2}
        size_map = {'Small': 0, 'Medium': 1, 'High': 2}
        city_type_map = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2}

        # Extract and map the raw data
        sample = {
            'Product_Weight': data['Product_Weight'],
            'Product_Sugar_Content': sugar_map.get(data['Product_Sugar_Content']),
            'Product_Allocated_Area': data['Product_Allocated_Area'],
            'Product_Type': data['Product_Type'],
            'Product_MRP': data['Product_MRP'],
            'Store_Size': size_map.get(data['Store_Size']),
            'Store_Location_City_Type': city_type_map.get(data['Store_Location_City_Type']),
            'Store_Type': data['Store_Type'],
            'Store_Age': data['Store_Age']
        }

        # Check if any mapping failed (resulted in None)
        if any(v is None for v in [sample['Product_Sugar_Content'], sample['Store_Size'], sample['Store_Location_City_Type']]):
            return jsonify({"error": "Invalid value for ordinal feature (e.g., 'Store_Size', 'Product_Sugar_Content')"}), 400

    except KeyError as e:
        return jsonify({"error": f"Missing key in JSON payload: {e}"}), 400
    except Exception as e:
         return jsonify({"error": f"Error processing input: {str(e)}"}), 400

    # Convert the extracted data into a 1-row DataFrame
    input_data = pd.DataFrame([sample])

    # --- Make a prediction ---
    try:
        # 1. Transform the now-mapped input data
        processed_data = preprocessor.transform(input_data)

        # 2. Make a prediction
        prediction = model.predict(processed_data).tolist()[0]

        return jsonify({'predicted_sales': round(prediction, 2)})

    except Exception as e:
        return jsonify({"error": f"Error during prediction: {str(e)}"}), 500

# Run the Flask app
if __name__ == '__main__':
    # Bind to 7860 as required by Hugging Face
    superkart_api.run(host='0.0.0.0', port=7860, debug=True)