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

738 lines
32 KiB
Python

"""Field extraction strategies. Each `FieldExtractor` proposes candidates
for a field, each with the features of how it was found; `RecordExtractor`
keeps them all and lets a `CandidateRanker` (`extraction.nlp.ranking`) pick
one per field. Without a trained ranker, the most confident candidate wins.
To add a strategy (a dictionary lookup, a statistical NER model, an LLM
call), subclass `FieldExtractor`, give it a `method` name and pass an
instance to `RecordExtractor(extractors=[...])`.
"""
import re
from abc import ABC, abstractmethod
from collections import Counter
from dataclasses import dataclass
from functools import lru_cache
from typing import Any, ClassVar, Iterable, Sequence
from rapidfuzz import fuzz
from extraction.document import Line
from extraction.nlp.context import ASSERTION_WEIGHT, Assertion, Context, Section, assess, heading_section, sections
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
from extraction.nlp.text import (
SEPARATOR,
find_date,
find_decimal,
find_identifier,
find_integer,
fold,
is_negated,
label_pattern,
ocr_fold,
)
FUZZY_LABEL_THRESHOLD = 0.86
MAX_TEXT_LENGTH = 1000
MAX_CONTINUATION_LINES = 8
# A choice whose label stands alone may state its value a few lines down,
# after a subheading.
MAX_CHOICE_LOOKAHEAD = 3
# Values in a column may start slightly left of the label heading it.
COLUMN_MARGIN = 0.02
# What an OCR look-alike match is worth next to an exact one.
OCR_MATCH_SCORE = 0.92
@dataclass(frozen=True)
class SegmentLine:
"""`ocr`: the line was read by OCR, so look-alike characters may stand in
for each other (`extraction.nlp.text.ocr_fold`)."""
document: str
page_number: int
line: Line
ocr: bool = False
@property
def text(self) -> str:
return self.line.text
@property
def folded(self) -> str:
return fold(self.line.text)
@property
def ocr_folded(self) -> str:
return ocr_fold(self.line.text)
@property
def ocr_confidence(self) -> float:
return self.line.confidence if self.line.confidence > 0 else 0.5
def evidence(self, text: str | None = None) -> Evidence:
return Evidence(self.document, self.page_number, text or self.line.text, self.line.bbox.as_list())
@dataclass(frozen=True)
class LabelHit:
field: str
start: int
end: int
score: float
class LabelIndex:
"""Every label occurrence of every field, per line. Knowing where *all*
labels sit is what lets one form line such as
`Nombre: ANA Sexo: F C.P.: 64000` be split into three values.
Captions no field knows (`Cualquier otra cosa:`) are tracked too, as
boundaries: they end the value before them and the text under the
label before them, without being read themselves."""
def __init__(self, lines: Sequence[SegmentLine], specs: Iterable[FieldSpec]):
self.lines = list(lines)
self.folded = [line.folded for line in self.lines]
self.hits: list[list[LabelHit]] = [_label_hits(line, tuple(specs)) for line in self.lines]
self.boundaries: list[list[int]] = [
_boundaries(folded, hits) for folded, hits in zip(self.folded, self.hits)
]
self.sections: list[Section] = sections([line.ocr_folded if line.ocr else line.folded for line in self.lines])
def context(self, line_index: int, start: int, end: int) -> Context:
"""The assertion of the mention at `start:end` of a line."""
line = self.lines[line_index]
return assess(line.ocr_folded if line.ocr else line.folded, start, end, self.sections[line_index])
def label_context(self, line_index: int, hit: "LabelHit") -> Context:
"""A label's value is the answer to it, so only where the label sits
qualifies it: its section, or a caption that names one
("Diagnóstico clínico:" is what was suspected, not found). A caption
inside reference text (a report date in the footer under an
interpretation guide) is still the document's own."""
folded = self.folded[line_index]
section = heading_section(folded[_caption_start(folded, hit.start) :]) or self.sections[line_index]
assertion = {
Section.CLINICA: Assertion.PRESUNTIVO,
Section.ANTECEDENTES: Assertion.HISTORICO,
}.get(section, Assertion.AFIRMADO)
return Context(assertion, section)
def position(self, line_index: int) -> float:
return line_index / max(1, len(self.lines) - 1)
def for_field(self, name: str) -> Iterable[tuple[int, LabelHit]]:
for index, hits in enumerate(self.hits):
for hit in hits:
if hit.field == name:
yield index, hit
def next_start(self, index: int, after: int) -> int | None:
starts = [start for start in self.boundaries[index] if start >= after]
return min(starts) if starts else None
def column(self, index: int, hit: LabelHit) -> tuple[float, float] | None:
"""Horizontal extent of the column a label heads, when its line
carries other captions too: from the label's left edge to the next
caption's. `None` for a label alone on its line or without word
positions."""
starts = self.boundaries[index]
line = self.lines[index].line
own = max((start for start in starts if start <= hit.start), default=None)
if len(starts) < 2 or not line.words or own is None:
return None
position = starts.index(own)
left = line.x_at(own) if position else 0.0
right = line.x_at(starts[position + 1]) if position + 1 < len(starts) else 1.0
if left is None or right is None or right <= left:
return None
return left - COLUMN_MARGIN if position else 0.0, right - COLUMN_MARGIN if position + 1 < len(starts) else 1.0
def label_in_column(self, index: int, column: tuple[float, float]) -> bool:
line = self.lines[index].line
return any(column[0] <= (line.x_at(start) or -1.0) < column[1] for start in self.boundaries[index])
def starts_with_label(self, index: int) -> bool:
text = self.lines[index].folded
offset = len(text) - len(text.lstrip())
return any(start <= offset + 2 for start in self.boundaries[index])
# A caption no field knows: a few words and a colon, at the start of the
# line or after an item number (`7.- `, `b) `).
_ITEM_NUMBER = r"(?:\d{1,3}|[A-Z])\s*[.)][.\-]*\s*"
_ANY_CAPTION = re.compile(rf"(?:^|(?<=\s))(?P<item>{_ITEM_NUMBER})?[A-Z][A-Z0-9./\-]*(?:\s+[A-Z0-9][A-Z0-9./\-]*){{0,5}}\s*:")
_TRAILING_ITEM_NUMBER = re.compile(rf"(?:^|(?<=\s)){_ITEM_NUMBER}$")
# An item number in the middle of a line (`... 3.- SIGUIENTE`) starts the next item.
_INLINE_ITEM = re.compile(r"(?<=\s)(?:\d{1,3}\.-|\d{1,3}\)|[A-Z]\))(?=\s)")
# A horizontal gap wider than this (fraction of the page) between two words
# separates two cells of a form line.
CELL_GAP = 0.02
def cell_starts(line: SegmentLine) -> list[int]:
"""Character offsets where a word starts after a wide horizontal gap;
without word positions, after a run of spaces or a tab."""
words = line.line.words
if not words:
return [match.end() for match in re.finditer(r"\s{2,}|\t", line.text)]
starts, offset = [], 0
for previous, word in zip((None, *words), words):
if previous is not None and word.x0 - previous.x1 > CELL_GAP:
starts.append(offset)
offset += len(word.text) + 1
return starts
def _within_cell(line: SegmentLine, start: int, tail: str) -> str:
"""A value ends where the next cell of the line begins, once it has
started: the gap between a caption and its value doesn't cut it."""
cuts = [cut for cut in cell_starts(line) if cut > start]
if not cuts or cuts[0] >= start + len(tail):
return tail
return line.text[start : cuts[0]].rstrip()
def _caption_start(folded: str, start: int) -> int:
"""Where a caption begins, counting the item number printed before it."""
item = _TRAILING_ITEM_NUMBER.search(folded[:start])
return item.start() if item else start
def _boundaries(folded: str, hits: list[LabelHit]) -> list[int]:
starts = {hit: _caption_start(folded, hit.start) for hit in hits}
extra: set[int] = {
match.start() for match in _INLINE_ITEM.finditer(folded) if not any(hit.start <= match.start() < hit.end for hit in hits)
}
line_start = len(folded) - len(folded.lstrip())
for match in _ANY_CAPTION.finditer(folded):
if match.start() != line_start and not match.group("item"):
continue
inside = [hit for hit in hits if match.start() <= hit.start < match.end()]
for hit in inside:
starts[hit] = min(starts[hit], match.start())
if not inside and not any(hit.start <= match.start() < hit.end for hit in hits):
extra.add(match.start())
return sorted(set(starts.values()) | extra)
_AFTER_CAPTION = re.compile(r"\s*[:=#]|\s{2,}|\s*$")
def _is_caption(folded: str, start: int, end: int) -> bool:
"""A caption starts its line or is followed by a separator; the same
words inside a sentence ("...muestra adecuada...") are just text."""
return not folded[:start].strip() or bool(_AFTER_CAPTION.match(folded, end))
# A caption may run on for a few words before its colon.
_CAPTION_RUN_ON = re.compile(r"(?:\s+[A-Z]{1,15}\.?){1,4}\s*:")
# Words a run-on caption may have before its label, counted from the start
# of the line, an item number or the previous colon; more is a sentence.
MAX_CAPTION_LEAD_WORDS = 2
_CONNECTOR_BEFORE = re.compile(r"(?<![A-Z0-9])(DE|DEL|PARA|POR|EN|CON|SIN|A|AL)\s+$")
def _names_something_else(folded: str, start: int) -> bool:
"""A label right after a connector is the tail of a longer caption
that names something else: `FECHA DE INTERPRETACION` is a date, not
the interpretation."""
return bool(_CONNECTOR_BEFORE.search(folded[max(0, start - 8) : start]))
def _near_segment_start(folded: str, start: int) -> bool:
segment = re.split(r":|(?:^|\s)(?:\d{1,3}|[A-Z])\s*[.)][.\-]*\s", folded[:start])[-1]
return len(segment.split()) <= MAX_CAPTION_LEAD_WORDS
def _label_hits(line: SegmentLine, specs: tuple[FieldSpec, ...]) -> list[LabelHit]:
folded = line.folded
canonical = line.ocr_folded if line.ocr else None
found: list[LabelHit] = []
for spec in specs:
for label in spec.labels:
exact = [LabelHit(spec.name, m.start(), m.end(), 1.0) for m in label_pattern(label).finditer(folded)]
if not exact and canonical is not None:
exact = [
LabelHit(spec.name, m.start(), m.end(), OCR_MATCH_SCORE)
for m in label_pattern(ocr_fold(label)).finditer(canonical)
]
found.extend(exact or _fuzzy_hits(canonical or folded, spec.name, ocr_fold(label) if canonical else label))
hits: list[LabelHit] = []
for hit in found:
if _names_something_else(folded, hit.start):
continue
if _is_caption(folded, hit.start, hit.end):
hits.append(hit)
continue
run_on = _CAPTION_RUN_ON.match(folded, hit.end)
if (
run_on
and _near_segment_start(folded, hit.start)
and not any(other is not hit and other.start < run_on.end() and other.end > hit.end for other in found)
):
hits.append(LabelHit(hit.field, hit.start, run_on.end(), hit.score))
# A label inside a longer one ("FECHA" inside "FECHA DE NACIMIENTO") is not a label.
hits.sort(key=lambda h: (h.start, -(h.end - h.start)))
kept: list[LabelHit] = []
for hit in hits:
if any(other.start <= hit.start and hit.end <= other.end and (other.end - other.start) > (hit.end - hit.start) for other in hits):
continue
kept.append(hit)
return kept
@lru_cache(maxsize=4096)
def _folded_label(label: str) -> str:
return " ".join(re.findall(r"[A-Z0-9]+", fold(label)))
def _fuzzy_hits(folded: str, field_name: str, label: str) -> list[LabelHit]:
"""Tolerates OCR misreads in long labels (`FECHA DE NAC1MIENTO`)."""
target = _folded_label(label)
if len(target) < 6:
return []
tokens = [(m.group(), m.start(), m.end()) for m in re.finditer(r"[A-Z0-9]+", folded)]
width = len(target.split())
hits = []
for i in range(len(tokens) - width + 1):
window = tokens[i : i + width]
candidate = " ".join(token for token, _, _ in window)
ratio = fuzz.ratio(candidate, target) / 100.0
if ratio >= FUZZY_LABEL_THRESHOLD:
hits.append(LabelHit(field_name, window[0][1], window[-1][2], round(ratio, 3)))
return hits
@dataclass(frozen=True)
class Parsed:
value: Any
raw: str
quality: float
def parse_value(spec: FieldSpec, text: str, *, ocr: bool = False) -> Parsed | None:
"""Reads a value of `spec.kind` out of the text found next to a label;
`ocr` also accepts choices written with OCR look-alikes."""
text = text.strip()
if not text:
return None
if spec.kind is FieldKind.DATE:
found = find_date(text)
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.85) if found else None
if spec.kind is FieldKind.INTEGER:
found = find_integer(text)
dated = find_date(text)
if found and dated and dated[1][0] <= found[1][0] < dated[1][1]:
return None
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.8) if found else None
if spec.kind is FieldKind.DECIMAL:
found = find_decimal(text)
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.8) if found else None
if spec.kind is FieldKind.IDENTIFIER:
found = find_identifier(text, spec.pattern)
return Parsed(found[0], found[0], 1.0 if found[1][0] <= 3 else 0.85) if found else None
if spec.kind is FieldKind.CHOICE:
found = find_choice(spec, fold(text))
quality = 1.0
if found is None and ocr:
found = find_choice(spec, ocr_fold(text), canonical=True)
quality = OCR_MATCH_SCORE
if found is None:
return None
value, surface, start = found
return Parsed(value, text[start : start + len(surface)], quality * (1.0 if start <= 3 else 0.85))
if spec.pattern:
match = re.search(spec.pattern, text, re.I)
return Parsed(match.group(), match.group(), 1.0 if match.start() <= 3 else 0.85) if match else None
return Parsed(text[:MAX_TEXT_LENGTH], text[:MAX_TEXT_LENGTH], 0.9)
def find_choice(spec: FieldSpec, folded: str, *, min_length: int = 1, canonical: bool = False) -> tuple[Any, str, int] | None:
"""Leftmost, then longest, non-negated surface form of `spec` in `folded`
(`canonical`: `folded` went through `ocr_fold`, and so do the surfaces)."""
best: tuple[Any, str, int] | None = None
for surface in spec.surface_forms:
if len(surface) < min_length:
continue
for match in _choice_pattern(ocr_fold(surface) if canonical else surface).finditer(folded):
if not _negates_itself(surface) and is_negated(folded, match.start()):
continue
if best is None or match.start() < best[2] or (match.start() == best[2] and len(surface) > len(best[1])):
best = (spec.choices[surface], surface, match.start())
break
return best
@lru_cache(maxsize=8192)
def _choice_pattern(surface: str) -> re.Pattern:
body = r"[\s.\-]+".join(re.escape(token) for token in surface.split())
return re.compile(rf"(?<![A-Z0-9]){body}(?![A-Z0-9])")
def _negates_itself(surface: str) -> bool:
return bool(re.search(r"(?<![A-Z])(NO|NEGATIV[OA]|SIN|AUSENCIA)(?![A-Z])", surface))
class FieldExtractor(ABC):
method: ClassVar[str]
@abstractmethod
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]: ...
class LabeledValueExtractor(FieldExtractor):
"""`Etiqueta: valor` on the same line, or the value on the line(s)
under the label — the layout of forms and of report section headers
(`DIAGNÓSTICO:` followed by a paragraph)."""
method = "etiqueta"
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
for line_index, hit in index.for_field(spec.name):
line = index.lines[line_index]
end = index.next_start(line_index, hit.end)
tail = line.text[hit.end : end]
tail = tail[len(SEPARATOR.match(tail).group()) :]
tail = _within_cell(line, line.text.index(tail, hit.end) if tail else hit.end, tail)
source_line = line
below = False
if not tail.strip() or (spec.multiline and spec.kind is FieldKind.TEXT):
continuation = self._continuation(spec, index, line_index, index.column(line_index, hit))
if continuation is not None:
tail, source_line = (f"{tail.strip()} {continuation[0]}".strip(), continuation[1])
below = True
parsed = parse_value(spec, tail, ocr=line.ocr or source_line.ocr)
if parsed is None:
continue
context = index.label_context(line_index, hit)
confidence = 0.95 * hit.score * parsed.quality * min(line.ocr_confidence, source_line.ocr_confidence)
confidence *= max(ASSERTION_WEIGHT[context.assertion], 0.1)
features = {
"assertion": context.assertion.value,
"section": context.section.value,
"label_score": hit.score,
"parse_quality": parsed.quality,
"value_below_label": below,
"position": index.position(line_index),
"ocr": line.ocr,
}
yield ExtractedValue(parsed.value, confidence, self.method, parsed.raw, source_line.evidence(line.text), features)
@staticmethod
def _continuation(
spec: FieldSpec, index: LabelIndex, line_index: int, column: tuple[float, float] | None = None
) -> tuple[str, SegmentLine] | None:
"""The text under a label. When the label shares its line with
other labels (a form laid out in columns, captions on one row and
values on the next), only the words under this label's column
count, and lines with nothing in that column are passed over."""
limit = MAX_CONTINUATION_LINES if spec.multiline else (MAX_CHOICE_LOOKAHEAD if spec.kind is FieldKind.CHOICE else 1)
collected: list[tuple[str, SegmentLine]] = []
for following in range(line_index + 1, min(len(index.lines), line_index + 1 + limit)):
candidate = index.lines[following]
if candidate.page_number != index.lines[line_index].page_number or not candidate.text.strip():
break
if index.starts_with_label(following):
break
text = candidate.text.strip()
if column is not None and candidate.line.words:
if index.label_in_column(following, column):
break
text = candidate.line.text_between(*column)
if not text:
continue
collected.append((text, candidate))
if spec.kind is FieldKind.CHOICE and parse_value(spec, text, ocr=candidate.ocr) is not None:
break
if not collected:
return None
return " ".join(text for text, _ in collected), collected[0][1]
class PatternExtractor(FieldExtractor):
"""Values with a recognizable shape (`EXP-0042`, a CIE-10 code) found
anywhere in the text, for fields with `scan_free_text` and a `pattern`.
Lines that also carry one of the field's labels score higher."""
method = "patron"
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
if not spec.pattern or not spec.scan_free_text:
return
regex = re.compile(spec.pattern, re.I)
labelled_lines = {line_index for line_index, _ in index.for_field(spec.name)}
for line_index, line in enumerate(index.lines):
for match in regex.finditer(line.text):
parsed = parse_value(spec, match.group())
if parsed is None:
continue
context = index.context(line_index, match.start(), match.end())
base = 0.85 if line_index in labelled_lines else 0.7
features = {
"assertion": context.assertion.value,
"section": context.section.value,
"labelled_line": line_index in labelled_lines,
"position": index.position(line_index),
"ocr": line.ocr,
}
confidence = base * line.ocr_confidence * max(ASSERTION_WEIGHT[context.assertion], 0.1)
yield ExtractedValue(parsed.value, confidence, self.method, match.group(), line.evidence(), features)
@dataclass(frozen=True)
class Mention:
value: Any
raw: str
line_index: int
context: Context
anchored: bool
generic: bool
@property
def weight(self) -> float:
return ASSERTION_WEIGHT[self.context.assertion]
def _anchor_terms(spec: FieldSpec) -> tuple[str, ...]:
return tuple(dict.fromkeys(fold(term).strip() for term in (*spec.anchors, *spec.labels) if term.strip()))
@lru_cache(maxsize=2048)
def _anchor_pattern(terms: tuple[str, ...]) -> re.Pattern | None:
if not terms:
return None
body = "|".join(r"[\s.\-]+".join(re.escape(token) for token in term.split()) for term in sorted(terms, key=len, reverse=True))
return re.compile(rf"(?<![A-Z0-9])(?:{body})(?![A-Z0-9])")
# How far before a mention, on its line, its anchor may be.
ANCHOR_REACH = 80
def is_generic(surface: str) -> bool:
from extraction.nlp.vocabulary import GENERIC_TERMS
return " ".join(surface.split()) in GENERIC_TERMS
class FreeTextMentionExtractor(FieldExtractor):
"""Catalog terms mentioned in narrative text ("...compatible con NIC
II...") without a label in front, each judged in its context
(`extraction.nlp.context`): denied, hypothetical, historical or
clinically presumed mentions count for little or nothing, a generic
answer ("POSITIVO") only counts after its concept (`FieldSpec.anchors`),
and a denied mention of a presence field gives its `negated_value`.
Every value mentioned is a candidate. The one proposed first is, for a
field with a `severity` order, the most severe value the report
affirms; otherwise the most repeated, ties going to the last mention,
since reports state their conclusion at the end."""
method = "texto_libre"
MIN_SURFACE_LENGTH = 4
def mentions(self, spec: FieldSpec, index: LabelIndex) -> list[Mention]:
anchors = _anchor_pattern(_anchor_terms(spec))
found: list[Mention] = []
for line_index, line in enumerate(index.lines):
texts = [(line.folded, False)]
if line.ocr:
texts.append((line.ocr_folded, True))
seen: set[tuple[int, int]] = set()
for text, canonical in texts:
taken: list[tuple[int, int]] = []
for surface in spec.surface_forms:
if len(surface) < self.MIN_SURFACE_LENGTH:
continue
pattern = _choice_pattern(ocr_fold(surface) if canonical else surface)
for match in pattern.finditer(text):
span = (match.start(), match.end())
# A longer surface already covers this one ("NIC III" over "NIC II").
if span in seen or any(s <= span[0] and span[1] <= e for s, e in taken):
continue
taken.append(span)
seen.add(span)
context = index.context(line_index, *span)
negates_itself = _negates_itself(surface)
if negates_itself and context.assertion is Assertion.NEGADO:
continue
value = spec.choices[surface]
if context.assertion is Assertion.NEGADO and not negates_itself:
if spec.negated_value is None:
continue
value = spec.negated_value
context = Context(Assertion.AFIRMADO, context.section, context.trigger)
reach = text[max(0, span[0] - ANCHOR_REACH) : span[0]]
anchored = bool(anchors and anchors.search(reach))
generic = is_generic(surface)
if generic and not anchored:
continue
found.append(Mention(value, line.text[span[0] : span[1]], line_index, context, anchored, generic))
return found
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
if spec.kind is not FieldKind.CHOICE or not spec.scan_free_text:
return
mentions = [m for m in self.mentions(spec, index) if m.weight > 0]
if not mentions:
return
total = sum(m.weight for m in mentions)
by_value: dict[Any, list[Mention]] = {}
for mention in mentions:
by_value.setdefault(mention.value, []).append(mention)
support = {value: sum(m.weight for m in group) for value, group in by_value.items()}
affirmed = [m for m in mentions if m.context.assertion is Assertion.AFIRMADO]
if spec.severity and affirmed:
winner_value = max((m.value for m in affirmed), key=lambda v: (spec.severity_rank(v), support[v]))
else:
top = max(support.values())
winner_value = [m for m in mentions if support[m.value] == top][-1].value
most_severe = max(by_value, key=spec.severity_rank) if spec.severity else None
def confidence_of(value: Any, best: Mention) -> float:
share = support[value] / total
return 0.65 * max(share, 0.5) * index.lines[best.line_index].ocr_confidence * best.weight
best_of = {value: max(group, key=lambda m: (m.weight, m.line_index)) for value, group in by_value.items()}
winner_confidence = confidence_of(winner_value, best_of[winner_value])
for value, group in by_value.items():
best = best_of[value]
line = index.lines[best.line_index]
share = support[value] / total
confidence = winner_confidence
if value != winner_value:
# The others stay below the winner, so ranking by confidence picks it.
confidence = min(0.8 * confidence_of(value, best), 0.9 * winner_confidence)
features = {
"assertion": best.context.assertion.value,
"section": best.context.section.value,
"share": share,
"mentions": len(group),
"anchored": best.anchored,
"generic": best.generic,
"most_severe": spec.severity and value == most_severe,
"last_mention": best.line_index == max(m.line_index for m in mentions),
"position": index.position(best.line_index),
"ocr": line.ocr,
}
yield ExtractedValue(value, confidence, self.method, best.raw, line.evidence(), features)
class MeasurementExtractor(FieldExtractor):
"""A number written with its unit after the field's concept, in the same
clause ("ritmo de fondo de 8 a 9 Hz"), for fields with a `unit`. A range
gives its midpoint."""
method = "medicion"
_NUMBER = r"\d+(?:[.,]\d+)?"
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
if not spec.unit or spec.kind not in (FieldKind.DECIMAL, FieldKind.INTEGER):
return
anchors = _anchor_pattern(_anchor_terms(spec))
measure = re.compile(
rf"(?<![\w.,])(?P<low>{self._NUMBER})(?:\s*(?:-|A|Y|AL)\s*(?P<high>{self._NUMBER}))?\s*(?:{spec.unit})(?![A-Z])"
)
for line_index, line in enumerate(index.lines):
folded = line.folded
for match in measure.finditer(folded):
reach = folded[max(0, match.start() - ANCHOR_REACH) : match.start()]
anchor = anchors.search(reach) if anchors else None
if anchor is None:
continue
if re.search(r"[.;]", reach[anchor.end() :]):
continue
low = float(match.group("low").replace(",", "."))
high = float(match.group("high").replace(",", ".")) if match.group("high") else low
value: float | int = (low + high) / 2
if spec.kind is FieldKind.INTEGER:
value = int(round(value))
context = index.context(line_index, match.start(), match.end())
if context.assertion is Assertion.NEGADO:
continue
features = {
"assertion": context.assertion.value,
"section": context.section.value,
"anchored": True,
"range": match.group("high") is not None,
"position": index.position(line_index),
"ocr": line.ocr,
}
confidence = 0.8 * line.ocr_confidence * ASSERTION_WEIGHT[context.assertion]
yield ExtractedValue(value, confidence, self.method, line.text[match.start() : match.end()], line.evidence(), features)
DEFAULT_EXTRACTORS: tuple[FieldExtractor, ...] = (
LabeledValueExtractor(),
PatternExtractor(),
FreeTextMentionExtractor(),
MeasurementExtractor(),
)
class RecordExtractor:
"""Every candidate of every field, then one per field: the ranker's pick
(`extraction.nlp.ranking`), by default the most confident."""
def __init__(self, specs: Sequence[FieldSpec], *, extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS, ranker=None):
from extraction.nlp.ranking import HeuristicRanker
self.specs = list(specs)
self.extractors = list(extractors)
self.ranker = ranker or HeuristicRanker()
def candidates(self, lines: Sequence[SegmentLine]) -> dict[str, list[ExtractedValue]]:
index = LabelIndex(lines, self.specs)
found: dict[str, list[ExtractedValue]] = {}
for spec in self.specs:
proposed = [candidate for extractor in self.extractors for candidate in extractor.candidates(spec, index)]
if proposed:
found[spec.name] = describe_candidates(proposed)
return found
def choose(self, candidates: dict[str, list[ExtractedValue]]) -> dict[str, ExtractedValue]:
specs = {spec.name: spec for spec in self.specs}
chosen = {}
for name, proposed in candidates.items():
best = self.ranker.choose(specs[name], proposed)
if best is not None:
chosen[name] = best
return chosen
def extract(self, lines: Sequence[SegmentLine]) -> dict[str, ExtractedValue]:
return self.choose(self.candidates(lines))
def describe_candidates(proposed: list[ExtractedValue]) -> list[ExtractedValue]:
"""Adds what only the set of a field's candidates tells: how each ranks
by confidence, how many there are and how many others agree with it."""
ordered = sorted(proposed, key=lambda c: -c.confidence)
values = Counter(_comparable(c.value) for c in proposed)
methods: dict[Any, set[str]] = {}
for candidate in proposed:
methods.setdefault(_comparable(candidate.value), set()).add(candidate.method)
return [
candidate.with_confidence(
candidate.confidence,
rank=rank,
candidates=len(proposed),
distinct_values=len(values),
agreeing=values[_comparable(candidate.value)] - 1,
agreeing_methods=len(methods[_comparable(candidate.value)]) - 1,
)
for rank, candidate in enumerate(ordered)
]
def _comparable(value: Any) -> Any:
return fold(value).strip() if isinstance(value, str) else value