fix: increased float rounding precision for CRF parser (#1369)

* increased float rounding precision for crf parser

* limited fractions to a max denominator of 32 to prevent weirdly specific values

* add test cases for 1/8 and 1/32

* add rounding to avoid more digits than necessary

Co-authored-by: Hayden <64056131+hay-kot@users.noreply.github.com>
This commit is contained in:
Michael Genson 2022-06-10 21:18:31 -05:00 committed by GitHub
parent 504bf41b9c
commit b904b161eb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 9 additions and 5 deletions

View file

@ -74,7 +74,7 @@ class RecipeIngredient(MealieModel):
empty string.
"""
if isinstance(value, float):
return value
return round(value, 3)
if value is None or value == "":
return None
return value

View file

@ -37,7 +37,7 @@ class CRFIngredient(BaseModel):
# Check if other contains a fraction
try:
if values["other"] is not None and values["other"].find("/") != -1:
return float(Fraction(values["other"])).__round__(1)
return round(float(Fraction(values["other"])), 3)
else:
return 1
except Exception:

View file

@ -74,7 +74,7 @@ class NLPParser(ABCIngredientParser):
unit=CreateIngredientUnit(name=crf_model.unit),
food=CreateIngredientFood(name=crf_model.name),
disable_amount=False,
quantity=float(sum(Fraction(s) for s in crf_model.qty.split())),
quantity=float(sum(Fraction(s).limit_denominator(32) for s in crf_model.qty.split())),
)
except Exception as e:
logger.error(f"Failed to parse ingredient: {crf_model}: {e}")

View file

@ -26,8 +26,12 @@ def crf_exists() -> bool:
test_ingredients = [
TestIngredient("½ cup all-purpose flour", 0.5, "cup", "all-purpose flour", ""),
TestIngredient("1½ teaspoons ground black pepper", 1.5, "teaspoon", "black pepper", "ground"),
TestIngredient("⅔ cup unsweetened flaked coconut", 0.7, "cup", "coconut", "unsweetened flaked"),
TestIngredient("⅓ cup panko bread crumbs", 0.3, "cup", "panko bread crumbs", ""),
TestIngredient("⅔ cup unsweetened flaked coconut", 0.667, "cup", "coconut", "unsweetened flaked"),
TestIngredient("⅓ cup panko bread crumbs", 0.333, "cup", "panko bread crumbs", ""),
# Small Fraction Tests - PR #1369
# Reported error is was for 1/8 - new lowest expected threshold is 1/32
TestIngredient("1/8 cup all-purpose flour", 0.125, "cup", "all-purpose flour", ""),
TestIngredient("1/32 cup all-purpose flour", 0.03125, "cup", "all-purpose flour", ""),
]