예제 #1
0
def get_calories_today(request):
    """ Tells whether the specified user ate more or less calories than recommended today.

    :request_field integer user_id: BotMother user platform_id.

    :response_field string message: Tells to user about calories eaten today.
    :response_field boolean success
    """

    user_id = int(request.POST['user_id'])

    user = BotUser.objects.get(bot_user_id=user_id)
    session_token = user.fatsecret_oauth_token, user.fatsecret_oauth_token_secret
    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, session_token=session_token)
    # Requesting datetime in my timezone
    dt = now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(tzinfo=None)

    # Reading recommended calories number
    with open("recommended.json") as f:
        calories_recommended = json.load(f)["calories"]

    # Requesting recent eaten food
    recent_eaten = fs.food_entries_get(date=dt)
    if not recent_eaten:
        return JsonResponse({"success": True, "message": "Похоже, сегодня вы ничего не добавляли в наш помощник."})

    # Calculating eaten calories
    calories_eaten = sum([int(food_item['calories']) for food_item in recent_eaten])

    # Answering
    if calories_eaten > calories_recommended:
        return JsonResponse({"success": True, "message": "Похоже, сегодня вы съели слишком много калорий."})
    else:
        return JsonResponse({"success": True, "message": "Сегодня вы съели не слишком много калорий."})
예제 #2
0
def create_fatsecret_profile(request):
    """ Creates new FatSecret profile in this FS app for the specified user.

    :response_field boolean success
    """

    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
    user_id = request.POST['user_id']

    if BotUser.objects.filter(bot_user_id=user_id).first() is None:
        return JsonResponse({"success": False, "error": "User with this id doesn't exist"})

    try:
        session_token = fs.profile_create(str(user_id))
    except FSParameterError:
        # This user already has a new FS account
        session_token = fs.profile_get_auth(str(user_id))

    # Update user fields
    user = BotUser.objects.get(bot_user_id=user_id)
    user.fatsecret_account = 'NEW'
    user.fatsecret_oauth_token = session_token[0]
    user.fatsecret_oauth_token_secret = session_token[1]
    user.save()

    return JsonResponse({"success": True})
예제 #3
0
def authenticate(request):
    """ Page where user is redirected from a FS account binding confirmation page to complete FS account binding.
    """

    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
    if request.GET.get('oauth_verifier', None):
        user_id = int(request.GET['user_id'])
        verifier_pin = request.GET['oauth_verifier']

        # Changing FS instance to use variables from 1st step of 3-Legged OAuth
        user = BotUser.objects.get(bot_user_id=user_id)
        fs.request_token = user.fs_request_token
        fs.request_token_secret = user.fs_request_token_secret

        session_token = fs.authenticate(verifier_pin)
        logger.info("Successful authentication. Token is {}, user id is {}".format(session_token, user_id))

        # Updating user fields
        user.fatsecret_account = 'OLD'
        user.fatsecret_oauth_token = session_token[0]
        user.fatsecret_oauth_token_secret = session_token[1]
        user.save()

        return render(request, "fat_secret_api/auth_complete.html")
    else:
        return JsonResponse({"error": "Authentication cannot be completed: OAUTH verifier is not set"})
예제 #4
0
def food_search(user_id, search_string):
    """Searches the specified query in the FS database.

    :param user_id: BotMother user platform_id.
    :type user_id: int
    :param search_string: Search query for FS food search.
    :type search_string: str
    """

    user = BotUser.objects.get(bot_user_id=user_id)
    session_token = user.fatsecret_oauth_token, user.fatsecret_oauth_token_secret
    fs = Fatsecret(settings.CONSUMER_KEY,
                   settings.CONSUMER_SECRET,
                   session_token=session_token)

    food_names = []
    food_ids = []
    try:
        results = fs.foods_search(search_string)[:4]
    except KeyError:
        # Found nothing, eg query in Russian
        return

    for food_item in results:
        food_names.append(food_item["food_name"])
        food_ids.append(food_item["food_id"])

    return {"success": True, "food_names": food_names, "food_ids": food_ids}
예제 #5
0
파일: views.py 프로젝트: i32agval/GymLuis
def load_recipes(request):
    """
    Required for ajax to show dynamically recipes when select a type
    """
    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)

    recipe_type = fs.recipe_types_get().get('recipe_type')
    recipe_type2 = int(request.GET.get('recipe_type'))
    recipe_type_number = []

    [recipe_type_number.append(x) for x in range(len(recipe_type))]
    recipe_type = dict(zip(recipe_type_number, recipe_type))
    for x in recipe_type:
        if x == recipe_type2:
            recipe_type = recipe_type[x]

    recipes = fs.recipes_search(search_expression='', recipe_type=recipe_type)
    recipes_list = []

    cont = 0
    for x in range(len(recipes)):
        recipes_list.append(recipes[x]['recipe_id'])
        cont = cont + 1

    cont = 0
    for x in recipes:
        recipes[cont] = recipes[cont]['recipe_name']
        cont = cont + 1

    recipes = dict(zip(recipes_list, recipes))

    return render(request, 'nutrition/recipe_dropdown_list_options.html',
                  {'recipes': recipes})
예제 #6
0
def create_food_entry(request):
    """ Creates food entry in the specified user's food diary.

    :request_field integer user_id: BotMother user platform_id.
    :request_field string food_id: FS food_id.
    :request_field string serving_id: FS serving_id.
    :request_field float number_of_units: FS number_of_units.

    :response_field string entry_id: FS food_entry_id.
    :response_field boolean success
    """

    user_id = int(request.POST['user_id'])
    food_id = str(request.POST['food_id'])
    serving_id = str(request.POST['serving_id'])
    number_of_units = float(request.POST['number_of_units'])

    if number_of_units <= 0:
        return JsonResponse({"success": False, "error": "Number of units must be positive"})

    # Getting parameters for food entry creation
    user = BotUser.objects.get(bot_user_id=user_id)
    session_token = user.fatsecret_oauth_token, user.fatsecret_oauth_token_secret
    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, session_token=session_token)
    # Requesting datetime in my timezone
    dt = now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(tzinfo=None)
    meal = hour_to_meal(dt.hour)
    entry_name = "{}: {}".format(dt.ctime(), fs.food_get(food_id)['food_name'])

    # Creating food entry in FS database
    entry_id_dict = fs.food_entry_create(food_id, entry_name, serving_id, number_of_units, meal)
    return JsonResponse({"success": True, "entry_id": entry_id_dict["value"]})
예제 #7
0
    def __init__(self):
        with open('keys.txt', 'r') as f:
            keys = f.read().splitlines()

        self.consumer_key = keys[0]
        self.consumer_secret = keys[1]
        self.fs = Fatsecret(self.consumer_key, self.consumer_secret)
        self.ignore = {
            'measurement_description', 'metric_serving_amount',
            'metric_serving_unit', 'number_of_units', 'serving_description',
            'serving_id', 'serving_url'
        }
        self.units = {
            'calories': 'kcal',
            'cholesterol': 'mg',
            'sodium': 'mg',
            'potassium': 'mg',
            'vitamin_d': 'mcg',
            'vitamin_a': 'mcg',
            'vitamin_c': 'mg',
            'calcium': 'mg',
            'iron': 'mg'
        }
        self.essential = {
            'calories', 'carbohydrate', 'protein', 'fat', 'fiber', 'sugar'
        }
 def auth_user(self):
     return Fatsecret(
         settings.FATSECRET["consumer_key"],
         settings.FATSECRET["consumer_secret"],
         session_token=(
             self.fatsecret_user.access_token,
             self.fatsecret_user.access_token_secret,
         ),
     )
예제 #9
0
def show(food_name):
    fs = Fatsecret(consumer_key, consumer_secret)
    foods = fs.foods_search(food_name)

    #print("Food Search Results: {}".format(len(foods)))
    #print("{}\n".format(foods))
    food_id = str(foods[0]["food_id"])
    #print(food_id)

    f = open('helloworld.html', 'w')

    message1 = """<!DOCTYPE html >
    <html>
    <head>
    		<title>Sample Code</title>
    		<style>
    			body
    			{
    				font-family: Arial;
    				font-size: 12px;
    			}
    			.title{
    				font-size: 200%;
    				font-weight:bold;
    				margin-bottom:20px;
    			}
    			.holder{
    				width:300px;
    				margin:0 auto;
    				padding: 10px;
    			}
    		</style>
    		<script src="http://platform.fatsecret.com/js?key=8575eae8dc11485090730817b5c67c94&amp;auto_template=false&amp;theme=none"></script>
    		<script>
    			function doLoad(){
    				fatsecret.setContainer('container');
    				fatsecret.setCanvas("food.get", {food_id: """

    message2 = """});
    			}
    		</script>
    	</head>
    	<body onload="doLoad()">
    		<div class="holder">
    			<div class="title"><script>fatsecret.writeHolder("foodtitle");</script></div>
    			<script>fatsecret.writeHolder("nutritionpanel");</script>
    			<div id="container"></div>
    		</div>
    	</body>
    </html>"""

    f.write(message1 + food_id + message2)
    f.close()

    #Change path to reflect file location
    filename = 'file:///Users/wd4446/Box Sync/Adv_Predictive_Modeling/Image_Recognition/model2.0/demo_test/' + 'helloworld.html'
    webbrowser.open_new_tab(filename)
예제 #10
0
def food_calorie():
    if request.method == "GET":
        if 'lastSearchedFoodItem' in session.keys():
            return render_template('food_calorie.html',
                                   food=session['lastSearchedFoodItem'],
                                   foodList=enumerate(
                                       session['lastSearchedFoodList']),
                                   diet=enumerate(session['diet'].items()),
                                   summary=totalCalories(session['diet']))
        else:
            return render_template('food_calorie.html', diet=session['diet'])

    elif request.method == "POST":
        # Handling the Search Bar
        if "search" in request.form:
            print(request.form)
            foodItem = request.form.get('fooditem')

            fs = Fatsecret(CONSUMER_KEY, CONSUMER_SECRET)
            foodItems = fs.foods_search(foodItem)
            foodList = []
            for food in foodItems:
                foodList.append(record_to_dict(food))

            session['lastSearchedFoodList'] = foodList
            session['lastSearchedFoodItem'] = foodItem
            session.modified = True

            return render_template('food_calorie.html',
                                   food=foodItem,
                                   foodList=enumerate(foodList),
                                   diet=enumerate(session['diet'].items()),
                                   summary=totalCalories(session['diet']))
        # Updation to the Account Page
        else:
            # Here we are by default updating the food entries
            # in terms of each field like Calories and Carbs
            for id, record in session['diet'].items():
                record = updatedQuantityRecord(record)
                foodItem = Food(name=record['food_name'],
                                quantity=record['quantity'],
                                perServing=record['serving_size'],
                                totalCalorie=record['Calories'],
                                totalCarbs=record['Carbs'],
                                totalFat=record["Fat"],
                                totalProtein=record['Protein'],
                                eatingDate=datetime.now(),
                                foodEater=current_user)
                db.session.add(foodItem)
                db.session.commit()

            session['diet'] = {}
            return redirect(url_for('account'))
예제 #11
0
 def __init__(self, name=None, speech_input=False, facebook_input=False):
     self.phrases = Phrases()
     self.speech = Speech()
     self.knowledge = Knowledge(weather_api_token=weather_api_token)
     self.name = name
     self.facebook_input = facebook_input
     if self.facebook_input:
         self.facebook_response = list()
     self.speech_input = speech_input
     self.witai = Wit("S73IKQDWJ22OJMOSD6AOT4CSJOWXIPX6")
     self.fs = Fatsecret("90fe184a283449ed8a83e35790c04d65", "054e80b2be154337af191be2c9e11c28")
     self.translator = Translator()
예제 #12
0
파일: fs.py 프로젝트: jmznxn77/eatr
def main():

    filename = "tags.txt"
    badTags = [
        "no person", "fruit", "food", "nutrition", "confection", "health",
        "tropical", "bunch", "healthy", "glass", "foam", "alcohol", "pub",
        "drink", "lager", "sesame", "unhealthy", "fast", "lunch", "mayonnaise",
        "bird", "poultry", "hen", "animal", "feather", "farm", "nature",
        "desktop", "wing", "meat", "barbecue", "fillet", "dinner", "vegetable",
        "pastry", "delicious", "refreshment", "delicious", "homemade",
        "citrus", "juice", "juicy", "isolated", "desktop", "meal", "plate",
        "bowl", "cuisine", "cooking", "person", "calcium", "cream", "glass",
        "cold", "closeup", "diet", "epicure", "close", "skin", "texture",
        "breakfast", "half", "moon", "grow", "one", "old", "wood", "stick"
    ]

    f0 = open(filename)
    lines = [line.rstrip('\n') for line in f0]
    f0.close

    #print(lines)

    #remove bad tags from the list
    goodList = [x for x in lines if x not in badTags]

    consumerkey = "916c5699f1614b4bb2b939a76df609b1"
    consumersecret = "ec94e8fc8be7483f810a81f7cba32c14"

    fs = Fatsecret(consumerkey, consumersecret)
    #print(goodList)
    try:
        foods = fs.foods_search(goodList[0], 0, 1)
    except Exception:
        print("titty tats")
        foods = str(fs.foods_search("chicken tenders", 0, 1)[0])
        pass

    if isinstance(foods, list):
        stringFood = str(foods[0])  #first entry
    else:
        stringFood = str(foods)

    s = stringFood.replace("u'", "\"")  #strip u' 's
    s2 = s.replace("\'", "\"")  #turn single quotes to double quotes

    # Open a file to write our shit to
    fo = open("guac.json", "w")
    fo.write(s2)

    # Close opend file
    fo.close()
예제 #13
0
파일: views.py 프로젝트: i32agval/GymLuis
def load_recipes_table(request):
    """
    Required for ajax to show dynamically recipes info when select a recipe
    """
    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
    recipe = request.GET.get('recipe')
    url_image = ''
    recipe_info = fs.recipe_get(recipe)
    ingredients = recipe_info['ingredients']
    ingredients = ingredients['ingredient']
    ingredients_list = []
    cooking_time_min = recipe_info.get('cooking_time_min')
    for x in ingredients:
        ingredients_list.append(x.get('ingredient_description'))

    image = recipe_info.get('recipe_images', '')
    if image:
        url_image = image.get('recipe_image')
    direction = recipe_info.get('directions')
    direction_list = direction['direction']
    cont = 0
    description = []
    if direction:
        for x in direction_list:
            try:
                description.append(
                    direction['direction']['direction_description'])
                break
            except:
                description.append(
                    direction['direction'][cont].get('direction_description'))
            cont = cont + 1
    else:
        description = ''

    nutrients = recipe_info['serving_sizes']
    nutrients = nutrients.get('serving')
    return render(
        request, 'nutrition/recipes_table.html', {
            'url_image': url_image,
            'description': description,
            'nutrients': nutrients,
            'ingredients_list': ingredients_list,
            'cooking_time_min': cooking_time_min
        })
예제 #14
0
파일: gui.py 프로젝트: amnona/reciper
    def __init__(self):
        '''Start the gui
        '''
        super().__init__()
        self.ingredients = []
        self.values = {}
        ck = 'b06a262d0e0b4321981d8c15d2cb866b'
        cs = 'bf6c1708b7ec4fedb7c3d0381ea7a2db'
        fs = Fatsecret(ck, cs)
        self.fs = fs

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        main_widget = QWidget(self)
        layout = QVBoxLayout(main_widget)

        button = QPushButton('Values')
        button.clicked.connect(self.get_values)
        layout.addWidget(button)

        self.w_search_ingredient = QLineEdit('pita')
        self.w_search_ingredient.returnPressed.connect(self.search)

        button = QPushButton('RecipeIt!')
        button.clicked.connect(self.get_recipe)
        layout.addWidget(button)

        button = QPushButton('remove')
        button.clicked.connect(self.remove)
        layout.addWidget(button)

        layout.addWidget(self.w_search_ingredient)
        # hlayout.addWidget(search_ingredient)

        self.w_ingredient_list = QListWidget()
        layout.addWidget(self.w_ingredient_list)

        self.ingredients = {}

        self.setWindowTitle('Reciper version %s' % __version__)
        main_widget.setFocus()
        self.setCentralWidget(main_widget)
        self.show()
예제 #15
0
def get_serving_for_food_id(request):
    """ Gets the serving we need for the specified food item.

    :request_field integer food_id: FS food_id.

    :response_field string measure: Metric serving unit (g, ml).
    :response_field string serving_id: Metric serving unit (g, ml).
    :response_field boolean success
    """

    food_id = str(request.POST['food_id'])

    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
    servings = fs.food_get(food_id)["servings"]["serving"]
    if isinstance(servings, dict):
        needed_serving = servings
    else:
        # Branded food, only one serving option, not list of servings
        needed_serving = servings[-1]

    measure = needed_serving["metric_serving_unit"]
    serving_id = needed_serving["serving_id"]
    return JsonResponse({"success": True, "measure": measure, "serving_id": serving_id})
예제 #16
0
def create_food_attributes(food, amount=None, measurement=None):
    consumer_key = '2430c39a9a3545fe95340690808444f7'
    consumer_secret = '9d60923bee3c4a209b053bcacd8f7159'
    fs = Fatsecret(consumer_key, consumer_secret)

    searchResults = fs.foods_search(str(food), max_results=10)

    finalFood = None

    for result in searchResults:
        servingTypes = fs.food_get(result['food_id'])['servings']['serving']

        if(not measurement or not amount):
            finalFood = servingTypes[0]
            break
        #endif

        for serving in servingTypes:
            if(not isinstance(serving, str) and measurement in serving['measurement_description'] and int(float(serving['number_of_units'])) == 1):
                finalFood = serving
                break
            #endif

            if(finalFood == None):
                finalFood = servingTypes[0]
            #endif
        # endfor
    # endfor

    fs.close()

    calories = int(int(finalFood['calories']) * (1 if amount == None else (amount/servingSize)))
    fat = int(round(float(finalFood['fat']) * (1 if amount == None else (amount/servingSize))))
    carbs = int(round(float(finalFood['carbohydrate']) * (1 if amount == None else (amount/servingSize))))
    protein = int(round(float(finalFood['protein']) * (1 if amount == None else (amount/servingSize))))

    return {"carbs": carbs, "protein": protein, "fat": fat, "calories": calories}
예제 #17
0
파일: views.py 프로젝트: i32agval/GymLuis
def recipe_data(request):
    """
    Access to Fatsecret API to obtain info for the recipe
    """
    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
    recipe_type = fs.recipe_types_get().get('recipe_type')
    recipe = fs.recipes_search(search_expression='', recipe_type='lunch')
    recipes_list = []
    [recipes_list.append(x['recipe_name']) for x in recipe]
    recipes_number = []
    [recipes_number.append(x) for x in range(len(recipes_list))]
    recipes_list = dict(zip(recipes_number, recipes_list))
    recipes_type_number = []
    [recipes_type_number.append(x) for x in range(len(recipe_type))]
    recipe_type = dict(zip(recipes_list, recipe_type))

    form = RecipeForm(instance=recipe_type, recipes=recipes_list)

    messages.info(request, 'Lista de recetas de la API Fatsecret')

    return render(request, 'nutrition/recipe_data.html', {
        'recipe_type': recipe_type,
        'form': form
    })
예제 #18
0
def get_auth_url(request):
    """ Requests url for an existing FS account binding to the specified user.

    :response_field string url: FS account binding URL.
    :response_field boolean success
    """

    fs = Fatsecret(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
    user_id = request.POST['user_id']
    if BotUser.objects.filter(bot_user_id=user_id).first() is None:
        return JsonResponse({"success": False, "error": "User with this id doesn't exist"})

    # Creating auth_url where token contains callback_url to our server page
    callback_url = urljoin(settings.REDIRECT_HOST, reverse('authenticate'))
    callback_url = urljoin(callback_url, '?user_id={}'.format(user_id))
    auth_url = fs.get_authorize_url(callback_url=callback_url)

    # Saving request token and secret for further FS instance creation in 'authenticate'
    user = BotUser.objects.get(bot_user_id=user_id)
    user.fs_request_token = fs.request_token
    user.fs_request_token_secret = fs.request_token_secret
    user.save()

    return JsonResponse({"success": True, "url": auth_url})
예제 #19
0
from .models import Food
from fatsecret import Fatsecret

api_key = "2a56ae2c434b429dbaaae13b500041c4"
api_secret = "242498e295b042a69c470fb4612fdf0a"

fs = Fatsecret(api_key, api_secret)
base_google_url = "http://www.google.com/search?q="
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,} 

# Called in views.py to get info of the food either from database or API
def get_food_info(food):
	results = Food.objects.filter(name=food)
	if results.count() == 0:
		calories, serving_size = get_food_nutrition_from_API(food)
	else:
		food_object = results[0]
		calories, serving_size = food_object.calories, food_object.serving_size

	return calories, serving_size

# Function to get food info from API if it is not in the database
def get_food_nutrition_from_API(food_query):

	foods = fs.foods_search(food_query)

	print foods
	
	calories = 0
예제 #20
0
from fatsecret import Fatsecret
fs = Fatsecret("b5249d29c66d4c729753596b947d6770",
               "4842ba359e2f4675a4fba57578c8cc88")

foods = fs.foods_search("Tacos")

print(foods)
예제 #21
0
from rest_framework.views import APIView  # Also adding these - Adam

from .models import *
from .serializers import *

from fatsecret import Fatsecret
from dotenv import load_dotenv
import json
from .recipe_api import *

load_dotenv()

consumer_key = os.getenv("FATSECRETS_CONSUMER_KEY")
consumer_secret = os.getenv("FATSECRETS_CONSUMER_SECRET")

fs = Fatsecret(consumer_key, consumer_secret)


def search_recipes(request):
    query = request.data.get('q')
    results = fs.foods_search(query)
    return json.dumps(results)


# https://pyfatsecret.readthedocs.io/en/latest/api_docs.html
from fatsecret import Fatsecret
consumer_key = os.getenv("FATSECRETS_CONSUMER_KEY")
consumer_secret = os.getenv("FATSECRETS_CONSUMER_SECRET")
fs = Fatsecret(consumer_key, consumer_secret)

예제 #22
0
 def __init__(self, intent_request, session):
   self.session = session
   self.fs = Fatsecret(oauth_consumer_key, oauth_secret_key)
   self.calorie_count = 0
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    #calculate position x, y
    x = (ws / 2) - (w / 2)
    y = (hs / 2) - (h / 2)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))


global root, f1
root = tkinter.Tk()
root.title("Personal Nutritionist")
root.geometry("1366x768")  #You want the size of the app to be 500x500
root.resizable(0, 0)
center_window(1366, 768)
root.attributes('-fullscreen', False)
fs = Fatsecret('16fab56f70d1452ea8fbc4619b11f3ae',
               'ed2efbca053542d688b24b360df70277')

global id_mob
global bmi_w, bmi_h

bmi_h = 0
bmi_w = 0

##########################################
'''
users_list = []

fo = open("Users.pkl", "wb")
pickle.dump(users_list, fo)
fo.close()
'''
예제 #24
0
#Importing the Libraries
import pandas as pd
import numpy as np
from flask import Flask, request, render_template
from flask_cors import CORS
import os
from sklearn.externals import joblib
from keras.models import load_model
import pickle
import flask
from imageio import imread
from PIL import Image
from keras.preprocessing import image
from fatsecret import Fatsecret
fs = Fatsecret('d82e5cd4d5674be99e298020286a1bd5',
               '823bef07377d4560ba7c3fa4a5c0b521')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import base64
from io import BytesIO

categories = pd.read_csv('category.csv', index_col=['Unnamed: 0'])
#Loading Flask and assigning the model variable
app = Flask(__name__)
CORS(app)
app = flask.Flask(__name__, template_folder='templates')

model = joblib.load('model.pkl')


@app.route('/')
예제 #25
0
client = MongoClient()
db = client.food
user_database = db.lookup


def get_food_info(item, name, fs):
    try:
        foods = fs.food_get(item)
        print foods
        exit()
    except Exception, e:
        print e


def populate(fs, filename):
    f = open(filename, 'r')
    dictio = {}
    for x in f:
        name, ide = x.rstrip().split(':')
        dictio[ide] = name
    f.close()
    for x in dictio.keys():
        time.sleep(1.1)
        get_food_info(x, dictio[x], fs)
        print dictio[x]


if __name__ == "__main__":
    fs = Fatsecret(sys.argv[1], sys.argv[2])
    z = populate(fs, sys.argv[3])
예제 #26
0
from tkinter import *
import tkinter
from fatsecret import Fatsecret
import webbrowser
import tkinter.messagebox as tkmessagebox

fs = Fatsecret("53d896611f274c93918b1ecfc3163e98",
               "53419fc7c2db4861b3360d0b7b89653f")

root = Tk()
root.geometry('800x800')
# root.attributes("-fullscreen" , True)


def enterDetails():
    global bmi, bmiLabel, b, n, a
    h = float(Height1.get())
    w = float(Weight1.get())
    n = Name1.get()
    a = int(Age1.get())
    hh = float(h * h)
    b = float(w / hh)
    f1 = Frame(root, bg="#172c3e")
    f1.place(height=800, width=800)

    bmiLabel = Label(f1,
                     text="Your BMI is : ",
                     fg="yellow",
                     font=("Arial", 25, "bold italic"),
                     bg="#172c3e")
    bmiLabel.place(x=150, y=70)
예제 #27
0
파일: main.py 프로젝트: takyyon/HackUmass
from fatsecret import Fatsecret
from flask import Flask, render_template, request
from google.cloud import vision
from google.cloud.vision import types
import json
import requests
import random

app = Flask(__name__)
fs = Fatsecret("e0f89e5553d34ffd972e75f869bd551f","35db6d8a8b98446b817c1c7d54ef1351")

@app.route('/product',methods=["POST"])
def response():
    value = request.files['Upload']
    #encodedImage = base64.b64encode(value.read())
    encodedImage = value.read()
    result = get_vision(encodedImage)
    return render_template("Product.html", result = result)
    

def get_vision(content):
    client = vision.ImageAnnotatorClient()
    image = types.Image(content=content)
    response = client.web_detection(image=image).web_detection
    food_item = response.web_entities[0].description
    foods = fs.foods_search(food_item,1,10)
    options = {}
    for food in foods:
          options[food['food_id']] = food['food_name']
    return options
from django.conf import settings
from tensorflow.keras.preprocessing import image

#testingdirect = "F://xampp//htdocs//upload"
testingdirect = "media"
#new_model = tf.keras.models.load_model('F://xampp//htdocs//saved_model//fmodel')

new_model = tf.keras.models.load_model(
    'F://xampp//htdocs//saved_model//fmodel')

#foodmodel = tf.keras.load_model("saved_model/fmodel")
# Create your views here.
new_model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.004),
                  loss=tf.keras.losses.CategoricalCrossentropy(),
                  metrics=['accuracy'])
fs = Fatsecret("896700be9d2449ce8838af1102898343",
               "d58a47e2b261425ab9191b76b8398c57")
name = [
    'apple_pie', 'baby_back_ribs', 'baklava', 'beef_carpaccio', 'beef_tartare',
    'beet_salad', 'beignets', 'bibimbap', 'bread_pudding', 'breakfast_burrito',
    'bruschetta', 'caesar_salad', 'cannoli', 'caprese_salad', 'carrot_cake',
    'ceviche', 'cheesecake', 'cheese_plate', 'chicken_curry',
    'chicken_quesadilla', 'chicken_wings', 'chocolate_cake',
    'chocolate_mousse', 'churros', 'clam_chowder', 'club_sandwich',
    'crab_cakes', 'creme_brulee', 'croque_madame', 'cup_cakes', 'deviled_eggs',
    'donuts', 'dumplings', 'edamame', 'eggs_benedict', 'escargots', 'falafel',
    'filet_mignon', 'fish_and_chips', 'foie_gras', 'french_fries',
    'french_onion_soup', 'french_toast', 'fried_calamari', 'fried_rice',
    'frozen_yogurt', 'garlic_bread', 'gnocchi', 'greek_salad',
    'grilled_cheese_sandwich', 'grilled_salmon', 'guacamole', 'gyoza',
    'hamburger', 'hot_and_sour_soup', 'hot_dog', 'huevos_rancheros', 'hummus',
    'ice_cream', 'lasagna', 'lobster_bisque', 'lobster_roll_sandwich',
예제 #29
0
from fatsecret import Fatsecret

fs = Fatsecret('fd1d348919f0451894bd32b2d3de6e5c',
               '1a36ce0def3949229b8c638dd5838383')

foods = fs.foods_search("Tacos")

print(foods)
 def system_fatsecret_instance(self):
     return Fatsecret(settings.FATSECRET["consumer_key"],
                      settings.FATSECRET["consumer_secret"])