Exemplo n.º 1
0
 def testAddEleANDreadWriteJSON(self):
     recipe = R.Recipe()
     bead1 = G.Glass()
     bead1.addElement("Al", 2)
     bead1.addElement("O", 10)
     bead2 = G.Glass()
     bead2.addElement("Ti", 2)
     bead2.addElement("O", 10)
     recipe.addElementWithBeadInRange(bead1, "Al", 8, 12, 1)
     recipe.addElementWithBeadInRange(bead2, "Ti", 3, 6, 1)
     recipe._checkSizes()
     recipe.writeJSON("../test/recipe")
     recipe2 = R.Recipe()
     recipe2.readJSON("../test/recipe")
     recipe2.writeJSON("../test/recipe2")
     self.assertEqual(11, recipe.index2percent(0, 3))
     self.assertEqual(2, recipe.percent2index(0, 10))
     recipe.initInventory()
     recipe.suggestNext()
     recipe.addInventory(8, 3)
     recipe.suggestNext()
     recipe.addInventory(8, 5)
     recipe.suggestNext()
     recipe.addInventory(8, 4)
     recipe.suggestNext()
     recipe2.writeJSON("../test/recipe")
Exemplo n.º 2
0
    def test_scrape_recipe_format2(self):

        self.maxDiff = None

        testfile = open("testfiles/format2_1.html", encoding="utf-8")
        scraped_recipe = recipe.scrape_recipe(testfile.read())
        testfile.close()

        recipe1 = recipe.Recipe(
            title="Broccoli Cheese Soup",
            url="https://www.allrecipes.com/recipe/13045/broccoli-cheese-soup/",
            rating="4.61602209944751",
            numreviews="2896",
            ingredients=[
                "½ cup butter", "1 onion, chopped",
                "1 (16 ounce) package frozen chopped broccoli",
                "4 (14.5 ounce) cans chicken broth",
                "1 (1 pound) loaf processed cheese food, cubed", "2 cups milk",
                "1 tablespoon garlic powder", "⅔ cup cornstarch", "1 cup water"
            ],
            instructions=
            ('In a stockpot, melt butter over medium heat. Cook onion in butter until softened. Stir in broccoli, and cover with chicken broth. Simmer until broccoli is tender, 10 to 15 minutes.\n'
             'Reduce heat, and stir in cheese cubes until melted. Mix in milk and garlic powder.\n'
             'In a small bowl, stir cornstarch into water until dissolved. Stir into soup; cook, stirring frequently, until thick.'
             ))

        self.assertEqual(scraped_recipe.title, recipe1.title)
        self.assertEqual(scraped_recipe.url, recipe1.url)
        self.assertEqual(scraped_recipe.ingredients, recipe1.ingredients)
        self.assertEqual(scraped_recipe.instructions, recipe1.instructions)
        self.assertEqual(scraped_recipe.rating, recipe1.rating)
        self.assertEqual(scraped_recipe.numreviews, recipe1.numreviews)
Exemplo n.º 3
0
 def gather_all_recipes():
     recipe_book = list()
     for root, dirs, files in os.walk('all_recipes'):
         for fp in files:
             current_recipe = os.path.join('all_recipes', fp)
             recipe_book.append(recipe.Recipe(fp=current_recipe))
     return recipe_book
    def prompt_add_recipe(self):
        """Prompts the user to add a recipe"""

        name = input("Recipe name: ")
        ingredients = recipe_adder.add_new_recipe(self.ureg)
        print("Attempting to convert ingredients to metric units...")
        try:
            new_ingredients = recipe_adder.convert_to_preferred(ingredients[:], self.ureg)
            ingredients = new_ingredients
        except Exception as e:
            print("An issue occurred during conversion. Ingredients unchanged.")
            print(e)
        else:
            print("Successfully converted ingredient units.")
        do_steps = input("Would you like to list steps?").lower()
        steps = None
        if do_steps == "yes" or do_steps == "y":
            print("Type your steps one by one, and when you're finished, type 'exit', or just press <Enter> on a blank line.")
            i = 1
            steps = []
            k = input("Step " + str(i) + ": ")
            while k.lower() != "exit" and k.lower() != "quit" and k.lower():
                steps.append(k)
                i += 1
                k = input("Step " + str(i) + ": ")
        new_recipe = None
        new_recipe = recipe.Recipe(name, ingredients, steps)
        self.recipes.append(new_recipe)
        self.save_recipes()
        print("Recipe successfully added.")
 def __init__(self):
     """Creates a freshroastsr700 object passing in methods included in this
     class."""
     self.recipes = recipe.Recipe()
     self.roaster = freshroastsr700.freshroastsr700(self.update_data,
                                                    self.next_state,
                                                    thermostat=True)
     self.total_steps = self.recipes.get_num_recipe_sections()
Exemplo n.º 6
0
    def create_recipe_object(recipeList, url):
        recipeList = recipeList.split('\n')

        idx = 0
		##iterate through recipe list
        for i in recipeList:
			##find and set the name of the recipe
            if ''',"@type": "Recipe"''' in i:
                name = recipeList[idx + 1]
                name = name.strip(',"name": "')
			##find and set the name of the author
            elif ''',"author": {''' in i:
                author = recipeList[idx + 2]
                author = author.strip(',"name": "')
			##find and set the description
            elif ''',"description":''' in i:
                description = recipeList[idx]
                description = description.strip('        ,"description": "')
			##find and set the recipe yield
            elif ''' ,"recipeYield":''' in i:
                servings = recipeList[idx]
                servings = servings.strip('        ,"recipeYield": "')
                servings = servings.strip(' servings')
			##find the ingredients and put into an array
            elif ''',"recipeIngredient"''' in i:
                ingredients = recipeList[idx + 1].split('","')
                idx2 = 0
                for i in ingredients:
                    ingredients[idx2] = ingredients[idx2].strip()
                    ingredients[idx2] = ingredients[idx2].strip('"')
                    ingredients[idx2] = ingredients[idx2].replace('\\u0022', '"')
                    idx2 += 1
			#find the steps and put into an array
            elif ''',"recipeInstructions":''' in i:
                steps = recipeList[idx + 1].strip('"},').split("{\"@type\":\"HowToStep\",\"text\":")
                idx2 = 0
                steps.pop(0)
                for i in steps:
                    steps[idx2] = steps[idx2].strip('"},')
                    steps[idx2] = steps[idx2].strip('"')
                    steps[idx2] = steps[idx2].strip('\'')
                    steps[idx2] = steps[idx2].replace('\\u0022', '"')
                    idx2 += 1
			##if none of the conditions are met just pass
            else:
                pass
            idx += 1

		## ya girl figure this shit out
		
        recipe_obj = recipe.Recipe(url, name, description, author, servings, ingredients, steps)
        return recipe_obj
Exemplo n.º 7
0
def construct_recipe_object(recipes_list):
    """
        Digs the relevant information from the list of list or recipe tokens:
        name, serving size, ingredient list.

        :param recipes_list: The list of list of recipes tokens
        :return: An instance of a Recipe
    """
    recipe_name = recipes_list[0]
    serving_number_string = recipes_list[1].split(' ')
    recipe_serving_size = serving_number_string[1]
    recipe_ingredients_list = [recipes_list[i] for i in
                               range(2, len(recipes_list))]
    if serving_size_override:
        recipe_obj = recipe.Recipe(recipe_name, recipe_serving_size,
                                   serving_size_override,
                                   recipe_ingredients_list)
    else:
        recipe_obj = recipe.Recipe(recipe_name, recipe_serving_size,
                                   recipe_serving_size,
                                   recipe_ingredients_list)
    return recipe_obj
Exemplo n.º 8
0
def main():
    print("What's cookin' good lookin'?")
    while True:
        more = input("Would you like to create a new recipe? ")
        if more == "yes":
            outDict = recipe.Recipe().genDict()
            filename = "recipes/" + outDict["name"].replace(" ", "-") + ".json"
            with open(filename, 'w') as outfile:
                json.dump(outDict, outfile, indent=4)
        elif more == "no":
            print("Have a nice day!")
            return
        else:
            print("I.. didn't quite understand that. Please say (yes/no)")
Exemplo n.º 9
0
def get_recipe(recipe_endpoint):
    # e.g. /recipe/56927/delicious-ham-and-potato-soup/ => Recipe object
    print('Loading {}'.format(recipe_endpoint))
    response = requests.get('http://allrecipes.com' + recipe_endpoint,
                            headers=HEADERS)
    if response.ok == False:
        raise Exception("Another bad thing happened!")
    soup = BeautifulSoup(response.content, 'html.parser')

    title_tag = soup.find(attrs={'class': 'recipe-summary__h1'})
    title = None
    if title_tag != None:
        title = title_tag.string.strip()

    description_tag = soup.find(attrs={'class': 'submitter__description'})
    description = None
    if description_tag != None:
        description = description_tag.string.strip()[
            1:-1]  # get rid of leading and trailing quotes

    ingredients = []
    for tag in soup.find_all(attrs={'class': 'recipe-ingred_txt'}):
        if tag.attrs.get(
                'itemprop') != None and tag.attrs['itemprop'] == 'ingredients':
            ingredients.append(tag.string.strip())

    single_line_ingredient_string = '\n'.join(ingredients)

    prepTime, cookTime, totalTime = None, None, None
    for tag in soup.find_all('time'):
        if prepTime == None:
            prepTime = tag.attrs['datetime']
            continue
        if cookTime == None:
            cookTime = tag.attrs['datetime']
            continue
        if totalTime == None:
            totalTime = tag.attrs['datetime']
            continue

    instructions = []
    for tag in soup.find_all(attrs={'class': 'recipe-directions__list--item'}):
        if tag.string and len(tag.string.strip()) > 0:
            instructions.append(tag.string.strip())

    return recipe.Recipe(title, cookTime, prepTime, description, None,
                         single_line_ingredient_string, instructions, None)
Exemplo n.º 10
0
def make_recipe(title, ingredients, steps, knowledge_base):
    """
    STUB DESCRIPTION:
    Write the make_recipe function in app.parser that will take as input the output of parse_html, and output a
    Recipe object. Use the various ingredient matching functions in kb.py to achieve this.
    :param title: title of recipe
    :param ingredients: list of ingredients (strings)
    :param steps: list of steps (strings)
    :return: Recipe
    """
    ingredient_object_list = []
    for ingredient_string, quantity_string in ingredients:
        quantity = knowledge_base.interpret_quantity(quantity_string)
        i_name, i_descriptor, i_prep, i_prep_descriptor = parse_ingredient(ingredient_string, knowledge_base)
        ingredient_object_list.append(
            recipe.Ingredient(i_name, quantity, i_descriptor, i_prep, i_prep_descriptor).match_to_food(knowledge_base))
    result = recipe.Recipe(title, ingredient_object_list, steps)
    result.methods = find_cooking_methods(steps, knowledge_base)
    result.tools = find_cooking_tools(steps, knowledge_base)
    result.primary_method = find_primary_method(result.methods)
    return result
Exemplo n.º 11
0
def make_healthy(from_recipe, knowledge_base):
    """
    STUB DESCRIPTION:
    Write make_healthy function to take a Recipe input and output a healthier Recipe.
    Loop through Ingredients in Recipe, and apply USDA lookup function from #62.
    Think of other ways also.
    :param from_recipe: old recipe
    :return: new recipe
    """
    new_recipe = recipe.Recipe('Healthy ' + from_recipe.title,
                               steps=from_recipe.steps)
    new_recipe.methods = from_recipe.methods
    new_recipe.primary_method = from_recipe.primary_method
    new_recipe.tools = from_recipe.tools

    for ingredient in from_recipe.ingredients:
        new_ingredient = recipe.Ingredient()
        new_ingredient.available = ingredient.available
        new_ingredient.descriptor = ingredient.descriptor
        new_ingredient.prep_description = ingredient.prep_description
        new_ingredient.preparation = ingredient.preparation
        new_ingredient.quantity = ingredient.quantity

        new_ingredient.name = 'low ' + ingredient.name
        new_ingredient.match_to_food(knowledge_base)
        if not new_ingredient.food_type:
            new_ingredient.name = 'soy ' + ingredient.name
            new_ingredient.match_to_food(knowledge_base)
        else:
            new_ingredient.name = new_ingredient.food_type.name
        if not new_ingredient.food_type:
            new_recipe.add_ingredients([ingredient])
        else:
            new_ingredient.name = new_ingredient.food_type.name
            new_recipe.add_ingredients([new_ingredient])

    return new_recipe
Exemplo n.º 12
0
import recipe

new_recipe = recipe.Recipe("omlet", 5, 89, ["couilles", "gel", "sel"], "",
                           "lunch")

x = 58
w = type(x)

print(str(new_recipe))
Exemplo n.º 13
0
#!/usr/bin/env python

import recipe as R
import glass as G
import cmd, sys

beads = []
recipe = R.Recipe()


class Shell(cmd.Cmd):
    intro = 'Welcome to the glass maker shell. Type help or ? to list commands.\n'
    prompt = 'gm>'
    file = None

    # ----- commands -----
    def do_makeBead(self, arg):
        'Make a new bead with list of elements and moles: e.g., Al 2 O 10:'
        argp = parse(arg)
        beads.append(G.Glass())
        #print argp
        for i in range(len(argp) / 2):
            element = argp[2 * i]
            mols = int(argp[2 * i + 1])
            beads[-1].addElement(element, mols)

    def do_setTarget(self, arg):
        'Set target percentages for element in new bead: e.g., "Al 0 8 12 1" sets target element "AL" in bead 0 (initialized with makeBead) from 8% to 12%, in 1% increments'
        argp = parse(arg)
        beadIndex = int(argp[1])
        element = argp[0]
Exemplo n.º 14
0
def scrape_recipe(soup):
    # This is called when user wants to scrape for specific recipe site
    # Try functions were used to prevent any one element from stopping the operation
    try:
        rtitle = soup.find_all('h1')
        rtitle = cleanhtml(str(rtitle[0]))
    except:
        rtitle = 'NA'
    recipe = r.Recipe(rtitle)
    # print("Recipe Title: {0}".format(rtitle))

    try:
        starrating = soup.find_all('div', {'class': 'rating-stars'})
        starrating = starrating[0]['data-ratingstars']
        recipe.set_rating(starrating)
    except:
        starrating = 'NA'

    try:
        reviewcount = soup.find_all("meta", {'itemprop': 'reviewCount'})
        reviewcount = reviewcount[0]['content']
        recipe.set_number_of_reviews(reviewcount)
    except:
        reviewcount = 'NA'

    try:
        calcount = soup.find_all("span", {"class": 'calorie-count'})
        calcount = calcount[0]['aria-label']
        recipe.set_calories(calcount)
    except:
        calcount = 'NA'

    # print("Calorie Count: {0}".format(calcount))

    # print("\nINGREDIENTS\n")

    ingredients = soup.find_all("span", {"itemprop": "recipeIngredient"})
    count = 1
    for i in ingredients:
        parsed_i = r.build_ingredient(cleanhtml(str(i)))
        recipe.add_ingredient([cleanhtml(str(i)), parsed_i])
        count += 1

    try:
        directions = soup.find_all("span",
                                   {"class": "recipe-directions__list--item"})
        utensils = set([])
        methods = set([])
        for i in directions:
            step = cleanhtml(str(i))
            if step.strip() != "" and "Watch Now" not in step:
                sentences = r.tokenize_step(step)
                for sentence in sentences:
                    uten, meth, ing, time = r.organize_directions(sentence)
                    for m in meth:
                        recipe.add_method(m.replace("_", " "))
                    utensils = utensils.union(uten)
                    # methods = methods.union(meth)
                    recipe.add_step(sentence, uten, meth, ing, time)
        for u in utensils:
            recipe.add_tool(u.replace("_", " "))
        # for m in methods:
        #     recipe.add_method(m.replace("_", " "))
    except:
        directions = "NA"

    return recipe
Exemplo n.º 15
0
        return html

    def _ingredients_to_table(self, ingredients):
        table = r"<table><tr><td>Ingredienser</td></tr>"
        for ing in ingredients:
            text = ing.name
            if ing.amount:
                text += f", {ing.amount}"
                if ing.unit:
                    text += f"{ing.unit}"
            table += f"<tr><td>{text}</td></tr>"
        return table + r"</table>"


RECIPES = []
REC = recipe.Recipe("Pasta med tonfisksås och sojabönor", 4, 15)
REC.add_ingredient("pasta", 4, "port")
REC.add_ingredient("tonfisk i burk", 2, "st")
REC.add_ingredient("sojabönor", 250, "g")
REC.add_ingredient("tomatpesto", 1, "dl")
REC.add_ingredient("matlagningsgrädde", 2.5, "dl")
REC.add_ingredient("ruccola", 75, "g")
REC.add_ingredient("salt och peppar")

json_tool.recipe_to_json_file(REC)

RECIPES.append(REC)

cherrypy.config.update({'server.socket_host': LAN_IP})
cherrypy.quickstart(RecipeWeb(RECIPES))
Exemplo n.º 16
0
    def test_scrape_recipe_format_1(self):

        self.maxDiff = None

        testfile = open("testfiles/format1_1.html", encoding="utf-8")
        scraped_recipe = recipe.scrape_recipe(testfile.read())
        testfile.close()

        recipe1 = recipe.Recipe(
            title="Double Layer Pumpkin Cheesecake",
            url=
            "https://www.allrecipes.com/recipe/13477/double-layer-pumpkin-cheesecake/",
            rating="4.77",
            numreviews="2786",
            ingredients=[
                "2 (8 ounce) packages cream cheese, softened",
                "1/2 cup white sugar", "1/2 teaspoon vanilla extract",
                "2 eggs", "1 (9 inch) prepared graham cracker crust",
                "1/2 cup pumpkin puree", "1/2 teaspoon ground cinnamon",
                "1 pinch ground cloves", "1 pinch ground nutmeg",
                "1/2 cup frozen whipped topping, thawed"
            ],
            instructions=
            ('Preheat oven to 325 degrees F (165 degrees C).\n'
             'In a large bowl, combine cream cheese, sugar and vanilla. Beat until smooth. Blend in eggs one at a time. Remove 1 cup of batter and spread into bottom of crust; set aside.\n'
             'Add pumpkin, cinnamon, cloves and nutmeg to the remaining batter and stir gently until well blended. Carefully spread over the batter in the crust.\n'
             'Bake in preheated oven for 35 to 40 minutes, or until center is almost set. Allow to cool, then refrigerate for 3 hours or overnight. Cover with whipped topping before serving.'
             ))

        self.assertEqual(scraped_recipe.title, recipe1.title)
        self.assertEqual(scraped_recipe.url, recipe1.url)
        self.assertEqual(scraped_recipe.ingredients, recipe1.ingredients)
        self.assertEqual(scraped_recipe.instructions, recipe1.instructions)
        self.assertEqual(scraped_recipe.rating, recipe1.rating)
        self.assertEqual(scraped_recipe.numreviews, recipe1.numreviews)

        testfile = open("testfiles/format1_2.html", encoding="utf-8")
        scraped_recipe = recipe.scrape_recipe(testfile.read())
        testfile.close()

        recipe1 = recipe.Recipe(
            title="Super Moist Zucchini Bread",
            url=
            "https://www.allrecipes.com/recipe/215488/super-moist-zucchini-bread/",
            rating="2.16",
            numreviews="37",
            ingredients=[
                "3 cups grated zucchini", "3 cups all-purpose flour",
                "3 tablespoons ground cinnamon", "1 teaspoon baking soda",
                "1 teaspoon baking powder", "1 teaspoon salt",
                "1 cup unsweetened applesauce",
                "3 tablespoons vanilla extract", "3 eggs",
                "3 tablespoons butter, melted",
                "1 cup chopped walnuts (optional)"
            ],
            instructions=
            ('Preheat an oven to 325 degrees F (165 degrees C). Grease 2 8x4-inch loaf pans or 2 12-cup muffin pans.\n'
             'Place the zucchini in a strainer and set aside to drain into a bowl or sink.\n'
             'Sift the flour, cinnamon, baking soda, baking powder, and salt together in a large bowl. Create a well in the middle of the flour mixture; combine the applesauce, vanilla, eggs, butter, walnuts, and drained zucchini in the center of the well. Mix until all ingredients are combined into a batter; pour into the loaf pans.\n'
             'Bake the loaves in the preheated oven until a toothpick inserted into the center comes out clean, about 1 hour for loaves or 25 minutes for muffins. Cool in the pans for 10 minutes before removing to cool completely on a wire rack.'
             ))

        self.assertEqual(scraped_recipe.title, recipe1.title)
        self.assertEqual(scraped_recipe.url, recipe1.url)
        self.assertEqual(scraped_recipe.ingredients, recipe1.ingredients)
        self.assertEqual(scraped_recipe.instructions, recipe1.instructions)
        self.assertEqual(scraped_recipe.rating, recipe1.rating)
        self.assertEqual(scraped_recipe.numreviews, recipe1.numreviews)