abhishek1504 commited on
Commit
fe30ba7
·
verified ·
1 Parent(s): 813b3e9

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +9 -7
  2. app.py +82 -71
  3. requirements.txt +8 -1
Dockerfile CHANGED
@@ -1,14 +1,16 @@
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"]
 
 
 
 
 
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: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:sales_api"]
app.py CHANGED
@@ -1,72 +1,83 @@
1
- import streamlit as st
2
  import pandas as pd
3
- import requests
4
-
5
- # ==================================
6
- # Streamlit UI
7
- # ==================================
8
- st.title("Product Store Sales Prediction App")
9
- st.write("This app predicts total sales for a product in a store based on product and store features.")
10
- st.write("Adjust the sliders and input fields below to get a prediction for a single product-store combination.")
11
-
12
- # -------------------------
13
- # Single record inputs
14
- # -------------------------
15
- Product_Id = st.number_input("Product ID", min_value=1, step=1)
16
- Product_Weight = st.number_input("Product Weight (kg)", min_value=0.0, step=0.01, value=0.5)
17
- Product_Sugar_Content = st.number_input("Sugar Content (%)", min_value=0.0, max_value=100.0, step=0.1, value=10.0)
18
- Product_Allocated_Area = st.number_input("Allocated Area (sq.m)", min_value=0.0, step=0.1, value=50.0)
19
- Product_Type = st.text_input("Product Type", value="Food")
20
- Product_MRP = st.number_input("Maximum Retail Price (MRP)", min_value=0.0, step=0.1, value=100.0)
21
-
22
- Store_Id = st.number_input("Store ID", min_value=1, step=1)
23
- Store_Establishment_Year = st.number_input("Store Establishment Year", min_value=1900, max_value=2025, step=1, value=2000)
24
- Store_Size = st.number_input("Store Size (sq.m)", min_value=0.0, step=0.1, value=100.0)
25
- Store_Location_City_Type = st.selectbox("City Type", ["A", "B", "C"])
26
- Store_Type = st.text_input("Store Type", value="Supermarket")
27
-
28
- # -------------------------
29
- # Single prediction
30
- # -------------------------
31
- if st.button("Predict Sales", type='primary'):
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
- }
45
-
46
- # Replace with your Hugging Face Space endpoint
47
- API_URL = "https://abhishek1504-learning.hf.space/v1/sales"
48
-
49
- response = requests.post(API_URL, json=input_data)
50
- if response.status_code == 200:
51
- result = response.json()
52
- predicted_sales = result["Predicted_Product_Store_Sales_Total"]
53
- st.success(f"💰 Predicted Total Product-Store Sales: **{predicted_sales:.2f} units**")
54
- else:
55
- st.error("Error in API request")
56
-
57
- # -------------------------
58
- # Batch prediction
59
- # -------------------------
60
- st.subheader("Batch Prediction")
61
- file = st.file_uploader("Upload CSV file with multiple product-store records", type=["csv"])
62
-
63
- if file is not None:
64
- if st.button("Predict for Batch", type='primary'):
65
- API_BATCH_URL = "https://abhishek1504-learning.hf.space/v1/salesbatch"
66
- response = requests.post(API_BATCH_URL, files={"file": file})
67
- if response.status_code == 200:
68
- result = response.json()
69
- st.header("Batch Prediction Results")
70
- st.write(result)
71
- else:
72
- st.error("Error in API request")
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import joblib
2
  import pandas as pd
3
+ from flask import Flask, request, jsonify
4
+
5
+ # Initialize Flask app
6
+ sales_api = Flask("Product Store Sales Predictor")
7
+
8
+ # Load the trained sales prediction model
9
+ model = joblib.load("sales_prediction_model_v1_0.joblib")
10
+
11
+
12
+ # Define a route for the home page
13
+ @sales_api.get('/')
14
+ def home():
15
+ return "Welcome to the Product Store Sales Prediction API!"
16
+
17
+ # ==============================
18
+ # Single record prediction endpoint
19
+ # ==============================
20
+ @sales_api.post('/v1/sales')
21
+ def predict_sales():
22
+ try:
23
+ # Get JSON data from the request
24
+ data = request.get_json()
25
+
26
+ # Extract all required product/store features from the input data
27
+ sample = {
28
+ 'Product_Id': data['Product_Id'],
29
+ 'Product_Weight': data['Product_Weight'],
30
+ 'Product_Sugar_Content': data['Product_Sugar_Content'],
31
+ 'Product_Allocated_Area': data['Product_Allocated_Area'],
32
+ 'Product_Type': data['Product_Type'],
33
+ 'Product_MRP': data['Product_MRP'],
34
+ 'Store_Id': data['Store_Id'],
35
+ 'Store_Establishment_Year': data['Store_Establishment_Year'],
36
+ 'Store_Size': data['Store_Size'],
37
+ 'Store_Location_City_Type': data['Store_Location_City_Type'],
38
+ 'Store_Type': data['Store_Type']
39
+ }
40
+
41
+ # Convert dictionary to DataFrame
42
+ input_df = pd.DataFrame([sample])
43
+
44
+ # Make prediction using the trained model
45
+ prediction = model.predict(input_df).tolist()[0]
46
+
47
+ # Return JSON response
48
+ return jsonify({'Predicted_Product_Store_Sales_Total': prediction})
49
+
50
+ except Exception as e:
51
+ return jsonify({'error': str(e)}), 400
52
+
53
+ # ==============================
54
+ # Batch prediction endpoint
55
+ # ==============================
56
+ @sales_api.post('/v1/salesbatch')
57
+ def predict_sales_batch():
58
+ try:
59
+ # Get uploaded CSV file from the request
60
+ file = request.files['file']
61
+
62
+ # Read CSV file into DataFrame
63
+ input_data = pd.read_csv(file)
64
+
65
+ # Make predictions on the batch
66
+ predictions = model.predict(input_data).tolist()
67
+
68
+ # Add predictions as new column
69
+ input_data['Predicted_Product_Store_Sales_Total'] = predictions
70
+
71
+ # Convert DataFrame to list of dicts for JSON output
72
+ result = input_data.to_dict(orient='records')
73
+
74
+ return jsonify(result)
75
+
76
+ except Exception as e:
77
+ return jsonify({'error': str(e)}), 400
78
+
79
+ # ==============================
80
+ # Run Flask app
81
+ # ==============================
82
+ if __name__ == '__main__':
83
+ sales_api.run(debug=True)
requirements.txt CHANGED
@@ -1,3 +1,10 @@
1
  pandas==2.2.2
 
 
 
 
 
 
 
2
  requests==2.28.1
3
- streamlit==1.43.2
 
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]