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,203 @@
|
|
|
1
|
+
"""Confidence assessment normalization enforcing range bounds and honest calibration semantics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
from structa_maestro.confidence.calibration import ConfidenceCalibrator, validate_calibrator
|
|
9
|
+
from structa_maestro.contracts.enums import IssueSeverity, PipelineStage
|
|
10
|
+
from structa_maestro.contracts.models import ConfidenceAssessment, DiagnosticIssue
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True)
|
|
14
|
+
class ConfidenceNormalizationResult:
|
|
15
|
+
"""Normalized ConfidenceAssessment plus any range/metadata/calibration warnings."""
|
|
16
|
+
|
|
17
|
+
confidence: ConfidenceAssessment | None
|
|
18
|
+
warnings: list[DiagnosticIssue] = field(default_factory=list)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ConfidenceNormalizer:
|
|
22
|
+
"""Enforces ConfidenceAssessment bounds, uncalibrated defaults, and optional calibration."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, *, calibrator: ConfidenceCalibrator | None = None) -> None:
|
|
25
|
+
self._calibrator = validate_calibrator(calibrator)
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def calibrator(self) -> ConfidenceCalibrator | None:
|
|
29
|
+
"""Optional fitted empirical calibrator applied to valid matching-scale scores."""
|
|
30
|
+
return self._calibrator
|
|
31
|
+
|
|
32
|
+
def normalize(
|
|
33
|
+
self,
|
|
34
|
+
*,
|
|
35
|
+
raw_value: float | None,
|
|
36
|
+
scale: str = "0-1",
|
|
37
|
+
method: str | None = None,
|
|
38
|
+
record_id: str | None = None,
|
|
39
|
+
field_path: str | None = None,
|
|
40
|
+
default_method: str = "extraction-assessment",
|
|
41
|
+
calibrator: ConfidenceCalibrator | None = None,
|
|
42
|
+
) -> ConfidenceNormalizationResult:
|
|
43
|
+
"""Normalize raw confidence metadata honestly, applying calibration only when warranted."""
|
|
44
|
+
active_calibrator = (
|
|
45
|
+
validate_calibrator(calibrator) if calibrator is not None else self._calibrator
|
|
46
|
+
)
|
|
47
|
+
clean_scale = scale.strip() if isinstance(scale, str) and scale.strip() else "0-1"
|
|
48
|
+
clean_method = (
|
|
49
|
+
method.strip()
|
|
50
|
+
if isinstance(method, str) and method.strip()
|
|
51
|
+
else (default_method or "unknown")
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
if raw_value is None:
|
|
55
|
+
return ConfidenceNormalizationResult(confidence=None)
|
|
56
|
+
|
|
57
|
+
if isinstance(raw_value, bool) or not isinstance(raw_value, (int, float)):
|
|
58
|
+
return ConfidenceNormalizationResult(
|
|
59
|
+
confidence=ConfidenceAssessment(
|
|
60
|
+
value=None,
|
|
61
|
+
scale=clean_scale,
|
|
62
|
+
method=clean_method,
|
|
63
|
+
calibrated=False,
|
|
64
|
+
),
|
|
65
|
+
warnings=[
|
|
66
|
+
DiagnosticIssue(
|
|
67
|
+
code="invalid_confidence_value",
|
|
68
|
+
severity=IssueSeverity.WARNING,
|
|
69
|
+
stage=PipelineStage.EXTRACTION,
|
|
70
|
+
message=(
|
|
71
|
+
f"Non-numeric confidence hint for field '{field_path}' was ignored."
|
|
72
|
+
),
|
|
73
|
+
record_id=record_id,
|
|
74
|
+
field_path=field_path,
|
|
75
|
+
)
|
|
76
|
+
],
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
numeric = float(raw_value)
|
|
80
|
+
if math.isnan(numeric) or math.isinf(numeric):
|
|
81
|
+
return ConfidenceNormalizationResult(
|
|
82
|
+
confidence=ConfidenceAssessment(
|
|
83
|
+
value=None,
|
|
84
|
+
scale=clean_scale,
|
|
85
|
+
method=clean_method,
|
|
86
|
+
calibrated=False,
|
|
87
|
+
),
|
|
88
|
+
warnings=[
|
|
89
|
+
DiagnosticIssue(
|
|
90
|
+
code="invalid_confidence_range",
|
|
91
|
+
severity=IssueSeverity.WARNING,
|
|
92
|
+
stage=PipelineStage.EXTRACTION,
|
|
93
|
+
message=f"Non-finite confidence score for field '{field_path}' discarded.",
|
|
94
|
+
record_id=record_id,
|
|
95
|
+
field_path=field_path,
|
|
96
|
+
)
|
|
97
|
+
],
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
if clean_scale == "0-1" and not (0.0 <= numeric <= 1.0):
|
|
101
|
+
return ConfidenceNormalizationResult(
|
|
102
|
+
confidence=ConfidenceAssessment(
|
|
103
|
+
value=None,
|
|
104
|
+
scale=clean_scale,
|
|
105
|
+
method=clean_method,
|
|
106
|
+
calibrated=False,
|
|
107
|
+
),
|
|
108
|
+
warnings=[
|
|
109
|
+
DiagnosticIssue(
|
|
110
|
+
code="invalid_confidence_range",
|
|
111
|
+
severity=IssueSeverity.WARNING,
|
|
112
|
+
stage=PipelineStage.EXTRACTION,
|
|
113
|
+
message=(
|
|
114
|
+
f"Confidence value for field '{field_path}' fell outside declared "
|
|
115
|
+
"scale '0-1' and was marked unavailable."
|
|
116
|
+
),
|
|
117
|
+
record_id=record_id,
|
|
118
|
+
field_path=field_path,
|
|
119
|
+
)
|
|
120
|
+
],
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
base_value = round(numeric, 6)
|
|
124
|
+
if active_calibrator is None:
|
|
125
|
+
return ConfidenceNormalizationResult(
|
|
126
|
+
confidence=ConfidenceAssessment(
|
|
127
|
+
value=base_value,
|
|
128
|
+
scale=clean_scale,
|
|
129
|
+
method=clean_method,
|
|
130
|
+
calibrated=False,
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
calibrator_scale = active_calibrator.scale.strip()
|
|
135
|
+
if clean_scale != calibrator_scale:
|
|
136
|
+
return ConfidenceNormalizationResult(
|
|
137
|
+
confidence=ConfidenceAssessment(
|
|
138
|
+
value=base_value,
|
|
139
|
+
scale=clean_scale,
|
|
140
|
+
method=clean_method,
|
|
141
|
+
calibrated=False,
|
|
142
|
+
),
|
|
143
|
+
warnings=[
|
|
144
|
+
DiagnosticIssue(
|
|
145
|
+
code="confidence_calibration_scale_mismatch",
|
|
146
|
+
severity=IssueSeverity.WARNING,
|
|
147
|
+
stage=PipelineStage.EXTRACTION,
|
|
148
|
+
message=(
|
|
149
|
+
f"Confidence calibration skipped for field '{field_path}' because "
|
|
150
|
+
f"scale '{clean_scale}' does not match calibrator scale "
|
|
151
|
+
f"'{calibrator_scale}'."
|
|
152
|
+
),
|
|
153
|
+
record_id=record_id,
|
|
154
|
+
field_path=field_path,
|
|
155
|
+
)
|
|
156
|
+
],
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
try:
|
|
160
|
+
raw_cal = active_calibrator.calibrate(numeric)
|
|
161
|
+
if isinstance(raw_cal, bool) or not isinstance(raw_cal, (int, float)):
|
|
162
|
+
raise ValueError("Calibrator returned non-numeric value.")
|
|
163
|
+
cal_val = float(raw_cal)
|
|
164
|
+
if not math.isfinite(cal_val) or not (0.0 <= cal_val <= 1.0):
|
|
165
|
+
raise ValueError("Calibrator returned out-of-bounds value.")
|
|
166
|
+
cal_method_tag = active_calibrator.method.strip()
|
|
167
|
+
if not cal_method_tag:
|
|
168
|
+
raise ValueError("Calibrator method must be non-empty.")
|
|
169
|
+
except Exception:
|
|
170
|
+
return ConfidenceNormalizationResult(
|
|
171
|
+
confidence=ConfidenceAssessment(
|
|
172
|
+
value=base_value,
|
|
173
|
+
scale=clean_scale,
|
|
174
|
+
method=clean_method,
|
|
175
|
+
calibrated=False,
|
|
176
|
+
),
|
|
177
|
+
warnings=[
|
|
178
|
+
DiagnosticIssue(
|
|
179
|
+
code="confidence_calibration_failed",
|
|
180
|
+
severity=IssueSeverity.WARNING,
|
|
181
|
+
stage=PipelineStage.EXTRACTION,
|
|
182
|
+
message=(
|
|
183
|
+
f"Confidence calibration failed for field '{field_path}'; "
|
|
184
|
+
"preserved uncalibrated confidence score."
|
|
185
|
+
),
|
|
186
|
+
record_id=record_id,
|
|
187
|
+
field_path=field_path,
|
|
188
|
+
)
|
|
189
|
+
],
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
suffix = f"+calibrated:{cal_method_tag}"
|
|
193
|
+
calibrated_method = (
|
|
194
|
+
clean_method if clean_method.endswith(suffix) else f"{clean_method}{suffix}"
|
|
195
|
+
)
|
|
196
|
+
return ConfidenceNormalizationResult(
|
|
197
|
+
confidence=ConfidenceAssessment(
|
|
198
|
+
value=round(cal_val, 6),
|
|
199
|
+
scale=clean_scale,
|
|
200
|
+
method=calibrated_method,
|
|
201
|
+
calibrated=True,
|
|
202
|
+
)
|
|
203
|
+
)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Configuration models, resource limits, secret masking, and privacy-safe logging helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
from structa_maestro.exceptions import ConfigurationError
|
|
11
|
+
|
|
12
|
+
_DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024 # 25 MB
|
|
13
|
+
_DEFAULT_MAX_DECOMPRESSED_BYTES = 50 * 1024 * 1024 # 50 MB
|
|
14
|
+
_DEFAULT_MAX_PAGES = 200
|
|
15
|
+
|
|
16
|
+
_SECRET_PATTERNS: tuple[re.Pattern[str], ...] = (
|
|
17
|
+
re.compile(r"(?i)(bearer\s+)[A-Za-z0-9._\-+/=]{8,}"),
|
|
18
|
+
re.compile(r"\bsk-[A-Za-z0-9_\-]{8,}\b"),
|
|
19
|
+
re.compile(r"(?i)(api[_-]?key\s*[:=]\s*['\"]?)([^\s'\",;}{]{6,})"),
|
|
20
|
+
re.compile(r"(?i)(authorization\s*[:=]\s*['\"]?)([^\s'\",;}{]{6,})"),
|
|
21
|
+
re.compile(r"(?i)(x-api-key\s*[:=]\s*['\"]?)([^\s'\",;}{]{6,})"),
|
|
22
|
+
re.compile(r"(?i)(x-goog-api-key['\"]?\s*[:=]\s*['\"]?)([^\s'\",;}{]{6,})"),
|
|
23
|
+
re.compile(r"\bAIza[0-9A-Za-z_\-]{16,}\b"),
|
|
24
|
+
re.compile(r"(?i)([?&]key=)([^&\s'\"#]{6,})"),
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class DocumentLimits:
|
|
30
|
+
"""Configurable safety limits enforced during document input and parsing.
|
|
31
|
+
|
|
32
|
+
Canonical fields per specs/001-structured-extraction-mvp/data-model.md Section 2.1:
|
|
33
|
+
- DocumentLimits.max_file_bytes
|
|
34
|
+
- DocumentLimits.max_decompressed_bytes
|
|
35
|
+
- DocumentLimits.max_pages
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
max_file_bytes: int = _DEFAULT_MAX_FILE_BYTES
|
|
39
|
+
max_decompressed_bytes: int = _DEFAULT_MAX_DECOMPRESSED_BYTES
|
|
40
|
+
max_pages: int = _DEFAULT_MAX_PAGES
|
|
41
|
+
|
|
42
|
+
def __post_init__(self) -> None:
|
|
43
|
+
if isinstance(self.max_file_bytes, bool) or self.max_file_bytes <= 0:
|
|
44
|
+
raise ConfigurationError("DocumentLimits.max_file_bytes must be a positive integer.")
|
|
45
|
+
if isinstance(self.max_decompressed_bytes, bool) or self.max_decompressed_bytes <= 0:
|
|
46
|
+
raise ConfigurationError(
|
|
47
|
+
"DocumentLimits.max_decompressed_bytes must be a positive integer."
|
|
48
|
+
)
|
|
49
|
+
if isinstance(self.max_pages, bool) or self.max_pages <= 0:
|
|
50
|
+
raise ConfigurationError("DocumentLimits.max_pages must be a positive integer.")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SecretValue:
|
|
54
|
+
"""Redacted container for API keys and credentials preventing accidental leakage."""
|
|
55
|
+
|
|
56
|
+
__slots__ = ("_value",)
|
|
57
|
+
|
|
58
|
+
def __init__(self, value: str) -> None:
|
|
59
|
+
if not isinstance(value, str) or not value.strip():
|
|
60
|
+
raise ConfigurationError("SecretValue requires a non-empty string.")
|
|
61
|
+
self._value = value
|
|
62
|
+
|
|
63
|
+
def get_secret_value(self) -> str:
|
|
64
|
+
"""Return the underlying raw secret value for authorized internal use."""
|
|
65
|
+
return self._value
|
|
66
|
+
|
|
67
|
+
def __repr__(self) -> str:
|
|
68
|
+
return "SecretValue('***')"
|
|
69
|
+
|
|
70
|
+
def __str__(self) -> str:
|
|
71
|
+
return "***"
|
|
72
|
+
|
|
73
|
+
def __eq__(self, other: object) -> bool:
|
|
74
|
+
if isinstance(other, SecretValue):
|
|
75
|
+
return self._value == other._value
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
def __hash__(self) -> int:
|
|
79
|
+
return hash(self._value)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def sanitize_message(
|
|
83
|
+
message: str,
|
|
84
|
+
*,
|
|
85
|
+
secrets: Iterable[str] = (),
|
|
86
|
+
max_length: int = 500,
|
|
87
|
+
) -> str:
|
|
88
|
+
"""Scrub known secrets and credential patterns from diagnostic messages."""
|
|
89
|
+
sanitized = message
|
|
90
|
+
for secret in secrets:
|
|
91
|
+
if secret:
|
|
92
|
+
sanitized = sanitized.replace(secret, "[REDACTED]")
|
|
93
|
+
sanitized = _SECRET_PATTERNS[0].sub(r"\1[REDACTED]", sanitized)
|
|
94
|
+
sanitized = _SECRET_PATTERNS[1].sub("[REDACTED]", sanitized)
|
|
95
|
+
sanitized = _SECRET_PATTERNS[2].sub(r"\1[REDACTED]", sanitized)
|
|
96
|
+
sanitized = _SECRET_PATTERNS[3].sub(r"\1[REDACTED]", sanitized)
|
|
97
|
+
sanitized = _SECRET_PATTERNS[4].sub(r"\1[REDACTED]", sanitized)
|
|
98
|
+
sanitized = _SECRET_PATTERNS[5].sub(r"\1[REDACTED]", sanitized)
|
|
99
|
+
sanitized = _SECRET_PATTERNS[6].sub("[REDACTED]", sanitized)
|
|
100
|
+
sanitized = _SECRET_PATTERNS[7].sub(r"\1[REDACTED]", sanitized)
|
|
101
|
+
if len(sanitized) > max_length:
|
|
102
|
+
sanitized = sanitized[: max_length - 3] + "..."
|
|
103
|
+
return sanitized
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def get_logger(name: str) -> logging.Logger:
|
|
107
|
+
"""Return a library logger configured with a NullHandler (no default document logging)."""
|
|
108
|
+
root = logging.getLogger("structa_maestro")
|
|
109
|
+
if not root.handlers:
|
|
110
|
+
root.addHandler(logging.NullHandler())
|
|
111
|
+
return logging.getLogger(name)
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Canonical enumerations for structa-maestro (data-model.md Section 1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DocumentFormat(StrEnum):
|
|
9
|
+
"""Supported input document formats."""
|
|
10
|
+
|
|
11
|
+
TXT = "txt"
|
|
12
|
+
PDF = "pdf"
|
|
13
|
+
DOCX = "docx"
|
|
14
|
+
HTML = "html"
|
|
15
|
+
MARKDOWN = "markdown"
|
|
16
|
+
EML = "eml"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class FieldType(StrEnum):
|
|
20
|
+
"""Supported MVP schema field data types."""
|
|
21
|
+
|
|
22
|
+
STRING = "string"
|
|
23
|
+
INTEGER = "integer"
|
|
24
|
+
DECIMAL = "decimal"
|
|
25
|
+
BOOLEAN = "boolean"
|
|
26
|
+
DATE = "date"
|
|
27
|
+
ARRAY = "array"
|
|
28
|
+
OBJECT = "object"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ExtractionCardinality(StrEnum):
|
|
32
|
+
"""Whether a schema targets a single record or multiple records per document."""
|
|
33
|
+
|
|
34
|
+
SINGLE = "single"
|
|
35
|
+
MULTIPLE = "multiple"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ProcessingStatus(StrEnum):
|
|
39
|
+
"""Operational completion state of an extraction or record."""
|
|
40
|
+
|
|
41
|
+
COMPLETED = "completed"
|
|
42
|
+
PARTIAL = "partial"
|
|
43
|
+
FAILED = "failed"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ValidationStatus(StrEnum):
|
|
47
|
+
"""Schema validation outcome of a field, record, or overall result."""
|
|
48
|
+
|
|
49
|
+
VALID = "valid"
|
|
50
|
+
INVALID = "invalid"
|
|
51
|
+
NOT_VALIDATED = "not_validated"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class FieldPresence(StrEnum):
|
|
55
|
+
"""Distinguishes an absent/unfound field from an explicitly extracted null or empty value."""
|
|
56
|
+
|
|
57
|
+
PRESENT = "present"
|
|
58
|
+
MISSING = "missing"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class EvidenceRelationship(StrEnum):
|
|
62
|
+
"""Relationship between a cited source excerpt and an extracted field value."""
|
|
63
|
+
|
|
64
|
+
DIRECT = "direct"
|
|
65
|
+
INFERRED = "inferred"
|
|
66
|
+
CONFLICTING = "conflicting"
|
|
67
|
+
UNVERIFIED = "unverified"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class IssueSeverity(StrEnum):
|
|
71
|
+
"""Diagnostic severity separating blocking errors from non-invalidating warnings."""
|
|
72
|
+
|
|
73
|
+
ERROR = "error"
|
|
74
|
+
WARNING = "warning"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class PipelineStage(StrEnum):
|
|
78
|
+
"""Originating processing stage for classified diagnostic issues."""
|
|
79
|
+
|
|
80
|
+
INPUT = "input"
|
|
81
|
+
DOCUMENT_PROCESSING = "document_processing"
|
|
82
|
+
SCHEMA = "schema"
|
|
83
|
+
EXTRACTION = "extraction"
|
|
84
|
+
PROVENANCE = "provenance"
|
|
85
|
+
VALIDATION = "validation"
|
|
86
|
+
SERIALIZATION = "serialization"
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Canonical Output Record Contract v1.0 models (data-model.md Sections 2.2 & 3.1-3.8)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
9
|
+
|
|
10
|
+
from structa_maestro.contracts.enums import (
|
|
11
|
+
EvidenceRelationship,
|
|
12
|
+
FieldPresence,
|
|
13
|
+
FieldType,
|
|
14
|
+
IssueSeverity,
|
|
15
|
+
PipelineStage,
|
|
16
|
+
ProcessingStatus,
|
|
17
|
+
ValidationStatus,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
CONTRACT_VERSION: Literal["1.0"] = "1.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _ContractModel(BaseModel):
|
|
24
|
+
model_config = ConfigDict(
|
|
25
|
+
frozen=True,
|
|
26
|
+
extra="forbid",
|
|
27
|
+
populate_by_name=True,
|
|
28
|
+
ser_json_timedelta="iso8601",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SourceMetadata(_ContractModel):
|
|
33
|
+
"""Public source document identity (data-model.md Section 2.2)."""
|
|
34
|
+
|
|
35
|
+
document_id: str = Field(min_length=1)
|
|
36
|
+
filename: str | None = None
|
|
37
|
+
media_type: str | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SchemaMetadata(_ContractModel):
|
|
41
|
+
"""Public schema identity (data-model.md Section 3.8)."""
|
|
42
|
+
|
|
43
|
+
schema_id: str = Field(min_length=1)
|
|
44
|
+
schema_version: str = Field(min_length=1)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SourceLocation(_ContractModel):
|
|
48
|
+
"""Optional granular location within the originating document (data-model.md Section 3.1)."""
|
|
49
|
+
|
|
50
|
+
page: int | None = Field(default=None, ge=1)
|
|
51
|
+
paragraph: int | None = Field(default=None, ge=1)
|
|
52
|
+
line_start: int | None = Field(default=None, ge=1)
|
|
53
|
+
line_end: int | None = Field(default=None, ge=1)
|
|
54
|
+
char_start: int | None = Field(default=None, ge=0)
|
|
55
|
+
char_end: int | None = Field(default=None, ge=0)
|
|
56
|
+
section: str | None = None
|
|
57
|
+
|
|
58
|
+
@model_validator(mode="after")
|
|
59
|
+
def _check_spans(self) -> SourceLocation:
|
|
60
|
+
if (
|
|
61
|
+
self.line_start is not None
|
|
62
|
+
and self.line_end is not None
|
|
63
|
+
and self.line_end < self.line_start
|
|
64
|
+
):
|
|
65
|
+
raise ValueError("SourceLocation.line_end must be >= line_start.")
|
|
66
|
+
if (
|
|
67
|
+
self.char_start is not None
|
|
68
|
+
and self.char_end is not None
|
|
69
|
+
and self.char_end < self.char_start
|
|
70
|
+
):
|
|
71
|
+
raise ValueError("SourceLocation.char_end must be >= char_start.")
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ProvenanceEvidence(_ContractModel):
|
|
76
|
+
"""Supporting source evidence linked to an extracted field (data-model.md Section 3.2)."""
|
|
77
|
+
|
|
78
|
+
source_document_id: str = Field(min_length=1)
|
|
79
|
+
location: SourceLocation | None = None
|
|
80
|
+
evidence: str
|
|
81
|
+
relationship: EvidenceRelationship
|
|
82
|
+
truncated: bool = False
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ConfidenceAssessment(_ContractModel):
|
|
86
|
+
"""Explicit reliability assessment independent of validation (data-model.md Section 3.3)."""
|
|
87
|
+
|
|
88
|
+
value: float | None = None
|
|
89
|
+
scale: str = Field(default="0-1", min_length=1)
|
|
90
|
+
method: str = Field(default="extraction-assessment", min_length=1)
|
|
91
|
+
calibrated: bool = False
|
|
92
|
+
|
|
93
|
+
@model_validator(mode="after")
|
|
94
|
+
def _check_value_bounds(self) -> ConfidenceAssessment:
|
|
95
|
+
if self.value is not None and self.scale == "0-1" and not (0.0 <= self.value <= 1.0):
|
|
96
|
+
raise ValueError("ConfidenceAssessment.value must be within [0.0, 1.0] for scale 0-1.")
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class DiagnosticIssue(_ContractModel):
|
|
101
|
+
"""Structured, privacy-safe error or warning (data-model.md Section 3.4)."""
|
|
102
|
+
|
|
103
|
+
code: str = Field(min_length=1)
|
|
104
|
+
severity: IssueSeverity
|
|
105
|
+
stage: PipelineStage
|
|
106
|
+
message: str = Field(min_length=1)
|
|
107
|
+
record_id: str | None = None
|
|
108
|
+
field_path: str | None = None
|
|
109
|
+
expected: str | None = None
|
|
110
|
+
actual: str | None = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ValidationOutcome(_ContractModel):
|
|
114
|
+
"""Independent structural and constraint validation result (data-model.md Section 3.5)."""
|
|
115
|
+
|
|
116
|
+
status: ValidationStatus
|
|
117
|
+
errors: list[DiagnosticIssue] = Field(default_factory=list)
|
|
118
|
+
|
|
119
|
+
@model_validator(mode="after")
|
|
120
|
+
def _check_validation_errors(self) -> ValidationOutcome:
|
|
121
|
+
for err in self.errors:
|
|
122
|
+
if err.severity != IssueSeverity.ERROR or err.stage != PipelineStage.VALIDATION:
|
|
123
|
+
raise ValueError(
|
|
124
|
+
"ValidationOutcome.errors must contain only validation-stage errors."
|
|
125
|
+
)
|
|
126
|
+
if self.status != ValidationStatus.INVALID and self.errors:
|
|
127
|
+
raise ValueError("ValidationOutcome.errors must be empty unless status is 'invalid'.")
|
|
128
|
+
return self
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class ExtractedField(_ContractModel):
|
|
132
|
+
"""Single extracted field with independent quality dimensions (data-model.md Section 3.6)."""
|
|
133
|
+
|
|
134
|
+
presence: FieldPresence
|
|
135
|
+
value: Any = None
|
|
136
|
+
value_type: FieldType | None = None
|
|
137
|
+
confidence: ConfidenceAssessment | None = None
|
|
138
|
+
provenance: list[ProvenanceEvidence] = Field(default_factory=list)
|
|
139
|
+
validation: ValidationOutcome
|
|
140
|
+
errors: list[DiagnosticIssue] = Field(default_factory=list)
|
|
141
|
+
warnings: list[DiagnosticIssue] = Field(default_factory=list)
|
|
142
|
+
|
|
143
|
+
@model_validator(mode="after")
|
|
144
|
+
def _check_presence_value(self) -> ExtractedField:
|
|
145
|
+
if self.presence == FieldPresence.MISSING and self.value is not None:
|
|
146
|
+
raise ValueError("ExtractedField.value must be None when presence is 'missing'.")
|
|
147
|
+
return self
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class ExtractedRecord(_ContractModel):
|
|
151
|
+
"""Single bounded structured record within an extraction result (data-model.md Section 3.7)."""
|
|
152
|
+
|
|
153
|
+
record_id: str = Field(min_length=1)
|
|
154
|
+
status: ProcessingStatus
|
|
155
|
+
fields: dict[str, ExtractedField] = Field(default_factory=dict)
|
|
156
|
+
validation: ValidationOutcome
|
|
157
|
+
errors: list[DiagnosticIssue] = Field(default_factory=list)
|
|
158
|
+
warnings: list[DiagnosticIssue] = Field(default_factory=list)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class ExtractionResult(_ContractModel):
|
|
162
|
+
"""Top-level Canonical Output Record Contract v1.0 (data-model.md Section 3.8).
|
|
163
|
+
|
|
164
|
+
Uses ``schema_metadata`` with ``alias="schema"`` so canonical JSON uses the exact
|
|
165
|
+
``"schema"`` key without shadowing Pydantic v2's deprecated ``BaseModel.schema()``.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
contract_version: Literal["1.0"] = CONTRACT_VERSION
|
|
169
|
+
extraction_id: str = Field(default_factory=lambda: str(uuid4()), min_length=1)
|
|
170
|
+
status: ProcessingStatus
|
|
171
|
+
source: SourceMetadata | None = None
|
|
172
|
+
schema_metadata: SchemaMetadata = Field(
|
|
173
|
+
validation_alias=AliasChoices("schema", "schema_metadata"),
|
|
174
|
+
serialization_alias="schema",
|
|
175
|
+
)
|
|
176
|
+
records: list[ExtractedRecord] = Field(default_factory=list)
|
|
177
|
+
validation: ValidationOutcome
|
|
178
|
+
errors: list[DiagnosticIssue] = Field(default_factory=list)
|
|
179
|
+
warnings: list[DiagnosticIssue] = Field(default_factory=list)
|
|
180
|
+
|
|
181
|
+
@field_validator("records")
|
|
182
|
+
@classmethod
|
|
183
|
+
def _check_unique_record_ids(cls, value: list[ExtractedRecord]) -> list[ExtractedRecord]:
|
|
184
|
+
seen: set[str] = set()
|
|
185
|
+
for rec in value:
|
|
186
|
+
if rec.record_id in seen:
|
|
187
|
+
raise ValueError(f"Duplicate record_id detected: {rec.record_id!r}")
|
|
188
|
+
seen.add(rec.record_id)
|
|
189
|
+
return value
|
|
190
|
+
|
|
191
|
+
@model_validator(mode="after")
|
|
192
|
+
def _check_provenance_source_binding(self) -> ExtractionResult:
|
|
193
|
+
if self.source is not None:
|
|
194
|
+
expected_doc_id = self.source.document_id
|
|
195
|
+
for record in self.records:
|
|
196
|
+
for field_name, extracted_field in record.fields.items():
|
|
197
|
+
for ev in extracted_field.provenance:
|
|
198
|
+
if ev.source_document_id != expected_doc_id:
|
|
199
|
+
raise ValueError(
|
|
200
|
+
f"Provenance for field {field_name!r} references foreign "
|
|
201
|
+
f"document_id {ev.source_document_id!r} != {expected_doc_id!r}."
|
|
202
|
+
)
|
|
203
|
+
return self
|
|
204
|
+
|
|
205
|
+
def to_dict(self) -> dict[str, Any]:
|
|
206
|
+
"""Serialize this result to a canonical JSON-compatible dictionary."""
|
|
207
|
+
from structa_maestro.contracts.serialization import serialize_result_to_dict
|
|
208
|
+
|
|
209
|
+
return serialize_result_to_dict(self)
|
|
210
|
+
|
|
211
|
+
def to_json(self, *, indent: int | None = None) -> str:
|
|
212
|
+
"""Serialize this result to canonical UTF-8 JSON."""
|
|
213
|
+
from structa_maestro.contracts.serialization import serialize_result_to_json
|
|
214
|
+
|
|
215
|
+
return serialize_result_to_json(self, indent=indent)
|
|
216
|
+
|
|
217
|
+
@classmethod
|
|
218
|
+
def from_dict(cls, data: dict[str, Any]) -> ExtractionResult:
|
|
219
|
+
"""Strictly deserialize a canonical dictionary into an ExtractionResult."""
|
|
220
|
+
from structa_maestro.contracts.serialization import deserialize_result_from_dict
|
|
221
|
+
|
|
222
|
+
return deserialize_result_from_dict(data)
|
|
223
|
+
|
|
224
|
+
@classmethod
|
|
225
|
+
def from_json(cls, raw_json: str) -> ExtractionResult:
|
|
226
|
+
"""Strictly deserialize canonical JSON into an ExtractionResult."""
|
|
227
|
+
from structa_maestro.contracts.serialization import deserialize_result_from_json
|
|
228
|
+
|
|
229
|
+
return deserialize_result_from_json(raw_json)
|