# This version uses a multi-agent system to plan dinners, analyze local PDF/Image recipes, # and optionally find new recipes from the internet using OpenAI's GPT-3.5-Turbo. # UPDATED FOR HUGGING FACE SPACES WITH GRADIO & OCR import os import random from typing import List, Optional from pydantic import BaseModel, Field import json import logging import asyncio from openai import AsyncOpenAI, OpenAIError import xml.etree.ElementTree as ET import pypdf import requests from bs4 import BeautifulSoup import gradio as gr # --- Added for Hugging Face UI from PIL import Image # --- Added for OCR import pytesseract # --- Added for OCR import pillow_heif # --- ADDED TO SUPPORT HEIC/HEIF IMAGE FORMATS import aiohttp # Add this import for async HTTP requests # --- Setup --- # This line registers the HEIC/HEIF plugin with Pillow pillow_heif.register_heif_opener() def ensure_prompt_files_exist(): """Ensures that the necessary prompt files exist, creating them with default content if they don't.""" default_recipe_converter = ''' You are an expert recipe parsing AI model. Your primary function is to meticulously analyze raw text from various sources and transform it into structured recipe objects. Your output MUST be a valid JSON array containing one or more recipe objects. Each recipe object MUST include these fields: A descriptive name for the recipe (required) The original recipe text (can be empty string) A brief summary (can be empty string) Array of ingredients with quantities (can be empty array) Array of cooking steps (can be empty array) Total time (optional) Number of servings (optional integer) Source URL if from web (optional) Even if some information is missing, always return a complete object with default values. Analyze the following recipe content and convert it into a structured JSON array. Always include all fields in the response, using empty strings or arrays for missing data. Recipe Content: {files_context} User Preferences: - Meal type: {meal_type} - Restrictions: {restrictions} ''' default_web_search = ''' You are a creative and effective search query generator for finding recipes online. Your purpose is to generate a single, concise Google search query based on user preferences and existing recipes to find a new and interesting recipe. Your output MUST be only the search query text. Consider all aspects of the user's preferences, including cuisine and dietary restrictions. Avoid generating queries too similar to existing recipes. Based on these user preferences: {preferences} And their existing saved recipes (titles): {existing_recipes} Generate a single, concise Google search query to find a new, exciting recipe they might like. ''' # Create directories if they don't exist os.makedirs(os.path.dirname(PROMPT_FILE_RECIPE_CONVERTER), exist_ok=True) os.makedirs(RECIPE_DIR, exist_ok=True) # Create prompt files if they don't exist if not os.path.exists(PROMPT_FILE_RECIPE_CONVERTER): logger.info(f"Creating default recipe converter prompt file at {PROMPT_FILE_RECIPE_CONVERTER}") with open(PROMPT_FILE_RECIPE_CONVERTER, 'w') as f: f.write(default_recipe_converter) if not os.path.exists(PROMPT_FILE_WEB_SEARCH): logger.info(f"Creating default web search prompt file at {PROMPT_FILE_WEB_SEARCH}") with open(PROMPT_FILE_WEB_SEARCH, 'w') as f: f.write(default_web_search) # --- Path Configuration --- # Determine if we're running in a Hugging Face Space IS_SPACE = os.getenv('SPACE_ID') is not None if IS_SPACE: # In a Space, files are in /home/user/app/ BASE_DIR = '/home/user/app' else: # Locally, use the script's directory BASE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # --- Configuration --- # IMPORTANT: Set your OpenAI API key as an environment variable in your Hugging Face Space secrets. # Name: OPENAI_API_KEY, Value: sk-.... client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY")) SERPER_API_KEY = os.getenv("SERPER_API_KEY") if not client.api_key: logger.error("OPENAI_API_KEY environment variable not set. The script will not be able to connect to OpenAI.") if not SERPER_API_KEY: logger.warning("SERPER_API_KEY environment variable not set. The script will not be able to search for new recipes.") # Define paths relative to BASE_DIR PROMPT_FILE_RECIPE_CONVERTER = os.path.join(BASE_DIR, "prompts", "recipe_converter.xml") PROMPT_FILE_WEB_SEARCH = os.path.join(BASE_DIR, "prompts", "web_search_query_generator.xml") RECIPE_DIR = os.path.join(BASE_DIR, "recipes") # Ensure all necessary files exist ensure_prompt_files_exist() GPT_MODEL = "gpt-3.5-turbo" # --- Pydantic Models (Unchanged) --- class MealPreferences(BaseModel): meal_type: str = "dinner" restrictions: dict = Field(default_factory=dict) cuisine: Optional[str] = "any" dietary_restrictions: List[str] = Field(default_factory=list) class Recipe(BaseModel): name: str content: Optional[str] = "" # Make content optional with empty string default description: str = "" ingredients: List[str] = Field(default_factory=list) instructions: List[str] = Field(default_factory=list) cooking_time: Optional[str] = None servings: Optional[int] = None source_url: Optional[str] = None # --- Core Components --- def load_prompt_from_xml(file_path: str) -> dict: """Loads and parses the prompt from an XML file.""" try: tree = ET.parse(file_path) root = tree.getroot() system_parts = [''.join(elem.itertext()).strip() for elem in root if elem.tag != "user_query_template"] user_template = root.find("user_query_template").text.strip() if root.find("user_query_template") is not None else "" return {"system_prompt": "\n".join(system_parts), "user_template": user_template} except (FileNotFoundError, ET.ParseError) as e: logger.error(f"Error loading prompt file {file_path}: {e}") return {"system_prompt": "You are a helpful recipe assistant.", "user_template": "Please convert this: {files_context}"} recipe_converter_prompt_config = load_prompt_from_xml(PROMPT_FILE_RECIPE_CONVERTER) web_search_prompt_config = load_prompt_from_xml(PROMPT_FILE_WEB_SEARCH) async def openai_completion(model: str, messages: List[dict], temperature: float = 0.2, max_tokens: int = 4096) -> dict: """Async function to interact with OpenAI Chat API.""" try: response = await client.chat.completions.create( model=model, messages=messages, temperature=temperature, max_tokens=max_tokens, ) return response.choices[0].message.model_dump() except OpenAIError as e: logger.error(f"OpenAI API request failed: {e}") return {"content": "[]"} # Return empty JSON array on error def clean_json_response(content: str) -> str: """Extracts a JSON array from a string.""" if "```json" in content: content = content.split("```json")[1].split("```")[0].strip() start_index = content.find('[') end_index = content.rfind(']') if start_index != -1 and end_index != -1: return content[start_index:end_index + 1] logger.warning("Could not find a valid JSON array in the response.") return "[]" def extract_text_from_pdf(file_path: str) -> str: """Extracts text from a PDF file.""" try: with open(file_path, 'rb') as f: reader = pypdf.PdfReader(f) return "".join(page.extract_text() for page in reader.pages) except Exception as e: logger.error(f"Error reading PDF {file_path}: {e}") return "" def extract_text_from_image(file_path: str) -> str: """Extracts text from an image file (JPEG, PNG, etc.) using OCR.""" try: return pytesseract.image_to_string(Image.open(file_path)) except Exception as e: logger.error(f"Error processing image {file_path} with OCR: {e}") return "" # --- Agent Definitions --- class RecipeConverterAgent: """An agent that converts raw text into structured Recipe objects using an LLM.""" def __init__(self): self.system_prompt = recipe_converter_prompt_config["system_prompt"] self.user_template = recipe_converter_prompt_config["user_template"] async def convert(self, files_content: List[dict], preferences: MealPreferences) -> List[Recipe]: if not files_content: return [] try: files_context = json.dumps(files_content, indent=2) user_prompt = self.user_template.format( files_context=files_context, meal_type=preferences.meal_type, restrictions=json.dumps(preferences.restrictions) ) messages = [ {"role": "system", "content": self.system_prompt}, {"role": "user", "content": user_prompt} ] response_message = await openai_completion(GPT_MODEL, messages) json_str = clean_json_response(response_message['content']) recipes_data = json.loads(json_str) return [Recipe(**data) for data in recipes_data] except (json.JSONDecodeError, TypeError) as e: logger.error(f"Error converting content to recipes: {e}") return [] class FileSystemRecipeAgent: """Fetches and processes recipe files from a local directory.""" def __init__(self, recipe_dir: str): self.recipe_dir = recipe_dir if not os.path.isdir(self.recipe_dir): logger.warning(f"Recipe directory '{self.recipe_dir}' not found. Creating it.") os.makedirs(self.recipe_dir, exist_ok=True) def get_recipe_files(self) -> List[dict]: """Reads all supported recipe files from the directory.""" recipes_content = [] for filename in os.listdir(self.recipe_dir): file_path = os.path.join(self.recipe_dir, filename) content = "" # --- UPDATED TO INCLUDE OCR --- if filename.endswith('.pdf'): content = extract_text_from_pdf(file_path) elif filename.endswith(('.txt', '.json')): try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() except Exception as e: logger.error(f"Error reading text file {filename}: {e}") elif filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')): content = extract_text_from_image(file_path) if content: recipes_content.append({ 'name': filename, 'content': content, 'description': f"Loaded from local file: {filename}" }) if not recipes_content: logger.warning("No recipe files found in the directory.") return recipes_content class WebRecipeAgent: """Finds and scrapes a new recipe from the internet using Serper API.""" def __init__(self): self.system_prompt = web_search_prompt_config["system_prompt"] self.user_template = web_search_prompt_config["user_template"] self.serper_api_key = SERPER_API_KEY async def search_recipes(self, query: str) -> List[dict]: """Search for recipes using Serper API.""" if not self.serper_api_key: logger.error("Serper API key not set. Cannot search for recipes.") return [] url = "https://google.serper.dev/search" headers = { "X-API-KEY": self.serper_api_key, "Content-Type": "application/json" } payload = { "q": f"{query} recipe", "num": 5 } try: async with aiohttp.ClientSession() as session: async with session.post(url, headers=headers, json=payload) as response: if response.status == 200: data = await response.json() logger.info(f"Serper API search successful for query: {query}") organic_results = data.get('organic', []) filtered_results = [ { 'title': result.get('title', ''), 'link': result.get('link', ''), 'snippet': result.get('snippet', '') } for result in organic_results if 'recipe' in result.get('title', '').lower() or 'recipe' in result.get('snippet', '').lower() ] logger.info(f"Found {len(filtered_results)} potential recipe results") return filtered_results else: logger.error(f"Serper API request failed with status {response.status}") return [] except Exception as e: logger.error(f"Failed to search recipes using Serper: {e}") return [] async def scrape_recipe(self, url: str) -> str: """Scrape recipe content from a URL.""" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } try: async with aiohttp.ClientSession() as session: async with session.get(url, headers=headers) as response: if response.status == 200: html = await response.text() soup = BeautifulSoup(html, 'lxml') # Remove unwanted elements for tag in soup(['script', 'style', 'meta', 'link', 'header', 'footer', 'nav']): tag.decompose() # Try to find recipe-specific content recipe_content = soup.find(class_=lambda x: x and ('recipe' in x.lower() or 'ingredients' in x.lower())) if recipe_content: logger.info(f"Successfully found recipe content at {url}") return recipe_content.get_text(separator='\n', strip=True) # Fallback to main content main_content = soup.find('main') or soup.find('article') or soup.find('body') text = main_content.get_text(separator='\n', strip=True) if main_content else "" logger.info(f"Scraped content from {url}: {len(text)} characters") return text else: logger.error(f"Failed to fetch recipe from {url}: {response.status}") return "" except Exception as e: logger.error(f"Failed to scrape recipe from {url}: {e}") return "" async def find_new_recipe(self, preferences: MealPreferences, existing_recipes: List[Recipe]) -> Optional[Recipe]: """Find and process a new recipe from the internet.""" logger.info("Attempting to find a new recipe online...") # 1. Generate search query cuisine_term = f"{preferences.cuisine} " if preferences.cuisine and preferences.cuisine.lower() != "any" else "" dietary_terms = " ".join(preferences.dietary_restrictions) base_query = f"{cuisine_term}{dietary_terms}".strip() user_prompt = self.user_template.format( preferences=preferences.model_dump_json(), existing_recipes=str([r.name for r in existing_recipes]) ) messages = [ {"role": "system", "content": self.system_prompt}, {"role": "user", "content": user_prompt} ] response_message = await openai_completion(GPT_MODEL, messages, temperature=0.5) search_query = response_message['content'].strip().replace('"', '') logger.info(f"Generated search query: {search_query}") # 2. Search for recipes using Serper search_results = await self.search_recipes(f"{base_query} {search_query}".strip()) if not search_results: logger.warning("No recipe search results found") return None # 3. Try each result until we find a valid recipe for result in search_results: logger.info(f"Attempting to process recipe: {result['title']}") recipe_text = await self.scrape_recipe(result['link']) if not recipe_text: continue # 4. Convert scraped text to Recipe object converter = RecipeConverterAgent() file_content = [{ 'name': result['title'], 'content': recipe_text, 'description': result['snippet'], 'source_url': result['link'] }] new_recipes = await converter.convert(file_content, preferences) if new_recipes: new_recipe = new_recipes[0] logger.info(f"Successfully converted new recipe: {new_recipe.name}") return new_recipe logger.warning("Could not find a suitable recipe from search results") return None class DinnerPlannerAgent: """Orchestrates the dinner planning process.""" def __init__(self, recipe_dir: str): self.fs_agent = FileSystemRecipeAgent(recipe_dir) self.web_agent = WebRecipeAgent() self.converter = RecipeConverterAgent() async def plan_dinners(self, preferences: MealPreferences, num_dinners: int = 3, try_something_new: bool = False) -> List[Recipe]: logger.info("Starting dinner planning...") local_recipe_files = self.fs_agent.get_recipe_files() local_recipes = await self.converter.convert(local_recipe_files, preferences) if not local_recipes: logger.warning("No local recipes found or could be converted.") if not try_something_new: return [] final_dinner_plan = [] if try_something_new: new_recipe = await self.web_agent.find_new_recipe(preferences, local_recipes) if new_recipe: final_dinner_plan.append(new_recipe) num_needed = num_dinners - len(final_dinner_plan) if num_needed > 0 and local_recipes: web_recipe_names = {r.name for r in final_dinner_plan} available_local = [r for r in local_recipes if r.name not in web_recipe_names] final_dinner_plan.extend(random.sample(available_local, min(num_needed, len(available_local)))) logger.info(f"Dinner plan created with {len(final_dinner_plan)} recipe(s).") return final_dinner_plan class GroceryListAgent: """Consolidates ingredients from multiple recipes into a single shopping list.""" # Common unit conversions and abbreviations UNIT_MAPPINGS = { # Volume 'tablespoon': ['tbsp', 'tbs', 'tablespoons'], 'teaspoon': ['tsp', 'teaspoons'], 'cup': ['cups', 'c.', 'c'], 'ounce': ['oz', 'ounces', 'fl oz', 'fluid ounce'], 'pint': ['pt', 'pints'], 'quart': ['qt', 'quarts'], 'gallon': ['gal', 'gallons'], # Weight 'pound': ['lb', 'lbs', 'pounds'], 'gram': ['g', 'grams'], 'kilogram': ['kg', 'kilograms'], # Count 'piece': ['pieces', 'pcs'], 'whole': ['entire', 'complete'], # Other 'can': ['cans'], 'package': ['pkg', 'pack', 'packages'], 'bunch': ['bunches'], 'clove': ['cloves'], } def _normalize_unit(self, unit: str) -> str: """Convert various unit formats to a standard form.""" unit = unit.lower().strip() for standard, variants in self.UNIT_MAPPINGS.items(): if unit == standard or unit in variants: return standard return unit def _extract_quantity_and_unit(self, ingredient: str) -> tuple: """Extract quantity, unit, and item from an ingredient string.""" # Common fraction replacements fractions = { '½': '0.5', '⅓': '0.33', '¼': '0.25', '¾': '0.75', '⅔': '0.67', '⅛': '0.125', '⅜': '0.375', '⅝': '0.625', '⅞': '0.875' } # Replace unicode fractions for fraction, decimal in fractions.items(): ingredient = ingredient.replace(fraction, decimal) # Try to find quantity and unit import re quantity_pattern = r'^(\d+(?:\.\d+)?(?:\s*-\s*\d+(?:\.\d+)?)?)\s*' unit_pattern = r'(?:(\b(?:cup|tablespoon|teaspoon|ounce|pound|gram|can|package|bunch|clove|piece|whole)s?\b))?' match = re.match(f"{quantity_pattern}{unit_pattern}", ingredient.lower()) if match: quantity_str, unit = match.groups() # Handle ranges (take the larger number) if '-' in quantity_str: start, end = map(float, quantity_str.split('-')) quantity = end else: try: quantity = float(quantity_str) except ValueError: quantity = 1 # Normalize unit if present unit = self._normalize_unit(unit) if unit else None # Get the item name, removing the quantity and unit item = ingredient[match.end():].strip() # Remove common prefixes item = re.sub(r'^of\s+', '', item) return quantity, unit, item return 1, None, ingredient.strip() def _combine_quantities(self, items: list) -> dict: """Combine like items and sum their quantities.""" combined = {} for quantity, unit, item in items: # Create a key that combines the unit and item key = f"{unit}_{item}" if unit else item if key in combined: # Sum quantities if units match combined[key]['quantity'] += quantity else: combined[key] = { 'quantity': quantity, 'unit': unit, 'item': item } return combined def _format_quantity(self, quantity: float) -> str: """Format quantity to be more readable.""" # Convert to float first to handle both int and float inputs quantity = float(quantity) # Check if it's effectively a whole number if quantity.is_integer(): return str(int(quantity)) # Round to 2 decimal places and remove trailing zeros return f"{quantity:.2f}".rstrip('0').rstrip('.') async def generate_list(self, recipes: List[Recipe]) -> str: """Creates a markdown-formatted grocery list from a list of recipes.""" logger.info("Generating grocery list...") # Collect all ingredients with their quantities and units parsed_ingredients = [] for recipe in recipes: for ing in recipe.ingredients: quantity, unit, item = self._extract_quantity_and_unit(ing.lower()) parsed_ingredients.append((quantity, unit, item)) # Combine like ingredients combined = self._combine_quantities(parsed_ingredients) # Sort ingredients by name sorted_ingredients = sorted(combined.values(), key=lambda x: x['item']) # Format as markdown markdown_list = "## 🛒 Your Grocery List\n\n" # Group by units categorized = { 'count': [], # Items with no unit 'weight': [], # pounds, grams, etc. 'volume': [], # cups, tablespoons, etc. 'other': [] # cans, packages, etc. } weight_units = {'pound', 'gram', 'kilogram'} volume_units = {'cup', 'tablespoon', 'teaspoon', 'ounce', 'pint', 'quart', 'gallon'} for item in sorted_ingredients: unit = item['unit'] if not unit: categorized['count'].append(item) elif unit in weight_units: categorized['weight'].append(item) elif unit in volume_units: categorized['volume'].append(item) else: categorized['other'].append(item) # Add items by category categories = { 'count': '📝 General Items', 'weight': '⚖️ By Weight', 'volume': '📏 By Volume', 'other': '📦 Packaged Items' } for category, title in categories.items(): items = categorized[category] if items: markdown_list += f"\n### {title}\n" for item in items: quantity = self._format_quantity(item['quantity']) unit = f" {item['unit']}" if item['unit'] else "" markdown_list += f"- [ ] {quantity}{unit} {item['item'].capitalize()}\n" logger.info(f"Generated grocery list with {len(combined)} unique items.") return markdown_list # --- NEW GRADIO INTERFACE --- async def run_dinner_plan(try_something_new: bool, cuisine: str, dietary_restrictions: List[str]): """ This function is the entry point for the Gradio interface. It runs the dinner planner and formats the output as Markdown. """ if not client.api_key: return "## 🛑 Error: `OPENAI_API_KEY` is not set!\nPlease set it in your Space secrets.", "" # Create a dummy recipe file if the directory is empty, so the demo works out-of-the-box. if not os.path.exists(RECIPE_DIR) or not os.listdir(RECIPE_DIR): os.makedirs(RECIPE_DIR, exist_ok=True) with open(os.path.join(RECIPE_DIR, "classic_spaghetti.txt"), "w") as f: f.write("Classic Spaghetti Bolognese.\nIngredients: Ground beef, tomatoes, pasta.\nInstructions: Brown the beef, add sauce, cook pasta.") logger.info(f"Running planner with 'Try Something New' set to: {try_something_new}") logger.info(f"Cuisine: {cuisine}, Dietary Restrictions: {dietary_restrictions}") planner = DinnerPlannerAgent(recipe_dir=RECIPE_DIR) # Pass user preferences to the planner prefs = MealPreferences( restrictions={"cuisine": cuisine, "dietary": dietary_restrictions}, cuisine=cuisine, dietary_restrictions=dietary_restrictions ) dinner_plan = await planner.plan_dinners(prefs, num_dinners=3, try_something_new=try_something_new) # Format the output for display in the Gradio app if not dinner_plan: no_plan_message = "😥 Could not create a dinner plan. Try adding some recipes to the `recipes` folder!" return no_plan_message, "" output_md = "## 🍽️ Your Dinner Plan\n" for recipe in dinner_plan: source = f"[{recipe.source_url}]({recipe.source_url})" if recipe.source_url else "Local File" output_md += f"### {recipe.name}\n" output_md += f"* **Source**: {source}\n\n" if recipe.ingredients: output_md += "**Ingredients:**\n" + "\n".join(f"- {item}" for item in recipe.ingredients) + "\n\n" if recipe.instructions: output_md += "**Instructions:**\n" + "\n".join(f"{i}. {step}" for i, step in enumerate(recipe.instructions, 1)) + "\n" output_md += "\n---\n" # Generate grocery list grocery_agent = GroceryListAgent() grocery_list_md = await grocery_agent.generate_list(dinner_plan) return output_md, grocery_list_md # --- UI Definition --- CUISINE_OPTIONS = ["Any", "Italian", "Mexican", "Spanish", "American", "Chinese", "Thai", "Greek", "Indian", "French", "Japanese", "Dutch", "Soul", "Middle Eastern", "Cajun"] DIETARY_OPTIONS = ["Dairy-free", "Nut-free", "Vegan", "Vegetarian", "Gluten-free"] with gr.Blocks() as iface: gr.Markdown("# 🤖 AI Dinner Planner") gr.Markdown("Let AI plan your next three dinners. This app searches your saved recipes that your family loves. If you want to try something new, check the box to have the agent search the web for one new recipe to include in the suggestions, based on your preferences.") # Add custom CSS for the loading animation loading_html = gr.HTML("""
🤖
🥘

Cooking up your dinner plan...

""", visible=False) with gr.Row(): try_new = gr.Checkbox(label="Try Something New?", value=False) cuisine = gr.Dropdown(CUISINE_OPTIONS, label="Cuisine", value="Any") dietary = gr.CheckboxGroup(DIETARY_OPTIONS, label="Dietary Restrictions") run_button = gr.Button("Plan My Dinners!", variant="primary") with gr.Tabs(): with gr.TabItem("Dinner Plan"): plan_output = gr.Markdown(label="Dinner Suggestions", sanitize_html=False) with gr.TabItem("Grocery List"): grocery_output = gr.Markdown(label="Shopping List", sanitize_html=False) def show_loading(): return {loading_html: gr.update(visible=True)} def hide_loading(): return {loading_html: gr.update(visible=False)} run_button.click( fn=show_loading, outputs=[loading_html], ).then( fn=run_dinner_plan, inputs=[try_new, cuisine, dietary], outputs=[plan_output, grocery_output], ).then( fn=hide_loading, outputs=[loading_html] ) iface.launch()