36 lines
1.4 KiB
Python
36 lines
1.4 KiB
Python
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Depends, Query
|
|
import aiosqlite
|
|
|
|
import ingredients as ingredients_mod
|
|
from api.deps import get_db, get_household_from_slug
|
|
|
|
|
|
router = APIRouter(prefix="/households/{householdSlug}/ingredients", tags=["ingredients"])
|
|
|
|
|
|
@router.get(
|
|
"/parse",
|
|
response_model=ingredients_mod.Ingredient | list[ingredients_mod.Ingredient],
|
|
summary="Parse an ingredient line or lines from a string",
|
|
)
|
|
async def parse_ingredient(
|
|
line: str | None = Query(None, description="Single ingredient line to parse"),
|
|
lines: list[str] | None = Query(None, description="Multiple ingredient lines to parse"),
|
|
household=Depends(get_household_from_slug),
|
|
conn: aiosqlite.Connection = Depends(get_db),
|
|
):
|
|
# Batch mode takes precedence if provided
|
|
if lines is not None:
|
|
parsed = [ingredients_mod.parse_ingredient_from_nlp(item_line) for item_line in lines]
|
|
matched = await ingredients_mod.match_existing_products(conn, parsed)
|
|
return matched
|
|
# Single line mode
|
|
if line is None:
|
|
from fastapi import HTTPException
|
|
|
|
raise HTTPException(status_code=422, detail="Query parameter 'line' or 'lines' is required")
|
|
parsed_one = ingredients_mod.parse_ingredient_from_nlp(line)
|
|
matched_one = await ingredients_mod.match_existing_products(conn, [parsed_one])
|
|
return matched_one[0]
|