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,38 @@
|
|
|
1
|
+
"""Typed public exceptions for structa-maestro (contracts/python-api-and-cli.md Section 1.2)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class StructaMaestroError(Exception):
|
|
7
|
+
"""Base exception for configuration, schema, binding, and contract deserialization errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SchemaDefinitionError(StructaMaestroError):
|
|
11
|
+
"""Raised before extraction when a user-supplied schema is invalid or unsupported."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ConfigurationError(StructaMaestroError):
|
|
15
|
+
"""Raised when engine, limits, or strategy configuration is invalid."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ContractDeserializationError(StructaMaestroError):
|
|
19
|
+
"""Raised when deserializing malformed or unsupported canonical output contract payloads."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RecordBindingError(StructaMaestroError):
|
|
23
|
+
"""Raised when binding canonical extraction records to a typed Pydantic model fails.
|
|
24
|
+
|
|
25
|
+
Messages and ``issues`` identify failing record/field locations and sanitized reasons
|
|
26
|
+
without embedding raw extracted field values or document secrets.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
message: str,
|
|
32
|
+
*,
|
|
33
|
+
record_id: str | None = None,
|
|
34
|
+
issues: tuple[str, ...] = (),
|
|
35
|
+
) -> None:
|
|
36
|
+
super().__init__(message)
|
|
37
|
+
self.record_id: str | None = record_id
|
|
38
|
+
self.issues: tuple[str, ...] = tuple(issues)
|
|
File without changes
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Provenance association, source location mapping, and evidence integrity verification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import date
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from structa_maestro.contracts.enums import (
|
|
12
|
+
EvidenceRelationship,
|
|
13
|
+
FieldPresence,
|
|
14
|
+
IssueSeverity,
|
|
15
|
+
PipelineStage,
|
|
16
|
+
)
|
|
17
|
+
from structa_maestro.contracts.models import (
|
|
18
|
+
DiagnosticIssue,
|
|
19
|
+
ProvenanceEvidence,
|
|
20
|
+
SourceLocation,
|
|
21
|
+
)
|
|
22
|
+
from structa_maestro.documents.models import DocumentSegment, PreparedDocument
|
|
23
|
+
from structa_maestro.strategies.base import ProposedEvidence
|
|
24
|
+
|
|
25
|
+
_MAX_EXCERPT_CHARS = 500
|
|
26
|
+
_WHITESPACE_RE = re.compile(r"\s+")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True, slots=True)
|
|
30
|
+
class ProvenanceAssociationResult:
|
|
31
|
+
"""Verified provenance entries and provenance-stage warnings for one extracted field."""
|
|
32
|
+
|
|
33
|
+
evidence: list[ProvenanceEvidence] = field(default_factory=list)
|
|
34
|
+
warnings: list[DiagnosticIssue] = field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _collapse_ws(text: str) -> str:
|
|
38
|
+
return _WHITESPACE_RE.sub(" ", text).strip()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _find_span(full_text: str, quote: str) -> tuple[int, int] | None:
|
|
42
|
+
if not quote or not quote.strip():
|
|
43
|
+
return None
|
|
44
|
+
idx = full_text.find(quote)
|
|
45
|
+
if idx != -1:
|
|
46
|
+
return idx, idx + len(quote)
|
|
47
|
+
|
|
48
|
+
# Fallback: whitespace-tolerant search preserving original offsets
|
|
49
|
+
tokens = _collapse_ws(quote).split(" ")
|
|
50
|
+
if not tokens:
|
|
51
|
+
return None
|
|
52
|
+
pattern = r"\s+".join(re.escape(tok) for tok in tokens)
|
|
53
|
+
match = re.search(pattern, full_text)
|
|
54
|
+
if match is not None:
|
|
55
|
+
return match.start(), match.end()
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _location_from_span(
|
|
60
|
+
segments: tuple[DocumentSegment, ...],
|
|
61
|
+
char_start: int,
|
|
62
|
+
char_end: int,
|
|
63
|
+
) -> SourceLocation:
|
|
64
|
+
overlapping = [
|
|
65
|
+
seg for seg in segments if seg.char_end >= char_start and seg.char_start <= char_end
|
|
66
|
+
]
|
|
67
|
+
if not overlapping:
|
|
68
|
+
return SourceLocation(char_start=char_start, char_end=char_end)
|
|
69
|
+
|
|
70
|
+
first = overlapping[0]
|
|
71
|
+
last = overlapping[-1]
|
|
72
|
+
line_start = first.line_start
|
|
73
|
+
line_end = last.line_end if last.line_end is not None else first.line_end
|
|
74
|
+
if line_start is not None and line_end is not None and line_end < line_start:
|
|
75
|
+
line_end = line_start
|
|
76
|
+
|
|
77
|
+
return SourceLocation(
|
|
78
|
+
page=first.page,
|
|
79
|
+
paragraph=first.paragraph,
|
|
80
|
+
line_start=line_start,
|
|
81
|
+
line_end=line_end,
|
|
82
|
+
char_start=char_start,
|
|
83
|
+
char_end=char_end,
|
|
84
|
+
section=first.heading,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _scalar_value_supported_by_excerpt(value: Any, excerpt: str) -> bool:
|
|
89
|
+
"""Verify whether a direct supporting excerpt plausibly supports a scalar extracted value."""
|
|
90
|
+
if value is None or isinstance(value, (bool, dict, list)):
|
|
91
|
+
return True
|
|
92
|
+
norm_excerpt = _collapse_ws(excerpt).lower()
|
|
93
|
+
if isinstance(value, str):
|
|
94
|
+
val = _collapse_ws(value).lower()
|
|
95
|
+
if not val:
|
|
96
|
+
return True
|
|
97
|
+
return val in norm_excerpt
|
|
98
|
+
if isinstance(value, Decimal):
|
|
99
|
+
candidates = {str(value), format(value.normalize(), "f")}
|
|
100
|
+
stripped_excerpt = norm_excerpt.replace(",", "")
|
|
101
|
+
return any(c.lower() in stripped_excerpt for c in candidates)
|
|
102
|
+
if isinstance(value, int):
|
|
103
|
+
stripped_excerpt = norm_excerpt.replace(",", "")
|
|
104
|
+
return str(value) in stripped_excerpt
|
|
105
|
+
if isinstance(value, date):
|
|
106
|
+
return value.isoformat() in norm_excerpt or str(value.year) in norm_excerpt
|
|
107
|
+
return True
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _parse_relationship(raw: str) -> EvidenceRelationship:
|
|
111
|
+
try:
|
|
112
|
+
return EvidenceRelationship(raw.lower())
|
|
113
|
+
except ValueError:
|
|
114
|
+
return EvidenceRelationship.DIRECT
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class ProvenanceAssociator:
|
|
118
|
+
"""Verifies candidate source quotes against PreparedDocument without fabricating locations."""
|
|
119
|
+
|
|
120
|
+
def __init__(self, *, max_excerpt_chars: int = _MAX_EXCERPT_CHARS) -> None:
|
|
121
|
+
self._max_excerpt_chars = max_excerpt_chars
|
|
122
|
+
|
|
123
|
+
def associate(
|
|
124
|
+
self,
|
|
125
|
+
*,
|
|
126
|
+
document: PreparedDocument,
|
|
127
|
+
proposed_evidence: tuple[ProposedEvidence, ...],
|
|
128
|
+
field_name: str,
|
|
129
|
+
presence: FieldPresence,
|
|
130
|
+
value: Any,
|
|
131
|
+
record_id: str,
|
|
132
|
+
) -> ProvenanceAssociationResult:
|
|
133
|
+
"""Associate and verify zero, one, or multiple evidence passages for one field."""
|
|
134
|
+
if not proposed_evidence:
|
|
135
|
+
return ProvenanceAssociationResult()
|
|
136
|
+
|
|
137
|
+
doc_id = document.source.document_id
|
|
138
|
+
verified: list[ProvenanceEvidence] = []
|
|
139
|
+
warnings: list[DiagnosticIssue] = []
|
|
140
|
+
|
|
141
|
+
for item in proposed_evidence:
|
|
142
|
+
# PRO-010: Reject evidence explicitly attributed to a foreign document
|
|
143
|
+
if item.source_document_id is not None and item.source_document_id != doc_id:
|
|
144
|
+
warnings.append(
|
|
145
|
+
DiagnosticIssue(
|
|
146
|
+
code="cross_document_evidence_rejected",
|
|
147
|
+
severity=IssueSeverity.WARNING,
|
|
148
|
+
stage=PipelineStage.PROVENANCE,
|
|
149
|
+
message=(
|
|
150
|
+
f"Rejected provenance referencing foreign document for field "
|
|
151
|
+
f"'{field_name}'."
|
|
152
|
+
),
|
|
153
|
+
record_id=record_id,
|
|
154
|
+
field_path=field_name,
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
continue
|
|
158
|
+
|
|
159
|
+
quote = item.quote.strip()
|
|
160
|
+
if not quote:
|
|
161
|
+
continue
|
|
162
|
+
|
|
163
|
+
requested_rel = _parse_relationship(item.relationship)
|
|
164
|
+
span = _find_span(document.full_text, quote)
|
|
165
|
+
|
|
166
|
+
if span is None:
|
|
167
|
+
# Quote does not appear in source document — never fabricate a location!
|
|
168
|
+
excerpt, truncated = self._bound_excerpt(quote)
|
|
169
|
+
verified.append(
|
|
170
|
+
ProvenanceEvidence(
|
|
171
|
+
source_document_id=doc_id,
|
|
172
|
+
location=None,
|
|
173
|
+
evidence=excerpt,
|
|
174
|
+
relationship=EvidenceRelationship.UNVERIFIED,
|
|
175
|
+
truncated=truncated,
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
warnings.append(
|
|
179
|
+
DiagnosticIssue(
|
|
180
|
+
code="unverified_evidence",
|
|
181
|
+
severity=IssueSeverity.WARNING,
|
|
182
|
+
stage=PipelineStage.PROVENANCE,
|
|
183
|
+
message=(
|
|
184
|
+
f"Proposed evidence for field '{field_name}' could not be located "
|
|
185
|
+
"in the source document."
|
|
186
|
+
),
|
|
187
|
+
record_id=record_id,
|
|
188
|
+
field_path=field_name,
|
|
189
|
+
)
|
|
190
|
+
)
|
|
191
|
+
continue
|
|
192
|
+
|
|
193
|
+
char_start, char_end = span
|
|
194
|
+
original_excerpt = document.full_text[char_start:char_end]
|
|
195
|
+
excerpt, truncated = self._bound_excerpt(original_excerpt)
|
|
196
|
+
location = _location_from_span(document.segments, char_start, char_end)
|
|
197
|
+
|
|
198
|
+
relationship = requested_rel
|
|
199
|
+
if (
|
|
200
|
+
presence == FieldPresence.PRESENT
|
|
201
|
+
and requested_rel == EvidenceRelationship.DIRECT
|
|
202
|
+
and not _scalar_value_supported_by_excerpt(value, original_excerpt)
|
|
203
|
+
):
|
|
204
|
+
relationship = EvidenceRelationship.CONFLICTING
|
|
205
|
+
warnings.append(
|
|
206
|
+
DiagnosticIssue(
|
|
207
|
+
code="evidence_value_conflict",
|
|
208
|
+
severity=IssueSeverity.WARNING,
|
|
209
|
+
stage=PipelineStage.PROVENANCE,
|
|
210
|
+
message=(
|
|
211
|
+
f"Cited direct evidence for field '{field_name}' does not match "
|
|
212
|
+
"the extracted value."
|
|
213
|
+
),
|
|
214
|
+
record_id=record_id,
|
|
215
|
+
field_path=field_name,
|
|
216
|
+
)
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
verified.append(
|
|
220
|
+
ProvenanceEvidence(
|
|
221
|
+
source_document_id=doc_id,
|
|
222
|
+
location=location,
|
|
223
|
+
evidence=excerpt,
|
|
224
|
+
relationship=relationship,
|
|
225
|
+
truncated=truncated,
|
|
226
|
+
)
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
return ProvenanceAssociationResult(evidence=verified, warnings=warnings)
|
|
230
|
+
|
|
231
|
+
def _bound_excerpt(self, text: str) -> tuple[str, bool]:
|
|
232
|
+
if len(text) <= self._max_excerpt_chars:
|
|
233
|
+
return text, False
|
|
234
|
+
return text[: self._max_excerpt_chars], True
|
structa_maestro/py.typed
ADDED
|
File without changes
|