ShanRaja commited on
Commit
0ae57cc
·
verified ·
1 Parent(s): 14e403b

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +10 -9
  2. app.py +71 -52
  3. requirements.txt +0 -8
Dockerfile CHANGED
@@ -1,16 +1,17 @@
 
1
  FROM python:3.10-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_predictor_api"]
 
1
+ # Use the official Python slim image
2
  FROM python:3.10-slim
3
 
4
+ # Set working directory
5
  WORKDIR /app
6
 
7
+ # Copy app files
8
  COPY . .
9
 
10
+ # Install dependencies
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
 
13
+ # Expose Streamlit default port
14
+ EXPOSE 7860
15
+
16
+ # Run the Streamlit app
17
+ CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.enableCORS=false"]
app.py CHANGED
@@ -1,53 +1,72 @@
1
- import numpy as np
2
- import joblib
 
3
  import pandas as pd
4
- from flask import Flask, request, jsonify
5
-
6
- # Initialize the Flask application
7
- sales_predictor_api = Flask("SuperKart Sales Predictor")
8
-
9
- # Load the trained machine learning model
10
- model = joblib.load("superkart_sales_prediction_model_v1_0.joblib")
11
-
12
- # Define a route for the home page (GET request)
13
- @sales_predictor_api.get('/')
14
- def home():
15
- """
16
- This function handles GET requests to the root URL ('/') of the API.
17
- It returns a simple welcome message.
18
- """
19
- return "Welcome to the SuperKart Sales Prediction API!"
20
-
21
- # Define an endpoint for single property prediction (POST request)
22
- @sales_predictor_api.post('/v1/sales')
23
- def predict_sales():
24
- """
25
- This function handles POST requests to the '/v1/sales' endpoint.
26
- It expects a JSON payload containing property details and returns
27
- the predicted rental price as a JSON response.
28
- """
29
- # Get the JSON data from the request body
30
- data = request.get_json()
31
- # Extract relevant features from the JSON data
32
- sample = {
33
- 'Product_Id': data['product_id'],
34
- 'Product_Weight': data['product_weight'],
35
- 'Product_Sugar_Content': data['product_sugar_content'],
36
- 'Product_Allocated_Area': data['product_allocated_area'],
37
- 'Product_Type': data['product_type'],
38
- 'Product_MRP': data['product_mrp'],
39
- 'Store_Id': data['store_id'],
40
- 'Store_Establishment_Year': data['store_establishment_year'],
41
- 'Store_Size': data['store_size'],
42
- 'Store_Location_City_Type': data['store_location_city_type'],
43
- 'Store_Type': 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
- pred = model.predict(input_data)[0]
51
-
52
- # Return the actual price
53
- return jsonify({'Predicted Sales': round(float(pred), 2)})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import re
3
+ import streamlit as st
4
  import pandas as pd
5
+ import requests
6
+
7
+ valid_store_ids = ["OUT001", "OUT002", "OUT003", "OUT004"]
8
+ store_meta = {
9
+ "OUT001": {"year": 1987, "size": "High", "city_type": "Tier 2", "store_type": "Supermarket Type1"},
10
+ "OUT002": {"year": 1998, "size": "Small", "city_type": "Tier 3", "store_type": "Food Mart"},
11
+ "OUT003": {"year": 1999, "size": "Medium", "city_type": "Tier 1", "store_type": "Departmental Store"},
12
+ "OUT004": {"year": 2009, "size": "Medium", "city_type": "Tier 2", "store_type": "Supermarket Type2"},
13
+ }
14
+
15
+ st.title("SmartKart: Product Sales Prediction")
16
+ st.subheader("Online Prediction")
17
+
18
+ product_id = st.text_input("Product ID (2 uppercase letters + 4 digits, e.g., FD6114)", max_chars=6)
19
+ product_id_valid = bool(re.fullmatch(r"[A-Z]{2}\d{4}", product_id))
20
+ if product_id and not product_id_valid:
21
+ st.error("Invalid Product ID format; it must be 2 uppercase letters followed by 4 digits.")
22
+ elif product_id_valid:
23
+ st.success("Product ID format is valid.")
24
+
25
+ store_id = st.selectbox("Store ID", options=valid_store_ids)
26
+ meta = store_meta[store_id]
27
+ st.text(f"Store Establishment Year: **{meta['year']}**")
28
+ st.text(f"Store Size: **{meta['size']}**")
29
+ st.text(f"Store Location City Type: **{meta['city_type']}**")
30
+ st.text(f"Store Type: **{meta['store_type']}**")
31
+
32
+ product_weight = st.number_input("Product Weight", min_value=0.0, value=12.0, format="%.2f")
33
+ product_sugar_content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar"])
34
+ product_allocated_area = st.slider("Product Allocated Area Ratio", min_value=0.0, max_value=1.0, step=0.001, value=0.05)
35
+ product_type = st.selectbox("Product Type", [
36
+ "Meat", "Snack Foods", "Hard Drinks", "Dairy", "Canned", "Soft Drinks",
37
+ "Health and Hygiene", "Baking Goods", "Bread", "Breakfast", "Frozen Foods",
38
+ "Fruits and Vegetables", "Household", "Seafood", "Starchy Foods", "Others"
39
+ ])
40
+ product_mrp = st.number_input("Product MRP", min_value=0.0, value=150.0, format="%.2f")
41
+
42
+ input_data = pd.DataFrame([{
43
+ "Product_Id": product_id,
44
+ "Product_Weight": product_weight,
45
+ "Product_Sugar_Content": product_sugar_content,
46
+ "Product_Allocated_Area": product_allocated_area,
47
+ "Product_Type": product_type,
48
+ "Product_MRP": product_mrp,
49
+ "Store_Id": store_id,
50
+ "Store_Establishment_Year": meta['year'],
51
+ "Store_Size": meta['size'],
52
+ "Store_Location_City_Type": meta['city_type'],
53
+ "Store_Type": meta['store_type'],
54
+ }])
55
+
56
+ if st.button("Predict"):
57
+ if not product_id_valid:
58
+ st.error("Please fix the Product ID before proceeding.")
59
+ else:
60
+ try:
61
+ with st.spinner("Fetching prediction..."):
62
+ response = requests.post(
63
+ "https://ShanRaja/Model_Sales_Prediction_SuperKart.hf.space/v1/sales",
64
+ json=input_data.to_dict(orient="records")[0]
65
+ )
66
+ if response.status_code == 200:
67
+ prediction = response.json().get("Predicted Sales")
68
+ st.success(f"Predicted Product Sales: {prediction}")
69
+ else:
70
+ st.error(f"API Error {response.status_code}: {response.text}")
71
+ except Exception as e:
72
+ st.error(f"Prediction request failed: {e}")
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