Files

182 lines
7.3 KiB
Python

"""Shared coercion helpers and field types for the import schemas: raw-value
shapes (Excel/SQL datetimes, ISO strings, empty CSV cells) and catalogs."""
import base64
import binascii
from datetime import date, datetime
from enum import Enum
from typing import Annotated, Any, Optional, Type
from pydantic import BeforeValidator, Field, StringConstraints, ValidationInfo
from core.columns import HOSPITAL_ID_LENGTH
from extraction import ExtractionError
from extraction.signals import EegRecording
# Same bound as Core's VARCHAR column, so an over-long id is a validation
# error here rather than a `Data too long` failure at insert on MySQL/Postgres.
HospitalId = Annotated[str, StringConstraints(max_length=HOSPITAL_ID_LENGTH)]
def required_str(v: Any, info: ValidationInfo) -> str:
if v is None or str(v).strip() == "":
raise ValueError(f"{info.field_name} es requerido")
return str(v).strip()
def optional_str(v: Any) -> Any:
if v is None:
return None
text = str(v).strip()
return text or None
_DAY_FIRST_FORMATS = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d")
def required_date(v: Any, info: ValidationInfo) -> Any:
coerced = coerce_date(v)
if coerced is None:
raise ValueError(f"{info.field_name} es requerido")
return coerced
def coerce_date(v: Any) -> Any:
"""Accepts a `date`, a `datetime` (Excel and SQL often return one for a
date-only column), an ISO-8601 string, or a day-first string such as
`15/01/1990`. Month-first is not supported because Mexican source systems
write dates day-first."""
if v is None or (isinstance(v, str) and not v.strip()):
return None
if isinstance(v, datetime):
return v.date()
if isinstance(v, date):
return v
if isinstance(v, str):
text = v.strip()
try:
return datetime.fromisoformat(text).date() if len(text) > 10 else date.fromisoformat(text)
except ValueError:
pass
for fmt in _DAY_FIRST_FORMATS:
try:
return datetime.strptime(text, fmt).date()
except ValueError:
continue
raise ValueError(f"'{text}' no es una fecha válida (use AAAA-MM-DD o DD/MM/AAAA)")
return v
class Catalog:
"""A closed set of valid values for one field: an `Enum`'s values plus any
aliases for them, matched case-insensitively. Built from the Enum because
several alias dicts only list the exceptions (`PARENTESCO_ALIAS` has one entry)."""
def __init__(self, enum_cls: Type[Enum], aliases: dict[str, str] | None = None, *, strict: bool = True):
self.name = enum_cls.__name__
# strict=False only for catalogs Core marks as tentative: known values are
# still normalized, unknown ones pass through instead of rejecting real data.
self.strict = strict
self._lookup: dict[str, str] = {}
for member in enum_cls:
self._lookup[member.value.upper()] = member.value
self._lookup.setdefault(member.name.upper(), member.value)
for raw, canonical in (aliases or {}).items():
self._lookup[str(raw).strip().upper()] = canonical
def __repr__(self) -> str:
return f"Catalog({self.name}{'' if self.strict else ', strict=False'})"
@property
def values(self) -> list[str]:
return sorted(set(self._lookup.values()))
@property
def choices(self) -> dict[str, str]:
"""Every accepted surface form (uppercased) mapped to its canonical value."""
return dict(self._lookup)
def resolve(self, raw: str) -> str | None:
return self._lookup.get(raw.strip().upper())
def coerce(self, v: Any) -> Any:
"""Normalizes a raw value to its canonical form. An unknown value is an
`out_of_catalog` error, never silently stored: the target columns are plain
text, so nothing downstream would catch it."""
if v is None:
return None
text = str(v).strip()
if not text:
return None
resolved = self.resolve(text)
if resolved is not None:
return resolved
if not self.strict:
return text
raise ValueError(f"'{text}' no está en el catálogo (válidos: {', '.join(map(str, self.values))})")
def CatalogValue(catalog: Catalog): # noqa: N802 (used in annotations, like a type)
"""Field type for a catalog-backed column; the Catalog stays in
`FieldInfo.metadata` so `ImportSchema.catalog_for` can find it."""
return Annotated[Optional[str], BeforeValidator(catalog.coerce), catalog]
def coerce_postal_code(v: Any) -> Any:
"""Mexican postal codes are 5 digits. A numeric source (Excel cell, SQL
INT column) has already dropped the leading zero, so restore it."""
if v is None or (isinstance(v, str) and not v.strip()):
return None
if isinstance(v, bool):
return v
if isinstance(v, int) or (isinstance(v, float) and v.is_integer()):
return f"{int(v):05d}"
return str(v).strip()
# Same shape as Core's CHAR(5) column. CaMa's REGEXP CHECK can't run on
# SQLite and is not in the migrations, so the format is enforced here.
CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")]
# A short code of a natural key made of bounded VARCHAR(32) columns (`relacion_ados2`): an over-long value is a
# validation error here rather than a `Data too long` failure at insert on MySQL/Postgres. Optional, like every
# TEA field (see `tea/pacientes.py`).
ShortKey = Annotated[Optional[Annotated[str, StringConstraints(max_length=32)]], BeforeValidator(optional_str)]
def edf_file(v: Any) -> Any:
"""`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment).
JSON sources may carry it base64-encoded."""
if v is None or (isinstance(v, str) and not v.strip()):
return None
if isinstance(v, str):
try:
v = base64.b64decode(v, validate=True)
except (binascii.Error, ValueError) as exc:
raise ValueError("el archivo EDF debe venir como bytes o base64") from exc
if not isinstance(v, (bytes, bytearray)):
raise ValueError("el archivo EDF debe venir como bytes o base64")
try:
EegRecording.validate_edf(bytes(v))
except ExtractionError as exc:
raise ValueError(f"no es un archivo EDF válido: {exc}") from exc
return bytes(v)
# Field types. Blank cells become None; required ones say which field is missing.
OptionalStr = Annotated[Optional[str], BeforeValidator(optional_str)]
# A TEA record's own id as the source sends it (its primary key is String(36)).
SourceId = Annotated[Optional[Annotated[str, StringConstraints(max_length=36)]], BeforeValidator(optional_str)]
RequiredStr = Annotated[str, BeforeValidator(required_str)]
RequiredHospitalId = Annotated[HospitalId, BeforeValidator(required_str)]
FlexDate = Annotated[Optional[date], BeforeValidator(coerce_date)]
RequiredDate = Annotated[date, BeforeValidator(required_date)]
PostalCode = Annotated[Optional[CodigoPostal], BeforeValidator(coerce_postal_code)]
EdfFile = Annotated[Optional[bytes], BeforeValidator(edf_file)]
def Bounded(kind: type, low: float | None = None, high: float | None = None): # noqa: N802 (used like a type)
"""An optional number within [low, high], either bound open when None: a score or a count out of range is a
validation error, not a stored value."""
return Optional[Annotated[kind, Field(ge=low, le=high)]]