11from enum import Enum
2+ from typing import TYPE_CHECKING , ClassVar , TypeAlias , Union
23
34from mindee .parsing .common .string_dict import StringDict
45from mindee .v2 .parsing .inference .field .field_confidence import FieldConfidence
@@ -13,17 +14,33 @@ class FieldType(str, Enum):
1314 SIMPLE = "SimpleField"
1415
1516
17+ if TYPE_CHECKING :
18+ from mindee .v2 .parsing .inference .field .list_field import ListField
19+ from mindee .v2 .parsing .inference .field .object_field import ObjectField
20+ from mindee .v2 .parsing .inference .field .simple_field import SimpleField
21+
22+
23+ ResultFieldsType : TypeAlias = Union ["SimpleField" , "ObjectField" , "ListField" ]
24+
25+
1626class BaseField :
17- """Field with base information ."""
27+ """Base class for V2 fields ."""
1828
1929 field_type : FieldType
20- _indent_level : int
30+ """The type of field."""
2131 locations : list [FieldLocation ]
32+ """List of the location candidates for the value."""
2233 confidence : FieldConfidence | None
34+ """Confidence associated with the field."""
35+ _indent_level : int
36+ """For pretty printing."""
37+
38+ _registry : ClassVar [dict [str , type [ResultFieldsType ]]] = {}
2339
2440 def __init__ (
2541 self , field_type : FieldType , raw_response : StringDict , indent_level : int = 0
2642 ) -> None :
43+
2744 self .field_type = field_type
2845 self ._indent_level = indent_level
2946
@@ -41,6 +58,27 @@ def __init__(
4158 for location in raw_response ["locations" ]:
4259 self .locations .append (FieldLocation (location ))
4360
61+ @classmethod
62+ def register (cls , discriminator_key : str ):
63+ """Class decorator: subclasses declare which JSON key identifies them."""
64+
65+ def decorator (subclass ):
66+ cls ._registry [discriminator_key ] = subclass
67+ return subclass
68+
69+ return decorator
70+
71+ @classmethod
72+ def build (cls , raw_response : dict , indent_level : int ) -> ResultFieldsType :
73+ """Build an instance of the appropriate subclass."""
74+
75+ if not isinstance (raw_response , dict ):
76+ raise ValueError ("Field must be a dict" )
77+ for key , subclass in cls ._registry .items ():
78+ if key in raw_response :
79+ return subclass (raw_response , indent_level )
80+ raise ValueError ("Invalid structure for field" )
81+
4482 def multi_str (self ) -> str :
4583 """String representation of the field in a list."""
4684 return str (self )
0 commit comments