from persons import Person from recipes.db import Recipe, insert_recipe, find_recipe_by_id, get_all, find_recipes_by_name, row_to_recipe, load_recipe_ingredients, hide_recipe from recipes.scraping import scrape_recipe_ldata as _scrape_recipe_ldata from ingredients import parse_ingredient_from_nlp as _parse_ingredient_from_nlp, match_existing_products as _match_existing_products import re async def parse_recipe(conn, created_by: Person, url: str) -> Recipe: ldata = await _scrape_recipe_ldata(url) if ldata: return await _get_recipe_from_ldata(conn, url, ldata, created_by) return None def find_yield(recipe_ldata: dict) -> int: if 'recipeYield' in recipe_ldata: yield_vals = recipe_ldata['recipeYield'] if not isinstance(yield_vals, list): yield_vals = [yield_vals] for val in yield_vals: try: return int(val) except ValueError: pass for val in yield_vals: match = re.match(r'(\d+)', val) if match: return int(match.group(1)) return 4 async def _get_recipe_from_ldata(conn, url: str, ldata: dict, created_by: Person) -> dict: ingredients = _parse_ingredient_from_nlp(ldata['recipeIngredient']) ingredients = await _match_existing_products(conn, ingredients) name = ldata['name'] if 'name' in ldata else url images = ldata['image'] if 'image' in ldata else [] serves = find_yield(ldata) if isinstance(images, list) and len(images) > 0 and isinstance(images[0], dict): images = [image['url'] for image in images] if isinstance(images, dict): images = [images['url']] if isinstance(images, str): images = [images] return Recipe( id=0, name=name, link=url, serves=serves, image_urls=images, ingredients=ingredients, created_by=created_by, created_by_id=created_by.id, )