-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsmart_pantry.py
More file actions
314 lines (259 loc) · 9.71 KB
/
smart_pantry.py
File metadata and controls
314 lines (259 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
smart_pantry.py
Smart Pantry Web App (Home Page Only)
Features:
- Personal pantry for each user, stored in Excel
- Add, edit, and track products with automatic expiry alerts
- Support for numeric quantities and units (e.g., g, kg, ml, count)
- Visual indicators for soon-to-expire and expired items
- Optional loading animation when saving
- Optional demo video to guide new users
Date: 27/11/2025
"""
import os
import time
from datetime import datetime
import pandas as pd
import streamlit as st
# ----- Styling Functions -----
def style_expired(expired_products_df):
return expired_products_df.style.set_properties(
**{
"background-color": "#EB4343", # Light Red
"color": "black",
}
)
def style_expiring_soon(expiring_products_df):
return expiring_products_df.style.set_properties(
**{
"background-color": "#F5DB76", # Light Yellow
"color": "black",
}
)
# ---------- Page Setup ----------
st.set_page_config(page_title="Smart Pantry Manager", page_icon="🧺", layout="centered")
st.markdown(
"""
<h1 style='text-align:center; color:#C69B3B;'>
🧺 Smart Pantry Manager
</h1>
<h3 style='text-align:center; color:#E0C27B; font-weight:300;'>
Smart tracking, elegant design, and a pantry that always works for you ✨
</h3>
""",
unsafe_allow_html=True,
)
# ---------- Auto-Switching Images on Home Page ----------
img1 = "smart_pantry_manager/assets/image1.png"
img2 = "smart_pantry_manager/assets/image2.png"
# Make sure the folder exists
os.makedirs("smart_pantry_manager/assets", exist_ok=True)
# Create a spot on the page where the image will update
placeholder = st.empty()
# Alternate images every 3 seconds
if "show_img1" not in st.session_state:
st.session_state["show_img1"] = True
if st.session_state["show_img1"]:
placeholder.image(img1, use_container_width=True)
st.session_state["show_img1"] = False
else:
placeholder.image(img2, use_container_width=True)
st.session_state["show_img1"] = True
time.sleep(3)
# ---------- Sidebar: User Profile ----------
st.sidebar.header("👤 User Profile")
username = st.sidebar.text_input("Enter your name or email:")
# If user has NOT entered anything → show info and stop the app
if not username:
st.info(
"👈 Please click 'User Profile' on the left to enter your name or email to start."
)
st.stop()
# If user HAS entered an email → show success message
else:
st.sidebar.success("You entered successfully! ✅")
st.session_state["username"] = username
# Create user-specific file path
os.makedirs("smart_pantry_manager/data/user_data", exist_ok=True)
USER_FILE = f"smart_pantry_manager/data/user_data/pantry_{username.replace(' ', '_').lower()}.xlsx"
# ---------- Load Pantry ----------
@st.cache_data
def load_pantry(file_path):
"""Load pantry data for a specific user or create empty table."""
try:
df = pd.read_excel(file_path)
df["Expiry Date"] = pd.to_datetime(df["Expiry Date"], errors="coerce")
df["Days Left"] = (df["Expiry Date"] - datetime.now()).dt.days
# Remove expired items automatically
# df = df[df["Days Left"] >= 0].reset_index(drop=True)
return df
except FileNotFoundError:
return pd.DataFrame(
columns=[
"Product",
"Category",
"Quantity",
"Unit",
"Expiry Date",
"Days Left",
]
)
pantry_df = load_pantry(USER_FILE)
# Store in session_state
if "pantry_data" not in st.session_state:
st.session_state["pantry_data"] = pantry_df
# ---------- Add New Product ----------
st.header("➕ Add a New Product")
product_name = st.text_input("Product name:")
product_category = st.selectbox(
"Category:",
[
"Uncategorized",
"Bakery",
"Fruits",
"Vegetables",
"Meat",
"Seafood",
"Dairy",
"Protein",
"Condiments",
"Grains",
"Snacks",
"Beverages",
"Frozen Foods",
"Canned Goods",
"Spices & Seasonings",
"Milks & Alternatives",
"Drinks",
],
)
product_quantity = st.number_input(
"Quantity (numeric or count):", min_value=0.0, step=0.1
)
product_unit = st.selectbox(
"Unit:", ["count", "g", "kg", "ml", "L", "cup", "tbsp", "tsp"]
)
expiry_date = st.date_input("Expiry date:")
if st.button("💾 Save product"):
if product_name:
with st.spinner("💾 Saving product... please wait..."):
time.sleep(2)
today = datetime.now().date()
days_left = (expiry_date - today).days
new_product = {
"Product": product_name,
"Category": product_category,
"Quantity": product_quantity,
"Unit": product_unit,
"Expiry Date": expiry_date,
"Days Left": days_left,
}
pantry_df = st.session_state["pantry_data"]
pantry_df = pd.concat(
[pantry_df, pd.DataFrame([new_product])], ignore_index=True
)
# Sort by Days Left
pantry_df = pantry_df.sort_values(
by="Days Left", ascending=True
).reset_index(drop=True)
pantry_df.to_excel(USER_FILE, index=False)
st.session_state["pantry_data"] = pantry_df
st.cache_data.clear()
st.success(f"✅ {product_name} added successfully!")
else:
st.warning("Please enter a product name.")
# ---------- Update Days Left ----------
if not st.session_state["pantry_data"].empty:
pantry_df = st.session_state["pantry_data"]
pantry_df["Expiry Date"] = pd.to_datetime(pantry_df["Expiry Date"], errors="coerce")
today = pd.Timestamp(datetime.now().date())
pantry_df["Days Left"] = (pantry_df["Expiry Date"] - today).dt.days
st.session_state["pantry_data"] = pantry_df
# ---------- Alerts ----------
st.markdown("### ⚠️ Expiry Alerts")
current_df = st.session_state["pantry_data"] # renamed
if not current_df.empty:
expired_items = current_df[current_df["Days Left"] <= 0].copy() # renamed
expired_items = expired_items.sort_values(by="Days Left")
expiring_items = current_df[
(current_df["Days Left"] > 0) & (current_df["Days Left"] <= 5)
].copy() # renamed
# ---------- Expired Products ----------
if not expired_items.empty:
with st.expander("❌ Expired Products (Click to view)", expanded=True):
st.dataframe(
style_expired(expired_items[["Product", "Expiry Date", "Days Left"]]),
use_container_width=True,
)
col1, col2 = st.columns([2, 1])
if col2.button("🗑️ Delete ALL expired"):
current_df = current_df[current_df["Days Left"] >= 0]
st.session_state["pantry_data"] = current_df
current_df.to_excel(USER_FILE, index=False)
st.success("All expired products deleted!")
# ---------- Expiring Soon ----------
if not expiring_items.empty:
with st.expander("⏰ Expiring Soon (Within 3 days)", expanded=True):
st.dataframe(
style_expiring_soon(
expiring_items[["Product", "Expiry Date", "Days Left"]]
),
use_container_width=True,
)
# ---------- Manage Section ----------
st.markdown("---")
st.markdown("### 🛠 Manage Products")
colA, colB = st.columns([2, 3])
selected_item = colA.selectbox("Choose a product:", current_df["Product"].unique())
if selected_item:
item_row = current_df[current_df["Product"] == selected_item].iloc[0]
colB.markdown(f"**Current:** {item_row['Quantity']} {item_row['Unit']}")
new_quantity = colB.number_input(
"New quantity:",
min_value=0.0,
max_value=float(item_row["Quantity"]),
value=float(item_row["Quantity"]),
step=0.1,
)
col1, col2 = st.columns([1, 1])
if col1.button("✔️ Update Quantity"):
current_df.loc[current_df["Product"] == selected_item, "Quantity"] = (
new_quantity
)
st.session_state["pantry_data"] = current_df
current_df.to_excel(USER_FILE, index=False)
st.success("Quantity updated!")
if col2.button("🗑️ Delete Product"):
current_df = current_df[current_df["Product"] != selected_item]
st.session_state["pantry_data"] = current_df
current_df.to_excel(USER_FILE, index=False)
st.success(f"{selected_item} deleted!")
st.markdown("---")
# ---------- Pantry Table ----------
st.header("📦 Your Pantry Items")
def color_days(val):
"""Color based on days left."""
if val < 0:
color = "#ff4d4d"
elif val <= 3:
color = "#ffcc00"
else:
color = "#85e085"
return f"background-color: {color}; color: black;"
if not pantry_df.empty:
display_data = pantry_df.sort_values(by="Days Left", ascending=True)
styled_data = display_data.reset_index(drop=True).style.applymap(
color_days, subset=["Days Left"]
)
st.dataframe(styled_data, use_container_width=True)
else:
st.info("Your pantry is empty. Add your first product above!")
# ---------- Manual Save ----------
if st.button("🔄 Save Changes"):
if not pantry_df.empty:
pantry_df_sorted = pantry_df.sort_values(by="Days Left", ascending=True)
pantry_df_sorted.to_excel(USER_FILE, index=False)
st.session_state["pantry_data"] = pantry_df_sorted
st.success("Pantry data saved successfully (sorted by expiry)!")
else:
st.info("No items to save.")