211 lines
10 KiB
Python
211 lines
10 KiB
Python
"""Reading documents whose layout is not one caption and value per line:
|
|
forms laid out in columns, captions the vocabulary doesn't know, item
|
|
numbers, abbreviated captions, overprinted text, pages that are mostly
|
|
a scanned image, and letterheads that repeat across patients. Also how
|
|
values handed over by a structured source key and group records.
|
|
|
|
Fixtures: none; every document is built inline with `text_pdf` or
|
|
`scanned_pdf` from `extraction.testing`, and field specs are declared at
|
|
module level below.
|
|
"""
|
|
import io
|
|
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.nlp.vocabulary import labels_for
|
|
from extraction.testing import page_image, scanned_pdf, text_pdf
|
|
|
|
KEY = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
|
CALIDAD = FieldSpec("cit_calidad_especimen", FieldKind.TEXT, labels=("calidad de la muestra",))
|
|
RESULTADO = FieldSpec(
|
|
"cit_vph_resultado",
|
|
FieldKind.CHOICE,
|
|
labels=("resultado",),
|
|
choices={"POSITIVO": "POSITIVO", "NEGATIVO": "NEGATIVO"},
|
|
)
|
|
REPORTE = FieldSpec("cit_fecha_reporte", FieldKind.DATE, labels=("fecha de reporte",))
|
|
ORDEN = FieldSpec("ord_numero_hospital", FieldKind.INTEGER, labels=("orden",))
|
|
NOTAS = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("observaciones",), multiline=True)
|
|
SPECS = [KEY, CALIDAD, RESULTADO, REPORTE, ORDEN, NOTAS]
|
|
|
|
|
|
def extract(raw: bytes) -> dict:
|
|
[record] = DocumentExtractor(SPECS, key_field="pac_id_hospital", merger=None).extract([read_document("d.pdf", raw)])
|
|
return record.row()
|
|
|
|
|
|
def lines(*texts: str) -> list[SegmentLine]:
|
|
return [SegmentLine("d.pdf", 1, Line(text, BBox(0, i / 40, 1, (i + 1) / 40))) for i, text in enumerate(texts)]
|
|
|
|
|
|
def test_captions_in_columns_take_the_value_under_each():
|
|
"""Two captions on one row with their values on the next row, each in
|
|
its own column. Fails if a caption takes the whole next line instead
|
|
of the words under it (`LabelIndex.column`)."""
|
|
raw = text_pdf(
|
|
[[
|
|
"Expediente: A-1",
|
|
[(60, "Calidad de la muestra:"), (320, "Resultado:")],
|
|
[(60, "ADECUADA"), (320, "NEGATIVO")],
|
|
]]
|
|
)
|
|
row = extract(raw)
|
|
assert row["cit_calidad_especimen"] == "ADECUADA"
|
|
assert row["cit_vph_resultado"] == "NEGATIVO"
|
|
|
|
|
|
def test_item_numbers_belong_to_the_next_caption():
|
|
"""`1.- Calidad de la muestra: 2.- Resultado:` must not read `2.-` as
|
|
the first caption's value. Fails if item numbers stop being folded
|
|
into the caption they precede (`_caption_start`)."""
|
|
raw = text_pdf(
|
|
[[
|
|
"Expediente: A-2",
|
|
[(60, "1.- Calidad de la muestra:"), (320, "2.- Resultado:")],
|
|
[(60, "ADECUADA"), (320, "POSITIVO")],
|
|
]]
|
|
)
|
|
row = extract(raw)
|
|
assert row["cit_calidad_especimen"] == "ADECUADA"
|
|
assert row["cit_vph_resultado"] == "POSITIVO"
|
|
|
|
|
|
def test_an_unknown_caption_ends_the_value_before_it():
|
|
"""A caption no field knows still marks where the previous value ends,
|
|
both on the same line and on the lines below. Fails if only known
|
|
labels bound a value (`_boundaries`)."""
|
|
found = RecordExtractor([NOTAS]).extract(
|
|
lines("Observaciones: sin cambios", "en el control", "Responsable de la toma: Persona X")
|
|
)
|
|
assert found["cit_observaciones"].value == "sin cambios en el control"
|
|
|
|
|
|
def test_abbreviated_captions_and_left_out_connectors_match():
|
|
"""`Fech. reporte` names the same field as `fecha de reporte`. Fails
|
|
if `label_pattern` stops accepting abbreviations ending in a period or
|
|
stops treating connector words as optional."""
|
|
found = RecordExtractor([REPORTE]).extract(lines("Fech. reporte: 03/04/2025"))
|
|
assert found["cit_fecha_reporte"].value == date(2025, 4, 3)
|
|
|
|
|
|
def test_a_caption_may_run_on_before_its_colon():
|
|
"""`Resultado obtenido en la prueba: POSITIVO` still reads the value
|
|
after the colon. Fails if a known label followed by a few more words
|
|
and a colon is no longer taken as a caption."""
|
|
found = RecordExtractor([RESULTADO]).extract(lines("Resultado obtenido en la prueba: POSITIVO"))
|
|
assert found["cit_vph_resultado"].value == "POSITIVO"
|
|
|
|
|
|
def test_an_integer_field_does_not_read_a_date():
|
|
"""`Orden: 12/03/2025` holds a date, not order number 12. Fails if
|
|
`parse_value` reads the day of a date as an integer."""
|
|
found = RecordExtractor([ORDEN]).extract(lines("Orden: 12/03/2025"))
|
|
assert "ord_numero_hospital" not in found
|
|
|
|
|
|
def test_schema_descriptions_become_captions_without_item_codes():
|
|
"""A description such as `B7 Calidad de la toma: notas` yields the
|
|
caption `Calidad de la toma`. Fails if `labels_for` keeps the leading
|
|
item code or the explanation after the colon."""
|
|
assert "Calidad de la toma" in labels_for("cit_calidad_especimen", "B7 Calidad de la toma: notas")
|
|
|
|
|
|
def test_overprinted_text_is_read_once():
|
|
"""Text drawn several times a fraction of a point apart (fake bold)
|
|
reads as one copy. Fails if the PDF reader stops deduplicating
|
|
glyphs (`dedupe_chars`)."""
|
|
document = read_document("b.pdf", text_pdf([["Expediente: A-3", "Resultado: POSITIVO"]], overprint=3))
|
|
assert "Resultado: POSITIVO" in document.pages[0].text
|
|
|
|
|
|
def test_a_scan_under_a_thin_text_layer_is_ocred():
|
|
"""A page that is a full-page image with only a short stamped text
|
|
layer is OCRed, so the content in the image is read. Fails if a few
|
|
characters of text layer are enough to skip OCR on a scanned page."""
|
|
picture = io.BytesIO()
|
|
page_image(["Expediente: A-4", "Resultado: NEGATIVO"]).save(picture, format="PNG")
|
|
raw = text_pdf([["Hoja 1"]], background_page=picture.getvalue())
|
|
document = read_document("h.pdf", raw)
|
|
assert document.pages[0].source == "ocr"
|
|
assert "NEGATIVO" in document.pages[0].text
|
|
|
|
|
|
def test_a_page_scanned_upside_down_is_read_after_turning_it():
|
|
"""OCR retries at the orientation Tesseract detects when the first
|
|
reading is poor. Fails if `TesseractOcr.read_lines` stops retrying
|
|
rotated pages."""
|
|
lines_ = ["Expediente: A-5", "Resultado del estudio: NEGATIVO", "Observaciones: sin cambios en el control"] * 3
|
|
document = read_document("r.pdf", scanned_pdf([lines_], rotate=180))
|
|
assert "NEGATIVO" in document.pages[0].text
|
|
|
|
|
|
def test_source_fields_key_records_and_outrank_the_text():
|
|
"""A value handed over by a structured source keys the record and wins
|
|
over what the page prints. Fails if `source_fields` stops reaching the
|
|
key or loses to a text reading."""
|
|
raw = text_pdf([["Expediente: OTRO-1", "Resultado: POSITIVO"]])
|
|
[record] = DocumentExtractor(SPECS, key_field="pac_id_hospital").extract(
|
|
[read_document("d.pdf", raw)], source_fields={"d.pdf": {"pac_id_hospital": "K-9", "ord_numero_hospital": "77"}}
|
|
)
|
|
assert record.key == "K-9"
|
|
assert record.row()["ord_numero_hospital"] == 77
|
|
|
|
|
|
def test_record_keys_group_documents_apart_from_the_key_field():
|
|
"""Documents of one patient under two record keys stay two records;
|
|
two documents under one record key merge. Fails if `record_keys` stops
|
|
overriding the key field when records are merged."""
|
|
first = read_document("a.pdf", text_pdf([["Expediente: P-1", "Resultado: POSITIVO"]]))
|
|
second = read_document("b.pdf", text_pdf([["Expediente: P-1", "Calidad de la muestra: ADECUADA"]]))
|
|
third = read_document("c.pdf", text_pdf([["Expediente: P-1", "Resultado: NEGATIVO"]]))
|
|
records = DocumentExtractor(SPECS, key_field="pac_id_hospital").extract(
|
|
[first, second, third], record_keys={"a.pdf": "O-1", "b.pdf": "O-1", "c.pdf": "O-2"}
|
|
)
|
|
by_key = {record.key: record.row() for record in records}
|
|
assert set(by_key) == {"O-1", "O-2"}
|
|
assert by_key["O-1"]["cit_calidad_especimen"] == "ADECUADA"
|
|
assert by_key["O-2"]["cit_vph_resultado"] == "NEGATIVO"
|
|
assert by_key["O-1"]["pac_id_hospital"] == "P-1"
|
|
|
|
|
|
CP = FieldSpec("pac_codigo_postal", FieldKind.TEXT, labels=("cp", "c.p."), pattern=r"(?<!\d)\d{5}(?!\d)")
|
|
NOMBRE = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("nombre",))
|
|
LETTERHEAD = "Clinica Ejemplo, Av. Uno 100, Col. Centro CP: 12345"
|
|
|
|
|
|
def test_an_issuers_letterhead_fills_no_patient_field():
|
|
"""The same address line atop two different patients' reports is the
|
|
issuer's, so its postal code is nobody's. Fails if margin lines shared
|
|
across patients stop being treated as template (`template_lines`)."""
|
|
first = read_document("a.pdf", text_pdf([[LETTERHEAD, "Expediente: A-10", "Resultado: POSITIVO"]]))
|
|
second = read_document("b.pdf", text_pdf([[LETTERHEAD, "Expediente: A-11", "Resultado: NEGATIVO"]]))
|
|
records = DocumentExtractor([KEY, CP, RESULTADO], key_field="pac_id_hospital").extract([first, second])
|
|
assert {r.key for r in records} == {"A-10", "A-11"}
|
|
assert all("pac_codigo_postal" not in r.row() for r in records)
|
|
assert {r.row()["cit_vph_resultado"] for r in records} == {"POSITIVO", "NEGATIVO"}
|
|
|
|
|
|
def test_a_letterhead_read_once_still_counts_when_alone():
|
|
"""With a single patient there is nothing to compare against, so the
|
|
line is read as usual. Fails if the template rule starts dropping
|
|
lines without seeing them repeat across patients."""
|
|
[record] = DocumentExtractor([KEY, CP], key_field="pac_id_hospital").extract(
|
|
[read_document("a.pdf", text_pdf([[LETTERHEAD, "Expediente: A-12"]]))]
|
|
)
|
|
assert record.row()["pac_codigo_postal"] == "12345"
|
|
|
|
|
|
def test_a_header_repeated_across_one_patients_documents_is_kept():
|
|
"""A patient's own header (her name) printed atop each of her studies
|
|
repeats only for her, so it is hers, not the template. Fails if lines
|
|
repeated by a single owner are dropped."""
|
|
header = "Nombre: ANA RUIZ PEREZ"
|
|
first = read_document("a.pdf", text_pdf([[header, "Expediente: A-13", "Resultado: POSITIVO"]]))
|
|
second = read_document("b.pdf", text_pdf([[header, "Expediente: A-13", "Resultado: POSITIVO"]]))
|
|
other = read_document("c.pdf", text_pdf([["Nombre: LUISA GOMEZ", "Expediente: A-14"]]))
|
|
records = DocumentExtractor([KEY, NOMBRE, RESULTADO], key_field="pac_id_hospital").extract([first, second, other])
|
|
by_key = {r.key: r.row() for r in records}
|
|
assert by_key["A-13"]["cit_observaciones"] == "ANA RUIZ PEREZ"
|