dschandra commited on
Commit
e5a7e53
·
verified ·
1 Parent(s): 804f756

Update nutritional_analysis.py

Browse files
Files changed (1) hide show
  1. nutritional_analysis.py +21 -20
nutritional_analysis.py CHANGED
@@ -1,8 +1,8 @@
1
  import requests
2
 
3
- def get_nutritional_info(food_item):
4
  """
5
- Fetch nutritional details dynamically for the detected food item using the Nutritionix API.
6
  """
7
  api_url = "https://trackapi.nutritionix.com/v2/natural/nutrients"
8
  app_id = "8af8f051" # Nutritionix Application ID
@@ -13,22 +13,23 @@ def get_nutritional_info(food_item):
13
  "x-app-key": app_key,
14
  "Content-Type": "application/json"
15
  }
16
-
17
- payload = {"query": food_item}
18
- response = requests.post(api_url, json=payload, headers=headers)
19
 
20
- # Parse the response
21
- if response.status_code == 200:
22
- result = response.json()
23
- if "foods" in result and len(result["foods"]) > 0:
24
- food_details = result["foods"][0]
25
- return {
26
- "Energy (kcal)": food_details.get("nf_calories", 0),
27
- "Protein (g)": food_details.get("nf_protein", 0),
28
- "Carbs (g)": food_details.get("nf_total_carbohydrate", 0),
29
- "Fiber (g)": food_details.get("nf_dietary_fiber", 0),
30
- "Fat (g)": food_details.get("nf_total_fat", 0),
31
- "Sugar (g)": food_details.get("nf_sugars", 0)
32
- }
33
- # Return an error if data is unavailable
34
- return {"Error": f"Failed to fetch data for {food_item}"}
 
 
 
 
 
1
  import requests
2
 
3
+ def get_nutritional_info(food_items):
4
  """
5
+ Fetch nutritional details dynamically using the Nutritionix API.
6
  """
7
  api_url = "https://trackapi.nutritionix.com/v2/natural/nutrients"
8
  app_id = "8af8f051" # Nutritionix Application ID
 
13
  "x-app-key": app_key,
14
  "Content-Type": "application/json"
15
  }
 
 
 
16
 
17
+ nutrition_data = {}
18
+ for food in food_items:
19
+ payload = {"query": food}
20
+ response = requests.post(api_url, json=payload, headers=headers)
21
+ if response.status_code == 200:
22
+ result = response.json()
23
+ if "foods" in result and len(result["foods"]) > 0:
24
+ food_details = result["foods"][0]
25
+ nutrition_data[food] = {
26
+ "Energy (kcal)": food_details.get("nf_calories", 0),
27
+ "Protein (g)": food_details.get("nf_protein", 0),
28
+ "Carbs (g)": food_details.get("nf_total_carbohydrate", 0),
29
+ "Fiber (g)": food_details.get("nf_dietary_fiber", 0),
30
+ "Fat (g)": food_details.get("nf_total_fat", 0),
31
+ "Sugar (g)": food_details.get("nf_sugars", 0)
32
+ }
33
+ else:
34
+ nutrition_data[food] = {"Error": f"Failed to fetch data for {food}"}
35
+ return nutrition_data