ssshruti commited on
Commit
b705d3f
·
verified ·
1 Parent(s): 5cb1271

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +16 -0
  2. app.py +101 -0
  3. requirements.txt +8 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ # Set the working directory inside the container
4
+ WORKDIR /app
5
+
6
+ # Copy all files from the current directory to the container's working directory
7
+ COPY . .
8
+
9
+ # Install dependencies from the requirements file without using cache to reduce image size
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ # Define the command to start the application using Gunicorn with 4 worker processes
13
+ # - `-w 4`: Uses 4 worker processes for handling requests
14
+ # - `-b 0.0.0.0:7860`: Binds the server to port 7860 on all network interfaces
15
+ # - `app:app`: Runs the Flask app (assuming `app.py` contains the Flask instance named `app`)
16
+ CMD ["gunicorn", "-w", "2", "-b", "0.0.0.0:7860", "app:app"]
app.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os,
3
+ import numpy as np,
4
+ import pandas as pd,
5
+ import joblib
6
+
7
+ from flask import Flask, request, jsonify # For creating the Flask API
8
+
9
+ # Initialize the Flask application
10
+ sales_predictor_api = Flask("Superkart Sales Predictor")
11
+ app = sales_predictor_api
12
+
13
+ # Load the trained machine learning model
14
+ model = joblib.load("sales_prediction_model_v1_0.joblib")
15
+
16
+ # Define a route for the home page (GET request)
17
+ @sales_predictor_api.get('/')
18
+ def home():
19
+ """
20
+ This function handles GET requests to the root URL ('/') of the API.
21
+ It returns a simple welcome message.
22
+ """
23
+ return "Welcome to the Superkart Total Sales Prediction API!"
24
+
25
+ # Define an endpoint for single product prediction (POST request)
26
+ @sales_predictor_api.post('/v1/storesales')
27
+ def predict_store_sales():
28
+ """
29
+ This function handles POST requests to the '/v1/storesales' endpoint.
30
+ It expects a JSON payload containing product details and returns
31
+ the predicted total sales as a JSON response.
32
+ """
33
+ # Get the JSON data from the request body
34
+ product_data = request.get_json()
35
+
36
+ # Extract relevant features from the JSON data
37
+ sample = {
38
+ 'Product_Sugar_Content': product_data['Product_Sugar_Content'],
39
+ 'Product_Weights': product_data['Product_Weights'],
40
+ 'Product_Allocated_Area': product_data['Product_Allocated_Area'],
41
+ 'Product_MRP': product_data['Product_MRP'],
42
+ 'Product_Type': product_data['Product_Type'],
43
+ 'Store_Establishment_Year': product_data['Store_Establishment_Year'],
44
+ 'Store_Size': product_data['Store_Size'],
45
+ 'Store_Location_City_Type': product_data['Store_Location_City_Type'],
46
+ 'Store_Type': product_data['Store_Type']
47
+ }
48
+
49
+ # Convert the extracted data into a Pandas DataFrame
50
+ input_data = pd.DataFrame([sample])
51
+
52
+ # Make prediction
53
+ pred = model.predict(input_data)[0]
54
+
55
+ # Calculate actual sales
56
+ #predictions_actual_product_store_sales_total = np.exp(pred)
57
+
58
+ # Convert predicted_actual_sales to Python float
59
+ predicted_sales = round(float(np.exp(pred)), 2)
60
+ # The conversion above is needed as we convert the model prediction (total sales) to actual sales using np.exp, which returns predictions as NumPy float32 values.
61
+ # When we send this value directly within a JSON response, Flask's jsonify function encounters a datatype error
62
+
63
+ # Return the actual price
64
+ return jsonify({'Predicted sales': predicted_sales})
65
+
66
+
67
+ # Define an endpoint for batch prediction (POST request)
68
+ @sales_predictor_api.post('/v1/storesalesbatch')
69
+ def predict_store_sales_batch():
70
+ """
71
+ This function handles POST requests to the '/v1/storesalesbatch' endpoint.
72
+ It expects a CSV file containing product details for multiple properties
73
+ and returns the predicted product sales as a dictionary in the JSON response.
74
+ """
75
+ # Get the uploaded CSV file from the request
76
+ file = request.files['file']
77
+
78
+ # Read the CSV file into a Pandas DataFrame
79
+ input_data = pd.read_csv(file)
80
+
81
+ # Make predictions for all properties in the DataFrame (get store totalsales)
82
+ predictions_product_store_sales_total = model.predict(input_data).tolist()
83
+
84
+ # Calculate actual sales
85
+ predictions_actual_product_store_sales_total = [round(float(np.exp(log_price)), 2) for log_price in predictions_product_store_sales_total]
86
+
87
+ # Create a dictionary of predictions with product IDs as keys
88
+ if "Product_ID" in input_data.columns:
89
+ product_ids = input_data["Product_ID"].tolist()
90
+ else:
91
+ product_ids = list(range(len(input_data)))
92
+
93
+ output_dict = dict(zip(product_ids, predictions_actual_product_store_sales_total))
94
+
95
+ # Return the predictions dictionary as a JSON response
96
+ return jsonify(output_dict)
97
+
98
+ # Run the Flask application in debug mode
99
+ if __name__ == "__main__":
100
+ port = int(os.environ.get("PORT", 7860))
101
+ sales_predictor_api.run(host="0.0.0.0", port=port, debug=False)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ flask==2.2.2
2
+ Werkzeug==2.2.2
3
+ gunicorn==20.1.0
4
+ pandas==2.2.2
5
+ numpy==2.0.2
6
+ scikit-learn==1.6.1
7
+ xgboost==2.1.4
8
+ joblib==1.4.2