1- # spell-checker: disable
21"""
2+ all_recipes.py
33All Recipes Page for Smart Pantry Application (SQLite version)
4+
5+ Features:
6+ - Load recipes from SQLite database
7+ - Display recipe list with ingredients and instructions
8+ - Supports search/filtering
9+
10+ Date: 2025-11-20
411"""
512
613import ast
1017import pandas as pd
1118import streamlit as st
1219
20+ # ---------- Page Setup ----------
1321st .set_page_config (page_title = "All Recipes" , page_icon = "π" , layout = "wide" )
1422
1523st .title ("π All Recipes" )
1624st .caption ("Browse all available recipes in the Smart Pantry system." )
1725
1826
19- # ---------- Load recipes from SQLite ----------
27+ # ---------- Load Recipes ----------
2028@st .cache_data
21- def load_recipes ():
29+ def load_recipes () -> pd . DataFrame :
2230 """
23- Load recipes from the SQLite database and normalize column names.
24- Returns a DataFrame with columns: Recipe, Ingredients, Instructions
31+ Load recipes from SQLite database and normalize column names.
32+
33+ Returns:
34+ pd.DataFrame: Columns = Recipe, Ingredients, Instructions
2535 """
2636 db_path = "smart_pantry_manager/data/Recipe_Dataset.sqlite"
27-
28- # Check if database file exists
2937 if not os .path .exists (db_path ):
3038 st .error (f"β Database file not found at: { db_path } " )
3139 return pd .DataFrame (columns = ["Recipe" , "Ingredients" , "Instructions" ])
3240
33- # Connect to SQLite database
3441 conn = sqlite3 .connect (db_path )
35-
3642 try :
37- # Load the table "recipes"
3843 df = pd .read_sql_query ("SELECT * FROM recipes" , conn )
39- except Exception as e :
40- st .error (f"Error reading database: { e } " )
44+ except Exception as err :
45+ st .error (f"Error reading database: { err } " )
4146 conn .close ()
4247 return pd .DataFrame (columns = ["Recipe" , "Ingredients" , "Instructions" ])
43-
4448 conn .close ()
4549
4650 # Normalize column names
4751 df .columns = [c .strip ().lower () for c in df .columns ]
4852
49- # Rename columns if they exist
5053 rename_map = {
5154 "title" : "Recipe" ,
5255 "cleaned_ingredients" : "Ingredients" ,
@@ -60,47 +63,59 @@ def load_recipes():
6063 # Keep only required columns
6164 required_cols = ["Recipe" , "Ingredients" , "Instructions" ]
6265 df = df [[col for col in required_cols if col in df .columns ]]
63-
6466 return df
6567
6668
67- def format_ingredients (ingredients_str ) :
69+ def format_ingredients (ingredients_str : str ) -> list :
6870 """
69- Convert ingredients from string representation of list to a Python list.
71+ Convert ingredients string into a list.
72+
73+ Args:
74+ ingredients_str (str): String representation of ingredients
75+
76+ Returns:
77+ list: List of ingredients as strings
7078 """
79+ if not ingredients_str :
80+ return []
81+
82+ s = ingredients_str .strip ()
7183 try :
72- # Try to parse as a Python list
73- if ingredients_str .startswith ("[" ):
74- return ast .literal_eval (ingredients_str )
75- # If it's comma-separated
76- elif "," in ingredients_str :
77- return [item .strip () for item in ingredients_str .split ("," )]
78- else :
79- return [ingredients_str ]
80- except :
81- # If parsing fails, return as single item list
82- return [ingredients_str ]
83-
84-
85- recipes = load_recipes ()
86-
87- # ---------- Display recipes ----------
88- if recipes .empty :
84+ if s .startswith ("[" ) and s .endswith ("]" ):
85+ parsed = ast .literal_eval (s )
86+ if isinstance (parsed , (list , tuple )):
87+ return [str (x ).strip () for x in parsed if str (x ).strip ()]
88+ if "," in s :
89+ return [item .strip () for item in s .split ("," ) if item .strip ()]
90+ return [s ]
91+ except Exception :
92+ # fallback for | or newline-separated strings
93+ if "|" in s :
94+ return [x .strip () for x in s .split ("|" ) if x .strip ()]
95+ if "\n " in s :
96+ return [x .strip () for x in s .split ("\n " ) if x .strip ()]
97+ return [s ]
98+
99+
100+ recipes_df = load_recipes ()
101+
102+ # ---------- Display Recipes ----------
103+ if recipes_df .empty :
89104 st .info ("No recipes found." )
90105else :
91- search = st .text_input ("π Search for a recipe:" )
92- filtered = (
93- recipes [ recipes ["Recipe" ].str .contains (search , case = False , na = False )]
94- if search
95- else recipes
106+ search_term = st .text_input ("π Search for a recipe:" )
107+ filtered_df = (
108+ recipes_df [ recipes_df ["Recipe" ].str .contains (search_term , case = False , na = False )]
109+ if search_term
110+ else recipes_df
96111 )
97112
98- for _ , row in filtered .iterrows ():
113+ for _ , row in filtered_df .iterrows ():
99114 with st .expander (f"π { row ['Recipe' ]} " ):
100115 st .markdown ("**π§ Ingredients:**" )
101- ingredients_list = format_ingredients (row [ "Ingredients" ] )
102- for ingredient in ingredients_list :
103- st .write (f"β’ { ingredient } " )
116+ ing_list = format_ingredients (row . get ( "Ingredients" ) or "" )
117+ for ing in ing_list :
118+ st .write (f"β’ { ing } " )
104119
105120 st .markdown ("**π©βπ³ Instructions:**" )
106- st .write (row [ "Instructions" ] )
121+ st .write (row . get ( "Instructions" ) or "No instructions available." )
0 commit comments