12ongo commited on
Commit
2c44f21
·
verified ·
1 Parent(s): e92edc6

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +9 -9
  2. app.py +48 -90
  3. requirements.txt +0 -8
Dockerfile CHANGED
@@ -1,16 +1,16 @@
 
1
  FROM python:3.9-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:sales_predictor_api`: Runs the Flask app instance named 'sales_predictor_api' from the 'app.py' file
16
- CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:7860", "app:sales_predictor_api"]
 
1
+ # Use a minimal base image with Python 3.9 installed
2
  FROM python:3.9-slim
3
 
4
+ # Set the working directory inside the container to /app
5
  WORKDIR /app
6
 
7
+ # Copy all files from the current directory on the host to the container's /app directory
8
  COPY . .
9
 
10
+ # Install Python dependencies listed in requirements.txt
11
+ RUN pip3 install -r requirements.txt
12
 
13
+ # Define the command to run the Streamlit app on port 8501 and make it accessible externally
14
+ CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false"]
15
+
16
+ # NOTE: Disable XSRF protection for easier external access in order to make batch predictions
 
app.py CHANGED
@@ -1,90 +1,48 @@
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
- sales_predictor_api = Flask("SuperKart Sales Predictor")
9
-
10
- # Load the trained machine learning model
11
- model = joblib.load("sales_predictor.joblib")
12
-
13
- # Define a route for the home page (GET request)
14
- @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 Sales Prediction API!"
21
-
22
- # Define an endpoint for single product prediction (POST request)
23
- @sales_predictor_api.post('/v1/predict')
24
- def predict_sales():
25
- """
26
- This function handles POST requests to the '/v1/predict' endpoint.
27
- It expects a JSON payload containing product and store details and returns
28
- the predicted sales as a JSON response.
29
- """
30
- # Get the JSON data from the request body
31
- product_store_data = request.get_json()
32
-
33
- # Extract relevant features from the JSON data
34
- sample = {
35
- 'Product_Weight': product_store_data['Product_Weight'],
36
- 'Product_Sugar_Content': product_store_data['Product_Sugar_Content'],
37
- 'Product_Allocated_Area': product_store_data['Product_Allocated_Area'],
38
- 'Product_Type': product_store_data['Product_Type'],
39
- 'Product_MRP': product_store_data['Product_MRP'],
40
- 'Store_Establishment_Year_Before_2005': product_store_data['Store_Establishment_Year_Before_2005'],
41
- 'Store_Size': product_store_data['Store_Size'],
42
- 'Store_Location_City_Type': product_store_data['Store_Location_City_Type'],
43
- 'Store_Type': product_store_data['Store_Type']
44
- }
45
-
46
- # Convert the extracted data into a Pandas DataFrame
47
- input_data = pd.DataFrame([sample])
48
-
49
- # Make prediction
50
- predicted_sales = model.predict(input_data)[0]
51
-
52
- # Convert predicted_sales to Python float
53
- predicted_sales = round(float(predicted_sales), 2)
54
-
55
-
56
- # Return the predicted sales
57
- return jsonify({'Predicted Sales Total (in dollars)': predicted_sales})
58
-
59
-
60
- # Define an endpoint for batch prediction (POST request) - This endpoint is not functional with the current model
61
- # as the model is trained on individual product-store combinations, not batch data with IDs.
62
- # @sales_predictor_api.post('/v1/predictbatch')
63
- # def predict_sales_batch():
64
- # """
65
- # This function handles POST requests to the '/v1/predictbatch' endpoint.
66
- # It expects a CSV file containing product and store details for multiple entries
67
- # and returns the predicted sales as a dictionary in the JSON response.
68
- # """
69
- # # Get the uploaded CSV file from the request
70
- # file = request.files['file']
71
-
72
- # # Read the CSV file into a Pandas DataFrame
73
- # input_data = pd.read_csv(file)
74
-
75
- # # Make predictions for all entries in the DataFrame
76
- # predicted_sales = model.predict(input_data).tolist()
77
-
78
- # # For batch prediction with IDs, you would need an ID column in the input data
79
- # # and a way to associate predictions with IDs.
80
- # # Since the current model predicts for individual entries based on features,
81
- # # this batch endpoint is not directly applicable without further modifications
82
- # # to handle input data with IDs and return predictions associated with those IDs.
83
-
84
- # # Returning a placeholder response
85
- # return jsonify({"message": "Batch prediction endpoint is not yet implemented for this model."})
86
-
87
-
88
- # Run the Flask application in debug mode if this script is executed directly
89
- if __name__ == '__main__':
90
- sales_predictor_api.run(debug=True)
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import requests
4
+
5
+ # Set the title of the Streamlit app
6
+ st.title("SuperKart Sales Prediction")
7
+
8
+ # Section for online prediction
9
+ st.subheader("Predict Single Product Sales")
10
+
11
+ # Collect user input for product and store features
12
+ product_weight = st.number_input("Product Weight", min_value=0.0, value=10.0)
13
+ product_sugar_content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar", "reg"]) # Include 'reg' based on EDA
14
+ product_allocated_area = st.number_input("Product Allocated Area", min_value=0.0, value=0.05)
15
+ product_type = st.selectbox("Product Type", ['Frozen Foods', 'Dairy', 'Canned', 'Baking Goods', 'Health and Hygiene', 'Snack Foods', 'Meat', 'Household', 'Hard Drinks', 'Fruits and Vegetables', 'Breads', 'Soft Drinks', 'Breakfast', 'Others', 'Starchy Foods', 'Seafood']) # Based on EDA
16
+ product_mrp = st.number_input("Product MRP", min_value=0.0, value=100.0)
17
+ store_establishment_year_before_2005 = st.selectbox("Store Established Before 2005?", ["True", "False"])
18
+ store_size = st.selectbox("Store Size", ["Small", "Medium", "High"])
19
+ store_location_city_type = st.selectbox("Store Location City Type", ["Tier 1", "Tier 2", "Tier 3"])
20
+ store_type = st.selectbox("Store Type", ['Supermarket Type2', 'Departmental Store', 'Supermarket Type1', 'Food Mart']) # Based on EDA
21
+
22
+
23
+ # Convert user input into a dictionary
24
+ input_data = {
25
+ 'Product_Weight': product_weight,
26
+ 'Product_Sugar_Content': product_sugar_content,
27
+ 'Product_Allocated_Area': product_allocated_area,
28
+ 'Product_Type': product_type,
29
+ 'Product_MRP': product_mrp,
30
+ 'Store_Establishment_Year_Before_2005': store_establishment_year_before_2005 == "True", # Convert string to boolean
31
+ 'Store_Size': store_size,
32
+ 'Store_Location_City_Type': store_location_city_type,
33
+ 'Store_Type': store_type
34
+ }
35
+
36
+ # Make prediction when the "Predict" button is clicked
37
+ if st.button("Predict Sales"):
38
+ # Replace <username>-<repo_id> with your actual Hugging Face username and backend space repo ID
39
+ backend_url = "https://<username>-<repo_id>.hf.space/v1/predict" # Update endpoint
40
+ response = requests.post(backend_url, json=input_data) # Send data as JSON
41
+ if response.status_code == 200:
42
+ prediction = response.json()['Predicted Sales Total (in dollars)']
43
+ st.success(f"Predicted Sales Total (in dollars): {prediction}")
44
+ else:
45
+ st.error(f"Error making prediction. Status code: {response.status_code}")
46
+ st.error(f"Response: {response.text}")
47
+
48
+ # Removed batch prediction section as it's commented out in the backend Flask app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,11 +1,3 @@
1
  pandas==2.2.2
2
- numpy==2.0.2
3
- scikit-learn==1.6.1
4
- xgboost==2.1.4
5
- joblib==1.4.2
6
- Werkzeug==2.2.2
7
- flask==2.2.2
8
- gunicorn==20.1.0
9
  requests==2.28.1
10
- uvicorn[standard]
11
  streamlit==1.43.2
 
1
  pandas==2.2.2
 
 
 
 
 
 
 
2
  requests==2.28.1
 
3
  streamlit==1.43.2