From 6452e43cad5d6d4fa196f07118f40eb51b5aa60b Mon Sep 17 00:00:00 2001 From: ulises Date: Mon, 23 Nov 2026 12:26:15 -0600 Subject: [PATCH] Governance TEA EEG: preview of one EDF and its ADOS-2 report analysed in memory, nothing stored --- tests/test_governance_tea_preview.py | 172 +++++++++++++++++++++++++++ webapi/blueprints/governance.py | 15 +++ webapi/fhir/tea.py | 18 +-- webapi/tea/eeg_preview.py | 161 +++++++++++++++++++++++++ 4 files changed, 358 insertions(+), 8 deletions(-) create mode 100644 tests/test_governance_tea_preview.py create mode 100644 webapi/tea/eeg_preview.py diff --git a/tests/test_governance_tea_preview.py b/tests/test_governance_tea_preview.py new file mode 100644 index 0000000..36ae380 --- /dev/null +++ b/tests/test_governance_tea_preview.py @@ -0,0 +1,172 @@ +"""What this module covers: `POST /governance/tea/eeg/preview`, which analyses one EDF (and an ADOS-2 report) in memory and +answers a patient-summary bundle without writing to any database, and the `EegPreview` class behind it. + +Fixtures: `app_client`, the real app over an empty migrated TEA database, with its engine so the tests can count rows; +`edf`, a synthetic two-minute EDF from `models/tests/tea/synth_edf.py` (too short to be a valid study, so only its +quality part is answered); `ados2_pdf`, a one-page report with a Module 2 score table drawn with reportlab. +""" +import importlib.util +import io +from pathlib import Path + +import pytest +from sqlalchemy import text + +SYNTH = Path(__file__).resolve().parents[2] / "models" / "tests" / "tea" / "synth_edf.py" +URL = "/governance/tea/eeg/preview" +ROWS = [("Señalar", "1"), ("Gestos descriptivos, convencionales, instrumentales o informativos", "0"), + ("Contacto visual inusual", "2"), ("Expresiones faciales dirigidas a otros", "1"), + ("Disfrute compartido durante la interacción", "0"), ("Mostrar", "2"), + ("Iniciación espontánea de la atención conjunta", "1"), ("Características de las iniciaciones sociales", "1"), + ("Calidad general de la relación", "2"), ("Uso estereotipado o idiosincrásico de palabras o frases", "1"), + ("Manierismos de manos y dedos y otros manierismos complejos", "2"), + ("Intereses inusualmente repetitivos o comportamientos estereotipados", "1")] + + +@pytest.fixture(scope="module") +def edf() -> bytes: + """A synthetic two-minute EDF, the same file for every test.""" + spec = importlib.util.spec_from_file_location("synth_edf", SYNTH) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.edf_bytes(minutes=2) + + +@pytest.fixture(scope="module") +def ados2_pdf() -> bytes: + """A report whose Module 2 table lists twelve items with their algorithm scores.""" + from reportlab.pdfgen.canvas import Canvas + + buffer = io.BytesIO() + pdf = Canvas(buffer, pagesize=(612, 792)) + pdf.setFont("Helvetica", 10) + y = 720 + for caption, score in [("Afectación Social (AS)", None), *ROWS[:8], ("TOTAL DE AFECTACIÓN SOCIAL", "7"), + ("Comportamiento restringido y repetitivo (CRR)", None), *ROWS[8:], + ("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", "6"), + ("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", "13")]: + pdf.drawString(76, y, caption) + if score is not None: + pdf.drawCentredString(512, y, score) + y -= 20 + pdf.showPage() + pdf.save() + return buffer.getvalue() + + +@pytest.fixture +def app_client(tmp_path): + """The real app over an empty migrated TEA database; yields (client, engine).""" + from conftest import base_de + + from webapi import create_app + + base = base_de("tea", tmp_path, datos=lambda session: None) + app = create_app() + app.config.update(TESTING=True) + try: + with app.test_client() as client: + yield client, base.motor + finally: + base.motor.dispose() + + +def _post(client, **files): + return client.post(URL, data={k: (io.BytesIO(v), name) for k, (name, v) in files.items()}, + content_type="multipart/form-data") + + +def _types(response): + return [e["resource"]["resourceType"] for e in response.json["bundle"]["entry"]] + + +def test_an_edf_is_analysed_and_nothing_is_stored(app_client, edf, monkeypatch): + """Pins the summary bundle (report with its quality observations) and zero rows written to `eeg`, `eeg_criterio` + and `eeg_metrica`. Fails if the route stores the recording, or answers without the EEG's report.""" + client, engine = app_client + monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False) + response = _post(client, edf=("estudio.edf", edf)) + assert response.status_code == 200, response.json + assert "DiagnosticReport" in _types(response) and "Procedure" in _types(response) + assert "Observation" in _types(response) + with engine.connect() as connection: + for table in ("eeg", "eeg_criterio", "eeg_metrica"): + assert connection.execute(text(f"select count(*) from {table}")).scalar() == 0 + + +def test_a_file_that_is_not_an_edf_is_refused(app_client): + """Pins 400 for a recording MNE cannot open and for a missing field. Fails if either answers 200 or 500.""" + client, _ = app_client + assert _post(client, edf=("estudio.edf", b"no es un edf")).status_code == 400 + assert client.post(URL, data={}, content_type="multipart/form-data").status_code == 400 + + +def test_without_a_report_the_bundle_has_no_ados2(app_client, edf): + """Pins that the ADOS-2 observation appears only with a readable report. Fails if one is invented.""" + client, _ = app_client + response = _post(client, edf=("estudio.edf", edf)) + assert [e for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")] == [] + + +def test_an_unreadable_report_gives_a_notice_not_an_error(app_client, edf): + """Pins 200 plus a Spanish notice when the attached PDF has no ADOS-2 table. Fails if the route answers 500, drops + the EEG, or says nothing about the report.""" + client, _ = app_client + from reportlab.pdfgen.canvas import Canvas + + buffer = io.BytesIO() + pdf = Canvas(buffer) + pdf.drawString(72, 700, "Nota clinica sin tabla") + pdf.showPage() + pdf.save() + response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", buffer.getvalue())) + assert response.status_code == 200 + assert any("ADOS-2" in aviso for aviso in response.json["avisos"]) + assert "DiagnosticReport" in _types(response) + + +def test_without_an_age_the_css_is_not_invented(app_client, edf, ados2_pdf): + """Pins the notice when the report gives no CSS and the EDF no age. Fails if a CSS is made up or the notice is lost.""" + client, _ = app_client + response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf)) + assert response.status_code == 200 + assert any("CSS" in aviso for aviso in response.json["avisos"]) + + +def test_a_report_that_is_not_a_pdf_is_refused(app_client, edf): + """Pins 400 for an ADOS-2 file that is not a PDF. Fails if text is handed to the document extraction.""" + client, _ = app_client + assert _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", b"texto")).status_code == 400 + + +def test_the_ados2_report_is_read_and_scored(app_client, edf, ados2_pdf, monkeypatch): + """Pins that the table's items and module reach the bundle's ADOS-2 observation, scored by the platform's scorer at + the age the analysis used. Fails if the report is ignored, or its items are lost, or nothing is scored.""" + import dataclasses + + from models.tea.eeg import analyze + + real = analyze.measure + monkeypatch.setattr(analyze, "measure", lambda *args: dataclasses.replace(real(*args), age_months=30.0)) + client, engine = app_client + response = _post(client, edf=("estudio.edf", edf), ados2=("informe.pdf", ados2_pdf)) + assert response.status_code == 200, response.json + ados2 = [e["resource"] for e in response.json["bundle"]["entry"] if e["resource"]["id"].startswith("ados2-")] + assert len(ados2) == 1 and len(ados2[0]["component"]) > 10, response.json["avisos"] + with engine.connect() as connection: + assert connection.execute(text("select count(*) from ados2")).scalar() == 0 + + +def test_alterations_are_listed_although_the_validation_flag_is_off(monkeypatch): + """Pins `show_alterations=True` over the environment gate in the FHIR builder. Fails if a preview of a valid EEG + hides its metrics because `TEA_ALTERACIONES_VALIDADAS` is unset.""" + from webapi.fhir import tea + + monkeypatch.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False) + eeg = {"procedimiento_id": "p", "fecha_eeg": "2026-01-01", "calidad": "BUENO", "valido": 1, "nivel": None, + "duracion_min": 5, "edad_meses": 24.0, "canales": 19} + metric = {"procedimiento_id": "p", "metrica": "ritmo_posterior", "valor": 7.0, "grupo_edad_eeg": "24 meses", + "ref_min": 6.0, "ref_mediana": 7.5, "ref_max": 9.0, "modelo": None, "valor_z": -0.4, "estado": "normal"} + hidden = tea.eeg_resources(eeg, "x", [metric], [], True) + shown = tea.eeg_resources(eeg, "x", [metric], [], True, show_alterations=True) + assert len(shown) == len(hidden) + 1 diff --git a/webapi/blueprints/governance.py b/webapi/blueprints/governance.py index 6bb5aaf..ee5da76 100644 --- a/webapi/blueprints/governance.py +++ b/webapi/blueprints/governance.py @@ -164,6 +164,21 @@ def upload_eeg(): return jsonify(added), 201 +@governance_bp.post("/tea/eeg/preview") +def preview_eeg(): + """Analyse one EDF, and the child's ADOS-2 report if given, without storing either: the summary bundle.""" + from webapi.tea.eeg_preview import EegPreview, PreviewError + + edf = request.files.get("edf") + if edf is None or not edf.filename: + return jsonify({"error": "Se requiere el campo edf."}), 400 + report = request.files.get("ados2") + try: + return jsonify(EegPreview().run(edf.read(), report.read() if report is not None and report.filename else None)) + except PreviewError as error: + return jsonify({"error": str(error)}), 400 + + # -- model versions ---------------------------------------------------------------- diff --git a/webapi/fhir/tea.py b/webapi/fhir/tea.py index 3da3405..6d67e28 100644 --- a/webapi/fhir/tea.py +++ b/webapi/fhir/tea.py @@ -273,7 +273,7 @@ def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulate return observations -def curve_extension(label: str, curve: dict) -> dict: +def curve_extension(label: str, curve: dict, validated: bool | None = None) -> dict: """The reference curve as one nested extension on the metric observation. `fuente` is the baseline's registered label and `estado` the alterations validation gate (`TEA_ALTERACIONES_VALIDADAS`); each series is a run of sub-extensions, one per point, read back in order (`edad-meses`, then the five percentiles), because a FHIR @@ -281,12 +281,12 @@ def curve_extension(label: str, curve: dict) -> dict: series = (("edad-meses", curve["edad_meses"]), *((p, curve[p]) for p in PERCENTILES)) return {"url": CURVE, "extension": [ {"url": f"{CURVE}/fuente", "valueString": label}, - {"url": f"{CURVE}/estado", "valueString": "validada" if alterations_validated() else "pendiente"}, + {"url": f"{CURVE}/estado", "valueString": "validada" if (alterations_validated() if validated is None else validated) else "pendiente"}, *({"url": f"{CURVE}/{name}", "valueDecimal": float(value)} for name, values in series for value in values)]} def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str, - simulated: bool, curves=None) -> list[dict]: + simulated: bool, curves=None, validated: bool | None = None) -> list[dict]: """One `Observation` per metric and one per metric with each electrode's z-score as a component. A metric's observation has its value, or `not-performed` without one; with a z, also its age baseline's p5-p95 at the EEG as the reference, H/L/N, and the z and the baseline's median as components. With the baseline's label @@ -322,7 +322,7 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], if curves is not None and m.get("modelo"): curve = curves.curve(m["modelo"], m["metrica"]) if curve is not None: - resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve)) + resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve, validated)) observations.append(tagged(resource, simulated)) at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"] and x["valor_z"] is not None] @@ -338,14 +338,16 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool, - checks: list[dict] = (), curves=None) -> list[dict]: + checks: list[dict] = (), curves=None, show_alterations: bool | None = None) -> list[dict]: """The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has no result beyond its quality, and the alterations stay out until validated. The report carries the recording's duration, channel count and the age the analysis compared the references at as extensions, and each metric - observation the baseline's full centile curve when its label resolves (`curves`).""" + observation the baseline's full centile curve when its label resolves (`curves`). `show_alterations` overrides + the validation gate for an analysis the caller shows without storing it; None follows the gate.""" quality = quality_observations(eeg, list(checks), pseudonym, simulated) - altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves) - if eeg["valido"] == 1 and alterations_validated() else []) + shown = alterations_validated() if show_alterations is None else show_alterations + altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves, validated=shown) + if eeg["valido"] == 1 and shown else []) procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed", "code": concept(CATALOG, "eeg", "Electroencefalograma"), "subject": {"reference": f"Patient/{pseudonym}"}, diff --git a/webapi/tea/eeg_preview.py b/webapi/tea/eeg_preview.py new file mode 100644 index 0000000..46d2712 --- /dev/null +++ b/webapi/tea/eeg_preview.py @@ -0,0 +1,161 @@ +"""Analyse one EDF, and read its ADOS-2 report, in memory: the answer is a patient summary bundle and nothing is stored. + +The recording goes through the same measurement and baselines as a stored EEG, and its rows are turned into the +dicts the FHIR summary builders take, so the web app draws it with the view it uses for a patient. No session is +opened, no row is added and no registry entry is written; the uploaded bytes live in this call only. +""" +from datetime import date + +from webapi.fhir import tea as fhir +from webapi.fhir.eeg_curves import baseline_curves + +PSEUDONYM = "vista-previa" +EEG_ID = "vista-previa" +ADOS2_ID = "vista-previa" + + +class PreviewError(ValueError): + """The file cannot be analysed at all (the EDF cannot be read, or the report is not a PDF).""" + + +def _item_labels() -> dict[str, str]: + """Each item's printed caption, from the score-table vocabulary the extraction reads reports with.""" + from extraction.nlp.vocabulary import SCORE_TABLES + + labels: dict[str, str] = {} + for captions in SCORE_TABLES["ados2"]["variants"].values(): + for caption, field in captions.items(): + labels.setdefault(field.removeprefix("ado_"), caption) + return labels + + +def _recording_date(edf: bytes) -> date: + from extraction import ExtractionError + from extraction.signals import EegRecording + + try: + start = EegRecording.read(edf).start + except ExtractionError as error: + raise PreviewError(f"El archivo no es un EDF legible: {error}") from error + return start.date() if start else date.today() + + +class EegPreview: + """Builds the summary of one EDF and, optionally, of the child's ADOS-2 report.""" + + def __init__(self, settings=None, baselines=None, measure_fn=None, curves=None): + self._settings, self._baselines, self._measure, self._curves = settings, baselines, measure_fn, curves + + def run(self, edf: bytes, ados2: bytes | None = None) -> dict: + from models.eeg_analysis import checked_settings, rows + from models.tea.eeg.analyze import measure + from models.tea.eeg.baselines import Baselines + + settings = self._settings or checked_settings() + baselines = self._baselines or Baselines(settings.domain) + taken = _recording_date(edf) + measured = (self._measure or measure)(EEG_ID, edf, None, settings) + if measured.error and measured.valid is None and not measured.checks: + raise PreviewError(f"No se pudo analizar el EDF: {measured.error}") + result = rows(measured, settings, baselines) + avisos: list[str] = [] + resources = [] + if ados2 is not None: + observation = self._ados2(ados2, measured.age_months, taken, avisos) + if observation is not None: + resources.append(observation) + if measured.error: + avisos.append(f"El análisis del EEG terminó con un error: {measured.error}") + resources += self._eeg(measured, result, taken) + return {"bundle": {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}, + "avisos": avisos} + + def _eeg(self, m, result, taken: date) -> list[dict]: + valid = result.eeg.get("eeg_valido") + quality = "SIN_ANALIZAR" if valid is None else "BUENO" if valid == 1 else "MALO" + eeg = {"procedimiento_id": EEG_ID, "fecha_eeg": taken, "calidad": quality, "valido": valid, + "nivel": result.eeg.get("eeg_nivel"), "duracion_min": result.eeg.get("eeg_duracion_min"), + "edad_meses": result.eeg.get("eeg_edad_meses"), "canales": result.eeg.get("eeg_canales")} + age_group = f"{round(m.age_months)} meses" if m.age_months is not None else "sin dato" + codes = {metric.met_id: metric.met_codigo for metric in result.metrics} + metrics = [{"procedimiento_id": EEG_ID, "metrica": x.met_codigo, "valor": x.met_valor, "grupo_edad_eeg": age_group, + "ref_min": x.met_p5, "ref_mediana": x.met_mediana, "ref_max": x.met_p95, "modelo": x.met_modelo, + "valor_z": x.met_z, + "estado": "no_evaluable" if x.met_z is None else + "aumentado" if x.met_fuera == 1 else "disminuido" if x.met_fuera == -1 else "normal"} + for x in result.metrics] + electrodes = [{"procedimiento_id": EEG_ID, "metrica": codes[x.mel_met_id], "electrodo": x.mel_electrodo, + "valor": x.mel_valor, "valor_z": x.mel_z} for x in result.electrodes] + checks = [{"procedimiento_id": EEG_ID, "criterio": c.cri_codigo, "electrodo": c.cri_electrodo, + "valor": c.cri_valor, "valor_texto": c.cri_valor_texto, "bajo": c.cri_bajo, "alto": c.cri_alto, + "anormal": c.cri_anormal, "decisivo": c.cri_decisivo, "etiqueta": c.cri_codigo, + "unidad": c.cri_unidad} for c in result.criteria] + return fhir.eeg_resources(eeg, PSEUDONYM, metrics, electrodes, True, checks, + curves=self._curves or baseline_curves(), show_alterations=True) + + def _ados2(self, raw: bytes, age_months: float | None, taken: date, avisos: list[str]) -> dict | None: + try: + row = self._report_row(raw) + items, module, algorithm = self._items(row), row.get("ado_modulo"), row.get("ado_algoritmo") + score = self._score(module, items, age_months, algorithm) + except PreviewError: + raise + except Exception as error: # noqa: BLE001 + avisos.append(f"No se pudo leer el ADOS-2 del PDF: {error}") + return None + css = row.get("ado_css") or (score.css if score else None) + classification = row.get("ado_clasificacion") or (score.classification if score else None) + if not items or not module: + avisos.append("No se pudo leer el ADOS-2 del PDF: faltan el módulo o los puntajes de los reactivos.") + return None + if css is None: + avisos.append("No se pudo calcular el CSS del ADOS-2: el informe no lo trae y el EDF no da la edad del niño.") + return None + labels = _item_labels() + lines = [{"procedimiento_id": ADOS2_ID, "fecha_ados2": _date(row.get("ado_fecha")) or taken, + "modulo": module, "algoritmo": algorithm, "css": int(css), "clasificacion": classification, + "dominio": "SA" if code.startswith("sa_") else "RRB", "reactivo": f"ados2.{code}", + "etiqueta": labels.get(code, code.replace("_", " ").upper()), "puntaje": value, + "puntaje_algoritmo": 2 if value == 3 else 0 if value in (7, 8, 9) else value} + for code, value in items.items()] + return fhir.ados2_observation(lines, PSEUDONYM, True) + + @staticmethod + def _report_row(raw: bytes) -> dict: + if not raw.lstrip()[:5].startswith(b"%PDF"): + raise PreviewError("El informe del ADOS-2 debe ser un PDF.") + from webapi.imports.connectors.document import DocumentConnector + + records, _ = DocumentConnector([("ados2.pdf", raw)], target="tea.Ados2")._extract() + if not records: + raise ValueError("el PDF no contiene una evaluación ADOS-2") + row = records[0].row() + return {k: (None if v in ("", None) else v) for k, v in row.items()} + + @staticmethod + def _items(row: dict) -> dict[str, int]: + from core.tea.models import ADOS2_ITEMS + + out = {} + for code in ADOS2_ITEMS: + value = row.get(f"ado_{code}") + if value is not None: + out[code] = int(float(value)) + return out + + @staticmethod + def _score(module, items, age_months, algorithm): + from tea.scoring import score + + return score(module, items, age_months=age_months, algorithm=algorithm) if module and items else None + + +def _date(value) -> date | None: + if value is None: + return None + if isinstance(value, date): + return value + try: + return date.fromisoformat(str(value)[:10]) + except ValueError: + return None -- 2.53.0