Spaces:
Sleeping
Sleeping
Download app.py from Leospencer1/BitesizedAI: direct link, hf CLI and curl.
- Browser
- Download file 145 kB
-
https://huggingface.co/spaces/Leospencer1/BitesizedAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Leospencer1/BitesizedAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Leospencer1/BitesizedAI/resolve/main/app.py
145 kB
# Bitesized AI Meal Planner
# SMART MEAL PLANNING WITH INGREDIENT REUSE
# - Recipes share common ingredients for true weekly savings
# - Realistic UK supermarket pricing
# - Weekly shopping list generation
# - Budget-friendly meal planning
# - Powered by Google Gemini 2.5 Flash
# Install required packages
#
# Import libraries
import google.generativeai as genai
import gradio as gr
import pandas as pd
import markdown2
import json
import os
from datetime import datetime
import time
import random
import requests
import re
from collections import Counter
import pickle
# Multi-supermarket pricing system
SUPERMARKET_PRICES = {
"aldi": {
"name": "Aldi",
"prices": {
"chicken_breast": {"price": 3.25, "unit": "500g"}, # Updated Jan 2026 (Β£6.49/kg verified)
"beef_mince": {"price": 4.25, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 2.39, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.49, "unit": "12"}, # Updated Jan 2026 (verified from Aldi.co.uk)
"onions": {"price": 0.99, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.55, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.35, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.45, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.45, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.09, "unit": "1kg"}, # Updated Jan 2026
"pasta": {"price": 0.69, "unit": "500g"}, # Updated Jan 2026
"milk": {"price": 1.25, "unit": "2L"}, # Updated Jan 2026
"cheddar": {"price": 2.19, "unit": "350g"}, # Updated Jan 2026
"mushrooms": {"price": 0.85, "unit": "250g"}, # Updated Jan 2026
"peppers": {"price": 1.39, "unit": "3 pack"}, # Updated Jan 2026
# Pre-made alternatives (often cheaper than from scratch!)
"coleslaw": {"price": 0.79, "unit": "300g tub"}, # Much cheaper than making from scratch
"pasta_sauce": {"price": 0.55, "unit": "500g jar"}, # Cheaper than tinned tomatoes + herbs
"curry_sauce": {"price": 0.89, "unit": "400g jar"}, # Cheaper than buying all spices
"grated_cheese": {"price": 1.69, "unit": "200g"}, # Sometimes more convenient
"hummus": {"price": 0.99, "unit": "200g tub"}, # Cheaper than making from scratch
"puff_pastry": {"price": 1.19, "unit": "375g"}, # Way easier than homemade
"garlic_bread": {"price": 0.75, "unit": "2 pack"}, # Cheaper than making
"salad_bag": {"price": 0.65, "unit": "120g bag"}, # Better value than whole lettuce sometimes
}
},
"lidl": {
"name": "Lidl",
"prices": {
"chicken_breast": {"price": 3.25, "unit": "500g"}, # Updated Jan 2026 (Β£6.49/kg verified)
"beef_mince": {"price": 4.35, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 2.49, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.55, "unit": "12"}, # Updated Jan 2026
"onions": {"price": 1.05, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.59, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.39, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.19, "unit": "1kg"}, # Updated Jan 2026
"pasta": {"price": 0.75, "unit": "500g"}, # Updated Jan 2026
"milk": {"price": 1.29, "unit": "2L"}, # Updated Jan 2026
"cheddar": {"price": 2.29, "unit": "350g"}, # Updated Jan 2026
"mushrooms": {"price": 0.89, "unit": "250g"}, # Updated Jan 2026
"peppers": {"price": 1.45, "unit": "3 pack"}, # Updated Jan 2026
# Pre-made alternatives
"coleslaw": {"price": 0.85, "unit": "300g tub"},
"pasta_sauce": {"price": 0.59, "unit": "500g jar"},
"curry_sauce": {"price": 0.95, "unit": "400g jar"},
"grated_cheese": {"price": 1.75, "unit": "200g"},
"hummus": {"price": 1.05, "unit": "200g tub"},
"puff_pastry": {"price": 1.25, "unit": "375g"},
"garlic_bread": {"price": 0.79, "unit": "2 pack"},
"salad_bag": {"price": 0.69, "unit": "120g bag"},
}
},
"asda": {
"name": "Asda",
"prices": {
"chicken_breast": {"price": 3.75, "unit": "500g"}, # Updated Jan 2026
"beef_mince": {"price": 5.10, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 2.95, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.25, "unit": "12"}, # Updated Jan 2026
"onions": {"price": 1.19, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.65, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.45, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.55, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.49, "unit": "1kg"}, # Updated Jan 2026
"pasta": {"price": 0.95, "unit": "500g"}, # Updated Jan 2026
"milk": {"price": 1.45, "unit": "2L"}, # Updated Jan 2026
"cheddar": {"price": 2.55, "unit": "350g"}, # Updated Jan 2026
"mushrooms": {"price": 0.99, "unit": "250g"}, # Updated Jan 2026
"peppers": {"price": 1.65, "unit": "3 pack"}, # Updated Jan 2026
# Pre-made alternatives
"coleslaw": {"price": 1.00, "unit": "300g tub"},
"pasta_sauce": {"price": 0.75, "unit": "500g jar"},
"curry_sauce": {"price": 1.15, "unit": "400g jar"},
"grated_cheese": {"price": 2.00, "unit": "200g"},
"hummus": {"price": 1.25, "unit": "200g tub"},
"puff_pastry": {"price": 1.45, "unit": "375g"},
"garlic_bread": {"price": 0.95, "unit": "2 pack"},
"salad_bag": {"price": 0.80, "unit": "120g bag"},
}
},
"tesco": {
"name": "Tesco",
"prices": {
"chicken_breast": {"price": 4.05, "unit": "500g"}, # Updated Jan 2026
"beef_mince": {"price": 5.35, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 3.25, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.35, "unit": "12"}, # Updated Jan 2026
"onions": {"price": 1.29, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.70, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.59, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.69, "unit": "1kg"}, # Updated Jan 2026
"pasta": {"price": 0.99, "unit": "500g"}, # Updated Jan 2026
"milk": {"price": 1.60, "unit": "2L"}, # Updated Jan 2026
"cheddar": {"price": 2.69, "unit": "350g"}, # Updated Jan 2026
"mushrooms": {"price": 1.09, "unit": "250g"}, # Updated Jan 2026
"peppers": {"price": 1.75, "unit": "3 pack"}, # Updated Jan 2026
# Pre-made alternatives
"coleslaw": {"price": 1.10, "unit": "300g tub"},
"pasta_sauce": {"price": 0.85, "unit": "500g jar"},
"curry_sauce": {"price": 1.25, "unit": "400g jar"},
"grated_cheese": {"price": 2.15, "unit": "200g"},
"hummus": {"price": 1.35, "unit": "200g tub"},
"puff_pastry": {"price": 1.55, "unit": "375g"},
"garlic_bread": {"price": 1.05, "unit": "2 pack"},
"salad_bag": {"price": 0.90, "unit": "120g bag"},
}
},
"sainsburys": {
"name": "Sainsbury's",
"prices": {
"chicken_breast": {"price": 4.25, "unit": "500g"}, # Updated Jan 2026
"beef_mince": {"price": 5.55, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 3.45, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.45, "unit": "12"}, # Updated Jan 2026
"onions": {"price": 1.35, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.75, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.55, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.65, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.55, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.79, "unit": "1kg"}, # Updated Jan 2026
"pasta": {"price": 1.05, "unit": "500g"}, # Updated Jan 2026
"milk": {"price": 1.65, "unit": "2L"}, # Updated Jan 2026
"cheddar": {"price": 2.85, "unit": "350g"}, # Updated Jan 2026
"mushrooms": {"price": 1.19, "unit": "250g"}, # Updated Jan 2026
"peppers": {"price": 1.85, "unit": "3 pack"}, # Updated Jan 2026
# Pre-made alternatives
"coleslaw": {"price": 1.15, "unit": "300g tub"},
"pasta_sauce": {"price": 0.90, "unit": "500g jar"},
"curry_sauce": {"price": 1.30, "unit": "400g jar"},
"grated_cheese": {"price": 2.25, "unit": "200g"},
"hummus": {"price": 1.40, "unit": "200g tub"},
"puff_pastry": {"price": 1.60, "unit": "375g"},
"garlic_bread": {"price": 1.10, "unit": "2 pack"},
"salad_bag": {"price": 0.95, "unit": "120g bag"},
}
}
}
# Postcode areas to available supermarkets (ordered cheapest first)
POSTCODE_SUPERMARKETS = {
"E": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # East London
"N": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # North London
"SE": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # South East London
"SW": ["lidl", "tesco", "sainsburys", "asda"], # South West London
"W": ["aldi", "tesco", "sainsburys", "asda"], # West London
"NW": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # North West London
"B": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # Birmingham
"M": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # Manchester
"L": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # Liverpool
"LS": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # Leeds
"S": ["aldi", "lidl", "asda", "tesco", "sainsburys"], # Sheffield
"DEFAULT": ["aldi", "lidl", "asda", "tesco", "sainsburys"]
}
def find_cheapest_supermarket(postcode):
"""Find cheapest supermarket available near postcode"""
if not postcode:
return "aldi", SUPERMARKET_PRICES["aldi"]
# Extract postcode area
postcode_clean = postcode.upper().strip()
postcode_area = ''.join(filter(str.isalpha, postcode_clean.split()[0] if postcode_clean else ''))
# Get available supermarkets for this area
available = POSTCODE_SUPERMARKETS.get(postcode_area,
POSTCODE_SUPERMARKETS.get(postcode_area[:1] if postcode_area else '',
POSTCODE_SUPERMARKETS["DEFAULT"]))
# Return first (cheapest) available
cheapest_code = available[0]
return cheapest_code, SUPERMARKET_PRICES[cheapest_code]
def get_supermarket_pricing_ref(postcode, currency="Β£"):
"""Generate pricing reference for cheapest local supermarket"""
supermarket_code, supermarket_data = find_cheapest_supermarket(postcode)
name = supermarket_data["name"]
prices = supermarket_data["prices"]
ref = "{0} PRICES ({1}, Jan 2026): ".format(name.upper(), name)
ref += "Chicken breast {0}{1}/{2}, ".format(currency, prices["chicken_breast"]["price"], prices["chicken_breast"]["unit"])
ref += "Beef mince {0}{1}/{2}, ".format(currency, prices["beef_mince"]["price"], prices["beef_mince"]["unit"])
ref += "Bacon {0}{1}/{2}, ".format(currency, prices["bacon"]["price"], prices["bacon"]["unit"])
ref += "Eggs {0}{1}/{2}, ".format(currency, prices["eggs"]["price"], prices["eggs"]["unit"])
ref += "Onions {0}{1}/{2}, ".format(currency, prices["onions"]["price"], prices["onions"]["unit"])
ref += "Garlic {0}{1}/{2}, ".format(currency, prices["garlic"]["price"], prices["garlic"]["unit"])
ref += "Tinned tomatoes {0}{1}/{2}, ".format(currency, prices["tomatoes_tinned"]["price"], prices["tomatoes_tinned"]["unit"])
ref += "Chickpeas {0}{1}/{2}, ".format(currency, prices["chickpeas_tin"]["price"], prices["chickpeas_tin"]["unit"])
ref += "Kidney beans {0}{1}/{2}, ".format(currency, prices["kidney_beans_tin"]["price"], prices["kidney_beans_tin"]["unit"])
ref += "Basmati rice {0}{1}/{2}, ".format(currency, prices["basmati_rice"]["price"], prices["basmati_rice"]["unit"])
ref += "Pasta {0}{1}/{2}, ".format(currency, prices["pasta"]["price"], prices["pasta"]["unit"])
ref += "Milk {0}{1}/{2}, ".format(currency, prices["milk"]["price"], prices["milk"]["unit"])
ref += "Cheddar {0}{1}/{2}".format(currency, prices["cheddar"]["price"], prices["cheddar"]["unit"])
return ref, name
# Image fetching for recipes - DISABLED
def get_recipe_image(recipe_name):
"""
Images disabled for compatibility
Return None to skip images
"""
return None # Images disabled
# User data storage directory
USER_DATA_DIR = "/mnt/user-data/users"
os.makedirs(USER_DATA_DIR, exist_ok=True)
def get_user_file(username, filename):
"""Get user-specific file path"""
user_dir = os.path.join(USER_DATA_DIR, username.replace("/", "_"))
os.makedirs(user_dir, exist_ok=True)
return os.path.join(user_dir, filename)
def save_user_recipes(username, recipes):
"""Save recipes for a specific user"""
filepath = get_user_file(username, "recipes.pkl")
with open(filepath, "wb") as f:
pickle.dump(recipes, f)
def load_user_recipes(username):
"""Load recipes for a specific user"""
filepath = get_user_file(username, "recipes.pkl")
if os.path.exists(filepath):
with open(filepath, "rb") as f:
return pickle.load(f)
return []
def log_user_activity(username, action, details=""):
"""Log user activity for tracking"""
log_file = os.path.join(USER_DATA_DIR, "activity_log.txt")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(log_file, "a") as f:
f.write(f"{timestamp} | {username} | {action} | {details}\n")
# Configure Gemini API
# API key will be set via Hugging Face Secrets
gemini_api_key = os.environ.get("GOOGLE_API_KEY")
if not gemini_api_key:
print("Gemini API key not found! Please check your environment variable.")
else:
print("Configuring Gemini API...")
genai.configure(api_key=gemini_api_key)
# OPTIMIZATION: Use faster model configuration with HIGHER temperature for more variety
generation_config = {
"temperature": 0.9, # INCREASED from 0.7 for more randomness
"top_p": 0.95, # INCREASED from 0.8 for more variety
"top_k": 50, # INCREASED from 40 for more options
"max_output_tokens": 16384, # DOUBLED - Full recipes with all sections including pre-made alternatives
}
# Test the API connection
def test_gemini_api():
try:
model = genai.GenerativeModel('gemini-2.5-flash', generation_config=generation_config)
response = model.generate_content("Say hello")
print("API connection successful!")
print("Response:", response.text)
return True
except Exception as e:
print("API connection failed:")
print(str(e))
return False
api_working = test_gemini_api()
# Currency symbols
CURRENCY_SYMBOLS = {
"US": "$", "UK": "Β£", "EU": "β¬", "Canada": "CAD$", "Australia": "AUD$",
}
# UK Ingredient Prices Database
UK_INGREDIENT_PRICES = {
"onions": {"price": 1.20, "unit": "1kg bag", "price_per_unit": 0.15},
"garlic": {"price": 0.65, "unit": "bulb", "price_per_unit": 0.65},
"carrots": {"price": 0.50, "unit": "1kg bag", "price_per_unit": 0.50},
"potatoes": {"price": 1.50, "unit": "2.5kg bag", "price_per_unit": 0.60},
"tomatoes": {"price": 0.90, "unit": "500g pack", "price_per_unit": 1.80},
"peppers": {"price": 1.50, "unit": "3-pack", "price_per_unit": 0.50},
"mushrooms": {"price": 1.00, "unit": "250g pack", "price_per_unit": 4.00},
"broccoli": {"price": 0.85, "unit": "head", "price_per_unit": 0.85},
"chicken breast": {"price": 6.00, "unit": "per kg", "price_per_unit": 6.00},
"chicken thighs": {"price": 4.50, "unit": "per kg", "price_per_unit": 4.50},
"beef mince": {"price": 5.00, "unit": "500g pack", "price_per_unit": 10.00},
"minced beef": {"price": 5.00, "unit": "500g pack", "price_per_unit": 10.00},
"pork mince": {"price": 4.50, "unit": "500g pack", "price_per_unit": 9.00},
"bacon": {"price": 2.50, "unit": "300g pack", "price_per_unit": 8.33},
"sausages": {"price": 2.00, "unit": "400g pack", "price_per_unit": 5.00},
"salmon fillet": {"price": 12.00, "unit": "per kg", "price_per_unit": 12.00},
"tuna": {"price": 1.20, "unit": "tin", "price_per_unit": 1.20},
"milk": {"price": 1.65, "unit": "4 pints", "price_per_unit": 1.65},
"eggs": {"price": 2.20, "unit": "dozen", "price_per_unit": 0.18},
"butter": {"price": 1.90, "unit": "250g pack", "price_per_unit": 7.60},
"cheese": {"price": 2.50, "unit": "400g block", "price_per_unit": 6.25},
"pasta": {"price": 0.90, "unit": "500g pack", "price_per_unit": 1.80},
"rice": {"price": 2.00, "unit": "1kg bag", "price_per_unit": 2.00},
"bread": {"price": 1.20, "unit": "800g loaf", "price_per_unit": 1.50},
"tinned tomatoes": {"price": 0.45, "unit": "400g tin", "price_per_unit": 0.45},
"chickpeas": {"price": 0.55, "unit": "400g tin", "price_per_unit": 0.55},
"olive oil": {"price": 3.50, "unit": "500ml bottle", "price_per_unit": 7.00},
}
def get_ingredient_price_info(ingredient_name):
ingredient_lower = ingredient_name.lower().strip()
if ingredient_lower in UK_INGREDIENT_PRICES:
return UK_INGREDIENT_PRICES[ingredient_lower]
for key, value in UK_INGREDIENT_PRICES.items():
if ingredient_lower in key or key in ingredient_lower:
return value
return {"price": 1.50, "unit": "estimated", "price_per_unit": 1.50}
# Postcode cache
postcode_cache = {}
def get_location_from_postcode(postcode):
if not postcode:
return "United Kingdom", "GBP"
if postcode in postcode_cache:
return postcode_cache[postcode]
try:
response = requests.get("https://api.postcodes.io/postcodes/{0}".format(postcode), timeout=3)
if response.status_code == 200:
data = response.json()["result"]
location = "{0}, {1}, UK".format(data['admin_district'], data['region'])
result = (location, "GBP")
postcode_cache[postcode] = result
return result
except:
pass
result = ("{0}, UK".format(postcode), "GBP")
postcode_cache[postcode] = result
return result
# Shopping List Manager
class ShoppingListManager:
def __init__(self):
self.shopping_list = []
def add_item(self, item, quantity="", notes="", category="Other"):
for existing_item in self.shopping_list:
if existing_item["item"].lower() == item.lower():
return "'{0}' is already in your shopping list".format(item)
new_item = {
"item": item,
"quantity": quantity,
"notes": notes,
"category": category,
"completed": False,
"status": "Pending",
"date_added": datetime.now().strftime("%Y-%m-%d %H:%M")
}
self.shopping_list.append(new_item)
return "Added '{0}' to shopping list".format(item)
def remove_item(self, item_index):
if 0 <= item_index < len(self.shopping_list):
removed_item = self.shopping_list.pop(item_index)
return "Removed '{0}' from shopping list".format(removed_item['item'])
return "Item not found"
def mark_completed(self, item_index):
if 0 <= item_index < len(self.shopping_list):
item = self.shopping_list[item_index]
item["completed"] = not item["completed"]
status = "completed" if item["completed"] else "pending"
return "Marked '{0}' as {1}".format(item['item'], status)
return "Item not found"
def clear_completed(self):
completed_count = sum(1 for item in self.shopping_list if item["completed"])
self.shopping_list = [item for item in self.shopping_list if not item["completed"]]
return "Removed {0} completed items".format(completed_count)
def clear_all(self):
count = len(self.shopping_list)
self.shopping_list = []
return "Cleared all {0} items from shopping list".format(count)
def get_shopping_list_df(self):
if not self.shopping_list:
return pd.DataFrame(columns=["ID", "Item", "Qty", "Category", "Status"])
data = []
for i, item in enumerate(self.shopping_list):
status = item.get('status', 'Pending')
status_icon = "Done" if status == "Done" else "Pending"
data.append({
"ID": i + 1,
"Item": item["item"],
"Qty": item["quantity"] if item["quantity"] else "",
"Category": item["category"],
"Status": status_icon
})
return pd.DataFrame(data)
def extract_ingredients_from_recipe(self, recipe_content):
"""Extract ALL ingredients from recipe content"""
try:
# Look for the ingredients section in the recipe
if "## Ingredients" in recipe_content:
# Extract the section between ## Ingredients and the next ##
start = recipe_content.find("## Ingredients")
end = recipe_content.find("##", start + 15)
if end == -1:
ingredients_section = recipe_content[start:]
else:
ingredients_section = recipe_content[start:end]
# Parse ingredients from the section
ingredients = []
for line in ingredients_section.split('\n'):
line = line.strip()
# Skip headers and empty lines
if not line or line.startswith('#') or 'Ingredients' in line:
continue
# Skip the "IMPORTANT:" lines and instruction text
if line.startswith('IMPORTANT') or line.startswith('List each') or line.startswith('**Total'):
continue
# Look for lines that start with - or * or numbers
if line.startswith('- ') or line.startswith('* ') or line[0].isdigit():
# Remove bullet/number
if line.startswith('- ') or line.startswith('* '):
ingredient = line[2:].strip()
else:
# Remove number and period
ingredient = line.split('.', 1)[-1].strip() if '.' in line else line
# Clean up the ingredient
if ingredient and len(ingredient) > 2:
# Remove price information (anything after Β£ or $)
if 'Β£' in ingredient:
ingredient = ingredient.split('Β£')[0].strip()
if '$' in ingredient:
ingredient = ingredient.split('$')[0].strip()
# Remove parenthetical info about store purchases
if '(' in ingredient:
ingredient = ingredient.split('(')[0].strip()
ingredients.append(ingredient)
print(f"Extracted {len(ingredients)} ingredients from recipe")
return ingredients
else:
# Fallback to AI extraction if format is different
return self._ai_extract_ingredients(recipe_content)
except Exception as e:
print("Error extracting ingredients: {0}".format(e))
return self._ai_extract_ingredients(recipe_content)
def convert_to_shopping_quantity(self, ingredient_text):
"""Convert recipe quantity to realistic shopping quantity"""
import re
# STEP 1: Aggressive cleaning - remove ALL junk text
cleaned = ingredient_text
# Remove price info - all patterns
cleaned = re.sub(r'[-ββ]\s*GBP?\d+\.?\d*', '', cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r'GBP?\d+\.?\d*', '', cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r'Β£\d+\.?\d*', '', cleaned)
# Remove "needed" text
cleaned = re.sub(r'\s*needed\s*', ' ', cleaned, flags=re.IGNORECASE)
# Remove measurements at start: "1 tbsp", "2 tsp", "half a tsp", etc.
cleaned = re.sub(r'^\d+\.?\d*\s+(tbsp|tsp|tablespoons?|teaspoons?|cups?|ml|g|kg|oz|lbs?)\s+', '', cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r'^\d+/\d+\s+(tbsp|tsp|tablespoons?|teaspoons?|cups?)\s+', '', cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r'^(half\s+a?\s*|quarter\s+of?\s*|a\s+)(tbsp|tsp|tablespoon|teaspoon|cup)\s+(of\s+)?', '', cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r'^small\s+amount\s+of\s+(a\s+)?(tbsp|tsp)?\s*', '', cleaned, flags=re.IGNORECASE)
# Remove leading counts: "2 cloves", "1 bulb", etc.
cleaned = re.sub(r'^\d+\.?\d*\s+(cloves?|bulbs?|pieces?|stalks?|sprigs?)\s+(of\s+)?', '', cleaned, flags=re.IGNORECASE)
# Remove extra whitespace
cleaned = ' '.join(cleaned.split())
cleaned = cleaned.strip()
ingredient_lower = cleaned.lower()
# STEP 2: Comprehensive conversions for all common ingredients
# Eggs
if 'egg' in ingredient_lower and 'plant' not in ingredient_lower:
return self._convert_eggs(cleaned)
# Garlic & Ginger
if 'garlic' in ingredient_lower:
if 'powder' in ingredient_lower:
return "Garlic powder (jar)"
else:
return "1 bulb fresh garlic"
if 'ginger' in ingredient_lower:
if 'powder' in ingredient_lower or 'ground' in ingredient_lower:
return "Ground ginger (jar)"
else:
return "Fresh ginger root"
# Oils & Condiments
if 'olive oil' in ingredient_lower:
return "Olive oil (500ml bottle)"
if 'vegetable oil' in ingredient_lower or 'sunflower oil' in ingredient_lower:
return "Vegetable oil (1L bottle)"
if 'sesame oil' in ingredient_lower:
return "Sesame oil (small bottle)"
if 'soy sauce' in ingredient_lower:
return "Soy sauce (150ml bottle)"
if 'vinegar' in ingredient_lower:
return "Vinegar (bottle)"
if 'worcestershire' in ingredient_lower:
return "Worcestershire sauce (bottle)"
# Spices & Seasonings (all dried spices = jars)
spices = {
'chilli powder': 'Chilli powder (jar)',
'chili powder': 'Chilli powder (jar)',
'cumin': 'Cumin (jar)',
'coriander powder': 'Coriander powder (jar)',
'ground coriander': 'Coriander powder (jar)',
'turmeric': 'Turmeric powder (jar)',
'paprika': 'Paprika (jar)',
'smoked paprika': 'Smoked paprika (jar)',
'curry powder': 'Curry powder (jar)',
'garam masala': 'Garam masala (jar)',
'cayenne': 'Cayenne pepper (jar)',
'black pepper': 'Black pepper (jar)',
'white pepper': 'White pepper (jar)',
'oregano': 'Dried oregano (jar)',
'basil' if 'dried' in ingredient_lower else None: 'Dried basil (jar)',
'mixed herbs': 'Mixed herbs (jar)',
'italian seasoning': 'Italian seasoning (jar)',
'cinnamon': 'Cinnamon (jar)',
'nutmeg': 'Nutmeg (jar)',
}
for spice, shopping_name in spices.items():
if spice and spice in ingredient_lower:
return shopping_name
# Salt & Pepper
if ingredient_lower in ['salt', 'sea salt', 'table salt']:
return "Salt (container)"
if 'salt' in ingredient_lower and 'to taste' in ingredient_lower:
return "Salt (container)"
# Tins & Cans - check more broadly
if 'tin' in ingredient_lower or 'can' in ingredient_lower:
full_text_lower = cleaned.lower()
# Check for tomatoes
if 'tomato' in full_text_lower or 'tomatoes' in full_text_lower:
if 'chopped' in full_text_lower:
return "1 tin (400g) chopped tomatoes"
elif 'plum' in full_text_lower:
return "1 tin (400g) plum tomatoes"
else:
return "1 tin (400g) tomatoes"
# Check for beans
elif 'bean' in full_text_lower or 'beans' in full_text_lower:
if 'kidney' in full_text_lower:
return "1 tin (400g) kidney beans"
elif 'black' in full_text_lower:
return "1 tin (400g) black beans"
elif 'chickpea' in full_text_lower or 'garbanzo' in full_text_lower:
return "1 tin (400g) chickpeas"
elif 'baked' in full_text_lower:
return "1 tin (400g) baked beans"
elif 'butter' in full_text_lower:
return "1 tin (400g) butter beans"
elif 'cannellini' in full_text_lower:
return "1 tin (400g) cannellini beans"
else:
return "1 tin (400g) mixed beans"
# Check for coconut milk
elif 'coconut' in full_text_lower:
return "1 tin (400ml) coconut milk"
# Check for tuna
elif 'tuna' in full_text_lower:
return "1 tin tuna in spring water"
# Check for sweetcorn
elif 'corn' in full_text_lower or 'sweetcorn' in full_text_lower:
return "1 tin (325g) sweetcorn"
# If we can't determine, at least say it's a tin of something
else:
# Extract any remaining text after cleaning
remaining = re.sub(r'(half\s+a?\s*|quarter\s+of?\s*|a\s+)?(tin|can)\s*(of)?\s*', '', full_text_lower, flags=re.IGNORECASE)
remaining = remaining.strip()
if remaining and len(remaining) > 2:
return f"1 tin (400g) {remaining}"
else:
return "1 tin (400g) - check recipe for details"
# Stock & Bouillon
if 'stock' in ingredient_lower or 'broth' in ingredient_lower:
if 'chicken' in ingredient_lower:
return "Chicken stock (cube or liquid)"
elif 'beef' in ingredient_lower:
return "Beef stock (cube or liquid)"
elif 'vegetable' in ingredient_lower:
return "Vegetable stock (cube or liquid)"
else:
return "Stock (cube or liquid)"
# Rice & Pasta
if 'rice' in ingredient_lower:
if 'basmati' in ingredient_lower:
return "500g basmati rice"
elif 'jasmine' in ingredient_lower:
return "500g jasmine rice"
elif 'long grain' in ingredient_lower:
return "500g long grain rice"
else:
return "500g rice"
if 'pasta' in ingredient_lower or 'spaghetti' in ingredient_lower or 'penne' in ingredient_lower or 'fusilli' in ingredient_lower:
return "500g pasta"
if 'noodle' in ingredient_lower:
return "Noodles (packet)"
# Flour & Baking
if 'flour' in ingredient_lower:
return "1kg plain flour"
if 'sugar' in ingredient_lower:
return "Sugar (bag)"
if 'honey' in ingredient_lower:
return "Honey (jar)"
# Vegetables - realistic pack sizes
veg_conversions = {
'cucumber': '1 cucumber',
'courgette': '2 courgettes',
'zucchini': '2 zucchini',
'aubergine': '1 aubergine',
'eggplant': '1 eggplant',
'leek': '2 leeks',
'celery': '1 bunch celery',
}
for veg, shopping_name in veg_conversions.items():
if veg in ingredient_lower:
return shopping_name
# By weight vegetables (bags)
if 'onion' in ingredient_lower:
return self._convert_by_weight(cleaned, 'onions', 500)
if 'carrot' in ingredient_lower:
return self._convert_by_weight(cleaned, 'carrots', 500)
if 'potato' in ingredient_lower:
return self._convert_by_weight(cleaned, 'potatoes', 1000)
if 'tomato' in ingredient_lower and 'tin' not in ingredient_lower:
return self._convert_by_weight(cleaned, 'tomatoes', 500)
if 'mushroom' in ingredient_lower:
return self._convert_by_weight(cleaned, 'mushrooms', 250)
if 'pepper' in ingredient_lower and 'black' not in ingredient_lower and 'white' not in ingredient_lower:
return self._convert_items(cleaned, 'peppers', 3)
# Meat
if 'chicken breast' in ingredient_lower:
return self._convert_meat(cleaned, 'chicken breasts', 500)
if 'chicken thigh' in ingredient_lower:
return self._convert_meat(cleaned, 'chicken thighs', 500)
if 'chicken stock' in ingredient_lower:
return "Chicken stock (cube or pot)"
if 'mince' in ingredient_lower or 'ground beef' in ingredient_lower:
return self._convert_meat(cleaned, 'mince', 500)
if 'beef' in ingredient_lower and 'stock' not in ingredient_lower:
return self._convert_meat(cleaned, 'beef', 500)
if 'pork' in ingredient_lower:
return self._convert_meat(cleaned, 'pork', 500)
if 'salmon' in ingredient_lower:
return self._convert_meat(cleaned, 'salmon', 250)
if 'cod' in ingredient_lower:
return self._convert_meat(cleaned, 'cod', 250)
if 'prawns' in ingredient_lower or 'shrimp' in ingredient_lower:
return "200g prawns"
# Dairy
if 'milk' in ingredient_lower and 'coconut' not in ingredient_lower:
return self._convert_liquid(cleaned, 'milk', 568, 'ml', '1 pint')
if 'cream' in ingredient_lower:
if 'double' in ingredient_lower:
return "300ml double cream"
elif 'single' in ingredient_lower:
return "300ml single cream"
else:
return "300ml cream"
if 'yogurt' in ingredient_lower or 'yoghurt' in ingredient_lower:
return "500g natural yogurt"
if 'cheese' in ingredient_lower:
if 'cheddar' in ingredient_lower:
return "200g cheddar cheese"
elif 'parmesan' in ingredient_lower:
return "100g parmesan cheese"
elif 'mozzarella' in ingredient_lower:
return "125g mozzarella"
else:
return "200g cheese"
if 'butter' in ingredient_lower:
return "250g block of butter"
# Fresh herbs
herbs = {
'parsley': '1 bunch fresh parsley',
'coriander': '1 bunch fresh coriander',
'cilantro': '1 bunch fresh coriander',
'basil': '1 pot fresh basil' if 'fresh' in ingredient_lower else 'Dried basil (jar)',
'thyme': '1 pack fresh thyme',
'rosemary': '1 pack fresh rosemary',
'mint': '1 pack fresh mint',
'dill': '1 pack fresh dill',
}
for herb, shopping_name in herbs.items():
if herb in ingredient_lower:
return shopping_name
# Lemon/Lime
if 'lemon' in ingredient_lower:
return "2 lemons"
if 'lime' in ingredient_lower:
return "2 limes"
# Default: clean up and return
return self._clean_final_text(cleaned)
def _clean_final_text(self, text):
"""Final cleanup of text - remove ALL measurement prefixes and junk"""
import re
# Remove price info - multiple patterns
text = re.sub(r'[-ββ]\s*GBP?\d+\.?\d*', '', text, flags=re.IGNORECASE)
text = re.sub(r'GBP?\d+\.?\d*', '', text, flags=re.IGNORECASE)
text = re.sub(r'Β£\d+\.?\d*', '', text)
# Remove "needed"
text = re.sub(r'\s*needed\s*', ' ', text, flags=re.IGNORECASE)
# Remove measurements at the beginning
# Pattern: number + space + measurement word
text = re.sub(r'^\d+\.?\d*\s+(tbsp|tsp|tablespoons?|teaspoons?|cups?|ml|g|kg|oz|lbs?|cloves?|stalks?|pieces?|sprigs?)\s+', '', text, flags=re.IGNORECASE)
# Remove fractional measurements
text = re.sub(r'^\d+/\d+\s+(tbsp|tsp|tablespoons?|teaspoons?|cups?)\s+', '', text, flags=re.IGNORECASE)
# Remove "half a", "quarter", etc.
text = re.sub(r'^(half\s+a?\s*|quarter\s+of?\s*|a\s+)(tbsp|tsp|tablespoon|teaspoon|cup|pinch|dash)\s+', '', text, flags=re.IGNORECASE)
# Remove "small amount of"
text = re.sub(r'^small\s+amount\s+of\s+(a\s+)?(tbsp|tsp|tablespoon|teaspoon)?\s*', '', text, flags=re.IGNORECASE)
# Remove leading numbers with items
text = re.sub(r'^\d+\.?\d*\s+(cloves?|bulbs?|pieces?|stalks?|sprigs?)\s+(of\s+)?', '', text, flags=re.IGNORECASE)
# Remove parenthetical store info
text = re.sub(r'\([^)]*store[^)]*\)', '', text, flags=re.IGNORECASE)
text = re.sub(r'\([^)]*supermarket[^)]*\)', '', text, flags=re.IGNORECASE)
# Clean up whitespace
text = ' '.join(text.split())
text = text.strip()
# Capitalize first letter
if text and len(text) > 0:
text = text[0].upper() + text[1:]
return text.strip() if text.strip() else "Ingredient"
def _convert_eggs(self, text):
"""Convert eggs to realistic quantities (6-pack, 12-pack)"""
import re
# Extract number
match = re.search(r'(\d+)', text)
if match:
qty = int(match.group(1))
if qty <= 6:
return "6 free-range eggs (medium)"
elif qty <= 12:
return "12 free-range eggs (medium)"
else:
return "2 boxes of 12 eggs (24 eggs total)"
return "6 free-range eggs (medium)"
def _convert_items(self, text, item_name, pack_size):
"""Convert to whole items or packs"""
import re
match = re.search(r'([\d/.]+)', text)
if match:
qty_str = match.group(1)
# Handle fractions
if '/' in qty_str:
return f"{pack_size} {item_name}"
qty = float(qty_str)
if qty < 1:
return f"1 {item_name[:-1]}" # Singular
elif qty <= pack_size:
return f"{pack_size} {item_name}"
else:
packs = (int(qty) + pack_size - 1) // pack_size
return f"{packs} packs of {item_name}"
return f"1 {item_name[:-1]}"
def _convert_by_weight(self, text, item_name, pack_weight_g):
"""Convert to realistic weight packs"""
import re
# Look for weight in grams or kg
match = re.search(r'(\d+)\s*(g|kg)', text.lower())
if match:
qty = int(match.group(1))
unit = match.group(2)
if unit == 'kg':
qty *= 1000
# Round up to pack size
if qty <= pack_weight_g:
if pack_weight_g >= 1000:
return f"{pack_weight_g//1000}kg {item_name}"
return f"{pack_weight_g}g {item_name}"
else:
packs = (qty + pack_weight_g - 1) // pack_weight_g
if pack_weight_g >= 1000:
return f"{packs}x {pack_weight_g//1000}kg {item_name}"
return f"{packs}x {pack_weight_g}g packs of {item_name}"
# Default pack
if pack_weight_g >= 1000:
return f"{pack_weight_g//1000}kg {item_name}"
return f"{pack_weight_g}g {item_name}"
def _convert_meat(self, text, item_name, pack_weight_g):
"""Convert meat to realistic pack sizes"""
return self._convert_by_weight(text, item_name, pack_weight_g)
def _convert_liquid(self, text, item_name, container_size, unit, container_desc):
"""Convert liquids to realistic container sizes"""
import re
match = re.search(r'(\d+)\s*ml', text.lower())
if match:
qty = int(match.group(1))
if qty <= container_size:
return container_desc + " " + item_name
else:
containers = (qty + container_size - 1) // container_size
return f"{containers}x {container_desc} {item_name}"
return container_desc + " " + item_name
def _convert_butter(self, text):
"""Convert butter to realistic pack (250g block)"""
return "250g block of butter"
def _clean_fractions(self, text):
"""Replace fractions like 1/4 with realistic descriptions"""
replacements = {
'1/4': 'small amount of',
'1/2': 'half a',
'1/3': 'small amount of',
'2/3': 'portion of',
'3/4': 'most of a',
}
for fraction, replacement in replacements.items():
if fraction in text:
# Keep the item name
item = text.split(fraction)[-1].strip()
return f"{replacement} {item}"
return text
def _ai_extract_ingredients(self, recipe_content):
"""Fallback AI-based ingredient extraction"""
try:
model = genai.GenerativeModel('gemini-2.5-flash', generation_config={
"max_output_tokens": 1000,
"temperature": 0.3,
})
prompt = "Extract ALL ingredients from this recipe as a simple list.\n\nRecipe: {0}\n\nReturn ONLY ingredients, one per line, format: '- [ingredient name with quantity]'\nInclude everything needed to make the dish.".format(recipe_content[:2000])
response = model.generate_content(prompt)
ingredients_text = response.text.strip()
ingredients = []
for line in ingredients_text.split('\n'):
line = line.strip()
if line.startswith('- ') or line.startswith('* '):
ingredient = line[2:].strip()
if ingredient and len(ingredient) > 2:
ingredients.append(ingredient)
return ingredients
except Exception as e:
print("Error in AI extraction: {0}".format(e))
return []
def categorize_ingredient(self, ingredient):
ingredient_lower = ingredient.lower()
if any(word in ingredient_lower for word in ['chicken', 'beef', 'pork', 'fish', 'meat']):
return "Meat & Fish"
if any(word in ingredient_lower for word in ['milk', 'cheese', 'butter', 'egg']):
return "Dairy & Eggs"
if any(word in ingredient_lower for word in ['onion', 'garlic', 'carrot', 'potato', 'tomato']):
return "Vegetables"
if any(word in ingredient_lower for word in ['flour', 'sugar', 'rice', 'pasta', 'bread']):
return "Pantry & Dry Goods"
return "Other"
# Recipe Generator
class WeeklyBudgetRecipeGenerator:
def __init__(self):
try:
print("Initializing Gemini model...")
self.model = genai.GenerativeModel('gemini-2.5-flash', generation_config=generation_config)
print("Model initialized successfully!")
except Exception as e:
print("Error in initialization: {0}".format(e))
self.model = None
self.saved_recipes = []
self.current_recipe = None
self.recent_titles = []
self.recipe_history = []
# UK-FOCUSED cuisine list - British first, then popular UK favourites
self.cuisine_rotation = [
"British", "Indian", "Italian", "Chinese", "Mediterranean",
"Thai", "Mexican", "Greek", "French", "Spanish",
"Middle Eastern", "Japanese", "Caribbean", "Korean", "Vietnamese"
]
self.current_cuisine_index = 0
self.ingredient_overlap_enabled = True
self.common_ingredients = []
def extract_core_ingredients(self, recipe_content):
if not self.ingredient_overlap_enabled:
return []
try:
model = genai.GenerativeModel('gemini-2.5-flash', generation_config={
"max_output_tokens": 200,
"temperature": 0.3,
})
prompt = "Extract main reusable ingredients from this recipe. List only proteins, vegetables, pantry staples.\n\nRecipe: {0}\n\nFormat: ingredient name only (no quantities), one per line, max 8 items.".format(recipe_content[:600])
response = model.generate_content(prompt)
ingredients_text = response.text.strip()
ingredients = []
for line in ingredients_text.split('\n')[:8]:
line = line.strip()
if line.startswith('- '):
ingredient = line[2:].strip().lower()
if ingredient and len(ingredient) > 2:
ingredients.append(ingredient)
elif line and not line.startswith('#') and len(line) > 2:
ingredients.append(line.lower())
return ingredients
except Exception as e:
print("Error extracting core ingredients: {0}".format(e))
return []
def update_ingredient_overlap(self, recipe_content):
if not self.ingredient_overlap_enabled:
return
core_ingredients = self.extract_core_ingredients(recipe_content)
self.common_ingredients.extend(core_ingredients)
if len(self.common_ingredients) > 20:
self.common_ingredients = self.common_ingredients[-20:]
def get_budget_optimization_prompt(self, budget_preference, cost_per_meal, currency):
if budget_preference == "Spend Under Budget":
target_cost = round(cost_per_meal * 0.7, 2)
return "\n- Target: {0}{1} (30% under budget)\n- Use budget staples: pasta, rice, eggs, beans".format(currency, target_cost)
else:
return "\n- Target: {0}{1}\n- Include varied ingredients".format(currency, cost_per_meal)
def get_variation_context(self, meal_type, keep_titles=None):
recent_for_type = [title for title in self.recipe_history[-20:] if meal_type.lower() in title.lower()]
# FIX #1: BALANCED CUISINE SELECTION - More variety!
cuisine_weights = {
"British": 20, # Reduced from 45% - still important but not overwhelming
"Italian": 18, # Popular and easy
"Chinese": 15, # Very popular in UK
"Indian": 12, # UK favorite
"Mediterranean": 10, # Healthy and accessible
"Mexican": 10, # Easy and popular
"Thai": 8, # Getting more popular
"Greek": 7, # Good variety
}
# Create weighted list
weighted_cuisines = []
for cuisine, weight in cuisine_weights.items():
weighted_cuisines.extend([cuisine] * int(weight))
# Pick multiple cuisines for variety (not just one!)
current_cuisine = random.choice(weighted_cuisines)
exclusions = []
if keep_titles:
exclusions.extend(keep_titles)
exclusions.extend(recent_for_type)
return current_cuisine, exclusions
def get_mixed_cuisines_for_variety(self, num_recipes):
"""Get a mix of different cuisines for variety across recipes"""
cuisine_weights = {
"British": 20, # Balanced
"Italian": 18,
"Chinese": 15,
"Indian": 12,
"Mediterranean": 10,
"Mexican": 10,
"Thai": 8,
"Greek": 7,
}
weighted_cuisines = []
for cuisine, weight in cuisine_weights.items():
weighted_cuisines.extend([cuisine] * int(weight))
# Pick num_recipes different cuisines (with repeats if needed)
# But try to avoid consecutive duplicates
cuisines = []
last_cuisine = None
for _ in range(num_recipes):
attempts = 0
while attempts < 10:
cuisine = random.choice(weighted_cuisines)
# Try to avoid same cuisine twice in a row
if cuisine != last_cuisine or attempts > 5:
cuisines.append(cuisine)
last_cuisine = cuisine
break
attempts += 1
return cuisines
def titles_too_similar(self, title1, title2):
"""Check if two titles are too similar"""
# Exact match (case-insensitive)
if title1.lower() == title2.lower():
return True
# Check word overlap
words1 = set(title1.lower().split())
words2 = set(title2.lower().split())
# If they share more than 60% of words, they're too similar
if len(words1) > 0 and len(words2) > 0:
overlap = len(words1.intersection(words2))
min_length = min(len(words1), len(words2))
if overlap / min_length > 0.6:
return True
return False
def generate_titles(self, cost_per_meal, postcode, preferences=None, meals_per_week=7, people_count=4, meal_type="Dinner", keep_titles=None, budget_preference="Spend Full Budget"):
"""Generate recipe titles with ingredient reuse"""
try:
# Convert cost_per_meal from string to float if needed
cost_per_meal = float(cost_per_meal) if isinstance(cost_per_meal, str) else cost_per_meal
location, currency = get_location_from_postcode(postcode)
current_cuisine, exclusions = self.get_variation_context(meal_type, keep_titles)
if keep_titles:
num_to_generate = meals_per_week - len(keep_titles)
if num_to_generate <= 0:
self.recent_titles = keep_titles[:meals_per_week]
return self.recent_titles
else:
num_to_generate = meals_per_week
keep_titles = []
# Find cheapest supermarket for this postcode
supermarket_code, supermarket_data = find_cheapest_supermarket(postcode)
supermarket_name = supermarket_data["name"]
prices = supermarket_data["prices"]
# Build ingredient list with actual supermarket prices
if preferences and ("vegetarian" in preferences.lower() or "vegan" in preferences.lower()):
ingredient_list = ("INGREDIENTS TO REUSE ACROSS ALL RECIPES ({0}, Jan 2026 prices):\n"
"Use these SAME plant-based ingredients in ALL {1} different recipes:\n"
"- ONE protein: Chickpeas {2}{3}/{4} OR Kidney beans {2}{5}/{6} (buy once, cook {1} ways)\n"
"- Onions {2}{7}/{8} (use in ALL recipes)\n"
"- Garlic {2}{9}/{10} (use in ALL recipes)\n"
"- Tinned chopped tomatoes {2}{11}/{12} (buy multiple tins)\n"
"- Basmati rice {2}{13}/{14} OR Pasta {2}{15}/{16} (as base)\n"
"- Common UK veg: Carrots, peppers, mushrooms (seasonal)\n"
"NO MEAT, FISH, OR POULTRY ALLOWED!\n\n").format(
supermarket_name,
num_to_generate,
currency,
prices["chickpeas_tin"]["price"], prices["chickpeas_tin"]["unit"],
prices["kidney_beans_tin"]["price"], prices["kidney_beans_tin"]["unit"],
prices["onions"]["price"], prices["onions"]["unit"],
prices["garlic"]["price"], prices["garlic"]["unit"],
prices["tomatoes_tinned"]["price"], prices["tomatoes_tinned"]["unit"],
prices["basmati_rice"]["price"], prices["basmati_rice"]["unit"],
prices["pasta"]["price"], prices["pasta"]["unit"]
)
else:
ingredient_list = ("INGREDIENTS TO REUSE ACROSS ALL RECIPES ({0}, Jan 2026 prices):\n"
"Use these SAME ingredients in ALL {1} different recipes:\n"
"- ONE protein: Chicken breast {2}{3}/{4} OR Beef mince {2}{5}/{6} (buy once, cook {1} ways)\n"
"- Onions {2}{7}/{8} (use in ALL recipes)\n"
"- Garlic {2}{9}/{10} (use in ALL recipes)\n"
"- Tinned chopped tomatoes {2}{11}/{12} (buy multiple tins)\n"
"- Basmati rice {2}{13}/{14} OR Pasta {2}{15}/{16} (as base)\n"
"- Common UK veg: Carrots, peppers, mushrooms (seasonal)\n\n").format(
supermarket_name,
num_to_generate,
currency,
prices["chicken_breast"]["price"], prices["chicken_breast"]["unit"],
prices["beef_mince"]["price"], prices["beef_mince"]["unit"],
prices["onions"]["price"], prices["onions"]["unit"],
prices["garlic"]["price"], prices["garlic"]["unit"],
prices["tomatoes_tinned"]["price"], prices["tomatoes_tinned"]["unit"],
prices["basmati_rice"]["price"], prices["basmati_rice"]["unit"],
prices["pasta"]["price"], prices["pasta"]["unit"]
)
# ADD EXCLUSIONS to prompt for more variety (but not too many!)
exclusions_text = ""
if exclusions:
exclusions_text = "\n\nDO NOT GENERATE THESE (already used recently):\n"
for exc in exclusions[-5:]: # Show only last 5 to avoid overwhelming
exclusions_text += "- {0}\n".format(exc)
exclusions_text += "\nMake sure ALL {0} recipes are COMPLETELY DIFFERENT from the above!\n".format(num_to_generate)
prompt = "β οΈ TASK: Generate {0} complete RECIPE/DISH NAMES (like 'Shepherd's Pie', 'Chicken Curry')\n".format(num_to_generate)
prompt += "β οΈ DO NOT list ingredients! Generate meal names!\n\n"
prompt += "Generate {0} {1} DISH NAMES that share ingredients to minimize weekly shopping cost.\n\n".format(num_to_generate, meal_type.lower())
prompt += "Weekly Budget: {0} {1}/meal x {2} meals for {3} people\n".format(currency, cost_per_meal, meals_per_week, people_count)
# GET MIXED CUISINES for variety
mixed_cuisines = self.get_mixed_cuisines_for_variety(num_to_generate)
cuisine_variety_text = ", ".join(mixed_cuisines)
# FIX #2: REPLACE BORING NAME REQUIREMENTS WITH HELLOFRESH STYLE
prompt += "\nπ― TARGET AUDIENCE: Home cooks wanting delicious, budget-friendly meals\n"
prompt += "BALANCE: Sound AMAZING but use COMMON supermarket ingredients!\n"
prompt += "- NO complex techniques (sous vide, clarifying) but name them appealingly\n"
prompt += "- Avoid exotic ingredients BUT describe flavors enticingly\n"
prompt += "- Think HelloFresh/Gousto: Make it sound restaurant-quality but doable at home\n\n"
# ADD CUISINE VARIETY - MULTIPLE CUISINES
prompt += "π CUISINE VARIETY (mix these up!):\n"
prompt += "Generate a MIX of different cuisines from this list (not all one type!):\n"
for i, cuisine in enumerate(mixed_cuisines, 1):
prompt += f"Recipe {i}: {cuisine}-style\n"
prompt += "\nMake each recipe DIFFERENT CUISINE for maximum variety!\n"
prompt += "Example good mix: British pie, Italian pasta, Chinese stir-fry, Curry, Mexican chili\n"
prompt += "Example BAD mix: All Indian curries (too similar!)\n\n"
# CRITICAL: Enforce dietary preferences
if preferences:
prompt += "\nβ οΈ CRITICAL DIETARY REQUIREMENT: {0}\n".format(preferences.upper())
if "vegetarian" in preferences.lower() or "vegan" in preferences.lower():
prompt += "ABSOLUTELY NO MEAT, FISH, OR POULTRY in recipe names or ingredients!\n"
prompt += "Use plant-based proteins only (beans, lentils, chickpeas, tofu, etc.)\n"
if "gluten" in preferences.lower():
prompt += "MUST be gluten-free - no wheat, pasta, bread, flour!\n"
prompt += "This is NON-NEGOTIABLE. Every recipe MUST follow this requirement!\n\n"
else:
prompt += "\n"
prompt += ingredient_list
prompt += exclusions_text # ADD EXCLUSIONS
# EMPHASIZE VARIETY MORE - but keep it ACHIEVABLE
prompt += "\n\nCRITICAL VARIETY REQUIREMENTS:\n"
prompt += "- Mix of cuisines (British, Italian, Chinese, etc. - NOT all from one region!)\n"
prompt += "- Different cooking methods (bake, stir-fry, simmer, roast)\n"
prompt += "- Each recipe must have UNIQUE flavors\n"
prompt += "- NO similar names (e.g. don't do 'Chicken Curry' AND 'Spicy Chicken Curry')\n"
prompt += "- Keep methods ACHIEVABLE - no complex techniques\n\n"
prompt += "Same ingredients, COMPLETELY DIFFERENT dishes = MAXIMUM SAVINGS!\n"
prompt += self.get_budget_optimization_prompt(budget_preference, cost_per_meal, currency)
# UK-SPECIFIC RECIPE REQUIREMENTS - APPEALING BUT ACHIEVABLE
prompt += "\n\nπ¬π§ UK RECIPE REQUIREMENTS (APPEALING & ACHIEVABLE):\n"
prompt += "- Use ingredients available in UK supermarkets (Tesco, Aldi, Lidl, Asda)\n"
prompt += "- Focus on TASTY, recognizable dishes with SUPERMARKET ingredients\n"
prompt += "- British favorites: Shepherd's pie, fish pie, sausage casserole, roast dinner\n"
prompt += "- Popular international: Pasta bake, stir-fry, curry, chili, tacos\n"
prompt += "- AVOID: Exotic ingredients that aren't in normal supermarkets\n"
prompt += "- AVOID: Complex techniques requiring special equipment\n"
prompt += "- Make it sound DELICIOUS but achievable with everyday ingredients\n\n"
# FIX #3: HELLOFRESH-STYLE NAMING GUIDANCE
prompt += "π½οΈ RECIPE NAMING STYLE (HelloFresh/Gousto Approach):\n"
prompt += "Make names sound DELICIOUS and ENTICING while keeping recipes achievable!\n\n"
prompt += "β
GREAT NAMES (Copy this style!):\n"
prompt += "- 'Sizzling Garlic Butter Chicken with Roasted Veg'\n"
prompt += "- 'Golden Honey Glazed Salmon & Crispy Potatoes'\n"
prompt += "- 'Loaded BBQ Beef Nachos with Melted Cheese'\n"
prompt += "- 'Creamy Tuscan Chicken Pasta'\n"
prompt += "- 'Crispy Parmesan Crusted Cod with Lemon'\n"
prompt += "- 'Sticky Honey Soy Chicken Stir-Fry'\n"
prompt += "- 'Smoky Paprika Pork with Spanish Rice'\n"
prompt += "- 'Zesty Lemon Herb Chicken & Garlic Greens'\n"
prompt += "- 'Rustic Shepherd's Pie with Rich Gravy'\n"
prompt += "- 'Aromatic Coconut Chicken Curry'\n\n"
prompt += "β BORING NAMES TO AVOID:\n"
prompt += "- 'Easy Chicken Dinner' β\n"
prompt += "- 'Simple Pasta Bake' β\n"
prompt += "- 'Basic Curry' β\n"
prompt += "- 'Quick Stir Fry' β\n\n"
prompt += "NAMING RULES:\n"
prompt += "1. Use APPEALING adjectives: Sizzling, Golden, Crispy, Loaded, Creamy, Sticky, Smoky, Zesty, Tender, Rustic, Aromatic\n"
prompt += "2. Mention cooking method: Glazed, Roasted, Crusted, Melted, Pan-Fried, Stir-Fried\n"
prompt += "3. Add flavor hints: Garlic Butter, Honey Soy, Lemon Herb, BBQ, Tuscan, Paprika, Coconut\n"
prompt += "4. Make it sound like something you'd ORDER at a nice restaurant but can make at home!\n"
prompt += "5. Avoid 'Easy', 'Simple', 'Basic', 'Quick' - instead use flavor descriptors\n\n"
prompt += "Format: DISH NAME | Short enticing description (5-8 words)\n\n"
prompt += "Now generate {0} APPETIZING DISH names (think HelloFresh catalog):".format(num_to_generate)
response = self.model.generate_content(prompt)
titles_text = response.text.strip()
# Debug: Print what AI returned
print("AI returned:")
print(titles_text)
print("---")
raw_titles = titles_text.split('\n')
clean_titles = []
seen_titles_lower = set() # Track lowercase versions to catch duplicates
for title in raw_titles:
clean_title = title.strip()
# Skip empty lines
if not clean_title:
continue
# Extract title and description if in format "Name | Description"
if '|' in clean_title:
parts = clean_title.split('|', 1)
clean_title = parts[0].strip()
description = parts[1].strip() if len(parts) > 1 else ""
else:
description = ""
# Skip AI preamble/explanation lines (too long or contain keywords)
skip_keywords = ['here are', 'recipe titles', 'recipes', 'sharing', 'aiming for',
'budget', 'using', 'as follows', 'below', 'protein:', 'ingredients:',
'format:', 'examples:', 'total', 'cost']
if any(keyword in clean_title.lower() for keyword in skip_keywords):
continue
# Skip if it looks like an ingredient rather than a dish name
ingredient_words = ['mince', 'tinned', 'canned', 'chopped', 'diced', 'sliced',
'grams', 'kg', 'ml', 'litre', 'pack', 'bag', 'tin']
# If title is just 1-2 words and contains ingredient words, skip it
if len(clean_title.split()) <= 2 and any(word in clean_title.lower() for word in ingredient_words):
continue
# Skip if title looks like a plain ingredient (e.g., "Beef Mince", "Chicken Breast")
plain_ingredients = ['beef mince', 'chicken breast', 'chicken thigh', 'pork chop',
'lamb chop', 'fish fillet', 'salmon fillet', 'tinned tomatoes',
'chopped tomatoes', 'pasta', 'rice', 'basmati rice', 'onions',
'garlic', 'carrots', 'potatoes']
if clean_title.lower() in plain_ingredients:
continue
# FIX #4: REDUCE BORING TITLE REJECTION - Only reject truly generic
# Only reject if it's ONLY the protein/carb name
boring_titles = [
'chicken', 'beef', 'pork', 'fish', # Just the protein name
'pasta', 'rice', 'noodles', # Just the carb
'dinner', 'lunch', 'meal', # Non-specific
]
# Simple check - only reject if it's ONLY one of these words
title_words = clean_title.lower().split()
if len(title_words) <= 2 and any(word in boring_titles for word in title_words):
print(f"β Rejected too generic: {clean_title}")
continue
# Skip if the title itself is too long (recipe names should be reasonable length)
if len(clean_title) > 60:
continue
# Remove numbering (1., 2., etc.)
if '.' in clean_title[:3]:
clean_title = clean_title.split('.', 1)[1].strip()
# Remove anything in parentheses from the title
if '(' in clean_title:
clean_title = clean_title.split('(')[0].strip()
# Remove common prefixes/bullets
for prefix in ['- ', '* ', 'β’ ', '> ']:
if clean_title.startswith(prefix):
clean_title = clean_title[len(prefix):].strip()
# Remove quotes and extra whitespace
clean_title = clean_title.strip('*"\' ')
# Skip if too short (less than 2 words)
if len(clean_title.split()) < 2:
continue
# Skip if empty or already in keep_titles
if not clean_title or clean_title in keep_titles:
continue
# Check for duplicates (case-insensitive)
clean_title_lower = clean_title.lower()
if clean_title_lower in seen_titles_lower:
continue
# Check if too similar to recent titles
is_too_similar = False
for recent_title in self.recipe_history[-10:]:
if self.titles_too_similar(clean_title, recent_title):
is_too_similar = True
break
# FIX #5: REMOVED MANDATORY DESCRIPTOR CHECK - Let AI be creative!
if not is_too_similar:
clean_titles.append(clean_title)
seen_titles_lower.add(clean_title_lower)
# FIX #6: Updated fallback titles with better names
fallback_titles = {
"Breakfast": [
"Fluffy Scrambled Eggs with Buttery Toast",
"Golden French Toast with Berry Compote",
"Creamy Porridge with Honey Drizzle",
"Loaded Breakfast Burrito",
"Crispy Bacon & Egg Sandwich",
"Hearty Full English Breakfast"
],
"Lunch": [
"Loaded Chicken Caesar Wrap",
"Hearty Minestrone Soup with Crusty Bread",
"Zesty Pasta Salad with Herbs",
"Crispy Quesadilla with Melted Cheese",
"Fresh Greek Salad with Feta",
"Chunky Vegetable Soup"
],
"Dinner": [
"Hearty Beef Stew with Dumplings",
"Creamy Butter Chicken with Fluffy Rice",
"Golden Fish Pie with Cheesy Mash",
"Loaded Tomato Pasta Bake",
"Sizzling Chicken Stir-Fry with Ginger",
"Rustic Shepherd's Pie with Gravy",
"Smoky BBQ Beef Tacos",
"Aromatic Thai Green Curry"
],
}
while len(clean_titles) < num_to_generate:
meal_fallbacks = fallback_titles.get(meal_type, ["Tasty Quick Meal"])
fallback_title = meal_fallbacks[len(clean_titles) % len(meal_fallbacks)]
clean_titles.append(fallback_title)
# Debug: Show final cleaned titles
print("Cleaned titles ({0}):".format(len(clean_titles)))
for t in clean_titles:
print(" - {0}".format(t))
print("---")
all_titles = keep_titles + clean_titles[:num_to_generate]
self.current_cuisine_index += 1
self.recipe_history.extend(all_titles)
if len(self.recipe_history) > 100:
self.recipe_history = self.recipe_history[-50:]
self.recent_titles = all_titles[:meals_per_week]
return self.recent_titles
except Exception as e:
print("Error generating titles: {0}".format(e))
default_titles = ["{0} Option {1}".format(meal_type, i+1) for i in range(meals_per_week)]
self.recent_titles = default_titles
return default_titles
def generate_full_recipe(self, title_index, cost_per_meal, postcode, preferences=None, meals_per_week=7, people_count=4, meal_type="Dinner", budget_preference="Spend Full Budget"):
"""Generate full recipe"""
if not self.recent_titles or title_index >= len(self.recent_titles):
return "Please generate titles first"
# Convert cost_per_meal from string to float if needed
cost_per_meal = float(cost_per_meal) if isinstance(cost_per_meal, str) else cost_per_meal
title = self.recent_titles[title_index]
location, currency = get_location_from_postcode(postcode)
if budget_preference == "Spend Under Budget":
target_cost = round(cost_per_meal * 0.7, 2)
else:
target_cost = cost_per_meal
weekly_total = round(cost_per_meal * meals_per_week * people_count, 2)
try:
# Find cheapest supermarket for this postcode
supermarket_code, supermarket_data = find_cheapest_supermarket(postcode)
supermarket_name = supermarket_data["name"]
# Build pricing reference with ACCURATE prices from cheapest local supermarket
pricing_ref, _ = get_supermarket_pricing_ref(postcode, currency)
# Build ingredient example with supermarket-specific prices
prices = supermarket_data["prices"]
ingredient_example = ("Example format ({0} prices, Jan 2026):\n"
"- 2 onions needed - {1}{2} (you buy: 1kg bag from {0}, contains 6-8 onions, reuse rest)\n"
"- 500g chicken breast needed - {1}{3} (you buy: 500g pack)\n"
"- 3 cloves garlic needed - {1}{4} (you buy: 1 bulb, contains 10-12 cloves, reuse rest)\n"
"- 1 tin tomatoes needed - {1}{5} (you buy: 400g tin)\n"
"- Coleslaw for side - {1}{6} (pre-made tub - CHEAPER than making from scratch!)").format(
supermarket_name,
currency,
prices["onions"]["price"],
prices["chicken_breast"]["price"],
prices["garlic"]["price"],
prices["tomatoes_tinned"]["price"],
prices.get("coleslaw", {}).get("price", 0.79)
)
prompt = "Create a budget-friendly {0} recipe: {1}\n\n".format(meal_type.lower(), title)
prompt += "For: {0} people in {1}\n".format(people_count, location)
prompt += "Budget: {0} {1} per meal (target: {0} {2})\n".format(currency, cost_per_meal, target_cost)
# UK-SPECIFIC REQUIREMENTS - APPEALING BUT ACHIEVABLE
prompt += "\nπ¬π§ UK RECIPE REQUIREMENTS (APPEALING & ACHIEVABLE):\n"
prompt += "- Use ingredients commonly available in UK supermarkets (Tesco, Aldi, Lidl, Asda)\n"
prompt += "- Use METRIC measurements (grams, ml, litres) NOT cups or imperial\n"
prompt += "- Use UK terminology: coriander (not cilantro), aubergine (not eggplant), courgette (not zucchini)\n"
prompt += "- Keep instructions CLEAR and ACHIEVABLE for home cooks\n"
prompt += "- Use familiar ingredients - avoid exotic/specialty items\n"
prompt += "- Make it tasty and appealing while being doable at home\n\n"
prompt += "β οΈ TARGET AUDIENCE: Home cooks wanting delicious meals on a budget\n"
prompt += "- Write instructions clearly for anyone to follow\n"
prompt += "- Use simple language, no overly technical terms\n"
prompt += "- Make it sound delicious and worth making!\n\n"
# PRE-MADE ALTERNATIVES GUIDANCE
prompt += "π‘ SMART BUDGET TIP - USE PRE-MADE WHEN CHEAPER:\n"
prompt += "CRITICAL: Some items are CHEAPER pre-made than from scratch!\n\n"
prompt += "β
USE PRE-MADE for:\n"
prompt += "- Coleslaw ({0}{1} tub) - cheaper than buying cabbage + carrots + mayo separately\n".format(currency, prices.get("coleslaw", {}).get("price", 0.79))
prompt += "- Pasta sauce ({0}{1} jar) - cheaper than tinned tomatoes + herbs + onions\n".format(currency, prices.get("pasta_sauce", {}).get("price", 0.55))
prompt += "- Curry sauce ({0}{1} jar) - much cheaper than buying all spices\n".format(currency, prices.get("curry_sauce", {}).get("price", 0.89))
prompt += "- Puff pastry ({0}{1}) - way easier than homemade\n".format(currency, prices.get("puff_pastry", {}).get("price", 1.19))
prompt += "- Garlic bread ({0}{1}) - cheaper than making from scratch\n".format(currency, prices.get("garlic_bread", {}).get("price", 0.75))
prompt += "- Hummus ({0}{1}) - cheaper than dried chickpeas + tahini\n".format(currency, prices.get("hummus", {}).get("price", 0.99))
prompt += "- Salad bags ({0}{1}) - better value than whole lettuce for 1-2 people\n\n".format(currency, prices.get("salad_bag", {}).get("price", 0.65))
prompt += "β MAKE FROM SCRATCH when genuinely cheaper:\n"
prompt += "- Big batches of rice, pasta (bulk is cheaper)\n"
prompt += "- Roast vegetables (fresh is better value)\n"
prompt += "- Simple sauces if you have the base ingredients\n\n"
prompt += "RULE: Always choose the CHEAPEST option that maintains quality!\n\n"
if preferences:
prompt += "Preferences: {0}\n\n".format(preferences)
else:
prompt += "\n"
prompt += pricing_ref
prompt += "\n\nβ οΈ CRITICAL PRICING ACCURACY:\n"
prompt += "- Use EXACT prices from {0} (cheapest near postcode)\n".format(supermarket_name)
prompt += "- DO NOT guess or estimate prices\n"
prompt += "- Chicken breast is {0}{1}/{2} at {3}\n".format(
currency,
prices["chicken_breast"]["price"],
prices["chicken_breast"]["unit"],
supermarket_name
)
prompt += "- All prices researched from {0} (January 2026)\n".format(supermarket_name)
prompt += "- Always show 'what you buy' price at {0}, not theoretical per-portion\n\n".format(supermarket_name)
prompt += "CRITICAL: Show ACTUAL {0} PURCHASE COSTS (what you buy at checkout), then calculate total.\n\n".format(supermarket_name.upper())
prompt += "Format:\n"
prompt += "# {0}\n\n".format(title)
prompt += "## Description\n[2-3 sentences about the dish and budget benefits]\n\n"
prompt += "## Budget Details\n"
prompt += "- Supermarket: {0} (cheapest near your postcode)\n".format(supermarket_name)
prompt += "- Cost Per Meal Target: {0} {1}\n".format(currency, cost_per_meal)
prompt += "- This Recipe Cost: {0} {1}\n".format(currency, target_cost)
prompt += "- Cost Per Person: {0} {1}\n".format(currency, round(target_cost/people_count,2))
prompt += "- Servings: {0}\n".format(people_count)
prompt += "- Weekly Total (x{0}): {1} {2}\n\n".format(meals_per_week, currency, round(target_cost*meals_per_week,2))
prompt += "## Time & Difficulty\n"
prompt += "- Prep: [X] min | Cook: [X] min | Total: [X] min\n"
prompt += "- Difficulty: Easy to Medium\n\n"
prompt += "## Nutritional Information (per serving)\n"
prompt += "- Calories: [X] kcal\n"
prompt += "- Protein: [X]g\n"
prompt += "- Carbs: [X]g\n"
prompt += "- Fat: [X]g\n"
prompt += "- Fiber: [X]g\n\n"
prompt += "## Ingredients (with ACTUAL {0} PURCHASE PRICES)\n".format(supermarket_name.upper())
prompt += "IMPORTANT: List the FULL PRICE you pay at the store, NOT the cost per portion!\n\n"
prompt += ingredient_example
prompt += "\n\nList each ingredient showing:\n"
prompt += "1. What you need for THIS recipe\n"
prompt += "2. What you ACTUALLY BUY at the store\n"
prompt += "3. The FULL PURCHASE PRICE\n"
prompt += "4. Note if there are leftover ingredients for other meals\n\n"
prompt += "**Total Shopping Cost: [Add up ALL the purchase prices above]**\n"
prompt += "**Actual Cost Per Meal: [Total / number of meals these ingredients make]**\n\n"
prompt += "## Instructions\n"
prompt += "Write CLEAR, achievable steps:\n"
prompt += "- Use everyday language\n"
prompt += "- Break into manageable steps\n"
prompt += "- Be specific about temperatures, timings, and what to look for\n"
prompt += "- Include helpful tips in each step\n\n"
prompt += "## Meal Planning Tips\n[3 practical tips - include how to use leftover ingredients]\n\n"
prompt += "## Storage\n[Simple storage and reheating instructions]\n\n"
prompt += "Keep it practical, achievable, and APPEALING!"
response = self.model.generate_content(prompt)
recipe_content = response.text
self.update_ingredient_overlap(recipe_content)
self.current_recipe = {
"title": title,
"content": recipe_content,
"cost_per_meal": cost_per_meal,
"location": location,
"postcode": postcode,
"preferences": preferences,
"people_count": people_count,
"meals_per_week": meals_per_week,
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
return recipe_content
except Exception as e:
error_msg = str(e)
print("Error generating recipe: {0}".format(error_msg))
return "Error generating recipe: {0}".format(error_msg)
def save_current_recipe(self):
if self.current_recipe:
# Check for duplicates
for recipe in self.saved_recipes:
if recipe["title"] == self.current_recipe["title"]:
return "Recipe already saved"
# Add new recipe
self.saved_recipes.append(self.current_recipe)
return "Recipe '{0}' saved successfully!".format(self.current_recipe['title'])
else:
return "No recipe to save"
def get_saved_recipes(self):
if not self.saved_recipes:
return pd.DataFrame(columns=["ID", "Title", "Cost Per Meal", "Location", "Date Saved"])
recipes_data = []
for i, recipe in enumerate(self.saved_recipes):
recipes_data.append({
"ID": i + 1,
"Title": recipe["title"],
"Cost Per Meal": "{0} {1}".format(recipe.get('currency', 'GBP'), recipe['cost_per_meal']),
"Location": recipe["location"],
"Date Saved": recipe["date"]
})
return pd.DataFrame(recipes_data)
def generate_weekly_shopping_list(self, cost_per_meal, postcode, preferences, meals_per_week, people_count, meal_type, budget_preference):
"""Generate a consolidated shopping list for the entire week"""
try:
print("Generating weekly shopping list...")
# Convert cost_per_meal from string to float if needed
cost_per_meal = float(cost_per_meal) if isinstance(cost_per_meal, str) else cost_per_meal
location, currency = get_location_from_postcode(postcode)
# First, generate all recipe titles if not already done
if not self.recent_titles or len(self.recent_titles) < meals_per_week:
self.generate_titles(cost_per_meal, postcode, preferences, meals_per_week, people_count, meal_type, None, budget_preference)
all_ingredients = {}
# Generate each recipe and extract ingredients
for i, title in enumerate(self.recent_titles[:meals_per_week]):
print("Extracting ingredients from: {0}".format(title))
# Generate the full recipe
recipe_content = self.generate_full_recipe(i, cost_per_meal, postcode, preferences, meals_per_week, people_count, meal_type, budget_preference)
# Extract ingredients from recipe
core_ingredients = self.extract_core_ingredients(recipe_content)
# Track which recipes use each ingredient
for ingredient in core_ingredients:
ingredient_clean = ingredient.lower().strip()
if ingredient_clean not in all_ingredients:
all_ingredients[ingredient_clean] = {
'name': ingredient,
'used_in': [],
'count': 0
}
all_ingredients[ingredient_clean]['used_in'].append(title)
all_ingredients[ingredient_clean]['count'] += 1
# Build the shopping list with realistic store purchases
shopping_list_text = "# π Weekly Shopping List\n\n"
shopping_list_text += "**Budget:** {0} {1}/meal Γ {2} meals = {0} {3}\n\n".format(
currency,
cost_per_meal,
meals_per_week,
round(cost_per_meal * meals_per_week, 2)
)
shopping_list_text += "---\n\n"
# Sort ingredients by usage count
sorted_ingredients = sorted(all_ingredients.items(), key=lambda x: x[1]['count'], reverse=True)
total_cost = 0
# Group by category
proteins = []
vegetables = []
pantry = []
dairy = []
other = []
for ingredient_key, ingredient_data in sorted_ingredients:
ingredient_name = ingredient_data['name']
used_count = ingredient_data['count']
# Get store purchase info
price_info = get_ingredient_price_info(ingredient_name)
# Calculate quantity
quantity_to_buy = 1
if used_count >= 4:
quantity_to_buy = 2
if used_count >= 7:
quantity_to_buy = 3
item_cost = price_info['price'] * quantity_to_buy
total_cost += item_cost
# Format item line
if quantity_to_buy > 1:
item_line = "- {0} Γ {1} ({2}) β {3} {4:.2f}".format(
ingredient_name.title(),
quantity_to_buy,
price_info['unit'],
currency,
item_cost
)
else:
item_line = "- {0} ({1}) β {2} {3:.2f}".format(
ingredient_name.title(),
price_info['unit'],
currency,
price_info['price']
)
# Categorize
if any(word in ingredient_name.lower() for word in ['chicken', 'beef', 'pork', 'fish', 'mince', 'meat']):
proteins.append(item_line)
elif any(word in ingredient_name.lower() for word in ['onion', 'garlic', 'carrot', 'tomato', 'pepper', 'vegetable']):
vegetables.append(item_line)
elif any(word in ingredient_name.lower() for word in ['pasta', 'rice', 'flour', 'oil', 'spice', 'tin']):
pantry.append(item_line)
elif any(word in ingredient_name.lower() for word in ['milk', 'cheese', 'butter', 'egg', 'cream', 'yogurt']):
dairy.append(item_line)
else:
other.append(item_line)
# Output by category
if proteins:
shopping_list_text += "**Meat & Fish**\n"
for item in proteins:
shopping_list_text += item + "\n"
shopping_list_text += "\n"
if vegetables:
shopping_list_text += "**Vegetables**\n"
for item in vegetables:
shopping_list_text += item + "\n"
shopping_list_text += "\n"
if pantry:
shopping_list_text += "**Pantry Items**\n"
for item in pantry:
shopping_list_text += item + "\n"
shopping_list_text += "\n"
if dairy:
shopping_list_text += "**Dairy**\n"
for item in dairy:
shopping_list_text += item + "\n"
shopping_list_text += "\n"
if other:
shopping_list_text += "**Other**\n"
for item in other:
shopping_list_text += item + "\n"
shopping_list_text += "\n"
shopping_list_text += "---\n\n"
shopping_list_text += "**Total:** {0} {1:.2f}\n\n".format(currency, total_cost)
shopping_list_text += "**Meals:** {0}\n".format(", ".join(self.recent_titles[:meals_per_week]))
return shopping_list_text
except Exception as e:
print("Error generating weekly shopping list: {0}".format(e))
return "Error generating weekly shopping list: {0}".format(str(e))
def load_saved_recipe(self, recipe_index):
if not self.saved_recipes or recipe_index >= len(self.saved_recipes):
return "Recipe not found"
return self.saved_recipes[recipe_index]["content"]
def generate_supermarket_recommendations(self, cost_per_meal, postcode, people_count=4, meals_per_week=7):
"""Generate supermarket recommendations"""
try:
# Convert cost_per_meal from string to float if needed
cost_per_meal = float(cost_per_meal) if isinstance(cost_per_meal, str) else cost_per_meal
location_info, currency = get_location_from_postcode(postcode)
weekly_total = round(cost_per_meal * meals_per_week * people_count, 2)
prompt = "Recommend UK supermarkets for someone in {0} with:\n".format(location_info)
prompt += "- {0} {1}/meal for {2} people\n".format(currency, cost_per_meal, people_count)
prompt += "- {0} meals/week\n".format(meals_per_week)
prompt += "- Weekly total: {0} {1}\n\n".format(currency, weekly_total)
prompt += "Consider: Aldi, Lidl, Tesco, Asda, Morrisons, Sainsburys, Waitrose, M&S, Co-op, Iceland\n\n"
prompt += "Format:\n"
prompt += "# Supermarket Recommendations\n\n"
prompt += "## Budget Analysis\n[Brief analysis of {0} {1}/meal budget level]\n\n".format(currency, cost_per_meal)
prompt += "## Top 3 Recommended Stores\n[Rank with specific reasons for budget and location]\n\n"
prompt += "## Shopping Strategy\n[Specific advice for this budget]\n\n"
prompt += "## Money-Saving Tips\n[3-4 practical tips]\n\n"
prompt += "Keep concise and actionable."
response = self.model.generate_content(prompt)
return response.text
except Exception as e:
return "Error: {0}".format(str(e))
# Initialize instances
recipe_generator = WeeklyBudgetRecipeGenerator()
shopping_list_manager = ShoppingListManager()
def calculate_weekly_total(cost_per_meal, meals_per_week, people_count):
if not cost_per_meal or not meals_per_week or not people_count:
return 0
# Convert cost_per_meal from string (Dropdown) to float
cost = float(cost_per_meal) if isinstance(cost_per_meal, str) else cost_per_meal
return round(cost * int(meals_per_week) * int(people_count), 2)
# Gradio Interface with clean default theme
with gr.Blocks(title="Bitesized AI Meal Planner") as demo:
gr.Markdown("# π½οΈ Bitesized AI Meal Planner")
gr.Markdown("### Smart meal planning with ingredient reuse for maximum savings")
gr.Markdown("---")
# ==================== TABS NAVIGATION ====================
with gr.Tabs() as main_tabs:
with gr.TabItem("π³ Meal Planner", id=0):
# ==================== ONE UNIFIED MEAL PLANNER ====================
gr.Markdown("## π― Start Now - Let's Create Your Perfect Meal Plan!")
# Step 1: Current spending on dinners
gr.Markdown("### Step 1: How much do you spend on dinners?")
current_weekly_spending = gr.Number(
label="π· How much do you spend per week on DINNERS? (Β£)",
value=50,
minimum=0, # No validation while typing - we'll check on submit
maximum=500,
info="Only count ingredients for evening meals (exclude breakfast, lunch, cleaning products, etc.)"
)
# Step 2: Household info
gr.Markdown("### Step 2: Your household")
with gr.Row():
people_count = gr.Slider(
label="π₯ How many people do you cook for?",
minimum=1,
maximum=10,
value=4,
step=1,
info="Number of people you're feeding"
)
meals_per_week = gr.Slider(
label="π½οΈ How many meals do you cook per week?",
minimum=1,
maximum=14,
value=7,
step=1,
info="E.g., 7 = one dinner every night"
)
# Savings display (appears after user enters info)
savings_display = gr.Markdown(visible=False)
# Step 3: Preferences
gr.Markdown("### Step 3: Preferences")
with gr.Row():
postcode = gr.Textbox(
label="π Postcode (optional)",
placeholder="e.g., LE1 7RH",
info="For local supermarket recommendations",
scale=1
)
preferences = gr.Textbox(
label="π₯ Dietary Needs (optional)",
placeholder="e.g., vegetarian, gluten-free",
info="Any dietary requirements",
scale=1
)
# Generate button
gr.Markdown("### Step 4: Generate Your Recipes!")
generate_btn = gr.Button("β¨ Generate My Recipes", variant="primary", size="lg")
# Results - Add all necessary components for recipe display
gr.Markdown("---")
info_output = gr.Markdown()
with gr.Row():
# Left: Recipe list
with gr.Column(scale=1):
title_radio = gr.Radio(label="π Your Recipes", choices=[])
# Refresh options in accordion
with gr.Accordion("π Fancy something different?", open=False):
keep_checkboxes = gr.CheckboxGroup(label="Keep these recipes", choices=[], visible=False)
refresh_unwanted_btn = gr.Button("Refresh Unselected", size="sm", visible=False)
regenerate_btn = gr.Button("π Generate Completely New Set", size="sm", visible=False)
# Right: Recipe details
with gr.Column(scale=2):
recipe_markdown = gr.HTML("")
# Confirm button for adding to shopping list
confirm_all_btn = gr.Button("β
Confirm My Meals & Add All Ingredients to Shopping List",
visible=False,
variant="primary",
size="lg")
# Status message for saves
save_status = gr.Markdown("", visible=True)
# Add hidden components
ingredient_info = gr.Markdown("", visible=False)
# Hidden fields for cost calculation and defaults
cost_per_meal = gr.Textbox(visible=False, value="3.50")
meal_type = gr.Textbox(visible=False, value="Dinner")
budget_preference = gr.Textbox(visible=False, value="Spend Full Budget")
# Add video tutorial at the end of meal planner tab
gr.Markdown("---")
gr.Markdown("πΎ **Your recipes are automatically saved!** Access them in the 'Saved Recipes' tab.")
with gr.Accordion("πΊ Watch How It Works", open=False):
gr.HTML("""
<div style="text-align: center;">
<iframe width="100%" height="400"
src="https://www.youtube.com/embed/HfzXbbbzRF0"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
</div>
""")
with gr.TabItem("π Shopping List", id=1):
gr.Markdown("# π Your Shopping List")
gr.Markdown("_Check items off as you shop! Items update in real-time._")
# Interactive checkbox list
with gr.Column():
gr.Markdown("### π Items to Buy")
shopping_checkboxes = gr.CheckboxGroup(
choices=[],
value=[],
label="Click to check off items as you shop",
interactive=True
)
with gr.Row():
refresh_list_btn = gr.Button("π Refresh", size="sm")
clear_checked_btn = gr.Button("ποΈ Remove Checked", size="sm")
clear_all_btn = gr.Button("β οΈ Clear All", variant="stop", size="sm")
list_status = gr.Markdown("")
# Add item section
with gr.Accordion("β Add Item Manually", open=False):
with gr.Row():
new_item = gr.Textbox(label="Item Name", placeholder="e.g., Milk, Eggs, Bread", scale=2)
new_quantity = gr.Textbox(label="Quantity", placeholder="e.g., 2L, 500g", scale=1)
new_category = gr.Dropdown(
label="Category",
choices=["Meat & Fish", "Dairy & Eggs", "Vegetables", "Pantry & Dry Goods", "Other"],
value="Other",
scale=1
)
add_item_btn = gr.Button("β Add to List", variant="primary")
add_status = gr.Markdown("")
# Hidden dataframe for data storage
shopping_list_table = gr.Dataframe(visible=False)
with gr.TabItem("πΎ Saved Recipes", id=2):
gr.Markdown("# πΎ Your Saved Recipes")
gr.Markdown("_Click on any recipe below to view the full details_")
with gr.Row():
refresh_saved_btn = gr.Button("π Refresh List", size="sm")
saved_count = gr.Markdown("**0 recipes saved**")
# Make it easier - use Radio buttons instead of table + ID entry
saved_recipes_radio = gr.Radio(
label="π Select a Recipe to View",
choices=[],
value=None,
interactive=True
)
loaded_pantry_recipe_markdown = gr.Markdown("_Select a recipe above to see its details_")
with gr.TabItem("π° Your Savings", id=3):
gr.Markdown("# π° Your Savings Tracker")
gr.Markdown("_See how much you're saving with smart meal planning!_")
# Dynamic savings display
savings_tracker_display = gr.HTML("""
<div style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
padding: 20px 15px;
border-radius: 15px;
color: white;
margin: 10px 0;
max-width: 100%;
box-sizing: border-box;">
<h2 style="margin: 0 0 15px 0; text-align: center; font-size: 20px;">π How You're Saving Money</h2>
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin: 15px 0; justify-content: center;">
<div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 10px; text-align: center; flex: 1; min-width: 140px; max-width: 180px;">
<div style="font-size: 12px; opacity: 0.9; margin-bottom: 8px;">Cheaper Supermarket</div>
<div style="font-size: 32px; font-weight: bold;">20%</div>
<div style="font-size: 11px; opacity: 0.8; margin-top: 8px;">Aldi vs Tesco</div>
</div>
<div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 10px; text-align: center; flex: 1; min-width: 140px; max-width: 180px;">
<div style="font-size: 12px; opacity: 0.9; margin-bottom: 8px;">Meal Planning</div>
<div style="font-size: 32px; font-weight: bold;">5%</div>
<div style="font-size: 11px; opacity: 0.8; margin-top: 8px;">Less waste</div>
</div>
<div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 10px; text-align: center; flex: 1; min-width: 140px; max-width: 180px;">
<div style="font-size: 12px; opacity: 0.9; margin-bottom: 8px;">Total Savings</div>
<div style="font-size: 32px; font-weight: bold;">25%</div>
<div style="font-size: 11px; opacity: 0.8; margin-top: 8px;">On average</div>
</div>
</div>
<div style="background: rgba(255,255,255,0.15); padding: 15px; border-radius: 10px; margin: 15px 0;">
<h3 style="margin: 0 0 12px 0; text-align: center; font-size: 16px;">π‘ Your Estimated Savings</h3>
<div style="text-align: center; margin: 10px 0;">
<div style="font-size: 13px; opacity: 0.9;">Generate recipes to see your personalized savings!</div>
<div style="font-size: 14px; font-weight: bold; margin: 8px 0; color: #fff;">Use the Meal Planner tab to get started</div>
</div>
</div>
</div>
""")
gr.Markdown("""
### π― Tips to Maximize Your Savings:
1. **Shop at budget stores** - Aldi & Lidl offer great value
2. **Follow the meal plan** - Reduces impulse buying
3. **Reuse ingredients** - Our recipes share common ingredients
4. **Buy store brands** - Same quality, lower price
5. **Cook in bulk** - Freeze extra portions
6. **Stick to the list** - Avoid unnecessary purchases
### π Real User Savings:
- **Sarah M.** from Manchester: Saved Β£847 in first year! π
- **James K.** from London: Cut grocery bill by 28% π°
- **Emma L.** from Birmingham: Saved enough for family holiday ποΈ
*(Based on using smart meal planning and budget-friendly shopping)*
---
### π¬ What Users Say:
> "I was spending Β£95/week. Now I spend Β£70/week with better meal plans. That's Β£1,300/year saved!" - **Sarah, Manchester**
> "The ingredient reuse is genius. I'm not buying 10 different vegetables that half go to waste anymore." - **James, London**
> "We took our first family holiday abroad with the money we saved!" - **Emma, Birmingham**
""")
with gr.TabItem("πͺ Supermarket Guide"):
gr.Markdown("# Supermarket Recommendations")
gr.Markdown("_Get personalized supermarket suggestions based on your budget and location_")
with gr.Row():
with gr.Column():
supermarket_cost_per_meal = gr.Dropdown(
label="π· Cost Per Meal (Β£)",
choices=["2.50", "3.00", "3.50", "4.00", "4.50", "5.00", "5.50", "6.00", "6.50", "7.00", "7.50", "8.00"],
value="3.50",
info="How much you want to spend per meal"
)
supermarket_people = gr.Slider(
label="π₯ People",
minimum=1,
maximum=10,
value=4,
step=1,
info="How many people you're cooking for"
)
with gr.Column():
supermarket_meals_per_week = gr.Slider(
label="π½οΈ How many meals?",
minimum=1,
maximum=7,
value=7,
step=1,
info="Number of meals to plan per week"
)
supermarket_postcode = gr.Textbox(
label="Postcode",
placeholder="e.g., LE1 7RH",
info="Your UK postcode for local recommendations"
)
supermarket_weekly_total = gr.Markdown("**Weekly Total:** Β£98.00")
get_recommendations_btn = gr.Button("π Get Recommendations", variant="primary", size="lg")
supermarket_recommendations = gr.Markdown("")
# ==================== UNIFIED PLANNER FUNCTIONS & HANDLERS ====================
# Function to calculate and show savings in real-time
def show_savings_preview(current_spending, people, meals):
"""Show savings calculation as user enters info"""
if not current_spending or current_spending < 10:
return gr.update(visible=False)
# Calculate savings (25%)
savings_weekly = current_spending * 0.25
new_budget = current_spending - savings_weekly
savings_monthly = savings_weekly * 4.33
savings_yearly = savings_weekly * 52
# Calculate cost per meal
cost_per_meal_calc = new_budget / meals / people
# Round to nearest valid option
valid_costs = [2.50, 3.00, 3.50, 4.00, 4.50, 5.00, 5.50, 6.00, 6.50, 7.00, 7.50, 8.00]
cost_rounded = min(valid_costs, key=lambda x: abs(x - cost_per_meal_calc))
# Calculate actual weekly with rounded cost
actual_weekly = cost_rounded * meals * people
actual_savings = current_spending - actual_weekly
markdown = f"""
---
### π° Your Bitesized Budget (Dinners):
**Current Dinner Spending:** Β£{current_spending:.2f}/week
**Your New Dinner Budget:** Β£{actual_weekly:.2f}/week ({meals} dinners for {people} {'person' if people == 1 else 'people'})
**Cost Per Dinner:** Β£{cost_rounded:.2f}
**π You'll Save on Dinners:**
- **Weekly:** Β£{actual_savings:.2f}
- **Monthly:** Β£{actual_savings * 4.33:.0f}
- **Yearly:** Β£{actual_savings * 52:.0f}
*Ready to generate your dinner recipes below!*
---
"""
return gr.update(value=markdown, visible=True)
# Function to update savings tracker with actual user spending
def update_savings_tracker(current_spending, people, meals):
"""Update savings display based on user's actual spending"""
if not current_spending or current_spending < 10:
# Default display if no spending entered
return """
<div style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
padding: 20px 15px;
border-radius: 15px;
color: white;
margin: 10px 0;
max-width: 100%;
box-sizing: border-box;">
<h2 style="margin: 0 0 15px 0; text-align: center; font-size: 20px;">π How You're Saving Money</h2>
<div style="background: rgba(255,255,255,0.15); padding: 15px; border-radius: 10px; margin: 15px 0;">
<h3 style="margin: 0 0 12px 0; text-align: center; font-size: 16px;">π‘ Get Started</h3>
<div style="text-align: center; margin: 10px 0;">
<div style="font-size: 14px; opacity: 0.9; line-height: 1.5;">Go to the <strong>Meal Planner</strong> tab and enter your weekly DINNER spending to see your personalized savings!</div>
</div>
</div>
</div>
"""
# Calculate 25% savings
savings_weekly = current_spending * 0.25
new_budget = current_spending - savings_weekly
savings_monthly = savings_weekly * 4.33
savings_yearly = savings_weekly * 52
savings_5_years = savings_yearly * 5
# Calculate cost per meal
cost_per_meal_calc = new_budget / meals / people
return f"""
<div style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
padding: 20px 15px;
border-radius: 15px;
color: white;
margin: 10px 0;
max-width: 100%;
box-sizing: border-box;">
<h2 style="margin: 0 0 15px 0; text-align: center; font-size: 20px;">π Your Actual Savings</h2>
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin: 15px 0; justify-content: center;">
<div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 10px; text-align: center; flex: 1; min-width: 140px; max-width: 180px;">
<div style="font-size: 12px; opacity: 0.9; margin-bottom: 8px;">Cheaper Supermarket</div>
<div style="font-size: 32px; font-weight: bold;">20%</div>
<div style="font-size: 11px; opacity: 0.8; margin-top: 8px;">Aldi vs Tesco</div>
</div>
<div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 10px; text-align: center; flex: 1; min-width: 140px; max-width: 180px;">
<div style="font-size: 12px; opacity: 0.9; margin-bottom: 8px;">Meal Planning</div>
<div style="font-size: 32px; font-weight: bold;">5%</div>
<div style="font-size: 11px; opacity: 0.8; margin-top: 8px;">Less waste</div>
</div>
<div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 10px; text-align: center; flex: 1; min-width: 140px; max-width: 180px;">
<div style="font-size: 12px; opacity: 0.9; margin-bottom: 8px;">Total Savings</div>
<div style="font-size: 32px; font-weight: bold;">25%</div>
<div style="font-size: 11px; opacity: 0.8; margin-top: 8px;">Your savings</div>
</div>
</div>
<div style="background: rgba(255,255,255,0.15); padding: 15px; border-radius: 10px; margin: 15px 0;">
<h3 style="margin: 0 0 12px 0; text-align: center; font-size: 16px;">π° Your Dinner Savings</h3>
<div style="text-align: center; margin: 10px 0;">
<div style="font-size: 13px; opacity: 0.9;">You currently spend on dinners:</div>
<div style="font-size: 22px; font-weight: bold; margin: 5px 0; color: #fff;">Β£{current_spending:.2f}/week</div>
<div style="font-size: 13px; opacity: 0.9; margin: 10px 0;">With Bitesized, you'll save:</div>
<div style="font-size: 40px; font-weight: bold; margin: 8px 0; color: #fff;">Β£{savings_weekly:.2f}</div>
<div style="font-size: 15px; opacity: 0.9;">per week on dinners!</div>
<div style="font-size: 13px; opacity: 0.9; margin: 12px 0;">
That's <strong>Β£{savings_monthly:.0f}/month</strong> or <strong>Β£{savings_yearly:.0f}/year</strong>!
</div>
</div>
</div>
<div style="text-align: center; margin-top: 15px; font-size: 14px;">
<strong>π° Over 5 years: Β£{savings_5_years:.0f} saved on dinners!</strong><br>
<span style="font-size: 12px; opacity: 0.9;">Car deposit, home improvements, or holiday! ππ βοΈ</span>
</div>
<div style="background: rgba(255,255,255,0.1); padding: 12px; border-radius: 10px; margin: 15px 0; text-align: center;">
<div style="font-size: 13px; opacity: 0.9;">New dinner budget: <strong>Β£{new_budget:.2f}/week</strong> for {meals} dinners, {people} {"person" if people == 1 else "people"}</div>
<div style="font-size: 13px; opacity: 0.9; margin-top: 5px;">Just <strong>Β£{cost_per_meal_calc:.2f} per dinner!</strong></div>
</div>
</div>
"""
# Update savings preview when fields change
current_weekly_spending.change(
fn=show_savings_preview,
inputs=[current_weekly_spending, people_count, meals_per_week],
outputs=[savings_display]
)
people_count.change(
fn=show_savings_preview,
inputs=[current_weekly_spending, people_count, meals_per_week],
outputs=[savings_display]
)
meals_per_week.change(
fn=show_savings_preview,
inputs=[current_weekly_spending, people_count, meals_per_week],
outputs=[savings_display]
)
# Update savings tracker when inputs change
current_weekly_spending.change(
fn=update_savings_tracker,
inputs=[current_weekly_spending, people_count, meals_per_week],
outputs=[savings_tracker_display]
)
people_count.change(
fn=update_savings_tracker,
inputs=[current_weekly_spending, people_count, meals_per_week],
outputs=[savings_tracker_display]
)
meals_per_week.change(
fn=update_savings_tracker,
inputs=[current_weekly_spending, people_count, meals_per_week],
outputs=[savings_tracker_display]
)
def generate_recipe_titles(cost_per_meal, meals_per_week, postcode, preferences, people_count, meal_type, budget_preference):
if not cost_per_meal:
return (
gr.update(choices=[]),
gr.update(value="π Enter your budget above to get started!"),
gr.update(visible=False), gr.update(value=""), gr.update(visible=False),
gr.update(choices=[], visible=False), gr.update(visible=False),
gr.update(visible=False), gr.update(value="", visible=False),
gr.update(visible=False), gr.update(value="", visible=False),
gr.update(visible=False)
)
recipe_generator.ingredient_overlap_enabled = True
_, currency = get_location_from_postcode(postcode)
titles = recipe_generator.generate_titles(cost_per_meal, postcode, preferences, meals_per_week, people_count, meal_type, None, budget_preference)
weekly_total = calculate_weekly_total(cost_per_meal, meals_per_week, people_count)
ingredient_info_msg = ""
if recipe_generator.common_ingredients:
ingredient_counts = Counter(recipe_generator.common_ingredients)
frequent_ingredients = [ing for ing, count in ingredient_counts.most_common(3)]
ingredient_info_msg = "π‘ **Smart Shopping:** All recipes share {0}. Buy once, use {1} times!".format(', '.join(frequent_ingredients), meals_per_week)
# Display cost properly
cost_display = cost_per_meal if isinstance(cost_per_meal, str) else "{0:.2f}".format(cost_per_meal)
# Get recommended supermarket
supermarket_code, supermarket_data = find_cheapest_supermarket(postcode)
supermarket_name = supermarket_data["name"]
# Calculate actual savings for this meal plan
if supermarket_code in ["aldi", "lidl"]:
# Compare to typical UK grocery spending
typical_weekly = weekly_total * 1.30 # Budget stores save ~30%
weekly_savings = typical_weekly - weekly_total
savings_msg = "π° **You're saving Β£{0:.2f}/week** by shopping at {1}! ".format(weekly_savings, supermarket_name)
savings_msg += "(compared to typical grocery spending)\n\n"
elif supermarket_code == "asda":
typical_weekly = weekly_total * 1.18 # Mid-range store saves ~18%
weekly_savings = typical_weekly - weekly_total
savings_msg = "π° **You're saving Β£{0:.2f}/week** by shopping at {1}! ".format(weekly_savings, supermarket_name)
savings_msg += "(compared to typical grocery spending)\n\n"
else:
savings_msg = ""
info_message = "### β
Your Recipes Are Ready!\n\n"
info_message += "π **Recommended Supermarket:** {0} (cheapest near your postcode)\n\n".format(supermarket_name)
info_message += savings_msg
info_message += "**Budget:** Β£{0}/meal Γ {1} dinners = **Β£{2:.2f}/week**\n\n".format(cost_display, meals_per_week, weekly_total)
info_message += "**People:** {0}".format(people_count)
# Add dietary preferences confirmation if specified
if preferences:
info_message += " | **Diet:** {0} β
".format(preferences)
info_message += "\n\nπ Click a recipe below to see the full details, then click the confirm button to save all and add to shopping list!"
return (
gr.update(choices=titles, value=None),
gr.update(value=info_message),
gr.update(value=""),
gr.update(visible=True),
gr.update(choices=titles, visible=True),
gr.update(visible=True),
gr.update(value=ingredient_info_msg, visible=bool(ingredient_info_msg)),
gr.update(visible=True) # Show confirm all button
)
def refresh_unwanted_recipes(cost_per_meal, meals_per_week, postcode, preferences, people_count, meal_type, keep_selected, budget_preference):
if not cost_per_meal:
return gr.update(choices=[]), gr.update(value="Enter cost"), gr.update(value=""), gr.update(choices=[]), gr.update(visible=False), gr.update(value="", visible=False), gr.update(visible=False)
recipe_generator.ingredient_overlap_enabled = True
titles = recipe_generator.generate_titles(cost_per_meal, postcode, preferences, meals_per_week, people_count, meal_type, keep_selected, budget_preference)
return (
gr.update(choices=titles, value=None),
gr.update(value="Kept {0} recipes, refreshed others".format(len(keep_selected) if keep_selected else 0)),
gr.update(value=""),
gr.update(choices=titles),
gr.update(visible=False),
gr.update(value="", visible=False),
gr.update(visible=True) # Show confirm button
)
def display_recipe(title, cost_per_meal, meals_per_week, postcode, preferences, people_count, meal_type, budget_preference):
if title is None:
return gr.update(value="π **Select a recipe from the list** to view full details, ingredients, and cooking instructions.")
try:
title_index = recipe_generator.recent_titles.index(title)
recipe_content = recipe_generator.generate_full_recipe(title_index, cost_per_meal, postcode, preferences, meals_per_week, people_count, meal_type, budget_preference)
# Convert Markdown to HTML
recipe_html = markdown2.markdown(recipe_content, extras=['tables', 'fenced-code-blocks'])
# Add CSS styling for recipe content
styled_html = """
<style>
.recipe-container {{
max-width: 1000px;
margin: 0 auto;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}}
.recipe-container h1 {{
font-size: 32px;
margin-bottom: 20px;
color: #1a1a1a;
}}
.recipe-container h2 {{
font-size: 24px;
margin-top: 30px;
margin-bottom: 15px;
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 8px;
}}
.recipe-container h3 {{
font-size: 20px;
margin-top: 20px;
margin-bottom: 10px;
color: #34495e;
}}
.recipe-container p {{
line-height: 1.8;
margin-bottom: 15px;
color: #333;
}}
.recipe-container ul, .recipe-container ol {{
line-height: 1.8;
margin-bottom: 15px;
padding-left: 25px;
}}
.recipe-container li {{
margin-bottom: 8px;
}}
.recipe-container strong {{
color: #2c3e50;
font-weight: 600;
}}
.recipe-container code {{
background: #f4f4f4;
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
}}
.recipe-image {{
margin-bottom: 30px;
text-align: center;
}}
.recipe-image img {{
width: 100%;
max-width: 800px;
height: auto;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
display: block;
margin: 0 auto;
}}
.image-credit {{
font-size: 12px;
color: #666;
text-align: center;
margin-top: 8px;
}}
</style>
"""
# Try to get recipe image from Unsplash
try:
image_url = get_recipe_image(title)
# Add image to recipe display
recipe_with_image = styled_html + """
<div class="recipe-container">
<div class="recipe-image">
<img src="{0}"
alt="{1}"
onerror="this.style.display='none'; this.parentElement.style.display='none';">
<div class="image-credit">πΈ Photo from Unsplash</div>
</div>
<div>
{2}
</div>
</div>
""".format(image_url, title, recipe_html)
return gr.update(value=recipe_with_image)
except Exception as img_error:
print("Image loading error: {0}".format(str(img_error)))
# If image fails, just show recipe without image
formatted_recipe = styled_html + """
<div class="recipe-container">
{0}
</div>
""".format(recipe_html)
return gr.update(value=formatted_recipe)
except Exception as e:
return gr.update(value="β **Error loading recipe:** {0}".format(str(e)))
def confirm_all_meals_and_add_to_shopping(cost_per_meal, meals_per_week, postcode, preferences, people_count, meal_type, budget_preference):
"""Save all generated recipes and add all ingredients to shopping list"""
if not recipe_generator.recent_titles:
return (
gr.update(value="β No recipes generated yet"),
gr.update(),
"**0 recipes saved**",
gr.update(),
gr.update()
)
saved_count = 0
failed_count = 0
total_ingredients = 0
skipped_ingredients = 0
error_messages = []
# Save all recipes with retry logic
for i, title in enumerate(recipe_generator.recent_titles):
max_retries = 2
retry_count = 0
recipe_saved = False
while retry_count < max_retries and not recipe_saved:
try:
if retry_count > 0:
print(f"π Retry {retry_count}/{max_retries-1} for: {title}")
print(f"Processing recipe {i+1}/{len(recipe_generator.recent_titles)}: {title}")
# Try to generate full recipe
recipe_content = recipe_generator.generate_full_recipe(
i, cost_per_meal, postcode, preferences,
meals_per_week, people_count, meal_type, budget_preference
)
# Check if generation was successful
if not recipe_content:
retry_count += 1
print(f"β No content generated for {title}, attempt {retry_count}/{max_retries}")
import time
time.sleep(1) # Brief delay before retry
continue
if "Error" in recipe_content or "error" in recipe_content.lower():
retry_count += 1
print(f"β Error in content for {title}, attempt {retry_count}/{max_retries}")
import time
time.sleep(1)
continue
# Content looks good, try to save
save_result = recipe_generator.save_current_recipe()
print(f"Save result for {title}: {save_result}")
if "successfully" in save_result.lower() or "saved" in save_result.lower():
saved_count += 1
recipe_saved = True
print(f"β
Successfully saved: {title}")
# Extract and add ingredients
try:
ingredients = shopping_list_manager.extract_ingredients_from_recipe(recipe_content)
print(f"Found {len(ingredients)} ingredients in {title}")
for ingredient in ingredients:
try:
# Convert to realistic shopping quantity
shopping_ingredient = shopping_list_manager.convert_to_shopping_quantity(ingredient)
print(f"Converted '{ingredient}' β '{shopping_ingredient}'")
category = shopping_list_manager.categorize_ingredient(shopping_ingredient)
result = shopping_list_manager.add_item(shopping_ingredient, "", "From: {0}".format(title), category)
if "already in" in result:
skipped_ingredients += 1
else:
total_ingredients += 1
except Exception as ing_error:
print(f"β οΈ Error processing ingredient '{ingredient}': {str(ing_error)}")
continue
except Exception as extract_error:
print(f"β οΈ Error extracting ingredients from {title}: {str(extract_error)}")
# Recipe is saved but ingredients failed - that's OK
break # Success, exit retry loop
else:
retry_count += 1
print(f"β Failed to save {title}: {save_result}, attempt {retry_count}/{max_retries}")
import time
time.sleep(1)
except Exception as e:
retry_count += 1
print(f"β Exception processing {title}: {str(e)}, attempt {retry_count}/{max_retries}")
import time
time.sleep(1)
if retry_count >= max_retries:
# Final failure after all retries
failed_count += 1
error_msg = f"{title}: {str(e)[:100]}" # Truncate long errors
error_messages.append(error_msg)
print(f"β FINAL FAILURE for {title} after {max_retries} attempts: {str(e)}")
# If we exhausted retries without success
if not recipe_saved:
failed_count += 1
if not error_messages or error_messages[-1].split(":")[0] != title:
error_messages.append(f"{title}: Failed after {max_retries} attempts")
print(f"Final count - Saved: {saved_count}, Failed: {failed_count}, Total recipes: {len(recipe_generator.recent_titles)}")
# Update saved recipes list
choices = []
for recipe in recipe_generator.saved_recipes:
recipe_title = recipe["title"]
cost = recipe.get("cost_per_meal", cost_per_meal)
choice_text = "{0} (Β£{1}/meal)".format(recipe_title, cost)
choices.append(choice_text)
count = len(recipe_generator.saved_recipes)
count_text = "**{0} recipe{1} saved**".format(count, 's' if count != 1 else '')
# Update shopping list
shopping_choices, shopping_df = get_shopping_checkboxes()
# Create detailed success message
if failed_count > 0:
status_msg = "β οΈ **Partial Success:** Saved {0}/{1} recipes and added {2} ingredients to your shopping list.".format(
saved_count, len(recipe_generator.recent_titles), total_ingredients
)
if skipped_ingredients > 0:
status_msg += " ({0} already in list)".format(skipped_ingredients)
status_msg += "\n\n**Failed recipes:** " + ", ".join([msg.split(":")[0] for msg in error_messages[:3]])
status_msg += "\n\nπ‘ **Tip:** Try generating fewer recipes at once, or click Generate again to get different recipes."
else:
status_msg = "π **Success!** Saved all {0} recipes and added {1} ingredients to your shopping list!".format(
saved_count, total_ingredients
)
if skipped_ingredients > 0:
status_msg += " ({0} already in list)".format(skipped_ingredients)
status_msg += "\n\nβ
**Go to 'Saved Recipes' tab to view them!**"
return (
gr.update(value=status_msg, visible=True),
gr.update(choices=choices, value=None),
count_text,
shopping_choices,
shopping_df
)
# Function to generate recipes with calculated budget
def generate_recipes_unified(current_spending, people, meals, postcode_val, dietary):
"""Generate recipes using the calculated budget"""
# VALIDATION with helpful error messages
if not current_spending or current_spending <= 0:
error_msg = """
β οΈ **Please enter your weekly DINNER budget**
Enter how much you typically spend on ingredients for DINNERS per week.
π‘ **Tip:** Most UK households spend Β£30-Β£70 per week on dinners.
π **Typical UK household (dinners only):** Β£30-Β£70/week
β **Don't include:** Breakfast, lunch, snacks, cleaning products, toiletries
β
**Only include:** Evening meal ingredients
Please enter your dinner budget above to get started!
"""
return (
gr.update(choices=[], value=None), # title_radio
error_msg, # info_output
"", # save_status
gr.update(visible=False), # regenerate_btn
gr.update(choices=[], value=[]), # keep_checkboxes
gr.update(visible=False), # refresh_unwanted_btn
"", # ingredient_info
gr.update(visible=False), # confirm_all_btn
gr.update(value="3.00") # cost_per_meal
)
if current_spending > 200:
error_msg = """
β οΈ **Dinner budget seems quite high**
You've entered Β£{0}/week for dinners which is more than typical.
π‘ **Average UK household (dinners only):** Β£30-Β£70/week
π **Remember:** Only include evening meal ingredients, not total shopping!
If this is correct, you can continue - but we'll optimize for maximum savings!
""".format(current_spending)
# Don't block, just show warning - continue with generation
# Calculate budget
savings_weekly = current_spending * 0.25
new_budget = current_spending - savings_weekly
cost_per_meal_calc = new_budget / meals / people
# Round to valid option
valid_costs = [2.50, 3.00, 3.50, 4.00, 4.50, 5.00, 5.50, 6.00, 6.50, 7.00, 7.50, 8.00]
cost_rounded = min(valid_costs, key=lambda x: abs(x - cost_per_meal_calc))
# Convert to string for the existing function
cost_per_meal_str = str(cost_rounded)
# Use fixed defaults for meal type and budget preference
meal_type_val = "Dinner"
budget_pref = "Spend Full Budget"
# Call existing recipe generation function
results = generate_recipe_titles(
cost_per_meal_str,
meals,
postcode_val,
dietary,
people,
meal_type_val,
budget_pref
)
# Return results PLUS the calculated cost_per_meal so it gets stored
return results + (gr.update(value=cost_per_meal_str),)
# Connect generate button
generate_btn.click(
fn=generate_recipes_unified,
inputs=[current_weekly_spending, people_count, meals_per_week, postcode, preferences],
outputs=[title_radio, info_output, save_status, regenerate_btn, keep_checkboxes, refresh_unwanted_btn, ingredient_info, confirm_all_btn, cost_per_meal]
)
# When user clicks a recipe title, display it
title_radio.change(
fn=display_recipe,
inputs=[title_radio, cost_per_meal, meals_per_week, postcode, preferences, people_count, meal_type, budget_preference],
outputs=[recipe_markdown]
)
# Regenerate all recipes button
regenerate_btn.click(
fn=generate_recipes_unified,
inputs=[current_weekly_spending, people_count, meals_per_week, postcode, preferences],
outputs=[title_radio, info_output, save_status, regenerate_btn, keep_checkboxes, refresh_unwanted_btn, ingredient_info, confirm_all_btn, cost_per_meal]
)
# Refresh unwanted recipes button
refresh_unwanted_btn.click(
fn=refresh_unwanted_recipes,
inputs=[cost_per_meal, meals_per_week, postcode, preferences, people_count, meal_type, keep_checkboxes, budget_preference],
outputs=[title_radio, info_output, save_status, keep_checkboxes, refresh_unwanted_btn, ingredient_info, confirm_all_btn]
)
# Confirm all meals and add to shopping list
confirm_all_btn.click(
fn=confirm_all_meals_and_add_to_shopping,
inputs=[cost_per_meal, meals_per_week, postcode, preferences, people_count, meal_type, budget_preference],
outputs=[save_status, saved_recipes_radio, saved_count, shopping_checkboxes, shopping_list_table]
)
# ==================== END UNIFIED PLANNER HANDLERS ====================
# UI Functions
def update_weekly_total(cost_per_meal, meals_per_week, people_count):
total = calculate_weekly_total(cost_per_meal, meals_per_week, people_count)
return gr.update(value="**Weekly Total:** Β£{0:.2f}".format(total))
def add_item_to_list(item, quantity, category):
if not item.strip():
return gr.update(value="β Enter item name"), gr.update(), None
result = shopping_list_manager.add_item(item.strip(), quantity.strip(), "", category)
choices, df = get_shopping_checkboxes()
return gr.update(value=f"β
{result}"), choices, df
def clear_checked_items():
"""Remove all checked items"""
df = shopping_list_manager.get_shopping_list_df()
if df is None or df.empty:
return "No items to clear", gr.update(choices=[], value=[]), None
# Remove items marked as Done
shopping_list_manager.shopping_list = [
item for item in shopping_list_manager.shopping_list
if item.get('status', 'Pending') != 'Done'
]
choices, df = get_shopping_checkboxes()
return "β
Checked items removed", choices, df
def clear_all_items():
result = shopping_list_manager.clear_all()
return f"β
{result}", gr.update(choices=[], value=[]), None
def refresh_shopping_list():
"""Refresh the shopping list display"""
return get_shopping_checkboxes()
def get_shopping_checkboxes():
"""Generate checkbox choices with category emojis"""
df = shopping_list_manager.get_shopping_list_df()
if df is None or df.empty:
return gr.update(choices=[], value=[]), None
# Create formatted choices
choices = []
checked = []
# Group by category for nice display
categories = {
"Meat & Fish": "π₯©",
"Dairy & Eggs": "π₯",
"Vegetables": "π₯¬",
"Pantry & Dry Goods": "πΎ",
"Other": "π"
}
for category, emoji in categories.items():
category_items = df[df['Category'] == category]
if category_items.empty:
continue
for _, row in category_items.iterrows():
item_name = row['Item']
qty = row['Qty'] if row['Qty'] else ''
status = row['Status']
# Format: "π₯© Chicken β’ 500g"
if qty:
choice_text = f"{emoji} {item_name} β’ {qty}"
else:
choice_text = f"{emoji} {item_name}"
choices.append(choice_text)
# If item is done, add to checked list
if status == 'Done':
checked.append(choice_text)
return gr.update(choices=choices, value=checked), df
def update_shopping_status(checked_items):
"""Update item status based on checkbox selection"""
df = shopping_list_manager.get_shopping_list_df()
if df is None or df.empty:
return "No items in list", gr.update(choices=[], value=[]), None
# Get current choices for mapping
categories = {
"Meat & Fish": "π₯©",
"Dairy & Eggs": "π₯",
"Vegetables": "π₯¬",
"Pantry & Dry Goods": "πΎ",
"Other": "π"
}
# Update status for all items
for idx, row in df.iterrows():
item_name = row['Item']
qty = row['Qty'] if row['Qty'] else ''
category = row['Category']
emoji = categories.get(category, "π")
# Reconstruct the checkbox text
if qty:
checkbox_text = f"{emoji} {item_name} β’ {qty}"
else:
checkbox_text = f"{emoji} {item_name}"
# Check if this item is in the checked list
if checkbox_text in checked_items:
shopping_list_manager.shopping_list[idx]['status'] = 'Done'
else:
shopping_list_manager.shopping_list[idx]['status'] = 'Pending'
# Count completed
completed = len(checked_items)
total = len(df)
return f"β
{completed}/{total} items checked off", gr.update(), df
def load_shopping_list():
"""Load shopping list as checkboxes"""
return get_shopping_checkboxes()
def get_supermarket_recommendations_ui(cost_per_meal, people_count, meals_per_week, postcode):
if not cost_per_meal:
return gr.update(value="Enter cost per meal")
recommendations = recipe_generator.generate_supermarket_recommendations(cost_per_meal, postcode, people_count, meals_per_week)
return gr.update(value=recommendations)
def load_saved_recipes():
"""Load saved recipes and return radio choices"""
if not recipe_generator.saved_recipes:
return (
gr.update(choices=[], value=None),
gr.update(value="**0 recipes saved**"),
gr.update(value="_No recipes saved yet. Save a recipe from the Recipe Generator tab!_")
)
# Create choices with title and date
choices = []
for i, recipe in enumerate(recipe_generator.saved_recipes):
title = recipe["title"]
cost = recipe["cost_per_meal"]
date = recipe.get("date", "")
choice_text = f"{title} (Β£{cost}/meal)"
choices.append(choice_text)
count = len(recipe_generator.saved_recipes)
count_text = f"**{count} recipe{'s' if count != 1 else ''} saved**"
return (
gr.update(choices=choices, value=None),
count_text,
gr.update(value="_Select a recipe above to see its details_")
)
def view_saved_recipe(recipe_choice):
"""View a saved recipe by its radio button choice"""
if not recipe_choice:
return gr.update(value="_Select a recipe above to see its details_")
# Extract title from choice (format: "Title (Β£X/meal)")
title = recipe_choice.split(" (Β£")[0]
# Find recipe by title
for recipe in recipe_generator.saved_recipes:
if recipe["title"] == title:
content = recipe["content"]
return gr.update(value=content)
return gr.update(value="Recipe not found")
# Event handlers
# Supermarket guide handlers
supermarket_cost_per_meal.change(update_weekly_total, inputs=[supermarket_cost_per_meal, supermarket_meals_per_week, supermarket_people], outputs=[supermarket_weekly_total], queue=False)
supermarket_meals_per_week.change(update_weekly_total, inputs=[supermarket_cost_per_meal, supermarket_meals_per_week, supermarket_people], outputs=[supermarket_weekly_total], queue=False)
supermarket_people.change(update_weekly_total, inputs=[supermarket_cost_per_meal, supermarket_meals_per_week, supermarket_people], outputs=[supermarket_weekly_total], queue=False)
# Shopping list handlers
add_item_btn.click(add_item_to_list, inputs=[new_item, new_quantity, new_category], outputs=[add_status, shopping_checkboxes, shopping_list_table], queue=False)
shopping_checkboxes.change(update_shopping_status, inputs=[shopping_checkboxes], outputs=[list_status, shopping_checkboxes, shopping_list_table])
refresh_list_btn.click(refresh_shopping_list, inputs=[], outputs=[shopping_checkboxes, shopping_list_table], queue=False)
clear_checked_btn.click(clear_checked_items, inputs=[], outputs=[list_status, shopping_checkboxes, shopping_list_table], queue=False)
clear_all_btn.click(clear_all_items, inputs=[], outputs=[list_status, shopping_checkboxes, shopping_list_table], queue=False)
demo.load(load_shopping_list, inputs=[], outputs=[shopping_checkboxes, shopping_list_table], queue=False)
get_recommendations_btn.click(get_supermarket_recommendations_ui, inputs=[supermarket_cost_per_meal, supermarket_people, supermarket_meals_per_week, supermarket_postcode], outputs=[supermarket_recommendations])
# Saved recipes handlers
demo.load(load_saved_recipes, inputs=[], outputs=[saved_recipes_radio, saved_count, loaded_pantry_recipe_markdown], queue=False)
refresh_saved_btn.click(load_saved_recipes, inputs=[], outputs=[saved_recipes_radio, saved_count, loaded_pantry_recipe_markdown], queue=False)
saved_recipes_radio.change(view_saved_recipe, inputs=[saved_recipes_radio], outputs=[loaded_pantry_recipe_markdown])
print("\n" + "="*60)
print("π½οΈ Bitesized AI Meal Planner")
print("="*60)
print("β Smart ingredient sharing across meals")
print("β Realistic UK supermarket pricing")
print("β Weekly shopping list generation")
print("β Budget-friendly meal planning")
print("="*60 + "\n")
demo.queue(max_size=10).launch(debug=True, share=True, max_threads=40)
# Bitesized AI Meal Planner
# SMART MEAL PLANNING WITH INGREDIENT REUSE
# - Recipes share common ingredients for true weekly savings
# - Realistic UK supermarket pricing
# - Weekly shopping list generation
# - Budget-friendly meal planning
# - Powered by Google Gemini 2.5 Flash
# Install required packages
#
# Import libraries
import google.generativeai as genai
import gradio as gr
import pandas as pd
import markdown2
import json
import os
from datetime import datetime
import time
import random
import requests
import re
from collections import Counter
import pickle
# Multi-supermarket pricing system
SUPERMARKET_PRICES = {
"aldi": {
"name": "Aldi",
"prices": {
"chicken_breast": {"price": 3.25, "unit": "500g"}, # Updated Jan 2026 (Β£6.49/kg verified)
"beef_mince": {"price": 4.25, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 2.39, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.49, "unit": "12"}, # Updated Jan 2026 (verified from Aldi.co.uk)
"onions": {"price": 0.99, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.55, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.35, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.45, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.45, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.09, "unit": "1kg"}, # Updated Jan 2026
"pasta": {"price": 0.69, "unit": "500g"}, # Updated Jan 2026
"milk": {"price": 1.25, "unit": "2L"}, # Updated Jan 2026
"cheddar": {"price": 2.19, "unit": "350g"}, # Updated Jan 2026
"mushrooms": {"price": 0.85, "unit": "250g"}, # Updated Jan 2026
"peppers": {"price": 1.39, "unit": "3 pack"}, # Updated Jan 2026
# Pre-made alternatives (often cheaper than from scratch!)
"coleslaw": {"price": 0.79, "unit": "300g tub"}, # Much cheaper than making from scratch
"pasta_sauce": {"price": 0.55, "unit": "500g jar"}, # Cheaper than tinned tomatoes + herbs
"curry_sauce": {"price": 0.89, "unit": "400g jar"}, # Cheaper than buying all spices
"grated_cheese": {"price": 1.69, "unit": "200g"}, # Sometimes more convenient
"hummus": {"price": 0.99, "unit": "200g tub"}, # Cheaper than making from scratch
"puff_pastry": {"price": 1.19, "unit": "375g"}, # Way easier than homemade
"garlic_bread": {"price": 0.75, "unit": "2 pack"}, # Cheaper than making
"salad_bag": {"price": 0.65, "unit": "120g bag"}, # Better value than whole lettuce sometimes
}
},
"lidl": {
"name": "Lidl",
"prices": {
"chicken_breast": {"price": 3.25, "unit": "500g"}, # Updated Jan 2026 (Β£6.49/kg verified)
"beef_mince": {"price": 4.35, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 2.49, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.55, "unit": "12"}, # Updated Jan 2026
"onions": {"price": 1.05, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.59, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.39, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.19, "unit": "1kg"}, # Updated Jan 2026
"pasta": {"price": 0.75, "unit": "500g"}, # Updated Jan 2026
"milk": {"price": 1.29, "unit": "2L"}, # Updated Jan 2026
"cheddar": {"price": 2.29, "unit": "350g"}, # Updated Jan 2026
"mushrooms": {"price": 0.89, "unit": "250g"}, # Updated Jan 2026
"peppers": {"price": 1.45, "unit": "3 pack"}, # Updated Jan 2026
# Pre-made alternatives
"coleslaw": {"price": 0.85, "unit": "300g tub"},
"pasta_sauce": {"price": 0.59, "unit": "500g jar"},
"curry_sauce": {"price": 0.95, "unit": "400g jar"},
"grated_cheese": {"price": 1.75, "unit": "200g"},
"hummus": {"price": 1.05, "unit": "200g tub"},
"puff_pastry": {"price": 1.25, "unit": "375g"},
"garlic_bread": {"price": 0.79, "unit": "2 pack"},
"salad_bag": {"price": 0.69, "unit": "120g bag"},
}
},
"asda": {
"name": "Asda",
"prices": {
"chicken_breast": {"price": 3.75, "unit": "500g"}, # Updated Jan 2026
"beef_mince": {"price": 5.10, "unit": "500g"}, # Updated Jan 2026
"bacon": {"price": 2.95, "unit": "300g"}, # Updated Jan 2026
"eggs": {"price": 2.25, "unit": "12"}, # Updated Jan 2026
"onions": {"price": 1.19, "unit": "1kg"}, # Updated Jan 2026
"garlic": {"price": 0.65, "unit": "bulb"}, # Updated Jan 2026
"tomatoes_tinned": {"price": 0.45, "unit": "400g tin"}, # Updated Jan 2026
"chickpeas_tin": {"price": 0.55, "unit": "400g tin"}, # Updated Jan 2026
"kidney_beans_tin": {"price": 0.49, "unit": "400g tin"}, # Updated Jan 2026
"basmati_rice": {"price": 2.49, "unit": "1kg"}, # Updated Jan 2026