import re from typing import Optional from ingredients import match_existing_products, parse_ingredient_from_nlp from persons import Person from recipes.db import ( Recipe as Recipe, find_recipe_by_id as find_recipe_by_id, find_recipes_by_name as find_recipes_by_name, find_recipes_by_name_paged as find_recipes_by_name_paged, get_all as get_all, get_all_paged as get_all_paged, compute_prev_cursor as compute_prev_cursor, count_all as count_all, count_by_name as count_by_name, hide_recipe as hide_recipe, insert_recipe as insert_recipe, load_recipe_ingredients as load_recipe_ingredients, row_to_recipe as row_to_recipe, ) from recipes.scraping import scrape_recipe_ldata as _scrape_recipe_ldata async def parse_recipe(conn, created_by: Person, url: str) -> Optional[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) -> Recipe: ingredients = [ parse_ingredient_from_nlp(ingredient) for ingredient in 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, )