Files
ISSSTELEON/Extraction/extraction/records.py
T

285 lines
13 KiB
Python

"""From documents to records: segment, extract every field per segment,
then merge the partial records that belong to the same patient."""
import re
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.nlp.text import ocr_fold
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
# What is left of a value's confidence when its document names another kind
# of study (`foreign`) and not the target's (`subject`).
OFF_TOPIC_FACTOR = 0.5
@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)
# Every reading proposed per field, the chosen one included, for review
# and for learning from corrections (`extraction.nlp.ranking`).
candidates: dict[str, list[ExtractedValue]] = field(default_factory=dict)
# Whether the record's pages are about what the target is: `True` when
# they name it, `False` when they only name another kind of study,
# `None` when they name neither or no subject was given.
on_topic: bool | None = None
# Values held back because their segment was off topic, restored if the
# record it merges into turns out to be on topic.
withheld: dict[str, ExtractedValue] = field(default_factory=dict)
flags: set[str] = field(default_factory=set)
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)
for record in merged:
if record.on_topic:
for name, value in record.withheld.items():
record.values.setdefault(name, value)
record.withheld = {}
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)
target.flags.update(record.flags)
for name, proposed in record.candidates.items():
target.candidates.setdefault(name, []).extend(proposed)
if record.on_topic is not None and target.on_topic is not True:
target.on_topic = record.on_topic
for name, value in record.withheld.items():
if name not in target.withheld or value.confidence > target.withheld[name].confidence:
target.withheld[name] = value
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. `subject` names what the target
is about and `foreign` what other targets are (`vocabulary.SUBJECTS`):
a segment that names only a foreign subject is another kind of report,
and fills nothing unless the record it merges into names the target's.
`ranker` picks each field's value among its candidates
(`extraction.nlp.ranking`).
"""
def __init__(
self,
specs: Sequence[FieldSpec],
*,
key_field: str | None = None,
segmenter: Segmenter | None = None,
extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS,
merger: RecordMerger | None = RecordMerger(),
subject: Sequence[str] = (),
foreign: Sequence[str] = (),
ranker=None,
):
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, ranker=ranker)
self.merger = merger
self.subject = _subject_pattern(subject)
self.foreign = _subject_pattern(foreign)
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 _on_topic(self, lines) -> bool | None:
texts = [line.ocr_folded for line in lines]
if self.subject is not None and any(self.subject.search(text) for text in texts):
return True
if self.foreign is not None and any(self.foreign.search(text) for text in texts):
return False
return None
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)]
flags: set[str] = set()
candidates = self.fields.candidates(lines, flags=flags)
on_topic = self._on_topic(lines)
if on_topic is not None:
factor = 1.0 if on_topic else OFF_TOPIC_FACTOR
candidates = {
name: [c.with_confidence(c.confidence * factor, on_topic=on_topic) for c in proposed]
for name, proposed in candidates.items()
}
values = self.fields.choose(candidates)
withheld = {}
if on_topic is False:
unchecked = {name: [c.with_confidence(c.confidence, on_topic=None) for c in proposed] for name, proposed in candidates.items()}
withheld = {name: value for name, value in self.fields.choose(unchecked).items() if name not in values}
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),
candidates=candidates,
on_topic=on_topic,
withheld=withheld,
flags=flags,
)
def _subject_pattern(terms: Sequence[str]) -> re.Pattern | None:
stems = sorted({" ".join(re.findall(r"[A-Z0-9]+", ocr_fold(term))) for term in terms if term.strip()}, key=len, reverse=True)
if not stems:
return None
body = "|".join(r"[\s.\-]*".join(re.escape(word) for word in stem.split()) for stem in stems)
return re.compile(rf"(?<![A-Z0-9])(?:{body})")
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)