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

186 lines
7.2 KiB
Python

"""What a report says about a mention: whether it affirms it, denies it, only
supposes it, or quotes it from somewhere else; and which section of the report
it sits in.
The approach is ConText (Harkema et al., 2009, J Biomed Inform 42:839), the
extension of NegEx (Chapman et al., 2001, J Biomed Inform 34:301) to
hypothetical, historical and uncertain mentions: trigger phrases before a
mention, within its clause, qualify it, and a clause ends at a terminator.
Two additions fit how forms and lab reports are laid out:
- form-style answers after the mention (`Carcinoma invasor: NO`);
- sections. A heading such as "Datos clínicos" or "Valores de referencia"
qualifies everything under it until the next heading: what the requesting
physician suspected is not the study's result, and an interpretation guide
printed on every report describes no patient.
Triggers and headings live in `extraction.nlp.vocabulary`.
"""
import re
from dataclasses import dataclass
from enum import Enum
from functools import lru_cache
from typing import Sequence
from extraction.nlp.text import fold
class Assertion(str, Enum):
AFIRMADO = "afirmado"
NEGADO = "negado"
INCIERTO = "incierto"
HIPOTETICO = "hipotetico"
HISTORICO = "historico"
PRESUNTIVO = "presuntivo"
class Section(str, Enum):
GENERAL = "general"
CLINICA = "clinica"
DESCRIPCION = "descripcion"
RESULTADO = "resultado"
ANTECEDENTES = "antecedentes"
REFERENCIA = "referencia"
# Sections whose content is about the patient's study as such.
REPORTING_SECTIONS = frozenset({Section.GENERAL, Section.DESCRIPCION, Section.RESULTADO})
# How far back, in characters, a trigger reaches within a clause.
TRIGGER_WINDOW = 60
@dataclass(frozen=True)
class Context:
assertion: Assertion
section: Section
trigger: str | None = None
def _alternatives(terms) -> str:
folded = sorted({" ".join(re.findall(r"[A-Z0-9]+", fold(t))) for t in terms if t.strip()}, key=len, reverse=True)
return "|".join(r"[\s.\-]+".join(re.escape(w) for w in term.split()) for term in folded)
@lru_cache(maxsize=1)
def _compiled():
from extraction.nlp.vocabulary import (
CLAUSE_TERMINATORS,
POST_AFFIRMATIONS,
POST_NEGATIONS,
PRE_TRIGGERS,
PSEUDO_TRIGGERS,
SECTION_HEADINGS,
)
pre = {
assertion: re.compile(rf"(?<![A-Z0-9])({_alternatives(terms)})(?![A-Z0-9])")
for assertion, terms in PRE_TRIGGERS.items()
}
pseudo = re.compile(rf"(?<![A-Z0-9])({_alternatives(PSEUDO_TRIGGERS)})(?![A-Z0-9])")
terminator = re.compile(rf"[.;:]|(?<![A-Z0-9])({_alternatives(CLAUSE_TERMINATORS)})(?![A-Z0-9])")
post_negation = re.compile(rf"^[\s.:=\-]*({_alternatives(POST_NEGATIONS)})(?![A-Z0-9])")
post_affirmation = re.compile(rf"^[\s.:=\-]*({_alternatives(POST_AFFIRMATIONS)})(?![A-Z0-9])")
headings = [
(section, re.compile(rf"^\s*(?:(?:\d{{1,3}}|[A-Z])\s*[.)][.\-]*\s*)?({_alternatives(terms)})(?![A-Z0-9])(?P<rest>.*)$"))
for section, terms in SECTION_HEADINGS.items()
]
return pre, pseudo, terminator, post_negation, post_affirmation, headings
def _heading(folded_line: str) -> tuple[Section, bool] | None:
"""The section a line's leading heading names, and whether the heading
stands alone (nothing but punctuation after it)."""
*_, headings = _compiled()
best: tuple[int, Section, bool] | None = None
for section, pattern in headings:
match = pattern.match(folded_line)
if not match:
continue
rest = match.group("rest")
if rest.strip() and not re.match(r"^\s*[:.\-]", rest):
continue
length = len(match.group(1))
if best is None or length > best[0]:
best = (length, section, not re.sub(r"[\s:.\-]", "", rest))
return (best[1], best[2]) if best else None
def heading_section(folded_line: str) -> Section | None:
"""The section a line's leading heading names: the heading alone, or
a caption followed by its content (`Metodología: PCR`)."""
found = _heading(folded_line)
return found[0] if found else None
def caption_section(folded_line: str, start: int) -> Section | None:
"""The section a caption earlier on the same line names (`... Diagnóstico
clínico: LIAG`), for a mention after it."""
before = folded_line[:start]
colon = before.rfind(":")
if colon < 0:
return None
caption_start = max(before.rfind(".", 0, colon), before.rfind(";", 0, colon), -1) + 1
return heading_section(before[caption_start : colon + 1])
def sections(folded_lines: Sequence[str]) -> list[Section]:
"""The section of each line: the last heading standing alone at or above
it. A caption with its content on the same line (`Metodología: PCR`)
qualifies only that line."""
current = Section.GENERAL
found = []
for line in folded_lines:
heading = _heading(line)
if heading is None:
found.append(current)
elif heading[1]:
current = heading[0]
found.append(current)
else:
found.append(heading[0])
return found
def assess(folded_line: str, start: int, end: int, section: Section = Section.GENERAL) -> Context:
"""The assertion of the mention at `folded_line[start:end]`."""
pre, pseudo, terminator, post_negation, post_affirmation, _ = _compiled()
named = caption_section(folded_line, start)
if named is not None:
section = named
clause_start = max((m.end() for m in terminator.finditer(folded_line, max(0, start - TRIGGER_WINDOW), start)), default=max(0, start - TRIGGER_WINDOW))
window = folded_line[clause_start:start]
for blocked in pseudo.finditer(window):
window = window[: blocked.start()] + " " * (blocked.end() - blocked.start()) + window[blocked.end() :]
for assertion in (Assertion.NEGADO, Assertion.HIPOTETICO, Assertion.HISTORICO, Assertion.INCIERTO):
pattern = pre.get(assertion)
found = pattern.search(window) if pattern else None
if found:
return Context(assertion, section, found.group(1))
after = folded_line[end : end + 30]
if re.match(r"^\s*:", after) and not post_affirmation.match(after):
# A caption asking about it (`Carcinoma invasor:`), answered elsewhere.
negated = post_negation.match(after)
return Context(Assertion.NEGADO if negated else Assertion.HIPOTETICO, section, negated.group(1) if negated else "rubro")
negated = post_negation.match(after)
if negated and not post_affirmation.match(after):
return Context(Assertion.NEGADO, section, negated.group(1))
if section is Section.REFERENCIA:
return Context(Assertion.HIPOTETICO, section, "seccion")
if section is Section.ANTECEDENTES:
return Context(Assertion.HISTORICO, section, "seccion")
if section is Section.CLINICA:
return Context(Assertion.PRESUNTIVO, section, "seccion")
return Context(Assertion.AFIRMADO, section)
# How much a mention's assertion leaves of the confidence of a value read from it.
ASSERTION_WEIGHT = {
Assertion.AFIRMADO: 1.0,
Assertion.INCIERTO: 0.75,
Assertion.PRESUNTIVO: 0.35,
Assertion.HISTORICO: 0.35,
Assertion.HIPOTETICO: 0.15,
Assertion.NEGADO: 0.0,
}