-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
208 lines (164 loc) · 7 KB
/
main.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
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
from dotenv import load_dotenv
import os
import requests
from database import *
#Documentation for API
#https://developer.edamam.com/edamam-docs-recipe-api-v1
#Load environment variables from .env file
load_dotenv()
#Get app id from environment variables
app_id = os.getenv("APP_ID")
#Get api key from environment variables
api_key = os.getenv("API_KEY")
#Create/user username to save favorite recipes
allUsers = get_all_users()
User = input("What is your username: ")
if User not in [user[1] for user in allUsers]:
add_user(User)
#Get user id
user_id = get_user_id_by_username(User)
#Decide between favorite recipe or new one
if User in [user[1] for user in allUsers]:
userChoice = input("Would you like to view favorite recipes or would you like to find a new one (1. favorite 2. new): ")
if userChoice == '1':
# Make sure user has favorite recipes
favorite_recipes = get_user_recipes(user_id)
if not favorite_recipes:
print("You have no favorite recipes.")
else:
print(f"Your favorite recipes: {favorite_recipes}")
userChoice = input("Would you like to find a new recipe (y/n): ")
if userChoice.lower() != 'y':
exit()
#Ask user what they are looking for in a recipe
foodChoice = input("Enter what food you want a recipe for: ")
proteinAmount = input("Enter how much protein do you need (Ex: 30): ")
calorieChoice = input("Enter the range of calories you want (Ex: 300-400): ")
#Calls api
response = requests.get(f"https://api.edamam.com/search?app_id={app_id}&app_key={api_key}&q={foodChoice}&nutrients[PROCNT]={proteinAmount}&calories={calorieChoice}", timeout=5)
data = response.json()
#Create recipe object for each recipe
class Recipes:
def __init__(self, recipe_num, recipe_name, ingredients, instructions, calories, protein, carbohydrates, fat, vitamins, minerals):
self.recipe_number = recipe_num
self.recipe_name = recipe_name
self.ingredients = ingredients
self.instructions = instructions
self.calories = calories
self.protein = protein
self.carbohydrates = carbohydrates
self.fat = fat
self.vitamins = vitamins
self.minerals = minerals
#Extract individual information about nutrients
def extract_nutritional_info(recipe_data):
nutrients = recipe_data.get('totalNutrients', {})
#Extract the specific nutrients you need
protein = nutrients.get('PROCNT', {}).get('quantity', 0)
carbohydrates = nutrients.get('CHOCDF', {}).get('quantity', 0)
fat = nutrients.get('FAT', {}).get('quantity', 0)
vitamins = {}
minerals = {}
for key, nutrient_data in nutrients.items():
if 'VITA' in key or 'VITB' in key or 'VITC' in key:
vitamins[key] = nutrient_data.get('quantity', 0)
elif 'CA' in key or 'FE' in key or 'MG' in key:
minerals[key] = nutrient_data.get('quantity', 0)
return protein, carbohydrates, fat, calories, vitamins, minerals
#Create an array to store recipe objects
recipes_list = []
# Dictionary that maps vitamin abbreviations to their full names
vitaminAndMineral_Names = {
'VITA_RAE': 'Vitamin A',
'VITC': 'Vitamin C',
'VITB6A': 'Vitamin B6',
'VITB12': 'Vitamin B12',
'CA': 'Calcium',
'MG': 'Magnesium',
'FE': 'Iron',
'FOLDFE': 'Folate',
}
#Function to display and add recipe to favorites
def display_and_add_to_favorites(user_id, recipes_list):
for idx, recipe in enumerate(recipes_list):
print(f"Recipe Number {idx + 1}:")
print("Recipe Name:", recipe.recipe_name)
print("Instructions:", recipe.instructions)
print("Ingredients:")
for ingredient in recipe.ingredients:
print("- " + ingredient)
print("\nNutritional Information:")
print(f"Protein: {recipe.protein:.2f} grams")
print(f"Carbohydrates: {recipe.carbohydrates:.2f} grams")
print(f"Fat: {recipe.fat:.2f} grams")
print(f"Calories: {recipe.calories:.2f}")
print("Vitamins:")
for nutrient, value in recipe.vitamins.items():
nutrient_name = vitaminAndMineral_Names.get(nutrient, nutrient)
if nutrient_name == 'ENERC_KCAL':
continue
print(f"- {nutrient_name}: {value:.2f}")
print("Minerals:")
for nutrient, value in recipe.minerals.items():
nutrient_name = vitaminAndMineral_Names.get(nutrient, nutrient)
if nutrient_name == 'ENERC_KCAL':
continue
print(f"- {nutrient_name}: {value:.2f}")
print("\n\n\n")
while True:
num = int(input("Enter the number of the recipe you want to favorite (or 0 to exit): "))
if num == 0:
break
elif 1 <= num <= len(recipes_list):
#Convert the list of ingredients to a string, separated by newlines
ingredients_str = '\n'.join(recipe.ingredients)
recipe = recipes_list[num - 1]
add_to_favorite_recipes(user_id, recipe.recipe_name, ingredients_str, recipe.instructions, recipe.calories, recipe.protein, recipe.carbohydrates, recipe.fat, recipe.vitamins, recipe.minerals)
print(f"Recipe {num} has been added to your favorites.")
else:
print("Invalid recipe number. Please enter a valid recipe number or 0 to exit.")
#Loop through the recipes
currentRecipe = 0
for recipe_data in data.get('hits', []):
recipe = recipe_data.get('recipe')
label = recipe['label']
image = recipe['image']
source = recipe['source']
url = recipe['url']
calories = recipe['calories']
ingredients = recipe['ingredientLines']
#Extract nutritional information
nutrients = recipe['totalNutrients']
#Extract specific nutritional information using function
protein, carbohydrates, fat, calories, vitamins, minerals = extract_nutritional_info(recipe)
#Display recipe details
print("Recipe Name:", label)
print("Image URL:", image)
print("Source:", source)
print("URL:", url + '\n\n')
print("Calories:", calories)
print("Ingredients:")
for ingredient in ingredients:
print("- " + ingredient)
#Display nutritional information
print("\nNutritional Information:")
for nutrient_name, nutrient_data in nutrients.items():
nutrient_label = nutrient_data['label']
nutrient_quantity = nutrient_data['quantity']
nutrient_unit = nutrient_data['unit']
print(f"- {nutrient_label}: {nutrient_quantity:.2f} {nutrient_unit}")
#Create a recipe object and add it to the list
recipe_obj = Recipes(currentRecipe, label, ingredients, url, calories, protein, carbohydrates, fat, vitamins, minerals)
recipes_list.append(recipe_obj)
currentRecipe += 1
#Add to favorite recipes
end = True
while end == True:
userChoice = input("Would you like to add a recipe to favorites? (y/n): ")
if userChoice == 'y':
display_and_add_to_favorites(user_id, recipes_list)
end = False
elif userChoice == 'n':
exit()
else:
print("Invalid choice.")