Пример #1
0
def add_recipe():
    with open("recipe_final.json", 'r') as f:
        data = json.load(f)

    user = User.objects.get(id=user_id)
    for idx, dt in enumerate(data):
        path_imgs, _ = get_list_images(os.path.join('images',dt['id']))
        # print(len(path_imgs))
        print(dt['name'])
        rec = Recipe()
        rec.name = dt['name']
        rec.user = user
        rec.servings = int(dt['servings'])
        rec.prep = dt['prep']
        # rec.cook = request.POST['cook']
        rec.total = dt['total']
        rec.total_min = parseTimes(dt['total'])
        rec.note = dt['notes']
        rec.rate = 0
        rec.description = dt['description']
        filename = os.path.join('images', dt['images'].split('%')[-1])
        rec.images = filename
        rec.save()

        for i in path_imgs:
            img = ImageRecipe()
            img.recipe = rec
            img.images = i.replace('images/','')
            img.save()

        categorys = dt['category']
        for i in categorys:
            cate = Category()
            cate.recipe = rec
            cate.name = i
            cate.save()

        ingredients = dt['ingredients']
        for i in ingredients:
            ing = Ingredient()
            ing.recipe = rec
            ing.content = i
            ing.save()

        ing_food = IngredientList(dt['ingredients'])
        for i in ing_food.all:
            math_food = MatchFood()
            math_food.recipe = rec
            math_food.food = Food.objects.get(id=i.matched_food.id)
            math_food.save()

        direction = dt['directions']
        for i in direction:
            dire = Direction()
            dire.recipe = rec
            dire.content = i
            dire.save()
        if idx == 100: break
Пример #2
0
    def post(self, request):
        rec = Recipe()
        rec.name = request.POST['name']
        if request.POST['note']:
            rec.note = request.POST['note']
        rec.description = request.POST['description']
        rec.servings = int(request.POST['servings'])
        prep, prep_min = parseTimes(request.POST['prep'],
                                    request.POST['prepTimeUnit'])
        cook, cook_min = parseTimes(request.POST['cook'],
                                    request.POST['cookTimeUnit'])
        rec.prep = prep
        rec.cook = cook
        rec.total_min = prep_min + cook_min
        image = request.FILES["image-file"]
        fs = FileSystemStorage()
        name = id_generator() + image.name
        filename = fs.save(name, image)
        rec.images = filename
        rec.rate = 0
        rec.user = request.user
        rec.save()

        img = ImageRecipe()
        img.recipe = rec
        img.images = filename
        img.save()

        categorys = request.POST['category']
        categorys = categorys.split(',')
        for i in categorys:
            if i.strip() == '':
                continue
            cate = Category()
            cate.recipe = rec
            cate.name = i.strip()
            cate.save()

        ingredients = request.POST['ingredient']
        ingredients = ingredients.split('\n')
        for i in ingredients:
            if i.strip() == '':
                continue
            ing = Ingredient()
            ing.recipe = rec
            ing.content = i.strip()
            ing.save()

        direction = request.POST['direction']
        direction = direction.split('\n')
        for i in direction:
            if i.strip() == '':
                continue
            dire = Direction()
            dire.recipe = rec
            dire.content = i.strip()
            dire.save()
        return HttpResponseRedirect('/share_recipe')
Пример #3
0
def scrap_recipe_from_url(url):
	
	#fake test
	#url = 'https://www.marmiton.org/recettes/recette_bruschetta-aux-aubergines_47116.aspx'

	recipe = Recipe()
	recipe.url = url
	recipe.save() #force save to add children

	#get page
	response = requests.get(url)
	soup = BeautifulSoup(response.text, "html.parser")

	#detect the domain and get appropriate tags
	domain_name = url.split('/')[2]

	if (domain_name == 'www.marmiton.org'):
		allItems = soup.findAll("li", {"class": "recipe-preparation__list__item"})
		allIngredientQty = soup.findAll("span", {"class": "recipe-ingredient-qt"})
		allIngredientUnitAndNames = soup.findAll("span", {"class": "ingredient"})
		#allImages = soup.findAll("img", {"id": "recipe-media-viewer-main-picture"})
		imageDiv = soup.find("div", {"class": "recipe-media-viewer-media-container"})
		allImages = imageDiv.findAll("img")
		if (len(allImages) >0):
			img_url = allImages[0]['data-src']
	elif (domain_name == 'www.cuisineaz.com'):
		allItems = soup.findAll("p", {"class": "p10"})
		ingredientSection = soup.find("section", {"class": "large-4 medium-4 small-12 columns recipe_ingredients"})
		allIngredientQty = ingredientSection.findAll("span")
		allIngredientUnitAndNames = 'MANUAL'
		allImages = soup.findAll("img", {"id": "ContentPlaceHolder_recipeImg"})
		if (len(allImages) >0):
			img_url = allImages[0]['data-src']

	#get title
	allTitles = soup.findAll('h1')
	allTitles
	#recipe.name = 'fake name'
	recipe.name = allTitles[0].contents[0].strip()

	#TODO detect url domain, and store list of tags


	#get items list
	#allItems = soup.findAll("li", {"class": "recipe-preparation__list__item"})
	#current_item_tag = allItems[0]
	i=0
	for current_item_tag in allItems:
		currentListContent = ''
		for current_content in current_item_tag.contents:
			currentListContent =  current_content
		if i==0:
			recipe.description = '*' + currentListContent
		else:
			recipe.description = recipe.description + '\n' + currentListContent
		i=i+1

	#INGREDIENTS
	#allIngredientQty = soup.findAll("span", {"class": "recipe-ingredient-qt"})
	#allIngredientUnitAndNames = soup.findAll("span", {"class": "ingredient"})

	#loop on ingredient
	i=0
	for current_ingredient_qty in allIngredientQty:
		
		#print('ouuuuuuu')
		#print(current_ingredient_qty.contents)
		if(len(current_ingredient_qty.contents)<0):
			break
		#if(len(current_ingredient_qty.contents)==1):
			#<span>400g de semoule de blé complète</span>
			#currentQty=1
			#currentUnitAndName = current_ingredient_qty.contents[0]
		else:
			currentQty = current_ingredient_qty.contents[0]
			#currentUnitAndName = allIngredientUnitAndNames[i].contents[0]
			
			#for some sites we need to split 
			if (allIngredientUnitAndNames == 'MANUAL'):
				currentUnitAndName = current_ingredient_qty.contents[0]

				#KO for 60g without space
				number = re.search('^\d+', currentUnitAndName)
				if(number is None):
					#'sel, poivre'
					currentQty = 1
				else:
					currentQty = number.group(0)
					currentUnitAndName = currentUnitAndName[number.end():]



				#currentQty = current_ingredient_qty.contents[0].split(' ')[0]
				#currentUnitAndName = current_ingredient_qty.contents[0].split(' ', 1)[1]
			else:
				currentUnitAndName = allIngredientUnitAndNames[i].contents[0]
			#avoid non integer values in crappy websites

			#check if fraction?
			#if ('/' in currentQty):
			#	myFraction = Fraction(currentQty)
			#	currentQty = float(myFraction)

		#currentQty = math.ceil(float(currentQty))


		#TODO get ingredient by name or create it
		ingredient = Ingredient()
		ingredient.name=currentUnitAndName
		ingredient.save()

		#init ingredient qty object and add it to recipe
		ingredientQty = IngredientQuantity()
		ingredientQty.ingredient = ingredient
		ingredientQty.quantity = currentQty
		ingredientQty.recipe = recipe
		ingredientQty.save()

		i = i+1

	#image
	#allImages = soup.findAll("img", {"id": "recipe-media-viewer-main-picture"})
	if (len(allImages) >0):
		#img_url = allImages[0]['src']
		#recipe.comment = img_url

		# Steam the image from the url
		#request = requests.get(img_url, stream=True)
		
		# Get the filename from the url, used for saving later
		file_name = img_url.split('/')[-1]
		#content = urllib.request.urlretrieve(img_url)
		#recipe.image.save(file_name, File(open(content[0])), save=True)

		

		# save in the ImageField
		result = urllib.request.urlretrieve(img_url) # image_url is a URL to an image
		recipe.image.save(
    		file_name,
    		File(open(result[0], 'rb'))
    	)

		#SECOND ATTEMPT
		#request = requests.get(img_url, stream=True)
		#file = tempfile.NamedTemporaryFile()
		#request.raw.decode_content = True
		#shutil.copyfileobj(request.raw, file)
		#recipe.image = request.raw

	#recipe.name = 'fake name'
	recipe.save()
	return recipe
Пример #4
0
    def handle(self, *args, **kwargs):
        self.stdout.write("Ouverture du fichier de sauvegarde et restauration \
en cours. Merci de patienter...")
        directory_path = kwargs['path'][0]
        add_media = kwargs['add_media'][0]
        if 'database.json' not in os.listdir(directory_path):
            if 'recipe' not in os.listdir(directory_path):
                cmd1 = f"cd {directory_path}"
                cmd2 = "unzip backup_db.zip"
                os.system(f"{cmd1} && {cmd2}")
                if add_media == 'add-media':
                    os.system(
                        f"mv {directory_path}recipe \"{settings.MEDIA_ROOT}\"")

        jsonfile_path = directory_path + 'database.json'
        with open(jsonfile_path, 'r') as jsonfile:
            data = json.load(jsonfile)

            for mlp in data['meals_per_day']:
                try:
                    MealsPerDay.objects.get(name=mlp)
                except:
                    new_mlp = MealsPerDay(name=mlp)
                    new_mlp.save()
                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(new_mlp.name)} \
ajouté à la base de données")

            for food_group in data['food_groups']:
                try:
                    FoodGroup.objects.get(name=food_group)
                except:
                    new_f_g = FoodGroup(name=food_group)
                    new_f_g.save()
                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(new_f_g.name)} \
ajouté à la base de données")

            for food in data['foods']:
                try:
                    Food.objects.get(name=food['name'])
                except:
                    new_food = Food()
                    for k, v in food.items():
                        if k == 'group_name':
                            new_food.id_group = FoodGroup.objects.get(name=v)
                        else:
                            setattr(new_food, k, v)
                    new_food.save()
                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(new_food.name)} \
ajouté à la base de données")

            for categ in data['recipe_categories']:
                try:
                    CategorieRecipe.objects.get(name=categ['name'])
                except:
                    new_categ = CategorieRecipe()
                    new_categ.name = categ['name']
                    new_categ.image_active = categ['image_active']
                    new_categ.image_not_active = categ['image_not_active']
                    new_categ.save()
                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(new_categ.name)} \
ajouté à la base de données")

            for origin in data['origins_recipe']:
                try:
                    OriginRecipe.objects.get(name=origin)
                except:
                    new_origin = OriginRecipe(name=origin)
                    new_origin.save()
                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(new_origin.name)} \
ajouté à la base de données")

            for level in data['levels']:
                try:
                    Level.objects.get(name=level)
                except:
                    new_level = Level(name=level)
                    new_level.save()
                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(new_level.name)} \
ajouté à la base de données")

            for price_scale in data['price_scales']:
                try:
                    PriceScale.objects.get(name=price_scale)
                except:
                    new_p_s = PriceScale(name=price_scale)
                    new_p_s.save()
                    if kwargs['verbose']:
                        self.stdout.write(
                            f"{self.style.SUCCESS(new_p_s.name)} \
ajouté à la base de données")

            for utensil in data['utensils']:
                try:
                    Utensil.objects.get(name=utensil)
                except:
                    new_u = Utensil(name=utensil)
                    new_u.save()
                    if kwargs['verbose']:
                        self.stdout.write(f"{self.style.SUCCESS(new_u.name)} \
ajouté à la base de données")

            for season in data['seasons']:
                try:
                    Season.objects.get(name=season)
                except:
                    new_s = Season(name=season)
                    new_s.save()
                    if kwargs['verbose']:
                        self.stdout.write(f"{self.style.SUCCESS(new_s.name)} \
ajouté à la base de données")

            for diet in data['diets']:
                try:
                    DietaryPlan.objects.get(name=diet['name'])
                except:
                    new_d = DietaryPlan(name=diet['name'],
                                        description=diet['desc'])
                    new_d.save()
                    if kwargs['verbose']:
                        self.stdout.write(f"{self.style.SUCCESS(new_d.name)} \
ajouté à la base de données")

            for allergie in data['allergies']:
                try:
                    Allergie.objects.get(name=allergie)
                except:
                    new_a = Allergie(name=allergie)
                    new_a.save()
                    if kwargs['verbose']:
                        self.stdout.write(f"{self.style.SUCCESS(new_a.name)} \
ajouté à la base de données")

            for recipe in data['recipes']:
                r_origin = OriginRecipe.objects.get(name=recipe['origin'])
                r_price_scale = PriceScale.objects.get(
                    name=recipe['price_scale'])
                r_level = Level.objects.get(name=recipe['level'])

                categories = set()
                for categ in recipe['categories']:
                    c = CategorieRecipe.objects.get(name=categ)
                    categories.add(c)

                utensils = set()
                for utensil in recipe['utensils']:
                    u = Utensil.objects.get(name=utensil)
                    utensils.add(u)

                seasons = set()
                for season in recipe['season']:
                    s = Season.objects.get(name=season)
                    seasons.add(s)

                diets = set()
                for diet in recipe['dietary_plan']:
                    d = DietaryPlan.objects.get(name=diet)
                    diets.add(d)

                try:
                    new_r = Recipe.objects.get(name=recipe['name'])
                    state = 'modifiée'
                except:
                    new_r = Recipe()
                    state = 'ajoutée'

                new_r.name = recipe['name']
                new_r.preparation_time = recipe['preparation_time']
                new_r.cooking_time = recipe['cooking_time']
                new_r.step = recipe['step']
                new_r.tip = recipe['tip']
                new_r.portion = recipe['portion']
                new_r.point = recipe['point']
                new_r.typical_recipe_city = recipe['typical_recipe_city']
                new_r.source = recipe['source']
                new_r.image = recipe['image']
                new_r.origin = r_origin
                new_r.price_scale = r_price_scale
                new_r.level = r_level
                new_r.save()

                new_r.categories.set(categories)
                new_r.utensils.set(utensils)
                new_r.season.set(seasons)
                new_r.dietary_plan.set(diets)

                for food in recipe['food']:
                    f = Food.objects.get(name=food['name'])
                    fq = FoodAndQuantity()
                    fq.food = f
                    fq.recipe = new_r
                    fq.recipe_quantity = food['recipe_quantity']
                    fq.recipe_unity = food['recipe_unity']
                    fq.food_purchase_quantity = food['purchase_quantity']
                    fq.food_purchase_unity = food['purchase_unity']
                    fq.save()

                if kwargs['verbose']:
                    self.stdout.write(
                        f"{self.style.SUCCESS(new_r.name)} {state} à la base de données"
                    )