File size: 3,921 Bytes
cf7a16c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import joblib
import pandas as pd
from flask import Flask, request, jsonify
import numpy as np

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

# Load the trained sales forecasting model
model = joblib.load("superkart_sales_forecast_model.pkl")

# Define a route for the home page
@sales_forecast_api.get('/')
def home():
    return "Welcome to the SuperKart Sales Forecasting API! ๐Ÿ›’๐Ÿ“Š"

# Define an endpoint to predict sales for a single product-store combination
@sales_forecast_api.post('/v1/predict_sales')
def predict_sales():
    try:
        # Get JSON data from the request
        input_data = request.get_json()
        
        # Extract relevant features from the input data
        sample = {
            'Product_Weight': input_data['Product_Weight'],
            'Product_Sugar_Content': input_data['Product_Sugar_Content'],
            'Product_Allocated_Area': input_data['Product_Allocated_Area'],
            'Product_Type': input_data['Product_Type'],
            'Product_MRP': input_data['Product_MRP'],
            'Store_Establishment_Year': input_data['Store_Establishment_Year'],
            'Store_Size': input_data['Store_Size'],
            'Store_Location_City_Type': input_data['Store_Location_City_Type'],
            'Store_Type': input_data['Store_Type']
        }
        
        # Convert the extracted data into a DataFrame
        input_df = pd.DataFrame([sample])
        
        # Make sales prediction using the trained model
        prediction = model.predict(input_df)[0]
        
        # Convert NumPy float32 to Python float
        prediction = float(prediction)  
        
        # Return the prediction as a JSON response
        return jsonify({
            'Product_Id': input_data.get('Product_Id', 'N/A'),
            'Store_Id': input_data.get('Store_Id', 'N/A'),
            'Predicted_Sales': round(prediction, 2),
            'Currency': 'INR',
            'Status': 'Success'
        })
    
    except Exception as e:
        return jsonify({
            'Error': str(e),
            'Status': 'Failed'
        }), 400

# Define an endpoint to predict sales for a batch of product-store combinations
@sales_forecast_api.post('/v1/predict_sales_batch')
def predict_sales_batch():
    try:
        # Get the uploaded CSV file from the request
        file = request.files['file']
        
        # Read the file into a DataFrame
        input_data = pd.read_csv(file)
        
        # Select only the required features for prediction
        feature_columns = [
            'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area', 
            'Product_Type', 'Product_MRP', 'Store_Establishment_Year', 
            'Store_Size', 'Store_Location_City_Type', 'Store_Type'
        ]
        
        # Prepare data for prediction
        prediction_data = input_data[feature_columns]
        
        # Make predictions for the batch data
        predictions = model.predict(prediction_data)
        
        # Create output with Product_Id and Store_Id mapping
        output_list = []
        for i, (_, row) in enumerate(input_data.iterrows()):
            prediction_entry = {
                'Product_Id': row.get('Product_Id', f'Product_{i}'),
                'Store_Id': row.get('Store_Id', f'Store_{i}'),
                'Predicted_Sales': float(predictions[i])  
            }
            output_list.append(prediction_entry)
        
        return jsonify({
            'Predictions': output_list,
            'Total_Records': len(predictions),
            'Currency': 'INR',
            'Status': 'Success'
        })
    
    except Exception as e:
        return jsonify({
            'Error': str(e),
            'Status': 'Failed'
        }), 400


# Run the Flask app
if __name__ == '__main__':
    sales_forecast_api.run(debug=True, host='0.0.0.0', port=7860)  # Port 7860 for Hugging Face