Files
ISSSTELEON/Extraction/extraction/nlp/score_tables.py
T

259 lines
11 KiB
Python

"""Read item scores from positioned rows in clinical tables."""
import re
from collections.abc import Iterator
from dataclasses import dataclass
from functools import cached_property
from itertools import groupby
from extraction.nlp.extractors import FieldExtractor, LabelIndex, SegmentLine, _folded_label, _fuzzy_hits
from extraction.nlp.fields import Evidence, ExtractedValue, FieldSpec
from extraction.nlp.text import fold
from extraction.nlp.vocabulary import SCORE_TABLES
COLUMN_TOLERANCE = 0.025
@dataclass(frozen=True)
class ScoreTable:
"""Captions, score syntax, and variant-specific column mappings."""
anchors: tuple[str, ...]
continuation_anchors: tuple[str, ...]
end_markers: tuple[str, ...]
variants: dict[str, dict[str, str]]
totals: dict[str, tuple[str, ...]]
value_pattern: str
missing_token: str
metadata: dict[str, dict[str, str]]
printed_metadata: dict[str, tuple[str, str]]
unmapped_items: dict[str, dict[str, str]]
aliases: dict[str, tuple[str, ...]]
@cached_property
def total_groups(self) -> dict[str, tuple[str, ...]]:
return {_folded_label(label): prefixes for label, prefixes in self.totals.items()}
@cached_property
def captions(self) -> dict[str, dict[str, str]]:
return {
variant: {
_folded_label(caption): name
for label, name in fields.items()
for caption in (label, *self.aliases.get(label, ()))
}
for variant, fields in self.variants.items()
}
@cached_property
def descriptions(self) -> frozenset[str]:
return frozenset(label for captions in self.captions.values() for label in captions)
@cached_property
def fields(self) -> frozenset[str]:
items = {name for fields in self.variants.values() for name in fields.values()}
return frozenset(items.union(*(fields.keys() for fields in self.metadata.values())))
def match(self, caption: str) -> frozenset[str]:
if caption in self.descriptions:
return frozenset((caption,))
scores = {
label: hit.score
for label in self.descriptions
for hit in _fuzzy_hits(caption, label, label)
if hit.start == 0 and hit.end == len(caption)
}
best = max(scores.values(), default=0.0)
return frozenset(label for label, score in scores.items() if score == best)
@dataclass(frozen=True)
class _Row:
caption: str
token: str
evidence: Evidence
labels: frozenset[str]
@dataclass(frozen=True)
class _Page:
lines: list[SegmentLine]
rows: list[_Row]
anchored: bool
restricted: bool
ended: bool
class ScoreTableExtractor(FieldExtractor):
"""Propose scores from the item set that best explains a table."""
method = "tabla_puntajes"
def __init__(self):
self.tables = {name: ScoreTable(**config) for name, config in SCORE_TABLES.items()}
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterator[ExtractedValue]:
for name, table in self.tables.items():
if spec.name not in table.fields:
continue
if name not in index.score_tables:
values, flags = self._read(table, index.lines)
index.score_tables[name] = values
index.flags.update(flags)
candidate = index.score_tables[name].get(spec.name)
if candidate is not None:
yield candidate
def _read(self, table: ScoreTable, lines: list[SegmentLine]) -> tuple[dict[str, ExtractedValue], set[str]]:
pages = [_read_page(table, list(group)) for _, group in
groupby(lines, key=lambda line: (line.document, line.page_number))]
best = None
ambiguous = False
for position, page in enumerate(pages):
following = pages[position + 1] if position + 1 < len(pages) else None
rows = page.rows
if (
following and page.rows and not page.restricted and not page.ended
and following.restricted and following.lines[0].document == page.lines[0].document
and following.lines[0].page_number == page.lines[0].page_number + 1
):
rows = rows + following.rows
if not any(row.labels for row in rows):
continue
ranked = sorted(
((_coverage(table, variant, rows), variant) for variant in table.variants),
reverse=True,
)
score, variant = ranked[0]
tied = len(ranked) > 1 and score == ranked[1][0]
if score < (0.5 if page.anchored else 0.75):
ambiguous |= tied or score < 0.5
continue
priority = (score, page.anchored)
if best is None or priority > best[0]:
best = priority, variant, tied, page, rows
if best is None:
return {}, {"modulo_ambiguo"} if ambiguous else set()
_, variant, tied, page, rows = best
if tied:
return {}, {"modulo_ambiguo"}
return self._values(table, variant, page, rows)
def _values(
self, table: ScoreTable, variant: str, page: _Page, rows: list[_Row]
) -> tuple[dict[str, ExtractedValue], set[str]]:
scores = {}
subtotal_items = {}
totals = {}
features = {}
for row in rows:
if row.token == table.missing_token:
continue
value = int(row.token)
if row.caption in table.total_groups:
totals.setdefault(table.total_groups[row.caption], []).append(value)
continue
if field := _field_for(table, variant, row):
scores.setdefault(field, (value, row.token, row.evidence))
elif prefix := _unmapped_prefix(table, variant, row):
subtotal_items[row.caption] = (prefix, value)
expected = set(table.total_groups.values())
totals_match = bool(totals) and expected == totals.keys()
for prefixes, printed in totals.items():
actual = sum(value for field, (value, _, _) in scores.items() if field.startswith(prefixes))
actual += sum(value for prefix, value in subtotal_items.values() if prefix in prefixes)
totals_match &= all(value == actual for value in printed)
confidence = 0.95 if totals_match else 0.6
if not totals_match:
features["totales_no_cuadran"] = True
evidence = next(row.evidence for row in rows if _field_for(table, variant, row))
for field, value in table.metadata.get(variant, {}).items():
if field in table.printed_metadata:
pattern, format_value = table.printed_metadata[field]
printed = next((match for line in page.lines if (match := re.search(pattern, line.folded))), None)
if printed and format_value.format(printed[1]) != value:
features["modulo_no_coincide"] = True
scores[field] = (value, str(value), evidence)
if features.get("modulo_no_coincide"):
confidence *= 0.8
return {
field: ExtractedValue(value, confidence, self.method, raw, source, features)
for field, (value, raw, source) in scores.items()
}, set(features)
def _field_for(table: ScoreTable, variant: str, row: _Row) -> str | None:
captions = table.captions[variant]
matches = {captions[label] for label in row.labels if label in captions}
return matches.pop() if len(matches) == 1 else None
def _unmapped_prefix(table: ScoreTable, variant: str, row: _Row) -> str | None:
return next((prefix for label, prefix in table.unmapped_items.get(variant, {}).items()
if _folded_label(label) in row.labels), None)
def _coverage(table: ScoreTable, variant: str, rows: list[_Row]) -> float:
matched = set()
foreign = 0
count = 0
for row in rows:
if row.caption in table.total_groups or _unmapped_prefix(table, variant, row):
continue
count += 1
if field := _field_for(table, variant, row):
matched.add(field)
else:
foreign += 1
return len(matched) / len(set(table.variants[variant].values())) - foreign / max(count, 1)
def _read_page(table: ScoreTable, lines: list[SegmentLine]) -> _Page:
anchors = {_folded_label(label) for label in table.anchors}
continuation = {_folded_label(label) for label in table.continuation_anchors}
end = {_folded_label(label) for label in table.end_markers}
headings = [_folded_label(line.text) for line in lines]
start = next((i for i, label in enumerate(headings) if label in anchors - continuation), 0)
cells = []
ended = False
for line, heading in zip(lines[start:], headings[start:]):
words = line.line.words
if len(words) >= 2:
token = fold(words[-1].text)
caption = _folded_label(" ".join(word.text for word in words[:-1]))
if token == table.missing_token or re.fullmatch(table.value_pattern, token) or (
token.isdecimal() and caption in table.total_groups
):
cells.append((line, words[-1].center, caption, token))
if caption in end:
ended = True
break
continue
cells.append((line, None, heading, ""))
if heading in end:
ended = True
break
positions = [x for _, x, _, _ in cells if x is not None]
if not positions:
return _Page(lines, [], bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)
column = max(positions, key=lambda x: (sum(abs(x - other) <= COLUMN_TOLERANCE for other in positions), x))
rows = []
previous = None
for line, x, caption, token in cells:
if x is None or abs(x - column) > COLUMN_TOLERANCE:
previous = line if x is None and caption not in anchors else None
continue
evidence = line.evidence()
labels = table.match(caption) if caption not in table.total_groups else frozenset()
if not labels and caption not in table.total_groups and previous is not None:
joined = f"{_folded_label(previous.text)} {caption}"
if joined_labels := table.match(joined):
caption, labels = joined, joined_labels
first, last = previous.line.bbox, line.line.bbox
bbox = [min(first.x0, last.x0), first.y0, max(first.x1, last.x1), last.y1]
evidence = Evidence(line.document, line.page_number, f"{previous.text} {line.text}",
[round(position, 4) for position in bbox])
rows.append(_Row(caption, token, evidence, labels))
previous = None
return _Page(lines, rows, bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)