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,19 @@
|
|
|
1
|
+
"""Schema definition models, declarative/Pydantic loaders, and JSON serializers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from structa_maestro.schema.loader import load_schema_from_dict, load_schema_from_json_file
|
|
6
|
+
from structa_maestro.schema.models import ExtractionSchema, FieldConstraints, FieldSpec
|
|
7
|
+
from structa_maestro.schema.pydantic_adapter import load_schema_from_pydantic
|
|
8
|
+
from structa_maestro.schema.serializer import serialize_schema_to_dict, serialize_schema_to_json
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"ExtractionSchema",
|
|
12
|
+
"FieldConstraints",
|
|
13
|
+
"FieldSpec",
|
|
14
|
+
"load_schema_from_dict",
|
|
15
|
+
"load_schema_from_json_file",
|
|
16
|
+
"load_schema_from_pydantic",
|
|
17
|
+
"serialize_schema_to_dict",
|
|
18
|
+
"serialize_schema_to_json",
|
|
19
|
+
]
|
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
"""Declarative dict and JSON Schema loader raising SchemaDefinitionError on invalid input."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from datetime import date
|
|
8
|
+
from decimal import Decimal, InvalidOperation
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from structa_maestro.contracts.enums import ExtractionCardinality, FieldType
|
|
13
|
+
from structa_maestro.exceptions import SchemaDefinitionError
|
|
14
|
+
from structa_maestro.schema.models import ExtractionSchema, FieldConstraints, FieldSpec
|
|
15
|
+
from structa_maestro.schema.rules import (
|
|
16
|
+
ArithmeticRule,
|
|
17
|
+
ArithmeticTerm,
|
|
18
|
+
ComparisonRule,
|
|
19
|
+
ConditionalPresenceKind,
|
|
20
|
+
ConditionalPresenceRule,
|
|
21
|
+
FieldCondition,
|
|
22
|
+
GroupPresenceKind,
|
|
23
|
+
GroupPresenceRule,
|
|
24
|
+
RuleSeverity,
|
|
25
|
+
ValidationRule,
|
|
26
|
+
resolve_schema_field_spec,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
_MAX_SCHEMA_JSON_BYTES = 2 * 1024 * 1024 # 2 MB safety limit for schema files
|
|
30
|
+
|
|
31
|
+
_TYPE_ALIASES: dict[str, FieldType] = {
|
|
32
|
+
"string": FieldType.STRING,
|
|
33
|
+
"str": FieldType.STRING,
|
|
34
|
+
"integer": FieldType.INTEGER,
|
|
35
|
+
"int": FieldType.INTEGER,
|
|
36
|
+
"decimal": FieldType.DECIMAL,
|
|
37
|
+
"number": FieldType.DECIMAL,
|
|
38
|
+
"boolean": FieldType.BOOLEAN,
|
|
39
|
+
"bool": FieldType.BOOLEAN,
|
|
40
|
+
"date": FieldType.DATE,
|
|
41
|
+
"array": FieldType.ARRAY,
|
|
42
|
+
"object": FieldType.OBJECT,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
_ALLOWED_TOP_LEVEL_KEYS = frozenset(
|
|
46
|
+
{
|
|
47
|
+
"schema_id",
|
|
48
|
+
"schema_version",
|
|
49
|
+
"cardinality",
|
|
50
|
+
"fields",
|
|
51
|
+
"properties",
|
|
52
|
+
"required",
|
|
53
|
+
"allow_additional_fields",
|
|
54
|
+
"additionalProperties",
|
|
55
|
+
"max_depth",
|
|
56
|
+
"title",
|
|
57
|
+
"type",
|
|
58
|
+
"$schema",
|
|
59
|
+
"$id",
|
|
60
|
+
"description",
|
|
61
|
+
"rules",
|
|
62
|
+
}
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
_ALLOWED_COMPARISON_KEYS = frozenset(
|
|
66
|
+
{"rule_id", "kind", "left_field", "operator", "right_field", "severity", "message"}
|
|
67
|
+
)
|
|
68
|
+
_ALLOWED_ARITHMETIC_KEYS = frozenset(
|
|
69
|
+
{"rule_id", "kind", "terms", "target_field", "tolerance", "severity", "message"}
|
|
70
|
+
)
|
|
71
|
+
_ALLOWED_TERM_KEYS = frozenset({"field", "sign", "item_field", "treat_missing_as_zero"})
|
|
72
|
+
_ALLOWED_CONDITIONAL_KEYS = frozenset(
|
|
73
|
+
{"rule_id", "kind", "when", "target_fields", "severity", "message"}
|
|
74
|
+
)
|
|
75
|
+
_ALLOWED_CONDITION_KEYS = frozenset({"field", "operator", "value", "values"})
|
|
76
|
+
_ALLOWED_GROUP_KEYS = frozenset({"rule_id", "kind", "fields", "severity", "message"})
|
|
77
|
+
|
|
78
|
+
_ALLOWED_FIELD_KEYS = frozenset(
|
|
79
|
+
{
|
|
80
|
+
"type",
|
|
81
|
+
"format",
|
|
82
|
+
"required",
|
|
83
|
+
"nullable",
|
|
84
|
+
"description",
|
|
85
|
+
"min_value",
|
|
86
|
+
"max_value",
|
|
87
|
+
"minimum",
|
|
88
|
+
"maximum",
|
|
89
|
+
"min_length",
|
|
90
|
+
"max_length",
|
|
91
|
+
"minLength",
|
|
92
|
+
"maxLength",
|
|
93
|
+
"min_items",
|
|
94
|
+
"max_items",
|
|
95
|
+
"minItems",
|
|
96
|
+
"maxItems",
|
|
97
|
+
"pattern",
|
|
98
|
+
"allowed_values",
|
|
99
|
+
"enum",
|
|
100
|
+
"properties",
|
|
101
|
+
"items",
|
|
102
|
+
"allow_additional_fields",
|
|
103
|
+
"additionalProperties",
|
|
104
|
+
"default",
|
|
105
|
+
"$ref",
|
|
106
|
+
}
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _reject_duplicate_json_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
111
|
+
obj: dict[str, Any] = {}
|
|
112
|
+
for key, val in pairs:
|
|
113
|
+
if key in obj:
|
|
114
|
+
raise SchemaDefinitionError(f"Duplicate key detected in schema definition: {key!r}")
|
|
115
|
+
obj[key] = val
|
|
116
|
+
return obj
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _coerce_numeric_bound(raw: Any, field_type: FieldType, bound_name: str) -> int | Decimal:
|
|
120
|
+
if isinstance(raw, bool):
|
|
121
|
+
raise SchemaDefinitionError(f"{bound_name} cannot be a boolean.")
|
|
122
|
+
if field_type == FieldType.INTEGER:
|
|
123
|
+
if isinstance(raw, int):
|
|
124
|
+
return raw
|
|
125
|
+
raise SchemaDefinitionError(f"{bound_name} for integer field must be an int.")
|
|
126
|
+
if isinstance(raw, (int, Decimal)):
|
|
127
|
+
return raw
|
|
128
|
+
if isinstance(raw, (float, str)):
|
|
129
|
+
try:
|
|
130
|
+
return Decimal(str(raw))
|
|
131
|
+
except InvalidOperation as exc:
|
|
132
|
+
raise SchemaDefinitionError(f"Invalid numeric {bound_name}: {raw!r}") from exc
|
|
133
|
+
raise SchemaDefinitionError(f"Invalid numeric {bound_name}: {raw!r}")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _parse_field_type(raw_field: Mapping[str, Any], field_name: str) -> tuple[FieldType, bool]:
|
|
137
|
+
raw_type = raw_field.get("type")
|
|
138
|
+
inferred_nullable = False
|
|
139
|
+
|
|
140
|
+
if isinstance(raw_type, list):
|
|
141
|
+
non_null = [t for t in raw_type if t != "null"]
|
|
142
|
+
inferred_nullable = "null" in raw_type
|
|
143
|
+
if len(non_null) != 1 or not isinstance(non_null[0], str):
|
|
144
|
+
raise SchemaDefinitionError(
|
|
145
|
+
f"Field {field_name!r} has unsupported union type: {raw_type!r}"
|
|
146
|
+
)
|
|
147
|
+
raw_type = non_null[0]
|
|
148
|
+
|
|
149
|
+
if not isinstance(raw_type, str):
|
|
150
|
+
raise SchemaDefinitionError(f"Field {field_name!r} must declare a valid string 'type'.")
|
|
151
|
+
|
|
152
|
+
fmt = raw_field.get("format")
|
|
153
|
+
if raw_type == "string" and fmt == "date":
|
|
154
|
+
return FieldType.DATE, inferred_nullable
|
|
155
|
+
|
|
156
|
+
mapped = _TYPE_ALIASES.get(raw_type.lower())
|
|
157
|
+
if mapped is None:
|
|
158
|
+
raise SchemaDefinitionError(
|
|
159
|
+
f"Unsupported schema type {raw_type!r} for field {field_name!r}."
|
|
160
|
+
)
|
|
161
|
+
return mapped, inferred_nullable
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _parse_field_spec(
|
|
165
|
+
name: str,
|
|
166
|
+
raw: Any,
|
|
167
|
+
*,
|
|
168
|
+
required_override: bool | None = None,
|
|
169
|
+
depth: int,
|
|
170
|
+
max_depth: int,
|
|
171
|
+
) -> FieldSpec:
|
|
172
|
+
if depth > max_depth:
|
|
173
|
+
raise SchemaDefinitionError(
|
|
174
|
+
f"Schema nesting depth at {name!r} exceeds maximum allowed depth ({max_depth})."
|
|
175
|
+
)
|
|
176
|
+
if not isinstance(raw, Mapping):
|
|
177
|
+
raise SchemaDefinitionError(f"Field definition for {name!r} must be an object/mapping.")
|
|
178
|
+
|
|
179
|
+
if "$ref" in raw:
|
|
180
|
+
raise SchemaDefinitionError(
|
|
181
|
+
f"Recursive or external '$ref' schema definitions are unsupported (field {name!r})."
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
unknown_keys = set(raw.keys()) - _ALLOWED_FIELD_KEYS
|
|
185
|
+
if unknown_keys:
|
|
186
|
+
raise SchemaDefinitionError(
|
|
187
|
+
f"Unknown schema attributes on field {name!r}: {', '.join(sorted(unknown_keys))}"
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
field_type, inferred_nullable = _parse_field_type(raw, name)
|
|
191
|
+
|
|
192
|
+
raw_required = raw.get("required")
|
|
193
|
+
if field_type == FieldType.OBJECT and isinstance(raw_required, list):
|
|
194
|
+
nested_required_names = set(raw_required)
|
|
195
|
+
is_required = True if required_override is None else required_override
|
|
196
|
+
else:
|
|
197
|
+
nested_required_names = None
|
|
198
|
+
if raw_required is None:
|
|
199
|
+
is_required = True if required_override is None else required_override
|
|
200
|
+
elif isinstance(raw_required, bool):
|
|
201
|
+
is_required = raw_required
|
|
202
|
+
else:
|
|
203
|
+
raise SchemaDefinitionError(f"Field {name!r} 'required' attribute must be a boolean.")
|
|
204
|
+
|
|
205
|
+
raw_nullable = raw.get("nullable")
|
|
206
|
+
if raw_nullable is None:
|
|
207
|
+
nullable = inferred_nullable
|
|
208
|
+
elif isinstance(raw_nullable, bool):
|
|
209
|
+
nullable = raw_nullable or inferred_nullable
|
|
210
|
+
else:
|
|
211
|
+
raise SchemaDefinitionError(f"Field {name!r} 'nullable' attribute must be a boolean.")
|
|
212
|
+
|
|
213
|
+
description = raw.get("description")
|
|
214
|
+
if description is not None and not isinstance(description, str):
|
|
215
|
+
raise SchemaDefinitionError(f"Field {name!r} 'description' must be a string.")
|
|
216
|
+
|
|
217
|
+
# Constraints
|
|
218
|
+
raw_min_val = raw.get("min_value", raw.get("minimum"))
|
|
219
|
+
raw_max_val = raw.get("max_value", raw.get("maximum"))
|
|
220
|
+
min_value = (
|
|
221
|
+
_coerce_numeric_bound(raw_min_val, field_type, "min_value")
|
|
222
|
+
if raw_min_val is not None
|
|
223
|
+
else None
|
|
224
|
+
)
|
|
225
|
+
max_value = (
|
|
226
|
+
_coerce_numeric_bound(raw_max_val, field_type, "max_value")
|
|
227
|
+
if raw_max_val is not None
|
|
228
|
+
else None
|
|
229
|
+
)
|
|
230
|
+
min_length = raw.get("min_length", raw.get("minLength"))
|
|
231
|
+
max_length = raw.get("max_length", raw.get("maxLength"))
|
|
232
|
+
min_items = raw.get("min_items", raw.get("minItems"))
|
|
233
|
+
max_items = raw.get("max_items", raw.get("maxItems"))
|
|
234
|
+
pattern = raw.get("pattern")
|
|
235
|
+
raw_allowed = raw.get("allowed_values", raw.get("enum"))
|
|
236
|
+
allowed_values: tuple[Any, ...] | None = None
|
|
237
|
+
if raw_allowed is not None:
|
|
238
|
+
if not isinstance(raw_allowed, (list, tuple)):
|
|
239
|
+
raise SchemaDefinitionError(
|
|
240
|
+
f"Field {name!r} 'allowed_values'/'enum' must be a list or tuple."
|
|
241
|
+
)
|
|
242
|
+
if field_type in (FieldType.DECIMAL, FieldType.DATE):
|
|
243
|
+
allowed_values = tuple(_coerce_condition_literal(v, field_type) for v in raw_allowed)
|
|
244
|
+
else:
|
|
245
|
+
allowed_values = tuple(raw_allowed)
|
|
246
|
+
|
|
247
|
+
constraints = FieldConstraints(
|
|
248
|
+
min_value=min_value,
|
|
249
|
+
max_value=max_value,
|
|
250
|
+
min_length=min_length,
|
|
251
|
+
max_length=max_length,
|
|
252
|
+
min_items=min_items,
|
|
253
|
+
max_items=max_items,
|
|
254
|
+
pattern=pattern,
|
|
255
|
+
allowed_values=allowed_values,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
# Nested properties (for object)
|
|
259
|
+
parsed_properties: dict[str, FieldSpec] | None = None
|
|
260
|
+
if "properties" in raw and raw["properties"] is not None:
|
|
261
|
+
raw_props = raw["properties"]
|
|
262
|
+
if not isinstance(raw_props, Mapping) or not raw_props:
|
|
263
|
+
raise SchemaDefinitionError(
|
|
264
|
+
f"Object field {name!r} must define a non-empty 'properties' mapping."
|
|
265
|
+
)
|
|
266
|
+
parsed_properties = {}
|
|
267
|
+
for prop_name, prop_def in raw_props.items():
|
|
268
|
+
req_override = (
|
|
269
|
+
prop_name in nested_required_names if nested_required_names is not None else None
|
|
270
|
+
)
|
|
271
|
+
parsed_properties[prop_name] = _parse_field_spec(
|
|
272
|
+
prop_name,
|
|
273
|
+
prop_def,
|
|
274
|
+
required_override=req_override,
|
|
275
|
+
depth=depth + 1,
|
|
276
|
+
max_depth=max_depth,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
# Array items
|
|
280
|
+
parsed_items: FieldSpec | None = None
|
|
281
|
+
if "items" in raw and raw["items"] is not None:
|
|
282
|
+
parsed_items = _parse_field_spec(
|
|
283
|
+
f"{name}[]",
|
|
284
|
+
raw["items"],
|
|
285
|
+
required_override=True,
|
|
286
|
+
depth=depth + 1,
|
|
287
|
+
max_depth=max_depth,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
raw_addl = raw.get("allow_additional_fields", raw.get("additionalProperties", False))
|
|
291
|
+
if not isinstance(raw_addl, bool):
|
|
292
|
+
raise SchemaDefinitionError(
|
|
293
|
+
f"Field {name!r} 'allow_additional_fields'/'additionalProperties' must be a boolean."
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
return FieldSpec(
|
|
297
|
+
name=name,
|
|
298
|
+
field_type=field_type,
|
|
299
|
+
required=is_required,
|
|
300
|
+
nullable=nullable,
|
|
301
|
+
description=description,
|
|
302
|
+
constraints=constraints,
|
|
303
|
+
properties=parsed_properties,
|
|
304
|
+
items=parsed_items,
|
|
305
|
+
allow_additional_fields=raw_addl,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def load_schema_from_dict(data: Mapping[str, Any]) -> ExtractionSchema:
|
|
310
|
+
"""Parse and validate a declarative dict or JSON Schema subset into ExtractionSchema."""
|
|
311
|
+
if not isinstance(data, Mapping) or not data:
|
|
312
|
+
raise SchemaDefinitionError("Schema definition must be a non-empty mapping.")
|
|
313
|
+
|
|
314
|
+
unknown_top = set(data.keys()) - _ALLOWED_TOP_LEVEL_KEYS
|
|
315
|
+
if unknown_top:
|
|
316
|
+
raise SchemaDefinitionError(
|
|
317
|
+
f"Unknown top-level schema attributes: {', '.join(sorted(unknown_top))}"
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
schema_id = data.get("schema_id") or data.get("title") or data.get("$id")
|
|
321
|
+
if not isinstance(schema_id, str) or not schema_id.strip():
|
|
322
|
+
raise SchemaDefinitionError("Schema must specify a non-empty 'schema_id' (or 'title').")
|
|
323
|
+
|
|
324
|
+
schema_version = data.get("schema_version", "1.0")
|
|
325
|
+
if not isinstance(schema_version, str) or not schema_version.strip():
|
|
326
|
+
raise SchemaDefinitionError("Schema 'schema_version' must be a non-empty string.")
|
|
327
|
+
|
|
328
|
+
raw_card = data.get("cardinality", ExtractionCardinality.SINGLE.value)
|
|
329
|
+
try:
|
|
330
|
+
cardinality = ExtractionCardinality(raw_card)
|
|
331
|
+
except ValueError as exc:
|
|
332
|
+
raise SchemaDefinitionError(
|
|
333
|
+
f"Unsupported schema cardinality {raw_card!r}; expected 'single' or 'multiple'."
|
|
334
|
+
) from exc
|
|
335
|
+
|
|
336
|
+
raw_max_depth = data.get("max_depth", 16)
|
|
337
|
+
if isinstance(raw_max_depth, bool) or not isinstance(raw_max_depth, int) or raw_max_depth < 1:
|
|
338
|
+
raise SchemaDefinitionError("Schema 'max_depth' must be an integer >= 1.")
|
|
339
|
+
|
|
340
|
+
raw_addl = data.get("allow_additional_fields", data.get("additionalProperties", False))
|
|
341
|
+
if not isinstance(raw_addl, bool):
|
|
342
|
+
raise SchemaDefinitionError(
|
|
343
|
+
"Schema 'allow_additional_fields'/'additionalProperties' must be a boolean."
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
raw_fields = data.get("fields") if "fields" in data else data.get("properties")
|
|
347
|
+
if not isinstance(raw_fields, Mapping) or not raw_fields:
|
|
348
|
+
raise SchemaDefinitionError(
|
|
349
|
+
"Schema must define a non-empty 'fields' (or 'properties') mapping."
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
top_required = data.get("required")
|
|
353
|
+
top_required_set: set[str] | None = None
|
|
354
|
+
if top_required is not None:
|
|
355
|
+
if not isinstance(top_required, list) or not all(isinstance(x, str) for x in top_required):
|
|
356
|
+
raise SchemaDefinitionError("Top-level 'required' must be a list of field names.")
|
|
357
|
+
top_required_set = set(top_required)
|
|
358
|
+
|
|
359
|
+
parsed_fields: dict[str, FieldSpec] = {}
|
|
360
|
+
for fname, fdef in raw_fields.items():
|
|
361
|
+
if not isinstance(fname, str) or not fname.strip():
|
|
362
|
+
raise SchemaDefinitionError("Schema field names must be non-empty strings.")
|
|
363
|
+
req_override = fname in top_required_set if top_required_set is not None else None
|
|
364
|
+
parsed_fields[fname] = _parse_field_spec(
|
|
365
|
+
fname,
|
|
366
|
+
fdef,
|
|
367
|
+
required_override=req_override,
|
|
368
|
+
depth=1,
|
|
369
|
+
max_depth=raw_max_depth,
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
parsed_rules = _parse_rules(data.get("rules"), parsed_fields)
|
|
373
|
+
|
|
374
|
+
return ExtractionSchema(
|
|
375
|
+
schema_id=schema_id.strip(),
|
|
376
|
+
schema_version=schema_version.strip(),
|
|
377
|
+
fields=parsed_fields,
|
|
378
|
+
cardinality=cardinality,
|
|
379
|
+
allow_additional_fields=raw_addl,
|
|
380
|
+
max_depth=raw_max_depth,
|
|
381
|
+
rules=parsed_rules,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _coerce_condition_literal(raw: Any, field_type: FieldType) -> Any:
|
|
386
|
+
if raw is None:
|
|
387
|
+
return None
|
|
388
|
+
if field_type == FieldType.DATE and isinstance(raw, str):
|
|
389
|
+
try:
|
|
390
|
+
return date.fromisoformat(raw.strip())
|
|
391
|
+
except ValueError as exc:
|
|
392
|
+
raise SchemaDefinitionError(
|
|
393
|
+
f"Invalid ISO date literal in rule condition: {raw!r}"
|
|
394
|
+
) from exc
|
|
395
|
+
if field_type == FieldType.DECIMAL and not isinstance(raw, bool):
|
|
396
|
+
if isinstance(raw, Decimal):
|
|
397
|
+
return raw
|
|
398
|
+
if isinstance(raw, (int, float, str)):
|
|
399
|
+
try:
|
|
400
|
+
return Decimal(str(raw).strip())
|
|
401
|
+
except InvalidOperation as exc:
|
|
402
|
+
raise SchemaDefinitionError(
|
|
403
|
+
f"Invalid decimal literal in rule condition: {raw!r}"
|
|
404
|
+
) from exc
|
|
405
|
+
return raw
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _parse_rules(
|
|
409
|
+
raw_rules: Any,
|
|
410
|
+
parsed_fields: Mapping[str, FieldSpec],
|
|
411
|
+
) -> tuple[ValidationRule, ...]:
|
|
412
|
+
if raw_rules is None:
|
|
413
|
+
return ()
|
|
414
|
+
if not isinstance(raw_rules, list):
|
|
415
|
+
raise SchemaDefinitionError("Schema 'rules' attribute must be a list of rule objects.")
|
|
416
|
+
|
|
417
|
+
rules: list[ValidationRule] = []
|
|
418
|
+
for idx, raw_rule in enumerate(raw_rules):
|
|
419
|
+
if not isinstance(raw_rule, Mapping):
|
|
420
|
+
raise SchemaDefinitionError(f"Rule at index {idx} must be a mapping/object.")
|
|
421
|
+
raw_kind = raw_rule.get("kind")
|
|
422
|
+
if not isinstance(raw_kind, str) or not raw_kind.strip():
|
|
423
|
+
raise SchemaDefinitionError(f"Rule at index {idx} must specify a string 'kind'.")
|
|
424
|
+
kind = raw_kind.strip().lower()
|
|
425
|
+
severity = raw_rule.get("severity", RuleSeverity.ERROR)
|
|
426
|
+
message = raw_rule.get("message")
|
|
427
|
+
rule_id = raw_rule.get("rule_id")
|
|
428
|
+
if not isinstance(rule_id, str):
|
|
429
|
+
raise SchemaDefinitionError(f"Rule at index {idx} must specify a string 'rule_id'.")
|
|
430
|
+
|
|
431
|
+
if kind == "comparison":
|
|
432
|
+
unknown = set(raw_rule.keys()) - _ALLOWED_COMPARISON_KEYS
|
|
433
|
+
if unknown:
|
|
434
|
+
raise SchemaDefinitionError(
|
|
435
|
+
f"Unknown attributes on comparison rule {rule_id!r}: "
|
|
436
|
+
f"{', '.join(sorted(unknown))}"
|
|
437
|
+
)
|
|
438
|
+
rules.append(
|
|
439
|
+
ComparisonRule(
|
|
440
|
+
rule_id=rule_id,
|
|
441
|
+
left_field=raw_rule.get("left_field", ""),
|
|
442
|
+
operator=raw_rule.get("operator", ""),
|
|
443
|
+
right_field=raw_rule.get("right_field", ""),
|
|
444
|
+
severity=severity,
|
|
445
|
+
message=message,
|
|
446
|
+
)
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
elif kind == "arithmetic":
|
|
450
|
+
unknown = set(raw_rule.keys()) - _ALLOWED_ARITHMETIC_KEYS
|
|
451
|
+
if unknown:
|
|
452
|
+
raise SchemaDefinitionError(
|
|
453
|
+
f"Unknown attributes on arithmetic rule {rule_id!r}: "
|
|
454
|
+
f"{', '.join(sorted(unknown))}"
|
|
455
|
+
)
|
|
456
|
+
raw_terms = raw_rule.get("terms")
|
|
457
|
+
if not isinstance(raw_terms, list) or not raw_terms:
|
|
458
|
+
raise SchemaDefinitionError(
|
|
459
|
+
f"Arithmetic rule {rule_id!r} must define a non-empty 'terms' list."
|
|
460
|
+
)
|
|
461
|
+
parsed_terms: list[ArithmeticTerm] = []
|
|
462
|
+
for t_idx, raw_term in enumerate(raw_terms):
|
|
463
|
+
if not isinstance(raw_term, Mapping):
|
|
464
|
+
raise SchemaDefinitionError(
|
|
465
|
+
f"Arithmetic rule {rule_id!r} term #{t_idx} must be an object."
|
|
466
|
+
)
|
|
467
|
+
t_unknown = set(raw_term.keys()) - _ALLOWED_TERM_KEYS
|
|
468
|
+
if t_unknown:
|
|
469
|
+
raise SchemaDefinitionError(
|
|
470
|
+
f"Unknown attributes on arithmetic term in {rule_id!r}: "
|
|
471
|
+
f"{', '.join(sorted(t_unknown))}"
|
|
472
|
+
)
|
|
473
|
+
parsed_terms.append(
|
|
474
|
+
ArithmeticTerm(
|
|
475
|
+
field=raw_term.get("field", ""),
|
|
476
|
+
sign=raw_term.get("sign", 1),
|
|
477
|
+
item_field=raw_term.get("item_field"),
|
|
478
|
+
treat_missing_as_zero=raw_term.get("treat_missing_as_zero", False),
|
|
479
|
+
)
|
|
480
|
+
)
|
|
481
|
+
rules.append(
|
|
482
|
+
ArithmeticRule(
|
|
483
|
+
rule_id=rule_id,
|
|
484
|
+
terms=tuple(parsed_terms),
|
|
485
|
+
target_field=raw_rule.get("target_field", ""),
|
|
486
|
+
tolerance=raw_rule.get("tolerance", Decimal("0")),
|
|
487
|
+
severity=severity,
|
|
488
|
+
message=message,
|
|
489
|
+
)
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
elif kind in (
|
|
493
|
+
ConditionalPresenceKind.REQUIRED_IF.value,
|
|
494
|
+
ConditionalPresenceKind.FORBIDDEN_IF.value,
|
|
495
|
+
):
|
|
496
|
+
unknown = set(raw_rule.keys()) - _ALLOWED_CONDITIONAL_KEYS
|
|
497
|
+
if unknown:
|
|
498
|
+
raise SchemaDefinitionError(
|
|
499
|
+
f"Unknown attributes on conditional rule {rule_id!r}: "
|
|
500
|
+
f"{', '.join(sorted(unknown))}"
|
|
501
|
+
)
|
|
502
|
+
raw_when = raw_rule.get("when")
|
|
503
|
+
if not isinstance(raw_when, Mapping):
|
|
504
|
+
raise SchemaDefinitionError(
|
|
505
|
+
f"Conditional rule {rule_id!r} must define a 'when' condition object."
|
|
506
|
+
)
|
|
507
|
+
w_unknown = set(raw_when.keys()) - _ALLOWED_CONDITION_KEYS
|
|
508
|
+
if w_unknown:
|
|
509
|
+
raise SchemaDefinitionError(
|
|
510
|
+
f"Unknown attributes on condition in rule {rule_id!r}: "
|
|
511
|
+
f"{', '.join(sorted(w_unknown))}"
|
|
512
|
+
)
|
|
513
|
+
cond_field = raw_when.get("field", "")
|
|
514
|
+
cond_spec = (
|
|
515
|
+
resolve_schema_field_spec(parsed_fields, cond_field.strip())
|
|
516
|
+
if isinstance(cond_field, str) and cond_field.strip()
|
|
517
|
+
else None
|
|
518
|
+
)
|
|
519
|
+
cond_val = raw_when.get("value")
|
|
520
|
+
if cond_val is not None and cond_spec is not None:
|
|
521
|
+
cond_val = _coerce_condition_literal(cond_val, cond_spec.field_type)
|
|
522
|
+
raw_vals = raw_when.get("values")
|
|
523
|
+
cond_vals: tuple[Any, ...] | None = None
|
|
524
|
+
if raw_vals is not None:
|
|
525
|
+
if not isinstance(raw_vals, (list, tuple)):
|
|
526
|
+
raise SchemaDefinitionError(
|
|
527
|
+
f"Condition 'values' in rule {rule_id!r} must be a list."
|
|
528
|
+
)
|
|
529
|
+
cond_vals = tuple(
|
|
530
|
+
_coerce_condition_literal(v, cond_spec.field_type)
|
|
531
|
+
if cond_spec is not None
|
|
532
|
+
else v
|
|
533
|
+
for v in raw_vals
|
|
534
|
+
)
|
|
535
|
+
when = FieldCondition(
|
|
536
|
+
field=cond_field,
|
|
537
|
+
operator=raw_when.get("operator", ""),
|
|
538
|
+
value=cond_val,
|
|
539
|
+
values=cond_vals,
|
|
540
|
+
)
|
|
541
|
+
raw_targets = raw_rule.get("target_fields")
|
|
542
|
+
if not isinstance(raw_targets, list) or not all(
|
|
543
|
+
isinstance(t, str) for t in raw_targets
|
|
544
|
+
):
|
|
545
|
+
raise SchemaDefinitionError(
|
|
546
|
+
f"Conditional rule {rule_id!r} 'target_fields' must be a list of strings."
|
|
547
|
+
)
|
|
548
|
+
rules.append(
|
|
549
|
+
ConditionalPresenceRule(
|
|
550
|
+
rule_id=rule_id,
|
|
551
|
+
kind=ConditionalPresenceKind(kind),
|
|
552
|
+
when=when,
|
|
553
|
+
target_fields=tuple(raw_targets),
|
|
554
|
+
severity=severity,
|
|
555
|
+
message=message,
|
|
556
|
+
)
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
elif kind in (
|
|
560
|
+
GroupPresenceKind.MUTUALLY_EXCLUSIVE.value,
|
|
561
|
+
GroupPresenceKind.AT_LEAST_ONE_OF.value,
|
|
562
|
+
):
|
|
563
|
+
unknown = set(raw_rule.keys()) - _ALLOWED_GROUP_KEYS
|
|
564
|
+
if unknown:
|
|
565
|
+
raise SchemaDefinitionError(
|
|
566
|
+
f"Unknown attributes on group rule {rule_id!r}: {', '.join(sorted(unknown))}"
|
|
567
|
+
)
|
|
568
|
+
raw_group = raw_rule.get("fields")
|
|
569
|
+
if not isinstance(raw_group, list) or not all(isinstance(f, str) for f in raw_group):
|
|
570
|
+
raise SchemaDefinitionError(
|
|
571
|
+
f"Group rule {rule_id!r} 'fields' must be a list of strings."
|
|
572
|
+
)
|
|
573
|
+
rules.append(
|
|
574
|
+
GroupPresenceRule(
|
|
575
|
+
rule_id=rule_id,
|
|
576
|
+
kind=GroupPresenceKind(kind),
|
|
577
|
+
fields=tuple(raw_group),
|
|
578
|
+
severity=severity,
|
|
579
|
+
message=message,
|
|
580
|
+
)
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
else:
|
|
584
|
+
raise SchemaDefinitionError(
|
|
585
|
+
f"Unsupported validation rule kind {raw_kind!r} on rule {rule_id!r}."
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
return tuple(rules)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def load_schema_from_json_file(path: str | Path) -> ExtractionSchema:
|
|
592
|
+
"""Load and validate an ExtractionSchema from a JSON file with duplicate-key rejection."""
|
|
593
|
+
schema_path = Path(path)
|
|
594
|
+
if not schema_path.exists():
|
|
595
|
+
raise SchemaDefinitionError(f"Schema file not found: {schema_path.name}")
|
|
596
|
+
if not schema_path.is_file():
|
|
597
|
+
raise SchemaDefinitionError(f"Schema path is not a regular file: {schema_path.name}")
|
|
598
|
+
if schema_path.stat().st_size > _MAX_SCHEMA_JSON_BYTES:
|
|
599
|
+
raise SchemaDefinitionError(
|
|
600
|
+
f"Schema file exceeds maximum allowed size ({_MAX_SCHEMA_JSON_BYTES} bytes)."
|
|
601
|
+
)
|
|
602
|
+
try:
|
|
603
|
+
raw_text = schema_path.read_text(encoding="utf-8")
|
|
604
|
+
except OSError as exc:
|
|
605
|
+
raise SchemaDefinitionError(f"Unable to read schema file: {exc}") from exc
|
|
606
|
+
|
|
607
|
+
try:
|
|
608
|
+
parsed = json.loads(raw_text, object_pairs_hook=_reject_duplicate_json_keys)
|
|
609
|
+
except json.JSONDecodeError as exc:
|
|
610
|
+
raise SchemaDefinitionError(
|
|
611
|
+
f"Invalid JSON syntax in schema file at line {exc.lineno}, col {exc.colno}."
|
|
612
|
+
) from exc
|
|
613
|
+
|
|
614
|
+
if not isinstance(parsed, Mapping):
|
|
615
|
+
raise SchemaDefinitionError("Schema JSON root must be an object.")
|
|
616
|
+
return load_schema_from_dict(parsed)
|