Skip to content

Commit

Permalink
Rework ingredient parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
felixschndr committed May 30, 2024
1 parent 46b78ca commit 286b4a2
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 34 deletions.
6 changes: 2 additions & 4 deletions source/bring_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,11 @@ def determine_list_uuid(self) -> str:
break

if not bring_list_uuid:
self.log.critical(
f"Could not find a bring list with the name {self.list_name}"
)
self.log.critical(f'Can not find a list with the name "{self.list_name}"')
sys.exit(1)

self.log.info(
f"Found the bring list {self.list_name} (UUID: {bring_list_uuid})"
f'Found the list with the name "{self.list_name}" (UUID: {bring_list_uuid})'
)

return bring_list_uuid
Expand Down
71 changes: 49 additions & 22 deletions source/ingredient.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@


class Ingredient(LoggerMixin):
def __init__(self, ingredient_input: dict, ignored_ingredients: list[str]):
def __init__(
self,
ingredient_input: dict,
ignored_ingredients: list[str],
enable_amount: bool,
):
super().__init__()

self.ingredient_input = ingredient_input
self.ignored_ingredients = ignored_ingredients

self.enable_amount = enable_amount

self.food = None
self.specification = ""

Expand All @@ -20,41 +27,61 @@ def __repr__(self):
return self.food

def parse_input(self) -> None:
self.log.debug(f"Parsing {self.ingredient_input}")
try:
_ = self.ingredient_input["food"]
if self.enable_amount:
self._parse_input_with_ingredient_amounts()
else:
self._parse_input_with_no_ingredient_amounts()
except KeyError:
# Happens if there is an empty ingredient (i.e. added one ingredient but did not fill it out)
raise ValueError("There is an ingredient with no name, it will be ignored!")
if self.ingredient_input["disableAmount"]:
self._parse_input_with_no_ingredient_amounts()
else:
self._parse_input_with_ingredient_amounts()

self.log.debug(f"Parsed ingredient: {self}")

def _parse_input_with_no_ingredient_amounts(self) -> None:
self.log.debug("Parsing input with no ingredient amount")
self.food = self.ingredient_input["display"]
note = self.ingredient_input["note"]
if not note:
raise KeyError()
self.food = note

def _parse_input_with_ingredient_amounts(self) -> None:
self.log.debug("Parsing input with ingredient amount")

food_name = self.ingredient_input["food"]["name"]
food_plural_name = self.ingredient_input["food"]["pluralName"]
quantity = int(self.ingredient_input["quantity"] or 0)
unit = self.ingredient_input["unit"]
note = self.ingredient_input["note"]

# Ignored check #
if food_name.lower() in self.ignored_ingredients:
raise IgnoredIngredient(f"Found ignored ingredient {food_name}")
self.food = food_name

quantity = self.ingredient_input.get("quantity", None)
# Food #
if quantity and quantity > 1 and food_plural_name:
self.food = food_plural_name
else:
self.food = food_name

# Quantity #
if quantity:
self.specification += f"{str(quantity)} "
self.specification += str(quantity)

unit = self.ingredient_input.get("unit", None)
# Seperator between Quantity and Unit #
if quantity and unit:
self.specification += " "

# Unit #
if unit:
abbreviation = unit["abbreviation"]
name = unit["name"]
if abbreviation:
self.specification += abbreviation
elif name:
self.specification += name

note = self.ingredient_input.get("note", None)
unit_name = unit["name"]
unit_abbreviation = unit["abbreviation"]
unit_plural_name = unit["pluralName"]
if unit_abbreviation:
self.specification += unit_abbreviation
elif unit_plural_name and quantity and quantity > 1:
self.specification += unit_plural_name
elif unit_name:
self.specification += unit_name

# Note #
if note:
self.specification += f" ({note})"
20 changes: 12 additions & 8 deletions source/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,29 @@
def webhook_handler():
data = request.get_json(force=True)

recipe_name = data["name"]
logger.log.info(f'Received recipe "{recipe_name}" from "{request.origin}"')
logger.log.info(f'Received recipe "{data["name"]}" from "{request.origin}"')

if data["settings"]["disableAmount"]:
enable_amount = not data["settings"]["disableAmount"]
if enable_amount:
logger.log.debug("This recipe has its ingredient amount enabled")
else:
logger.log.warning(
"This recipe has its ingredient amount this disabled. Its ingredients will not be checked whether they are supposed to be ignored."
"This recipe has its ingredient amount this disabled --> Its ingredients will not be checked whether they are supposed to be ignored"
)

for ingredient in data["recipeIngredient"]:
try:
ingredient = Ingredient(ingredient, bring_handler.ignored_ingredients)
parsed_ingredient = Ingredient(
ingredient, bring_handler.ignored_ingredients, enable_amount
)
except ValueError as e:
logging.warning(e)
logger.log.warning(e)
continue
except IgnoredIngredient as e:
logging.debug(e)
logger.log.debug(e)
continue

bring_handler.add_item_to_list(ingredient)
bring_handler.add_item_to_list(parsed_ingredient)

logger.log.info("Added all ingredients to Bring")
bring_handler.notify_users_about_changes_in_list()
Expand Down

0 comments on commit 286b4a2

Please sign in to comment.