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,269 @@
|
|
|
1
|
+
"""User-defined ExtractionSchema domain models (data-model.md Section 2.4)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from structa_maestro.contracts.enums import ExtractionCardinality, FieldType
|
|
13
|
+
from structa_maestro.exceptions import SchemaDefinitionError
|
|
14
|
+
from structa_maestro.schema.rules import ValidationRule, validate_schema_rules
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from pydantic import BaseModel
|
|
18
|
+
|
|
19
|
+
_NUMERIC_TYPES = frozenset({FieldType.INTEGER, FieldType.DECIMAL})
|
|
20
|
+
_DEFAULT_MAX_DEPTH = 16
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class FieldConstraints:
|
|
25
|
+
"""Optional single-field validation constraints (data-model.md Section 2.4)."""
|
|
26
|
+
|
|
27
|
+
min_value: int | Decimal | None = None
|
|
28
|
+
max_value: int | Decimal | None = None
|
|
29
|
+
min_length: int | None = None
|
|
30
|
+
max_length: int | None = None
|
|
31
|
+
min_items: int | None = None
|
|
32
|
+
max_items: int | None = None
|
|
33
|
+
pattern: str | None = None
|
|
34
|
+
allowed_values: tuple[Any, ...] | None = None
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
if isinstance(self.min_value, bool) or isinstance(self.max_value, bool):
|
|
38
|
+
raise SchemaDefinitionError("min_value/max_value cannot be booleans.")
|
|
39
|
+
if (
|
|
40
|
+
self.min_value is not None
|
|
41
|
+
and self.max_value is not None
|
|
42
|
+
and self.min_value > self.max_value
|
|
43
|
+
):
|
|
44
|
+
raise SchemaDefinitionError(
|
|
45
|
+
f"Conflicting numeric bounds: min_value ({self.min_value}) > "
|
|
46
|
+
f"max_value ({self.max_value})."
|
|
47
|
+
)
|
|
48
|
+
if self.min_length is not None and (
|
|
49
|
+
isinstance(self.min_length, bool) or self.min_length < 0
|
|
50
|
+
):
|
|
51
|
+
raise SchemaDefinitionError("min_length must be an integer >= 0.")
|
|
52
|
+
if self.max_length is not None and (
|
|
53
|
+
isinstance(self.max_length, bool) or self.max_length < 0
|
|
54
|
+
):
|
|
55
|
+
raise SchemaDefinitionError("max_length must be an integer >= 0.")
|
|
56
|
+
if (
|
|
57
|
+
self.min_length is not None
|
|
58
|
+
and self.max_length is not None
|
|
59
|
+
and self.min_length > self.max_length
|
|
60
|
+
):
|
|
61
|
+
raise SchemaDefinitionError(
|
|
62
|
+
f"Conflicting length bounds: min_length ({self.min_length}) > "
|
|
63
|
+
f"max_length ({self.max_length})."
|
|
64
|
+
)
|
|
65
|
+
if self.min_items is not None and (isinstance(self.min_items, bool) or self.min_items < 0):
|
|
66
|
+
raise SchemaDefinitionError("min_items must be an integer >= 0.")
|
|
67
|
+
if self.max_items is not None and (isinstance(self.max_items, bool) or self.max_items < 0):
|
|
68
|
+
raise SchemaDefinitionError("max_items must be an integer >= 0.")
|
|
69
|
+
if (
|
|
70
|
+
self.min_items is not None
|
|
71
|
+
and self.max_items is not None
|
|
72
|
+
and self.min_items > self.max_items
|
|
73
|
+
):
|
|
74
|
+
raise SchemaDefinitionError(
|
|
75
|
+
f"Conflicting array bounds: min_items ({self.min_items}) > "
|
|
76
|
+
f"max_items ({self.max_items})."
|
|
77
|
+
)
|
|
78
|
+
if self.pattern is not None:
|
|
79
|
+
if not isinstance(self.pattern, str):
|
|
80
|
+
raise SchemaDefinitionError("pattern constraint must be a string.")
|
|
81
|
+
try:
|
|
82
|
+
re.compile(self.pattern)
|
|
83
|
+
except re.error as exc:
|
|
84
|
+
raise SchemaDefinitionError(f"Invalid regex pattern constraint: {exc}") from exc
|
|
85
|
+
if self.allowed_values is not None and len(self.allowed_values) == 0:
|
|
86
|
+
raise SchemaDefinitionError("allowed_values cannot be an empty collection.")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True, slots=True)
|
|
90
|
+
class FieldSpec:
|
|
91
|
+
"""Definition of a single target field in an ExtractionSchema (data-model.md Section 2.4)."""
|
|
92
|
+
|
|
93
|
+
name: str
|
|
94
|
+
field_type: FieldType
|
|
95
|
+
required: bool = True
|
|
96
|
+
nullable: bool = False
|
|
97
|
+
description: str | None = None
|
|
98
|
+
constraints: FieldConstraints = field(default_factory=FieldConstraints)
|
|
99
|
+
properties: dict[str, FieldSpec] | None = None
|
|
100
|
+
items: FieldSpec | None = None
|
|
101
|
+
allow_additional_fields: bool = False
|
|
102
|
+
|
|
103
|
+
def __post_init__(self) -> None:
|
|
104
|
+
if not isinstance(self.name, str) or not self.name.strip():
|
|
105
|
+
raise SchemaDefinitionError("FieldSpec.name must be a non-empty string.")
|
|
106
|
+
if not isinstance(self.field_type, FieldType):
|
|
107
|
+
raise SchemaDefinitionError(f"Unsupported field_type: {self.field_type!r}")
|
|
108
|
+
if not isinstance(self.required, bool):
|
|
109
|
+
raise SchemaDefinitionError("FieldSpec.required must be a boolean.")
|
|
110
|
+
if not isinstance(self.nullable, bool):
|
|
111
|
+
raise SchemaDefinitionError("FieldSpec.nullable must be a boolean.")
|
|
112
|
+
if not isinstance(self.allow_additional_fields, bool):
|
|
113
|
+
raise SchemaDefinitionError("FieldSpec.allow_additional_fields must be a boolean.")
|
|
114
|
+
|
|
115
|
+
c = self.constraints
|
|
116
|
+
if (c.min_value is not None or c.max_value is not None) and (
|
|
117
|
+
self.field_type not in _NUMERIC_TYPES
|
|
118
|
+
):
|
|
119
|
+
raise SchemaDefinitionError(
|
|
120
|
+
"Numeric min_value/max_value constraints are incompatible with "
|
|
121
|
+
f"{self.field_type.value!r}."
|
|
122
|
+
)
|
|
123
|
+
if (c.min_length is not None or c.max_length is not None or c.pattern is not None) and (
|
|
124
|
+
self.field_type != FieldType.STRING
|
|
125
|
+
):
|
|
126
|
+
raise SchemaDefinitionError(
|
|
127
|
+
f"String constraints are incompatible with field type {self.field_type.value!r}."
|
|
128
|
+
)
|
|
129
|
+
if (c.min_items is not None or c.max_items is not None) and (
|
|
130
|
+
self.field_type != FieldType.ARRAY
|
|
131
|
+
):
|
|
132
|
+
raise SchemaDefinitionError(
|
|
133
|
+
f"Array item count constraints are incompatible with {self.field_type.value!r}."
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
if self.field_type == FieldType.OBJECT:
|
|
137
|
+
if not self.properties:
|
|
138
|
+
raise SchemaDefinitionError(
|
|
139
|
+
f"Object field {self.name!r} must define non-empty properties."
|
|
140
|
+
)
|
|
141
|
+
for prop_key, prop_spec in self.properties.items():
|
|
142
|
+
if prop_spec.name != prop_key:
|
|
143
|
+
raise SchemaDefinitionError(
|
|
144
|
+
f"Property key {prop_key!r} does not match "
|
|
145
|
+
f"FieldSpec.name {prop_spec.name!r}."
|
|
146
|
+
)
|
|
147
|
+
elif self.properties is not None:
|
|
148
|
+
raise SchemaDefinitionError(
|
|
149
|
+
f"Non-object field {self.name!r} cannot define nested properties."
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
if self.field_type == FieldType.ARRAY:
|
|
153
|
+
if self.items is None:
|
|
154
|
+
raise SchemaDefinitionError(f"Array field {self.name!r} must define items.")
|
|
155
|
+
elif self.items is not None:
|
|
156
|
+
raise SchemaDefinitionError(f"Non-array field {self.name!r} cannot define items.")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True, slots=True)
|
|
160
|
+
class ExtractionSchema:
|
|
161
|
+
"""User-defined structured extraction schema (data-model.md Section 2.4)."""
|
|
162
|
+
|
|
163
|
+
schema_id: str
|
|
164
|
+
schema_version: str
|
|
165
|
+
fields: dict[str, FieldSpec]
|
|
166
|
+
cardinality: ExtractionCardinality = ExtractionCardinality.SINGLE
|
|
167
|
+
allow_additional_fields: bool = False
|
|
168
|
+
max_depth: int = _DEFAULT_MAX_DEPTH
|
|
169
|
+
rules: tuple[ValidationRule, ...] = ()
|
|
170
|
+
|
|
171
|
+
def __post_init__(self) -> None:
|
|
172
|
+
if not isinstance(self.schema_id, str) or not self.schema_id.strip():
|
|
173
|
+
raise SchemaDefinitionError("ExtractionSchema.schema_id must be a non-empty string.")
|
|
174
|
+
if not isinstance(self.schema_version, str) or not self.schema_version.strip():
|
|
175
|
+
raise SchemaDefinitionError(
|
|
176
|
+
"ExtractionSchema.schema_version must be a non-empty string."
|
|
177
|
+
)
|
|
178
|
+
if not isinstance(self.cardinality, ExtractionCardinality):
|
|
179
|
+
raise SchemaDefinitionError(f"Unsupported cardinality: {self.cardinality!r}")
|
|
180
|
+
if not isinstance(self.allow_additional_fields, bool):
|
|
181
|
+
raise SchemaDefinitionError("ExtractionSchema.allow_additional_fields must be boolean.")
|
|
182
|
+
if isinstance(self.max_depth, bool) or self.max_depth < 1:
|
|
183
|
+
raise SchemaDefinitionError("ExtractionSchema.max_depth must be an integer >= 1.")
|
|
184
|
+
if not self.fields:
|
|
185
|
+
raise SchemaDefinitionError("ExtractionSchema.fields must define at least one field.")
|
|
186
|
+
|
|
187
|
+
for key, spec in self.fields.items():
|
|
188
|
+
if spec.name != key:
|
|
189
|
+
raise SchemaDefinitionError(
|
|
190
|
+
f"Schema field key {key!r} does not match FieldSpec.name {spec.name!r}."
|
|
191
|
+
)
|
|
192
|
+
_validate_depth(spec, depth=1, max_depth=self.max_depth, seen_ids=set())
|
|
193
|
+
|
|
194
|
+
validate_schema_rules(self.fields, self.rules)
|
|
195
|
+
|
|
196
|
+
@classmethod
|
|
197
|
+
def from_dict(cls, data: Mapping[str, Any]) -> ExtractionSchema:
|
|
198
|
+
"""Parse and validate a declarative dict or JSON Schema subset into ExtractionSchema."""
|
|
199
|
+
from structa_maestro.schema.loader import load_schema_from_dict
|
|
200
|
+
|
|
201
|
+
return load_schema_from_dict(data)
|
|
202
|
+
|
|
203
|
+
@classmethod
|
|
204
|
+
def from_json_file(cls, path: str | Path) -> ExtractionSchema:
|
|
205
|
+
"""Load and validate an ExtractionSchema from a JSON file."""
|
|
206
|
+
from structa_maestro.schema.loader import load_schema_from_json_file
|
|
207
|
+
|
|
208
|
+
return load_schema_from_json_file(path)
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def from_pydantic(
|
|
212
|
+
cls,
|
|
213
|
+
model_cls: type[BaseModel],
|
|
214
|
+
*,
|
|
215
|
+
schema_id: str | None = None,
|
|
216
|
+
schema_version: str = "1.0",
|
|
217
|
+
cardinality: ExtractionCardinality | str = ExtractionCardinality.SINGLE,
|
|
218
|
+
rules: Sequence[ValidationRule] = (),
|
|
219
|
+
allow_additional_fields: bool | None = None,
|
|
220
|
+
max_depth: int = _DEFAULT_MAX_DEPTH,
|
|
221
|
+
) -> ExtractionSchema:
|
|
222
|
+
"""Deterministically derive an ExtractionSchema from a Pydantic v2 BaseModel subclass."""
|
|
223
|
+
from structa_maestro.schema.pydantic_adapter import load_schema_from_pydantic
|
|
224
|
+
|
|
225
|
+
return load_schema_from_pydantic(
|
|
226
|
+
model_cls,
|
|
227
|
+
schema_id=schema_id,
|
|
228
|
+
schema_version=schema_version,
|
|
229
|
+
cardinality=cardinality,
|
|
230
|
+
rules=rules,
|
|
231
|
+
allow_additional_fields=allow_additional_fields,
|
|
232
|
+
max_depth=max_depth,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
def to_dict(self) -> dict[str, Any]:
|
|
236
|
+
"""Serialize this schema into a JSON-safe declarative dictionary."""
|
|
237
|
+
from structa_maestro.schema.serializer import serialize_schema_to_dict
|
|
238
|
+
|
|
239
|
+
return serialize_schema_to_dict(self)
|
|
240
|
+
|
|
241
|
+
def to_json(self, *, indent: int | None = None) -> str:
|
|
242
|
+
"""Serialize this schema into a declarative JSON string (compatible with CLI --schema)."""
|
|
243
|
+
from structa_maestro.schema.serializer import serialize_schema_to_json
|
|
244
|
+
|
|
245
|
+
return serialize_schema_to_json(self, indent=indent)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _validate_depth(
|
|
249
|
+
spec: FieldSpec,
|
|
250
|
+
*,
|
|
251
|
+
depth: int,
|
|
252
|
+
max_depth: int,
|
|
253
|
+
seen_ids: set[int],
|
|
254
|
+
) -> None:
|
|
255
|
+
obj_id = id(spec)
|
|
256
|
+
if obj_id in seen_ids:
|
|
257
|
+
raise SchemaDefinitionError(
|
|
258
|
+
f"Recursive/cyclic schema definition detected at {spec.name!r}."
|
|
259
|
+
)
|
|
260
|
+
if depth > max_depth:
|
|
261
|
+
raise SchemaDefinitionError(
|
|
262
|
+
f"Schema nesting depth at {spec.name!r} exceeds maximum allowed depth ({max_depth})."
|
|
263
|
+
)
|
|
264
|
+
next_seen = seen_ids | {obj_id}
|
|
265
|
+
if spec.properties:
|
|
266
|
+
for child in spec.properties.values():
|
|
267
|
+
_validate_depth(child, depth=depth + 1, max_depth=max_depth, seen_ids=next_seen)
|
|
268
|
+
if spec.items is not None:
|
|
269
|
+
_validate_depth(spec.items, depth=depth + 1, max_depth=max_depth, seen_ids=next_seen)
|