66 lines
No EOL
2.2 KiB
Python
66 lines
No EOL
2.2 KiB
Python
from product import Product
|
|
from recipe.db import Recipe, Ingredient, insert_recipe, insert_ingredient, find_recipe_by_id, find_ingredients_by_recipe_id
|
|
from recipe.scraping import scrape_recipe
|
|
|
|
from ingredient_parser import parse_multiple_ingredients
|
|
from typing import List
|
|
from product import find_product_by_tag
|
|
|
|
import json, units
|
|
|
|
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 ''
|
|
|
|
quantity, unit = 1, units.ITEMS.name
|
|
if ingredient.amount:
|
|
amount = ingredient.amount[0]
|
|
quantity = amount.quantity if amount.quantity else 1
|
|
|
|
real_unit = units.get_unit(unit)
|
|
if real_unit:
|
|
unit = real_unit.name
|
|
elif not name:
|
|
name = unit
|
|
|
|
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:
|
|
ldata = await scrape_recipe(url)
|
|
if ldata:
|
|
return await _get_recipe_from_ldata(conn, url, ldata)
|
|
return None |