Fitjv commited on
Commit
7dd24bc
·
verified ·
1 Parent(s): 494b0d5

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +40 -71
app.py CHANGED
@@ -1,8 +1,8 @@
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
  # Initialize the Flask application
8
  Superkart_sales_predictor_api = Flask("SuperKart Store Sales Prediction")
@@ -10,81 +10,50 @@ Superkart_sales_predictor_api = Flask("SuperKart Store Sales Prediction")
10
  # Load the trained machine learning model
11
  model = joblib.load("best_random_forest_model.joblib")
12
 
13
- # Define a route for the home page (GET request)
14
  @Superkart_sales_predictor_api.get('/')
15
  def home():
16
- """
17
- This function handles GET requests to the root URL ('/') of the API.
18
- It returns a simple welcome message.
19
- """
20
  return "Welcome to the SuperKart Store Sales Prediction API!"
21
 
22
- # Define an endpoint for single property prediction (POST request)
23
  @Superkart_sales_predictor_api.post('/v1/sales')
24
  def predict_sales_price():
25
- """
26
- This function handles POST requests to the '/v1/sales' endpoint.
27
- It expects a JSON payload containing store details and returns
28
- the predicted sales price as a JSON response.
29
- """
30
- # Get the JSON data from the request body
31
- store_data = request.get_json()
32
- df = pd.DataFrame([store_data])
33
-
34
- # Extract relevant features from the JSON data
35
- sample = {
36
- 'Product_Weight': store_data['Product_Weight'],
37
- 'Product_Sugar_Content': store_data['Product_Sugar_Content'],
38
- 'Product_Allocated_Area': store_data['Product_Allocated_Area'],
39
- 'Product_Type': store_data['Product_Type'],
40
- 'Product_MRP': store_data['Product_MRP'],
41
- 'Store_Id': store_data['Store_Id'],
42
- 'Store_Establishment_Year':store_data['Store_Establishment_Year'],
43
- 'Store_Size': store_data['Store_Size'],
44
- 'Store_Type': store_data['Store_Type'],
45
- 'Store_Location_City_Type': store_data['Store_Location_City_Type']
46
- }
47
-
48
- # Convert the extracted data into a Pandas DataFrame
49
- input_data = pd.DataFrame([sample])
50
-
51
- # Make prediction (get log_price)
52
- predicted_sale = model.predict(input_data)[0]
53
-
54
- # Convert predicted_price to Python float
55
- predicted_sale = round(float(predicted_sale), 2)
56
-
57
- # The conversion above is needed as we convert the model prediction (log price) to actual price using np.exp, which returns predictions as NumPy float32 values.
58
- # When we send this value directly within a JSON response, Flask's jsonify function encounters a datatype error
59
-
60
- # Return the actual price
61
- return jsonify({'Predicted Sales (in dollars)': predicted_sale})
62
-
63
-
64
- # Define an endpoint for batch prediction (POST request)
65
  @Superkart_sales_predictor_api.post('/v1/salesbatch')
66
  def predict_sales_price_batch():
67
- """
68
- This function handles POST requests to the '/v1/salesbatch' endpoint.
69
- It expects a CSV file containing store details for multiple properties
70
- and returns the predicted store sales as a dictionary in the JSON response.
71
- """
72
- # Get the uploaded CSV file from the request
73
- file = request.files['file']
74
-
75
- # Read the CSV file into a Pandas DataFrame
76
- input_data = pd.read_csv(file)
77
-
78
- # Make predictions for all properties in the DataFrame (get log_prices)
79
- predicted_sale = model.predict(input_data).tolist()
80
-
81
- # Create a dictionary of predictions with store IDs as keys
82
- store_ids = input_data['Store_Id'].tolist()
83
- output_dict = dict(zip(store_ids, predicted_sale)) # Use actual sales
84
-
85
- # Return the predictions dictionary as a JSON response
86
- return output_dict
87
-
88
- # Run the Flask application in debug mode if this script is executed directly
89
  if __name__ == '__main__':
90
  Superkart_sales_predictor_api.run(debug=True)
 
1
  # Import necessary libraries
2
  import numpy as np
3
+ import joblib
4
+ import pandas as pd
5
+ from flask import Flask, request, jsonify
6
 
7
  # Initialize the Flask application
8
  Superkart_sales_predictor_api = Flask("SuperKart Store Sales Prediction")
 
10
  # Load the trained machine learning model
11
  model = joblib.load("best_random_forest_model.joblib")
12
 
13
+ # Home route
14
  @Superkart_sales_predictor_api.get('/')
15
  def home():
 
 
 
 
16
  return "Welcome to the SuperKart Store Sales Prediction API!"
17
 
18
+ # Single prediction endpoint
19
  @Superkart_sales_predictor_api.post('/v1/sales')
20
  def predict_sales_price():
21
+ try:
22
+ store_data = request.get_json()
23
+ sample = {
24
+ 'Product_Weight': store_data['Product_Weight'],
25
+ 'Product_Sugar_Content': store_data['Product_Sugar_Content'],
26
+ 'Product_Allocated_Area': store_data['Product_Allocated_Area'],
27
+ 'Product_Type': store_data['Product_Type'],
28
+ 'Product_MRP': store_data['Product_MRP'],
29
+ 'Store_Id': store_data['Store_Id'],
30
+ 'Store_Establishment_Year': store_data['Store_Establishment_Year'],
31
+ 'Store_Size': store_data['Store_Size'],
32
+ 'Store_Type': store_data['Store_Type'],
33
+ 'Store_Location_City_Type': store_data['Store_Location_City_Type']
34
+ }
35
+ input_data = pd.DataFrame([sample])
36
+ predicted_sale = model.predict(input_data)[0]
37
+ predicted_sale = round(float(predicted_sale), 2)
38
+ return jsonify({'Predicted Sales (in dollars)': predicted_sale})
39
+ except Exception as e:
40
+ print("ERROR in /v1/sales:", str(e))
41
+ return jsonify({'error': str(e)}), 500
42
+
43
+ # Batch prediction endpoint
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  @Superkart_sales_predictor_api.post('/v1/salesbatch')
45
  def predict_sales_price_batch():
46
+ try:
47
+ file = request.files['file']
48
+ input_data = pd.read_csv(file)
49
+ predicted_sale = model.predict(input_data).tolist()
50
+ store_ids = input_data['Store_Id'].tolist()
51
+ output_dict = dict(zip(store_ids, predicted_sale))
52
+ return jsonify(output_dict)
53
+ except Exception as e:
54
+ print("ERROR in /v1/salesbatch:", str(e))
55
+ return jsonify({'error': str(e)}), 500
56
+
57
+ # Run the app
 
 
 
 
 
 
 
 
 
 
58
  if __name__ == '__main__':
59
  Superkart_sales_predictor_api.run(debug=True)