swaraj shinde commited on
Commit
1a698ed
·
1 Parent(s): 013c4d0

initial_commit

Browse files
Dockerfile CHANGED
@@ -1,20 +1,16 @@
1
- FROM python:3.13.5-slim
2
 
3
- WORKDIR /app
 
 
4
 
5
- RUN apt-get update && apt-get install -y \
6
- build-essential \
7
- curl \
8
- git \
9
- && rm -rf /var/lib/apt/lists/*
10
 
11
  COPY requirements.txt ./
12
- COPY src/ ./src/
13
-
14
- RUN pip3 install -r requirements.txt
15
 
16
- EXPOSE 8501
17
 
18
- HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
19
 
20
- ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
1
+ FROM python:3.11-slim
2
 
3
+ ENV PYTHONDONTWRITEBYTECODE=1 \
4
+ PYTHONUNBUFFERED=1 \
5
+ PIP_NO_CACHE_DIR=1
6
 
7
+ WORKDIR /app
 
 
 
 
8
 
9
  COPY requirements.txt ./
10
+ RUN pip install --upgrade pip && pip install -r requirements.txt
 
 
11
 
12
+ COPY . .
13
 
14
+ EXPOSE 7860
15
 
16
+ CMD ["streamlit", "run", "/app/main.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.headless=true"]
README.md CHANGED
@@ -1,19 +1,30 @@
1
  ---
2
- title: Test 4
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
  sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
  pinned: false
11
- short_description: Streamlit template space
12
  ---
13
 
14
- # Welcome to Streamlit!
15
 
16
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
 
17
 
18
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
19
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Agri ML Hub
3
+ emoji: 🌾
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
 
 
8
  pinned: false
 
9
  ---
10
 
11
+ # Agri ML Hub (Docker Space)
12
 
13
+ This Space runs a Streamlit app with multiple ML model interfaces.
14
+ Model artifacts are fetched from Hugging Face Hub repo `pankaj-munde/dataintel_v1` at runtime.
15
 
16
+ ## Runtime env (optional)
17
+
18
+ - `HF_REPO_ID` (default: `pankaj-munde/dataintel_v1`)
19
+ - `HF_REPO_TYPE` (default: `model`; set `dataset` if your repo is a dataset repo)
20
+ - `HF_REVISION` (optional branch/tag/commit)
21
+ - `HF_TOKEN` (required only for private repos)
22
+
23
+ ## Local run
24
+
25
+ ```bash
26
+ docker build -t agri-ml-hub .
27
+ docker run -p 7860:7860 agri-ml-hub
28
+ ```
29
+
30
+ Then open `http://localhost:7860`.
main.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from model_interface.a_2_banana_harvest_forecasting import banana_harvest_forecasting
3
+ from model_interface.a_1_sales_forecasting_vegpro import sales_forecasting
4
+ from model_interface.a_3_customer_scoring_vegpro import run_sales_score_app
5
+ # -------------------------------
6
+ # Sidebar Project Selection
7
+ # -------------------------------
8
+ st.set_page_config(page_title="🌾 Agri ML Hub", layout="wide")
9
+ st.sidebar.title("🔘 Select DS Model")
10
+ project = st.sidebar.selectbox("Choose a Model:", [
11
+ "1_Sales_forecasting_vegpro",
12
+ "2_Banana_Harvest_Forecasting",
13
+ "3_Customer_scoring_vegpro"
14
+ ])
15
+
16
+ if project == "2_Banana_Harvest_Forecasting":
17
+ banana_harvest_forecasting()
18
+ elif project=="1_Sales_forecasting_vegpro":
19
+ sales_forecasting()
20
+ elif project=="3_Customer_scoring_vegpro":
21
+ run_sales_score_app()
model_interface/__init__.py ADDED
File without changes
model_interface/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (145 Bytes). View file
 
model_interface/__pycache__/a_1_banana_harvest_forecasting.cpython-312.pyc ADDED
Binary file (3.57 kB). View file
 
model_interface/__pycache__/a_1_sales_forecasting_vegpro.cpython-312.pyc ADDED
Binary file (6.73 kB). View file
 
model_interface/__pycache__/a_2_banana_harvest_forecasting.cpython-312.pyc ADDED
Binary file (3.57 kB). View file
 
model_interface/__pycache__/a_3_customer_scoring_vegpro.cpython-312.pyc ADDED
Binary file (2.21 kB). View file
 
model_interface/a_1_sales_forecasting_vegpro.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib
5
+ from model_interface.hf_model_store import get_artifact_path
6
+
7
+ # ---------------------------
8
+ # Load Weekly Model
9
+ # ---------------------------
10
+ def load_weekly_model():
11
+ model = joblib.load(get_artifact_path("model_files/1_sales_forecasting_vegpro/weekly/week_best_model.joblib"))
12
+ scaler = joblib.load(get_artifact_path("model_files/1_sales_forecasting_vegpro/weekly/week_scaler.joblib"))
13
+ label_enc = joblib.load(get_artifact_path("model_files/1_sales_forecasting_vegpro/weekly/week_label_encoder.joblib"))
14
+ return model, scaler, label_enc
15
+
16
+ # ---------------------------
17
+ # Load Monthly Model
18
+ # ---------------------------
19
+ def load_monthly_model():
20
+ model = joblib.load(get_artifact_path("model_files/1_sales_forecasting_vegpro/monthly/month_best_model.joblib"))
21
+ scaler = joblib.load(get_artifact_path("model_files/1_sales_forecasting_vegpro/monthly/month_scaler.joblib"))
22
+ label_enc = joblib.load(get_artifact_path("model_files/1_sales_forecasting_vegpro/monthly/month_label_encoder.joblib"))
23
+ return model, scaler, label_enc
24
+
25
+ # ---------------------------
26
+ # Sidebar – LHS Selection
27
+ # ---------------------------
28
+ def sales_forecasting():
29
+ st.sidebar.title("📊 Prediction Dashboard")
30
+ project = st.sidebar.radio(
31
+ "Select Prediction Type",
32
+ ["Weekly Prediction", "Monthly Prediction"]
33
+ )
34
+
35
+ # ---------------------------
36
+ # WEEKLY PREDICTION SECTION
37
+ # ---------------------------
38
+ if project == "Weekly Prediction":
39
+
40
+ st.title("🌾 Weekly Crop Order Quantity Prediction")
41
+
42
+ def predict_weekly(input_data, model, scaler, label_enc):
43
+ input_data = input_data.copy()
44
+
45
+ crop_name = input_data["Crop_Name"].values[0]
46
+ if crop_name not in label_enc.classes_:
47
+ return f"❌ Error: Crop '{crop_name}' was not seen during training!"
48
+
49
+ input_data["Crop_Name"] = label_enc.transform([crop_name])[0]
50
+
51
+ feature_cols = [
52
+ 'Crop_Name', 'Weekly_rate_mean_t-5', 'Weekly_rate_mean_t-4', 'Weekly_rate_mean_t-3',
53
+ 'Weekly_rate_mean_t-2', 'Weekly_rate_mean_t-1',
54
+ 'Crop_wise_weekly_quantity_t-5', 'Crop_wise_weekly_quantity_t-4',
55
+ 'Crop_wise_weekly_quantity_t-3', 'Crop_wise_weekly_quantity_t-2',
56
+ 'Crop_wise_weekly_quantity_t-1'
57
+ ]
58
+
59
+ input_data = input_data[feature_cols]
60
+
61
+ num_cols = [col for col in feature_cols if col != "Crop_Name"]
62
+ input_data[num_cols] = scaler.transform(input_data[num_cols])
63
+
64
+ predicted = model.predict(input_data)[0]
65
+ return f"✅ Predicted Quantity: {predicted:.2f} KG"
66
+
67
+ # Load weekly model
68
+ model, scaler, label_enc = load_weekly_model()
69
+
70
+ crop_name = st.selectbox("Crop Name:", label_enc.classes_)
71
+ weekly_rates = [st.number_input(f"Weekly Rate Mean (t-{i})", step=1) for i in range(5,0,-1)]
72
+ weekly_qty = [st.number_input(f"Crop-wise Quantity (t-{i})", step=1) for i in range(5,0,-1)]
73
+
74
+ if st.button("Predict Weekly Quantity"):
75
+ df = pd.DataFrame({
76
+ "Crop_Name": [crop_name],
77
+ "Weekly_rate_mean_t-5": [weekly_rates[0]],
78
+ "Weekly_rate_mean_t-4": [weekly_rates[1]],
79
+ "Weekly_rate_mean_t-3": [weekly_rates[2]],
80
+ "Weekly_rate_mean_t-2": [weekly_rates[3]],
81
+ "Weekly_rate_mean_t-1": [weekly_rates[4]],
82
+ "Crop_wise_weekly_quantity_t-5": [weekly_qty[0]],
83
+ "Crop_wise_weekly_quantity_t-4": [weekly_qty[1]],
84
+ "Crop_wise_weekly_quantity_t-3": [weekly_qty[2]],
85
+ "Crop_wise_weekly_quantity_t-2": [weekly_qty[3]],
86
+ "Crop_wise_weekly_quantity_t-1": [weekly_qty[4]],
87
+ })
88
+
89
+ result = predict_weekly(df, model, scaler, label_enc)
90
+ st.success(result)
91
+
92
+ # ---------------------------
93
+ # MONTHLY PREDICTION SECTION
94
+ # ---------------------------
95
+ elif project == "Monthly Prediction":
96
+
97
+ st.title("🌱 Monthly Crop Order Quantity Prediction")
98
+
99
+ def preprocess_input(data, label_encoders, scaler, categorical_cols, numerical_cols):
100
+ data = data.copy()
101
+
102
+ for col in categorical_cols:
103
+ enc = label_encoders.get(col)
104
+ data[col] = data[col].apply(lambda x: enc.transform([x])[0] if x in enc.classes_ else -1)
105
+
106
+ data[numerical_cols] = scaler.transform(data[numerical_cols])
107
+ return data
108
+
109
+ categorical_cols = ["Crop_Name"]
110
+ numerical_cols = [
111
+ "Mean_per_kg_rate-3", "Mean_per_kg_rate-2", "Mean_per_kg_rate-1",
112
+ "Mean_order_quantity-3", "Mean_order_quantity-2", "Mean_order_quantity-1"
113
+ ]
114
+
115
+ model, scaler, label_encoders = load_monthly_model()
116
+ crop_names = list(label_encoders["Crop_Name"].classes_)
117
+
118
+ selected_crop = st.selectbox("Select Crop Name", crop_names)
119
+
120
+ rate_3 = st.number_input("Mean per kg rate (3 months ago)", step=1)
121
+ rate_2 = st.number_input("Mean per kg rate (2 months ago)", step=1)
122
+ rate_1 = st.number_input("Mean per kg rate (1 month ago)", step=1)
123
+
124
+ qty_3 = st.number_input("Mean order quantity (3 months ago)", step=1)
125
+ qty_2 = st.number_input("Mean order quantity (2 months ago)", step=1)
126
+ qty_1 = st.number_input("Mean order quantity (1 month ago)", step=1)
127
+
128
+ if st.button("Predict Monthly Quantity"):
129
+
130
+ df = pd.DataFrame({
131
+ "Crop_Name": [selected_crop],
132
+ "Mean_per_kg_rate-3": [rate_3],
133
+ "Mean_per_kg_rate-2": [rate_2],
134
+ "Mean_per_kg_rate-1": [rate_1],
135
+ "Mean_order_quantity-3": [qty_3],
136
+ "Mean_order_quantity-2": [qty_2],
137
+ "Mean_order_quantity-1": [qty_1],
138
+ })
139
+
140
+ X_new = preprocess_input(df, label_encoders, scaler, categorical_cols, numerical_cols)
141
+ y_pred = model.predict(X_new)[0]
142
+
143
+ st.success(f"Predicted Monthly Quantity: {y_pred:.2f} KG")
144
+
145
+ # ---------------------------
146
+ # CUSTOMER SCORE SECTION
147
+ # ---------------------------
model_interface/a_2_banana_harvest_forecasting.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import pandas as pd
4
+ import joblib
5
+ from model_interface.hf_model_store import get_artifact_path
6
+
7
+ @st.cache_resource
8
+ def load_files():
9
+ best_model = joblib.load(get_artifact_path("model_files/2_banana_harvest_forecasting/best_regression_model.joblib"))
10
+ scaler = joblib.load(get_artifact_path("model_files/2_banana_harvest_forecasting/banana_scale.joblib"))
11
+ label_enc = joblib.load(get_artifact_path("model_files/2_banana_harvest_forecasting/banana_label.joblib"))
12
+ return best_model, scaler, label_enc
13
+
14
+ best_model, scaler, label_enc = load_files()
15
+
16
+ def banana_harvest_forecasting():
17
+
18
+
19
+ # Feature names
20
+ cat_col = ['Crop']
21
+ num_col = [
22
+ 'Temperature_avg_day', 'Relative_humidity_avg_day', 'Rain_avg_day',
23
+ 'Wind_speed_avg_day', 'Wind_direction_avg_day',
24
+ 'Shortwave_radiation_avg_day', 'NDVI'
25
+ ]
26
+
27
+ # Streamlit UI
28
+ st.title("🍌 Banana Yield Prediction App")
29
+
30
+ with st.form("prediction_form"):
31
+ st.subheader("Enter the following inputs:")
32
+
33
+ crop = st.selectbox("Crop", ["Banana"]) # Only Banana for now
34
+ temp = st.number_input("Temperature Avg (°C)", value=25.0)
35
+ humidity = st.number_input("Relative Humidity Avg (%)", value=86.0)
36
+ rain = st.number_input("Rain Avg (mm)", value=1.0)
37
+ wind_speed = st.number_input("Wind Speed Avg (km/h)", value=10.0)
38
+ wind_dir = st.number_input("Wind Direction Avg (°)", value=114.0)
39
+ radiation = st.number_input("Shortwave Radiation Avg", value=193.0)
40
+ ndvi = st.number_input("NDVI", value=0.32)
41
+
42
+ submitted = st.form_submit_button("Predict Yield")
43
+
44
+ if submitted:
45
+ # Prepare input DataFrame
46
+ input_data = pd.DataFrame({
47
+ "Crop": [crop],
48
+ "Temperature_avg_day": [temp],
49
+ "Relative_humidity_avg_day": [humidity],
50
+ "Rain_avg_day": [rain],
51
+ "Wind_speed_avg_day": [wind_speed],
52
+ "Wind_direction_avg_day": [wind_dir],
53
+ "Shortwave_radiation_avg_day": [radiation],
54
+ "NDVI": [ndvi]
55
+ })
56
+
57
+ # Preprocess function
58
+ def preprocess_data(df):
59
+ for col in cat_col:
60
+ if col in label_enc:
61
+ df[col] = label_enc[col].transform(df[col])
62
+ df[num_col] = scaler.transform(df[num_col])
63
+ return df
64
+
65
+ # Prediction
66
+ processed_input = preprocess_data(input_data)
67
+ prediction = best_model.predict(processed_input)[0]
68
+
69
+ st.success(f"✅ Predicted Yield: **{prediction:.2f} Kg/acre**")
model_interface/a_3_customer_scoring_vegpro.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import joblib
3
+ import pandas as pd
4
+ from model_interface.hf_model_store import get_artifact_path
5
+
6
+ def run_sales_score_app():
7
+
8
+ # -----------------------------
9
+ # Load model + scaler
10
+ # -----------------------------
11
+ best_model = joblib.load(get_artifact_path("model_files/3_customer_scoring_vegpro/top_1_model_Gradient_Boosting.joblib"))
12
+ scaler = joblib.load(get_artifact_path("model_files/3_customer_scoring_vegpro/scale.joblib"))
13
+
14
+ # -----------------------------
15
+ # UI
16
+ # -----------------------------
17
+ st.title("Sales Score Prediction App")
18
+ st.write("Enter the required details below to predict the sales score.")
19
+
20
+ # Inputs
21
+ sales_order_quantity = st.number_input("Sales Order Quantity", min_value=0, step=1, value=10)
22
+ total_order_count = st.number_input("Total Order Count", min_value=0, step=1, value=1)
23
+ avg_spend_per_order_crop = st.number_input("Avg Spend per Order Crop", min_value=0.0, step=0.01, value=500.0)
24
+ order_frequency_days = st.number_input("Order Frequency (Days)", min_value=1, step=1, value=1)
25
+ total_amount = st.number_input("Total Amount", min_value=0.0, step=0.01, value=1000.0)
26
+
27
+ # Predict button
28
+ if st.button("Predict Sales Score"):
29
+
30
+ # Create dataframe
31
+ df = pd.DataFrame({
32
+ "SalesOrder_Quantity": [sales_order_quantity],
33
+ "Total_order_count": [total_order_count],
34
+ "Avg_spend_per_order_crop": [avg_spend_per_order_crop],
35
+ "Order_frequency_days": [order_frequency_days],
36
+ "Total_Amount": [total_amount]
37
+ })
38
+
39
+ # Scale
40
+ cols = df.columns
41
+ df[cols] = scaler.transform(df[cols])
42
+
43
+ # Predict
44
+ prediction = best_model.predict(df)[0].round(2)
45
+
46
+ st.success(f"Predicted Sales Score: {prediction}")
47
+
48
+
49
+
50
+ # https://github.com/swarajshinde2003/dash_test_1/blob/00ba0ec378468aae2defe669f5a4e3c13e8f59f4/model_files/3_customer_scoring_vegpro/top_1_model_Gradient_Boosting.joblib
51
+ # https://github.com/swarajshinde2003/dash_test_1/blob/main/model_files/3_customer_scoring_vegpro/top_1_model_Gradient_Boosting.joblib
model_interface/a_4_inventory_managemnt.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+
4
+ def inventory_management():
5
+ st.title("Inventory Management Vegpro")
6
+ # Load Excel file directly from path
7
+ df = pd.read_excel("model_files/4_inventory_mangement/Final5.xlsx")
8
+
9
+ # Step 1: Select Item Type
10
+ item_type = st.selectbox(
11
+ "Select Item Type",
12
+ sorted(df["Item_Type"].unique())
13
+ )
14
+
15
+ df_type = df[df["Item_Type"] == item_type]
16
+
17
+ # Step 2: Select Item SubType
18
+ item_subtype = st.selectbox(
19
+ "Select Item SubType",
20
+ sorted(df_type["Item_SubType"].unique())
21
+ )
22
+
23
+ df_subtype = df_type[df_type["Item_SubType"] == item_subtype]
24
+
25
+ # Step 3: Select Item Name
26
+ item_name = st.selectbox(
27
+ "Select Item Name",
28
+ sorted(df_subtype["Item_Name"].unique())
29
+ )
30
+
31
+ df_name = df_subtype[df_subtype["Item_Name"] == item_name]
32
+
33
+ # Step 4: Select Item Code
34
+ item_code = st.selectbox(
35
+ "Select Item Code",
36
+ sorted(df_name["Item_Code"].unique())
37
+ )
38
+
39
+ df_code = df_name[df_name["Item_Code"] == item_code]
40
+
41
+ # Step 5: Select Unit
42
+ unit = st.selectbox(
43
+ "Select Unit",
44
+ sorted(df_code["Unit"].unique())
45
+ )
46
+
47
+ df_final = df_code[df_code["Unit"] == unit]
48
+
49
+ st.subheader("Result:")
50
+
51
+ # Display final result
52
+ st.write(df_final[["Safety_stock", "Minimum_level", "Maximum_level", "Reorder_quantity"]])
model_interface/hf_model_store.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from huggingface_hub import hf_hub_download
5
+ from huggingface_hub.errors import EntryNotFoundError
6
+
7
+ HF_REPO_ID = os.getenv("HF_REPO_ID", "pankaj-munde/dataintel_v1")
8
+ HF_REPO_TYPE = os.getenv("HF_REPO_TYPE", "model")
9
+ HF_REVISION = os.getenv("HF_REVISION")
10
+ HF_CACHE_DIR = os.getenv("HF_HOME")
11
+
12
+
13
+ def get_artifact_path(relative_path: str) -> Path:
14
+ candidates = [relative_path]
15
+
16
+ if relative_path.startswith("model_files/"):
17
+ candidates.append(relative_path.removeprefix("model_files/"))
18
+ else:
19
+ candidates.append(f"model_files/{relative_path}")
20
+
21
+ last_error = None
22
+ for candidate in dict.fromkeys(candidates):
23
+ try:
24
+ return Path(
25
+ hf_hub_download(
26
+ repo_id=HF_REPO_ID,
27
+ filename=candidate,
28
+ repo_type=HF_REPO_TYPE,
29
+ revision=HF_REVISION,
30
+ cache_dir=HF_CACHE_DIR,
31
+ )
32
+ )
33
+ except EntryNotFoundError as exc:
34
+ last_error = exc
35
+
36
+ raise FileNotFoundError(
37
+ f"Artifact not found in '{HF_REPO_ID}'. Tried paths: {candidates}. "
38
+ "Verify repo folder structure and file names."
39
+ ) from last_error
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ