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 @register_connector class EdfConnector(FileConnector): """EEG recordings (`.edf`), one row per file, shaped for `tea.Eeg`: the laboratory's study id, the patient and the study date from the header, the channels and duration of the recording, and the file itself (column `estudio`, stored in `eeg.eeg_estudio`). The quality criteria, sleep and metrics are the EEG analysis'.""" 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 return { "id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem, "paciente": eeg.patient.code, "fecha_estudio": eeg.start.date() if eeg.start else None, "canales": len(eeg.channels), "duracion_min": round(eeg.duration_seconds / 60, 1) if eeg.duration_seconds else None, "archivo": name, "estudio": raw, }