def lambda_handler(event, context): search = "" if event != None and 'pathParameters' in event: search = event['pathParameters']['search'] if len(search) > 0: nix = Nutritionix(app_id=os.environ["app_id"], api_key=os.environ["api_key"]) nix_results = nix.search().nxql(fields=[ "item_id", "item_name", "brand_name", "nf_total_carbohydrate" ], query=search).json() else: nix_results = {'hits': []} results = {'hits': []} count = 0 for hit in nix_results['hits']: if hit['fields']['nf_total_carbohydrate'] is not None: results['hits'].append({ 'id': count, 'value': '%s, %s, %sg' % (hit['fields']['item_name'], hit['fields']['brand_name'], hit['fields']['nf_total_carbohydrate']) }) count += 1 pass return respond(None, results['hits'])
def restaurant(request): if request.method == 'POST': form = RestaurantSearch(data=request.POST) if form.is_valid(): #Capture user input, assign it to variable 'name' name = form.cleaned_data['name'] #Nutritionix API request nix = Nutritionix(app_id="a70d76f6", api_key="e0d08a959dacfd68dd69b5473f2fc41c") cal1 = nix.search(offset="0", limit="50").nxql( queries={ "brand_name":name, }, fields=["item_name", "brand_name", "nf_calories", "nf_total_fat", "nf_protein", "nf_total_carbohydrate", "nf_sodium"], ).json() response1 = json.dumps(cal1) a = json.loads(response1) b = (a.get("hits")) r = [] for c in b: kitten = (c.get("fields").get("brand_name")) if kitten not in r: r.append(kitten) context = {'form':form,'name':name,'r':r} return render(request, 'macro/restaurant.html', context) else: form = RestaurantSearch() context = {'form':form} return render(request, 'macro/restaurant.html', context)
def nutritionix_ID(label): """ This function will give the first product ID for a specific label input: label (string) output: ID (string) """ nix = Nutritionix(app_id="8dfdbdb1", api_key="66ad2fcd0f25722ca73662505e9fd492") return nix.search(label, results="0:1").json()['hits'][0]['fields']['item_id']
def findMeal(request): """ Finds meal based on POST request from client. Arguments: request -- should contain restaurant name and macros in a matrix (protein, fat, carbs) """ if request.method == "GET": restaurant_name = request.GET['restaurant'] # for testing purposes #Restaurant.objects.get(name=restaurant_name).delete() try: # Query restaurant items restaurant = Restaurant.objects.get(name=restaurant_name) except Exception as e: # if not found, query Nutritionix database # query database nix = Nutritionix() nixResults = nix.search().nxql(queries={ "brand_name": "%s" % restaurant_name }, filters={ "item_type": 1 }, fields=[ "item_name", "nf_total_fat", "nf_total_carbohydrate", "nf_protein" ]).json() # Invalid restaurant name returns no results if (nixResults["total"] == 0): return HttpResponse("Invalid request") # Store restaurant items into DB items = [] for item in nixResults["hits"]: items.append(item["fields"]) Restaurant.objects.create(name=restaurant_name, items=items) # Query restaurant items restaurant = Restaurant.objects.get(name=restaurant_name) clientMacros = request.GET['macros'] items = restaurant.items # find closest meal to fit macros # for meal in restaurant.items: # item = meal return HttpResponse(restaurant.items) else: return HttpResponse("Invalid request")
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 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
def results(request): if request.method == 'GET': sku = request.GET.get('sku') nix = Nutritionix(app_id="a70d76f6", api_key="e0d08a959dacfd68dd69b5473f2fc41c") cal1 = nix.search(offset="0", limit="50").nxql( queries={ "brand_name": sku, }, fields=["item_name", "brand_name", "nf_calories", "nf_total_fat", "nf_protein", "nf_total_carbohydrate", "nf_sodium"], ).json() response1 = json.dumps(cal1) a = json.loads(response1) b = (a.get("hits")) r = [] blue = [] aye = [] for c in b: kitten = (c.get("fields").get("brand_name")) kitten1 = (c.get("fields").get("item_name")) kitten2 = (c.get("fields").get("nf_calories")) if kitten == sku: r.append(kitten) blue.append(kitten1) aye.append(kitten2) h = len(blue) context = {'sku':sku,'r':r,'blue':blue,'aye':aye,'h':h} return render(request, 'macro/results.html',context) else: return render(request, 'macro/results.html')
def download(examples_to_download, offset, only_calories): save_file = create_new_file(examples_to_download, offset, only_calories) nix = Nutritionix(app_id=private_consts.NUTRITIONIX["app_id"], api_key=private_consts.NUTRITIONIX["api_key"]) items = [] num_calls = examples_to_download / ITEMS_PER_API_CALL for i in range(num_calls): print "Downloading items {0} through {1}".format( i * ITEMS_PER_API_CALL + offset, (i + 1) * ITEMS_PER_API_CALL + offset) results = nix.search().nxql(filters=create_filter(only_calories), offset=i * ITEMS_PER_API_CALL + offset, limit=ITEMS_PER_API_CALL).json() items += [hit["_source"] for hit in results["hits"]] # Save data print "Saving " + str(len(items)) + " items" pickle.dump(items, open(save_file, "wb")) return
def download(examples_to_download, offset, only_calories): save_file = create_new_file(examples_to_download, offset, only_calories) nix = Nutritionix(app_id=private_consts.NUTRITIONIX["app_id"], api_key=private_consts.NUTRITIONIX["api_key"]) items = [] num_calls = examples_to_download/ITEMS_PER_API_CALL for i in range(num_calls): print "Downloading items {0} through {1}".format(i*ITEMS_PER_API_CALL + offset, (i+1)*ITEMS_PER_API_CALL + offset) results = nix.search().nxql( filters = create_filter(only_calories), offset = i*ITEMS_PER_API_CALL + offset, limit = ITEMS_PER_API_CALL ).json() items += [hit["_source"] for hit in results["hits"]] # Save data print "Saving " + str(len(items)) + " items" pickle.dump( items, open( save_file, "wb" ) ) return
print("Today's Food For You: ") if gender == "male": need_calories = (10 * weight * 0.4536 + 6.25 * height * 30.48 - 5 * age + 5) * 1.2 elif gender == "female": need_calories = (10 * weight * 0.4536 + 6.25 * height * 30.48 - 5 * age - 161) * 1.2 nix = Nutritionix(app_id="your_app_id", api_key="your_api_key") obj = nix.search().nxql( filters={ "nf_calories": { #"lte": 500 "from": 200, "to": 500 } }, fields=["item_name", "nf_calories"]).json() results = [] for food in obj['hits']: result = { "item_name": food['fields']['item_name'], "calories": food['fields']['nf_calories'] } results.append(result) filter_results = [] total_calories = 0
print( "Instructions:\nPlease enter your ingredients one at a time followed by the ammount in grams when prompted.\nWhen finished, enter nothing for ingredient and grams and simply press enter twice" ) 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']) *
from nutritionix import Nutritionix import json nix = Nutritionix(app_id="XXXXXXXX", api_key="XXXXXXXXXXXXXXXXXXXXXXXXXXX") mcd_search = nix.search().nxql(queries={"brand_name": "mcdonald"}).json() mcd_hits = mcd_search['total'] dict_mcd = [] for i in range(round(mcd_hits / 50) + 1): data = nix.search().nxql( queries={ "brand_name": "mcdonald" }, fields=[ "brand_name", "brand_id", "item_name", "item_id", "updated_at", "nf_calories", "nf_total_fat", "nf_saturated_fat", "nf_cholesterol", "nf_sodium", "nf_total_carbohydrate", "nf_dietary_fiber", "nf_sugars", "nf_protein", "nf_servings_per_container", "nf_serving_size_qty", "nf_serving_size_unit", "nf_serving_weight_grams" ], offset=i * 50, limit=50).json() dict_mcd.append(data) i += 1 with open('mcd.json', 'w') as f: json.dump(dict_mcd, f)
#Insert Statment for 20 attributes for Food add_food = ( "INSERT INTO FoodNutrition" "(IDFoodNutrition,foodName," "total_calories,serving_size_value,serving_size_mass,serving_size_units," "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[
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
with open('lipton.jpg', 'rb') as f: response = api.image_request(f, 'lipton.jpg', { 'image_request[locale]': 'en-US', }) status = api.image_response(response['token']) if status['status'] != cloudsight.STATUS_NOT_COMPLETED: # Done! pass status = api.wait(response['token'], timeout=30) from nutritionix import Nutritionix nix = Nutritionix(app_id="76986486", api_key="28882f3d105c4c9e3222a05eeafd049a") result = nix.search('pizza').json()
def search(request): if request.method == 'POST': form = MacroSearch(data=request.POST) if form.is_valid(): cal1 = form.cleaned_data['calmin'] cal2 = form.cleaned_data['calmax'] fat1 = form.cleaned_data['fatmin'] fat2 = form.cleaned_data['fatmax'] carb1 = form.cleaned_data['carbsmin'] carb2 = form.cleaned_data['carbsmax'] pro1 = form.cleaned_data['promin'] pro2 = form.cleaned_data['promax'] sod1 = form.cleaned_data['sodmin'] sod2 = form.cleaned_data['sodmax'] nix = Nutritionix(app_id="a70d76f6", api_key="e0d08a959dacfd68dd69b5473f2fc41c") cal = nix.search(offset="0", limit="50").nxql( filters={ "nf_calories": { "from": cal1, "to": cal2 }, "nf_total_fat": { "from": fat1, "to": fat2 }, "nf_total_carbohydrate": { "from": carb1, "to": carb2 }, "nf_protein": { "from": pro1, "to": pro2 }, "nf_sodium": { "from": sod1, "to": sod2 }, "item_type": 1, }, fields=["item_name", "brand_name", "nf_calories", "nf_total_fat", "nf_protein", "nf_total_carbohydrate", "nf_sodium"], ).json() response = json.dumps(cal) a = json.loads(response) b = (a.get("hits")) calories = [] fat = [] az = ['monkey','money','ham'] protein = [] carbs = [] sodium = [] itemname=[] restaurant=[] for c in b: kitten = (c.get("fields").get("brand_name")) restaurant.append(kitten) meal = (c.get("fields").get("item_name")) restaurant.append(meal) h = (c.get("fields").get("nf_calories")) restaurant.append(h) j = (c.get("fields").get("nf_total_fat")) restaurant.append(j) l = (c.get("fields").get("nf_protein")) restaurant.append(l) k = (c.get("fields").get("nf_total_carbohydrate")) restaurant.append(k) s = (c.get("fields").get("nf_sodium")) sodium.append(s) all = restaurant + itemname context = {'form':form,'b':b,'restuarant':restaurant,'protein':protein,'itemname':itemname,'calories':calories,'fat':fat,'protein':protein,'az':az} else: form = MacroSearch() context = {'form':form} return render(request,'macro/index.html',context)
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']
def extract_nutrition_data(query): nix = Nutritionix(app_id="ac86d1b1", api_key="290ca52d8ffea5cfa546000bb592c349") query = nix.search(query).json() return query
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")