11"""Models for the base data types."""
22
33from enum import Enum
4- from typing import List , Tuple
4+ from typing import Any , List , Tuple
55
66from pydantic import BaseModel , FieldSerializationInfo , field_serializer
77
@@ -21,16 +21,23 @@ class CoordOrigin(str, Enum):
2121 BOTTOMLEFT = "BOTTOMLEFT"
2222
2323
24- _CTX_COORD_PREC = "coord_prec"
24+ class PydanticSerCtxKey (str , Enum ):
25+ """Pydantic serialization context keys."""
2526
27+ COORD_PREC = "coord_prec" # key for coordinates precision
28+ CONFID_PREC = "confid_prec" # key for confidence values precision
2629
27- def _serialize_precision (
28- value : float , info : FieldSerializationInfo , ctx_key : str
30+
31+ def round_pydantic_float (
32+ val : float , ctx : Any , precision_ctx_key : PydanticSerCtxKey
2933) -> float :
30- precision = info .context .get (ctx_key ) if info .context else None
31- if isinstance (precision , int ):
32- return round (value , precision )
33- return value
34+ """Round float, provided the precision is available in the context."""
35+ precision = (
36+ ctx .get (precision_ctx_key .value )
37+ if isinstance (ctx , dict )
38+ else getattr (ctx , precision_ctx_key .value , None )
39+ )
40+ return round (val , precision ) if isinstance (precision , int ) else val
3441
3542
3643class Size (BaseModel ):
@@ -41,7 +48,7 @@ class Size(BaseModel):
4148
4249 @field_serializer ("width" , "height" )
4350 def _serialize (self , value : float , info : FieldSerializationInfo ) -> float :
44- return _serialize_precision (value , info , _CTX_COORD_PREC )
51+ return round_pydantic_float (value , info . context , PydanticSerCtxKey . COORD_PREC )
4552
4653 def as_tuple (self ):
4754 """as_tuple."""
@@ -70,7 +77,7 @@ def height(self):
7077
7178 @field_serializer ("l" , "t" , "r" , "b" )
7279 def _serialize (self , value : float , info : FieldSerializationInfo ) -> float :
73- return _serialize_precision (value , info , _CTX_COORD_PREC )
80+ return round_pydantic_float (value , info . context , PydanticSerCtxKey . COORD_PREC )
7481
7582 def resize_by_scale (self , x_scale : float , y_scale : float ):
7683 """resize_by_scale."""
0 commit comments