munch-ease-backend/recipe/__init__.py

63 lines
2.1 KiB
Python
Raw Normal View History

2024-01-13 03:21:38 +00:00
from product import Product
2024-01-13 05:40:10 +00:00
from recipe.db import Recipe, Ingredient, insert_recipe, insert_ingredient
2024-01-13 03:21:38 +00:00
from recipe.scraping import scrape_recipe
from ingredient_parser import parse_multiple_ingredients
from typing import List
from product import find_product_by_tag
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 05:40:10 +00:00
real_unit = units.get_unit(unit)
unit = real_unit.name if real_unit else units.ITEMS.name
2024-01-13 05:48:09 +00:00
quantity = amount.quantity if amount.quantity else 1
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)
return Recipe(
id=0,
name=ldata['name'],
link=url,
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