munch-ease-backend/recipes/__init__.py

68 lines
2.3 KiB
Python
Raw Normal View History

2024-01-13 08:44:07 +00:00
from products import Product, find_product_by_tag
from recipes.db import Recipe, Ingredient, insert_recipe, insert_ingredient, find_recipe_by_id, find_ingredients_by_recipe_id, get_all
2024-01-13 07:44:48 +00:00
from recipes.scraping import scrape_recipe
2024-01-13 03:21:38 +00:00
from ingredient_parser import parse_multiple_ingredients
from typing import List
2024-01-13 05:40:10 +00:00
import json, units
2024-01-13 03:21:38 +00:00
async def find_existing_product(conn, ingredient: str) -> Product:
async for item in find_product_by_tag(conn, ingredient):
return item
return None
def parse_ingredient_from_nlp(ingredients: List[str]) -> Ingredient:
results = []
for ingredient in parse_multiple_ingredients(ingredients):
name = ingredient.name.text if ingredient.name else ''
2024-01-13 05:48:09 +00:00
quantity, unit = 1, units.ITEMS.name
2024-01-13 03:21:38 +00:00
if ingredient.amount:
amount = ingredient.amount[0]
2024-01-13 06:59:35 +00:00
quantity = amount.quantity if amount.quantity else 1
2024-01-13 05:40:10 +00:00
real_unit = units.get_unit(unit)
2024-01-13 06:59:35 +00:00
if real_unit:
unit = real_unit.name
elif not name:
name = unit
2024-01-13 03:21:38 +00:00
results.append(Ingredient(id=0,
line=ingredient.sentence,
name=name,
quantity=quantity,
unit=unit,
preparation=ingredient.preparation.text if ingredient.preparation else '',
product_id=0
))
return results
async def match_existing_products(conn, ingredients: List[Ingredient]) -> List[Ingredient]:
for ingredient in ingredients:
if not ingredient.product:
existing = await find_existing_product(conn, ingredient.name)
if existing:
ingredient.product = existing
return ingredients
async def _get_recipe_from_ldata(conn, url: str, ldata: dict) -> dict:
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 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
)
async def parse_recipe(conn, url: str) -> dict:
2024-01-13 05:40:10 +00:00
ldata = await scrape_recipe(url)
2024-01-13 03:21:38 +00:00
if ldata:
return await _get_recipe_from_ldata(conn, url, ldata)
return None