parsing: also accept short ingredients without amounts

for example 'oil' will now be allowed, previously it would have to be `1
spoon oil` when sometimes people don't know the amount
This commit is contained in:
Emi Vasilek 2024-10-12 00:05:45 +02:00
parent 3e3de7ea59
commit cc9206306a

View file

@ -197,19 +197,20 @@ class IngredientInstance(Element):
def from_dict(cls, ctx: Context, dct: str | Dict[str, Any]) -> Self: def from_dict(cls, ctx: Context, dct: str | Dict[str, Any]) -> Self:
if isinstance(dct, str): if isinstance(dct, str):
string = dct.strip() string = dct.strip()
p = re.compile(r"^(?:([0-9\.]+) ([a-zA-Z]+) )?([\w ]+)(?: \((.*)\))?$") p = re.compile(r"^(?:([0-9\.]+) ([a-zA-Z]+) )+([\w ]+)(?: \((.*)\))?$")
match = p.match(string) match = p.match(string)
if match is None:
raise RuntimeError( amount = float(1)
"ingredient {string} regex not matched, it should be in the format [amount(num) unit(string, one word)] name(string, any number of words) [(note(string))]" unit = ctx.default_unit
) name = string
note = None
if match is not None:
amount = float(match.group(1)) amount = float(match.group(1))
unitstr = match.group(2) unitstr = match.group(2)
unit = ctx.default_unit
if unit is not None: if unit is not None:
unitx = ctx.units.get(unitstr) unitx = ctx.units.get(unitstr)
if unitx is None: if unitx is None:
ctx.issues.error(issues.ISSUE_UNKNOWN_UNIT, "unknown unit {unitstr}") ctx.issues.error(issues.ISSUE_UNKNOWN_UNIT, f"unknown unit {unitstr}")
else: else:
unit = unitx unit = unitx
name = match.group(3) name = match.group(3)