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:
if isinstance(dct, str):
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)
if match is None:
raise RuntimeError(
"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)
amount = float(1)
unit = ctx.default_unit
if unit is not None:
unitx = ctx.units.get(unitstr)
if unitx is None:
ctx.issues.error(issues.ISSUE_UNKNOWN_UNIT, "unknown unit {unitstr}")
else:
unit = unitx
name = match.group(3)
note = match.group(4)
name = string
note = None
if match is not None:
amount = float(match.group(1))
unitstr = match.group(2)
if unit is not None:
unitx = ctx.units.get(unitstr)
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:
note = ""
return cls(