def nutritionix_wrapper(label): """ This function will take a label and give out the weight to calories ratio input: label (string) output: weight / calories (double) """ nutritionix_id = nutritionix_ID(label) nix = Nutritionix(app_id="8dfdbdb1", api_key="66ad2fcd0f25722ca73662505e9fd492") nutritionix_info = nix.item(id=nutritionix_id).json() weight_key = 'nf_serving_weight_grams' calories_key = 'nf_calories' weight = nutritionix_info[weight_key] calories = nutritionix_info[calories_key] if weight is not None and calories is not None: print('ME GOOD') ratio = calories / weight return ratio print('ME BAD') return 0
def result(): print(request.form['out']) chosenLabel = request.form['out'] nix = Nutritionix(app_id="b3151f58", api_key="f9c4b99b77d236006962c81e4ddbffee") apple = nix.search(chosenLabel) results = apple.json() resultsItem = nix.item(id=results['hits'][0]['fields']['item_id']).json() return render_template('description.html', sum=wikipedia.summary(chosenLabel, sentences=3), calories=str(resultsItem['nf_calories']), serving=str(resultsItem['nf_serving_weight_grams']))
def nutritionix_calories(nutritionix_id): """ This function will take an ID and return calories | Useful for the total count of calories per user input: id (string) output: calories """ nix = Nutritionix(app_id="8dfdbdb1", api_key="66ad2fcd0f25722ca73662505e9fd492") calories_key = 'nf_calories' nutritionix_info = nix.item(id=nutritionix_id).json() calories = nutritionix_info[calories_key] if calories is not None: return calories else: return None
def FatFinder(string): num = 1 ###From https://github.com/leetrout/python-nutritionix### from nutritionix import Nutritionix api_key = "5fc43e41551148e7105f4c0b6e8cba31" app_id = "cd1f176e" nix = Nutritionix(app_id, api_key) stringsearch = nix.search(string, results=("0:"+str(num))).json() ### My Code ### item_id = stringsearch["hits"][0]["fields"]["item_id"] itemidsearch = nix.item(id=str(item_id)).json() itemfat = itemidsearch['nf_saturated_fat'] if itemfat is None: OUTPUT = "Please enter a food that contains Fat. " return OUTPUT else: return itemfat
def get_nutrient(food): """Hepler function to get raw data for a food from API. Arguments: food {string} -- food to be found Returns: detail {dictionary} -- raw data is store in the dictionary """ nix = Nutritionix(app_id=APP_ID, api_key="") a = nix.search(food, results="0:1").json() detail = {} if 'hits' in a: hits = a['hits'] try: item_id = hits[0]['_id'] detail = nix.item(id=item_id).json() except IndexError: pass detail["key_ingredient"] = food print(detail["key_ingredient"]) return detail
from flask import Flask, request, jsonify #sudo pip install flask-cors from flask_cors import CORS from nutritionix import Nutritionix nix = Nutritionix(app_id="67a461a2", api_key="e2e3a5f32358c6197ad841f6a0bbbb0d") app = Flask(__name__) CORS(app) #pizza = nix.search("pizza") #print nix.search('big mac', results="0:1").json() print nix.item(id="58bedf1bde25a28564cebeb9").json() @app.route('/', methods=['GET']) def home_page(): return "Hello, World!" @app.route('/hand_checker', methods=['POST']) def hand_checker(): # print request.form hand = request.form.getlist('hand[]') print hand #hand = ['1h 2h 1s 9d 13d'] return jsonify({'message': 'You have %s and %s!' % (hand[0], hand[1])}) if __name__ == '__main__':
"calories_from_fats,total_fat_grams,trans_fat_grams,saturated_fat_grams," "cholesterol_grams,sodium_grams,total_carbohydrates_grams," "dietary_fiber_grams,sugars_grams,protein_grams," "vitamin_a_dv,vitamin_c_dv,calcium_dv,iron_dv)" "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" ) #For each food item in our test list of food items for item in ifile: #0:2 means only get two items from the results list. food = nix.search(item, results="0:2").json() #if more than one item is returned food_list = food['hits'] for food_item in food_list: foodid = food_item['_id'] food_info = nix.item(id=foodid).json() #prep the data for insert food_data = food_info['item_id'], food_info['item_name'], food_info[ 'nf_calories'], food_info['nf_serving_size_qty'], food_info[ 'nf_serving_weight_grams'], food_info['nf_serving_size_unit'], food_info[ 'nf_calories_from_fat'], food_info['nf_total_fat'], food_info[ 'nf_trans_fatty_acid'], food_info['nf_saturated_fat'], food_info[ 'nf_cholesterol'], food_info['nf_sodium'], food_info[ 'nf_total_carbohydrate'], food_info[ 'nf_dietary_fiber'], food_info[ 'nf_sugars'], food_info[ 'nf_protein'], food_info[ 'nf_vitamin_a_dv'], food_info[ 'nf_vitamin_c_dv'], food_info[ 'nf_calcium_dv'], food_info[
from nutritionix import Nutritionix nix = Nutritionix(app_id="a43c505b", api_key="ce2e2ad8e38bbf9dbb2043575c591179") a = nix.search("pizza", results="0:1").json() b = a['hits'] _id = b[0] calorie = nix.item(id=_id['_id']).json()['nf_calories']
class FoodNutrition(object): def __init__(self, nutritionix_id = "46e19a0a", \ nutritionix_key = "b05d85f8570c41a40f5bc4cca2c5d57f"): self.nix = Nutritionix(app_id=nutritionix_id, api_key=nutritionix_key) self.food_model = \ {u'nf_ingredient_statement': u'', u'nf_serving_weight_grams': 0, u'allergen_contains_soybeans': None, u'brand_name': u"", u'nf_calories_from_fat': 0, u'nf_calcium_dv': 0, u'brand_id': u'', u'allergen_contains_eggs': None, u'nf_iron_dv': 0, u'nf_cholesterol': 0, u'item_description': u'', u'usda_fields': None, u'nf_monounsaturated_fat': None, u'nf_dietary_fiber': 0, u'item_name': u'', u'allergen_contains_tree_nuts': None, u'allergen_contains_shellfish': None, u'nf_vitamin_c_dv': 0, u'nf_polyunsaturated_fat': None, u'allergen_contains_peanuts': None, u'nf_sugars': 0, u'nf_servings_per_container': None, u'nf_total_fat': 0, u'nf_total_carbohydrate': 0, u'leg_loc_id': 0, u'nf_saturated_fat': 0, u'allergen_contains_wheat': None, u'old_api_id': None, u'updated_at': u'', u'allergen_contains_gluten': None, u'nf_protein': 0, u'item_id': u'', u'nf_calories': 0, u'nf_water_grams': None, u'allergen_contains_fish': None, u'nf_trans_fatty_acid': 0, u'nf_serving_size_qty': 0, u'allergen_contains_milk': None, u'nf_vitamin_a_dv': 0, u'nf_serving_size_unit': u'', u'nf_refuse_pct': None, u'nf_sodium': 0, u'food_group': u'', u'food_subgroup': u'', u'restaurant_id': u'', u'restaurant_name': u''} def get_food_healthy_score(self, food_id): # traverse scored nutrients score = 0 score_nutrients = FoodScoreNutrient.query.all() # get food tuple food = Food.query.filter_by(food_id=food_id).first() food_energy = food.energy for score_nutrient in score_nutrients: # get scored nutrient info score_nutrient_name = score_nutrient.score_nutrient_name nutrient_dv = float(score_nutrient.nutrient_dv) if score_nutrient.recommend: recom_flag = 1 else: recom_flag = -1 # get corresponding food nutrient try: food_nutrient = float(eval('food.' + score_nutrient_name)) except: food_nutrient = 0 # calculate score += recom_flag * (food_nutrient / nutrient_dv) / food_energy # update food healthy score food.healthy_score = score db.session.add(food) db.session.commit() return score def search_food_name(self, food_name, result_num=10, prior_search="hpb_focos"): if prior_search == "hpb_focos": name_results = self.hpb_focos_search_food_name( food_name, result_num) search_num = len(name_results) if search_num < result_num: name_results_2 = self.nutritionix_search_food_name(food_name, \ result_num - search_num) search_num += len(name_results_2) name_results.update(name_results_2) if search_num < result_num: print "Only get " + str(search_num) + " results!" elif prior_search == "nutritionix": name_results = self.nutritionix_search_food_name( food_name, result_num) search_num = len(name_results) if search_num < result_num: name_results_2 = self.hpb_focos_search_food_name(food_name, \ result_num - search_num) search_num += len(name_results_2) name_results.update(name_results_2) if search_num < result_num: print "Only get " + str(search_num) + " results!" else: raise Exception("prior_search must be hpb_focos or nutritionix!") return name_results def search_food_id(self, food_id): if food_id[0:8] == 'hpbfocos': food_id = food_id[8:] food = self.hpb_focos_search_food_id(food_id) else: food = self.nutritionix_search_food_id(food_id) return food def nutritionix_search_food_name(self, food_name, result_num=5): # result_num should <= 50 if result_num <= 50: try: search_result = self.nix.search(food_name, results = "0:" + \ str(result_num)).json() except: # > total results search_num = self.nix.search(food_name).json()['total_hits'] search_result = nix.search(food_name, results = "0:" + \ str(search_num)).json() else: raise Exception("Result num must <= 50!") results = search_result['hits'] name_results = {} for result in results: name_results[result[u'fields'][u'item_name']] = result[u'_id'] return name_results def nutritionix_search_food_id(self, food_id): try: food_entry = self.nix.item(id=food_id).json() except: raise Exception("Invalid Food ID") return food_entry def hpb_focos_search_food_name(self, food_name, result_num=5): results = db.session.query(HpbFocosFood).filter(HpbFocosFood.\ food_name.like('%%' + food_name + '%%')).all() search_num = len(results) if result_num <= search_num: results = results[0:result_num] else: print "Only get " + str(search_num) + " search results!" name_results = {} for result in results: name_results[result.food_name] = u'hpbfocos' + str(result.food_id) return name_results def hpb_focos_search_food_id(self, food_id): hpb_food = HpbFocosFood.query.filter_by(food_id=food_id).first() food = {} food[u'nf_serving_weight_grams'] = hpb_food.serving_gram # food[u'nf_calcium_dv'] = 0, # u'nf_iron_dv': 0, food[u'nf_cholesterol'] = hpb_food.cholesterol food[u'nf_dietary_fiber'] = hpb_food.fiber food[u'item_name'] = hpb_food.food_name # u'nf_vitamin_c_dv': 0, food[u'nf_total_fat'] = hpb_food.fat food[u'nf_total_carbohydrate'] = hpb_food.carb food[u'nf_saturated_fat'] = hpb_food.sat_fat food[u'nf_protein'] = hpb_food.protein food[u'item_id'] = u'hpbfocos' + str(hpb_food.food_id) food[u'nf_calories'] = hpb_food.energy #u'nf_vitamin_a_dv': 0, food[u'nf_serving_size_unit'] = hpb_food.serving_unit food[u'nf_sodium'] = hpb_food.sodium food[u'food_group'] = hpb_food.food_group food[u'food_subgroup'] = hpb_food.food_subgroup return food
with io.open(file_name, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) # Performs label detection on the image file response = client.label_detection(image=image) labels = response.label_annotations print('Labels:') for label in labels: print(label.description + " " + str(label.score)) # Let the user choose what label best fits chosenLabel = input("Which label do you choose? ") for label in labels: if label.description == chosenLabel: # Scrape description from Wikipedia print("\nDescription: ") print(wikipedia.summary(chosenLabel, sentences=3)) # Scrape nutrition data nix = Nutritionix(app_id="149637d3", api_key="db3b7737e2bb69592a78ddea290e1704") apple = nix.search(chosenLabel) results = apple.json() resultsItem = nix.item( id=results['hits'][0]['fields']['item_id']).json() print("Calories: " + str(resultsItem['nf_calories'])) print("Serving Weight: " + str(resultsItem['nf_serving_weight_grams']) + "g")
from nutritionix import Nutritionix nix = Nutritionix(app_id="0acff812", api_key="fe3234b8d467860ae368067d62ae5600") result = nix.item(id="513fc9e73fe3ffd40300109f").json() num = result['nf_protein'] den = result['nf_serving_weight_grams'] proRatio = float(num)/float(den) print proRatio ### Iteration for 100 most protein filled ff = nix.search().nxql( filters={ "nf_protein": { "gte": 120 } }, fields=["item_name", "item_id"] ).json() print ff
) ingredients = [] meal = [] try: grub = input("First Ingredient: ") ammount = input("Ammount (in grams): ") while grub: ingredients.append(tuple([str(grub), int(ammount)])) grub = input("Next ingredient: ") ammount = input("Ammount (in grams): ") for ingredient in ingredients: food = nix.search(ingredient[0], results="0:1") foodID = food.json()['hits'][0]['_id'] data = nix.item(id=foodID).json() #print(data) if data['nf_serving_weight_grams'] != None: calories = ( (data['nf_calories'] / data['nf_serving_weight_grams']) * ingredient[1]) fat = ((data['nf_total_fat'] / data['nf_serving_weight_grams']) * ingredient[1]) carbs = ((data['nf_total_carbohydrate'] / data['nf_serving_weight_grams']) * ingredient[1]) protein = ((data['nf_protein'] / data['nf_serving_weight_grams']) * ingredient[1]) sugar = ((data['nf_sugars'] / data['nf_serving_weight_grams']) * ingredient[1]) meal.append([