Beispiel #1
0
def add_recipe():
    '''If request method is GET, load the 'add recipe' page.
    If request method is POST:
      1. Get all posted form data
      2. Get ID of currently logged-in user
      3. Call the relevant function of the Recipes class to add/create
         a new record in the recipes table. Pass in the relevant 
         information as arguments to the function.
      4. Redirect to the Recipes (listing) page.'''
    if request.method == 'GET':
        return render_template('add_recipe.html')

    elif request.method == 'POST':
        title = request.form.get('recipe-title')
        image = request.form.get('recipe-image')
        category = request.form.get('recipe-category')
        description = request.form.get('recipe-description')
        ingredients = request.form.get('recipe-ingredients')

        auth = Auth()
        user = auth.get_current_user()
        user_id = user[0]

        new_recipe = {
            'title': title,
            'image_URL': image,
            'category': category,
            'description': description,
            'ingredients': ingredients,
        }

        recipe = Recipes()
        recipe.add_recipe(new_recipe, user_id)
        return redirect(url_for('show_recipes'))
Beispiel #2
0
def delete_recipe(recipe_id):
    auth = Auth()
    user = auth.get_current_user()
    user_id = user[0]
    recipe = Recipes()
    recipe.delete_recipe(recipe_id, user_id)
    return redirect(url_for('show_recipes'))
Beispiel #3
0
def show_recipes():
    auth = Auth()
    if auth.is_logged_in():
        recipe_manager = Recipes()
        user = auth.get_current_user()
        recipes = recipe_manager.get_recipes(user['user_id'])
        print(recipes)
        print([recipe['recipe_id'] for recipe in recipes])
        return render_template('recipes.html', recipes=recipes)
    return redirect(url_for('login'))
Beispiel #4
0
def main():
	recs = Recipes()
	# print(len(recs.rank(40, 'butter')))
	index_file = './index.pickle'
	test_index_file = './test_index.pickle'

	# gen_test_index(recs, test_index_file)
	test_idxs = load_test_index(test_index_file)

	# gen_index(recs,index_file)
	rank_list = list()
	removed_idxs = load_index(index_file)

	#calculate ranks
	# for indice in range(1,52376):
	for indice in test_idxs:
		recipe_id,reclength,removed_ingr = recs.rand_remove(indice,removed_idxs[indice-1])
		# removed_idxs.append(rm_idx)
		# print('recipe id: '+str(recipe_id))
		logging.info('recipe id: ' + str(recipe_id) + ' == recipe length: ' + str(reclength) + \
			' == removed ingredient: '+ removed_ingr+' == index in recipe: '+str(removed_idxs[indice-1]) )
		# logging.info('recipe length: '+str(reclength))
		rank = len(recs.rank(recipe_id, removed_ingr))
		logging.info('prediction rank: '+str(rank))
		rank_list.append(rank)
		# break
	# print(rank_list)

	rank_file = './rank_list_context+cooccur.pickle'
	with open(rank_file,'wb') as handle:
		pickle.dump(rank_list, handle)
	handle.close()



	#measure the performance
	# rank_list = [1,5,6,2,3,7,9,10,4,8,11]
	# rank_list = [244,244,244]
	rank_array = np.array(rank_list)
	avg_rank = reduce(lambda x,y: x+y, rank_list)/len(rank_list)
	# median_rank = statistics.median(sorted(rank_list))
	median_rank = np.median(sorted(rank_list))
	n_10 = len(np.where(rank_array<=10)[0])
	n_1 = len(np.where(rank_array==1)[0])

	n_neg = 247
	auc = 1 - (rank_array-1)/n_neg
	mean_auc = np.mean(auc)

	print('using contex+cooccur, median rank: '+str(median_rank))
	print('using contex+cooccur, average rank: '+str(avg_rank))
	print('number of rank with in 10: '+str(n_10))
	print('correct prediction: '+str(n_1))
	print('mean auc: '+str(mean_auc))
    def test_get_recipe_by_uri1(self, mock_get_response):
        inst = Recipes.getInstance('http://127.0.0.1')
        test_path = os.path.join("test-responses-recipes", "response5.json")
        file = open(test_path, "r")
        ml = json.loads(file.read())
        file.close()

        mock_get_response.return_value = ml
        res = inst.get_recipe_by_uri(
            "http://www.edamam.com/ontologies/edamam.owl#recipe_35a93fee16e7683b1ece4d9070f974f1"
        )
        expected_res = {
            'recipe_uri':
            'http://www.edamam.com/ontologies/edamam.owl#recipe_35a93fee16e7683b1ece4d9070f974f1',
            'recipe_name':
            'Chicken, Spinach, And Noodle Casserole',
            'recipe_image':
            'https://www.edamam.com/web-img/bf8/bf8173103cd9cffd0da967b1cbb93636.jpg',
            'recipe_url':
            'http://www.realsimple.com/food-recipes/browse-all-recipes/chicken-noodle-casserole-00100000075552/index.html',
            'recipe_calories':
            3902,
            'recipe_ingredients': [
                '6 tablespoons unsalted butter', '1/4 cup all-purpose flour',
                '4 cups whole milk', '1 cup sour cream',
                'kosher salt and black pepper', '12 ounces egg noodles',
                '4 slices sandwich bread',
                '2 cups shredded cooked chicken or rotisserie chicken',
                '5 ounces baby spinach, chopped', '2 teaspoons dried thyme'
            ],
            'recipe_time':
            0.0
        }

        self.assertEqual(expected_res, res)
Beispiel #6
0
def orbibuild_project(prjpath, app_args, buildid, recipes_use=None):
    if not os.path.isdir(prjpath):
        raise ValueError("Incorrect path '" + prjpath + "'")
    prjpath = os.path.abspath(prjpath) + "/"

    builddir = prjpath + "/build"
    if not os.path.exists(builddir):
        os.makedirs(builddir)

    if __get_build_id(builddir) == buildid:
        return
    __set_build_id(builddir, buildid)

    recipes = None
    try:
        recipes = Recipes(prjpath, recipes_use)
    except ValueError as e:
        print(e.args[0])
        build_break(prjpath)

    if len(recipes.list):
        export(prjpath, recipes.list[0])
    for recipe in recipes.list:
        __info_recipe(recipe)
        deps_travel(prjpath, __copy_bins)
        __compile(prjpath, app_args, recipe, buildid)
        __linking(prjpath, recipe)
        __copy_files(prjpath, recipe)
Beispiel #7
0
    def initialize():
        MsgHandlers.stock = Stock()
        MsgHandlers.recipes = Recipes(Config.recipes_file)

        #map recipe names to some generated ID for ability to make a /craft_ID link
        MsgHandlers.recipes_name_to_id_map = {}
        weapon_list, intermediate_list = MsgHandlers.recipes.list_all()
        all_list = []
        all_list.extend([w[0] for w in weapon_list])
        all_list.extend(intermediate_list)

        MsgHandlers.recipes_name_to_id_map.update(
            {all_list[i]: i
             for i in range(0, len(all_list))})

        MsgHandlers.keyboard_markups = {
            "main_menu": {
                "keyboard": [["Гайды"], ["Крафт"], ["Стата"]],
                "resize_keyboard": True
            },
            "craft_menu": {
                "keyboard": [["Расчет стоимости /stock"], ["Список рецептов"],
                             ["Главное меню"]],
                "resize_keyboard":
                True
            }
        }
    def __init__(self, config="config.json"):
        """Load files and setup recipe helper"""
        recipes = Recipes()
        self.recipes = recipes
        vocab_size = 20000
        ing_size, unit_size, vocab_size = recipes.create_dictionaries(vocab_size)
        self.ing_size = ing_size
        self.unit_size = unit_size
        self.vocab_size = vocab_size

        with open(config, "r", encoding="utf-8") as cfg:
            settings = json.load(cfg)["network"]
        self.settings = settings

        # these were the control id's
        ing_ids = recipes.ings2ids(['kartoffel(n)','knoblauch','schokolade','nudeln'])
        
        self.dfg(ing_ids)
Beispiel #9
0
def show_recipes():
    '''If logged in, show recipes for the current user.
	Otherwise, redirect to the Login page.'''

    # Hämtar mallen Recipies.
    recipes = Recipes()
    # Hämtar mallen Auth.
    auth = Auth()
    # Kollar om User är online.
    if auth.is_logged_in() == True:
        # I dont understand this.... user_id
        user_id = auth.get_current_user()['user_id']
        # Test skriver ut user_id i terminalen.
        print(user_id)
        # Hämtar funktionen get_recipes. Med user_id.
        recipes = recipes.get_recipes(user_id)
        return render_template('recipes.html', recipes=recipes)
    else:
        return redirect(url_for('login'))
Beispiel #10
0
def add_recipe():
    if request.method == 'GET':
        return render_template('add_recipe.html')

    title = request.form.get('title', None)
    description = request.form.get('description')
    image = request.form.get('image', None)
    ingredients = request.form.get('ingredients', None)
    user_id = Auth().get_current_user()['user_id']

    recipe_manager = Recipes()
    recipe_manager.add_recipe(
        {
            'title': title,
            'description': description,
            'image': image,
            'ingredients': ingredients
        }, user_id)
    return redirect(url_for('show_recipes'))
Beispiel #11
0
def add_recipe():
    '''If request method is GET, load the 'add recipe' page.
	If request method is POST:
	1. Get all posted form data
	2. Get ID of currently logged-in user
	3. Call the relevant function of the Recipes class to add/create
	a new record in the recipes table. Pass in the relevant 
	information as arguments to the function.
	4. Redirect to the Recipes (listing) page.'''
    if request.method == "GET":
        return render_template('add_recipe.html')
    if request.method == "POST":
        recipe = Recipes()
        auth = Auth()
        description = request.form.get('description', None)
        ingredients = request.form.get('ingredients', None)
        user_id = auth.get_current_user()[0]

        recipe.add_recipe(description, ingredients, user_id)
        return redirect(url_for('show_recipes'))
Beispiel #12
0
 def build(self):
     manager = ScreenManager()
     #getuser4.stuff(getuser.username)
     manager.add_widget(Login(name='login'))
     manager.add_widget(Connected(name='connected'))
     manager.add_widget(Registration(name='registration'))
     manager.add_widget(Recipes(name='recipes'))
     manager.add_widget(Adddish(name='adddish'))
     manager.add_widget(YourDishes(name='yourdishes'))
     manager.add_widget(DeleteRec(name='deleterec'))
     return manager
Beispiel #13
0
def api_get_recipes():
    recipes = Recipes()
    recipes.ingredients = request.args.getlist('ingredients')
    recipes.fulltext = request.args.get('fullText')
    recipes.lang = request.args.get('lang')
    return jsonify(recipes=recipes.get_recipes(),
                   not_found=recipes._not_founds), 200
    def test_get_recipe_by_ingredients4(self, mock_get_response):
        inst = Recipes.getInstance('http://127.0.0.1')
        test_path = os.path.join("test-responses-recipes", "response4.json")
        file = open(test_path, "r")
        ml = json.loads(file.read())
        file.close()

        mock_get_response.return_value = ml

        res = inst.get_recipe_by_ingredients("noodles, chicken, pepper, egg",
                                             random_recipes=False,
                                             health="vegan")
        expected_res = None

        self.assertEqual(expected_res, res)
    def test_get_recipe_by_ingredients2(self, mock_get_response):

        inst = Recipes.getInstance('http://127.0.0.1')
        test_path = os.path.join("test-responses-recipes", "response2.json")
        file = open(test_path, "r")
        ml = json.loads(file.read())
        file.close()

        mock_get_response.return_value = ml

        res = inst.get_recipe_by_ingredients("noodles, chicken, pepper, milk",
                                             random_recipes=False,
                                             diet="low-fat")
        expected_res = {
            'recipe_uri':
            'http://www.edamam.com/ontologies/edamam.owl#recipe_696ea2fc73f79991174e2a7b650b48f9',
            'recipe_name':
            'Tuna Casserole',
            'recipe_image':
            'https://www.edamam.com/web-img/ea7/ea714deca9d0a2fc9067263de1d7db55.jpeg',
            'recipe_url':
            'https://www.foodnetwork.com/recipes/tuna-casserole-recipe-1938022',
            'recipe_calories':
            3317,
            'recipe_ingredients': [
                '5 slices whole-wheat bread, crusts included',
                '1 tablespoon canola oil',
                '1 small onion, chopped (about 1 cup)',
                '1 large stalk celery, finely diced (about 1/2 cup)',
                '1 (10-ounce) box white mushroom, stemmed and chopped (about 2 1/2 cups)',
                '1/4 cup all-purpose flour', '3 cups 1 percent milk',
                '1 cup low-sodium chicken broth or vegetable broth',
                '3/4 teaspoon salt', '1/4 teaspoon ground black pepper',
                '1/2 pound whole-wheat fettuccine noodles, broken into thirds and cooked according to package directions',
                '1 (10-ounce) box frozen chopped broccoli, thawed',
                '1 (10-ounce) box frozen peas, thawed',
                '4 (6-ounce) cans chunk light tuna in water, drained'
            ],
            'recipe_time':
            60.0
        }

        self.assertEqual(expected_res, res)
Beispiel #16
0
    def __init__(self):
        self.verbose = False
        self.home = os.getcwd()
        self.local_config = os.path.join(os.path.expanduser("~"), ".config",
                                         "DataDog", "workbench")
        self.local_data = os.path.join(os.path.expanduser("~"), ".local",
                                       "share", "DataDog")
        self.conf_d_path = os.path.join(self.local_config, "conf.d")
        self.auto_conf_dir = os.path.join(self.conf_d_path, "auto_conf")

        try:
            os.makedirs(self.auto_conf_dir)
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise
            pass

        self.setting = Setting(self)
        self.state = State(self)
        self.recipes = Recipes(self)
        self.dev_mode = DevMode(self)
    def test_get_recipe_by_ingredients3(self, mock_get_response):
        inst = Recipes.getInstance('http://127.0.0.1')
        test_path = os.path.join("test-responses-recipes", "response3.json")
        file = open(test_path, "r")
        ml = json.loads(file.read())
        file.close()

        mock_get_response.return_value = ml

        res = inst.get_recipe_by_ingredients("noodles, onion, pepper",
                                             random_recipes=False,
                                             health="vegan")
        expected_res = {
            'recipe_uri':
            'http://www.edamam.com/ontologies/edamam.owl#recipe_abc04cbb4dec1b122e9fcdbd3c434184',
            'recipe_name':
            'Singapore Noodles With Tofu',
            'recipe_image':
            'https://www.edamam.com/web-img/727/7278fe73f2043c240b8070ea8a4f9a81.jpg',
            'recipe_url':
            'http://www.bbcgoodfood.com/recipes/10769/',
            'recipe_calories':
            975,
            'recipe_ingredients': [
                '2 tsp reduced-salt soy sauce', '1 red pepper , thinly sliced',
                '100.0g fine rice noodles',
                '1 small chunk fresh root ginger , finely chopped',
                '100.0g mangetout', '1 tsp tikka masala paste',
                '100.0g bean sprouts', '2 tbsp sunflower oil',
                'roughly chopped coriander and lime wedges, to serve',
                '140.0g firm tofu', '1 tbsp sweet chilli sauce',
                '3 spring onions , shredded'
            ],
            'recipe_time':
            0.0
        }

        self.assertEqual(expected_res, res)
Beispiel #18
0
def main():
    contRun = True

    if os.path.isfile("Breakfast.json"):
        pass
    else:
        with open("Breakfast.json", "w") as outfile:
            newFile = {}
            json.dump(newFile, outfile)
            outfile.close()

        with open("Main_Dish.json", "w") as outfile:
            newFile = {}
            json.dump(newFile, outfile)
            outfile.close()

        with open("Side_Dish.json", "w") as outfile:
            newFile = {}
            json.dump(newFile, outfile)
            outfile.close()

        with open("Soup.json", "w") as outfile:
            newFile = {}
            json.dump(newFile, outfile)
            outfile.close()

        with open("Bread.json", "w") as outfile:
            newFile = {}
            json.dump(newFile, outfile)
            outfile.close()

        with open("Dessert.json", "w") as outfile:
            newFile = {}
            json.dump(newFile, outfile)
            outfile.close()

        with open("Drink.json", "w") as outfile:
            newFile = {}
            json.dump(newFile, outfile)
            outfile.close()

    # Used to ask if they want to continue
    def reRun():
        hold = input(
            '\nWould you like to look up or add another recipe? (yes or no)\n')
        if hold.lower() == 'no':
            contCheck = False
        else:
            contCheck = True
        return contCheck

    # Loop to keep asking what they would like to do
    while (contRun):
        print(
            'Welcome to the recipe adder, updater and viewer. What would you like to do today?'
        )
        # Select between different options via a number
        selection = input(
            'Please enter a number. \n(1)Add a recipe \n(2)View all recipes \n(3)View a select recipe'
            ' \n(4)To update a recipe \n(5)To delete a recipe \n(6)Quit\n')

        # Runs the add method and adds the new recipe to the database
        if selection == "1":
            x = Recipes()
            x.add()
            contRun = reRun()

        # Displays all recipes in the database
        elif selection == "2":
            y = ViewRecipes()
            y.viewAll()
            contRun = reRun()

        # Displays a recipes based on the type of recipe the user picks
        elif selection == "3":
            y = ViewRecipes()
            y.viewSelect()
            contRun = reRun()

        # Update a recipe
        elif selection == "4":
            u = Recipes()
            u.update()
            contRun = reRun()

        # Delete a recipe
        elif selection == "5":
            d = Recipes()
            d.delete()
            contRun = reRun()

        # Ends the program
        elif selection == "6":
            contRun = False

        else:
            print("Incorrect input.")
Beispiel #19
0
def show_recipe(recipe_id):
    '''Show the recipe that matches the given recipe ID.'''
    recipe = Recipes()
    recipe = recipe.get_recipe(recipe_id)
    return render_template('recipe.html', recipe=recipe)
Beispiel #20
0
tmt_thread = cook.TempMonThread(cook.tmt_state_cb)
tmt_thread.start()
wqt_thread = wq.WorkQueueThread(cook.wqt_state_cb)
wqt_thread.start()
wq.wqt_thread = wqt_thread
dlt_thread = datalogger.DataLoggerThread(cook.status, cook.dlt_state_cb)
dlt_thread.start()
bm = wq.BlubberManager(cook.bm_state_cb)
wq.bm = bm
smt_thread = datalogger.SocketMessageThread(cook.status, socketio)
smt_thread.start()

last_action = 'Leer'
default_str_time = '07:00'

recipes = Recipes()
brew_recipe = recipes.get_default()


def stop_all_threads():
    threads = [pct_thread, tmt_thread, wqt_thread, dlt_thread, smt_thread]
    for thread in threads:
        if thread.is_alive():
            log(thread.name + ' is still alive')
        thread.exit()
        while thread.is_alive():
            time.sleep(0.1)


def handler(signum, frame):
    log('Signal handler called with signal %d' % signum)
Beispiel #21
0
pct_thread = cook.ProcControlThread(cook.pct_state_cb, cook.pct_get_state_cb,
                                    tpc)
pct_thread.start()
tmt_thread = cook.TempMonThread(cook.tmt_state_cb)
tmt_thread.start()
wqt_thread = wq.WorkQueueThread(cook.wqt_state_cb)
wqt_thread.start()
wq.wqt_thread = wqt_thread
dlt_thread = datalogger.DataLoggerThread(cook.status, cook.dlt_state_cb)
dlt_thread.start()
bm = wq.BlubberManager(cook.bm_state_cb)
wq.bm = bm

last_action = 'Empty'

recipes = Recipes()
brew_recipe = recipes.get_default()


def stop_all_threads():
    threads = [pct_thread, tmt_thread, wqt_thread, dlt_thread]
    for thread in threads:
        if thread.is_alive():
            print thread.name + ' is still alive'
        thread.exit()
        while thread.is_alive():
            time.sleep(0.1)


def handler(signum, frame):
    print 'Signal handler called with signal', signum
Beispiel #22
0
"""
A simple guestbook flask app.
"""
import flask
from flask.views import MethodView
from index import Index
from add_recipe import AddRecipe
from recipes import Recipes

app = flask.Flask(__name__)  # Our Flask app

app.add_url_rule('/',
                 view_func=Index.as_view('index'),
                 methods=["GET"])

app.add_url_rule('/add_recipe/',
                 view_func=AddRecipe.as_view('add_recipe'),
                 methods=['GET', 'POST'])

app.add_url_rule('/recipes/',
                 view_func=Recipes.as_view('recipes'),
                 methods=['GET', 'POST'])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)
Beispiel #23
0
 def get_recipes(self, utdate):
     fn = self.get_recipe_name(utdate)
     from recipes import Recipes  #load_recipe_list, make_recipe_dict
     return Recipes(fn)
Beispiel #24
0
import cherrypy
import cherrypy_cors
from recipes import Recipes

if __name__ == "__main__":
    cherrypy_cors.install()
    cherrypy.tree.mount(
        Recipes(), '/recipes', {
            "/": {
                "request.dispatch": cherrypy.dispatch.MethodDispatcher(),
                "cors.expose.on": True,
                "cors.preflight.on": True,
                "cors.preflight.allowed_methods":
                ["GET", "POST", "DELETE", "PUT"]
            }
        })
    cherrypy.engine.start()
    cherrypy.engine.block()
Beispiel #25
0
def show_recipe(recipe_id):
    recipe = Recipes().get_recipe(recipe_id)
    return render_template('recipe.html', recipe=recipe)