-
Notifications
You must be signed in to change notification settings - Fork 0
/
recipe_parser.py
36 lines (29 loc) · 1.34 KB
/
recipe_parser.py
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
def parse_recipe(recipe_text):
"""Parses the recipe text generated by GPT to extract relevant fields except Meal_ID."""
recipe = {}
lines = recipe_text.split("\n")
ingredient_lines = [] # to collect ingredient lines
collecting_ingredients = False
for line in lines:
if ":" in line:
key, value = line.split(":", 1)
key = key.strip()
value = value.strip().replace("kcal", "").replace("~", "").strip() # Removing unwanted characters
else:
if collecting_ingredients:
ingredient_lines.append(line.strip('- '))
continue
if key == "Ingredients":
collecting_ingredients = True
continue
elif key in ["Meal Name", "Calories", "Protein", "Carbs", "Fats", "Meal_Type"]:
collecting_ingredients = False
recipe[key] = value
recipe["Ingredients"] = ", ".join(ingredient_lines) # converting ingredient list to a string
# Check if all the essential keys (excluding Meal_ID) are present; if not, return None
essential_keys = ["Meal Name", "Calories", "Protein", "Carbs", "Fats", "Ingredients", "Meal_Type"]
missing_keys = [key for key in essential_keys if key not in recipe]
if missing_keys:
print(f"Missing keys: {missing_keys}")
return None
return recipe