Files
ISSSTELEON/Extraction/extraction/records.py
T
2026-11-13 11:53:06 -06:00

210 lines
9.1 KiB
Python

"""From documents to records: segment, extract every field per segment,
then merge the partial records that belong to the same patient."""
from dataclasses import dataclass, field
from typing import Any, Sequence
from extraction.document import Document, EmbeddedImage
from extraction.nlp.discovery import DiscoveredField, discover_captions
from extraction.nlp.extractors import DEFAULT_EXTRACTORS, FieldExtractor, RecordExtractor, parse_value
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
from extraction.segmentation import AutoSegmenter, Segment, Segmenter, normalize_key
from extraction.template import in_margin, normalized, template_lines
# Two readings of the same field that disagree only count as a conflict
# when the losing one is itself reasonably confident.
CONFLICT_CONFIDENCE = 0.5
# A field sourced straight from a database column, not read off the page.
# Above every built-in extractor's ceiling (0.95, `LabeledValueExtractor`'s
# own), so it always wins a disagreement with a text-derived reading.
SOURCE_FIELD_METHOD = "columna_fuente"
SOURCE_FIELD_CONFIDENCE = 1.0
@dataclass
class SegmentRef:
document: str
page_numbers: list[int] = field(default_factory=list)
@dataclass
class FieldConflict:
field: str
kept: ExtractedValue
discarded: ExtractedValue
@dataclass
class ExtractedRecord:
values: dict[str, ExtractedValue]
sources: list[SegmentRef]
images: list[tuple[str, EmbeddedImage]] = field(default_factory=list)
key: str | None = None
conflicts: list[FieldConflict] = field(default_factory=list)
# Captions no known `FieldSpec` claimed (`discover_captions`): what a
# source outside today's vocabulary carries, for a caller to match
# against a catalog or register as new (catalog_matching, in WebApi).
discovered: list[DiscoveredField] = field(default_factory=list)
def row(self) -> dict[str, Any]:
return {name: extracted.value for name, extracted in self.values.items()}
@property
def confidence(self) -> float:
if not self.values:
return 0.0
return min(extracted.confidence for extracted in self.values.values())
class RecordMerger:
"""Combines records that share a key — a patient's demographics on one
page, their lab result on another, their biopsy in another file. Per
field, the most confident reading wins; a confident disagreement is
kept as a `FieldConflict` so it can be reviewed."""
def merge(self, records: Sequence[ExtractedRecord]) -> list[ExtractedRecord]:
merged: list[ExtractedRecord] = []
by_key: dict[str, ExtractedRecord] = {}
for record in records:
if record.key is None:
merged.append(record)
continue
target = by_key.get(record.key)
if target is None:
target = ExtractedRecord(values={}, sources=[], key=record.key)
by_key[record.key] = target
merged.append(target)
self._absorb(target, record)
return merged
@staticmethod
def _absorb(target: ExtractedRecord, record: ExtractedRecord) -> None:
target.sources.extend(record.sources)
target.images.extend(record.images)
target.conflicts.extend(record.conflicts)
target.discovered.extend(record.discovered)
for name, incoming in record.values.items():
current = target.values.get(name)
if current is None:
target.values[name] = incoming
continue
if current.value == incoming.value:
if incoming.confidence > current.confidence:
target.values[name] = incoming
continue
kept, discarded = (incoming, current) if incoming.confidence > current.confidence else (current, incoming)
target.values[name] = kept
if discarded.confidence >= CONFLICT_CONFIDENCE:
target.conflicts.append(FieldConflict(name, kept, discarded))
class DocumentExtractor:
"""Entry point: `DocumentExtractor(specs, key_field="pac_id_hospital").extract(docs)`.
`key_field` names the spec that identifies a patient; it drives both
the default segmentation (split a document where the key changes) and
the merge across pages and documents.
"""
def __init__(
self,
specs: Sequence[FieldSpec],
*,
key_field: str | None = None,
segmenter: Segmenter | None = None,
extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS,
merger: RecordMerger | None = RecordMerger(),
):
self.specs = list(specs)
self.key_spec = next((spec for spec in self.specs if spec.name == key_field), None)
self.segmenter = segmenter or AutoSegmenter(self.key_spec)
self.fields = RecordExtractor(self.specs, extractors=extractors)
self.merger = merger
def segments(self, documents: Sequence[Document]) -> list[Segment]:
return [segment for document in documents for segment in self.segmenter.split(document)]
def extract(
self,
documents: Sequence[Document],
*,
source_fields: dict[str, dict[str, Any]] | None = None,
record_keys: dict[str, str] | None = None,
) -> list[ExtractedRecord]:
"""`source_fields` carries, per document name, field values read
straight from a structured column rather than the page (a SQL
source's own patient or study id, say); they override whatever
the text parses to for that field, on every segment of that
document, including the key field itself.
`record_keys` names, per document, the record it belongs to (a
study or order id from the source): documents sharing one merge
into a single record, and documents that don't stay apart even
when they share the key field."""
segments = self.segments(documents)
def extract(segment: Segment, template: set[str] = frozenset()) -> ExtractedRecord:
name = segment.document.name
return self.extract_segment(segment, (source_fields or {}).get(name), (record_keys or {}).get(name), template=template)
records = [extract(segment) for segment in segments]
# A second pass without the template lines the first one revealed:
# an issuer's letterhead must not fill any patient's fields.
template = template_lines((self._owner(record), segment.lines_only()) for segment, record in zip(segments, records))
if template:
records = [
extract(segment, template) if any(normalized(line) in template for line in segment.lines_only()) else record
for segment, record in zip(segments, records)
]
return self.merger.merge(records) if self.merger else records
def _owner(self, record: ExtractedRecord) -> str | None:
"""Whose document a record is: its key field's value, when known."""
if self.key_spec is None or self.key_spec.name not in record.values:
return None
return normalize_key(record.values[self.key_spec.name].value)
def extract_segment(
self,
segment: Segment,
source_fields: dict[str, Any] | None = None,
record_key: str | None = None,
*,
template: set[str] = frozenset(),
) -> ExtractedRecord:
"""`template`: normalized texts of margin lines to read nothing from
(`extraction.template`)."""
lines = [line for line in segment.lines() if not (template and in_margin(line.line) and normalized(line.line) in template)]
values = self.fields.extract(lines)
specs = {spec.name: spec for spec in self.specs}
for name, raw_value in (source_fields or {}).items():
if raw_value is None:
continue
values[name] = ExtractedValue(
value=_source_value(specs.get(name), raw_value),
confidence=SOURCE_FIELD_CONFIDENCE,
method=SOURCE_FIELD_METHOD,
raw=str(raw_value),
evidence=Evidence(document=segment.document.name, page_number=segment.page_numbers[0] if segment.page_numbers else 0, line=f"columna {name}"),
)
key = segment.key
if self.key_spec is not None and self.key_spec.name in values:
key = normalize_key(values[self.key_spec.name].value)
if record_key is not None:
key = normalize_key(str(record_key))
return ExtractedRecord(
values=values,
sources=[SegmentRef(segment.document.name, list(segment.page_numbers))],
images=[(segment.document.name, image) for image in segment.images],
key=key,
discovered=discover_captions(lines, self.specs),
)
def _source_value(spec: FieldSpec | None, raw_value: Any) -> Any:
"""A column's value typed like the field it fills, so a source's
`datetime` or date string becomes a date and a number stays one."""
if spec is None or spec.kind in (FieldKind.TEXT, FieldKind.IDENTIFIER):
return str(raw_value)
parsed = parse_value(spec, str(raw_value))
return parsed.value if parsed is not None else str(raw_value)