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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This version uses a multi-agent system to plan dinners, analyze local PDF recipes,
|
| 2 |
+
# and optionally find new recipes from the internet using OpenAI's GPT-3.5-Turbo.
|
| 3 |
+
# UPDATED FOR HUGGING FACE SPACES WITH GRADIO
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
from typing import List, Optional
|
| 8 |
+
from pydantic import BaseModel, Field
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import asyncio
|
| 12 |
+
import openai
|
| 13 |
+
import xml.etree.ElementTree as ET
|
| 14 |
+
import pypdf
|
| 15 |
+
import requests
|
| 16 |
+
from bs4 import BeautifulSoup
|
| 17 |
+
import gradio as gr # --- Added for Hugging Face UI
|
| 18 |
+
|
| 19 |
+
# --- Setup ---
|
| 20 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
# --- Configuration ---
|
| 24 |
+
# IMPORTANT: Set your OpenAI API key as an environment variable in your Hugging Face Space secrets.
|
| 25 |
+
# Name: OPENAI_API_KEY, Value: sk-....
|
| 26 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 27 |
+
if not openai.api_key:
|
| 28 |
+
logger.error("OPENAI_API_KEY environment variable not set. The script will not be able to connect to OpenAI.")
|
| 29 |
+
# In a live app, you might want a more visible error in the UI
|
| 30 |
+
# raise ValueError("Missing OPENAI_API_KEY")
|
| 31 |
+
|
| 32 |
+
PROMPT_FILE = "prompts/recipe_converter.xml"
|
| 33 |
+
RECIPE_DIR = "recipes" # Directory for local PDF/text recipes
|
| 34 |
+
GPT_MODEL = "gpt-3.5-turbo"
|
| 35 |
+
|
| 36 |
+
# --- Pydantic Models (Unchanged) ---
|
| 37 |
+
class MealPreferences(BaseModel):
|
| 38 |
+
meal_type: str = "dinner"
|
| 39 |
+
restrictions: dict = Field(default_factory=dict)
|
| 40 |
+
|
| 41 |
+
class Recipe(BaseModel):
|
| 42 |
+
name: str
|
| 43 |
+
content: str
|
| 44 |
+
description: str = ""
|
| 45 |
+
ingredients: List[str] = Field(default_factory=list)
|
| 46 |
+
instructions: List[str] = Field(default_factory=list)
|
| 47 |
+
cooking_time: Optional[str] = None
|
| 48 |
+
servings: Optional[int] = None
|
| 49 |
+
source_url: Optional[str] = None
|
| 50 |
+
|
| 51 |
+
# --- Core Components (Unchanged) ---
|
| 52 |
+
|
| 53 |
+
def load_prompt_from_xml(file_path: str) -> dict:
|
| 54 |
+
"""Loads and parses the prompt from an XML file."""
|
| 55 |
+
try:
|
| 56 |
+
tree = ET.parse(file_path)
|
| 57 |
+
root = tree.getroot()
|
| 58 |
+
system_parts = [''.join(elem.itertext()).strip() for elem in root if elem.tag != "user_query_template"]
|
| 59 |
+
user_template = root.find("user_query_template").text.strip() if root.find("user_query_template") is not None else ""
|
| 60 |
+
return {"system_prompt": "\n".join(system_parts), "user_template": user_template}
|
| 61 |
+
except (FileNotFoundError, ET.ParseError) as e:
|
| 62 |
+
logger.error(f"Error loading prompt file {file_path}: {e}")
|
| 63 |
+
return {"system_prompt": "You are a helpful recipe assistant.", "user_template": "Please convert this: {files_context}"}
|
| 64 |
+
|
| 65 |
+
prompt_config = load_prompt_from_xml(PROMPT_FILE)
|
| 66 |
+
|
| 67 |
+
async def openai_completion(model: str, messages: List[dict], temperature: float = 0.2, max_tokens: int = 4096) -> dict:
|
| 68 |
+
"""Async function to interact with OpenAI Chat API."""
|
| 69 |
+
try:
|
| 70 |
+
response = await openai.ChatCompletion.acreate(
|
| 71 |
+
model=model,
|
| 72 |
+
messages=messages,
|
| 73 |
+
temperature=temperature,
|
| 74 |
+
max_tokens=max_tokens,
|
| 75 |
+
)
|
| 76 |
+
return response.choices[0].message
|
| 77 |
+
except openai.error.OpenAIError as e:
|
| 78 |
+
logger.error(f"OpenAI API request failed: {e}")
|
| 79 |
+
return {"content": "[]"} # Return empty JSON array on error
|
| 80 |
+
|
| 81 |
+
def clean_json_response(content: str) -> str:
|
| 82 |
+
"""Extracts a JSON array from a string."""
|
| 83 |
+
if "```json" in content:
|
| 84 |
+
content = content.split("```json")[1].split("```")[0].strip()
|
| 85 |
+
|
| 86 |
+
start_index = content.find('[')
|
| 87 |
+
end_index = content.rfind(']')
|
| 88 |
+
|
| 89 |
+
if start_index != -1 and end_index != -1:
|
| 90 |
+
return content[start_index:end_index + 1]
|
| 91 |
+
|
| 92 |
+
logger.warning("Could not find a valid JSON array in the response.")
|
| 93 |
+
return "[]"
|
| 94 |
+
|
| 95 |
+
def extract_text_from_pdf(file_path: str) -> str:
|
| 96 |
+
"""Extracts text from a PDF file."""
|
| 97 |
+
try:
|
| 98 |
+
with open(file_path, 'rb') as f:
|
| 99 |
+
reader = pypdf.PdfReader(f)
|
| 100 |
+
return "".join(page.extract_text() for page in reader.pages)
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Error reading PDF {file_path}: {e}")
|
| 103 |
+
return ""
|
| 104 |
+
|
| 105 |
+
# --- Agent Definitions (Unchanged) ---
|
| 106 |
+
|
| 107 |
+
class RecipeConverterAgent:
|
| 108 |
+
"""An agent that converts raw text into structured Recipe objects using an LLM."""
|
| 109 |
+
def __init__(self):
|
| 110 |
+
self.system_prompt = prompt_config["system_prompt"]
|
| 111 |
+
self.user_template = prompt_config["user_template"]
|
| 112 |
+
|
| 113 |
+
async def convert(self, files_content: List[dict], preferences: MealPreferences) -> List[Recipe]:
|
| 114 |
+
if not files_content:
|
| 115 |
+
return []
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
files_context = json.dumps(files_content, indent=2)
|
| 119 |
+
user_prompt = self.user_template.format(
|
| 120 |
+
files_context=files_context,
|
| 121 |
+
meal_type=preferences.meal_type,
|
| 122 |
+
restrictions=json.dumps(preferences.restrictions)
|
| 123 |
+
)
|
| 124 |
+
messages = [
|
| 125 |
+
{"role": "system", "content": self.system_prompt},
|
| 126 |
+
{"role": "user", "content": user_prompt}
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
response_message = await openai_completion(GPT_MODEL, messages)
|
| 130 |
+
json_str = clean_json_response(response_message['content'])
|
| 131 |
+
recipes_data = json.loads(json_str)
|
| 132 |
+
return [Recipe(**data) for data in recipes_data]
|
| 133 |
+
|
| 134 |
+
except (json.JSONDecodeError, TypeError) as e:
|
| 135 |
+
logger.error(f"Error converting content to recipes: {e}")
|
| 136 |
+
return []
|
| 137 |
+
|
| 138 |
+
class FileSystemRecipeAgent:
|
| 139 |
+
"""Fetches and processes recipe files from a local directory."""
|
| 140 |
+
def __init__(self, recipe_dir: str):
|
| 141 |
+
self.recipe_dir = recipe_dir
|
| 142 |
+
if not os.path.isdir(self.recipe_dir):
|
| 143 |
+
logger.warning(f"Recipe directory '{self.recipe_dir}' not found. Creating it.")
|
| 144 |
+
os.makedirs(self.recipe_dir, exist_ok=True)
|
| 145 |
+
|
| 146 |
+
def get_recipe_files(self) -> List[dict]:
|
| 147 |
+
"""Reads all supported recipe files from the directory."""
|
| 148 |
+
recipes_content = []
|
| 149 |
+
for filename in os.listdir(self.recipe_dir):
|
| 150 |
+
file_path = os.path.join(self.recipe_dir, filename)
|
| 151 |
+
content = ""
|
| 152 |
+
if filename.endswith('.pdf'):
|
| 153 |
+
content = extract_text_from_pdf(file_path)
|
| 154 |
+
elif filename.endswith(('.txt', '.json')):
|
| 155 |
+
try:
|
| 156 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 157 |
+
content = f.read()
|
| 158 |
+
except Exception as e:
|
| 159 |
+
logger.error(f"Error reading text file {filename}: {e}")
|
| 160 |
+
|
| 161 |
+
if content:
|
| 162 |
+
recipes_content.append({
|
| 163 |
+
'name': filename, 'content': content,
|
| 164 |
+
'description': f"Loaded from local file: {filename}"
|
| 165 |
+
})
|
| 166 |
+
|
| 167 |
+
if not recipes_content:
|
| 168 |
+
logger.warning("No recipe files found in the directory.")
|
| 169 |
+
return recipes_content
|
| 170 |
+
|
| 171 |
+
class WebRecipeAgent:
|
| 172 |
+
"""Finds and scrapes a new recipe from the internet."""
|
| 173 |
+
async def find_new_recipe(self, preferences: MealPreferences, existing_recipes: List[Recipe]) -> Optional[Recipe]:
|
| 174 |
+
logger.info("Attempting to find a new recipe online...")
|
| 175 |
+
# 1. Generate a search query
|
| 176 |
+
search_query_prompt = f"""
|
| 177 |
+
Based on these user preferences: {preferences.json()}
|
| 178 |
+
And their existing saved recipes (titles): {[r.name for r in existing_recipes]}
|
| 179 |
+
Generate a single, concise Google search query to find a new, exciting recipe they might like.
|
| 180 |
+
The query should be creative and specific. For example: "spicy vegetarian thai curry recipe easy".
|
| 181 |
+
Return ONLY the search query text, nothing else.
|
| 182 |
+
"""
|
| 183 |
+
messages = [{"role": "system", "content": "You are a creative search query generator."}, {"role": "user", "content": search_query_prompt}]
|
| 184 |
+
response_message = await openai_completion(GPT_MODEL, messages, temperature=0.5)
|
| 185 |
+
search_query = response_message['content'].strip().replace('"', '')
|
| 186 |
+
logger.info(f"Generated search query: {search_query}")
|
| 187 |
+
|
| 188 |
+
# 2. Search the web (simplified using requests + beautifulsoup)
|
| 189 |
+
try:
|
| 190 |
+
# Note: Directly scraping Google can be unreliable.
|
| 191 |
+
search_url = f"[https://www.google.com/search?q=](https://www.google.com/search?q=){search_query.replace(' ', '+')}"
|
| 192 |
+
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'}
|
| 193 |
+
response = requests.get(search_url, headers=headers)
|
| 194 |
+
response.raise_for_status()
|
| 195 |
+
soup = BeautifulSoup(response.text, 'lxml')
|
| 196 |
+
recipe_link_element = soup.find('a', href=lambda href: href and href.startswith('http') and ('/recipe' in href or '/recipes' in href))
|
| 197 |
+
if not recipe_link_element:
|
| 198 |
+
logger.warning("Could not find a recipe link in search results.")
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
recipe_url = recipe_link_element['href']
|
| 202 |
+
logger.info(f"Found recipe URL: {recipe_url}")
|
| 203 |
+
|
| 204 |
+
# 3. Scrape the recipe page
|
| 205 |
+
response = requests.get(recipe_url, headers=headers)
|
| 206 |
+
response.raise_for_status()
|
| 207 |
+
scrape_soup = BeautifulSoup(response.text, 'lxml')
|
| 208 |
+
recipe_text = scrape_soup.get_text(separator='\n', strip=True)
|
| 209 |
+
|
| 210 |
+
# 4. Convert scraped text to a Recipe object
|
| 211 |
+
converter = RecipeConverterAgent()
|
| 212 |
+
file_content = [{'name': recipe_url.split('/')[-1], 'content': recipe_text, 'description': f"Scraped from {recipe_url}"}]
|
| 213 |
+
new_recipes = await converter.convert(file_content, preferences)
|
| 214 |
+
if new_recipes:
|
| 215 |
+
new_recipe = new_recipes[0]
|
| 216 |
+
new_recipe.source_url = recipe_url # Set source URL
|
| 217 |
+
logger.info(f"Successfully converted new recipe: {new_recipe.name}")
|
| 218 |
+
return new_recipe
|
| 219 |
+
except Exception as e:
|
| 220 |
+
logger.error(f"Failed to find or process new recipe: {e}")
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
class DinnerPlannerAgent:
|
| 224 |
+
"""Orchestrates the dinner planning process."""
|
| 225 |
+
def __init__(self, recipe_dir: str):
|
| 226 |
+
self.fs_agent = FileSystemRecipeAgent(recipe_dir)
|
| 227 |
+
self.web_agent = WebRecipeAgent()
|
| 228 |
+
self.converter = RecipeConverterAgent()
|
| 229 |
+
|
| 230 |
+
async def plan_dinners(self, preferences: MealPreferences, num_dinners: int = 3, try_something_new: bool = False) -> List[Recipe]:
|
| 231 |
+
logger.info("Starting dinner planning...")
|
| 232 |
+
local_recipe_files = self.fs_agent.get_recipe_files()
|
| 233 |
+
local_recipes = await self.converter.convert(local_recipe_files, preferences)
|
| 234 |
+
|
| 235 |
+
if not local_recipes:
|
| 236 |
+
logger.warning("No local recipes found or could be converted.")
|
| 237 |
+
if not try_something_new: return []
|
| 238 |
+
|
| 239 |
+
final_dinner_plan = []
|
| 240 |
+
if try_something_new:
|
| 241 |
+
new_recipe = await self.web_agent.find_new_recipe(preferences, local_recipes)
|
| 242 |
+
if new_recipe: final_dinner_plan.append(new_recipe)
|
| 243 |
+
|
| 244 |
+
num_needed = num_dinners - len(final_dinner_plan)
|
| 245 |
+
if num_needed > 0 and local_recipes:
|
| 246 |
+
web_recipe_names = {r.name for r in final_dinner_plan}
|
| 247 |
+
available_local = [r for r in local_recipes if r.name not in web_recipe_names]
|
| 248 |
+
final_dinner_plan.extend(random.sample(available_local, min(num_needed, len(available_local))))
|
| 249 |
+
|
| 250 |
+
logger.info(f"Dinner plan created with {len(final_dinner_plan)} recipe(s).")
|
| 251 |
+
return final_dinner_plan
|
| 252 |
+
|
| 253 |
+
# --- NEW GRADIO INTERFACE ---
|
| 254 |
+
|
| 255 |
+
async def run_dinner_plan(try_something_new: bool):
|
| 256 |
+
"""
|
| 257 |
+
This function is the entry point for the Gradio interface.
|
| 258 |
+
It runs the dinner planner and formats the output as Markdown.
|
| 259 |
+
"""
|
| 260 |
+
if not openai.api_key:
|
| 261 |
+
return "## 🛑 Error: `OPENAI_API_KEY` is not set!\nPlease set it in your Space secrets."
|
| 262 |
+
|
| 263 |
+
# Create a dummy recipe file if the directory is empty, so the demo works out-of-the-box.
|
| 264 |
+
if not os.path.exists(RECIPE_DIR) or not os.listdir(RECIPE_DIR):
|
| 265 |
+
os.makedirs(RECIPE_DIR, exist_ok=True)
|
| 266 |
+
with open(os.path.join(RECIPE_DIR, "classic_spaghetti.txt"), "w") as f:
|
| 267 |
+
f.write("Classic Spaghetti Bolognese.\nIngredients: Ground beef, tomatoes, pasta.\nInstructions: Brown the beef, add sauce, cook pasta.")
|
| 268 |
+
|
| 269 |
+
logger.info(f"Running planner with 'Try Something New' set to: {try_something_new}")
|
| 270 |
+
|
| 271 |
+
planner = DinnerPlannerAgent(recipe_dir=RECIPE_DIR)
|
| 272 |
+
prefs = MealPreferences(restrictions={"cuisine": "any"})
|
| 273 |
+
|
| 274 |
+
dinner_plan = await planner.plan_dinners(prefs, num_dinners=3, try_something_new=try_something_new)
|
| 275 |
+
|
| 276 |
+
# Format the output for display in the Gradio app
|
| 277 |
+
if not dinner_plan:
|
| 278 |
+
return "😥 Could not create a dinner plan. Try adding some recipes to the `recipes` folder!"
|
| 279 |
+
|
| 280 |
+
output_md = "## 🍽️ Your Dinner Plan\n"
|
| 281 |
+
for recipe in dinner_plan:
|
| 282 |
+
source = f"[{recipe.source_url}]({recipe.source_url})" if recipe.source_url else "Local File"
|
| 283 |
+
output_md += f"### {recipe.name}\n"
|
| 284 |
+
output_md += f"* **Source**: {source}\n\n"
|
| 285 |
+
|
| 286 |
+
if recipe.ingredients:
|
| 287 |
+
output_md += "**Ingredients:**\n" + "\n".join(f"- {item}" for item in recipe.ingredients) + "\n\n"
|
| 288 |
+
|
| 289 |
+
if recipe.instructions:
|
| 290 |
+
output_md += "**Instructions:**\n" + "\n".join(f"{i}. {step}" for i, step in enumerate(recipe.instructions, 1)) + "\n"
|
| 291 |
+
|
| 292 |
+
output_md += "\n---\n"
|
| 293 |
+
|
| 294 |
+
return output_md
|
| 295 |
+
|
| 296 |
+
# Launch the Gradio app
|
| 297 |
+
iface = gr.Interface(
|
| 298 |
+
fn=run_dinner_plan,
|
| 299 |
+
inputs=gr.Checkbox(label="Try Something New? (Searches the web for one recipe)", value=False),
|
| 300 |
+
outputs=gr.Markdown(label="Dinner Suggestions", sanitize_html=False),
|
| 301 |
+
title="AI Dinner Planner",
|
| 302 |
+
description="Let the AI plan your next three dinners. Check the box to have the agent search the web for one new recipe to include in the suggestions.",
|
| 303 |
+
allow_flagging="never",
|
| 304 |
+
examples=[[False], [True]]
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
iface.launch()
|