def hook(request, token): try: tb = get_object_or_404(TelegramBot, webhook_token=token) data = json.loads(request.body.decode()) if tb.chat_id == '': tb.chat_id = data['message']['chat']['id'] tb.save() if tb.chat_id == str(data['message']['chat']['id']): sl = ShoppingList.objects.filter(Q(created_by=tb.created_by)).filter(finished=False, space=tb.space).order_by('-created_at').first() if not sl: sl = ShoppingList.objects.create(created_by=tb.created_by, space=tb.space) amount, unit, ingredient, note = parse(data['message']['text']) f = get_food(ingredient, tb.space) u = get_unit(unit, tb.space) sl.entries.add( ShoppingListEntry.objects.create( food=f, unit=u, amount=amount ) ) return JsonResponse({'data': data['message']['text']}) except: pass return JsonResponse({})
def get_recipe_from_file(self, file): print('------------ getting recipe') servings = 1 ingredients = [] directions = [] for line in file.replace('\r', '').split('\n'): print('testing line') if not line.startswith('MMMMM') and line.strip != '': if 'Title:' in line: title = line.replace('Title:', '').strip() else: if 'Categories:' in line: tags = line.replace('Categories:', '').strip() else: if 'Yield:' in line: servings_text = line.replace('Yield:', '').strip() else: if re.match('\s{2,}([0-9])+', line): ingredients.append(line.strip()) else: directions.append(line.strip()) try: servings = re.findall('([0-9])+', servings_text)[0] except Exception as e: print('failed parsing servings ', e) recipe = Recipe.objects.create(name=title, servings=servings, created_by=self.request.user, internal=True, space=self.request.space) for k in tags.split(','): keyword, created = Keyword.objects.get_or_create( name=k.strip(), space=self.request.space) recipe.keywords.add(keyword) step = Step.objects.create( instruction='\n'.join(directions) + '\n\n', space=self.request.space, ) for ingredient in ingredients: if len(ingredient.strip()) > 0: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=amount, note=note, space=self.request.space, )) recipe.steps.add(step) return recipe
def get_recipe_from_file(self, file): ingredient_mode = False direction_mode = False ingredients = [] directions = [] for line in file.replace('\r', '').split('\n'): if 'Titel:' in line: title = line.replace('Titel:', '').strip() if 'Kategorien:' in line: tags = line.replace('Kategorien:', '').strip() if ingredient_mode and ('quelle' in line.lower() or 'source' in line.lower()): ingredient_mode = False if ingredient_mode: if line != '' and '===' not in line and 'Zubereitung' not in line: ingredients.append(line.strip()) if direction_mode: if line.strip() != '' and line.strip() != '=====': directions.append(line.strip()) if 'Zutaten:' in line: ingredient_mode = True if 'Zubereitung:' in line: ingredient_mode = False direction_mode = True recipe = Recipe.objects.create(name=title, created_by=self.request.user, internal=True, space=self.request.space) for k in tags.split(','): keyword, created = Keyword.objects.get_or_create( name=k.strip(), space=self.request.space) recipe.keywords.add(keyword) step = Step.objects.create( instruction='\n'.join(directions) + '\n\n', space=self.request.space, ) for ingredient in ingredients: if len(ingredient.strip()) > 0: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=amount, note=note, space=self.request.space, )) recipe.steps.add(step) return recipe
def get_recipe_from_file(self, file): source_url = '' ingredient_mode = 0 ingredients = [] directions = [] for i, fl in enumerate(file.readlines(), start=0): line = fl.decode("utf-8") if i == 0: title = line.strip() else: if line.startswith('https:') or line.startswith('http:'): source_url = line.strip() else: if ingredient_mode == 1 and len(line.strip()) == 0: ingredient_mode = 2 if re.match(r'^([0-9])[^.](.)*$', line) and ingredient_mode < 2: ingredient_mode = 1 ingredients.append(line.strip()) else: directions.append(line.strip()) recipe = Recipe.objects.create( name=title, created_by=self.request.user, internal=True, space=self.request.space, ) step = Step.objects.create( instruction='\n'.join(directions), space=self.request.space, ) if source_url != '': step.instruction += '\n' + source_url step.save() for ingredient in ingredients: if len(ingredient.strip()) > 0: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=amount, note=note, space=self.request.space, )) recipe.steps.add(step) return recipe
def get_recipe_from_file(self, file): with gzip.open(file, 'r') as recipe_zip: recipe_json = json.loads(recipe_zip.read().decode("utf-8")) recipe = Recipe.objects.create( name=recipe_json['name'].strip(), description=recipe_json['description'].strip(), created_by=self.request.user, internal=True, space=self.request.space) try: if re.match(r'([0-9])+\s(.)*', recipe_json['servings'] ): s = recipe_json['servings'].split(' ') recipe.servings = s[0] recipe.servings_text = s[1] if len(recipe_json['cook_time'].strip()) > 0: recipe.waiting_time = re.findall(r'\d+', recipe_json['cook_time'])[0] if len(recipe_json['prep_time'].strip()) > 0: recipe.working_time = re.findall(r'\d+', recipe_json['prep_time'])[0] except Exception: pass recipe.save() instructions = recipe_json['directions'] if len(recipe_json['notes'].strip()) > 0: instructions += '\n\n### ' + _('Notes') + ' \n' + recipe_json['notes'] if len(recipe_json['nutritional_info'].strip()) > 0: instructions += '\n\n### ' + _('Nutritional Information') + ' \n' + recipe_json['nutritional_info'] if len(recipe_json['source'].strip()) > 0 or len(recipe_json['source_url'].strip()) > 0: instructions += '\n\n### ' + _('Source') + ' \n' + recipe_json['source'].strip() + ' \n' + recipe_json['source_url'].strip() step = Step.objects.create( instruction=instructions ) if 'categories' in recipe_json: for c in recipe_json['categories']: keyword, created = Keyword.objects.get_or_create(name=c.strip(), space=self.request.space) recipe.keywords.add(keyword) for ingredient in recipe_json['ingredients'].split('\n'): if len(ingredient.strip()) > 0: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add(Ingredient.objects.create( food=f, unit=u, amount=amount, note=note )) recipe.steps.add(step) self.import_recipe_image(recipe, BytesIO(base64.b64decode(recipe_json['photo_data']))) return recipe
def get_recipe_from_file(self, file): ingredient_mode = False direction_mode = False ingredients = [] directions = [] for fl in file.readlines(): line = fl.decode("utf-8") if 'Title:' in line: title = line.replace('Title:', '').replace('"', '').strip() if 'Description:' in line: description = line.replace('Description:', '').strip() if 'Original URL:' in line or 'Source:' in line or 'Yield:' in line or 'Total:' in line: if len(line.strip().split(':')[1]) > 0: directions.append(line.strip() + '\n') if ingredient_mode: if len(line) > 2 and 'Instructions:' not in line: ingredients.append(line.strip()) if direction_mode: if len(line) > 2: directions.append(line.strip() + '\n') if 'Ingredients:' in line: ingredient_mode = True if 'Instructions:' in line: ingredient_mode = False direction_mode = True recipe = Recipe.objects.create(name=title, description=description, created_by=self.request.user, internal=True, space=self.request.space) step = Step.objects.create( instruction='\n'.join(directions) + '\n\n', space=self.request.space, ) for ingredient in ingredients: if len(ingredient.strip()) > 0: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=amount, note=note, space=self.request.space, )) recipe.steps.add(step) return recipe
def get_recipe_from_file(self, file): recipe = Recipe.objects.create(name=file['name'].strip(), created_by=self.request.user, internal=True, space=self.request.space) if file['servings'] != '': recipe.servings = file['servings'] if file['timeCook'] != '': recipe.waiting_time = file['timeCook'] if file['timePrep'] != '': recipe.working_time = file['timePrep'] recipe.save() step = Step.objects.create( instruction=file['directions'], space=self.request.space, ) if file['source'] != '': step.instruction += '\n' + file['source'] for ingredient in file['ingredients'].split('\n'): if len(ingredient.strip()) > 0: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=amount, note=note, space=self.request.space, )) recipe.steps.add(step) if file['image'] != '': self.import_recipe_image( recipe, BytesIO( base64.b64decode(file['image'].replace( 'data:image/jpeg;base64,', ''))), filetype='.jpeg') return recipe
def get_recipe_from_file(self, file): ingredient_mode = False direction_mode = False ingredients = [] directions = [] for fl in file.readlines(): line = fl.decode("utf-8") if 'Title:' in line: title = line.replace('Title:', '').strip() if 'Description:' in line: description = line.replace('Description:', '').strip() if 'Yield:' in line: directions.append(_('Servings') + ' ' + line.replace('Yield:', '').strip() + '\n') if 'Cook:' in line: directions.append(_('Waiting time') + ' ' + line.replace('Cook:', '').strip() + '\n') if 'Prep:' in line: directions.append(_('Preparation Time') + ' ' + line.replace('Prep:', '').strip() + '\n') if 'Cookbook:' in line: directions.append(_('Cookbook') + ' ' + line.replace('Cookbook:', '').strip() + '\n') if 'Section:' in line: directions.append(_('Section') + ' ' + line.replace('Section:', '').strip() + '\n') if ingredient_mode: if len(line) > 2 and 'Instructions:' not in line: ingredients.append(line.strip()) if direction_mode: if len(line) > 2: directions.append(line.strip()) if 'Ingredients:' in line: ingredient_mode = True if 'Instructions:' in line: ingredient_mode = False direction_mode = True recipe = Recipe.objects.create(name=title, description=description, created_by=self.request.user, internal=True, space=self.request.space, ) step = Step.objects.create(instruction='\n'.join(directions)) for ingredient in ingredients: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add(Ingredient.objects.create( food=f, unit=u, amount=amount, note=note )) recipe.steps.add(step) return recipe
def get_recipe_from_file(self, file): recipe = Recipe.objects.create(name=file['name'].strip(), created_by=self.request.user, internal=True, space=self.request.space) try: if file['recipeYield'] != '': recipe.servings = int(file['recipeYield']) if file['totalTime'] != '': recipe.waiting_time = int(file['totalTime']) - int( file['timePrep']) if file['prepTime'] != '': recipe.working_time = int(file['timePrep']) recipe.save() except Exception as e: print('failed to parse yield or time ', str(e)) ingredients_added = False for s in file['recipeInstructions']: step = Step.objects.create(instruction=s['text']) if not ingredients_added: ingredients_added = True for ingredient in file['recipeIngredient']: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create(food=f, unit=u, amount=amount, note=note)) recipe.steps.add(step) if len(file['image']) > 0: try: response = requests.get(file['image'][0]) self.import_recipe_image(recipe, BytesIO(response.content)) except Exception as e: print('failed to import image ', str(e)) return recipe
def get_recipe_from_file(self, file): recipe_json = json.loads(file.getvalue().decode("utf-8")) recipe = Recipe.objects.create( name=recipe_json['name'].strip(), description=recipe_json['description'].strip(), created_by=self.request.user, internal=True, servings=recipe_json['recipeYield'], space=self.request.space) # TODO parse times (given in PT2H3M ) # TODO parse keywords ingredients_added = False for s in recipe_json['recipeInstructions']: step = Step.objects.create(instruction=s) if not ingredients_added: ingredients_added = True for ingredient in recipe_json['recipeIngredient']: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create(food=f, unit=u, amount=amount, note=note)) recipe.steps.add(step) for f in self.files: if '.zip' in f['name']: import_zip = ZipFile(f['file']) for z in import_zip.filelist: if re.match(f'^Recipes/{recipe.name}/full.jpg$', z.filename): self.import_recipe_image( recipe, BytesIO(import_zip.read(z.filename))) return recipe
def get_recipe_from_file(self, file): recipe = Recipe.objects.create(name=file['name'].strip(), created_by=self.request.user, internal=True, servings=file['servings'], space=self.request.space, waiting_time=file['cook_time'], working_time=file['prep_time']) instructions = '' if file["info"] != '': instructions += file["info"] if file["directions"] != '': instructions += file["directions"] if file["source"] != '': instructions += file["source"] step = Step.objects.create( instruction=instructions, space=self.request.space, ) for ingredient in file['ingredients']: f = get_food(ingredient['food'], self.request.space) u = get_unit(ingredient['unit'], self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=ingredient['amount'], space=self.request.space, )) recipe.steps.add(step) return recipe
def get_recipe_from_file(self, file): ingredient_mode = False direction_mode = False description_mode = False ingredients = [] directions = [] descriptions = [] for fl in file.readlines(): line = fl.decode("utf-8") if 'title:' in line: title = line.replace('title:', '').replace('"', '').strip() if 'image:' in line: image = line.replace('image:', '').strip() if 'tags:' in line: tags = line.replace('tags:', '').strip() if ingredient_mode: if len(line) > 2 and 'directions:' not in line: ingredients.append(line[2:]) if '---' in line and direction_mode: direction_mode = False description_mode = True if direction_mode: if len(line) > 2: directions.append(line[2:]) if 'ingredients:' in line: ingredient_mode = True if 'directions:' in line: ingredient_mode = False direction_mode = True if description_mode and len(line) > 3 and '---' not in line: descriptions.append(line) recipe = Recipe.objects.create(name=title, created_by=self.request.user, internal=True, space=self.request.space) for k in tags.split(','): keyword, created = Keyword.objects.get_or_create( name=k.strip(), space=self.request.space) recipe.keywords.add(keyword) step = Step.objects.create(instruction='\n'.join(directions) + '\n\n' + '\n'.join(descriptions)) for ingredient in ingredients: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create(food=f, unit=u, amount=amount, note=note)) recipe.steps.add(step) for f in self.files: if '.zip' in f['name']: import_zip = ZipFile(f['file']) for z in import_zip.filelist: if re.match(f'^images/{image}$', z.filename): self.import_recipe_image( recipe, BytesIO(import_zip.read(z.filename))) return recipe
def get_recipe_from_file(self, file): # Create initial recipe with just a title and a decription recipe = Recipe.objects.create( name=file['title'], created_by=self.request.user, internal=True, space=self.request.space, ) # set the description as an empty string for later use for the source URL, incase there is no description text. recipe.description = '' try: if file['description'] != '': recipe.description = file['description'].strip() except Exception as e: print(recipe.name, ': failed to parse recipe description ', str(e)) instructions = file['instructions'] if not instructions: instructions = '' step = Step.objects.create( instruction=instructions, space=self.request.space, ) # Append the original import url to the step (if it exists) try: if file['url'] != '': step.instruction += '\n\nImported from: ' + file['url'] step.save() except Exception as e: print(recipe.name, ': failed to import source url ', str(e)) try: # Process the ingredients. Assumes 1 ingredient per line. for ingredient in file['ingredients'].split('\n'): if len(ingredient.strip()) > 0: amount, unit, ingredient, note = parse(ingredient) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=amount, note=note, space=self.request.space, )) except Exception as e: print(recipe.name, ': failed to parse recipe ingredients ', str(e)) recipe.steps.add(step) # Attempt to import prep/cooking times # quick hack, this assumes only one number in the quantity field. try: if file['quantity'] != '': for item in file['quantity'].split(' '): if item.isdigit(): recipe.servings = int(item) break except Exception as e: print(recipe.name, ': failed to parse quantity ', str(e)) try: if file['totalTime'] != '': recipe.waiting_time = int(file['totalTime']) except Exception as e: print(recipe.name, ': failed to parse total times ', str(e)) try: if file['preparationTime'] != '': recipe.working_time = int(file['preparationTime']) except Exception as e: print(recipe.name, ': failed to parse prep time ', str(e)) try: if file['cookingTime'] != '': recipe.waiting_time = int(file['cookingTime']) except Exception as e: print(recipe.name, ': failed to parse cooking time ', str(e)) recipe.save() # Import the recipe keywords try: if file['keywords'] != '': for keyword in file['keywords'].split(';'): k, created = Keyword.objects.get_or_create( name=keyword.strip(), space=self.request.space) recipe.keywords.add(k) recipe.save() except Exception as e: pass # TODO: Parse Nutritional Information # Import the original image from the zip file, if we cannot do that, attempt to download it again. try: if file['pictures'][0] != '': image_file_name = file['pictures'][0].split('/')[-1] for f in self.files: if '.rtk' in f['name']: import_zip = ZipFile(f['file']) self.import_recipe_image( recipe, BytesIO(import_zip.read(image_file_name)), filetype=get_filetype(image_file_name)) else: if file['originalPicture'] != '': response = requests.get(file['originalPicture']) if imghdr.what(BytesIO(response.content)) != None: self.import_recipe_image(recipe, BytesIO(response.content), filetype=get_filetype( file['originalPicture'])) else: raise Exception("Original image failed to download.") except Exception as e: print(recipe.name, ': failed to import image ', str(e)) return recipe
def get_recipe_from_file(self, file): # 'file' comes is as a beautifulsoup object recipe = Recipe.objects.create( name=file.find("h2", { "itemprop": "name" }).text.strip(), created_by=self.request.user, internal=True, space=self.request.space, ) # add 'Courses' and 'Categories' as keywords for course in file.find_all("span", {"itemprop": "recipeCourse"}): keyword, created = Keyword.objects.get_or_create( name=course.text, space=self.request.space) recipe.keywords.add(keyword) for category in file.find_all("meta", {"itemprop": "recipeCategory"}): keyword, created = Keyword.objects.get_or_create( name=category.get("content"), space=self.request.space) recipe.keywords.add(keyword) try: recipe.servings = parse_servings( file.find("span", { "itemprop": "recipeYield" }).text.strip()) recipe.working_time = iso_duration_to_minutes( file.find("span", { "meta": "prepTime" }).text.strip()) recipe.waiting_time = iso_duration_to_minutes( file.find("span", { "meta": "cookTime" }).text.strip()) recipe.save() except AttributeError: pass step = Step.objects.create( instruction='', space=self.request.space, ) for ingredient in file.find("div", { "itemprop": "recipeIngredients" }).findChildren("p"): if ingredient.text == "": continue amount, unit, ingredient, note = parse(ingredient.text.strip()) f = get_food(ingredient, self.request.space) u = get_unit(unit, self.request.space) step.ingredients.add( Ingredient.objects.create( food=f, unit=u, amount=amount, note=note, space=self.request.space, )) for s in file.find("div", { "itemprop": "recipeDirections" }).find_all("p"): if s.text == "": continue step.instruction += s.text + ' \n' if file.find("span", {"itemprop": "recipeSource"}).text != '': step.instruction += "\n\nImported from: " + file.find( "span", { "itemprop": "recipeSource" }).text step.save() source_url_added = True recipe.steps.add(step) # import the Primary recipe image that is stored in the Zip try: for f in self.files: if '.zip' in f['name']: import_zip = ZipFile(f['file']) self.import_recipe_image( recipe, BytesIO( import_zip.read( file.find("img", class_="recipe-photo").get("src"))), filetype='.jpeg') except Exception as e: pass return recipe