diff --git a/tests/test_imports_ados2_document.py b/tests/test_imports_ados2_document.py new file mode 100644 index 0000000..9f02b29 --- /dev/null +++ b/tests/test_imports_ados2_document.py @@ -0,0 +1,147 @@ +"""What this module covers: filling `tea.Ados2`'s item columns from the ADOS-2 score table of a PDF read from a SQL +source (`DocumentConnector` with `sql`, the score-table extractor of `extraction.nlp.score_tables`) and merging them +with `on_conflict=upsert` into the row the hospital's table import created, which keeps its header. + +Fixtures: `client`, a Flask app over a throwaway TEA database (`conftest.wire_domain`); `hospital`, a SQLite file +standing for the hospital with one ADOS-2 row whose evaluation PDF is a two-page report, prose first and the +Module 2 score table second. +""" +import base64 +import io +import json +import sqlite3 + +import pytest +from sqlalchemy import create_engine, text + +# Module 2 rows as the evaluation prints them: description, algorithm score, column. +_ROWS = [ + ("Señalar", "1", "ado_sa_a6"), + ("Gestos descriptivos, convencionales, instrumentales o informativos", "0", "ado_sa_a7"), + ("Contacto visual inusual", "2", "ado_sa_b1"), + ("Expresiones faciales dirigidas a otros", "1", "ado_sa_b2"), + ("Disfrute compartido durante la interacción", "0", "ado_sa_b3"), + ("Mostrar", "2", "ado_sa_b5"), + ("Iniciación espontánea de la atención conjunta", "1", "ado_sa_b6"), + ("Características de las iniciaciones sociales", "1", "ado_sa_b8"), + ("Cantidad de comunicación social recíproca", "S/D", "ado_sa_b11"), + ("Calidad general de la relación", "2", "ado_sa_b12"), + ("Uso estereotipado o idiosincrásico de palabras o frases", "1", "ado_rrb_a4"), + ("Interés sensorial inusual en los materiales de juego o en las personas", "0", "ado_rrb_d1"), + ("Manierismos de manos y dedos y otros manierismos complejos", "2", "ado_rrb_d2"), + ("Intereses inusualmente repetitivos o comportamientos estereotipados", "1", "ado_rrb_d4"), +] + + +def _evaluation_pdf() -> bytes: + from reportlab.pdfgen.canvas import Canvas + + buffer = io.BytesIO() + pdf = Canvas(buffer, pagesize=(612, 792)) + pdf.setFont("Helvetica", 10) + pdf.drawString(72, 720, "Evaluación psicológica. Se observa afectación social en el juego libre.") + pdf.showPage() + pdf.setFont("Helvetica", 10) + y = 720 + + def row(caption, score=None): + nonlocal y + pdf.drawString(76, y, caption) + if score is not None: + pdf.drawCentredString(512, y, score) + y -= 20 + + row("Afectación Social (AS)") + for caption, score, _ in _ROWS[:10]: + row(caption, score) + social = sum(int(s) for _, s, _ in _ROWS[:10] if s != "S/D") + row("TOTAL DE AFECTACIÓN SOCIAL", str(social)) + row("Comportamiento restringido y repetitivo (CRR)") + for caption, score, _ in _ROWS[10:]: + row(caption, score) + restricted = sum(int(s) for _, s, _ in _ROWS[10:]) + row("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", str(restricted)) + row("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", str(social + restricted)) + pdf.showPage() + pdf.save() + return buffer.getvalue() + + +@pytest.fixture(scope="module") +def client(wire_domain): + 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 + + +@pytest.fixture +def hospital(tmp_path): + """The hospital: `ados2` with one header row and no items, and the ADOS-2 order holding the evaluation PDF.""" + url = f"sqlite:///{tmp_path / 'hospital.db'}" + with create_engine(url).begin() as conn: + conn.execute(text("CREATE TABLE ados2 (ado_id TEXT, ado_pac_id INTEGER, ado_ord_id TEXT)")) + conn.execute(text("CREATE TABLE ordenes_estudio (ord_id TEXT, ord_pdf_blob BLOB)")) + conn.execute(text("INSERT INTO ados2 VALUES ('ADO-1', 7, 'ORD-1')")) + conn.execute(text("INSERT INTO ordenes_estudio VALUES ('ORD-1', :pdf)"), {"pdf": _evaluation_pdf()}) + return url + + +def _json_source(records: list[dict]) -> dict: + return { + "source_type": "json", + "target": "tea.Ados2", + "column_mapping": {name: name for name in records[0]}, + "payload": {"file_base64": base64.b64encode(json.dumps(records).encode()).decode()}, + } + + +def _document_source(url: str) -> dict: + items = [column for _, _, column in _ROWS] + return { + "source_type": "document", + "target": "tea.Ados2", + "column_mapping": {name: name for name in ["ado_id", *items]}, + "payload": { + "target": "tea.Ados2", + "sql": { + "connection_string": url, + "query": "select a.ado_id, a.ado_pac_id, o.ord_pdf_blob from ados2 a " + "join ordenes_estudio o on o.ord_id = a.ado_ord_id", + "column": "ord_pdf_blob", + "key_column": "ado_id", + "fields": {"ado_id": "ado_id", "ado_pac_id": "ado_pac_id"}, + }, + }, + } + + +def test_the_evaluations_score_table_fills_the_items_of_the_existing_row(client, hospital, wire_domain): + """Pins down: after the header row is imported, a `document` source over the hospital's ADOS-2 PDF, committed + with upsert, writes each item's algorithm score into its Module 2 column on that same row, leaves an `S/D` item + empty, and keeps the header (module, CSS, patient). Fails if the document's items stop reaching the columns, + the upsert creates a second row or blanks the header, or the module is read from the wrong item set.""" + header = {"ado_id": "ADO-1", "ado_pac_id": 7, "ado_modulo": "MODULO_2", "ado_algoritmo": "Menor de 5 años", + "ado_css": 6, "ado_clasificacion": "AUTISMO"} + first = client.post("/imports/commit", json={"sources": [_json_source([header])], "on_conflict": "upsert"}) + assert first.status_code == 200, first.get_json() + second = client.post("/imports/commit", json={"sources": [_document_source(hospital)], "on_conflict": "upsert"}) + body = second.get_json() + assert second.status_code == 200, body + assert [(r["created"], r["updated"], r["rejected"]) for r in body["results"]] == [(0, 1, 0)] + + from persistance import settings + + path = settings.settings.tea_database_url.removeprefix("sqlite:///") + con = sqlite3.connect(path) + con.row_factory = sqlite3.Row + rows = con.execute("select * from ados2").fetchall() + assert len(rows) == 1 + stored = dict(rows[0]) + expected = {column: (None if score == "S/D" else int(score)) for _, score, column in _ROWS} + assert {column: stored[column] for column in expected} == expected + assert (stored["ado_modulo"], stored["ado_css"], stored["ado_pac_id"]) == ("MODULO_2", 6, 7) diff --git a/webapi/imports/connectors/document.py b/webapi/imports/connectors/document.py index 7b729fd..d667e3c 100644 --- a/webapi/imports/connectors/document.py +++ b/webapi/imports/connectors/document.py @@ -150,7 +150,8 @@ class DocumentConnector(DataFrameConnector): self.include_pattern = _compile_filter(include_pattern, "include_pattern") self.exclude_pattern = _compile_filter(exclude_pattern, "exclude_pattern") self.skipped: list[dict[str, str]] = [] - known = {spec.name for spec in self.specs} + # A source's own ids (`ado_id`) are never read off a page, but a source may carry them. + known = set(entity.schema.model_fields) unknown = sorted({name for values in self.source_fields.values() for name in values} - known) if unknown: raise ConnectorError(f"fields desconocidos para {target}: {', '.join(unknown)}") @@ -264,6 +265,7 @@ class DocumentConnector(DataFrameConnector): if self._df is None: columns = ( [spec.name for spec in self.specs] + + self._carried_columns() + ([self.nlp_field] if self.nlp_field else []) + self.caption_columns() + [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN] @@ -272,11 +274,19 @@ class DocumentConnector(DataFrameConnector): self._df = pd.DataFrame(rows, columns=columns, dtype=object) return self._df + def _carried_columns(self) -> list[str]: + """Fields the source carries that no document spec reads, such as its own ids, in the order first seen.""" + specs = {spec.name for spec in self.specs} + carried: list[str] = [] + for values in self.source_fields.values(): + carried.extend(name for name in values if name not in specs and name not in carried) + return carried + def caption_columns(self) -> list[str]: """Every caption the documents print that no field of the target claims, in the order first seen: columns of their own, mappable and usable in derived fields like any column of a table.""" - reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN} + reserved = {spec.name for spec in self.specs} | set(self._carried_columns()) | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN} columns: list[str] = [] for record in self.records: for found in record.discovered: @@ -294,7 +304,7 @@ class DocumentConnector(DataFrameConnector): def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]: row: dict[str, Any] = record.row() - reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN} + reserved = {spec.name for spec in self.specs} | set(self._carried_columns()) | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN} for found in record.discovered: row.setdefault(_caption_column(found.caption, reserved), found.value) row.update(self.overrides.get(str(index), {})) @@ -468,11 +478,11 @@ def document_options(raw: dict[str, Any]) -> dict[str, Any]: def connector_for_batch(batch: DocumentBatch, target: str, options: dict[str, Any]) -> "DocumentConnector": """A `DocumentConnector` over documents read from a source's columns, - their row values restricted to the fields extraction knows.""" + their row values restricted to the target's fields.""" entity = ENTITY_REGISTRY.get(target) if entity is None: raise ConnectorError(f"destino desconocido: {target!r}") - known = {spec.name for spec in field_specs_for(entity)} + known = set(entity.schema.model_fields) source_fields = {name: {k: v for k, v in values.items() if k in known} for name, values in batch.source_fields.items()} return DocumentConnector( batch.files, target=target, source_fields=source_fields, record_keys=batch.record_keys, **document_options(options)