Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c0979dd0ed | |||
| 23f529e85c | |||
| 7ea755d3aa | |||
| 8802b804ac | |||
| 3b9099f6bf | |||
| 35bcd2fdcc | |||
| 6f656cec6d | |||
| 0c970b0080 | |||
| f318fb89da | |||
| 6470e99ea5 | |||
| 0351476ec9 | |||
| 444c806d5c | |||
| 7fcc7bdfe9 | |||
| 4ab37f8433 | |||
| 92eae777c9 | |||
| 8b0c0c6733 | |||
| 798ba005cd | |||
| abd056aa8a | |||
| c159a69284 | |||
| 87a02938a9 | |||
| 8572e90e06 | |||
| 5840de1163 | |||
| 73238205ba | |||
| 4a18656dd2 | |||
| 6efa4c6151 | |||
| 84144b03db |
+3
-3
@@ -1,6 +1,4 @@
|
||||
# WebApi's docker-compose service builds with context: . (this directory)
|
||||
# so it can COPY its sibling Core/, Persistance/ and models/ directories —
|
||||
# this is the .dockerignore Docker actually reads for that build.
|
||||
# Read by the webapi build, whose context is the repo root.
|
||||
.git/
|
||||
WebApp/
|
||||
**/__pycache__/
|
||||
@@ -10,3 +8,5 @@ WebApp/
|
||||
**/.pytest_cache/
|
||||
**/*.db
|
||||
**/uv.lock
|
||||
dist/
|
||||
**/node_modules/
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Copy to .env (docker compose reads it for the webapi service; Persistance's
|
||||
# settings also read a .env in the working directory when run directly).
|
||||
|
||||
# --- Target databases (one per domain; SQLite files by default) ---
|
||||
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
|
||||
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
|
||||
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
|
||||
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
|
||||
CACU_DATABASE_URL=sqlite:////data/cacu.db
|
||||
CAMA_DATABASE_URL=sqlite:////data/cama.db
|
||||
TEA_DATABASE_URL=sqlite:////data/tea.db
|
||||
# Model and cohort versions, artifacts, predictions, extraction log.
|
||||
GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
|
||||
|
||||
# --- SQL import sources a client may point the server at ---
|
||||
# SQLAlchemy backend names. sqlite is excluded on purpose: its URL is a
|
||||
# path on this server's disk.
|
||||
WEBAPI_SQL_ALLOWED_DIALECTS=mysql,mariadb,postgresql,mssql,oracle
|
||||
# Optional host allowlist (unset = any host reachable from the server).
|
||||
# WEBAPI_SQL_ALLOWED_HOSTS=10.0.10.41,his-db.internal
|
||||
|
||||
# --- Model artifacts (checkpoints, training by-products) ---
|
||||
# Must live on a persisted volume, not the container's filesystem.
|
||||
MODELS_ARTIFACT_ROOT=/data/artifacts
|
||||
|
||||
# --- WebApi process ---
|
||||
# Max request size (files travel inside import requests). Keep nginx's
|
||||
# client_max_body_size (WebApp/nginx.conf) about 35% above it.
|
||||
WEBAPI_MAX_UPLOAD_MB=200
|
||||
# WEBAPI_WORKERS=2
|
||||
# Seconds; OCR over many scanned pages runs inside one request.
|
||||
# WEBAPI_TIMEOUT=600
|
||||
# Tesseract languages for scanned documents.
|
||||
# EXTRACTION_OCR_LANG=spa+eng
|
||||
# Only for browser clients on another origin (the WebApp uses the proxy).
|
||||
# WEBAPI_CORS_ORIGINS=https://example.internal
|
||||
+20
-1
@@ -1,4 +1,23 @@
|
||||
# Local orientation docs, not committed anywhere in this workspace.
|
||||
# Local agent notes, not committed.
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
HANDOFF*.md
|
||||
|
||||
# Local environment (database credentials); docker-compose reads it but git
|
||||
# must never see it. Committed template lives in .env.example.
|
||||
.env
|
||||
|
||||
# Agent-session scratch: a scripted/browser E2E harness built up as an
|
||||
# ad hoc proof-of-work diary across sessions, not project deliverables.
|
||||
# Equivalent synthetic-data/smoke-test tooling on the team's side lives in
|
||||
# its own separate repo (dev-data), never inside the main one.
|
||||
e2e/
|
||||
|
||||
.DS_Store
|
||||
|
||||
|
||||
# Deliverable bundle: images and local state are built/created, not versioned.
|
||||
dist/imagenes/
|
||||
dist/.env
|
||||
dist/datos/
|
||||
dist/*.tar.gz
|
||||
|
||||
@@ -7,3 +7,7 @@
|
||||
[submodule "models"]
|
||||
path = models
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
|
||||
[submodule "indicadores_kit"]
|
||||
path = indicadores_kit
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/indicadores_kit.git
|
||||
branch = dev
|
||||
|
||||
@@ -7,7 +7,6 @@ registry = orm.registry()
|
||||
class CaCuModel(SQLModel, registry=registry):
|
||||
"""Base class for every CaCu table.
|
||||
|
||||
Own SQLAlchemy registry/metadata so table names (e.g. NotaMedica) don't
|
||||
collide with CaMa's identically-named tables now that both domains live
|
||||
in the same Python package.
|
||||
Uses its own SQLAlchemy registry so table names such as `notamedica`
|
||||
don't collide with CaMa's tables of the same name.
|
||||
"""
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
|
||||
class BiometriaHematica(CaCuModel, table=True):
|
||||
@@ -16,20 +17,20 @@ class BiometriaHematica(CaCuModel, table=True):
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
)
|
||||
# Identificador del hospital — permite vincular estudios con pacientes
|
||||
# Identificador del hospital; permite vincular estudios con pacientes
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
|
||||
)
|
||||
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
|
||||
ord_numero_hospital: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="numero de orden HIS — join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
)
|
||||
bh_fecha: Optional[date] = Field(
|
||||
default=None,
|
||||
|
||||
@@ -15,4 +15,8 @@ GRADO_CIN_ALIAS: dict[str, str] = {
|
||||
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
|
||||
"CARCINOMA IN SITU": "CIS",
|
||||
"CARCINOMA INVASOR": "CARCINOMA",
|
||||
# CIN/NIC grades as reports write them; CIN2 and CIN3 are both LIEAG.
|
||||
"CIN1": "LIEBG", "CIN 1": "LIEBG", "CIN-1": "LIEBG", "NIC1": "LIEBG", "NIC 1": "LIEBG", "NIC-1": "LIEBG",
|
||||
"CIN2": "LIEAG", "CIN 2": "LIEAG", "CIN-2": "LIEAG", "NIC2": "LIEAG", "NIC 2": "LIEAG", "NIC-2": "LIEAG",
|
||||
"CIN3": "LIEAG", "CIN 3": "LIEAG", "CIN-3": "LIEAG", "NIC3": "LIEAG", "NIC 3": "LIEAG", "NIC-3": "LIEAG",
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
|
||||
|
||||
class BiopsiaCervical(CaCuModel, table=True):
|
||||
"""
|
||||
@@ -15,20 +16,20 @@ class BiopsiaCervical(CaCuModel, table=True):
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
)
|
||||
# Identificador del hospital — obligatorio, es el que permite vincular estudios con pacientes
|
||||
# Identificador del hospital, obligatorio; permite vincular estudios con pacientes
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
|
||||
)
|
||||
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
|
||||
ord_numero_hospital: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="numero de orden HIS — join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
)
|
||||
cit_id: Optional[int] = Field(
|
||||
default=None,
|
||||
@@ -53,11 +54,29 @@ class BiopsiaCervical(CaCuModel, table=True):
|
||||
)
|
||||
bx_pdf_blob: Optional[bytes] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.LargeBinary),
|
||||
sa_column=sa.Column(FileBlob),
|
||||
)
|
||||
bx_ocr_confianza: Optional[float] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Float),
|
||||
)
|
||||
# VAR-03
|
||||
bx_ocr_estatus: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="valor de core.ocr.OcrEstatus guardado como texto",
|
||||
)
|
||||
bx_ocr_requiere_revision: Optional[bool] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Boolean),
|
||||
)
|
||||
bx_ocr_metodo_principal: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
bx_ocr_metodo_alternativo: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -20,6 +20,11 @@ CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
|
||||
"LESIÓN INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
|
||||
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
|
||||
"CARCINOMA IN SITU": "CIS",
|
||||
# Bethesda "negativo para lesión intraepitelial o malignidad" (NILM).
|
||||
"NEGATIVO": "NORMAL",
|
||||
"NILM": "NORMAL",
|
||||
"NEGATIVO PARA LESION INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
|
||||
"NEGATIVO PARA LESIÓN INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
|
||||
}
|
||||
|
||||
CITO_CALIDAD_ESPECIMEN_ALIAS: dict[str,bool] = {
|
||||
|
||||
@@ -4,26 +4,27 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
|
||||
|
||||
class CitologiaCervical(CaCuModel, table=True):
|
||||
cit_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
)
|
||||
# Identificador del hospital — obligatorio, es el que permite vincular estudios con pacientes
|
||||
# Identificador del hospital, obligatorio; permite vincular estudios con pacientes
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
|
||||
)
|
||||
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
|
||||
ord_numero_hospital: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="numero de orden HIS — join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
)
|
||||
cit_fecha_toma: Optional[date] = Field(
|
||||
default=None,
|
||||
@@ -40,33 +41,33 @@ class CitologiaCervical(CaCuModel, table=True):
|
||||
)
|
||||
cit_pdf_blob: Optional[bytes] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.LargeBinary),
|
||||
sa_column=sa.Column(FileBlob),
|
||||
description="PDF de resultado",
|
||||
)
|
||||
cit_observaciones: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="Observaciones — hacer enum cuando se conozcan valores",
|
||||
description="Observaciones; hacer enum cuando se conozcan valores",
|
||||
)
|
||||
cit_condiciones_ginecoobs: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="Condiciones gineco-obstétricas: embarazo, DIU, etc. — hacer enum",
|
||||
description="Condiciones gineco-obstétricas: embarazo, DIU, etc.; hacer enum",
|
||||
)
|
||||
cit_exploracion: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="Hallazgos en exploración — hacer enum",
|
||||
description="Hallazgos en exploración; hacer enum",
|
||||
)
|
||||
cit_dx_lesion: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="TC6 Diagnóstico citológico para lesión — hacer enum",
|
||||
description="TC6 Diagnóstico citológico para lesión; hacer enum",
|
||||
)
|
||||
cit_celulas_glandulares: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="TC9 Anomalías del epitelio glandular — hacer enum",
|
||||
description="TC9 Anomalías del epitelio glandular; hacer enum",
|
||||
)
|
||||
cit_carcinoma_invasor: Optional[str] = Field(
|
||||
default=None,
|
||||
@@ -79,7 +80,7 @@ class CitologiaCervical(CaCuModel, table=True):
|
||||
)
|
||||
cit_vph_pdf_blob: Optional[bytes] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.LargeBinary)
|
||||
sa_column=sa.Column(FileBlob)
|
||||
)
|
||||
cit_vph_ocr_confianza: Optional[float] = Field(
|
||||
default=None,
|
||||
@@ -94,9 +95,28 @@ class CitologiaCervical(CaCuModel, table=True):
|
||||
sa_column=sa.Column(sa.Integer)
|
||||
)
|
||||
cit_vph_genotipo_18: Optional[int] = Field(
|
||||
default=None,
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer)
|
||||
)
|
||||
# VAR-03: además de la confianza se guarda el estatus, la bandera de
|
||||
# revisión manual y el método (principal o alternativo) que produjo el valor.
|
||||
cit_vph_ocr_estatus: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="valor de core.ocr.OcrEstatus guardado como texto",
|
||||
)
|
||||
cit_vph_ocr_requiere_revision: Optional[bool] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Boolean),
|
||||
)
|
||||
cit_vph_ocr_metodo_principal: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
cit_vph_ocr_metodo_alternativo: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -3,3 +3,4 @@ from core.cacu.citologia_cervical.enums import CelulasEscamosas, CELULAS_ESCAMOS
|
||||
from core.cacu.biopsia_cervical.enums import GradoCIN, GRADO_CIN_ALIAS
|
||||
from core.cacu.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
|
||||
from core.cacu.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
|
||||
from core.cacu.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class TipoEpisodio(str, Enum):
|
||||
"""IND-02: la unidad de análisis para evaluación de desempeño del
|
||||
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
|
||||
|
||||
TAMIZAJE = "TAMIZAJE"
|
||||
DIAGNOSTICO = "DIAGNOSTICO"
|
||||
TRATAMIENTO = "TRATAMIENTO"
|
||||
|
||||
|
||||
TIPO_EPISODIO_ALIAS: dict[str, str] = {
|
||||
"SCREENING": "TAMIZAJE",
|
||||
"DIAGNOSTIC": "DIAGNOSTICO",
|
||||
"TREATMENT": "TRATAMIENTO",
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
|
||||
class EpisodioClinico(CaCuModel, table=True):
|
||||
"""IND-02/IND-03: a screening, diagnosis or treatment episode, the unit
|
||||
of analysis for model evaluation.
|
||||
|
||||
An episode combines a CIE10 code and medical specialty, a time window
|
||||
bounded by the previous episode (`episodio_anterior_id`), and the medical
|
||||
note it originates from (`nm_id`). The CIE10 code and specialty are
|
||||
usually copied from `NotaMedica` and stored here so episodes can be
|
||||
filtered without joining back to the note. Storage only; building
|
||||
episodes from notes and orders is not implemented yet.
|
||||
"""
|
||||
|
||||
episodio_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
|
||||
)
|
||||
tipo_episodio: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="valor de core.cacu.episodio_clinico.enums.TipoEpisodio guardado como texto",
|
||||
)
|
||||
nm_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
|
||||
description="nota médica cuyo contenido escrito origina/documenta el episodio",
|
||||
)
|
||||
cie10_codigo: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
especialidad_medica: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
evento_fecha: date = Field(
|
||||
sa_column=sa.Column(sa.Date, nullable=False),
|
||||
description="fecha del evento de interés que define el episodio",
|
||||
)
|
||||
ventana_inicio: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
description="inicio de la ventana de tiempo fija delimitada a partir del evento anterior",
|
||||
)
|
||||
ventana_fin: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
)
|
||||
episodio_anterior_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
|
||||
description="evento anterior que delimita la ventana de este episodio",
|
||||
)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Las tablas de indicadores_kit en el dominio CaCu.
|
||||
|
||||
Viven en el registro de `CaCuModel`, en la misma base que el staging de
|
||||
CaCu (ADR-004). Las columnas se declaran una vez en `core.indicadores`;
|
||||
aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
|
||||
staging: `persona` es propia aunque repita a `paciente`.
|
||||
"""
|
||||
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.indicadores.cohortes import (
|
||||
CohorteArmadoBase,
|
||||
CohorteExclusionBase,
|
||||
CohorteMiembroBase,
|
||||
CohorteVariableBase,
|
||||
EvaluacionRiesgoBase,
|
||||
EvaluacionRiesgoLoteBase,
|
||||
armado_unico,
|
||||
evaluacion_unica,
|
||||
variable_con_un_valor,
|
||||
)
|
||||
from core.indicadores.catalogos import (
|
||||
CatEstudioBase,
|
||||
CatResultadoBase,
|
||||
CatValorBase,
|
||||
estado_de_valor_conocido,
|
||||
tipo_de_valor_conocido,
|
||||
)
|
||||
from core.indicadores.plata import (
|
||||
ObservacionClinicaBase,
|
||||
ProcedimientoClinicoBase,
|
||||
clase_conocida,
|
||||
indice_de_observacion,
|
||||
indice_de_procedimiento,
|
||||
observacion_en_catalogo,
|
||||
llave_de_observacion,
|
||||
llave_de_procedimiento,
|
||||
)
|
||||
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
|
||||
from core.indicadores.registro import (
|
||||
DefParametroBase,
|
||||
DimFechaBase,
|
||||
DimGrupoEdadBase,
|
||||
DimPeriodoBase,
|
||||
)
|
||||
from core.indicadores.publicacion import (
|
||||
CatEstratoBase,
|
||||
CatEstratoValorBase,
|
||||
CatMeasureBase,
|
||||
CatMeasureEstratoBase,
|
||||
CatMeasureGrupoBase,
|
||||
CatMeasureResultadoBase,
|
||||
CatMeasureValorBase,
|
||||
MeasureReportUnidadBase,
|
||||
MeasureReportUnidadEstratoBase,
|
||||
contrato_y_unidad_conocidos,
|
||||
origen_conocido,
|
||||
poblacion_conocida,
|
||||
una_poblacion_por_indicador,
|
||||
unidad_de_estrato_conocida,
|
||||
valor_de_estrato_en_catalogo,
|
||||
)
|
||||
from core.indicadores.reportes import (
|
||||
MeasureReportBase,
|
||||
)
|
||||
|
||||
|
||||
class Persona(CaCuModel, PersonaDerechohabienteBase, table=True):
|
||||
__tablename__ = "persona"
|
||||
|
||||
|
||||
class PeriodoObservacion(CaCuModel, PeriodoObservacionBase, table=True):
|
||||
__tablename__ = "periodo_observacion"
|
||||
|
||||
|
||||
class Carga(CaCuModel, CargaBase, table=True):
|
||||
__tablename__ = "carga"
|
||||
|
||||
|
||||
class DefParametro(CaCuModel, DefParametroBase, table=True):
|
||||
__tablename__ = "def_parametro"
|
||||
|
||||
|
||||
class DimPeriodo(CaCuModel, DimPeriodoBase, table=True):
|
||||
__tablename__ = "dim_periodo"
|
||||
|
||||
|
||||
class DimFecha(CaCuModel, DimFechaBase, table=True):
|
||||
__tablename__ = "dim_fecha"
|
||||
|
||||
|
||||
class DimGrupoEdad(CaCuModel, DimGrupoEdadBase, table=True):
|
||||
__tablename__ = "dim_grupo_edad"
|
||||
|
||||
|
||||
class MeasureReport(CaCuModel, MeasureReportBase, table=True):
|
||||
__tablename__ = "measure_report"
|
||||
|
||||
|
||||
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
|
||||
|
||||
|
||||
class CatMeasure(CaCuModel, CatMeasureBase, table=True):
|
||||
__tablename__ = "cat_measure"
|
||||
__table_args__ = contrato_y_unidad_conocidos()
|
||||
|
||||
|
||||
class CatMeasureResultado(CaCuModel, CatMeasureResultadoBase, table=True):
|
||||
__tablename__ = "cat_measure_resultado"
|
||||
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
|
||||
|
||||
|
||||
class CatMeasureValor(CaCuModel, CatMeasureValorBase, table=True):
|
||||
__tablename__ = "cat_measure_valor"
|
||||
__table_args__ = (origen_conocido(),)
|
||||
|
||||
|
||||
class CatMeasureGrupo(CaCuModel, CatMeasureGrupoBase, table=True):
|
||||
__tablename__ = "cat_measure_grupo"
|
||||
|
||||
|
||||
class CatEstrato(CaCuModel, CatEstratoBase, table=True):
|
||||
__tablename__ = "cat_estrato"
|
||||
__table_args__ = (unidad_de_estrato_conocida(),)
|
||||
|
||||
|
||||
class CatEstratoValor(CaCuModel, CatEstratoValorBase, table=True):
|
||||
__tablename__ = "cat_estrato_valor"
|
||||
|
||||
|
||||
class CatMeasureEstrato(CaCuModel, CatMeasureEstratoBase, table=True):
|
||||
__tablename__ = "cat_measure_estrato"
|
||||
|
||||
|
||||
class MeasureReportUnidad(CaCuModel, MeasureReportUnidadBase, table=True):
|
||||
__tablename__ = "measure_report_unidad"
|
||||
|
||||
|
||||
class MeasureReportUnidadEstrato(CaCuModel, MeasureReportUnidadEstratoBase, table=True):
|
||||
__tablename__ = "measure_report_unidad_estrato"
|
||||
__table_args__ = (valor_de_estrato_en_catalogo(),)
|
||||
|
||||
|
||||
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cacu.toml ---
|
||||
|
||||
|
||||
class CatEstudio(CaCuModel, CatEstudioBase, table=True):
|
||||
__tablename__ = "cat_estudio"
|
||||
|
||||
|
||||
class CatResultado(CaCuModel, CatResultadoBase, table=True):
|
||||
__tablename__ = "cat_resultado"
|
||||
__table_args__ = (tipo_de_valor_conocido(),)
|
||||
|
||||
|
||||
class CatValor(CaCuModel, CatValorBase, table=True):
|
||||
__tablename__ = "cat_valor"
|
||||
__table_args__ = (estado_de_valor_conocido(),)
|
||||
|
||||
|
||||
# --- La plata de dos tablas (F5, ADR-MD-007) ---
|
||||
|
||||
|
||||
class Procedimiento(CaCuModel, ProcedimientoClinicoBase, table=True):
|
||||
__tablename__ = "procedimiento"
|
||||
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
|
||||
|
||||
|
||||
class Observacion(CaCuModel, ObservacionClinicaBase, table=True):
|
||||
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
|
||||
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
|
||||
|
||||
|
||||
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003) ---
|
||||
|
||||
|
||||
class CohorteArmado(CaCuModel, CohorteArmadoBase, table=True):
|
||||
__tablename__ = "cohorte_armado"
|
||||
__table_args__ = (armado_unico(),)
|
||||
|
||||
|
||||
class CohorteMiembro(CaCuModel, CohorteMiembroBase, table=True):
|
||||
__tablename__ = "cohorte_miembro"
|
||||
|
||||
|
||||
class CohorteExclusion(CaCuModel, CohorteExclusionBase, table=True):
|
||||
__tablename__ = "cohorte_exclusion"
|
||||
|
||||
|
||||
class CohorteVariable(CaCuModel, CohorteVariableBase, table=True):
|
||||
__tablename__ = "cohorte_variable"
|
||||
__table_args__ = (variable_con_un_valor(),)
|
||||
|
||||
|
||||
class EvaluacionRiesgoLote(CaCuModel, EvaluacionRiesgoLoteBase, table=True):
|
||||
__tablename__ = "evaluacion_riesgo_lote"
|
||||
|
||||
|
||||
class EvaluacionRiesgo(CaCuModel, EvaluacionRiesgoBase, table=True):
|
||||
__tablename__ = "evaluacion_riesgo"
|
||||
__table_args__ = (evaluacion_unica(),)
|
||||
@@ -4,6 +4,7 @@ from core.cacu.citologia_cervical.model import CitologiaCervical
|
||||
from core.cacu.biopsia_cervical.model import BiopsiaCervical
|
||||
from core.cacu.nota_medica.model import NotaMedica
|
||||
from core.cacu.biometria_hematica.model import BiometriaHematica
|
||||
from core.cacu.episodio_clinico.model import EpisodioClinico
|
||||
|
||||
__all__ = [
|
||||
"Paciente",
|
||||
@@ -12,4 +13,5 @@ __all__ = [
|
||||
"BiopsiaCervical",
|
||||
"NotaMedica",
|
||||
"BiometriaHematica",
|
||||
"EpisodioClinico",
|
||||
]
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
class NotaMedica(CaCuModel, table=True):
|
||||
"""
|
||||
@@ -17,14 +18,16 @@ class NotaMedica(CaCuModel, table=True):
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="rellenado por el loader via lookup en paciente.pac_id_hospital — puede quedar nulo",
|
||||
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, index=True, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
|
||||
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
|
||||
)
|
||||
# Bounded and indexed: part of the natural key (with pac_id_hospital)
|
||||
# the import layer upserts/merges notes on.
|
||||
nm_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
|
||||
)
|
||||
nm_nota_previa_id: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
class OrdenesEstudio(CaCuModel, table=True):
|
||||
"""
|
||||
@@ -22,7 +23,7 @@ class OrdenesEstudio(CaCuModel, table=True):
|
||||
)
|
||||
# Desnormalizado para joins directos sin pasar por paciente
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
|
||||
)
|
||||
ord_numero_hospital: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
class Paciente(CaCuModel, table=True):
|
||||
"""
|
||||
@@ -14,17 +15,18 @@ class Paciente(CaCuModel, table=True):
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
# Identificador original del paciente en el HIS (DG1) — indice unico para lookups confiables
|
||||
# Identificador original del paciente en el HIS (DG1), con indice unico para busquedas
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, unique=True, index=True, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
|
||||
)
|
||||
pac_sexo: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
pac_fecha_nacimiento: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
# IND-01: obligatoria; el sistema calcula la edad en cada evento de
|
||||
# interés (episodio clínico) a partir de esta fecha.
|
||||
pac_fecha_nacimiento: date = Field(
|
||||
sa_column=sa.Column(sa.Date, nullable=False),
|
||||
)
|
||||
pac_codigo_postal: Optional[str] = Field(
|
||||
default=None,
|
||||
@@ -42,7 +44,7 @@ class Paciente(CaCuModel, table=True):
|
||||
pac_parentesco: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="Parentesco", # descripción original decía Departamento — corregida
|
||||
description="Parentesco",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ registry = orm.registry()
|
||||
class CaMaModel(SQLModel, registry=registry):
|
||||
"""Base class for every CaMa table.
|
||||
|
||||
Own SQLAlchemy registry/metadata so table names (e.g. NotaMedica) don't
|
||||
collide with CaCu's identically-named tables now that both domains live
|
||||
in the same Python package.
|
||||
Uses its own SQLAlchemy registry so table names such as `notamedica`
|
||||
don't collide with CaCu's tables of the same name.
|
||||
"""
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cama.base import CaMaModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
|
||||
class BiometriaHematica(CaMaModel, table=True):
|
||||
@@ -16,20 +17,20 @@ class BiometriaHematica(CaMaModel, table=True):
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
)
|
||||
# Identificador del hospital — permite vincular estudios con pacientes
|
||||
# Identificador del hospital; permite vincular estudios con pacientes
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
|
||||
)
|
||||
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
|
||||
ord_numero_hospital: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="numero de orden HIS — join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
)
|
||||
bh_fecha: Optional[date] = Field(
|
||||
default=None,
|
||||
|
||||
@@ -4,10 +4,11 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cama.base import CaMaModel
|
||||
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
|
||||
|
||||
class BiopsiaMama(CaMaModel, table=True):
|
||||
"""
|
||||
Modelo ORM para biopsia de mama. Fechas en sa.Date — sistema estructurado.
|
||||
Modelo ORM para biopsia de mama. Fechas en sa.Date (sistema estructurado).
|
||||
"""
|
||||
bx_id: Optional[int] = Field(
|
||||
default=None,
|
||||
@@ -16,11 +17,11 @@ class BiopsiaMama(CaMaModel, table=True):
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="join logico — resuelto por el loader via lookup en paciente.pac_id_hospital",
|
||||
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False, index=True),
|
||||
description="identificador hospitalario — obligatorio para vincular estudios con pacientes",
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
|
||||
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
|
||||
)
|
||||
ord_id: Optional[int] = Field(
|
||||
default=None,
|
||||
@@ -30,7 +31,7 @@ class BiopsiaMama(CaMaModel, table=True):
|
||||
ord_numero_hospital: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="numero de orden HIS — join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
)
|
||||
mast_id: Optional[int] = Field(
|
||||
default=None,
|
||||
@@ -50,12 +51,30 @@ class BiopsiaMama(CaMaModel, table=True):
|
||||
)
|
||||
bx_pdf_blob: Optional[bytes] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.LargeBinary),
|
||||
sa_column=sa.Column(FileBlob),
|
||||
)
|
||||
bx_ocr_confianza: Optional[float] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Float),
|
||||
)
|
||||
# VARM-04a
|
||||
bx_ocr_estatus: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="valor de core.ocr.OcrEstatus guardado como texto",
|
||||
)
|
||||
bx_ocr_requiere_revision: Optional[bool] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Boolean),
|
||||
)
|
||||
bx_ocr_metodo_principal: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
bx_ocr_metodo_alternativo: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -3,3 +3,4 @@ from core.cama.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad,
|
||||
from core.cama.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
|
||||
from core.cama.biopsia_mama.enums import GradoHistologicoMama
|
||||
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
|
||||
from core.cama.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class TipoEpisodio(str, Enum):
|
||||
"""IND-02: la unidad de análisis para evaluación de desempeño del
|
||||
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
|
||||
|
||||
TAMIZAJE = "TAMIZAJE"
|
||||
DIAGNOSTICO = "DIAGNOSTICO"
|
||||
TRATAMIENTO = "TRATAMIENTO"
|
||||
|
||||
|
||||
TIPO_EPISODIO_ALIAS: dict[str, str] = {
|
||||
"SCREENING": "TAMIZAJE",
|
||||
"DIAGNOSTIC": "DIAGNOSTICO",
|
||||
"TREATMENT": "TRATAMIENTO",
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cama.base import CaMaModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
|
||||
class EpisodioClinico(CaMaModel, table=True):
|
||||
"""IND-02/IND-03: clinical episode for CaMa. Same structure as
|
||||
`core.cacu.episodio_clinico.model.EpisodioClinico`."""
|
||||
|
||||
episodio_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
|
||||
)
|
||||
tipo_episodio: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="valor de core.cama.episodio_clinico.enums.TipoEpisodio guardado como texto",
|
||||
)
|
||||
nm_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
|
||||
description="nota médica cuyo contenido escrito origina/documenta el episodio",
|
||||
)
|
||||
cie10_codigo: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
especialidad_medica: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
evento_fecha: date = Field(
|
||||
sa_column=sa.Column(sa.Date, nullable=False),
|
||||
description="fecha del evento de interés que define el episodio",
|
||||
)
|
||||
ventana_inicio: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
)
|
||||
ventana_fin: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
)
|
||||
episodio_anterior_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
|
||||
)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Las tablas de indicadores_kit en el dominio CaMa.
|
||||
|
||||
Viven en el registro de `CaMaModel`, en la misma base que el staging de
|
||||
CaMa (ADR-004). Las columnas se declaran una vez en `core.indicadores`;
|
||||
aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
|
||||
staging: `persona` es propia aunque repita a `paciente`.
|
||||
"""
|
||||
|
||||
from core.cama.base import CaMaModel
|
||||
from core.indicadores.cohortes import (
|
||||
CohorteArmadoBase,
|
||||
CohorteExclusionBase,
|
||||
CohorteMiembroBase,
|
||||
CohorteVariableBase,
|
||||
EvaluacionRiesgoBase,
|
||||
EvaluacionRiesgoLoteBase,
|
||||
armado_unico,
|
||||
evaluacion_unica,
|
||||
variable_con_un_valor,
|
||||
)
|
||||
from core.indicadores.catalogos import (
|
||||
CatEstudioBase,
|
||||
CatResultadoBase,
|
||||
CatValorBase,
|
||||
estado_de_valor_conocido,
|
||||
tipo_de_valor_conocido,
|
||||
)
|
||||
from core.indicadores.plata import (
|
||||
ObservacionClinicaBase,
|
||||
ProcedimientoClinicoBase,
|
||||
clase_conocida,
|
||||
indice_de_observacion,
|
||||
indice_de_procedimiento,
|
||||
observacion_en_catalogo,
|
||||
llave_de_observacion,
|
||||
llave_de_procedimiento,
|
||||
)
|
||||
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
|
||||
from core.indicadores.registro import (
|
||||
DefParametroBase,
|
||||
DimFechaBase,
|
||||
DimGrupoEdadBase,
|
||||
DimPeriodoBase,
|
||||
)
|
||||
from core.indicadores.publicacion import (
|
||||
CatEstratoBase,
|
||||
CatEstratoValorBase,
|
||||
CatMeasureBase,
|
||||
CatMeasureEstratoBase,
|
||||
CatMeasureGrupoBase,
|
||||
CatMeasureResultadoBase,
|
||||
CatMeasureValorBase,
|
||||
MeasureReportUnidadBase,
|
||||
MeasureReportUnidadEstratoBase,
|
||||
contrato_y_unidad_conocidos,
|
||||
origen_conocido,
|
||||
poblacion_conocida,
|
||||
una_poblacion_por_indicador,
|
||||
unidad_de_estrato_conocida,
|
||||
valor_de_estrato_en_catalogo,
|
||||
)
|
||||
from core.indicadores.reportes import (
|
||||
MeasureReportBase,
|
||||
)
|
||||
|
||||
|
||||
class Persona(CaMaModel, PersonaDerechohabienteBase, table=True):
|
||||
__tablename__ = "persona"
|
||||
|
||||
|
||||
class PeriodoObservacion(CaMaModel, PeriodoObservacionBase, table=True):
|
||||
__tablename__ = "periodo_observacion"
|
||||
|
||||
|
||||
class Carga(CaMaModel, CargaBase, table=True):
|
||||
__tablename__ = "carga"
|
||||
|
||||
|
||||
class DefParametro(CaMaModel, DefParametroBase, table=True):
|
||||
__tablename__ = "def_parametro"
|
||||
|
||||
|
||||
class DimPeriodo(CaMaModel, DimPeriodoBase, table=True):
|
||||
__tablename__ = "dim_periodo"
|
||||
|
||||
|
||||
class DimFecha(CaMaModel, DimFechaBase, table=True):
|
||||
__tablename__ = "dim_fecha"
|
||||
|
||||
|
||||
class DimGrupoEdad(CaMaModel, DimGrupoEdadBase, table=True):
|
||||
__tablename__ = "dim_grupo_edad"
|
||||
|
||||
|
||||
class MeasureReport(CaMaModel, MeasureReportBase, table=True):
|
||||
__tablename__ = "measure_report"
|
||||
|
||||
|
||||
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
|
||||
|
||||
|
||||
class CatMeasure(CaMaModel, CatMeasureBase, table=True):
|
||||
__tablename__ = "cat_measure"
|
||||
__table_args__ = contrato_y_unidad_conocidos()
|
||||
|
||||
|
||||
class CatMeasureResultado(CaMaModel, CatMeasureResultadoBase, table=True):
|
||||
__tablename__ = "cat_measure_resultado"
|
||||
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
|
||||
|
||||
|
||||
class CatMeasureValor(CaMaModel, CatMeasureValorBase, table=True):
|
||||
__tablename__ = "cat_measure_valor"
|
||||
__table_args__ = (origen_conocido(),)
|
||||
|
||||
|
||||
class CatMeasureGrupo(CaMaModel, CatMeasureGrupoBase, table=True):
|
||||
__tablename__ = "cat_measure_grupo"
|
||||
|
||||
|
||||
class CatEstrato(CaMaModel, CatEstratoBase, table=True):
|
||||
__tablename__ = "cat_estrato"
|
||||
__table_args__ = (unidad_de_estrato_conocida(),)
|
||||
|
||||
|
||||
class CatEstratoValor(CaMaModel, CatEstratoValorBase, table=True):
|
||||
__tablename__ = "cat_estrato_valor"
|
||||
|
||||
|
||||
class CatMeasureEstrato(CaMaModel, CatMeasureEstratoBase, table=True):
|
||||
__tablename__ = "cat_measure_estrato"
|
||||
|
||||
|
||||
class MeasureReportUnidad(CaMaModel, MeasureReportUnidadBase, table=True):
|
||||
__tablename__ = "measure_report_unidad"
|
||||
|
||||
|
||||
class MeasureReportUnidadEstrato(CaMaModel, MeasureReportUnidadEstratoBase, table=True):
|
||||
__tablename__ = "measure_report_unidad_estrato"
|
||||
__table_args__ = (valor_de_estrato_en_catalogo(),)
|
||||
|
||||
|
||||
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cama.toml ---
|
||||
|
||||
|
||||
class CatEstudio(CaMaModel, CatEstudioBase, table=True):
|
||||
__tablename__ = "cat_estudio"
|
||||
|
||||
|
||||
class CatResultado(CaMaModel, CatResultadoBase, table=True):
|
||||
__tablename__ = "cat_resultado"
|
||||
__table_args__ = (tipo_de_valor_conocido(),)
|
||||
|
||||
|
||||
class CatValor(CaMaModel, CatValorBase, table=True):
|
||||
__tablename__ = "cat_valor"
|
||||
__table_args__ = (estado_de_valor_conocido(),)
|
||||
|
||||
|
||||
# --- La plata de dos tablas (F5, ADR-MD-007) ---
|
||||
|
||||
|
||||
class Procedimiento(CaMaModel, ProcedimientoClinicoBase, table=True):
|
||||
__tablename__ = "procedimiento"
|
||||
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
|
||||
|
||||
|
||||
class Observacion(CaMaModel, ObservacionClinicaBase, table=True):
|
||||
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
|
||||
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
|
||||
|
||||
|
||||
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003; CaMa desde MD-12) ---
|
||||
|
||||
|
||||
class CohorteArmado(CaMaModel, CohorteArmadoBase, table=True):
|
||||
__tablename__ = "cohorte_armado"
|
||||
__table_args__ = (armado_unico(),)
|
||||
|
||||
|
||||
class CohorteMiembro(CaMaModel, CohorteMiembroBase, table=True):
|
||||
__tablename__ = "cohorte_miembro"
|
||||
|
||||
|
||||
class CohorteExclusion(CaMaModel, CohorteExclusionBase, table=True):
|
||||
__tablename__ = "cohorte_exclusion"
|
||||
|
||||
|
||||
class CohorteVariable(CaMaModel, CohorteVariableBase, table=True):
|
||||
__tablename__ = "cohorte_variable"
|
||||
__table_args__ = (variable_con_un_valor(),)
|
||||
|
||||
|
||||
class EvaluacionRiesgoLote(CaMaModel, EvaluacionRiesgoLoteBase, table=True):
|
||||
__tablename__ = "evaluacion_riesgo_lote"
|
||||
|
||||
|
||||
class EvaluacionRiesgo(CaMaModel, EvaluacionRiesgoBase, table=True):
|
||||
__tablename__ = "evaluacion_riesgo"
|
||||
__table_args__ = (evaluacion_unica(),)
|
||||
@@ -15,6 +15,15 @@ BIRADS_ALIAS: dict[str, str] = {
|
||||
"BI-RADS 0": "B0", "BI-RADS 1": "B1", "BI-RADS 2": "B2",
|
||||
"BI-RADS 3": "B3", "BI-RADS 4": "B4", "BI-RADS 5": "B5", "BI-RADS 6": "B6",
|
||||
"0": "B0", "1": "B1", "2": "B2", "3": "B3", "4": "B4", "5": "B5", "6": "B6",
|
||||
# The 4A/4B/4C subcategories (ACR BI-RADS lexicon) are common in real
|
||||
# reports; this schema doesn't track them separately, so they fold into
|
||||
# the base B4 rather than being rejected as out-of-catalog.
|
||||
"BIRADS 4A": "B4", "BIRADS 4B": "B4", "BIRADS 4C": "B4",
|
||||
"BI-RADS 4A": "B4", "BI-RADS 4B": "B4", "BI-RADS 4C": "B4",
|
||||
"4A": "B4", "4B": "B4", "4C": "B4",
|
||||
# Raw hospital source values (mastografia.mast_birads) spell the
|
||||
# subcategory directly onto the code, e.g. "B4A" rather than "4A".
|
||||
"B4A": "B4", "B4B": "B4", "B4C": "B4",
|
||||
}
|
||||
|
||||
class GradoHistologicoMama(str, Enum):
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cama.base import CaMaModel
|
||||
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
|
||||
|
||||
class Mastografia(CaMaModel, table=True):
|
||||
"""
|
||||
@@ -16,11 +17,11 @@ class Mastografia(CaMaModel, table=True):
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="join logico — resuelto por el loader via lookup en paciente.pac_id_hospital",
|
||||
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False, index=True),
|
||||
description="identificador hospitalario — obligatorio para vincular estudios con pacientes",
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
|
||||
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
|
||||
)
|
||||
ord_id: Optional[int] = Field(
|
||||
default=None,
|
||||
@@ -30,7 +31,7 @@ class Mastografia(CaMaModel, table=True):
|
||||
ord_numero_hospital: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="numero de orden HIS — join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
|
||||
)
|
||||
mast_fecha_toma: Optional[date] = Field(
|
||||
default=None,
|
||||
@@ -50,12 +51,12 @@ class Mastografia(CaMaModel, table=True):
|
||||
)
|
||||
mast_dicom_blob: Optional[bytes] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.LargeBinary),
|
||||
sa_column=sa.Column(FileBlob),
|
||||
)
|
||||
mast_interpretacion: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="enlace o referencia a la interpretación del radiólogo — formato pendiente",
|
||||
description="enlace o referencia a la interpretación del radiólogo; formato pendiente",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from core.cama.mastografia.model import Mastografia
|
||||
from core.cama.biopsia_mama.model import BiopsiaMama
|
||||
from core.cama.nota_medica.model import NotaMedica
|
||||
from core.cama.biometria_hematica.model import BiometriaHematica
|
||||
from core.cama.episodio_clinico.model import EpisodioClinico
|
||||
|
||||
__all__ = [
|
||||
"Paciente",
|
||||
@@ -12,4 +13,5 @@ __all__ = [
|
||||
"BiopsiaMama",
|
||||
"NotaMedica",
|
||||
"BiometriaHematica",
|
||||
"EpisodioClinico",
|
||||
]
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cama.base import CaMaModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
class NotaMedica(CaMaModel, table=True):
|
||||
"""
|
||||
@@ -17,14 +18,16 @@ class NotaMedica(CaMaModel, table=True):
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="rellenado por el loader via lookup en paciente.pac_id_hospital — puede quedar nulo",
|
||||
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, index=True, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
|
||||
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
|
||||
)
|
||||
# Bounded and indexed: part of the natural key (with pac_id_hospital)
|
||||
# the import layer upserts/merges notes on.
|
||||
nm_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
|
||||
)
|
||||
nm_nota_previa_id: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from enum import Enum
|
||||
|
||||
class TipoEstudio(str, Enum):
|
||||
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders (indicadores_kit cama)
|
||||
BIOPSIA_CHICA = "BIOPSIA_CHICA"
|
||||
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cama.base import CaMaModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
class OrdenesEstudio(CaMaModel, table=True):
|
||||
"""
|
||||
@@ -22,7 +23,7 @@ class OrdenesEstudio(CaMaModel, table=True):
|
||||
)
|
||||
# Desnormalizado para joins directos sin pasar por paciente
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
|
||||
)
|
||||
ord_numero_hospital: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Optional
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.cama.base import CaMaModel
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
|
||||
class Paciente(CaMaModel, table=True):
|
||||
"""
|
||||
@@ -14,23 +15,24 @@ class Paciente(CaMaModel, table=True):
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
# Identificador original del paciente en el HIS (DG1) — indice unico para lookups confiables
|
||||
# Identificador original del paciente en el HIS (DG1), con indice unico para busquedas
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.Text, unique=True, index=True, nullable=False),
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
|
||||
)
|
||||
pac_sexo: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
pac_fecha_nacimiento: Optional[date] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Date),
|
||||
# IND-01: obligatoria; el sistema calcula la edad en cada evento de
|
||||
# interés (episodio clínico) a partir de esta fecha.
|
||||
pac_fecha_nacimiento: date = Field(
|
||||
sa_column=sa.Column(sa.Date, nullable=False),
|
||||
)
|
||||
pac_codigo_postal: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(
|
||||
sa.CHAR(5),
|
||||
sa.CheckConstraint("pac_codigo_postal REGEXP '^[0-9]{5}$'"), # CheckConstraint con REGEXP no aplica en SQLite
|
||||
# sa.CheckConstraint("pac_codigo_postal REGEXP '^[0-9]{5}$'"), # CheckConstraint con REGEXP no aplica en SQLite; la regla de 5 dígitos se valida en la capa de importación
|
||||
),
|
||||
description="Código postal de 5 dígitos",
|
||||
)
|
||||
@@ -42,7 +44,7 @@ class Paciente(CaMaModel, table=True):
|
||||
pac_parentesco: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="Parentesco", # descripción original decía Departamento — corregida
|
||||
description="Parentesco",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Catálogos de la plata (F1)
|
||||
|
||||
Un TOML por proyecto: estudio → resultado → valor (`../../../_docs/esquema_generico_catalogos.md` §3 y §5).
|
||||
La arista `catalogos` de Orquestacion los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
|
||||
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
|
||||
|
||||
```toml
|
||||
[<estudio>]
|
||||
etiqueta = "..."
|
||||
codigos_hospital = ["..."] # cómo lo nombra el hospital (tipo de estudio de la orden, instrumento)
|
||||
|
||||
[<estudio>.resultados.<resultado>] # resultado_id = "<estudio>.<resultado>"
|
||||
etiqueta = "..."
|
||||
tipo_valor = "codigo" # codigo, booleano, numero, fecha, texto, externo
|
||||
unidad = "min" # opcional (numero)
|
||||
sistema = "CIE-10" # solo externo
|
||||
valores = [ # solo codigo; el orden de la lista es el de presentación
|
||||
{ valor = "NORMAL", etiqueta = "Normal" },
|
||||
]
|
||||
```
|
||||
|
||||
Los valores son los que llegan del hospital (los enums de Core). Las etiquetas y los colores de las figuras
|
||||
siguen en `parametros.toml` del kit hasta F3; `indicadores_kit/tests/test_catalogos.py` exige que coincidan.
|
||||
@@ -0,0 +1,145 @@
|
||||
# Catálogo de CaCu (F1). Valores: los enums de Core (`core/cacu/*/enums.py`) y lo que guarda la carga.
|
||||
|
||||
[citologia]
|
||||
etiqueta = "Citología cervical"
|
||||
codigos_hospital = ["SOLICITUD_PAPANICOLAO_BASE_LIQUIDA", "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA"]
|
||||
|
||||
[citologia.resultados.calidad_muestra]
|
||||
etiqueta = "Calidad de la muestra"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "SATISFACTORIO", etiqueta = "Satisfactoria" },
|
||||
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
|
||||
]
|
||||
|
||||
[citologia.resultados.bethesda]
|
||||
etiqueta = "Células escamosas (Bethesda)"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NORMAL", etiqueta = "Normal" },
|
||||
{ valor = "ASC-US", etiqueta = "ASC-US" },
|
||||
{ valor = "LIEBG", etiqueta = "LIEBG" },
|
||||
{ valor = "ASC-H", etiqueta = "ASC-H" },
|
||||
{ valor = "LIEAG", etiqueta = "LIEAG" },
|
||||
{ valor = "CIS", etiqueta = "Carcinoma in situ" },
|
||||
]
|
||||
|
||||
[citologia.resultados.celulas_glandulares]
|
||||
etiqueta = "Células glandulares"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[citologia.resultados.carcinoma_invasor]
|
||||
etiqueta = "Carcinoma invasor"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[citologia.resultados.dx_lesion]
|
||||
etiqueta = "Diagnóstico de la lesión"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[vph]
|
||||
etiqueta = "Prueba de VPH"
|
||||
|
||||
[vph.resultados.resultado]
|
||||
etiqueta = "VPH de alto riesgo"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NEGATIVO", etiqueta = "Negativo" },
|
||||
{ valor = "POSITIVO", etiqueta = "Positivo" },
|
||||
{ valor = "INDETERMINADO", etiqueta = "Indeterminado" },
|
||||
]
|
||||
|
||||
[vph.resultados.genotipo_16_18]
|
||||
etiqueta = "Genotipo 16 o 18"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[vph.resultados.genotipo_16]
|
||||
etiqueta = "Genotipo 16"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[vph.resultados.genotipo_18]
|
||||
etiqueta = "Genotipo 18"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[biopsia]
|
||||
etiqueta = "Biopsia cervical"
|
||||
codigos_hospital = ["BIOPSIA_CHICA"]
|
||||
|
||||
[biopsia.resultados.grado]
|
||||
etiqueta = "Grado histológico"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NORMAL", etiqueta = "Normal" },
|
||||
{ valor = "LIEBG", etiqueta = "LIEBG (CIN 1)" },
|
||||
{ valor = "LIEAG", etiqueta = "LIEAG (CIN 2 y 3)" },
|
||||
{ valor = "CIS", etiqueta = "Carcinoma in situ" },
|
||||
{ valor = "CARCINOMA", etiqueta = "Carcinoma invasor" },
|
||||
{ valor = "DESCONOCIDO", etiqueta = "Desconocido" },
|
||||
]
|
||||
|
||||
[biopsia.resultados.fecha_solicitud]
|
||||
etiqueta = "Fecha de solicitud"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
|
||||
[nota_medica.resultados.diagnostico]
|
||||
etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
# El motivo de consulta, tal como lo escribe el hospital (p. ej. «ACUDE A COLPOSCOPIA»). La plata no lo
|
||||
# normaliza (I-K61): quien lo compare (el estatus de seguimiento, T-24c) lo normaliza con sus reglas.
|
||||
[nota_medica.resultados.motivo]
|
||||
etiqueta = "Motivo de consulta"
|
||||
tipo_valor = "texto"
|
||||
|
||||
# El diagnóstico en texto, tal como lo escribe el hospital: la nota de colposcopia puede traer
|
||||
# el CIE-10 como «S/C» y el diagnóstico solo aquí (p. ej. «VIRUS DEL PAPILOMA HUMANO»; usuario,
|
||||
# 2026-10-22). Sin normalizar, como el motivo.
|
||||
[nota_medica.resultados.diagnostico_texto]
|
||||
etiqueta = "Diagnóstico (texto)"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[nota_medica.resultados.especialidad]
|
||||
etiqueta = "Especialidad que la escribe"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
|
||||
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
|
||||
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
|
||||
]
|
||||
|
||||
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
|
||||
# `codigos_hospital`). ADR-MD-007.
|
||||
[orden]
|
||||
etiqueta = "Orden de estudio"
|
||||
|
||||
[orden.resultados.intencion]
|
||||
etiqueta = "Intención (FHIR intent)"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.fecha_solicitud]
|
||||
etiqueta = "Fecha para la que se pidió"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[orden.resultados.fecha_resultado]
|
||||
etiqueta = "Fecha del resultado"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[orden.resultados.estatus]
|
||||
etiqueta = "Estatus de la orden"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.diagnostico]
|
||||
etiqueta = "Diagnóstico con que se pidió"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.especialidad]
|
||||
etiqueta = "Especialidad que la pidió"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
|
||||
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
|
||||
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
|
||||
]
|
||||
@@ -0,0 +1,100 @@
|
||||
# Catálogo de CaMa (F1). Valores: los enums de Core (`core/cama/*/enums.py`) y lo que guarda la carga.
|
||||
# BI-RADS: el hospital reporta 4A, 4B y 4C, normalizados (usuario, 2026-10-16); un 4 sin subcategoría
|
||||
# también puede llegar (`cama.birads_gravedad` en parametros.toml).
|
||||
|
||||
[mastografia]
|
||||
etiqueta = "Mastografía"
|
||||
codigos_hospital = ["MASTOGRAFIA"]
|
||||
|
||||
[mastografia.resultados.calidad_imagen]
|
||||
etiqueta = "Calidad de la imagen"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "SATISFACTORIO", etiqueta = "Satisfactoria" },
|
||||
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
|
||||
]
|
||||
|
||||
[mastografia.resultados.birads]
|
||||
etiqueta = "BI-RADS"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "B0", etiqueta = "BI-RADS 0" },
|
||||
{ valor = "B1", etiqueta = "BI-RADS 1" },
|
||||
{ valor = "B2", etiqueta = "BI-RADS 2" },
|
||||
{ valor = "B3", etiqueta = "BI-RADS 3" },
|
||||
{ valor = "B4", etiqueta = "BI-RADS 4 (sin subcategoría)" },
|
||||
{ valor = "B4A", etiqueta = "BI-RADS 4A" },
|
||||
{ valor = "B4B", etiqueta = "BI-RADS 4B" },
|
||||
{ valor = "B4C", etiqueta = "BI-RADS 4C" },
|
||||
{ valor = "B5", etiqueta = "BI-RADS 5" },
|
||||
{ valor = "B6", etiqueta = "BI-RADS 6" },
|
||||
]
|
||||
|
||||
[biopsia]
|
||||
etiqueta = "Biopsia de mama"
|
||||
codigos_hospital = ["BIOPSIA_CHICA"]
|
||||
|
||||
[biopsia.resultados.grado]
|
||||
etiqueta = "Grado histológico"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "BENIGNO", etiqueta = "Benigno" },
|
||||
{ valor = "CARCINOMA_IN_SITU", etiqueta = "Carcinoma in situ" },
|
||||
{ valor = "CARCINOMA_INVASOR", etiqueta = "Carcinoma invasor" },
|
||||
{ valor = "DESCONOCIDO", etiqueta = "Desconocido" },
|
||||
]
|
||||
|
||||
[biopsia.resultados.fecha_solicitud]
|
||||
etiqueta = "Fecha de solicitud"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
|
||||
[nota_medica.resultados.diagnostico]
|
||||
etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
[nota_medica.resultados.especialidad]
|
||||
etiqueta = "Especialidad que la escribe"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
|
||||
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
|
||||
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
|
||||
]
|
||||
|
||||
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
|
||||
# `codigos_hospital`). ADR-MD-007.
|
||||
[orden]
|
||||
etiqueta = "Orden de estudio"
|
||||
|
||||
[orden.resultados.intencion]
|
||||
etiqueta = "Intención (FHIR intent)"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.fecha_solicitud]
|
||||
etiqueta = "Fecha para la que se pidió"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[orden.resultados.fecha_resultado]
|
||||
etiqueta = "Fecha del resultado"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[orden.resultados.estatus]
|
||||
etiqueta = "Estatus de la orden"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.diagnostico]
|
||||
etiqueta = "Diagnóstico con que se pidió"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.especialidad]
|
||||
etiqueta = "Especialidad que la pidió"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
|
||||
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
|
||||
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
|
||||
]
|
||||
@@ -0,0 +1,267 @@
|
||||
# Catálogo de TEA (F1). Valores: los enums de Core (`core/tea/enums.py`) y lo que guarda la carga.
|
||||
# Los instrumentos aplicados (M-CHAT-R/F, Ramos) son un estudio cada uno: una aplicación por informante y área.
|
||||
|
||||
[evaluacion_psicologica]
|
||||
etiqueta = "Evaluación psicológica"
|
||||
codigos_hospital = ["EVALUACION_PSICOLOGICA_TEA"]
|
||||
|
||||
[evaluacion_psicologica.resultados.instrumento_tamizaje]
|
||||
etiqueta = "Instrumento de tamizaje"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "M_CHAT_R", etiqueta = "M-CHAT-R" },
|
||||
{ valor = "M_CHAT_RF", etiqueta = "M-CHAT-R/F" },
|
||||
{ valor = "OTRO", etiqueta = "Otro" },
|
||||
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
|
||||
]
|
||||
|
||||
[evaluacion_psicologica.resultados.edad_meses]
|
||||
etiqueta = "Edad del niño"
|
||||
tipo_valor = "numero"
|
||||
unidad = "meses"
|
||||
|
||||
[evaluacion_psicologica.resultados.fecha_evaluacion]
|
||||
etiqueta = "Fecha de la evaluación"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[evaluacion_psicologica.resultados.fecha_entrevista_inicial]
|
||||
etiqueta = "Fecha de la entrevista inicial"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[ados2]
|
||||
etiqueta = "ADOS-2"
|
||||
|
||||
[ados2.resultados.css]
|
||||
etiqueta = "Puntaje de severidad (CSS)"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[mchat]
|
||||
etiqueta = "M-CHAT-R/F aplicado"
|
||||
codigos_hospital = ["M_CHAT_R_F"]
|
||||
|
||||
[mchat.resultados.informante]
|
||||
etiqueta = "Informante"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MADRE", etiqueta = "Madre" },
|
||||
{ valor = "PADRE", etiqueta = "Padre" },
|
||||
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
|
||||
{ valor = "MAESTRO", etiqueta = "Maestro" },
|
||||
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
|
||||
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
|
||||
]
|
||||
|
||||
[mchat.resultados.area]
|
||||
etiqueta = "Área"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "TOTAL", etiqueta = "Total" },
|
||||
]
|
||||
|
||||
[mchat.resultados.interpretacion]
|
||||
etiqueta = "Interpretación"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "RIESGO_BAJO", etiqueta = "Riesgo bajo" },
|
||||
{ valor = "RIESGO_MEDIO", etiqueta = "Riesgo medio" },
|
||||
{ valor = "RIESGO_ALTO", etiqueta = "Riesgo alto" },
|
||||
]
|
||||
|
||||
[ramos]
|
||||
etiqueta = "Escala de Ramos aplicada"
|
||||
codigos_hospital = ["RAMOS"]
|
||||
|
||||
[ramos.resultados.informante]
|
||||
etiqueta = "Informante"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MADRE", etiqueta = "Madre" },
|
||||
{ valor = "PADRE", etiqueta = "Padre" },
|
||||
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
|
||||
{ valor = "MAESTRO", etiqueta = "Maestro" },
|
||||
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
|
||||
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
|
||||
]
|
||||
|
||||
[ramos.resultados.area]
|
||||
etiqueta = "Área"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "ADAPTATIVO", etiqueta = "Adaptativo" },
|
||||
{ valor = "COGNOSCITIVO", etiqueta = "Cognoscitivo" },
|
||||
{ valor = "FISICO", etiqueta = "Físico" },
|
||||
{ valor = "LINGUISTICO", etiqueta = "Lingüístico" },
|
||||
{ valor = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" },
|
||||
{ valor = "TOTAL", etiqueta = "Total" },
|
||||
]
|
||||
|
||||
[ramos.resultados.interpretacion]
|
||||
etiqueta = "Interpretación"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado" },
|
||||
{ valor = "MONITOREO", etiqueta = "Monitoreo" },
|
||||
{ valor = "RETRASO", etiqueta = "Retraso" },
|
||||
]
|
||||
|
||||
[eeg]
|
||||
etiqueta = "Electroencefalograma"
|
||||
codigos_hospital = ["ELECTROENCEFALOGRAMA"]
|
||||
|
||||
[eeg.resultados.duracion_min]
|
||||
etiqueta = "Duración"
|
||||
tipo_valor = "numero"
|
||||
unidad = "min"
|
||||
|
||||
[eeg.resultados.utilizable]
|
||||
etiqueta = "Utilizable"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.fecha_nacimiento_archivo]
|
||||
etiqueta = "Fecha de nacimiento en el archivo del equipo"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
# Un segmento es una parte del EEG (procedimiento con clase `parte`).
|
||||
[eeg.resultados.estado_segmento]
|
||||
etiqueta = "Estado del segmento"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NO_MARCADO", etiqueta = "No marcado" },
|
||||
{ valor = "OJOS_CERRADOS", etiqueta = "Ojos cerrados" },
|
||||
{ valor = "FOTOESTIMULACION", etiqueta = "Fotoestimulación" },
|
||||
{ valor = "SUENO", etiqueta = "Sueño" },
|
||||
]
|
||||
|
||||
[eeg.resultados.duracion_segmento]
|
||||
etiqueta = "Duración del segmento"
|
||||
tipo_valor = "numero"
|
||||
unidad = "s"
|
||||
|
||||
[pea]
|
||||
etiqueta = "Potenciales evocados auditivos"
|
||||
codigos_hospital = ["POTENCIALES_EVOCADOS_AUDITIVOS", "POTENCIALES_EVOCADOS"] # el segundo, como llega (responsable de TEA, 2026-10-21)
|
||||
|
||||
[pea.resultados.grado_hipoacusia]
|
||||
etiqueta = "Grado de hipoacusia"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NORMAL", etiqueta = "Normal" },
|
||||
{ valor = "LEVE", etiqueta = "Leve" },
|
||||
{ valor = "MODERADA", etiqueta = "Moderada" },
|
||||
{ valor = "SEVERA", etiqueta = "Severa" },
|
||||
{ valor = "PROFUNDA", etiqueta = "Profunda" },
|
||||
{ valor = "NO_CONCLUYENTE", etiqueta = "No concluyente" },
|
||||
]
|
||||
|
||||
[parto]
|
||||
etiqueta = "Parto"
|
||||
|
||||
[parto.resultados.apgar_5min]
|
||||
etiqueta = "APGAR a los 5 minutos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[parto.resultados.ingreso_ucin]
|
||||
etiqueta = "Ingreso a UCIN"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal]
|
||||
etiqueta = "Antecedentes maternos de la gestación"
|
||||
|
||||
[historia_perinatal.resultados.antecedente_aborto]
|
||||
etiqueta = "Antecedente de aborto"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.asma]
|
||||
etiqueta = "Asma"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.crisis_convulsivas]
|
||||
etiqueta = "Crisis convulsivas"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.diabetes_gestacional]
|
||||
etiqueta = "Diabetes gestacional"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.embarazo_multiple]
|
||||
etiqueta = "Embarazo múltiple"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.enfermedad_autoinmune]
|
||||
etiqueta = "Enfermedad autoinmune"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.estres_agudo]
|
||||
etiqueta = "Estrés agudo"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.farmaco_riesgo_neurodesarrollo]
|
||||
etiqueta = "Fármaco de riesgo para el neurodesarrollo"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.hipertension_preeclampsia]
|
||||
etiqueta = "Hipertensión o preeclampsia"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.hipertiroidismo]
|
||||
etiqueta = "Hipertiroidismo"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.hipotiroidismo]
|
||||
etiqueta = "Hipotiroidismo"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.hipoxia_materna]
|
||||
etiqueta = "Hipoxia materna"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.incompatibilidad_rh]
|
||||
etiqueta = "Incompatibilidad Rh"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.infeccion_gestacion]
|
||||
etiqueta = "Infección en la gestación"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.liquido_amniotico]
|
||||
etiqueta = "Alteración del líquido amniótico"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.migrana]
|
||||
etiqueta = "Migraña"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.proceso_proinflamatorio]
|
||||
etiqueta = "Proceso proinflamatorio"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.tabaquismo_gestacion]
|
||||
etiqueta = "Tabaquismo en la gestación"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[historia_perinatal.resultados.trastorno_neurologico]
|
||||
etiqueta = "Trastorno neurológico"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
|
||||
[nota_medica.resultados.diagnostico]
|
||||
etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
|
||||
# `codigos_hospital`). ADR-MD-007.
|
||||
[orden]
|
||||
etiqueta = "Orden de estudio"
|
||||
|
||||
[orden.resultados.intencion]
|
||||
etiqueta = "Intención (FHIR intent)"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.fecha_realizacion]
|
||||
etiqueta = "Fecha de realización"
|
||||
tipo_valor = "fecha"
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Column types and sizes shared across domains, so the storage schema and
|
||||
the import validation in WebApi use the same limits."""
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
# Hospital patient identifiers are indexed in CaCu/CaMa, and MySQL can't
|
||||
# index an unbounded TEXT column (error 1170), so they are a bounded VARCHAR.
|
||||
HOSPITAL_ID_LENGTH = 64
|
||||
|
||||
# Stored files (PDF reports, DICOM, EDF). Plain LargeBinary is a 64 KB BLOB
|
||||
# on MySQL/MariaDB; LONGBLOB holds up to 4 GB.
|
||||
FileBlob = sa.LargeBinary().with_variant(mysql.LONGBLOB(), "mysql", "mariadb")
|
||||
@@ -0,0 +1,14 @@
|
||||
import sqlalchemy.orm as orm
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
registry = orm.registry()
|
||||
|
||||
|
||||
class GovernanceModel(SQLModel, registry=registry):
|
||||
"""Base class for the governance domain: cohort and model versioning,
|
||||
training artifacts and persisted predictions (EL, ML and MLD requirements).
|
||||
|
||||
Governance is its own database. Rows refer to CaCu/CaMa/TEA patients and
|
||||
episodes by natural key (`pac_id_hospital`, `episodio_id`) because foreign
|
||||
keys can't cross databases.
|
||||
"""
|
||||
@@ -0,0 +1,44 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from sqlmodel import Field
|
||||
from core.governance.base import GovernanceModel
|
||||
|
||||
|
||||
class CohortExclusion(GovernanceModel, table=True):
|
||||
"""EL-05: one row per excluded episode, with the criterion and reason code.
|
||||
|
||||
EL-04a: rows are only written when building the training cohort
|
||||
(`models.cohort.CohortBuilder.build`). The production applicability check
|
||||
(EL-04b, `models.cohort.evaluate_applicability`) does not write here.
|
||||
"""
|
||||
|
||||
cohort_exclusion_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
cohort_version_id: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, sa.ForeignKey("cohortversion.cohort_version_id"), nullable=False, index=True),
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
|
||||
)
|
||||
episodio_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
)
|
||||
criterion_code: str = Field(
|
||||
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
|
||||
description="código del criterio de exclusión evaluado (p.ej. EDAD_FUERA_DE_RANGO)",
|
||||
)
|
||||
reason_code: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="EL-05: código de razón específico de por qué este criterio excluyó al episodio",
|
||||
)
|
||||
excluded_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.governance.base import GovernanceModel
|
||||
|
||||
|
||||
class CohortExclusionCount(GovernanceModel, table=True):
|
||||
"""EL-07: per-criterion exclusion count for a cohort version (TRIPOD+AI 20a).
|
||||
|
||||
Written once by the same `build()` that writes `CohortExclusion`, so the
|
||||
count is materialized with the cohort instead of derived on demand.
|
||||
"""
|
||||
|
||||
cohort_exclusion_count_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
cohort_version_id: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, sa.ForeignKey("cohortversion.cohort_version_id"), nullable=False, index=True),
|
||||
)
|
||||
criterion_code: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
)
|
||||
reason_code: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
)
|
||||
count: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, nullable=False),
|
||||
)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,45 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from sqlmodel import Field
|
||||
from core.governance.base import GovernanceModel
|
||||
|
||||
|
||||
class CohortMember(GovernanceModel, table=True):
|
||||
"""A frozen row of a cohort table.
|
||||
|
||||
`feature_snapshot` holds the predictors as JSON at build time, so a trained
|
||||
model stays reproducible even if `episodioclinico` changes later.
|
||||
"""
|
||||
|
||||
cohort_member_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
cohort_version_id: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, sa.ForeignKey("cohortversion.cohort_version_id"), nullable=False, index=True),
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
|
||||
)
|
||||
episodio_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
description="join logico hacia <domain>.episodioclinico.episodio_id",
|
||||
)
|
||||
feature_snapshot: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="JSON serializado de los predictores congelados al momento de construir la cohorte",
|
||||
)
|
||||
outcome: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="desenlace observado al momento de construir la cohorte, si ya se conocía",
|
||||
)
|
||||
included_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.governance.base import GovernanceModel
|
||||
|
||||
|
||||
class CohortVersion(GovernanceModel, table=True):
|
||||
"""EL-01/EL-02/EL-03: header of a materialized, versioned cohort for one
|
||||
clinical scenario.
|
||||
|
||||
Versions are never updated. A change in eligibility criteria or period
|
||||
produces a new row with a new hash, so a trained model can point to the
|
||||
exact data it was built from (ML-03).
|
||||
"""
|
||||
|
||||
cohort_version_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
domain: str = Field(
|
||||
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
|
||||
description="cacu | cama | tea",
|
||||
)
|
||||
scenario: str = Field(
|
||||
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
|
||||
description="escenario clínico; cada uno tiene su propio modelo y tabla de cohorte",
|
||||
)
|
||||
criteria_version: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="EL-02: etiqueta versionada del criterio de elegibilidad clínica usado para construir esta cohorte",
|
||||
)
|
||||
version_hash: str = Field(
|
||||
sa_column=sa.Column(sa.String(128), nullable=False, unique=True, index=True),
|
||||
description="EL-03: hash (sha256) que identifica esta versión de forma única y determinística (ver models.cohort.CohortBuilder)",
|
||||
)
|
||||
source_table: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="EL-01: tabla de episodios clínicos de origen (p.ej. cacu.episodioclinico)",
|
||||
)
|
||||
description: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
)
|
||||
n_source: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, nullable=False),
|
||||
description="conteo de episodios evaluados antes de aplicar exclusión",
|
||||
)
|
||||
n_included: int = Field(
|
||||
sa_column=sa.Column(sa.Integer, nullable=False),
|
||||
description="conteo final incluido en la cohorte (20a)",
|
||||
)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Environment(str, Enum):
|
||||
"""ML-02: development versions are tagged separately from production."""
|
||||
|
||||
DEV = "DEV"
|
||||
PROD = "PROD"
|
||||
|
||||
|
||||
class ArtifactKind(str, Enum):
|
||||
"""ML-01a: kinds of artifacts saved from the routines around training,
|
||||
in addition to the final model."""
|
||||
|
||||
MUESTREO = "MUESTREO"
|
||||
DATOS_FALTANTES = "DATOS_FALTANTES"
|
||||
METODO_ANALITICO = "METODO_ANALITICO"
|
||||
BALANCE_CLASES = "BALANCE_CLASES"
|
||||
CONFIANZA_SALIDA = "CONFIANZA_SALIDA"
|
||||
ONNX_CHECKPOINT = "ONNX_CHECKPOINT"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class EstatusExtraccion(str, Enum):
|
||||
"""VAR-07/VAR-09: status of an extraction run."""
|
||||
|
||||
EN_PROGRESO = "EN_PROGRESO"
|
||||
COMPLETADA = "COMPLETADA"
|
||||
FALLIDA = "FALLIDA"
|
||||
@@ -0,0 +1,70 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
from core.governance.base import GovernanceModel
|
||||
|
||||
|
||||
class ExtractionRun(GovernanceModel, table=True):
|
||||
"""VAR-07/VAR-08/VAR-09: log of each extraction run (OCR or other).
|
||||
|
||||
Records the data source and date range (VAR-08), the transformation and
|
||||
quality check applied (VAR-07), and serves as an idempotency log (VAR-09):
|
||||
callers check for a `COMPLETADA` run on the same `(domain, entity,
|
||||
entity_pk)` before extracting again. The extracted value itself lives in
|
||||
the source row's `*_ocr_*` columns.
|
||||
"""
|
||||
|
||||
extraction_run_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
domain: str = Field(
|
||||
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
|
||||
description="cacu | cama | tea",
|
||||
)
|
||||
entity: str = Field(
|
||||
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
|
||||
description="nombre de la tabla/entidad de Core sobre la que corrió la extracción",
|
||||
)
|
||||
entity_pk: str = Field(
|
||||
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
|
||||
description="valor de la llave primaria de la fila extraída, como texto",
|
||||
)
|
||||
column_extracted: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="columna destino que esta corrida pobló (p.ej. cit_vph_resultado)",
|
||||
)
|
||||
source_description: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="VAR-08: fuente de los datos crudos",
|
||||
)
|
||||
source_started_at: Optional[datetime] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.DateTime),
|
||||
description="VAR-08: inicio del periodo que cubren los datos crudos cargados",
|
||||
)
|
||||
source_ended_at: Optional[datetime] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.DateTime),
|
||||
)
|
||||
transform_description: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="VAR-07: descripción de la transformación de datos crudos aplicada",
|
||||
)
|
||||
quality_validation: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="VAR-07: resultado de la validación de calidad de los datos, texto libre o JSON serializado",
|
||||
)
|
||||
estatus: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="valor de core.governance.enums.EstatusExtraccion guardado como texto",
|
||||
)
|
||||
executed_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from sqlmodel import Field
|
||||
from core.governance.base import GovernanceModel
|
||||
|
||||
|
||||
class ModelPrediction(GovernanceModel, table=True):
|
||||
"""MLD-4/MLD-5: a persisted prediction, linked to the MLflow model
|
||||
version that produced it.
|
||||
|
||||
Model training, versioning and promotion live in MLflow, not here
|
||||
(`models.registry`); this row only carries the keys to find that version
|
||||
again (`mlflow_run_id`, `modelo_nombre`, `modelo_version`), the same
|
||||
reference-only pattern `core.indicadores.cohortes.EvaluacionRiesgoLoteBase`
|
||||
already uses for its own risk evaluations.
|
||||
|
||||
`interpretability` stores the MLD-03 fields (OR, HR, cumulative
|
||||
probability) with the estimate. `applicability_passed` is False when the
|
||||
input failed the EL-04b applicability check; the prediction is kept for
|
||||
traceability but should not be used clinically.
|
||||
"""
|
||||
|
||||
model_prediction_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
mlflow_run_id: str = Field(
|
||||
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
|
||||
description="la corrida de MLflow que entrenó el modelo",
|
||||
)
|
||||
modelo_nombre: str = Field(
|
||||
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
|
||||
description="nombre del modelo registrado en MLflow",
|
||||
)
|
||||
modelo_version: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="versión del modelo registrado en MLflow",
|
||||
)
|
||||
domain: str = Field(
|
||||
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
|
||||
)
|
||||
pac_id_hospital: str = Field(
|
||||
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
|
||||
)
|
||||
episodio_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, index=True),
|
||||
)
|
||||
input_hash: str = Field(
|
||||
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
|
||||
description="sha256 del vector de entrada, para detectar predicciones duplicadas",
|
||||
)
|
||||
output: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
description="JSON serializado: salida cruda del modelo",
|
||||
)
|
||||
prediccion: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description="etiqueta/puntaje principal, en texto, para filtrar sin deserializar `output`",
|
||||
)
|
||||
confianza: Optional[float] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Float),
|
||||
description="0..1, nivel de confianza casuístico de esta estimación (MLD-01)",
|
||||
)
|
||||
interpretability: Optional[str] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Text),
|
||||
description='JSON serializado (MLD-03): {"odds_ratio":, "hazard_ratio":, "probabilidad_acumulada":}',
|
||||
)
|
||||
applicability_passed: bool = Field(
|
||||
sa_column=sa.Column(sa.Boolean, nullable=False),
|
||||
description="EL-04b: resultado de evaluar los criterios de aplicabilidad de producción contra esta fila",
|
||||
)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc),
|
||||
sa_column=sa.Column(sa.DateTime, nullable=False),
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
from core.governance.extraction_run.model import ExtractionRun
|
||||
from core.governance.cohort_version.model import CohortVersion
|
||||
from core.governance.cohort_member.model import CohortMember
|
||||
from core.governance.cohort_exclusion.model import CohortExclusion
|
||||
from core.governance.cohort_exclusion_count.model import CohortExclusionCount
|
||||
from core.governance.model_prediction.model import ModelPrediction
|
||||
|
||||
__all__ = [
|
||||
"ExtractionRun",
|
||||
"CohortVersion",
|
||||
"CohortMember",
|
||||
"CohortExclusion",
|
||||
"CohortExclusionCount",
|
||||
"ModelPrediction",
|
||||
]
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Los catálogos de la plata: estudio -> resultado -> valor (F1, `_docs/esquema_generico_catalogos.md` §3 y §5).
|
||||
|
||||
Son el diccionario de datos de cada proyecto: qué estudios hay, qué resultados
|
||||
da cada uno y qué valores admite un resultado codificado. Se escriben en
|
||||
`core/catalogos/<proyecto>.toml` y la arista `catalogos` los materializa en
|
||||
estas tablas, antes de cargar. En F5 las observaciones apuntan a ellos con llave
|
||||
foránea; hoy solo se materializan y se prueban contra los enums de Core y los
|
||||
catálogos de `parametros.toml` del kit.
|
||||
|
||||
Un valor no se borra nunca: si sale del TOML, pasa a `retirado` (lo pueden
|
||||
seguir usando hechos ya cargados).
|
||||
"""
|
||||
|
||||
from sqlalchemy import CheckConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
# Cómo se guarda el valor de un resultado (en F5, la columna de `observacion` que lo lleva).
|
||||
TIPOS_DE_VALOR = (
|
||||
"codigo", # un `valor_id` de `cat_valor`
|
||||
"booleano", # 0 o 1
|
||||
"numero", # con `unidad` si la tiene
|
||||
"fecha",
|
||||
"texto", # texto libre, sin catálogo
|
||||
"externo", # un código de otro sistema (`sistema`, p. ej. CIE-10), sin catálogo propio
|
||||
)
|
||||
ESTADOS_DE_VALOR = ("vigente", "retirado")
|
||||
|
||||
|
||||
class CatEstudioBase(SQLModel):
|
||||
"""Un estudio o acto clínico: citología, mastografía, EEG, una nota médica (FHIR `ActivityDefinition`)."""
|
||||
|
||||
estudio_id: str = Field(primary_key=True, max_length=64) # "citologia", "mastografia", "eeg"
|
||||
etiqueta: str
|
||||
|
||||
|
||||
class CatResultadoBase(SQLModel):
|
||||
"""Un resultado que da un estudio (FHIR `ObservationDefinition`): qué se mide y cómo se guarda."""
|
||||
|
||||
resultado_id: str = Field(primary_key=True, max_length=128) # "<estudio>.<resultado>": "citologia.bethesda"
|
||||
estudio_id: str = Field(foreign_key="cat_estudio.estudio_id", index=True, max_length=64)
|
||||
etiqueta: str
|
||||
tipo_valor: str # uno de TIPOS_DE_VALOR
|
||||
unidad: str | None = None # "min", "s", "meses", "puntos"
|
||||
sistema: str | None = None # el del código, si es externo: "CIE-10"
|
||||
|
||||
|
||||
class CatValorBase(SQLModel):
|
||||
"""Un valor admitido de un resultado codificado (FHIR `ValueSet`, una entrada)."""
|
||||
|
||||
resultado_id: str = Field(foreign_key="cat_resultado.resultado_id", primary_key=True, max_length=128)
|
||||
valor_id: str = Field(primary_key=True, max_length=64) # "LIEAG", "B4A": tal como llega del hospital
|
||||
etiqueta: str
|
||||
orden: int # de presentación, de menos a más grave donde aplica
|
||||
estado: str = "vigente" # vigente o retirado
|
||||
|
||||
|
||||
def tipo_de_valor_conocido() -> CheckConstraint:
|
||||
"""`cat_resultado.tipo_valor` es uno de `TIPOS_DE_VALOR`."""
|
||||
return CheckConstraint(
|
||||
"tipo_valor IN (" + ", ".join(f"'{t}'" for t in TIPOS_DE_VALOR) + ")", name="ck_cat_resultado_tipo_valor"
|
||||
)
|
||||
|
||||
|
||||
def estado_de_valor_conocido() -> CheckConstraint:
|
||||
"""`cat_valor.estado` es uno de `ESTADOS_DE_VALOR`."""
|
||||
return CheckConstraint(
|
||||
"estado IN (" + ", ".join(f"'{e}'" for e in ESTADOS_DE_VALOR) + ")", name="ck_cat_valor_estado"
|
||||
)
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Las columnas de las cohortes para modelos y de sus estimaciones de riesgo, sin tabla.
|
||||
|
||||
Oro restringido: identifican pacientes y no salen de la máquina segura. Adoptan
|
||||
el diseño del kit de campo (`indicadores_kit_0/campo/cohortes/tablas.py` y
|
||||
`campo/riesgos/columnas.py`) con tres cambios (ADR-MD-003):
|
||||
|
||||
- un armado tiene su llave (`armado_id`) y guarda su `marco_sha` (I-K90 de campo);
|
||||
- las variables de cada miembro van en formato largo (`cohorte_variable`), sin nulos:
|
||||
sin dato es sin fila. La vista ancha para el modelo se arma desde aquí;
|
||||
- el lote apunta al armado puntuado por su llave, no por cuatro columnas.
|
||||
|
||||
MLflow y estas tablas no comparten filas: se guardan llaves del otro lado
|
||||
(`mlflow_run_id`, `modelo_sha`; y en MLflow, `kit.marco_sha` y `kit.armado_id`).
|
||||
|
||||
cohorte_armado un armado de una definición (FHIR Group enumerado / OMOP COHORT)
|
||||
cohorte_miembro quién entró: paciente, fecha índice y la fila de su hecho índice
|
||||
cohorte_exclusion la atrición, un paso por fila (contrato C5)
|
||||
cohorte_variable el desenlace y los predictores de cada miembro (EvidenceVariable)
|
||||
evaluacion_riesgo_lote una puntuación: qué modelo, sobre qué armado, cuándo
|
||||
evaluacion_riesgo el riesgo de una paciente a un horizonte (FHIR RiskAssessment)
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import CheckConstraint, Text, UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
|
||||
# FHIR `RiskAssessment.status`: los que se usan. Una evaluación solo crece: cambiar de estado es otra versión.
|
||||
ESTADOS_RIESGO = ("preliminary", "final", "entered-in-error")
|
||||
|
||||
|
||||
class CohorteArmadoBase(SQLModel):
|
||||
"""Un armado de una cohorte: qué definición, con qué parámetros y datos, y su huella."""
|
||||
|
||||
armado_id: int | None = Field(default=None, primary_key=True)
|
||||
url: str # la definición: "cacu/cohorte_vigilancia"
|
||||
version: str
|
||||
definicion_sha: str # sha256 del TOML de la definición
|
||||
reglas_sha: str # sha256 de sus reglas clínicas, en JSON canónico
|
||||
parametros: str = Field(sa_type=Text) # JSON: ventana de reclutamiento y corte
|
||||
datos_as_of: date # el corte: hasta qué día llegan los datos
|
||||
huella: str = Field(max_length=128) # definición + reglas + parámetros: dos armados con la misma huella son el mismo pedido
|
||||
marco_sha: str = Field(max_length=128) # el contenido del marco; con la huella, rearmar lo mismo no guarda otro
|
||||
n_miembros: int
|
||||
armado_en: datetime = Field(sa_type=FechaHoraUTC)
|
||||
|
||||
|
||||
class CohorteMiembroBase(SQLModel):
|
||||
"""Quién entró a un armado y desde cuándo cuenta su seguimiento."""
|
||||
|
||||
armado_id: int = Field(foreign_key="cohorte_armado.armado_id", primary_key=True)
|
||||
pac_id: int = Field(foreign_key="persona.pac_id", primary_key=True)
|
||||
fecha_indice: date
|
||||
# El hecho índice (la citología en CaCu): su fila de staging, como en la línea de tiempo.
|
||||
indice_fuente_tabla: str
|
||||
indice_fuente_id: str
|
||||
|
||||
|
||||
class CohorteExclusionBase(SQLModel):
|
||||
"""La atrición de un armado: cuántas quedan después de cada paso (contrato C5)."""
|
||||
|
||||
armado_id: int = Field(foreign_key="cohorte_armado.armado_id", primary_key=True)
|
||||
orden: int = Field(primary_key=True)
|
||||
paso: str # "candidatas", "sin evento_previo"...
|
||||
n: int
|
||||
|
||||
|
||||
class CohorteVariableBase(SQLModel):
|
||||
"""Una variable de un miembro: el desenlace (`c`, `l`, `r`) o un predictor. Sin dato es sin fila."""
|
||||
|
||||
armado_id: int = Field(foreign_key="cohorte_armado.armado_id", primary_key=True)
|
||||
pac_id: int = Field(foreign_key="persona.pac_id", primary_key=True)
|
||||
variable: str = Field(primary_key=True, max_length=128)
|
||||
valor_codigo: str | None = None # una categoría
|
||||
valor_numerico: float | None = None # un número
|
||||
|
||||
|
||||
class EvaluacionRiesgoLoteBase(SQLModel):
|
||||
"""Una puntuación. No copia nada de MLflow: solo las llaves que llevan a la corrida y a su artefacto."""
|
||||
|
||||
lote_id: int | None = Field(default=None, primary_key=True)
|
||||
armado_id: int = Field(foreign_key="cohorte_armado.armado_id") # basis: la cohorte puntuada
|
||||
modelo_nombre: str # el modelo registrado en MLflow
|
||||
modelo_version: str
|
||||
mlflow_run_id: str # method: la corrida que entrenó el modelo
|
||||
modelo_sha: str # guarda: sha256 del artefacto; el run_id no fija su contenido
|
||||
desenlace: str # prediction.outcome: la variable de desenlace de la cohorte
|
||||
evaluado_en: datetime = Field(sa_type=FechaHoraUTC) # occurrence
|
||||
n_evaluaciones: int
|
||||
huella: str = Field(unique=True, max_length=128) # del contenido del lote: puntuar lo mismo no duplica
|
||||
|
||||
|
||||
class EvaluacionRiesgoBase(SQLModel):
|
||||
"""El riesgo de una paciente a un horizonte. Solo crece: cambiar de estado es una versión nueva."""
|
||||
|
||||
evaluacion_id: int | None = Field(default=None, primary_key=True)
|
||||
lote_id: int = Field(foreign_key="evaluacion_riesgo_lote.lote_id", index=True)
|
||||
pac_id: int = Field(foreign_key="persona.pac_id") # subject
|
||||
horizonte_anios: float # prediction.when: años desde la fecha índice; 0 = prevalente
|
||||
probabilidad: float # prediction.probabilityDecimal, de 0 a 1
|
||||
# Incertidumbre, si el modelo la da (solo con un Hessiano definido positivo). Nula si no.
|
||||
ic_bajo: float | None = None
|
||||
ic_alto: float | None = None
|
||||
version: int # 1, 2... por (lote, paciente, horizonte)
|
||||
estado: str # preliminary, final o entered-in-error
|
||||
motivo: str | None = None # por qué cambió de estado; nulo en la versión 1
|
||||
registrado_en: datetime = Field(sa_type=FechaHoraUTC)
|
||||
|
||||
|
||||
def armado_unico() -> UniqueConstraint:
|
||||
"""Rearmar lo mismo (misma huella y mismo contenido) no agrega otro armado."""
|
||||
return UniqueConstraint("huella", "marco_sha")
|
||||
|
||||
|
||||
def variable_con_un_valor() -> CheckConstraint:
|
||||
"""Cada fila de `cohorte_variable` trae exactamente un valor. Sin comparar
|
||||
booleanos (`IS NULL <> IS NULL`): SQL Server no los admite."""
|
||||
return CheckConstraint("(valor_codigo IS NULL AND valor_numerico IS NOT NULL) OR (valor_codigo IS NOT NULL AND valor_numerico IS NULL)", name="ck_cohorte_variable_un_valor")
|
||||
|
||||
|
||||
def evaluacion_unica() -> UniqueConstraint:
|
||||
"""Una sola fila por versión de cada evaluación."""
|
||||
return UniqueConstraint("lote_id", "pac_id", "horizonte_anios", "version")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TablasCohorte:
|
||||
"""Las seis tablas de cohortes y riesgos de un dominio, juntas (como `TablasKit` del kit).
|
||||
|
||||
Las declara cada proyecto (`indicadores_kit.<proyecto>.tablas.COHORTES`); el kit las lee
|
||||
y Persistance las escribe.
|
||||
"""
|
||||
|
||||
CohorteArmado: type[SQLModel]
|
||||
CohorteMiembro: type[SQLModel]
|
||||
CohorteExclusion: type[SQLModel]
|
||||
CohorteVariable: type[SQLModel]
|
||||
EvaluacionRiesgoLote: type[SQLModel]
|
||||
EvaluacionRiesgo: type[SQLModel]
|
||||
|
||||
def todas(self) -> list[type[SQLModel]]:
|
||||
return [self.CohorteArmado, self.CohorteMiembro, self.CohorteExclusion, self.CohorteVariable,
|
||||
self.EvaluacionRiesgoLote, self.EvaluacionRiesgo]
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Las columnas de las tablas comunes de indicadores_kit, sin tabla.
|
||||
|
||||
`persona` y `periodo_observacion` (OMOP `PERSON`, `OBSERVATION_PERIOD`) y
|
||||
`carga` (FHIR `Provenance`, una fila por lote). Cada dominio las
|
||||
instancia en su registro: `core/<dominio>/indicadores/models.py`.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Text
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
|
||||
|
||||
class PersonaBase(SQLModel):
|
||||
"""Las columnas de `persona`, sin tabla: cada dominio la instancia."""
|
||||
|
||||
# Viene del staging: nunca lo genera la base.
|
||||
pac_id: int = Field(primary_key=True, sa_column_kwargs={"autoincrement": False})
|
||||
pac_id_hospital: str = Field(unique=True, max_length=64) # identificador original del hospital
|
||||
fecha_nacimiento: date | None = None # para calcular la edad a una fecha
|
||||
|
||||
|
||||
class PersonaDerechohabienteBase(PersonaBase):
|
||||
"""`persona` con lo que el hospital sabe de la derechohabiente (CaCu y CaMa).
|
||||
|
||||
Es el valor vigente en staging, no el de la fecha de cada estudio. El
|
||||
texto entra como viene, sin espacios alrededor; vacío es nulo.
|
||||
"""
|
||||
|
||||
dependencia: str | None = None # dependencia de adscripción (`pac_dependencia`)
|
||||
parentesco: str | None = None # afiliada o familiar de un afiliado (`pac_parentesco`)
|
||||
codigo_postal: str | None = None # de su domicilio; no se publica, sirve para la zona
|
||||
|
||||
|
||||
class PeriodoObservacionBase(SQLModel):
|
||||
"""Periodo en que una paciente es observable; puede tener varios."""
|
||||
|
||||
periodo_observacion_id: int | None = Field(default=None, primary_key=True)
|
||||
pac_id: int = Field(foreign_key="persona.pac_id") # de quién es el periodo
|
||||
fecha_inicio: date # primer día en que hay datos de la paciente
|
||||
fecha_fin: date # último día en que los hay
|
||||
tipo_periodo: str # de dónde sale el periodo, por ejemplo "extraccion"
|
||||
|
||||
|
||||
class CargaBase(SQLModel):
|
||||
"""Las columnas de `carga`, sin tabla: cada dominio la instancia."""
|
||||
|
||||
carga_id: int | None = Field(default=None, primary_key=True)
|
||||
fuente: str # tabla de staging que se cargó
|
||||
inicio: datetime = Field(sa_type=FechaHoraUTC) # cuándo empezó la carga
|
||||
fin: datetime | None = Field(default=None, sa_type=FechaHoraUTC) # nulo: no terminó
|
||||
filas_nuevas: int = 0 # filas fuente que no existían
|
||||
filas_cambiadas: int = 0 # filas fuente que dieron una versión nueva
|
||||
filas_sin_cambio: int = 0 # filas fuente con el mismo contenido
|
||||
codigo_sha: str | None = None # versión del código que hizo la carga
|
||||
# Lo que la carga dejó fuera a propósito, por motivo, en JSON (`{"eeg sin paciente": 3}`): los descartes del
|
||||
# staging directo y los huérfanos de la plata (T-20c). Nulo si no descartó nada.
|
||||
descartes: str | None = Field(default=None, sa_type=Text)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Portable day-arithmetic SQL helpers for the indicator layer.
|
||||
|
||||
dias_entre(inicio, fin) means fin - inicio; an engine with no @compiles
|
||||
rule gets the non-executable neutral default instead of silently running
|
||||
invalid SQL, so a missing dialect rule fails loudly."""
|
||||
|
||||
from sqlalchemy import Float, Integer, cast, func
|
||||
from sqlalchemy.ext.compiler import compiles
|
||||
from sqlalchemy.sql.expression import FunctionElement
|
||||
|
||||
|
||||
class dias_entre(FunctionElement):
|
||||
"""Whole days from `inicio` to `fin` (`fin - inicio`)."""
|
||||
|
||||
type = Integer()
|
||||
inherit_cache = True
|
||||
|
||||
|
||||
def _clauses(elemento, compilador, opciones):
|
||||
inicio, fin = list(elemento.clauses)
|
||||
return compilador.process(inicio, **opciones), compilador.process(fin, **opciones)
|
||||
|
||||
|
||||
@compiles(dias_entre)
|
||||
def _dias_entre_neutral(elemento, compilador, **opciones):
|
||||
# No rule registered for this dialect: emit a non-executable
|
||||
# placeholder instead of guessing at syntax, so an unsupported engine
|
||||
# fails loudly rather than running the wrong SQL silently.
|
||||
inicio, fin = _clauses(elemento, compilador, opciones)
|
||||
return f"dias_entre({inicio}, {fin})"
|
||||
|
||||
|
||||
@compiles(dias_entre, "sqlite")
|
||||
def _dias_entre_sqlite(elemento, compilador, **opciones):
|
||||
inicio, fin = _clauses(elemento, compilador, opciones)
|
||||
return f"CAST(julianday({fin}) - julianday({inicio}) AS INTEGER)"
|
||||
|
||||
|
||||
@compiles(dias_entre, "postgresql")
|
||||
def _dias_entre_postgresql(elemento, compilador, **opciones):
|
||||
inicio, fin = _clauses(elemento, compilador, opciones)
|
||||
return f"(CAST({fin} AS DATE) - CAST({inicio} AS DATE))"
|
||||
|
||||
|
||||
@compiles(dias_entre, "mysql", "mariadb")
|
||||
def _dias_entre_mysql(elemento, compilador, **opciones):
|
||||
# MySQL's DATEDIFF(a, b) is a - b with no "day" keyword, unlike
|
||||
# SQL Server's DATEDIFF(day, start, end).
|
||||
inicio, fin = _clauses(elemento, compilador, opciones)
|
||||
return f"DATEDIFF({fin}, {inicio})"
|
||||
|
||||
|
||||
@compiles(dias_entre, "mssql")
|
||||
def _dias_entre_mssql(elemento, compilador, **opciones):
|
||||
inicio, fin = _clauses(elemento, compilador, opciones)
|
||||
return f"DATEDIFF(day, {inicio}, {fin})"
|
||||
|
||||
|
||||
class redondear(FunctionElement):
|
||||
"""`ROUND(x, decimales)`; PostgreSQL only rounds NUMERIC, so it casts."""
|
||||
|
||||
type = Float()
|
||||
inherit_cache = True
|
||||
|
||||
|
||||
@compiles(redondear)
|
||||
def _redondear(elemento, compilador, **opciones):
|
||||
x, decimales = list(elemento.clauses)
|
||||
return f"ROUND({compilador.process(x, **opciones)}, {compilador.process(decimales, **opciones)})"
|
||||
|
||||
|
||||
@compiles(redondear, "postgresql")
|
||||
def _redondear_postgresql(elemento, compilador, **opciones):
|
||||
x, decimales = list(elemento.clauses)
|
||||
return (
|
||||
f"CAST(ROUND(CAST({compilador.process(x, **opciones)} AS NUMERIC), "
|
||||
f"{compilador.process(decimales, **opciones)}) AS DOUBLE PRECISION)"
|
||||
)
|
||||
|
||||
|
||||
def edad_meses(nacimiento, fecha, dias_por_mes: float):
|
||||
"""Age in months, to one decimal, as of `fecha`."""
|
||||
return redondear(cast(dias_entre(nacimiento, fecha), Float) / dias_por_mes, 1)
|
||||
|
||||
|
||||
def meses_cumplidos(edad):
|
||||
"""Completed months: truncates an already-rounded age in months."""
|
||||
return func.floor(edad)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""La plata de dos tablas (F5): `procedimiento` y `observacion` (ADR-MD-007, `_docs/esquema_generico_catalogos.md` §3).
|
||||
|
||||
Cada acto clínico con fecha es un `procedimiento`: la orden, el encuentro (una
|
||||
nota, una evaluación, un parto), la toma (una citología, un EEG), el reporte de
|
||||
una toma y una parte de un estudio (un segmento de EEG). `clase` dice cuál y
|
||||
`estudio_id` de qué estudio del catálogo. `padre_id` liga el reporte con su toma,
|
||||
la toma con su orden o con su encuentro, y la parte con su estudio.
|
||||
|
||||
Cada valor de un procedimiento es una `observacion`: un `resultado_id` del
|
||||
catálogo y un solo valor (`valor_id` de `cat_valor`, número, fecha o texto). Un
|
||||
diagnóstico es la observación `<estudio>.diagnostico` de un encuentro (decisión
|
||||
del usuario, 2026-10-19). Los datos de una orden son resultados del estudio
|
||||
`orden`.
|
||||
|
||||
Sin versiones de fila (decisión del usuario, 2026-10-20: queda para una versión
|
||||
futura). Las dos tablas guardan el estado actual: recargar una fila de staging
|
||||
actualiza en su lugar lo que cambió, por su llave lógica
|
||||
`(fuente_tabla, fuente_id, estudio_id, clase)` en `procedimiento` y
|
||||
`(procedimiento_id, resultado_id)` en `observacion`. Por eso `procedimiento_id`
|
||||
es la llave primaria y `padre_id` y `observacion.procedimiento_id` son llaves
|
||||
foráneas reales. `carga_id` dice qué carga escribió o cambió la fila por última
|
||||
vez. Las tablas por tipo siguen versionando mientras existan.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import CheckConstraint, ForeignKeyConstraint, Index, Text, UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
|
||||
CLASES = ("orden", "encuentro", "toma", "reporte", "parte")
|
||||
|
||||
|
||||
class ProcedimientoClinicoBase(SQLModel):
|
||||
"""Un acto clínico con fecha. FHIR `ServiceRequest`, `Encounter`, `Procedure` o `DiagnosticReport`, según `clase`."""
|
||||
|
||||
procedimiento_id: int | None = Field(default=None, primary_key=True)
|
||||
fuente_tabla: str = Field(max_length=64) # tabla de staging de donde vino
|
||||
fuente_id: str = Field(max_length=64) # llave de la fila en esa tabla
|
||||
carga_id: int = Field(foreign_key="carga.carga_id") # la última carga que lo escribió o lo cambió
|
||||
pac_id: int = Field(foreign_key="persona.pac_id")
|
||||
estudio_id: str = Field(foreign_key="cat_estudio.estudio_id", max_length=64)
|
||||
clase: str = Field(max_length=16) # uno de CLASES
|
||||
fecha: date | None = None # la del acto: la orden, el encuentro, la toma, el reporte
|
||||
padre_id: int | None = Field(default=None, foreign_key="procedimiento.procedimiento_id") # la toma de un reporte, la orden de una toma
|
||||
numero_hospital: int | None = None # el número de la orden (clase `orden`)
|
||||
orden_numero: int | None = None # el número de orden que trae una toma, tal como llega
|
||||
codigo_fuente: str | None = None # el código del acto tal como llega
|
||||
id_hospital: str | None = None # el identificador del acto en el hospital, si es texto (la nota: `nm_id_hospital`); provisional (usuario, 2026-10-22)
|
||||
|
||||
|
||||
class ObservacionClinicaBase(SQLModel):
|
||||
"""Un valor de un procedimiento. FHIR `Observation` / OMOP `MEASUREMENT`, `OBSERVATION`, `CONDITION_OCCURRENCE`."""
|
||||
|
||||
observacion_id: int | None = Field(default=None, primary_key=True)
|
||||
procedimiento_id: int = Field(foreign_key="procedimiento.procedimiento_id", index=True)
|
||||
carga_id: int = Field(foreign_key="carga.carga_id") # la última carga que la escribió o la cambió
|
||||
pac_id: int = Field(foreign_key="persona.pac_id")
|
||||
resultado_id: str = Field(max_length=128) # de `cat_resultado`; la llave foránea va en `__table_args__` (compuesta con `valor_id`)
|
||||
valor_id: str | None = Field(default=None, max_length=64) # de `cat_valor`, si el resultado es `codigo` y el valor está en el catálogo
|
||||
valor_numerico: float | None = None # `numero` y `booleano` (0 o 1)
|
||||
valor_fecha: date | None = None # `fecha`
|
||||
valor_texto: str | None = Field(default=None, sa_type=Text) # `texto` y `externo` (el código, p. ej. CIE-10 normalizado)
|
||||
valor_fuente: str | None = Field(default=None, sa_type=Text) # el valor tal como llegó, si es codigo (también fuera de catálogo)
|
||||
|
||||
|
||||
def clase_conocida() -> CheckConstraint:
|
||||
return CheckConstraint("clase IN (" + ", ".join(f"'{c}'" for c in CLASES) + ")", name="ck_procedimiento_clase")
|
||||
|
||||
|
||||
def llave_de_procedimiento() -> UniqueConstraint:
|
||||
"""Un procedimiento por fila de staging, estudio y clase: la llave con que se recarga."""
|
||||
return UniqueConstraint("fuente_tabla", "fuente_id", "estudio_id", "clase", name="uq_procedimiento_llave")
|
||||
|
||||
|
||||
def indice_de_procedimiento() -> Index:
|
||||
"""Para buscar por paciente, estudio y clase en orden de fecha (casi todas las consultas)."""
|
||||
return Index("ix_procedimiento_paciente", "pac_id", "estudio_id", "clase", "fecha")
|
||||
|
||||
|
||||
def llave_de_observacion() -> UniqueConstraint:
|
||||
"""Un valor por resultado en cada procedimiento."""
|
||||
return UniqueConstraint("procedimiento_id", "resultado_id", name="uq_observacion_llave")
|
||||
|
||||
|
||||
def observacion_en_catalogo() -> tuple:
|
||||
"""Llaves foráneas de la observación al catálogo: el resultado, y el par (resultado, valor) si hay valor."""
|
||||
return (
|
||||
ForeignKeyConstraint(["resultado_id"], ["cat_resultado.resultado_id"], name="fk_observacion_resultado"),
|
||||
ForeignKeyConstraint(
|
||||
["resultado_id", "valor_id"], ["cat_valor.resultado_id", "cat_valor.valor_id"], name="fk_observacion_valor"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def indice_de_observacion() -> Index:
|
||||
return Index("ix_observacion_resultado", "resultado_id", "valor_id")
|
||||
@@ -0,0 +1,160 @@
|
||||
"""El oro por unidad y su catálogo (§6f, MD-19): de qué se publica un indicador y con qué unidades.
|
||||
|
||||
El kit no agrega: escribe cada unidad en cada población de un reporte y el
|
||||
estrato de cada unidad, decidido al calcular. El número publicado es una
|
||||
vista (`v_c1`, `v_c2`, `v_c3r`) sobre estas tablas. Viene de
|
||||
`ISSSTELEON-medallon/_docs/prototipo/vistas.py`.
|
||||
|
||||
cat_measure, cat_measure_resultado el indicador, su contrato y sus poblaciones
|
||||
cat_measure_valor las categorías de un C2, en orden
|
||||
cat_measure_grupo los grupos de un indicador (`TOTAL`, las ventanas de TEA)
|
||||
cat_estrato, cat_estrato_valor las dimensiones y sus valores
|
||||
cat_measure_estrato qué estrato admite cada indicador como desglose o filtro
|
||||
measure_report_unidad cada unidad en cada población de un reporte
|
||||
measure_report_unidad_estrato el valor de cada estrato de cada unidad
|
||||
|
||||
Los catálogos se generan de los TOML del kit (el analista no los escribe) y
|
||||
se reemplazan enteros. Las unidades identifican pacientes: no salen de la
|
||||
máquina segura.
|
||||
"""
|
||||
|
||||
from sqlalchemy import CheckConstraint, ForeignKeyConstraint, UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
CONTRATOS = ("C1", "C2", "C3r")
|
||||
UNIDADES = ("paciente", "examen", "episodio")
|
||||
POBLACIONES = (
|
||||
"initial-population", "denominator", "numerator", "denominator-exclusion", "numerator-exclusion", "measure-observation",
|
||||
)
|
||||
ORIGENES_DE_VALOR = ("catalogo", "fuera_de_catalogo")
|
||||
|
||||
|
||||
class CatMeasureBase(SQLModel):
|
||||
"""Un indicador como se publica: su contrato y su unidad. Sale del TOML del measure."""
|
||||
|
||||
measure_id: str = Field(primary_key=True, max_length=64) # "CACU_EU8": el final de su `url`
|
||||
url: str = Field(unique=True, max_length=255)
|
||||
version: str
|
||||
titulo: str
|
||||
contrato: str # uno de CONTRATOS
|
||||
unidad: str # uno de UNIDADES
|
||||
decide: str | None = None # qué procedimiento representa a la unidad (MD-Q8); nulo hasta decidirlo
|
||||
|
||||
|
||||
class CatMeasureResultadoBase(SQLModel):
|
||||
"""Una población de un indicador: `<measure_id>.<poblacion>`."""
|
||||
|
||||
resultado_id: str = Field(primary_key=True, max_length=128) # "CACU_EU8.numerator"
|
||||
measure_id: str = Field(foreign_key="cat_measure.measure_id", index=True, max_length=64)
|
||||
poblacion: str = Field(max_length=32) # una de POBLACIONES
|
||||
etiqueta: str
|
||||
|
||||
|
||||
class CatMeasureValorBase(SQLModel):
|
||||
"""Una categoría de un C2, en el orden en que se presenta."""
|
||||
|
||||
measure_id: str = Field(foreign_key="cat_measure.measure_id", primary_key=True, max_length=64)
|
||||
valor_id: str = Field(primary_key=True, max_length=64) # "LIEAG", "SIN_DATO"
|
||||
etiqueta: str
|
||||
orden: int
|
||||
origen: str = "catalogo" # uno de ORIGENES_DE_VALOR
|
||||
|
||||
|
||||
class CatMeasureGrupoBase(SQLModel):
|
||||
"""Un grupo de un indicador, en orden: tiene filas publicadas aunque ninguna unidad caiga en él.
|
||||
|
||||
Sin ficha, el único grupo es el `linkId` del TOML; con ficha, los de la ficha (T-19c).
|
||||
"""
|
||||
|
||||
measure_id: str = Field(foreign_key="cat_measure.measure_id", primary_key=True, max_length=64)
|
||||
grupo: str = Field(primary_key=True, max_length=64) # "TOTAL", "V1_16_23"
|
||||
etiqueta: str
|
||||
orden: int
|
||||
|
||||
|
||||
class CatEstratoBase(SQLModel):
|
||||
"""Una dimensión por la que se desglosa o se filtra: `grupo_edad`, `ronda`."""
|
||||
|
||||
estrato_id: str = Field(primary_key=True, max_length=64)
|
||||
etiqueta: str
|
||||
unidad: str # uno de UNIDADES: a qué unidad se le asigna
|
||||
|
||||
|
||||
class CatEstratoValorBase(SQLModel):
|
||||
"""Un valor de un estrato, con `sin_dato` al final."""
|
||||
|
||||
estrato_id: str = Field(foreign_key="cat_estrato.estrato_id", primary_key=True, max_length=64)
|
||||
valor_id: str = Field(primary_key=True, max_length=64)
|
||||
etiqueta: str
|
||||
orden: int
|
||||
|
||||
|
||||
class CatMeasureEstratoBase(SQLModel):
|
||||
"""Qué estrato admite un indicador: como desglose publicado o como filtro."""
|
||||
|
||||
measure_id: str = Field(foreign_key="cat_measure.measure_id", primary_key=True, max_length=64)
|
||||
estrato_id: str = Field(foreign_key="cat_estrato.estrato_id", primary_key=True, max_length=64)
|
||||
desglose: int = 1 # se publica desglosado por él
|
||||
filtro: int = 0 # se puede filtrar por uno de sus valores
|
||||
|
||||
|
||||
class MeasureReportUnidadBase(SQLModel):
|
||||
"""Una unidad en una población de un reporte, con su categoría (C2) o su número (C3r)."""
|
||||
|
||||
report_id: int = Field(foreign_key="measure_report.report_id", primary_key=True)
|
||||
grupo: str = Field(primary_key=True, max_length=64) # "principal"; en TEA, cada ventana
|
||||
unidad_id: str = Field(primary_key=True, max_length=64) # el pac_id o la llave del examen, según la unidad
|
||||
resultado_id: str = Field(foreign_key="cat_measure_resultado.resultado_id", primary_key=True, max_length=128)
|
||||
pac_id: int | None = None
|
||||
# El procedimiento que decide (MD-Q8): nulo hasta que la familia lo devuelva.
|
||||
procedimiento_id: int | None = Field(default=None, foreign_key="procedimiento.procedimiento_id")
|
||||
valor_id: str | None = Field(default=None, max_length=64) # la categoría, en C2
|
||||
numero: float | None = None # la medición, en C3r
|
||||
|
||||
|
||||
class MeasureReportUnidadEstratoBase(SQLModel):
|
||||
"""El valor de un estrato de una unidad de un reporte; `sin_dato` si no tiene."""
|
||||
|
||||
report_id: int = Field(foreign_key="measure_report.report_id", primary_key=True)
|
||||
unidad_id: str = Field(primary_key=True, max_length=64)
|
||||
estrato_id: str = Field(primary_key=True, max_length=64)
|
||||
estrato_valor: str = Field(max_length=64)
|
||||
|
||||
|
||||
def _uno_de(tabla: str, columna: str, valores: tuple[str, ...]) -> CheckConstraint:
|
||||
return CheckConstraint(
|
||||
f"{columna} IN (" + ", ".join(f"'{v}'" for v in valores) + ")", name=f"ck_{tabla}_{columna}"
|
||||
)
|
||||
|
||||
|
||||
def contrato_y_unidad_conocidos() -> tuple[CheckConstraint, CheckConstraint]:
|
||||
"""`cat_measure.contrato` es uno de `CONTRATOS` y `unidad`, uno de `UNIDADES`."""
|
||||
return _uno_de("cat_measure", "contrato", CONTRATOS), _uno_de("cat_measure", "unidad", UNIDADES)
|
||||
|
||||
|
||||
def poblacion_conocida() -> CheckConstraint:
|
||||
"""`cat_measure_resultado.poblacion` es una de `POBLACIONES`."""
|
||||
return _uno_de("cat_measure_resultado", "poblacion", POBLACIONES)
|
||||
|
||||
|
||||
def una_poblacion_por_indicador() -> UniqueConstraint:
|
||||
"""Un indicador tiene cada población una sola vez."""
|
||||
return UniqueConstraint("measure_id", "poblacion", name="uq_cat_measure_resultado_poblacion")
|
||||
|
||||
|
||||
def origen_conocido() -> CheckConstraint:
|
||||
"""`cat_measure_valor.origen` es uno de `ORIGENES_DE_VALOR`."""
|
||||
return _uno_de("cat_measure_valor", "origen", ORIGENES_DE_VALOR)
|
||||
|
||||
|
||||
def unidad_de_estrato_conocida() -> CheckConstraint:
|
||||
"""`cat_estrato.unidad` es una de `UNIDADES`."""
|
||||
return _uno_de("cat_estrato", "unidad", UNIDADES)
|
||||
|
||||
|
||||
def valor_de_estrato_en_catalogo() -> ForeignKeyConstraint:
|
||||
"""`(estrato_id, estrato_valor)` es un valor de `cat_estrato_valor`."""
|
||||
return ForeignKeyConstraint(
|
||||
["estrato_id", "estrato_valor"], ["cat_estrato_valor.estrato_id", "cat_estrato_valor.valor_id"],
|
||||
name="fk_measure_report_unidad_estrato_valor",
|
||||
)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Las columnas del registro de indicadores_kit, sin tabla.
|
||||
|
||||
`def_parametro` (parámetros cargados de un TOML), `dim_periodo` (los
|
||||
periodos de cálculo, cada uno `[inicio, fin)`), `dim_fecha` (un día por
|
||||
fila, para la aritmética de fechas sin funciones del motor) y
|
||||
`dim_grupo_edad` (los grupos de edad como datos). Se reconstruyen o se
|
||||
completan desde el kit; nadie las edita a mano.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import Text
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
|
||||
class DefParametroBase(SQLModel):
|
||||
"""Las columnas de `def_parametro`, sin tabla: cada dominio la instancia.
|
||||
|
||||
`valor` y `fuente` son `Text`, no un `str` corto: `valor` puede ser un
|
||||
JSON largo (una lista de grupos de edad, un catálogo con colores) y
|
||||
`fuente` es la explicación en prosa de por qué se eligió ese valor —
|
||||
ambos superan los 255 caracteres de la `VARCHAR` por omisión en
|
||||
bastantes filas reales de `parametros.toml` (confirmado contra MySQL:
|
||||
sin esto, `INSERT` falla con "Data too long for column 'valor'").
|
||||
"""
|
||||
|
||||
clave: str = Field(primary_key=True, max_length=128) # "seccion.nombre"
|
||||
valor: str = Field(sa_type=Text) # JSON: un escalar o una lista
|
||||
estado: str
|
||||
fuente: str = Field(sa_type=Text)
|
||||
toml_sha: str
|
||||
|
||||
|
||||
class DimPeriodoBase(SQLModel):
|
||||
"""Las columnas de `dim_periodo`, sin tabla: cada dominio la instancia."""
|
||||
|
||||
periodo_id: str = Field(primary_key=True, max_length=32) # "2024-S1"
|
||||
tipo: str
|
||||
inicio: date
|
||||
fin: date # exclusivo
|
||||
anio: int
|
||||
semestre: int
|
||||
|
||||
|
||||
class DimFechaBase(SQLModel):
|
||||
"""Las columnas de `dim_fecha`, sin tabla: cada dominio la instancia.
|
||||
|
||||
Sumar días o medir un intervalo es una resta de `dia_num` con un
|
||||
cruce; la edad cumplida sale de `anio`, `mes` y `dia`. Los días
|
||||
hábiles son de lunes a viernes, sin festivos.
|
||||
"""
|
||||
|
||||
fecha: date = Field(primary_key=True)
|
||||
dia_num: int # días desde el inicio de la tabla
|
||||
dia_habil_num: int # días hábiles transcurridos hasta esa fecha, incluida
|
||||
anio: int
|
||||
mes: int
|
||||
dia: int # día del mes
|
||||
|
||||
|
||||
class DimGrupoEdadBase(SQLModel):
|
||||
"""Las columnas de `dim_grupo_edad`, sin tabla: cada dominio la instancia."""
|
||||
|
||||
etiqueta: str = Field(primary_key=True, max_length=32) # "25-34"
|
||||
edad_min: int # años cumplidos, incluido
|
||||
edad_max: int # años cumplidos, incluido
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Las columnas de los resultados de indicadores_kit, sin tabla.
|
||||
|
||||
Forma de FHIR `MeasureReport`, formato largo (ADR-001). Solo reportes de
|
||||
tipo `summary`: son los únicos que pueden salir de la máquina segura.
|
||||
Las filas de un reporte son sus unidades (`core.indicadores.publicacion`, §6f);
|
||||
el número publicado lo dan las vistas del kit (MD-19).
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Text
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
|
||||
|
||||
class MeasureReportBase(SQLModel):
|
||||
"""Las columnas de `measure_report`, sin tabla: cada dominio la instancia."""
|
||||
|
||||
report_id: int | None = Field(default=None, primary_key=True)
|
||||
measure_url: str
|
||||
measure_version: str
|
||||
# Con la `url` y la `version` del Measure, identifica con qué se calculó
|
||||
# (D-S2, v0.5.0); reemplaza a `sql_sha`. Nula en reportes anteriores.
|
||||
kit_version: str | None = None
|
||||
toml_sha: str # versión del archivo de parámetros con que se calculó
|
||||
# Huella de los valores en uso: los que recibió el SQL y el umbral de
|
||||
# supresión. Nula en los reportes de antes de v0.4.0 (I-K58).
|
||||
parametros_sha: str | None = None
|
||||
# Los valores en uso, en JSON: los que recibió la consulta y el umbral de
|
||||
# supresión. Es el texto del que sale `parametros_sha`. Nula en los
|
||||
# reportes anteriores.
|
||||
parametros: str | None = Field(default=None, sa_type=Text)
|
||||
# Hasta qué día llegan los datos con que se calculó (I-K2, D-T6). Nula en
|
||||
# los reportes anteriores y en los de definiciones que no la usan.
|
||||
fecha_corte: date | None = None
|
||||
periodo_id: str = Field(foreign_key="dim_periodo.periodo_id", max_length=32)
|
||||
periodo_inicio: date
|
||||
periodo_fin: date
|
||||
status: str
|
||||
tipo: str
|
||||
generado_en: datetime = Field(sa_type=FechaHoraUTC)
|
||||
# §6f (MD-19): la revisión de las vistas con que se publica y la huella de sus unidades y
|
||||
# estratos. Las filas del reporte son sus unidades (`measure_report_unidad`); desde T-19e no hay
|
||||
# `measure_report_valor`, y la migración borró los reportes sin huella.
|
||||
agregacion_version: str | None = None
|
||||
huella: str | None = None
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Tipos de columna propios de las tablas de indicadores_kit."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import Text
|
||||
from sqlalchemy.types import TypeDecorator
|
||||
|
||||
|
||||
def a_texto_utc(momento: datetime) -> str:
|
||||
"""Texto ISO 8601 en UTC, de ancho fijo: se ordena igual que el tiempo."""
|
||||
if momento.tzinfo is None:
|
||||
raise ValueError("Se esperaba una fecha y hora con zona horaria.")
|
||||
return momento.astimezone(timezone.utc).isoformat(timespec="microseconds")
|
||||
|
||||
|
||||
class FechaHoraUTC(TypeDecorator):
|
||||
"""Tiempo del sistema: se guarda como texto en UTC y se lee con zona.
|
||||
|
||||
SQLite no tiene tipo de fecha y hora, y el `DateTime` de SQLAlchemy
|
||||
pierde la zona al leer. Rechaza valores sin zona horaria.
|
||||
"""
|
||||
|
||||
impl = Text
|
||||
cache_ok = True
|
||||
|
||||
def process_bind_param(self, value, dialect):
|
||||
return None if value is None else a_texto_utc(value)
|
||||
|
||||
def process_result_value(self, value, dialect):
|
||||
return None if value is None else datetime.fromisoformat(value)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""OCR traceability vocabulary shared by CaCu and CaMa (VAR-03/VARM-04a).
|
||||
|
||||
Every OCR-derived value records its status, whether it needs manual review,
|
||||
and which method produced it. The same columns appear on CaCu's
|
||||
`citologia_cervical`/`biopsia_cervical` and CaMa's `biopsia_mama`, so the
|
||||
enum lives here instead of in each domain."""
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class OcrEstatus(str, Enum):
|
||||
PENDIENTE = "PENDIENTE"
|
||||
REALIZADO = "REALIZADO"
|
||||
FALLIDO = "FALLIDO"
|
||||
|
||||
|
||||
OCR_ESTATUS_ALIAS: dict[str, str] = {
|
||||
"OK": "REALIZADO",
|
||||
"EXITOSO": "REALIZADO",
|
||||
"ERROR": "FALLIDO",
|
||||
}
|
||||
@@ -5,7 +5,8 @@ registry = orm.registry()
|
||||
|
||||
|
||||
class TeaModel(SQLModel, registry=registry):
|
||||
"""Base class for every TEA table. Own SQLAlchemy registry/metadata,
|
||||
same as CaCu/CaMa, so each domain's Alembic environment can target its
|
||||
own metadata independently.
|
||||
"""Base class for every TEA table.
|
||||
|
||||
Uses its own SQLAlchemy registry, like CaCu and CaMa, so each domain's
|
||||
Alembic environment targets its own metadata.
|
||||
"""
|
||||
|
||||
@@ -45,6 +45,15 @@ class TipoEstudio(str, Enum):
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
|
||||
"POTENCIALES_EVOCADOS": "POTENCIALES_EVOCADOS_AUDITIVOS",
|
||||
"POTENCIALES EVOCADOS": "POTENCIALES_EVOCADOS_AUDITIVOS",
|
||||
"POTENCIALES EVOCADOS AUDITIVOS": "POTENCIALES_EVOCADOS_AUDITIVOS",
|
||||
"EVALUACION PSICOLOGICA TEA": "EVALUACION_PSICOLOGICA_TEA",
|
||||
"EEG": "ELECTROENCEFALOGRAMA",
|
||||
}
|
||||
|
||||
|
||||
class EstatusEstudio(str, Enum):
|
||||
"""ord_estatus in table ordenes_estudio."""
|
||||
SOLICITADO = "SOLICITADO"
|
||||
@@ -126,6 +135,26 @@ class GradoHipoacusia(str, Enum):
|
||||
NO_CONCLUYENTE = "NO_CONCLUYENTE"
|
||||
|
||||
|
||||
class ClasificacionEeg(str, Enum):
|
||||
"""eeg_clasificacion in table eeg_estudio."""
|
||||
SIN_REFERENCIA_AURICULAR = "SIN_REFERENCIA_AURICULAR"
|
||||
|
||||
|
||||
class EstadoSegmentoEeg(str, Enum):
|
||||
"""seg_estado in table eeg_segmento."""
|
||||
NO_MARCADO = "NO_MARCADO"
|
||||
OJOS_CERRADOS = "OJOS_CERRADOS"
|
||||
FOTOESTIMULACION = "FOTOESTIMULACION"
|
||||
SUENO = "SUENO"
|
||||
|
||||
|
||||
class FuenteSegmentoEeg(str, Enum):
|
||||
"""seg_fuente in table eeg_segmento."""
|
||||
SIN_ANOTACION = "SIN_ANOTACION"
|
||||
ANOTACION_TECNICO = "ANOTACION_TECNICO"
|
||||
TRIGGER_EQUIPO = "TRIGGER_EQUIPO"
|
||||
|
||||
|
||||
class FuenteInterpretacionEeg(str, Enum):
|
||||
"""eeg_fuente_interpretacion in table eeg_estudio."""
|
||||
REPORTE_NEUROPEDIATRIA = "REPORTE_NEUROPEDIATRIA"
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Las tablas de indicadores_kit en el dominio TEA.
|
||||
|
||||
Viven en el registro de `TeaModel`, en la misma base que el staging de
|
||||
TEA (ADR-004). Las columnas se declaran una vez en `core.indicadores`;
|
||||
aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
|
||||
staging: `persona` es propia aunque repita a `pacientes`.
|
||||
"""
|
||||
|
||||
from core.indicadores.cohortes import (
|
||||
CohorteArmadoBase,
|
||||
CohorteExclusionBase,
|
||||
CohorteMiembroBase,
|
||||
CohorteVariableBase,
|
||||
EvaluacionRiesgoBase,
|
||||
EvaluacionRiesgoLoteBase,
|
||||
armado_unico,
|
||||
evaluacion_unica,
|
||||
variable_con_un_valor,
|
||||
)
|
||||
from core.indicadores.catalogos import (
|
||||
CatEstudioBase,
|
||||
CatResultadoBase,
|
||||
CatValorBase,
|
||||
estado_de_valor_conocido,
|
||||
tipo_de_valor_conocido,
|
||||
)
|
||||
from core.indicadores.plata import (
|
||||
ObservacionClinicaBase,
|
||||
ProcedimientoClinicoBase,
|
||||
clase_conocida,
|
||||
indice_de_observacion,
|
||||
indice_de_procedimiento,
|
||||
observacion_en_catalogo,
|
||||
llave_de_observacion,
|
||||
llave_de_procedimiento,
|
||||
)
|
||||
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaBase
|
||||
from core.indicadores.registro import (
|
||||
DefParametroBase,
|
||||
DimFechaBase,
|
||||
DimGrupoEdadBase,
|
||||
DimPeriodoBase,
|
||||
)
|
||||
from core.indicadores.publicacion import (
|
||||
CatEstratoBase,
|
||||
CatEstratoValorBase,
|
||||
CatMeasureBase,
|
||||
CatMeasureEstratoBase,
|
||||
CatMeasureGrupoBase,
|
||||
CatMeasureResultadoBase,
|
||||
CatMeasureValorBase,
|
||||
MeasureReportUnidadBase,
|
||||
MeasureReportUnidadEstratoBase,
|
||||
contrato_y_unidad_conocidos,
|
||||
origen_conocido,
|
||||
poblacion_conocida,
|
||||
una_poblacion_por_indicador,
|
||||
unidad_de_estrato_conocida,
|
||||
valor_de_estrato_en_catalogo,
|
||||
)
|
||||
from core.indicadores.reportes import (
|
||||
MeasureReportBase,
|
||||
)
|
||||
from core.tea.base import TeaModel
|
||||
from sqlmodel import Field
|
||||
|
||||
|
||||
class Persona(TeaModel, PersonaBase, table=True):
|
||||
"""La persona de TEA lleva además el sexo: los indicadores de TEA lo cuentan (M2)."""
|
||||
|
||||
__tablename__ = "persona"
|
||||
|
||||
sexo: str | None = None # código de `pac_sexo` (F, M, I), ya sin espacios y en mayúsculas
|
||||
|
||||
|
||||
class PeriodoObservacion(TeaModel, PeriodoObservacionBase, table=True):
|
||||
__tablename__ = "periodo_observacion"
|
||||
|
||||
|
||||
class Carga(TeaModel, CargaBase, table=True):
|
||||
__tablename__ = "carga"
|
||||
|
||||
|
||||
class DefParametro(TeaModel, DefParametroBase, table=True):
|
||||
__tablename__ = "def_parametro"
|
||||
|
||||
|
||||
class DimPeriodo(TeaModel, DimPeriodoBase, table=True):
|
||||
__tablename__ = "dim_periodo"
|
||||
|
||||
|
||||
class DimFecha(TeaModel, DimFechaBase, table=True):
|
||||
__tablename__ = "dim_fecha"
|
||||
|
||||
|
||||
class DimGrupoEdad(TeaModel, DimGrupoEdadBase, table=True):
|
||||
__tablename__ = "dim_grupo_edad"
|
||||
|
||||
|
||||
class MeasureReport(TeaModel, MeasureReportBase, table=True):
|
||||
__tablename__ = "measure_report"
|
||||
|
||||
|
||||
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
|
||||
|
||||
|
||||
class CatMeasure(TeaModel, CatMeasureBase, table=True):
|
||||
__tablename__ = "cat_measure"
|
||||
__table_args__ = contrato_y_unidad_conocidos()
|
||||
|
||||
|
||||
class CatMeasureResultado(TeaModel, CatMeasureResultadoBase, table=True):
|
||||
__tablename__ = "cat_measure_resultado"
|
||||
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
|
||||
|
||||
|
||||
class CatMeasureValor(TeaModel, CatMeasureValorBase, table=True):
|
||||
__tablename__ = "cat_measure_valor"
|
||||
__table_args__ = (origen_conocido(),)
|
||||
|
||||
|
||||
class CatMeasureGrupo(TeaModel, CatMeasureGrupoBase, table=True):
|
||||
__tablename__ = "cat_measure_grupo"
|
||||
|
||||
|
||||
class CatEstrato(TeaModel, CatEstratoBase, table=True):
|
||||
__tablename__ = "cat_estrato"
|
||||
__table_args__ = (unidad_de_estrato_conocida(),)
|
||||
|
||||
|
||||
class CatEstratoValor(TeaModel, CatEstratoValorBase, table=True):
|
||||
__tablename__ = "cat_estrato_valor"
|
||||
|
||||
|
||||
class CatMeasureEstrato(TeaModel, CatMeasureEstratoBase, table=True):
|
||||
__tablename__ = "cat_measure_estrato"
|
||||
|
||||
|
||||
class MeasureReportUnidad(TeaModel, MeasureReportUnidadBase, table=True):
|
||||
__tablename__ = "measure_report_unidad"
|
||||
|
||||
|
||||
class MeasureReportUnidadEstrato(TeaModel, MeasureReportUnidadEstratoBase, table=True):
|
||||
__tablename__ = "measure_report_unidad_estrato"
|
||||
__table_args__ = (valor_de_estrato_en_catalogo(),)
|
||||
|
||||
|
||||
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/tea.toml ---
|
||||
|
||||
|
||||
class CatEstudio(TeaModel, CatEstudioBase, table=True):
|
||||
__tablename__ = "cat_estudio"
|
||||
|
||||
|
||||
class CatResultado(TeaModel, CatResultadoBase, table=True):
|
||||
__tablename__ = "cat_resultado"
|
||||
__table_args__ = (tipo_de_valor_conocido(),)
|
||||
|
||||
|
||||
class CatValor(TeaModel, CatValorBase, table=True):
|
||||
__tablename__ = "cat_valor"
|
||||
__table_args__ = (estado_de_valor_conocido(),)
|
||||
|
||||
|
||||
# --- La plata de dos tablas (F5, ADR-MD-007) ---
|
||||
|
||||
|
||||
class Procedimiento(TeaModel, ProcedimientoClinicoBase, table=True):
|
||||
__tablename__ = "procedimiento"
|
||||
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
|
||||
|
||||
|
||||
class Observacion(TeaModel, ObservacionClinicaBase, table=True):
|
||||
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
|
||||
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
|
||||
|
||||
|
||||
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003) ---
|
||||
|
||||
|
||||
class CohorteArmado(TeaModel, CohorteArmadoBase, table=True):
|
||||
__tablename__ = "cohorte_armado"
|
||||
__table_args__ = (armado_unico(),)
|
||||
|
||||
|
||||
class CohorteMiembro(TeaModel, CohorteMiembroBase, table=True):
|
||||
__tablename__ = "cohorte_miembro"
|
||||
|
||||
|
||||
class CohorteExclusion(TeaModel, CohorteExclusionBase, table=True):
|
||||
__tablename__ = "cohorte_exclusion"
|
||||
|
||||
|
||||
class CohorteVariable(TeaModel, CohorteVariableBase, table=True):
|
||||
__tablename__ = "cohorte_variable"
|
||||
__table_args__ = (variable_con_un_valor(),)
|
||||
|
||||
|
||||
class EvaluacionRiesgoLote(TeaModel, EvaluacionRiesgoLoteBase, table=True):
|
||||
__tablename__ = "evaluacion_riesgo_lote"
|
||||
|
||||
|
||||
class EvaluacionRiesgo(TeaModel, EvaluacionRiesgoBase, table=True):
|
||||
__tablename__ = "evaluacion_riesgo"
|
||||
__table_args__ = (evaluacion_unica(),)
|
||||
+70
-15
@@ -12,14 +12,15 @@ import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
|
||||
from core.tea.base import TeaModel
|
||||
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
|
||||
|
||||
|
||||
class Pacientes(TeaModel, table=True):
|
||||
__tablename__ = "pacientes"
|
||||
|
||||
pac_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
pac_id: Optional[int] = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
pac_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_id_titular: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
@@ -40,9 +41,13 @@ class OrdenesEstudio(TeaModel, table=True):
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
ord_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
ord_nota_medica_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# Bounded and indexed, unlike TEA's other unenforced Text references: it
|
||||
# is the natural key the import layer upserts/merges orders on.
|
||||
ord_id_hospital: Optional[str] = Field(
|
||||
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
|
||||
)
|
||||
ord_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_medico_solicitante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
@@ -72,8 +77,12 @@ class NotaMedica(TeaModel, table=True):
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
nm_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
# Bounded and indexed, unlike TEA's other unenforced Text references: it
|
||||
# is the natural key the import layer upserts/merges notes on.
|
||||
nm_id_hospital: Optional[str] = Field(
|
||||
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
|
||||
)
|
||||
nm_nota_previa_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_tipo_nota: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
@@ -116,7 +125,9 @@ class EvaluacionPsicologica(TeaModel, table=True):
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
psi_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_fecha_entrevista_inicial: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
psi_fecha_ados2: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
psi_fecha_evaluacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
psi_psicologo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
@@ -184,7 +195,7 @@ class PotencialesEvocadosAuditivos(TeaModel, table=True):
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
pea_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pea_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
pea_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_umbral_od: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
@@ -209,10 +220,12 @@ class EegEstudio(TeaModel, table=True):
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
eeg_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# The child's integer pac_id, like the other studies' `*_pac_id`: the
|
||||
# indicator kit links each EEG to its patient by this key.
|
||||
eeg_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_reporte_disponible: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_fuente_interpretacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_fecha_nacimiento_declarada: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
eeg_fecha_nacimiento_archivo: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
eeg_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
eeg_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
eeg_fecha_reporte: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
@@ -222,7 +235,7 @@ class EegEstudio(TeaModel, table=True):
|
||||
eeg_privacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_sedacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_sedacion_farmaco: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_duracion_min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_duracion_min: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
eeg_calidad_tecnica: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_descripcion_senal: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
@@ -239,14 +252,56 @@ class EegEstudio(TeaModel, table=True):
|
||||
eeg_respuesta_fotoestimulacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_conclusion_categoria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_id_registro_laboratorio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# Bounded and indexed (unlike TEA's other unenforced Text references):
|
||||
# it is the natural key multiple sources (a report PDF, the EDF file
|
||||
# itself) use to land in the same row, so the import layer upserts on it.
|
||||
eeg_id_registro_laboratorio: Optional[str] = Field(
|
||||
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
|
||||
)
|
||||
eeg_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
eeg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_utilizable: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_estudio: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob))
|
||||
eeg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
eeg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
|
||||
|
||||
class EegSegmento(TeaModel, table=True):
|
||||
__tablename__ = "eeg_segmento"
|
||||
|
||||
seg_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
seg_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
seg_estado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
seg_inicio_s: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_fin_s: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_duracion_s: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_fuente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
seg_frecuencia_flash_hz: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_n_destellos: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
seg_cobertura: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_rms_uv: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_emg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_p2p_max_uv: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
|
||||
|
||||
class InstrumentoAplicado(TeaModel, table=True):
|
||||
__tablename__ = "instrumento_aplicado"
|
||||
|
||||
ins_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
ins_psi_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_instrumento: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_informante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_area: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_interpretacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
|
||||
|
||||
class AntecedentesMaternosGestacion(TeaModel, table=True):
|
||||
__tablename__ = "antecedentes_maternos_gestacion"
|
||||
|
||||
@@ -254,7 +309,7 @@ class AntecedentesMaternosGestacion(TeaModel, table=True):
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
amg_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_id_madre_seudonimo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_flag_vinculo_verificado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
@@ -299,7 +354,7 @@ class PartoNeonatal(TeaModel, table=True):
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
pnn_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_tipo_parto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_complicaciones_intraparto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
|
||||
@@ -7,6 +7,14 @@ dependencies = [
|
||||
"sqlmodel>=0.0.22",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# DB-API drivers for running the portability tests against MySQL/MariaDB or
|
||||
# PostgreSQL instead of just SQLite.
|
||||
drivers = [
|
||||
"pymysql>=1.1",
|
||||
"psycopg2-binary>=2.9",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
+83
-13
@@ -10,7 +10,7 @@ cumplir cada una.
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `pac_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `pac_id` | INTEGER, llave primaria, autoincremental | — | — | — |
|
||||
| `pac_id_hospital` | TEXT | — | — | — |
|
||||
| `pac_id_titular` | TEXT | — | — | — |
|
||||
| `pac_parentesco` | TEXT | — | Catálogo cerrado `Parentesco`: `HIJO, HIJA, HIJASTRO, TUTELADO, OTRO`. | — |
|
||||
@@ -24,6 +24,16 @@ cumplir cada una.
|
||||
|
||||
Sin validaciones cruzadas.
|
||||
|
||||
`pac_id` cambió de `VARCHAR(36)` (UUID) a `INTEGER` autoincremental el
|
||||
2026-10-19, para que `indicadores_kit` pueda cargar su CDM directamente
|
||||
(`core.indicadores.comunes.PersonaBase.pac_id` es `int`; el ETL del kit,
|
||||
`tea/etl.py::a_persona`, pasa `paciente.pac_id` sin convertir). Todas las
|
||||
columnas `*_pac_id` de las demás tablas de este documento cambiaron con
|
||||
ella. `eeg_estudio.eeg_pac_id` pasó a INTEGER después (2026-10-29): el
|
||||
origen la trae y `indicadores_kit` liga cada EEG a su niño por esta llave. Reset de la cadena de Alembic a una
|
||||
sola migración base (rule 3), no una migración de `ALTER COLUMN`: no había
|
||||
datos reales en ninguna base de TEA todavía.
|
||||
|
||||
---
|
||||
|
||||
## 2. Tabla `ordenes_estudio`
|
||||
@@ -31,9 +41,9 @@ Sin validaciones cruzadas.
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `ord_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `ord_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
|
||||
| `ord_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `ord_nota_medica_id` | TEXT | — | — | → `nota_medica.nm_id` |
|
||||
| `ord_id_hospital` | TEXT | — | — | — |
|
||||
| `ord_id_hospital` | VARCHAR(64), indexado | — | Llave natural para `on_conflict=upsert`/`merge` al importar órdenes de varias fuentes. | — |
|
||||
| `ord_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `ord_medico_solicitante` | TEXT | — | — | — |
|
||||
| `ord_especialidad` | TEXT | — | Catálogo `Especialidad`: `NEUROLOGIA_PEDIATRICA, PEDIATRIA, PSICOLOGIA, PSIQUIATRIA_INFANTIL, AUDIOLOGIA, MEDICINA_FAMILIAR, ENFERMERIA, OTRO`. | — |
|
||||
@@ -68,8 +78,8 @@ Sin validaciones cruzadas.
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `nm_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `nm_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
|
||||
| `nm_id_hospital` | TEXT | — | — | — |
|
||||
| `nm_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `nm_id_hospital` | VARCHAR(64), indexado | — | Llave natural para `on_conflict=upsert`/`merge` al importar notas de varias fuentes. | — |
|
||||
| `nm_nota_previa_id` | TEXT | — | — | → `nota_medica.nm_id` (autorreferencia: nota previa del mismo paciente) |
|
||||
| `nm_tipo_nota` | TEXT | — | Catálogo `TipoNota`: `PRIMERA_VEZ, TAMIZAJE, INTERPRETACION_EEG, TRATAMIENTO, SEGUIMIENTO, INTERCONSULTA, URGENCIA, OTRO`. | — |
|
||||
| `nm_especialidad` | TEXT | — | Catálogo `Especialidad` (mismo que `ord_especialidad`). | — |
|
||||
@@ -116,7 +126,9 @@ Sin validaciones cruzadas.
|
||||
|---|---|---|---|---|
|
||||
| `psi_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `psi_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `psi_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
|
||||
| `psi_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `psi_fecha_entrevista_inicial` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `psi_fecha_ados2` | DATE | — | No puede ser una fecha futura. La fecha en que se aplicó el ADOS-2, distinta de `psi_fecha_evaluacion`. | — |
|
||||
| `psi_fecha_evaluacion` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `psi_psicologo` | TEXT | — | — | — |
|
||||
| `psi_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
@@ -174,7 +186,7 @@ suman a esta lista.
|
||||
|---|---|---|---|---|
|
||||
| `pea_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `pea_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `pea_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
|
||||
| `pea_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `pea_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `pea_medico_interpreta` | TEXT | — | — | — |
|
||||
| `pea_umbral_od` | INTEGER | dB | Entre 0 y 120 (oído derecho). | — |
|
||||
@@ -201,10 +213,10 @@ suman a esta lista.
|
||||
|---|---|---|---|---|
|
||||
| `eeg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `eeg_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `eeg_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
|
||||
| `eeg_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `eeg_reporte_disponible` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_fuente_interpretacion` | TEXT | — | Catálogo `FuenteInterpretacionEeg`: `REPORTE_NEUROPEDIATRIA, NOTA_MEDICA, AMBAS, NINGUNA`. | — |
|
||||
| `eeg_fecha_nacimiento_declarada` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `eeg_fecha_nacimiento_archivo` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `eeg_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `eeg_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `eeg_fecha_reporte` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
|
||||
@@ -214,7 +226,7 @@ suman a esta lista.
|
||||
| `eeg_privacion_sueno` | BOOL | — | — | — |
|
||||
| `eeg_sedacion` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_sedacion_farmaco` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `eeg_duracion_min` | INTEGER | min | Entre 10 y 1440. | — |
|
||||
| `eeg_duracion_min` | REAL | min | Entre 10 y 1440. | — |
|
||||
| `eeg_calidad_tecnica` | TEXT | — | Catálogo `CalidadTecnicaEeg`: `SATISFACTORIA, LIMITADA_POR_ARTEFACTO, LIMITADA_POR_COLABORACION, NO_VALORABLE, NO_ESPECIFICADA`. | — |
|
||||
| `eeg_descripcion_senal` | TEXT | — | — | — |
|
||||
| `eeg_ritmo_base_frecuencia` | FLOAT | Hz | Entre 2.0 y 14.0. | — |
|
||||
@@ -231,10 +243,12 @@ suman a esta lista.
|
||||
| `eeg_respuesta_fotoestimulacion` | TEXT | — | Catálogo `RespuestaFotoestimulacion`: `NORMAL, RESPUESTA_FOTOPAROXISTICA, SIN_RESPUESTA, NO_PRACTICADA`. | — |
|
||||
| `eeg_conclusion_texto` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `eeg_conclusion_categoria` | TEXT | — | Catálogo `ConclusionEeg`: `NORMAL_PARA_LA_EDAD, NORMAL_CON_VARIANTES, ANORMAL_EPILEPTIFORME, ANORMAL_NO_EPILEPTIFORME, ANORMAL_MIXTO, NO_CONCLUYENTE`. Ver validación cruzada. | — |
|
||||
| `eeg_id_registro_laboratorio` | TEXT | — | — | — |
|
||||
| `eeg_id_registro_laboratorio` | VARCHAR(64), indexado | — | Llave natural: un reporte en PDF y el archivo EDF del mismo estudio comparten este valor y se combinan en el mismo renglón al importar (`on_conflict=upsert`/`merge`). | — |
|
||||
| `eeg_pdf_ruta` | TEXT | — | — | — |
|
||||
| `eeg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `eeg_nlp_version` | TEXT | — | — | — |
|
||||
| `eeg_utilizable` | BOOL | — | Si el estudio completo puede usarse para calcular indicadores; criterio de `indicadores_kit` (medida K06), no de esta capa. | — |
|
||||
| `eeg_estudio` | BLOB | — | Archivo European Data Format (`.edf`) del registro; se valida con `mne.io.read_raw_edf` (Enmienda). | — |
|
||||
| `eeg_created_at` | DATETIME | — | — | — |
|
||||
| `eeg_updated_at` | DATETIME | — | — | — |
|
||||
|
||||
@@ -247,6 +261,14 @@ suman a esta lista.
|
||||
- Si `eeg_reporte_disponible` es verdadero, `eeg_conclusion_texto` no puede quedar vacío.
|
||||
- Si `eeg_conclusion_categoria` es `NORMAL_PARA_LA_EDAD` o `NORMAL_CON_VARIANTES`, entonces `eeg_anormalidad_presente` debe ser falso.
|
||||
|
||||
`eeg_fecha_nacimiento_archivo` se llamaba `eeg_fecha_nacimiento_declarada`
|
||||
hasta el 2026-10-19: se renombró para que coincidiera con el nombre real
|
||||
de la columna en el hospital (confirmado por introspección directa de
|
||||
`hospital.eeg_estudio` vía el túnel) y con lo que lee
|
||||
`indicadores_kit.tea.mapeo.ligar_eegs` (la liga del EEG con el niño por
|
||||
fecha de nacimiento, ver `tea/mapeo.md`). Mismo nombre, no un campo
|
||||
nuevo.
|
||||
|
||||
---
|
||||
|
||||
## 7. Tabla `antecedentes_maternos_gestacion`
|
||||
@@ -254,7 +276,7 @@ suman a esta lista.
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `amg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `amg_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
|
||||
| `amg_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `amg_id_madre_seudonimo` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `amg_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteMaterno`: `EXPEDIENTE_MATERNO, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADO`. Ver validación cruzada. | — |
|
||||
| `amg_flag_vinculo_verificado` | BOOL | — | — | — |
|
||||
@@ -304,7 +326,7 @@ suman a esta lista.
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `pnn_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `pnn_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
|
||||
| `pnn_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `pnn_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteNeonatal`: `NOTA_RECIEN_NACIDO, NOTA_RESOLUCION_OBSTETRICA, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADA`. | — |
|
||||
| `pnn_tipo_parto` | TEXT | — | Catálogo `TipoParto`: `VAGINAL_ESPONTANEO, VAGINAL_INSTRUMENTADO, CESAREA_ELECTIVA, CESAREA_URGENCIA, NO_REGISTRADO`. | — |
|
||||
| `pnn_complicaciones_intraparto` | BOOL | — | Ver validación cruzada. | — |
|
||||
@@ -347,6 +369,52 @@ suman a esta lista.
|
||||
|
||||
---
|
||||
|
||||
## 9. Tabla `eeg_segmento`
|
||||
|
||||
Añadida 2026-10-19, junto con `eeg_utilizable` e `instrumento_aplicado`,
|
||||
para que `indicadores_kit` pueda calcular sus indicadores TEA (el campo
|
||||
que falta en su `tea/etl.py`/`tea/mapeo.py`, confirmado leyendo el fork).
|
||||
Una fila por segmento de un estudio de EEG (por ejemplo, el tramo de
|
||||
fotoestimulación o el tramo de sueño dentro del registro). Solo
|
||||
`seg_eeg_id`, `seg_estado` y `seg_duracion_s` los lee el kit hoy (K7, K8);
|
||||
el resto queda sin mapear pero existe en la fuente real (confirmado
|
||||
contra `hospital.eeg_segmento` en el espejo MySQL del hospital).
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `seg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `seg_eeg_id` | TEXT | — | — | → `eeg_estudio.eeg_id` |
|
||||
| `seg_estado` | TEXT | — | Código del segmento, por ejemplo `FOTOESTIMULACION` o `SUENO`. | — |
|
||||
| `seg_inicio_s` | FLOAT | s | — | — |
|
||||
| `seg_fin_s` | FLOAT | s | — | — |
|
||||
| `seg_duracion_s` | FLOAT | s | — | — |
|
||||
| `seg_fuente` | TEXT | — | — | — |
|
||||
| `seg_frecuencia_flash_hz` | FLOAT | Hz | — | — |
|
||||
| `seg_n_destellos` | INTEGER | — | — | — |
|
||||
| `seg_cobertura` | FLOAT | — | — | — |
|
||||
| `seg_rms_uv` | FLOAT | µV | — | — |
|
||||
| `seg_emg` | FLOAT | — | — | — |
|
||||
| `seg_p2p_max_uv` | FLOAT | µV | — | — |
|
||||
|
||||
---
|
||||
|
||||
## 10. Tabla `instrumento_aplicado`
|
||||
|
||||
Añadida 2026-10-19, ver nota de `eeg_segmento`. Una fila por instrumento
|
||||
aplicado dentro de una evaluación psicológica (por ejemplo, un
|
||||
cuestionario a un informante distinto del niño).
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `ins_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `ins_psi_id` | TEXT | — | Puede ser nulo: el kit no lo exige. | → `evaluacion_psicologica.psi_id` |
|
||||
| `ins_instrumento` | TEXT | — | Código del instrumento. | — |
|
||||
| `ins_informante` | TEXT | — | Código de quién lo respondió. | — |
|
||||
| `ins_area` | TEXT | — | Código del área evaluada. | — |
|
||||
| `ins_interpretacion` | TEXT | — | Código de la interpretación. | — |
|
||||
|
||||
---
|
||||
|
||||
## Anexo A — Funciones de referencia usadas en varias validaciones cruzadas
|
||||
|
||||
**Ventana madurativa según edad en meses** (usada en `ordenes_estudio`, `nota_medica`, `evaluacion_psicologica`):
|
||||
@@ -471,3 +539,5 @@ quedar vacías.
|
||||
| `eeg_estudio.eeg_pac_id` | `pacientes.pac_id` |
|
||||
| `antecedentes_maternos_gestacion.amg_pac_id` | `pacientes.pac_id` |
|
||||
| `parto_neonatal.pnn_pac_id` | `pacientes.pac_id` |
|
||||
| `eeg_segmento.seg_eeg_id` | `eeg_estudio.eeg_id` |
|
||||
| `instrumento_aplicado.ins_psi_id` | `evaluacion_psicologica.psi_id` |
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Portability tests for core.indicadores.fechas.
|
||||
|
||||
Checks the compiled SQL text for every supported dialect (no live
|
||||
connection needed) plus live execution against SQLite always, and MySQL
|
||||
when MYSQL_TEST_URL is set (see WebApi/tests/test_connectors_mysql.py for
|
||||
the same convention).
|
||||
"""
|
||||
import os
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.indicadores.fechas import dias_entre, edad_meses, meses_cumplidos, redondear
|
||||
|
||||
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
|
||||
|
||||
|
||||
def _compiled(expr, dialect_name):
|
||||
from sqlalchemy.dialects import mssql, mysql, postgresql, sqlite
|
||||
|
||||
dialects = {
|
||||
"sqlite": sqlite.dialect(),
|
||||
"postgresql": postgresql.dialect(),
|
||||
"mysql": mysql.dialect(),
|
||||
"mariadb": mysql.dialect(),
|
||||
"mssql": mssql.dialect(),
|
||||
}
|
||||
return str(expr.compile(dialect=dialects[dialect_name], compile_kwargs={"literal_binds": True}))
|
||||
|
||||
|
||||
def test_dias_entre_neutral_default_is_not_executable():
|
||||
from sqlalchemy.dialects import oracle
|
||||
|
||||
compiled = str(
|
||||
dias_entre(date(2026, 1, 1), date(2026, 3, 1)).compile(
|
||||
dialect=oracle.dialect(), compile_kwargs={"literal_binds": True}
|
||||
)
|
||||
)
|
||||
assert compiled.startswith("dias_entre(")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dialect_name,expected",
|
||||
[
|
||||
("sqlite", "CAST(julianday('2026-03-01') - julianday('2026-01-01') AS INTEGER)"),
|
||||
("postgresql", "(CAST('2026-03-01' AS DATE) - CAST('2026-01-01' AS DATE))"),
|
||||
("mysql", "DATEDIFF('2026-03-01', '2026-01-01')"),
|
||||
("mariadb", "DATEDIFF('2026-03-01', '2026-01-01')"),
|
||||
("mssql", "DATEDIFF(day, '2026-01-01', '2026-03-01')"),
|
||||
],
|
||||
)
|
||||
def test_dias_entre_compiles_per_dialect(dialect_name, expected):
|
||||
expr = dias_entre(date(2026, 1, 1), date(2026, 3, 1))
|
||||
assert _compiled(expr, dialect_name) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dialect_name,expected",
|
||||
[
|
||||
("sqlite", "ROUND(5.555, 1)"),
|
||||
("mysql", "ROUND(5.555, 1)"),
|
||||
("mariadb", "ROUND(5.555, 1)"),
|
||||
("mssql", "ROUND(5.555, 1)"),
|
||||
("postgresql", "CAST(ROUND(CAST(5.555 AS NUMERIC), 1) AS DOUBLE PRECISION)"),
|
||||
],
|
||||
)
|
||||
def test_redondear_compiles_per_dialect(dialect_name, expected):
|
||||
expr = redondear(5.555, 1)
|
||||
assert _compiled(expr, dialect_name) == expected
|
||||
|
||||
|
||||
def test_dias_entre_executes_on_sqlite():
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(sa.select(dias_entre(sa.literal(date(2026, 1, 1)), sa.literal(date(2026, 3, 1))))).scalar()
|
||||
assert result == 59 # Jan (31) + Feb (28) in 2026, a non-leap year
|
||||
|
||||
|
||||
def test_edad_meses_and_meses_cumplidos_on_sqlite():
|
||||
engine = sa.create_engine("sqlite://")
|
||||
nacimiento = date(2024, 1, 1)
|
||||
fecha = date(2026, 1, 17) # 2 years and 16 days old
|
||||
with engine.connect() as conn:
|
||||
edad = conn.execute(sa.select(edad_meses(sa.literal(nacimiento), sa.literal(fecha), 30.44))).scalar()
|
||||
cumplidos = conn.execute(sa.select(meses_cumplidos(sa.literal(edad)))).scalar()
|
||||
dias = (fecha - nacimiento).days
|
||||
assert edad == round(dias / 30.44, 1)
|
||||
assert cumplidos == int(edad // 1)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
|
||||
def test_dias_entre_executes_on_real_mysql():
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(sa.select(dias_entre(sa.literal(date(2026, 1, 1)), sa.literal(date(2026, 3, 1))))).scalar()
|
||||
assert result == 59
|
||||
|
||||
|
||||
@pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
|
||||
def test_edad_meses_executes_on_real_mysql():
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
nacimiento = date(2024, 1, 1)
|
||||
fecha = date(2026, 1, 17)
|
||||
with engine.connect() as conn:
|
||||
edad = conn.execute(sa.select(edad_meses(sa.literal(nacimiento), sa.literal(fecha), 30.44))).scalar()
|
||||
dias = (fecha - nacimiento).days
|
||||
assert float(edad) == round(dias / 30.44, 1)
|
||||
@@ -3,32 +3,100 @@ own isolated metadata (no cross-domain table-name collisions)."""
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.cama.base import CaMaModel
|
||||
from core.tea.base import TeaModel
|
||||
from core.governance.base import GovernanceModel
|
||||
from core.cacu import models as cacu_models
|
||||
from core.cacu.indicadores import models as cacu_indicadores_models
|
||||
from core.cama import models as cama_models
|
||||
from core.cama.indicadores import models as cama_indicadores_models
|
||||
from core.tea import models as tea_models
|
||||
from core.tea.indicadores import models as tea_indicadores_models
|
||||
from core.governance import models as governance_models
|
||||
|
||||
INDICADORES_KIT_CDM = {
|
||||
"persona",
|
||||
"periodo_observacion",
|
||||
"carga",
|
||||
"def_parametro",
|
||||
"dim_periodo",
|
||||
"dim_fecha",
|
||||
"dim_grupo_edad",
|
||||
"cat_estudio",
|
||||
"cat_resultado",
|
||||
"cat_valor",
|
||||
"procedimiento",
|
||||
"observacion_clinica",
|
||||
"cat_measure",
|
||||
"cat_measure_resultado",
|
||||
"cat_measure_valor",
|
||||
"cat_measure_grupo",
|
||||
"cat_estrato",
|
||||
"cat_estrato_valor",
|
||||
"cat_measure_estrato",
|
||||
"measure_report",
|
||||
"measure_report_unidad",
|
||||
"measure_report_unidad_estrato",
|
||||
"cohorte_armado",
|
||||
"cohorte_miembro",
|
||||
"cohorte_exclusion",
|
||||
"cohorte_variable",
|
||||
"evaluacion_riesgo_lote",
|
||||
"evaluacion_riesgo",
|
||||
}
|
||||
|
||||
|
||||
def test_cacu_tables_registered():
|
||||
"""Staging (hospital-shaped) and indicadores_kit CDM tables share
|
||||
CaCuModel's registry (same database, per the kit's ADR-004)."""
|
||||
names = set(CaCuModel.metadata.tables.keys())
|
||||
assert names == {"paciente", "ordenesestudio", "citologiacervical", "biopsiacervical", "notamedica", "biometriahematica"}
|
||||
assert names == {
|
||||
"paciente", "ordenesestudio", "citologiacervical", "biopsiacervical",
|
||||
"notamedica", "biometriahematica", "episodioclinico",
|
||||
*INDICADORES_KIT_CDM,
|
||||
}
|
||||
|
||||
|
||||
def test_cama_tables_registered():
|
||||
"""Staging (hospital-shaped) and indicadores_kit CDM tables share
|
||||
CaMaModel's registry (same database, per the kit's ADR-004)."""
|
||||
names = set(CaMaModel.metadata.tables.keys())
|
||||
assert names == {"paciente", "ordenesestudio", "mastografia", "biopsiamama", "notamedica", "biometriahematica"}
|
||||
assert names == {
|
||||
"paciente", "ordenesestudio", "mastografia", "biopsiamama",
|
||||
"notamedica", "biometriahematica", "episodioclinico",
|
||||
*INDICADORES_KIT_CDM,
|
||||
}
|
||||
|
||||
|
||||
def test_tea_tables_registered():
|
||||
"""Staging (hospital-shaped) and indicadores_kit CDM tables share
|
||||
TeaModel's registry (same database, per the kit's ADR-004), so both
|
||||
module's tables are asserted together."""
|
||||
names = set(TeaModel.metadata.tables.keys())
|
||||
assert names == {
|
||||
# Staging: fed by the hospital source via the import pipeline.
|
||||
"pacientes",
|
||||
"ordenes_estudio",
|
||||
"nota_medica",
|
||||
"evaluacion_psicologica",
|
||||
"potenciales_evocados_auditivos",
|
||||
"eeg_estudio",
|
||||
"eeg_segmento",
|
||||
"instrumento_aplicado",
|
||||
"antecedentes_maternos_gestacion",
|
||||
"parto_neonatal",
|
||||
# indicadores_kit CDM, built from staging by the Orquestacion graph.
|
||||
*INDICADORES_KIT_CDM,
|
||||
}
|
||||
|
||||
|
||||
def test_governance_tables_registered():
|
||||
names = set(GovernanceModel.metadata.tables.keys())
|
||||
assert names == {
|
||||
"extractionrun",
|
||||
"cohortversion",
|
||||
"cohortmember",
|
||||
"cohortexclusion",
|
||||
"cohortexclusioncount",
|
||||
"modelprediction",
|
||||
}
|
||||
|
||||
|
||||
@@ -36,3 +104,6 @@ def test_domains_do_not_share_metadata():
|
||||
assert CaCuModel.metadata is not CaMaModel.metadata
|
||||
assert CaCuModel.metadata is not TeaModel.metadata
|
||||
assert CaMaModel.metadata is not TeaModel.metadata
|
||||
assert CaCuModel.metadata is not GovernanceModel.metadata
|
||||
assert CaMaModel.metadata is not GovernanceModel.metadata
|
||||
assert TeaModel.metadata is not GovernanceModel.metadata
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
# Demo: hospital data → ingestion UI → indicators dashboard
|
||||
|
||||
End-to-end walkthrough on the shared dev server: pull the team's simulated
|
||||
hospital data through the **Conectar datos** ingestion UI (which calls
|
||||
WebApi's `/imports/*` endpoints), compute the indicators with the team's own
|
||||
`Orquestacion` pipeline, and explore them in the team's own **Dashboard de
|
||||
indicadores**.
|
||||
|
||||
Verified end to end for **CaCu** on 2026-10-23. TEA and CaMa follow the same
|
||||
steps (see §6); they were ingested and computed by script earlier, but not yet
|
||||
clicked through this UI flow.
|
||||
|
||||
---
|
||||
|
||||
## 1. What is running
|
||||
|
||||
| Piece | Where |
|
||||
|---|---|
|
||||
| WebApp (ingestion UI + dashboard) | http://10.0.10.41:9541 |
|
||||
| WebApi | http://10.0.10.41:9540 (the WebApp proxies to it, no need to open it) |
|
||||
| Simulated hospital MySQL (team's `dev-data-prueba` stack) | container `hospital`, port 3306, reachable only from inside Docker |
|
||||
| Our databases | SQLite files in the `issteleon-staging_webapi_data` volume, under `/data/demo/` |
|
||||
|
||||
Compose project `issteleon-staging`, checkout at
|
||||
`/srv/shared-notebooks/ISSSTELEON-wt/staging`, configured by its `.env`
|
||||
(ports, hospital network, database URLs). It is isolated from the team's own
|
||||
environments. It only joins their `dev-data-prueba_default` network to read
|
||||
the hospital mirror.
|
||||
|
||||
You need network access to `10.0.10.41` (VPN) and SSH as `admon` for §4.
|
||||
|
||||
## 2. Before the demo: start from empty databases (optional)
|
||||
|
||||
The current `/data/demo/` databases already hold the CaCu import from the
|
||||
verification run. To show ingestion from zero, point the stack at a new,
|
||||
empty directory. Nothing is deleted:
|
||||
|
||||
```bash
|
||||
ssh admon@10.0.10.41
|
||||
cd /srv/shared-notebooks/ISSSTELEON-wt/staging
|
||||
sed -i 's#/data/demo/#/data/demo2/#g' .env # pick any new directory name
|
||||
docker compose -p issteleon-staging up -d webapi # migrations run on startup
|
||||
```
|
||||
|
||||
The entrypoint creates the directory and runs every Alembic migration (CaCu,
|
||||
CaMa, TEA, governance) before gunicorn starts.
|
||||
|
||||
**Browser tip:** if a password manager is installed, dismiss its autofill
|
||||
popup on the connection form and don't save the password. Its overlay can
|
||||
block the page.
|
||||
|
||||
## 3. Ingest CaCu through the UI
|
||||
|
||||
1. Open http://10.0.10.41:9541 → **Cargar información**.
|
||||
2. Pick the **CaCu** domain toggle (top left).
|
||||
3. **Conectar una base de datos** → **MySQL**, then:
|
||||
- Servidor `hospital`, Puerto `3306`
|
||||
- Base de datos `hospital_cacu`
|
||||
- Usuario `hospital`, Contraseña `hospital` (disposable mirror account)
|
||||
- **Probar conexión** shows "Conexión correcta (mysql)" → **Conectar**.
|
||||
|
||||
*Talking point:* the dialog states the connection is read-only and only
|
||||
allows `SELECT`. The backend enforces this (`SqlSourcePolicy`: one SELECT
|
||||
statement, never the app's own databases), not just the UI.
|
||||
4. The connection lists 4 tables. For each one, click its **→** arrow,
|
||||
check the destination and click **Crear flujo**:
|
||||
|
||||
| Source table | Destination | Rows |
|
||||
|---|---|---|
|
||||
| `paciente` | Paciente | 300 |
|
||||
| `citologiacervical` | CitologiaCervical | 442 |
|
||||
| `biopsiacervical` | BiopsiaCervical | 7 |
|
||||
| `notamedica` | NotaMedica | 221 |
|
||||
|
||||
The destination is pre-selected ("Sugerida") and the column mapping is
|
||||
filled automatically (6/6, 19/19, 10/10, 26/26 fields). Open a flow's
|
||||
**Mapeo** tab to show how source columns line up with target fields, and
|
||||
**Datos** to preview real rows.
|
||||
5. **Validar todo**: every flow turns **Válido**, 0 errors. Validation runs
|
||||
the same schema checks the commit will (types, catalogs, required fields).
|
||||
6. **Cargar a la base** opens a summary: 970 valid rows in 4 flows, "en una
|
||||
sola transacción: si algo falla en la base, no se escribe nada".
|
||||
- *Omitirlo* (default): an existing record is reported as a conflict.
|
||||
- *Actualizarlo*: upsert on the natural key shown under each destination
|
||||
(e.g. `pac_id_hospital`, `pac_id_hospital + ord_numero_hospital`).
|
||||
|
||||
Click **Cargar 970 filas** → "Carga completa: 970 insertadas, 0
|
||||
actualizadas, 0 omitidas."
|
||||
7. **Explorar la base** shows the rows now stored, per table.
|
||||
|
||||
*Talking points:*
|
||||
- Parents are written before children, and each child's patient FK is
|
||||
resolved from `pac_id_hospital` within the same transaction. After the
|
||||
load, all 442 citologías, 7 biopsias and 221 notes are linked to a patient.
|
||||
- Running the same load again with **Actualizarlo** updates instead of
|
||||
duplicating.
|
||||
- Switching engines (MySQL, MariaDB, PostgreSQL, SQL Server) only changes
|
||||
`*_DATABASE_URL`. The same SQL connector reads from any of them.
|
||||
|
||||
## 4. Compute the indicators (team's Orquestacion pipeline)
|
||||
|
||||
The team's design (MD-16) keeps the kit itself calculation-only, and the
|
||||
orchestration graph does the writes. It runs inside the WebApi container:
|
||||
|
||||
```bash
|
||||
ssh admon@10.0.10.41
|
||||
docker exec -w /app/Orquestacion issteleon-staging-webapi-1 \
|
||||
uv run --no-sync python -m orquestacion ciclo cacu --desde 2024 --hasta 2026 --permitir-sin-definir
|
||||
```
|
||||
|
||||
Expected (about 30 s): `migrar → cargar (442) → cargar_resultados (879) →
|
||||
vistas (12) → registro → definiciones (9) → calcular (9) → observar (300) →
|
||||
verificar_vinculos → cohortes (1)`. That gives 9 CaCu indicators and the
|
||||
`cacu/cohorte_vigilancia` cohort. `python -m orquestacion grafo cacu` prints
|
||||
the graph as Mermaid, which is useful for explaining the architecture.
|
||||
|
||||
The data spans 2024-01 to 2026-01, hence `--desde 2024 --hasta 2026`.
|
||||
|
||||
## 5. Explore the dashboard
|
||||
|
||||
Open http://10.0.10.41:9541/indicadores/cacu (or **Indicadores** on the
|
||||
home page → **CaCu**).
|
||||
|
||||
What you should see with the CaCu data above:
|
||||
|
||||
- **Indicadores destacados** (latest visible period, 2025-S2):
|
||||
- Pacientes evaluadas: **112 pacientes**. Cross-check: 112 distinct
|
||||
patients have a citología taken in 2025-S2.
|
||||
- Tasa de confirmación histopatológica: **1.8 %** (2 of 112).
|
||||
- Tiempo de tamizaje a diagnóstico: **57 días (mediana)**, Q1–Q3
|
||||
37.5–109.5.
|
||||
- **Indicadores gráficos**, 6 published indicators: confirmation rate per
|
||||
semester with confidence intervals, distribution of cytology results
|
||||
(LIEBG, ASC-H, LIEAG, carcinoma in situ, "Sin dato"…), screening-to-diagnosis
|
||||
box plot, cytology turnaround time, patients with abnormal cytology, and
|
||||
biopsy results.
|
||||
- "Distribución de resultados de biopsia" shows *"No hay valores visibles"*.
|
||||
This is expected: only 7 biopsies, below the kit's small-cell suppression
|
||||
threshold. It is privacy protection working, not a bug.
|
||||
- Try **Filtros generales** (granularity semester/month, mode), the "Cómo
|
||||
leer" help, the chart-type selector ("Representación gráfica") and "Fijar
|
||||
indicador".
|
||||
|
||||
The dashboard, the figures (Plotly JSON generated server-side by
|
||||
`indicadores_kit.serving.figuras`) and the `/{domain}/indicadores/*` routes
|
||||
are the team's own code from `dev`. We only wired them into our shell.
|
||||
|
||||
## 6. TEA and CaMa
|
||||
|
||||
Same steps, other database and toggle:
|
||||
|
||||
| Domain | Toggle | Base de datos | Pipeline |
|
||||
|---|---|---|---|
|
||||
| TEA | TEA | `hospital` (10 tables) | `ciclo tea --desde 2024 --hasta 2026 --permitir-sin-definir` |
|
||||
| CaMa | CaMa | `hospital_cama` | `ciclo cama --desde 2024 --hasta 2026 --permitir-sin-definir` |
|
||||
|
||||
TEA specifics: the patient flow must include `pac_id` → `pac_id` (the
|
||||
destination now shows "8 campos · clave pac_id"). Every other TEA table
|
||||
references the patient by that source id. Load `pacientes` in the same batch
|
||||
as, or before, the rest.
|
||||
|
||||
Earlier scripted runs against the same hospital data produced 23 TEA
|
||||
indicators (5 published) and 8 CaMa. In CaMa, the kit's own
|
||||
`verificar_vinculos` reports every `biopsia_resultado` as `otra_paciente`.
|
||||
That is a linkage issue in the seed data to raise with Edgar's team, not an
|
||||
ingestion error.
|
||||
|
||||
## 7. What makes it production-ready (summary for Q&A)
|
||||
|
||||
- **Read-only, policy-checked SQL sources**: single `SELECT` only; the app's
|
||||
own databases are refused; credentials are never stored.
|
||||
- **Atomic batches**: a whole multi-table load is one transaction.
|
||||
- **Validation before writing**: same schemas at preview and commit;
|
||||
catalog values (e.g. Bethesda, BI-RADS incl. `B4A/B4B/B4C`) are
|
||||
normalized or rejected with a reason.
|
||||
- **Idempotent re-imports**: natural keys per table and an explicit
|
||||
skip/update choice.
|
||||
- **Cross-source linking and merging**: FKs resolved from hospital ids;
|
||||
"combinar duplicados" fills one record from several sources (CSV, SQL,
|
||||
scanned PDFs via OCR/NLP, EDF files).
|
||||
- **Database-agnostic**: SQLite, MySQL/MariaDB, PostgreSQL, SQL Server by
|
||||
connection string. Migrations are verified on SQLite and MySQL 8.
|
||||
- **Deployment**: migrations on startup, gunicorn with long timeouts for OCR,
|
||||
`Orquestacion` with MySQL/PostgreSQL drivers in the image, `index.html`
|
||||
served `no-cache` so a redeploy reaches users immediately.
|
||||
|
||||
## 8. Known limits (say them before someone asks)
|
||||
|
||||
- Computing indicators is a CLI step (§4); there is no button in the UI yet.
|
||||
- No login yet (Módulo-00); the SQL connection credentials travel with each
|
||||
request from the browser.
|
||||
- SQL connections live in the browser tab only: reloading the page means
|
||||
connecting again.
|
||||
@@ -0,0 +1,8 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
uv.lock
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Structured data out of clinical documents and biosignal files.
|
||||
|
||||
from extraction import DocumentExtractor, FieldKind, FieldSpec, read_document
|
||||
|
||||
document = read_document("reporte.pdf", raw)
|
||||
records = DocumentExtractor(
|
||||
[FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))],
|
||||
key_field="pac_id_hospital",
|
||||
).extract([document])
|
||||
"""
|
||||
from extraction.document import BBox, Document, EmbeddedImage, Line, Page
|
||||
from extraction.errors import ExtractionError
|
||||
from extraction.nlp import ExtractedValue, FieldExtractor, FieldKind, FieldSpec
|
||||
from extraction.readers import read_document, reader_for, supported_extensions
|
||||
from extraction.records import DocumentExtractor, ExtractedRecord, FieldConflict, RecordMerger
|
||||
from extraction.segmentation import SEGMENTERS, Segmenter, make_segmenter
|
||||
|
||||
__all__ = [
|
||||
"BBox",
|
||||
"Document",
|
||||
"DocumentExtractor",
|
||||
"EmbeddedImage",
|
||||
"ExtractedRecord",
|
||||
"ExtractedValue",
|
||||
"ExtractionError",
|
||||
"FieldConflict",
|
||||
"FieldExtractor",
|
||||
"FieldKind",
|
||||
"FieldSpec",
|
||||
"Line",
|
||||
"Page",
|
||||
"RecordMerger",
|
||||
"SEGMENTERS",
|
||||
"Segmenter",
|
||||
"make_segmenter",
|
||||
"read_document",
|
||||
"reader_for",
|
||||
"supported_extensions",
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
"""In-memory representation of a read document: pages, positioned text
|
||||
lines and embedded images. Every reader produces this shape, so the
|
||||
segmentation and NLP layers never care whether a page came from a PDF text
|
||||
layer, Tesseract, or a scanned TIFF."""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
|
||||
PageSource = Literal["text", "ocr"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BBox:
|
||||
"""Normalized to the page (0..1, origin top-left), so coordinates are
|
||||
comparable across renders at any DPI."""
|
||||
|
||||
x0: float
|
||||
y0: float
|
||||
x1: float
|
||||
y1: float
|
||||
|
||||
@property
|
||||
def area(self) -> float:
|
||||
return max(0.0, self.x1 - self.x0) * max(0.0, self.y1 - self.y0)
|
||||
|
||||
def as_list(self) -> list[float]:
|
||||
return [round(self.x0, 4), round(self.y0, 4), round(self.x1, 4), round(self.y1, 4)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Line:
|
||||
text: str
|
||||
bbox: BBox
|
||||
confidence: float = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EmbeddedImage:
|
||||
page_number: int
|
||||
bbox: BBox
|
||||
width_px: int | None = None
|
||||
height_px: int | None = None
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
"""`scan` when the image is the page itself (a scanned sheet), `figure` otherwise."""
|
||||
return "scan" if self.bbox.area >= 0.8 else "figure"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Page:
|
||||
number: int # 1-indexed
|
||||
lines: list[Line]
|
||||
source: PageSource
|
||||
images: list[EmbeddedImage] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return "\n".join(line.text for line in self.lines)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Document:
|
||||
name: str
|
||||
media_type: str
|
||||
pages: list[Page]
|
||||
raw: bytes = field(repr=False, default=b"")
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
return len(self.pages)
|
||||
|
||||
def page(self, number: int) -> Page:
|
||||
if not 1 <= number <= len(self.pages):
|
||||
raise IndexError(f"page {number} out of range (1..{len(self.pages)})")
|
||||
return self.pages[number - 1]
|
||||
@@ -0,0 +1,2 @@
|
||||
class ExtractionError(Exception):
|
||||
"""Unreadable input: a corrupt PDF, an unsupported format, a malformed EDF header."""
|
||||
@@ -0,0 +1,24 @@
|
||||
from extraction.nlp.extractors import (
|
||||
DEFAULT_EXTRACTORS,
|
||||
FieldExtractor,
|
||||
FreeTextMentionExtractor,
|
||||
LabeledValueExtractor,
|
||||
PatternExtractor,
|
||||
RecordExtractor,
|
||||
SegmentLine,
|
||||
)
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_EXTRACTORS",
|
||||
"Evidence",
|
||||
"ExtractedValue",
|
||||
"FieldExtractor",
|
||||
"FieldKind",
|
||||
"FieldSpec",
|
||||
"FreeTextMentionExtractor",
|
||||
"LabeledValueExtractor",
|
||||
"PatternExtractor",
|
||||
"RecordExtractor",
|
||||
"SegmentLine",
|
||||
]
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Field extraction strategies. Each `FieldExtractor` proposes candidates
|
||||
for a field; `RecordExtractor` keeps the most confident one per field.
|
||||
|
||||
To add a strategy (a dictionary lookup, a statistical NER model, an LLM
|
||||
call), subclass `FieldExtractor`, give it a `method` name and pass an
|
||||
instance to `RecordExtractor(extractors=[...])`.
|
||||
"""
|
||||
import re
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
from difflib import SequenceMatcher
|
||||
from functools import lru_cache
|
||||
from typing import Any, ClassVar, Iterable, Sequence
|
||||
|
||||
from extraction.document import Line
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
|
||||
from extraction.nlp.text import (
|
||||
SEPARATOR,
|
||||
find_date,
|
||||
find_decimal,
|
||||
find_identifier,
|
||||
find_integer,
|
||||
fold,
|
||||
is_negated,
|
||||
label_pattern,
|
||||
)
|
||||
|
||||
FUZZY_LABEL_THRESHOLD = 0.86
|
||||
MAX_TEXT_LENGTH = 1000
|
||||
MAX_CONTINUATION_LINES = 8
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SegmentLine:
|
||||
document: str
|
||||
page_number: int
|
||||
line: Line
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self.line.text
|
||||
|
||||
@property
|
||||
def folded(self) -> str:
|
||||
return fold(self.line.text)
|
||||
|
||||
@property
|
||||
def ocr_confidence(self) -> float:
|
||||
return self.line.confidence if self.line.confidence > 0 else 0.5
|
||||
|
||||
def evidence(self, text: str | None = None) -> Evidence:
|
||||
return Evidence(self.document, self.page_number, text or self.line.text, self.line.bbox.as_list())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LabelHit:
|
||||
field: str
|
||||
start: int
|
||||
end: int
|
||||
score: float
|
||||
|
||||
|
||||
class LabelIndex:
|
||||
"""Every label occurrence of every field, per line. Knowing where *all*
|
||||
labels sit is what lets one form line such as
|
||||
`Nombre: ANA Sexo: F C.P.: 64000` be split into three values."""
|
||||
|
||||
def __init__(self, lines: Sequence[SegmentLine], specs: Iterable[FieldSpec]):
|
||||
self.lines = list(lines)
|
||||
self.hits: list[list[LabelHit]] = [_label_hits(line.folded, tuple(specs)) for line in self.lines]
|
||||
|
||||
def for_field(self, name: str) -> Iterable[tuple[int, LabelHit]]:
|
||||
for index, hits in enumerate(self.hits):
|
||||
for hit in hits:
|
||||
if hit.field == name:
|
||||
yield index, hit
|
||||
|
||||
def next_start(self, index: int, after: int) -> int | None:
|
||||
starts = [hit.start for hit in self.hits[index] if hit.start >= after]
|
||||
return min(starts) if starts else None
|
||||
|
||||
def starts_with_label(self, index: int) -> bool:
|
||||
text = self.lines[index].folded
|
||||
offset = len(text) - len(text.lstrip())
|
||||
return any(hit.start <= offset + 2 for hit in self.hits[index])
|
||||
|
||||
|
||||
_AFTER_CAPTION = re.compile(r"\s*[:=#]|\s{2,}|\s*$")
|
||||
|
||||
|
||||
def _is_caption(folded: str, start: int, end: int) -> bool:
|
||||
"""A caption starts its line or is followed by a separator; the same
|
||||
words inside a sentence ("...muestra adecuada...") are just text."""
|
||||
return not folded[:start].strip() or bool(_AFTER_CAPTION.match(folded, end))
|
||||
|
||||
|
||||
def _label_hits(folded: str, specs: tuple[FieldSpec, ...]) -> list[LabelHit]:
|
||||
hits: list[LabelHit] = []
|
||||
for spec in specs:
|
||||
for label in spec.labels:
|
||||
exact = [LabelHit(spec.name, m.start(), m.end(), 1.0) for m in label_pattern(label).finditer(folded)]
|
||||
found = exact or _fuzzy_hits(folded, spec.name, label)
|
||||
hits.extend(hit for hit in found if _is_caption(folded, hit.start, hit.end))
|
||||
# A label inside a longer one ("FECHA" inside "FECHA DE NACIMIENTO") is not a label.
|
||||
hits.sort(key=lambda h: (h.start, -(h.end - h.start)))
|
||||
kept: list[LabelHit] = []
|
||||
for hit in hits:
|
||||
if any(other.start <= hit.start and hit.end <= other.end and (other.end - other.start) > (hit.end - hit.start) for other in hits):
|
||||
continue
|
||||
kept.append(hit)
|
||||
return kept
|
||||
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def _folded_label(label: str) -> str:
|
||||
return " ".join(re.findall(r"[A-Z0-9]+", fold(label)))
|
||||
|
||||
|
||||
def _fuzzy_hits(folded: str, field_name: str, label: str) -> list[LabelHit]:
|
||||
"""Tolerates OCR misreads in long labels (`FECHA DE NAC1MIENTO`)."""
|
||||
target = _folded_label(label)
|
||||
if len(target) < 6:
|
||||
return []
|
||||
tokens = [(m.group(), m.start(), m.end()) for m in re.finditer(r"[A-Z0-9]+", folded)]
|
||||
width = len(target.split())
|
||||
hits = []
|
||||
for i in range(len(tokens) - width + 1):
|
||||
window = tokens[i : i + width]
|
||||
candidate = " ".join(token for token, _, _ in window)
|
||||
matcher = SequenceMatcher(None, candidate, target)
|
||||
if matcher.real_quick_ratio() < FUZZY_LABEL_THRESHOLD or matcher.quick_ratio() < FUZZY_LABEL_THRESHOLD:
|
||||
continue
|
||||
ratio = matcher.ratio()
|
||||
if ratio >= FUZZY_LABEL_THRESHOLD:
|
||||
hits.append(LabelHit(field_name, window[0][1], window[-1][2], round(ratio, 3)))
|
||||
return hits
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Parsed:
|
||||
value: Any
|
||||
raw: str
|
||||
quality: float
|
||||
|
||||
|
||||
def parse_value(spec: FieldSpec, text: str) -> Parsed | None:
|
||||
"""Reads a value of `spec.kind` out of the text found next to a label."""
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return None
|
||||
if spec.kind is FieldKind.DATE:
|
||||
found = find_date(text)
|
||||
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.85) if found else None
|
||||
if spec.kind is FieldKind.INTEGER:
|
||||
found = find_integer(text)
|
||||
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.8) if found else None
|
||||
if spec.kind is FieldKind.DECIMAL:
|
||||
found = find_decimal(text)
|
||||
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.8) if found else None
|
||||
if spec.kind is FieldKind.IDENTIFIER:
|
||||
found = find_identifier(text, spec.pattern)
|
||||
return Parsed(found[0], found[0], 1.0 if found[1][0] <= 3 else 0.85) if found else None
|
||||
if spec.kind is FieldKind.CHOICE:
|
||||
found = find_choice(spec, fold(text))
|
||||
if found is None:
|
||||
return None
|
||||
value, surface, start = found
|
||||
return Parsed(value, text[start : start + len(surface)], 1.0 if start <= 3 else 0.85)
|
||||
if spec.pattern:
|
||||
match = re.search(spec.pattern, text, re.I)
|
||||
return Parsed(match.group(), match.group(), 1.0 if match.start() <= 3 else 0.85) if match else None
|
||||
return Parsed(text[:MAX_TEXT_LENGTH], text[:MAX_TEXT_LENGTH], 0.9)
|
||||
|
||||
|
||||
def find_choice(spec: FieldSpec, folded: str, *, min_length: int = 1) -> tuple[Any, str, int] | None:
|
||||
"""Leftmost, then longest, non-negated surface form of `spec` in `folded`."""
|
||||
best: tuple[Any, str, int] | None = None
|
||||
for surface in spec.surface_forms:
|
||||
if len(surface) < min_length:
|
||||
continue
|
||||
for match in _choice_pattern(surface).finditer(folded):
|
||||
if not _negates_itself(surface) and is_negated(folded, match.start()):
|
||||
continue
|
||||
if best is None or match.start() < best[2] or (match.start() == best[2] and len(surface) > len(best[1])):
|
||||
best = (spec.choices[surface], surface, match.start())
|
||||
break
|
||||
return best
|
||||
|
||||
|
||||
@lru_cache(maxsize=8192)
|
||||
def _choice_pattern(surface: str) -> re.Pattern:
|
||||
body = r"[\s.\-]+".join(re.escape(token) for token in surface.split())
|
||||
return re.compile(rf"(?<![A-Z0-9]){body}(?![A-Z0-9])")
|
||||
|
||||
|
||||
def _negates_itself(surface: str) -> bool:
|
||||
return bool(re.search(r"(?<![A-Z])(NO|NEGATIV[OA]|SIN|AUSENCIA)(?![A-Z])", surface))
|
||||
|
||||
|
||||
class FieldExtractor(ABC):
|
||||
method: ClassVar[str]
|
||||
|
||||
@abstractmethod
|
||||
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]: ...
|
||||
|
||||
|
||||
class LabeledValueExtractor(FieldExtractor):
|
||||
"""`Etiqueta: valor` on the same line, or the value on the line(s)
|
||||
under the label — the layout of forms and of report section headers
|
||||
(`DIAGNÓSTICO:` followed by a paragraph)."""
|
||||
|
||||
method = "etiqueta"
|
||||
|
||||
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
|
||||
for line_index, hit in index.for_field(spec.name):
|
||||
line = index.lines[line_index]
|
||||
end = index.next_start(line_index, hit.end)
|
||||
tail = line.text[hit.end : end]
|
||||
tail = tail[len(SEPARATOR.match(tail).group()) :]
|
||||
source_line = line
|
||||
if not tail.strip() or (spec.multiline and spec.kind is FieldKind.TEXT):
|
||||
continuation = self._continuation(spec, index, line_index)
|
||||
if continuation is not None:
|
||||
tail, source_line = (f"{tail.strip()} {continuation[0]}".strip(), continuation[1])
|
||||
parsed = parse_value(spec, tail)
|
||||
if parsed is None:
|
||||
continue
|
||||
confidence = 0.95 * hit.score * parsed.quality * min(line.ocr_confidence, source_line.ocr_confidence)
|
||||
yield ExtractedValue(parsed.value, confidence, self.method, parsed.raw, source_line.evidence(f"{line.text}"))
|
||||
|
||||
@staticmethod
|
||||
def _continuation(spec: FieldSpec, index: LabelIndex, line_index: int) -> tuple[str, SegmentLine] | None:
|
||||
limit = MAX_CONTINUATION_LINES if spec.multiline else 1
|
||||
collected: list[SegmentLine] = []
|
||||
for following in range(line_index + 1, min(len(index.lines), line_index + 1 + limit)):
|
||||
candidate = index.lines[following]
|
||||
if candidate.page_number != index.lines[line_index].page_number or not candidate.text.strip():
|
||||
break
|
||||
if index.starts_with_label(following):
|
||||
break
|
||||
collected.append(candidate)
|
||||
if not collected:
|
||||
return None
|
||||
return " ".join(line.text.strip() for line in collected), collected[0]
|
||||
|
||||
|
||||
class PatternExtractor(FieldExtractor):
|
||||
"""Values with a recognizable shape (`EXP-0042`, a CIE-10 code) found
|
||||
anywhere in the text, for fields with `scan_free_text` and a `pattern`.
|
||||
Lines that also carry one of the field's labels score higher."""
|
||||
|
||||
method = "patron"
|
||||
|
||||
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
|
||||
if not spec.pattern or not spec.scan_free_text:
|
||||
return
|
||||
regex = re.compile(spec.pattern, re.I)
|
||||
labelled_lines = {line_index for line_index, _ in index.for_field(spec.name)}
|
||||
for line_index, line in enumerate(index.lines):
|
||||
for match in regex.finditer(line.text):
|
||||
parsed = parse_value(spec, match.group())
|
||||
if parsed is None:
|
||||
continue
|
||||
base = 0.85 if line_index in labelled_lines else 0.7
|
||||
yield ExtractedValue(parsed.value, base * line.ocr_confidence, self.method, match.group(), line.evidence())
|
||||
|
||||
|
||||
class FreeTextMentionExtractor(FieldExtractor):
|
||||
"""Catalog terms mentioned in narrative text ("...compatible con NIC
|
||||
II...") without a label in front. Negated mentions ("negativo para
|
||||
lesión intraepitelial") are skipped. When several values are
|
||||
mentioned, the most repeated wins; ties go to the last mention,
|
||||
since reports state their conclusion at the end."""
|
||||
|
||||
method = "texto_libre"
|
||||
MIN_SURFACE_LENGTH = 4
|
||||
|
||||
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
|
||||
if spec.kind is not FieldKind.CHOICE or not spec.scan_free_text:
|
||||
return
|
||||
mentions: list[tuple[Any, str, SegmentLine]] = []
|
||||
for line in index.lines:
|
||||
folded = line.folded
|
||||
for surface in spec.surface_forms:
|
||||
if len(surface) < self.MIN_SURFACE_LENGTH:
|
||||
continue
|
||||
for match in _choice_pattern(surface).finditer(folded):
|
||||
if not _negates_itself(surface) and is_negated(folded, match.start()):
|
||||
continue
|
||||
mentions.append((spec.choices[surface], line.text[match.start() : match.end()], line))
|
||||
if not mentions:
|
||||
return
|
||||
counts = Counter(value for value, _, _ in mentions)
|
||||
top = max(counts.values())
|
||||
winner = [m for m in mentions if counts[m[0]] == top][-1]
|
||||
agreement = top / len(mentions)
|
||||
value, raw, line = winner
|
||||
yield ExtractedValue(value, 0.65 * agreement * line.ocr_confidence, self.method, raw, line.evidence())
|
||||
|
||||
|
||||
DEFAULT_EXTRACTORS: tuple[FieldExtractor, ...] = (
|
||||
LabeledValueExtractor(),
|
||||
PatternExtractor(),
|
||||
FreeTextMentionExtractor(),
|
||||
)
|
||||
|
||||
|
||||
class RecordExtractor:
|
||||
def __init__(self, specs: Sequence[FieldSpec], *, extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS):
|
||||
self.specs = list(specs)
|
||||
self.extractors = list(extractors)
|
||||
|
||||
def extract(self, lines: Sequence[SegmentLine]) -> dict[str, ExtractedValue]:
|
||||
index = LabelIndex(lines, self.specs)
|
||||
found: dict[str, ExtractedValue] = {}
|
||||
for spec in self.specs:
|
||||
best = None
|
||||
for extractor in self.extractors:
|
||||
for candidate in extractor.candidates(spec, index):
|
||||
if best is None or candidate.confidence > best.confidence:
|
||||
best = candidate
|
||||
if best is not None:
|
||||
found[spec.name] = best
|
||||
return found
|
||||
@@ -0,0 +1,77 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from enum import Enum
|
||||
from typing import Any, Mapping
|
||||
|
||||
from extraction.nlp.text import fold
|
||||
|
||||
|
||||
class FieldKind(str, Enum):
|
||||
TEXT = "text"
|
||||
IDENTIFIER = "identifier"
|
||||
INTEGER = "integer"
|
||||
DECIMAL = "decimal"
|
||||
DATE = "date"
|
||||
CHOICE = "choice"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FieldSpec:
|
||||
"""What to look for in a document to fill one column.
|
||||
|
||||
`labels` are the captions a form or report prints before the value
|
||||
("Fecha de nacimiento", "F. Nac."). `choices` maps surface forms to the
|
||||
value stored (`"NO DETECTADO" -> 0`, `"NIC II" -> "LIEAG"`); matching is
|
||||
accent- and case-insensitive and prefers the longest form.
|
||||
`pattern` is the shape of a valid value (the match is what's kept).
|
||||
`scan_free_text` lets the field be found anywhere in the narrative, not
|
||||
only after one of its labels: as a mention for CHOICE fields, by
|
||||
`pattern` for the rest.
|
||||
"""
|
||||
|
||||
name: str
|
||||
kind: FieldKind = FieldKind.TEXT
|
||||
labels: tuple[str, ...] = ()
|
||||
choices: Mapping[str, Any] = field(default_factory=dict)
|
||||
pattern: str | None = None
|
||||
scan_free_text: bool = False
|
||||
multiline: bool = False
|
||||
required: bool = False
|
||||
|
||||
def __post_init__(self):
|
||||
folded = {fold(str(surface)).strip(): value for surface, value in self.choices.items() if str(surface).strip()}
|
||||
object.__setattr__(self, "choices", folded)
|
||||
|
||||
@property
|
||||
def surface_forms(self) -> list[str]:
|
||||
return sorted(self.choices, key=len, reverse=True)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Evidence:
|
||||
document: str
|
||||
page_number: int
|
||||
line: str
|
||||
bbox: list[float] | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractedValue:
|
||||
value: Any
|
||||
confidence: float
|
||||
method: str
|
||||
raw: str
|
||||
evidence: Evidence
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
value = self.value.isoformat() if isinstance(self.value, date) else self.value
|
||||
return {
|
||||
"value": value,
|
||||
"confidence": round(self.confidence, 3),
|
||||
"method": self.method,
|
||||
"raw": self.raw,
|
||||
"document": self.evidence.document,
|
||||
"page_number": self.evidence.page_number,
|
||||
"line": self.evidence.line,
|
||||
"bbox": self.evidence.bbox,
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Spanish clinical text normalization and value parsing.
|
||||
|
||||
`fold` maps every character to exactly one character (uppercase, without
|
||||
accents), so a match found in folded text points at the same span in the
|
||||
original text.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
from datetime import date
|
||||
|
||||
_PUNCT_EQUIVALENTS = {"–": "-", "—": "-", "·": ".", "’": "'", " ": " "}
|
||||
|
||||
|
||||
def fold_char(ch: str) -> str:
|
||||
ch = _PUNCT_EQUIVALENTS.get(ch, ch)
|
||||
base = unicodedata.normalize("NFKD", ch)[:1] or ch
|
||||
upper = base.upper()
|
||||
return upper[:1] if upper else base
|
||||
|
||||
|
||||
def fold(text: str) -> str:
|
||||
return "".join(fold_char(ch) for ch in text)
|
||||
|
||||
|
||||
def label_pattern(label: str) -> re.Pattern:
|
||||
"""`"fecha de nacimiento"` -> a pattern matching `FECHA DE NACIMIENTO`,
|
||||
`Fecha de nacimiento`, `F.DE NACIMIENTO` style spacing/punctuation
|
||||
variants, on word boundaries."""
|
||||
tokens = re.findall(r"[A-Z0-9]+", fold(label))
|
||||
body = r"[\s.\-_/]*".join(re.escape(token) for token in tokens)
|
||||
return re.compile(rf"(?<![A-Z0-9]){body}\.?(?![A-Z0-9])")
|
||||
|
||||
|
||||
SEPARATOR = re.compile(r"^[\s.:\-=#•|]*")
|
||||
|
||||
# -- dates ---------------------------------------------------------------
|
||||
|
||||
MONTHS = {
|
||||
"ENERO": 1, "ENE": 1, "JAN": 1, "JANUARY": 1,
|
||||
"FEBRERO": 2, "FEB": 2, "FEBRUARY": 2,
|
||||
"MARZO": 3, "MAR": 3, "MARCH": 3,
|
||||
"ABRIL": 4, "ABR": 4, "APR": 4, "APRIL": 4,
|
||||
"MAYO": 5, "MAY": 5,
|
||||
"JUNIO": 6, "JUN": 6, "JUNE": 6,
|
||||
"JULIO": 7, "JUL": 7, "JULY": 7,
|
||||
"AGOSTO": 8, "AGO": 8, "AUG": 8, "AUGUST": 8,
|
||||
"SEPTIEMBRE": 9, "SETIEMBRE": 9, "SEP": 9, "SEPT": 9, "SET": 9, "SEPTEMBER": 9,
|
||||
"OCTUBRE": 10, "OCT": 10, "OCTOBER": 10,
|
||||
"NOVIEMBRE": 11, "NOV": 11, "NOVEMBER": 11,
|
||||
"DICIEMBRE": 12, "DIC": 12, "DEC": 12, "DECEMBER": 12,
|
||||
}
|
||||
_MONTH_NAMES = "|".join(sorted(MONTHS, key=len, reverse=True))
|
||||
|
||||
_DATE_PATTERNS = (
|
||||
# 2024-01-15
|
||||
(re.compile(r"(?<!\d)(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?!\d)"), ("y", "m", "d")),
|
||||
# 15/01/2024, 15-01-24 (day first: how dates are written in Mexico)
|
||||
(re.compile(r"(?<!\d)(\d{1,2})[-/.](\d{1,2})[-/.](\d{4}|\d{2})(?!\d)"), ("d", "m", "y")),
|
||||
# 15 de enero de 2024, 15-ENE-2024, 15 ene. 2024
|
||||
(re.compile(rf"(?<!\d)(\d{{1,2}})[\s.\-/]*(?:DE[\s]+)?({_MONTH_NAMES})\.?[\s.\-/,]*(?:DE(?:L)?[\s]+)?(\d{{4}}|\d{{2}})(?!\d)"), ("d", "M", "y")),
|
||||
# enero 15, 2024
|
||||
(re.compile(rf"(?<![A-Z])({_MONTH_NAMES})\.?\s+(\d{{1,2}}),?\s+(\d{{4}})(?!\d)"), ("M", "d", "y")),
|
||||
)
|
||||
|
||||
|
||||
def find_date(text: str) -> tuple[date, tuple[int, int]] | None:
|
||||
"""First valid date in `text` and its span."""
|
||||
folded = fold(text)
|
||||
best: tuple[date, tuple[int, int]] | None = None
|
||||
for pattern, order in _DATE_PATTERNS:
|
||||
for match in pattern.finditer(folded):
|
||||
parts = dict(zip(order, match.groups()))
|
||||
parsed = _build_date(parts)
|
||||
if parsed and (best is None or match.start() < best[1][0]):
|
||||
best = (parsed, match.span())
|
||||
break
|
||||
return best
|
||||
|
||||
|
||||
def _build_date(parts: dict[str, str]) -> date | None:
|
||||
try:
|
||||
month = MONTHS[parts["M"]] if "M" in parts else int(parts["m"])
|
||||
year = int(parts["y"])
|
||||
if year < 100:
|
||||
year += 2000 if year <= date.today().year % 100 else 1900
|
||||
return date(year, month, int(parts["d"]))
|
||||
except (KeyError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
# -- numbers and identifiers ----------------------------------------------
|
||||
|
||||
_NUMBER = re.compile(r"(?<![\w.])[-+]?\d{1,3}(?:[,\s]\d{3})*(?:[.,]\d+)?(?![\w])|(?<![\w.])[-+]?\d+(?:[.,]\d+)?(?![\w])")
|
||||
_INTEGER = re.compile(r"(?<![\w.,])[-+]?\d+(?![\w.,]\d)")
|
||||
_IDENTIFIER = re.compile(r"[A-Z0-9][A-Z0-9\-/._]*\d[A-Z0-9\-/._]*|\d+[A-Z][A-Z0-9\-]*")
|
||||
|
||||
|
||||
def find_decimal(text: str) -> tuple[float, tuple[int, int]] | None:
|
||||
match = _NUMBER.search(text)
|
||||
if not match:
|
||||
return None
|
||||
raw = match.group().replace(" ", "")
|
||||
if "," in raw and "." in raw:
|
||||
raw = raw.replace(",", "")
|
||||
elif "," in raw:
|
||||
whole, _, frac = raw.rpartition(",")
|
||||
raw = f"{whole}.{frac}" if len(frac) != 3 else raw.replace(",", "")
|
||||
try:
|
||||
return float(raw), match.span()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def find_integer(text: str) -> tuple[int, tuple[int, int]] | None:
|
||||
match = _INTEGER.search(text)
|
||||
return (int(match.group()), match.span()) if match else None
|
||||
|
||||
|
||||
def find_identifier(text: str, pattern: str | None = None) -> tuple[str, tuple[int, int]] | None:
|
||||
folded = fold(text)
|
||||
regex = re.compile(pattern, re.I) if pattern else _IDENTIFIER
|
||||
match = regex.search(folded if not pattern else text)
|
||||
if not match:
|
||||
return None
|
||||
return text[match.start() : match.end()].strip(" .,;:"), match.span()
|
||||
|
||||
|
||||
# -- negation ---------------------------------------------------------------
|
||||
|
||||
_NEGATION_TRIGGERS = re.compile(
|
||||
r"(?<![A-Z])(NO|SIN|NI|NUNCA|NIEGA|NEGATIVO (?:PARA|A)|AUSENCIA DE|DESCARTA(?:DO|R)?|NO SE OBSERVA(?:N)?|NO HAY|LIBRE DE)(?![A-Z])[^.;:]{0,30}$"
|
||||
)
|
||||
|
||||
|
||||
def is_negated(folded_text: str, start: int) -> bool:
|
||||
"""NegEx-style check: does a negation trigger precede position `start`
|
||||
within the same clause?"""
|
||||
window = folded_text[max(0, start - 45) : start]
|
||||
return bool(_NEGATION_TRIGGERS.search(window))
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Captions and clinical synonyms used by the source documents, keyed by
|
||||
the column they fill. Extend these tables when a new report format shows a
|
||||
caption or a term the extractor doesn't know yet; no code changes are needed.
|
||||
"""
|
||||
import re
|
||||
|
||||
# Column -> captions printed before its value (accents/case don't matter).
|
||||
LABELS: dict[str, tuple[str, ...]] = {
|
||||
"pac_id_hospital": ("expediente", "no. expediente", "num. expediente", "número de expediente", "nss", "no. de afiliación", "afiliación", "registro", "folio del paciente"),
|
||||
"pac_sexo": ("sexo", "género", "genero"),
|
||||
"pac_fecha_nacimiento": ("fecha de nacimiento", "f. de nacimiento", "f. nacimiento", "fecha nac", "f. nac", "nacimiento", "fec. nac"),
|
||||
"pac_codigo_postal": ("código postal", "c.p.", "cp"),
|
||||
"pac_dependencia": ("dependencia",),
|
||||
"pac_parentesco": ("parentesco",),
|
||||
"ord_numero_hospital": ("número de orden", "no. de orden", "orden", "folio de orden", "solicitud"),
|
||||
"ord_fecha_solicitud": ("fecha de solicitud", "solicitado el"),
|
||||
"ord_fecha_resultado": ("fecha de resultado", "fecha del resultado"),
|
||||
"ord_medico_solicitante": ("médico solicitante", "solicitante", "solicita"),
|
||||
"ord_diagnostico": ("diagnóstico", "dx"),
|
||||
"cit_fecha_toma": ("fecha de toma", "toma de muestra", "fecha toma", "fecha de muestra"),
|
||||
"cit_fecha_reporte": ("fecha de reporte", "fecha del reporte", "fecha de informe", "reportado el"),
|
||||
"cit_calidad_especimen": ("calidad de la muestra", "calidad del espécimen", "calidad de muestra", "muestra"),
|
||||
"cit_celulas_escamosas": ("células escamosas", "celulas escamosas", "anormalidades en células escamosas", "interpretación", "resultado citológico"),
|
||||
"cit_celulas_glandulares": ("células glandulares",),
|
||||
"cit_dx_lesion": ("diagnóstico", "lesión"),
|
||||
"cit_observaciones": ("observaciones", "comentarios", "notas"),
|
||||
"cit_vph_resultado": ("resultado vph", "vph de alto riesgo", "vph alto riesgo", "virus del papiloma humano", "detección de vph", "vph", "hpv"),
|
||||
"cit_vph_genotipo_16": ("genotipo 16", "vph 16", "hpv 16", "vph-16", "tipo 16"),
|
||||
"cit_vph_genotipo_18": ("genotipo 18", "vph 18", "hpv 18", "vph-18", "tipo 18"),
|
||||
"bx_fecha_solicitud": ("fecha de solicitud", "fecha de toma"),
|
||||
"bx_fecha_reporte": ("fecha de reporte", "fecha del reporte", "fecha de informe"),
|
||||
"bx_cin_grado": ("diagnóstico", "diagnóstico histopatológico", "resultado", "conclusión", "nic", "cin"),
|
||||
"bx_grado_histologico": ("diagnóstico", "diagnóstico histopatológico", "resultado", "conclusión", "grado histológico"),
|
||||
"bx_observaciones": ("observaciones", "descripción microscópica", "comentarios"),
|
||||
"mast_birads": ("bi-rads", "birads", "categoría", "clasificación"),
|
||||
"mast_fecha_toma": ("fecha de estudio", "fecha de toma", "fecha"),
|
||||
"mast_interpretacion": ("interpretación", "impresión diagnóstica", "conclusión", "hallazgos"),
|
||||
"nm_fecha": ("fecha", "fecha de consulta", "fecha de la nota"),
|
||||
"nm_medico_tratante": ("médico tratante", "médico", "atendió"),
|
||||
"nm_especialidad": ("especialidad", "servicio"),
|
||||
"nm_motivo_consulta": ("motivo de consulta", "motivo"),
|
||||
"nm_diagnostico_texto": ("diagnóstico", "impresión diagnóstica", "dx"),
|
||||
"nm_cie_codigo": ("cie-10", "cie10", "cie"),
|
||||
"nm_tratamiento_texto": ("tratamiento", "plan terapéutico"),
|
||||
"nm_plan_estudios": ("plan", "estudios solicitados"),
|
||||
"nm_pronostico": ("pronóstico",),
|
||||
"nm_talla": ("talla", "estatura"),
|
||||
"nm_masa_corporal": ("peso",),
|
||||
"nm_imc_visita": ("imc", "índice de masa corporal"),
|
||||
"nm_temperatura": ("temperatura", "temp"),
|
||||
"nm_frecuencia_cardiaca": ("frecuencia cardiaca", "fc"),
|
||||
"nm_frecuencia_respiratoria": ("frecuencia respiratoria", "fr"),
|
||||
"hemoglobina_g_dl": ("hemoglobina", "hb", "hgb"),
|
||||
"hematocrito_pct": ("hematocrito", "hto", "hct"),
|
||||
"eritrocitos_mill_ul": ("eritrocitos", "glóbulos rojos", "rbc"),
|
||||
"leucocitos_mil_ul": ("leucocitos", "glóbulos blancos", "wbc"),
|
||||
"plaquetas_mil_ul": ("plaquetas", "plt"),
|
||||
"neutrofilos_pct": ("neutrófilos",),
|
||||
"linfocitos_pct": ("linfocitos",),
|
||||
"monocitos_pct": ("monocitos",),
|
||||
"eosinofilos_pct": ("eosinófilos",),
|
||||
"basofilos_pct": ("basófilos",),
|
||||
"bh_fecha": ("fecha", "fecha de toma"),
|
||||
"eeg_id_registro_laboratorio": ("no. de estudio", "número de estudio", "folio", "no. de registro", "registro de laboratorio"),
|
||||
"eeg_fecha_estudio": ("fecha de estudio", "fecha del estudio", "fecha de registro"),
|
||||
"eeg_fecha_reporte": ("fecha de reporte", "fecha del reporte", "fecha de interpretación"),
|
||||
"eeg_medico_interpreta": ("médico interpreta", "interpretado por", "médico que interpreta"),
|
||||
"eeg_estado_registro": ("estado del registro", "estado"),
|
||||
"eeg_calidad_tecnica": ("calidad técnica", "calidad del registro"),
|
||||
"eeg_simetria": ("simetría", "simetria"),
|
||||
"eeg_distribucion_anormalidad": ("distribución de la anormalidad", "localización de la anormalidad"),
|
||||
"eeg_respuesta_fotoestimulacion": ("respuesta a fotoestimulación", "fotoestimulación"),
|
||||
"eeg_conclusion_texto": ("conclusión", "impresión diagnóstica", "interpretación"),
|
||||
"eeg_conclusion_categoria": ("conclusión", "categoría diagnóstica"),
|
||||
}
|
||||
|
||||
# Free-text terms -> catalog value. Only what the source documents say
|
||||
# differently from the catalog itself; the catalog values and their own
|
||||
# aliases are added by whoever builds the FieldSpec.
|
||||
CLINICAL_TERMS: dict[str, dict[str, object]] = {
|
||||
"cit_vph_resultado": {
|
||||
"POSITIVO": "POSITIVO",
|
||||
"DETECTADO": "POSITIVO",
|
||||
"NEGATIVO": "NEGATIVO",
|
||||
"NO DETECTADO": "NEGATIVO",
|
||||
"INDETERMINADO": "INDETERMINADO",
|
||||
"INVALIDO": "INDETERMINADO",
|
||||
"NO CONCLUYENTE": "INDETERMINADO",
|
||||
},
|
||||
"cit_vph_genotipo_16": {"POSITIVO": 1, "DETECTADO": 1, "PRESENTE": 1, "NEGATIVO": 0, "NO DETECTADO": 0, "AUSENTE": 0},
|
||||
"cit_vph_genotipo_18": {"POSITIVO": 1, "DETECTADO": 1, "PRESENTE": 1, "NEGATIVO": 0, "NO DETECTADO": 0, "AUSENTE": 0},
|
||||
"cit_celulas_escamosas": {
|
||||
"ASCUS": "ASC-US",
|
||||
"ASC US": "ASC-US",
|
||||
"LSIL": "LIEBG",
|
||||
"LIE BAJO GRADO": "LIEBG",
|
||||
"LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
|
||||
"HSIL": "LIEAG",
|
||||
"LIE ALTO GRADO": "LIEAG",
|
||||
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
|
||||
"NEGATIVO PARA LESION INTRAEPITELIAL": "NORMAL",
|
||||
"NEGATIVO PARA LESION INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
|
||||
},
|
||||
"bx_cin_grado": {
|
||||
"NIC I": "LIEBG", "NIC 1": "LIEBG", "CIN I": "LIEBG", "CIN 1": "LIEBG", "DISPLASIA LEVE": "LIEBG",
|
||||
"NIC II": "LIEAG", "NIC 2": "LIEAG", "CIN II": "LIEAG", "CIN 2": "LIEAG", "DISPLASIA MODERADA": "LIEAG",
|
||||
"NIC III": "LIEAG", "NIC 3": "LIEAG", "CIN III": "LIEAG", "CIN 3": "LIEAG", "DISPLASIA SEVERA": "LIEAG",
|
||||
"LESION INTRAEPITELIAL DE BAJO GRADO": "LIEBG", "LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
|
||||
"LESION INTRAEPITELIAL DE ALTO GRADO": "LIEAG", "LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
|
||||
"CARCINOMA IN SITU": "CIS",
|
||||
"CARCINOMA EPIDERMOIDE INVASOR": "CARCINOMA", "CARCINOMA INVASOR": "CARCINOMA", "CARCINOMA EPIDERMOIDE": "CARCINOMA",
|
||||
"ADENOCARCINOMA": "CARCINOMA",
|
||||
"CERVICITIS CRONICA": "NORMAL", "SIN ALTERACIONES": "NORMAL", "NEGATIVO PARA DISPLASIA": "NORMAL",
|
||||
"NEGATIVO PARA MALIGNIDAD": "NORMAL",
|
||||
},
|
||||
"bx_grado_histologico": {
|
||||
"CARCINOMA DUCTAL INFILTRANTE": "CARCINOMA_INVASOR",
|
||||
"CARCINOMA LOBULILLAR INFILTRANTE": "CARCINOMA_INVASOR",
|
||||
"CARCINOMA DUCTAL INVASOR": "CARCINOMA_INVASOR",
|
||||
"CARCINOMA INVASOR": "CARCINOMA_INVASOR",
|
||||
"CARCINOMA INFILTRANTE": "CARCINOMA_INVASOR",
|
||||
"CARCINOMA DUCTAL IN SITU": "CARCINOMA_IN_SITU",
|
||||
"CARCINOMA LOBULILLAR IN SITU": "CARCINOMA_IN_SITU",
|
||||
"CARCINOMA IN SITU": "CARCINOMA_IN_SITU",
|
||||
"CDIS": "CARCINOMA_IN_SITU",
|
||||
"FIBROADENOMA": "BENIGNO",
|
||||
"MASTOPATIA FIBROQUISTICA": "BENIGNO",
|
||||
"CAMBIOS FIBROQUISTICOS": "BENIGNO",
|
||||
"HIPERPLASIA DUCTAL USUAL": "BENIGNO",
|
||||
"BENIGNO": "BENIGNO",
|
||||
"NEGATIVO PARA MALIGNIDAD": "BENIGNO",
|
||||
},
|
||||
"mast_birads": {f"BI-RADS {n}": str(n) for n in ("0", "1", "2", "3", "4", "4A", "4B", "4C", "5", "6")},
|
||||
}
|
||||
|
||||
# Columns worth looking for anywhere in the narrative, not only after a caption.
|
||||
FREE_TEXT_FIELDS = frozenset(
|
||||
{"cit_vph_resultado", "cit_celulas_escamosas", "bx_cin_grado", "bx_grado_histologico", "mast_birads", "nm_cie_codigo"}
|
||||
)
|
||||
|
||||
# Shape of a valid value.
|
||||
PATTERNS: dict[str, str] = {
|
||||
"pac_codigo_postal": r"(?<!\d)\d{5}(?!\d)",
|
||||
"nm_cie_codigo": r"\b[A-TV-Z][0-9]{2}(?:\.[0-9A-Z]{1,2})?\b",
|
||||
}
|
||||
|
||||
_DOMAIN_PREFIX = re.compile(r"^(pac|ord|cit|bx|mast|nm|bh|eeg|psi|pea|amg|pn)_")
|
||||
|
||||
|
||||
def labels_for(column: str, description: str | None = None) -> tuple[str, ...]:
|
||||
"""Known captions, plus the column name itself in words
|
||||
(`pac_fecha_nacimiento` -> "fecha nacimiento") and a short
|
||||
description when the schema has one."""
|
||||
labels = list(LABELS.get(column, ()))
|
||||
words = _DOMAIN_PREFIX.sub("", column).replace("_", " ").strip()
|
||||
if words and words not in labels and not words.isdigit():
|
||||
labels.append(words)
|
||||
if description:
|
||||
short = description.split("—")[0].split("(")[0].strip()
|
||||
if short and len(short.split()) <= 5 and short.lower() not in (label.lower() for label in labels):
|
||||
labels.append(short)
|
||||
return tuple(labels)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Tesseract wrapper that returns positioned lines with a real per-line
|
||||
confidence (mean of Tesseract's word confidences), not just a string."""
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytesseract
|
||||
from PIL import Image
|
||||
from pytesseract import Output
|
||||
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.errors import ExtractionError
|
||||
|
||||
DEFAULT_LANG = os.environ.get("EXTRACTION_OCR_LANG", "spa+eng")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TesseractOcr:
|
||||
"""`psm=3` (automatic layout) suits a whole page; `psm=6` (one uniform
|
||||
block) suits a small crop such as a single form field, where PSM 3
|
||||
discards short strings like a lone "F" as noise."""
|
||||
|
||||
lang: str = DEFAULT_LANG
|
||||
psm: int = 3
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
try:
|
||||
return f"tesseract-{pytesseract.get_tesseract_version()}"
|
||||
except Exception:
|
||||
return "tesseract"
|
||||
|
||||
def read_lines(self, image: Image.Image) -> list[Line]:
|
||||
try:
|
||||
data = pytesseract.image_to_data(image, output_type=Output.DICT, lang=self.lang, config=f"--psm {self.psm}")
|
||||
except Exception as exc:
|
||||
raise ExtractionError(f"OCR failed: {exc}") from exc
|
||||
width, height = image.size
|
||||
return [_line(words, width, height) for words in group_words(data)]
|
||||
|
||||
|
||||
def group_words(data: dict[str, list]) -> list[list[dict]]:
|
||||
"""Words grouped by Tesseract's own (block, paragraph, line) segmentation, left to right."""
|
||||
grouped: dict[tuple[int, int, int], list[dict]] = {}
|
||||
for i, raw_text in enumerate(data["text"]):
|
||||
text = raw_text.strip()
|
||||
if not text:
|
||||
continue
|
||||
key = (data["block_num"][i], data["par_num"][i], data["line_num"][i])
|
||||
grouped.setdefault(key, []).append(
|
||||
{
|
||||
"text": text,
|
||||
"left": data["left"][i],
|
||||
"top": data["top"][i],
|
||||
"width": data["width"][i],
|
||||
"height": data["height"][i],
|
||||
"conf": float(data["conf"][i]),
|
||||
}
|
||||
)
|
||||
lines = [sorted(grouped[key], key=lambda w: w["left"]) for key in sorted(grouped)]
|
||||
return sorted(lines, key=lambda words: min(w["top"] for w in words))
|
||||
|
||||
|
||||
def _line(words: list[dict], width: int, height: int) -> Line:
|
||||
x0 = min(w["left"] for w in words)
|
||||
y0 = min(w["top"] for w in words)
|
||||
x1 = max(w["left"] + w["width"] for w in words)
|
||||
y1 = max(w["top"] + w["height"] for w in words)
|
||||
confidences = [w["conf"] for w in words if w["conf"] >= 0]
|
||||
confidence = (sum(confidences) / len(confidences) / 100) if confidences else 0.0
|
||||
return Line(
|
||||
text=" ".join(w["text"] for w in words),
|
||||
bbox=BBox(x0 / width, y0 / height, x1 / width, y1 / height),
|
||||
confidence=round(confidence, 4),
|
||||
)
|
||||
@@ -0,0 +1,46 @@
|
||||
from extraction.document import Document
|
||||
from extraction.errors import ExtractionError
|
||||
from extraction.readers.base import DocumentReader, OcrMode
|
||||
from extraction.readers.image import ImageReader
|
||||
from extraction.readers.pdf import PdfReader, combine_pages, extract_pages
|
||||
|
||||
READERS: list[type[DocumentReader]] = []
|
||||
|
||||
|
||||
def register_reader(cls: type[DocumentReader]) -> type[DocumentReader]:
|
||||
READERS.append(cls)
|
||||
return cls
|
||||
|
||||
|
||||
register_reader(PdfReader)
|
||||
register_reader(ImageReader)
|
||||
|
||||
|
||||
def reader_for(name: str, raw: bytes, **options) -> DocumentReader:
|
||||
head = raw[:16]
|
||||
for cls in READERS:
|
||||
if cls.accepts(name, head):
|
||||
return cls(**options)
|
||||
raise ExtractionError(f"unsupported document format: {name!r}")
|
||||
|
||||
|
||||
def read_document(name: str, raw: bytes, *, ocr_mode: OcrMode = "auto") -> Document:
|
||||
return reader_for(name, raw, ocr_mode=ocr_mode).read(name, raw)
|
||||
|
||||
|
||||
def supported_extensions() -> list[str]:
|
||||
return sorted({extension for cls in READERS for extension in cls.extensions})
|
||||
|
||||
|
||||
__all__ = [
|
||||
"READERS",
|
||||
"DocumentReader",
|
||||
"ImageReader",
|
||||
"PdfReader",
|
||||
"combine_pages",
|
||||
"extract_pages",
|
||||
"read_document",
|
||||
"reader_for",
|
||||
"register_reader",
|
||||
"supported_extensions",
|
||||
]
|
||||
@@ -0,0 +1,49 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import ClassVar, Literal
|
||||
|
||||
from extraction.document import BBox, Document
|
||||
|
||||
OcrMode = Literal["auto", "always", "never"]
|
||||
|
||||
|
||||
class DocumentReader(ABC):
|
||||
"""Turns raw bytes of one document format into a `Document`.
|
||||
|
||||
To support a new format, subclass this, fill in `media_type`,
|
||||
`extensions` and `magic`, and decorate the class with
|
||||
`@register_reader` (see `extraction.readers`).
|
||||
"""
|
||||
|
||||
media_type: ClassVar[str]
|
||||
extensions: ClassVar[tuple[str, ...]]
|
||||
magic: ClassVar[tuple[bytes, ...]] = ()
|
||||
|
||||
def __init__(self, *, ocr_mode: OcrMode = "auto", dpi: int = 200):
|
||||
self.ocr_mode = ocr_mode
|
||||
self.dpi = dpi
|
||||
|
||||
@classmethod
|
||||
def accepts(cls, name: str, head: bytes) -> bool:
|
||||
if any(head.startswith(signature) for signature in cls.magic):
|
||||
return True
|
||||
return name.lower().rsplit(".", 1)[-1] in cls.extensions
|
||||
|
||||
@abstractmethod
|
||||
def read(self, name: str, raw: bytes) -> Document: ...
|
||||
|
||||
@abstractmethod
|
||||
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
||||
"""PNG of one page."""
|
||||
|
||||
def render_region(self, raw: bytes, page_number: int, bbox: BBox, *, dpi: int = 150) -> bytes:
|
||||
"""PNG of a normalized region of one page (an embedded image, a signature, ...)."""
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
page = Image.open(io.BytesIO(self.render_page(raw, page_number, dpi=dpi)))
|
||||
width, height = page.size
|
||||
crop = page.crop((round(bbox.x0 * width), round(bbox.y0 * height), round(bbox.x1 * width), round(bbox.y1 * height)))
|
||||
buffer = io.BytesIO()
|
||||
crop.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
@@ -0,0 +1,48 @@
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageSequence
|
||||
|
||||
from extraction.document import BBox, Document, EmbeddedImage, Page
|
||||
from extraction.errors import ExtractionError
|
||||
from extraction.ocr import TesseractOcr
|
||||
from extraction.readers.base import DocumentReader
|
||||
|
||||
|
||||
class ImageReader(DocumentReader):
|
||||
"""A photo or scan of a document. Multi-frame TIFFs (the usual output of
|
||||
a document scanner) become one page per frame."""
|
||||
|
||||
media_type = "image/*"
|
||||
extensions = ("png", "jpg", "jpeg", "tif", "tiff", "bmp", "webp")
|
||||
magic = (b"\x89PNG", b"\xff\xd8\xff", b"II*\x00", b"MM\x00*")
|
||||
|
||||
def read(self, name: str, raw: bytes) -> Document:
|
||||
ocr = TesseractOcr()
|
||||
pages = []
|
||||
for number, frame in enumerate(self._frames(raw), start=1):
|
||||
width, height = frame.size
|
||||
pages.append(
|
||||
Page(
|
||||
number=number,
|
||||
lines=[] if self.ocr_mode == "never" else ocr.read_lines(frame),
|
||||
source="ocr",
|
||||
images=[EmbeddedImage(number, BBox(0, 0, 1, 1), width, height)],
|
||||
)
|
||||
)
|
||||
return Document(name=name, media_type=self.media_type, pages=pages, raw=raw)
|
||||
|
||||
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
||||
frames = self._frames(raw)
|
||||
if not 1 <= page_number <= len(frames):
|
||||
raise ExtractionError(f"page {page_number} out of range (1..{len(frames)})")
|
||||
buffer = io.BytesIO()
|
||||
frames[page_number - 1].save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
@staticmethod
|
||||
def _frames(raw: bytes) -> list[Image.Image]:
|
||||
try:
|
||||
image = Image.open(io.BytesIO(raw))
|
||||
return [frame.convert("RGB") for frame in ImageSequence.Iterator(image)]
|
||||
except Exception as exc:
|
||||
raise ExtractionError(f"could not open image: {exc}") from exc
|
||||
@@ -0,0 +1,108 @@
|
||||
import io
|
||||
|
||||
import pdfplumber
|
||||
import pypdfium2 as pdfium
|
||||
|
||||
from extraction.document import BBox, Document, EmbeddedImage, Line, Page
|
||||
from extraction.errors import ExtractionError
|
||||
from extraction.ocr import TesseractOcr
|
||||
from extraction.readers.base import DocumentReader
|
||||
|
||||
# Below this many characters a page is treated as scanned (no usable text layer).
|
||||
MIN_TEXT_CHARS = 20
|
||||
# Images smaller than this fraction of the page are bullets, logos or rules.
|
||||
MIN_IMAGE_AREA = 0.01
|
||||
|
||||
|
||||
class PdfReader(DocumentReader):
|
||||
"""Reads the text layer where there is one and OCRs the pages where
|
||||
there isn't, page by page. Hospital exports often mix typed pages with
|
||||
scanned attachments."""
|
||||
|
||||
media_type = "application/pdf"
|
||||
extensions = ("pdf",)
|
||||
magic = (b"%PDF",)
|
||||
|
||||
def read(self, name: str, raw: bytes) -> Document:
|
||||
pages = []
|
||||
with _open(raw) as pdf:
|
||||
for plumber_page in pdf.pages:
|
||||
pages.append(self._read_page(plumber_page))
|
||||
return Document(name=name, media_type=self.media_type, pages=pages, raw=raw)
|
||||
|
||||
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
||||
with _open(raw) as pdf:
|
||||
if not 1 <= page_number <= len(pdf.pages):
|
||||
raise ExtractionError(f"page {page_number} out of range (1..{len(pdf.pages)})")
|
||||
image = pdf.pages[page_number - 1].to_image(resolution=dpi).original
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
def _read_page(self, page) -> Page:
|
||||
images = _embedded_images(page)
|
||||
lines = [] if self.ocr_mode == "always" else _text_layer_lines(page)
|
||||
if self.ocr_mode == "never" or sum(len(line.text) for line in lines) >= MIN_TEXT_CHARS:
|
||||
return Page(number=page.page_number, lines=lines, source="text", images=images)
|
||||
rendered = page.to_image(resolution=self.dpi).original
|
||||
return Page(number=page.page_number, lines=TesseractOcr().read_lines(rendered), source="ocr", images=images)
|
||||
|
||||
|
||||
def extract_pages(raw: bytes, page_numbers: list[int]) -> bytes:
|
||||
"""A new PDF holding only `page_numbers` (1-indexed) of `raw`."""
|
||||
return combine_pages([(raw, page_numbers)])
|
||||
|
||||
|
||||
def combine_pages(parts: list[tuple[bytes, list[int]]]) -> bytes:
|
||||
"""One PDF with the given pages of several PDFs, in order: how a
|
||||
patient's pages, spread over several files, become their own document."""
|
||||
page_numbers = [numbers for _, numbers in parts]
|
||||
try:
|
||||
target = pdfium.PdfDocument.new()
|
||||
for raw, numbers in parts:
|
||||
target.import_pages(pdfium.PdfDocument(raw), [n - 1 for n in numbers])
|
||||
buffer = io.BytesIO()
|
||||
target.save(buffer)
|
||||
return buffer.getvalue()
|
||||
except Exception as exc:
|
||||
raise ExtractionError(f"could not extract pages {page_numbers}: {exc}") from exc
|
||||
|
||||
|
||||
def _open(raw: bytes):
|
||||
try:
|
||||
return pdfplumber.open(io.BytesIO(raw))
|
||||
except Exception as exc:
|
||||
raise ExtractionError(f"could not open PDF: {exc}") from exc
|
||||
|
||||
|
||||
def _text_layer_lines(page) -> list[Line]:
|
||||
try:
|
||||
raw_lines = page.extract_text_lines()
|
||||
except Exception:
|
||||
return []
|
||||
width, height = float(page.width), float(page.height)
|
||||
return [
|
||||
Line(
|
||||
text=line["text"].strip(),
|
||||
bbox=BBox(line["x0"] / width, line["top"] / height, line["x1"] / width, line["bottom"] / height),
|
||||
)
|
||||
for line in raw_lines
|
||||
if line.get("text", "").strip()
|
||||
]
|
||||
|
||||
|
||||
def _embedded_images(page) -> list[EmbeddedImage]:
|
||||
width, height = float(page.width), float(page.height)
|
||||
found = []
|
||||
for image in page.images:
|
||||
bbox = BBox(
|
||||
max(0.0, image["x0"] / width),
|
||||
max(0.0, image["top"] / height),
|
||||
min(1.0, image["x1"] / width),
|
||||
min(1.0, image["bottom"] / height),
|
||||
)
|
||||
if bbox.area < MIN_IMAGE_AREA:
|
||||
continue
|
||||
src_width, src_height = image.get("srcsize") or (None, None)
|
||||
found.append(EmbeddedImage(page_number=page.page_number, bbox=bbox, width_px=src_width, height_px=src_height))
|
||||
return found
|
||||
@@ -0,0 +1,122 @@
|
||||
"""From documents to records: segment, extract every field per segment,
|
||||
then merge the partial records that belong to the same patient."""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Sequence
|
||||
|
||||
from extraction.document import Document, EmbeddedImage
|
||||
from extraction.nlp.extractors import DEFAULT_EXTRACTORS, FieldExtractor, RecordExtractor
|
||||
from extraction.nlp.fields import ExtractedValue, FieldSpec
|
||||
from extraction.segmentation import AutoSegmenter, Segment, Segmenter, SegmentRef, normalize_key
|
||||
|
||||
# Two readings of the same field that disagree only count as a conflict
|
||||
# when the losing one is itself reasonably confident.
|
||||
CONFLICT_CONFIDENCE = 0.5
|
||||
|
||||
|
||||
@dataclass
|
||||
class FieldConflict:
|
||||
field: str
|
||||
kept: ExtractedValue
|
||||
discarded: ExtractedValue
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExtractedRecord:
|
||||
values: dict[str, ExtractedValue]
|
||||
sources: list[SegmentRef]
|
||||
images: list[tuple[str, EmbeddedImage]] = field(default_factory=list)
|
||||
key: str | None = None
|
||||
conflicts: list[FieldConflict] = field(default_factory=list)
|
||||
|
||||
def row(self) -> dict[str, Any]:
|
||||
return {name: extracted.value for name, extracted in self.values.items()}
|
||||
|
||||
@property
|
||||
def confidence(self) -> float:
|
||||
if not self.values:
|
||||
return 0.0
|
||||
return min(extracted.confidence for extracted in self.values.values())
|
||||
|
||||
|
||||
class RecordMerger:
|
||||
"""Combines records that share a key — a patient's demographics on one
|
||||
page, their lab result on another, their biopsy in another file. Per
|
||||
field, the most confident reading wins; a confident disagreement is
|
||||
kept as a `FieldConflict` so it can be reviewed."""
|
||||
|
||||
def merge(self, records: Sequence[ExtractedRecord]) -> list[ExtractedRecord]:
|
||||
merged: list[ExtractedRecord] = []
|
||||
by_key: dict[str, ExtractedRecord] = {}
|
||||
for record in records:
|
||||
if record.key is None:
|
||||
merged.append(record)
|
||||
continue
|
||||
target = by_key.get(record.key)
|
||||
if target is None:
|
||||
target = ExtractedRecord(values={}, sources=[], key=record.key)
|
||||
by_key[record.key] = target
|
||||
merged.append(target)
|
||||
self._absorb(target, record)
|
||||
return merged
|
||||
|
||||
@staticmethod
|
||||
def _absorb(target: ExtractedRecord, record: ExtractedRecord) -> None:
|
||||
target.sources.extend(record.sources)
|
||||
target.images.extend(record.images)
|
||||
target.conflicts.extend(record.conflicts)
|
||||
for name, incoming in record.values.items():
|
||||
current = target.values.get(name)
|
||||
if current is None:
|
||||
target.values[name] = incoming
|
||||
continue
|
||||
if current.value == incoming.value:
|
||||
if incoming.confidence > current.confidence:
|
||||
target.values[name] = incoming
|
||||
continue
|
||||
kept, discarded = (incoming, current) if incoming.confidence > current.confidence else (current, incoming)
|
||||
target.values[name] = kept
|
||||
if discarded.confidence >= CONFLICT_CONFIDENCE:
|
||||
target.conflicts.append(FieldConflict(name, kept, discarded))
|
||||
|
||||
|
||||
class DocumentExtractor:
|
||||
"""Entry point: `DocumentExtractor(specs, key_field="pac_id_hospital").extract(docs)`.
|
||||
|
||||
`key_field` names the spec that identifies a patient; it drives both
|
||||
the default segmentation (split a document where the key changes) and
|
||||
the merge across pages and documents.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
specs: Sequence[FieldSpec],
|
||||
*,
|
||||
key_field: str | None = None,
|
||||
segmenter: Segmenter | None = None,
|
||||
extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS,
|
||||
merger: RecordMerger | None = RecordMerger(),
|
||||
):
|
||||
self.specs = list(specs)
|
||||
self.key_spec = next((spec for spec in self.specs if spec.name == key_field), None)
|
||||
self.segmenter = segmenter or AutoSegmenter(self.key_spec)
|
||||
self.fields = RecordExtractor(self.specs, extractors=extractors)
|
||||
self.merger = merger
|
||||
|
||||
def segments(self, documents: Sequence[Document]) -> list[Segment]:
|
||||
return [segment for document in documents for segment in self.segmenter.split(document)]
|
||||
|
||||
def extract(self, documents: Sequence[Document]) -> list[ExtractedRecord]:
|
||||
records = [self.extract_segment(segment) for segment in self.segments(documents)]
|
||||
return self.merger.merge(records) if self.merger else records
|
||||
|
||||
def extract_segment(self, segment: Segment) -> ExtractedRecord:
|
||||
values = self.fields.extract(segment.lines())
|
||||
key = segment.key
|
||||
if self.key_spec is not None and self.key_spec.name in values:
|
||||
key = normalize_key(values[self.key_spec.name].value)
|
||||
return ExtractedRecord(
|
||||
values=values,
|
||||
sources=[SegmentRef(segment.document.name, list(segment.page_numbers))],
|
||||
images=[(segment.document.name, image) for image in segment.images],
|
||||
key=key,
|
||||
)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Splitting documents into records. A record is the set of pages that
|
||||
belong to one patient (or one study): a single-page report, several pages
|
||||
of one report, or one stretch of a long export holding many patients.
|
||||
|
||||
To add a strategy, subclass `Segmenter` and register it in `SEGMENTERS`.
|
||||
"""
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import ClassVar
|
||||
|
||||
from extraction.document import Document, EmbeddedImage
|
||||
from extraction.nlp.extractors import LabeledValueExtractor, LabelIndex, PatternExtractor, SegmentLine
|
||||
from extraction.nlp.fields import FieldSpec
|
||||
|
||||
MIN_KEY_CONFIDENCE = 0.4
|
||||
|
||||
|
||||
@dataclass
|
||||
class Segment:
|
||||
document: Document
|
||||
page_numbers: list[int]
|
||||
key: str | None = None
|
||||
|
||||
def lines(self) -> list[SegmentLine]:
|
||||
return [
|
||||
SegmentLine(self.document.name, number, line)
|
||||
for number in self.page_numbers
|
||||
for line in self.document.page(number).lines
|
||||
]
|
||||
|
||||
@property
|
||||
def images(self) -> list[EmbeddedImage]:
|
||||
return [image for number in self.page_numbers for image in self.document.page(number).images]
|
||||
|
||||
|
||||
class Segmenter(ABC):
|
||||
name: ClassVar[str]
|
||||
label: ClassVar[str]
|
||||
|
||||
@abstractmethod
|
||||
def split(self, document: Document) -> list[Segment]: ...
|
||||
|
||||
|
||||
class WholeDocument(Segmenter):
|
||||
name = "document"
|
||||
label = "Un registro por documento"
|
||||
|
||||
def split(self, document: Document) -> list[Segment]:
|
||||
return [Segment(document, [page.number for page in document.pages])]
|
||||
|
||||
|
||||
@dataclass
|
||||
class FixedPages(Segmenter):
|
||||
name = "pages"
|
||||
label = "Un registro cada N páginas"
|
||||
pages_per_record: int = 1
|
||||
|
||||
def split(self, document: Document) -> list[Segment]:
|
||||
size = max(1, self.pages_per_record)
|
||||
numbers = [page.number for page in document.pages]
|
||||
return [Segment(document, numbers[i : i + size]) for i in range(0, len(numbers), size)]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ByRecordKey(Segmenter):
|
||||
"""A new record starts on every page whose key (expediente, NSS, folio)
|
||||
differs from the current one. Pages without a readable key continue the
|
||||
record before them, so a report's second page joins its first."""
|
||||
|
||||
name = "key"
|
||||
label = "Por identificador del paciente"
|
||||
key: FieldSpec | None = None
|
||||
|
||||
def split(self, document: Document) -> list[Segment]:
|
||||
if self.key is None:
|
||||
return WholeDocument().split(document)
|
||||
segments: list[Segment] = []
|
||||
for page in document.pages:
|
||||
key = self.page_key(document, page.number)
|
||||
current = segments[-1] if segments else None
|
||||
if current is not None and (key is None or key == current.key):
|
||||
current.page_numbers.append(page.number)
|
||||
current.key = current.key or key
|
||||
else:
|
||||
segments.append(Segment(document, [page.number], key))
|
||||
return segments
|
||||
|
||||
def page_key(self, document: Document, page_number: int) -> str | None:
|
||||
lines = Segment(document, [page_number]).lines()
|
||||
index = LabelIndex(lines, [self.key])
|
||||
best = None
|
||||
for extractor in (LabeledValueExtractor(), PatternExtractor()):
|
||||
for candidate in extractor.candidates(self.key, index):
|
||||
if best is None or candidate.confidence > best.confidence:
|
||||
best = candidate
|
||||
if best is None or best.confidence < MIN_KEY_CONFIDENCE:
|
||||
return None
|
||||
return normalize_key(best.value)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoSegmenter(Segmenter):
|
||||
"""Splits by key when more than one key shows up in the document,
|
||||
otherwise treats the document as a single record."""
|
||||
|
||||
name = "auto"
|
||||
label = "Automático"
|
||||
key: FieldSpec | None = None
|
||||
|
||||
def split(self, document: Document) -> list[Segment]:
|
||||
by_key = ByRecordKey(self.key).split(document)
|
||||
if len({segment.key for segment in by_key if segment.key}) > 1:
|
||||
return by_key
|
||||
whole = WholeDocument().split(document)
|
||||
whole[0].key = next((segment.key for segment in by_key if segment.key), None)
|
||||
return whole
|
||||
|
||||
|
||||
SEGMENTERS: dict[str, type[Segmenter]] = {
|
||||
cls.name: cls for cls in (AutoSegmenter, WholeDocument, FixedPages, ByRecordKey)
|
||||
}
|
||||
|
||||
|
||||
def make_segmenter(name: str, *, key: FieldSpec | None = None, pages_per_record: int = 1) -> Segmenter:
|
||||
if name == FixedPages.name:
|
||||
return FixedPages(pages_per_record)
|
||||
if name in (ByRecordKey.name, AutoSegmenter.name):
|
||||
return SEGMENTERS[name](key)
|
||||
if name == WholeDocument.name:
|
||||
return WholeDocument()
|
||||
raise ValueError(f"unknown segmentation {name!r} (available: {', '.join(SEGMENTERS)})")
|
||||
|
||||
|
||||
def normalize_key(value) -> str:
|
||||
return "".join(str(value).split()).upper()
|
||||
|
||||
|
||||
@dataclass
|
||||
class SegmentRef:
|
||||
document: str
|
||||
page_numbers: list[int] = field(default_factory=list)
|
||||
@@ -0,0 +1,3 @@
|
||||
from extraction.signals.edf import BANDS_HZ, EdfAnnotation, EdfChannel, EdfPatient, EegRecording, band_powers
|
||||
|
||||
__all__ = ["BANDS_HZ", "EdfAnnotation", "EdfChannel", "EdfPatient", "EegRecording", "band_powers"]
|
||||
@@ -0,0 +1,191 @@
|
||||
"""EEG recordings in EDF/EDF+ (and BDF) read through MNE.
|
||||
|
||||
`EegRecording.validate_edf` is the check the TEA amendment sets for
|
||||
`eeg_estudio.eeg_estudio`: the file must open with `mne.io.read_raw_edf`.
|
||||
"""
|
||||
import io
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
|
||||
import mne
|
||||
import numpy as np
|
||||
|
||||
from extraction.errors import ExtractionError
|
||||
|
||||
BANDS_HZ = {
|
||||
"delta": (0.5, 4.0),
|
||||
"theta": (4.0, 8.0),
|
||||
"alpha": (8.0, 13.0),
|
||||
"beta": (13.0, 30.0),
|
||||
"gamma": (30.0, 45.0),
|
||||
}
|
||||
POSTERIOR_ELECTRODES = {"O1", "O2", "OZ", "P3", "P4", "PZ", "PO3", "PO4", "POZ", "T5", "T6", "P7", "P8"}
|
||||
_SEX = {1: "M", 2: "F"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EdfPatient:
|
||||
code: str | None = None
|
||||
sex: str | None = None
|
||||
birthdate: date | None = None
|
||||
name: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EdfAnnotation:
|
||||
onset_seconds: float
|
||||
duration_seconds: float | None
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EdfChannel:
|
||||
index: int
|
||||
label: str
|
||||
sample_rate: float
|
||||
|
||||
|
||||
class EegRecording:
|
||||
def __init__(self, raw: mne.io.BaseRaw, header: bytes, *, is_bdf: bool):
|
||||
self.raw = raw
|
||||
self.is_bdf = is_bdf
|
||||
self._recording_field = header[88:168].decode("latin-1").strip()
|
||||
reserved = header[192:236].decode("latin-1").strip()
|
||||
self.variant = ("BDF" if is_bdf else "EDF") + ("+" if reserved.startswith(("EDF+", "BDF+")) else "")
|
||||
|
||||
@staticmethod
|
||||
def validate_edf(data: bytes) -> None:
|
||||
"""The check `eeg_estudio.eeg_estudio` requires: MNE's EDF reader opens the file."""
|
||||
try:
|
||||
mne.io.read_raw_edf(io.BytesIO(data), preload=True, verbose="error")
|
||||
except Exception as exc:
|
||||
raise ExtractionError(f"not a valid EDF file: {exc}") from exc
|
||||
|
||||
@classmethod
|
||||
def read(cls, data: bytes) -> "EegRecording":
|
||||
is_bdf = data[:1] == b"\xff"
|
||||
reader = mne.io.read_raw_bdf if is_bdf else mne.io.read_raw_edf
|
||||
try:
|
||||
raw = reader(io.BytesIO(data), preload=True, verbose="error")
|
||||
except Exception as exc:
|
||||
raise ExtractionError(f"not a valid {'BDF' if is_bdf else 'EDF'} file: {exc}") from exc
|
||||
return cls(raw, data[:256], is_bdf=is_bdf)
|
||||
|
||||
# -- header ---------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def patient(self) -> EdfPatient:
|
||||
info = self.raw.info.get("subject_info") or {}
|
||||
names = [info.get("first_name"), info.get("middle_name"), info.get("last_name")]
|
||||
return EdfPatient(
|
||||
code=info.get("his_id"),
|
||||
sex=_SEX.get(info.get("sex")),
|
||||
birthdate=info.get("birthday"),
|
||||
name=" ".join(n for n in names if n) or None,
|
||||
)
|
||||
|
||||
@property
|
||||
def start(self) -> datetime | None:
|
||||
meas_date = self.raw.info.get("meas_date")
|
||||
return meas_date.replace(tzinfo=None) if meas_date else None
|
||||
|
||||
@property
|
||||
def duration_seconds(self) -> float:
|
||||
return self.raw.n_times / self.raw.info["sfreq"]
|
||||
|
||||
@property
|
||||
def channels(self) -> list[EdfChannel]:
|
||||
rate = float(self.raw.info["sfreq"])
|
||||
return [EdfChannel(i, name, rate) for i, name in enumerate(self.raw.ch_names)]
|
||||
|
||||
@property
|
||||
def recording_fields(self) -> dict[str, str | None]:
|
||||
"""EDF+ `Startdate dd-MMM-yyyy admincode technician equipment`; MNE
|
||||
doesn't expose this header field, so it's read from the raw bytes."""
|
||||
parts = self._recording_field.split()
|
||||
if len(parts) >= 2 and parts[0] == "Startdate":
|
||||
values = [None if p == "X" else p.replace("_", " ") for p in parts[2:5]] + [None] * 3
|
||||
return {"admin_code": values[0], "technician": values[1], "equipment": values[2]}
|
||||
return {"admin_code": None, "technician": None, "equipment": None}
|
||||
|
||||
def annotations(self) -> list[EdfAnnotation]:
|
||||
return [
|
||||
EdfAnnotation(float(a["onset"]), float(a["duration"]) or None, a["description"])
|
||||
for a in self.raw.annotations
|
||||
]
|
||||
|
||||
# -- signal -----------------------------------------------------------------
|
||||
|
||||
def samples(self, channel: int | str) -> np.ndarray:
|
||||
"""Microvolts (MNE stores volts)."""
|
||||
picks = [channel] if isinstance(channel, str) else [self.raw.ch_names[channel]]
|
||||
return self.raw.get_data(picks=picks)[0] * 1e6
|
||||
|
||||
def background_rhythm(self) -> dict[str, float | None]:
|
||||
"""Posterior dominant rhythm from the occipital/parietal channels:
|
||||
peak frequency within 4–13 Hz and its peak-to-peak amplitude in µV.
|
||||
A screening aid for the report's "ritmo de base", not a reading."""
|
||||
rate = float(self.raw.info["sfreq"])
|
||||
channels = [name for name in self.raw.ch_names if electrode(name) in POSTERIOR_ELECTRODES]
|
||||
peaks = [p for p in (_peak(self.samples(name), rate, low=4.0, high=13.0) for name in channels) if p]
|
||||
if not peaks:
|
||||
return {"frequency_hz": None, "amplitude_uv": None, "channels": len(channels)}
|
||||
return {
|
||||
"frequency_hz": round(float(np.median([p[0] for p in peaks])), 1),
|
||||
"amplitude_uv": round(float(np.median([p[1] for p in peaks]))),
|
||||
"channels": len(channels),
|
||||
}
|
||||
|
||||
|
||||
def electrode(label: str) -> str:
|
||||
"""`EEG O1-REF` / `O1-A2` / `o1` -> `O1`."""
|
||||
name = label.upper().replace("EEG", "").strip()
|
||||
return re.split(r"[-\s:/]", name, maxsplit=1)[0]
|
||||
|
||||
|
||||
def _windows(values: np.ndarray, sample_rate: float) -> tuple[np.ndarray, int] | None:
|
||||
window = int(sample_rate * 4)
|
||||
if sample_rate <= 0 or window < 8 or values.size < window:
|
||||
return None
|
||||
segments = values[: values.size // window * window].reshape(-1, window)
|
||||
return segments - segments.mean(axis=1, keepdims=True), window
|
||||
|
||||
|
||||
def band_powers(values: np.ndarray, sample_rate: float) -> dict[str, float | None]:
|
||||
"""Relative power per EEG band and the dominant frequency (Hann-windowed
|
||||
periodogram averaged over 4-second windows)."""
|
||||
result: dict[str, float | None] = {f"power_{name}": None for name in BANDS_HZ}
|
||||
result["dominant_frequency_hz"] = None
|
||||
windowed = _windows(values, sample_rate)
|
||||
if windowed is None:
|
||||
return result
|
||||
segments, window = windowed
|
||||
spectrum = np.mean(np.abs(np.fft.rfft(segments * np.hanning(window), axis=1)) ** 2, axis=0)
|
||||
freqs = np.fft.rfftfreq(window, d=1.0 / sample_rate)
|
||||
in_range = (freqs >= 0.5) & (freqs <= 45.0)
|
||||
total = spectrum[in_range].sum()
|
||||
if total <= 0:
|
||||
return result
|
||||
for name, (low, high) in BANDS_HZ.items():
|
||||
band = (freqs >= low) & (freqs < high)
|
||||
result[f"power_{name}"] = round(float(spectrum[band].sum() / total), 4)
|
||||
result["dominant_frequency_hz"] = round(float(freqs[in_range][np.argmax(spectrum[in_range])]), 2)
|
||||
return result
|
||||
|
||||
|
||||
def _peak(values: np.ndarray, sample_rate: float, *, low: float, high: float) -> tuple[float, float] | None:
|
||||
windowed = _windows(values, sample_rate)
|
||||
if windowed is None:
|
||||
return None
|
||||
segments, window = windowed
|
||||
freqs = np.fft.rfftfreq(window, d=1.0 / sample_rate)
|
||||
power = np.mean(np.abs(np.fft.rfft(segments * np.hanning(window), axis=1)) ** 2, axis=0)
|
||||
band = (freqs >= low) & (freqs <= high)
|
||||
if not band.any() or power[band].max() <= 0:
|
||||
return None
|
||||
peak = float(freqs[band][np.argmax(power[band])])
|
||||
spectrum = np.fft.rfft(segments, axis=1)
|
||||
spectrum[:, (freqs < peak - 1) | (freqs > peak + 1)] = 0
|
||||
narrow = np.fft.irfft(spectrum, n=window, axis=1)
|
||||
return peak, float(2 * np.sqrt(2) * narrow.std())
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Synthetic documents for tests: typed and scanned PDFs, EDF recordings.
|
||||
`text_pdf` needs reportlab (a dev dependency)."""
|
||||
import io
|
||||
import struct
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
def text_pdf(pages: list[list[str]], *, image_on_page: int | None = None) -> bytes:
|
||||
"""One list of lines per page, typed (real text layer)."""
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
pdf = canvas.Canvas(buffer, pagesize=letter)
|
||||
for number, lines in enumerate(pages, start=1):
|
||||
y = 740
|
||||
for line in lines:
|
||||
pdf.drawString(60, y, line)
|
||||
y -= 20
|
||||
if image_on_page == number:
|
||||
picture = Image.new("RGB", (200, 150), (180, 60, 60))
|
||||
pdf.drawImage(ImageReader(picture), 300, 300, width=200, height=150)
|
||||
pdf.showPage()
|
||||
pdf.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def scanned_pdf(pages: list[list[str]]) -> bytes:
|
||||
"""Same as `text_pdf` but every page is a picture of text — no text layer."""
|
||||
images = []
|
||||
for lines in pages:
|
||||
image = Image.new("L", (1275, 1650), 255)
|
||||
draw = ImageDraw.Draw(image)
|
||||
font = _font(34)
|
||||
y = 120
|
||||
for line in lines:
|
||||
draw.text((110, y), line, fill=0, font=font)
|
||||
y += 60
|
||||
images.append(image.convert("RGB"))
|
||||
buffer = io.BytesIO()
|
||||
images[0].save(buffer, format="PDF", save_all=True, append_images=images[1:], resolution=150)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _font(size: int):
|
||||
for path in ("/System/Library/Fonts/Supplemental/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except OSError:
|
||||
continue
|
||||
return ImageFont.load_default(size=size)
|
||||
|
||||
|
||||
def edf_file(
|
||||
*,
|
||||
signals: dict[str, np.ndarray],
|
||||
sample_rate: int,
|
||||
patient: str = "EXP-0042 F 02-MAY-2019 Ana_Perez",
|
||||
recording: str = "Startdate 15-JAN-2024 LAB-778 Tec_Ruiz Nihon_Kohden",
|
||||
annotations: list[tuple[float, str]] = (),
|
||||
bdf: bool = False,
|
||||
) -> bytes:
|
||||
"""A valid EDF+ (or BDF+) file with one second per data record."""
|
||||
labels = list(signals)
|
||||
seconds = len(next(iter(signals.values()))) // sample_rate
|
||||
has_annotations = bool(annotations)
|
||||
total_signals = len(labels) + (1 if has_annotations else 0)
|
||||
annotation_samples = 60
|
||||
width = 3 if bdf else 2
|
||||
digital_max = (1 << 23) - 1 if bdf else 32767
|
||||
digital_min = -digital_max - 1
|
||||
|
||||
def field(value, size):
|
||||
return str(value).ljust(size)[:size].encode("latin-1")
|
||||
|
||||
header = b"\xffBIOSEMI" if bdf else field("0", 8)
|
||||
header += field(patient, 80) + field(recording, 80)
|
||||
header += field("15.01.24", 8) + field("10.30.00", 8)
|
||||
header += field(256 * (total_signals + 1), 8)
|
||||
header += field("BDF+C" if bdf else "EDF+C", 44)
|
||||
header += field(seconds, 8) + field(1, 8) + field(total_signals, 4)
|
||||
|
||||
all_labels = labels + (["BDF Annotations" if bdf else "EDF Annotations"] if has_annotations else [])
|
||||
per_record = [sample_rate] * len(labels) + ([annotation_samples] if has_annotations else [])
|
||||
columns = [
|
||||
[field(label, 16) for label in all_labels],
|
||||
[field("AgAgCl electrode" if label not in ("EDF Annotations", "BDF Annotations") else "", 80) for label in all_labels],
|
||||
[field("uV" if i < len(labels) else "", 8) for i in range(total_signals)],
|
||||
[field(-500 if i < len(labels) else -1, 8) for i in range(total_signals)],
|
||||
[field(500 if i < len(labels) else 1, 8) for i in range(total_signals)],
|
||||
[field(digital_min, 8) for _ in range(total_signals)],
|
||||
[field(digital_max, 8) for _ in range(total_signals)],
|
||||
[field("HP:0.1Hz LP:75Hz" if i < len(labels) else "", 80) for i in range(total_signals)],
|
||||
[field(n, 8) for n in per_record],
|
||||
[field("", 32) for _ in range(total_signals)],
|
||||
]
|
||||
for column in columns:
|
||||
header += b"".join(column)
|
||||
|
||||
gain = (digital_max - digital_min) / 1000.0
|
||||
body = b""
|
||||
for second in range(seconds):
|
||||
for label in labels:
|
||||
chunk = signals[label][second * sample_rate : (second + 1) * sample_rate]
|
||||
digital = np.clip(np.round((chunk + 500) * gain + digital_min), digital_min, digital_max).astype(np.int32)
|
||||
if bdf:
|
||||
body += b"".join(struct.pack("<i", int(v))[:3] for v in digital)
|
||||
else:
|
||||
body += digital.astype("<i2").tobytes()
|
||||
if has_annotations:
|
||||
tal = f"+{second}\x14\x14\x00".encode()
|
||||
for onset, text in annotations:
|
||||
if int(onset) == second:
|
||||
tal += f"+{onset}\x14{text}\x14\x00".encode()
|
||||
body += tal.ljust(annotation_samples * width, b"\x00")
|
||||
return header + body
|
||||
@@ -0,0 +1,26 @@
|
||||
[project]
|
||||
name = "extraction"
|
||||
version = "0.1.0"
|
||||
description = "Reads clinical documents (PDF, scanned images) and biosignal files (EDF/BDF) and extracts structured fields from them."
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"pdfplumber>=0.11",
|
||||
"pypdfium2>=4.0",
|
||||
"pytesseract>=0.3.10",
|
||||
"Pillow>=10.0",
|
||||
"numpy>=1.26",
|
||||
"mne>=1.7",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["extraction"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
@@ -0,0 +1,99 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from extraction.testing import scanned_pdf, text_pdf
|
||||
from extraction import DocumentExtractor, ExtractionError, FieldKind, FieldSpec, make_segmenter, read_document
|
||||
from extraction.readers import extract_pages, reader_for
|
||||
|
||||
EXPEDIENTE = FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))
|
||||
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento",))
|
||||
VPH = FieldSpec(
|
||||
"cit_vph_resultado",
|
||||
FieldKind.CHOICE,
|
||||
labels=("vph alto riesgo", "resultado vph"),
|
||||
choices={"POSITIVO": "POSITIVO", "NEGATIVO": "NEGATIVO"},
|
||||
scan_free_text=True,
|
||||
)
|
||||
SPECS = [EXPEDIENTE, NACIMIENTO, VPH]
|
||||
|
||||
|
||||
def test_text_layer_pages_are_read_without_ocr():
|
||||
document = read_document("r.pdf", text_pdf([["Expediente: EXP-0001", "VPH alto riesgo: POSITIVO"]]))
|
||||
assert document.pages[0].source == "text"
|
||||
assert "EXP-0001" in document.pages[0].text
|
||||
|
||||
|
||||
def test_scanned_pages_are_ocred():
|
||||
document = read_document("s.pdf", scanned_pdf([["Expediente: EXP-0002", "Resultado VPH: NEGATIVO"]]))
|
||||
page = document.pages[0]
|
||||
assert page.source == "ocr"
|
||||
assert page.images and page.images[0].kind == "scan"
|
||||
|
||||
|
||||
def test_embedded_figures_are_located():
|
||||
document = read_document("f.pdf", text_pdf([["Expediente: EXP-0003"], ["Imagen colposcópica"]], image_on_page=2))
|
||||
assert document.pages[0].images == []
|
||||
[figure] = document.pages[1].images
|
||||
assert figure.kind == "figure"
|
||||
assert 0.2 < figure.bbox.x0 < 0.6
|
||||
|
||||
|
||||
def test_one_document_with_several_patients_and_continuation_pages():
|
||||
raw = text_pdf(
|
||||
[
|
||||
["Expediente: EXP-0010", "Fecha de nacimiento: 01/02/1980"],
|
||||
["Hoja 2", "VPH alto riesgo: POSITIVO"],
|
||||
["Expediente: EXP-0011", "Fecha de nacimiento: 03/04/1975", "VPH alto riesgo: NEGATIVO"],
|
||||
]
|
||||
)
|
||||
records = DocumentExtractor(SPECS, key_field="pac_id_hospital").extract([read_document("lote.pdf", raw)])
|
||||
assert [r.key for r in records] == ["EXP-0010", "EXP-0011"]
|
||||
first, second = records
|
||||
assert first.sources[0].page_numbers == [1, 2]
|
||||
assert first.row() == {"pac_id_hospital": "EXP-0010", "pac_fecha_nacimiento": date(1980, 2, 1), "cit_vph_resultado": "POSITIVO"}
|
||||
assert second.row()["cit_vph_resultado"] == "NEGATIVO"
|
||||
|
||||
|
||||
def test_patient_scattered_across_documents_is_merged():
|
||||
demographics = read_document("a.pdf", text_pdf([["Expediente: EXP-0020", "Fecha de nacimiento: 05/06/1970"]]))
|
||||
lab = read_document("b.pdf", scanned_pdf([["Expediente: EXP-0020", "Resultado VPH: POSITIVO"]]))
|
||||
[record] = DocumentExtractor(SPECS, key_field="pac_id_hospital").extract([demographics, lab])
|
||||
assert record.row()["pac_fecha_nacimiento"] == date(1970, 6, 5)
|
||||
assert record.row()["cit_vph_resultado"] == "POSITIVO"
|
||||
assert {source.document for source in record.sources} == {"a.pdf", "b.pdf"}
|
||||
|
||||
|
||||
def test_confident_disagreement_is_reported_as_conflict():
|
||||
one = read_document("a.pdf", text_pdf([["Expediente: EXP-0030", "VPH alto riesgo: POSITIVO"]]))
|
||||
two = read_document("b.pdf", text_pdf([["Expediente: EXP-0030", "VPH alto riesgo: NEGATIVO"]]))
|
||||
[record] = DocumentExtractor(SPECS, key_field="pac_id_hospital").extract([one, two])
|
||||
assert [conflict.field for conflict in record.conflicts] == ["cit_vph_resultado"]
|
||||
|
||||
|
||||
def test_fixed_page_segmentation():
|
||||
raw = text_pdf([["Expediente: EXP-1"], ["x"], ["Expediente: EXP-2"], ["y"]])
|
||||
extractor = DocumentExtractor(SPECS, key_field="pac_id_hospital", segmenter=make_segmenter("pages", pages_per_record=2), merger=None)
|
||||
assert [r.sources[0].page_numbers for r in extractor.extract([read_document("d.pdf", raw)])] == [[1, 2], [3, 4]]
|
||||
|
||||
|
||||
def test_extract_pages_builds_a_smaller_pdf():
|
||||
raw = text_pdf([["Expediente: EXP-A"], ["Expediente: EXP-B"], ["Expediente: EXP-C"]])
|
||||
subset = read_document("sub.pdf", extract_pages(raw, [2, 3]))
|
||||
assert subset.page_count == 2
|
||||
assert "EXP-B" in subset.pages[0].text
|
||||
|
||||
|
||||
def test_unknown_format_is_rejected():
|
||||
with pytest.raises(ExtractionError):
|
||||
reader_for("notes.docx", b"PK\x03\x04")
|
||||
|
||||
|
||||
def test_combine_pages_from_several_pdfs():
|
||||
from extraction.readers import combine_pages
|
||||
|
||||
one = text_pdf([["Expediente: EXP-A"], ["Expediente: EXP-B"]])
|
||||
two = scanned_pdf([["Expediente: EXP-B", "Resultado VPH: NEGATIVO"]])
|
||||
combined = read_document("c.pdf", combine_pages([(one, [2]), (two, [1])]))
|
||||
assert combined.page_count == 2
|
||||
assert "EXP-B" in combined.pages[0].text and "NEGATIVO" in combined.pages[1].text
|
||||
@@ -0,0 +1,77 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from extraction.testing import edf_file
|
||||
from extraction import ExtractionError
|
||||
from extraction.signals import EegRecording, band_powers
|
||||
|
||||
RATE = 128
|
||||
SECONDS = 8
|
||||
|
||||
|
||||
def sine(frequency: float, amplitude: float = 50.0) -> np.ndarray:
|
||||
t = np.arange(RATE * SECONDS) / RATE
|
||||
return amplitude * np.sin(2 * np.pi * frequency * t)
|
||||
|
||||
|
||||
def test_header_patient_and_recording():
|
||||
eeg = EegRecording.read(edf_file(signals={"O1": sine(10), "Fp1": sine(20)}, sample_rate=RATE))
|
||||
assert eeg.variant == "EDF+"
|
||||
assert eeg.patient.code == "EXP-0042"
|
||||
assert eeg.patient.sex == "F"
|
||||
assert eeg.patient.birthdate == date(2019, 5, 2)
|
||||
assert eeg.patient.name == "Ana Perez"
|
||||
assert eeg.start == datetime(2024, 1, 15, 10, 30)
|
||||
assert eeg.duration_seconds == SECONDS
|
||||
assert eeg.recording_fields == {"admin_code": "LAB-778", "technician": "Tec Ruiz", "equipment": "Nihon Kohden"}
|
||||
assert [c.label for c in eeg.channels] == ["O1", "Fp1"]
|
||||
assert eeg.channels[0].sample_rate == RATE
|
||||
|
||||
|
||||
def test_samples_are_in_microvolts():
|
||||
signal = sine(10)
|
||||
eeg = EegRecording.read(edf_file(signals={"O1": signal}, sample_rate=RATE))
|
||||
np.testing.assert_allclose(eeg.samples("O1"), signal, atol=0.05)
|
||||
|
||||
|
||||
def test_band_power_finds_the_dominant_rhythm():
|
||||
eeg = EegRecording.read(edf_file(signals={"O1": sine(10), "Fp1": sine(6)}, sample_rate=RATE))
|
||||
alpha = band_powers(eeg.samples("O1"), RATE)
|
||||
theta = band_powers(eeg.samples("Fp1"), RATE)
|
||||
assert alpha["dominant_frequency_hz"] == pytest.approx(10, abs=0.3)
|
||||
assert alpha["power_alpha"] > 0.9
|
||||
assert theta["power_theta"] > 0.9
|
||||
|
||||
|
||||
def test_background_rhythm_from_posterior_channels():
|
||||
signals = {"EEG O1-REF": sine(9.5, 40), "EEG O2-REF": sine(9.5, 40), "Fp1": sine(20)}
|
||||
rhythm = EegRecording.read(edf_file(signals=signals, sample_rate=RATE)).background_rhythm()
|
||||
assert rhythm["channels"] == 2
|
||||
assert rhythm["frequency_hz"] == pytest.approx(9.5, abs=0.3)
|
||||
assert rhythm["amplitude_uv"] == pytest.approx(80, rel=0.15)
|
||||
|
||||
|
||||
def test_annotations():
|
||||
raw = edf_file(signals={"O1": sine(10)}, sample_rate=RATE, annotations=[(2.5, "Ojos cerrados"), (5.0, "Fotoestimulacion")])
|
||||
eeg = EegRecording.read(raw)
|
||||
assert [(a.onset_seconds, a.text) for a in eeg.annotations()] == [(2.5, "Ojos cerrados"), (5.0, "Fotoestimulacion")]
|
||||
assert [c.label for c in eeg.channels] == ["O1"]
|
||||
|
||||
|
||||
def test_bdf_24_bit_samples():
|
||||
signal = sine(10)
|
||||
eeg = EegRecording.read(edf_file(signals={"Cz": signal}, sample_rate=RATE, bdf=True))
|
||||
assert eeg.is_bdf and eeg.variant == "BDF+"
|
||||
np.testing.assert_allclose(eeg.samples("Cz"), signal, atol=0.001)
|
||||
|
||||
|
||||
def test_plain_edf_recording_field_is_not_structured():
|
||||
eeg = EegRecording.read(edf_file(signals={"O1": sine(10)}, sample_rate=RATE, recording="estudio 7"))
|
||||
assert eeg.recording_fields["admin_code"] is None
|
||||
|
||||
|
||||
def test_garbage_is_rejected():
|
||||
with pytest.raises(ExtractionError):
|
||||
EegRecording.read(b"0 " + b"not an edf" * 40)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user