AI-based Recipe Generator Python
👤 Sharing: AI
```python
import random
class RecipeGenerator:
"""
A simple AI-based recipe generator. It uses a basic, hardcoded knowledge base
to suggest ingredients and cooking methods. Not truly "AI" but demonstrates
the core concept.
"""
def __init__(self):
self.ingredients = {
"protein": ["chicken", "beef", "tofu", "lentils", "fish", "pork"],
"vegetable": ["broccoli", "carrots", "onions", "peppers", "spinach", "tomatoes", "mushrooms"],
"grain": ["rice", "pasta", "quinoa", "couscous", "bread"],
"spice": ["garlic", "ginger", "cumin", "paprika", "oregano", "basil", "chili powder", "turmeric"],
"sauce": ["soy sauce", "tomato sauce", "pesto", "bbq sauce", "lemon juice", "olive oil", "vinegar"]
}
self.cooking_methods = ["bake", "stir-fry", "grill", "roast", "boil", "saute", "steam"]
def generate_recipe(self, num_ingredients=4, desired_flavor=None, desired_cook_time=None):
"""
Generates a random recipe.
Args:
num_ingredients (int): The number of ingredients to include in the recipe. Defaults to 4.
desired_flavor (str, optional): A desired flavor profile (e.g., "spicy", "sweet"). This is currently ignored
but included for potential future expansion.
desired_cook_time (int, optional): Desired cooking time in minutes. This is currently ignored
but included for potential future expansion.
Returns:
dict: A dictionary containing the recipe name, ingredients, and cooking method.
"""
chosen_ingredients = {}
for category in self.ingredients:
chosen_ingredients[category] = random.choice(self.ingredients[category])
# Ensure at least one of each type is included in the final recipe if the desired number
# of total ingredients allows for it.
available_ingredients = []
for category, ingredient in chosen_ingredients.items():
available_ingredients.append(ingredient)
num_additional_ingredients = max(0,num_ingredients - len(chosen_ingredients)) # how many more beyond the chosen category ingredients we need
additional_ingredients = []
all_ingredients_list = []
for k,v in self.ingredients.items():
all_ingredients_list.extend(v) #make a list of all the ingredients
for _ in range(num_additional_ingredients):
additional_ingredients.append(random.choice(all_ingredients_list))
recipe_ingredients = available_ingredients + additional_ingredients
random.shuffle(recipe_ingredients)
cooking_method = random.choice(self.cooking_methods)
recipe_name = f"{' '.join(recipe_ingredients[:2]).title()} {cooking_method.title()}"
#recipe_name = "Random Recipe" # Simpler, less descriptive recipe name
recipe = {
"name": recipe_name,
"ingredients": recipe_ingredients,
"cooking_method": cooking_method
}
return recipe
def display_recipe(self, recipe):
"""
Prints the recipe in a user-friendly format.
Args:
recipe (dict): The recipe dictionary generated by generate_recipe().
"""
print("Recipe Name:", recipe["name"])
print("\nIngredients:")
for ingredient in recipe["ingredients"]:
print(f"- {ingredient}")
print("\nCooking Method:", recipe["cooking_method"])
print("\nEnjoy!")
if __name__ == "__main__":
generator = RecipeGenerator()
# Get user input for number of ingredients
try:
num_ingredients = int(input("How many ingredients would you like in your recipe (default is 4): ") or 4) # Default to 4 if input is empty or invalid
if num_ingredients <= 0:
print("Number of ingredients must be greater than 0. Using default (4).")
num_ingredients = 4
except ValueError:
print("Invalid input for number of ingredients. Using default (4).")
num_ingredients = 4
recipe = generator.generate_recipe(num_ingredients=num_ingredients)
generator.display_recipe(recipe)
```
👁️ Viewed: 8
Comments