demo-app / src /streamlit_app.py
indiapuig's picture
Update src/streamlit_app.py
f6c7aed verified
# streamlit run fridge.py
import os
import json
import streamlit as st
from datetime import datetime
name = "Project Cooking"
st.set_page_config(
page_title=name,
page_icon="πŸ‘©β€πŸ³"
)
#
# app title
st.title(name)
st.subheader("Add Items")
# dict for items
if 'items' not in st.session_state:
st.session_state.fridge_items = []
DATA_DIR = "data"
FRIDGE_FILE = "data/items.json"
# load items
def load_items():
if os.path.exists(FRIDGE_FILE):
with open(FRIDGE_FILE, 'r') as f:
return json.load(f)
return [] # empty list if no file
# save items
def save_items(items):
with open(FRIDGE_FILE, 'w') as f:
json.dump(items, f)
# load items into the project
st.session_state.fridge_items = load_items()
# split into 2 columns
col1, col2 = st.columns([2.5, 1])
with col1:
new_item = st.text_input("Item Name")
with col2:
categories = ["Meats", "Vegetables", "Dairy", "Fruits", "Carbs", "Other"]
category = st.selectbox("Category", categories)
col1, col2 = st.columns([1, 2.5])
with col2:
units = ["Amount", "Weight (g)"]
unit = st.selectbox("Units", units)
unit = 'g' if unit == 'Weight (g)' else ''
with col1:
amount = st.number_input("Amount (optional)", step=1)
# button to add item to fridge
if st.button("Add Item", use_container_width=True):
if new_item:
# create item with today's day's
item_data = {
'name': new_item,
'category': category,
'amount': f'{amount}{unit}',
'added_on': datetime.now().strftime("%Y-%m-%d")
}
st.session_state.fridge_items.append(item_data)
save_items(st.session_state.fridge_items)
# confermation
st.success(f"Added {new_item} to the fridge")
else:
st.warning("Please enter an item name")
#Display Items
st.subheader("Items in Fridge")
if not st.session_state.fridge_items:
st.info("Your Fridge is empty. Add some items to get started")
else:
#Group by category
fridge_categories = {}
for item in st.session_state.fridge_items:
category = item["category"]
if category not in fridge_categories:
fridge_categories[category] = []
fridge_categories[category].append(item)
# display
for category, items in fridge_categories.items():
with st.expander(f"{category} ({len(items)} items)", expanded=True):
for i, item in enumerate(items):
col1, col2 = st.columns([3, 1])
with col1:
st.write(f"{item['name']}: {item['amount']}")
with col2:
if st.button("Remove", key=f"remove_{category}_{i}"):
original_index = st.session_state.fridge_items.index(item)
st.session_state.fridge_items.pop(original_index)
save_items(st.session_state.fridge_items)
st.rerun()
# Clear all button
if st.button("Clear All Items", use_container_width=True):
if st.session_state.fridge_items:
st.session_state.fridge_items = []
save_items([])
st.success("All items cleared from your fridge!")
st.experimental_rerun()
else:
st.info("Your fridge is already empty!")