def get_recipe_details(best_recipe_combo, user_profile_data):
    profile_init = rootprofile.UserProfile(user_profile_data)
    recipe_init = recipes.Recipes(profile_init)
    # get ingredients from the recipe list
    recipe_details = []
    i = 0
    for rec_idx in best_recipe_combo:
        recipe_details.append(recipe_init.recipe_clean[rec_idx])
        # recipe_details = recipe_details.update(rec_idx=recipe_init.recipe_clean[rec_idx])
    # print(recipe_details)
    return recipe_details
def get_shopping_list(best_recipe_combo, user_profile_data):
    profile_init = rootprofile.UserProfile(user_profile_data)
    recipe_init = recipes.Recipes(profile_init)
    # get ingredients from the recipe list
    ingredient_list = []
    for rec_idx in best_recipe_combo:
        ingredient_list = ingredient_list + recipe_init.recipe_clean[rec_idx][
            'ingredients']

    while '' in ingredient_list:
        ingredient_list.remove('')
    return (ingredient_list)
def get_recipe_list(session, user):
    user_profile_data = pd.read_json(session['data'])

    # Run Recipe Recomendation Alg
    profile_init = rootprofile.UserProfile(user_profile_data)
    recipe_init = recipes.Recipes(profile_init)

    # Check for any recipes to ignore
    ignore_list = get_user_ignore_responses(session, user)

    # number of meal preferences
    if 'meals_per_week' not in user_profile_data.keys():
        meals_per_week = 6  # Default
    elif user_profile_data.meals_per_week.values[0] == '':
        meals_per_week = 6  # Default - User did not specify in survey
    else:
        meals_per_week = int(user_profile_data.meals_per_week.values[0])

    # Algroithm initiation settings
    num_generations = 10
    amount_per_population = 30
    amount_parents_mating = 10
    # Run GA Recipe/Meal Plan Optimization
    # (macro_list=profile_init.macro_label_list)
    GA = models.GA(macro_list=profile_init.macro_label_list)
    label_of_weights = GA.labels
    weekly_diet_amount = (GA.user_df[GA.macro_labels] / 3.0) * meals_per_week
    best_recipe_combo, weekly_diet_amount = GA.AMGA(
        num_generations, meals_per_week, amount_per_population,
        amount_parents_mating, weekly_diet_amount, ignore_list)
    # user_profile_data['list_keys'] = [best_recipe_combo]
    # user_profile_data.list_keys = best_recipe_combo
    user_profile_data['plan_exists'] = True
    recipe_names = []
    for rec_idx in best_recipe_combo:
        recipe_names.append(recipe_init.recipe_clean[rec_idx]['name'])
    # user_profile_data.recipe_names = recipe_names
    # user_profile_data['recipe_names'] = [recipe_names]

    user_meal_plan = pd.DataFrame(data={
        'recipe_id': best_recipe_combo,
        'recipe_name': recipe_names
    })
    session['user_meal_plan'] = user_meal_plan.to_json()

    df_ingredient_NDB = get_ingredient_NDB_number(session, best_recipe_combo)
    # session['df_ingredient_NDB'] = df_ingredient_NDB.to_json()

    return best_recipe_combo, weekly_diet_amount, user_profile_data, df_ingredient_NDB
def create_recipe_rec_df(session, user_meal_plan):
    user_profile_data = pd.read_json(session['data'])
    #// START: initialize for df creation to plot bar/radar plots
    profile_init = rootprofile.UserProfile(user_profile_data)
    recipe_init = recipes.Recipes(profile_init)
    list_keys = user_meal_plan['recipe_id'].get_values()
    #// END

    #// START: loop through each recipe and convert into mathmatical nutrition space
    # return:
    # df_list -> for stacked barplot graph of each recipe individual and what is inside the recipe
    # df_summed_list -> for radar and barplot graph of meal plan
    # recipe_id_list -> used book keeping/linking
    # name_list -> used to help name and make images pretty
    df_list = []
    df_summed_list = []
    recipe_id_list = []
    name_list = []
    recipe_itr = 0
    for recipe in list_keys:
        # print("*******************************", "Recipe Itr: ", recipe_itr, "Out of: ", len(list_keys) - 1, recipe)
        try:
            temp_recipe_df = recipe_init.recipe_list_to_conversion_factor_list(
                recipe)
            multiplier_normalizer = profile_init.profile_macro_filtered_df[
                'calories'].get_values()[0] / 3.0
            multiplier_normalizer = multiplier_normalizer / temp_recipe_df[
                'Energy (kcal)'].sum()
            for column in [profile_init.macro_list + profile_init.micro_list]:
                temp_recipe_df[
                    column] = temp_recipe_df[column] * multiplier_normalizer
            df_list.append(temp_recipe_df)
            df_summed_list.append(
                temp_recipe_df.loc[:, profile_init.macro_list +
                                   profile_init.micro_list].sum().to_frame())
            name_list.append(recipe_init.recipe_clean[recipe]['name'])
            recipe_id_list.append(recipe)
        except:
            print("FAILED, Recipe concatenation...RECIPE=", recipe)
        recipe_itr += 1

    df = pd.concat(df_summed_list, axis=1)
    df = df.T.reset_index(drop=True)
    se = pd.Series(name_list)
    df['recipe_name'] = se.values
    se2 = pd.Series(recipe_id_list)
    df['recipe_id'] = se2.values
    return df, df_list, df_summed_list, profile_init, name_list
def run_master_ingredient_sub(user_profile_data):
    profile_init = rootprofile.UserProfile(user_profile_data)
    recipe_init = recipes.Recipes(profile_init)
    research_init = research.Research(profile_init)

    # Run Subsitution option for Ingredients
    recipe_itr = 0
    df_list = []
    df_summed_list = []
    recipe_id_list = []
    name_list = []

    if 'list_keys' not in user_profile_data.keys():
        # If no recipes exist for user create a meal plan
        # if len(best_recipe_combo) == 0:
        print("****** Running get recipes ****")
        best_recipe_combo, weekly_diet_amount, user_profile_data = get_recipe_list(
            user_profile_data, recipe_init)

    for recipe in user_profile_data.list_keys:
        print(recipe)
        temp_recipe_df = recipe_init.recipe_list_to_conversion_factor_list(
            recipe)
        df_list.append(temp_recipe_df)
        df_summed_list.append(
            temp_recipe_df.loc[:, profile_init.macro_list +
                               profile_init.micro_list].sum().to_frame())
        name_list.append(recipe_init.recipe_clean[recipe]['name'])
        recipe_id_list.append(recipe)
        recipe_itr += 1

    # SMASH Files together for optimization mapp
    df = pd.concat(df_summed_list, axis=1)
    df = df.T.reset_index(drop=True)
    se = pd.Series(name_list)
    df['recipe_name'] = se.values
    se2 = pd.Series(recipe_id_list)
    df['recipe_id'] = se2.values

    # Create Recipe Visuals for Display
    recipe_visuals(df_list, df, profile_init, name_list)

    return df, df_list
def get_ingredient_NDB_number(session, best_recipe_combo):
    # Returns Ingredits in recipes to dataframe
    # Save ingredients to Session Data
    profile_init = rootprofile.UserProfile(pd.read_json(session['data']))
    recipe_init = recipes.Recipes(profile_init)
    df_ingredient_NDB = pd.DataFrame()
    for recipe_id in best_recipe_combo:
        recipe_data = recipe_init.recipe_list_to_conversion_factor_list(
            recipe_id)[['Description', 'NDB_NO']]
        df_ingredient_NDBi = pd.DataFrame(recipe_data)
        df_ingredient_NDBi['recipe_id'] = recipe_id
        if df_ingredient_NDB.empty:
            df_ingredient_NDB = df_ingredient_NDBi
        else:
            df_ingredient_NDB = pd.concat(
                [df_ingredient_NDB, df_ingredient_NDBi])

    df_ingredient_NDB = df_ingredient_NDB.reset_index()
    # print(df_ingredient_NDB.recipe_id.unique())

    return (df_ingredient_NDB)
def get_recipe_list(user_profile_data, user):
    # Run Recipe Recomendation Alg
    profile_init = rootprofile.UserProfile(user_profile_data)
    recipe_init = recipes.Recipes(profile_init)

    # Check for any recipes to ignore
    user_profile_data = get_user_ignore_responses(user_profile_data, user)
    ignore_list = user_profile_data.ignore_list

    # number of meal preferences
    if 'meals_per_week' not in user_profile_data.keys():
        meals_per_week = 6  # Default
    elif user_profile_data.meals_per_week.values[0] == '':
        meals_per_week = 6  # Default - User did not specify in survey
    else:
        meals_per_week = int(user_profile_data.meals_per_week.values[0])

    # Algroithm initiation settings
    num_generations = 10
    amount_per_population = 30
    amount_parents_mating = 10

    # Run GA Recipe/Meal Plan Optimization
    GA = models.GA()
    label_of_weights = GA.labels
    weekly_diet_amount = (GA.user_df[GA.macro_labels] / 3.0) * meals_per_week
    best_recipe_combo, weekly_diet_amount = GA.AMGA(
        num_generations, meals_per_week, amount_per_population,
        amount_parents_mating, weekly_diet_amount, ignore_list)
    user_profile_data.list_keys = best_recipe_combo
    recipe_names = []
    for rec_idx in best_recipe_combo:
        recipe_names.append(recipe_init.recipe_clean[rec_idx]['name'])
    user_profile_data.recipe_names = recipe_names

    return best_recipe_combo, weekly_diet_amount, user_profile_data
示例#8
0
def get_pantry_suggetsions(user_profile_data,
                           ingredient_list,
                           num_suggested_recipes=5):
    # Input: list of pantry items and nutriotial Goals
    # Output: List of x recipe ID

    # initlize user needs:
    profile_init = rootprofile.UserProfile(user_profile_data)
    recipe_init = recipes.Recipes(profile_init)
    model_init = models.Models(recipe_init)

    ## Virtual Pantry to recipe suggestion
    # ingredient_list = ['12 large egg', '12 oz mayonnaise', '12 oz BBQ Sauce', '24 oz mustard', '6 skinless chicken breast',
    #                    '12 salmon burgers', '12 pita', '2 zucchini', '4 onions', '1 pound mushrooms',
    #                    '12 cups lettuce', '24 beer', '1 whole duck', '4 oranges', '2 potatoes', '2 red peppers',
    #                    '4 pounds white rice', '48 oz peanut butter', '6 sausage', '4 pounds ham', '1 cauliflower',
    #                    '6 sticks butter', '12 cups sugar', '12 brown sugar', 'water', '1 whole lemon', '0.25 cup lemon juice',
    #                    '10 whole apples', '1 tomato', '0.25 cup Lime juice', '1 bottle rum', '12 egg whites', '1 whole garlic']

    pantry_list = []
    pantry_tag_list = []
    for ingredient in ingredient_list:
        ingredient_filtered = model_init.transform_data_for_tokenizer(
            ingredient)
        tokens = model_init.tokenizer.texts_to_matrix([ingredient_filtered])
        prediction_key = str(
            model_init.loaded_model.predict(
                np.array(tokens)).argsort()[0][-1:][::-1][0])
        for item in model_init.NDB_tag_unique_unique_dict.items():
            if item[1] == int(prediction_key):
                tag_key = item[0]
                break
        prediction_value = recipe_init.nutrition_init.NDB_NO_lookup(
            tag_key, filter_list=['Description']).get_values()[0][0]
        pantry_tag_list.append(tag_key)

    recipe_id_list = []
    percent_overlap_list = []
    ingredient_pantry_list = []
    recipe_full_list = []
    for recipe in recipe_init.recipe_clean.keys():
        temp_recipe_list = []
        itr = 0
        while itr < len(recipe_init.recipe_clean[recipe]["NDB_NO_tags"]):
            try:
                if recipe_init.nutrition_init.NDB_NO_lookup(
                        recipe_init.recipe_clean[recipe]["NDB_NO_tags"][itr],
                        filter_list=['Category']).get_values()[0][0] not in [
                            'Fats_and_Oils', 'Spices_and_Herbs'
                        ]:
                    temp_recipe_list.append(
                        recipe_init.recipe_clean[recipe]["NDB_NO_tags"][itr])
            except:
                pass
            itr += 1

        overlap_list = list(
            set(temp_recipe_list).intersection(pantry_tag_list))
        amount_overlap = len(overlap_list)
        amount_recipe = len(temp_recipe_list)

        recipe_id_list.append(recipe)
        try:
            percent_overlap_list.append(amount_overlap / amount_recipe)
            ingredient_pantry_list.append(overlap_list)
            recipe_full_list.append(temp_recipe_list)
        except:
            percent_overlap_list.append(0.0)
            ingredient_pantry_list.append([])
            recipe_full_list.append([])

    df = pd.DataFrame({
        'recipe_id': recipe_id_list,
        'percent_overlap': percent_overlap_list,
        'ingredient_pantry_list': ingredient_pantry_list,
        'recipe_full_list': recipe_full_list
    })

    df = df.sort_values(by='percent_overlap', ascending=False).reset_index()[[
        'recipe_id', 'percent_overlap', 'ingredient_pantry_list',
        'recipe_full_list'
    ]]

    # create list of recipe ids
    recipe_ids = df.recipe_id.values[:num_suggested_recipes]
    return recipe_ids
def get_single_ingredient_replacement(session, ingredientSubForm, recipe_id,
                                      nbd_no):
    # Single food replacement based on macros

    # Get intial information on user
    profile_init = rootprofile.UserProfile(pd.read_json(session['data']))
    recipe_init = recipes.Recipes(profile_init)
    research_init = research.Research(profile_init)
    ingredient_list = recipe_init.recipe_clean[recipe_id]['ingredients']

    # temp_recipe_dict = {}
    # temp_recipe_dict[recipe_id] = recipe_init.recipe_clean[recipe_id].copy()
    if ingredientSubForm.ingredientSub.data is not '':
        replacement_key_dict = {
            1: 'Baked',
            2: 'Beef',
            3: 'Beverages',
            4: 'Breakfast_Cereals',
            5: 'Cereal_Grains_and_Pasta',
            6: 'Dairy_and_Egg',
            7: 'Fats_and_Oils',
            8: 'Finfish_and_Shellfish',
            9: 'Fruits_and_Fruit_Juices',
            10: 'Lamb_Veal_and_Game',
            11: 'Legumes_and_Legume',
            12: 'Nut_and_Seed',
            13: 'Pork',
            14: 'Poultry',
            15: 'Sausages_and_Luncheon_Meats',
            16: 'Soups_Sauces_and_Gravies',
            17: 'Spices_and_Herbs',
            18: 'Sweets',
            19: 'Vegetables_and_Vegetable'
        }

        # split_raw_return = raw_input_return.split(",")
        # "05097":8,"44005":7
        # TODO: improve to allow user to input multiple replacements
        # master_tag_list = []
        # replace_list = []
        # for replacement_ndb_tag in range(len(ingredientSubForm.ingredientSub.data)):
        # replacement_ndb_tag = replacement.split(":")[0].lstrip(" ")
        # replacement_category_key = int(replacement.split(":")[-1].strip("'").strip('"'))

        # Get the replacement_ndb_tag from the entry form

        # replacement_ndb_tag = ingredientSubForm.ingredientSub.data
        replacement_ndb_tag = nbd_no
        replacement_category_key = ingredientSubForm.foodType.data
        tag_list, potential_switches = research_init.macro_space_distance_top_n(
            4, replacement_ndb_tag,
            [replacement_key_dict[int(replacement_category_key)]])

        # Verify one of top three option is not the same as input
        for i, tag in enumerate(tag_list):
            if tag == replacement_ndb_tag:
                tag_list.remove(tag)
                potential_switches.remove(potential_switches[i])
        switch_df = pd.DataFrame(data={
            'tags': tag_list[:3],
            "potential_switches": potential_switches[:3]
        })
        session['potential_switches'] = potential_switches

        # # Get Visuals Data
        # print("******Ingredeint Sub Visual****")
        # # Split User input into the item to replace and type, format: ['"44005":7']
        # master_tag_list = []
        # replace_list = []
        #
        # temp_recipe_dict = {}
        # temp_recipe_dict[recipe_id] = recipe_init.recipe_clean[recipe_id].copy()
        #
        # new_recipe_dict = recipe_init.recipe_alternitive_create(replacement_ndb_tag, tag_list, temp_recipe_dict)
        # replace_list.append(replacement_ndb_tag)
        # master_tag_list.append(tag_list)
        #
        # # Create an iterable list. Change Masetr tage list from:
        # # master_tag_list =  [['"04042"', '"04618"', '"04545"']] to
        # # iterable_list =  [('"04042"',), ('"04618"',), ('"04545"',)]
        # iterable_list = list(itertools.product(*master_tag_list))
        # new_recipe_dict = recipe_init.recipe_alternitive_iter_create(replace_list, iterable_list, temp_recipe_dict)
        # temp = recipe_init.recipe_list_to_conversion_factor_list(recipe_id)
        # df_list = []
        # name_list = []
        # for recipe in new_recipe_dict.keys():
        #     temp_recipe_df = recipe_init.recipe_list_to_conversion_factor_list(recipe, dict=new_recipe_dict)
        #     df_list.append(temp_recipe_df)
        #     name_list.append(new_recipe_dict[recipe]['name'])
        # print('*____ Visuals ___*')
        # # print("df_list", df_list)
        # # print("profile_init", profile_init)
        # # print('name_list', name_list)
        # visualizations.Plots(df_list, profile_init).bar_plot_recipe(name_list, 'test_replacement_barplot', session)
        # # print("visual 1")
        # # visualizations.Plots(df_list, profile_init).radar_plot_recipe(name_list, 'test_replacement_radar_plot')
        # # print("visual 2")

        return switch_df, potential_switches[:3]