Skip to content

Commit

Permalink
fix: update normalize_weight function after Pint upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
raphael0202 committed Aug 31, 2023
1 parent 2e94d11 commit 80d3a09
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
9 changes: 8 additions & 1 deletion robotoff/prediction/ocr/product_weight.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import functools
import math
import re
from typing import Optional, Union

Expand Down Expand Up @@ -42,7 +43,13 @@ def normalize_weight(value: str, unit: str) -> tuple[float, str]:
else:
raise ValueError(f"unknown unit: {quantity.u}")

return normalized_quantity.magnitude, normalized_unit
# Rounding errors due to float may occur with Pint,
# round normalized value to floor if there is no significant difference
normalized_value = normalized_quantity.magnitude
if math.isclose(math.floor(normalized_value), normalized_value):
normalized_value = math.floor(normalized_value)

return normalized_value, normalized_unit


def is_valid_weight(weight_value: str) -> bool:
Expand Down
7 changes: 5 additions & 2 deletions tests/unit/prediction/ocr/test_product_weight.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import math

import pytest

from robotoff.prediction.ocr.dataclass import OCRRegex
Expand Down Expand Up @@ -66,8 +68,9 @@ def test_product_weight_with_ending_mention_regex(input_str: str, is_match: bool
],
)
def test_normalize_weight(value: str, unit: str, expected: tuple[float, str]):
result = normalize_weight(value, unit)
assert result == expected
normalized_value, normalized_unit = normalize_weight(value, unit)
assert math.isclose(normalized_value, expected[0])
assert normalized_unit == expected[1]


@pytest.mark.parametrize(
Expand Down

0 comments on commit 80d3a09

Please sign in to comment.