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,169 @@
1
+ """Lossless JSON/dict serialization and strict deserialization for Canonical Contract v1.0."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import date, datetime
7
+ from decimal import Decimal, InvalidOperation
8
+ from typing import Any
9
+
10
+ from pydantic import ValidationError as PydanticValidationError
11
+
12
+ from structa_maestro.contracts.enums import FieldType
13
+ from structa_maestro.contracts.models import CONTRACT_VERSION, ExtractionResult
14
+ from structa_maestro.exceptions import ContractDeserializationError
15
+
16
+ _REQUIRED_TOP_LEVEL_KEYS = frozenset(
17
+ {
18
+ "contract_version",
19
+ "extraction_id",
20
+ "status",
21
+ "source",
22
+ "schema",
23
+ "records",
24
+ "validation",
25
+ "errors",
26
+ "warnings",
27
+ }
28
+ )
29
+
30
+
31
+ def _encode_json_value(value: Any) -> Any:
32
+ """Recursively convert Python scalar types into lossless JSON-native values."""
33
+ if value is None or isinstance(value, (bool, int, float, str)):
34
+ return value
35
+ if isinstance(value, Decimal):
36
+ return str(value)
37
+ if isinstance(value, datetime):
38
+ return value.isoformat()
39
+ if isinstance(value, date):
40
+ return value.isoformat()
41
+ if isinstance(value, list):
42
+ return [_encode_json_value(item) for item in value]
43
+ if isinstance(value, tuple):
44
+ return [_encode_json_value(item) for item in value]
45
+ if isinstance(value, dict):
46
+ return {str(k): _encode_json_value(v) for k, v in value.items()}
47
+ return str(value)
48
+
49
+
50
+ def _restore_typed_field_value(value: Any, value_type: str | None) -> Any:
51
+ """Restore Decimal and date Python types on deserialization when value_type is declared."""
52
+ if value is None or value_type is None:
53
+ return value
54
+ if value_type == FieldType.DECIMAL.value:
55
+ if isinstance(value, Decimal):
56
+ return value
57
+ if isinstance(value, (str, int)) and not isinstance(value, bool):
58
+ try:
59
+ return Decimal(str(value))
60
+ except InvalidOperation:
61
+ return value
62
+ if isinstance(value, float):
63
+ return Decimal(str(value))
64
+ return value
65
+ if value_type == FieldType.DATE.value:
66
+ if isinstance(value, date) and not isinstance(value, datetime):
67
+ return value
68
+ if isinstance(value, str):
69
+ try:
70
+ return date.fromisoformat(value)
71
+ except ValueError:
72
+ return value
73
+ return value
74
+ return value
75
+
76
+
77
+ def serialize_result_to_dict(result: ExtractionResult) -> dict[str, Any]:
78
+ """Convert an ExtractionResult to a canonical JSON-compatible dictionary."""
79
+ raw = result.model_dump(mode="python", by_alias=True)
80
+ # Encode enums & special scalar values cleanly for JSON schema compliance
81
+ encoded = _normalize_for_json_dict(raw)
82
+ if not isinstance(encoded, dict):
83
+ raise ContractDeserializationError("Serialized canonical result must be a dictionary.")
84
+ return encoded
85
+
86
+
87
+ def _normalize_for_json_dict(obj: Any) -> Any:
88
+ if obj is None or isinstance(obj, (bool, int, float, str)):
89
+ return obj
90
+ if isinstance(obj, Decimal):
91
+ return str(obj)
92
+ if isinstance(obj, datetime):
93
+ return obj.isoformat()
94
+ if isinstance(obj, date):
95
+ return obj.isoformat()
96
+ if isinstance(obj, list):
97
+ return [_normalize_for_json_dict(item) for item in obj]
98
+ if isinstance(obj, dict):
99
+ return {str(k): _normalize_for_json_dict(v) for k, v in obj.items()}
100
+ return _encode_json_value(obj)
101
+
102
+
103
+ def serialize_result_to_json(result: ExtractionResult, *, indent: int | None = None) -> str:
104
+ """Serialize an ExtractionResult to canonical UTF-8 JSON preserving exact field meaning."""
105
+ payload = serialize_result_to_dict(result)
106
+ return json.dumps(payload, ensure_ascii=False, indent=indent, allow_nan=False)
107
+
108
+
109
+ def deserialize_result_from_dict(data: Any) -> ExtractionResult:
110
+ """Strictly deserialize and validate a canonical dictionary into ExtractionResult."""
111
+ if not isinstance(data, dict):
112
+ raise ContractDeserializationError("Canonical result payload must be a JSON object.")
113
+
114
+ missing = _REQUIRED_TOP_LEVEL_KEYS - set(data.keys())
115
+ if missing:
116
+ missing_str = ", ".join(sorted(missing))
117
+ raise ContractDeserializationError(
118
+ f"Missing required canonical contract properties: {missing_str}"
119
+ )
120
+
121
+ version = data.get("contract_version")
122
+ if version != CONTRACT_VERSION:
123
+ raise ContractDeserializationError(
124
+ f"Unsupported contract_version {version!r}; expected {CONTRACT_VERSION!r}."
125
+ )
126
+
127
+ # Restore typed scalar values (Decimal / date) on fields before Pydantic validation
128
+ prepared = dict(data)
129
+ raw_records = prepared.get("records")
130
+ if isinstance(raw_records, list):
131
+ restored_records: list[Any] = []
132
+ for rec in raw_records:
133
+ if isinstance(rec, dict) and isinstance(rec.get("fields"), dict):
134
+ new_fields: dict[str, Any] = {}
135
+ for fname, fdata in rec["fields"].items():
136
+ if isinstance(fdata, dict):
137
+ fcopy = dict(fdata)
138
+ fcopy["value"] = _restore_typed_field_value(
139
+ fcopy.get("value"), fcopy.get("value_type")
140
+ )
141
+ new_fields[fname] = fcopy
142
+ else:
143
+ new_fields[fname] = fdata
144
+ rec_copy = dict(rec)
145
+ rec_copy["fields"] = new_fields
146
+ restored_records.append(rec_copy)
147
+ else:
148
+ restored_records.append(rec)
149
+ prepared["records"] = restored_records
150
+
151
+ try:
152
+ return ExtractionResult.model_validate(prepared)
153
+ except PydanticValidationError as exc:
154
+ raise ContractDeserializationError(
155
+ f"Canonical result failed contract validation: {exc.error_count()} error(s)."
156
+ ) from exc
157
+
158
+
159
+ def deserialize_result_from_json(raw_json: str) -> ExtractionResult:
160
+ """Strictly parse and deserialize canonical JSON into ExtractionResult."""
161
+ if not isinstance(raw_json, str) or not raw_json.strip():
162
+ raise ContractDeserializationError("Canonical JSON input must be a non-empty string.")
163
+ try:
164
+ parsed = json.loads(raw_json)
165
+ except json.JSONDecodeError as exc:
166
+ raise ContractDeserializationError(
167
+ f"Invalid JSON syntax in canonical result at line {exc.lineno}, col {exc.colno}."
168
+ ) from exc
169
+ return deserialize_result_from_dict(parsed)
@@ -0,0 +1,32 @@
1
+ """Document input descriptors, safe loaders, and prepared document models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from structa_maestro.documents.inputs import (
6
+ SUPPORTED_MEDIA_TYPES,
7
+ DocumentInput,
8
+ DocumentInputKind,
9
+ normalize_media_type,
10
+ sanitize_filename,
11
+ )
12
+ from structa_maestro.documents.loader import (
13
+ DocumentLoadResult,
14
+ load_document,
15
+ load_document_input,
16
+ read_stream_bounded,
17
+ )
18
+ from structa_maestro.documents.models import DocumentSegment, PreparedDocument
19
+
20
+ __all__ = [
21
+ "SUPPORTED_MEDIA_TYPES",
22
+ "DocumentInput",
23
+ "DocumentInputKind",
24
+ "DocumentLoadResult",
25
+ "DocumentSegment",
26
+ "PreparedDocument",
27
+ "load_document",
28
+ "load_document_input",
29
+ "normalize_media_type",
30
+ "read_stream_bounded",
31
+ "sanitize_filename",
32
+ ]
@@ -0,0 +1,215 @@
1
+ """ZIP-bomb-guarded DOCX parser extracting paragraphs, headings, and table text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import zipfile
7
+
8
+ import docx
9
+
10
+ from structa_maestro.config import DocumentLimits
11
+ from structa_maestro.contracts.enums import DocumentFormat, IssueSeverity, PipelineStage
12
+ from structa_maestro.contracts.models import DiagnosticIssue, SourceMetadata
13
+ from structa_maestro.documents.models import DocumentSegment, PreparedDocument
14
+ from structa_maestro.documents.normalization import normalize_document_text
15
+ from structa_maestro.documents.txt_parser import ParseResult
16
+
17
+
18
+ def parse_docx_bytes(
19
+ raw: bytes,
20
+ source: SourceMetadata,
21
+ limits: DocumentLimits,
22
+ ) -> ParseResult:
23
+ """Parse raw DOCX bytes with pre-open ZIP-bomb and archive-integrity guards."""
24
+ if len(raw) == 0:
25
+ return ParseResult(
26
+ document=None,
27
+ errors=(
28
+ DiagnosticIssue(
29
+ code="empty_document",
30
+ severity=IssueSeverity.ERROR,
31
+ stage=PipelineStage.DOCUMENT_PROCESSING,
32
+ message="Input DOCX document is empty (zero bytes).",
33
+ ),
34
+ ),
35
+ )
36
+
37
+ try:
38
+ with zipfile.ZipFile(io.BytesIO(raw), "r") as zf:
39
+ names = set(zf.namelist())
40
+ if "word/document.xml" not in names:
41
+ return ParseResult(
42
+ document=None,
43
+ errors=(
44
+ DiagnosticIssue(
45
+ code="unsupported_format",
46
+ severity=IssueSeverity.ERROR,
47
+ stage=PipelineStage.DOCUMENT_PROCESSING,
48
+ message=(
49
+ "ZIP archive is not a valid DOCX container "
50
+ "(missing word/document.xml)."
51
+ ),
52
+ ),
53
+ ),
54
+ )
55
+ total_uncompressed = sum(info.file_size for info in zf.infolist())
56
+ if total_uncompressed > limits.max_decompressed_bytes:
57
+ return ParseResult(
58
+ document=None,
59
+ errors=(
60
+ DiagnosticIssue(
61
+ code="resource_limit_exceeded",
62
+ severity=IssueSeverity.ERROR,
63
+ stage=PipelineStage.DOCUMENT_PROCESSING,
64
+ message=(
65
+ "DOCX uncompressed archive size exceeds configured "
66
+ f"max_decompressed_bytes limit ({limits.max_decompressed_bytes})."
67
+ ),
68
+ ),
69
+ ),
70
+ )
71
+ except zipfile.BadZipFile:
72
+ return ParseResult(
73
+ document=None,
74
+ errors=(
75
+ DiagnosticIssue(
76
+ code="corrupted_document",
77
+ severity=IssueSeverity.ERROR,
78
+ stage=PipelineStage.DOCUMENT_PROCESSING,
79
+ message="DOCX container is corrupted or not a valid ZIP archive.",
80
+ ),
81
+ ),
82
+ )
83
+ except Exception:
84
+ return ParseResult(
85
+ document=None,
86
+ errors=(
87
+ DiagnosticIssue(
88
+ code="corrupted_document",
89
+ severity=IssueSeverity.ERROR,
90
+ stage=PipelineStage.DOCUMENT_PROCESSING,
91
+ message="Unable to inspect DOCX container safely.",
92
+ ),
93
+ ),
94
+ )
95
+
96
+ try:
97
+ document = docx.Document(io.BytesIO(raw))
98
+ except Exception:
99
+ return ParseResult(
100
+ document=None,
101
+ errors=(
102
+ DiagnosticIssue(
103
+ code="corrupted_document",
104
+ severity=IssueSeverity.ERROR,
105
+ stage=PipelineStage.DOCUMENT_PROCESSING,
106
+ message="DOCX document structure is corrupted or unreadable.",
107
+ ),
108
+ ),
109
+ )
110
+
111
+ segments: list[DocumentSegment] = []
112
+ full_parts: list[str] = []
113
+ current_heading: str | None = None
114
+ paragraph_index = 0
115
+ cumulative_bytes = 0
116
+ offset = 0
117
+
118
+ for para in document.paragraphs:
119
+ text = normalize_document_text(para.text).strip()
120
+ if not text:
121
+ continue
122
+ style_name = para.style.name if para.style is not None else ""
123
+ if style_name and style_name.lower().startswith("heading"):
124
+ current_heading = text
125
+ paragraph_index += 1
126
+ cumulative_bytes += len(text.encode("utf-8"))
127
+ if cumulative_bytes > limits.max_decompressed_bytes:
128
+ return ParseResult(
129
+ document=None,
130
+ errors=(
131
+ DiagnosticIssue(
132
+ code="resource_limit_exceeded",
133
+ severity=IssueSeverity.ERROR,
134
+ stage=PipelineStage.DOCUMENT_PROCESSING,
135
+ message="Extracted DOCX text exceeds configured max_decompressed_bytes.",
136
+ ),
137
+ ),
138
+ )
139
+ if full_parts:
140
+ offset += 1 # '\n'
141
+ char_start = offset
142
+ char_end = offset + len(text)
143
+ segments.append(
144
+ DocumentSegment(
145
+ text=text,
146
+ char_start=char_start,
147
+ char_end=char_end,
148
+ paragraph=paragraph_index,
149
+ heading=current_heading,
150
+ )
151
+ )
152
+ full_parts.append(text)
153
+ offset = char_end
154
+
155
+ for table in document.tables:
156
+ for row in table.rows:
157
+ row_cells = [normalize_document_text(c.text).strip() for c in row.cells]
158
+ row_text = " | ".join(cell for cell in row_cells if cell)
159
+ if not row_text:
160
+ continue
161
+ paragraph_index += 1
162
+ cumulative_bytes += len(row_text.encode("utf-8"))
163
+ if cumulative_bytes > limits.max_decompressed_bytes:
164
+ return ParseResult(
165
+ document=None,
166
+ errors=(
167
+ DiagnosticIssue(
168
+ code="resource_limit_exceeded",
169
+ severity=IssueSeverity.ERROR,
170
+ stage=PipelineStage.DOCUMENT_PROCESSING,
171
+ message=(
172
+ "Extracted DOCX text exceeds configured max_decompressed_bytes."
173
+ ),
174
+ ),
175
+ ),
176
+ )
177
+ if full_parts:
178
+ offset += 1
179
+ char_start = offset
180
+ char_end = offset + len(row_text)
181
+ segments.append(
182
+ DocumentSegment(
183
+ text=row_text,
184
+ char_start=char_start,
185
+ char_end=char_end,
186
+ paragraph=paragraph_index,
187
+ heading=current_heading,
188
+ )
189
+ )
190
+ full_parts.append(row_text)
191
+ offset = char_end
192
+
193
+ full_text = "\n".join(full_parts)
194
+ if not full_text.strip():
195
+ return ParseResult(
196
+ document=None,
197
+ errors=(
198
+ DiagnosticIssue(
199
+ code="no_extractable_text",
200
+ severity=IssueSeverity.ERROR,
201
+ stage=PipelineStage.DOCUMENT_PROCESSING,
202
+ message="DOCX document contains no extractable text.",
203
+ ),
204
+ ),
205
+ )
206
+
207
+ return ParseResult(
208
+ document=PreparedDocument(
209
+ source=source,
210
+ format=DocumentFormat.DOCX,
211
+ full_text=full_text,
212
+ segments=tuple(segments),
213
+ page_count=None,
214
+ )
215
+ )