Files
WebApi/webapi/imports/connectors/edf.py
T

106 lines
4.2 KiB
Python

from datetime import date, timedelta
from pathlib import PurePath
from typing import Any
import pandas as pd
from extraction import ExtractionError
from extraction.signals import EegRecording
from webapi.imports.connectors.base import decode_file
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.tabular import FileConnector
MAX_LISTED_EVENTS = 20
@register_connector
class EdfConnector(FileConnector):
"""EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`:
patient and dates from the header, an estimated background rhythm from
the posterior channels, a text summary of the recording, and the file
itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`)."""
kind = "edf"
label = "EEG (EDF)"
description = "Registros de electroencefalografía en European Data Format"
category = "signal"
icon = "monitor_heart"
extensions = ("edf",)
option_names = ("file_name",)
def __init__(self, files: list[tuple[str, bytes]]):
self.files = files
self._df: pd.DataFrame | None = None
@classmethod
def from_bytes(cls, raw: bytes, options: dict[str, Any] | None = None) -> "EdfConnector":
return cls([((options or {}).get("file_name") or "registro.edf", raw)])
@classmethod
def from_payload(cls, payload: dict[str, Any]) -> "EdfConnector":
"""One file (`file_base64` + `options.file_name`) or several (`files: [{name, file_base64}]`)."""
if not payload.get("files"):
return super().from_payload(payload)
return cls([(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)])
def metadata(self) -> dict[str, Any]:
return {"files": [name for name, _ in self.files]}
def _dataframe(self) -> pd.DataFrame:
if self._df is None:
self._df = pd.DataFrame([self._row(name, raw) for name, raw in self.files], dtype=object)
return self._df
def _row(self, name: str, raw: bytes) -> dict[str, Any]:
try:
eeg = EegRecording.read(raw)
except ExtractionError as exc:
raise ConnectorError(f"{name}: {exc}") from exc
patient = eeg.patient
study_date = eeg.start.date() if eeg.start else None
rhythm = eeg.background_rhythm()
return {
"id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem,
"paciente": patient.code,
"sexo": patient.sex,
"fecha_nacimiento_declarada": patient.birthdate,
"edad_meses": age_in_months(patient.birthdate, study_date),
"fecha_estudio": study_date,
"duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None,
"ritmo_base_frecuencia": rhythm["frequency_hz"],
"ritmo_base_amplitud": rhythm["amplitude_uv"],
"descripcion_senal": describe(eeg),
"archivo": name,
"estudio": raw,
}
def describe(eeg: EegRecording) -> str:
channels = eeg.channels
parts = [
f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant,
f"duración {timedelta(seconds=round(eeg.duration_seconds))}",
"montaje: " + ", ".join(c.label for c in channels),
]
fields = eeg.recording_fields
if fields["equipment"]:
parts.append(f"equipo: {fields['equipment']}")
if fields["technician"]:
parts.append(f"técnico: {fields['technician']}")
events = eeg.annotations()
if events:
listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS])
more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else ""
parts.append(f"eventos: {listed}{more}")
return ". ".join(parts) + "."
def age_in_months(birthdate: date | None, on: date | None) -> float | None:
if birthdate is None or on is None or on < birthdate:
return None
months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month)
if on.day < birthdate.day:
months -= 1
return float(months)