Spaces:
Running
Running
File size: 18,791 Bytes
13be71d c30b4ba dc464ea c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 c30b4ba 753f6f9 c30b4ba 753f6f9 dc464ea c30b4ba dc464ea fbaab7a dc464ea 6f35cc8 dc464ea 753f6f9 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 753f6f9 c30b4ba 753f6f9 c30b4ba 0dbd4b2 c30b4ba 0dbd4b2 | 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 | import google.generativeai as genai
import json
from difflib import get_close_matches
import os
from dotenv import load_dotenv
from difflib import SequenceMatcher
load_dotenv()
genai.configure(api_key=os.getenv("EXTRACTION_API_KEY"))
# Define categories from dataset
RECIPE_CATEGORIES = [
"frozen desserts",
"chicken breast",
"beverages",
"soy/tofu",
"vegetable",
"pie",
"chicken",
"dessert",
"southwestern u.s.",
"sauces",
"stew",
"black beans",
"< 60 mins",
"lactose free",
"yeast breads",
"whole chicken",
"cheesecake",
"free of...",
"brazilian",
"breakfast",
"breads",
"bar cookie",
"brown rice",
"oranges",
"pork",
"low protein",
"asian",
"potato",
"cheese",
"halibut",
"meat",
"lamb/sheep",
"very low carbs",
"spaghetti",
"scones",
"drop cookies",
"lunch/snacks",
"beans",
"punch beverage",
"pineapple",
"quick breads",
"sourdough breads",
"curries",
"chicken livers",
"coconut",
"savory pies",
"poultry",
"steak",
"healthy",
"rice",
"apple",
"spreads",
"crab",
"jellies",
"pears",
"chowders",
"cauliflower",
"candy",
"chutneys",
"white rice",
"tex mex",
"bass",
"fruit",
"european",
"smoothies",
"manicotti",
"onions",
"new zealand",
"chicken thigh & leg",
"indonesian",
"greek",
"corn",
"lentil",
"long grain rice",
"southwest asia (middle east)",
"spanish",
"dutch",
"gelatin",
"tuna",
"citrus",
"berries",
"peppers",
"salad dressings",
"clear soup",
"mexican",
"raspberries",
"crawfish",
"beef organ meats",
"lobster",
"strawberry",
"shakes",
"short grain rice",
"< 15 mins",
"german",
"one dish meal",
"thai",
"cajun",
"russian",
"melons",
"swiss",
"papaya",
"veal",
"orange roughy",
"canadian",
"caribbean",
"mussels",
"medium grain rice",
"japanese",
"penne",
"elk",
"colombian",
"gumbo",
"roast beef",
"perch",
"vietnamese",
"rabbit",
"lebanese",
"turkish",
"kid friendly",
"whole turkey",
"chinese",
"grains",
"yam/sweet potato",
"meatloaf",
"trout",
"african",
"ham",
"goose",
"pasta shells",
"stocks",
"meatballs",
"whole duck",
"scandinavian",
"greens",
"catfish",
"duck breasts",
"polish",
"deer",
"wild game",
"pheasant",
"hungarian",
"no shell fish",
"collard greens",
"tilapia",
"quail",
"moroccan",
"squid",
"korean",
"plums",
"danish",
"creole",
"mahi mahi",
"tarts",
"hawaiian",
"austrian",
"moose",
"native american",
"swedish",
"norwegian",
"ethiopian",
"belgian",
"australian",
"bear",
"scottish",
"tempeh",
"cuban",
"spinach",
"turkey breasts",
"cantonese",
"tropical fruits",
"peanut butter",
"szechuan",
"portuguese",
"costa rican",
"duck",
"nuts",
"filipino",
"pot pie",
"polynesian",
"mango",
"cherries",
"egyptian",
"chard",
"lime",
"lemon",
"kiwifruit",
"whitefish",
"south american",
"malaysian",
"octopus",
"nigerian",
"south african",
"nepalese",
"palestinian",
"czech",
"avocado",
"iraqi",
"pakistani",
"chocolate chip cookies",
"finnish",
"puerto rican",
"cambodian",
"honduran",
"mongolian",
"peruvian",
"turkey gravy",
"somalian",
"ice cream",
"oatmeal",
"artichoke",
"indian",
"grapes",
"macaroni and cheese",
"mashed potatoes",
"pumpkin",
"guatemalan"
]
def find_closest_category(category):
"""Find the closest matching category from the dataset."""
if not category:
return ""
# First check for exact match
if category.lower() in [c.lower() for c in RECIPE_CATEGORIES]:
return next(c for c in RECIPE_CATEGORIES if c.lower() == category.lower())
# For compound categories, check parts
category_parts = category.lower().split()
if len(category_parts) == 1 and category_parts[0] in [c.lower() for c in RECIPE_CATEGORIES]:
# If the input is a single word that exists in the category list, return it
return next(c for c in RECIPE_CATEGORIES if c.lower() == category_parts[0])
for part in category_parts:
matches = [c for c in RECIPE_CATEGORIES if part in c.lower()]
if matches:
return matches[0]
# If no matches found, use difflib to find closest match
matches = get_close_matches(category.lower(), [c.lower() for c in RECIPE_CATEGORIES], n=1, cutoff=0.75)
if matches:
closest_match = matches[0]
# Check if the closest match is close enough (similarity score > 0.8)
if SequenceMatcher(None, category.lower(), closest_match).ratio() > 0.8:
return next(c for c in RECIPE_CATEGORIES if c.lower() == closest_match)
else:
return ""
# If no match is found at all, return empty string
return ""
def extract_recipe_attributes(text):
messages = [
{"role": "system", "content": "You are an assistant that extracts recipe attributes from user input. If the input contains an uncommon or unrecognized category, add relevant general keywords based on common culinary types, such as 'beverages' for drinks, 'dessert' for sweets, etc."},
{"role": "user", "content": f"""
From the given text, identify:
- **category**: The main name or type of the recipe (like "chicken", "ice cream").
- **calories**: Number of calories, if mentioned.
- **time**: Time to cook, in minutes.
- **ingredients**: List of ingredients mentioned in the text. Include basic cooking ingredients even if not explicitly mentioned (e.g., if it's a cake, include "flour", "sugar" as basic ingredients).
- **keywords**: Important words related to the recipe. If the category is not common (like "noodles" or "biryani"), include relevant characteristics (e.g., "asian", "main course", "stir fry", "quick meal", "wheat based", "high protein", etc).
- **keywords_name**: List of individual words from the category/name. For uncommon categories, include descriptive terms and related categories (e.g., for "noodles": ["asian", "pasta", "wheat", "main dish"]).
Examples:
---
Input: "noodles"
Output: {{
"category": "",
"calories": "",
"time": "",
"ingredients": ["noodles", "oil", "salt"],
"keywords": ["asian", "stir fry", "wheat based", "quick meal", "main course", "pasta", "noodles"],
"keywords_name": ["asian", "pasta", "main dish", "wheat"]
}}
---
Input: "biryani"
Output: {{
"category": "",
"calories": "",
"time": "",
"ingredients": ["rice", "spices", "oil", "onions", "garlic"],
"keywords": ["rice", "indian", "spicy", "main course", "one dish meal", "biryani"],
"keywords_name": ["rice", "indian", "spicy"]
}}
---
Input: "I wish to cook chicken soup which contains around 200 calories within 30 mins"
Output: {{
"category": "chicken",
"calories": "200",
"time": "30",
"ingredients": ["chicken", "water", "vegetables", "salt", "pepper"],
"keywords": ["chicken", "soup", "200 calories", "30 mins"],
"keywords_name": ["chicken", "soup"]
}}
---
Input: "beef tacos"
Output: {{
"category": "beef organ meats",
"calories": "",
"time": "",
"ingredients": ["beef", "tortillas", "lettuce", "tomatoes", "cheese", "onions"],
"keywords": ["mexican", "beef", "spicy", "snack", "tortilla", "street food"],
"keywords_name": ["mexican", "beef", "snack"]
}}
---
Input: "chocolate cake with milk and sugar"
Output: {{
"category": "dessert",
"calories": "",
"time": "",
"ingredients": ["chocolate", "milk", "sugar", "flour", "eggs", "butter"],
"keywords": ["dessert", "baking", "sweet", "cake"],
"keywords_name": ["dessert", "cake", "chocolate"]
}}
---
Input: "tea with milk, sugar, water"
Output: {{
"category": "",
"calories": "",
"time": "",
"ingredients": ["tea", "milk", "sugar", "water"],
"keywords": ["milk", "sugar", "water", "beverages"],
"keywords_name": [""]
}}
---
Input: "I have basil, tomato and clove what can i make in 30 minutes"
Output: {{
"category": "",
"calories": "",
"time": "30",
"ingredients": ["basil", "tomato", "clove"],
"keywords": ["quick meal", "30 minutes", "italian"],
"keywords_name": [""]
}}
---
Now process this input:
Input: "{text}"
Output:
"""}
]
# Send the prompt to OpenAI API
prompt = ""
for message in messages:
if message["role"] == "system":
prompt += message["content"] + "\n\n"
else:
prompt += message["content"]
# Configure the Gemini model
model = genai.GenerativeModel('gemini-2.5-flash')
# Generate response
response = model.generate_content(
prompt,
generation_config=genai.types.GenerationConfig(
temperature=0,
max_output_tokens=500, # Safety net, not a hard limit
top_p=1,
response_mime_type="application/json" # 🔥 FORCES JSON OUTPUT
))
# Process the response
output_text = response.text.strip()
# Check if output is wrapped in markdown code blocks and extract the JSON if needed
if output_text.strip().startswith('```') and '```' in output_text:
import re
match = re.search(r'```(?:json)?\n(.*?)\n```', output_text, re.DOTALL)
if match:
output_text = match.group(1).strip()
try:
result = json.loads(output_text)
# Update category with closest match from dataset
original_category = result["category"]
matched_category = find_closest_category(original_category)
if matched_category:
result["category"] = matched_category
if original_category != matched_category:
result["keywords_name"] = matched_category.split()
else:
result["category"] = ""
# Add additional context-based keywords and ingredients if category is empty
if "coffee" in text.lower() or "latte" in text.lower():
result["keywords"] = result.get("keywords", []) + ["coffee", "beverages", "caffeinated", "hot drink"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "caffeinated", "coffee"]
result["ingredients"] = result.get("ingredients", []) + ["coffee beans", "water"]
elif "smoothie bowl" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverages", "healthy", "smoothie bowl"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "smoothie bowl"]
result["ingredients"] = result.get("ingredients", []) + ["fruits", "yogurt", "granola"]
elif "kombucha" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverage", "fermented", "kombucha"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "kombucha"]
result["ingredients"] = result.get("ingredients", []) + ["tea", "sugar", "SCOBY"]
elif "herbal tea" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverages", "caffeine-free", "herbal tea"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "herbal tea"]
result["ingredients"] = result.get("ingredients", []) + ["herbs", "water"]
elif "seaweed" in text.lower():
result["keywords"] = result.get("keywords", []) + ["ingredient", "seafood", "seaweed"]
result["keywords_name"] = result.get("keywords_name", []) + ["seaweed"]
result["ingredients"] = result.get("ingredients", []) + ["seaweed"]
elif "vegan cheese" in text.lower():
result["keywords"] = result.get("keywords", []) + ["dairy-free", "vegan", "cheese"]
result["keywords_name"] = result.get("keywords_name", []) + ["vegan cheese"]
result["ingredients"] = result.get("ingredients", []) + ["cashews", "nutritional yeast", "coconut oil"]
elif "air fryer" in text.lower():
result["keywords"] = result.get("keywords", []) + ["cooking method", "air fryer", "healthy"]
result["keywords_name"] = result.get("keywords_name", []) + ["air fryer"]
result["ingredients"] = result.get("ingredients", []) # Ingredients vary with recipe, left blank
elif "instant pot" in text.lower():
result["keywords"] = result.get("keywords", []) + ["cooking method", "instant pot", "pressure cooker"]
result["keywords_name"] = result.get("keywords_name", []) + ["instant pot"]
result["ingredients"] = result.get("ingredients", []) # Ingredients vary with recipe, left blank
elif "sous vide" in text.lower():
result["keywords"] = result.get("keywords", []) + ["cooking method", "sous vide", "precision cooking"]
result["keywords_name"] = result.get("keywords_name", []) + ["sous vide"]
result["ingredients"] = result.get("ingredients", []) # Ingredients vary with recipe, left blank
elif "paleo" in text.lower():
result["keywords"] = result.get("keywords", []) + ["diet", "paleo", "low-carb"]
result["keywords_name"] = result.get("keywords_name", []) + ["paleo"]
result["ingredients"] = result.get("ingredients", []) # Ingredients vary with recipe, left blank
elif "fodmap" in text.lower():
result["keywords"] = result.get("keywords", []) + ["diet", "fodmap", "digestive health"]
result["keywords_name"] = result.get("keywords_name", []) + ["fodmap"]
result["ingredients"] = result.get("ingredients", []) # Ingredients vary with recipe, left blank
elif "cold brew" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverages", "caffeinated", "cold coffee"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "cold brew"]
result["ingredients"] = result.get("ingredients", []) + ["coffee grounds", "water"]
elif "matcha" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverages", "green tea", "matcha"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "matcha"]
result["ingredients"] = result.get("ingredients", []) + ["matcha powder", "water", "milk"]
elif "smoothie" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverages", "healthy", "smoothie"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "smoothie"]
result["ingredients"] = result.get("ingredients", []) + ["fruits", "milk", "yogurt"]
elif "protein shake" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverages", "high protein", "shake"]
result["keywords_name"] = result.get("keywords_name", []) + ["beverages", "protein shake"]
result["ingredients"] = result.get("ingredients", []) + ["protein powder", "milk", "banana"]
elif "oat milk" in text.lower() or "almond milk" in text.lower():
result["keywords"] = result.get("keywords", []) + ["dairy-free", "vegan", "plant-based milk"]
result["keywords_name"] = result.get("keywords_name", []) + ["oat milk" if "oat" in text.lower() else "almond milk"]
result["ingredients"] = result.get("ingredients", []) + ["oats" if "oat" in text.lower() else "almonds", "water"]
elif "zoodles" in text.lower():
result["keywords"] = result.get("keywords", []) + ["low carb", "gluten-free", "vegetable noodles", "noodles"]
result["keywords_name"] = result.get("keywords_name", []) + ["zoodles", "noodles"]
result["ingredients"] = result.get("ingredients", []) + ["zucchini"]
elif "avocado toast" in text.lower():
result["keywords"] = result.get("keywords", []) + ["breakfast", "healthy", "avocado"]
result["keywords_name"] = result.get("keywords_name", []) + ["avocado toast"]
result["ingredients"] = result.get("ingredients", []) + ["avocado", "bread"]
elif "golden milk" in text.lower():
result["keywords"] = result.get("keywords", []) + ["beverage", "turmeric", "anti-inflammatory"]
result["keywords_name"] = result.get("keywords_name", []) + ["golden milk"]
result["ingredients"] = result.get("ingredients", []) + ["turmeric", "milk", "honey", "spices"]
# other cases...
except json.JSONDecodeError:
result = {"error": "Failed to parse JSON", "output": output_text}
return result
# Example usage:
if __name__ == '__main__':
test_cases = [
# "Something i can make with chocolate, milk and cheese",
# "I have basil, tomato and clove what can i make in 30 minutes",
# "beef stew with potatoes, carrots, and herbs",
# "chocolate cake with milk and sugar",
# "avocado smoothie with milk and ice",
"noodles",
# "need a pasta recipe",
# "looking for a chicken dish",
# "want to make something with rice",
# "need a dessert recipe",
# "biryani",
# "30 mins",
# "chole bhature",
# "give some recipes involving almonds",
# "latte with foam, coffee, milk",
# "cold drink beverage",
# "beans",
# "coffee",
# "latte",
# "something involving nuts",
# "i wish to cook something with crab",
# "livers",
# "popcorn",
# "beef stew with potatoes, carrots, and herbs.",
# "dessert with chocolate, brownie, cake"
# "chocolate, brownie, cake, brown sugar",
# "avocado smoothie, avocado, milk, ice",
# "momo, momo, sauce",
]
for test_input in test_cases:
print(f"\nTesting: {test_input}")
result = extract_recipe_attributes(test_input)
print(json.dumps(result, indent=2)) |