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.
Files changed (55) hide show
  1. structa_maestro/__init__.py +294 -0
  2. structa_maestro/batch.py +564 -0
  3. structa_maestro/binding.py +206 -0
  4. structa_maestro/builder/__init__.py +0 -0
  5. structa_maestro/builder/result_builder.py +308 -0
  6. structa_maestro/cli.py +730 -0
  7. structa_maestro/confidence/__init__.py +49 -0
  8. structa_maestro/confidence/calibration.py +990 -0
  9. structa_maestro/confidence/normalizer.py +203 -0
  10. structa_maestro/config.py +111 -0
  11. structa_maestro/contracts/__init__.py +0 -0
  12. structa_maestro/contracts/enums.py +86 -0
  13. structa_maestro/contracts/models.py +229 -0
  14. structa_maestro/contracts/serialization.py +169 -0
  15. structa_maestro/documents/__init__.py +32 -0
  16. structa_maestro/documents/docx_parser.py +215 -0
  17. structa_maestro/documents/eml_parser.py +360 -0
  18. structa_maestro/documents/html_parser.py +337 -0
  19. structa_maestro/documents/inputs.py +277 -0
  20. structa_maestro/documents/loader.py +675 -0
  21. structa_maestro/documents/markdown_parser.py +225 -0
  22. structa_maestro/documents/models.py +33 -0
  23. structa_maestro/documents/normalization.py +24 -0
  24. structa_maestro/documents/pdf_parser.py +186 -0
  25. structa_maestro/documents/txt_parser.py +169 -0
  26. structa_maestro/engine.py +1201 -0
  27. structa_maestro/exceptions.py +38 -0
  28. structa_maestro/provenance/__init__.py +0 -0
  29. structa_maestro/provenance/associator.py +234 -0
  30. structa_maestro/py.typed +0 -0
  31. structa_maestro/review.py +1234 -0
  32. structa_maestro/schema/__init__.py +19 -0
  33. structa_maestro/schema/loader.py +616 -0
  34. structa_maestro/schema/models.py +269 -0
  35. structa_maestro/schema/pydantic_adapter.py +566 -0
  36. structa_maestro/schema/rules.py +526 -0
  37. structa_maestro/schema/serializer.py +156 -0
  38. structa_maestro/strategies/__init__.py +45 -0
  39. structa_maestro/strategies/base.py +101 -0
  40. structa_maestro/strategies/llm_anthropic.py +1142 -0
  41. structa_maestro/strategies/llm_config.py +154 -0
  42. structa_maestro/strategies/llm_gemini.py +1171 -0
  43. structa_maestro/strategies/llm_helpers.py +240 -0
  44. structa_maestro/strategies/llm_openai_compat.py +1183 -0
  45. structa_maestro/strategies/schema_compiler.py +248 -0
  46. structa_maestro/strategies/testing.py +71 -0
  47. structa_maestro/telemetry.py +800 -0
  48. structa_maestro/validation/__init__.py +0 -0
  49. structa_maestro/validation/cross_field.py +463 -0
  50. structa_maestro/validation/validator.py +531 -0
  51. structa_maestro-0.2.0.dist-info/METADATA +394 -0
  52. structa_maestro-0.2.0.dist-info/RECORD +55 -0
  53. structa_maestro-0.2.0.dist-info/WHEEL +4 -0
  54. structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
  55. structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,248 @@
1
+ """Deterministic closed JSON Schema compiler for strict OpenAI-compatible structured outputs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from datetime import date
8
+ from decimal import Decimal
9
+ from typing import Any
10
+
11
+ from structa_maestro.contracts.enums import FieldType
12
+ from structa_maestro.schema.models import ExtractionSchema, FieldSpec
13
+
14
+ _SCHEMA_NAME_RE = re.compile(r"[^a-zA-Z0-9_-]+")
15
+
16
+
17
+ class StrictSchemaIncompatibilityError(ValueError):
18
+ """Raised when an ExtractionSchema cannot be compiled into a closed strict JSON Schema."""
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class CompiledOutputSchema:
23
+ """Compiled strict OpenAI-compatible json_schema payload metadata and schema body."""
24
+
25
+ name: str
26
+ strict: bool
27
+ schema: dict[str, Any]
28
+
29
+ def to_response_format(self) -> dict[str, Any]:
30
+ """Return OpenAI-compatible Chat Completions response_format dictionary."""
31
+ return {
32
+ "type": "json_schema",
33
+ "json_schema": {
34
+ "name": self.name,
35
+ "strict": self.strict,
36
+ "schema": self.schema,
37
+ },
38
+ }
39
+
40
+
41
+ def _sanitize_schema_name(schema_id: str) -> str:
42
+ cleaned = _SCHEMA_NAME_RE.sub("_", schema_id.strip()).strip("_")
43
+ if not cleaned:
44
+ cleaned = "extraction_output"
45
+ return cleaned[:64]
46
+
47
+
48
+ def _has_open_additional_fields(schema: ExtractionSchema) -> str | None:
49
+ if schema.allow_additional_fields:
50
+ return schema.schema_id
51
+
52
+ def _walk(spec: FieldSpec, path: str) -> str | None:
53
+ if spec.allow_additional_fields:
54
+ return path
55
+ if spec.properties:
56
+ for key, child in spec.properties.items():
57
+ found = _walk(child, f"{path}.{key}")
58
+ if found is not None:
59
+ return found
60
+ if spec.items is not None:
61
+ return _walk(spec.items, f"{path}[]")
62
+ return None
63
+
64
+ for fname, fspec in schema.fields.items():
65
+ found = _walk(fspec, fname)
66
+ if found is not None:
67
+ return found
68
+ return None
69
+
70
+
71
+ def _to_json_enum_value(val: Any) -> Any:
72
+ if isinstance(val, Decimal):
73
+ return str(val)
74
+ if isinstance(val, date):
75
+ return val.isoformat()
76
+ return val
77
+
78
+
79
+ def _compile_value_schema(spec: FieldSpec, *, allow_null: bool) -> dict[str, Any]:
80
+ """Compile a FieldSpec into a strict-mode-compatible JSON Schema for its value."""
81
+ allowed = spec.constraints.allowed_values
82
+
83
+ if spec.field_type == FieldType.STRING:
84
+ node: dict[str, Any] = {"type": ["string", "null"] if allow_null else "string"}
85
+ if allowed is not None:
86
+ vals = [_to_json_enum_value(v) for v in allowed]
87
+ if allow_null and None not in vals:
88
+ vals.append(None)
89
+ node["enum"] = vals
90
+ return node
91
+
92
+ if spec.field_type == FieldType.INTEGER:
93
+ node = {"type": ["integer", "null"] if allow_null else "integer"}
94
+ if allowed is not None:
95
+ vals = [_to_json_enum_value(v) for v in allowed]
96
+ if allow_null and None not in vals:
97
+ vals.append(None)
98
+ node["enum"] = vals
99
+ return node
100
+
101
+ if spec.field_type == FieldType.BOOLEAN:
102
+ node = {"type": ["boolean", "null"] if allow_null else "boolean"}
103
+ if allowed is not None:
104
+ vals = [_to_json_enum_value(v) for v in allowed]
105
+ if allow_null and None not in vals:
106
+ vals.append(None)
107
+ node["enum"] = vals
108
+ return node
109
+
110
+ if spec.field_type == FieldType.DATE:
111
+ node = {
112
+ "type": ["string", "null"] if allow_null else "string",
113
+ "description": "ISO-8601 date string (YYYY-MM-DD).",
114
+ }
115
+ if allowed is not None:
116
+ vals = [_to_json_enum_value(v) for v in allowed]
117
+ if allow_null and None not in vals:
118
+ vals.append(None)
119
+ node["enum"] = vals
120
+ return node
121
+
122
+ if spec.field_type == FieldType.DECIMAL:
123
+ if allowed is not None:
124
+ str_vals = [str(v) for v in allowed]
125
+ num_vals: list[float] = []
126
+ for v in allowed:
127
+ if isinstance(v, (int, float, Decimal)) and not isinstance(v, bool):
128
+ num_vals.append(float(v))
129
+ variants: list[dict[str, Any]] = [{"type": "string", "enum": str_vals}]
130
+ if num_vals:
131
+ variants.append({"type": "number", "enum": num_vals})
132
+ if allow_null:
133
+ variants.append({"type": "null"})
134
+ return {"anyOf": variants}
135
+ variants = [{"type": "string"}, {"type": "number"}]
136
+ if allow_null:
137
+ variants.append({"type": "null"})
138
+ return {"anyOf": variants}
139
+
140
+ if spec.field_type == FieldType.OBJECT:
141
+ props = spec.properties or {}
142
+ compiled_props: dict[str, Any] = {}
143
+ req_keys: list[str] = []
144
+ for prop_name, prop_spec in props.items():
145
+ req_keys.append(prop_name)
146
+ prop_nullable = prop_spec.nullable or not prop_spec.required
147
+ compiled_props[prop_name] = _compile_value_schema(prop_spec, allow_null=prop_nullable)
148
+ obj_schema: dict[str, Any] = {
149
+ "type": "object",
150
+ "additionalProperties": False,
151
+ "required": req_keys,
152
+ "properties": compiled_props,
153
+ }
154
+ if allow_null:
155
+ return {"anyOf": [obj_schema, {"type": "null"}]}
156
+ return obj_schema
157
+
158
+ if spec.field_type == FieldType.ARRAY:
159
+ item_spec = spec.items
160
+ if item_spec is None:
161
+ item_schema: dict[str, Any] = {"type": ["string", "null"]}
162
+ else:
163
+ item_schema = _compile_value_schema(item_spec, allow_null=item_spec.nullable)
164
+ arr_schema: dict[str, Any] = {"type": "array", "items": item_schema}
165
+ if allow_null:
166
+ return {"anyOf": [arr_schema, {"type": "null"}]}
167
+ return arr_schema
168
+
169
+ return {"type": ["string", "null"] if allow_null else "string"}
170
+
171
+
172
+ def _compile_field_envelope(spec: FieldSpec) -> dict[str, Any]:
173
+ """Compile one top-level declared field into its canonical extraction envelope schema."""
174
+ evidence_item: dict[str, Any] = {
175
+ "type": "object",
176
+ "additionalProperties": False,
177
+ "required": ["quote", "relationship"],
178
+ "properties": {
179
+ "quote": {"type": "string"},
180
+ "relationship": {
181
+ "type": "string",
182
+ "enum": ["direct", "inferred", "conflicting"],
183
+ },
184
+ },
185
+ }
186
+ envelope: dict[str, Any] = {
187
+ "type": "object",
188
+ "additionalProperties": False,
189
+ "required": ["presence", "value", "confidence", "ambiguous", "evidence"],
190
+ "properties": {
191
+ "presence": {"type": "string", "enum": ["present", "missing"]},
192
+ # Always allow null on top-level field value because presence="missing" pairs with null.
193
+ "value": _compile_value_schema(spec, allow_null=True),
194
+ "confidence": {"type": ["number", "null"]},
195
+ "ambiguous": {"type": "boolean"},
196
+ "evidence": {"type": "array", "items": evidence_item},
197
+ },
198
+ }
199
+ if spec.description:
200
+ envelope["description"] = spec.description
201
+ return envelope
202
+
203
+
204
+ def compile_extraction_output_schema(schema: ExtractionSchema) -> CompiledOutputSchema:
205
+ """Compile ExtractionSchema into a deterministic closed strict JSON Schema envelope."""
206
+ open_path = _has_open_additional_fields(schema)
207
+ if open_path is not None:
208
+ raise StrictSchemaIncompatibilityError(
209
+ f"ExtractionSchema allows additional fields at {open_path!r}, which cannot be "
210
+ "represented in closed strict json_schema mode."
211
+ )
212
+
213
+ field_names = list(schema.fields.keys())
214
+ field_properties = {
215
+ fname: _compile_field_envelope(fspec) for fname, fspec in schema.fields.items()
216
+ }
217
+
218
+ record_schema: dict[str, Any] = {
219
+ "type": "object",
220
+ "additionalProperties": False,
221
+ "required": ["fields"],
222
+ "properties": {
223
+ "fields": {
224
+ "type": "object",
225
+ "additionalProperties": False,
226
+ "required": field_names,
227
+ "properties": field_properties,
228
+ }
229
+ },
230
+ }
231
+
232
+ root_schema: dict[str, Any] = {
233
+ "type": "object",
234
+ "additionalProperties": False,
235
+ "required": ["records"],
236
+ "properties": {
237
+ "records": {
238
+ "type": "array",
239
+ "items": record_schema,
240
+ }
241
+ },
242
+ }
243
+
244
+ return CompiledOutputSchema(
245
+ name=_sanitize_schema_name(schema.schema_id),
246
+ strict=True,
247
+ schema=root_schema,
248
+ )
@@ -0,0 +1,71 @@
1
+ """Built-in offline deterministic test strategies (sync and async) for automated testing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable
6
+
7
+ from structa_maestro.documents.models import PreparedDocument
8
+ from structa_maestro.exceptions import ConfigurationError
9
+ from structa_maestro.schema.models import ExtractionSchema
10
+ from structa_maestro.strategies.base import StrategyOutput
11
+
12
+ StrategyHandler = Callable[[PreparedDocument, ExtractionSchema], StrategyOutput]
13
+ AsyncStrategyHandler = Callable[[PreparedDocument, ExtractionSchema], Awaitable[StrategyOutput]]
14
+
15
+
16
+ class DeterministicTestStrategy:
17
+ """Deterministic offline extraction strategy for unit, contract, and integration testing."""
18
+
19
+ def __init__(
20
+ self,
21
+ handler: StrategyHandler | StrategyOutput,
22
+ *,
23
+ name: str = "deterministic-test",
24
+ ) -> None:
25
+ self._handler = handler
26
+ self._name = name
27
+
28
+ @property
29
+ def name(self) -> str:
30
+ return self._name
31
+
32
+ def extract_raw(
33
+ self,
34
+ document: PreparedDocument,
35
+ schema: ExtractionSchema,
36
+ ) -> StrategyOutput:
37
+ if isinstance(self._handler, StrategyOutput):
38
+ return self._handler
39
+ return self._handler(document, schema)
40
+
41
+
42
+ class AsyncDeterministicTestStrategy:
43
+ """Deterministic offline asyncio extraction strategy implementing AsyncExtractionStrategy."""
44
+
45
+ def __init__(
46
+ self,
47
+ handler: AsyncStrategyHandler | StrategyOutput,
48
+ *,
49
+ name: str = "async-deterministic-test",
50
+ ) -> None:
51
+ if not isinstance(handler, StrategyOutput) and not callable(handler):
52
+ raise ConfigurationError(
53
+ "AsyncDeterministicTestStrategy handler must be a StrategyOutput or async callable."
54
+ )
55
+ if not isinstance(name, str) or not name.strip():
56
+ raise ConfigurationError("AsyncDeterministicTestStrategy name must be a non-empty str.")
57
+ self._handler = handler
58
+ self._name = name.strip()
59
+
60
+ @property
61
+ def name(self) -> str:
62
+ return self._name
63
+
64
+ async def aextract_raw(
65
+ self,
66
+ document: PreparedDocument,
67
+ schema: ExtractionSchema,
68
+ ) -> StrategyOutput:
69
+ if isinstance(self._handler, StrategyOutput):
70
+ return self._handler
71
+ return await self._handler(document, schema)