Files
WebApi/tests/test_new_sources.py
T

351 lines
16 KiB
Python

"""Connector catalog, SQL Server, EEG files and clinical documents, end to end."""
import base64
import io
from datetime import date
import numpy as np
import pytest
import sqlalchemy as sa
from sqlalchemy.dialects import mssql
from extraction.testing import edf_file, scanned_pdf, text_pdf
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
wire_domain("cama")
wire_domain("tea")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
def b64(raw: bytes) -> str:
return base64.b64encode(raw).decode()
def eeg(seconds: int = 8, rate: int = 128, **kwargs) -> bytes:
t = np.arange(rate * seconds) / rate
alpha = 40 * np.sin(2 * np.pi * 10 * t)
return edf_file(signals={"EEG O1-REF": alpha, "EEG O2-REF": alpha, "EEG Fp1-REF": 20 * np.sin(2 * np.pi * 20 * t)}, sample_rate=rate, **kwargs)
# -- catalog ------------------------------------------------------------------------
def test_catalog_lists_every_connector(client):
connectors = {c["kind"]: c for c in client.get("/imports/connectors").get_json()["connectors"]}
assert {"csv", "excel", "json", "pdf", "document", "edf", "sql"} <= set(connectors)
assert connectors["edf"]["extensions"] == ["edf"]
assert "pdf" in connectors["document"]["extensions"] and "tif" in connectors["document"]["extensions"]
assert {s["id"] for s in connectors["document"]["segmentations"]} == {"auto", "document", "pages", "key"}
engines = {e["id"]: e for e in connectors["sql"]["engines"]}
assert engines["mssql"]["label"] == "SQL Server" and engines["mssql"]["default_port"] == 1433
assert engines["mssql"]["available"] is True
# -- SQL Server ----------------------------------------------------------------------
def test_sql_server_url_is_built_from_form_fields():
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url({"engine": "mssql", "host": "his.local", "database": "HIS", "user": "lector", "password": "p@ss:/w"})
assert url.drivername == "mssql+pymssql"
assert url.port == 1433
assert url.password == "p@ss:/w"
def test_sql_server_preview_compiles_to_top(monkeypatch):
from webapi.imports.connectors.sql import _text_subquery
statement = sa.select(_text_subquery("SELECT * FROM pacientes")).limit(5)
compiled = str(statement.compile(dialect=mssql.dialect(), compile_kwargs={"literal_binds": True}))
assert "TOP 5" in compiled and "LIMIT" not in compiled
def test_unknown_engine_and_missing_host_are_rejected(client):
assert client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "db2", "host": "x", "database": "y"}}).status_code == 400
response = client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "mssql", "database": "y"}})
assert response.status_code == 400 and "host" in response.get_json()["error"]
# -- EEG -----------------------------------------------------------------------------
def test_edf_preview_maps_onto_eeg(client):
"""Pins down: an EDF previews as one row with the study id, patient, date, channels and duration read from the
file, and its columns suggest the `eeg` fields. Fails if the connector stops reading the header or the column
matcher stops pairing them."""
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.Eeg"}
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
[row] = body["sample_rows"]
assert row["id_registro_laboratorio"] == "LAB-778"
assert row["paciente"] == "EXP-0042"
assert row["fecha_estudio"] == "2024-01-15"
assert row["canales"] == 3
assert row["duracion_min"] == pytest.approx(8 / 60, abs=0.05)
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
assert suggested["estudio"] == "eeg_estudio"
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
assert suggested["canales"] == "eeg_canales"
def test_several_edf_files_load_into_eeg_with_the_file(client):
"""Pins down: several EDF files commit as one `eeg` row each, keyed by the lab's study id (or the file name),
with the file stored. Fails if the commit drops the file or the key."""
source = {
"source_type": "edf",
"target": "tea.Eeg",
"column_mapping": {
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
"fecha_estudio": "eeg_fecha_estudio",
"duracion_min": "eeg_duracion_min",
"canales": "eeg_canales",
"estudio": "eeg_estudio",
},
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
}
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.tea import eeg_repository
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_repository.list()}
assert set(stored) == {"LAB-778", "b"}
assert stored["LAB-778"].eeg_canales == 3
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
def test_eeg_rejects_a_file_mne_cannot_read():
"""Pins down: `eeg_estudio` only takes a file MNE can open. Fails if the schema stops validating the EDF."""
from webapi.imports.schemas.service import validate_rows
from webapi.imports.schemas.tea.eeg import EegImportSchema
result = validate_rows(EegImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
[row] = result.rejected
assert row.errors[0].field == "eeg_estudio"
# -- clinical documents -----------------------------------------------------------------
def _document_source(files: list[tuple[str, bytes]], target: str, mapping: dict, **options) -> dict:
return {
"source_type": "document",
"target": target,
"column_mapping": mapping,
"payload": {"files": [{"name": n, "file_base64": b64(r)} for n, r in files], **options},
"label": "documentos",
}
REPORTS = text_pdf(
[
["HOSPITAL REGIONAL - LABORATORIO DE PATOLOGIA", "Expediente: DOC-0001 Sexo: Femenino", "Fecha de nacimiento: 12/03/1981",
"VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"],
["Observaciones: muestra adecuada,", "con escaso moco cervical."],
["Expediente: DOC-0002 Sexo: F", "Fecha de nacimiento: 1 de mayo de 1975",
"Se identifica ADN de virus del papiloma humano de alto riesgo: NEGATIVO"],
],
image_on_page=2,
)
def test_document_extract_reports_records_evidence_and_images(client):
body = client.post(
"/imports/sources/document/extract",
json={"files": [{"name": "lote.pdf", "file_base64": b64(REPORTS)}], "target": "cacu.CitologiaCervical"},
).get_json()
assert body["key_field"] == "pac_id_hospital"
first, second = body["records"]
assert first["key"] == "DOC-0001" and first["sources"] == [{"document": "lote.pdf", "page_numbers": [1, 2]}]
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert first["fields"]["cit_vph_genotipo_16"]["value"] == 0
assert first["fields"]["cit_vph_genotipo_18"]["value"] == 1
assert first["fields"]["cit_observaciones"]["value"] == "muestra adecuada, con escaso moco cervical."
assert first["fields"]["cit_vph_resultado"]["page_number"] == 1
assert [image["page_number"] for image in first["images"]] == [2]
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
assert second["fields"]["cit_vph_resultado"]["method"] == "texto_libre"
def test_document_page_and_image_render(client):
data = {"file": (io.BytesIO(REPORTS), "lote.pdf"), "page_number": "2", "bbox": "[0.4, 0.4, 0.8, 0.7]"}
response = client.post("/imports/sources/document/page-image", data=data, content_type="multipart/form-data")
assert response.status_code == 200 and response.mimetype == "image/png"
def test_documents_commit_with_overrides_and_the_record_pdf(client):
mapping = {
"pac_id_hospital": "pac_id_hospital",
"cit_vph_resultado": "cit_vph_resultado",
"cit_vph_genotipo_18": "cit_vph_genotipo_18",
"documento": "cit_vph_pdf_blob",
}
source = _document_source([("lote.pdf", REPORTS)], "cacu.CitologiaCervical", mapping, overrides={"1": {"cit_vph_resultado": "INDETERMINADO"}})
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.cacu import citologia_cervical_repository
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("DOC-")}
assert rows["DOC-0001"].cit_vph_resultado == "POSITIVO"
assert rows["DOC-0002"].cit_vph_resultado == "INDETERMINADO"
assert rows["DOC-0001"].cit_vph_pdf_blob.startswith(b"%PDF")
def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
csv = b"expediente,sexo,codigo_postal\nMIX-0001,F,64000\nMIX-0002,M,01000\n"
scan = scanned_pdf([["FICHA DE IDENTIFICACION", "Expediente: MIX-0001", "Fecha de nacimiento: 15/08/1979", "Sexo: Masculino"]])
sources = [
{
"source_type": "csv",
"target": "cacu.Paciente",
"label": "padron.csv",
"column_mapping": {"expediente": "pac_id_hospital", "sexo": "pac_sexo", "codigo_postal": "pac_codigo_postal"},
"payload": {"file_base64": b64(csv)},
},
_document_source(
[("ficha.pdf", scan)],
"cacu.Paciente",
{"pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento", "pac_sexo": "pac_sexo"},
),
]
# On its own the CSV lacks the required birth date.
assert client.post("/imports/validate", json={"source": sources[0]}).get_json()["error_count"] == 2
padron, ficha = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
assert (padron["created"], padron["rejected"]) == (1, 1) # MIX-0002 has no birth date anywhere
assert (ficha["merged"], ficha["created"]) == (1, 0)
assert [(w["field"], w["raw_value"]) for w in ficha["warnings"]] == [("pac_sexo", "Masculino")]
from persistance.cacu import paciente_repository
[patient] = paciente_repository.list(pac_id_hospital="MIX-0001")
assert patient.pac_fecha_nacimiento == date(1979, 8, 15)
assert patient.pac_codigo_postal == "64000"
EEG_REPORT = text_pdf(
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024"]],
)
# A second study id, distinct from LAB-778 (already used by an earlier test
# against this module-scoped client/database), for the merge test below.
EEG_REPORT_2 = text_pdf(
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024"]],
)
def test_an_eeg_report_gives_its_study_id_and_date(client):
"""Pins down: a report read with NLP lands on `eeg` by the lab's own study id, with the study date. Fails if
the extractor stops keying EEG records by `eeg_id_registro_laboratorio` or stops reading the date."""
body = client.post(
"/imports/sources/document/extract",
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.Eeg"},
).get_json()
assert body["key_field"] == "eeg_id_registro_laboratorio"
[record] = body["records"]
assert record["key"] == "LAB-778"
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_row(client):
"""Pins down: the EDF and its report, two sources of the same study, land on one `eeg` row through the lab's
study id (read from the EDF header by one and from the report text by the other). Fails if
`merge_duplicates` stops matching them on `eeg_id_registro_laboratorio`."""
edf_source = {
"source_type": "edf",
"target": "tea.Eeg",
"label": "estudio.edf",
"column_mapping": {
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
"duracion_min": "eeg_duracion_min",
"estudio": "eeg_estudio",
},
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
}
document_source = _document_source(
[("reporte.pdf", EEG_REPORT_2)],
"tea.Eeg",
{"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", "eeg_fecha_estudio": "eeg_fecha_estudio"},
)
body = client.post(
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
).get_json()
edf_result, doc_result = body["results"]
assert edf_result["created"] == 1, body
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
from persistance.tea import eeg_repository
[row] = eeg_repository.list(eeg_id_registro_laboratorio="LAB-900")
# From the EDF file itself:
assert row.eeg_duracion_min is not None
assert row.eeg_estudio[:8].strip() == b"0"
# From the report, on the very same row:
assert row.eeg_fecha_estudio == date(2024, 2, 20)
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
"""The order/date come from a structured table (a CSV export of the lab's
own HIS); the VPH result comes from NLP over the scanned report PDF.
`(pac_id_hospital, ord_numero_hospital)` is what lets them land on one
`citologiacervical` row instead of two half-populated ones."""
csv = b"expediente,orden,fecha_toma\nMRG-0001,5001,2024-03-01\n"
report = text_pdf([["LABORATORIO DE CITOLOGIA", "Expediente: MRG-0001", "No. de orden: 5001", "VPH alto riesgo: POSITIVO"]])
sources = [
{
"source_type": "csv",
"target": "cacu.CitologiaCervical",
"label": "padron.csv",
"column_mapping": {"expediente": "pac_id_hospital", "orden": "ord_numero_hospital", "fecha_toma": "cit_fecha_toma"},
"payload": {"file_base64": b64(csv)},
},
_document_source(
[("reporte.pdf", report)],
"cacu.CitologiaCervical",
{"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital", "cit_vph_resultado": "cit_vph_resultado"},
),
]
tabla, documento = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
assert tabla["created"] == 1, tabla
assert documento["merged"] == 1, documento # absorbed into the table row, not inserted again
from persistance.cacu import citologia_cervical_repository
[row] = citologia_cervical_repository.list(pac_id_hospital="MRG-0001")
# From the structured table:
assert row.ord_numero_hospital == 5001
assert row.cit_fecha_toma == date(2024, 3, 1)
# From the scanned report, on the very same row:
assert row.cit_vph_resultado == "POSITIVO"
def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
"""The report has a picture of the mammogram alongside its narrative
text; `imagen` (like `documento`, the combined PDF) is mappable onto any
target column, so it lands in `mast_dicom_blob` next to the fields read
from the surrounding text."""
report = text_pdf(
[["LABORATORIO DE IMAGENOLOGIA", "Expediente: IMG-0001", "Interpretación: nódulo circunscrito en cuadrante superior externo."]],
image_on_page=1,
)
mapping = {"pac_id_hospital": "pac_id_hospital", "mast_interpretacion": "mast_interpretacion", "imagen": "mast_dicom_blob"}
source = _document_source([("reporte.pdf", report)], "cama.Mastografia", mapping)
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 1, result
from persistance.cama import mastografia_repository
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
assert "nódulo circunscrito" in row.mast_interpretacion
assert row.mast_dicom_blob.startswith(b"\x89PNG")