Hugo014 commited on
Commit
00db09c
·
verified ·
1 Parent(s): 8dc40a1

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +8 -9
  2. app.py +65 -65
  3. requirements.txt +1 -7
Dockerfile CHANGED
@@ -1,16 +1,15 @@
1
  FROM python:3.11.13
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", "4", "-b", "0.0.0.0:7860", "app:super_kart_api"]
 
1
  FROM python:3.11.13
2
 
3
+ # Set the working directory inside the container to /app
4
  WORKDIR /app
5
 
6
+ # Copy all files from the current directory on the host to the container's /app directory
7
  COPY . .
8
 
9
+ # Install Python dependencies listed in requirements.txt
10
+ RUN pip3 install -r requirements.txt
11
 
12
+ # Define the command to run the Streamlit app on port 8501 and make it accessible externally
13
+ CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false"]
14
+
15
+ # NOTE: Disable XSRF protection for easier external access in order to make batch predictions
 
app.py CHANGED
@@ -1,81 +1,81 @@
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
- super_kart_api = Flask("Super Kart Price Predictor")
 
 
 
 
 
 
 
 
9
 
10
- # Load the trained machine learning model (updated path to match deployment structure)
11
- model_path = "super_kart_model_v1_0.joblib"
12
- try:
13
- model = joblib.load(model_path)
14
- print(f"Model loaded successfully from {model_path}")
15
- except FileNotFoundError:
16
- raise FileNotFoundError(f"Model file not found at {model_path}. Ensure it's included in the deployment.")
17
 
18
- # Define a route for the home page (GET request)
19
- @super_kart_api.get('/')
20
- def home():
21
- """
22
- This function handles GET requests to the root URL ('/') of the API.
23
- It returns a simple welcome message.
24
- """
25
- return "Welcome to the Super Kart Price Prediction API!"
 
 
26
 
27
- # Define an endpoint for single product sales prediction (POST request)
28
- @super_kart_api.post('/v1/sales')
29
- def predict_sales():
30
- """
31
- This function handles POST requests to the '/v1/sales' endpoint.
32
- It expects a JSON payload containing product and store details and returns
33
- the predicted sales total as a JSON response.
34
- """
35
- # Get the JSON data from the request body
36
- input_data = request.get_json()
37
-
38
- # Extract relevant features from the JSON data
39
- # Note: Exclude Product_Id and Store_Id if they are not used in prediction
40
  sample = {
41
- 'Product_Weight': input_data['Product_Weight'],
42
- 'Product_Sugar_Content': input_data['Product_Sugar_Content'],
43
- 'Product_Allocated_Area': input_data['Product_Allocated_Area'],
44
- 'Product_Type': input_data['Product_Type'],
45
- 'Product_MRP': input_data['Product_MRP'],
46
- 'Store_Establishment_Year': input_data['Store_Establishment_Year'],
47
- 'Store_Size': input_data['Store_Size'],
48
- 'Store_Location_City_Type': input_data['Store_Location_City_Type'],
49
- 'Store_Type': input_data['Store_Type']
50
  }
51
- # Convert the extracted data into a Pandas DataFrame
 
52
  features_df = pd.DataFrame([sample])
53
-
54
- # Apply one-hot encoding for nominal columns (matching training)
55
  features_df = pd.get_dummies(features_df, columns=['Product_Type', 'Store_Type'], drop_first=True)
56
-
57
- # Apply ordinal encoding (based on provided orders)
58
  sugar_mapping = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2}
59
  size_mapping = {'Small': 0, 'Medium': 1, 'High': 2}
60
  city_mapping = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2}
61
-
62
  features_df['Product_Sugar_Content'] = features_df['Product_Sugar_Content'].map(sugar_mapping)
63
  features_df['Store_Size'] = features_df['Store_Size'].map(size_mapping)
64
  features_df['Store_Location_City_Type'] = features_df['Store_Location_City_Type'].map(city_mapping)
65
-
66
- # Make prediction (assuming direct sales prediction; adjust if log-transformed)
67
- predicted_sales = model.predict(features_df)[0]
68
-
69
- # If your model predicts log(sales), uncomment and use this instead:
70
- # predicted_log_sales = model.predict(features_df)[0]
71
- # predicted_sales = np.exp(predicted_log_sales)
72
-
73
- # Convert to Python float and round to 2 decimals
74
- predicted_sales = round(float(predicted_sales), 2)
75
-
76
- # Return the predicted sales total
77
- return jsonify({'Predicted Sales Total (in dollars)': predicted_sales})
78
 
79
- # Run the app (for testing locally; remove or adjust for production)
80
- if __name__ == '__main__':
81
- super_kart_api.run(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import joblib
5
  import numpy as np
 
 
 
6
 
7
+ # Load the trained model
8
+ @st.cache_resource
9
+ def load_model():
10
+ return joblib.load("super_kart_model_v1_0.joblib")
11
+
12
+ model = load_model()
13
+
14
+ # Streamlit UI for Super Kart Sales Prediction
15
+ st.title("Super Kart Product Sales Prediction App")
16
+ st.write("This tool predicts the total sales for a product based on store and product details.")
17
 
18
+ st.subheader("Enter the product and store details:")
 
 
 
 
 
 
19
 
20
+ # Collect user input (matching Super Kart features)
21
+ product_weight = st.number_input("Product Weight", min_value=0.0, value=10.0, step=0.1)
22
+ product_sugar_content = st.selectbox("Product Sugar Content", ["No Sugar", "Low Sugar", "Regular"])
23
+ product_allocated_area = st.number_input("Product Allocated Area (sq ft)", min_value=0.0, value=500.0, step=1.0)
24
+ product_type = st.selectbox("Product Type", ["Dairy", "Soft Drinks", "Meat", "Fruits and Vegetables", "Snack Foods", "Household", "Frozen Foods", "Baking Goods", "Canned", "Health and Hygiene", "Hard Drinks", "Breads", "Starchy Foods", "Breakfast", "Seafood", "Others"]) # Add actual types from your data
25
+ product_mrp = st.number_input("Product MRP (price)", min_value=0.0, value=100.0, step=1.0)
26
+ store_establishment_year = st.number_input("Store Establishment Year", min_value=1900, max_value=2025, value=2000, step=1)
27
+ store_size = st.selectbox("Store Size", ["Small", "Medium", "High"])
28
+ store_location_city_type = st.selectbox("Store Location City Type", ["Tier 3", "Tier 2", "Tier 1"])
29
+ store_type = st.selectbox("Store Type", ["Grocery Store", "Supermarket Type1", "Supermarket Type2", "Supermarket Type3"]) # Add actual types from your data
30
 
31
+ # Predict button
32
+ if st.button("Predict"):
33
+ # Create input dictionary
 
 
 
 
 
 
 
 
 
 
34
  sample = {
35
+ 'Product_Weight': product_weight,
36
+ 'Product_Sugar_Content': product_sugar_content,
37
+ 'Product_Allocated_Area': product_allocated_area,
38
+ 'Product_Type': product_type,
39
+ 'Product_MRP': product_mrp,
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
  }
45
+
46
+ # Convert to DataFrame
47
  features_df = pd.DataFrame([sample])
48
+
49
+ # Apply one-hot encoding for nominal columns (matching backend)
50
  features_df = pd.get_dummies(features_df, columns=['Product_Type', 'Store_Type'], drop_first=True)
51
+
52
+ # Apply ordinal encoding (based on backend mappings)
53
  sugar_mapping = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2}
54
  size_mapping = {'Small': 0, 'Medium': 1, 'High': 2}
55
  city_mapping = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2}
56
+
57
  features_df['Product_Sugar_Content'] = features_df['Product_Sugar_Content'].map(sugar_mapping)
58
  features_df['Store_Size'] = features_df['Store_Size'].map(size_mapping)
59
  features_df['Store_Location_City_Type'] = features_df['Store_Location_City_Type'].map(city_mapping)
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ # Option 1: Predict locally (if model is loaded)
62
+ # predicted_sales = model.predict(features_df)[0]
63
+ # predicted_sales = round(float(predicted_sales), 2) # Or np.exp if log-transformed
64
+
65
+ # Option 2: Call the backend Flask API (recommended if backend is hosted separately)
66
+ # Replace with your actual backend URL (e.g., from Hugging Face Space)
67
+ backend_url = "https://Hugo014/TotalSalesPredictionBackend.hf.space/v1/sales" # Update with real URL
68
+ try:
69
+ response = requests.post(backend_url, json=sample)
70
+ if response.status_code == 200:
71
+ result = response.json()
72
+ predicted_sales = result['Predicted Sales Total (in dollars)']
73
+ else:
74
+ st.error(f"Backend error: {response.status_code} - {response.text}")
75
+ predicted_sales = None
76
+ except Exception as e:
77
+ st.error(f"Error calling backend: {str(e)}")
78
+ predicted_sales = None
79
+
80
+ if predicted_sales is not None:
81
+ st.write(f"The predicted sales total for the product is ${predicted_sales:.2f}.")
requirements.txt CHANGED
@@ -1,9 +1,3 @@
1
  pandas==2.2.2
2
- numpy==2.0.2
3
- scikit-learn==1.6.1
4
- xgboost==3.0.4
5
- joblib==1.5.1
6
- Werkzeug==3.1.3
7
- flask==3.1.1
8
- gunicorn==20.1.0
9
  requests==2.28.1
 
 
1
  pandas==2.2.2
 
 
 
 
 
 
 
2
  requests==2.28.1
3
+ streamlit==1.48.1