allow using a single string as an ingredient instead of a dict
This commit is contained in:
parent
072aa03a53
commit
883f0756f9
5 changed files with 59 additions and 17 deletions
|
@ -1,5 +1,6 @@
|
|||
from abc import abstractmethod
|
||||
import collections
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Self
|
||||
|
||||
import comfyrecipes.settings as settings
|
||||
|
@ -178,8 +179,8 @@ class IngredientInstance(Element):
|
|||
self,
|
||||
ctx: Context,
|
||||
name: str,
|
||||
amount: float,
|
||||
unit: Unit,
|
||||
amount: Optional[float],
|
||||
unit: Optional[Unit],
|
||||
alternatives: List["IngredientInstance"],
|
||||
note: str,
|
||||
price: Optional["PriceDB"],
|
||||
|
@ -193,7 +194,37 @@ class IngredientInstance(Element):
|
|||
self.price = price
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, ctx: Context, dct: Dict[str, Any]) -> Self:
|
||||
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 ]+)(?: \((.*)\))?$")
|
||||
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)
|
||||
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)
|
||||
if note is None:
|
||||
note = ""
|
||||
return cls(
|
||||
ctx=ctx,
|
||||
name=dct,
|
||||
amount=amount,
|
||||
unit=unit,
|
||||
alternatives=[],
|
||||
note=note,
|
||||
price=None,
|
||||
)
|
||||
name = dct["name"]
|
||||
|
||||
ingredient = ctx.ingredients.get(name)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue