munch-ease-backend/ingredients/__init__.py

60 lines
2 KiB
Python
Raw Normal View History

2024-05-02 11:20:52 +00:00
from ingredients.db import Ingredient, find_ingredients_by_meal_id, find_ingredients_by_recipe_id, insert_ingredient, delete_ingredients_by_meal_id
2024-01-17 07:21:16 +00:00
import units
from products import Product, find_product_by_tag
from ingredient_parser import parse_multiple_ingredients
from typing import List
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 ''
quantity, unit = None, None
for amount in ingredient.amount:
if quantity is None and amount.quantity:
quantity = amount.quantity
if unit is None and amount.unit:
real_unit = units.get_unit(amount.unit)
if real_unit:
unit = real_unit.name
if isinstance(quantity, str):
try:
quantity = float(quantity)
except ValueError:
pass
if quantity is None or not isinstance(quantity, (int, float)):
quantity = 1
if unit is None:
unit = units.ITEMS.name
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 _find_existing_product(conn, ingredient: str) -> Product:
async for item in find_product_by_tag(conn, ingredient):
return item
return None
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_id = existing.id
ingredient.product = existing
return ingredients