def addRecipe(img_file, title, description, cat_code, servings, cooktime,
              skillLevel, cuisine, ingredients, steps, user):
    """ It adds a recipe, ingredients, recipe steps, recipe_user"""

    try:
        # Saves the img file in the directory
        filename = img_file

        print "IMG_FILE", img_file

        # If img is not from a website
        # if img_file and allowed_file(img_file.filename) and 'http' not in img_file:

        #     filename = secure_filename(img_file.filename)
        # print "FILENAME" , filename
        # img_file.save(os.path.join(UPLOAD_FOLDER, filename))

        # Add recipe in 'recipes' Table
        Recipe.addRecipe(title, description, filename, cat_code, servings,
                         cooktime, skillLevel, cuisine)

        # Finds the recipe_id
        recipeIds = db.session.query(func.max(Recipe.recipe_id)).one()
        recipeFk = recipeIds[0]
        print "RECIPE ID:  ", recipeFk

        # ingredients = ingredients
        print "INGREDIENTS LIST", ingredients

        for ingredient in ingredients:
            name = ingredient["name"]
            qty = ingredient["qty"]
            unit = ingredient["unit"]
            print "INGREDIENT UNICODE", ingredient

            # Add ingredients in 'RecipeIngredient'
            RecipeIngredient.addIngredients(recipeFk, name, qty, unit)
            # Add ingredients in 'Ingredients'
            Ingredient.addIngredients(name)

        for i in range(len(steps)):
            print "STEP%d" % i
            print "step value: ", steps[i]
            # Add steps in 'recipe_step'
            RecipeStep.addRecipeStep(recipeFk, i + 1, steps[i])

        if 'User' in session:
            RecipeUser.addRecipeForUser(recipeFk, session['User'])

        db.session.commit()

        # Recipe.updateRecipeImg(title=title, cat_code=cat_code)

        message = {'msg': "Recipe successfully added", 'recipeid': recipeFk}

        return recipeFk

    except Exception, error:
        return "Error: %s" % error
예제 #2
0
def create_recipe_ingredient(recipe_id, ingredient_id):  # -- TESTED
    """Create new recipe_ingredient in db."""

    new_recipe_ingredient = RecipeIngredient(recipe_id=recipe_id,
                                             ingredient_id=ingredient_id)
    db.session.add(new_recipe_ingredient)
    db.session.commit()
def getListIngredient():

    all_ingr_list = []
    ingr_list = []

    ingredients = RecipeIngredient.getAllIngredients()

    recipe = ingredients[0].recipe_fk

    for ingr in ingredients:

        if ingr.recipe_fk == recipe:

            ingr_list.append(ingr.ingredient_name)

        else:    

            recipe = ingr.recipe_fk

            all_ingr_list.append(ingr_list)  

            ingr_list = [ingr.ingredient_name]

    print "ALL_LIST", all_ingr_list

    return all_ingr_list        
def getListIngredient():

    all_ingr_list = []
    ingr_list = []

    ingredients = RecipeIngredient.getAllIngredients()

    recipe = ingredients[0].recipe_fk

    for ingr in ingredients:

        if ingr.recipe_fk == recipe:

            ingr_list.append(ingr.ingredient_name)

        else:

            recipe = ingr.recipe_fk

            all_ingr_list.append(ingr_list)

            ingr_list = [ingr.ingredient_name]

    print "ALL_LIST", all_ingr_list

    return all_ingr_list
예제 #5
0
def load_recipes_from_file(recipe_filename):
    """Load all recipes into database."""

    for row in open(recipe_filename):
        recipe_info = row.rstrip().split("\t")
        
        cuisine, ingredients_list = recipe_info[0], recipe_info[1:]

        cuisine_obj = Cuisine.query.filter_by(name = cuisine).first()

        if cuisine_obj:
            # cuisine_id = cuisine_obj.cuisine_id

            recipe = Recipe(cuisine_id=cuisine_obj.id)
            db.session.add(recipe)
        
        db.session.commit()

        for ingredient_row in ingredients_list:
            ingredient = ingredient_row[:]

            ingredient_obj = Ingredient.query.filter_by(name = ingredient).first()

            if ingredient_obj:
                recipe_ingredient = RecipeIngredient(ingredient_id = ingredient_obj.id, recipe_id = recipe.id)
                db.session.add(recipe_ingredient)
        db.session.commit()             
예제 #6
0
def create_recipe_ingredient(recipe, ingredient):
    """Creates relationship between a recipe and its ingredient"""

    recipe_ingredient = RecipeIngredient(recipe=recipe, ingredient=ingredient)

    db.session.add(recipe_ingredient)
    db.session.commit()

    return recipe_ingredient
예제 #7
0
def create_recipe_ingredient(recipe_id, ingredient_id, measurement):
    """Create and return a new recipe ingredient."""

    recipe_ingredient = RecipeIngredient(recipe_id=recipe_id,
                                         ingredient_id=ingredient_id,
                                         measurement=measurement)

    db.session.add(recipe_ingredient)
    db.session.commit()

    return recipe_ingredient
예제 #8
0
def add_recipe_ingredient(recipe_id, ing_id, meas_unit, mass_qty):
    """Adds recipe's ingredient to RecipeIngredient table in DB."""

    new_recipe_ingredient = RecipeIngredient(recipe_id=recipe_id,
                                             ing_id=ing_id,
                                             meas_unit=meas_unit,
                                             mass_qty=mass_qty)

    db.session.add(new_recipe_ingredient)
    db.session.commit()

    return new_recipe_ingredient
예제 #9
0
def load_recipe_ingredients(ingredients_per_recipe):
    """ Load ingredient/recipe relationships in RECIPE_INGREDIENTS table """

    print "Adding Recipe/Ingredient Relationshps"

    for key, value in ingredients_per_recipe:
        recipe_url = key
        for item in value:
            ingredient_name = item
            relationship = RecipeIngredient(recipe_url=recipe_url,
                                            ingredient_name=ingredient_name)

            db.session.add(relationship)

    db.session.commit()
def makeDict(ingredient, recipe_lists, counter=0, seen=None):

    """
        It takes an ingredient and a list of recipe ingredients (recipe_lists)

        It returns a dictionary with all the ingredients (keys) that match the 

        given ingredient across all of the recipes in the recipe_lists and 

        their weight (value), sorted by value.

        The weight measure the number of times that ingredient is in combination

        with the given ingredient.

        OUTPUT: dictionary like { ingredient A: 5, ingredient B: 4, ... }

    """

    chains = {}

    counter += 1

    if not seen:
        seen= set()

    if ingredient not in seen:

        seen.add(ingredient)

    chains['name'] = ingredient
    chains['children']=[]

    for rec in recipe_lists:

        ingrs = RecipeIngredient.getAllIngredientsNamesByRecipe(rec.recipe_fk)

        for ingr in ingrs:

            if ingr[0] not in seen:
            # children = [s for s in ingrs if s not in seen]
                seen.add(ingr[0])

                chains['children'].append(ingr[0])

    print "chains",chains

    return chains
def makeDict(ingredient, recipe_lists, counter=0, seen=None):
    """
        It takes an ingredient and a list of recipe ingredients (recipe_lists)

        It returns a dictionary with all the ingredients (keys) that match the 

        given ingredient across all of the recipes in the recipe_lists and 

        their weight (value), sorted by value.

        The weight measure the number of times that ingredient is in combination

        with the given ingredient.

        OUTPUT: dictionary like { ingredient A: 5, ingredient B: 4, ... }

    """

    chains = {}

    counter += 1

    if not seen:
        seen = set()

    if ingredient not in seen:

        seen.add(ingredient)

    chains['name'] = ingredient
    chains['children'] = []

    for rec in recipe_lists:

        ingrs = RecipeIngredient.getAllIngredientsNamesByRecipe(rec.recipe_fk)

        for ingr in ingrs:

            if ingr[0] not in seen:
                # children = [s for s in ingrs if s not in seen]
                seen.add(ingr[0])

                chains['children'].append(ingr[0])

    print "chains", chains

    return chains
예제 #12
0
def load_recipe_ingredients(urls_plus_ingredients):
    """ Populate association table of recipes to ingredients in each recipe """

    print "Adding All Recipe/Ingredient Associations"

    # RecipeIngredient.query.delete()

    all_recipe_ids = db.session.query(Recipe.recipe_id,
                                      Recipe.recipe_url).all()

    for pair in all_recipe_ids:
        recipe_url = pair[1]
        for item in urls_plus_ingredients[recipe_url]:
            ingredient_name = item
            ingredient_id = Ingredient.query.filter_by(
                ingredient_name=ingredient_name).first().ingredient_id

            recipe_ingredient = RecipeIngredient(recipe_id=pair[0],
                                                 ingredient_id=ingredient_id)

            db.session.add(recipe_ingredient)

    db.session.commit()
예제 #13
0
def load_recipe_ingredients(recipe_name, all_ingredients, scrape_ingredients):
    """Load recipeingredients into database."""

    print "Recipe Ingredients"

    recipe_id = Recipe.query.filter_by(
        recipe_name=recipe_name).first().recipe_id

    for i in range(len(scrape_ingredients)):
        original_string = scrape_ingredients[i]['stripped_ingredient']
        ingredient_id = None
        ingredient_ids = []
        for ingredient in all_ingredients:
            name = ingredient['name']
            name_words = name.split()

            # to make sure the original string from webscrape
            # matches the correct ingredient name received from the api
            if len(name_words) > 1:
                if name_words[-1] in original_string and name_words[
                        -2] in original_string:
                    ingredient_id = Ingredient.query.filter_by(
                        ingredient_name=name).first().ingredient_id
                    ingredient_ids.append(ingredient_id)
            elif len(name_words) == 1:
                if name in original_string:
                    ingredient_id = Ingredient.query.filter_by(
                        ingredient_name=name).first().ingredient_id
                    ingredient_ids.append(ingredient_id)

        new_ingredient = None
        if not ingredient_ids:
            new_string = original_string
            if re.search(r'\(.*\)', new_string):
                new_string = ''.join(
                    filter(None, re.split(r'\(.*\)', new_string)))
            if re.search(r'[A-Za-z]+ed', new_string):
                new_string = ''.join(
                    filter(None, re.split(r'[A-Za-z]+ed', new_string)))
            if re.search(r'\,.*', new_string):
                new_string = ''.join(
                    filter(None, re.split(r'\,.*', new_string)))
            new_string = new_string.split()
            for i in range(len(new_string)):
                new_string[i] = new_string[i].strip()
            new_string = ' '.join(new_string)
            if not Ingredient.query.filter_by(
                    ingredient_name=new_string).all():
                new_ingredient = Ingredient(ingredient_name=new_string)
                db.session.add(new_ingredient)

        if not ingredient_id:
            ingredient_id = Ingredient.query.filter_by(
                ingredient_name=new_string).first().ingredient_id
        # to make sure the same ingredient is not added to the same
        # recipe multiple times
        if not RecipeIngredient.query.filter_by(
                original_string=original_string).all():
            if scrape_ingredients[i].get('link'):
                link = scrape_ingredients[i]['link']
                recipeingredient = RecipeIngredient(
                    original_string=original_string,
                    recipe_id=recipe_id,
                    ingredient_id=ingredient_id,
                    link=link)
            else:
                recipeingredient = RecipeIngredient(
                    original_string=original_string,
                    recipe_id=recipe_id,
                    ingredient_id=ingredient_id)
            db.session.add(recipeingredient)

    db.session.commit()
예제 #14
0
def get_recipe_attributes_db(name, p):
	"""Get the recipes' attributes."""


	payload = { 'q': name,
				'app_id': EDAMAM_RECIPE_SEARCH_APPLICATION_ID,
				'app_key': EDAMAM_RECIPE_SEARCH_APPLICATION_KEY }
	
	response = requests.get(EDAMAM_URL, params=payload)
	data = response.json()


	if response.ok:
		for n in range(p):
			recipe_obj = Recipe(recipe_name=data["hits"][n]["recipe"]["label"],
								recipe_url=data["hits"][n]["recipe"]["uri"],
								recipe_image=data["hits"][n]["recipe"]["image"],
								directions=data["hits"][n]["recipe"]["url"],
								servings=data["hits"][n]["recipe"]["yield"],
								calories=data["hits"][n]["recipe"]["calories"],
								carbohydrates=data["hits"][n]["recipe"]["totalNutrients"]["CHOCDF"]["quantity"],
								fat=data["hits"][n]["recipe"]["totalNutrients"]["FAT"]["quantity"],
								protein=data["hits"][n]["recipe"]["totalNutrients"]["PROCNT"]["quantity"])
			db.session.add(recipe_obj)
			db.session.commit()


			recipe_labels_1 = data["hits"][n]["recipe"]["dietLabels"]
			recipe_labels = data["hits"][n]["recipe"]["healthLabels"]

			for rec_lab_1 in recipe_labels_1:
				recipe_labels.append(rec_lab_1)

			diet_id_lst = []
			for recipe_label in recipe_labels:
				label = Diet.query.filter_by(diet_name=recipe_label).first()
				diet_id = label.diet_id
				diet_id_lst.append(diet_id)



			for diet_id in diet_id_lst:
				diet_connection = RecipeDiet(recipe_id=recipe_obj.recipe_id, diet_id=diet_id)
				db.session.add(diet_connection)

			recipe_cautions = data["hits"][n]["recipe"]["cautions"]

			cautions_id_lst = []

			for caution in recipe_cautions:

				caution_obj = Allergy.query.filter_by(allergy_name=caution).first()

				caution_id = caution_obj.allergy_id
				cautions_id_lst.append(caution_id)




			for caution_id in cautions_id_lst:
				caution_connection = RecipeAllergy(recipe_id=recipe_obj.recipe_id, allergy_id=caution_id)
				db.session.add(caution_connection)




			ingredients = data["hits"][n]["recipe"]["ingredientLines"]
			
			for i, ingredient in enumerate(ingredients):
				ingredient_obj = Ingredient(ingredient_name=ingredient)
				db.session.add(ingredient_obj)
				db.session.commit()
				recipe_ingredient_obj = RecipeIngredient(ingredient_id=ingredient_obj.ingredient_id, 
														recipe_id=recipe_obj.recipe_id, 
														amount=data["hits"][n]["recipe"]["ingredients"][i]["weight"])
				db.session.add(recipe_ingredient_obj)	
			print (recipe_cautions)

		db.session.commit()
def addRecipe(img_file, title, description, cat_code, servings,
             cooktime, skillLevel, cuisine, ingredients, steps, user):

    """ It adds a recipe, ingredients, recipe steps, recipe_user"""

    try:
        # Saves the img file in the directory
        filename = img_file

        print "IMG_FILE" ,img_file

        # If img is not from a website
        # if img_file and allowed_file(img_file.filename) and 'http' not in img_file:

        #     filename = secure_filename(img_file.filename)
            # print "FILENAME" , filename
            # img_file.save(os.path.join(UPLOAD_FOLDER, filename))

        # Add recipe in 'recipes' Table
        Recipe.addRecipe(title, description, filename, cat_code,
                 servings, cooktime, skillLevel,cuisine)

        # Finds the recipe_id
        recipeIds= db.session.query(func.max(Recipe.recipe_id)).one()
        recipeFk = recipeIds[0]
        print "RECIPE ID:  ",recipeFk

        # ingredients = ingredients
        print "INGREDIENTS LIST", ingredients

        for ingredient in ingredients:
            name = ingredient["name"]
            qty = ingredient["qty"]
            unit = ingredient["unit"]
            print "INGREDIENT UNICODE", ingredient

            # Add ingredients in 'RecipeIngredient'
            RecipeIngredient.addIngredients(recipeFk, name, qty, unit)
            # Add ingredients in 'Ingredients'
            Ingredient.addIngredients(name)


        for i in range(len(steps)):
            print "STEP%d" % i
            print "step value: ", steps[i]
            # Add steps in 'recipe_step'
            RecipeStep.addRecipeStep(recipeFk,i+1,steps[i])

        if 'User' in session:
            RecipeUser.addRecipeForUser(recipeFk,session['User'])

        db.session.commit()

        # Recipe.updateRecipeImg(title=title, cat_code=cat_code)

        message = {

            'msg': "Recipe successfully added",
            'recipeid': recipeFk
        }

        return recipeFk

    except Exception, error:
        return "Error: %s" % error
예제 #16
0
def add_new_recipe(user_id, recipe_id):
    """Add recipe to user's recipe box"""
    user = User.query.filter(User.user_id == user_id).one()
    saved_recipe = get_recipe_info(recipe_id)
    saved_recipe_title = saved_recipe['title'].encode('utf-8')
    saved_recipe_source_name = saved_recipe.get('sourceName')
    saved_recipe_source_url = saved_recipe.get('sourceUrl')
    saved_recipe_image_url = saved_recipe.get('image')
    print saved_recipe_image_url

    steps = saved_recipe['analyzedInstructions'][0]['steps']
    step_instructions = []  #create list for all instruction steps

    for step in steps:
        if len(step['step']) > 1:
            step_instructions.append(step['step'])

    if not Recipe.query.filter(Recipe.url == saved_recipe_source_url).all():
        #Create new recipe for database if does not exist already
        new_recipe = Recipe(title=saved_recipe_title,
                            source_name=saved_recipe_source_name,
                            url=saved_recipe_source_url,
                            instructions=step_instructions,
                            image=saved_recipe_image_url)

        db.session.add(new_recipe)
        db.session.flush()

        new_recipe_id = new_recipe.recipe_id

        ingredients = saved_recipe[
            'extendedIngredients']  # list of dictionaries. each dict contains info about all ingredients, including 'name', 'amount', 'unit'
        #Create Ingredient instances for ingredients that do not already exist in db
        for ingredient in ingredients:
            ingredient_name = ingredient['name']
            ingredient_amt = round(ingredient['amount'], 2)
            ingredient_unit = ingredient['unitShort']
            if not Ingredient.query.filter(
                    Ingredient.ingred_name == ingredient_name).all(
                    ):  #if ingredient not in db. add to it
                new_ingred = Ingredient(ingred_name=ingredient_name)
                db.session.add(new_ingred)
                db.session.flush()

            ingred_id = Ingredient.query.filter(
                Ingredient.ingred_name == ingredient_name).one().ingred_id

            #Create RecipeIngredient instances
            ingred_info = str(ingredient_amt) + " " + ingredient_unit.lower(
            ) + " - " + ingredient_name.title()

            new_recipe_ingred = RecipeIngredient(recipe_id=new_recipe_id,
                                                 ingred_id=ingred_id,
                                                 ingred_info=ingred_info)
            db.session.add(new_recipe_ingred)
            db.session.flush()

    existing_recipe_id = Recipe.query.filter(
        Recipe.url == saved_recipe_source_url).one().recipe_id

    if not UserRecipe.query.filter(UserRecipe.user_id == user_id,
                                   UserRecipe.recipe_id
                                   == existing_recipe_id).all():
        new_user_recipe = UserRecipe(recipe_id=existing_recipe_id,
                                     user_id=user_id,
                                     cooked=False)
        db.session.add(new_user_recipe)
        db.session.flush()

    db.session.commit()

    return jsonify({})
예제 #17
0
def add_meal_to_db(user_id, recipe_name, recipe_url, recipe_image, directions,
                   servings, calories, carbohydrates, fat, protein,
                   ingredients, cautions, diets):
    """Helper function."""

    old_recipe = Recipe.query.filter_by(recipe_url=recipe_url).first()

    new_cautions = ""
    for char in cautions:
        if char == "'":
            new_cautions += '"'
        else:
            new_cautions += char

    new_cautions_lst = json.loads(new_cautions)

    new_diets = ""
    for char in diets:
        if char == "'":
            new_diets += '"'
        else:
            new_diets += char

    new_diets_lst = json.loads(new_diets)

    if old_recipe is not None:
        new_recipe_obj = old_recipe
    else:
        new_recipe_obj = Recipe(recipe_name=recipe_name,
                                recipe_url=recipe_url,
                                recipe_image=recipe_image,
                                directions=directions,
                                servings=servings,
                                calories=calories,
                                carbohydrates=carbohydrates,
                                fat=fat,
                                protein=protein)
        db.session.add(new_recipe_obj)
        db.session.commit()

        for caution in new_cautions_lst:

            allergy = Allergy.query.filter_by(allergy_name=caution).first()

            new_caution_recipe_obj = RecipeAllergy(
                recipe_id=new_recipe_obj.recipe_id,
                allergy_id=allergy.allergy_id)
            db.session.add(new_caution_recipe_obj)

        for diet in new_diets_lst:

            diet = Diet.query.filter_by(diet_name=diet).first()

            new_diet_recipe_obj = RecipeDiet(
                recipe_id=new_recipe_obj.recipe_id, diet_id=diet.diet_id)
            db.session.add(new_diet_recipe_obj)

    db.session.commit()

    recipe = Recipe.query.filter_by(recipe_name=recipe_name).first()
    plan = Plan.query.filter_by(user_id=user_id).order_by(
        Plan.plan_id.desc()).first()

    plan_recipe_obj = PlanRecipe(plan_id=plan.plan_id,
                                 recipe_id=recipe.recipe_id)
    db.session.add(plan_recipe_obj)
    db.session.commit()

    new_ingredients = ""
    for char in ingredients:
        if char == "'":
            new_ingredients += '"'
        else:
            new_ingredients += char

    new_ingredients_dict = json.loads(new_ingredients)

    for ingredient in new_ingredients_dict:
        ingredient_name = ingredient["text"]
        amount = ingredient["weight"]

        ingredient = Ingredient.query.filter_by(
            ingredient_name=ingredient_name).first()
        if ingredient is None:
            new_ingredient_obj = Ingredient(ingredient_name=ingredient_name)
            db.session.add(new_ingredient_obj)
            db.session.commit()

            ingredient = Ingredient.query.filter_by(
                ingredient_name=ingredient_name).first()
            new_recipe_ingredient_obj = RecipeIngredient(
                recipe_id=recipe.recipe_id,
                ingredient_id=ingredient.ingredient_id,
                amount=amount)
            db.session.add(new_recipe_ingredient_obj)
            db.session.commit()