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,206 @@
|
|
|
1
|
+
"""Strict, non-coercing opt-in binding of canonical ExtractedRecords to Pydantic v2 models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import types
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from typing import Annotated, Any, TypeVar, Union, get_args, get_origin
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ValidationError
|
|
11
|
+
|
|
12
|
+
from structa_maestro.contracts.enums import FieldPresence, ProcessingStatus, ValidationStatus
|
|
13
|
+
from structa_maestro.contracts.models import ExtractedRecord, ExtractionResult
|
|
14
|
+
from structa_maestro.exceptions import RecordBindingError
|
|
15
|
+
|
|
16
|
+
TModel = TypeVar("TModel", bound=BaseModel)
|
|
17
|
+
_UNION_ORIGINS = (Union, types.UnionType)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _unwrap_target_annotation(annotation: Any) -> Any:
|
|
21
|
+
"""Unwrap Annotated[...] and Optional[T] / T | None to inspect the concrete target type."""
|
|
22
|
+
current = annotation
|
|
23
|
+
while get_origin(current) is Annotated:
|
|
24
|
+
current = get_args(current)[0]
|
|
25
|
+
origin = get_origin(current)
|
|
26
|
+
if origin in _UNION_ORIGINS:
|
|
27
|
+
non_none = [arg for arg in get_args(current) if arg is not type(None)]
|
|
28
|
+
if len(non_none) == 1:
|
|
29
|
+
current = non_none[0]
|
|
30
|
+
while get_origin(current) is Annotated:
|
|
31
|
+
current = get_args(current)[0]
|
|
32
|
+
return current
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _adapt_value_for_annotation(value: Any, annotation: Any) -> Any:
|
|
36
|
+
"""Adapt validated canonical values for strict Pydantic v2 validation without coercion.
|
|
37
|
+
|
|
38
|
+
Only performs lossless structural/representation adaptations required by Pydantic's strict mode:
|
|
39
|
+
- Exact-type primitive -> Enum member matching ``member.value == value`` and exact runtime type.
|
|
40
|
+
- Finite ``Decimal`` -> ``float`` for fields explicitly annotated as ``float``.
|
|
41
|
+
- Non-bool ``int`` -> ``Decimal`` for fields explicitly annotated as ``Decimal``.
|
|
42
|
+
- Recursive adaptation across nested ``BaseModel`` dicts and ``list[T]`` items.
|
|
43
|
+
Strings, booleans, and mismatched types are never coerced.
|
|
44
|
+
"""
|
|
45
|
+
if value is None:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
target = _unwrap_target_annotation(annotation)
|
|
49
|
+
origin = get_origin(target)
|
|
50
|
+
|
|
51
|
+
if origin is list:
|
|
52
|
+
if isinstance(value, list):
|
|
53
|
+
args = get_args(target)
|
|
54
|
+
if len(args) == 1:
|
|
55
|
+
return [_adapt_value_for_annotation(item, args[0]) for item in value]
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
if isinstance(target, type):
|
|
59
|
+
if issubclass(target, BaseModel):
|
|
60
|
+
if isinstance(value, dict):
|
|
61
|
+
return _adapt_model_dict(value, target)
|
|
62
|
+
return value
|
|
63
|
+
|
|
64
|
+
if issubclass(target, Enum):
|
|
65
|
+
if isinstance(value, target):
|
|
66
|
+
return value
|
|
67
|
+
for member in target:
|
|
68
|
+
if type(member.value) is type(value) and member.value == value:
|
|
69
|
+
return member
|
|
70
|
+
return value
|
|
71
|
+
|
|
72
|
+
if target is float:
|
|
73
|
+
if isinstance(value, Decimal) and not value.is_nan() and not value.is_infinite():
|
|
74
|
+
return float(value)
|
|
75
|
+
return value
|
|
76
|
+
|
|
77
|
+
if target is Decimal:
|
|
78
|
+
if not isinstance(value, bool) and isinstance(value, int):
|
|
79
|
+
return Decimal(value)
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
return value
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _adapt_model_dict(raw_dict: dict[str, Any], model_cls: type[BaseModel]) -> dict[str, Any]:
|
|
86
|
+
adapted: dict[str, Any] = {}
|
|
87
|
+
model_fields = model_cls.model_fields
|
|
88
|
+
for key, val in raw_dict.items():
|
|
89
|
+
if key in model_fields:
|
|
90
|
+
adapted[key] = _adapt_value_for_annotation(val, model_fields[key].annotation)
|
|
91
|
+
else:
|
|
92
|
+
adapted[key] = val
|
|
93
|
+
return adapted
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _build_record_payload(record: ExtractedRecord, model_cls: type[BaseModel]) -> dict[str, Any]:
|
|
97
|
+
"""Extract a binding payload preserving the missing-versus-null distinction."""
|
|
98
|
+
payload: dict[str, Any] = {}
|
|
99
|
+
model_fields = model_cls.model_fields
|
|
100
|
+
for field_name, extracted_field in record.fields.items():
|
|
101
|
+
if extracted_field.presence == FieldPresence.MISSING:
|
|
102
|
+
continue
|
|
103
|
+
if field_name in model_fields:
|
|
104
|
+
payload[field_name] = _adapt_value_for_annotation(
|
|
105
|
+
extracted_field.value,
|
|
106
|
+
model_fields[field_name].annotation,
|
|
107
|
+
)
|
|
108
|
+
else:
|
|
109
|
+
payload[field_name] = extracted_field.value
|
|
110
|
+
return payload
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _sanitize_pydantic_errors(exc: ValidationError) -> tuple[str, ...]:
|
|
114
|
+
"""Extract field locations and error types without ever echoing raw input values."""
|
|
115
|
+
issues: list[str] = []
|
|
116
|
+
for err in exc.errors(include_url=False, include_input=False):
|
|
117
|
+
loc_parts = [str(part) for part in err.get("loc", ())]
|
|
118
|
+
loc = ".".join(loc_parts) if loc_parts else "<root>"
|
|
119
|
+
err_type = str(err.get("type", "validation_error"))
|
|
120
|
+
# Use error type rather than raw msg if msg could echo unexpected data
|
|
121
|
+
issues.append(f"{loc}: {err_type}")
|
|
122
|
+
return tuple(issues)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _validate_model_cls(model_cls: Any) -> None:
|
|
126
|
+
if not (isinstance(model_cls, type) and issubclass(model_cls, BaseModel)):
|
|
127
|
+
raise RecordBindingError("model_cls must be a Pydantic v2 BaseModel subclass.")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def bind_record(record: ExtractedRecord, model_cls: type[TModel]) -> TModel:
|
|
131
|
+
"""Strictly materialize one completed, schema-valid ExtractedRecord into a Pydantic model.
|
|
132
|
+
|
|
133
|
+
Raises ``RecordBindingError`` (with privacy-safe field paths and zero raw values) if the
|
|
134
|
+
record is not completed/valid or fails strict Pydantic validation.
|
|
135
|
+
"""
|
|
136
|
+
_validate_model_cls(model_cls)
|
|
137
|
+
if not isinstance(record, ExtractedRecord):
|
|
138
|
+
raise RecordBindingError("record must be an ExtractedRecord instance.")
|
|
139
|
+
|
|
140
|
+
if record.status != ProcessingStatus.COMPLETED:
|
|
141
|
+
raise RecordBindingError(
|
|
142
|
+
f"Cannot bind record {record.record_id!r}: processing status is "
|
|
143
|
+
f"{record.status.value!r} (expected 'completed').",
|
|
144
|
+
record_id=record.record_id,
|
|
145
|
+
)
|
|
146
|
+
if record.validation.status != ValidationStatus.VALID:
|
|
147
|
+
raise RecordBindingError(
|
|
148
|
+
f"Cannot bind record {record.record_id!r}: validation status is "
|
|
149
|
+
f"{record.validation.status.value!r} (expected 'valid').",
|
|
150
|
+
record_id=record.record_id,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
payload = _build_record_payload(record, model_cls)
|
|
154
|
+
try:
|
|
155
|
+
return model_cls.model_validate(payload, strict=True)
|
|
156
|
+
except ValidationError as exc:
|
|
157
|
+
issues = _sanitize_pydantic_errors(exc)
|
|
158
|
+
summary = "; ".join(issues) if issues else "strict_validation_failed"
|
|
159
|
+
raise RecordBindingError(
|
|
160
|
+
f"Strict binding failed for record {record.record_id!r} against "
|
|
161
|
+
f"{model_cls.__name__}: {summary}.",
|
|
162
|
+
record_id=record.record_id,
|
|
163
|
+
issues=issues,
|
|
164
|
+
) from None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def bind_records(
|
|
168
|
+
result: ExtractionResult,
|
|
169
|
+
model_cls: type[TModel],
|
|
170
|
+
*,
|
|
171
|
+
only_valid: bool = False,
|
|
172
|
+
) -> list[TModel]:
|
|
173
|
+
"""Strictly materialize records from an ExtractionResult into typed Pydantic model instances.
|
|
174
|
+
|
|
175
|
+
- When ``only_valid=False`` (default): requires ``result.status == COMPLETED`` and
|
|
176
|
+
``result.validation.status == VALID``, raising ``RecordBindingError`` otherwise.
|
|
177
|
+
- When ``only_valid=True``: binds only records with ``status == COMPLETED`` and
|
|
178
|
+
``validation.status == VALID`` in exact canonical order, skipping invalid/failed records.
|
|
179
|
+
"""
|
|
180
|
+
_validate_model_cls(model_cls)
|
|
181
|
+
if not isinstance(result, ExtractionResult):
|
|
182
|
+
raise RecordBindingError("result must be an ExtractionResult instance.")
|
|
183
|
+
if not isinstance(only_valid, bool):
|
|
184
|
+
raise RecordBindingError("only_valid must be a boolean.")
|
|
185
|
+
|
|
186
|
+
if not only_valid:
|
|
187
|
+
if result.status != ProcessingStatus.COMPLETED:
|
|
188
|
+
raise RecordBindingError(
|
|
189
|
+
f"Cannot bind ExtractionResult: processing status is "
|
|
190
|
+
f"{result.status.value!r} (expected 'completed')."
|
|
191
|
+
)
|
|
192
|
+
if result.validation.status != ValidationStatus.VALID:
|
|
193
|
+
raise RecordBindingError(
|
|
194
|
+
f"Cannot bind ExtractionResult: validation status is "
|
|
195
|
+
f"{result.validation.status.value!r} (expected 'valid')."
|
|
196
|
+
)
|
|
197
|
+
return [bind_record(rec, model_cls) for rec in result.records]
|
|
198
|
+
|
|
199
|
+
bound: list[TModel] = []
|
|
200
|
+
for rec in result.records:
|
|
201
|
+
if (
|
|
202
|
+
rec.status == ProcessingStatus.COMPLETED
|
|
203
|
+
and rec.validation.status == ValidationStatus.VALID
|
|
204
|
+
):
|
|
205
|
+
bound.append(bind_record(rec, model_cls))
|
|
206
|
+
return bound
|
|
File without changes
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""Canonical ExtractionResult builder assembling records, provenance, confidence, and validation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from structa_maestro.confidence.calibration import ConfidenceCalibrator, validate_calibrator
|
|
8
|
+
from structa_maestro.confidence.normalizer import ConfidenceNormalizer
|
|
9
|
+
from structa_maestro.contracts.enums import (
|
|
10
|
+
FieldPresence,
|
|
11
|
+
IssueSeverity,
|
|
12
|
+
PipelineStage,
|
|
13
|
+
ProcessingStatus,
|
|
14
|
+
ValidationStatus,
|
|
15
|
+
)
|
|
16
|
+
from structa_maestro.contracts.models import (
|
|
17
|
+
DiagnosticIssue,
|
|
18
|
+
ExtractedField,
|
|
19
|
+
ExtractedRecord,
|
|
20
|
+
ExtractionResult,
|
|
21
|
+
SchemaMetadata,
|
|
22
|
+
SourceMetadata,
|
|
23
|
+
ValidationOutcome,
|
|
24
|
+
)
|
|
25
|
+
from structa_maestro.documents.models import PreparedDocument
|
|
26
|
+
from structa_maestro.exceptions import ConfigurationError
|
|
27
|
+
from structa_maestro.provenance.associator import ProvenanceAssociator
|
|
28
|
+
from structa_maestro.schema.models import ExtractionSchema
|
|
29
|
+
from structa_maestro.strategies.base import ProposedRecord, StrategyOutput
|
|
30
|
+
from structa_maestro.validation.validator import DeterministicValidator
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ResultBuilder:
|
|
34
|
+
"""Assembles Canonical Output Record Contract v1.0 results with strict status honesty."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
*,
|
|
39
|
+
validator: DeterministicValidator | None = None,
|
|
40
|
+
provenance_associator: ProvenanceAssociator | None = None,
|
|
41
|
+
confidence_normalizer: ConfidenceNormalizer | None = None,
|
|
42
|
+
calibrator: ConfidenceCalibrator | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
if confidence_normalizer is not None and calibrator is not None:
|
|
45
|
+
raise ConfigurationError(
|
|
46
|
+
"Cannot pass both confidence_normalizer and calibrator to ResultBuilder."
|
|
47
|
+
)
|
|
48
|
+
validated_calibrator = validate_calibrator(calibrator)
|
|
49
|
+
self._validator = validator or DeterministicValidator()
|
|
50
|
+
self._provenance = provenance_associator or ProvenanceAssociator()
|
|
51
|
+
self._confidence = confidence_normalizer or ConfidenceNormalizer(
|
|
52
|
+
calibrator=validated_calibrator
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def build_failed(
|
|
56
|
+
self,
|
|
57
|
+
*,
|
|
58
|
+
schema: ExtractionSchema,
|
|
59
|
+
source: SourceMetadata | None,
|
|
60
|
+
errors: list[DiagnosticIssue],
|
|
61
|
+
warnings: list[DiagnosticIssue] | None = None,
|
|
62
|
+
extraction_id: str | None = None,
|
|
63
|
+
) -> ExtractionResult:
|
|
64
|
+
"""Build a canonical failed result when processing fails prior to producing records."""
|
|
65
|
+
extra_kwargs: dict[str, Any] = {}
|
|
66
|
+
if extraction_id is not None:
|
|
67
|
+
extra_kwargs["extraction_id"] = extraction_id
|
|
68
|
+
return ExtractionResult(
|
|
69
|
+
status=ProcessingStatus.FAILED,
|
|
70
|
+
source=source,
|
|
71
|
+
schema_metadata=SchemaMetadata(
|
|
72
|
+
schema_id=schema.schema_id,
|
|
73
|
+
schema_version=schema.schema_version,
|
|
74
|
+
),
|
|
75
|
+
records=[],
|
|
76
|
+
validation=ValidationOutcome(status=ValidationStatus.NOT_VALIDATED),
|
|
77
|
+
errors=list(errors),
|
|
78
|
+
warnings=list(warnings or ()),
|
|
79
|
+
**extra_kwargs,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def build(
|
|
83
|
+
self,
|
|
84
|
+
*,
|
|
85
|
+
document: PreparedDocument,
|
|
86
|
+
schema: ExtractionSchema,
|
|
87
|
+
strategy_output: StrategyOutput,
|
|
88
|
+
document_warnings: list[DiagnosticIssue] | None = None,
|
|
89
|
+
extraction_id: str | None = None,
|
|
90
|
+
calibrator: ConfidenceCalibrator | None = None,
|
|
91
|
+
) -> ExtractionResult:
|
|
92
|
+
"""Assemble full canonical ExtractionResult from prepared document and strategy output."""
|
|
93
|
+
call_calibrator = validate_calibrator(calibrator)
|
|
94
|
+
result_errors = list(strategy_output.errors)
|
|
95
|
+
result_warnings = list(document_warnings or ()) + list(strategy_output.warnings)
|
|
96
|
+
|
|
97
|
+
if strategy_output.failed and not strategy_output.records:
|
|
98
|
+
return self.build_failed(
|
|
99
|
+
schema=schema,
|
|
100
|
+
source=document.source,
|
|
101
|
+
errors=result_errors
|
|
102
|
+
or [
|
|
103
|
+
DiagnosticIssue(
|
|
104
|
+
code="extraction_failed",
|
|
105
|
+
severity=IssueSeverity.ERROR,
|
|
106
|
+
stage=PipelineStage.EXTRACTION,
|
|
107
|
+
message="Extraction strategy failed without returning any records.",
|
|
108
|
+
)
|
|
109
|
+
],
|
|
110
|
+
warnings=result_warnings,
|
|
111
|
+
extraction_id=extraction_id,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
built_records: list[ExtractedRecord] = []
|
|
115
|
+
any_record_partial_or_failed = False
|
|
116
|
+
|
|
117
|
+
for idx, proposed_record in enumerate(strategy_output.records, start=1):
|
|
118
|
+
record_id = f"record-{idx:03d}"
|
|
119
|
+
built = self._build_record(
|
|
120
|
+
record_id=record_id,
|
|
121
|
+
document=document,
|
|
122
|
+
schema=schema,
|
|
123
|
+
proposed_record=proposed_record,
|
|
124
|
+
default_confidence_method=strategy_output.default_confidence_method,
|
|
125
|
+
calibrator=call_calibrator,
|
|
126
|
+
)
|
|
127
|
+
if built.status != ProcessingStatus.COMPLETED:
|
|
128
|
+
any_record_partial_or_failed = True
|
|
129
|
+
for rec_warn in built.warnings:
|
|
130
|
+
if rec_warn.stage == PipelineStage.VALIDATION:
|
|
131
|
+
result_warnings.append(rec_warn)
|
|
132
|
+
built_records.append(built)
|
|
133
|
+
|
|
134
|
+
overall_validation = self._validator.validate_result_cardinality(
|
|
135
|
+
[rec.validation for rec in built_records],
|
|
136
|
+
schema,
|
|
137
|
+
has_records=bool(built_records),
|
|
138
|
+
failed_before_validation=strategy_output.failed,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# Processing status is strictly independent of schema validation status!
|
|
142
|
+
has_processing_errors = bool(result_errors) or strategy_output.partial
|
|
143
|
+
if strategy_output.failed and not built_records:
|
|
144
|
+
overall_status = ProcessingStatus.FAILED
|
|
145
|
+
elif (
|
|
146
|
+
strategy_output.failed
|
|
147
|
+
or strategy_output.partial
|
|
148
|
+
or has_processing_errors
|
|
149
|
+
or any_record_partial_or_failed
|
|
150
|
+
):
|
|
151
|
+
overall_status = ProcessingStatus.PARTIAL
|
|
152
|
+
else:
|
|
153
|
+
overall_status = ProcessingStatus.COMPLETED
|
|
154
|
+
|
|
155
|
+
extra_kwargs: dict[str, Any] = {}
|
|
156
|
+
if extraction_id is not None:
|
|
157
|
+
extra_kwargs["extraction_id"] = extraction_id
|
|
158
|
+
|
|
159
|
+
return ExtractionResult(
|
|
160
|
+
status=overall_status,
|
|
161
|
+
source=document.source,
|
|
162
|
+
schema_metadata=SchemaMetadata(
|
|
163
|
+
schema_id=schema.schema_id,
|
|
164
|
+
schema_version=schema.schema_version,
|
|
165
|
+
),
|
|
166
|
+
records=built_records,
|
|
167
|
+
validation=overall_validation,
|
|
168
|
+
errors=result_errors,
|
|
169
|
+
warnings=result_warnings,
|
|
170
|
+
**extra_kwargs,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def _build_record(
|
|
174
|
+
self,
|
|
175
|
+
*,
|
|
176
|
+
record_id: str,
|
|
177
|
+
document: PreparedDocument,
|
|
178
|
+
schema: ExtractionSchema,
|
|
179
|
+
proposed_record: ProposedRecord,
|
|
180
|
+
default_confidence_method: str,
|
|
181
|
+
calibrator: ConfidenceCalibrator | None = None,
|
|
182
|
+
) -> ExtractedRecord:
|
|
183
|
+
record_errors = list(proposed_record.errors)
|
|
184
|
+
record_warnings = list(proposed_record.warnings)
|
|
185
|
+
|
|
186
|
+
# Prepare deterministic field map covering all declared schema fields + any extra fields
|
|
187
|
+
validation_input: dict[str, tuple[FieldPresence, Any]] = {}
|
|
188
|
+
ordered_field_names: list[str] = list(schema.fields.keys())
|
|
189
|
+
for extra_name in sorted(set(proposed_record.fields.keys()) - set(schema.fields.keys())):
|
|
190
|
+
ordered_field_names.append(extra_name)
|
|
191
|
+
|
|
192
|
+
for fname in ordered_field_names:
|
|
193
|
+
pf = proposed_record.fields.get(fname)
|
|
194
|
+
if pf is None or pf.presence == FieldPresence.MISSING:
|
|
195
|
+
validation_input[fname] = (FieldPresence.MISSING, None)
|
|
196
|
+
else:
|
|
197
|
+
validation_input[fname] = (FieldPresence.PRESENT, pf.value)
|
|
198
|
+
|
|
199
|
+
val_result = self._validator.validate_record(
|
|
200
|
+
validation_input,
|
|
201
|
+
schema,
|
|
202
|
+
record_id=record_id,
|
|
203
|
+
)
|
|
204
|
+
record_warnings.extend(val_result.warnings)
|
|
205
|
+
|
|
206
|
+
fields_map: dict[str, ExtractedField] = {}
|
|
207
|
+
any_field_errors = False
|
|
208
|
+
|
|
209
|
+
for fname in ordered_field_names:
|
|
210
|
+
pf = proposed_record.fields.get(fname)
|
|
211
|
+
spec = schema.fields.get(fname)
|
|
212
|
+
field_val_outcome = val_result.field_outcomes[fname]
|
|
213
|
+
value_type = spec.field_type if spec is not None else None
|
|
214
|
+
|
|
215
|
+
if pf is None:
|
|
216
|
+
fields_map[fname] = ExtractedField(
|
|
217
|
+
presence=FieldPresence.MISSING,
|
|
218
|
+
value=None,
|
|
219
|
+
value_type=value_type,
|
|
220
|
+
confidence=None,
|
|
221
|
+
provenance=[],
|
|
222
|
+
validation=field_val_outcome,
|
|
223
|
+
errors=[],
|
|
224
|
+
warnings=[],
|
|
225
|
+
)
|
|
226
|
+
continue
|
|
227
|
+
|
|
228
|
+
presence = pf.presence
|
|
229
|
+
value = None if presence == FieldPresence.MISSING else pf.value
|
|
230
|
+
field_errors = list(pf.errors)
|
|
231
|
+
field_warnings = list(pf.warnings)
|
|
232
|
+
if field_errors:
|
|
233
|
+
any_field_errors = True
|
|
234
|
+
|
|
235
|
+
if pf.ambiguous:
|
|
236
|
+
field_warnings.append(
|
|
237
|
+
DiagnosticIssue(
|
|
238
|
+
code="ambiguous_source_value",
|
|
239
|
+
severity=IssueSeverity.WARNING,
|
|
240
|
+
stage=PipelineStage.EXTRACTION,
|
|
241
|
+
message=f"Source document contains ambiguous candidates for '{fname}'.",
|
|
242
|
+
record_id=record_id,
|
|
243
|
+
field_path=fname,
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
conf_res = self._confidence.normalize(
|
|
248
|
+
raw_value=pf.confidence,
|
|
249
|
+
scale=pf.confidence_scale,
|
|
250
|
+
method=pf.confidence_method,
|
|
251
|
+
record_id=record_id,
|
|
252
|
+
field_path=fname,
|
|
253
|
+
default_method=default_confidence_method,
|
|
254
|
+
calibrator=calibrator,
|
|
255
|
+
)
|
|
256
|
+
field_warnings.extend(conf_res.warnings)
|
|
257
|
+
|
|
258
|
+
try:
|
|
259
|
+
prov_res = self._provenance.associate(
|
|
260
|
+
document=document,
|
|
261
|
+
proposed_evidence=pf.evidence,
|
|
262
|
+
field_name=fname,
|
|
263
|
+
presence=presence,
|
|
264
|
+
value=value,
|
|
265
|
+
record_id=record_id,
|
|
266
|
+
)
|
|
267
|
+
provenance_entries = prov_res.evidence
|
|
268
|
+
field_warnings.extend(prov_res.warnings)
|
|
269
|
+
except Exception:
|
|
270
|
+
provenance_entries = []
|
|
271
|
+
field_errors.append(
|
|
272
|
+
DiagnosticIssue(
|
|
273
|
+
code="provenance_association_failed",
|
|
274
|
+
severity=IssueSeverity.ERROR,
|
|
275
|
+
stage=PipelineStage.PROVENANCE,
|
|
276
|
+
message=f"Provenance association failed for field '{fname}'.",
|
|
277
|
+
record_id=record_id,
|
|
278
|
+
field_path=fname,
|
|
279
|
+
)
|
|
280
|
+
)
|
|
281
|
+
any_field_errors = True
|
|
282
|
+
|
|
283
|
+
fields_map[fname] = ExtractedField(
|
|
284
|
+
presence=presence,
|
|
285
|
+
value=value,
|
|
286
|
+
value_type=value_type,
|
|
287
|
+
confidence=conf_res.confidence,
|
|
288
|
+
provenance=provenance_entries,
|
|
289
|
+
validation=field_val_outcome,
|
|
290
|
+
errors=field_errors,
|
|
291
|
+
warnings=field_warnings,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
if proposed_record.failed:
|
|
295
|
+
record_status = ProcessingStatus.FAILED
|
|
296
|
+
elif proposed_record.partial or record_errors or any_field_errors:
|
|
297
|
+
record_status = ProcessingStatus.PARTIAL
|
|
298
|
+
else:
|
|
299
|
+
record_status = ProcessingStatus.COMPLETED
|
|
300
|
+
|
|
301
|
+
return ExtractedRecord(
|
|
302
|
+
record_id=record_id,
|
|
303
|
+
status=record_status,
|
|
304
|
+
fields=fields_map,
|
|
305
|
+
validation=val_result.record_outcome,
|
|
306
|
+
errors=record_errors,
|
|
307
|
+
warnings=record_warnings,
|
|
308
|
+
)
|