File size: 31,773 Bytes
af0717b
28034fc
af0717b
28034fc
 
 
 
 
 
 
 
a73c05e
28034fc
 
 
 
 
af0717b
 
028192b
831ca1d
28034fc
 
028192b
 
 
0b6069d
 
 
 
 
14613dc
0b6069d
 
 
 
14613dc
 
 
 
 
 
 
 
 
 
0b6069d
 
 
 
14613dc
0b6069d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11b4700
 
 
 
 
 
 
 
 
 
28034fc
 
 
 
 
 
a73c05e
831ca1d
a73c05e
28034fc
831ca1d
 
28034fc
11b4700
 
 
 
 
0b6069d
 
11b4700
28034fc
 
 
 
 
 
a73c05e
 
28034fc
 
 
14613dc
28034fc
 
 
 
 
 
 
af0717b
28034fc
 
 
 
 
 
 
 
 
 
 
 
 
a73c05e
 
28034fc
 
 
 
a73c05e
28034fc
 
 
 
 
a73c05e
 
28034fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af0717b
 
 
 
 
 
 
 
 
28034fc
 
 
 
a73c05e
 
28034fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af0717b
28034fc
 
 
 
 
 
 
 
af0717b
 
28034fc
 
 
 
 
 
 
 
 
 
 
 
831ca1d
a73c05e
 
 
831ca1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a73c05e
28034fc
831ca1d
28034fc
831ca1d
 
 
 
 
 
a73c05e
 
 
 
 
 
 
 
28034fc
 
 
 
831ca1d
 
 
 
 
28034fc
831ca1d
 
 
 
 
 
28034fc
831ca1d
28034fc
831ca1d
 
 
 
 
 
28034fc
831ca1d
28034fc
 
 
 
831ca1d
 
28034fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a73c05e
 
df66bd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b39eb31
 
 
 
df66bd7
 
b39eb31
 
df66bd7
 
a73c05e
df66bd7
a73c05e
 
df66bd7
 
 
 
 
 
 
 
 
a73c05e
df66bd7
 
a73c05e
 
 
 
df66bd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a73c05e
 
28034fc
 
a73c05e
28034fc
 
 
 
a73c05e
 
28034fc
 
 
 
 
 
 
 
a73c05e
28034fc
 
a73c05e
 
 
 
 
 
28034fc
 
 
 
 
a73c05e
 
28034fc
 
 
 
 
 
 
 
 
 
 
 
 
 
a73c05e
 
 
 
28034fc
a73c05e
 
 
 
 
 
 
 
c1e7f60
a73c05e
c1e7f60
34b43a2
c1e7f60
34b43a2
c1e7f60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34b43a2
c1e7f60
 
 
 
 
 
34b43a2
c1e7f60
a73c05e
 
 
 
 
 
 
 
 
 
 
 
 
34b43a2
 
 
 
 
 
a73c05e
34b43a2
 
 
a73c05e
 
c1e7f60
 
34b43a2
 
a73c05e
28034fc
028192b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# 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 = '''<prompt>
  <role_definition>
    <role>You are an expert recipe parsing AI model.</role>
    <purpose>Your primary function is to meticulously analyze raw text from various sources and transform it into structured recipe objects.</purpose>
  </role_definition>

  <instructions>
    <item>Your output MUST be a valid JSON array containing one or more recipe objects.</item>
    <item>Each recipe object MUST include these fields:</item>
    <field name="name">A descriptive name for the recipe (required)</field>
    <field name="content">The original recipe text (can be empty string)</field>
    <field name="description">A brief summary (can be empty string)</field>
    <field name="ingredients">Array of ingredients with quantities (can be empty array)</field>
    <field name="instructions">Array of cooking steps (can be empty array)</field>
    <field name="cooking_time">Total time (optional)</field>
    <field name="servings">Number of servings (optional integer)</field>
    <field name="source_url">Source URL if from web (optional)</field>
    <item>Even if some information is missing, always return a complete object with default values.</item>
  </instructions>

  <user_query_template>
    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}
  </user_query_template>
</prompt>'''

    default_web_search = '''<prompt>
  <role_definition>
    <role>You are a creative and effective search query generator for finding recipes online.</role>
    <purpose>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.</purpose>
  </role_definition>

  <instructions>
    <item>Your output MUST be only the search query text.</item>
    <item>Consider all aspects of the user's preferences, including cuisine and dietary restrictions.</item>
    <item>Avoid generating queries too similar to existing recipes.</item>
  </instructions>

  <user_query_template>
    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.
  </user_query_template>
</prompt>'''

    # 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("""
        <style>
        #robot-chef {
            text-align: center;
            padding: 20px;
            margin: 20px auto;
            max-width: 300px;
        }
        .robot-container {
            background: #f0f0f0;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .robot {
            font-size: 40px;
            animation: stir 2s infinite;
            display: inline-block;
            transform-origin: bottom center;
        }
        .pot {
            font-size: 40px;
            margin-left: 10px;
        }
        @keyframes stir {
            0% { transform: rotate(0deg); }
            25% { transform: rotate(-20deg); }
            75% { transform: rotate(20deg); }
            100% { transform: rotate(0deg); }
        }
        </style>
        <div id="robot-chef">
            <div class="robot-container">
                <div class="robot">πŸ€–</div>
                <div class="pot">πŸ₯˜</div>
                <p>Cooking up your dinner plan...</p>
            </div>
        </div>
    """, 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()