Monikasulur commited on
Commit
048339d
Β·
verified Β·
1 Parent(s): 3b82402

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +9 -9
  2. app.py +52 -66
  3. requirements.txt +1 -15
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_api`: Runs the Flask app (Flask app instance is named `superkart_api` inside app.py)
16
- CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:7860", "app:superkart_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 7860 and make it accessible externally
14
+ CMD ["streamlit", "run", "app.py", "--server.port=7860", "--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,57 @@
1
 
 
 
 
2
  import numpy as np
3
- import pandas as pd
4
- import joblib
5
- from flask import Flask, request, jsonify
6
- from flask_cors import CORS
7
- import os
8
 
9
- # Initialize Flask app
10
- superkart_api = Flask("superkart_sales_api")
11
- CORS(superkart_api)
12
-
13
- # Load the trained model pipeline (preprocessing + model)
14
- model = joblib.load("/content/drive/My Drive/Python/Superkart/deployment_files/superkart_sales_forecast_model_v1_0.joblib")
15
-
16
- # Health check route
17
- @superkart_api.get('/')
18
- def home():
19
- return "βœ… Welcome to the SuperKart Sales Prediction API"
20
-
21
- # Prediction route
22
- @superkart_api.post('/v1/predict')
23
- def predict_sales():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  try:
25
- # Parse JSON payload
26
- data = request.get_json()
27
- print("Raw incoming data:", data)
28
-
29
- # Validate expected fields
30
- required_fields = [
31
- 'Product_Weight',
32
- 'Product_Sugar_Content',
33
- 'Product_Allocated_Area',
34
- 'Product_MRP',
35
- 'Store_Size',
36
- 'Store_Location_City_Type',
37
- 'Store_Type',
38
- 'Store_Age_Years',
39
- 'Product_Type_Category'
40
- ]
41
- missing_fields = [f for f in required_fields if f not in data]
42
- if missing_fields:
43
- return jsonify({'error': f"Missing fields: {missing_fields}"}), 400
44
-
45
- # Convert and transform input
46
- sample = {
47
- 'Product_Weight': float(data['Product_Weight']),
48
- 'Product_Sugar_Content': data['Product_Sugar_Content'],
49
- 'Product_Allocated_Area_Log': np.log1p(float(data['Product_Allocated_Area'])), # transform here
50
- 'Product_MRP': float(data['Product_MRP']),
51
- 'Store_Size': data['Store_Size'],
52
- 'Store_Location_City_Type': data['Store_Location_City_Type'],
53
- 'Store_Type': data['Store_Type'],
54
- 'Store_Age_Years': int(data['Store_Age_Years']),
55
- 'Product_Type_Category': data['Product_Type_Category']
56
- }
57
-
58
- input_df = pd.DataFrame([sample])
59
- print("Transformed input for model:\n", input_df)
60
-
61
- # Make prediction
62
- prediction = model.predict(input_df).tolist()[0]
63
- return jsonify({'Predicted_Sales': prediction})
64
-
65
  except Exception as e:
66
- print("❌ Error during prediction:", str(e))
67
- return jsonify({'error': f"Prediction failed: {str(e)}"}), 500
68
-
69
- # Run the app (for local testing only)
70
- if __name__ == '__main__':
71
- superkart_api.run(debug=True)
 
1
 
2
+ # Streamlit Web App for SuperKart Sales Forecasting
3
+ import streamlit as st
4
+ import requests
5
  import numpy as np
 
 
 
 
 
6
 
7
+ # Add Logo
8
+ st.image("https://i.postimg.cc/2yM4LgJM/Superkart-notebook-cover-image.png", width=400)
9
+
10
+ # App Title
11
+ st.title("πŸ›’ SuperKart Sales Forecasting App")
12
+
13
+ # Instructions
14
+ st.markdown("πŸ” Enter product and store attributes to forecast **monthly product sales revenue**.\n\n_All sales are reported in ($) USD._")
15
+
16
+ # User Inputs
17
+ Product_Weight = st.number_input("Product Weight (oz)", min_value=0.0, value=12.66)
18
+ Product_Sugar_Content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar"])
19
+ Product_Allocated_Area = st.number_input("Product Allocated Area (linear in.)", min_value=0.0, value=100.0)
20
+ Product_MRP = st.number_input("Maximum Retail Price (USD)", min_value=0.0, value=150.0)
21
+ Store_Size = st.selectbox("Store Size", ["Small", "Medium", "High"])
22
+ Store_Location_City_Type = st.selectbox("Store Location City Type", ["Tier 1", "Tier 2", "Tier 3"])
23
+ Store_Type = st.selectbox("Store Type", ["Supermarket Type1", "Supermarket Type2", "Departmental Store", "Food Mart"])
24
+ Store_Age_Years = st.slider("Store Age (years)", min_value=0, max_value=30, value=10)
25
+ Product_Type_Category = st.selectbox("Product Type Category", ["Perishables", "Non Perishables"])
26
+
27
+ # Apply log1p transform (must match backend model training)
28
+ Product_Allocated_Area_Log = np.log1p(Product_Allocated_Area)
29
+
30
+ # Prepare JSON payload for the backend
31
+ product_data = {
32
+ "Product_Weight": str(Product_Weight),
33
+ "Product_Sugar_Content": Product_Sugar_Content,
34
+ "Product_Allocated_Area": str(Product_Allocated_Area),
35
+ "Product_MRP": str(Product_MRP),
36
+ "Store_Size": Store_Size,
37
+ "Store_Location_City_Type": Store_Location_City_Type,
38
+ "Store_Type": Store_Type,
39
+ "Store_Age_Years": str(Store_Age_Years),
40
+ "Product_Type_Category": Product_Type_Category
41
+ }
42
+
43
+ # Trigger Prediction
44
+ if st.button("Predict", type='primary'):
45
  try:
46
+ response = requests.post(
47
+ "https://thomash007-superkart-sales-forecast-backend2.hf.space/v1/predict",
48
+ json=product_data
49
+ )
50
+ if response.status_code == 200:
51
+ result = response.json()
52
+ predicted_sales = result["Predicted_Sales"]
53
+ st.success(f"πŸ“ˆ Predicted Monthly Sales: **${predicted_sales:,.2f} USD**")
54
+ else:
55
+ st.error("❌ API Error: Please verify input values or try again later.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  except Exception as e:
57
+ st.error(f"⚠️ Connection error: {e}")
 
 
 
 
 
requirements.txt CHANGED
@@ -1,16 +1,2 @@
1
- # Core libraries
2
- pandas==2.2.2
3
- numpy==2.0.2
4
- scikit-learn==1.6.1
5
- seaborn==0.13.2
6
- joblib==1.4.2
7
- xgboost==2.1.4
8
-
9
- # Flask web server
10
- flask==2.2.2
11
- flask-cors==3.0.10
12
- gunicorn==20.1.0
13
- Werkzeug==2.2.2
14
-
15
- # For API testing
16
  requests==2.32.3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  requests==2.32.3
2
+ streamlit==1.45.0