munch-ease-backend/recipes/__init__.py

59 lines
1.9 KiB
Python
Raw Normal View History

2024-05-19 11:22:30 +00:00
from persons import Person
2024-04-28 03:57:02 +00:00
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
2024-01-17 07:21:16 +00:00
from recipes.scraping import scrape_recipe_ldata as _scrape_recipe_ldata
2024-05-21 12:12:09 +00:00
from ingredients import parse_ingredient_from_nlp, match_existing_products
2024-01-13 03:21:38 +00:00
2024-05-19 11:22:30 +00:00
import re
async def parse_recipe(conn, created_by: Person, url: str) -> Recipe:
2024-01-17 07:21:16 +00:00
ldata = await _scrape_recipe_ldata(url)
if ldata:
2024-05-19 11:22:30 +00:00
return await _get_recipe_from_ldata(conn, url, ldata, created_by)
2024-01-13 03:21:38 +00:00
return None
2024-05-19 11:22:30 +00:00
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
2024-01-13 03:21:38 +00:00
2024-05-19 11:22:30 +00:00
async def _get_recipe_from_ldata(conn, url: str, ldata: dict, created_by: Person) -> dict:
2024-09-21 21:11:01 +00:00
ingredients = [parse_ingredient_from_nlp(ingredient) for ingredient in ldata['recipeIngredient']]
2024-05-21 12:12:09 +00:00
ingredients = await match_existing_products(conn, ingredients)
2024-01-13 08:44:07 +00:00
name = ldata['name'] if 'name' in ldata else url
images = ldata['image'] if 'image' in ldata else []
2024-05-19 11:22:30 +00:00
serves = find_yield(ldata)
2024-01-13 23:41:15 +00:00
2024-01-17 06:53:27 +00:00
if isinstance(images, list) and len(images) > 0 and isinstance(images[0], dict):
2024-01-13 23:41:15 +00:00
images = [image['url'] for image in images]
if isinstance(images, dict):
images = [images['url']]
if isinstance(images, str):
images = [images]
2024-01-13 03:21:38 +00:00
return Recipe(
id=0,
2024-01-13 08:44:07 +00:00
name=name,
2024-01-13 03:21:38 +00:00
link=url,
2024-05-19 11:22:30 +00:00
serves=serves,
2024-01-13 08:44:07 +00:00
image_urls=images,
2024-05-19 11:22:30 +00:00
ingredients=ingredients,
created_by=created_by,
created_by_id=created_by.id,
2024-01-17 07:21:16 +00:00
)