Governance TEA EEG: preview of one EDF and its ADOS-2 report analysed in memory, nothing stored

This commit is contained in:
ulises
2026-11-23 12:26:15 -06:00
parent b0b797ac15
commit 6452e43cad
4 changed files with 358 additions and 8 deletions
+15
View File
@@ -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 ----------------------------------------------------------------
+10 -8
View File
@@ -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}"},
+161
View File
@@ -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