structa-maestro 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- structa_maestro/__init__.py +294 -0
- structa_maestro/batch.py +564 -0
- structa_maestro/binding.py +206 -0
- structa_maestro/builder/__init__.py +0 -0
- structa_maestro/builder/result_builder.py +308 -0
- structa_maestro/cli.py +730 -0
- structa_maestro/confidence/__init__.py +49 -0
- structa_maestro/confidence/calibration.py +990 -0
- structa_maestro/confidence/normalizer.py +203 -0
- structa_maestro/config.py +111 -0
- structa_maestro/contracts/__init__.py +0 -0
- structa_maestro/contracts/enums.py +86 -0
- structa_maestro/contracts/models.py +229 -0
- structa_maestro/contracts/serialization.py +169 -0
- structa_maestro/documents/__init__.py +32 -0
- structa_maestro/documents/docx_parser.py +215 -0
- structa_maestro/documents/eml_parser.py +360 -0
- structa_maestro/documents/html_parser.py +337 -0
- structa_maestro/documents/inputs.py +277 -0
- structa_maestro/documents/loader.py +675 -0
- structa_maestro/documents/markdown_parser.py +225 -0
- structa_maestro/documents/models.py +33 -0
- structa_maestro/documents/normalization.py +24 -0
- structa_maestro/documents/pdf_parser.py +186 -0
- structa_maestro/documents/txt_parser.py +169 -0
- structa_maestro/engine.py +1201 -0
- structa_maestro/exceptions.py +38 -0
- structa_maestro/provenance/__init__.py +0 -0
- structa_maestro/provenance/associator.py +234 -0
- structa_maestro/py.typed +0 -0
- structa_maestro/review.py +1234 -0
- structa_maestro/schema/__init__.py +19 -0
- structa_maestro/schema/loader.py +616 -0
- structa_maestro/schema/models.py +269 -0
- structa_maestro/schema/pydantic_adapter.py +566 -0
- structa_maestro/schema/rules.py +526 -0
- structa_maestro/schema/serializer.py +156 -0
- structa_maestro/strategies/__init__.py +45 -0
- structa_maestro/strategies/base.py +101 -0
- structa_maestro/strategies/llm_anthropic.py +1142 -0
- structa_maestro/strategies/llm_config.py +154 -0
- structa_maestro/strategies/llm_gemini.py +1171 -0
- structa_maestro/strategies/llm_helpers.py +240 -0
- structa_maestro/strategies/llm_openai_compat.py +1183 -0
- structa_maestro/strategies/schema_compiler.py +248 -0
- structa_maestro/strategies/testing.py +71 -0
- structa_maestro/telemetry.py +800 -0
- structa_maestro/validation/__init__.py +0 -0
- structa_maestro/validation/cross_field.py +463 -0
- structa_maestro/validation/validator.py +531 -0
- structa_maestro-0.2.0.dist-info/METADATA +394 -0
- structa_maestro-0.2.0.dist-info/RECORD +55 -0
- structa_maestro-0.2.0.dist-info/WHEEL +4 -0
- structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
- structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
"""Pure-introspection Pydantic v2 BaseModel to ExtractionSchema compiler (Spec 007)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import types
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from datetime import date, datetime
|
|
8
|
+
from decimal import Decimal, InvalidOperation
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from typing import Annotated, Any, Literal, Union, get_args, get_origin
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel
|
|
13
|
+
|
|
14
|
+
from structa_maestro.contracts.enums import ExtractionCardinality, FieldType
|
|
15
|
+
from structa_maestro.exceptions import SchemaDefinitionError
|
|
16
|
+
from structa_maestro.schema.models import ExtractionSchema, FieldConstraints, FieldSpec
|
|
17
|
+
from structa_maestro.schema.rules import ValidationRule
|
|
18
|
+
|
|
19
|
+
_UNION_ORIGINS = (Union, types.UnionType)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _unwrap_annotated(annotation: Any) -> tuple[Any, list[Any]]:
|
|
23
|
+
"""Unwrap nested typing.Annotated wrappers, collecting all attached metadata."""
|
|
24
|
+
meta: list[Any] = []
|
|
25
|
+
current = annotation
|
|
26
|
+
while get_origin(current) is Annotated:
|
|
27
|
+
args = get_args(current)
|
|
28
|
+
current = args[0]
|
|
29
|
+
meta.extend(args[1:])
|
|
30
|
+
return current, meta
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _unwrap_optional(annotation: Any) -> tuple[Any, bool, list[Any]]:
|
|
34
|
+
"""Unwrap Optional[T] / T | None and return (inner_type, nullable, extra_metadata)."""
|
|
35
|
+
current, meta = _unwrap_annotated(annotation)
|
|
36
|
+
origin = get_origin(current)
|
|
37
|
+
if origin in _UNION_ORIGINS:
|
|
38
|
+
args = get_args(current)
|
|
39
|
+
non_none: list[Any] = []
|
|
40
|
+
has_none = False
|
|
41
|
+
for arg in args:
|
|
42
|
+
if arg is type(None):
|
|
43
|
+
has_none = True
|
|
44
|
+
else:
|
|
45
|
+
non_none.append(arg)
|
|
46
|
+
if not has_none or len(non_none) != 1:
|
|
47
|
+
raise SchemaDefinitionError(
|
|
48
|
+
f"Unsupported Union type {annotation!r}: only Optional[T] (T | None) is supported."
|
|
49
|
+
)
|
|
50
|
+
inner, inner_meta = _unwrap_annotated(non_none[0])
|
|
51
|
+
return inner, True, meta + inner_meta
|
|
52
|
+
return current, False, meta
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _scalar_type_for_literal(value: Any, field_name: str) -> tuple[FieldType, Any]:
|
|
56
|
+
if isinstance(value, bool):
|
|
57
|
+
return FieldType.BOOLEAN, value
|
|
58
|
+
if isinstance(value, int):
|
|
59
|
+
return FieldType.INTEGER, value
|
|
60
|
+
if isinstance(value, Decimal):
|
|
61
|
+
return FieldType.DECIMAL, value
|
|
62
|
+
if isinstance(value, float):
|
|
63
|
+
try:
|
|
64
|
+
dec = Decimal(str(value))
|
|
65
|
+
except InvalidOperation as exc:
|
|
66
|
+
raise SchemaDefinitionError(
|
|
67
|
+
f"Non-finite float literal in field {field_name!r} is unsupported."
|
|
68
|
+
) from exc
|
|
69
|
+
if dec.is_nan() or dec.is_infinite():
|
|
70
|
+
raise SchemaDefinitionError(
|
|
71
|
+
f"Non-finite float literal in field {field_name!r} is unsupported."
|
|
72
|
+
)
|
|
73
|
+
return FieldType.DECIMAL, dec
|
|
74
|
+
if isinstance(value, str):
|
|
75
|
+
return FieldType.STRING, value
|
|
76
|
+
if isinstance(value, date) and not isinstance(value, datetime):
|
|
77
|
+
return FieldType.DATE, value
|
|
78
|
+
raise SchemaDefinitionError(
|
|
79
|
+
f"Unsupported Literal/Enum member value type {type(value).__name__!r} "
|
|
80
|
+
f"on field {field_name!r}."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _to_decimal_bound(raw: Any, field_name: str, label: str) -> Decimal:
|
|
85
|
+
if isinstance(raw, bool):
|
|
86
|
+
raise SchemaDefinitionError(f"Boolean {label} bound on field {field_name!r} is invalid.")
|
|
87
|
+
if isinstance(raw, (int, Decimal)):
|
|
88
|
+
dec = Decimal(raw) if isinstance(raw, int) else raw
|
|
89
|
+
elif isinstance(raw, float):
|
|
90
|
+
try:
|
|
91
|
+
dec = Decimal(str(raw))
|
|
92
|
+
except InvalidOperation as exc:
|
|
93
|
+
raise SchemaDefinitionError(f"Invalid {label} bound on field {field_name!r}.") from exc
|
|
94
|
+
else:
|
|
95
|
+
raise SchemaDefinitionError(f"Invalid {label} bound on field {field_name!r}.")
|
|
96
|
+
if dec.is_nan() or dec.is_infinite():
|
|
97
|
+
raise SchemaDefinitionError(f"Non-finite {label} bound on field {field_name!r}.")
|
|
98
|
+
return dec
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _extract_constraints(
|
|
102
|
+
*,
|
|
103
|
+
field_name: str,
|
|
104
|
+
field_type: FieldType,
|
|
105
|
+
metadata: Sequence[Any],
|
|
106
|
+
allowed_values: tuple[Any, ...] | None,
|
|
107
|
+
) -> FieldConstraints:
|
|
108
|
+
min_value: int | Decimal | None = None
|
|
109
|
+
max_value: int | Decimal | None = None
|
|
110
|
+
min_length: int | None = None
|
|
111
|
+
max_length: int | None = None
|
|
112
|
+
min_items: int | None = None
|
|
113
|
+
max_items: int | None = None
|
|
114
|
+
pattern: str | None = None
|
|
115
|
+
|
|
116
|
+
def _merge_min(cur: int | Decimal | None, nxt: int | Decimal) -> int | Decimal:
|
|
117
|
+
return nxt if cur is None else max(cur, nxt)
|
|
118
|
+
|
|
119
|
+
def _merge_max(cur: int | Decimal | None, nxt: int | Decimal) -> int | Decimal:
|
|
120
|
+
return nxt if cur is None else min(cur, nxt)
|
|
121
|
+
|
|
122
|
+
for item in metadata:
|
|
123
|
+
if item is None:
|
|
124
|
+
continue
|
|
125
|
+
# Reject unsupported constraints that would otherwise be silently dropped
|
|
126
|
+
if getattr(item, "multiple_of", None) is not None:
|
|
127
|
+
raise SchemaDefinitionError(
|
|
128
|
+
f"Constraint 'multiple_of' on field {field_name!r} is unsupported in "
|
|
129
|
+
"ExtractionSchema."
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
ge = getattr(item, "ge", None)
|
|
133
|
+
if ge is not None:
|
|
134
|
+
if field_type == FieldType.INTEGER:
|
|
135
|
+
if isinstance(ge, bool) or not isinstance(ge, int):
|
|
136
|
+
raise SchemaDefinitionError(
|
|
137
|
+
f"Integer field {field_name!r} requires an integer 'ge' bound."
|
|
138
|
+
)
|
|
139
|
+
min_value = _merge_min(min_value, ge)
|
|
140
|
+
elif field_type == FieldType.DECIMAL:
|
|
141
|
+
min_value = _merge_min(min_value, _to_decimal_bound(ge, field_name, "ge"))
|
|
142
|
+
else:
|
|
143
|
+
raise SchemaDefinitionError(
|
|
144
|
+
f"Numeric 'ge' constraint is incompatible with field {field_name!r} "
|
|
145
|
+
f"({field_type.value})."
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
le = getattr(item, "le", None)
|
|
149
|
+
if le is not None:
|
|
150
|
+
if field_type == FieldType.INTEGER:
|
|
151
|
+
if isinstance(le, bool) or not isinstance(le, int):
|
|
152
|
+
raise SchemaDefinitionError(
|
|
153
|
+
f"Integer field {field_name!r} requires an integer 'le' bound."
|
|
154
|
+
)
|
|
155
|
+
max_value = _merge_max(max_value, le)
|
|
156
|
+
elif field_type == FieldType.DECIMAL:
|
|
157
|
+
max_value = _merge_max(max_value, _to_decimal_bound(le, field_name, "le"))
|
|
158
|
+
else:
|
|
159
|
+
raise SchemaDefinitionError(
|
|
160
|
+
f"Numeric 'le' constraint is incompatible with field {field_name!r} "
|
|
161
|
+
f"({field_type.value})."
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
gt = getattr(item, "gt", None)
|
|
165
|
+
if gt is not None:
|
|
166
|
+
if field_type == FieldType.INTEGER and not isinstance(gt, bool) and isinstance(gt, int):
|
|
167
|
+
min_value = _merge_min(min_value, gt + 1)
|
|
168
|
+
else:
|
|
169
|
+
raise SchemaDefinitionError(
|
|
170
|
+
f"Strict exclusive 'gt' constraint on non-integer field {field_name!r} "
|
|
171
|
+
f"({field_type.value}) cannot be represented losslessly; use 'ge' instead."
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
lt = getattr(item, "lt", None)
|
|
175
|
+
if lt is not None:
|
|
176
|
+
if field_type == FieldType.INTEGER and not isinstance(lt, bool) and isinstance(lt, int):
|
|
177
|
+
max_value = _merge_max(max_value, lt - 1)
|
|
178
|
+
else:
|
|
179
|
+
raise SchemaDefinitionError(
|
|
180
|
+
f"Strict exclusive 'lt' constraint on non-integer field {field_name!r} "
|
|
181
|
+
f"({field_type.value}) cannot be represented losslessly; use 'le' instead."
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
mlen = getattr(item, "min_length", None)
|
|
185
|
+
if mlen is not None:
|
|
186
|
+
if field_type == FieldType.STRING:
|
|
187
|
+
min_length = mlen if min_length is None else max(min_length, mlen)
|
|
188
|
+
elif field_type == FieldType.ARRAY:
|
|
189
|
+
min_items = mlen if min_items is None else max(min_items, mlen)
|
|
190
|
+
else:
|
|
191
|
+
raise SchemaDefinitionError(
|
|
192
|
+
f"'min_length' constraint is incompatible with field {field_name!r} "
|
|
193
|
+
f"({field_type.value})."
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
xlen = getattr(item, "max_length", None)
|
|
197
|
+
if xlen is not None:
|
|
198
|
+
if field_type == FieldType.STRING:
|
|
199
|
+
max_length = xlen if max_length is None else min(max_length, xlen)
|
|
200
|
+
elif field_type == FieldType.ARRAY:
|
|
201
|
+
max_items = xlen if max_items is None else min(max_items, xlen)
|
|
202
|
+
else:
|
|
203
|
+
raise SchemaDefinitionError(
|
|
204
|
+
f"'max_length' constraint is incompatible with field {field_name!r} "
|
|
205
|
+
f"({field_type.value})."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
pat = getattr(item, "pattern", None)
|
|
209
|
+
if pat is not None:
|
|
210
|
+
if field_type != FieldType.STRING:
|
|
211
|
+
raise SchemaDefinitionError(
|
|
212
|
+
f"'pattern' constraint is incompatible with field {field_name!r} "
|
|
213
|
+
f"({field_type.value})."
|
|
214
|
+
)
|
|
215
|
+
if pattern is not None and pattern != pat:
|
|
216
|
+
raise SchemaDefinitionError(
|
|
217
|
+
f"Conflicting 'pattern' constraints defined on field {field_name!r}."
|
|
218
|
+
)
|
|
219
|
+
pattern = pat
|
|
220
|
+
|
|
221
|
+
return FieldConstraints(
|
|
222
|
+
min_value=min_value,
|
|
223
|
+
max_value=max_value,
|
|
224
|
+
min_length=min_length,
|
|
225
|
+
max_length=max_length,
|
|
226
|
+
min_items=min_items,
|
|
227
|
+
max_items=max_items,
|
|
228
|
+
pattern=pattern,
|
|
229
|
+
allowed_values=allowed_values,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _compile_annotation(
|
|
234
|
+
*,
|
|
235
|
+
field_name: str,
|
|
236
|
+
annotation: Any,
|
|
237
|
+
required: bool,
|
|
238
|
+
description: str | None,
|
|
239
|
+
field_metadata: Sequence[Any],
|
|
240
|
+
depth: int,
|
|
241
|
+
max_depth: int,
|
|
242
|
+
active_models: frozenset[type[BaseModel]],
|
|
243
|
+
) -> FieldSpec:
|
|
244
|
+
if depth > max_depth:
|
|
245
|
+
raise SchemaDefinitionError(
|
|
246
|
+
f"Schema nesting depth at {field_name!r} exceeds maximum allowed depth ({max_depth})."
|
|
247
|
+
)
|
|
248
|
+
if annotation is None or annotation is Any:
|
|
249
|
+
raise SchemaDefinitionError(
|
|
250
|
+
f"Unsupported type annotation {annotation!r} on field {field_name!r}."
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
inner, nullable, ann_meta = _unwrap_optional(annotation)
|
|
254
|
+
combined_meta = list(field_metadata) + ann_meta
|
|
255
|
+
|
|
256
|
+
if inner is Any:
|
|
257
|
+
raise SchemaDefinitionError(f"Unsupported 'Any' type annotation on field {field_name!r}.")
|
|
258
|
+
|
|
259
|
+
origin = get_origin(inner)
|
|
260
|
+
|
|
261
|
+
# Literal[...]
|
|
262
|
+
if origin is Literal:
|
|
263
|
+
lit_args = get_args(inner)
|
|
264
|
+
if not lit_args:
|
|
265
|
+
raise SchemaDefinitionError(f"Empty Literal annotation on field {field_name!r}.")
|
|
266
|
+
non_null_vals: list[Any] = []
|
|
267
|
+
for val in lit_args:
|
|
268
|
+
if val is None:
|
|
269
|
+
nullable = True
|
|
270
|
+
else:
|
|
271
|
+
non_null_vals.append(val)
|
|
272
|
+
if not non_null_vals:
|
|
273
|
+
raise SchemaDefinitionError(
|
|
274
|
+
f"Literal[None] alone is not a valid field type on field {field_name!r}."
|
|
275
|
+
)
|
|
276
|
+
inferred_type: FieldType | None = None
|
|
277
|
+
normalized_vals: list[Any] = []
|
|
278
|
+
for val in non_null_vals:
|
|
279
|
+
ft, norm_val = _scalar_type_for_literal(val, field_name)
|
|
280
|
+
if inferred_type is None:
|
|
281
|
+
inferred_type = ft
|
|
282
|
+
elif inferred_type != ft:
|
|
283
|
+
raise SchemaDefinitionError(
|
|
284
|
+
f"Mixed-type Literal on field {field_name!r} is unsupported "
|
|
285
|
+
f"({inferred_type.value} vs {ft.value})."
|
|
286
|
+
)
|
|
287
|
+
normalized_vals.append(norm_val)
|
|
288
|
+
if inferred_type is None:
|
|
289
|
+
raise SchemaDefinitionError(f"Unable to infer Literal type on field {field_name!r}.")
|
|
290
|
+
constraints = _extract_constraints(
|
|
291
|
+
field_name=field_name,
|
|
292
|
+
field_type=inferred_type,
|
|
293
|
+
metadata=combined_meta,
|
|
294
|
+
allowed_values=tuple(normalized_vals),
|
|
295
|
+
)
|
|
296
|
+
return FieldSpec(
|
|
297
|
+
name=field_name,
|
|
298
|
+
field_type=inferred_type,
|
|
299
|
+
required=required,
|
|
300
|
+
nullable=nullable,
|
|
301
|
+
description=description,
|
|
302
|
+
constraints=constraints,
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
# list[T]
|
|
306
|
+
if origin is list:
|
|
307
|
+
args = get_args(inner)
|
|
308
|
+
if len(args) != 1:
|
|
309
|
+
raise SchemaDefinitionError(
|
|
310
|
+
f"Unparameterized or invalid list type on field {field_name!r}; use list[T]."
|
|
311
|
+
)
|
|
312
|
+
item_spec = _compile_annotation(
|
|
313
|
+
field_name=f"{field_name}[]",
|
|
314
|
+
annotation=args[0],
|
|
315
|
+
required=True,
|
|
316
|
+
description=None,
|
|
317
|
+
field_metadata=(),
|
|
318
|
+
depth=depth + 1,
|
|
319
|
+
max_depth=max_depth,
|
|
320
|
+
active_models=active_models,
|
|
321
|
+
)
|
|
322
|
+
constraints = _extract_constraints(
|
|
323
|
+
field_name=field_name,
|
|
324
|
+
field_type=FieldType.ARRAY,
|
|
325
|
+
metadata=combined_meta,
|
|
326
|
+
allowed_values=None,
|
|
327
|
+
)
|
|
328
|
+
return FieldSpec(
|
|
329
|
+
name=field_name,
|
|
330
|
+
field_type=FieldType.ARRAY,
|
|
331
|
+
required=required,
|
|
332
|
+
nullable=nullable,
|
|
333
|
+
description=description,
|
|
334
|
+
constraints=constraints,
|
|
335
|
+
items=item_spec,
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
# Reject other generic containers (dict, set, tuple, etc.)
|
|
339
|
+
if origin is not None:
|
|
340
|
+
raise SchemaDefinitionError(
|
|
341
|
+
f"Unsupported generic container type {annotation!r} on field {field_name!r}."
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
if not isinstance(inner, type):
|
|
345
|
+
raise SchemaDefinitionError(
|
|
346
|
+
f"Unsupported type annotation {annotation!r} on field {field_name!r}."
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
# Nested Pydantic BaseModel
|
|
350
|
+
if issubclass(inner, BaseModel):
|
|
351
|
+
if inner in active_models:
|
|
352
|
+
raise SchemaDefinitionError(
|
|
353
|
+
f"Recursive/cyclic Pydantic model reference detected at field {field_name!r} "
|
|
354
|
+
f"({inner.__name__})."
|
|
355
|
+
)
|
|
356
|
+
nested_fields = _compile_model_fields(
|
|
357
|
+
inner,
|
|
358
|
+
depth=depth + 1,
|
|
359
|
+
max_depth=max_depth,
|
|
360
|
+
active_models=active_models | {inner},
|
|
361
|
+
)
|
|
362
|
+
nested_extra = inner.model_config.get("extra") == "allow"
|
|
363
|
+
constraints = _extract_constraints(
|
|
364
|
+
field_name=field_name,
|
|
365
|
+
field_type=FieldType.OBJECT,
|
|
366
|
+
metadata=combined_meta,
|
|
367
|
+
allowed_values=None,
|
|
368
|
+
)
|
|
369
|
+
return FieldSpec(
|
|
370
|
+
name=field_name,
|
|
371
|
+
field_type=FieldType.OBJECT,
|
|
372
|
+
required=required,
|
|
373
|
+
nullable=nullable,
|
|
374
|
+
description=description,
|
|
375
|
+
constraints=constraints,
|
|
376
|
+
properties=nested_fields,
|
|
377
|
+
allow_additional_fields=nested_extra,
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
# Enum subclass (checked before str/int because StrEnum/IntEnum subclass str/int)
|
|
381
|
+
if issubclass(inner, Enum):
|
|
382
|
+
members = list(inner)
|
|
383
|
+
if not members:
|
|
384
|
+
raise SchemaDefinitionError(
|
|
385
|
+
f"Empty Enum {inner.__name__!r} on field {field_name!r} is unsupported."
|
|
386
|
+
)
|
|
387
|
+
enum_type: FieldType | None = None
|
|
388
|
+
enum_values: list[Any] = []
|
|
389
|
+
for member in members:
|
|
390
|
+
ft, norm_val = _scalar_type_for_literal(member.value, field_name)
|
|
391
|
+
if enum_type is None:
|
|
392
|
+
enum_type = ft
|
|
393
|
+
elif enum_type != ft:
|
|
394
|
+
raise SchemaDefinitionError(
|
|
395
|
+
f"Mixed-type Enum {inner.__name__!r} on field {field_name!r} is unsupported."
|
|
396
|
+
)
|
|
397
|
+
enum_values.append(norm_val)
|
|
398
|
+
if enum_type is None:
|
|
399
|
+
raise SchemaDefinitionError(f"Unable to infer Enum type on field {field_name!r}.")
|
|
400
|
+
constraints = _extract_constraints(
|
|
401
|
+
field_name=field_name,
|
|
402
|
+
field_type=enum_type,
|
|
403
|
+
metadata=combined_meta,
|
|
404
|
+
allowed_values=tuple(enum_values),
|
|
405
|
+
)
|
|
406
|
+
return FieldSpec(
|
|
407
|
+
name=field_name,
|
|
408
|
+
field_type=enum_type,
|
|
409
|
+
required=required,
|
|
410
|
+
nullable=nullable,
|
|
411
|
+
description=description,
|
|
412
|
+
constraints=constraints,
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
# Scalar types (order matters: bool before int; datetime rejected before date)
|
|
416
|
+
if inner is bool:
|
|
417
|
+
scalar_type = FieldType.BOOLEAN
|
|
418
|
+
elif inner is int:
|
|
419
|
+
scalar_type = FieldType.INTEGER
|
|
420
|
+
elif inner is Decimal or inner is float:
|
|
421
|
+
scalar_type = FieldType.DECIMAL
|
|
422
|
+
elif inner is str:
|
|
423
|
+
scalar_type = FieldType.STRING
|
|
424
|
+
elif issubclass(inner, datetime):
|
|
425
|
+
raise SchemaDefinitionError(
|
|
426
|
+
f"Unsupported type 'datetime' on field {field_name!r}: Canonical Output Record "
|
|
427
|
+
"Contract v1.0 supports 'date' only."
|
|
428
|
+
)
|
|
429
|
+
elif inner is date:
|
|
430
|
+
scalar_type = FieldType.DATE
|
|
431
|
+
else:
|
|
432
|
+
raise SchemaDefinitionError(
|
|
433
|
+
f"Unsupported Pydantic field type {inner.__name__!r} on field {field_name!r}."
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
constraints = _extract_constraints(
|
|
437
|
+
field_name=field_name,
|
|
438
|
+
field_type=scalar_type,
|
|
439
|
+
metadata=combined_meta,
|
|
440
|
+
allowed_values=None,
|
|
441
|
+
)
|
|
442
|
+
return FieldSpec(
|
|
443
|
+
name=field_name,
|
|
444
|
+
field_type=scalar_type,
|
|
445
|
+
required=required,
|
|
446
|
+
nullable=nullable,
|
|
447
|
+
description=description,
|
|
448
|
+
constraints=constraints,
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _ensure_model_complete(model_cls: type[BaseModel]) -> None:
|
|
453
|
+
if not getattr(model_cls, "__pydantic_complete__", True):
|
|
454
|
+
try:
|
|
455
|
+
rebuilt = model_cls.model_rebuild()
|
|
456
|
+
except Exception as exc:
|
|
457
|
+
raise SchemaDefinitionError(
|
|
458
|
+
f"Pydantic model {model_cls.__name__!r} has unresolved forward references."
|
|
459
|
+
) from exc
|
|
460
|
+
if rebuilt is False or not getattr(model_cls, "__pydantic_complete__", False):
|
|
461
|
+
raise SchemaDefinitionError(
|
|
462
|
+
f"Pydantic model {model_cls.__name__!r} is incomplete (unresolved forward refs)."
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _compile_model_fields(
|
|
467
|
+
model_cls: type[BaseModel],
|
|
468
|
+
*,
|
|
469
|
+
depth: int,
|
|
470
|
+
max_depth: int,
|
|
471
|
+
active_models: frozenset[type[BaseModel]],
|
|
472
|
+
) -> dict[str, FieldSpec]:
|
|
473
|
+
_ensure_model_complete(model_cls)
|
|
474
|
+
model_fields = model_cls.model_fields
|
|
475
|
+
if not model_fields:
|
|
476
|
+
raise SchemaDefinitionError(
|
|
477
|
+
f"Pydantic model {model_cls.__name__!r} must define at least one field."
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
compiled: dict[str, FieldSpec] = {}
|
|
481
|
+
for field_name, field_info in model_fields.items():
|
|
482
|
+
if field_info.alias is not None and field_info.alias != field_name:
|
|
483
|
+
raise SchemaDefinitionError(
|
|
484
|
+
f"Custom field alias {field_info.alias!r} on field {field_name!r} is unsupported "
|
|
485
|
+
"in ExtractionSchema.from_pydantic."
|
|
486
|
+
)
|
|
487
|
+
if field_info.validation_alias is not None and field_info.validation_alias != field_name:
|
|
488
|
+
raise SchemaDefinitionError(
|
|
489
|
+
f"Custom validation_alias on field {field_name!r} is unsupported in "
|
|
490
|
+
"ExtractionSchema.from_pydantic."
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
compiled[field_name] = _compile_annotation(
|
|
494
|
+
field_name=field_name,
|
|
495
|
+
annotation=field_info.annotation,
|
|
496
|
+
required=field_info.is_required(),
|
|
497
|
+
description=field_info.description,
|
|
498
|
+
field_metadata=field_info.metadata,
|
|
499
|
+
depth=depth,
|
|
500
|
+
max_depth=max_depth,
|
|
501
|
+
active_models=active_models,
|
|
502
|
+
)
|
|
503
|
+
return compiled
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def load_schema_from_pydantic(
|
|
507
|
+
model_cls: type[BaseModel],
|
|
508
|
+
*,
|
|
509
|
+
schema_id: str | None = None,
|
|
510
|
+
schema_version: str = "1.0",
|
|
511
|
+
cardinality: ExtractionCardinality | str = ExtractionCardinality.SINGLE,
|
|
512
|
+
rules: Sequence[ValidationRule] = (),
|
|
513
|
+
allow_additional_fields: bool | None = None,
|
|
514
|
+
max_depth: int = 16,
|
|
515
|
+
) -> ExtractionSchema:
|
|
516
|
+
"""Deterministically derive an immutable ExtractionSchema from a Pydantic v2 BaseModel."""
|
|
517
|
+
if not (isinstance(model_cls, type) and issubclass(model_cls, BaseModel)):
|
|
518
|
+
raise SchemaDefinitionError(
|
|
519
|
+
"ExtractionSchema.from_pydantic requires a Pydantic v2 BaseModel subclass."
|
|
520
|
+
)
|
|
521
|
+
if isinstance(max_depth, bool) or not isinstance(max_depth, int) or max_depth < 1:
|
|
522
|
+
raise SchemaDefinitionError("ExtractionSchema.max_depth must be an integer >= 1.")
|
|
523
|
+
|
|
524
|
+
resolved_schema_id = model_cls.__name__ if schema_id is None else schema_id
|
|
525
|
+
if not isinstance(resolved_schema_id, str) or not resolved_schema_id.strip():
|
|
526
|
+
raise SchemaDefinitionError("ExtractionSchema.schema_id must be a non-empty string.")
|
|
527
|
+
|
|
528
|
+
if isinstance(cardinality, ExtractionCardinality):
|
|
529
|
+
resolved_cardinality = cardinality
|
|
530
|
+
elif isinstance(cardinality, str):
|
|
531
|
+
try:
|
|
532
|
+
resolved_cardinality = ExtractionCardinality(cardinality.strip().lower())
|
|
533
|
+
except ValueError as exc:
|
|
534
|
+
raise SchemaDefinitionError(f"Unsupported cardinality: {cardinality!r}") from exc
|
|
535
|
+
else:
|
|
536
|
+
raise SchemaDefinitionError(f"Unsupported cardinality: {cardinality!r}")
|
|
537
|
+
|
|
538
|
+
if allow_additional_fields is None:
|
|
539
|
+
resolved_extra = model_cls.model_config.get("extra") == "allow"
|
|
540
|
+
elif isinstance(allow_additional_fields, bool):
|
|
541
|
+
resolved_extra = allow_additional_fields
|
|
542
|
+
else:
|
|
543
|
+
raise SchemaDefinitionError("allow_additional_fields must be a boolean or None.")
|
|
544
|
+
|
|
545
|
+
if isinstance(rules, (str, bytes)) or not isinstance(rules, Sequence):
|
|
546
|
+
raise SchemaDefinitionError("rules must be a sequence of ValidationRule instances.")
|
|
547
|
+
|
|
548
|
+
fields = _compile_model_fields(
|
|
549
|
+
model_cls,
|
|
550
|
+
depth=1,
|
|
551
|
+
max_depth=max_depth,
|
|
552
|
+
active_models=frozenset({model_cls}),
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
return ExtractionSchema(
|
|
556
|
+
schema_id=resolved_schema_id.strip(),
|
|
557
|
+
schema_version=schema_version,
|
|
558
|
+
fields=fields,
|
|
559
|
+
cardinality=resolved_cardinality,
|
|
560
|
+
allow_additional_fields=resolved_extra,
|
|
561
|
+
max_depth=max_depth,
|
|
562
|
+
rules=tuple(rules),
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
__all__ = ["load_schema_from_pydantic"]
|