File size: 1,461 Bytes
8b0f9fd
dc863a2
 
 
 
8b0f9fd
 
 
 
d7b3c3f
8b0f9fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fe627c
8b0f9fd
 
 
2fe627c
 
 
 
 
 
 
 
8b0f9fd
 
2fe627c
 
8b0f9fd
 
 
 
 
 
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

import joblib
import pandas as pd
from flask import Flask, request, jsonify

# Initialize Flask app
sales_forecast_api = Flask("SuperKart Sales Forecast API")

# Load trained model (includes preprocessing pipeline)
model = joblib.load("best_random_forest.pkl")

# Home route
@sales_forecast_api.get('/')
def home():
    return "Welcome to the SuperKart Sales Forecast API!"

# Predict for a single input
@sales_forecast_api.post('/v1/predict')
def predict_sales():
    data = request.get_json()

    # Convert JSON into DataFrame (1 row)
    input_df = pd.DataFrame([data])

    # Model prediction
    prediction = model.predict(input_df).tolist()[0]

    return jsonify({"Predicted_Sales_Total": prediction})

# Predict for a batch (CSV upload)
@sales_forecast_api.post('/v1/predict_batch')
def predict_sales_batch():
    # Read uploaded CSV file
    file = request.files['file']
    input_data = pd.read_csv(file)

    # Check for optional Product_Id column
    if "Product_Id" in input_data.columns:
        ids = input_data["Product_Id"].astype(str)
        input_data = input_data.drop(columns=["Product_Id"])
    else:
        ids = input_data.index.astype(str)  # fallback to row indices

    # Make predictions
    preds = model.predict(input_data).tolist()

    # Map Product_Id (or row index) → prediction
    results = dict(zip(ids, preds))

    return jsonify(results)

# Run app
if __name__ == "__main__":
    sales_forecast_api.run(debug=True)