163 lines
8.4 KiB
Python
163 lines
8.4 KiB
Python
"""Fields read from narrative text and from OCR: generic answers that need
|
|
their concept next to them, the most severe of several findings, what a
|
|
denied mention means for a presence field, measurements with units, OCR
|
|
look-alike characters, date captions that name the time too, and text the
|
|
report only supposes. Also the subject check that keeps one kind of report
|
|
from filling another kind's fields.
|
|
|
|
Fixtures: none; field specs are declared at module level and lines and
|
|
documents are built inline (`lines` below, `text_pdf` from
|
|
`extraction.testing`).
|
|
"""
|
|
from datetime import date
|
|
|
|
from extraction import DocumentExtractor, FieldKind, FieldSpec, read_document
|
|
from extraction.document import BBox, Line
|
|
from extraction.nlp import RecordExtractor, SegmentLine
|
|
from extraction.segmentation import WholeDocument
|
|
from extraction.testing import text_pdf
|
|
|
|
VPH = FieldSpec(
|
|
"cit_vph_resultado",
|
|
FieldKind.CHOICE,
|
|
labels=("resultado vph",),
|
|
choices={"POSITIVO": "POSITIVO", "NEGATIVO": "NEGATIVO"},
|
|
scan_free_text=True,
|
|
anchors=("vph", "papiloma"),
|
|
)
|
|
GRADO = FieldSpec(
|
|
"bx_cin_grado",
|
|
FieldKind.CHOICE,
|
|
labels=("diagnóstico",),
|
|
choices={"NIC I": "LIEBG", "NIC II": "LIEAG", "NIC III": "LIEAG", "CARCINOMA INVASOR": "CARCINOMA"},
|
|
scan_free_text=True,
|
|
severity=("NORMAL", "LIEBG", "LIEAG", "CIS", "CARCINOMA"),
|
|
)
|
|
EPILEPTIFORME = FieldSpec(
|
|
"eeg_actividad_epileptiforme",
|
|
FieldKind.CHOICE,
|
|
choices={"ACTIVIDAD EPILEPTIFORME": 1, "PUNTAS": 1},
|
|
scan_free_text=True,
|
|
negated_value=0,
|
|
)
|
|
FRECUENCIA = FieldSpec("eeg_ritmo_base_frecuencia", FieldKind.DECIMAL, anchors=("ritmo de fondo",), unit=r"HZ")
|
|
AMPLITUD = FieldSpec("eeg_ritmo_base_amplitud", FieldKind.INTEGER, anchors=("amplitud",), unit=r"[µU]\s*V")
|
|
EMISION = FieldSpec("bx_fecha_reporte", FieldKind.DATE, labels=("fecha de emisión",))
|
|
|
|
|
|
def lines(*texts: str, ocr: bool = False) -> list[SegmentLine]:
|
|
return [SegmentLine("doc.pdf", 1, Line(text, BBox(0, i / 40, 1, (i + 1) / 40)), ocr) for i, text in enumerate(texts)]
|
|
|
|
|
|
def test_a_generic_answer_needs_its_concept():
|
|
""""POSITIVO" alone says nothing about which test; after "VPH" it does.
|
|
Fails if generic answers are taken without an anchor, which fills the
|
|
HPV result from any positive line of a cytology form."""
|
|
assert "cit_vph_resultado" not in RecordExtractor([VPH]).extract(lines("Diagnóstico para lesión: POSITIVO"))
|
|
found = RecordExtractor([VPH]).extract(lines("Se detectó virus del papiloma humano de alto riesgo, positivo."))
|
|
assert found["cit_vph_resultado"].value == "POSITIVO"
|
|
|
|
|
|
def test_the_most_severe_affirmed_finding_wins():
|
|
"""Two specimens, two grades: the worse one is the finding, wherever it
|
|
is written. Fails if repetition or order outvotes severity."""
|
|
found = RecordExtractor([GRADO]).extract(lines("Fragmento A: NIC III.", "Fragmento B: NIC I.", "Fragmento C: NIC I."))
|
|
assert found["bx_cin_grado"].value == "LIEAG"
|
|
|
|
|
|
def test_a_presumed_diagnosis_does_not_beat_the_final_one():
|
|
"""The request's suspicion (clinical section) is not the study's result.
|
|
Fails if a clinical caption's value outranks the diagnosis heading's."""
|
|
found = RecordExtractor([GRADO]).extract(lines("Diagnóstico clínico: NIC III", "Diagnóstico:", "NIC I"))
|
|
assert found["bx_cin_grado"].value == "LIEBG"
|
|
|
|
|
|
def test_a_denied_presence_reads_as_absent():
|
|
""""Sin actividad epileptiforme" means 0, not unknown. Fails if denied
|
|
mentions of a presence field are dropped instead of read as its
|
|
`negated_value`."""
|
|
found = RecordExtractor([EPILEPTIFORME]).extract(lines("Trazo sin actividad epileptiforme durante el registro."))
|
|
assert found["eeg_actividad_epileptiforme"].value == 0
|
|
found = RecordExtractor([EPILEPTIFORME]).extract(lines("Se registran puntas en región temporal izquierda."))
|
|
assert found["eeg_actividad_epileptiforme"].value == 1
|
|
|
|
|
|
def test_measurements_with_units_after_their_concept():
|
|
"""A range gives its midpoint; each unit fills its own field. Fails if
|
|
`MeasurementExtractor` stops requiring the concept or mixes units."""
|
|
found = RecordExtractor([FRECUENCIA, AMPLITUD]).extract(lines("Ritmo de fondo de 7 a 8 Hz con amplitud de 60 uV, reactivo."))
|
|
assert found["eeg_ritmo_base_frecuencia"].value == 7.5
|
|
assert found["eeg_ritmo_base_amplitud"].value == 60
|
|
assert "eeg_ritmo_base_frecuencia" not in RecordExtractor([FRECUENCIA]).extract(lines("Fotoestimulación a 12 Hz sin cambios."))
|
|
|
|
|
|
def test_ocr_look_alikes_still_match_captions_and_terms():
|
|
"""`Dlagnóstico` and `NlC` are OCR misreads of `Diagnóstico` and `NIC`.
|
|
Fails if OCR lines stop falling back to `ocr_fold`."""
|
|
found = RecordExtractor([GRADO]).extract(lines("Dlagnóstlco: NlC II", ocr=True))
|
|
assert found["bx_cin_grado"].value == "LIEAG"
|
|
assert "bx_cin_grado" not in RecordExtractor([GRADO]).extract(lines("Dlagnóstlco: NlC II", ocr=False))
|
|
|
|
|
|
def test_a_date_caption_may_name_the_time():
|
|
"""Fails if `label_pattern` stops allowing "/hora" or "y hora" after "fecha"."""
|
|
found = RecordExtractor([EMISION]).extract(lines("Fecha/hora de emisión: 03/02/2025 10:15 hrs."))
|
|
assert found["bx_fecha_reporte"].value == date(2025, 2, 3)
|
|
found = RecordExtractor([EMISION]).extract(lines("Fecha y hora de emisión: 4 de marzo de 2025"))
|
|
assert found["bx_fecha_reporte"].value == date(2025, 3, 4)
|
|
|
|
|
|
def test_reference_text_fills_nothing():
|
|
"""Reference text printed under its heading describes no patient. Fails if mentions in a reference section can be chosen."""
|
|
found = RecordExtractor([VPH]).extract(lines("Valores de referencia", "Un resultado de VPH positivo indica infección."))
|
|
assert "cit_vph_resultado" not in found
|
|
|
|
|
|
def test_every_candidate_is_kept_with_how_it_was_found():
|
|
"""The ranker and the reviewer see all readings, with features but no
|
|
document text in them. Fails if `RecordExtractor.candidates` drops the
|
|
losers or features carry strings from the page."""
|
|
candidates = RecordExtractor([GRADO]).candidates(lines("Diagnóstico: NIC I", "Se observa NIC II en otro fragmento."))
|
|
values = {c.value for c in candidates["bx_cin_grado"]}
|
|
assert values == {"LIEBG", "LIEAG"}
|
|
for candidate in candidates["bx_cin_grado"]:
|
|
assert {"assertion", "section", "rank", "agreeing"} <= set(candidate.features)
|
|
assert all(not isinstance(v, str) or v.isidentifier() for v in candidate.features.values())
|
|
|
|
|
|
BIOPSIA = text_pdf([["ESTUDIO HISTOPATOLÓGICO", "Biopsia cervical dirigida", "Diagnóstico:", "NIC I", "Fecha de emisión: 05/05/2025"]])
|
|
SIN_TEMA = text_pdf([["Diagnóstico:", "NIC II", "Fecha de emisión: 06/06/2025"]])
|
|
|
|
|
|
def _extractor(**options) -> DocumentExtractor:
|
|
return DocumentExtractor([GRADO, EMISION], segmenter=WholeDocument(), merger=None, **options)
|
|
|
|
|
|
def test_a_report_about_another_study_fills_nothing():
|
|
"""A biopsy report fed to a cytology target names only a foreign
|
|
subject. Fails if `foreign` stops gating its values."""
|
|
document = read_document("biopsia.pdf", BIOPSIA)
|
|
[record] = _extractor(subject=("citología",), foreign=("biopsia", "histopatológico")).extract([document])
|
|
assert record.on_topic is False and record.values == {}
|
|
[record] = _extractor(subject=("biopsia",), foreign=("citología",)).extract([document])
|
|
assert record.on_topic is True and record.values["bx_cin_grado"].value == "LIEBG"
|
|
|
|
|
|
def test_a_report_that_names_no_subject_is_not_gated():
|
|
"""Only positive evidence of another kind of report gates. Fails if a
|
|
report that names no study at all is treated as off topic."""
|
|
[record] = _extractor(subject=("biopsia",), foreign=("citología",)).extract([read_document("x.pdf", SIN_TEMA)])
|
|
assert record.on_topic is None and record.values["bx_cin_grado"].value == "LIEAG"
|
|
|
|
|
|
def test_held_back_values_return_when_the_record_is_on_topic():
|
|
"""A page that names only a foreign subject, merged by key with a page
|
|
that names the target's, gives its values back. Fails if `withheld`
|
|
values are lost in the merge."""
|
|
key = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
|
pages = text_pdf([["Expediente: K-1", "Biopsia cervical dirigida", "Diagnóstico:", "NIC I"], ["Expediente: K-1", "Citología previa", "Fecha de emisión: 07/07/2025"]])
|
|
extractor = DocumentExtractor([key, GRADO, EMISION], key_field="pac_id_hospital", subject=("biopsia",), foreign=("citología",))
|
|
[record] = extractor.extract([read_document("k.pdf", pages)])
|
|
assert record.on_topic is True
|
|
assert record.values["bx_fecha_reporte"].value == date(2025, 7, 7)
|