Files
ISSSTELEON/Extraction/tests/test_nlp.py
T
edgar 8fc3dda18a CaCu glandular cytology result: catalog, timeline, extraction vocabulary and the surveillance rule
The glandular result (`citologia.celulas_glandulares`) is a closed result with the codes AGC and ADENOCARCINOMA, one of
KPNC's six cytology categories. The timeline carries it as `glandular`; the surveillance cohort's `no_index_result`
counts it; the extractor maps the Bethesda wordings to its codes. Known gap: "adenocarcinoma in situ" is still read as
ADENOCARCINOMA (no AIS code in the catalog).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:17:48 -06:00

127 lines
5.6 KiB
Python

from datetime import date
from extraction.document import BBox, Line
from extraction.nlp import FieldKind, FieldSpec, RecordExtractor, SegmentLine
from extraction.nlp.text import find_date, find_decimal, find_integer, fold
from extraction.nlp.vocabulary import CLINICAL_TERMS, SEVERITY, labels_for
SEXO = FieldSpec("pac_sexo", FieldKind.CHOICE, labels=("sexo",), choices={"F": "Femenino", "FEMENINO": "Femenino", "M": "Masculino"})
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento", "f. nac"))
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
CP = FieldSpec("pac_codigo_postal", FieldKind.TEXT, labels=("c.p.",), pattern=r"^\d{5}$")
VPH = FieldSpec(
"cit_vph_resultado",
FieldKind.CHOICE,
labels=("vph alto riesgo",),
choices={"POSITIVO": "POSITIVO", "NEGATIVO": "NEGATIVO", "NO DETECTADO": "NEGATIVO", "DETECTADO": "POSITIVO"},
scan_free_text=True,
)
CIN = 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,
)
OBSERVACIONES = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("observaciones",), multiline=True)
GLANDULARES = FieldSpec(
"cit_celulas_glandulares",
FieldKind.CHOICE,
labels=labels_for("cit_celulas_glandulares"),
choices=CLINICAL_TERMS["cit_celulas_glandulares"],
scan_free_text=True,
severity=SEVERITY["cit_celulas_glandulares"],
)
def lines(*texts: str, confidence: float = 1.0) -> list[SegmentLine]:
return [SegmentLine("doc.pdf", 1, Line(text, BBox(0, i / 40, 1, (i + 1) / 40), confidence)) for i, text in enumerate(texts)]
def test_fold_keeps_length_and_drops_accents():
assert fold("Diagnóstico: Lesión") == "DIAGNOSTICO: LESION"
assert len(fold("Ñandú ß")) == len("Ñandú ß")
def test_dates_in_spanish_formats():
assert find_date("Nació el 15/01/1990 en Monterrey")[0] == date(1990, 1, 15)
assert find_date("15 de enero de 2024")[0] == date(2024, 1, 15)
assert find_date("Fecha: 3-ABR-2023")[0] == date(2023, 4, 3)
assert find_date("2024-02-29")[0] == date(2024, 2, 29)
assert find_date("sin fecha") is None
def test_decimal_with_comma():
assert find_decimal("Hb 12,5 g/dL")[0] == 12.5
assert find_decimal("1,250 plaquetas")[0] == 1250.0
def test_integer_is_not_read_out_of_a_decimal():
assert find_integer("Edad: 34 años")[0] == 34
assert find_integer("12.5") is None
assert find_integer("12,5") is None
assert find_integer("peso 12.5 kg, talla 98 cm")[0] == 98
def test_several_labels_on_one_form_line():
found = RecordExtractor([EXPEDIENTE, SEXO, CP]).extract(lines("Expediente: EXP-0042 Sexo: F C.P.: 01000"))
assert found["pac_id_hospital"].value == "EXP-0042"
assert found["pac_sexo"].value == "Femenino"
assert found["pac_codigo_postal"].value == "01000"
def test_value_on_line_below_label():
found = RecordExtractor([NACIMIENTO]).extract(lines("Fecha de nacimiento", "02/05/1985"))
assert found["pac_fecha_nacimiento"].value == date(1985, 5, 2)
def test_ocr_misread_label_is_still_found():
found = RecordExtractor([NACIMIENTO]).extract(lines("Fecha de nac1miento: 02/05/1985"))
assert found["pac_fecha_nacimiento"].value == date(1985, 5, 2)
assert found["pac_fecha_nacimiento"].confidence < 0.95
def test_longest_choice_wins_over_its_substring():
found = RecordExtractor([VPH]).extract(lines("VPH alto riesgo: NO DETECTADO"))
assert found["cit_vph_resultado"].value == "NEGATIVO"
def test_free_text_mention_with_negation():
text = lines(
"Se recibe fragmento de cérvix.",
"No se observa carcinoma invasor.",
"Los hallazgos son compatibles con NIC II.",
)
found = RecordExtractor([CIN]).extract(text)
assert found["bx_cin_grado"].value == "LIEAG"
assert found["bx_cin_grado"].method == "texto_libre"
def test_labeled_value_beats_free_text_mention():
text = lines("Diagnóstico: NIC I", "Previamente reportado como NIC III")
assert RecordExtractor([CIN]).extract(text)["bx_cin_grado"].value == "LIEBG"
def test_multiline_text_stops_at_next_label():
text = lines("Observaciones: muestra con", "abundante moco cervical", "Sexo: F")
found = RecordExtractor([OBSERVACIONES, SEXO]).extract(text)
assert found["cit_observaciones"].value == "muestra con abundante moco cervical"
def test_low_ocr_confidence_lowers_value_confidence():
clean = RecordExtractor([SEXO]).extract(lines("Sexo: F"))["pac_sexo"].confidence
noisy = RecordExtractor([SEXO]).extract(lines("Sexo: F", confidence=0.6))["pac_sexo"].confidence
assert noisy < clean
def test_glandular_atypical_cells_wording_maps_to_agc():
"""Pins down that a cytology line naming atypical glandular cells maps to the catalog value AGC, using the vocabulary's glandular CLINICAL_TERMS as the field's choices. Fails if those terms are missing from the vocabulary, not built into the field, or mapped to another value."""
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: células glandulares atípicas"))
assert found["cit_celulas_glandulares"].value == "AGC"
def test_adenocarcinoma_endocervical_wording_maps_to_adenocarcinoma():
"""Pins down that a cytology line naming endocervical adenocarcinoma maps to the catalog value ADENOCARCINOMA through the vocabulary's glandular CLINICAL_TERMS. Fails if the term is missing from the vocabulary or mapped to AGC or to nothing."""
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: adenocarcinoma endocervical"))
assert found["cit_celulas_glandulares"].value == "ADENOCARCINOMA"