Пример #1
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}
Пример #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 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})
Пример #4
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"]})
Пример #5
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": "Сегодня вы съели не слишком много калорий."})
Пример #6
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"})
Пример #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'
        }
Пример #8
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)
Пример #9
0
class SofiaAPI:
  def __init__(self, intent_request, session):
    self.session = session
    self.fs = Fatsecret(oauth_consumer_key, oauth_secret_key)
    self.calorie_count = 0
    # self.request_date = datetime.strptime(intent_request['timestamp'], "%Y-%m-%dT%H:%M:%SZ")

  # ------- Interface with the Intents ----------
  #def save_exercise(self, exercise_name, duration):
    #method = "method":"exercises.get"
   # response = encode([method])
   # if response is not None:
   #     exercise_name = response.exercise_types.exercise[0].exercise_name
   # method = "exercise_entries.commit_day"
   # #return encode([method, self.auth_token])

  def calculate(self, response_type):
    if self.calorie_count < 500:
        return "You have eaten way too little today! Only "+ calorie_count + " calories!"
    elif self.calorie_count < 1000 and calorie_count > 500:
        return "You are doing well today. You have eaten "+ calorie_count + " calories!"
    elif self.calorie_count > 1000:
        return "You have eaten way too much, you fatty!"

  def add_food(self, food_name):
    foods = self.fs.foods_search(food_name)
    if foods is not None:
        food_description = foods[0]['food_description']
        print(food_description)
        food_id = foods[0]['food_id']
        food_name = foods[0]['food_name']
        #self.fs.food_entry_create(food_id, food_name, 0, 1, "breakfast", date=None)
        print(food_description)
        return self.get_calories(food_description)
    return "Could not find this food type."

  def get_calories(self, str):
      index = str.find("Calories: ")
      if index != -1:
        str = str[index+9: index+13]
        cals = str.strip(' ')
        self.calorie_count = self.calorie_count + int(cals)
        return cals
      else:
        return 0

  def configure_me(self, height, weight, age, gender):
      return "2000"
    # self.fs.profile_create(user_id=None)
    # if weight:
    #     if height:
    #         return self.set_weight(weight, height)
    #     else:
    #         return self.set_weight(weight, 180)

  def set_weight(self, weight, height):
      self.fs.weight_update(weight, date=None, weight_type='kg', height_type='cm', goal_weight_kg=None, current_height_cm=None, comment=None)
Пример #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
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
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
        })
 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,
         ),
     )
Пример #15
0
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"]
	consumerkey = "916c5699f1614b4bb2b939a76df609b1"
	consumersecret = "ec94e8fc8be7483f810a81f7cba32c14"

	#read file tags.txt into a list
	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]

	#print(goodList)

	#write the goodList to a new file tags2.txt
	f1 = open("tags2.txt", "w")
	for item in goodList:
  		f1.write("%s\n" % item)
  	f1.close()

	fs = Fatsecret(consumerkey, consumersecret)
	foods = fs.foods_search(goodList[0], 0, 1)
	
	#print(foods)

	stringFood = str(foods[0]) #top good tag used here
	s=stringFood.replace("u'","\"")  #strip u' 's
	s2=s.replace("\'","\"")   #turn single quotes to double quotes

	#print(s2)

	# Open a file to write our result to, then close it
	f2 = open("guac.json", "w")
	f2.write(s2)
	f2.close()
Пример #16
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})
Пример #17
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})
Пример #18
0
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
    })
Пример #19
0
    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()
Пример #20
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}
Пример #21
0
class Bot(object):
    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()

    def gr_to_en(self, text):
        return self.translator.translate(text, 'en', 'el').text

    def en_to_gr(self, text):
        return self.translator.translate(text, 'el', 'en').text

    def start(self):
        if self.speech_input or self.facebook_input:
            self.decide_action()
        else:
            print("Γεία σου! Πως θα μπορούσα να σε βοηθήσω;")
            while 1:
                self.decide_action()

    def learn_action(self, filename, phraseslist):
        Knowledge.learn_default_responses(file=filename,
                                          phrases=phraseslist)

    def decide_action(self, facebook_input=None):

        if self.speech_input or self.facebook_input:
            if self.speech_input:
                recognizer, audio = self.speech.listen_for_audio()
                # received audio data, now we'll recognize it using Google Speech Recognition
                bot_input = self.speech.google_speech_recognition(recognizer, audio)
            if self.facebook_input:
                self.facebook_response[:] = []
                bot_input = facebook_input
        else:
            bot_input = input()

        if bot_input is not None:
            try:
                resp = self.witai.message(bot_input)
                entities = None
                intent = None
                if 'entities' in resp and 'intent' in resp['entities']:
                    entities = resp['entities']
                    intent = resp['entities']['intent'][0]["value"]
                    # print('Intent: {intent}'.format(intent=intent))
                if intent == 'greeting':
                    self.__text_action(self.phrases.get_phrases('greetings_phrases'))
                elif intent == 'tutorial':
                    self.__tutorial_action()
                elif intent == 'name':
                    if self.name is not None:
                        self.__text_action(self.phrases.get_phrases('name_phrases').replace('<name>', self.name))
                    else:
                        self.__text_action('Οι δημιουργοί μου δεν μου έδωσαν κάποιο όνομα')
                elif intent == 'swear':
                    self.__text_action(self.phrases.get_phrases('swear_phrases'))
                elif intent == 'funny':
                    self.__text_action(self.phrases.get_phrases('funny_phrases'))
                elif intent == 'sex_type':
                    self.__text_action('Λίγο απ\'όλα')
                elif intent == 'user_joke':
                    self.__text_action('χαχαχα')
                elif intent == 'personal_status':
                    self.__personal_status()
                elif intent == 'joke':
                    self.__joke_action()
                elif intent == 'datetime':
                    # print(resp)
                    self.__datetime_action(entities)
                elif intent == 'weather':
                    self.__weather_action()
                elif intent == 'search':
                    self.__search_action(entities)
                elif intent == 'food_det':
                    self.__food_action(entities)
                elif intent == 'recipe':
                    self.__recipe_action(entities)
                elif intent == 'thanksgiving':
                    self.__text_action(self.phrases.get_phrases('thanks_phrases'))
                elif intent == 'sticker':
                    self.__text_action('Επίσης')
                else:  # No recognized intent
                    # print('Intent not recognized')
                    self.__text_action(self.phrases.get_phrases('unrecognized_intent_phrases'))
                    return

            except Exception as e:
                print("Exception occured")
                print(e)
                traceback.print_exc()
                self.__text_action("Έγινε κάποιο λάθος")
                return

    def __text_action(self, text=None):
        if text is not None:
            if self.speech_input:
                self.speech.synthesize_text(text)
            if self.facebook_input:
                self.facebook_response.append(text)
            if not (self.facebook_input or self.speech_input):
                print(text)

    def __tutorial_action(self):
        self.__text_action(self.phrases.get_phrases('tutorial_phrases'))

    def __personal_status(self):
        self.__text_action(self.phrases.get_phrases('personal_status_phrases'))

    def __joke_action(self):
        joke = self.phrases.get_phrases('joke_phrases')
        self.__text_action(joke)

    def __datetime_action(self, entities):
        dt = None
        if 'date' in entities:
            dt = entities['date'][0]['value']
            print('Datetime: {dt}'.format(dt=dt))
        if str(dt) == 'hour':
            self.__text_action('Η ώρα είναι {time}'.format(time=self.knowledge.get_time()))
        elif str(dt) == 'day':
            self.__text_action('Σήμερα είναι {weekday}'.format(weekday=self.knowledge.get_weekday()))
        elif str(dt) == 'date':
            self.__text_action('Σήμερα είναι {date}'.format(date=self.knowledge.get_date()))

    def __weather_action(self):
        weather_obj = self.knowledge.find_weather()
        self.__text_action('Η θερμοκρασία είναι ' + str(weather_obj['temperature']) + '° Κελσίου.')

    def __search_action(self, entities=None):
        self.__text_action(self.phrases.get_phrases('search_phrases'))
        if 'wikipedia_search_query' in entities:
            query = entities['wikipedia_search_query'][0]['value']
            # print('wikipedia query: {query}'.format(query=query))
            wikipedia.set_lang("el")
            try:
                self.__text_action(re.sub(r'\([^)]*\)', '', wikipedia.summary(query, sentences=1)))
            except wikipedia.PageError as e:
                print(e)
                self.__text_action('Δεν βρήκα κάποιο αποτέλεσμα')
        else:
            self.__text_action('Δεν μου είπες τί να ψάξω')

    def __food_action(self, entities):
        self.__text_action(self.phrases.get_phrases('search_phrases'))
        inp = self.gr_to_en(entities['wikipedia_search_query'][0]['value'])
        try:
            resp = self.fs.foods_search(inp)
            food = self.fs.food_get(resp[0]['food_id'])
            if 'nutrient_type' in entities.keys():
                self.__text_action(
                    self.en_to_gr(
                        '{type} - 1 {serving}'.format(serving=food['servings']['serving'][0]['measurement_description'],
                                                      type=resp[0]["food_name"])))
                for nutrient in entities['nutrient_type']:
                    self.__text_action(self.en_to_gr('{nutrient}: {value}'.format(nutrient=nutrient['value'],
                                                                                  value=
                                                                                  food['servings']['serving'][0][
                                                                                      nutrient['value']])))
            else:
                self.__text_action(self.en_to_gr(resp[0]["food_name"] + "\n" + resp[0]["food_description"]))
        except Exception as e:
            self.__text_action(
                "Δεν υπάρχουν διαθέσιμες διατροφικές πληροφορίες για " + entities['wikipedia_search_query'][0]['value'])
            self.__search_action(entities)

    def __recipe_action(self, entities):
        self.__text_action(self.phrases.get_phrases('search_phrases'))
        inp = self.gr_to_en(entities['wikipedia_search_query'][0]['value'])
        try:
            resp = self.fs.recipes_search(inp)
            recipe = self.fs.recipe_get(resp[0]['recipe_id'])
            if self.facebook_input:
                self.__text_action("Μπορείς να δεις την συνταγή στο παρακάτω link:")
                self.__text_action(recipe['recipe_url'])
            else:
                self.__text_action(self.en_to_gr(recipe['recipe_name'] + "\n"))
                self.__text_action("Οδηγίες")
                for dir in recipe['directions']['direction']:
                    self.__text_action(self.en_to_gr(dir['direction_description']))
                self.__text_action("Συστατικά")
                for ing in recipe['ingredients']['ingredient']:
                    self.__text_action(self.en_to_gr(ing['ingredient_description']))
        except Exception as e:
            self.__text_action(
                "Δεν υπάρχει διαθέσιμη συνταγή για " + entities['wikipedia_search_query'][0]['value'])
            self.__search_action(entities)
Пример #22
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)

Пример #23
0
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()
Пример #24
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)
Пример #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 .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
Пример #27
0
from fatsecret import Fatsecret

# Be sure to add your own keys
consumer_key = None
consumer_secret = None

fs = Fatsecret(consumer_key, consumer_secret)

# Test Calls w/o authentication

print("\n\n ---- No Authentication Required ---- \n\n")

foods = fs.foods_search("Tacos")
print("Food Search Results: {}".format(len(foods)))
print("{}\n".format(foods))

food = fs.food_get("1345")
print("Food Item 1345")
print("{}\n".format(food))

recipes = fs.recipes_search("Tomato Soup")
print("Recipe Search Results:")
print("{}\n".format(recipes))

recipe = fs.recipe_get("88339")
print("Recipe 88339")
print("{}\n".format(recipe))

# Test Calls with 3 Legged Oauth

print("\n\n ------ OAuth Example ------ \n\n")
Пример #28
0
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
Пример #29
0
from fatsecret import Fatsecret

# Be sure to add your own keys
consumer_key = None
consumer_secret = None


fs = Fatsecret(consumer_key, consumer_secret)

# Test Calls w/o authentication

print("\n\n ---- No Authentication Required ---- \n\n")

foods = fs.foods_search("Tacos")
print("Food Search Results: {}".format(len(foods)))
print("{}\n".format(foods))

food = fs.food_get("1345")
print("Food Item 1345")
print("{}\n".format(food))

recipes = fs.recipes_search("Tomato Soup")
print("Recipe Search Results:")
print("{}\n".format(recipes))

recipe = fs.recipe_get("88339")
print("Recipe 88339")
print("{}\n".format(recipe))

# Test Calls with 3 Legged Oauth
Пример #30
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('/')
    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()
'''
Пример #32
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"])