munch-ease-backend/recipes/__init__.py

35 lines
1.3 KiB
Python
Raw Normal View History

2024-01-17 10:39:48 +00:00
from recipes.db import Recipe, insert_recipe, find_recipe_by_id, get_all, find_recipes_by_name, row_to_recipe
2024-01-17 07:21:16 +00:00
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
2024-01-13 03:21:38 +00:00
2024-01-17 07:21:16 +00:00
import json
2024-01-13 03:21:38 +00:00
2024-01-17 07:21:16 +00:00
async def parse_recipe(conn, url: str) -> Recipe:
ldata = await _scrape_recipe_ldata(url)
if ldata:
return await _get_recipe_from_ldata(conn, url, ldata)
2024-01-13 03:21:38 +00:00
return None
async def _get_recipe_from_ldata(conn, url: str, ldata: dict) -> dict:
2024-01-17 07:21:16 +00:00
ingredients = _parse_ingredient_from_nlp(ldata['recipeIngredient'])
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-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-01-13 08:44:07 +00:00
image_urls=images,
2024-01-13 03:21:38 +00:00
raw_data=json.dumps(ldata),
ingredients=ingredients
2024-01-17 07:21:16 +00:00
)