Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ harmonize printing float values #112

Merged
merged 1 commit into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mindee/documents/invoice/invoice_v4.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def __str__(self) -> str:
taxes = "\n ".join(f"{t}" for t in self.taxes)
line_items = "\n"
if self.line_items:
line_items = "\n Code | QTY | Price | Amount | Tax (Rate) | Description\n"
line_items = "\n Code | QTY | Price | Amount | Tax (Rate) | Description\n"
for item in self.line_items:
line_items += f" {item}\n"

Expand Down
19 changes: 7 additions & 12 deletions mindee/documents/invoice/line_item.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Optional

from mindee.fields.base import FieldPositionMixin, TypePrediction
from mindee.fields.base import FieldPositionMixin, TypePrediction, float_to_string


class InvoiceLineItem(FieldPositionMixin):
Expand Down Expand Up @@ -55,24 +55,19 @@ def to_opt_float(key: str) -> Optional[float]:
self.tax_amount = to_opt_float("tax_amount")

def __str__(self) -> str:
def opt_float_to_str(value: Optional[float]) -> str:
if value is None:
return ""
return str(value)

tax = f"{opt_float_to_str(self.tax_amount)}"
tax = float_to_string(self.tax_amount)
if self.tax_rate is not None:
tax += f" ({self.tax_rate} %)"
tax += f" ({float_to_string(self.tax_rate)}%)"

description = self.description or ""
if len(description) > 32:
description = description[:32] + "..."
row = [
self.product_code or "",
opt_float_to_str(self.quantity),
opt_float_to_str(self.unit_price),
opt_float_to_str(self.total_amount),
float_to_string(self.quantity),
float_to_string(self.unit_price),
float_to_string(self.total_amount),
tax,
description,
]
return "{:<14} | {:<6} | {:<7} | {:<8} | {:<14} | {} ".format(*row)
return "{:<14} | {:<6} | {:<7} | {:<8} | {:<16} | {} ".format(*row)
2 changes: 1 addition & 1 deletion mindee/documents/passport/passport_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def __str__(self) -> str:
]
)
return clean_out_string(
"-----Passport data-----\n"
"----- Passport V1 -----\n"
f"Filename: {self.filename or ''}\n"
f"Full name: {self.full_name}\n"
f"Given names: {given_names}\n"
Expand Down
10 changes: 9 additions & 1 deletion mindee/fields/amount.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from typing import Optional

from mindee.fields.base import BaseField, FieldPositionMixin, TypePrediction
from mindee.fields.base import (
BaseField,
FieldPositionMixin,
TypePrediction,
float_to_string,
)


class AmountField(FieldPositionMixin, BaseField):
Expand Down Expand Up @@ -32,3 +37,6 @@ def __init__(
self.confidence = 0.0

self._set_position(prediction)

def __str__(self) -> str:
return float_to_string(self.value)
9 changes: 9 additions & 0 deletions mindee/fields/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,12 @@ def field_array_sum(array: TypeFieldList) -> float:
except (AttributeError, TypeError):
return 0.0
return float(arr_sum)


def float_to_string(value: Optional[float], min_precision=2) -> str:
"""Print a float with a specified minimum precision, but allowing greater precision."""
if value is not None:
precision = len(str(value).split(".")[1])
precision = max(precision, min_precision)
return f"{value:.{precision}f}"
return ""
6 changes: 3 additions & 3 deletions mindee/fields/locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

class LocaleField(BaseField):
language: Optional[str] = None
"""Language ISO code"""
"""ISO 639-1 language code"""
country: Optional[str] = None
"""Country ISO code"""
"""ISO 3166-1 alpha-2 country code"""
currency: Optional[str] = None
"""3 letter currency code"""
"""ISO 4217 currency code"""

def __init__(
self,
Expand Down
13 changes: 8 additions & 5 deletions mindee/fields/tax.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from typing import Optional

from mindee.fields.base import BaseField, FieldPositionMixin, TypePrediction
from mindee.fields.base import (
BaseField,
FieldPositionMixin,
TypePrediction,
float_to_string,
)


class TaxField(FieldPositionMixin, BaseField):
Expand Down Expand Up @@ -65,11 +70,9 @@ def __init__(
self.confidence = 0.0

def __str__(self) -> str:
out_str = ""
if self.value is not None:
out_str += str(self.value)
out_str = float_to_string(self.value)
if self.rate is not None:
out_str += f" {self.rate}%"
out_str += f" {float_to_string(self.rate)}%"
if self.code is not None:
out_str += f" {self.code}"
return out_str.strip()
19 changes: 18 additions & 1 deletion tests/fields/test_field.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
from mindee.fields.base import BaseField, field_array_confidence, field_array_sum
import pytest

from mindee.fields.base import (
BaseField,
field_array_confidence,
field_array_sum,
float_to_string,
)
from mindee.fields.company_registration import CompanyRegistrationField
from mindee.fields.text import TextField

Expand Down Expand Up @@ -82,3 +89,13 @@ def test_array_sum():
BaseField({"value": 4, "confidence": 0.8}),
]
assert field_array_sum(fields) == 0.0


def test_float_to_string():
assert float_to_string(1.0) == "1.00"
assert float_to_string(1.001, min_precision=1) == "1.001"
assert float_to_string(1.0, min_precision=4) == "1.0000"

# should not work on integer values
with pytest.raises(IndexError):
float_to_string(1)
4 changes: 2 additions & 2 deletions tests/fields/test_tax.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ def test_constructor():
assert tax.confidence == 0.1
assert tax.rate == 0.2
assert len(tax.bounding_box) > 0
assert str(tax) == "2.0 0.2% QST"
assert str(tax) == "2.00 0.20% QST"


def test_constructor_no_rate():
field_dict = {"value": 2.0, "confidence": 0.1}
tax = TaxField(field_dict)
assert tax.rate is None
assert tax.bounding_box is None
assert str(tax) == "2.0"
assert str(tax) == "2.00"


def test_constructor_no_amount():
Expand Down