162 lines
7.9 KiB
Python
162 lines
7.9 KiB
Python
"""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
|