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,277 @@
|
|
|
1
|
+
"""Immutable in-memory and path-based document input descriptors and sanitizers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, BinaryIO
|
|
10
|
+
|
|
11
|
+
from structa_maestro.contracts.enums import DocumentFormat
|
|
12
|
+
from structa_maestro.exceptions import ConfigurationError
|
|
13
|
+
|
|
14
|
+
SUPPORTED_MEDIA_TYPES: dict[str, DocumentFormat] = {
|
|
15
|
+
"text/plain": DocumentFormat.TXT,
|
|
16
|
+
"application/pdf": DocumentFormat.PDF,
|
|
17
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": DocumentFormat.DOCX,
|
|
18
|
+
"text/html": DocumentFormat.HTML,
|
|
19
|
+
"text/markdown": DocumentFormat.MARKDOWN,
|
|
20
|
+
"message/rfc822": DocumentFormat.EML,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class DocumentInputKind(StrEnum):
|
|
25
|
+
"""Mutually exclusive origin kind for a DocumentInput descriptor."""
|
|
26
|
+
|
|
27
|
+
PATH = "path"
|
|
28
|
+
BYTES = "bytes"
|
|
29
|
+
TEXT = "text"
|
|
30
|
+
STREAM = "stream"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def sanitize_filename(filename: str | None) -> str | None:
|
|
34
|
+
"""Sanitize a caller-supplied filename to a safe basename only.
|
|
35
|
+
|
|
36
|
+
- Rejects non-string values and embedded null bytes eagerly with ConfigurationError.
|
|
37
|
+
- Strips POSIX and Windows directory prefixes (e.g. ``/a/b/c.pdf``, ``C:\\a\\b.docx``,
|
|
38
|
+
``../../etc/passwd``) so directory paths never leak into canonical metadata or logs.
|
|
39
|
+
- Returns ``None`` when no safe basename remains (blank, ``/``, ``.``, ``..``, drive root).
|
|
40
|
+
"""
|
|
41
|
+
if filename is None:
|
|
42
|
+
return None
|
|
43
|
+
if not isinstance(filename, str):
|
|
44
|
+
raise ConfigurationError("filename must be a string or None.")
|
|
45
|
+
if "\x00" in filename:
|
|
46
|
+
raise ConfigurationError("filename cannot contain null bytes.")
|
|
47
|
+
|
|
48
|
+
normalized = filename.replace("\\", "/").strip()
|
|
49
|
+
if not normalized:
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
parts = [segment.strip() for segment in normalized.split("/") if segment.strip()]
|
|
53
|
+
if not parts:
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
candidate = parts[-1]
|
|
57
|
+
if candidate in (".", "..") or candidate.endswith(":"):
|
|
58
|
+
return None
|
|
59
|
+
return candidate
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def normalize_media_type(media_type: str | None) -> str | None:
|
|
63
|
+
"""Normalize and validate an optional MIME media_type hint eagerly."""
|
|
64
|
+
if media_type is None:
|
|
65
|
+
return None
|
|
66
|
+
if not isinstance(media_type, str) or not media_type.strip():
|
|
67
|
+
raise ConfigurationError("media_type must be a non-empty MIME type string or None.")
|
|
68
|
+
base_type = media_type.split(";", 1)[0].strip().lower()
|
|
69
|
+
if base_type not in SUPPORTED_MEDIA_TYPES:
|
|
70
|
+
allowed = ", ".join(sorted(SUPPORTED_MEDIA_TYPES))
|
|
71
|
+
raise ConfigurationError(
|
|
72
|
+
f"Unsupported media_type hint {media_type!r}. Supported values: {allowed}."
|
|
73
|
+
)
|
|
74
|
+
return base_type
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _validate_optional_document_id(document_id: str | None) -> str | None:
|
|
78
|
+
if document_id is None:
|
|
79
|
+
return None
|
|
80
|
+
if not isinstance(document_id, str) or not document_id.strip():
|
|
81
|
+
raise ConfigurationError("document_id must be a non-empty string or None.")
|
|
82
|
+
return document_id.strip()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _validate_binary_stream(stream: Any) -> BinaryIO:
|
|
86
|
+
if stream is None or isinstance(stream, (str, bytes, bytearray, memoryview, io.TextIOBase)):
|
|
87
|
+
raise ConfigurationError("DocumentInput.from_stream requires a readable binary stream.")
|
|
88
|
+
read_fn = getattr(stream, "read", None)
|
|
89
|
+
if not callable(read_fn):
|
|
90
|
+
raise ConfigurationError("DocumentInput.from_stream requires a stream with a read method.")
|
|
91
|
+
if getattr(stream, "closed", False) is True:
|
|
92
|
+
raise ConfigurationError("DocumentInput.from_stream cannot accept a closed stream.")
|
|
93
|
+
readable_fn = getattr(stream, "readable", None)
|
|
94
|
+
if callable(readable_fn):
|
|
95
|
+
try:
|
|
96
|
+
if not readable_fn():
|
|
97
|
+
raise ConfigurationError(
|
|
98
|
+
"DocumentInput.from_stream requires a readable binary stream."
|
|
99
|
+
)
|
|
100
|
+
except ValueError as exc:
|
|
101
|
+
raise ConfigurationError(
|
|
102
|
+
"DocumentInput.from_stream cannot accept a closed or unusable stream."
|
|
103
|
+
) from exc
|
|
104
|
+
return stream # type: ignore[no-any-return]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
108
|
+
class DocumentInput:
|
|
109
|
+
"""Immutable descriptor for path, raw bytes, plain text, or binary stream extraction inputs."""
|
|
110
|
+
|
|
111
|
+
kind: DocumentInputKind
|
|
112
|
+
path: Path | None = None
|
|
113
|
+
content: bytes | None = None
|
|
114
|
+
text: str | None = None
|
|
115
|
+
stream: BinaryIO | None = None
|
|
116
|
+
filename: str | None = None
|
|
117
|
+
document_id: str | None = None
|
|
118
|
+
media_type: str | None = None
|
|
119
|
+
|
|
120
|
+
def __post_init__(self) -> None:
|
|
121
|
+
if not isinstance(self.kind, DocumentInputKind):
|
|
122
|
+
raise ConfigurationError("DocumentInput.kind must be a DocumentInputKind value.")
|
|
123
|
+
|
|
124
|
+
object.__setattr__(self, "document_id", _validate_optional_document_id(self.document_id))
|
|
125
|
+
object.__setattr__(self, "media_type", normalize_media_type(self.media_type))
|
|
126
|
+
sanitized_name = sanitize_filename(self.filename)
|
|
127
|
+
object.__setattr__(self, "filename", sanitized_name)
|
|
128
|
+
|
|
129
|
+
if self.kind == DocumentInputKind.PATH:
|
|
130
|
+
if self.content is not None or self.text is not None or self.stream is not None:
|
|
131
|
+
raise ConfigurationError(
|
|
132
|
+
"PATH DocumentInput cannot specify bytes, text, or stream."
|
|
133
|
+
)
|
|
134
|
+
raw_path: Any = self.path
|
|
135
|
+
if isinstance(raw_path, str):
|
|
136
|
+
if not raw_path.strip():
|
|
137
|
+
raise ConfigurationError("DocumentInput.path must be a non-empty file path.")
|
|
138
|
+
if "\x00" in raw_path:
|
|
139
|
+
raise ConfigurationError("DocumentInput.path cannot contain null bytes.")
|
|
140
|
+
resolved_path = Path(raw_path)
|
|
141
|
+
elif isinstance(raw_path, Path):
|
|
142
|
+
path_str = str(raw_path)
|
|
143
|
+
if not path_str.strip():
|
|
144
|
+
raise ConfigurationError("DocumentInput.path must be a non-empty file path.")
|
|
145
|
+
if "\x00" in path_str:
|
|
146
|
+
raise ConfigurationError("DocumentInput.path cannot contain null bytes.")
|
|
147
|
+
resolved_path = raw_path
|
|
148
|
+
else:
|
|
149
|
+
raise ConfigurationError("DocumentInput.path must be a str or pathlib.Path.")
|
|
150
|
+
object.__setattr__(self, "path", resolved_path)
|
|
151
|
+
if sanitized_name is None:
|
|
152
|
+
object.__setattr__(self, "filename", sanitize_filename(resolved_path.name))
|
|
153
|
+
|
|
154
|
+
elif self.kind == DocumentInputKind.BYTES:
|
|
155
|
+
if self.path is not None or self.text is not None or self.stream is not None:
|
|
156
|
+
raise ConfigurationError(
|
|
157
|
+
"BYTES DocumentInput cannot specify path, text, or stream."
|
|
158
|
+
)
|
|
159
|
+
raw_content: Any = self.content
|
|
160
|
+
if not isinstance(raw_content, (bytes, bytearray, memoryview)):
|
|
161
|
+
raise ConfigurationError(
|
|
162
|
+
"DocumentInput.from_bytes requires bytes, bytearray, or memoryview."
|
|
163
|
+
)
|
|
164
|
+
# Snapshot mutable buffers to immutable bytes for thread safety & isolation
|
|
165
|
+
object.__setattr__(self, "content", bytes(raw_content))
|
|
166
|
+
|
|
167
|
+
elif self.kind == DocumentInputKind.TEXT:
|
|
168
|
+
if self.path is not None or self.content is not None or self.stream is not None:
|
|
169
|
+
raise ConfigurationError(
|
|
170
|
+
"TEXT DocumentInput cannot specify path, bytes, or stream."
|
|
171
|
+
)
|
|
172
|
+
if not isinstance(self.text, str):
|
|
173
|
+
raise ConfigurationError("DocumentInput.from_text requires a str payload.")
|
|
174
|
+
if self.media_type is not None and self.media_type not in (
|
|
175
|
+
"text/plain",
|
|
176
|
+
"text/html",
|
|
177
|
+
"text/markdown",
|
|
178
|
+
"message/rfc822",
|
|
179
|
+
):
|
|
180
|
+
raise ConfigurationError(
|
|
181
|
+
"DocumentInput.from_text only supports text-based media_type values "
|
|
182
|
+
"('text/plain', 'text/html', 'text/markdown', 'message/rfc822') or None."
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
elif self.kind == DocumentInputKind.STREAM:
|
|
186
|
+
if self.path is not None or self.content is not None or self.text is not None:
|
|
187
|
+
raise ConfigurationError(
|
|
188
|
+
"STREAM DocumentInput cannot specify path, bytes, or text."
|
|
189
|
+
)
|
|
190
|
+
validated_stream = _validate_binary_stream(self.stream)
|
|
191
|
+
object.__setattr__(self, "stream", validated_stream)
|
|
192
|
+
|
|
193
|
+
@classmethod
|
|
194
|
+
def from_path(
|
|
195
|
+
cls,
|
|
196
|
+
path: str | Path,
|
|
197
|
+
*,
|
|
198
|
+
filename: str | None = None,
|
|
199
|
+
document_id: str | None = None,
|
|
200
|
+
media_type: str | None = None,
|
|
201
|
+
) -> DocumentInput:
|
|
202
|
+
"""Create a DocumentInput referencing a filesystem path."""
|
|
203
|
+
return cls(
|
|
204
|
+
kind=DocumentInputKind.PATH,
|
|
205
|
+
path=path, # type: ignore[arg-type]
|
|
206
|
+
filename=filename,
|
|
207
|
+
document_id=document_id,
|
|
208
|
+
media_type=media_type,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
@classmethod
|
|
212
|
+
def from_bytes(
|
|
213
|
+
cls,
|
|
214
|
+
content: bytes | bytearray | memoryview,
|
|
215
|
+
*,
|
|
216
|
+
filename: str | None = None,
|
|
217
|
+
document_id: str | None = None,
|
|
218
|
+
media_type: str | None = None,
|
|
219
|
+
) -> DocumentInput:
|
|
220
|
+
"""Create a DocumentInput from an immutable snapshot of raw binary content."""
|
|
221
|
+
return cls(
|
|
222
|
+
kind=DocumentInputKind.BYTES,
|
|
223
|
+
content=content, # type: ignore[arg-type]
|
|
224
|
+
filename=filename,
|
|
225
|
+
document_id=document_id,
|
|
226
|
+
media_type=media_type,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
@classmethod
|
|
230
|
+
def from_text(
|
|
231
|
+
cls,
|
|
232
|
+
text: str,
|
|
233
|
+
*,
|
|
234
|
+
filename: str | None = None,
|
|
235
|
+
document_id: str | None = None,
|
|
236
|
+
media_type: str | None = None,
|
|
237
|
+
) -> DocumentInput:
|
|
238
|
+
"""Create a DocumentInput directly from plain text content."""
|
|
239
|
+
return cls(
|
|
240
|
+
kind=DocumentInputKind.TEXT,
|
|
241
|
+
text=text,
|
|
242
|
+
filename=filename,
|
|
243
|
+
document_id=document_id,
|
|
244
|
+
media_type=media_type,
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
@classmethod
|
|
248
|
+
def from_stream(
|
|
249
|
+
cls,
|
|
250
|
+
stream: BinaryIO,
|
|
251
|
+
*,
|
|
252
|
+
filename: str | None = None,
|
|
253
|
+
document_id: str | None = None,
|
|
254
|
+
media_type: str | None = None,
|
|
255
|
+
) -> DocumentInput:
|
|
256
|
+
"""Create a DocumentInput wrapping a readable binary stream (caller owns closing)."""
|
|
257
|
+
return cls(
|
|
258
|
+
kind=DocumentInputKind.STREAM,
|
|
259
|
+
stream=stream,
|
|
260
|
+
filename=filename,
|
|
261
|
+
document_id=document_id,
|
|
262
|
+
media_type=media_type,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
def __repr__(self) -> str:
|
|
266
|
+
"""Privacy-safe representation that never discloses raw document content or host paths."""
|
|
267
|
+
parts = [
|
|
268
|
+
f"kind={self.kind.value!r}",
|
|
269
|
+
f"filename={self.filename!r}",
|
|
270
|
+
f"document_id={self.document_id!r}",
|
|
271
|
+
f"media_type={self.media_type!r}",
|
|
272
|
+
]
|
|
273
|
+
if self.kind == DocumentInputKind.BYTES and self.content is not None:
|
|
274
|
+
parts.append(f"size_bytes={len(self.content)}")
|
|
275
|
+
elif self.kind == DocumentInputKind.TEXT and self.text is not None:
|
|
276
|
+
parts.append(f"size_chars={len(self.text)}")
|
|
277
|
+
return f"DocumentInput({', '.join(parts)})"
|