Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added smart_pantry_manager/data/pantry_omnia.xlsx
Binary file not shown.
101 changes: 76 additions & 25 deletions smart_pantry_manager/pages/all_recipes.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,55 @@
# spell-checker: disable
"""
all_recipes.py
All Recipes Page for Smart Pantry Application (SQLite version)

Features:
- Load recipes from SQLite database
- Display recipe list with ingredients and instructions
- Supports search/filtering

Date: 2025-11-20
"""

import ast
import os
import sqlite3

import pandas as pd
import streamlit as st

# ---------- Page Setup ----------
st.set_page_config(page_title="All Recipes", page_icon="📜", layout="wide")

st.title("📜 All Recipes")
st.caption("Browse all available recipes in the Smart Pantry system.")


# ---------- Load recipes from SQLite ----------
# ---------- Load Recipes ----------
@st.cache_data
def load_recipes():
def load_recipes() -> pd.DataFrame:
"""
Load recipes from the SQLite database and normalize column names.
Returns a DataFrame with columns: Recipe, Ingredients, Instructions
Load recipes from SQLite database and normalize column names.

Returns:
pd.DataFrame: Columns = Recipe, Ingredients, Instructions
"""
db_path = "the_app/data/Recipe_Dataset.sqlite"
db_path = "smart_pantry_manager/data/Recipe_Dataset.sqlite"
if not os.path.exists(db_path):
st.error(f"❌ Database file not found at: {db_path}")
return pd.DataFrame(columns=["Recipe", "Ingredients", "Instructions"])

# Connect to SQLite database
conn = sqlite3.connect(db_path)

# Load the table "recipes"
df = pd.read_sql_query("SELECT * FROM recipes", conn)

try:
df = pd.read_sql_query("SELECT * FROM recipes", conn)
except Exception as err:
st.error(f"Error reading database: {err}")
conn.close()
return pd.DataFrame(columns=["Recipe", "Ingredients", "Instructions"])
conn.close()

# Normalize column names
df.columns = [c.strip().lower() for c in df.columns]

# Rename columns if they exist
rename_map = {
"title": "Recipe",
"cleaned_ingredients": "Ingredients",
Expand All @@ -47,24 +63,59 @@ def load_recipes():
# Keep only required columns
required_cols = ["Recipe", "Ingredients", "Instructions"]
df = df[[col for col in required_cols if col in df.columns]]

return df


recipes = load_recipes()
def format_ingredients(ingredients_str: str) -> list:
"""
Convert ingredients string into a list.

Args:
ingredients_str (str): String representation of ingredients

# ---------- Display recipes ----------
if recipes.empty:
Returns:
list: List of ingredients as strings
"""
if not ingredients_str:
return []

s = ingredients_str.strip()
try:
if s.startswith("[") and s.endswith("]"):
parsed = ast.literal_eval(s)
if isinstance(parsed, (list, tuple)):
return [str(x).strip() for x in parsed if str(x).strip()]
if "," in s:
return [item.strip() for item in s.split(",") if item.strip()]
return [s]
except Exception:
# fallback for | or newline-separated strings
if "|" in s:
return [x.strip() for x in s.split("|") if x.strip()]
if "\n" in s:
return [x.strip() for x in s.split("\n") if x.strip()]
return [s]


recipes_df = load_recipes()

# ---------- Display Recipes ----------
if recipes_df.empty:
st.info("No recipes found.")
else:
search = st.text_input("🔍 Search for a recipe:")
filtered = (
recipes[recipes["Recipe"].str.contains(search, case=False, na=False)]
if search
else recipes
search_term = st.text_input("🔍 Search for a recipe:")
filtered_df = (
recipes_df[recipes_df["Recipe"].str.contains(search_term, case=False, na=False)]
if search_term
else recipes_df
)

for _, row in filtered.iterrows():
with st.expander(row["Recipe"]):
st.markdown(f"**🧂 Ingredients:** {row['Ingredients']}")
st.markdown(f"**👩‍🍳 Instructions:** {row['Instructions']}")
for _, row in filtered_df.iterrows():
with st.expander(f"📖 {row['Recipe']}"):
st.markdown("**🧂 Ingredients:**")
ing_list = format_ingredients(row.get("Ingredients") or "")
for ing in ing_list:
st.write(f"• {ing}")

st.markdown("**👩‍🍳 Instructions:**")
st.write(row.get("Instructions") or "No instructions available.")
Loading
Loading