Garg06 commited on
Commit
1ce026d
·
verified ·
1 Parent(s): efa458c

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +9 -9
  2. app.py +76 -56
  3. requirements.txt +1 -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:superkart_sales_api`: Runs the Flask app (assuming `app.py` contains the Flask instance named `superkart_sales_api`)
16
- CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:7860", "app:superkart_sales_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,71 +1,91 @@
1
- import joblib
2
  import pandas as pd
3
- from flask import Flask, request, jsonify
4
 
5
- # Initialize Flask app
6
- superkart_sales_api = Flask("SuperKart Product Store Sales Predictor")
7
 
8
- # Load the trained SuperKart sales model
9
- model = joblib.load("SuperKart_model_v1_0.joblib")
10
 
11
- # Define a route for the home page
12
- @superkart_sales_api.get('/')
13
- def home():
14
- return "Welcome to the SuperKart Product Store Sales Prediction API!"
 
 
 
 
 
 
 
 
15
 
16
- # Define an endpoint to predict sales for a single product
17
- @superkart_sales_api.post('/v1/product')
18
- def predict_product_sales():
19
- # Get JSON data from the request
20
- product_data = request.get_json()
21
 
22
- # Extract relevant product and store features from the input data
23
- sample = {
24
- 'Product_Id': product_data['Product_Id'],
25
- 'Product_Weight': product_data['Product_Weight'],
26
- 'Product_Sugar_Content': product_data['Product_Sugar_Content'],
27
- 'Product_Allocated_Area': product_data['Product_Allocated_Area'],
28
- 'Product_Type': product_data['Product_Type'],
29
- 'Product_MRP': product_data['Product_MRP'],
30
- 'Store_Id': product_data['Store_Id'],
31
- 'Store_Establishment_Year': product_data['Store_Establishment_Year'],
32
- 'Store_Size': product_data['Store_Size'],
33
- 'Store_Location_City_Type': product_data['Store_Location_City_Type'],
34
- 'Store_Type': product_data['Store_Type'],
35
- 'Product_Category_from_ID': product_data['Product_Category_from_ID'], # Include engineered features
36
- 'Store_Age': product_data['Store_Age'],
37
- 'Product_Category_Type': product_data['Product_Category_Type']
38
- }
39
 
40
- # Convert the extracted data into a DataFrame
41
- input_data = pd.DataFrame([sample])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- # Make a prediction using the trained model
44
- prediction = model.predict(input_data).tolist()[0]
45
 
46
- # Return the prediction as a JSON response
47
- return jsonify({'Predicted_Product_Store_Sales_Total': prediction})
 
 
 
48
 
49
- # Define an endpoint to predict sales for a batch of products
50
- @superkart_sales_api.post('/v1/productbatch')
51
- def predict_product_batch():
52
- # Get the uploaded CSV file from the request
53
- file = request.files['file']
 
 
 
 
 
54
 
55
- # Read the file into a DataFrame
56
- input_data = pd.read_csv(file)
57
 
58
- # Make predictions for the batch data
59
- predictions = model.predict(input_data).tolist()
60
 
61
- # Add predictions to the DataFrame
62
- input_data['Predicted_Product_Store_Sales_Total'] = predictions
63
 
64
- # Convert results to dictionary
65
- result = input_data.to_dict(orient="records")
 
 
 
 
66
 
67
- return jsonify(result)
68
-
69
- # Run the Flask app in debug mode
70
- if __name__ == '__main__':
71
- superkart_sales_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 Product Store 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_id = st.text_input("Product ID")
13
+ product_weight = st.number_input("Product Weight", min_value=0.0, value=10.0)
14
+ product_sugar_content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar", "low sugar"])
15
+ product_allocated_area = st.number_input("Product Allocated Area", min_value=0.0, value=0.05)
16
+ product_type = st.selectbox("Product Type", ['Frozen Foods', 'Dairy', 'Canned', 'Baking Goods', 'Health and Hygiene', 'Snack Foods', 'Meat', 'Soft Drinks', 'Breads', 'Hard Drinks', 'Others', 'Starchy Foods', 'Breakfast', 'Seafood', 'Fruits and Vegetables', 'Household'])
17
+ product_mrp = st.number_input("Product MRP", min_value=0.0, value=100.0)
18
+ store_id = st.selectbox("Store ID", ['OUT004', 'OUT003', 'OUT001', 'OUT002'])
19
+ store_establishment_year = st.number_input("Store Establishment Year", min_value=1900, value=2000)
20
+ store_size = st.selectbox("Store Size", ["Medium", "High", "Small"])
21
+ store_location_city_type = st.selectbox("Store Location City Type", ["Tier 2", "Tier 1", "Tier 3"])
22
+ store_type = st.selectbox("Store Type", ['Supermarket Type2', 'Departmental Store', 'Supermarket Type1', 'Food Mart'])
23
 
24
+ # Calculate engineered features (ensure these match the backend)
25
+ current_year = pd.to_datetime('now').year
26
+ store_age = current_year - store_establishment_year
 
 
27
 
28
+ perishables = ['Fruits and Vegetables', 'Dairy', 'Meat', 'Seafood', 'Breads', 'Breakfast']
29
+ product_category_type = 'Perishables' if product_type in perishables else 'Non Perishables'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # Create a dictionary with the input data
32
+ input_data = {
33
+ 'Product_Id': product_id,
34
+ 'Product_Weight': product_weight,
35
+ 'Product_Sugar_Content': product_sugar_content,
36
+ 'Product_Allocated_Area': product_allocated_area,
37
+ 'Product_Type': product_type,
38
+ 'Product_MRP': product_mrp,
39
+ 'Store_Id': store_id,
40
+ 'Store_Establishment_Year': store_establishment_year,
41
+ 'Store_Size': store_size,
42
+ 'Store_Location_City_Type': store_location_city_type,
43
+ 'Store_Type': store_type,
44
+ 'Product_Category_from_ID': product_id[:2] if product_id else '', # Assuming product_id is not empty
45
+ 'Store_Age': store_age,
46
+ 'Product_Category_Type': product_category_type
47
+ }
48
 
 
 
49
 
50
+ # Make prediction when the "Predict" button is clicked
51
+ if st.button("Predict"):
52
+ # Replace with the actual URL of your deployed backend Hugging Face Space
53
+ backend_url = "https://Garg06-superkartsalesbackend.hf.space" # Example URL format
54
+ predict_url = f"{backend_url}/v1/product"
55
 
56
+ try:
57
+ response = requests.post(predict_url, json=input_data)
58
+ if response.status_code == 200:
59
+ prediction = response.json()['Predicted_Product_Store_Sales_Total']
60
+ st.success(f"Predicted Product Store Sales Total: {prediction:.2f}")
61
+ else:
62
+ st.error(f"Error making prediction. Status code: {response.status_code}")
63
+ st.error(f"Response: {response.text}")
64
+ except requests.exceptions.RequestException as e:
65
+ st.error(f"Error connecting to the backend: {e}")
66
 
 
 
67
 
68
+ # Section for batch prediction
69
+ st.subheader("Batch Prediction")
70
 
71
+ # Allow users to upload a CSV file for batch prediction
72
+ uploaded_file = st.file_uploader("Upload CSV file for batch prediction", type=["csv"])
73
 
74
+ # Make batch prediction when the "Predict Batch" button is clicked
75
+ if uploaded_file is not None:
76
+ if st.button("Predict Batch"):
77
+ # Replace with the actual URL of your deployed backend Hugging Face Space
78
+ backend_url = "https://Garg06-superkartsalesbackend.hf.space" # Example URL format
79
+ predict_batch_url = f"{backend_url}/v1/productbatch"
80
 
81
+ try:
82
+ response = requests.post(predict_batch_url, files={"file": uploaded_file}) # Send file to Flask API
83
+ if response.status_code == 200:
84
+ predictions = response.json()
85
+ st.success("Batch predictions completed!")
86
+ st.write(predictions) # Display the predictions
87
+ else:
88
+ st.error(f"Error making batch prediction. Status code: {response.status_code}")
89
+ st.error(f"Response: {response.text}")
90
+ except requests.exceptions.RequestException as e:
91
+ st.error(f"Error connecting to the backend: {e}")
requirements.txt CHANGED
@@ -1,10 +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]
 
1
  pandas==2.2.2
 
 
 
 
 
 
 
2
  requests==2.28.1
3
+ streamlit==1.43.2