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,23 +197,24 @@ 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))]"
)
amount = float(match.group(1))
unitstr = match.group(2)
unit = ctx.default_unit unit = ctx.default_unit
if unit is not None: name = string
unitx = ctx.units.get(unitstr) note = None
if unitx is None: if match is not None:
ctx.issues.error(issues.ISSUE_UNKNOWN_UNIT, "unknown unit {unitstr}") amount = float(match.group(1))
else: unitstr = match.group(2)
unit = unitx if unit is not None:
name = match.group(3) unitx = ctx.units.get(unitstr)
note = match.group(4) if unitx is None:
ctx.issues.error(issues.ISSUE_UNKNOWN_UNIT, f"unknown unit {unitstr}")
else:
unit = unitx
name = match.group(3)
note = match.group(4)
if note is None: if note is None:
note = "" note = ""
return cls( return cls(