Lokiiparihar commited on
Commit
a3ff8b8
·
verified ·
1 Parent(s): 768f739

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -0
app.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import numpy as np
3
+ import joblib # For loading the serialized model
4
+ import pandas as pd # For data manipulation
5
+ from flask import Flask, request, jsonify # For creating the Flask API
6
+
7
+ print("--- app.py: Starting Flask application setup ---")
8
+
9
+ # Initialize the Flask application
10
+ superkart_sales_api = Flask(__name__)
11
+ print("--- app.py: Flask app initialized ---")
12
+
13
+ # Load the trained machine learning model
14
+ model = None
15
+
16
+ def load_model():
17
+ global model
18
+ if model is None:
19
+ model = joblib.load("superkart_sales_model.pkl")
20
+ print("Model loaded successfully")
21
+
22
+ # Define a route for the home page (GET request)
23
+ @superkart_sales_api.get('/')
24
+ def home():
25
+ print("--- API: Home route accessed ---")
26
+ """
27
+ This function handles GET requests to the root URL ('/') of the API.
28
+ It returns a simple welcome message.
29
+ """
30
+ return "Welcome to the SuperKart Sales Prediction API!"
31
+
32
+ # Define an endpoint for single sales prediction (POST request)
33
+ @superkart_sales_api.post('/v1/sales')
34
+ def predict_sales():
35
+ print("--- API: Single sales prediction route accessed ---")
36
+ """
37
+ This function handles POST requests to the '/v1/sales' endpoint.
38
+ It expects a JSON payload containing product and store details and returns
39
+ the predicted sales as a JSON response.
40
+ """
41
+ # Get the JSON data from the request body
42
+ input_data_json = request.get_json()
43
+
44
+ # Extract relevant features from the JSON data, matching x_train columns
45
+ # The model expects original feature names before one-hot encoding
46
+ sample = {
47
+ 'Product_Id': input_data_json['Product_Id'],
48
+ 'Product_Weight': input_data_json['Product_Weight'],
49
+ 'Product_Sugar_Content': input_data_json['Product_Sugar_Content'],
50
+ 'Product_Allocated_Area': input_data_json['Product_Allocated_Area'],
51
+ 'Product_Type': input_data_json['Product_Type'],
52
+ 'Product_MRP': input_data_json['Product_MRP'],
53
+ 'Store_Id': input_data_json['Store_Id'],
54
+ 'Store_Size': input_data_json['Store_Size'],
55
+ 'Store_Location_City_Type': input_data_json['Store_Location_City_Type'],
56
+ 'Store_Current_Age': input_data_json['Store_Current_Age']
57
+ }
58
+
59
+ # Convert the extracted data into a Pandas DataFrame
60
+ input_df = pd.DataFrame([sample])
61
+
62
+ # Make prediction
63
+ load_model()
64
+ predicted_sales = model.predict(input_df)[0]
65
+
66
+ # Convert predicted_sales to Python float and round
67
+ predicted_sales = round(float(predicted_sales), 2)
68
+
69
+ # Return the predicted sales
70
+ return jsonify({'Predicted Sales': predicted_sales})
71
+
72
+
73
+ # Define an endpoint for batch prediction (POST request)
74
+ @superkart_sales_api.post('/v1/salesbatch')
75
+ def predict_sales_batch():
76
+ print("--- API: Batch sales prediction route accessed ---")
77
+ """
78
+ This function handles POST requests to the '/v1/salesbatch' endpoint.
79
+ It expects a CSV file containing product and store details for multiple entries
80
+ and returns the predicted sales as a list in the JSON response.
81
+ """
82
+ # Get the uploaded CSV file from the request
83
+ file = request.files['file']
84
+
85
+ # Read the CSV file into a Pandas DataFrame
86
+ input_df_batch = pd.read_csv(file)
87
+
88
+ # Make predictions for all entries in the DataFrame
89
+ load_model()
90
+ predicted_sales_batch = model.predict(input_df_batch).tolist()
91
+
92
+ # Round each prediction and convert to float
93
+ predicted_sales_batch = [round(float(s), 2) for s in predicted_sales_batch]
94
+
95
+ # Return the predictions list as a JSON response
96
+ return jsonify({'Predicted Sales': predicted_sales_batch})
97
+
98
+ # Run the Flask application in debug mode if this script is executed directly
99
+ # When deploying with Gunicorn, this block is usually commented out or removed
100
+ # if __name__ == '__main__':
101
+ # print("--- app.py: Running Flask app in debug mode ---")
102
+ # superkart_sales_api.run(debug=True)
103
+ if __name__ == '__main__':
104
+ superkart_sales_api.run(debug=True)